Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectScripts.ts

61 lines1.9 KB

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