Open History to see the last commit
1import type { ProjectScript } from "@t3tools/contracts";
2
3const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
4const MAX_SCRIPT_ID_LENGTH = 64;
5
6function normalizeScriptId(value: string): string {
7 const cleaned = value
8 .trim()
9 .toLowerCase()
10 .replace(/[^a-z0-9]+/g, "-")
11 .replace(/^-+|-+$/g, "");
12 if (cleaned.length === 0) {
13 return "script";
14 }
15 if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
16 return cleaned;
17 }
18 return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
19}
20
21export function commandForProjectScript(scriptId: string): string {
22 return `script.${scriptId}.run`;
23}
24
25export function projectScriptIdFromCommand(command: string): string | null {
26 const match = SCRIPT_RUN_COMMAND_PATTERN.exec(command.trim());
27 return match?.[1] ?? null;
28}
29
30export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
31 const taken = new Set(Array.from(existingIds));
32 const baseId = normalizeScriptId(name);
33 if (!taken.has(baseId)) return baseId;
34
35 let suffix = 2;
36 while (suffix < 10_000) {
37 const candidate = `${baseId}-${suffix}`;
38 const safeCandidate =
39 candidate.length <= MAX_SCRIPT_ID_LENGTH
40 ? candidate
41 : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
42 if (!taken.has(safeCandidate)) {
43 return safeCandidate;
44 }
45 suffix += 1;
46 }
47
48 // This last-resort fallback only triggers after exhausting thousands of suffixes.
49 return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
50}
51
52interface ProjectScriptRuntimeEnvInput {
53 project: {
54 cwd: string;
55 };
56 worktreePath?: string | null;
57 extraEnv?: Record<string, string>;
58}
59
60export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
61 const env: Record<string, string> = {
62 T3CODE_PROJECT_ROOT: input.project.cwd,
63 };
64 if (input.worktreePath) {
65 env.T3CODE_WORKTREE_PATH = input.worktreePath;
66 }
67 if (input.extraEnv) {
68 return { ...env, ...input.extraEnv };
69 }
70 return env;
71}
72
73export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
74 const regular = scripts.find((script) => !script.runOnWorktreeCreate);
75 return regular ?? scripts[0] ?? null;
76}
77
78export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
79 return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
80}