Open History to see the last commit
1import {
2 MAX_SCRIPT_ID_LENGTH,
3 SCRIPT_RUN_COMMAND_PATTERN,
4 type KeybindingCommand,
5 type ProjectScript,
6} from "@v12/contracts";
7import * as Schema from "effect/Schema";
8const isScriptRunCommand = Schema.is(SCRIPT_RUN_COMMAND_PATTERN);
9
10function normalizeScriptId(value: string): string {
11 const cleaned = value
12 .trim()
13 .toLowerCase()
14 .replace(/[^a-z0-9]+/g, "-")
15 .replace(/^-+|-+$/g, "");
16 if (cleaned.length === 0) {
17 return "script";
18 }
19 if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
20 return cleaned;
21 }
22 return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
23}
24
25export const commandForProjectScript = (scriptId: string): KeybindingCommand =>
26 SCRIPT_RUN_COMMAND_PATTERN.make(`script.${scriptId}.run`);
27
28export function projectScriptIdFromCommand(command: string): string | null {
29 const trimmed = command.trim();
30 if (!isScriptRunCommand(trimmed)) {
31 return null;
32 }
33 const [prefix, , suffix] = SCRIPT_RUN_COMMAND_PATTERN.parts;
34 return trimmed.slice(prefix.literal.length, -suffix.literal.length);
35}
36
37export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
38 const taken = new Set(Array.from(existingIds));
39 const baseId = normalizeScriptId(name);
40 if (!taken.has(baseId)) return baseId;
41
42 let suffix = 2;
43 while (suffix < 10_000) {
44 const candidate = `${baseId}-${suffix}`;
45 const safeCandidate =
46 candidate.length <= MAX_SCRIPT_ID_LENGTH
47 ? candidate
48 : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
49 if (!taken.has(safeCandidate)) {
50 return safeCandidate;
51 }
52 suffix += 1;
53 }
54
55 // This last-resort fallback only triggers after exhausting thousands of suffixes.
56 return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
57}
58
59export function primaryProjectScript(scripts: ReadonlyArray<ProjectScript>): ProjectScript | null {
60 const regular = scripts.find((script) => !script.runOnWorktreeCreate);
61 return regular ?? scripts[0] ?? null;
62}