repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/composer.ts

Raw
File outline
export type ComposerParseResult =
	| {
			kind: "prompt";
			text: string;
			refs: string[];
	  }
	| {
			kind: "slash";
			command: string;
			args: string;
			text: string;
			refs: string[];
	  }
	| {
			kind: "bash";
			command: string;
			excludeFromContext: boolean;
			refs: string[];
	  };

const REF_RE = /(^|\s)@([^\s]+)/g;

export function parseComposerInput(input: string): ComposerParseResult {
	const text = input.trim();
	if (text.startsWith("!!")) {
		return {
			kind: "bash",
			command: text.slice(2).trimStart(),
			excludeFromContext: true,
			refs: [],
		};
	}
	if (text.startsWith("!")) {
		return {
			kind: "bash",
			command: text.slice(1).trimStart(),
			excludeFromContext: false,
			refs: [],
		};
	}
	if (text.startsWith("/") && text.length > 1) {
		const body = text.slice(1);
		const space = body.search(/\s/);
		const command = space === -1 ? body : body.slice(0, space);
		const args = space === -1 ? "" : body.slice(space).trimStart();
		return {
			kind: "slash",
			command,
			args,
			text,
			refs: refs(text),
		};
	}
	return { kind: "prompt", text, refs: refs(text) };
}

function refs(text: string): string[] {
	return [...text.matchAll(REF_RE)].map((match) => match[2]);
}