76 lines
1.8 KiB
TypeScript
76 lines
1.8 KiB
TypeScript
/**
|
|
* Splits a command line into argv tokens without invoking a shell, so that quoted JSON payloads
|
|
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
|
|
* need it; importing it from the server entry would make the CLI graph circular.
|
|
*/
|
|
import { usageError } from "../core/errors.js";
|
|
export function tokenizeCommand(command: string): string[] {
|
|
const tokens: string[] = [];
|
|
let token = "";
|
|
let quote: "'" | '"' | undefined;
|
|
let escaped = false;
|
|
let tokenStarted = false;
|
|
|
|
for (const character of command) {
|
|
if (escaped) {
|
|
token += character;
|
|
escaped = false;
|
|
tokenStarted = true;
|
|
continue;
|
|
}
|
|
|
|
if (character === "\\" && quote !== "'") {
|
|
escaped = true;
|
|
tokenStarted = true;
|
|
continue;
|
|
}
|
|
|
|
if (quote) {
|
|
if (character === quote) {
|
|
quote = undefined;
|
|
} else {
|
|
token += character;
|
|
}
|
|
tokenStarted = true;
|
|
continue;
|
|
}
|
|
|
|
if (character === "'" || character === '"') {
|
|
quote = character;
|
|
tokenStarted = true;
|
|
continue;
|
|
}
|
|
|
|
if (/\s/.test(character)) {
|
|
if (tokenStarted) {
|
|
tokens.push(token);
|
|
token = "";
|
|
tokenStarted = false;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
token += character;
|
|
tokenStarted = true;
|
|
}
|
|
|
|
if (escaped) throw usageError("Invalid command: trailing escape");
|
|
if (quote) throw usageError("Invalid command: unterminated quote");
|
|
if (tokenStarted) tokens.push(token);
|
|
return tokens;
|
|
}
|
|
|
|
export function normalizeCliArgs(tokens: string[]): string[] {
|
|
const first = tokens[0];
|
|
if (!first) return [];
|
|
if (
|
|
first === "seal-use" ||
|
|
first === "seal-home" ||
|
|
first.endsWith("/seal-use") ||
|
|
first.endsWith("/seal-home")
|
|
) {
|
|
return tokens.slice(1);
|
|
}
|
|
return tokens;
|
|
}
|