designsource 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +112 -20
  2. package/dist/index.js +3279 -257
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,5 +1,926 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/connect/apps.ts
4
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
5
+ import { posix as posix3, win32 } from "node:path";
6
+
7
+ // src/add/setup.ts
8
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "node:fs";
9
+ import { join as join2, posix as posix2 } from "node:path";
10
+
11
+ // src/errors.ts
12
+ var CliError = class extends Error {
13
+ constructor(message, exitCode = 1) {
14
+ super(message);
15
+ this.exitCode = exitCode;
16
+ }
17
+ exitCode;
18
+ };
19
+ var CANCELLED = "Cancelled.";
20
+ var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
21
+ var MCP_TOKEN_REQUIRED = "A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).";
22
+ var UNREACHABLE = (api) => `Could not reach ${api}.`;
23
+ var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
24
+ var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
25
+ function messageForResponse(status, body, api) {
26
+ if (status === 401) return TOKEN_MESSAGE;
27
+ if (status === 402) return PLAN_MESSAGE;
28
+ const serverMessage = typeof body === "object" && body !== null && typeof body.error === "string" ? body.error : null;
29
+ if (status === 400) return serverMessage ?? `${api} rejected the request (400).`;
30
+ return `${api} answered ${status}.`;
31
+ }
32
+
33
+ // src/paths.ts
34
+ import { isAbsolute, resolve, sep } from "node:path";
35
+ function resolveInside(root, relPath) {
36
+ const escapes = (why) => new CliError(`Manifest path "${relPath}" is outside the target folder (${why}).`);
37
+ if (!relPath) throw escapes("empty");
38
+ if (isAbsolute(relPath) || /^[a-zA-Z]:[\\/]/.test(relPath) || relPath.startsWith("\\")) throw escapes("absolute");
39
+ if (relPath.split(/[\\/]/).includes("..")) throw escapes("..");
40
+ const abs = resolve(root, relPath);
41
+ if (abs === root || !abs.startsWith(root.endsWith(sep) ? root : root + sep)) throw escapes("resolves above it");
42
+ return abs;
43
+ }
44
+
45
+ // src/add/targets.ts
46
+ import { existsSync, readFileSync } from "node:fs";
47
+ import { join, posix } from "node:path";
48
+ var BAD_COMPONENTS_JSON = "components.json is missing its aliases or tailwind.css path.";
49
+ var noAlias = (alias) => new CliError(`Could not resolve the import alias "${alias}" from tsconfig.json.`);
50
+ var outside = (alias) => new CliError(`The import alias "${alias}" points outside the app folder.`);
51
+ function stripJsonc(text) {
52
+ let out = "";
53
+ let i = 0;
54
+ while (i < text.length) {
55
+ const c = text[i];
56
+ if (c === '"') {
57
+ let j = i + 1;
58
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
59
+ out += text.slice(i, j + 1);
60
+ i = j + 1;
61
+ } else if (c === "/" && text[i + 1] === "/") {
62
+ while (i < text.length && text[i] !== "\n") i++;
63
+ } else if (c === "/" && text[i + 1] === "*") {
64
+ const end = text.indexOf("*/", i + 2);
65
+ i = end === -1 ? text.length : end + 2;
66
+ } else {
67
+ out += c;
68
+ i++;
69
+ }
70
+ }
71
+ return out.replace(/,(\s*[}\]])/g, "$1");
72
+ }
73
+ function readTsconfig(path) {
74
+ if (!existsSync(path)) return null;
75
+ try {
76
+ const json = JSON.parse(stripJsonc(readFileSync(path, "utf8")));
77
+ return typeof json === "object" && json !== null ? json : null;
78
+ } catch {
79
+ throw new CliError(`${path.slice(path.lastIndexOf("/") + 1)} is not valid JSON.`);
80
+ }
81
+ }
82
+ function pathsOf(config) {
83
+ const options = config?.compilerOptions;
84
+ if (typeof options !== "object" || options === null) return null;
85
+ const { paths, baseUrl } = options;
86
+ if (typeof paths !== "object" || paths === null) return null;
87
+ const clean = Object.fromEntries(Object.entries(paths).filter((e) => Array.isArray(e[1]) && typeof e[1][0] === "string"));
88
+ return { paths: clean, baseUrl: typeof baseUrl === "string" ? baseUrl : "." };
89
+ }
90
+ function readPaths(root) {
91
+ const base = readTsconfig(join(root, "tsconfig.json"));
92
+ return pathsOf(base) ?? (base?.references ? pathsOf(readTsconfig(join(root, "tsconfig.app.json"))) : null);
93
+ }
94
+ function resolveAlias(alias, tsconfig) {
95
+ if (!tsconfig) throw noAlias(alias);
96
+ let best = null;
97
+ for (const [key, targets] of Object.entries(tsconfig.paths)) {
98
+ const star = key.indexOf("*");
99
+ const prefix = star === -1 ? key : key.slice(0, star);
100
+ const suffix = star === -1 ? "" : key.slice(star + 1);
101
+ const matches = star === -1 ? alias === key : alias.startsWith(prefix) && alias.endsWith(suffix) && alias.length >= prefix.length + suffix.length;
102
+ if (!matches || best && best.prefixLength >= prefix.length) continue;
103
+ const rest = star === -1 ? "" : alias.slice(prefix.length, alias.length - suffix.length);
104
+ const target = targets[0];
105
+ best = { prefixLength: prefix.length, resolved: star === -1 ? target : target.replace("*", () => rest) };
106
+ }
107
+ if (!best) throw noAlias(alias);
108
+ const relative5 = posix.normalize(posix.join(tsconfig.baseUrl, best.resolved));
109
+ if (relative5 === ".." || relative5.startsWith("../") || posix.isAbsolute(relative5)) throw outside(alias);
110
+ return relative5 === "." ? "" : relative5;
111
+ }
112
+ function resolveTargets(root, shadcn) {
113
+ const { aliases, tailwind } = shadcn ?? {};
114
+ if (typeof aliases?.components !== "string" || typeof aliases.utils !== "string" || typeof tailwind?.css !== "string") throw new CliError(BAD_COMPONENTS_JSON);
115
+ const tsconfig = readPaths(root);
116
+ const uiAlias = typeof aliases.ui === "string" ? aliases.ui : `${aliases.components}/ui`;
117
+ const uiDir = resolveAlias(uiAlias, tsconfig);
118
+ const utilsFile = `${resolveAlias(aliases.utils, tsconfig)}.ts`;
119
+ return {
120
+ uiDir,
121
+ utilsFile,
122
+ cssFile: tailwind.css,
123
+ uiAlias,
124
+ utilsAlias: aliases.utils,
125
+ componentsDir: componentsDirOf(aliases.components, tsconfig),
126
+ componentsAlias: aliases.components,
127
+ ...libOf(utilsFile, aliases.utils)
128
+ };
129
+ }
130
+ function componentsDirOf(alias, tsconfig) {
131
+ try {
132
+ const file = resolveAlias(`${alias}/x`, tsconfig);
133
+ const dir = posix.dirname(file);
134
+ return dir === "." ? "" : dir;
135
+ } catch {
136
+ try {
137
+ return resolveAlias(alias, tsconfig);
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ }
143
+ function libOf(utilsFile, utilsAlias) {
144
+ const dir = posix.dirname(utilsFile);
145
+ const slash = utilsAlias.lastIndexOf("/");
146
+ return { libDir: dir === "." ? "" : dir, libAlias: slash > 0 ? utilsAlias.slice(0, slash) : "" };
147
+ }
148
+ function rewriteForApp(contents, t) {
149
+ return contents.replace(/(['"])@\/components\/ui\//g, (_, q) => `${q}${t.uiAlias}/`).replace(/(['"])@\/lib\/utils\1/g, (_, q) => `${q}${t.utilsAlias}${q}`).replace(/(['"])@\/components\/(design-system|blocks)\//g, (_, q, dir) => `${q}${t.componentsAlias}/${dir}/`).replace(/(['"])@\/components\/(preview-gallery|custom-surface|sample-surfaces)\1/g, (_, q, file) => `${q}${t.componentsAlias}/${file}${q}`).replace(/(['"])@\/lib\/(mockup-schema|surface-inference)\1/g, (_, q, file) => `${q}${t.libAlias}/${file}${q}`);
150
+ }
151
+
152
+ // src/add/setup.ts
153
+ var StepError = class extends CliError {
154
+ constructor(message, outputTail2) {
155
+ super(message);
156
+ this.outputTail = outputTail2;
157
+ }
158
+ outputTail;
159
+ };
160
+ var OUTPUT_TAIL_LINES = 20;
161
+ var VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
162
+ var POSTCSS_CONFIGS = ["postcss.config.mjs", "postcss.config.js", "postcss.config.cjs", "postcss.config.ts", ".postcssrc", ".postcssrc.json"];
163
+ var NO_POSTCSS_TAILWIND = 'This app has a PostCSS config without Tailwind. Add "@tailwindcss/postcss" to its plugins, then run this again.';
164
+ var NO_STYLESHEET = "Could not find the app's global stylesheet (app/globals.css or src/index.css). Create it, import it in your root layout or entry file, then run this again.";
165
+ var NO_VITE_TAILWIND = "Could not add Tailwind to vite.config.ts automatically. Add the @tailwindcss/vite plugin, then run this again.";
166
+ var NO_VITE_ALIAS = 'Could not add the @/ import alias to vite.config.ts automatically. Add resolve.alias for "@", then run this again.';
167
+ var noTsconfigAlias = (file) => new CliError(`Could not add the @/ import alias to ${file} automatically. Add "paths": { "@/*": ["./src/*"] }, then run this again.`);
168
+ function installArgs(pm, pkgs, dev) {
169
+ const specs = Object.entries(pkgs).map(([name, range]) => `${name}@${range}`);
170
+ const verb = pm === "npm" ? "install" : "add";
171
+ const flag = dev ? [pm === "bun" ? "-d" : "-D"] : [];
172
+ return [pm, [verb, ...flag, ...specs]];
173
+ }
174
+ function outputTail(output) {
175
+ return output.trimEnd().split("\n").slice(-OUTPUT_TAIL_LINES).join("\n");
176
+ }
177
+ async function run(exec, cwd, cmd, args) {
178
+ const { code: code2, output } = await exec(cmd, args, { cwd });
179
+ if (code2 === 0) return;
180
+ throw new StepError(`${cmd} ${args.join(" ")} failed (exit ${code2}).`, outputTail(output));
181
+ }
182
+ function findGlobalStylesheet(info) {
183
+ const candidates = info.framework === "next" ? ["app/globals.css", "src/app/globals.css"] : info.framework === "vite" ? ["src/index.css"] : ["app/globals.css", "src/app/globals.css", "src/index.css"];
184
+ const found = candidates.find((file) => existsSync2(join2(info.root, file)));
185
+ if (!found) throw new CliError(NO_STYLESHEET);
186
+ return found;
187
+ }
188
+ function maskComments(text, { line = true } = {}) {
189
+ let out = "";
190
+ let i = 0;
191
+ while (i < text.length) {
192
+ const c = text[i];
193
+ if (c === '"' || c === "'" || c === "`") {
194
+ let j = i + 1;
195
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
196
+ const end = Math.min(j + 1, text.length);
197
+ out += text.slice(i, end);
198
+ i = end;
199
+ } else if (line && c === "/" && text[i + 1] === "/") {
200
+ let j = i;
201
+ while (j < text.length && text[j] !== "\n") j++;
202
+ out += " ".repeat(j - i);
203
+ i = j;
204
+ } else if (c === "/" && text[i + 1] === "*") {
205
+ const close = text.indexOf("*/", i + 2);
206
+ const end = close === -1 ? text.length : close + 2;
207
+ out += text.slice(i, end).replace(/[^\n]/g, " ");
208
+ i = end;
209
+ } else {
210
+ out += c;
211
+ i++;
212
+ }
213
+ }
214
+ return out;
215
+ }
216
+ function pinned(manifest, name) {
217
+ const range = manifest.devPackages[name];
218
+ if (!range) throw new CliError(`The kit manifest does not pin ${name}.`);
219
+ return range;
220
+ }
221
+ function readText(info, rel) {
222
+ return readFileSync2(resolveInside(info.root, rel), "utf8");
223
+ }
224
+ function writeText(info, rel, text) {
225
+ writeFileSync(resolveInside(info.root, rel), text);
226
+ }
227
+ function firstExisting(info, files) {
228
+ return files.find((file) => existsSync2(join2(info.root, file))) ?? null;
229
+ }
230
+ function insertAt(text, index, insert) {
231
+ return text.slice(0, index) + insert + text.slice(index);
232
+ }
233
+ function insertImports(text, lines) {
234
+ const masked = maskComments(text);
235
+ let end = -1;
236
+ for (const m of masked.matchAll(/^[ \t]*import\s[^;]*?['"][^'"\n]*['"][ \t]*;?/gm)) end = m.index + m[0].length;
237
+ if (end !== -1) {
238
+ const semi = text[end - 1] === ";" ? ";" : "";
239
+ return insertAt(text, end, lines.map((line) => `
240
+ ${line}${semi}`).join(""));
241
+ }
242
+ const leading = /^(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/))*/.exec(text)[0].length;
243
+ const block = lines.join("\n");
244
+ return leading === 0 ? `${block}
245
+ ${text}` : insertAt(text, leading, `
246
+ ${block}`);
247
+ }
248
+ function editViteTailwind(text) {
249
+ const masked = maskComments(text);
250
+ const plugins = /\bplugins\s*:\s*\[/.exec(masked);
251
+ if (!plugins) throw new CliError(NO_VITE_TAILWIND);
252
+ const imported = /\bimport\s+(\w+)\s+from\s*['"]@tailwindcss\/vite['"]/.exec(masked);
253
+ if (!imported && masked.includes("@tailwindcss/vite")) throw new CliError(NO_VITE_TAILWIND);
254
+ const local = imported?.[1] ?? "tailwindcss";
255
+ if (new RegExp(`\\b${local}\\s*\\(`).test(masked)) return text;
256
+ const withCall = insertAt(text, plugins.index + plugins[0].length, `${local}(), `);
257
+ return imported ? withCall : insertImports(withCall, ["import tailwindcss from '@tailwindcss/vite'"]);
258
+ }
259
+ function viteHasAlias(masked) {
260
+ return /['"]@['"]\s*:/.test(masked) || /\bfind\s*:\s*['"]@['"]/.test(masked);
261
+ }
262
+ function ensureNodeUrlImports(text, refusal = NO_VITE_ALIAS) {
263
+ const masked = maskComments(text);
264
+ const wanted = ["fileURLToPath", "URL"];
265
+ const named = /\bimport\s*\{([^}]*)\}\s*from\s*(['"])(?:node:)?url\2/.exec(masked);
266
+ if (!named) {
267
+ if (/\bfrom\s*['"](?:node:)?url['"]/.test(masked)) throw new CliError(refusal);
268
+ return insertImports(text, [`import { ${wanted.join(", ")} } from 'node:url'`]);
269
+ }
270
+ const have = named[1].split(",").map((name) => name.trim());
271
+ const missing = wanted.filter((name) => !have.includes(name));
272
+ if (missing.length === 0) return text;
273
+ const inner = named[1];
274
+ const start = named.index + named[0].indexOf("{") + 1;
275
+ const next = inner.trim() === "" ? ` ${missing.join(", ")} ` : `${inner.trimEnd()}, ${missing.join(", ")}${/\s*$/.exec(inner)[0]}`;
276
+ return text.slice(0, start) + next + text.slice(start + inner.length);
277
+ }
278
+ function editViteAlias(text, srcDir) {
279
+ const masked = maskComments(text);
280
+ if (viteHasAlias(masked)) return text;
281
+ const define = /\bdefineConfig\(\s*\{/.exec(masked);
282
+ if (/\bresolve\s*:/.test(masked) || !define) throw new CliError(NO_VITE_ALIAS);
283
+ const alias = `
284
+ resolve: { alias: { '@': fileURLToPath(new URL('./${srcDir}', import.meta.url)) } },`;
285
+ return ensureNodeUrlImports(insertAt(text, define.index + define[0].length, alias));
286
+ }
287
+ var VITE_INPUT_MANUAL = "Could not add design-system.html to vite.config automatically. Add it to build.rollupOptions.input beside index.html so the built site includes /design-system.html.";
288
+ var VITE_INPUTS = `
289
+ build: {
290
+ rollupOptions: {
291
+ input: {
292
+ main: fileURLToPath(new URL('./index.html', import.meta.url)),
293
+ 'design-system': fileURLToPath(new URL('./design-system.html', import.meta.url)),
294
+ },
295
+ },
296
+ },`;
297
+ function editViteInputs(text) {
298
+ const masked = maskComments(text);
299
+ if (masked.includes("design-system.html")) return text;
300
+ const define = /\bdefineConfig\(\s*\{/.exec(masked);
301
+ if (/\bbuild\s*:/.test(masked) || !define) throw new CliError(VITE_INPUT_MANUAL);
302
+ return ensureNodeUrlImports(insertAt(text, define.index + define[0].length, VITE_INPUTS), VITE_INPUT_MANUAL);
303
+ }
304
+ function listViteInputStep(info) {
305
+ const file = firstExisting(info, VITE_CONFIGS);
306
+ if (!file || !existsSync2(join2(info.root, "index.html"))) throw new CliError(VITE_INPUT_MANUAL);
307
+ const text = readText(info, file);
308
+ if (editViteInputs(text) === text) return null;
309
+ return {
310
+ line: "Listing design-system.html in vite.config\u2026",
311
+ run: async () => writeText(info, file, editViteInputs(readText(info, file)))
312
+ };
313
+ }
314
+ function aliasTarget(baseUrl, srcDir) {
315
+ const rel = posix2.relative(posix2.normalize(baseUrl), srcDir) || ".";
316
+ return `${rel === "." ? "." : rel.startsWith("..") ? rel : `./${rel}`}/*`;
317
+ }
318
+ function editTsconfig(text, config, file, srcDir) {
319
+ const options = config.compilerOptions;
320
+ const masked = maskComments(text);
321
+ if (typeof options !== "object" || options === null) {
322
+ const open2 = /^\s*\{/.exec(masked);
323
+ if (config.extends !== void 0 || !config.references || !open2) throw noTsconfigAlias(file);
324
+ return insertAt(text, open2[0].length, `
325
+ "compilerOptions": {
326
+ "paths": { "@/*": ["${aliasTarget(".", srcDir)}"] }
327
+ },`);
328
+ }
329
+ const { paths, baseUrl } = options;
330
+ if (typeof paths === "object" && paths !== null && "@/*" in paths) return text;
331
+ const entry = `"@/*": ["${aliasTarget(typeof baseUrl === "string" ? baseUrl : ".", srcDir)}"]`;
332
+ if (typeof paths === "object" && paths !== null) {
333
+ const open2 = /"paths"\s*:\s*\{/.exec(masked);
334
+ if (!open2) throw noTsconfigAlias(file);
335
+ return insertAt(text, open2.index + open2[0].length, ` ${entry},`);
336
+ }
337
+ const open = /"compilerOptions"\s*:\s*\{/.exec(masked);
338
+ if (config.extends !== void 0 || !open) throw noTsconfigAlias(file);
339
+ return insertAt(text, open.index + open[0].length, `
340
+ "paths": { ${entry} },`);
341
+ }
342
+ function addTailwind(info, manifest, exec) {
343
+ const vite = info.framework === "vite";
344
+ const plugin = vite ? "@tailwindcss/vite" : "@tailwindcss/postcss";
345
+ const pkgs = { tailwindcss: pinned(manifest, "tailwindcss"), [plugin]: pinned(manifest, plugin) };
346
+ const viteFile = vite ? firstExisting(info, VITE_CONFIGS) : null;
347
+ if (vite) {
348
+ if (!viteFile) throw new CliError(NO_VITE_TAILWIND);
349
+ editViteTailwind(readText(info, viteFile));
350
+ } else {
351
+ const postcss = firstExisting(info, POSTCSS_CONFIGS);
352
+ if (postcss && !readText(info, postcss).includes("@tailwindcss/postcss")) throw new CliError(NO_POSTCSS_TAILWIND);
353
+ }
354
+ return {
355
+ line: "Adding Tailwind",
356
+ run: async () => {
357
+ const [cmd, args] = installArgs(info.packageManager, pkgs, true);
358
+ await run(exec, info.root, cmd, args);
359
+ if (viteFile) writeText(info, viteFile, editViteTailwind(readText(info, viteFile)));
360
+ else if (!firstExisting(info, POSTCSS_CONFIGS)) writeText(info, "postcss.config.mjs", `export default {
361
+ plugins: {
362
+ '@tailwindcss/postcss': {},
363
+ },
364
+ }
365
+ `);
366
+ }
367
+ };
368
+ }
369
+ function upgradeTailwind(info, manifest, exec) {
370
+ const version = pinned(manifest, "tailwindcss").replace(/^[\s^~>=v]+/, "");
371
+ return { line: "Upgrading Tailwind to v4", run: () => run(exec, info.root, "npx", ["--yes", `@tailwindcss/upgrade@${version}`]) };
372
+ }
373
+ function aliasEdits(info, srcDir, viteText) {
374
+ const edits = [];
375
+ if (!readPaths(info.root)?.paths["@/*"]) {
376
+ if (!existsSync2(join2(info.root, "tsconfig.json"))) throw noTsconfigAlias("tsconfig.json");
377
+ for (const file of ["tsconfig.json", "tsconfig.app.json"]) {
378
+ if (file === "tsconfig.app.json" && !existsSync2(join2(info.root, file))) continue;
379
+ const config = readTsconfig(join2(info.root, file));
380
+ if (!config) throw noTsconfigAlias(file);
381
+ edits.push([file, editTsconfig(readText(info, file), config, file, srcDir)]);
382
+ }
383
+ }
384
+ if (info.framework === "vite") {
385
+ const file = firstExisting(info, VITE_CONFIGS);
386
+ if (!file) throw new CliError(NO_VITE_ALIAS);
387
+ edits.push([file, editViteAlias(viteText(file), srcDir)]);
388
+ }
389
+ return edits;
390
+ }
391
+ function addAlias(info, srcDir, tailwindAddedToVite) {
392
+ aliasEdits(info, srcDir, (file) => tailwindAddedToVite ? editViteTailwind(readText(info, file)) : readText(info, file));
393
+ return {
394
+ line: "Adding the @/ import alias",
395
+ run: async () => {
396
+ for (const [file, text] of aliasEdits(info, srcDir, (f) => readText(info, f))) writeText(info, file, text);
397
+ }
398
+ };
399
+ }
400
+ function needsAlias(info) {
401
+ if (!readPaths(info.root)?.paths["@/*"]) return true;
402
+ if (info.framework !== "vite") return false;
403
+ const file = firstExisting(info, VITE_CONFIGS);
404
+ return !file || !viteHasAlias(maskComments(readText(info, file)));
405
+ }
406
+ function addShadcnConfig(info, css) {
407
+ return {
408
+ line: "Adding the shadcn config",
409
+ run: async () => {
410
+ const config = {
411
+ $schema: "https://ui.shadcn.com/schema.json",
412
+ style: "new-york",
413
+ rsc: info.framework === "next",
414
+ tsx: true,
415
+ tailwind: { config: "", css, baseColor: "neutral", cssVariables: true, prefix: "" },
416
+ iconLibrary: "lucide",
417
+ aliases: { components: "@/components", utils: "@/lib/utils", ui: "@/components/ui", lib: "@/lib", hooks: "@/hooks" }
418
+ };
419
+ writeText(info, "components.json", `${JSON.stringify(config, null, 2)}
420
+ `);
421
+ }
422
+ };
423
+ }
424
+ function stylesheetHasPreflight(info, css) {
425
+ try {
426
+ const text = maskComments(readText(info, css), { line: false });
427
+ return /@import\s+(?:url\(\s*)?(["'])tailwindcss\1/.test(text) || /@tailwind\s+base\b/.test(text);
428
+ } catch {
429
+ return false;
430
+ }
431
+ }
432
+ function planSetup(info, manifest, exec) {
433
+ const steps = [];
434
+ const css = typeof info.shadcn?.tailwind?.css === "string" ? info.shadcn.tailwind.css : info.shadcn ? null : findGlobalStylesheet(info);
435
+ const srcDir = existsSync2(join2(info.root, "src")) ? "src" : ".";
436
+ if (info.tailwindMajor === null) steps.push(addTailwind(info, manifest, exec));
437
+ else if (info.tailwindMajor < 4) steps.push(upgradeTailwind(info, manifest, exec));
438
+ if (info.shadcn === null) {
439
+ if (needsAlias(info)) steps.push(addAlias(info, srcDir, info.tailwindMajor === null && info.framework === "vite"));
440
+ steps.push(addShadcnConfig(info, css));
441
+ }
442
+ return { steps, preflight: css !== null && stylesheetHasPreflight(info, css) };
443
+ }
444
+
445
+ // src/connect/secret-backends.ts
446
+ var SECRET_SERVICE = "designsource";
447
+ var STORE_TIMEOUT_MS = 15e3;
448
+ var PROJECT_ID = /^[A-Za-z0-9_-]+$/;
449
+ var TOKEN_SHAPE = /^[A-Za-z0-9._-]+$/;
450
+ function assertProjectId(projectId) {
451
+ if (!PROJECT_ID.test(projectId)) throw new CliError("Unexpected project id from the API.");
452
+ }
453
+ function readOutput(result) {
454
+ if (result.code !== 0) return null;
455
+ const value = result.output.trimEnd();
456
+ return value === "" ? null : value;
457
+ }
458
+ function readToken(result) {
459
+ const value = readOutput(result);
460
+ return value !== null && TOKEN_SHAPE.test(value) ? value : null;
461
+ }
462
+ function keychain(exec, cwd) {
463
+ const run2 = (args, opts = {}) => exec("security", args, { cwd, timeoutMs: STORE_TIMEOUT_MS, ...opts });
464
+ const backend = {
465
+ where: "keychain",
466
+ async put(projectId, _name, token) {
467
+ assertProjectId(projectId);
468
+ if (!TOKEN_SHAPE.test(token)) return null;
469
+ const wrote = await run2(["-i"], { input: `add-generic-password -U -s ${SECRET_SERVICE} -a "${projectId}" -w "${token}"
470
+ ` });
471
+ if (wrote.code === 0 && await backend.get(projectId, void 0) === token) return {};
472
+ await backend.remove(projectId);
473
+ return null;
474
+ },
475
+ async get(projectId) {
476
+ assertProjectId(projectId);
477
+ return readToken(await run2(["find-generic-password", "-s", SECRET_SERVICE, "-a", projectId, "-w"], { stdoutOnly: true }));
478
+ },
479
+ async remove(projectId) {
480
+ assertProjectId(projectId);
481
+ await run2(["delete-generic-password", "-s", SECRET_SERVICE, "-a", projectId]);
482
+ }
483
+ };
484
+ return backend;
485
+ }
486
+ function secretService(exec, cwd) {
487
+ const run2 = (args, opts = {}) => exec("secret-tool", args, { cwd, timeoutMs: STORE_TIMEOUT_MS, ...opts });
488
+ const backend = {
489
+ where: "secret-service",
490
+ async put(projectId, name, token) {
491
+ assertProjectId(projectId);
492
+ const wrote = await run2(["store", `--label=${SECRET_SERVICE} ${name}`, "service", SECRET_SERVICE, "project", projectId], { input: token });
493
+ if (wrote.code === 0 && await backend.get(projectId, void 0) === token) return {};
494
+ await backend.remove(projectId);
495
+ return null;
496
+ },
497
+ async get(projectId) {
498
+ assertProjectId(projectId);
499
+ return readToken(await run2(["lookup", "service", SECRET_SERVICE, "project", projectId], { stdoutOnly: true }));
500
+ },
501
+ async remove(projectId) {
502
+ assertProjectId(projectId);
503
+ await run2(["clear", "service", SECRET_SERVICE, "project", projectId]);
504
+ }
505
+ };
506
+ return backend;
507
+ }
508
+ var DPAPI_ENCRYPT = [
509
+ // PowerShell 5.1 otherwise writes progress records (`#< CLIXML`) to stderr.
510
+ "$ProgressPreference = 'SilentlyContinue'",
511
+ "$ErrorActionPreference = 'Stop'",
512
+ "$plain = [Console]::In.ReadToEnd()",
513
+ "[Console]::Out.Write((ConvertTo-SecureString -String $plain -AsPlainText -Force | ConvertFrom-SecureString))"
514
+ ].join("\n");
515
+ var DPAPI_DECRYPT = [
516
+ "$ProgressPreference = 'SilentlyContinue'",
517
+ "$ErrorActionPreference = 'Stop'",
518
+ "$secure = ConvertTo-SecureString -String ([Console]::In.ReadToEnd().Trim())",
519
+ "$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)",
520
+ "try { [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }"
521
+ ].join("\n");
522
+ function powershellArgs(script) {
523
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")];
524
+ }
525
+ function dpapi(exec, cwd) {
526
+ const run2 = (script, input) => exec("powershell", powershellArgs(script), { cwd, timeoutMs: STORE_TIMEOUT_MS, input, stdoutOnly: true });
527
+ const backend = {
528
+ where: "dpapi",
529
+ async put(projectId, _name, token) {
530
+ assertProjectId(projectId);
531
+ const ciphertext = readOutput(await run2(DPAPI_ENCRYPT, token));
532
+ if (ciphertext === null || !/^[0-9a-fA-F]+$/.test(ciphertext)) return null;
533
+ return await backend.get(projectId, ciphertext) === token ? { secret: ciphertext } : null;
534
+ },
535
+ async get(_projectId, secret) {
536
+ if (!secret) return null;
537
+ return readToken(await run2(DPAPI_DECRYPT, secret));
538
+ },
539
+ // The ciphertext lives in the credentials file, which the store rewrites without it.
540
+ async remove() {
541
+ }
542
+ };
543
+ return backend;
544
+ }
545
+ function backendFor(where, exec, cwd) {
546
+ if (where === "keychain") return keychain(exec, cwd);
547
+ if (where === "secret-service") return secretService(exec, cwd);
548
+ return dpapi(exec, cwd);
549
+ }
550
+ async function secretServiceAnswers(exec, cwd) {
551
+ const probe = await exec("secret-tool", ["lookup", "service", SECRET_SERVICE, "project", "designsource-probe"], { cwd, timeoutMs: STORE_TIMEOUT_MS });
552
+ return (probe.code === 0 || probe.code === 1) && !/d-?bus/i.test(probe.output);
553
+ }
554
+ async function chooseBackend(opts) {
555
+ const { platform, exec, cwd, token } = opts;
556
+ if (platform === "darwin") return TOKEN_SHAPE.test(token) ? keychain(exec, cwd) : null;
557
+ if (platform === "linux") return await secretServiceAnswers(exec, cwd) ? secretService(exec, cwd) : null;
558
+ if (platform === "win32") return dpapi(exec, cwd);
559
+ return null;
560
+ }
561
+
562
+ // src/connect/apps.ts
563
+ var SPECS = [
564
+ { id: "claude", label: "Claude Code", file: ".mcp.json", format: { kind: "json", key: "mcpServers", stdioType: false } },
565
+ { id: "cursor", label: "Cursor", file: ".cursor/mcp.json", format: { kind: "json", key: "mcpServers", stdioType: true } },
566
+ { id: "vscode", label: "VS Code", file: ".vscode/mcp.json", format: { kind: "json", key: "servers", stdioType: true } },
567
+ { id: "codex", label: "Codex", file: ".codex/config.toml", format: { kind: "toml" } },
568
+ { id: "gemini", label: "Gemini CLI", file: ".gemini/settings.json", format: { kind: "json", key: "mcpServers", stdioType: false } }
569
+ ];
570
+ var APPS = SPECS.map(({ id, label, file, format }) => ({
571
+ id,
572
+ label,
573
+ file,
574
+ format: format.kind,
575
+ key: format.kind === "json" ? format.key : "mcp_servers"
576
+ }));
577
+ function serverEntry(projectId) {
578
+ assertProjectId(projectId);
579
+ return { command: "npx", args: ["-y", "designsource@latest", "mcp", "--project", projectId] };
580
+ }
581
+ function detectApps({ env, platform, home, exists, onPath: onPath2 }) {
582
+ const path = platform === "win32" ? win32 : posix3;
583
+ const inHome = (...parts) => path.join(home, ...parts);
584
+ const bundle = (name) => platform === "darwin" && exists(`/Applications/${name}.app`);
585
+ const appData = platform === "darwin" ? inHome("Library", "Application Support") : platform === "win32" ? env.APPDATA || inHome("AppData", "Roaming") : env.XDG_CONFIG_HOME && posix3.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : inHome(".config");
586
+ const found = {
587
+ claude: () => onPath2("claude") || exists(inHome(".claude")) || exists(inHome(".claude.json")),
588
+ cursor: () => onPath2("cursor") || exists(inHome(".cursor")) || bundle("Cursor"),
589
+ vscode: () => onPath2("code") || onPath2("code-insiders") || exists(path.join(appData, "Code")) || exists(path.join(appData, "Code - Insiders")) || bundle("Visual Studio Code") || bundle("Visual Studio Code - Insiders"),
590
+ codex: () => onPath2("codex") || exists(inHome(".codex")),
591
+ gemini: () => onPath2("gemini") || exists(inHome(".gemini"))
592
+ };
593
+ return SPECS.map((s) => s.id).filter((id) => found[id]());
594
+ }
595
+ function planAppFile(root, app2, projectId) {
596
+ const spec = SPECS.find((s) => s.id === app2);
597
+ const entry = spec.format.kind === "json" && spec.format.stdioType ? { type: "stdio", ...serverEntry(projectId) } : serverEntry(projectId);
598
+ const abs = resolveInside(root, spec.file);
599
+ let text = null;
600
+ if (existsSync3(abs)) {
601
+ try {
602
+ text = readFileSync3(abs, "utf8");
603
+ } catch {
604
+ throw new CliError(`Could not read ${spec.file}.`);
605
+ }
606
+ }
607
+ return spec.format.kind === "toml" ? planToml(spec.file, text, projectId) : planJson(spec.file, text, spec.format.key, entry, projectId);
608
+ }
609
+ function namesProject(words, projectId) {
610
+ return words.some((w, i) => w === "--project" && words[i + 1] === projectId || w === `--project=${projectId}`);
611
+ }
612
+ function entryWords(entry) {
613
+ if (!isObject(entry)) return [];
614
+ const words = typeof entry.command === "string" ? entry.command.split(/\s+/) : [];
615
+ if (Array.isArray(entry.args)) {
616
+ for (const a of entry.args) if (typeof a === "string") words.push(a);
617
+ }
618
+ return words;
619
+ }
620
+ function isObject(value) {
621
+ return typeof value === "object" && value !== null && !Array.isArray(value);
622
+ }
623
+ function carries(value) {
624
+ return value !== void 0 && !(isObject(value) && Object.keys(value).length === 0);
625
+ }
626
+ function planJson(path, text, key, entry, projectId) {
627
+ if (text === null || text.trim() === "") return { path, status: "create", contents: `${JSON.stringify({ [key]: { designsource: entry } }, null, 2)}
628
+ ` };
629
+ const manual = { path, status: "manual", contents: null, manualEntry: `"designsource": ${JSON.stringify(entry, null, 2)}` };
630
+ const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
631
+ const body = text.slice(bom.length);
632
+ if (maskComments(body) !== body) return manual;
633
+ let parsed;
634
+ try {
635
+ parsed = JSON.parse(body);
636
+ } catch {
637
+ return manual;
638
+ }
639
+ if (!isObject(parsed)) return manual;
640
+ const servers = Object.hasOwn(parsed, key) ? parsed[key] : void 0;
641
+ if (servers !== void 0 && !isObject(servers)) return manual;
642
+ const existing = servers && Object.hasOwn(servers, "designsource") ? servers.designsource : void 0;
643
+ if (existing !== void 0 && namesProject(entryWords(existing), projectId)) {
644
+ return { path, status: "unchanged", contents: text, hasEnv: isObject(existing) && carries(existing.env) };
645
+ }
646
+ return { path, status: "update", contents: bom + insertJsonEntry(body, key, entry) };
647
+ }
648
+ var WS = " \n\r";
649
+ function skipWs(text, i) {
650
+ while (i < text.length && WS.includes(text[i])) i++;
651
+ return i;
652
+ }
653
+ function skipString(text, i) {
654
+ let j = i + 1;
655
+ while (text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
656
+ return j + 1;
657
+ }
658
+ function skipValue(text, i) {
659
+ const c = text[i];
660
+ if (c === '"') return skipString(text, i);
661
+ if (c === "{" || c === "[") {
662
+ let depth = 0;
663
+ let j2 = i;
664
+ for (; ; ) {
665
+ const d = text[j2];
666
+ if (d === '"') {
667
+ j2 = skipString(text, j2);
668
+ continue;
669
+ }
670
+ if (d === "{" || d === "[") depth++;
671
+ else if (d === "}" || d === "]") {
672
+ depth--;
673
+ if (depth === 0) return j2 + 1;
674
+ }
675
+ j2++;
676
+ }
677
+ }
678
+ let j = i;
679
+ while (j < text.length && !",}]".includes(text[j]) && !WS.includes(text[j])) j++;
680
+ return j;
681
+ }
682
+ function objectMembers(text, open) {
683
+ const members = [];
684
+ let i = skipWs(text, open + 1);
685
+ if (text[i] === "}") return { members, close: i };
686
+ for (; ; ) {
687
+ const keyStart = i;
688
+ const keyEnd = skipString(text, i);
689
+ const valueStart = skipWs(text, skipWs(text, keyEnd) + 1);
690
+ const valueEnd = skipValue(text, valueStart);
691
+ members.push({ key: JSON.parse(text.slice(keyStart, keyEnd)), keyStart, valueStart, valueEnd });
692
+ i = skipWs(text, valueEnd);
693
+ if (text[i] !== ",") return { members, close: i };
694
+ i = skipWs(text, i + 1);
695
+ }
696
+ }
697
+ function lastMember(members, key) {
698
+ return members.filter((m) => m.key === key).at(-1);
699
+ }
700
+ function ownLineIndent(text, pos) {
701
+ const before = text.slice(text.lastIndexOf("\n", pos - 1) + 1, pos);
702
+ return /^[ \t]*$/.test(before) ? before : null;
703
+ }
704
+ function lineIndent(text, pos) {
705
+ return /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", pos - 1) + 1))[0];
706
+ }
707
+ function render(value, unit, indent, eol) {
708
+ return JSON.stringify(value, null, unit).split("\n").join(eol + indent);
709
+ }
710
+ function insertJsonEntry(text, key, entry) {
711
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
712
+ const open = skipWs(text, 0);
713
+ const top = objectMembers(text, open);
714
+ const firstTop = top.members[0];
715
+ const unit = firstTop && text.slice(open + 1, firstTop.keyStart).includes("\n") && ownLineIndent(text, firstTop.keyStart) || " ";
716
+ const servers = lastMember(top.members, key);
717
+ if (!servers) {
718
+ const value = { designsource: entry };
719
+ if (!firstTop) return text.slice(0, open + 1) + eol + unit + `${JSON.stringify(key)}: ` + render(value, unit, unit, eol) + eol + text.slice(top.close);
720
+ const indent2 = text.slice(open + 1, firstTop.keyStart).includes("\n") ? ownLineIndent(text, firstTop.keyStart) : null;
721
+ if (indent2 === null) return text.slice(0, open + 1) + `${JSON.stringify(key)}: ${JSON.stringify(value)}, ` + text.slice(open + 1);
722
+ return text.slice(0, open + 1) + eol + indent2 + `${JSON.stringify(key)}: ` + render(value, unit, indent2, eol) + "," + text.slice(open + 1);
723
+ }
724
+ const inner = objectMembers(text, servers.valueStart);
725
+ const existing = lastMember(inner.members, "designsource");
726
+ if (existing) {
727
+ const indent2 = ownLineIndent(text, existing.keyStart);
728
+ const value = indent2 === null ? JSON.stringify(entry) : render(entry, unit, indent2, eol);
729
+ return text.slice(0, existing.valueStart) + value + text.slice(existing.valueEnd);
730
+ }
731
+ const first = inner.members[0];
732
+ const last = inner.members.at(-1);
733
+ if (!first || !last) {
734
+ if (ownLineIndent(text, servers.keyStart) === null && !text.slice(servers.valueStart + 1, inner.close).includes("\n")) {
735
+ return text.slice(0, servers.valueStart + 1) + `"designsource": ${JSON.stringify(entry)}` + text.slice(inner.close);
736
+ }
737
+ const outer = lineIndent(text, servers.keyStart);
738
+ const indent2 = outer + unit;
739
+ return text.slice(0, servers.valueStart + 1) + eol + indent2 + '"designsource": ' + render(entry, unit, indent2, eol) + eol + outer + text.slice(inner.close);
740
+ }
741
+ const indent = text.slice(servers.valueStart + 1, first.keyStart).includes("\n") ? ownLineIndent(text, first.keyStart) : null;
742
+ const addition = indent === null ? `, "designsource": ${JSON.stringify(entry)}` : `,${eol}${indent}"designsource": ${render(entry, unit, indent, eol)}`;
743
+ return text.slice(0, last.valueEnd) + addition + text.slice(last.valueEnd);
744
+ }
745
+ var OURS = ["mcp_servers", "designsource"];
746
+ function codexTable(projectId, eol) {
747
+ const { command, args } = serverEntry(projectId);
748
+ return [`[mcp_servers.designsource]`, `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`, "startup_timeout_sec = 60", ""].join(eol);
749
+ }
750
+ function tomlLines(text) {
751
+ const lines = [];
752
+ let inString = null;
753
+ let depth = 0;
754
+ let start = 0;
755
+ for (; ; ) {
756
+ const nl = text.indexOf("\n", start);
757
+ const end = nl === -1 ? text.length : nl;
758
+ lines.push({ start, end, free: inString === null && depth === 0 });
759
+ let i = start;
760
+ while (i < end) {
761
+ if (inString !== null) {
762
+ if (inString === '"""' && text[i] === "\\") i += 2;
763
+ else if (text.startsWith(inString, i)) {
764
+ inString = null;
765
+ i += 3;
766
+ } else i++;
767
+ continue;
768
+ }
769
+ const c = text[i];
770
+ if (c === "#") break;
771
+ if (text.startsWith('"""', i) || text.startsWith("'''", i)) {
772
+ inString = text.slice(i, i + 3);
773
+ i += 3;
774
+ } else if (c === '"' || c === "'") {
775
+ i++;
776
+ while (i < end && text[i] !== c) i += c === '"' && text[i] === "\\" ? 2 : 1;
777
+ i++;
778
+ } else {
779
+ if (c === "[" || c === "{") depth++;
780
+ else if ((c === "]" || c === "}") && depth > 0) depth--;
781
+ i++;
782
+ }
783
+ }
784
+ if (nl === -1) return lines;
785
+ start = nl + 1;
786
+ }
787
+ }
788
+ function skipSpaces(s, i) {
789
+ while (s[i] === " " || s[i] === " ") i++;
790
+ return i;
791
+ }
792
+ function parseKeyPath(s, i) {
793
+ const path = [];
794
+ for (; ; ) {
795
+ i = skipSpaces(s, i);
796
+ if (s[i] === '"') {
797
+ let j = i + 1;
798
+ while (j < s.length && s[j] !== '"') j += s[j] === "\\" ? 2 : 1;
799
+ if (j >= s.length) return null;
800
+ const raw = s.slice(i, j + 1);
801
+ path.push(jsonOr(raw));
802
+ i = j + 1;
803
+ } else if (s[i] === "'") {
804
+ const j = s.indexOf("'", i + 1);
805
+ if (j === -1) return null;
806
+ path.push(s.slice(i + 1, j));
807
+ i = j + 1;
808
+ } else {
809
+ const bare = /^[A-Za-z0-9_-]+/.exec(s.slice(i));
810
+ if (!bare) return null;
811
+ path.push(bare[0]);
812
+ i += bare[0].length;
813
+ }
814
+ i = skipSpaces(s, i);
815
+ if (s[i] !== ".") return { path, end: i };
816
+ i++;
817
+ }
818
+ }
819
+ function jsonOr(raw) {
820
+ try {
821
+ return JSON.parse(raw);
822
+ } catch {
823
+ return raw.slice(1, -1);
824
+ }
825
+ }
826
+ function tomlHeader(s) {
827
+ const i = skipSpaces(s, 0);
828
+ if (s[i] !== "[") return null;
829
+ const array = s[i + 1] === "[";
830
+ const key = parseKeyPath(s, i + (array ? 2 : 1));
831
+ if (!key || !s.startsWith(array ? "]]" : "]", key.end)) return null;
832
+ return { path: key.path, array };
833
+ }
834
+ function tomlKey(s) {
835
+ const key = parseKeyPath(s, 0);
836
+ if (!key || s[key.end] !== "=") return null;
837
+ return { path: key.path, valueAt: key.end + 1 };
838
+ }
839
+ function tomlStrings(text, from) {
840
+ const out = [];
841
+ let i = skipSpaces(text, from);
842
+ let depth = 0;
843
+ do {
844
+ const c = text[i];
845
+ if (c === void 0) break;
846
+ if (text.startsWith('"""', i) || text.startsWith("'''", i)) {
847
+ const close = text.indexOf(text.slice(i, i + 3), i + 3);
848
+ const end = close === -1 ? text.length : close;
849
+ out.push(text.slice(i + 3, end));
850
+ i = end + 3;
851
+ } else if (c === '"' || c === "'") {
852
+ let j = i + 1;
853
+ while (j < text.length && text[j] !== c && text[j] !== "\n") j += c === '"' && text[j] === "\\" ? 2 : 1;
854
+ out.push(c === '"' ? jsonOr(text.slice(i, j + 1)) : text.slice(i + 1, j));
855
+ i = j + 1;
856
+ } else if (c === "#") {
857
+ while (i < text.length && text[i] !== "\n") i++;
858
+ } else if (c === "[" || c === "{") {
859
+ depth++;
860
+ i++;
861
+ } else if (c === "]" || c === "}") {
862
+ depth--;
863
+ i++;
864
+ } else if (depth === 0) {
865
+ break;
866
+ } else i++;
867
+ } while (depth > 0);
868
+ return out;
869
+ }
870
+ var startsWithPath = (path, prefix) => prefix.every((p, i) => path[i] === p);
871
+ var samePath = (a, b) => a.length === b.length && startsWithPath(a, b);
872
+ function planToml(path, text, projectId) {
873
+ if (text === null) return { path, status: "create", contents: codexTable(projectId, "\n") };
874
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
875
+ const lines = tomlLines(text).map((line) => ({ ...line, text: text.slice(line.start, line.end).replace(/\r$/, "") }));
876
+ const headers = lines.map((line) => line.free ? tomlHeader(line.text) : null);
877
+ const ours = headers.findIndex((h) => h !== null && !h.array && samePath(h.path, OURS));
878
+ if (ours === -1) {
879
+ let table = [];
880
+ const elsewhere = lines.some((line, n) => {
881
+ if (!line.free) return false;
882
+ const header = headers[n];
883
+ if (header) {
884
+ table = header.path;
885
+ return startsWithPath(header.path, OURS);
886
+ }
887
+ const key = tomlKey(line.text);
888
+ const full = key ? [...table, ...key.path] : [];
889
+ return key !== null && (startsWithPath(full, OURS) || samePath(full, ["mcp_servers"]));
890
+ });
891
+ if (elsewhere) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
892
+ const separator = text.trim() === "" ? null : /\r?\n\r?\n$/.test(text) ? "" : /\n$/.test(text) ? eol : eol + eol;
893
+ return { path, status: "update", contents: separator === null ? codexTable(projectId, eol) : text + separator + codexTable(projectId, eol) };
894
+ }
895
+ const words = [];
896
+ let hasEnv = false;
897
+ for (let n = ours + 1; n < lines.length && !headers[n]; n++) {
898
+ const line = lines[n];
899
+ const key = line.free ? tomlKey(line.text) : null;
900
+ if (key && key.path.length === 1 && (key.path[0] === "command" || key.path[0] === "args")) {
901
+ const values = tomlStrings(text, line.start + key.valueAt);
902
+ words.push(...key.path[0] === "command" ? values.flatMap((v) => v.split(/\s+/)) : values);
903
+ }
904
+ if (key && key.path[0] === "env" && (key.path.length > 1 || !/^\s*\{\s*\}/.test(line.text.slice(key.valueAt)))) hasEnv = true;
905
+ }
906
+ if (namesProject(words, projectId)) {
907
+ for (let n = ours + 1; n < lines.length && !hasEnv; n++) {
908
+ const header = headers[n];
909
+ if (!header || header.array || !samePath(header.path, [...OURS, "env"])) continue;
910
+ for (let m = n + 1; m < lines.length && !headers[m]; m++) if (lines[m].free && tomlKey(lines[m].text)) hasEnv = true;
911
+ }
912
+ return { path, status: "unchanged", contents: text, hasEnv };
913
+ }
914
+ let next = ours + 1;
915
+ while (next < lines.length && !(headers[next] && !startsWithPath(headers[next].path, OURS))) next++;
916
+ const stray = headers.some((h, n) => h !== null && (n < ours || n >= next) && startsWithPath(h.path, OURS));
917
+ if (stray) return { path, status: "manual", contents: null, manualEntry: codexTable(projectId, "\n").trimEnd() };
918
+ let last = next - 1;
919
+ while (last > ours && lines[last].free && /^\s*(#.*)?$/.test(lines[last].text)) last--;
920
+ const cut = Math.min(lines[last].end + 1, text.length);
921
+ return { path, status: "update", contents: text.slice(0, lines[ours].start) + codexTable(projectId, eol) + text.slice(cut) };
922
+ }
923
+
3
924
  // src/args.ts
4
925
  var FRAMEWORKS = ["next", "vue", "svelte", "angular", "css"];
5
926
  var INTEGRATE_FRAMEWORKS = ["vue", "svelte", "angular", "css"];
@@ -9,6 +930,8 @@ var INTEGRATE_DEFAULT_FOLDER = ".";
9
930
  var USAGE = `designsource <command> [options] (also installed as: dss)
10
931
 
11
932
  Commands
933
+ add [names\u2026] add your design system's UI kit to this React app (theme, components, libraries)
934
+ connect connect your coding apps (Claude Code, Cursor, VS Code, Codex, Gemini CLI) to this design system
12
935
  integrate [folder] add the design system to an existing app \u2014 writes design-system/ (default folder: .)
13
936
  create [folder] new Next.js project with the tokens, every component and your mockup page (default folder: ${CREATE_DEFAULT_FOLDER})
14
937
  mcp serve the design system to a coding agent over MCP (stdio) \u2014 for .mcp.json, not for a terminal
@@ -34,18 +957,49 @@ ${TOKEN_LINE}
34
957
  ${API_LINE}
35
958
  --force overwrite files the bundle writes when design-system/ already exists
36
959
  `;
37
- var MCP_USAGE = `designsource mcp [--token <project token>] [--api <origin>]
960
+ var ADD_USAGE = `designsource add [names\u2026] [--yes] [--all] [--force] [--skip-install] [--no-blocks] [--token <project token>] [--api <origin>]
961
+
962
+ Adds your design system's UI kit to the React app in this folder: the theme in its global stylesheet, the
963
+ components and the libraries they import. Sets up Tailwind and the shadcn config when the app has none.
964
+ Run it again to pull updates: it refreshes the theme and every component it added before.
965
+ With every component, a Next.js app (App Router) also gets /design-system, a Vite app /design-system.html:
966
+ your components, blocks and sample pages.
967
+ names components to add, plus the kit files they import (default: what an earlier run added, else asked)
968
+ --all every component, no question
969
+ --yes no questions (also outside a terminal): all components on a first run, edited files kept
970
+ --force replace component files add did not write, and edited ones
971
+ --skip-install write the files, then print the install command instead of running it
972
+ --no-blocks the /design-system section without its blocks and their libraries (blocks already there stay)
973
+ --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN
974
+ --api API origin (default ${DEFAULT_API_ORIGIN})
975
+ `;
976
+ var APP_IDS = APPS.map((a) => a.id);
977
+ var CONNECT_USAGE = `designsource connect [--apps ${APP_IDS.join(",")}] [--yes] [--token <project token>] [--api <origin>]
978
+ designsource connect --forget [--project <id>]
979
+
980
+ Connects your coding apps to this design system: saves the project token once, privately, on this computer, and writes
981
+ each app's MCP settings in the project folder (the nearest folder holding .git, else this one). The settings hold no
982
+ token, so they are safe to commit; a teammate runs npx designsource connect once to save their own.
983
+ --apps the apps to set up, comma-separated: ${APP_IDS.join(",")} (default: picked, the ones found ticked)
984
+ --yes no questions: the apps found on this computer (also outside a terminal)
985
+ ${TOKEN_LINE}
986
+ ${API_LINE}
987
+ --forget remove the token saved for this folder from this computer; settings files are left as they are
988
+ --project with --forget: which project, when several are connected to this folder
989
+ `;
990
+ var MCP_USAGE = `designsource mcp [--project <id>] [--token <project token>] [--api <origin>]
38
991
 
39
992
  Serves the design system to a coding agent over MCP on stdin/stdout. Put it in your MCP
40
- client's config (Claude Code, Cursor, Codex\u2026); the token comes from --token or DS_SYNC_TOKEN.
41
- Read-only: tokens, component source, the mockup page and an integration guide.
993
+ client's config (Claude Code, Cursor, Codex\u2026); npx designsource connect writes the entry for you.
994
+ Tokens, component source, the mockup page, an integration guide, and add_ui_kit, which adds the UI kit to the React app in the current folder.
42
995
 
43
996
  Options
44
- ${TOKEN_LINE}
997
+ --project the project id; the token comes from this computer's saved one (npx designsource connect)
998
+ --token the project token (workbench \u2192 Project settings); or DS_SYNC_TOKEN, which wins over a saved one
45
999
  ${API_LINE}
46
1000
  `;
47
1001
  function usageFor(verb) {
48
- return verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
1002
+ return verb === "add" ? ADD_USAGE : verb === "connect" ? CONNECT_USAGE : verb === "create" ? CREATE_USAGE : verb === "integrate" ? INTEGRATE_USAGE : verb === "mcp" ? MCP_USAGE : USAGE;
49
1003
  }
50
1004
  var ArgsError = class extends Error {
51
1005
  constructor(message, usage) {
@@ -60,14 +1014,17 @@ function baseArgs(env) {
60
1014
  return args;
61
1015
  }
62
1016
  var HELP = /* @__PURE__ */ new Set(["--help", "-h", "help"]);
1017
+ var USE_VERBS = "Use add, connect, integrate, create or mcp.";
63
1018
  function parseArgs(argv, env) {
64
1019
  const [first, ...rest] = argv;
65
1020
  if (first === void 0) return { kind: "menu" };
66
1021
  if (HELP.has(first)) return { kind: "help", verb: void 0 };
67
1022
  if (first === "create" || first === "integrate") return parseVerb(first, rest, env);
68
1023
  if (first === "mcp") return parseMcp(rest, env);
69
- if (first.startsWith("-")) throw new ArgsError("Missing command. Use integrate, create or mcp.", USAGE);
70
- throw new ArgsError(`Unknown command "${first}". Use integrate, create or mcp.`, USAGE);
1024
+ if (first === "add") return parseAdd(rest, env);
1025
+ if (first === "connect") return parseConnect(rest, env);
1026
+ if (first.startsWith("-")) throw new ArgsError(`Missing command. ${USE_VERBS}`, USAGE);
1027
+ throw new ArgsError(`Unknown command "${first}". ${USE_VERBS}`, USAGE);
71
1028
  }
72
1029
  function parseApiOrigin(value, usage) {
73
1030
  const origin = value.replace(/\/+$/, "");
@@ -79,6 +1036,72 @@ function parseApiOrigin(value, usage) {
79
1036
  if (!parsed || !parsed.host) throw new ArgsError(`Option --api needs a full origin such as http://localhost:3001 (got "${value}")`, usage);
80
1037
  return origin;
81
1038
  }
1039
+ var ADD_SWITCHES = { yes: "yes", all: "all", force: "force", "skip-install": "skipInstall", "no-blocks": "noBlocks" };
1040
+ function parseAdd(argv, env) {
1041
+ const args = { components: [], api: DEFAULT_API_ORIGIN, yes: false, all: false, force: false, skipInstall: false, noBlocks: false };
1042
+ if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1043
+ for (let i = 0; i < argv.length; i++) {
1044
+ const arg = argv[i];
1045
+ if (arg === "--help" || arg === "-h") return { kind: "help", verb: "add" };
1046
+ if (!arg.startsWith("-")) {
1047
+ args.components.push(arg);
1048
+ continue;
1049
+ }
1050
+ if (!arg.startsWith("--")) throw new ArgsError(`Unknown option ${arg}`, ADD_USAGE);
1051
+ const eq = arg.indexOf("=");
1052
+ const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1053
+ if (key in ADD_SWITCHES) {
1054
+ if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, ADD_USAGE);
1055
+ args[ADD_SWITCHES[key]] = true;
1056
+ continue;
1057
+ }
1058
+ if (key !== "token" && key !== "api") throw new ArgsError(`Unknown option --${key}`, ADD_USAGE);
1059
+ const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1060
+ if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, ADD_USAGE);
1061
+ if (key === "token") args.token = value;
1062
+ else {
1063
+ args.api = parseApiOrigin(value, ADD_USAGE);
1064
+ args.apiGiven = true;
1065
+ }
1066
+ }
1067
+ return { kind: "add", args };
1068
+ }
1069
+ function appsIn(value) {
1070
+ const ids = [...new Set(value.split(/[\s,]+/).filter(Boolean))];
1071
+ if (ids.length === 0) throw new ArgsError(`Option --apps needs one or more of ${APP_IDS.join(", ")}`, CONNECT_USAGE);
1072
+ const unknown = ids.find((id) => !APP_IDS.includes(id));
1073
+ if (unknown !== void 0) throw new ArgsError(`Unknown app "${unknown}". Use ${APP_IDS.slice(0, -1).join(", ")} or ${APP_IDS.at(-1)}.`, CONNECT_USAGE);
1074
+ return ids;
1075
+ }
1076
+ var CONNECT_SWITCHES = { yes: "yes", forget: "forget" };
1077
+ function parseConnect(argv, env) {
1078
+ const args = { api: DEFAULT_API_ORIGIN, yes: false, forget: false };
1079
+ if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
1080
+ for (let i = 0; i < argv.length; i++) {
1081
+ const arg = argv[i];
1082
+ if (arg === "--help" || arg === "-h") return { kind: "help", verb: "connect" };
1083
+ if (!arg.startsWith("--")) throw new ArgsError(arg.startsWith("-") ? `Unknown option ${arg}` : "connect takes no folder: run it in the project folder", CONNECT_USAGE);
1084
+ const eq = arg.indexOf("=");
1085
+ const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
1086
+ if (key in CONNECT_SWITCHES) {
1087
+ if (eq !== -1) throw new ArgsError(`Option --${key} takes no value`, CONNECT_USAGE);
1088
+ args[CONNECT_SWITCHES[key]] = true;
1089
+ continue;
1090
+ }
1091
+ if (key !== "apps" && key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, CONNECT_USAGE);
1092
+ const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
1093
+ if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, CONNECT_USAGE);
1094
+ if (key === "apps") args.apps = appsIn(value);
1095
+ else if (key === "token") args.token = value;
1096
+ else if (key === "project") args.project = value;
1097
+ else {
1098
+ args.api = parseApiOrigin(value, CONNECT_USAGE);
1099
+ args.apiGiven = true;
1100
+ }
1101
+ }
1102
+ if (args.project !== void 0 && !args.forget) throw new ArgsError("Option --project goes with --forget", CONNECT_USAGE);
1103
+ return { kind: "connect", args };
1104
+ }
82
1105
  function parseMcp(argv, env) {
83
1106
  const args = { api: DEFAULT_API_ORIGIN };
84
1107
  if (env.DS_SYNC_TOKEN) args.token = env.DS_SYNC_TOKEN;
@@ -89,10 +1112,16 @@ function parseMcp(argv, env) {
89
1112
  const eq = arg.indexOf("=");
90
1113
  const key = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
91
1114
  const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
92
- if (key !== "token" && key !== "api") throw new ArgsError(`Unknown option --${key}`, MCP_USAGE);
1115
+ if (key !== "token" && key !== "api" && key !== "project") throw new ArgsError(`Unknown option --${key}`, MCP_USAGE);
93
1116
  if (value === void 0) throw new ArgsError(`Option --${key} needs a value`, MCP_USAGE);
94
1117
  if (key === "token") args.token = value;
95
- else args.api = parseApiOrigin(value, MCP_USAGE);
1118
+ else if (key === "project") {
1119
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new ArgsError("--project must be a project id from the workbench (letters, digits, - and _).", MCP_USAGE);
1120
+ args.project = value;
1121
+ } else {
1122
+ args.api = parseApiOrigin(value, MCP_USAGE);
1123
+ args.apiGiven = true;
1124
+ }
96
1125
  }
97
1126
  return { kind: "mcp", args };
98
1127
  }
@@ -125,6 +1154,7 @@ function parseVerb(verb, argv, env) {
125
1154
  } else if (key === "api") {
126
1155
  needs();
127
1156
  args.api = parseApiOrigin(value, usage);
1157
+ args.apiGiven = true;
128
1158
  } else throw new ArgsError(`Unknown option --${key}`, usage);
129
1159
  continue;
130
1160
  }
@@ -140,50 +1170,768 @@ function parseVerb(verb, argv, env) {
140
1170
  return { kind: "integrate", args };
141
1171
  }
142
1172
 
143
- // src/errors.ts
144
- var CliError = class extends Error {
145
- constructor(message, exitCode = 1) {
146
- super(message);
147
- this.exitCode = exitCode;
1173
+ // src/add/detect.ts
1174
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
1175
+ import { join as join3 } from "node:path";
1176
+ var NO_PACKAGE_JSON = "No package.json here. Run this in your React app's folder.";
1177
+ var NO_REACT = "This folder has no React app. Run this in your React app's folder; for Vue, Svelte, Angular or plain CSS use the AI prompt in the workbench's Export dialog.";
1178
+ var OLD_REACT = (major) => `The UI kit needs React 19 \u2014 this app is on React ${major}.`;
1179
+ var NO_TYPESCRIPT = "The UI kit is TypeScript and this app is plain JavaScript. Use the AI prompt in the workbench's Export dialog instead.";
1180
+ var LOCKFILES = [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]];
1181
+ function majorOf(spec) {
1182
+ if (spec === void 0) return null;
1183
+ const match = /^[\s^~>=v]*(\d+)/.exec(spec);
1184
+ return match ? Number(match[1]) : Number.POSITIVE_INFINITY;
1185
+ }
1186
+ function readJson(path, message) {
1187
+ try {
1188
+ return JSON.parse(readFileSync4(path, "utf8"));
1189
+ } catch {
1190
+ throw new CliError(message);
148
1191
  }
149
- exitCode;
150
- };
151
- var CANCELLED = "Cancelled.";
152
- var TOKEN_MESSAGE = "Project token not recognised. In the workbench open Project settings and copy the project token.";
153
- var UNREACHABLE = (api) => `Could not reach ${api}.`;
154
- var UPDATE_MESSAGE = "This design system needs a newer designsource CLI. Update it (for example `npx designsource@latest`) and run again.";
155
- var PLAN_MESSAGE = "This project's account is on the free plan. Exports need Pro: https://designsource.app/pricing";
156
- function messageForResponse(status, body, api) {
157
- if (status === 401) return TOKEN_MESSAGE;
158
- if (status === 402) return PLAN_MESSAGE;
159
- const serverMessage = typeof body === "object" && body !== null && typeof body.error === "string" ? body.error : null;
160
- if (status === 400) return serverMessage ?? `${api} rejected the request (400).`;
161
- return `${api} answered ${status}.`;
1192
+ }
1193
+ function stringMap(value) {
1194
+ if (typeof value !== "object" || value === null) return {};
1195
+ return Object.fromEntries(Object.entries(value).filter((e) => typeof e[1] === "string"));
1196
+ }
1197
+ function detectApp(root) {
1198
+ const packagePath = join3(root, "package.json");
1199
+ if (!existsSync4(packagePath)) throw new CliError(NO_PACKAGE_JSON);
1200
+ const pkg = readJson(packagePath, "package.json is not valid JSON.");
1201
+ const deps = { ...stringMap(pkg?.dependencies), ...stringMap(pkg?.devDependencies) };
1202
+ const componentsPath = join3(root, "components.json");
1203
+ const shadcn = existsSync4(componentsPath) ? readJson(componentsPath, "components.json is not valid JSON.") : null;
1204
+ return {
1205
+ root,
1206
+ reactMajor: majorOf(deps.react),
1207
+ typescript: "typescript" in deps || existsSync4(join3(root, "tsconfig.json")),
1208
+ tailwindMajor: majorOf(deps.tailwindcss),
1209
+ shadcn,
1210
+ framework: "next" in deps ? "next" : "vite" in deps ? "vite" : "other",
1211
+ packageManager: LOCKFILES.find(([file]) => existsSync4(join3(root, file)))?.[1] ?? "npm",
1212
+ deps
1213
+ };
1214
+ }
1215
+ function assertCanAdd(info) {
1216
+ if (info.reactMajor === null) throw new CliError(NO_REACT);
1217
+ if (info.reactMajor < 19) throw new CliError(OLD_REACT(info.reactMajor));
1218
+ if (!info.typescript) throw new CliError(NO_TYPESCRIPT);
162
1219
  }
163
1220
 
164
- // src/manifest.ts
165
- var malformed = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
166
- function validateManifest(json) {
167
- if (typeof json !== "object" || json === null) throw malformed();
168
- const m = json;
169
- if (typeof m.version !== "number") throw malformed();
170
- if (m.version !== 1) throw new CliError(UPDATE_MESSAGE);
171
- if (typeof m.framework !== "string" || !FRAMEWORKS.includes(m.framework)) throw malformed();
172
- if (typeof m.name !== "string" || !Array.isArray(m.files) || !Array.isArray(m.nextSteps)) throw malformed();
173
- for (const f of m.files) {
174
- if (typeof f !== "object" || f === null) throw malformed();
175
- const { path, contents } = f;
176
- if (typeof path !== "string" || typeof contents !== "string") throw malformed();
1221
+ // src/add/exec.ts
1222
+ import { spawn } from "node:child_process";
1223
+ function quoteArg(arg) {
1224
+ return `"${arg.replace(/"/g, '\\"')}"`;
1225
+ }
1226
+ function childEnv(env) {
1227
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "DS_SYNC_TOKEN"));
1228
+ }
1229
+ var spawnExec = (cmd, args, { cwd, timeoutMs, input, stdoutOnly }) => new Promise((resolve6) => {
1230
+ let output = "";
1231
+ let child;
1232
+ try {
1233
+ const shell = process.platform === "win32";
1234
+ child = spawn(cmd, shell ? args.map(quoteArg) : args, { cwd, env: childEnv(process.env), stdio: [input === void 0 ? "ignore" : "pipe", "pipe", "pipe"], shell });
1235
+ } catch (e) {
1236
+ resolve6({ code: 127, output: e instanceof Error ? e.message : String(e) });
1237
+ return;
177
1238
  }
178
- if (!m.nextSteps.every((s) => typeof s === "string")) throw malformed();
179
- return { version: 1, framework: m.framework, name: m.name, files: m.files, nextSteps: m.nextSteps };
1239
+ let timedOut = false;
1240
+ const timer = timeoutMs === void 0 ? null : setTimeout(() => {
1241
+ timedOut = true;
1242
+ child.kill("SIGKILL");
1243
+ }, timeoutMs);
1244
+ const done = (result) => {
1245
+ if (timer) clearTimeout(timer);
1246
+ resolve6(timedOut ? { code: result.code === 0 ? 124 : result.code, output: `${result.output.trimEnd()}
1247
+ timed out after ${timeoutMs / 1e3}s` } : result);
1248
+ };
1249
+ child.stdout?.on("data", (chunk) => {
1250
+ output += chunk.toString();
1251
+ });
1252
+ child.stderr?.on("data", (chunk) => {
1253
+ if (!stdoutOnly) output += chunk.toString();
1254
+ });
1255
+ child.on("error", (e) => done({ code: 127, output: output + e.message }));
1256
+ child.on("close", (code2) => done({ code: code2 ?? 124, output }));
1257
+ if (input !== void 0 && child.stdin) {
1258
+ child.stdin.on("error", () => {
1259
+ });
1260
+ child.stdin.end(input);
1261
+ }
1262
+ });
1263
+
1264
+ // src/add/plan-files.ts
1265
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync5 } from "node:fs";
1266
+ import { posix as posix4 } from "node:path";
1267
+
1268
+ // src/add/stamp.ts
1269
+ import { createHash } from "node:crypto";
1270
+ var PREFIX = "designsource: ";
1271
+ var STAMP_LINE = /^(?:\/\/ designsource: (\S+) ([0-9a-f]{12})|\/\* designsource: (\S+) ([0-9a-f]{12}) \*\/|<!-- designsource: (\S+) ([0-9a-f]{12}) -->)\r?$/;
1272
+ var hashOf = (body) => createHash("sha256").update(body.replace(/\r\n/g, "\n")).digest("hex").slice(0, 12);
1273
+ function stampContents(name, contents, comment = "line") {
1274
+ const stamp2 = `${PREFIX}${name} ${hashOf(contents)}`;
1275
+ if (comment === "html") return `<!-- ${stamp2} -->
1276
+ ${contents}`;
1277
+ return comment === "line" ? `// ${stamp2}
1278
+ ${contents}` : `/* ${stamp2} */
1279
+ ${contents}`;
1280
+ }
1281
+ function readStamp(text) {
1282
+ const end = text.indexOf("\n");
1283
+ if (end === -1) return null;
1284
+ const match = STAMP_LINE.exec(text.slice(0, end));
1285
+ if (!match) return null;
1286
+ const name = match[1] ?? match[3] ?? match[5];
1287
+ const hash = match[2] ?? match[4] ?? match[6];
1288
+ return { name, hash, edited: hashOf(text.slice(end + 1)) !== hash };
180
1289
  }
181
1290
 
182
- // src/fetch-manifest.ts
183
- async function fetchManifest(opts, fetchImpl = fetch) {
184
- const url = new URL("/api/starter", `${opts.api}/`);
185
- url.searchParams.set("framework", opts.framework);
186
- if (opts.name) url.searchParams.set("name", opts.name);
1291
+ // src/add/plan-files.ts
1292
+ var readText2 = (abs) => {
1293
+ try {
1294
+ return readFileSync5(abs, "utf8");
1295
+ } catch {
1296
+ return null;
1297
+ }
1298
+ };
1299
+ function stampedFiles(root, t) {
1300
+ let entries;
1301
+ try {
1302
+ entries = readdirSync(resolveInside(root, t.uiDir), { withFileTypes: true });
1303
+ } catch {
1304
+ return [];
1305
+ }
1306
+ const found = [];
1307
+ for (const entry of entries) {
1308
+ if (!entry.name.endsWith(".tsx") || !entry.isFile()) continue;
1309
+ const path = posix4.join(t.uiDir, entry.name);
1310
+ const text = readText2(resolveInside(root, path));
1311
+ const stamp2 = text === null ? null : readStamp(text);
1312
+ if (stamp2 && !stamp2.name.startsWith("section:")) found.push({ path, name: stamp2.name });
1313
+ }
1314
+ return found.sort((a, b) => a.path < b.path ? -1 : 1);
1315
+ }
1316
+ function previouslyAdded(root, t) {
1317
+ return stampedFiles(root, t).map((f) => f.name).sort();
1318
+ }
1319
+ var EXPORTS_CN = /export\s+(function|const)\s+cn\b/;
1320
+ function assertKitUtils(root, info, t) {
1321
+ if (info.shadcn !== null) return;
1322
+ const text = readText2(resolveInside(root, t.utilsFile));
1323
+ if (text === null || EXPORTS_CN.test(text)) return;
1324
+ throw new CliError(`${t.utilsFile} exists and has no cn helper, which every kit component imports. Add one (see https://ui.shadcn.com/docs/installation/manual) or rename that file, then run this again.`);
1325
+ }
1326
+ function existingFileStatus(abs) {
1327
+ if (!existsSync5(abs)) return "none";
1328
+ const text = readText2(abs);
1329
+ const stamp2 = text === null ? null : readStamp(text);
1330
+ if (!stamp2) return "foreign";
1331
+ return stamp2.edited ? "edited" : "stamped";
1332
+ }
1333
+ function planFiles(root, t, components, manifest) {
1334
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1335
+ const plan = { write: [], replaceForeign: [], edited: [], previouslyAdded: [], gone: [] };
1336
+ for (const name of components) {
1337
+ const component = byName.get(name);
1338
+ if (!component) throw new CliError(`The kit has no component "${name}".`);
1339
+ const path = t.uiDir ? `${t.uiDir}/${component.file}` : component.file;
1340
+ const abs = resolveInside(root, path);
1341
+ plan.write.push({ path, contents: stampContents(name, rewriteForApp(component.contents, t)), component: name });
1342
+ const status = existingFileStatus(abs);
1343
+ if (status === "foreign") plan.replaceForeign.push(path);
1344
+ else if (status === "edited") plan.edited.push(path);
1345
+ }
1346
+ const utilsAbs = resolveInside(root, t.utilsFile);
1347
+ if (!existsSync5(utilsAbs)) {
1348
+ plan.write.push({ path: t.utilsFile, contents: stampContents("utils", rewriteForApp(manifest.utils, t)), component: "utils" });
1349
+ }
1350
+ const stamped2 = stampedFiles(root, t);
1351
+ plan.previouslyAdded = stamped2.map((f) => f.name).sort();
1352
+ plan.gone = stamped2.filter((f) => f.name !== "utils" && !byName.has(f.name)).map((f) => f.path);
1353
+ return plan;
1354
+ }
1355
+
1356
+ // src/add/section.ts
1357
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync6 } from "node:fs";
1358
+ import { join as join4 } from "node:path";
1359
+ var SECTION_NEEDS_FULL_KIT = "The /design-system section comes with the full kit: run designsource add --all.";
1360
+ var SECTION_NEEDS_FULL_KIT_FOR_AGENT = 'The /design-system section comes with the full kit: call add_ui_kit again with every component in "components" (list_components names them).';
1361
+ var NO_COMPONENTS_DIR = (alias) => `tsconfig.json does not resolve components.json's components alias "${alias}"; the /design-system section goes in that folder, so add a paths entry for it.`;
1362
+ var NO_LIB_ALIAS = (alias) => `components.json's utils alias "${alias}" has no folder; the /design-system section needs one, such as "@/lib/utils".`;
1363
+ var NO_APP_ROUTER = "This Next.js app uses the Pages Router; the /design-system section needs the App Router, so it was skipped.";
1364
+ var OWN_DESIGN_SYSTEM_ROUTE = (path) => `Skipped the /design-system section: this app already has its own /design-system route (${path}).`;
1365
+ function shownBlockGroups(groups, blocks, keptBlockIds = []) {
1366
+ if (blocks === "write") return groups;
1367
+ if (blocks === "skip") return [];
1368
+ const kept = new Set(keptBlockIds);
1369
+ return groups.map((g) => ({ ...g, blocks: g.blocks.filter((b) => kept.has(b.id)) })).filter((g) => g.blocks.length > 0);
1370
+ }
1371
+ function cliSectionConfig(config) {
1372
+ return `import type { SectionConfig } from './section-nav'
1373
+
1374
+ export const SECTION_CONFIG: SectionConfig = ${JSON.stringify(config, null, 2)}
1375
+ `;
1376
+ }
1377
+ var join22 = (dir, rest) => dir ? `${dir}/${rest}` : rest;
1378
+ var COMPONENT_FILES = /* @__PURE__ */ new Set(["preview-gallery.tsx", "custom-surface.tsx", "sample-surfaces.tsx"]);
1379
+ var LIB_FILES = /* @__PURE__ */ new Set(["surface-inference.ts", "mockup-schema.ts"]);
1380
+ var pointAtStub = (contents, alias) => contents.replace(/(['"])([^'"]*)\/blocks\/block-view\1/g, (whole, q, prefix) => prefix === alias ? `${q}./block-view${q}` : whole);
1381
+ var withoutExtension = (file) => file.replace(/\.(tsx?|json|css)$/, "");
1382
+ function placeManifestFile(key, componentsDir, t) {
1383
+ if (key.startsWith("section/")) {
1384
+ const file = key.slice("section/".length);
1385
+ return { path: join22(componentsDir, `design-system/${file}`), name: `section:${withoutExtension(file)}` };
1386
+ }
1387
+ if (key.startsWith("blocks/")) {
1388
+ const rest = key.slice("blocks/".length);
1389
+ return { path: join22(componentsDir, `blocks/${rest}`), name: `section:block:${withoutExtension(rest)}` };
1390
+ }
1391
+ if (COMPONENT_FILES.has(key)) return { path: join22(componentsDir, key), name: `section:${withoutExtension(key)}` };
1392
+ if (LIB_FILES.has(key)) return { path: join22(t.libDir, key), name: `section:${withoutExtension(key)}` };
1393
+ throw new CliError(UPDATE_MESSAGE);
1394
+ }
1395
+ function stamped(path, name, contents) {
1396
+ if (path.endsWith(".json")) return { path, name, contents };
1397
+ const comment = path.endsWith(".css") ? "block" : path.endsWith(".html") ? "html" : "line";
1398
+ return { path, name, contents: stampContents(name, contents, comment) };
1399
+ }
1400
+ function planSectionFiles(input) {
1401
+ const { targets: t, manifest, blocks } = input;
1402
+ const section = manifest.section;
1403
+ if (!section) throw new CliError(UPDATE_MESSAGE);
1404
+ const vite = input.framework === "vite";
1405
+ if (!vite && input.appDir === null) throw new CliError(NO_APP_ROUTER);
1406
+ const componentsDir = t.componentsDir;
1407
+ if (componentsDir === null) throw new CliError(NO_COMPONENTS_DIR(t.componentsAlias));
1408
+ if (!t.libAlias) throw new CliError(NO_LIB_ALIAS(t.utilsAlias));
1409
+ const ds = (file) => join22(componentsDir, `design-system/${file}`);
1410
+ const files = [];
1411
+ for (const f of section.files) {
1412
+ if (f.block && blocks !== "write") continue;
1413
+ const { path, name } = placeManifestFile(f.key, componentsDir, t);
1414
+ let contents = rewriteForApp(f.contents, t);
1415
+ if (f.key === "section/section-views.tsx" && blocks === "skip") contents = pointAtStub(contents, t.componentsAlias);
1416
+ files.push(stamped(path, name, contents));
1417
+ }
1418
+ if (blocks === "skip") files.push(stamped(ds("block-view.tsx"), "section:block-view", NO_BLOCKS_VIEW));
1419
+ const hasMockup = section.mockupSpec !== null;
1420
+ const darkMarker = vite ? { kind: "class", name: "dark" } : input.darkMarker;
1421
+ const config = {
1422
+ name: manifest.name,
1423
+ hasMockup,
1424
+ hasBlocks: blocks !== "skip",
1425
+ darkMarker,
1426
+ homeHref: "/",
1427
+ blockGroups: shownBlockGroups(section.blockGroups, blocks, input.keptBlockIds)
1428
+ };
1429
+ files.push(stamped(ds("section-config.ts"), "section:config", cliSectionConfig(config)));
1430
+ if (hasMockup) files.push(stamped(ds("page.json"), "section:page", `${JSON.stringify(section.mockupSpec, null, 2)}
1431
+ `));
1432
+ files.push(stamped(ds("section-routes.ts"), "section:routes", vite ? viteSectionRoutes(hasMockup, t) : sectionRoutes(hasMockup, t)));
1433
+ if (vite) {
1434
+ const entry = (file) => join22(input.srcDir, `design-system/${file}`);
1435
+ files.push(stamped("design-system.html", "section:page-html", vitePage(manifest.name, entry("main.tsx"))));
1436
+ files.push(stamped(entry("main.tsx"), "section:entry", viteEntry(t)));
1437
+ files.push(stamped(entry("section.css"), "section:stylesheet", viteStylesheet(manifest, section.themeCss)));
1438
+ return files;
1439
+ }
1440
+ files.push(stamped(ds("section-theme.css"), "section:theme", section.themeCss));
1441
+ files.push(stamped(ds("section-page.tsx"), "section:section-page", NEXT_SECTION_PAGE));
1442
+ files.push(stamped(`${input.appDir}/design-system/layout.tsx`, "section:route:layout", nextLayout(t)));
1443
+ files.push(stamped(`${input.appDir}/design-system/[[...path]]/page.tsx`, "section:route:page", nextPage(t)));
1444
+ return files;
1445
+ }
1446
+ var NO_BLOCKS_VIEW = `// This project was added without blocks (designsource add --no-blocks): the section has no Blocks views.
1447
+ export function BlockView({ id }: { id: string }) {
1448
+ return <p className="p-6 text-sm text-muted-foreground">No block named \u201C{id}\u201D.</p>
1449
+ }
1450
+ BlockView.displayName = 'BlockView'
1451
+ `;
1452
+ function mockupModule(hasMockup, t) {
1453
+ return hasMockup ? `import { mockupSpecShapeSchema, type StoredMockupSpec } from '${t.libAlias}/mockup-schema'
1454
+ import page from './page.json'
1455
+
1456
+ // The Custom page is page.json rendered by the design system's page renderer. designsource writes it on every run.
1457
+ export const MOCKUP_SPEC: StoredMockupSpec | null = mockupSpecShapeSchema.parse(page)
1458
+ ` : `import type { StoredMockupSpec } from '${t.libAlias}/mockup-schema'
1459
+
1460
+ /** This project had no generated page: no Custom view. */
1461
+ export const MOCKUP_SPEC: StoredMockupSpec | null = null
1462
+ `;
1463
+ }
1464
+ var ROUTES_IMPORTS = `import { SECTION_CONFIG } from './section-config'
1465
+ import { parseSectionPath, type SectionFeatures, type SectionRoute, sectionPath } from './section-nav'
1466
+ `;
1467
+ var FEATURES = `export const SECTION_FEATURES: SectionFeatures = {
1468
+ hasMockup: SECTION_CONFIG.hasMockup,
1469
+ hasBlocks: SECTION_CONFIG.hasBlocks,
1470
+ blockIds: SECTION_CONFIG.blockGroups.flatMap((group) => group.blocks.map((block) => block.id)),
1471
+ }
1472
+ `;
1473
+ function sectionRoutes(hasMockup, t) {
1474
+ return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1475
+ /** Where the section lives. */
1476
+ export const SECTION_BASE = '/design-system'
1477
+
1478
+ ${FEATURES}
1479
+ /** A \`sectionPath()\` result as an href. */
1480
+ export const sectionHref = (path: string) => \`\${SECTION_BASE}\${path}\`
1481
+
1482
+ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
1483
+
1484
+ /** The route a pathname under /design-system names. */
1485
+ export const routeFor = (pathname: string) => parseSectionPath(pathname.slice(SECTION_BASE.length), SECTION_FEATURES)
1486
+ `;
1487
+ }
1488
+ function viteSectionRoutes(hasMockup, t) {
1489
+ return `${ROUTES_IMPORTS}${mockupModule(hasMockup, t)}
1490
+ ${FEATURES}
1491
+ /** A \`sectionPath()\` result as an href: the page's hash. */
1492
+ export const sectionHref = (path: string) => \`#\${path}\`
1493
+
1494
+ export const hrefFor = (route: SectionRoute) => sectionHref(sectionPath(route))
1495
+
1496
+ /** The route a \`location.hash\` names. */
1497
+ export const routeFor = (hash: string) => parseSectionPath(hash.replace(/^#/, ''), SECTION_FEATURES)
1498
+ `;
1499
+ }
1500
+ var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1501
+ function vitePage(name, entry) {
1502
+ return `<!doctype html>
1503
+ <html lang="en">
1504
+ <head>
1505
+ <meta charset="UTF-8" />
1506
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1507
+ <title>${escapeHtml(`${name} \xB7 Design system`)}</title>
1508
+ </head>
1509
+ <body>
1510
+ <div id="ds-root"></div>
1511
+ <script type="module" src="/${entry}"></script>
1512
+ </body>
1513
+ </html>
1514
+ `;
1515
+ }
1516
+ function viteStylesheet(manifest, themeCss) {
1517
+ const fonts = manifest.theme.fontImports.length > 0 ? `${manifest.theme.fontImports.join("\n")}
1518
+ ` : "";
1519
+ return `${fonts}@import "tailwindcss";
1520
+ @import "tw-animate-css";
1521
+ @import "shadcn/tailwind.css";
1522
+
1523
+ @custom-variant dark (&:is(.dark *));
1524
+
1525
+ ${manifest.theme.css.trim()}
1526
+
1527
+ ${themeCss.trim()}
1528
+ `;
1529
+ }
1530
+ function viteEntry(t) {
1531
+ const c = t.componentsAlias;
1532
+ return `import { StrictMode, useEffect, useState } from 'react'
1533
+ import { createRoot } from 'react-dom/client'
1534
+ import { SECTION_CONFIG } from '${c}/design-system/section-config'
1535
+ import { SectionHeader } from '${c}/design-system/section-header'
1536
+ import { hrefFor, MOCKUP_SPEC, routeFor, SECTION_FEATURES } from '${c}/design-system/section-routes'
1537
+ import { SectionShell } from '${c}/design-system/section-shell'
1538
+ import { SectionView } from '${c}/design-system/section-views'
1539
+ import './section.css'
1540
+
1541
+ /** \`location.hash\`, kept current: Back and Forward change it too. */
1542
+ function useHash(): string {
1543
+ const [hash, setHash] = useState(() => window.location.hash)
1544
+ useEffect(() => {
1545
+ const onChange = () => setHash(window.location.hash)
1546
+ window.addEventListener('hashchange', onChange)
1547
+ return () => window.removeEventListener('hashchange', onChange)
1548
+ }, [])
1549
+ return hash
1550
+ }
1551
+
1552
+ // The design system, written by designsource: its own page, on its own stylesheet, with the project's theme scoped to
1553
+ // the shell and its own light and dark switch. The view is the hash: #/components, #/blocks/login-01.
1554
+ function DesignSystem() {
1555
+ const hash = useHash()
1556
+ const route = routeFor(hash)
1557
+ return (
1558
+ <SectionShell
1559
+ scoped
1560
+ cover={false}
1561
+ darkMarker={SECTION_CONFIG.darkMarker}
1562
+ header={({ dark, toggleDark }) => (
1563
+ <SectionHeader
1564
+ name={SECTION_CONFIG.name}
1565
+ route={route.view === 'missing' ? { view: 'components', blockId: null } : route}
1566
+ features={SECTION_FEATURES}
1567
+ blockGroups={SECTION_CONFIG.blockGroups}
1568
+ homeHref={SECTION_CONFIG.homeHref}
1569
+ hrefFor={hrefFor}
1570
+ dark={dark}
1571
+ onToggleDark={toggleDark}
1572
+ />
1573
+ )}
1574
+ >
1575
+ <SectionView route={route} mockupSpec={MOCKUP_SPEC} blockGroups={SECTION_CONFIG.blockGroups} hrefFor={hrefFor} />
1576
+ </SectionShell>
1577
+ )
1578
+ }
1579
+ DesignSystem.displayName = 'DesignSystem'
1580
+
1581
+ createRoot(document.getElementById('ds-root')!).render(
1582
+ <StrictMode>
1583
+ <DesignSystem />
1584
+ </StrictMode>,
1585
+ )
1586
+ `;
1587
+ }
1588
+ var NEXT_SECTION_PAGE = `'use client'
1589
+
1590
+ import Link from 'next/link'
1591
+ import { usePathname } from 'next/navigation'
1592
+ import { SECTION_CONFIG } from './section-config'
1593
+ import { hrefFor, MOCKUP_SPEC, routeFor } from './section-routes'
1594
+ import { SectionView } from './section-views'
1595
+
1596
+ /** What /design-system/... shows: the view the path names. A client component because the views take functions. */
1597
+ export function SectionPage() {
1598
+ return (
1599
+ <SectionView
1600
+ route={routeFor(usePathname())}
1601
+ mockupSpec={MOCKUP_SPEC}
1602
+ blockGroups={SECTION_CONFIG.blockGroups}
1603
+ hrefFor={hrefFor}
1604
+ LinkComponent={Link}
1605
+ />
1606
+ )
1607
+ }
1608
+ SectionPage.displayName = 'SectionPage'
1609
+ `;
1610
+ function nextLayout(t) {
1611
+ const c = t.componentsAlias;
1612
+ return `'use client'
1613
+
1614
+ import Link from 'next/link'
1615
+ import { usePathname } from 'next/navigation'
1616
+ import { Suspense, type ReactNode } from 'react'
1617
+ import { SECTION_CONFIG } from '${c}/design-system/section-config'
1618
+ import { SectionHeader } from '${c}/design-system/section-header'
1619
+ import { hrefFor, routeFor, SECTION_FEATURES } from '${c}/design-system/section-routes'
1620
+ import { SectionShell } from '${c}/design-system/section-shell'
1621
+ import '${c}/design-system/section-theme.css'
1622
+
1623
+ // The design system, written by designsource. It renders inside the app's root layout, so the shell covers the whole
1624
+ // window above it, with the project's own theme scoped to the shell and its own light and dark switch.
1625
+ // The Suspense boundary is for Next's Cache Components (the default of a new app): \`usePathname\` in a layout over a
1626
+ // dynamic segment is not known while the fallback shell prerenders, and a client render outside a boundary fails the build.
1627
+ export default function DesignSystemLayout({ children }: { children: ReactNode }) {
1628
+ return (
1629
+ <Suspense fallback={null}>
1630
+ <SectionLayout>{children}</SectionLayout>
1631
+ </Suspense>
1632
+ )
1633
+ }
1634
+ DesignSystemLayout.displayName = 'DesignSystemLayout'
1635
+
1636
+ function SectionLayout({ children }: { children: ReactNode }) {
1637
+ const route = routeFor(usePathname())
1638
+ return (
1639
+ <SectionShell
1640
+ scoped
1641
+ cover
1642
+ darkMarker={SECTION_CONFIG.darkMarker}
1643
+ header={({ dark, toggleDark }) => (
1644
+ <SectionHeader
1645
+ name={SECTION_CONFIG.name}
1646
+ route={route.view === 'missing' ? { view: 'components', blockId: null } : route}
1647
+ features={SECTION_FEATURES}
1648
+ blockGroups={SECTION_CONFIG.blockGroups}
1649
+ homeHref={SECTION_CONFIG.homeHref}
1650
+ hrefFor={hrefFor}
1651
+ LinkComponent={Link}
1652
+ dark={dark}
1653
+ onToggleDark={toggleDark}
1654
+ />
1655
+ )}
1656
+ >
1657
+ {children}
1658
+ </SectionShell>
1659
+ )
1660
+ }
1661
+ SectionLayout.displayName = 'SectionLayout'
1662
+ `;
1663
+ }
1664
+ function nextPage(t) {
1665
+ const c = t.componentsAlias;
1666
+ return `import { componentSlug, GALLERY_COMPONENTS } from '${c}/design-system/gallery-groups'
1667
+ import { NAV_ITEMS } from '${c}/design-system/section-nav'
1668
+ import { SectionPage } from '${c}/design-system/section-page'
1669
+ import { SECTION_FEATURES } from '${c}/design-system/section-routes'
1670
+
1671
+ export const metadata = { title: 'Design system' }
1672
+
1673
+ // Every route of the section is prerendered; anything else renders the section's own "not found" view.
1674
+ export function generateStaticParams() {
1675
+ const views: string[] = NAV_ITEMS(SECTION_FEATURES).map((item) => item.view)
1676
+ const routes = [
1677
+ '',
1678
+ ...views,
1679
+ ...GALLERY_COMPONENTS.map((title) => \`components/\${componentSlug(title)}\`),
1680
+ ...SECTION_FEATURES.blockIds.map((id) => \`blocks/\${id}\`),
1681
+ ]
1682
+ return routes.map((route) => ({ path: route === '' ? [] : route.split('/') }))
1683
+ }
1684
+
1685
+ export default function DesignSystemPage() {
1686
+ return <SectionPage />
1687
+ }
1688
+ `;
1689
+ }
1690
+ function nextAppDir(root) {
1691
+ for (const dir of ["app", "src/app"]) {
1692
+ if (["tsx", "jsx", "ts", "js"].some((ext) => existsSync6(join4(root, dir, `layout.${ext}`)))) return dir;
1693
+ }
1694
+ return null;
1695
+ }
1696
+ function entriesOf(abs) {
1697
+ try {
1698
+ return readdirSync2(abs, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1);
1699
+ } catch {
1700
+ return [];
1701
+ }
1702
+ }
1703
+ function firstForeignFile(root, rel) {
1704
+ for (const entry of entriesOf(join4(root, rel))) {
1705
+ const child = `${rel}/${entry.name}`;
1706
+ if (entry.isDirectory()) {
1707
+ const found = firstForeignFile(root, child);
1708
+ if (found) return found;
1709
+ continue;
1710
+ }
1711
+ let text = null;
1712
+ try {
1713
+ text = readFileSync6(join4(root, child), "utf8");
1714
+ } catch {
1715
+ }
1716
+ if (!(text !== null && readStamp(text)?.name.startsWith("section:"))) return child;
1717
+ }
1718
+ return null;
1719
+ }
1720
+ function groupedDesignSystem(root, rel) {
1721
+ for (const entry of entriesOf(join4(root, rel))) {
1722
+ if (!entry.isDirectory() || !/^\(.+\)$/.test(entry.name)) continue;
1723
+ const group = `${rel}/${entry.name}`;
1724
+ if (existsSync6(join4(root, group, "design-system"))) return `${group}/design-system`;
1725
+ const nested = groupedDesignSystem(root, group);
1726
+ if (nested) return nested;
1727
+ }
1728
+ return null;
1729
+ }
1730
+ function ownDesignSystemRoute(root, appDir) {
1731
+ return firstForeignFile(root, `${appDir}/design-system`) ?? groupedDesignSystem(root, appDir);
1732
+ }
1733
+ function stampNames(abs, recursive) {
1734
+ let entries;
1735
+ try {
1736
+ entries = readdirSync2(abs, { withFileTypes: true });
1737
+ } catch {
1738
+ return [];
1739
+ }
1740
+ const names = [];
1741
+ for (const entry of entries) {
1742
+ const child = join4(abs, entry.name);
1743
+ if (entry.isDirectory()) {
1744
+ if (recursive) names.push(...stampNames(child, true));
1745
+ continue;
1746
+ }
1747
+ if (!entry.isFile()) continue;
1748
+ let text;
1749
+ try {
1750
+ text = readFileSync6(child, "utf8");
1751
+ } catch {
1752
+ continue;
1753
+ }
1754
+ const stamp2 = readStamp(text);
1755
+ if (stamp2) names.push(stamp2.name);
1756
+ }
1757
+ return names;
1758
+ }
1759
+ function blockIdOfStamp(name) {
1760
+ const rest = name.startsWith("section:block:") ? name.slice("section:block:".length) : null;
1761
+ if (rest === null) return null;
1762
+ const chart = /^charts\/group-([a-z0-9-]+)$/.exec(rest);
1763
+ if (chart) return `charts-${chart[1]}`;
1764
+ const page = /^([a-z0-9-]+)\/page$/.exec(rest);
1765
+ return page ? page[1] : null;
1766
+ }
1767
+ function sectionPresent(root, t) {
1768
+ if (t.componentsDir === null) return { present: false, blocksOnDisk: false, blockIds: [] };
1769
+ const present = stampNames(resolveInside(root, join22(t.componentsDir, "design-system")), false).some((n) => n.startsWith("section:"));
1770
+ const blockStamps = stampNames(resolveInside(root, join22(t.componentsDir, "blocks")), true).filter((n) => n.startsWith("section:block:"));
1771
+ const blockIds = [...new Set(blockStamps.map(blockIdOfStamp).filter((id) => id !== null))];
1772
+ return { present, blocksOnDisk: blockStamps.length > 0, blockIds };
1773
+ }
1774
+
1775
+ // src/add/run-add.ts
1776
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
1777
+ import { join as join5 } from "node:path";
1778
+
1779
+ // src/write.ts
1780
+ import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync7, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
1781
+ import { dirname, relative, resolve as resolve2 } from "node:path";
1782
+ function planTarget(cwd, folder, framework, force) {
1783
+ const root = resolve2(cwd, folder);
1784
+ if (!existsSync7(root)) return { root, created: true };
1785
+ if (!statSync(root).isDirectory()) throw new CliError(`${folder} exists and is not a folder.`);
1786
+ if (framework === "next") {
1787
+ if (readdirSync3(root).length > 0 && !force) throw new CliError(`Folder ${folder} is not empty. Pick another name, or pass --force to overwrite the files the starter writes.`);
1788
+ } else if (existsSync7(resolve2(root, "design-system")) && !force) {
1789
+ throw new CliError(`${folder}/design-system/ already exists. Remove it, or pass --force to overwrite the files the bundle writes.`);
1790
+ }
1791
+ return { root, created: false };
1792
+ }
1793
+ function writeFiles(root, files, opts, writeFile = writeFileSync2) {
1794
+ const targets = files.map((f) => ({ file: f, abs: resolveInside(root, f.path) }));
1795
+ if (!opts.force) {
1796
+ const clash = targets.find((t) => existsSync7(t.abs));
1797
+ if (clash) throw new CliError(`${clash.file.path} already exists. Pass --force to overwrite the files the starter writes.`);
1798
+ }
1799
+ const written = [];
1800
+ const previous = /* @__PURE__ */ new Map();
1801
+ const madeDirs = [];
1802
+ let failingPath;
1803
+ try {
1804
+ for (const { file, abs } of targets) {
1805
+ failingPath = file.path;
1806
+ if (!previous.has(file.path)) previous.set(file.path, existsSync7(abs) ? readFileSync7(abs) : void 0);
1807
+ madeDirs.push(...missingDirs(root, dirname(abs)));
1808
+ mkdirSync(dirname(abs), { recursive: true });
1809
+ writeFile(abs, file.path === "package.json" && opts.packageManager ? withPackageManager(file.contents, opts.packageManager) : file.contents);
1810
+ written.push(file.path);
1811
+ }
1812
+ } catch (e) {
1813
+ const code2 = e?.code ?? e.message;
1814
+ if (opts.created) {
1815
+ rmSync(root, { recursive: true, force: true });
1816
+ throw new CliError(`Could not write ${failingPath} (${code2}). Removed ${root} again; nothing was left behind.`);
1817
+ }
1818
+ let restored = 0;
1819
+ let removed = 0;
1820
+ for (const [p, before] of previous) {
1821
+ const abs = resolveInside(root, p);
1822
+ if (before === void 0) {
1823
+ if (existsSync7(abs) && statSync(abs).isFile()) {
1824
+ rmSync(abs, { force: true });
1825
+ removed++;
1826
+ }
1827
+ } else {
1828
+ writeFileSync2(abs, before);
1829
+ restored++;
1830
+ }
1831
+ }
1832
+ for (const dir of [...madeDirs].reverse()) rmSync(dir, { recursive: true, force: true });
1833
+ throw new CliError(`Could not write ${failingPath} (${code2}). Restored ${restored} file(s) and removed ${removed} new file(s); the folder is as it was.`);
1834
+ }
1835
+ return { written };
1836
+ }
1837
+ function missingDirs(root, dir) {
1838
+ const missing = [];
1839
+ let d = dir;
1840
+ while (relative(root, d) !== "" && !relative(root, d).startsWith("..") && !existsSync7(d)) {
1841
+ missing.unshift(d);
1842
+ d = dirname(d);
1843
+ }
1844
+ return missing;
1845
+ }
1846
+ function withPackageManager(contents, packageManager) {
1847
+ const pkg = JSON.parse(contents);
1848
+ return `${JSON.stringify({ ...pkg, packageManager }, null, 2)}
1849
+ `;
1850
+ }
1851
+
1852
+ // src/add/dark-marker.ts
1853
+ var UNKNOWN_DARK = (sel) => `This app marks dark mode as ${sel}; inside /design-system a few dark-only details follow its own switch.`;
1854
+ var DEFAULT_MARKER = { kind: "class", name: "dark" };
1855
+ var VARIANT = /@custom-variant\s+dark\s*([({])/;
1856
+ var CLASS = /\.(-?[_a-zA-Z][\w-]*)/g;
1857
+ var ATTR = /\[\s*([\w-]+)\s*(=?)\s*(?:"([^"]*)"|'([^']*)'|([\w-]*))\s*\]/g;
1858
+ function balanced(css, open) {
1859
+ let depth = 0;
1860
+ for (let i = open; i < css.length; i++) {
1861
+ if (css[i] === "(") depth++;
1862
+ else if (css[i] === ")" && --depth === 0) return css.slice(open + 1, i);
1863
+ }
1864
+ return null;
1865
+ }
1866
+ function variantSelector(css) {
1867
+ const match = VARIANT.exec(css);
1868
+ if (!match) return null;
1869
+ const open = match.index + match[0].length - 1;
1870
+ if (match[1] === "(") return (balanced(css, open) ?? css.slice(open + 1)).trim();
1871
+ const inner = css.indexOf("{", open + 1);
1872
+ return (inner === -1 ? css.slice(open + 1) : css.slice(open + 1, inner)).trim();
1873
+ }
1874
+ function readDarkMarker(css) {
1875
+ const selector = variantSelector(css.replace(/\/\*[\s\S]*?\*\//g, ""));
1876
+ if (selector === null) return { marker: DEFAULT_MARKER, known: true, selector };
1877
+ const classes = new Set([...selector.replace(/"[^"]*"|'[^']*'/g, "").matchAll(CLASS)].map((m) => m[1]));
1878
+ const attrs = [...selector.matchAll(ATTR)];
1879
+ const attrKeys = new Set(attrs.map((m) => `${m[1]}=${m[3] ?? m[4] ?? m[5]}`));
1880
+ if (classes.size === 1 && attrs.length === 0) return { marker: { kind: "class", name: [...classes][0] }, known: true, selector };
1881
+ const [first] = attrs;
1882
+ if (classes.size === 0 && first && attrKeys.size === 1 && first[2] === "=") {
1883
+ const value = first[3] ?? first[4] ?? first[5] ?? "";
1884
+ if (value) return { marker: { kind: "attr", name: first[1], value }, known: true, selector };
1885
+ }
1886
+ return { marker: DEFAULT_MARKER, known: false, selector };
1887
+ }
1888
+
1889
+ // src/add/kit-manifest.ts
1890
+ var malformed = () => new CliError("Unexpected response from the API \u2014 not a kit manifest.");
1891
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1892
+ var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1893
+ var isStringMap = (v) => isRecord(v) && Object.values(v).every((s) => typeof s === "string");
1894
+ var isSectionFile = (f) => isRecord(f) && typeof f.key === "string" && typeof f.contents === "string" && isStrings(f.kitImports) && isStrings(f.packages) && typeof f.block === "boolean";
1895
+ var isBlockGroup = (g) => isRecord(g) && typeof g.family === "string" && typeof g.label === "string" && Array.isArray(g.blocks) && g.blocks.every((b) => isRecord(b) && typeof b.id === "string" && typeof b.title === "string");
1896
+ function validateSection(s) {
1897
+ if (!isRecord(s) || !Array.isArray(s.files) || !s.files.every(isSectionFile)) throw malformed();
1898
+ if (typeof s.themeCss !== "string" || !Array.isArray(s.blockGroups) || !s.blockGroups.every(isBlockGroup)) throw malformed();
1899
+ if (!isStringMap(s.packages) || !isStringMap(s.blockPackages)) throw malformed();
1900
+ return { files: s.files, themeCss: s.themeCss, blockGroups: s.blockGroups, packages: s.packages, blockPackages: s.blockPackages, mockupSpec: s.mockupSpec ?? null };
1901
+ }
1902
+ function validateKitManifest(json) {
1903
+ if (!isRecord(json)) throw malformed();
1904
+ if (typeof json.version !== "number") throw malformed();
1905
+ if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
1906
+ if (json.kind !== "kit" || typeof json.name !== "string" || typeof json.utils !== "string") throw malformed();
1907
+ const { theme } = json;
1908
+ if (!isRecord(theme) || typeof theme.css !== "string" || !isStrings(theme.fontImports)) throw malformed();
1909
+ if (!Array.isArray(json.components)) throw malformed();
1910
+ for (const c of json.components) {
1911
+ if (!isRecord(c)) throw malformed();
1912
+ if (typeof c.name !== "string" || typeof c.file !== "string" || typeof c.contents !== "string") throw malformed();
1913
+ if (!isStrings(c.kitImports) || !isStrings(c.packages)) throw malformed();
1914
+ }
1915
+ if (!isStrings(json.utilsPackages)) throw malformed();
1916
+ if (!isStringMap(json.packages) || !isStringMap(json.devPackages)) throw malformed();
1917
+ const section = json.section === void 0 ? void 0 : validateSection(json.section);
1918
+ return {
1919
+ version: 1,
1920
+ kind: "kit",
1921
+ name: json.name,
1922
+ theme: { css: theme.css, fontImports: theme.fontImports },
1923
+ components: json.components,
1924
+ utils: json.utils,
1925
+ utilsPackages: json.utilsPackages,
1926
+ packages: json.packages,
1927
+ devPackages: json.devPackages,
1928
+ ...section ? { section } : {}
1929
+ };
1930
+ }
1931
+
1932
+ // src/add/fetch-kit.ts
1933
+ async function fetchKit(opts, fetchImpl = fetch) {
1934
+ const url = new URL("/api/kit", `${opts.api}/`);
187
1935
  let res;
188
1936
  try {
189
1937
  res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
@@ -192,19 +1940,656 @@ async function fetchManifest(opts, fetchImpl = fetch) {
192
1940
  }
193
1941
  const body = await res.json().catch(() => null);
194
1942
  if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
195
- return validateManifest(body);
1943
+ return validateKitManifest(body);
196
1944
  }
197
1945
 
198
- // src/package-name.ts
199
- function packageNameFor(folder) {
200
- const trimmed = folder.replace(/[\\/]+$/, "");
201
- const segments = trimmed.split(/[\\/]/).filter((p) => p !== "" && p !== ".");
202
- const last = segments[segments.length - 1];
203
- if (!last) return void 0;
204
- const slug = last.normalize("NFKD").replace(new RegExp("\\p{M}", "gu"), "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "").replace(/[-._]+$/, "").slice(0, 214).replace(/[-._]+$/, "");
205
- return slug || void 0;
1946
+ // src/add/plan-packages.ts
1947
+ function componentClosure(picked, manifest) {
1948
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1949
+ const seen = /* @__PURE__ */ new Set();
1950
+ const queue = [...picked];
1951
+ for (let name = queue.shift(); name !== void 0; name = queue.shift()) {
1952
+ if (seen.has(name)) continue;
1953
+ seen.add(name);
1954
+ queue.push(...byName.get(name)?.kitImports ?? []);
1955
+ }
1956
+ return [...seen];
1957
+ }
1958
+ function conflictBetween(pkg, have, need) {
1959
+ const haveMajor = majorOf(have);
1960
+ const needMajor = majorOf(need);
1961
+ if (haveMajor === null || needMajor === null || !Number.isFinite(haveMajor) || !Number.isFinite(needMajor) || haveMajor === needMajor) return null;
1962
+ return { pkg, have, need };
1963
+ }
1964
+ var reasonFor = (c) => `this app uses ${c.pkg} ${majorOf(c.have)}, the kit needs ${majorOf(c.need)}`;
1965
+ function planPackages(components, manifest, appDeps, extra = {}) {
1966
+ const byName = new Map(manifest.components.map((c) => [c.name, c]));
1967
+ const conflictOf = /* @__PURE__ */ new Map();
1968
+ for (const name of componentClosure(components, manifest)) {
1969
+ for (const pkg of byName.get(name)?.packages ?? []) {
1970
+ const have = appDeps[pkg];
1971
+ const need = manifest.packages[pkg];
1972
+ if (have === void 0 || need === void 0 || conflictOf.has(pkg)) continue;
1973
+ const conflict = conflictBetween(pkg, have, need);
1974
+ if (conflict) conflictOf.set(pkg, conflict);
1975
+ }
1976
+ }
1977
+ const skipped = [];
1978
+ const kept = [];
1979
+ for (const name of components) {
1980
+ const blocking = componentClosure([name], manifest).flatMap((n) => byName.get(n)?.packages ?? []).map((pkg) => conflictOf.get(pkg)).find((c) => c !== void 0);
1981
+ if (blocking) skipped.push({ name, reason: reasonFor(blocking) });
1982
+ else kept.push(name);
1983
+ }
1984
+ const needed = new Set(componentClosure(kept, manifest).flatMap((n) => byName.get(n)?.packages ?? []));
1985
+ const install = {};
1986
+ for (const pkg of needed) {
1987
+ const need = manifest.packages[pkg];
1988
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1989
+ }
1990
+ for (const pkg of manifest.utilsPackages) {
1991
+ const need = manifest.packages[pkg];
1992
+ if (need !== void 0 && appDeps[pkg] === void 0) install[pkg] = need;
1993
+ }
1994
+ const extraConflicts = [];
1995
+ for (const [pkg, need] of Object.entries(extra)) {
1996
+ const have = appDeps[pkg];
1997
+ const conflict = have === void 0 ? null : conflictBetween(pkg, have, need);
1998
+ if (conflict) extraConflicts.push(conflict);
1999
+ }
2000
+ if (extraConflicts.length === 0) {
2001
+ for (const [pkg, need] of Object.entries(extra)) if (appDeps[pkg] === void 0 && !(pkg in install)) install[pkg] = need;
2002
+ }
2003
+ const reactIs = manifest.packages["react-is"] ?? extra["react-is"];
2004
+ if ("recharts" in install && reactIs !== void 0 && appDeps["react-is"] === void 0) install["react-is"] = reactIs;
2005
+ return { install, conflicts: [...conflictOf.values()], skipped, components: kept, extraConflicts };
206
2006
  }
207
2007
 
2008
+ // src/add/css-blocks.ts
2009
+ var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
2010
+ function commentEnd(css, at) {
2011
+ const close = css.indexOf("*/", at + 2);
2012
+ return close === -1 ? css.length : close + 2;
2013
+ }
2014
+ function stringEnd(css, at) {
2015
+ const quote = css[at];
2016
+ let i = at + 1;
2017
+ while (i < css.length) {
2018
+ const c = css[i];
2019
+ if (c === "\\") i += 2;
2020
+ else if (c === quote) return i + 1;
2021
+ else i++;
2022
+ }
2023
+ return css.length;
2024
+ }
2025
+ function skipBlank(css, from) {
2026
+ let i = from;
2027
+ while (i < css.length) {
2028
+ if (isSpace(css[i])) i++;
2029
+ else if (css[i] === "/" && css[i + 1] === "*") i = commentEnd(css, i);
2030
+ else break;
2031
+ }
2032
+ return i;
2033
+ }
2034
+ function scanStatements(css) {
2035
+ const out = [];
2036
+ const n = css.length;
2037
+ let i = 0;
2038
+ while (true) {
2039
+ i = skipBlank(css, i);
2040
+ if (i >= n) break;
2041
+ if (css[i] === "}") {
2042
+ i++;
2043
+ continue;
2044
+ }
2045
+ const start = i;
2046
+ let open = -1;
2047
+ let depth = 0;
2048
+ let paren = 0;
2049
+ let end = -1;
2050
+ let j = i;
2051
+ while (j < n) {
2052
+ const c = css[j];
2053
+ if (c === "/" && css[j + 1] === "*") j = commentEnd(css, j);
2054
+ else if (c === '"' || c === "'") j = stringEnd(css, j);
2055
+ else if (c === "\\") j += 2;
2056
+ else {
2057
+ if (c === "(") paren++;
2058
+ else if (c === ")") paren = Math.max(0, paren - 1);
2059
+ else if (c === ";" && depth === 0 && paren === 0) {
2060
+ end = j + 1;
2061
+ break;
2062
+ } else if (c === "{") {
2063
+ if (depth === 0) open = j;
2064
+ depth++;
2065
+ } else if (c === "}") {
2066
+ if (depth === 0) {
2067
+ end = j;
2068
+ break;
2069
+ }
2070
+ depth--;
2071
+ if (depth === 0) {
2072
+ end = j + 1;
2073
+ break;
2074
+ }
2075
+ }
2076
+ j++;
2077
+ }
2078
+ }
2079
+ const closed2 = end !== -1 || open === -1;
2080
+ if (end === -1) end = n;
2081
+ const raw = css.slice(start, end);
2082
+ const text = (raw.endsWith(";") ? raw.slice(0, -1) : raw).trimEnd();
2083
+ const preludeSource = open === -1 ? text : css.slice(start, open);
2084
+ out.push({
2085
+ start,
2086
+ end,
2087
+ text,
2088
+ prelude: preludeSource.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\s+/g, " ").trim(),
2089
+ body: open !== -1 && closed2 ? css.slice(open + 1, end - 1) : null,
2090
+ closed: closed2
2091
+ });
2092
+ i = end;
2093
+ }
2094
+ return out;
2095
+ }
2096
+
2097
+ // src/add/stylesheet.ts
2098
+ var THEME_START = "/* designsource:theme:start \u2014 generated, edit tokens in the workbench */";
2099
+ var THEME_END = "/* designsource:theme:end */";
2100
+ var FONTS_START = "/* designsource:fonts:start */";
2101
+ var FONTS_END = "/* designsource:fonts:end */";
2102
+ var APP_THEME_KEPT = "/* designsource:app-theme \u2014 this app's own :root, .dark and @theme blocks are left as they were */";
2103
+ var KEPT_COMMENT = "/* designsource:kept \u2014 variables from the previous theme that this design system does not define */";
2104
+ var KIT_SCOPED_RESET = `@layer base {
2105
+ :where([data-slot], [data-slot]::before, [data-slot]::after) { box-sizing: border-box; border: 0 solid; }
2106
+ :where(button, input, select, textarea)[data-slot] { font: inherit; color: inherit; background-color: transparent; }
2107
+ }`;
2108
+ var STAGE_CONTAINER = `html {
2109
+ container: stage / inline-size;
2110
+ }`;
2111
+ var BASE_BLOCK = `@layer base {
2112
+ * {
2113
+ border-color: var(--border);
2114
+ }
2115
+ body {
2116
+ background-color: var(--background);
2117
+ color: var(--foreground);
2118
+ font-family: var(--font-sans);
2119
+ }
2120
+ }`;
2121
+ var ANIMATE_IMPORT = '@import "tw-animate-css";';
2122
+ var SHADCN_IMPORT = '@import "shadcn/tailwind.css";';
2123
+ var DARK_VARIANT = "@custom-variant dark (&:is(.dark *));";
2124
+ var LAYER_ORDER = "@layer theme, base, components, utilities;";
2125
+ var LAYERED_IMPORTS = [
2126
+ '@import "tailwindcss/theme.css" layer(theme);',
2127
+ '@import "tailwindcss/utilities.css" layer(utilities);'
2128
+ ];
2129
+ var SHADCN_APPLY = /^(border-border|outline-ring(\/\d+)?|bg-background|text-foreground)$/;
2130
+ function findRegion(css, start, end) {
2131
+ const s = css.indexOf(start);
2132
+ if (s === -1) return null;
2133
+ const e = css.indexOf(end, s + start.length);
2134
+ return e === -1 ? null : { start: s, end: e + end.length };
2135
+ }
2136
+ var within = (s, r) => r !== null && s.start >= r.start && s.end <= r.end;
2137
+ function declarationsOf(body) {
2138
+ const out = [];
2139
+ for (const s of scanStatements(body)) {
2140
+ if (s.body !== null || !s.closed) return null;
2141
+ const colon = s.text.indexOf(":");
2142
+ out.push({
2143
+ name: colon === -1 ? "" : s.text.slice(0, colon).trim(),
2144
+ value: colon === -1 ? "" : s.text.slice(colon + 1).trim(),
2145
+ text: s.text
2146
+ });
2147
+ }
2148
+ return out;
2149
+ }
2150
+ function isShadcnBaseRule(rule) {
2151
+ if (rule.body === null) return false;
2152
+ const selectors = rule.prelude.split(",").map((p) => p.trim());
2153
+ if (!selectors.every((p) => p === "*" || p === "body" || p === "html")) return false;
2154
+ const inner = scanStatements(rule.body);
2155
+ if (inner.length === 0) return false;
2156
+ return inner.every((s) => {
2157
+ if (s.body !== null || !s.closed) return false;
2158
+ if (!s.text.startsWith("@apply")) return false;
2159
+ const classes = s.text.slice("@apply".length).trim().split(/\s+/);
2160
+ return classes.every((c) => SHADCN_APPLY.test(c));
2161
+ });
2162
+ }
2163
+ function classify(s) {
2164
+ if (s.body === null) return null;
2165
+ if (s.prelude === ":root" || s.prelude === ".dark") {
2166
+ return declarationsOf(s.body) === null ? null : s.prelude === ":root" ? "root" : "dark";
2167
+ }
2168
+ if (s.prelude === "@theme inline") return declarationsOf(s.body) === null ? null : "theme";
2169
+ if (s.prelude === "@layer base") {
2170
+ const rules = scanStatements(s.body);
2171
+ return rules.length > 0 && rules.every(isShadcnBaseRule) ? "base" : null;
2172
+ }
2173
+ return null;
2174
+ }
2175
+ function definedBy(themeCss) {
2176
+ const defs = { root: /* @__PURE__ */ new Set(), dark: /* @__PURE__ */ new Set(), theme: /* @__PURE__ */ new Set() };
2177
+ for (const s of scanStatements(themeCss)) {
2178
+ const kind = classify(s);
2179
+ if (kind === null || kind === "base") continue;
2180
+ for (const d of declarationsOf(s.body ?? "") ?? []) defs[kind].add(d.name);
2181
+ }
2182
+ return defs;
2183
+ }
2184
+ function keptBlockOf(css, statements) {
2185
+ const at = css.indexOf(KEPT_COMMENT);
2186
+ if (at === -1) return null;
2187
+ const kept = [];
2188
+ let prev = at + KEPT_COMMENT.length;
2189
+ let rank = -1;
2190
+ for (const s of statements) {
2191
+ if (s.start < prev) continue;
2192
+ const order = [":root", ".dark", "@theme inline"].indexOf(s.prelude);
2193
+ if (order <= rank || s.body === null || declarationsOf(s.body) === null || css.slice(prev, s.start).trim() !== "") break;
2194
+ kept.push(s);
2195
+ rank = order;
2196
+ prev = s.end;
2197
+ }
2198
+ return { statements: kept, start: at, end: prev };
2199
+ }
2200
+ var importTarget = (prelude) => /^@import\s+(?:url\(\s*)?["']?([^"')\s]+)/.exec(prelude)?.[1] ?? null;
2201
+ var isImport = (s) => s.prelude.startsWith("@import");
2202
+ var importsOf = (live, target) => live.find((s) => isImport(s) && importTarget(s.prelude) === target) ?? null;
2203
+ function render2(parts, idx, rest) {
2204
+ parts.sort((a, b) => a.seq - b.seq);
2205
+ let out = "";
2206
+ parts.forEach((p, i) => {
2207
+ out += (i === 0 ? "" : p.kind === "line" && parts[i - 1].kind === "line" ? "\n" : "\n\n") + p.text;
2208
+ });
2209
+ if (idx === 0) return `${out}${parts[parts.length - 1].kind === "chunk" && rest.trim() !== "" ? "\n\n" : "\n"}`;
2210
+ return `${parts[0].kind === "line" ? "\n" : "\n\n"}${out}`;
2211
+ }
2212
+ var isThemeRoot = (prelude) => prelude.split(",").some((p) => p.trim() === ":root" || p.trim() === ".dark");
2213
+ function collisionsAfterRegion(css, wanted) {
2214
+ const region = findRegion(css, THEME_START, THEME_END);
2215
+ if (!region) return [];
2216
+ const all = scanStatements(css);
2217
+ const kept = keptBlockOf(css, all);
2218
+ const found = /* @__PURE__ */ new Set();
2219
+ const visit = (statements) => {
2220
+ for (const s of statements) {
2221
+ if (s.body === null) continue;
2222
+ if (isThemeRoot(s.prelude)) {
2223
+ for (const d of scanStatements(s.body)) {
2224
+ const name = d.body === null ? d.text.slice(0, Math.max(0, d.text.indexOf(":"))).trim() : "";
2225
+ if (name.startsWith("--") && wanted.has(name)) found.add(name);
2226
+ }
2227
+ } else if (s.prelude.startsWith("@") && !/^@(layer|theme|keyframes|font-face|property)\b/.test(s.prelude)) visit(scanStatements(s.body));
2228
+ }
2229
+ };
2230
+ visit(all.filter((s) => s.start >= region.end && !kept?.statements.includes(s)));
2231
+ return [...found].sort();
2232
+ }
2233
+ var hasThemeRegion = (css) => findRegion(css, THEME_START, THEME_END) !== null;
2234
+ var THEME_RADIUS_RUNGS = /^--radius-(sm|md|lg|xl)$/;
2235
+ function applyTheme(css, theme, opts) {
2236
+ const all = scanStatements(css);
2237
+ const fontsRegion = findRegion(css, FONTS_START, FONTS_END);
2238
+ const themeRegion = findRegion(css, THEME_START, THEME_END);
2239
+ const keptBlock = keptBlockOf(css, all);
2240
+ const removeScaffolding = opts.removeScaffolding && !(themeRegion !== null && css.slice(themeRegion.start, themeRegion.end).includes(APP_THEME_KEPT));
2241
+ const live = all.filter((s) => !within(s, fontsRegion) && !within(s, themeRegion) && !keptBlock?.statements.includes(s));
2242
+ const edits = [];
2243
+ const inserts = [];
2244
+ const fontsText = theme.fontImports.length > 0 ? [FONTS_START, ...theme.fontImports, FONTS_END].join("\n") : null;
2245
+ if (fontsRegion && fontsText) edits.push({ ...fontsRegion, text: fontsText });
2246
+ else if (fontsRegion) {
2247
+ const nl = css.startsWith("\r\n", fontsRegion.end) ? 2 : css[fontsRegion.end] === "\n" ? 1 : 0;
2248
+ edits.push({ start: fontsRegion.start, end: fontsRegion.end + nl, text: "" });
2249
+ } else if (fontsText) inserts.push({ idx: 0, seq: 0, kind: "line", text: fontsText });
2250
+ const headIdx = fontsRegion ? fontsText ? fontsRegion.end : fontsRegion.start : 0;
2251
+ const tailwinds = live.filter((s) => {
2252
+ const target = isImport(s) ? importTarget(s.prelude) : null;
2253
+ return target === "tailwindcss" || (target?.startsWith("tailwindcss/") ?? false);
2254
+ });
2255
+ const tailwind = tailwinds.length > 0 ? tailwinds.reduce((a, b) => b.end > a.end ? b : a) : null;
2256
+ const fullTailwind = tailwinds.some((s) => importTarget(s.prelude) === "tailwindcss");
2257
+ const animate = importsOf(live, "tw-animate-css");
2258
+ const shadcnCss = importsOf(live, "shadcn/tailwind.css");
2259
+ const head = [];
2260
+ if (!tailwind) {
2261
+ if (opts.preflight) head.push('@import "tailwindcss";');
2262
+ else {
2263
+ if (!live.some((s) => s.body === null && /^@layer theme ?, ?base ?, ?components ?, ?utilities$/.test(s.prelude))) head.push(LAYER_ORDER);
2264
+ head.push(...LAYERED_IMPORTS);
2265
+ }
2266
+ }
2267
+ if (tailwind) {
2268
+ if (!animate) inserts.push({ idx: tailwind.end, seq: 1, kind: "line", text: ANIMATE_IMPORT });
2269
+ if (!shadcnCss) inserts.push({ idx: (animate ?? tailwind).end, seq: 2, kind: "line", text: SHADCN_IMPORT });
2270
+ } else {
2271
+ if (!animate) head.push(ANIMATE_IMPORT);
2272
+ if (!shadcnCss) head.push(SHADCN_IMPORT);
2273
+ }
2274
+ head.forEach((text, i) => inserts.push({ idx: headIdx, seq: 1 + i / 100, kind: "line", text }));
2275
+ const anchors = live.filter((s) => isImport(s) || s.prelude.startsWith("@custom-variant") || s.prelude.startsWith("@plugin"));
2276
+ const anchorIdx = anchors.length > 0 ? Math.max(...anchors.map((s) => s.end)) : headIdx;
2277
+ if (!live.some((s) => /^@custom-variant dark\b/.test(s.prelude))) inserts.push({ idx: anchorIdx, seq: 3, kind: "line", text: DARK_VARIANT });
2278
+ const removed = live.flatMap((s) => {
2279
+ const kind = removeScaffolding ? classify(s) : null;
2280
+ return kind ? [{ s, kind }] : [];
2281
+ });
2282
+ const defs = definedBy(theme.css);
2283
+ const SELECTORS = { root: ":root", dark: ".dark", theme: "@theme inline" };
2284
+ const kinds = ["root", "dark", "theme"];
2285
+ const keptLines = { root: /* @__PURE__ */ new Map(), dark: /* @__PURE__ */ new Map(), theme: /* @__PURE__ */ new Map() };
2286
+ const addKept = (kind, d) => {
2287
+ if (defs[kind].has(d.name) || kind === "theme" && THEME_RADIUS_RUNGS.test(d.name)) return;
2288
+ keptLines[kind].set(d.name || d.text, d.name ? ` ${d.name}: ${d.value};` : ` ${d.text};`);
2289
+ };
2290
+ for (const s of keptBlock?.statements ?? []) {
2291
+ const kind = kinds.find((k) => SELECTORS[k] === s.prelude);
2292
+ if (kind) for (const d of declarationsOf(s.body ?? "") ?? []) addKept(kind, d);
2293
+ }
2294
+ for (const { s, kind } of removed) {
2295
+ if (kind === "base") continue;
2296
+ for (const d of declarationsOf(s.body ?? "") ?? []) addKept(kind, d);
2297
+ }
2298
+ const keptBlocksText = kinds.filter((k) => keptLines[k].size > 0).map((k) => `${SELECTORS[k]} {
2299
+ ${[...keptLines[k].values()].join("\n")}
2300
+ }`);
2301
+ const keptText = keptBlocksText.length > 0 ? `${KEPT_COMMENT}
2302
+ ${keptBlocksText.join("\n")}` : null;
2303
+ const useReset = !opts.preflight && !fullTailwind;
2304
+ const region = [THEME_START, ...removeScaffolding ? [] : [APP_THEME_KEPT], theme.css.trimEnd(), "", STAGE_CONTAINER, "", useReset ? KIT_SCOPED_RESET : BASE_BLOCK, THEME_END].join("\n");
2305
+ const keptAfter = keptText !== null && keptBlock === null;
2306
+ const chunk = keptAfter ? `${region}
2307
+
2308
+ ${keptText}` : region;
2309
+ if (keptBlock) {
2310
+ if (keptText !== null) edits.push({ start: keptBlock.start, end: keptBlock.end, text: keptText });
2311
+ else {
2312
+ let end = keptBlock.end;
2313
+ while (end < css.length && /\s/.test(css[end])) end++;
2314
+ edits.push({ start: keptBlock.start, end, text: "" });
2315
+ }
2316
+ }
2317
+ if (themeRegion) {
2318
+ edits.push({ ...themeRegion, text: chunk });
2319
+ } else if (removed.length === 0) {
2320
+ inserts.push({ idx: anchorIdx, seq: 4, kind: "chunk", text: chunk });
2321
+ }
2322
+ removed.forEach(({ s }, i) => {
2323
+ if (i === 0 && !themeRegion) {
2324
+ edits.push({ start: s.start, end: s.end, text: chunk });
2325
+ return;
2326
+ }
2327
+ let end = s.end;
2328
+ while (end < css.length && /\s/.test(css[end])) end++;
2329
+ edits.push({ start: s.start, end, text: "" });
2330
+ });
2331
+ const groups = /* @__PURE__ */ new Map();
2332
+ for (const p of inserts) groups.set(p.idx, [...groups.get(p.idx) ?? [], p]);
2333
+ for (const [idx, parts] of groups) edits.push({ start: idx, end: idx, text: render2(parts, idx, css.slice(idx)) });
2334
+ let result = css;
2335
+ for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {
2336
+ result = result.slice(0, e.start) + e.text + result.slice(e.end);
2337
+ }
2338
+ const wanted = /* @__PURE__ */ new Set([...defs.root, ...defs.dark]);
2339
+ return { css: result, replacedShadcnTheme: removed.length > 0, collisions: collisionsAfterRegion(result, wanted) };
2340
+ }
2341
+
2342
+ // src/add/run-add.ts
2343
+ var NO_SHADCN = "This app doesn't use shadcn yet. Setting it up: adds Tailwind and the shadcn config.";
2344
+ var REPLACE_DECLINED = "Nothing was changed. Run again and answer yes to replace them, or remove those files first.";
2345
+ var REPLACE_NEEDS_FORCE = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Pass --force to replace them.`;
2346
+ var UNKNOWN_COMPONENTS = (names) => `Unknown component(s): ${names.join(", ")}. Run without names to pick from the list.`;
2347
+ var SECTION_CONFLICT = (reason) => `Skipped the /design-system section: ${reason}.`;
2348
+ var NO_THEME_FILE = (file) => `${file} does not exist. components.json names it as the app's stylesheet (tailwind.css); create it or fix the path, then run this again.`;
2349
+ var INSTALL_FAILED = (command) => `Installing libraries failed. The files were written; run this to finish: ${command}`;
2350
+ var UnknownComponentsError = class extends CliError {
2351
+ constructor(names) {
2352
+ super(UNKNOWN_COMPONENTS(names));
2353
+ this.names = names;
2354
+ }
2355
+ names;
2356
+ };
2357
+ var PORTAL = "preview-portal";
2358
+ var ALIASES = { components: "@/components", utils: "@/lib/utils", ui: "@/components/ui" };
2359
+ var InstallError = class extends StepError {
2360
+ constructor(message, outputTail2, installCommand) {
2361
+ super(message, outputTail2);
2362
+ this.installCommand = installCommand;
2363
+ }
2364
+ installCommand;
2365
+ };
2366
+ function nonInteractiveQuestions(args) {
2367
+ return {
2368
+ pickComponents: async (all) => all,
2369
+ confirmReplace: async (paths) => {
2370
+ if (!args.force) throw new CliError(REPLACE_NEEDS_FORCE(paths));
2371
+ return true;
2372
+ },
2373
+ keepEdits: async () => !args.force
2374
+ };
2375
+ }
2376
+ function defaultTargets(root, info) {
2377
+ const cssFile = findGlobalStylesheet(info);
2378
+ if (readPaths(root)?.paths["@/*"]) return resolveTargets(root, { tailwind: { css: cssFile }, aliases: ALIASES });
2379
+ const src = join5(root, "src");
2380
+ const prefix = existsSync8(src) && statSync2(src).isDirectory() ? "src/" : "";
2381
+ const utilsFile = `${prefix}lib/utils.ts`;
2382
+ return {
2383
+ uiDir: `${prefix}components/ui`,
2384
+ utilsFile,
2385
+ cssFile,
2386
+ uiAlias: ALIASES.ui,
2387
+ utilsAlias: ALIASES.utils,
2388
+ componentsDir: `${prefix}components`,
2389
+ componentsAlias: ALIASES.components,
2390
+ ...libOf(utilsFile, ALIASES.utils)
2391
+ };
2392
+ }
2393
+ function assertSameTargets(planned, actual) {
2394
+ for (const key of Object.keys(planned)) {
2395
+ if (planned[key] === actual[key]) continue;
2396
+ throw new CliError(`After setup, components.json resolves ${key} to "${actual[key]}" instead of "${planned[key]}". The kit was not written; run this again to add it there.`);
2397
+ }
2398
+ }
2399
+ async function chooseComponents(input, manifest, before, sectionOnDisk, questions) {
2400
+ const known = new Set(manifest.components.map((c) => c.name));
2401
+ const offered = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
2402
+ const checked = (names) => {
2403
+ const unknown = names.filter((n) => !known.has(n));
2404
+ if (unknown.length > 0) throw new UnknownComponentsError(unknown);
2405
+ return [...new Set(names)];
2406
+ };
2407
+ if (input.components.length > 0) return checked(input.components);
2408
+ if (input.all || sectionOnDisk) return offered;
2409
+ const earlier = before.filter((n) => known.has(n));
2410
+ if (earlier.length > 0) return earlier;
2411
+ return checked(await questions.pickComponents(offered));
2412
+ }
2413
+ var SECTION_FRAMEWORKS = ["next", "vite"];
2414
+ function sectionDecision(input) {
2415
+ const none = (note) => ({ write: false, blocks: "skip", note });
2416
+ if (!SECTION_FRAMEWORKS.includes(input.framework)) return none(null);
2417
+ if (input.framework === "next" && input.appDir === null) return none(NO_APP_ROUTER);
2418
+ const chosen = new Set(input.chosen);
2419
+ if (!input.allComponents.every((n) => chosen.has(n))) return none(input.present ? null : SECTION_NEEDS_FULL_KIT);
2420
+ const blocks = !input.present ? input.blocksWanted ? "write" : "skip" : input.blocksOnDisk ? input.blocksWanted ? "write" : "keep" : "skip";
2421
+ return { write: true, blocks, note: null };
2422
+ }
2423
+ function planSection(root, input, info, t, manifest, chosen, onDisk) {
2424
+ const none = (note) => ({ decision: { write: false, blocks: "skip", note }, files: () => [], paths: [], packages: {}, blockCount: 0 });
2425
+ const section = manifest.section;
2426
+ if (!section) return none(null);
2427
+ const appDir = info.framework === "next" ? nextAppDir(root) : null;
2428
+ const own = appDir === null ? null : ownDesignSystemRoute(root, appDir);
2429
+ if (own) return none(OWN_DESIGN_SYSTEM_ROUTE(own));
2430
+ const { present, blocksOnDisk, blockIds } = onDisk;
2431
+ const allComponents = manifest.components.map((c) => c.name).filter((n) => n !== PORTAL);
2432
+ const decision = sectionDecision({ chosen, allComponents, present, blocksOnDisk, blocksWanted: input.blocks ?? true, framework: info.framework, appDir });
2433
+ if (!decision.write) return none(decision.note);
2434
+ if (t.componentsDir === null) return none(NO_COMPONENTS_DIR(t.componentsAlias));
2435
+ if (!t.libAlias) return none(NO_LIB_ALIAS(t.utilsAlias));
2436
+ const framework = info.framework === "vite" ? "vite" : "next";
2437
+ const srcDir = existsSync8(join5(root, "src")) ? "src" : "";
2438
+ const files = (darkMarker) => planSectionFiles({ framework, appDir, srcDir, targets: t, manifest, blocks: decision.blocks, keptBlockIds: blockIds, darkMarker });
2439
+ return {
2440
+ decision,
2441
+ files,
2442
+ paths: files({ kind: "class", name: "dark" }).map((f) => f.path),
2443
+ packages: { ...section.packages, ...decision.blocks === "write" ? section.blockPackages : {} },
2444
+ blockCount: shownBlockGroups(section.blockGroups, decision.blocks, blockIds).reduce((n, g) => n + g.blocks.length, 0)
2445
+ };
2446
+ }
2447
+ function installCommands(info, manifest, install) {
2448
+ const lacks = (pkg) => info.deps[pkg] === void 0;
2449
+ const runtime = { ...install };
2450
+ const animate = manifest.devPackages["tw-animate-css"];
2451
+ if (animate && lacks("tw-animate-css")) runtime["tw-animate-css"] = animate;
2452
+ const dev = {};
2453
+ const shadcn = manifest.devPackages.shadcn;
2454
+ if (shadcn && lacks("shadcn")) dev.shadcn = shadcn;
2455
+ const commands = [];
2456
+ if (Object.keys(runtime).length > 0) commands.push(installArgs(info.packageManager, runtime, false));
2457
+ if (Object.keys(dev).length > 0) commands.push(installArgs(info.packageManager, dev, true));
2458
+ return commands;
2459
+ }
2460
+ function printedCommand([cmd, args]) {
2461
+ return [cmd, ...args.map((a) => a.includes("@") ? `"${a}"` : a)].join(" ");
2462
+ }
2463
+ async function runAdd(input, deps) {
2464
+ const { root } = input;
2465
+ const info = detectApp(root);
2466
+ assertCanAdd(info);
2467
+ const planned = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
2468
+ const cssAbs = resolveInside(root, planned.cssFile);
2469
+ if (!existsSync8(cssAbs)) throw new CliError(NO_THEME_FILE(planned.cssFile));
2470
+ assertKitUtils(root, info, planned);
2471
+ const manifest = await fetchKit({ api: input.api, token: input.token }, deps.fetchImpl);
2472
+ const onDisk = sectionPresent(root, planned);
2473
+ const chosen = await chooseComponents(input, manifest, previouslyAdded(root, planned), onDisk.present, deps.questions);
2474
+ const section = planSection(root, input, info, planned, manifest, chosen, onDisk);
2475
+ let packages = planPackages(chosen, manifest, info.deps);
2476
+ let sectionNote = section.decision.note;
2477
+ let writeSection = section.decision.write;
2478
+ if (writeSection) {
2479
+ const withSection = planPackages(chosen, manifest, info.deps, section.packages);
2480
+ const blocking = packages.skipped[0]?.reason ?? (withSection.extraConflicts[0] ? reasonFor(withSection.extraConflicts[0]) : null);
2481
+ if (blocking) {
2482
+ writeSection = false;
2483
+ sectionNote = SECTION_CONFLICT(blocking);
2484
+ } else packages = withSection;
2485
+ }
2486
+ const plan = planFiles(root, planned, componentClosure(packages.components, manifest), manifest);
2487
+ const sectionStatus = (writeSection ? section.paths : []).filter((p) => !p.endsWith(".json")).map((p) => [p, existingFileStatus(resolveInside(root, p))]);
2488
+ const setup = planSetup(info, manifest, deps.exec);
2489
+ if (writeSection && info.framework === "vite") {
2490
+ try {
2491
+ const step = listViteInputStep(info);
2492
+ if (step) setup.steps.push(step);
2493
+ } catch (e) {
2494
+ if (!(e instanceof CliError)) throw e;
2495
+ sectionNote = VITE_INPUT_MANUAL;
2496
+ }
2497
+ }
2498
+ const replaceForeign = [...plan.replaceForeign, ...sectionStatus.filter(([, s]) => s === "foreign").map(([p]) => p)];
2499
+ if (replaceForeign.length > 0 && !await deps.questions.confirmReplace(replaceForeign)) throw new CliError(REPLACE_DECLINED);
2500
+ const kept = [];
2501
+ for (const path of [...plan.edited, ...sectionStatus.filter(([, s]) => s === "edited").map(([p]) => p)]) {
2502
+ if (await deps.questions.keepEdits(path)) kept.push(path);
2503
+ }
2504
+ const writes = plan.write.filter((w) => !kept.includes(w.path));
2505
+ if (!info.shadcn) deps.progress(NO_SHADCN);
2506
+ for (const step of setup.steps) {
2507
+ await step.run();
2508
+ deps.progress(`${step.line} \u2713`);
2509
+ }
2510
+ if (!info.shadcn) {
2511
+ const written = detectApp(root).shadcn;
2512
+ if (!written) throw new CliError("Setup did not leave a components.json. Run this again.");
2513
+ assertSameTargets(planned, resolveTargets(root, written));
2514
+ }
2515
+ const sheet = readFileSync8(cssAbs, "utf8");
2516
+ const dark = readDarkMarker(sheet);
2517
+ if (writeSection && info.framework !== "vite" && !dark.known) sectionNote = UNKNOWN_DARK(dark.selector ?? "");
2518
+ const sectionWrites = writeSection ? section.files(dark.marker).filter((f) => !kept.includes(f.path)) : [];
2519
+ const removeScaffolding = info.shadcn !== null || hasThemeRegion(sheet);
2520
+ const themed = applyTheme(sheet, manifest.theme, { preflight: setup.preflight, removeScaffolding });
2521
+ try {
2522
+ writeFiles(
2523
+ root,
2524
+ [{ path: planned.cssFile, contents: themed.css }, ...[...writes, ...sectionWrites].map(({ path, contents }) => ({ path, contents }))],
2525
+ { force: true, created: false }
2526
+ );
2527
+ } catch (e) {
2528
+ if (!(e instanceof CliError) || setup.steps.length === 0) throw e;
2529
+ throw new CliError(`${e.message} Setup changes (${setup.steps.map((s) => s.line).join(", ")}) were kept; run this again to finish.`, e.exitCode);
2530
+ }
2531
+ deps.progress("Adding theme\u2026 \u2713");
2532
+ const added = writes.filter((w) => w.component !== "utils").map((w) => w.component);
2533
+ const shown = added.filter((n) => n !== PORTAL).length;
2534
+ if (shown > 0) deps.progress(`Adding ${shown} component${shown === 1 ? "" : "s"}\u2026 \u2713`);
2535
+ if (writeSection) deps.progress("Adding the /design-system section\u2026 \u2713");
2536
+ const commands = installCommands(info, manifest, packages.install);
2537
+ const installCommand = commands.map(printedCommand).join(" && ") || null;
2538
+ if (installCommand && input.skipInstall) deps.progress(`Skipped installing libraries. Run: ${installCommand}`);
2539
+ else if (installCommand) {
2540
+ for (const [cmd, args] of commands) {
2541
+ const { code: code2, output } = await deps.exec(cmd, args, { cwd: root });
2542
+ if (code2 !== 0) throw new InstallError(INSTALL_FAILED(installCommand), outputTail(output), installCommand);
2543
+ }
2544
+ deps.progress("Installing libraries\u2026 \u2713");
2545
+ }
2546
+ return {
2547
+ setup: setup.steps.map((s) => s.line),
2548
+ added,
2549
+ skipped: packages.skipped,
2550
+ kept,
2551
+ gone: plan.gone,
2552
+ themeFile: planned.cssFile,
2553
+ installCommand: input.skipInstall ? installCommand : null,
2554
+ projectName: manifest.name,
2555
+ replacedTheme: themed.replacedShadcnTheme,
2556
+ collisions: themed.collisions,
2557
+ uiAlias: planned.uiAlias,
2558
+ section: writeSection ? {
2559
+ path: info.framework === "vite" ? "/design-system.html" : "/design-system",
2560
+ blocks: section.blockCount,
2561
+ ...section.decision.blocks === "keep" ? { blocksLeftInPlace: true } : {}
2562
+ } : null,
2563
+ sectionNote
2564
+ };
2565
+ }
2566
+
2567
+ // src/add/summary.ts
2568
+ var leftBlocksLine = (n, reader) => `Left ${n} block${n === 1 ? "" : "s"} in place; ${reader === "agent" ? "no_blocks" : "--no-blocks"} does not remove ${n === 1 ? "it" : "them"}.`;
2569
+ var sectionNoteFor = (note, reader) => reader === "agent" && note === SECTION_NEEDS_FULL_KIT ? SECTION_NEEDS_FULL_KIT_FOR_AGENT : note;
2570
+ function summaryLines(r, reader = "cli") {
2571
+ return [
2572
+ ...r.replacedTheme ? [`Replaced the theme in ${r.themeFile}`] : [],
2573
+ ...r.collisions.length > 0 ? [`${r.themeFile} also sets ${r.collisions.join(", ")} in its own :root; those values win over the theme. Rename them there to let the theme apply.`] : [],
2574
+ ...r.skipped.map((s) => `Skipped ${s.name}: ${s.reason}`),
2575
+ ...r.kept.map((path) => `Kept your edits to ${path}`),
2576
+ ...r.gone.map((path) => `${path} is no longer in the kit; left it in place`),
2577
+ ...r.section?.blocksLeftInPlace ? [leftBlocksLine(r.section.blocks, reader)] : [],
2578
+ ...r.section ? [`Your design system: ${r.section.path}`] : [],
2579
+ ...r.sectionNote ? [sectionNoteFor(r.sectionNote, reader)] : [],
2580
+ `Done. Your components now use "${r.projectName}" from designsource.app.`,
2581
+ "Run it again any time to pull updates."
2582
+ ];
2583
+ }
2584
+
2585
+ // src/connect/api-for.ts
2586
+ function apiFor(args, entry) {
2587
+ return args.apiGiven ? args.api : entry?.api ?? args.api;
2588
+ }
2589
+
2590
+ // src/picker.ts
2591
+ import { emitKeypressEvents } from "node:readline";
2592
+
208
2593
  // src/prompts.ts
209
2594
  import { createInterface } from "node:readline";
210
2595
  var shared;
@@ -244,10 +2629,10 @@ function nextLine() {
244
2629
  if (line !== void 0) return Promise.resolve(line);
245
2630
  if (closed) return Promise.reject(new CliError(EOF_MESSAGE));
246
2631
  process.stdin.ref?.();
247
- return new Promise((resolve3, reject) => waiting.push({
2632
+ return new Promise((resolve6, reject) => waiting.push({
248
2633
  resolve: (line2) => {
249
2634
  process.stdin.unref?.();
250
- resolve3(line2);
2635
+ resolve6(line2);
251
2636
  },
252
2637
  reject: (err) => {
253
2638
  process.stdin.unref?.();
@@ -264,6 +2649,13 @@ function promptLine(promptText, fallback) {
264
2649
  function ask(question, fallback) {
265
2650
  return promptLine(`${question} (${fallback}) `, fallback);
266
2651
  }
2652
+ async function confirm(question, defaultYes = false) {
2653
+ const answer = await promptLine(`${question} ${defaultYes ? "(Y/n)" : "(y/N)"} `, "");
2654
+ return /^y/i.test(answer) ? true : /^n/i.test(answer) ? false : defaultYes;
2655
+ }
2656
+ function askLine(question) {
2657
+ return promptLine(`${question} `, "");
2658
+ }
267
2659
  async function askChoice(question, options, defaultIndex) {
268
2660
  const list = options.map((o, i) => ` ${i + 1}) ${o}${i === defaultIndex ? " (default)" : ""}`).join("\n");
269
2661
  process.stdout.write(`${question}
@@ -285,21 +2677,390 @@ async function askHidden(question) {
285
2677
  if (!original) {
286
2678
  throw new CliError("Cannot hide input on this terminal. Pass --token or set DS_SYNC_TOKEN instead.");
287
2679
  }
288
- let muted = false;
289
- r._writeToOutput = (s) => {
290
- if (!muted) original(s);
291
- };
292
- r.setPrompt(`${question} `);
293
- r.prompt();
294
- muted = true;
2680
+ let muted = false;
2681
+ r._writeToOutput = (s) => {
2682
+ if (!muted) original(s);
2683
+ };
2684
+ r.setPrompt(`${question} `);
2685
+ r.prompt();
2686
+ muted = true;
2687
+ try {
2688
+ const a = await nextLine();
2689
+ return a.trim();
2690
+ } finally {
2691
+ muted = false;
2692
+ original("\n");
2693
+ r._writeToOutput = original;
2694
+ }
2695
+ }
2696
+
2697
+ // src/picker.ts
2698
+ function pick(question, options, defaultIndex = 0) {
2699
+ if (!rawTerminal()) return askChoice(question, options.map((o) => o.value), defaultIndex);
2700
+ return pickTty(question, options, defaultIndex, process.stdin, process.stdout);
2701
+ }
2702
+ function rawTerminal() {
2703
+ const { stdin, stdout } = process;
2704
+ return stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
2705
+ }
2706
+ function pickMany(question, options, preselected) {
2707
+ if (!rawTerminal()) return pickManyNumbered(question, options, preselected);
2708
+ return pickManyTty(question, options, preselected, process.stdin, process.stdout);
2709
+ }
2710
+ async function pickManyNumbered(question, options, preselected) {
2711
+ const list = options.map((o, i) => ` ${i + 1}) ${o.label}${preselected.includes(o.value) ? " (picked)" : ""}`).join("\n");
2712
+ process.stdout.write(`${question}
2713
+ ${list}
2714
+ `);
2715
+ const defaults = options.flatMap((o, i) => preselected.includes(o.value) ? [String(i + 1)] : []);
2716
+ const fallback = defaults.length > 0 ? defaults.join(",") : "none";
2717
+ for (; ; ) {
2718
+ const answer = await ask("Choices", fallback);
2719
+ if (answer === "none") return [];
2720
+ const indexes = answer.split(/[\s,]+/).filter(Boolean).map((part) => {
2721
+ const byValue = options.findIndex((o) => o.value === part.toLowerCase());
2722
+ if (byValue !== -1) return byValue;
2723
+ const byNumber = /^\d+$/.test(part) ? Number(part) - 1 : -1;
2724
+ return options[byNumber] !== void 0 ? byNumber : -1;
2725
+ });
2726
+ if (indexes.length > 0 && !indexes.includes(-1)) return options.filter((_, i) => indexes.includes(i)).map((o) => o.value);
2727
+ process.stdout.write(`Pick from 1-${options.length}, separated by commas.
2728
+ `);
2729
+ }
2730
+ }
2731
+ function pickTty(question, options, start, stdin, stdout) {
2732
+ const color = !process.env.NO_COLOR;
2733
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
2734
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
2735
+ const n = options.length;
2736
+ let index = start;
2737
+ const rows = () => options.map((o, i) => {
2738
+ const label = i === index ? bold(o.label) : o.label;
2739
+ return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
2740
+ });
2741
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
2742
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
2743
+ emitKeypressEvents(stdin);
2744
+ stdin.setRawMode(true);
2745
+ stdin.resume();
2746
+ stdout.write("\x1B[?25l");
2747
+ draw([question, ...rows()]);
2748
+ return new Promise((resolve6, reject) => {
2749
+ const finish = (after) => {
2750
+ stdin.off("keypress", onKey);
2751
+ stdin.setRawMode(false);
2752
+ stdin.pause();
2753
+ after();
2754
+ stdout.write("\x1B[?25h");
2755
+ };
2756
+ const onKey = (str, key = {}) => {
2757
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
2758
+ finish(() => stdout.write("\n"));
2759
+ reject(new CliError(CANCELLED, 130));
2760
+ return;
2761
+ }
2762
+ if (key.name === "return" || key.name === "enter") {
2763
+ const chosen = options[index];
2764
+ finish(() => {
2765
+ up();
2766
+ stdout.write(`\r\x1B[J${question} ${chosen.label}
2767
+ `);
2768
+ });
2769
+ resolve6(chosen.value);
2770
+ return;
2771
+ }
2772
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
2773
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
2774
+ else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
2775
+ else return;
2776
+ up();
2777
+ draw([question, ...rows()]);
2778
+ };
2779
+ stdin.on("keypress", onKey);
2780
+ });
2781
+ }
2782
+ function pickManyTty(question, options, preselected, stdin, stdout) {
2783
+ const color = !process.env.NO_COLOR;
2784
+ const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
2785
+ const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
2786
+ const n = options.length;
2787
+ const ticked = options.map((o) => preselected.includes(o.value));
2788
+ let index = 0;
2789
+ const rows = () => options.map((o, i) => {
2790
+ const label = i === index ? bold(o.label) : o.label;
2791
+ return `${i === index ? "\u276F" : " "} ${ticked[i] ? "\u25C9" : "\u25EF"} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
2792
+ });
2793
+ const head = `${question} ${dim("space toggles, a all, enter confirms")}`;
2794
+ const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
2795
+ const up = () => stdout.write(`\x1B[${n + 1}A`);
2796
+ emitKeypressEvents(stdin);
2797
+ stdin.setRawMode(true);
2798
+ stdin.resume();
2799
+ stdout.write("\x1B[?25l");
2800
+ draw([head, ...rows()]);
2801
+ return new Promise((resolve6, reject) => {
2802
+ const finish = (after) => {
2803
+ stdin.off("keypress", onKey);
2804
+ stdin.setRawMode(false);
2805
+ stdin.pause();
2806
+ after();
2807
+ stdout.write("\x1B[?25h");
2808
+ };
2809
+ const onKey = (str, key = {}) => {
2810
+ if (key.ctrl && key.name === "c" || key.name === "escape") {
2811
+ finish(() => stdout.write("\n"));
2812
+ reject(new CliError(CANCELLED, 130));
2813
+ return;
2814
+ }
2815
+ if (key.name === "return" || key.name === "enter") {
2816
+ const chosen = options.filter((_, i) => ticked[i]);
2817
+ finish(() => {
2818
+ up();
2819
+ stdout.write(`\r\x1B[J${question} ${chosen.length > 0 ? chosen.map((o) => o.label).join(", ") : "none"}
2820
+ `);
2821
+ });
2822
+ resolve6(chosen.map((o) => o.value));
2823
+ return;
2824
+ }
2825
+ if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
2826
+ else if (key.name === "down" || str === "j") index = (index + 1) % n;
2827
+ else if (key.name === "space" || str === " ") ticked[index] = !ticked[index];
2828
+ else if (str === "a") ticked.fill(!ticked.every(Boolean));
2829
+ else return;
2830
+ up();
2831
+ draw([head, ...rows()]);
2832
+ };
2833
+ stdin.on("keypress", onKey);
2834
+ });
2835
+ }
2836
+
2837
+ // src/connect/resolve-token.ts
2838
+ import { homedir } from "node:os";
2839
+
2840
+ // src/connect/store.ts
2841
+ import { randomBytes } from "node:crypto";
2842
+ import { chmodSync, constants, copyFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync9, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2843
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
2844
+ var WHERE = ["keychain", "secret-service", "dpapi", "file"];
2845
+ function credentialsPath(env, platform, home) {
2846
+ if (platform === "win32") return join6(env.APPDATA || join6(home, "AppData", "Roaming"), "designsource", "credentials.json");
2847
+ const config = env.XDG_CONFIG_HOME && isAbsolute2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join6(home, ".config");
2848
+ return join6(config, "designsource", "credentials.json");
2849
+ }
2850
+ function isFileEntry(value) {
2851
+ if (typeof value !== "object" || value === null) return false;
2852
+ const e = value;
2853
+ return typeof e.name === "string" && Array.isArray(e.folders) && e.folders.every((f) => typeof f === "string") && WHERE.includes(e.where) && (e.secret === void 0 || typeof e.secret === "string") && (e.api === void 0 || typeof e.api === "string");
2854
+ }
2855
+ function readCredentials(path) {
2856
+ let text;
2857
+ try {
2858
+ text = readFileSync9(path, "utf8");
2859
+ } catch {
2860
+ return { version: 1, projects: {} };
2861
+ }
2862
+ let parsed;
2863
+ try {
2864
+ parsed = JSON.parse(text);
2865
+ } catch {
2866
+ return { version: 1, projects: {}, unreadable: true };
2867
+ }
2868
+ const raw = parsed;
2869
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || typeof raw.projects !== "object" || raw.projects === null) return { version: 1, projects: {}, unreadable: true };
2870
+ const projects = {};
2871
+ for (const [id, entry] of Object.entries(raw.projects)) if (isFileEntry(entry)) projects[id] = entry;
2872
+ return { version: 1, projects };
2873
+ }
2874
+ function stamp(d) {
2875
+ const p = (n) => String(n).padStart(2, "0");
2876
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
2877
+ }
2878
+ function backUp(path) {
2879
+ const base = `${path}.bak-${stamp(/* @__PURE__ */ new Date())}`;
2880
+ for (let n = 0; ; n++) {
2881
+ const target = n === 0 ? base : `${base}-${n}`;
2882
+ try {
2883
+ copyFileSync(path, target, constants.COPYFILE_EXCL);
2884
+ } catch (e) {
2885
+ if (e.code === "EEXIST") continue;
2886
+ throw e;
2887
+ }
2888
+ chmodSync(target, 384);
2889
+ return target;
2890
+ }
2891
+ }
2892
+ function detach(data, keep, folder) {
2893
+ let changed = false;
2894
+ for (const [id, entry] of Object.entries(data.projects)) {
2895
+ if (id === keep) continue;
2896
+ const folders = entry.folders.filter((f) => !isWithin(resolve3(f), folder));
2897
+ if (folders.length !== entry.folders.length) {
2898
+ entry.folders = folders;
2899
+ changed = true;
2900
+ }
2901
+ }
2902
+ return changed;
2903
+ }
2904
+ function writeCredentials(path, data) {
2905
+ const dir = dirname2(path);
2906
+ mkdirSync2(dir, { recursive: true, mode: 448 });
2907
+ chmodSync(dir, 448);
2908
+ const temp = join6(dir, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
2909
+ try {
2910
+ writeFileSync3(temp, `${JSON.stringify(data, null, 2)}
2911
+ `, { mode: 384, flag: "wx" });
2912
+ chmodSync(temp, 384);
2913
+ renameSync(temp, path);
2914
+ } catch (e) {
2915
+ rmSync2(temp, { force: true });
2916
+ throw e;
2917
+ }
2918
+ }
2919
+ function publicEntry(projectId, e) {
2920
+ return { projectId, name: e.name, folders: [...e.folders], where: e.where, ...e.api === void 0 ? {} : { api: e.api } };
2921
+ }
2922
+ function isWithin(folder, root) {
2923
+ const rel = relative2(root, folder);
2924
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
2925
+ }
2926
+ function createStore(opts) {
2927
+ const { env, platform, exec, home } = opts;
2928
+ const path = credentialsPath(env, platform, home);
2929
+ const forceFile = env.DESIGNSOURCE_STORE === "file";
2930
+ const osBackend = (where) => where === "file" ? null : backendFor(where, exec, home);
2931
+ return {
2932
+ async save({ projectId, name, folder, token, api }) {
2933
+ assertProjectId(projectId);
2934
+ const { unreadable, ...data } = readCredentials(path);
2935
+ const previous = data.projects[projectId];
2936
+ const folders = [.../* @__PURE__ */ new Set([...previous?.folders ?? [], resolve3(folder)])];
2937
+ detach(data, projectId, resolve3(folder));
2938
+ const origin = api === void 0 ? {} : { api };
2939
+ let entry = { name, folders, where: "file", secret: token, ...origin };
2940
+ const backend = forceFile ? null : await chooseBackend({ platform, exec, cwd: home, token });
2941
+ if (backend) {
2942
+ const kept = await backend.put(projectId, name, token);
2943
+ if (kept) entry = { name, folders, where: backend.where, ...kept.secret === void 0 ? {} : { secret: kept.secret }, ...origin };
2944
+ }
2945
+ data.projects[projectId] = entry;
2946
+ const backup = unreadable ? backUp(path) : void 0;
2947
+ writeCredentials(path, data);
2948
+ if (previous && previous.where !== entry.where) await osBackend(previous.where)?.remove(projectId);
2949
+ return { ...publicEntry(projectId, entry), ...backup === void 0 ? {} : { backup } };
2950
+ },
2951
+ async token(projectId) {
2952
+ assertProjectId(projectId);
2953
+ const entry = readCredentials(path).projects[projectId];
2954
+ if (!entry) return null;
2955
+ if (entry.where === "file") return entry.secret ?? null;
2956
+ return osBackend(entry.where).get(projectId, entry.secret);
2957
+ },
2958
+ byFolder(folder) {
2959
+ const target = resolve3(folder);
2960
+ return Object.entries(readCredentials(path).projects).filter(([, e]) => e.folders.some((saved) => isWithin(target, resolve3(saved)))).map(([id, e]) => publicEntry(id, e));
2961
+ },
2962
+ entry(projectId) {
2963
+ const found = readCredentials(path).projects;
2964
+ return Object.hasOwn(found, projectId) ? publicEntry(projectId, found[projectId]) : null;
2965
+ },
2966
+ addFolder(projectId, folder, api) {
2967
+ assertProjectId(projectId);
2968
+ const data = readCredentials(path);
2969
+ if (!Object.hasOwn(data.projects, projectId)) return null;
2970
+ const entry = data.projects[projectId];
2971
+ const target = resolve3(folder);
2972
+ const changed = detach(data, projectId, target) || !entry.folders.includes(target) || entry.api !== api;
2973
+ if (!entry.folders.includes(target)) entry.folders = [...entry.folders, target];
2974
+ if (api === void 0) delete entry.api;
2975
+ else entry.api = api;
2976
+ if (changed) writeCredentials(path, data);
2977
+ return publicEntry(projectId, entry);
2978
+ },
2979
+ async forget(projectId) {
2980
+ const data = readCredentials(path);
2981
+ const entry = data.projects[projectId];
2982
+ if (!entry) return null;
2983
+ await osBackend(entry.where)?.remove(projectId);
2984
+ delete data.projects[projectId];
2985
+ writeCredentials(path, data);
2986
+ return publicEntry(projectId, entry);
2987
+ }
2988
+ };
2989
+ }
2990
+
2991
+ // src/connect/resolve-token.ts
2992
+ var NO_TOKEN_FOR_PROJECT = (nameOrId) => `This computer has no token for the "${nameOrId}" design system. Run npx designsource connect in the project folder.`;
2993
+ function defaultStore(env = process.env) {
2994
+ return createStore({ env, platform: process.platform, exec: spawnExec, home: homedir() });
2995
+ }
2996
+ var TERMINAL = { askHidden, pick: (q, options) => pick(q, options, 0) };
2997
+ async function resolveToken(input, prompts = TERMINAL) {
2998
+ const { given, cwd, projectId, store, interactive, prompt } = input;
2999
+ if (given) return { token: given, entry: projectId ? store.entry(projectId) : null };
3000
+ if (projectId) {
3001
+ const token = await store.token(projectId);
3002
+ return token ? { token, entry: store.entry(projectId) } : null;
3003
+ }
3004
+ const matches = store.byFolder(cwd);
3005
+ let chosen = matches[0];
3006
+ if (matches.length > 1) {
3007
+ if (!interactive) {
3008
+ throw new CliError(`More than one design system is connected to this folder: ${matches.map((m) => m.name).join(", ")}. Pass --token, or run in the project folder you mean.`);
3009
+ }
3010
+ const id = await prompts.pick("Which design system?", matches.map((m) => ({ value: m.projectId, label: m.name })));
3011
+ chosen = matches.find((m) => m.projectId === id);
3012
+ }
3013
+ if (chosen) {
3014
+ const token = await store.token(chosen.projectId);
3015
+ if (token) return { token, entry: chosen };
3016
+ }
3017
+ if (!prompt) return null;
3018
+ const typed = await prompts.askHidden("Project token (workbench \u2192 Project settings):");
3019
+ return typed ? { token: typed, entry: null } : null;
3020
+ }
3021
+
3022
+ // src/manifest.ts
3023
+ var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a starter manifest.");
3024
+ function validateManifest(json) {
3025
+ if (typeof json !== "object" || json === null) throw malformed2();
3026
+ const m = json;
3027
+ if (typeof m.version !== "number") throw malformed2();
3028
+ if (m.version !== 1) throw new CliError(UPDATE_MESSAGE);
3029
+ if (typeof m.framework !== "string" || !FRAMEWORKS.includes(m.framework)) throw malformed2();
3030
+ if (typeof m.name !== "string" || !Array.isArray(m.files) || !Array.isArray(m.nextSteps)) throw malformed2();
3031
+ for (const f of m.files) {
3032
+ if (typeof f !== "object" || f === null) throw malformed2();
3033
+ const { path, contents } = f;
3034
+ if (typeof path !== "string" || typeof contents !== "string") throw malformed2();
3035
+ }
3036
+ if (!m.nextSteps.every((s) => typeof s === "string")) throw malformed2();
3037
+ return { version: 1, framework: m.framework, name: m.name, files: m.files, nextSteps: m.nextSteps };
3038
+ }
3039
+
3040
+ // src/fetch-manifest.ts
3041
+ async function fetchManifest(opts, fetchImpl = fetch) {
3042
+ const url = new URL("/api/starter", `${opts.api}/`);
3043
+ url.searchParams.set("framework", opts.framework);
3044
+ if (opts.name) url.searchParams.set("name", opts.name);
3045
+ let res;
295
3046
  try {
296
- const a = await nextLine();
297
- return a.trim();
298
- } finally {
299
- muted = false;
300
- original("\n");
301
- r._writeToOutput = original;
3047
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
3048
+ } catch {
3049
+ throw new CliError(UNREACHABLE(opts.api));
302
3050
  }
3051
+ const body = await res.json().catch(() => null);
3052
+ if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3053
+ return validateManifest(body);
3054
+ }
3055
+
3056
+ // src/package-name.ts
3057
+ function packageNameFor(folder) {
3058
+ const trimmed = folder.replace(/[\\/]+$/, "");
3059
+ const segments = trimmed.split(/[\\/]/).filter((p) => p !== "" && p !== ".");
3060
+ const last = segments[segments.length - 1];
3061
+ if (!last) return void 0;
3062
+ const slug = last.normalize("NFKD").replace(new RegExp("\\p{M}", "gu"), "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+/, "").replace(/[-._]+$/, "").slice(0, 214).replace(/[-._]+$/, "");
3063
+ return slug || void 0;
303
3064
  }
304
3065
 
305
3066
  // src/runner.ts
@@ -324,101 +3085,27 @@ function nextStepsText({ runner, framework, folder, created }) {
324
3085
  `;
325
3086
  }
326
3087
 
327
- // src/write.ts
328
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
329
- import { dirname, relative, resolve as resolve2 } from "node:path";
330
-
331
- // src/paths.ts
332
- import { isAbsolute, resolve, sep } from "node:path";
333
- function resolveInside(root, relPath) {
334
- const escapes = (why) => new CliError(`Manifest path "${relPath}" is outside the target folder (${why}).`);
335
- if (!relPath) throw escapes("empty");
336
- if (isAbsolute(relPath) || /^[a-zA-Z]:[\\/]/.test(relPath) || relPath.startsWith("\\")) throw escapes("absolute");
337
- if (relPath.split(/[\\/]/).includes("..")) throw escapes("..");
338
- const abs = resolve(root, relPath);
339
- if (abs === root || !abs.startsWith(root.endsWith(sep) ? root : root + sep)) throw escapes("resolves above it");
340
- return abs;
341
- }
342
-
343
- // src/write.ts
344
- function planTarget(cwd, folder, framework, force) {
345
- const root = resolve2(cwd, folder);
346
- if (!existsSync(root)) return { root, created: true };
347
- if (!statSync(root).isDirectory()) throw new CliError(`${folder} exists and is not a folder.`);
348
- if (framework === "next") {
349
- if (readdirSync(root).length > 0 && !force) throw new CliError(`Folder ${folder} is not empty. Pick another name, or pass --force to overwrite the files the starter writes.`);
350
- } else if (existsSync(resolve2(root, "design-system")) && !force) {
351
- throw new CliError(`${folder}/design-system/ already exists. Remove it, or pass --force to overwrite the files the bundle writes.`);
352
- }
353
- return { root, created: false };
354
- }
355
- function writeFiles(root, files, opts, writeFile = writeFileSync) {
356
- const targets = files.map((f) => ({ file: f, abs: resolveInside(root, f.path) }));
357
- if (!opts.force) {
358
- const clash = targets.find((t) => existsSync(t.abs));
359
- if (clash) throw new CliError(`${clash.file.path} already exists. Pass --force to overwrite the files the starter writes.`);
360
- }
361
- const written = [];
362
- const previous = /* @__PURE__ */ new Map();
363
- const madeDirs = [];
364
- let failingPath;
365
- try {
366
- for (const { file, abs } of targets) {
367
- failingPath = file.path;
368
- if (!previous.has(file.path)) previous.set(file.path, existsSync(abs) ? readFileSync(abs) : void 0);
369
- madeDirs.push(...missingDirs(root, dirname(abs)));
370
- mkdirSync(dirname(abs), { recursive: true });
371
- writeFile(abs, file.path === "package.json" && opts.packageManager ? withPackageManager(file.contents, opts.packageManager) : file.contents);
372
- written.push(file.path);
373
- }
374
- } catch (e) {
375
- const code2 = e?.code ?? e.message;
376
- if (opts.created) {
377
- rmSync(root, { recursive: true, force: true });
378
- throw new CliError(`Could not write ${failingPath} (${code2}). Removed ${root} again; nothing was left behind.`);
379
- }
380
- let restored = 0;
381
- let removed = 0;
382
- for (const [p, before] of previous) {
383
- const abs = resolveInside(root, p);
384
- if (before === void 0) {
385
- if (existsSync(abs) && statSync(abs).isFile()) {
386
- rmSync(abs, { force: true });
387
- removed++;
388
- }
389
- } else {
390
- writeFileSync(abs, before);
391
- restored++;
392
- }
393
- }
394
- for (const dir of [...madeDirs].reverse()) rmSync(dir, { recursive: true, force: true });
395
- throw new CliError(`Could not write ${failingPath} (${code2}). Restored ${restored} file(s) and removed ${removed} new file(s); the folder is as it was.`);
396
- }
397
- return { written };
398
- }
399
- function missingDirs(root, dir) {
400
- const missing = [];
401
- let d = dir;
402
- while (relative(root, d) !== "" && !relative(root, d).startsWith("..") && !existsSync(d)) {
403
- missing.unshift(d);
404
- d = dirname(d);
405
- }
406
- return missing;
407
- }
408
- function withPackageManager(contents, packageManager) {
409
- const pkg = JSON.parse(contents);
410
- return `${JSON.stringify({ ...pkg, packageManager }, null, 2)}
411
- `;
412
- }
413
-
414
3088
  // src/commands/scaffold.ts
415
3089
  function askFolder(fallback) {
416
3090
  return process.stdin.isTTY === true ? ask("Folder", fallback) : Promise.resolve(fallback);
417
3091
  }
418
- async function requireToken(given) {
419
- const token = given ?? await askHidden("Project token (workbench \u2192 Project settings):");
420
- if (!token) throw new CliError("A project token is required. In the workbench open Project settings and copy the project token.");
421
- return token;
3092
+ var TOKEN_REQUIRED = "A project token is required. In the workbench open Project settings and copy the project token.";
3093
+ var isTerminal = () => process.stdin.isTTY === true && process.stdout.isTTY === true;
3094
+ async function requireToken(given, opts) {
3095
+ if (!opts) {
3096
+ const token = given ?? await askHidden("Project token (workbench \u2192 Project settings):");
3097
+ if (!token) throw new CliError(TOKEN_REQUIRED);
3098
+ return token;
3099
+ }
3100
+ return (await requireSavedToken(given, opts)).token;
3101
+ }
3102
+ async function requireSavedToken(given, opts) {
3103
+ const resolved = await resolveToken({ given, cwd: opts.cwd, store: opts.store ?? defaultStore(), interactive: opts.interactive ?? isTerminal(), prompt: true });
3104
+ if (!resolved) throw new CliError(TOKEN_REQUIRED);
3105
+ return resolved;
3106
+ }
3107
+ async function savedToken(given, opts) {
3108
+ return resolveToken({ given, cwd: opts.cwd, store: opts.store ?? defaultStore(), interactive: opts.interactive ?? isTerminal(), prompt: false });
422
3109
  }
423
3110
  async function scaffold(input, env, io) {
424
3111
  const { folder, framework, token, api, force } = input;
@@ -434,72 +3121,285 @@ ${written.map((p) => ` ${p}`).join("\n")}
434
3121
  io.stdout(nextStepsText({ runner, framework, folder, created }));
435
3122
  }
436
3123
 
437
- // src/commands/create.ts
438
- async function runCreate(args, env, io) {
439
- const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
440
- const token = await requireToken(args.token);
441
- await scaffold({ folder, framework: "next", token, api: args.api, force: args.force }, env, io);
3124
+ // src/commands/add.ts
3125
+ var ADD_MODES = [
3126
+ { value: "all", label: "All" },
3127
+ { value: "some", label: "Pick some\u2026" }
3128
+ ];
3129
+ var PICK_QUESTION = "Add which components?";
3130
+ var namesIn = (line) => [...new Set(line.split(/[\s,]+/).filter(Boolean))];
3131
+ function ttyQuestions(args, mode, io) {
3132
+ return {
3133
+ async pickComponents(all) {
3134
+ if ((mode ?? await pick(PICK_QUESTION, ADD_MODES, 0)) === "all") return all;
3135
+ const valid = new Set(all);
3136
+ for (let attempt = 0; ; attempt++) {
3137
+ const names = namesIn(await askLine("Components (comma-separated):"));
3138
+ const unknown = names.filter((n) => !valid.has(n));
3139
+ if (names.length > 0 && unknown.length === 0) return names;
3140
+ if (attempt > 0) throw new CliError(unknown.length > 0 ? `Unknown component(s): ${unknown.join(", ")}.` : "No components given.");
3141
+ io.stdout(`${unknown.length > 0 ? `Unknown: ${unknown.join(", ")}. ` : ""}The components are: ${all.join(", ")}
3142
+ `);
3143
+ }
3144
+ },
3145
+ async confirmReplace(paths) {
3146
+ if (args.force) return true;
3147
+ io.stdout(`${paths.map((p) => ` ${p}`).join("\n")}
3148
+ `);
3149
+ return confirm(`Replace ${paths.length} existing component${paths.length === 1 ? "" : "s"} with your design system's?`, false);
3150
+ },
3151
+ async keepEdits(path) {
3152
+ if (args.force) return false;
3153
+ return confirm(`Keep your edits to ${path}?`, true);
3154
+ }
3155
+ };
3156
+ }
3157
+ async function runAddCommand(args, io, exec = spawnExec, store) {
3158
+ const root = io.cwd;
3159
+ const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
3160
+ const interactive = !args.yes && terminal;
3161
+ const info = detectApp(root);
3162
+ assertCanAdd(info);
3163
+ const targets = info.shadcn ? resolveTargets(root, info.shadcn) : defaultTargets(root, info);
3164
+ assertKitUtils(root, info, targets);
3165
+ let mode;
3166
+ if (interactive && args.components.length === 0 && !args.all) {
3167
+ const first = previouslyAdded(root, targets).every((n) => n === "utils") && !sectionPresent(root, targets).present;
3168
+ if (first) mode = await pick(PICK_QUESTION, ADD_MODES, 0);
3169
+ }
3170
+ const { token, entry } = await requireSavedToken(args.token, { cwd: root, store, interactive: terminal });
3171
+ const questions = interactive ? ttyQuestions(args, mode, io) : nonInteractiveQuestions(args);
3172
+ try {
3173
+ const result = await runAdd(
3174
+ { root, token, api: apiFor(args, entry), components: args.components, skipInstall: args.skipInstall, all: args.all, blocks: !args.noBlocks },
3175
+ { fetchImpl: io.fetchImpl, exec, questions, progress: (line) => io.stdout(`${line}
3176
+ `) }
3177
+ );
3178
+ io.stdout(summaryLines(result).map((line) => `${line}
3179
+ `).join(""));
3180
+ } catch (e) {
3181
+ if (e instanceof StepError && e.outputTail) io.stderr(`${e.outputTail}
3182
+ `);
3183
+ throw e;
3184
+ }
442
3185
  }
443
3186
 
444
- // src/picker.ts
445
- import { emitKeypressEvents } from "node:readline";
446
- function pick(question, options, defaultIndex = 0) {
447
- const stdin = process.stdin;
448
- const stdout = process.stdout;
449
- const tty = stdin.isTTY === true && stdout.isTTY === true && typeof stdin.setRawMode === "function" && !hasInterface();
450
- if (!tty) return askChoice(question, options.map((o) => o.value), defaultIndex);
451
- return pickTty(question, options, defaultIndex, stdin, stdout);
3187
+ // src/commands/connect.ts
3188
+ import { accessSync, constants as constants2, existsSync as existsSync10, statSync as statSync3 } from "node:fs";
3189
+ import { homedir as homedir2 } from "node:os";
3190
+ import { join as join8 } from "node:path";
3191
+
3192
+ // src/connect/fetch-project.ts
3193
+ var RejectedTokenError = class extends CliError {
3194
+ constructor() {
3195
+ super(TOKEN_MESSAGE);
3196
+ }
3197
+ };
3198
+ var malformed3 = () => new CliError("Unexpected response from the API \u2014 not a project.");
3199
+ async function fetchProject(opts, fetchImpl = fetch) {
3200
+ const url = new URL("/api/project", `${opts.api}/`);
3201
+ let res;
3202
+ try {
3203
+ res = await fetchImpl(url.toString(), { headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/json" } });
3204
+ } catch {
3205
+ throw new CliError(UNREACHABLE(opts.api));
3206
+ }
3207
+ const body = await res.json().catch(() => null);
3208
+ if (res.status === 401) throw new RejectedTokenError();
3209
+ if (!res.ok) throw new CliError(messageForResponse(res.status, body, opts.api));
3210
+ if (typeof body !== "object" || body === null) throw malformed3();
3211
+ const { id, name } = body;
3212
+ if (typeof id !== "string" || typeof name !== "string") throw malformed3();
3213
+ assertProjectId(id);
3214
+ return { id, name };
452
3215
  }
453
- function pickTty(question, options, start, stdin, stdout) {
454
- const color = !process.env.NO_COLOR;
455
- const bold = (s) => color ? `\x1B[1m${s}\x1B[22m` : s;
456
- const dim = (s) => color ? `\x1B[2m${s}\x1B[22m` : s;
457
- const n = options.length;
458
- let index = start;
459
- const rows = () => options.map((o, i) => {
460
- const label = i === index ? bold(o.label) : o.label;
461
- return `${i === index ? "\u276F" : " "} ${label}${o.hint ? ` ${dim(o.hint)}` : ""}`;
462
- });
463
- const draw = (lines) => stdout.write(lines.map((l) => `\r\x1B[2K${l}`).join("\n") + "\n");
464
- const up = () => stdout.write(`\x1B[${n + 1}A`);
465
- emitKeypressEvents(stdin);
466
- stdin.setRawMode(true);
467
- stdin.resume();
468
- stdout.write("\x1B[?25l");
469
- draw([question, ...rows()]);
470
- return new Promise((resolve3, reject) => {
471
- const finish = (after) => {
472
- stdin.off("keypress", onKey);
473
- stdin.setRawMode(false);
474
- stdin.pause();
475
- after();
476
- stdout.write("\x1B[?25h");
477
- };
478
- const onKey = (str, key = {}) => {
479
- if (key.ctrl && key.name === "c" || key.name === "escape") {
480
- finish(() => stdout.write("\n"));
481
- reject(new CliError(CANCELLED, 130));
482
- return;
483
- }
484
- if (key.name === "return" || key.name === "enter") {
485
- const chosen = options[index];
486
- finish(() => {
487
- up();
488
- stdout.write(`\r\x1B[J${question} ${chosen.label}
489
- `);
490
- });
491
- resolve3(chosen.value);
492
- return;
3216
+
3217
+ // src/connect/project-root.ts
3218
+ import { existsSync as existsSync9 } from "node:fs";
3219
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
3220
+ function projectRoot(cwd, exists = existsSync9) {
3221
+ let dir = resolve4(cwd);
3222
+ for (; ; ) {
3223
+ if (exists(join7(dir, ".git"))) return dir;
3224
+ const parent = dirname3(dir);
3225
+ if (parent === dir) return resolve4(cwd);
3226
+ dir = parent;
3227
+ }
3228
+ }
3229
+ function within2(folder, root) {
3230
+ const rel = relative3(root, folder);
3231
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep3}`) && !isAbsolute3(rel);
3232
+ }
3233
+ function homeFolderRefusal(root, home) {
3234
+ const folder = resolve4(root);
3235
+ const homeDir = resolve4(home);
3236
+ const tail = "and writing there would set up every project on this computer.";
3237
+ if (folder === homeDir) return `Run this in your project folder \u2014 ${folder} is your home folder, ${tail}`;
3238
+ if (dirname3(folder) === folder || within2(homeDir, folder)) return `Run this in your project folder \u2014 ${folder} is a system folder, ${tail}`;
3239
+ return null;
3240
+ }
3241
+
3242
+ // src/commands/connect.ts
3243
+ var TERMINAL_PROMPTS = { pickMany, pick: (question, options) => pick(question, options, 0), askHidden };
3244
+ function onPath(bin, env, platform) {
3245
+ const windows = platform === "win32";
3246
+ const dirs = (env.PATH ?? env.Path ?? "").split(windows ? ";" : ":").filter(Boolean);
3247
+ const exts = windows ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""];
3248
+ return dirs.some(
3249
+ (dir) => exts.some((ext) => {
3250
+ const file = join8(dir, bin + ext);
3251
+ try {
3252
+ if (!statSync3(file).isFile()) return false;
3253
+ if (!windows) accessSync(file, constants2.X_OK);
3254
+ return true;
3255
+ } catch {
3256
+ return false;
493
3257
  }
494
- if (key.name === "up" || str === "k") index = (index - 1 + n) % n;
495
- else if (key.name === "down" || str === "j") index = (index + 1) % n;
496
- else if (str && /^[1-9]$/.test(str) && Number(str) <= n) index = Number(str) - 1;
497
- else return;
498
- up();
499
- draw([question, ...rows()]);
500
- };
501
- stdin.on("keypress", onKey);
502
- });
3258
+ })
3259
+ );
3260
+ }
3261
+ function defaultConnectDeps(env) {
3262
+ const home = homedir2();
3263
+ const platform = process.platform;
3264
+ return {
3265
+ store: defaultStore(env),
3266
+ detect: () => detectApps({ env, platform, home, exists: existsSync10, onPath: (bin) => onPath(bin, env, platform) }),
3267
+ credentialsPath: credentialsPath(env, platform, home)
3268
+ };
3269
+ }
3270
+ var APP_OPTIONS = APPS.map((a) => ({ value: a.id, label: a.label, hint: a.file }));
3271
+ var app = (id) => APPS.find((a) => a.id === id);
3272
+ var NO_APPS_FOUND = "No coding apps found. Pass --apps claude,cursor,vscode,codex,gemini.";
3273
+ var NO_APPS_PICKED = "No apps picked. Nothing was changed.";
3274
+ var SAVED_TOKEN_REJECTED = "The saved token for this project was not accepted. Run again with --token <project token> (or DS_SYNC_TOKEN) to replace it.";
3275
+ function savedLine(name, where, file, reused) {
3276
+ if (reused) return `Using your saved token for "${name}" from ${whereFrom(where, file)} \u2713`;
3277
+ if (where === "keychain") return `Saved your token for "${name}" in the macOS keychain \u2713`;
3278
+ if (where === "secret-service") return `Saved your token for "${name}" in the system keyring \u2713`;
3279
+ if (where === "dpapi") return `Saved your token for "${name}" with Windows protection \u2713`;
3280
+ return `Saved your token for "${name}" in ${file} (readable only by you) \u2713`;
3281
+ }
3282
+ function whereFrom(where, file) {
3283
+ return where === "keychain" ? "the macOS keychain" : where === "secret-service" ? "the system keyring" : file;
3284
+ }
3285
+ function appLines(id, plan) {
3286
+ const { label, format, key } = app(id);
3287
+ const head = ` ${label} ${plan.path}`;
3288
+ if (plan.status === "create" || plan.status === "update") return [`${head} \u2713`];
3289
+ if (plan.status === "unchanged") {
3290
+ const lines = [`${head} (already set up)`];
3291
+ if (plan.hasEnv) lines.push(` ${plan.path} still holds a token in its env; connect does not need it, so you can delete that env block.`);
3292
+ return lines;
3293
+ }
3294
+ const entry = (plan.manualEntry ?? "").split("\n").map((l) => ` ${l}`);
3295
+ const why = format === "toml" ? `${head}: it defines designsource another way, so it was not changed. Put this table in its place:` : `${head}: it has comments or is not plain JSON, so it was not changed. Add this entry under "${key}":`;
3296
+ return [why, ...entry];
3297
+ }
3298
+ function closingLines(apps, changed) {
3299
+ const has = (id) => apps.includes(id);
3300
+ const restart = [changed.includes("cursor") && "Cursor", changed.includes("vscode") && "VS Code"].filter((s) => typeof s === "string");
3301
+ return [
3302
+ "Done.",
3303
+ ...restart.length > 0 ? [`Restart ${restart.join(" and ")}.`] : [],
3304
+ ...has("claude") ? ["Claude Code asks once to allow the server."] : [],
3305
+ ...has("codex") ? ["Codex reads it once you trust this project in Codex."] : [],
3306
+ ...has("gemini") ? ["Gemini CLI reads it unless folder trust is on and this folder is not trusted."] : [],
3307
+ "Then ask your agent to add the UI kit.",
3308
+ "These files hold no token and are safe to commit; teammates run npx designsource connect once."
3309
+ ];
3310
+ }
3311
+ async function runConnect(args, io, deps = defaultConnectDeps(process.env)) {
3312
+ const { store } = deps;
3313
+ const terminal = deps.terminal ?? (process.stdin.isTTY === true && process.stdout.isTTY === true);
3314
+ const interactive = terminal && !args.yes;
3315
+ const prompts = deps.prompts ?? TERMINAL_PROMPTS;
3316
+ const root = projectRoot(io.cwd);
3317
+ const say = (lines) => io.stdout(lines.map((l) => `${l}
3318
+ `).join(""));
3319
+ if (args.forget) return forget(args, root, store, interactive, prompts, deps.credentialsPath, say);
3320
+ const refusal = homeFolderRefusal(root, deps.home ?? homedir2());
3321
+ if (refusal) throw new CliError(refusal);
3322
+ say([`Connecting ${root}`]);
3323
+ let apps;
3324
+ const connected = args.apps ? null : connectedApps(root, store);
3325
+ if (args.apps) apps = args.apps;
3326
+ else if (connected) apps = connected;
3327
+ else {
3328
+ const detected = deps.detect();
3329
+ if (interactive) {
3330
+ apps = await prompts.pickMany("Connect which apps?", APP_OPTIONS, detected);
3331
+ if (apps.length === 0) throw new CliError(NO_APPS_PICKED);
3332
+ } else {
3333
+ if (detected.length === 0) throw new CliError(NO_APPS_FOUND);
3334
+ apps = detected;
3335
+ }
3336
+ }
3337
+ const resolved = await resolveToken({ given: args.token, cwd: root, store, interactive, prompt: true }, prompts);
3338
+ if (!resolved) throw new CliError(TOKEN_REQUIRED);
3339
+ let token = resolved.token;
3340
+ let saved = args.token === void 0 ? resolved.entry : null;
3341
+ const api = apiFor(args, saved);
3342
+ const savedApi = api === DEFAULT_API_ORIGIN ? void 0 : api;
3343
+ let project;
3344
+ try {
3345
+ project = await fetchProject({ api, token }, io.fetchImpl);
3346
+ } catch (e) {
3347
+ if (!(e instanceof RejectedTokenError) || !saved) throw e;
3348
+ if (!interactive) throw new CliError(SAVED_TOKEN_REJECTED);
3349
+ token = await prompts.askHidden("The saved token was not accepted. Project token (workbench \u2192 Project settings):");
3350
+ if (!token) throw new CliError(TOKEN_REQUIRED);
3351
+ saved = null;
3352
+ project = await fetchProject({ api, token }, io.fetchImpl);
3353
+ }
3354
+ const plans = apps.map((id) => ({ id, plan: planAppFile(root, id, project.id) }));
3355
+ const kept = saved && saved.projectId === project.id ? store.addFolder(project.id, root, savedApi) : null;
3356
+ const entry = kept ?? await store.save({ projectId: project.id, name: project.name, folder: root, token, ...savedApi === void 0 ? {} : { api: savedApi } });
3357
+ const files = plans.flatMap(({ plan }) => plan.contents !== null && (plan.status === "create" || plan.status === "update") ? [{ path: plan.path, contents: plan.contents }] : []);
3358
+ try {
3359
+ if (files.length > 0) writeFiles(root, files, { force: true, created: false });
3360
+ } catch (e) {
3361
+ if (e instanceof CliError) throw new CliError(`${e.message} Your token for "${project.name}" was saved; run connect again to write the settings.`, e.exitCode);
3362
+ throw e;
3363
+ }
3364
+ const changed = plans.filter(({ plan }) => plan.status === "create" || plan.status === "update").map(({ id }) => id);
3365
+ const backup = "backup" in entry && entry.backup ? [`Your old credentials file could not be read, so it was kept as ${entry.backup}.`] : [];
3366
+ say([...backup, savedLine(project.name, entry.where, deps.credentialsPath, kept !== null), ...plans.flatMap(({ id, plan }) => appLines(id, plan)), ...closingLines(apps, changed)]);
3367
+ }
3368
+ function connectedApps(root, store) {
3369
+ const saved = store.byFolder(root);
3370
+ if (saved.length !== 1) return null;
3371
+ const { projectId } = saved[0];
3372
+ const apps = APPS.filter((a) => {
3373
+ try {
3374
+ return planAppFile(root, a.id, projectId).status === "unchanged";
3375
+ } catch {
3376
+ return false;
3377
+ }
3378
+ }).map((a) => a.id);
3379
+ return apps.length > 0 ? apps : null;
3380
+ }
3381
+ async function forget(args, root, store, interactive, prompts, file, say) {
3382
+ const matches = store.byFolder(root).filter((m) => args.project === void 0 || m.projectId === args.project);
3383
+ if (matches.length === 0) return say(["No saved token for this folder."]);
3384
+ let chosen = matches[0];
3385
+ if (matches.length > 1) {
3386
+ if (!interactive) {
3387
+ const names = matches.map((m) => `${m.name} (${m.projectId})`).join(", ");
3388
+ throw new CliError(`More than one design system is connected to this folder: ${names}. Pass --project <id> to say which to forget.`);
3389
+ }
3390
+ const id = await prompts.pick("Forget which design system?", matches.map((m) => ({ value: m.projectId, label: m.name, hint: m.projectId })));
3391
+ chosen = matches.find((m) => m.projectId === id);
3392
+ }
3393
+ const removed = await store.forget(chosen.projectId) ?? chosen;
3394
+ say([`Removed the saved token for "${removed.name}" from ${whereFrom(removed.where, file)}.`]);
3395
+ }
3396
+
3397
+ // src/commands/create.ts
3398
+ async function runCreate(args, env, io, store) {
3399
+ const saved = await savedToken(args.token, { cwd: io.cwd, store });
3400
+ const folder = args.folder ?? await askFolder(CREATE_DEFAULT_FOLDER);
3401
+ const token = saved?.token ?? await requireToken(void 0);
3402
+ await scaffold({ folder, framework: "next", token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
503
3403
  }
504
3404
 
505
3405
  // src/commands/integrate.ts
@@ -509,18 +3409,19 @@ var INTEGRATE_OPTIONS = [
509
3409
  { value: "angular", label: "Angular" },
510
3410
  { value: "css", label: "Plain CSS", hint: "any other stack" }
511
3411
  ];
512
- async function runIntegrate(args, env, io) {
3412
+ async function runIntegrate(args, env, io, store) {
513
3413
  const framework = args.framework ?? await pick("Framework", INTEGRATE_OPTIONS, 0);
3414
+ const saved = await savedToken(args.token, { cwd: io.cwd, store });
514
3415
  const folder = args.folder ?? await askFolder(INTEGRATE_DEFAULT_FOLDER);
515
- const token = await requireToken(args.token);
516
- await scaffold({ folder, framework, token, api: args.api, force: args.force }, env, io);
3416
+ const token = saved?.token ?? await requireToken(void 0);
3417
+ await scaffold({ folder, framework, token, api: apiFor(args, saved?.entry), force: args.force }, env, io);
517
3418
  }
518
3419
 
519
3420
  // src/mcp/server.ts
520
3421
  import { createInterface as createInterface2 } from "node:readline";
521
3422
 
522
3423
  // src/version.ts
523
- var VERSION = true ? "0.4.1" : "0.0.0-dev";
3424
+ var VERSION = true ? "0.6.0" : "0.0.0-dev";
524
3425
 
525
3426
  // src/mcp/jsonrpc.ts
526
3427
  var PARSE_ERROR = -32700;
@@ -576,7 +3477,23 @@ function getPrompt(name) {
576
3477
  return { description: "Integrate the design system into the current repository.", messages: [{ role: "user", content: { type: "text", text: INTEGRATE_TEXT } }] };
577
3478
  }
578
3479
 
3480
+ // src/mcp/project-folder.ts
3481
+ import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve5, sep as sep4 } from "node:path";
3482
+ var NOT_SURE_WHICH_FOLDER = "Not sure which project folder to change: run npx designsource connect in it first.";
3483
+ function isWithin2(folder, root) {
3484
+ const rel = relative4(root, folder);
3485
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep4}`) && !isAbsolute4(rel);
3486
+ }
3487
+ function resolveProjectFolder(cwd, entry) {
3488
+ if (!entry) return cwd;
3489
+ const here = resolve5(cwd);
3490
+ const holding = entry.folders.map((f) => resolve5(f)).filter((f) => isWithin2(here, f)).sort((a, b) => b.length - a.length);
3491
+ if (holding[0]) return holding[0];
3492
+ return entry.folders.length === 1 ? resolve5(entry.folders[0]) : null;
3493
+ }
3494
+
579
3495
  // src/mcp/tools.ts
3496
+ var READ_ONLY = { readOnlyHint: true };
580
3497
  var textResult = (text) => ({ content: [{ type: "text", text }] });
581
3498
  var errorResult = (text) => ({ content: [{ type: "text", text }], isError: true });
582
3499
  var TIERS = ["design", "semantic", "component"];
@@ -602,11 +3519,56 @@ function optionalEnum(args, key, allowed) {
602
3519
  }
603
3520
  return { ok: true, value: v };
604
3521
  }
3522
+ var MCP_EXEC_TIMEOUT_MS = 10 * 60 * 1e3;
3523
+ var UNKNOWN_FOR_AGENT = (names) => `Unknown component(s): ${names.join(", ")}. Call list_components for the names.`;
3524
+ var FOREIGN_FILES = (paths) => `These files exist and were not added by designsource: ${paths.join(", ")}. Ask the user whether to replace them, then call add_ui_kit again with replace_existing: true.`;
3525
+ async function addUiKit(args, ctx) {
3526
+ const { components, replace_existing: replace, no_blocks: noBlocks } = args;
3527
+ if (components !== void 0 && !(Array.isArray(components) && components.every((c) => typeof c === "string"))) {
3528
+ return errorResult('"components" must be an array of component names.');
3529
+ }
3530
+ if (replace !== void 0 && typeof replace !== "boolean") return errorResult('"replace_existing" must be true or false.');
3531
+ if (noBlocks !== void 0 && typeof noBlocks !== "boolean") return errorResult('"no_blocks" must be true or false.');
3532
+ if (ctx.token === null) return errorResult(ctx.missingToken ?? MCP_TOKEN_REQUIRED);
3533
+ const root = resolveProjectFolder(ctx.cwd, ctx.projectFolders === null ? null : { folders: ctx.projectFolders });
3534
+ if (root === null) return errorResult(NOT_SURE_WHICH_FOLDER);
3535
+ const questions = {
3536
+ pickComponents: async (all) => all,
3537
+ confirmReplace: async (paths) => {
3538
+ if (replace !== true) throw new CliError(FOREIGN_FILES(paths));
3539
+ return true;
3540
+ },
3541
+ keepEdits: async () => true
3542
+ };
3543
+ const progress = [];
3544
+ const exec = (cmd, cmdArgs, opts) => ctx.exec(cmd, cmdArgs, { ...opts, timeoutMs: MCP_EXEC_TIMEOUT_MS });
3545
+ try {
3546
+ const result = await runAdd(
3547
+ { root, token: ctx.token, api: ctx.api, components: components ?? [], skipInstall: false, blocks: noBlocks !== true },
3548
+ { fetchImpl: ctx.fetchImpl, exec, questions, progress: (line) => progress.push(line) }
3549
+ );
3550
+ const written = result.added.filter((n) => n !== "preview-portal");
3551
+ return textResult(
3552
+ [
3553
+ ...progress,
3554
+ ...summaryLines(result, "agent"),
3555
+ ...written.length > 0 ? [`Added: ${written.join(", ")}`] : [],
3556
+ `Next: import components from ${result.uiAlias} (for example: import { Button } from "${result.uiAlias}/button").`
3557
+ ].join("\n")
3558
+ );
3559
+ } catch (e) {
3560
+ if (!(e instanceof CliError) && progress.length === 0) throw e;
3561
+ const message = e instanceof UnknownComponentsError ? UNKNOWN_FOR_AGENT(e.names) : e instanceof Error ? e.message : String(e);
3562
+ const tail = e instanceof StepError && e.outputTail ? ["Last output:", e.outputTail] : [];
3563
+ return errorResult([...progress, message, ...tail].join("\n"));
3564
+ }
3565
+ }
605
3566
  var TOOLS = [
606
3567
  {
607
3568
  name: "get_project",
608
3569
  description: "The design system's name, token count, corner-radius strategy, font families and whether it has a mockup page. Call this first.",
609
3570
  inputSchema: NO_INPUT,
3571
+ annotations: READ_ONLY,
610
3572
  run: (snapshot, fetchedAt) => textResult(pretty({ ...snapshot.project, fetchedAt: new Date(fetchedAt).toISOString() }))
611
3573
  },
612
3574
  {
@@ -621,6 +3583,7 @@ var TOOLS = [
621
3583
  },
622
3584
  additionalProperties: false
623
3585
  },
3586
+ annotations: READ_ONLY,
624
3587
  run: (snapshot, _at, args) => {
625
3588
  const tier = optionalEnum(args, "tier", TIERS);
626
3589
  if (!tier.ok) return tier.error;
@@ -638,18 +3601,21 @@ var TOOLS = [
638
3601
  name: "get_css_variables",
639
3602
  description: "The whole design system as plain CSS custom properties for any stack: design tokens in :root, semantic and component tokens as var() aliases per theme, light and dark via [data-theme] and prefers-color-scheme.",
640
3603
  inputSchema: NO_INPUT,
3604
+ annotations: READ_ONLY,
641
3605
  run: (snapshot) => textResult(snapshot.cssVars)
642
3606
  },
643
3607
  {
644
3608
  name: "get_shadcn_theme",
645
3609
  description: "The design system as a shadcn/ui theme stylesheet for Tailwind v4: :root and .dark blocks plus @theme inline. Use on the React + Tailwind path.",
646
3610
  inputSchema: NO_INPUT,
3611
+ annotations: READ_ONLY,
647
3612
  run: (snapshot) => textResult(snapshot.shadcnTheme)
648
3613
  },
649
3614
  {
650
3615
  name: "list_components",
651
3616
  description: "Every component in the kit with the CSS variables its source reads, plus the helper files. Follow with get_component_source.",
652
3617
  inputSchema: NO_INPUT,
3618
+ annotations: READ_ONLY,
653
3619
  run: (snapshot) => textResult(
654
3620
  pretty({
655
3621
  components: Object.entries(snapshot.kit.variables).sort(([a], [b]) => a.localeCompare(b)).map(([name, variables]) => ({ name, variables })),
@@ -661,6 +3627,7 @@ var TOOLS = [
661
3627
  name: "get_component_source",
662
3628
  description: 'The React + Tailwind source of one component (see list_components), or a helper: "utils" for the cn helper, "preview-portal" for the portal context components import. Use verbatim in React; port to any other stack keeping every var() chain.',
663
3629
  inputSchema: { type: "object", properties: { name: { type: "string", description: "A name from list_components, or a helper (utils, preview-portal)." } }, required: ["name"], additionalProperties: false },
3630
+ annotations: READ_ONLY,
664
3631
  run: (snapshot, _at, args) => {
665
3632
  const names = Object.keys(snapshot.kit.sources).sort();
666
3633
  const name = args.name;
@@ -674,6 +3641,7 @@ ${snapshot.kit.sources[name]}`);
674
3641
  name: "get_mockup_page",
675
3642
  description: "The project's own mockup page as a layout spec, followed by the React renderer and schema that paint it. Render it as the first route.",
676
3643
  inputSchema: NO_INPUT,
3644
+ annotations: READ_ONLY,
677
3645
  run: (snapshot) => {
678
3646
  if (!snapshot.mockup) return textResult("This project has no mockup page.");
679
3647
  const files = Object.entries(snapshot.mockup.renderer).sort(([a], [b]) => a.localeCompare(b)).map(([file, source]) => `
@@ -687,18 +3655,21 @@ ${files.join("\n")}`);
687
3655
  name: "get_integration_guide",
688
3656
  description: "Step-by-step instructions for integrating this design system into the current repository: wire the tokens, bring in the components, migrate existing styles, document. Read this before changing anything.",
689
3657
  inputSchema: NO_INPUT,
3658
+ annotations: READ_ONLY,
690
3659
  run: (snapshot) => textResult(snapshot.guide)
691
3660
  },
692
3661
  {
693
3662
  name: "list_blocks",
694
3663
  description: "Ready-made page layouts built from the kit (login, signup, sidebars, a dashboard, chart sets): id, title, family, components used and files. Follow with get_block_source.",
695
3664
  inputSchema: NO_INPUT,
3665
+ annotations: READ_ONLY,
696
3666
  run: (snapshot) => snapshot.blocks ? textResult(pretty(snapshot.blocks.index)) : errorResult(NO_BLOCKS)
697
3667
  },
698
3668
  {
699
3669
  name: "get_block_source",
700
3670
  description: "Every file of one block (see list_blocks), each headed by the path it takes in the app: the block under components/blocks/, plus BlockStage (components/blocks/stage.tsx), which supplies the @container/stage its responsive classes query and the frame height, and the portal context it provides (components/ui/preview-portal.tsx). Render <BlockStage><Block /></BlockStage> as a full-viewport page. Use verbatim in React + Tailwind; port elsewhere keeping every var() chain.",
701
3671
  inputSchema: { type: "object", properties: { id: { type: "string", description: "A block id from list_blocks." } }, required: ["id"], additionalProperties: false },
3672
+ annotations: READ_ONLY,
702
3673
  run: (snapshot, _at, args) => {
703
3674
  const blocks = snapshot.blocks;
704
3675
  if (!blocks) return errorResult(NO_BLOCKS);
@@ -709,11 +3680,27 @@ ${blocks.sources[f] ?? ""}`);
709
3680
  return textResult(`${blocks.header ?? FALLBACK_BLOCK_SOURCE_HEADER}
710
3681
  ${files.join("\n\n")}`);
711
3682
  }
3683
+ },
3684
+ {
3685
+ name: "add_ui_kit",
3686
+ description: "Add this design system's UI kit to the React app in the current folder: the theme, the components and their libraries. Sets up Tailwind and shadcn when the app lacks them. A full run (no components named) also writes the /design-system section, every component, block and sample page in the project's theme, with its blocks unless no_blocks is true. Changes files in the project, so your client will ask the user first. Never overwrites components the user edited.",
3687
+ inputSchema: {
3688
+ type: "object",
3689
+ properties: {
3690
+ components: { type: "array", items: { type: "string" }, description: "Component names such as button or dialog. Omit to add everything (or refresh what was added before)." },
3691
+ replace_existing: { type: "boolean", description: "Replace component files that exist but were not added by designsource. Ask the user first." },
3692
+ no_blocks: { type: "boolean", description: "Add the /design-system section without its blocks and their libraries. Blocks an earlier run wrote are left in place." }
3693
+ },
3694
+ additionalProperties: false
3695
+ },
3696
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
3697
+ needsSnapshot: false,
3698
+ run: (_snapshot, _at, args, ctx) => addUiKit(args, ctx)
712
3699
  }
713
3700
  ];
714
3701
  var TOOL_NAMES = TOOLS.map((t) => t.name);
715
3702
  function toolList() {
716
- return { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
3703
+ return { tools: TOOLS.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, annotations })) };
717
3704
  }
718
3705
  function findTool(name) {
719
3706
  return TOOLS.find((t) => t.name === name);
@@ -721,6 +3708,7 @@ function findTool(name) {
721
3708
 
722
3709
  // src/mcp/protocol.ts
723
3710
  var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
3711
+ var NO_SNAPSHOT = {};
724
3712
  var asObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
725
3713
  async function handle(parsed, deps) {
726
3714
  if (parsed.kind === "error") return parsed.response;
@@ -744,17 +3732,29 @@ async function request(msg, deps) {
744
3732
  if (typeof params.name !== "string") return fail(id, INVALID_PARAMS, 'tools/call needs a string "name"');
745
3733
  const tool = findTool(params.name);
746
3734
  if (!tool) return fail(id, INVALID_PARAMS, `Unknown tool: ${params.name}`);
747
- let cached;
3735
+ let context;
748
3736
  try {
749
- cached = await deps.snapshot();
3737
+ context = await deps.context();
750
3738
  } catch (e) {
751
3739
  if (e instanceof CliError) return respond(id, errorResult(e.message));
752
3740
  const message = e instanceof Error ? e.message : String(e);
753
- deps.warn(`designsource mcp: loading the design system failed: ${message}`);
754
- return respond(id, errorResult(`Could not load the design system: ${message}`));
3741
+ deps.warn(`designsource mcp: finding the project token failed: ${message}`);
3742
+ return respond(id, errorResult(`Could not find the project token: ${message}`));
3743
+ }
3744
+ if (context.token === null) return respond(id, errorResult(context.missingToken ?? MCP_TOKEN_REQUIRED));
3745
+ let cached = { snapshot: NO_SNAPSHOT, fetchedAt: 0 };
3746
+ if (tool.needsSnapshot !== false) {
3747
+ try {
3748
+ cached = await deps.snapshot();
3749
+ } catch (e) {
3750
+ if (e instanceof CliError) return respond(id, errorResult(e.message));
3751
+ const message = e instanceof Error ? e.message : String(e);
3752
+ deps.warn(`designsource mcp: loading the design system failed: ${message}`);
3753
+ return respond(id, errorResult(`Could not load the design system: ${message}`));
3754
+ }
755
3755
  }
756
3756
  try {
757
- return respond(id, tool.run(cached.snapshot, cached.fetchedAt, asObject(params.arguments)));
3757
+ return respond(id, await tool.run(cached.snapshot, cached.fetchedAt, asObject(params.arguments), context));
758
3758
  } catch (e) {
759
3759
  if (e instanceof CliError) return respond(id, errorResult(e.message));
760
3760
  const message = e instanceof Error ? e.message : String(e);
@@ -775,22 +3775,22 @@ async function request(msg, deps) {
775
3775
  }
776
3776
 
777
3777
  // src/mcp/snapshot-client.ts
778
- var malformed2 = () => new CliError("Unexpected response from the API \u2014 not a design system snapshot.");
779
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
780
- var isStringRecord = (v) => isObject(v) && Object.values(v).every((x) => typeof x === "string");
781
- var isStringListRecord = (v) => isObject(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
782
- var isBlockEntry = (v) => isObject(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
3778
+ var malformed4 = () => new CliError("Unexpected response from the API \u2014 not a design system snapshot.");
3779
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3780
+ var isStringRecord = (v) => isObject2(v) && Object.values(v).every((x) => typeof x === "string");
3781
+ var isStringListRecord = (v) => isObject2(v) && Object.values(v).every((x) => Array.isArray(x) && x.every((s) => typeof s === "string"));
3782
+ var isBlockEntry = (v) => isObject2(v) && typeof v.id === "string" && typeof v.title === "string" && typeof v.family === "string" && Array.isArray(v.components) && v.components.every((c) => typeof c === "string") && Array.isArray(v.files) && v.files.every((f) => typeof f === "string");
783
3783
  function validateSnapshot(json) {
784
- if (!isObject(json)) throw malformed2();
785
- if (typeof json.version !== "number") throw malformed2();
3784
+ if (!isObject2(json)) throw malformed4();
3785
+ if (typeof json.version !== "number") throw malformed4();
786
3786
  if (json.version !== 1) throw new CliError(UPDATE_MESSAGE);
787
3787
  const { project, canonical, cssVars, shadcnTheme, kit, mockup, blocks, guide } = json;
788
- if (!isObject(project) || typeof project.name !== "string" || typeof project.radiusStrategy !== "string" || typeof project.tokenCount !== "number" || typeof project.hasMockup !== "boolean" || !isStringRecord(project.fonts)) throw malformed2();
789
- if (!isObject(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject)) throw malformed2();
790
- if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed2();
791
- if (!isObject(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed2();
792
- if (mockup !== null && !(isObject(mockup) && isObject(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed2();
793
- const validBlocks = isObject(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
3788
+ if (!isObject2(project) || typeof project.name !== "string" || typeof project.radiusStrategy !== "string" || typeof project.tokenCount !== "number" || typeof project.hasMockup !== "boolean" || !isStringRecord(project.fonts)) throw malformed4();
3789
+ if (!isObject2(canonical) || !Array.isArray(canonical.tokens) || !canonical.tokens.every(isObject2)) throw malformed4();
3790
+ if (typeof cssVars !== "string" || typeof shadcnTheme !== "string" || typeof guide !== "string") throw malformed4();
3791
+ if (!isObject2(kit) || !isStringRecord(kit.sources) || !isStringListRecord(kit.variables)) throw malformed4();
3792
+ if (mockup !== null && !(isObject2(mockup) && isObject2(mockup.spec) && isStringRecord(mockup.renderer))) throw malformed4();
3793
+ const validBlocks = isObject2(blocks) && Array.isArray(blocks.index) && blocks.index.every(isBlockEntry) && isStringRecord(blocks.sources);
794
3794
  if (!validBlocks) return { ...json, blocks: void 0 };
795
3795
  if (blocks.header !== void 0 && typeof blocks.header !== "string") return { ...json, blocks: { ...blocks, header: void 0 } };
796
3796
  return json;
@@ -836,13 +3836,31 @@ function createSnapshotCache(fetcher, opts = {}) {
836
3836
  }
837
3837
 
838
3838
  // src/mcp/server.ts
839
- async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }) {
840
- const token = args.token;
841
- if (!token) throw new CliError("A project token is required: pass --token or set DS_SYNC_TOKEN (workbench \u2192 Project settings).");
3839
+ async function runMcp(args, io, streams = { input: process.stdin, output: process.stdout }, deps = {}) {
3840
+ const cwd = deps.cwd ?? process.cwd();
3841
+ const store = deps.store ?? defaultStore();
842
3842
  const warn = (line) => io.stderr(`${line}
843
3843
  `);
844
- const cache = createSnapshotCache(() => fetchSnapshot({ api: args.api, token }, io.fetchImpl), { warn });
845
- const deps = { version: VERSION, snapshot: () => cache.get(), warn };
3844
+ let found = null;
3845
+ const fromStore = !args.token;
3846
+ const session = async () => {
3847
+ if (!found && (args.token || args.project)) found = await resolveToken({ given: args.token, cwd, projectId: args.project, store, interactive: false, prompt: false });
3848
+ else if (found && found.entry === null && args.project) found = { ...found, entry: store.entry(args.project) };
3849
+ if (found) return { token: found.token, projectFolders: args.project ? found.entry?.folders ?? [] : null, api: apiFor(args, found.entry), cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
3850
+ const missingToken = args.project ? NO_TOKEN_FOR_PROJECT(store.entry(args.project)?.name ?? args.project) : MCP_TOKEN_REQUIRED;
3851
+ return { token: null, missingToken, projectFolders: args.project ? [] : null, api: args.api, cwd, fetchImpl: io.fetchImpl, exec: spawnExec };
3852
+ };
3853
+ const cache = createSnapshotCache(async () => {
3854
+ const { token, missingToken, api } = await session();
3855
+ if (token === null) throw new CliError(missingToken);
3856
+ try {
3857
+ return await fetchSnapshot({ api, token }, io.fetchImpl);
3858
+ } catch (e) {
3859
+ if (fromStore && e instanceof CliError && e.message === TOKEN_MESSAGE) found = null;
3860
+ throw e;
3861
+ }
3862
+ }, { warn });
3863
+ const protocol = { version: VERSION, snapshot: () => cache.get(), warn, context: session };
846
3864
  const lines = createInterface2({ input: streams.input, crlfDelay: Infinity });
847
3865
  streams.output.on("error", () => {
848
3866
  lines.close();
@@ -850,13 +3868,15 @@ async function runMcp(args, io, streams = { input: process.stdin, output: proces
850
3868
  for await (const raw of lines) {
851
3869
  const line = raw.trim();
852
3870
  if (!line) continue;
853
- const response = await handle(parseLine(line), deps);
3871
+ const response = await handle(parseLine(line), protocol);
854
3872
  if (response) streams.output.write(encode(response));
855
3873
  }
856
3874
  }
857
3875
 
858
3876
  // src/index.ts
859
3877
  var MENU = [
3878
+ { value: "add", label: "Add the UI kit to a React app", hint: "your components and theme, set up for you" },
3879
+ { value: "connect", label: "Connect your coding apps", hint: "Claude Code, Cursor, VS Code and more" },
860
3880
  { value: "integrate", label: "Add to an existing project", hint: "writes design-system/ \u2014 tokens, prompt, reference kit" },
861
3881
  { value: "create", label: "Create a new project", hint: "a Next.js app with every component and your mockup page" }
862
3882
  ];
@@ -880,20 +3900,22 @@ ${e.usage}`);
880
3900
  try {
881
3901
  if (command.kind === "menu") {
882
3902
  if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
883
- io.stderr(`Missing command. Use integrate, create or mcp.
3903
+ io.stderr(`Missing command. ${USE_VERBS}
884
3904
 
885
3905
  ${USAGE}`);
886
3906
  return 1;
887
3907
  }
888
3908
  const verb = await pick("What do you want to do?", MENU, 0);
889
- command = verb === "create" ? { kind: "create", args: baseArgs(env) } : { kind: "integrate", args: baseArgs(env) };
3909
+ command = parseArgs([verb], env);
890
3910
  }
891
3911
  if (command.kind === "mcp") {
892
3912
  await runMcp(command.args, io);
893
3913
  return 0;
894
3914
  }
895
- if (command.kind === "create") await runCreate(command.args, env, io);
896
- else await runIntegrate(command.args, env, io);
3915
+ if (command.kind === "add") await runAddCommand(command.args, io);
3916
+ else if (command.kind === "connect") await runConnect(command.args, io, defaultConnectDeps(env));
3917
+ else if (command.kind === "create") await runCreate(command.args, env, io);
3918
+ else if (command.kind === "integrate") await runIntegrate(command.args, env, io);
897
3919
  return 0;
898
3920
  } catch (e) {
899
3921
  if (e instanceof CliError) {