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

projectScripts.ts

87 lines2.7 KB

1import {
2 MAX_SCRIPT_ID_LENGTH,
3 SCRIPT_RUN_COMMAND_PATTERN,
4 type KeybindingCommand,
5 type ProjectScript,
6} from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8const isScriptRunCommand = Schema.is(SCRIPT_RUN_COMMAND_PATTERN);
9​
10export interface ProjectScriptInput {
11 readonly name: ProjectScript["name"];
12 readonly command: ProjectScript["command"];
13 readonly icon: ProjectScript["icon"];
14 readonly runOnWorktreeCreate: ProjectScript["runOnWorktreeCreate"];
15 readonly previewUrl: Exclude<ProjectScript["previewUrl"], undefined> | null;
16 readonly autoOpenPreview: boolean;
18​
19export function buildProjectScript(id: string, input: ProjectScriptInput): ProjectScript {
20 return {
21 id,
22 name: input.name,
23 command: input.command,
24 icon: input.icon,
25 runOnWorktreeCreate: input.runOnWorktreeCreate,
26 ...(input.previewUrl === null
27 ? {}
28 : {
29 previewUrl: input.previewUrl,
30 autoOpenPreview: input.autoOpenPreview,
31 }),
32 };
34​
35function normalizeScriptId(value: string): string {
36 const cleaned = value
37 .trim()
38 .toLowerCase()
39 .replace(/[^a-z0-9]+/g, "-")
40 .replace(/^-+|-+$/g, "");
41 if (cleaned.length === 0) {
42 return "script";
43 }
44 if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
45 return cleaned;
46 }
47 return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
49​
50export const commandForProjectScript = (scriptId: string): KeybindingCommand =>
51 SCRIPT_RUN_COMMAND_PATTERN.make(`script.${scriptId}.run`);
52​
53export function projectScriptIdFromCommand(command: string): string | null {
54 const trimmed = command.trim();
55 if (!isScriptRunCommand(trimmed)) {
56 return null;
57 }
58 const [prefix, , suffix] = SCRIPT_RUN_COMMAND_PATTERN.parts;
59 return trimmed.slice(prefix.literal.length, -suffix.literal.length);
61​
62export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
63 const taken = new Set(Array.from(existingIds));
64 const baseId = normalizeScriptId(name);
65 if (!taken.has(baseId)) return baseId;
66​
67 let suffix = 2;
68 while (suffix < 10_000) {
69 const candidate = `${baseId}-${suffix}`;
70 const safeCandidate =
71 candidate.length <= MAX_SCRIPT_ID_LENGTH
72 ? candidate
73 : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
74 if (!taken.has(safeCandidate)) {
75 return safeCandidate;
76 }
77 suffix += 1;
78 }
79​
80 // This last-resort fallback only triggers after exhausting thousands of suffixes.
81 return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
83​
84export function primaryProjectScript(scripts: ReadonlyArray<ProjectScript>): ProjectScript | null {
85 const regular = scripts.find((script) => !script.runOnWorktreeCreate);
86 return regular ?? scripts[0] ?? null;