Merge branch 'main' into fix-resume
This commit is contained in:
commit
b64249d800
11 changed files with 432 additions and 365 deletions
|
|
@ -1,3 +1,10 @@
|
|||
## [1.3.2](https://github.com/continuedev/cli/compare/v1.3.1...v1.3.2) (2025-07-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6))
|
||||
|
||||
## [1.3.1](https://github.com/continuedev/cli/compare/v1.3.0...v1.3.1) (2025-07-16)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -7,22 +7,21 @@ export default {
|
|||
},
|
||||
|
||||
moduleNameMapper: {
|
||||
"^highlight\\.js/lib/languages/(.+)\\.js$": "<rootDir>/src/ui/__mocks__/highlightLanguage.js",
|
||||
"^highlight\\.js/lib/languages/(.+)$":
|
||||
"<rootDir>/src/ui/__mocks__/highlightLanguage.js",
|
||||
"^lowlight$": "<rootDir>/src/ui/__mocks__/lowlight.js",
|
||||
"(.+)\\.js": "$1",
|
||||
"^ink-testing-library$": "<rootDir>/node_modules/ink-testing-library/build/index.js",
|
||||
"^./SyntaxHighlighter\\.js$": "<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
|
||||
"^ink-testing-library$":
|
||||
"<rootDir>/node_modules/ink-testing-library/build/index.js",
|
||||
"^./SyntaxHighlighter\\.js$":
|
||||
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
|
||||
},
|
||||
extensionsToTreatAsEsm: [".ts", ".tsx"],
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
testTimeout: 10000,
|
||||
testEnvironment: "node",
|
||||
testPathIgnorePatterns: [
|
||||
"<rootDir>/dist/"
|
||||
],
|
||||
transformIgnorePatterns: [
|
||||
"node_modules/(?!(highlight.js|lowlight)/)"
|
||||
],
|
||||
testPathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"],
|
||||
globals: {
|
||||
__dirname: path.dirname(fileURLToPath(import.meta.url)),
|
||||
__filename: path.resolve(fileURLToPath(import.meta.url)),
|
||||
|
|
|
|||
10
package-lock.json
generated
10
package-lock.json
generated
|
|
@ -18,6 +18,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"glob": "^11.0.3",
|
||||
|
|
@ -5420,6 +5421,15 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "14.0.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-14.0.0.tgz",
|
||||
"integrity": "sha512-2uM9rYjPvyq39NwLRqaiLtWHyDC1FvryJDa2ATTVims5YAS4PupsEQsDvP14FqhFr0P49CYDugi59xaxJlTXRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/compare-func": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@continuedev/cli",
|
||||
"version": "1.3.1",
|
||||
"version": "1.3.2",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
|
@ -40,6 +40,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"axios": "^1.8.4",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"glob": "^11.0.3",
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ export function loadAuthConfig(): AuthConfig {
|
|||
if (process.env.CONTINUE_API_KEY) {
|
||||
return {
|
||||
accessToken: process.env.CONTINUE_API_KEY,
|
||||
organizationId: null,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -139,7 +140,7 @@ async function refreshToken(refreshToken: string): Promise<AuthConfig> {
|
|||
try {
|
||||
// Load existing config to preserve organizationId and other fields
|
||||
const existingConfig = loadAuthConfig();
|
||||
|
||||
|
||||
const response = await axios.post(
|
||||
new URL("auth/refresh", env.apiBase).toString(),
|
||||
{
|
||||
|
|
@ -221,7 +222,7 @@ export async function login(
|
|||
}
|
||||
|
||||
/**
|
||||
* Ensures the user has selected an organization, prompting if necessary
|
||||
* Ensures the user has selected an organization, automatically selecting the first one if available
|
||||
*/
|
||||
export async function ensureOrganization(
|
||||
authConfig: AuthConfig,
|
||||
|
|
@ -259,9 +260,6 @@ export async function ensureOrganization(
|
|||
const organizations = resp.organizations;
|
||||
|
||||
if (organizations.length === 0) {
|
||||
console.info(
|
||||
chalk.green("No organizations found. Using personal organization.")
|
||||
);
|
||||
const updatedConfig = {
|
||||
...authConfig,
|
||||
organizationId: null,
|
||||
|
|
@ -270,78 +268,10 @@ export async function ensureOrganization(
|
|||
return updatedConfig;
|
||||
}
|
||||
|
||||
if (organizations.length === 1) {
|
||||
// Show choice between personal and the one organization
|
||||
const org = organizations[0];
|
||||
console.info(chalk.cyan("\nSelect an organization:"));
|
||||
console.info(chalk.white(`1. Personal (default)`));
|
||||
console.info(chalk.white(`2. ${org.name}`));
|
||||
|
||||
const selection = await prompt(
|
||||
chalk.yellow("Enter your choice (number): ")
|
||||
);
|
||||
const selectedIndex = parseInt(selection) - 1;
|
||||
|
||||
if (selectedIndex < 0 || selectedIndex > 1) {
|
||||
console.error(chalk.red("Invalid selection. Please try again."));
|
||||
return await ensureOrganization(authConfig, isHeadless);
|
||||
}
|
||||
|
||||
let selectedOrgId: string | null;
|
||||
let selectedOrgName: string;
|
||||
|
||||
if (selectedIndex === 0) {
|
||||
// Personal organization selected
|
||||
selectedOrgId = null;
|
||||
selectedOrgName = "Personal";
|
||||
} else {
|
||||
// The one organization selected
|
||||
selectedOrgId = org.id;
|
||||
selectedOrgName = org.name;
|
||||
}
|
||||
|
||||
console.info(chalk.green(`Selected organization: ${selectedOrgName}`));
|
||||
|
||||
const updatedConfig = {
|
||||
...authConfig,
|
||||
organizationId: selectedOrgId,
|
||||
};
|
||||
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
// Multiple organizations - show selection including personal
|
||||
console.info(chalk.cyan("\nSelect an organization:"));
|
||||
console.info(chalk.white(`1. Personal (default)`));
|
||||
organizations.forEach((org, index) => {
|
||||
console.info(chalk.white(`${index + 2}. ${org.name}`));
|
||||
});
|
||||
|
||||
const selection = await prompt(
|
||||
chalk.yellow("Enter your choice (number): ")
|
||||
);
|
||||
const selectedIndex = parseInt(selection) - 1;
|
||||
|
||||
if (selectedIndex < 0 || selectedIndex > organizations.length) {
|
||||
console.error(chalk.red("Invalid selection. Please try again."));
|
||||
return await ensureOrganization(authConfig, isHeadless);
|
||||
}
|
||||
|
||||
let selectedOrgId: string | null;
|
||||
let selectedOrgName: string;
|
||||
|
||||
if (selectedIndex === 0) {
|
||||
// Personal organization selected
|
||||
selectedOrgId = null;
|
||||
selectedOrgName = "Personal";
|
||||
} else {
|
||||
// Regular organization selected
|
||||
const selectedOrg = organizations[selectedIndex - 1];
|
||||
selectedOrgId = selectedOrg.id;
|
||||
selectedOrgName = selectedOrg.name;
|
||||
}
|
||||
console.info(chalk.green(`Selected organization: ${selectedOrgName}`));
|
||||
// Automatically select the first organization if available, otherwise use personal
|
||||
const selectedOrg = organizations[0];
|
||||
const selectedOrgId = selectedOrg.id;
|
||||
const selectedOrgName = selectedOrg.name;
|
||||
|
||||
const updatedConfig = {
|
||||
...authConfig,
|
||||
|
|
@ -356,7 +286,12 @@ export async function ensureOrganization(
|
|||
error.response?.data?.message || error.message || error
|
||||
);
|
||||
console.info(chalk.yellow("Continuing without organization selection."));
|
||||
return authConfig;
|
||||
const updatedConfig = {
|
||||
...authConfig,
|
||||
organizationId: null,
|
||||
};
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -419,4 +354,4 @@ export function logout(): void {
|
|||
} else {
|
||||
console.info(chalk.yellow("No active session found"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
146
src/commands/chat.ts
Normal file
146
src/commands/chat.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import chalk from "chalk";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
import { initializeAssistant } from "../assistant.js";
|
||||
import { ensureAuthenticated } from "../auth/ensureAuth.js";
|
||||
import { ensureOrganization, loadAuthConfig } from "../auth/workos.js";
|
||||
import { introMessage } from "../intro.js";
|
||||
import { configureLogger } from "../logger.js";
|
||||
import { loadSession, saveSession } from "../session.js";
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import { startTUIChat } from "../ui/index.js";
|
||||
|
||||
export interface ChatOptions {
|
||||
headless?: boolean;
|
||||
config?: string;
|
||||
resume?: boolean;
|
||||
}
|
||||
|
||||
async function initializeChat(options: ChatOptions) {
|
||||
const isAuthenticated = await ensureAuthenticated(true);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
console.error(chalk.red("Authentication failed. Exiting..."));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
// Ensure organization is selected
|
||||
const authConfigWithOrg = await ensureOrganization(
|
||||
authConfig,
|
||||
options.headless ?? false
|
||||
);
|
||||
|
||||
// Initialize ContinueSDK and MCPService once
|
||||
const { config, llmApi, model, mcpService } = await initializeAssistant(
|
||||
authConfigWithOrg,
|
||||
options.config
|
||||
);
|
||||
|
||||
return { config, llmApi, model, mcpService };
|
||||
}
|
||||
|
||||
export async function chat(prompt?: string, options: ChatOptions = {}) {
|
||||
// Configure logger based on headless mode
|
||||
configureLogger(options.headless ?? false);
|
||||
|
||||
try {
|
||||
let { config, llmApi, model, mcpService } = await initializeChat(options);
|
||||
|
||||
// If not in headless mode, start the TUI chat (default)
|
||||
if (!options.headless) {
|
||||
await startTUIChat(
|
||||
config,
|
||||
llmApi,
|
||||
model,
|
||||
mcpService,
|
||||
prompt,
|
||||
options.resume,
|
||||
options.config
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show intro message for headless mode
|
||||
introMessage(config, model, mcpService);
|
||||
|
||||
// Rules
|
||||
let chatHistory: ChatCompletionMessageParam[] = [];
|
||||
|
||||
// Load previous session if --resume flag is used
|
||||
if (options.resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
chatHistory = savedHistory;
|
||||
console.log(chalk.yellow("Resuming previous session..."));
|
||||
} else {
|
||||
console.log(
|
||||
chalk.yellow("No previous session found, starting fresh...")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If no session loaded or not resuming, initialize with system message
|
||||
if (chatHistory.length === 0) {
|
||||
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
|
||||
const systemMessage = constructSystemMessage(rulesSystemMessage);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
}
|
||||
|
||||
let isFirstMessage = true;
|
||||
while (true) {
|
||||
// When in headless mode, don't ask for user input
|
||||
if (!isFirstMessage && prompt && options.headless) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Get user input
|
||||
let userInput =
|
||||
isFirstMessage && prompt
|
||||
? prompt
|
||||
: readlineSync.question(`\n${chalk.bold.green("You:")} `);
|
||||
|
||||
isFirstMessage = false;
|
||||
|
||||
// Add user message to history
|
||||
chatHistory.push({ role: "user", content: userInput });
|
||||
|
||||
// Get AI response with potential tool usage
|
||||
if (!options.headless) {
|
||||
console.info(`\n${chalk.bold.blue("Assistant:")}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const abortController = new AbortController();
|
||||
const finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
);
|
||||
|
||||
// In headless mode, only print the final response
|
||||
if (options.headless && finalResponse.trim()) {
|
||||
console.log(finalResponse);
|
||||
}
|
||||
|
||||
// Save session after each successful response
|
||||
saveSession(chatHistory);
|
||||
} catch (e: any) {
|
||||
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
||||
if (!options.headless) {
|
||||
console.info(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red(`Fatal error: ${error.message}`));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
14
src/commands/login.ts
Normal file
14
src/commands/login.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import chalk from "chalk";
|
||||
import { login as workosLogin } from "../auth/workos.js";
|
||||
|
||||
export async function login() {
|
||||
console.info(chalk.yellow("Logging in to Continue..."));
|
||||
|
||||
try {
|
||||
await workosLogin();
|
||||
console.info(chalk.green("Successfully logged in!"));
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red(`Login failed: ${error.message}`));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
5
src/commands/logout.ts
Normal file
5
src/commands/logout.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { logout as workosLogout } from "../auth/workos.js";
|
||||
|
||||
export async function logout() {
|
||||
workosLogout();
|
||||
}
|
||||
170
src/index.ts
170
src/index.ts
|
|
@ -1,144 +1,42 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import chalk from "chalk";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
import { parseArgs } from "./args.js";
|
||||
import { initializeAssistant } from "./assistant.js";
|
||||
import { ensureAuthenticated } from "./auth/ensureAuth.js";
|
||||
import { ensureOrganization, loadAuthConfig } from "./auth/workos.js";
|
||||
import { introMessage } from "./intro.js";
|
||||
import { configureLogger } from "./logger.js";
|
||||
import { loadSession, saveSession } from "./session.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { constructSystemMessage } from "./systemMessage.js";
|
||||
import { startTUIChat } from "./ui/index.js";
|
||||
import { Command } from "commander";
|
||||
import { chat } from "./commands/chat.js";
|
||||
import { login } from "./commands/login.js";
|
||||
import { logout } from "./commands/logout.js";
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
// Parse command line arguments
|
||||
const args = parseArgs();
|
||||
const program = new Command();
|
||||
|
||||
// Configure logger based on headless mode
|
||||
configureLogger(args.isHeadless);
|
||||
program
|
||||
.name("cn")
|
||||
.description("Continue CLI - AI-powered development assistant")
|
||||
.version(getVersion());
|
||||
|
||||
async function initializeChat() {
|
||||
const isAuthenticated = await ensureAuthenticated(true);
|
||||
// Root command - chat functionality (default)
|
||||
program
|
||||
.argument("[prompt]", "Optional prompt to send to the assistant")
|
||||
.option("--headless", "Run in headless mode (non-interactive)")
|
||||
.option("--config <path>", "Path to configuration file")
|
||||
.option("--resume", "Resume from last session")
|
||||
.action(async (prompt, options) => {
|
||||
await chat(prompt, options);
|
||||
});
|
||||
|
||||
if (!isAuthenticated) {
|
||||
console.error(chalk.red("Authentication failed. Exiting..."));
|
||||
process.exit(1);
|
||||
}
|
||||
// Login subcommand
|
||||
program
|
||||
.command("login")
|
||||
.description("Authenticate with Continue")
|
||||
.action(async () => {
|
||||
await login();
|
||||
});
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
// Logout subcommand
|
||||
program
|
||||
.command("logout")
|
||||
.description("Log out from Continue")
|
||||
.action(async () => {
|
||||
await logout();
|
||||
});
|
||||
|
||||
// Ensure organization is selected
|
||||
const authConfigWithOrg = await ensureOrganization(
|
||||
authConfig,
|
||||
args.isHeadless
|
||||
);
|
||||
|
||||
// Initialize ContinueSDK and MCPService once
|
||||
const { config, llmApi, model, mcpService } = await initializeAssistant(
|
||||
authConfigWithOrg,
|
||||
args.configPath
|
||||
);
|
||||
|
||||
return { config, llmApi, model, mcpService };
|
||||
}
|
||||
|
||||
async function chat() {
|
||||
let { config, llmApi, model, mcpService } = await initializeChat();
|
||||
|
||||
// If not in headless mode, start the TUI chat (default)
|
||||
if (!args.isHeadless) {
|
||||
await startTUIChat(
|
||||
config,
|
||||
llmApi,
|
||||
model,
|
||||
mcpService,
|
||||
args.prompt,
|
||||
args.resume,
|
||||
args.configPath
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show intro message for headless mode
|
||||
introMessage(config, model, mcpService);
|
||||
|
||||
// Rules
|
||||
let chatHistory: ChatCompletionMessageParam[] = [];
|
||||
|
||||
// Load previous session if --resume flag is used
|
||||
if (args.resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
chatHistory = savedHistory;
|
||||
console.log(chalk.yellow("Resuming previous session..."));
|
||||
} else {
|
||||
console.log(chalk.yellow("No previous session found, starting fresh..."));
|
||||
}
|
||||
}
|
||||
|
||||
// If no session loaded or not resuming, initialize with system message
|
||||
if (chatHistory.length === 0) {
|
||||
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
|
||||
const systemMessage = constructSystemMessage(rulesSystemMessage);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
}
|
||||
|
||||
let isFirstMessage = true;
|
||||
while (true) {
|
||||
// When in headless mode, don't ask for user input
|
||||
if (!isFirstMessage && args.prompt && args.isHeadless) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Get user input
|
||||
let userInput =
|
||||
isFirstMessage && args.prompt
|
||||
? args.prompt
|
||||
: readlineSync.question(`\n${chalk.bold.green("You:")} `);
|
||||
|
||||
isFirstMessage = false;
|
||||
|
||||
|
||||
// Add user message to history
|
||||
chatHistory.push({ role: "user", content: userInput });
|
||||
|
||||
// Get AI response with potential tool usage
|
||||
if (!args.isHeadless) {
|
||||
console.info(`\n${chalk.bold.blue("Assistant:")}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const abortController = new AbortController();
|
||||
const finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController
|
||||
);
|
||||
|
||||
// In headless mode, only print the final response
|
||||
if (args.isHeadless && finalResponse.trim()) {
|
||||
console.log(finalResponse);
|
||||
}
|
||||
|
||||
// Save session after each successful response
|
||||
saveSession(chatHistory);
|
||||
} catch (e: any) {
|
||||
console.error(`\n${chalk.red(`Error: ${e.message}`)}`);
|
||||
if (!args.isHeadless) {
|
||||
console.info(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chat().catch((error) =>
|
||||
console.error(chalk.red(`Fatal error: ${error.message}`))
|
||||
);
|
||||
program.parse();
|
||||
|
|
|
|||
|
|
@ -1,26 +1,46 @@
|
|||
import { createLowlight } from 'lowlight';
|
||||
import { Text } from 'ink';
|
||||
import React from 'react';
|
||||
import js from 'highlight.js/lib/languages/javascript';
|
||||
import ts from 'highlight.js/lib/languages/typescript';
|
||||
import python from 'highlight.js/lib/languages/python';
|
||||
import java from 'highlight.js/lib/languages/java';
|
||||
import c from 'highlight.js/lib/languages/c';
|
||||
import cpp from 'highlight.js/lib/languages/cpp';
|
||||
import csharp from 'highlight.js/lib/languages/csharp';
|
||||
import go from 'highlight.js/lib/languages/go';
|
||||
import rust from 'highlight.js/lib/languages/rust';
|
||||
import php from 'highlight.js/lib/languages/php';
|
||||
import ruby from 'highlight.js/lib/languages/ruby';
|
||||
import swift from 'highlight.js/lib/languages/swift';
|
||||
import kotlin from 'highlight.js/lib/languages/kotlin';
|
||||
import sql from 'highlight.js/lib/languages/sql';
|
||||
import json from 'highlight.js/lib/languages/json';
|
||||
import yaml from 'highlight.js/lib/languages/yaml';
|
||||
import bash from 'highlight.js/lib/languages/bash';
|
||||
import markdown from 'highlight.js/lib/languages/markdown';
|
||||
import css from 'highlight.js/lib/languages/css';
|
||||
import xml from 'highlight.js/lib/languages/xml';
|
||||
// @ts-ignore - Suppress deprecation warnings for highlight.js imports
|
||||
import bash from "highlight.js/lib/languages/bash.js";
|
||||
// @ts-ignore
|
||||
import c from "highlight.js/lib/languages/c.js";
|
||||
// @ts-ignore
|
||||
import cpp from "highlight.js/lib/languages/cpp.js";
|
||||
// @ts-ignore
|
||||
import csharp from "highlight.js/lib/languages/csharp.js";
|
||||
// @ts-ignore
|
||||
import css from "highlight.js/lib/languages/css.js";
|
||||
// @ts-ignore
|
||||
import go from "highlight.js/lib/languages/go.js";
|
||||
// @ts-ignore
|
||||
import java from "highlight.js/lib/languages/java.js";
|
||||
// @ts-ignore
|
||||
import js from "highlight.js/lib/languages/javascript.js";
|
||||
// @ts-ignore
|
||||
import json from "highlight.js/lib/languages/json.js";
|
||||
// @ts-ignore
|
||||
import kotlin from "highlight.js/lib/languages/kotlin.js";
|
||||
// @ts-ignore
|
||||
import markdown from "highlight.js/lib/languages/markdown.js";
|
||||
// @ts-ignore
|
||||
import php from "highlight.js/lib/languages/php.js";
|
||||
// @ts-ignore
|
||||
import python from "highlight.js/lib/languages/python.js";
|
||||
// @ts-ignore
|
||||
import ruby from "highlight.js/lib/languages/ruby.js";
|
||||
// @ts-ignore
|
||||
import rust from "highlight.js/lib/languages/rust.js";
|
||||
// @ts-ignore
|
||||
import sql from "highlight.js/lib/languages/sql.js";
|
||||
// @ts-ignore
|
||||
import swift from "highlight.js/lib/languages/swift.js";
|
||||
// @ts-ignore
|
||||
import ts from "highlight.js/lib/languages/typescript.js";
|
||||
// @ts-ignore
|
||||
import xml from "highlight.js/lib/languages/xml.js";
|
||||
// @ts-ignore
|
||||
import yaml from "highlight.js/lib/languages/yaml.js";
|
||||
import { Text } from "ink";
|
||||
import { createLowlight } from "lowlight";
|
||||
import React from "react";
|
||||
|
||||
export interface SyntaxHighlighterTheme {
|
||||
keyword: string;
|
||||
|
|
@ -39,69 +59,69 @@ export interface SyntaxHighlighterTheme {
|
|||
}
|
||||
|
||||
export const defaultTheme: SyntaxHighlighterTheme = {
|
||||
keyword: 'magenta',
|
||||
string: 'green',
|
||||
comment: 'gray',
|
||||
number: 'cyan',
|
||||
operator: 'white',
|
||||
punctuation: 'white',
|
||||
function: 'yellow',
|
||||
variable: 'white',
|
||||
property: 'blue',
|
||||
class: 'yellow',
|
||||
constant: 'cyan',
|
||||
regex: 'red',
|
||||
default: 'white'
|
||||
keyword: "magenta",
|
||||
string: "green",
|
||||
comment: "gray",
|
||||
number: "cyan",
|
||||
operator: "white",
|
||||
punctuation: "white",
|
||||
function: "yellow",
|
||||
variable: "white",
|
||||
property: "blue",
|
||||
class: "yellow",
|
||||
constant: "cyan",
|
||||
regex: "red",
|
||||
default: "white",
|
||||
};
|
||||
|
||||
// Map highlight.js token types to theme colors
|
||||
const tokenColorMap: Record<string, keyof SyntaxHighlighterTheme> = {
|
||||
'keyword': 'keyword',
|
||||
'string': 'string',
|
||||
'comment': 'comment',
|
||||
'number': 'number',
|
||||
'operator': 'operator',
|
||||
'punctuation': 'punctuation',
|
||||
'function': 'function',
|
||||
'variable': 'variable',
|
||||
'property': 'property',
|
||||
'class': 'class',
|
||||
'constant': 'constant',
|
||||
'regexp': 'regex',
|
||||
'boolean': 'constant',
|
||||
'null': 'constant',
|
||||
'undefined': 'constant',
|
||||
'builtin': 'keyword',
|
||||
'tag': 'keyword',
|
||||
'attr': 'property',
|
||||
'attribute': 'property',
|
||||
'selector': 'property',
|
||||
'important': 'keyword',
|
||||
'atrule': 'keyword',
|
||||
'rule': 'keyword',
|
||||
'entity': 'constant',
|
||||
'url': 'string',
|
||||
'symbol': 'constant',
|
||||
'prolog': 'comment',
|
||||
'doctype': 'comment',
|
||||
'cdata': 'comment',
|
||||
'title': 'function',
|
||||
'section': 'keyword',
|
||||
'name': 'function',
|
||||
'strong': 'keyword',
|
||||
'emphasis': 'string',
|
||||
'quote': 'string',
|
||||
'built_in': 'keyword',
|
||||
'literal': 'constant',
|
||||
'type': 'class',
|
||||
'params': 'variable',
|
||||
'meta': 'comment',
|
||||
'link': 'string'
|
||||
keyword: "keyword",
|
||||
string: "string",
|
||||
comment: "comment",
|
||||
number: "number",
|
||||
operator: "operator",
|
||||
punctuation: "punctuation",
|
||||
function: "function",
|
||||
variable: "variable",
|
||||
property: "property",
|
||||
class: "class",
|
||||
constant: "constant",
|
||||
regexp: "regex",
|
||||
boolean: "constant",
|
||||
null: "constant",
|
||||
undefined: "constant",
|
||||
builtin: "keyword",
|
||||
tag: "keyword",
|
||||
attr: "property",
|
||||
attribute: "property",
|
||||
selector: "property",
|
||||
important: "keyword",
|
||||
atrule: "keyword",
|
||||
rule: "keyword",
|
||||
entity: "constant",
|
||||
url: "string",
|
||||
symbol: "constant",
|
||||
prolog: "comment",
|
||||
doctype: "comment",
|
||||
cdata: "comment",
|
||||
title: "function",
|
||||
section: "keyword",
|
||||
name: "function",
|
||||
strong: "keyword",
|
||||
emphasis: "string",
|
||||
quote: "string",
|
||||
built_in: "keyword",
|
||||
literal: "constant",
|
||||
type: "class",
|
||||
params: "variable",
|
||||
meta: "comment",
|
||||
link: "string",
|
||||
};
|
||||
|
||||
export function highlightCode(
|
||||
code: string,
|
||||
language: string = 'javascript',
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
theme: SyntaxHighlighterTheme = defaultTheme
|
||||
): React.ReactNode[] {
|
||||
try {
|
||||
|
|
@ -128,44 +148,51 @@ export function highlightCode(
|
|||
markdown: markdown,
|
||||
css: css,
|
||||
html: xml,
|
||||
xml: xml
|
||||
xml: xml,
|
||||
});
|
||||
|
||||
const result = lowlight.highlight(language, code, { prefix: '' });
|
||||
|
||||
|
||||
const result = lowlight.highlight(language, code, { prefix: "" });
|
||||
|
||||
// Convert the hast tree to React elements
|
||||
const elements: React.ReactNode[] = [];
|
||||
|
||||
|
||||
let keyCounter = 0;
|
||||
|
||||
function processNode(node: any, parentColor: string = theme.default): React.ReactNode {
|
||||
if (node.type === 'text') {
|
||||
|
||||
function processNode(
|
||||
node: any,
|
||||
parentColor: string = theme.default
|
||||
): React.ReactNode {
|
||||
if (node.type === "text") {
|
||||
const text = node.value;
|
||||
if (text) {
|
||||
return React.createElement(Text, {
|
||||
key: `text-${keyCounter++}`,
|
||||
color: parentColor
|
||||
}, text);
|
||||
return React.createElement(
|
||||
Text,
|
||||
{
|
||||
key: `text-${keyCounter++}`,
|
||||
color: parentColor,
|
||||
},
|
||||
text
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (node.type === 'element') {
|
||||
|
||||
if (node.type === "element") {
|
||||
const className = node.properties?.className || [];
|
||||
|
||||
|
||||
// Extract token type from class names
|
||||
let tokenType = '';
|
||||
let tokenType = "";
|
||||
for (const cls of className) {
|
||||
if (tokenColorMap[cls]) {
|
||||
tokenType = cls;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Get color from theme
|
||||
const colorKey = tokenColorMap[tokenType] || 'default';
|
||||
const colorKey = tokenColorMap[tokenType] || "default";
|
||||
const color = theme[colorKey];
|
||||
|
||||
|
||||
if (node.children && node.children.length > 0) {
|
||||
// Process child nodes with this color
|
||||
const children: React.ReactNode[] = [];
|
||||
|
|
@ -179,35 +206,39 @@ export function highlightCode(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
|
||||
const textContent = getTextContent(node);
|
||||
if (textContent) {
|
||||
return React.createElement(Text, {
|
||||
key: `element-${keyCounter++}`,
|
||||
color
|
||||
}, textContent);
|
||||
return React.createElement(
|
||||
Text,
|
||||
{
|
||||
key: `element-${keyCounter++}`,
|
||||
color,
|
||||
},
|
||||
textContent
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// Helper function to extract text content from a node
|
||||
function getTextContent(node: any): string {
|
||||
if (node.type === 'text') {
|
||||
return node.value || '';
|
||||
if (node.type === "text") {
|
||||
return node.value || "";
|
||||
}
|
||||
|
||||
if (node.type === 'element' && node.children) {
|
||||
return node.children.map(getTextContent).join('');
|
||||
|
||||
if (node.type === "element" && node.children) {
|
||||
return node.children.map(getTextContent).join("");
|
||||
}
|
||||
|
||||
return '';
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
// Process all child nodes
|
||||
if (result.children) {
|
||||
for (let i = 0; i < result.children.length; i++) {
|
||||
|
|
@ -221,39 +252,44 @@ export function highlightCode(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return elements;
|
||||
|
||||
} catch (error) {
|
||||
// Fallback to plain text on error
|
||||
return [React.createElement(Text, { key: 'error-fallback', color: theme.default }, code)];
|
||||
return [
|
||||
React.createElement(
|
||||
Text,
|
||||
{ key: "error-fallback", color: theme.default },
|
||||
code
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export function detectLanguage(code: string): string {
|
||||
// Simple language detection based on common patterns
|
||||
const patterns = [
|
||||
{ regex: /^\s*import\s+.*from\s+['"]/, language: 'javascript' },
|
||||
{ regex: /^\s*const\s+\w+\s*=\s*require\s*\(/, language: 'javascript' },
|
||||
{ regex: /^\s*function\s+\w+\s*\(/, language: 'javascript' },
|
||||
{ regex: /^\s*interface\s+\w+\s*\{/, language: 'typescript' },
|
||||
{ regex: /^\s*type\s+\w+\s*=/, language: 'typescript' },
|
||||
{ regex: /^\s*def\s+\w+\s*\(/, language: 'python' },
|
||||
{ regex: /^\s*class\s+\w+\s*:/, language: 'python' },
|
||||
{ regex: /^\s*public\s+class\s+\w+/, language: 'java' },
|
||||
{ regex: /^\s*#include\s*</, language: 'c' },
|
||||
{ regex: /^\s*using\s+namespace\s+/, language: 'cpp' },
|
||||
{ regex: /^\s*using\s+System\s*;/, language: 'csharp' },
|
||||
{ regex: /^\s*package\s+main/, language: 'go' },
|
||||
{ regex: /^\s*fn\s+\w+\s*\(/, language: 'rust' },
|
||||
{ regex: /^\s*<\?php/, language: 'php' },
|
||||
{ regex: /^\s*SELECT\s+.*FROM\s+/i, language: 'sql' },
|
||||
{ regex: /^\s*\{[\s\S]*".*":\s*/, language: 'json' },
|
||||
{ regex: /^\s*---\s*$/, language: 'yaml' },
|
||||
{ regex: /^\s*#!/, language: 'bash' },
|
||||
{ regex: /^\s*<(!DOCTYPE html|html)/i, language: 'html' },
|
||||
{ regex: /^\s*@media\s+/, language: 'css' },
|
||||
{ regex: /^\s*#\s+/, language: 'markdown' }
|
||||
{ regex: /^\s*import\s+.*from\s+['"]/, language: "javascript" },
|
||||
{ regex: /^\s*const\s+\w+\s*=\s*require\s*\(/, language: "javascript" },
|
||||
{ regex: /^\s*function\s+\w+\s*\(/, language: "javascript" },
|
||||
{ regex: /^\s*interface\s+\w+\s*\{/, language: "typescript" },
|
||||
{ regex: /^\s*type\s+\w+\s*=/, language: "typescript" },
|
||||
{ regex: /^\s*def\s+\w+\s*\(/, language: "python" },
|
||||
{ regex: /^\s*class\s+\w+\s*:/, language: "python" },
|
||||
{ regex: /^\s*public\s+class\s+\w+/, language: "java" },
|
||||
{ regex: /^\s*#include\s*</, language: "c" },
|
||||
{ regex: /^\s*using\s+namespace\s+/, language: "cpp" },
|
||||
{ regex: /^\s*using\s+System\s*;/, language: "csharp" },
|
||||
{ regex: /^\s*package\s+main/, language: "go" },
|
||||
{ regex: /^\s*fn\s+\w+\s*\(/, language: "rust" },
|
||||
{ regex: /^\s*<\?php/, language: "php" },
|
||||
{ regex: /^\s*SELECT\s+.*FROM\s+/i, language: "sql" },
|
||||
{ regex: /^\s*\{[\s\S]*".*":\s*/, language: "json" },
|
||||
{ regex: /^\s*---\s*$/, language: "yaml" },
|
||||
{ regex: /^\s*#!/, language: "bash" },
|
||||
{ regex: /^\s*<(!DOCTYPE html|html)/i, language: "html" },
|
||||
{ regex: /^\s*@media\s+/, language: "css" },
|
||||
{ regex: /^\s*#\s+/, language: "markdown" },
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
|
|
@ -262,5 +298,5 @@ export function detectLanguage(code: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
return 'javascript'; // default fallback
|
||||
}
|
||||
return "javascript"; // default fallback
|
||||
}
|
||||
|
|
|
|||
16
src/version.ts
Normal file
16
src/version.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { readFileSync } from "fs";
|
||||
import { dirname, join } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
export function getVersion(): string {
|
||||
try {
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const packageJsonPath = join(__dirname, "../package.json");
|
||||
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
||||
return packageJson.version;
|
||||
} catch (error) {
|
||||
console.warn("Warning: Could not read version from package.json");
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue