@soroush.design/cli 0.3.0-alpha.0 → 0.3.0-alpha.2

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 (128) hide show
  1. package/README.md +6 -4
  2. package/dist/bin.mjs +2 -9
  3. package/dist/index.d.mts +19 -27
  4. package/dist/index.mjs +1 -1
  5. package/dist/init-C32LggZ7.mjs +1279 -0
  6. package/dist/{io-BFbf4S_u.mjs → io-BevxSPoR.mjs} +105 -883
  7. package/dist/migrate-Bhkz8pnP.mjs +22239 -0
  8. package/package.json +23 -22
  9. package/templates/astro/js/base/README.md +4 -3
  10. package/templates/astro/js/base/astro.config.mjs +16 -1
  11. package/templates/astro/js/base/src/components/About.jsx +2 -2
  12. package/templates/astro/js/base/src/components/Counter.jsx +3 -3
  13. package/templates/astro/js/base/src/components/Greeting.jsx +1 -1
  14. package/templates/astro/js/base/src/components/Header.jsx +6 -6
  15. package/templates/astro/js/base/src/components/Home.jsx +6 -6
  16. package/templates/astro/js/base/src/components/Home.test.jsx +5 -1
  17. package/templates/astro/js/base/src/components/NotFound.jsx +3 -3
  18. package/templates/astro/js/base/src/components/SchemeSwitch.jsx +4 -4
  19. package/templates/astro/js/base/src/theme/Island.jsx +1 -1
  20. package/templates/astro/js/sample-data/src/components/ItemDetails.jsx +3 -3
  21. package/templates/astro/js/sample-data/src/components/ItemList.jsx +3 -3
  22. package/templates/astro/js/sample-data/src/components/StatusChip.jsx +1 -1
  23. package/templates/astro/js/with/jotai/src/components/Counter.jsx +3 -3
  24. package/templates/astro/js/with/react-hook-form/src/components/Form.jsx +4 -4
  25. package/templates/astro/js/with/redux-toolkit/src/components/Counter.jsx +3 -3
  26. package/templates/astro/js/with/zustand/src/components/Counter.jsx +3 -3
  27. package/templates/astro/ts/base/README.md +4 -3
  28. package/templates/astro/ts/base/astro.config.mjs +16 -1
  29. package/templates/astro/ts/base/src/components/About.tsx +2 -2
  30. package/templates/astro/ts/base/src/components/Counter.tsx +3 -3
  31. package/templates/astro/ts/base/src/components/Greeting.tsx +1 -1
  32. package/templates/astro/ts/base/src/components/Header.tsx +6 -6
  33. package/templates/astro/ts/base/src/components/Home.test.tsx +5 -1
  34. package/templates/astro/ts/base/src/components/Home.tsx +6 -6
  35. package/templates/astro/ts/base/src/components/NotFound.tsx +3 -3
  36. package/templates/astro/ts/base/src/components/SchemeSwitch.tsx +4 -4
  37. package/templates/astro/ts/base/src/theme/Island.tsx +1 -1
  38. package/templates/astro/ts/sample-data/src/components/ItemDetails.tsx +3 -3
  39. package/templates/astro/ts/sample-data/src/components/ItemList.tsx +3 -3
  40. package/templates/astro/ts/sample-data/src/components/StatusChip.tsx +1 -1
  41. package/templates/astro/ts/with/jotai/src/components/Counter.tsx +3 -3
  42. package/templates/astro/ts/with/react-hook-form/src/components/Form.tsx +4 -4
  43. package/templates/astro/ts/with/redux-toolkit/src/components/Counter.tsx +3 -3
  44. package/templates/astro/ts/with/zustand/src/components/Counter.tsx +3 -3
  45. package/templates/react-router/js/base/README.md +4 -3
  46. package/templates/react-router/js/base/src/components/Header.jsx +5 -5
  47. package/templates/react-router/js/base/src/components/RouterLink.jsx +2 -2
  48. package/templates/react-router/js/base/src/components/SchemeSwitch.jsx +4 -4
  49. package/templates/react-router/js/base/src/main.jsx +5 -0
  50. package/templates/react-router/js/base/src/pages/ErrorPage.jsx +2 -2
  51. package/templates/react-router/js/base/src/pages/Layout.jsx +1 -1
  52. package/templates/react-router/js/base/src/pages/about/Page.jsx +2 -2
  53. package/templates/react-router/js/base/src/pages/index/Counter.jsx +3 -3
  54. package/templates/react-router/js/base/src/pages/index/Greeting.jsx +1 -1
  55. package/templates/react-router/js/base/src/pages/index/Page.jsx +6 -6
  56. package/templates/react-router/js/base/src/pages/index/Page.test.jsx +5 -1
  57. package/templates/react-router/js/sample-data/src/pages/item/Page.jsx +2 -2
  58. package/templates/react-router/js/sample-data/src/pages/items/Page.jsx +2 -2
  59. package/templates/react-router/js/sample-data/src/pages/items/StatusChip.jsx +1 -1
  60. package/templates/react-router/js/with/jotai/src/pages/index/Counter.jsx +3 -3
  61. package/templates/react-router/js/with/react-hook-form/src/pages/form/Page.jsx +4 -4
  62. package/templates/react-router/js/with/redux-toolkit/src/pages/index/Counter.jsx +3 -3
  63. package/templates/react-router/js/with/zustand/src/pages/index/Counter.jsx +3 -3
  64. package/templates/react-router/ts/base/README.md +4 -3
  65. package/templates/react-router/ts/base/src/components/Header.tsx +5 -5
  66. package/templates/react-router/ts/base/src/components/RouterLink.tsx +2 -2
  67. package/templates/react-router/ts/base/src/components/SchemeSwitch.tsx +4 -4
  68. package/templates/react-router/ts/base/src/main.tsx +5 -0
  69. package/templates/react-router/ts/base/src/pages/ErrorPage.tsx +2 -2
  70. package/templates/react-router/ts/base/src/pages/Layout.tsx +1 -1
  71. package/templates/react-router/ts/base/src/pages/about/Page.tsx +2 -2
  72. package/templates/react-router/ts/base/src/pages/index/Counter.tsx +3 -3
  73. package/templates/react-router/ts/base/src/pages/index/Greeting.tsx +1 -1
  74. package/templates/react-router/ts/base/src/pages/index/Page.test.tsx +5 -1
  75. package/templates/react-router/ts/base/src/pages/index/Page.tsx +6 -6
  76. package/templates/react-router/ts/sample-data/src/pages/item/Page.tsx +2 -2
  77. package/templates/react-router/ts/sample-data/src/pages/items/Page.tsx +2 -2
  78. package/templates/react-router/ts/sample-data/src/pages/items/StatusChip.tsx +1 -1
  79. package/templates/react-router/ts/with/jotai/src/pages/index/Counter.tsx +3 -3
  80. package/templates/react-router/ts/with/react-hook-form/src/pages/form/Page.tsx +4 -4
  81. package/templates/react-router/ts/with/redux-toolkit/src/pages/index/Counter.tsx +3 -3
  82. package/templates/react-router/ts/with/zustand/src/pages/index/Counter.tsx +3 -3
  83. package/templates/vike/js/base/README.md +3 -2
  84. package/templates/vike/js/base/src/components/Header.jsx +6 -6
  85. package/templates/vike/js/base/src/components/SchemeSwitch.jsx +4 -4
  86. package/templates/vike/js/base/src/pages/+Layout.jsx +1 -1
  87. package/templates/vike/js/base/src/pages/+onCreateGlobalContext.js +7 -0
  88. package/templates/vike/js/base/src/pages/+onRenderHtml.jsx +2 -3
  89. package/templates/vike/js/base/src/pages/PageShell.jsx +2 -2
  90. package/templates/vike/js/base/src/pages/_error/+Page.jsx +3 -3
  91. package/templates/vike/js/base/src/pages/about/+Page.jsx +2 -2
  92. package/templates/vike/js/base/src/pages/index/+Page.jsx +6 -6
  93. package/templates/vike/js/base/src/pages/index/Counter.jsx +3 -3
  94. package/templates/vike/js/base/src/pages/index/Greeting.jsx +1 -1
  95. package/templates/vike/js/base/src/pages/index/Page.test.jsx +5 -1
  96. package/templates/vike/js/sample-data/src/pages/items/+Page.jsx +3 -3
  97. package/templates/vike/js/sample-data/src/pages/items/@id/+Page.jsx +3 -3
  98. package/templates/vike/js/sample-data/src/pages/items/StatusChip.jsx +1 -1
  99. package/templates/vike/js/ssg/src/pages/about/+Page.jsx +2 -2
  100. package/templates/vike/js/ssr/src/pages/+onRenderHtml.jsx +2 -3
  101. package/templates/vike/js/ssr/src/pages/about/+Page.jsx +2 -2
  102. package/templates/vike/js/with/jotai/src/pages/index/Counter.jsx +3 -3
  103. package/templates/vike/js/with/react-hook-form/src/pages/form/+Page.jsx +4 -4
  104. package/templates/vike/js/with/redux-toolkit/src/pages/index/Counter.jsx +3 -3
  105. package/templates/vike/js/with/zustand/src/pages/index/Counter.jsx +3 -3
  106. package/templates/vike/ts/base/README.md +3 -2
  107. package/templates/vike/ts/base/src/components/Header.tsx +6 -6
  108. package/templates/vike/ts/base/src/components/SchemeSwitch.tsx +4 -4
  109. package/templates/vike/ts/base/src/pages/+Layout.tsx +1 -1
  110. package/templates/vike/ts/base/src/pages/+onCreateGlobalContext.ts +7 -0
  111. package/templates/vike/ts/base/src/pages/+onRenderHtml.tsx +2 -3
  112. package/templates/vike/ts/base/src/pages/PageShell.tsx +2 -2
  113. package/templates/vike/ts/base/src/pages/_error/+Page.tsx +3 -3
  114. package/templates/vike/ts/base/src/pages/about/+Page.tsx +2 -2
  115. package/templates/vike/ts/base/src/pages/index/+Page.tsx +6 -6
  116. package/templates/vike/ts/base/src/pages/index/Counter.tsx +3 -3
  117. package/templates/vike/ts/base/src/pages/index/Greeting.tsx +1 -1
  118. package/templates/vike/ts/base/src/pages/index/Page.test.tsx +5 -1
  119. package/templates/vike/ts/sample-data/src/pages/items/+Page.tsx +3 -3
  120. package/templates/vike/ts/sample-data/src/pages/items/@id/+Page.tsx +3 -3
  121. package/templates/vike/ts/sample-data/src/pages/items/StatusChip.tsx +1 -1
  122. package/templates/vike/ts/ssg/src/pages/about/+Page.tsx +2 -2
  123. package/templates/vike/ts/ssr/src/pages/+onRenderHtml.tsx +2 -3
  124. package/templates/vike/ts/ssr/src/pages/about/+Page.tsx +2 -2
  125. package/templates/vike/ts/with/jotai/src/pages/index/Counter.tsx +3 -3
  126. package/templates/vike/ts/with/react-hook-form/src/pages/form/+Page.tsx +4 -4
  127. package/templates/vike/ts/with/redux-toolkit/src/pages/index/Counter.tsx +3 -3
  128. package/templates/vike/ts/with/zustand/src/pages/index/Counter.tsx +3 -3
@@ -1,847 +1,11 @@
1
+ import { A as APP_PACKAGE, D as applyPlan, E as FONTS_STEP, M as CORE_PACKAGE, T as AGENT_STEPS, g as formatPlan, h as createThemesSource, j as APP_PACKAGE_VERSION, k as nodeFileSystem, m as createSetupSource, p as createProvidersSource, r as runInit, t as askScheme } from "./init-C32LggZ7.mjs";
1
2
  import { parseArgs } from "node:util";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
3
- import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync } from "node:fs";
4
+ import { dirname, join, relative } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { emitKeypressEvents } from "node:readline";
7
8
  import { createInterface } from "node:readline/promises";
8
- // src/apply/fileSystem.ts
9
- const nodeFileSystem = {
10
- readFile: (path) => readFileSync(path, "utf8"),
11
- createFile: (path, content) => writeFileSync(path, content, { flag: "wx" }),
12
- writeFile: (path, content) => writeFileSync(path, content),
13
- removeFile: (path) => rmSync(path),
14
- createDirectory: (path) => mkdirSync(path),
15
- removeDirectory: (path) => rmdirSync(path),
16
- removeTree: (path) => rmSync(path, {
17
- recursive: true,
18
- force: true
19
- }),
20
- isSymbolicLink: (path) => {
21
- try {
22
- return lstatSync(path).isSymbolicLink();
23
- } catch {
24
- return;
25
- }
26
- }
27
- };
28
- /**
29
- * The absolute path of `path`, given from the app's root, when it stays inside the root and
30
- * passes through no symbolic link. Anything else throws: init writes only inside the app.
31
- */
32
- function resolveInside(root, path, fileSystem) {
33
- const absolute = resolve(root, path);
34
- const fromRoot = relative(root, absolute);
35
- if (!fromRoot || fromRoot.startsWith("..") || isAbsolute(fromRoot)) throw new Error(`${path} is outside the app's folder`);
36
- let current = root;
37
- for (const segment of fromRoot.split(sep)) {
38
- current = join(current, segment);
39
- const isLink = fileSystem.isSymbolicLink(current);
40
- if (isLink === void 0) break;
41
- if (isLink) throw new Error(`${path} goes through a symbolic link, which init does not follow`);
42
- }
43
- return absolute;
44
- }
45
- /** The folders between the root and `directory` that do not exist yet, outermost first. */
46
- function findMissingDirectories(root, directory, fileSystem) {
47
- const missing = [];
48
- let current = directory;
49
- while (current !== root && fileSystem.isSymbolicLink(current) === void 0) {
50
- missing.unshift(current);
51
- current = dirname(current);
52
- }
53
- return missing;
54
- }
55
- // src/apply/applyPlan.ts
56
- /** A write failed. `isUndone` says whether every change made before it was taken back. */
57
- var ApplyError = class extends Error {
58
- isUndone;
59
- constructor(message, isUndone) {
60
- super(message);
61
- this.name = "ApplyError";
62
- this.isUndone = isUndone;
63
- }
64
- };
65
- /**
66
- * Writes the plan's files and edits. Each change keeps a step that takes it back, in memory: when
67
- * one write fails, the steps run in reverse, so the app is left as it was. Each edit is checked
68
- * against the file before it is written and read back after.
69
- */
70
- function applyPlan(plan, root, fileSystem = nodeFileSystem) {
71
- const undoSteps = [];
72
- try {
73
- for (const file of plan.creates) {
74
- const absolute = resolveInside(root, file.path, fileSystem);
75
- for (const directory of findMissingDirectories(root, dirname(absolute), fileSystem)) {
76
- fileSystem.createDirectory(directory);
77
- undoSteps.push(() => fileSystem.removeDirectory(directory));
78
- }
79
- fileSystem.createFile(absolute, file.content);
80
- undoSteps.push(() => fileSystem.removeFile(absolute));
81
- }
82
- for (const edit of plan.edits) {
83
- const absolute = resolveInside(root, edit.path, fileSystem);
84
- if (fileSystem.readFile(absolute) !== edit.before) throw new Error(`${edit.path} changed while init was running`);
85
- undoSteps.push(() => fileSystem.writeFile(absolute, edit.before));
86
- fileSystem.writeFile(absolute, edit.after);
87
- if (fileSystem.readFile(absolute) !== edit.after) throw new Error(`${edit.path} did not read back as init wrote it`);
88
- }
89
- } catch (error) {
90
- let isUndone = true;
91
- for (const undo of undoSteps.reverse()) try {
92
- undo();
93
- } catch {
94
- isUndone = false;
95
- }
96
- throw new ApplyError(error.message, isUndone);
97
- }
98
- }
99
- // src/closing.ts
100
- const SETUP_DOCS$1 = "https://docs.soroush.tech/design-system/getting-started/installation/";
101
- const FONTS_STEP = ` - Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. To add them,
102
- see ${SETUP_DOCS$1}#fonts`;
103
- const AGENT_STEPS = `For a coding agent, if you use one (any agent):
104
- - The house-style skill: npx skills add soroush-tech/design-system
105
- - The MCP server, for any MCP client: https://mcp.soroush.design/mcp
106
- `;
107
- // src/plan/rootEdit.ts
108
- const RENDER_CALL = /\.render\s*\(/g;
109
- const CLOSERS = {
110
- ")": "(",
111
- "]": "[",
112
- "}": "{"
113
- };
114
- /** Whether a source starts a client-rendered React app: `createRoot(...).render(` or `ReactDOM.render(`. */
115
- function isRootSource(source) {
116
- return /\bcreateRoot\s*\(/.test(source) && /\.render\s*\(/.test(source) || /\bReactDOM\.render\s*\(/.test(source);
117
- }
118
- /** Skips a string or a comment starting at `index`, returning the index after it, or `index` if none starts there. */
119
- function skipStringOrComment(source, index) {
120
- const char = source[index];
121
- if (char === "\"" || char === "'" || char === "`") {
122
- let cursor = index + 1;
123
- while (cursor < source.length && source[cursor] !== char) cursor += source[cursor] === "\\" ? 2 : 1;
124
- return cursor + 1;
125
- }
126
- if (source.startsWith("//", index)) {
127
- const end = source.indexOf("\n", index);
128
- return end === -1 ? source.length : end;
129
- }
130
- if (source.startsWith("/*", index)) {
131
- const end = source.indexOf("*/", index + 2);
132
- return end === -1 ? source.length : end + 2;
133
- }
134
- return index;
135
- }
136
- /**
137
- * The span of the first argument of the call whose `(` ends just before `from`: up to the first
138
- * comma or the closing parenthesis at its own depth. `null` when the call never closes.
139
- */
140
- function readFirstArgument(source, from) {
141
- const stack = [];
142
- let cursor = from;
143
- while (cursor < source.length) {
144
- const skipped = skipStringOrComment(source, cursor);
145
- if (skipped !== cursor) {
146
- cursor = skipped;
147
- continue;
148
- }
149
- const char = source[cursor];
150
- if (char === "(" || char === "[" || char === "{") stack.push(char);
151
- else if (char in CLOSERS) {
152
- if (stack.length === 0) return trimSpan(source, from, cursor);
153
- if (stack.pop() !== CLOSERS[char]) return null;
154
- } else if (char === "," && stack.length === 0) return trimSpan(source, from, cursor);
155
- cursor += 1;
156
- }
157
- return null;
158
- }
159
- function trimSpan(source, start, end) {
160
- let from = start;
161
- let to = end;
162
- while (from < to && /\s/.test(source[from])) from += 1;
163
- while (to > from && /\s/.test(source[to - 1])) to -= 1;
164
- return {
165
- start: from,
166
- end: to
167
- };
168
- }
169
- /** The indentation of the line `index` sits on. */
170
- function indentationAt(source, index) {
171
- const line = source.slice(source.lastIndexOf("\n", index - 1) + 1, index);
172
- return line.slice(0, line.length - line.trimStart().length);
173
- }
174
- /** Wraps a JSX child in `<Providers>`, keeping a multi-line tree on its own lines, one step deeper. */
175
- function wrapTree(tree, indentation) {
176
- if (!tree.includes("\n")) return `<Providers>${tree}</Providers>`;
177
- const step = indentation.includes(" ") ? " " : " ";
178
- return `<Providers>\n${indentation}${step}${tree.replaceAll("\n", `\n${step}`)}\n${indentation}</Providers>`;
179
- }
180
- const IMPORT_DECLARATION = /^import(?=[\s{*'"])[\s\S]*?(['"])[^'"\n]*\1[^\S\n]*(;?)/gm;
181
- /**
182
- * Adds an import after the last import declaration, in the file's own quote and semicolon style:
183
- * `statement` is written with single quotes and no semicolon.
184
- */
185
- function insertImport(source, statement) {
186
- const last = [...source.matchAll(IMPORT_DECLARATION)].at(-1);
187
- if (!last) return `${statement}\n${source}`;
188
- const [text, quote, semicolon] = last;
189
- const styled = (quote === "\"" ? statement.replaceAll("'", "\"") : statement) + semicolon;
190
- const end = last.index + text.length;
191
- return `${source.slice(0, end)}\n${styled}${source.slice(end)}`;
192
- }
193
- /**
194
- * The root with what it renders wrapped in `<Providers>` and the import added, or `null` when it
195
- * is not the standard shape: one render call. A JSX tree is wrapped as it is; any other argument -
196
- * a call, a variable - is wrapped as `<Providers>{...}</Providers>`, but only in a file that may
197
- * hold JSX (`canHoldJsx`, a `.jsx` or `.tsx` file).
198
- */
199
- function wrapRoot(source, importStatement, canHoldJsx) {
200
- const calls = [...source.matchAll(RENDER_CALL)];
201
- if (calls.length !== 1) return null;
202
- const call = calls[0];
203
- const argument = readFirstArgument(source, call.index + call[0].length);
204
- if (!argument) return null;
205
- const rendered = source.slice(argument.start, argument.end);
206
- const isTree = rendered.startsWith("<") && rendered.endsWith(">");
207
- if (!isTree && (!canHoldJsx || rendered === "")) return null;
208
- const wrapped = wrapTree(isTree ? rendered : `{${rendered}}`, indentationAt(source, argument.start));
209
- return insertImport(source.slice(0, argument.start) + wrapped + source.slice(argument.end), importStatement);
210
- }
211
- // src/detect/detect.ts
212
- /** A file's text, or `undefined` when it cannot be read. */
213
- function readText(path) {
214
- try {
215
- return readFileSync(path, "utf8");
216
- } catch {
217
- return;
218
- }
219
- }
220
- function readPackageJson(directory) {
221
- const text = readText(join(directory, "package.json"));
222
- return text === void 0 ? void 0 : JSON.parse(text);
223
- }
224
- /** A dependency's declared range, from `dependencies` or `devDependencies`. */
225
- function getDependency(packageJson, name) {
226
- return packageJson.dependencies?.[name] ?? packageJson.devDependencies?.[name];
227
- }
228
- const LOCKFILES = [
229
- ["pnpm-lock.yaml", "pnpm"],
230
- ["yarn.lock", "yarn"],
231
- ["bun.lock", "bun"],
232
- ["bun.lockb", "bun"],
233
- ["package-lock.json", "npm"],
234
- ["npm-shrinkwrap.json", "npm"]
235
- ];
236
- /**
237
- * The app's package manager: its `packageManager` field, else the lockfile in its folder or the
238
- * nearest one above it inside the same repository (a workspace keeps one at its root), else npm.
239
- */
240
- function detectPackageManager(root, packageJson, fileExists = existsSync) {
241
- const declared = /^(npm|pnpm|yarn|bun)@(\d+)/.exec(packageJson.packageManager ?? "");
242
- if (declared) {
243
- const name = declared[1];
244
- return {
245
- name,
246
- isYarnBerry: name === "yarn" && Number(declared[2]) >= 2
247
- };
248
- }
249
- for (let directory = root;; directory = dirname(directory)) {
250
- const lockfile = LOCKFILES.find(([file]) => fileExists(join(directory, file)));
251
- if (lockfile) {
252
- const name = lockfile[1];
253
- return {
254
- name,
255
- isYarnBerry: name === "yarn" && fileExists(join(directory, ".yarnrc.yml"))
256
- };
257
- }
258
- if (fileExists(join(directory, ".git")) || dirname(directory) === directory) return {
259
- name: "npm",
260
- isYarnBerry: false
261
- };
262
- }
263
- }
264
- /**
265
- * The React version the app has installed - in its own node_modules or a workspace's above it -
266
- * else the lowest its declared range allows. Only node_modules folders are searched: a global
267
- * folder or NODE_PATH says nothing about the app.
268
- */
269
- function findReactVersion(root, packageJson) {
270
- for (let directory = root;; directory = dirname(directory)) {
271
- const installed = readPackageJson(join(directory, "node_modules", "react"));
272
- if (installed) return installed.version;
273
- if (dirname(directory) === directory) break;
274
- }
275
- const match = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(getDependency(packageJson, "react") ?? "");
276
- return match ? `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}` : void 0;
277
- }
278
- /**
279
- * Whether `version` is in `range`. Only the shape the design system's peer ranges use is read:
280
- * caret ranges joined by `||`, such as `^18.0.0 || ^19.0.0`. Any other shape throws.
281
- */
282
- function satisfiesRange(version, range) {
283
- const [major, minor, patch] = version.split(/[.-]/).map(Number);
284
- return range.split("||").some((part) => {
285
- const match = /^\s*\^(\d+)\.(\d+)\.(\d+)\s*$/.exec(part);
286
- if (!match) throw new Error(`init cannot read the range ${range}`);
287
- const [low, lowMinor, lowPatch] = match.slice(1).map(Number);
288
- return major === low && (minor > lowMinor || minor === lowMinor && patch >= lowPatch);
289
- });
290
- }
291
- /** Whether the app is in a git repository with no uncommitted change. */
292
- function getGitState(root, io) {
293
- const { status, stdout } = io.run("git", ["status", "--porcelain"], { cwd: root });
294
- if (status !== 0) return "not-a-repository";
295
- return stdout.trim() === "" ? "clean" : "dirty";
296
- }
297
- const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([
298
- "node_modules",
299
- "dist",
300
- "build",
301
- "out",
302
- "coverage",
303
- "public"
304
- ]);
305
- const MAX_DEPTH = 5;
306
- /**
307
- * Every file under the app's folder that starts a client-rendered app, by its path from the root.
308
- * Tests, stories, folders that hold output or dependencies, hidden folders and symbolic links are
309
- * not read.
310
- */
311
- function findRootFiles(root, folder = "", depth = 0) {
312
- const found = [];
313
- for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
314
- const path = posix.join(folder, entry.name);
315
- if (entry.name.startsWith(".")) continue;
316
- if (entry.isDirectory() && !SKIPPED_FOLDERS.has(entry.name) && depth < MAX_DEPTH) found.push(...findRootFiles(root, path, depth + 1));
317
- else if (entry.isFile() && /\.m?[jt]sx?$/.test(entry.name) && !/\.(test|spec|stories)\./.test(entry.name) && isRootSource(readFileSync(join(root, path), "utf8"))) found.push(path);
318
- }
319
- return found;
320
- }
321
- /** Whether the folder is a workspace's root: pnpm's `pnpm-workspace.yaml`, or a `workspaces` field. */
322
- function isWorkspaceRoot(root, packageJson) {
323
- return packageJson.workspaces !== void 0 || existsSync(join(root, "pnpm-workspace.yaml"));
324
- }
325
- /**
326
- * The folder of the package a file belongs to: the nearest one above it, inside `root`, with a
327
- * `package.json`, by its path from the root - `''` for the root itself.
328
- */
329
- function findPackageFolder(root, path) {
330
- for (let folder = posix.dirname(path); folder !== "."; folder = posix.dirname(folder)) if (existsSync(join(root, folder, "package.json"))) return folder;
331
- return "";
332
- }
333
- /**
334
- * The `package.json` of `@soroush.tech/design-system`: the nearest one above `fromFile` that is named
335
- * for it. Its bin finds itself this way.
336
- */
337
- function readDesignSystemPackage(fromFile) {
338
- for (let directory = dirname(fromFile);; directory = dirname(directory)) {
339
- const packageJson = readPackageJson(directory);
340
- if (packageJson?.name === "@soroush.tech/design-system") return packageJson;
341
- if (dirname(directory) === directory) throw new Error("init cannot find the package.json of @soroush.tech/design-system");
342
- }
343
- }
344
- const UNSUPPORTED_FRAMEWORKS = [
345
- ["next", "Next.js"],
346
- ["vike", "Vike"],
347
- ["@react-router/dev", "React Router in framework mode"],
348
- ["@remix-run/react", "Remix"],
349
- ["gatsby", "Gatsby"],
350
- ["astro", "Astro"],
351
- ["expo", "Expo"],
352
- ["react-native", "React Native"]
353
- ];
354
- /** The framework an app is built on that init does not set up yet, if any. */
355
- function findUnsupportedFramework(packageJson) {
356
- return UNSUPPORTED_FRAMEWORKS.find(([name]) => getDependency(packageJson, name))?.[1];
357
- }
358
- /**
359
- * Whether the app builds with Parcel and has not turned on its reading of package exports, which
360
- * every subpath of the design system (`/theme`, `/engine`, `/Button`, ...) needs.
361
- */
362
- function needsParcelPackageExports(packageJson) {
363
- return getDependency(packageJson, "parcel") !== void 0 && packageJson["@parcel/resolver-default"]?.packageExports !== true;
364
- }
365
- // src/plan/diff.ts
366
- /**
367
- * A line diff of two texts, as printed lines: `+ ` added, `- ` removed, and up to `context`
368
- * unchanged lines around each change, with ` ...` where unchanged lines are left out. The files
369
- * it compares are an app's root, a few dozen lines, so the plain longest-common-subsequence
370
- * table is fast enough.
371
- */
372
- function diffLines(before, after, context = 2) {
373
- const oldLines = before.split("\n");
374
- const newLines = after.split("\n");
375
- const common = Array.from({ length: oldLines.length + 1 }, () => new Array(newLines.length + 1).fill(0));
376
- for (let i = oldLines.length - 1; i >= 0; i -= 1) for (let j = newLines.length - 1; j >= 0; j -= 1) common[i][j] = oldLines[i] === newLines[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
377
- const lines = [];
378
- let i = 0;
379
- let j = 0;
380
- while (i < oldLines.length || j < newLines.length) if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
381
- lines.push({
382
- mark: " ",
383
- text: oldLines[i]
384
- });
385
- i += 1;
386
- j += 1;
387
- } else if (i < oldLines.length && (j === newLines.length || common[i + 1][j] >= common[i][j + 1])) {
388
- lines.push({
389
- mark: "-",
390
- text: oldLines[i]
391
- });
392
- i += 1;
393
- } else {
394
- lines.push({
395
- mark: "+",
396
- text: newLines[j]
397
- });
398
- j += 1;
399
- }
400
- const isNearChange = (index) => lines.slice(Math.max(0, index - context), index + context + 1).some((line) => line.mark !== " ");
401
- const printed = [];
402
- lines.forEach((line, index) => {
403
- if (isNearChange(index)) printed.push(`${line.mark} ${line.text}`.trimEnd());
404
- else if (printed.at(-1) !== " ...") printed.push(" ...");
405
- });
406
- return printed;
407
- }
408
- // src/plan/formatPlan.ts
409
- /** The plan as the developer reads it before saying yes: every file, every edit and the install. */
410
- function formatPlan(plan) {
411
- const sections = [];
412
- if (plan.creates.length > 0) sections.push(["Create:", ...plan.creates.map((file) => ` ${file.path}`)].join("\n"));
413
- for (const edit of plan.edits) {
414
- const diff = diffLines(edit.before, edit.after).map((line) => ` ${line}`.trimEnd());
415
- sections.push([`Edit ${edit.path}:`, ...diff].join("\n"));
416
- }
417
- if (plan.install) {
418
- const { command, args, env } = plan.install;
419
- const prefix = Object.entries(env).map(([name, value]) => `${name}=${value} `);
420
- sections.push(`Install:\n ${prefix.join("")}${[command, ...args].join(" ")}`);
421
- }
422
- if (plan.skips.length > 0) sections.push(["Skip:", ...plan.skips.map((skip) => ` ${skip.path}: ${skip.reason}`)].join("\n"));
423
- if (plan.manual.length > 0) sections.push(["Left to you:", ...plan.manual.map((step) => ` - ${step}`)].join("\n"));
424
- return `${sections.join("\n\n")}\n`;
425
- }
426
- // src/templates/templates.ts
427
- /** The first line of every file init writes: a second run finds its own files by it. */
428
- const MARKER = "// Set up by @soroush.tech/design-system init.";
429
- const THEMING_DOCS = "https://docs.soroush.tech/design-system/customization/theming/";
430
- const AUGMENTATION_STUB = `
431
- // To add tokens of your own, declare them here, then give them values in each theme:
432
- //
433
- // import type { PaletteEntry } from '@soroush.tech/design-system/theme'
434
- //
435
- // declare module '@soroush.tech/design-system/theme' {
436
- // interface ThemePalette {
437
- // brand: PaletteEntry
438
- // }
439
- // }
440
- `;
441
- /**
442
- * The app's themes. The default export is an object of named themes, each a `createTheme` call
443
- * with a literal object last: the shape tools that edit a theme read and write.
444
- */
445
- function createThemesSource({ isTypeScript }) {
446
- return `${MARKER} Your themes: change any value, or add a theme.
447
- // Every token is listed at ${THEMING_DOCS}
448
- import { baseTheme, createTheme } from '@soroush.tech/design-system/theme'
449
- ${isTypeScript ? AUGMENTATION_STUB : ""}
450
- const themes = {
451
- light: createTheme(baseTheme, {
452
- name: 'light',
453
- colorScheme: 'light',
454
- logoFilter: 'brightness(0)',
455
- portraitBlend: 'multiply',
456
- portraitOpacity: 1,
457
- palette: {
458
- default: { main: '#5E6065', light: '#8F9094', dark: '#111214', contrastText: '#FFFFFF' },
459
- primary: { main: '#006E17', light: '#D4F9D2', dark: '#00530F', contrastText: '#FFFFFF' },
460
- secondary: { main: '#5ACC57', light: '#D4F9D2', dark: '#3AAA37', contrastText: '#FFFFFF' },
461
- success: { main: '#009928', light: '#E8FFE5', dark: '#006413', contrastText: '#FFFFFF' },
462
- error: { main: '#BA1A1A', light: '#FFDAD6', dark: '#93000A', contrastText: '#FFFFFF' },
463
- info: { main: '#0071A4', light: '#E0FAFF', dark: '#004D70', contrastText: '#FFFFFF' },
464
- warning: { main: '#CCA800', light: '#FFF0A0', dark: '#8C6D00', contrastText: '#FFFFFF' },
465
- },
466
- background: {
467
- backdrop: '#00000080',
468
- appBar: '#FFFFFFD9',
469
- glass: '#FFFFFF4D',
470
- modal: '#FFFFFF',
471
- default: '#EEEEEE',
472
- primary: '#F9F9F9',
473
- secondary: '#F3F3F3',
474
- paper: '#FFFFFF',
475
- terminal: '#EEEEEE',
476
- grid: '#5ACC5733',
477
- transparent: '#00000000',
478
- scrollbar: '#0000004D',
479
- scrollbarTrack: '#F3F3F380',
480
- },
481
- text: {
482
- inherit: 'inherit',
483
- initial: '#1A1C1C',
484
- primary: '#006E17',
485
- secondary: '#444748',
486
- disabled: '#1A1C1C73',
487
- error: '#BA1A1A',
488
- success: '#009928',
489
- info: '#0071A4',
490
- warning: '#8C6D00',
491
- },
492
- border: {
493
- default: '#1A1C1C24',
494
- light: '#0073181A',
495
- primary: '#006E17',
496
- dark: '#003D0B',
497
- },
498
- skeleton: {
499
- highlight: '#FFFFFFA6',
500
- },
501
- }),
502
- dark: createTheme(baseTheme, {
503
- name: 'dark',
504
- colorScheme: 'dark',
505
- }),
506
- }
507
-
508
- export default themes
509
- `;
510
- }
511
- /**
512
- * The providers the app's root renders inside: the theme, and the package's base page styles.
513
- * `scheme` picks the theme, `scheme` by default, so an app can switch it. It holds no JSX, so it
514
- * needs none of the app's JSX settings.
515
- */
516
- function createProvidersSource({ isTypeScript, scheme, themesImport }) {
517
- const typeImport = isTypeScript ? `import type { ReactNode } from 'react'
518
- ` : "";
519
- const props = isTypeScript ? `{
520
- children,
521
- scheme = '${scheme}',
522
- }: {
523
- readonly children?: ReactNode
524
- /** The theme to draw with, by its name in themes. */
525
- readonly scheme?: keyof typeof themes
526
- }` : `{ children, scheme = '${scheme}' }`;
527
- return `${MARKER} The app's root renders inside Providers.
528
- import { createElement } from 'react'
529
- ${typeImport}import { Global, globalStyles } from '@soroush.tech/design-system/engine'
530
- import { ThemeProvider } from '@soroush.tech/design-system/theme'
531
- import themes from '${themesImport}'
532
-
533
- /** Gives every component its theme, and draws the page's base styles. */
534
- export function Providers(${props}) {
535
- return createElement(
536
- ThemeProvider,
537
- { theme: themes[scheme] },
538
- createElement(Global, { styles: globalStyles }),
539
- children
540
- )
541
- }
542
- `;
543
- }
544
- // src/plan/importPath.ts
545
- const RELATIVE_SPECIFIER = /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g;
546
- /**
547
- * The extension style of a file's relative imports of code, so a new import matches its
548
- * neighbours: `./App.tsx` means the app imports TypeScript files by their own extension, `./App.js`
549
- * the Node style, and `./App` none.
550
- */
551
- function readExtensionStyle(source) {
552
- for (const [, specifier] of source.matchAll(RELATIVE_SPECIFIER)) {
553
- const extension = /\.(m?[jt]sx?)$/.exec(specifier)?.[1];
554
- if (extension) return extension.includes("t") ? ".ts" : ".js";
555
- }
556
- return "";
557
- }
558
- /** The specifier `fromFile` imports `toFile` by, both relative to the app's root, in `style`. */
559
- function toImportSpecifier(fromFile, toFile, style) {
560
- const target = toFile.replace(/\.[^./]+$/, style);
561
- const specifier = posix.relative(posix.dirname(fromFile), target);
562
- return specifier.startsWith(".") ? specifier : `./${specifier}`;
563
- }
564
- // src/plan/planInit.ts
565
- const SETUP_DOCS = "https://docs.soroush.tech/design-system/getting-started/installation/";
566
- /** The command that adds the design system with the app's own package manager, running no scripts. */
567
- function createInstallCommand({ name, isYarnBerry }, version) {
568
- const spec = `@soroush.tech/design-system@${version.includes("-") ? version : `^${version}`}`;
569
- if (name === "yarn" && isYarnBerry) return {
570
- command: "yarn",
571
- args: ["add", spec],
572
- env: { YARN_ENABLE_SCRIPTS: "false" }
573
- };
574
- return {
575
- command: name,
576
- args: [
577
- name === "npm" ? "install" : "add",
578
- spec,
579
- "--ignore-scripts"
580
- ],
581
- env: {}
582
- };
583
- }
584
- function describeRootProblem(facts) {
585
- if (facts.rootCandidates.length === 0) return "init found no file that calls createRoot(...).render( or ReactDOM.render(.";
586
- return `init found more than one root (${facts.rootCandidates.join(", ")}) and edits none.`;
587
- }
588
- /** Works out the changes, reading files through `facts.readFile` and writing nothing. */
589
- function planInit(facts) {
590
- const plan = {
591
- creates: [],
592
- edits: [],
593
- skips: [],
594
- manual: [],
595
- install: void 0
596
- };
597
- const extension = facts.isTypeScript ? "ts" : "js";
598
- const themeDir = facts.hasSrcFolder || !facts.root ? "src/theme" : posix.join(posix.dirname(facts.root.path), "theme");
599
- const themesPath = `${themeDir}/themes.${extension}`;
600
- const providersPath = `${themeDir}/Providers.${extension}`;
601
- const style = facts.root ? readExtensionStyle(facts.root.source) : "";
602
- if (planThemeFiles(plan, facts, {
603
- themesPath,
604
- providersPath,
605
- style
606
- })) planRootEdit(plan, facts, providersPath, style);
607
- else plan.manual.push(`Set up the theme by hand: ${SETUP_DOCS}`);
608
- if (facts.needsParcelPackageExports) plan.manual.push("Parcel finds @soroush.tech/design-system/theme and the other subpaths only once it reads package exports. Add to package.json: \"@parcel/resolver-default\": { \"packageExports\": true }");
609
- if (!facts.hasDesignSystem) plan.install = createInstallCommand(facts.packageManager, facts.version);
610
- return plan;
611
- }
612
- /** Whether a file is missing, was written by init, or by someone else. */
613
- function getOwnership(facts, path) {
614
- const content = facts.readFile(path);
615
- if (content === void 0) return "missing";
616
- return content.startsWith("// Set up by @soroush.tech/design-system init.") ? "ours" : "theirs";
617
- }
618
- /**
619
- * Plans the themes and the providers, never over a file init did not write. Returns whether the
620
- * app ends up with init's providers.
621
- */
622
- function planThemeFiles(plan, facts, { themesPath, providersPath, style }) {
623
- const themes = getOwnership(facts, themesPath);
624
- const providers = getOwnership(facts, providersPath);
625
- if (themes === "missing") plan.creates.push({
626
- path: themesPath,
627
- content: createThemesSource(facts)
628
- });
629
- else if (themes === "theirs") plan.skips.push({
630
- path: themesPath,
631
- reason: "exists, and init did not write it"
632
- });
633
- if (providers === "theirs") plan.skips.push({
634
- path: providersPath,
635
- reason: "exists, and init did not write it"
636
- });
637
- else if (providers === "missing" && themes === "theirs") plan.skips.push({
638
- path: providersPath,
639
- reason: `would read ${themesPath}, which init did not write`
640
- });
641
- else if (providers === "missing") {
642
- const themesImport = toImportSpecifier(providersPath, themesPath, style);
643
- plan.creates.push({
644
- path: providersPath,
645
- content: createProvidersSource({
646
- ...facts,
647
- themesImport
648
- })
649
- });
650
- }
651
- return providers === "ours" || plan.creates.some((file) => file.path === providersPath);
652
- }
653
- /** Plans the root's edit, or the lines to add by hand when init cannot make it. */
654
- function planRootEdit(plan, facts, providersPath, style) {
655
- if (!facts.root) {
656
- plan.manual.push(`${describeRootProblem(facts)} In the file that renders your app, import { Providers } from ${providersPath} and wrap the tree it renders: render(<Providers><App /></Providers>).`);
657
- return;
658
- }
659
- const specifier = toImportSpecifier(facts.root.path, providersPath, style);
660
- const statement = `import { Providers } from '${specifier}'`;
661
- const { path, source } = facts.root;
662
- const after = source.includes(`'${specifier}'`) || source.includes(`"${specifier}"`) ? source : wrapRoot(source, statement, /\.[jt]sx$/.test(path));
663
- if (after === null) plan.manual.push(`${path} is not the standard shape, so init leaves it as it is. Add ${statement} to it, and wrap the tree it renders: render(<Providers><App /></Providers>).`);
664
- else if (after !== source) plan.edits.push({
665
- path,
666
- before: source,
667
- after
668
- });
669
- }
670
- /** Whether the plan has nothing to write or install. */
671
- function isPlanEmpty(plan) {
672
- return plan.creates.length === 0 && plan.edits.length === 0 && !plan.install;
673
- }
674
- // src/init.ts
675
- function formatClosing$1({ creates, manual }) {
676
- const themes = creates.find((file) => /\/themes\.[jt]s$/.test(file.path));
677
- const themesStep = themes ? `\n - Make the themes your own in ${themes.path}.` : "";
678
- const steps = manual.map((step) => ` - ${step}`).join("\n");
679
- return `Done: the design system is set up.
680
- ${manual.length > 0 ? `\nStill left to you:\n${steps}\n` : ""}
681
- Next:
682
- - Use a component: import { Button } from '@soroush.tech/design-system/Button'${themesStep}
683
- ${FONTS_STEP}
684
-
685
- ${AGENT_STEPS}`;
686
- }
687
- /** Why init refuses this app, or `undefined` when it can set it up. */
688
- function findRefusal(root, packageJson, reactRange) {
689
- const framework = findUnsupportedFramework(packageJson);
690
- if (framework) return `This looks like a ${framework} app. init sets up client-rendered React apps for now, so it changes nothing here. To set it up by hand, see ${SETUP_DOCS$1}`;
691
- const reactVersion = findReactVersion(root, packageJson);
692
- if (!reactVersion) return "init found no React in this app. Add react and react-dom first.";
693
- if (!satisfiesRange(reactVersion, reactRange)) return `This app has React ${reactVersion}, and the design system needs React ${reactRange}. init changes nothing, and never upgrades React.`;
694
- }
695
- function findGitRefusal(root, io) {
696
- const state = getGitState(root, io);
697
- if (state === "not-a-repository") return "This folder is not in a git repository, so init could not show you its changes afterwards. Run git init and commit first, or run again with --force.";
698
- if (state === "dirty") return "This folder has uncommitted changes. Commit or stash them first, so init's changes stand on their own, or run again with --force.";
699
- }
700
- /**
701
- * The app init sets up from `cwd`: the folder itself, or - in a workspace's root - the one package
702
- * in it that starts an app. A string says why there is none. A file in a nested package is never
703
- * taken for the app's own.
704
- */
705
- function findApp(cwd) {
706
- const packageJson = readPackageJson(cwd);
707
- if (!packageJson) return "There is no package.json in this folder. Run init in your app's folder.";
708
- const rootFilesByFolder = /* @__PURE__ */ new Map();
709
- for (const path of findRootFiles(cwd)) {
710
- const folder = findPackageFolder(cwd, path);
711
- rootFilesByFolder.set(folder, [...rootFilesByFolder.get(folder) ?? [], path]);
712
- }
713
- if (!isWorkspaceRoot(cwd, packageJson)) return {
714
- root: cwd,
715
- packageJson,
716
- rootCandidates: rootFilesByFolder.get("") ?? [],
717
- folder: ""
718
- };
719
- const folders = [...rootFilesByFolder.keys()];
720
- if (folders.length === 0) return "This is a workspace's root, and init found no app in it that calls createRoot(...).render( or ReactDOM.render(. Run init in your app's folder.";
721
- if (folders.length > 1) return `This is a workspace's root with more than one app (${folders.map((folder) => folder || ".").join(", ")}). Run init in the one to set up, for example: cd ${folders.find(Boolean)}`;
722
- const [folder] = folders;
723
- const root = join(cwd, folder);
724
- const rootCandidates = rootFilesByFolder.get(folder).map((path) => folder ? path.slice(folder.length + 1) : path);
725
- return {
726
- root,
727
- packageJson: readPackageJson(root),
728
- rootCandidates,
729
- folder
730
- };
731
- }
732
- /** Asks for the default color scheme, starting on light. */
733
- async function askScheme(io) {
734
- return await io.select("Default color scheme", [{
735
- value: "light",
736
- label: "light"
737
- }, {
738
- value: "dark",
739
- label: "dark"
740
- }]);
741
- }
742
- function collectFacts(app, scheme, designSystem) {
743
- const { root, packageJson, rootCandidates } = app;
744
- const rootPath = rootCandidates.length === 1 ? rootCandidates[0] : void 0;
745
- return {
746
- isTypeScript: rootPath ? /\.m?tsx?$/.test(rootPath) : existsSync(join(root, "tsconfig.json")),
747
- hasSrcFolder: existsSync(join(root, "src")),
748
- root: rootPath ? {
749
- path: rootPath,
750
- source: readText(join(root, rootPath))
751
- } : void 0,
752
- rootCandidates,
753
- hasDesignSystem: Boolean(getDependency(packageJson, "@soroush.tech/design-system")),
754
- needsParcelPackageExports: needsParcelPackageExports(packageJson),
755
- packageManager: detectPackageManager(root, packageJson),
756
- version: designSystem.version,
757
- scheme: scheme ?? "light",
758
- readFile: (path) => readText(join(root, path))
759
- };
760
- }
761
- /** Plans, asking for the default scheme first when init creates the providers and may ask. */
762
- async function planWithScheme(facts, canAsk, io) {
763
- const plan = planInit(facts);
764
- return plan.creates.some((file) => /\/Providers\.[jt]s$/.test(file.path)) && canAsk ? planInit({
765
- ...facts,
766
- scheme: await askScheme(io)
767
- }) : plan;
768
- }
769
- /** Whether to apply the plan: never on a dry run or with no terminal, else on --yes or a yes. */
770
- async function isApproved$1(options, isPreviewOnly, io) {
771
- if (options.isDryRun) {
772
- io.write("Dry run: nothing was changed.\n");
773
- return false;
774
- }
775
- if (isPreviewOnly) {
776
- io.write("Preview only: there is no terminal to answer in. Run again with --yes to apply.\n");
777
- return false;
778
- }
779
- if (options.isConfirmed) return true;
780
- const isYes = /^y(es)?$/i.test((await io.ask("Apply these changes? (y/N) ")).trim());
781
- if (!isYes) io.write("Nothing was changed.\n");
782
- return isYes;
783
- }
784
- /** Writes the plan, then installs the package. Returns the exit code. */
785
- function applyAndInstall(plan, root, io, fileSystem) {
786
- try {
787
- applyPlan(plan, root, fileSystem);
788
- } catch (error) {
789
- const { message, isUndone } = error;
790
- const outcome = isUndone ? "Every change it made was taken back." : "It could not take back every change: check git status.";
791
- io.write(`init stopped: ${message}. ${outcome}\n`);
792
- return 1;
793
- }
794
- if (plan.install) {
795
- const { command, args, env } = plan.install;
796
- io.write(`\nInstalling with ${command}:\n`);
797
- if (io.run(command, args, {
798
- cwd: root,
799
- env,
800
- showOutput: true
801
- }).status !== 0) {
802
- const commandLine = [command, ...args].join(" ");
803
- io.write(`\nThe install failed. The files are written; install the package yourself:\n ${commandLine}\n`);
804
- return 1;
805
- }
806
- }
807
- io.write(formatClosing$1(plan));
808
- return 0;
809
- }
810
- /**
811
- * Sets up the design system in the app in `io.cwd`: checks, plans, shows the plan, and applies it
812
- * only after a yes. `designSystem` is the package it installs: its version, and the React range it
813
- * checks the app against. Returns the exit code.
814
- */
815
- async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
816
- const app = findApp(realpathSync(io.cwd));
817
- if (typeof app === "string") {
818
- io.write(`${app}\n`);
819
- return 1;
820
- }
821
- const { root, packageJson, folder } = app;
822
- if (folder) io.write(`This is a workspace's root: init sets up the app in ${folder}.\n\n`);
823
- const refusal = findRefusal(root, packageJson, designSystem.peerDependencies.react);
824
- if (refusal) {
825
- io.write(`${refusal}\n`);
826
- return 1;
827
- }
828
- const isPreviewOnly = options.isDryRun || !io.isInteractive && !options.isConfirmed;
829
- const gitRefusal = isPreviewOnly || options.isForced ? void 0 : findGitRefusal(root, io);
830
- if (gitRefusal) {
831
- io.write(`${gitRefusal}\n`);
832
- return 1;
833
- }
834
- const plan = await planWithScheme(collectFacts(app, options.scheme, designSystem), !options.scheme && !isPreviewOnly && !options.isConfirmed, io);
835
- if (isPlanEmpty(plan)) {
836
- const leftovers = plan.skips.length + plan.manual.length > 0 ? `\n${formatPlan(plan)}` : "";
837
- io.write(`The design system is already set up here: init has nothing to change.\n${leftovers}`);
838
- return 0;
839
- }
840
- const appName = packageJson.name ?? "this app";
841
- io.write(`init will set up @soroush.tech/design-system in ${appName}:\n\n${formatPlan(plan)}\n`);
842
- if (!await isApproved$1(options, isPreviewOnly, io)) return 0;
843
- return applyAndInstall(plan, root, io, fileSystem);
844
- }
845
9
  // src/create/packageManager.ts
846
10
  /** The package managers create installs with, in the order it offers them. */
847
11
  const PACKAGE_MANAGERS = [
@@ -1127,38 +291,39 @@ function createTemplateFiles(framework, facts, root = findTemplatesRoot()) {
1127
291
  /** The versions the starters install: the ones this package is tested with. */
1128
292
  const VERSIONS = {
1129
293
  "@astrojs/check": "^0.9.12",
1130
- "@astrojs/node": "^11.1.13",
294
+ "@astrojs/node": "^11.1.14",
1131
295
  "@astrojs/react": "^7.1.9",
1132
- "@hookform/resolvers": "^7.0.6",
1133
- "@reduxjs/toolkit": "^2.14.0",
296
+ "@babel/parser": "^8.1.3",
297
+ "@babel/types": "^8.1.3",
298
+ "@hookform/resolvers": "^7.0.10",
299
+ "@reduxjs/toolkit": "^2.16.0",
1134
300
  "@soroush.tech/eslint-config": "workspace:*",
1135
- "@tanstack/react-query": "^5.107.1",
301
+ "@tanstack/react-query": "^5.108.4",
1136
302
  "@testing-library/dom": "^10.4.2",
1137
303
  "@testing-library/react": "^16.3.3",
1138
- "@types/node": "^26.6.6",
1139
- "@types/react": "^19.3.0",
304
+ "@types/node": "^26.6.11",
305
+ "@types/react": "^19.3.3",
1140
306
  "@types/react-dom": "^19.3.0",
1141
- "@umber-style/server": "0.3.0",
1142
307
  "@vitejs/plugin-react": "^6.3.0",
1143
- "@vitest/coverage-v8": "^5.1.0",
1144
- "astro": "^7.4.12",
1145
- "jotai": "^3.0.2",
308
+ "@vitest/coverage-v8": "^5.1.2",
309
+ "astro": "^7.4.13",
310
+ "jotai": "^3.1.0",
1146
311
  "jsdom": "^31.0.1",
1147
- "msw": "^3.0.5",
1148
- "oxlint": "^1.93.0",
312
+ "msw": "^3.0.8",
313
+ "oxlint": "^1.96.0",
1149
314
  "react": "^19.3.1",
1150
315
  "react-dom": "^19.3.1",
1151
316
  "react-hook-form": "^7.92.0",
1152
317
  "react-redux": "^9.3.1",
1153
- "react-router": "^8.5.1",
318
+ "react-router": "^8.5.3",
1154
319
  "swr": "^2.5.1",
1155
- "ts-blank-space": "^0.9.0",
320
+ "ts-blank-space": "^0.10.1",
1156
321
  "tsdown": "^0.23.7",
1157
322
  "typescript": "~7.0.2",
1158
323
  "typescript-astro": "npm:typescript@^6.0.3",
1159
324
  "vike": "0.4.270",
1160
- "vite": "~8.3.8",
1161
- "vitest": "^5.1.0",
325
+ "vite": "~8.4.0",
326
+ "vitest": "^5.1.2",
1162
327
  "zod": "^4.6.7",
1163
328
  "zustand": "^5.1.0"
1164
329
  };
@@ -1213,7 +378,8 @@ function createPackageJson$2({ packageName, isTypeScript, rendering, libraries,
1213
378
  test: "vitest run"
1214
379
  },
1215
380
  dependencies: {
1216
- "@soroush.tech/design-system": toRange(version),
381
+ [APP_PACKAGE]: toRange(version),
382
+ [CORE_PACKAGE]: toRange(version),
1217
383
  ...pickVersions([
1218
384
  ...isServer ? ["@astrojs/node"] : [],
1219
385
  "@astrojs/react",
@@ -1251,6 +417,14 @@ function createFiles$2(facts) {
1251
417
  path: `src/theme/themes.${x}`,
1252
418
  content: createThemesSource({ isTypeScript })
1253
419
  },
420
+ {
421
+ path: `src/theme/setup.${x}`,
422
+ content: createSetupSource({
423
+ isTypeScript,
424
+ themesImport: "./themes",
425
+ theme: `themes.${scheme}`
426
+ })
427
+ },
1254
428
  {
1255
429
  path: `src/theme/Providers.${x}`,
1256
430
  content: createProvidersSource({
@@ -1285,7 +459,8 @@ function createPackageJson$1({ packageName, isTypeScript, libraries, version })
1285
459
  test: "vitest run"
1286
460
  },
1287
461
  dependencies: {
1288
- "@soroush.tech/design-system": toRange(version),
462
+ [APP_PACKAGE]: toRange(version),
463
+ [CORE_PACKAGE]: toRange(version),
1289
464
  ...pickVersions([
1290
465
  ...libraryPackages,
1291
466
  "react",
@@ -1320,6 +495,14 @@ function createFiles$1(facts) {
1320
495
  path: `src/theme/themes.${x}`,
1321
496
  content: createThemesSource({ isTypeScript })
1322
497
  },
498
+ {
499
+ path: `src/theme/setup.${x}`,
500
+ content: createSetupSource({
501
+ isTypeScript,
502
+ themesImport: "./themes",
503
+ theme: `themes.${scheme}`
504
+ })
505
+ },
1323
506
  {
1324
507
  path: `src/theme/Providers.${x}`,
1325
508
  content: createProvidersSource({
@@ -1355,9 +538,9 @@ function createPackageJson({ packageName, isTypeScript, rendering, libraries, ve
1355
538
  test: "vitest run"
1356
539
  },
1357
540
  dependencies: {
1358
- "@soroush.tech/design-system": toRange(version),
541
+ [APP_PACKAGE]: toRange(version),
542
+ [CORE_PACKAGE]: toRange(version),
1359
543
  ...pickVersions([
1360
- "@umber-style/server",
1361
544
  ...libraryPackages,
1362
545
  "react",
1363
546
  "react-dom",
@@ -1391,6 +574,14 @@ function createFiles(facts) {
1391
574
  path: `src/theme/themes.${x}`,
1392
575
  content: createThemesSource({ isTypeScript })
1393
576
  },
577
+ {
578
+ path: `src/theme/setup.${x}`,
579
+ content: createSetupSource({
580
+ isTypeScript,
581
+ themesImport: "./themes",
582
+ theme: `themes.${scheme}`
583
+ })
584
+ },
1394
585
  {
1395
586
  path: `src/theme/Providers.${x}`,
1396
587
  content: createProvidersSource({
@@ -1555,11 +746,6 @@ function removeApp(target, wasMissing, fileSystem) {
1555
746
  return false;
1556
747
  }
1557
748
  }
1558
- /** Whether `folder` is inside a git work tree. */
1559
- function isInsideRepository(folder, io) {
1560
- const { status, stdout } = io.run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: folder });
1561
- return status === 0 && stdout.trim() === "true";
1562
- }
1563
749
  const YES_OR_NO = [{
1564
750
  value: "yes",
1565
751
  label: "Yes"
@@ -1731,9 +917,6 @@ function writeAndInstall({ name, target, wasMissing, plan, packageManager }, opt
1731
917
  env,
1732
918
  showOutput: true
1733
919
  }).status !== 0) return fail("the install failed");
1734
- if (options.isGit && !isInsideRepository(target, io)) {
1735
- if (io.run("git", ["init"], { cwd: target }).status !== 0) io.write("\ngit init failed, so the app has no repository. Run git init there yourself.\n");
1736
- }
1737
920
  io.write(formatClosing(name, plan, packageManager));
1738
921
  return 0;
1739
922
  }
@@ -1828,11 +1011,11 @@ function formatHeadline({ name, packageName, starter, isTypeScript, rendering, l
1828
1011
  return `create will make ${name}${packageNote}, ${article} ${starter.title} app in ${language} (${renderingName}), ${workspaceNote}in ./${name}:`;
1829
1012
  }
1830
1013
  /**
1831
- * Starts a new app on the design system, in a new or empty folder in `io.cwd`: asks what it is
1014
+ * Starts a new app on Gild UI, in a new or empty folder in `io.cwd`: asks what it is
1832
1015
  * not told, plans with the starter, shows the plan, and writes and installs only after a yes.
1833
- * `designSystem` is the package it installs. Returns the exit code.
1016
+ * Returns the exit code.
1834
1017
  */
1835
- async function runCreate(options, io, designSystem, { starters = STARTERS, fileSystem = nodeFileSystem, userAgent = process.env.npm_config_user_agent } = {}) {
1018
+ async function runCreate(options, io, { starters = STARTERS, fileSystem = nodeFileSystem, userAgent = process.env.npm_config_user_agent } = {}) {
1836
1019
  const isPreviewOnly = options.isDryRun || !io.isInteractive && !options.isConfirmed;
1837
1020
  const choices = await readChoices(options, io, starters, userAgent, !isPreviewOnly && !options.isConfirmed);
1838
1021
  if ("refusal" in choices) {
@@ -1850,7 +1033,7 @@ async function runCreate(options, io, designSystem, { starters = STARTERS, fileS
1850
1033
  libraries: choices.libraries,
1851
1034
  scheme: choices.scheme,
1852
1035
  hasSampleData: choices.hasSampleData,
1853
- version: designSystem.version
1036
+ version: APP_PACKAGE_VERSION
1854
1037
  });
1855
1038
  const plan = {
1856
1039
  creates: isWorkspace ? createWorkspaceFiles(appFiles, {
@@ -1933,8 +1116,9 @@ const BIN = "npx @soroush.design/cli";
1933
1116
  const USAGE = `Usage: ${BIN} <command> [options]
1934
1117
 
1935
1118
  Commands:
1936
- init set up @soroush.tech/design-system in the React app in this folder
1937
- create [name] start a new app on the design system, in a new folder
1119
+ init set up ${APP_PACKAGE} in the React app in this folder
1120
+ create [name] start a new app on Gild UI, in a new folder
1121
+ migrate move the app in this folder to the latest Gild UI, step by step
1938
1122
 
1939
1123
  Each shows every change first, and writes nothing until you say yes.
1940
1124
  For a command's options, run it with --help: ${BIN} create --help
@@ -1944,22 +1128,48 @@ const [defaultFramework, ...otherFrameworks] = Object.keys(STARTERS);
1944
1128
  const HELP = {
1945
1129
  init: `Usage: ${BIN} init [options]
1946
1130
 
1947
- Sets the design system up in the React app in this folder, or in a workspace's root that holds
1131
+ Sets Gild UI up in the React app in this folder, or in a workspace's root that holds
1948
1132
  one app. It shows every change first, and writes nothing until you say yes.
1949
1133
 
1950
1134
  Options:
1951
1135
  -y, --yes apply without asking
1952
1136
  --dry-run show the changes and exit
1953
- --force run outside git, or with uncommitted changes
1137
+ --force no effect: init checks no git now (kept for older scripts)
1954
1138
  --scheme <name> the default color scheme: light (the default) or dark
1955
1139
  -h, --help show this help
1956
1140
 
1957
1141
  Example:
1958
1142
  ${BIN} init --scheme dark
1143
+ `,
1144
+ migrate: `Usage: ${BIN} migrate [options]
1145
+
1146
+ Moves the app in this folder forward, from @soroush.tech/design-system 2.x or from an earlier
1147
+ Gild UI version to the latest the command line knows: it finds the version the app is on, picks
1148
+ the migration steps from there to the target, and shows every change of every step first - the
1149
+ dependencies, the file edits, and what only you can decide, with its file and line. It writes
1150
+ nothing until you say yes, then applies the steps in order and installs once.
1151
+
1152
+ It runs no git: committing the result is yours. Run it again after: an app that is on the latest
1153
+ version has nothing to change.
1154
+
1155
+ Exit codes: 0 applied, nothing left for you; 2 applied, items left for you; 3 nothing to
1156
+ migrate; 1 refused, or failed and was taken back (or a wrong command line). With --dry-run: 0
1157
+ when there is something to do, 3 when there is not.
1158
+
1159
+ Options:
1160
+ -y, --yes apply without asking
1161
+ --dry-run show the changes and exit
1162
+ --to <version> stop at this version instead of the latest
1163
+ --json print the run as one JSON object on stdout, and nothing else there;
1164
+ it never asks, so without --yes it is a preview
1165
+ -h, --help show this help
1166
+
1167
+ Example:
1168
+ ${BIN} migrate --dry-run
1959
1169
  `,
1960
1170
  create: `Usage: ${BIN} create [name] [options]
1961
1171
 
1962
- Starts a new app on the design system in ./<name>, my-app when it is not given: a new folder, or
1172
+ Starts a new app on Gild UI in ./<name>, my-app when it is not given: a new folder, or
1963
1173
  an empty one. Its package.json takes the name in lowercase: testApp is test-app. It asks for what
1964
1174
  the options do not say, shows every file first, and writes nothing until you say yes.
1965
1175
 
@@ -1978,7 +1188,7 @@ Options:
1978
1188
  --with <names> the libraries to add, by comma: ${LIBRARY_NAMES.join(", ")}
1979
1189
  --scheme <name> the default color scheme: light (the default) or dark
1980
1190
  --sample-data add a list of sample items, and a page for each
1981
- --no-git do not run git init
1191
+ --no-git no effect: create runs no git (kept for older scripts)
1982
1192
  -h, --help show this help
1983
1193
 
1984
1194
  Examples:
@@ -2000,6 +1210,8 @@ const OPTIONS = {
2000
1210
  short: "h"
2001
1211
  },
2002
1212
  force: { type: "boolean" },
1213
+ to: { type: "string" },
1214
+ json: { type: "boolean" },
2003
1215
  framework: { type: "string" },
2004
1216
  title: { type: "string" },
2005
1217
  ts: { type: "boolean" },
@@ -2014,6 +1226,7 @@ const OPTIONS = {
2014
1226
  /** The options only one command takes. */
2015
1227
  const OWN_OPTIONS = {
2016
1228
  init: ["force"],
1229
+ migrate: ["to", "json"],
2017
1230
  create: [
2018
1231
  "framework",
2019
1232
  "title",
@@ -2034,6 +1247,7 @@ function findMisuse(command, extra, used) {
2034
1247
  const option = used.find((name) => options.includes(name));
2035
1248
  if (option) return `--${option} is an option of ${other}, not of ${command}.`;
2036
1249
  }
1250
+ if (command === "migrate" && used.includes("scheme")) return "--scheme is an option of init and create, not of migrate.";
2037
1251
  const maxPositionals = command === "create" ? 1 : 0;
2038
1252
  return extra.length > maxPositionals ? `Unknown command: ${command} ${extra.join(" ")}` : void 0;
2039
1253
  }
@@ -2051,8 +1265,9 @@ function findValueRefusal({ scheme, ts, js, render, layout, pm }, libraries) {
2051
1265
  }
2052
1266
  /**
2053
1267
  * Reads the command line and runs the command, for `designSystem`: the package of
2054
- * `@soroush.tech/design-system` the command installs. Returns the exit code: 130 when the person
2055
- * stops it at a question, which is before anything is written.
1268
+ * `@gild-ui/react`, whose peer range for React `init` checks the app against.
1269
+ * Returns the exit code: 130 when the person stops it at a question, which is before anything is
1270
+ * written.
2056
1271
  */
2057
1272
  async function main(argv, io, designSystem) {
2058
1273
  try {
@@ -2115,15 +1330,22 @@ async function runCommandLine(argv, io, designSystem) {
2115
1330
  libraries,
2116
1331
  scheme,
2117
1332
  hasSampleData: values["sample-data"],
1333
+ isConfirmed,
1334
+ isDryRun
1335
+ }, io);
1336
+ }
1337
+ if (command === "migrate") {
1338
+ const { runMigrate } = await import("./migrate-Bhkz8pnP.mjs");
1339
+ return runMigrate({
2118
1340
  isConfirmed,
2119
1341
  isDryRun,
2120
- isGit: !values["no-git"]
2121
- }, io, designSystem);
1342
+ isJson: Boolean(values.json),
1343
+ to: values.to
1344
+ }, io);
2122
1345
  }
2123
1346
  return runInit({
2124
1347
  isConfirmed,
2125
1348
  isDryRun,
2126
- isForced: Boolean(values.force),
2127
1349
  scheme
2128
1350
  }, io, designSystem);
2129
1351
  }
@@ -2233,4 +1455,4 @@ function createNodeIo({ stdin = process.stdin, stdout = process.stdout, platform
2233
1455
  }
2234
1456
  };
2235
1457
  }
2236
- export { main as n, readDesignSystemPackage as r, createNodeIo as t };
1458
+ export { main as n, createNodeIo as t };