@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.
- package/README.md +6 -4
- package/dist/bin.mjs +2 -9
- package/dist/index.d.mts +19 -27
- package/dist/index.mjs +1 -1
- package/dist/init-C32LggZ7.mjs +1279 -0
- package/dist/{io-BFbf4S_u.mjs → io-BevxSPoR.mjs} +105 -883
- package/dist/migrate-Bhkz8pnP.mjs +22239 -0
- package/package.json +23 -22
- package/templates/astro/js/base/README.md +4 -3
- package/templates/astro/js/base/astro.config.mjs +16 -1
- package/templates/astro/js/base/src/components/About.jsx +2 -2
- package/templates/astro/js/base/src/components/Counter.jsx +3 -3
- package/templates/astro/js/base/src/components/Greeting.jsx +1 -1
- package/templates/astro/js/base/src/components/Header.jsx +6 -6
- package/templates/astro/js/base/src/components/Home.jsx +6 -6
- package/templates/astro/js/base/src/components/Home.test.jsx +5 -1
- package/templates/astro/js/base/src/components/NotFound.jsx +3 -3
- package/templates/astro/js/base/src/components/SchemeSwitch.jsx +4 -4
- package/templates/astro/js/base/src/theme/Island.jsx +1 -1
- package/templates/astro/js/sample-data/src/components/ItemDetails.jsx +3 -3
- package/templates/astro/js/sample-data/src/components/ItemList.jsx +3 -3
- package/templates/astro/js/sample-data/src/components/StatusChip.jsx +1 -1
- package/templates/astro/js/with/jotai/src/components/Counter.jsx +3 -3
- package/templates/astro/js/with/react-hook-form/src/components/Form.jsx +4 -4
- package/templates/astro/js/with/redux-toolkit/src/components/Counter.jsx +3 -3
- package/templates/astro/js/with/zustand/src/components/Counter.jsx +3 -3
- package/templates/astro/ts/base/README.md +4 -3
- package/templates/astro/ts/base/astro.config.mjs +16 -1
- package/templates/astro/ts/base/src/components/About.tsx +2 -2
- package/templates/astro/ts/base/src/components/Counter.tsx +3 -3
- package/templates/astro/ts/base/src/components/Greeting.tsx +1 -1
- package/templates/astro/ts/base/src/components/Header.tsx +6 -6
- package/templates/astro/ts/base/src/components/Home.test.tsx +5 -1
- package/templates/astro/ts/base/src/components/Home.tsx +6 -6
- package/templates/astro/ts/base/src/components/NotFound.tsx +3 -3
- package/templates/astro/ts/base/src/components/SchemeSwitch.tsx +4 -4
- package/templates/astro/ts/base/src/theme/Island.tsx +1 -1
- package/templates/astro/ts/sample-data/src/components/ItemDetails.tsx +3 -3
- package/templates/astro/ts/sample-data/src/components/ItemList.tsx +3 -3
- package/templates/astro/ts/sample-data/src/components/StatusChip.tsx +1 -1
- package/templates/astro/ts/with/jotai/src/components/Counter.tsx +3 -3
- package/templates/astro/ts/with/react-hook-form/src/components/Form.tsx +4 -4
- package/templates/astro/ts/with/redux-toolkit/src/components/Counter.tsx +3 -3
- package/templates/astro/ts/with/zustand/src/components/Counter.tsx +3 -3
- package/templates/react-router/js/base/README.md +4 -3
- package/templates/react-router/js/base/src/components/Header.jsx +5 -5
- package/templates/react-router/js/base/src/components/RouterLink.jsx +2 -2
- package/templates/react-router/js/base/src/components/SchemeSwitch.jsx +4 -4
- package/templates/react-router/js/base/src/main.jsx +5 -0
- package/templates/react-router/js/base/src/pages/ErrorPage.jsx +2 -2
- package/templates/react-router/js/base/src/pages/Layout.jsx +1 -1
- package/templates/react-router/js/base/src/pages/about/Page.jsx +2 -2
- package/templates/react-router/js/base/src/pages/index/Counter.jsx +3 -3
- package/templates/react-router/js/base/src/pages/index/Greeting.jsx +1 -1
- package/templates/react-router/js/base/src/pages/index/Page.jsx +6 -6
- package/templates/react-router/js/base/src/pages/index/Page.test.jsx +5 -1
- package/templates/react-router/js/sample-data/src/pages/item/Page.jsx +2 -2
- package/templates/react-router/js/sample-data/src/pages/items/Page.jsx +2 -2
- package/templates/react-router/js/sample-data/src/pages/items/StatusChip.jsx +1 -1
- package/templates/react-router/js/with/jotai/src/pages/index/Counter.jsx +3 -3
- package/templates/react-router/js/with/react-hook-form/src/pages/form/Page.jsx +4 -4
- package/templates/react-router/js/with/redux-toolkit/src/pages/index/Counter.jsx +3 -3
- package/templates/react-router/js/with/zustand/src/pages/index/Counter.jsx +3 -3
- package/templates/react-router/ts/base/README.md +4 -3
- package/templates/react-router/ts/base/src/components/Header.tsx +5 -5
- package/templates/react-router/ts/base/src/components/RouterLink.tsx +2 -2
- package/templates/react-router/ts/base/src/components/SchemeSwitch.tsx +4 -4
- package/templates/react-router/ts/base/src/main.tsx +5 -0
- package/templates/react-router/ts/base/src/pages/ErrorPage.tsx +2 -2
- package/templates/react-router/ts/base/src/pages/Layout.tsx +1 -1
- package/templates/react-router/ts/base/src/pages/about/Page.tsx +2 -2
- package/templates/react-router/ts/base/src/pages/index/Counter.tsx +3 -3
- package/templates/react-router/ts/base/src/pages/index/Greeting.tsx +1 -1
- package/templates/react-router/ts/base/src/pages/index/Page.test.tsx +5 -1
- package/templates/react-router/ts/base/src/pages/index/Page.tsx +6 -6
- package/templates/react-router/ts/sample-data/src/pages/item/Page.tsx +2 -2
- package/templates/react-router/ts/sample-data/src/pages/items/Page.tsx +2 -2
- package/templates/react-router/ts/sample-data/src/pages/items/StatusChip.tsx +1 -1
- package/templates/react-router/ts/with/jotai/src/pages/index/Counter.tsx +3 -3
- package/templates/react-router/ts/with/react-hook-form/src/pages/form/Page.tsx +4 -4
- package/templates/react-router/ts/with/redux-toolkit/src/pages/index/Counter.tsx +3 -3
- package/templates/react-router/ts/with/zustand/src/pages/index/Counter.tsx +3 -3
- package/templates/vike/js/base/README.md +3 -2
- package/templates/vike/js/base/src/components/Header.jsx +6 -6
- package/templates/vike/js/base/src/components/SchemeSwitch.jsx +4 -4
- package/templates/vike/js/base/src/pages/+Layout.jsx +1 -1
- package/templates/vike/js/base/src/pages/+onCreateGlobalContext.js +7 -0
- package/templates/vike/js/base/src/pages/+onRenderHtml.jsx +2 -3
- package/templates/vike/js/base/src/pages/PageShell.jsx +2 -2
- package/templates/vike/js/base/src/pages/_error/+Page.jsx +3 -3
- package/templates/vike/js/base/src/pages/about/+Page.jsx +2 -2
- package/templates/vike/js/base/src/pages/index/+Page.jsx +6 -6
- package/templates/vike/js/base/src/pages/index/Counter.jsx +3 -3
- package/templates/vike/js/base/src/pages/index/Greeting.jsx +1 -1
- package/templates/vike/js/base/src/pages/index/Page.test.jsx +5 -1
- package/templates/vike/js/sample-data/src/pages/items/+Page.jsx +3 -3
- package/templates/vike/js/sample-data/src/pages/items/@id/+Page.jsx +3 -3
- package/templates/vike/js/sample-data/src/pages/items/StatusChip.jsx +1 -1
- package/templates/vike/js/ssg/src/pages/about/+Page.jsx +2 -2
- package/templates/vike/js/ssr/src/pages/+onRenderHtml.jsx +2 -3
- package/templates/vike/js/ssr/src/pages/about/+Page.jsx +2 -2
- package/templates/vike/js/with/jotai/src/pages/index/Counter.jsx +3 -3
- package/templates/vike/js/with/react-hook-form/src/pages/form/+Page.jsx +4 -4
- package/templates/vike/js/with/redux-toolkit/src/pages/index/Counter.jsx +3 -3
- package/templates/vike/js/with/zustand/src/pages/index/Counter.jsx +3 -3
- package/templates/vike/ts/base/README.md +3 -2
- package/templates/vike/ts/base/src/components/Header.tsx +6 -6
- package/templates/vike/ts/base/src/components/SchemeSwitch.tsx +4 -4
- package/templates/vike/ts/base/src/pages/+Layout.tsx +1 -1
- package/templates/vike/ts/base/src/pages/+onCreateGlobalContext.ts +7 -0
- package/templates/vike/ts/base/src/pages/+onRenderHtml.tsx +2 -3
- package/templates/vike/ts/base/src/pages/PageShell.tsx +2 -2
- package/templates/vike/ts/base/src/pages/_error/+Page.tsx +3 -3
- package/templates/vike/ts/base/src/pages/about/+Page.tsx +2 -2
- package/templates/vike/ts/base/src/pages/index/+Page.tsx +6 -6
- package/templates/vike/ts/base/src/pages/index/Counter.tsx +3 -3
- package/templates/vike/ts/base/src/pages/index/Greeting.tsx +1 -1
- package/templates/vike/ts/base/src/pages/index/Page.test.tsx +5 -1
- package/templates/vike/ts/sample-data/src/pages/items/+Page.tsx +3 -3
- package/templates/vike/ts/sample-data/src/pages/items/@id/+Page.tsx +3 -3
- package/templates/vike/ts/sample-data/src/pages/items/StatusChip.tsx +1 -1
- package/templates/vike/ts/ssg/src/pages/about/+Page.tsx +2 -2
- package/templates/vike/ts/ssr/src/pages/+onRenderHtml.tsx +2 -3
- package/templates/vike/ts/ssr/src/pages/about/+Page.tsx +2 -2
- package/templates/vike/ts/with/jotai/src/pages/index/Counter.tsx +3 -3
- package/templates/vike/ts/with/react-hook-form/src/pages/form/+Page.tsx +4 -4
- package/templates/vike/ts/with/redux-toolkit/src/pages/index/Counter.tsx +3 -3
- package/templates/vike/ts/with/zustand/src/pages/index/Counter.tsx +3 -3
|
@@ -0,0 +1,1279 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
3
|
+
// ../react/package.json
|
|
4
|
+
var name = "@gild-ui/react";
|
|
5
|
+
var version = "0.1.0-alpha.2";
|
|
6
|
+
var peerDependencies = {
|
|
7
|
+
"next": "^16.3.3",
|
|
8
|
+
"react": "^19.2.8",
|
|
9
|
+
"react-dom": "^19.2.8"
|
|
10
|
+
};
|
|
11
|
+
// src/designSystemPackage.ts
|
|
12
|
+
/**
|
|
13
|
+
* The npm name of the React package: what `init` and `create` install, and an app imports from. They
|
|
14
|
+
* check an app's React against the range it declares.
|
|
15
|
+
*/
|
|
16
|
+
const APP_PACKAGE = "@gild-ui/react";
|
|
17
|
+
/**
|
|
18
|
+
* The package an app takes its theme from (`createTheme`, `baseTheme`): the React package depends on
|
|
19
|
+
* it, and an app that imports it names it in its own dependencies, at the same version.
|
|
20
|
+
*/
|
|
21
|
+
const CORE_PACKAGE = "@gild-ui/core";
|
|
22
|
+
/**
|
|
23
|
+
* The version of the React package the app gets. It is read from the workspace when this package is
|
|
24
|
+
* built, so only this field ships; the version is a released one, so even an alpha cli installs the
|
|
25
|
+
* stable package.
|
|
26
|
+
*/
|
|
27
|
+
const APP_PACKAGE_VERSION = version;
|
|
28
|
+
// src/apply/fileSystem.ts
|
|
29
|
+
const nodeFileSystem = {
|
|
30
|
+
readFile: (path) => readFileSync(path, "utf8"),
|
|
31
|
+
createFile: (path, content) => writeFileSync(path, content, { flag: "wx" }),
|
|
32
|
+
writeFile: (path, content) => writeFileSync(path, content),
|
|
33
|
+
removeFile: (path) => rmSync(path),
|
|
34
|
+
createDirectory: (path) => mkdirSync(path),
|
|
35
|
+
removeDirectory: (path) => rmdirSync(path),
|
|
36
|
+
removeTree: (path) => rmSync(path, {
|
|
37
|
+
recursive: true,
|
|
38
|
+
force: true
|
|
39
|
+
}),
|
|
40
|
+
isSymbolicLink: (path) => {
|
|
41
|
+
try {
|
|
42
|
+
return lstatSync(path).isSymbolicLink();
|
|
43
|
+
} catch {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The absolute path of `path`, given from the app's root, when it stays inside the root and
|
|
50
|
+
* passes through no symbolic link. Anything else throws: init writes only inside the app.
|
|
51
|
+
*/
|
|
52
|
+
function resolveInside(root, path, fileSystem) {
|
|
53
|
+
const absolute = resolve(root, path);
|
|
54
|
+
const fromRoot = relative(root, absolute);
|
|
55
|
+
if (!fromRoot || fromRoot.startsWith("..") || isAbsolute(fromRoot)) throw new Error(`${path} is outside the app's folder`);
|
|
56
|
+
let current = root;
|
|
57
|
+
for (const segment of fromRoot.split(sep)) {
|
|
58
|
+
current = join(current, segment);
|
|
59
|
+
const isLink = fileSystem.isSymbolicLink(current);
|
|
60
|
+
if (isLink === void 0) break;
|
|
61
|
+
if (isLink) throw new Error(`${path} goes through a symbolic link, which init does not follow`);
|
|
62
|
+
}
|
|
63
|
+
return absolute;
|
|
64
|
+
}
|
|
65
|
+
/** The folders between the root and `directory` that do not exist yet, outermost first. */
|
|
66
|
+
function findMissingDirectories(root, directory, fileSystem) {
|
|
67
|
+
const missing = [];
|
|
68
|
+
let current = directory;
|
|
69
|
+
while (current !== root && fileSystem.isSymbolicLink(current) === void 0) {
|
|
70
|
+
missing.unshift(current);
|
|
71
|
+
current = dirname(current);
|
|
72
|
+
}
|
|
73
|
+
return missing;
|
|
74
|
+
}
|
|
75
|
+
// src/apply/applyPlan.ts
|
|
76
|
+
/** A write failed. `isUndone` says whether every change made before it was taken back. */
|
|
77
|
+
var ApplyError = class extends Error {
|
|
78
|
+
isUndone;
|
|
79
|
+
/** The place, among the plans, of the one whose write failed. */
|
|
80
|
+
planIndex;
|
|
81
|
+
constructor(message, isUndone, planIndex = 0) {
|
|
82
|
+
super(message);
|
|
83
|
+
this.name = "ApplyError";
|
|
84
|
+
this.isUndone = isUndone;
|
|
85
|
+
this.planIndex = planIndex;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Writes the plan's files and edits. Each change keeps a step that takes it back, in memory: when
|
|
90
|
+
* one write fails, the steps run in reverse, so the app is left as it was. Each edit is checked
|
|
91
|
+
* against the file before it is written and read back after.
|
|
92
|
+
*/
|
|
93
|
+
function applyPlan(plan, root, fileSystem = nodeFileSystem) {
|
|
94
|
+
applyPlans([plan], root, fileSystem);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Writes several plans one after another, each on what the one before wrote. They share one undo
|
|
98
|
+
* list: when a write fails in any of them, every change of every plan is taken back. `command`
|
|
99
|
+
* names the command in the errors.
|
|
100
|
+
*/
|
|
101
|
+
function applyPlans(plans, root, fileSystem = nodeFileSystem, command = "init") {
|
|
102
|
+
const undoSteps = [];
|
|
103
|
+
let planIndex = 0;
|
|
104
|
+
try {
|
|
105
|
+
for (const plan of plans) {
|
|
106
|
+
writePlan(plan, root, fileSystem, undoSteps, command);
|
|
107
|
+
planIndex += 1;
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {
|
|
110
|
+
let isUndone = true;
|
|
111
|
+
for (const undo of undoSteps.reverse()) try {
|
|
112
|
+
undo();
|
|
113
|
+
} catch {
|
|
114
|
+
isUndone = false;
|
|
115
|
+
}
|
|
116
|
+
throw new ApplyError(error.message, isUndone, planIndex);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function writePlan(plan, root, fileSystem, undoSteps, command) {
|
|
120
|
+
for (const file of plan.creates) {
|
|
121
|
+
const absolute = resolveInside(root, file.path, fileSystem);
|
|
122
|
+
for (const directory of findMissingDirectories(root, dirname(absolute), fileSystem)) {
|
|
123
|
+
fileSystem.createDirectory(directory);
|
|
124
|
+
undoSteps.push(() => fileSystem.removeDirectory(directory));
|
|
125
|
+
}
|
|
126
|
+
fileSystem.createFile(absolute, file.content);
|
|
127
|
+
undoSteps.push(() => fileSystem.removeFile(absolute));
|
|
128
|
+
}
|
|
129
|
+
for (const edit of plan.edits) {
|
|
130
|
+
const absolute = resolveInside(root, edit.path, fileSystem);
|
|
131
|
+
if (fileSystem.readFile(absolute) !== edit.before) throw new Error(`${edit.path} changed while ${command} was running`);
|
|
132
|
+
undoSteps.push(() => fileSystem.writeFile(absolute, edit.before));
|
|
133
|
+
fileSystem.writeFile(absolute, edit.after);
|
|
134
|
+
if (fileSystem.readFile(absolute) !== edit.after) throw new Error(`${edit.path} did not read back as ${command} wrote it`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// src/closing.ts
|
|
138
|
+
const SETUP_DOCS$1 = "https://gild-ui.soroush.design/react/installation/";
|
|
139
|
+
const FONTS_STEP = ` - Fonts: the theme names Space Grotesk and JetBrains Mono, and does not load them. To add them,
|
|
140
|
+
see ${SETUP_DOCS$1}#fonts`;
|
|
141
|
+
const AGENT_STEPS = `For a coding agent, if you use one (any agent):
|
|
142
|
+
- The house-style skill: npx skills add soroush-tech/design-system
|
|
143
|
+
- The MCP server, for any MCP client: https://mcp.soroush.design/mcp
|
|
144
|
+
`;
|
|
145
|
+
// src/compareText.ts
|
|
146
|
+
/** Orders two strings by their UTF-16 code units, as `sort()` does without a compare function. */
|
|
147
|
+
const compareText = (a, b) => Number(a > b) - Number(a < b);
|
|
148
|
+
// src/plan/rootEdit.ts
|
|
149
|
+
const RENDER_CALL = /\.render\s*\(/g;
|
|
150
|
+
const CLOSERS = {
|
|
151
|
+
")": "(",
|
|
152
|
+
"]": "[",
|
|
153
|
+
"}": "{"
|
|
154
|
+
};
|
|
155
|
+
/** Whether a source starts a client-rendered React app: `createRoot(...).render(` or `ReactDOM.render(`. */
|
|
156
|
+
function isRootSource(source) {
|
|
157
|
+
return /\bcreateRoot\s*\(/.test(source) && /\.render\s*\(/.test(source) || /\bReactDOM\.render\s*\(/.test(source);
|
|
158
|
+
}
|
|
159
|
+
/** Skips a string or a comment starting at `index`, returning the index after it, or `index` if none starts there. */
|
|
160
|
+
function skipStringOrComment(source, index) {
|
|
161
|
+
const char = source[index];
|
|
162
|
+
if (char === "\"" || char === "'" || char === "`") {
|
|
163
|
+
let cursor = index + 1;
|
|
164
|
+
while (cursor < source.length && source[cursor] !== char) cursor += source[cursor] === "\\" ? 2 : 1;
|
|
165
|
+
return cursor + 1;
|
|
166
|
+
}
|
|
167
|
+
if (source.startsWith("//", index)) {
|
|
168
|
+
const end = source.indexOf("\n", index);
|
|
169
|
+
return end === -1 ? source.length : end;
|
|
170
|
+
}
|
|
171
|
+
if (source.startsWith("/*", index)) {
|
|
172
|
+
const end = source.indexOf("*/", index + 2);
|
|
173
|
+
return end === -1 ? source.length : end + 2;
|
|
174
|
+
}
|
|
175
|
+
return index;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The span of the first argument of the call whose `(` ends just before `from`: up to the first
|
|
179
|
+
* comma or the closing parenthesis at its own depth. `null` when the call never closes.
|
|
180
|
+
*/
|
|
181
|
+
function readFirstArgument(source, from) {
|
|
182
|
+
const stack = [];
|
|
183
|
+
let cursor = from;
|
|
184
|
+
while (cursor < source.length) {
|
|
185
|
+
const skipped = skipStringOrComment(source, cursor);
|
|
186
|
+
if (skipped !== cursor) {
|
|
187
|
+
cursor = skipped;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const char = source[cursor];
|
|
191
|
+
if (char === "(" || char === "[" || char === "{") stack.push(char);
|
|
192
|
+
else if (char in CLOSERS) {
|
|
193
|
+
if (stack.length === 0) return trimSpan(source, from, cursor);
|
|
194
|
+
if (stack.pop() !== CLOSERS[char]) return null;
|
|
195
|
+
} else if (char === "," && stack.length === 0) return trimSpan(source, from, cursor);
|
|
196
|
+
cursor += 1;
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
function trimSpan(source, start, end) {
|
|
201
|
+
let from = start;
|
|
202
|
+
let to = end;
|
|
203
|
+
while (from < to && /\s/.test(source[from])) from += 1;
|
|
204
|
+
while (to > from && /\s/.test(source[to - 1])) to -= 1;
|
|
205
|
+
return {
|
|
206
|
+
start: from,
|
|
207
|
+
end: to
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** The indentation of the line `index` sits on. */
|
|
211
|
+
function indentationAt(source, index) {
|
|
212
|
+
const line = source.slice(source.lastIndexOf("\n", index - 1) + 1, index);
|
|
213
|
+
return line.slice(0, line.length - line.trimStart().length);
|
|
214
|
+
}
|
|
215
|
+
/** Wraps a JSX child in `<Providers>`, keeping a multi-line tree on its own lines, one step deeper. */
|
|
216
|
+
function wrapTree(tree, indentation) {
|
|
217
|
+
if (!tree.includes("\n")) return `<Providers>${tree}</Providers>`;
|
|
218
|
+
const step = indentation.includes(" ") ? " " : " ";
|
|
219
|
+
return `<Providers>\n${indentation}${step}${tree.replaceAll("\n", `\n${step}`)}\n${indentation}</Providers>`;
|
|
220
|
+
}
|
|
221
|
+
const IMPORT_DECLARATION = /^import(?=[\s{*'"])[\s\S]*?(['"])[^'"\n]*\1[^\S\n]*(;?)/gm;
|
|
222
|
+
/**
|
|
223
|
+
* Adds an import after the last import declaration, in the file's own quote and semicolon style:
|
|
224
|
+
* `statement` is written with single quotes and no semicolon.
|
|
225
|
+
*/
|
|
226
|
+
function insertImport(source, statement) {
|
|
227
|
+
const last = [...source.matchAll(IMPORT_DECLARATION)].at(-1);
|
|
228
|
+
if (!last) return `${statement}\n${source}`;
|
|
229
|
+
const [text, quote, semicolon] = last;
|
|
230
|
+
const styled = (quote === "\"" ? statement.replaceAll("'", "\"") : statement) + semicolon;
|
|
231
|
+
const end = last.index + text.length;
|
|
232
|
+
return `${source.slice(0, end)}\n${styled}${source.slice(end)}`;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The root with what it renders wrapped in `<Providers>` and the import added, or `null` when it
|
|
236
|
+
* is not the standard shape: one render call. A JSX tree is wrapped as it is; any other argument -
|
|
237
|
+
* a call, a variable - is wrapped as `<Providers>{...}</Providers>`, but only in a file that may
|
|
238
|
+
* hold JSX (`canHoldJsx`, a `.jsx` or `.tsx` file).
|
|
239
|
+
*/
|
|
240
|
+
function wrapRoot(source, importStatement, canHoldJsx) {
|
|
241
|
+
const calls = [...source.matchAll(RENDER_CALL)];
|
|
242
|
+
if (calls.length !== 1) return null;
|
|
243
|
+
const call = calls[0];
|
|
244
|
+
const argument = readFirstArgument(source, call.index + call[0].length);
|
|
245
|
+
if (!argument) return null;
|
|
246
|
+
const rendered = source.slice(argument.start, argument.end);
|
|
247
|
+
const isTree = rendered.startsWith("<") && rendered.endsWith(">");
|
|
248
|
+
if (!isTree && (!canHoldJsx || rendered === "")) return null;
|
|
249
|
+
const wrapped = wrapTree(isTree ? rendered : `{${rendered}}`, indentationAt(source, argument.start));
|
|
250
|
+
return insertImport(source.slice(0, argument.start) + wrapped + source.slice(argument.end), importStatement);
|
|
251
|
+
}
|
|
252
|
+
// src/detect/detect.ts
|
|
253
|
+
/** A file's text, or `undefined` when it cannot be read. */
|
|
254
|
+
function readText(path) {
|
|
255
|
+
try {
|
|
256
|
+
return readFileSync(path, "utf8");
|
|
257
|
+
} catch {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function readPackageJson(directory) {
|
|
262
|
+
const text = readText(join(directory, "package.json"));
|
|
263
|
+
return text === void 0 ? void 0 : JSON.parse(text);
|
|
264
|
+
}
|
|
265
|
+
/** A dependency's declared range, from `dependencies` or `devDependencies`. */
|
|
266
|
+
function getDependency(packageJson, name) {
|
|
267
|
+
return packageJson.dependencies?.[name] ?? packageJson.devDependencies?.[name];
|
|
268
|
+
}
|
|
269
|
+
const LOCKFILES = [
|
|
270
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
271
|
+
["yarn.lock", "yarn"],
|
|
272
|
+
["bun.lock", "bun"],
|
|
273
|
+
["bun.lockb", "bun"],
|
|
274
|
+
["package-lock.json", "npm"],
|
|
275
|
+
["npm-shrinkwrap.json", "npm"]
|
|
276
|
+
];
|
|
277
|
+
/**
|
|
278
|
+
* The app's package manager: its `packageManager` field, else the lockfile in its folder or the
|
|
279
|
+
* nearest one above it inside the same repository (a workspace keeps one at its root), else npm.
|
|
280
|
+
*/
|
|
281
|
+
function detectPackageManager(root, packageJson, fileExists = existsSync) {
|
|
282
|
+
const declared = /^(npm|pnpm|yarn|bun)@(\d+)/.exec(packageJson.packageManager ?? "");
|
|
283
|
+
if (declared) {
|
|
284
|
+
const name = declared[1];
|
|
285
|
+
return {
|
|
286
|
+
name,
|
|
287
|
+
isYarnBerry: name === "yarn" && Number(declared[2]) >= 2
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
for (let directory = root;; directory = dirname(directory)) {
|
|
291
|
+
const lockfile = LOCKFILES.find(([file]) => fileExists(join(directory, file)));
|
|
292
|
+
if (lockfile) {
|
|
293
|
+
const name = lockfile[1];
|
|
294
|
+
return {
|
|
295
|
+
name,
|
|
296
|
+
isYarnBerry: name === "yarn" && fileExists(join(directory, ".yarnrc.yml"))
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
if (fileExists(join(directory, ".git")) || dirname(directory) === directory) return {
|
|
300
|
+
name: "npm",
|
|
301
|
+
isYarnBerry: false
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The version of `name` the app has installed - in its own node_modules or a workspace's above it.
|
|
307
|
+
* Only node_modules folders are searched: a global folder or NODE_PATH says nothing about the app.
|
|
308
|
+
*/
|
|
309
|
+
function findInstalledVersion(root, name) {
|
|
310
|
+
for (let directory = root;; directory = dirname(directory)) {
|
|
311
|
+
const installed = readPackageJson(join(directory, "node_modules", name));
|
|
312
|
+
if (installed) return installed.version;
|
|
313
|
+
if (dirname(directory) === directory) return void 0;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* The React version the app has installed, else the lowest its declared range allows.
|
|
318
|
+
*/
|
|
319
|
+
function findReactVersion(root, packageJson) {
|
|
320
|
+
const installed = findInstalledVersion(root, "react");
|
|
321
|
+
if (installed) return installed;
|
|
322
|
+
const match = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(getDependency(packageJson, "react") ?? "");
|
|
323
|
+
return match ? `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}` : void 0;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Whether `version` is in `range`. Only the shape Gild UI's peer ranges use is read:
|
|
327
|
+
* caret ranges joined by `||`, such as `^18.0.0 || ^19.0.0`. Any other shape throws.
|
|
328
|
+
*/
|
|
329
|
+
function satisfiesRange(version, range) {
|
|
330
|
+
const [major, minor, patch] = version.split(/[.-]/).map(Number);
|
|
331
|
+
return range.split("||").some((part) => {
|
|
332
|
+
const match = /^\s*\^(\d+)\.(\d+)\.(\d+)\s*$/.exec(part);
|
|
333
|
+
if (!match) throw new Error(`init cannot read the range ${range}`);
|
|
334
|
+
const [low, lowMinor, lowPatch] = match.slice(1).map(Number);
|
|
335
|
+
return major === low && (minor > lowMinor || minor === lowMinor && patch >= lowPatch);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([
|
|
339
|
+
"node_modules",
|
|
340
|
+
"dist",
|
|
341
|
+
"build",
|
|
342
|
+
"out",
|
|
343
|
+
"coverage",
|
|
344
|
+
"public"
|
|
345
|
+
]);
|
|
346
|
+
const MAX_DEPTH = 5;
|
|
347
|
+
/** The hidden folders that hold the app's own source: its Storybook configuration imports the design system too. */
|
|
348
|
+
const SOURCE_HIDDEN_FOLDERS = /* @__PURE__ */ new Set([".storybook"]);
|
|
349
|
+
/**
|
|
350
|
+
* Every file under the app's folder that starts a client-rendered app, by its path from the root.
|
|
351
|
+
* Tests, stories, folders that hold output or dependencies, hidden folders and symbolic links are
|
|
352
|
+
* not read.
|
|
353
|
+
*/
|
|
354
|
+
function findRootFiles(root, folder = "", depth = 0) {
|
|
355
|
+
const found = [];
|
|
356
|
+
for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
|
|
357
|
+
const path = posix.join(folder, entry.name);
|
|
358
|
+
if (entry.name.startsWith(".")) continue;
|
|
359
|
+
if (entry.isDirectory() && !SKIPPED_FOLDERS.has(entry.name) && depth < MAX_DEPTH) found.push(...findRootFiles(root, path, depth + 1));
|
|
360
|
+
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);
|
|
361
|
+
}
|
|
362
|
+
return found;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Every file under the app's folder, by its path from the root, sorted. Hidden folders (but
|
|
366
|
+
* `.storybook`, which holds source), the ones that hold output or dependencies, and symbolic
|
|
367
|
+
* links are not listed.
|
|
368
|
+
*/
|
|
369
|
+
function listAppFiles(root, folder = "", depth = 0) {
|
|
370
|
+
const found = [];
|
|
371
|
+
for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) {
|
|
372
|
+
const path = posix.join(folder, entry.name);
|
|
373
|
+
if (entry.name.startsWith(".") && !SOURCE_HIDDEN_FOLDERS.has(entry.name)) continue;
|
|
374
|
+
if (entry.isDirectory() && !SKIPPED_FOLDERS.has(entry.name) && depth < MAX_DEPTH) found.push(...listAppFiles(root, path, depth + 1));
|
|
375
|
+
else if (entry.isFile()) found.push(path);
|
|
376
|
+
}
|
|
377
|
+
return found.sort(compareText);
|
|
378
|
+
}
|
|
379
|
+
/** Whether the folder is a workspace's root: pnpm's `pnpm-workspace.yaml`, or a `workspaces` field. */
|
|
380
|
+
function isWorkspaceRoot(root, packageJson) {
|
|
381
|
+
return packageJson.workspaces !== void 0 || existsSync(join(root, "pnpm-workspace.yaml"));
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The folder of the package a file belongs to: the nearest one above it, inside `root`, with a
|
|
385
|
+
* `package.json`, by its path from the root - `''` for the root itself.
|
|
386
|
+
*/
|
|
387
|
+
function findPackageFolder(root, path) {
|
|
388
|
+
for (let folder = posix.dirname(path); folder !== "."; folder = posix.dirname(folder)) if (existsSync(join(root, folder, "package.json"))) return folder;
|
|
389
|
+
return "";
|
|
390
|
+
}
|
|
391
|
+
const UNSUPPORTED_FRAMEWORKS = [
|
|
392
|
+
["next", "Next.js"],
|
|
393
|
+
["vike", "Vike"],
|
|
394
|
+
["@react-router/dev", "React Router in framework mode"],
|
|
395
|
+
["@remix-run/react", "Remix"],
|
|
396
|
+
["gatsby", "Gatsby"],
|
|
397
|
+
["astro", "Astro"],
|
|
398
|
+
["expo", "Expo"],
|
|
399
|
+
["react-native", "React Native"]
|
|
400
|
+
];
|
|
401
|
+
/** The framework an app is built on that init does not set up yet, if any: its package and its name. */
|
|
402
|
+
function findFramework(packageJson) {
|
|
403
|
+
return UNSUPPORTED_FRAMEWORKS.find(([name]) => getDependency(packageJson, name));
|
|
404
|
+
}
|
|
405
|
+
/** The framework an app is built on that init does not set up yet, if any. */
|
|
406
|
+
function findUnsupportedFramework(packageJson) {
|
|
407
|
+
return findFramework(packageJson)?.[1];
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Whether the app builds with Parcel and has not turned on its reading of package exports, which
|
|
411
|
+
* every subpath of Gild UI (`/theme`, `/engine`, `/Button`, ...) needs.
|
|
412
|
+
*/
|
|
413
|
+
function needsParcelPackageExports(packageJson) {
|
|
414
|
+
return getDependency(packageJson, "parcel") !== void 0 && packageJson["@parcel/resolver-default"]?.packageExports !== true;
|
|
415
|
+
}
|
|
416
|
+
// src/plan/diff.ts
|
|
417
|
+
/**
|
|
418
|
+
* A line diff of two texts, as printed lines: `+ ` added, `- ` removed, and up to `context`
|
|
419
|
+
* unchanged lines around each change, with ` ...` where unchanged lines are left out. The files
|
|
420
|
+
* it compares are an app's root, a few dozen lines, so the plain longest-common-subsequence
|
|
421
|
+
* table is fast enough.
|
|
422
|
+
*/
|
|
423
|
+
function diffLines(before, after, context = 2) {
|
|
424
|
+
const oldLines = before.split("\n");
|
|
425
|
+
const newLines = after.split("\n");
|
|
426
|
+
const common = Array.from({ length: oldLines.length + 1 }, () => new Array(newLines.length + 1).fill(0));
|
|
427
|
+
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]);
|
|
428
|
+
const lines = [];
|
|
429
|
+
let i = 0;
|
|
430
|
+
let j = 0;
|
|
431
|
+
while (i < oldLines.length || j < newLines.length) if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
|
|
432
|
+
lines.push({
|
|
433
|
+
mark: " ",
|
|
434
|
+
text: oldLines[i]
|
|
435
|
+
});
|
|
436
|
+
i += 1;
|
|
437
|
+
j += 1;
|
|
438
|
+
} else if (i < oldLines.length && (j === newLines.length || common[i + 1][j] >= common[i][j + 1])) {
|
|
439
|
+
lines.push({
|
|
440
|
+
mark: "-",
|
|
441
|
+
text: oldLines[i]
|
|
442
|
+
});
|
|
443
|
+
i += 1;
|
|
444
|
+
} else {
|
|
445
|
+
lines.push({
|
|
446
|
+
mark: "+",
|
|
447
|
+
text: newLines[j]
|
|
448
|
+
});
|
|
449
|
+
j += 1;
|
|
450
|
+
}
|
|
451
|
+
const isNearChange = (index) => lines.slice(Math.max(0, index - context), index + context + 1).some((line) => line.mark !== " ");
|
|
452
|
+
const printed = [];
|
|
453
|
+
lines.forEach((line, index) => {
|
|
454
|
+
if (isNearChange(index)) printed.push(`${line.mark} ${line.text}`.trimEnd());
|
|
455
|
+
else if (printed.at(-1) !== " ...") printed.push(" ...");
|
|
456
|
+
});
|
|
457
|
+
return printed;
|
|
458
|
+
}
|
|
459
|
+
// src/plan/formatPlan.ts
|
|
460
|
+
/** The plan as the developer reads it before saying yes: every file, every edit and the install. */
|
|
461
|
+
function formatPlan(plan) {
|
|
462
|
+
const sections = [];
|
|
463
|
+
if (plan.creates.length > 0) sections.push(["Create:", ...plan.creates.map((file) => ` ${file.path}`)].join("\n"));
|
|
464
|
+
for (const edit of plan.edits) {
|
|
465
|
+
const diff = diffLines(edit.before, edit.after).map((line) => ` ${line}`.trimEnd());
|
|
466
|
+
sections.push([`Edit ${edit.path}:`, ...diff].join("\n"));
|
|
467
|
+
}
|
|
468
|
+
if (plan.install) {
|
|
469
|
+
const { command, args, env } = plan.install;
|
|
470
|
+
const prefix = Object.entries(env).map(([name, value]) => `${name}=${value} `);
|
|
471
|
+
sections.push(`Install:\n ${prefix.join("")}${[command, ...args].join(" ")}`);
|
|
472
|
+
}
|
|
473
|
+
if (plan.skips.length > 0) sections.push(["Skip:", ...plan.skips.map((skip) => ` ${skip.path}: ${skip.reason}`)].join("\n"));
|
|
474
|
+
if (plan.manual.length > 0) sections.push(["Left to you:", ...plan.manual.map((step) => ` - ${step}`)].join("\n"));
|
|
475
|
+
return `${sections.join("\n\n")}\n`;
|
|
476
|
+
}
|
|
477
|
+
// src/templates/templates.ts
|
|
478
|
+
/** The first line of every file init writes: a second run finds its own files by it. */
|
|
479
|
+
const MARKER = `// Set up by ${APP_PACKAGE} init.`;
|
|
480
|
+
const FORMER_MARKERS = ["// Set up by @soroush.design/react-components init.", "// Set up by @soroush.tech/design-system init."];
|
|
481
|
+
/** Whether a file starts with the line init writes, under the current name or a former one. */
|
|
482
|
+
function isSetUpByInit(content) {
|
|
483
|
+
return [MARKER, ...FORMER_MARKERS].some((marker) => content.startsWith(marker));
|
|
484
|
+
}
|
|
485
|
+
const THEMING_DOCS = "https://gild-ui.soroush.design/react/theme/";
|
|
486
|
+
const AUGMENTATION_STUB = `
|
|
487
|
+
// To add tokens of your own, declare them here, then give them values in each theme:
|
|
488
|
+
//
|
|
489
|
+
// import type { PaletteEntry } from '${CORE_PACKAGE}/theme'
|
|
490
|
+
//
|
|
491
|
+
// declare module '${CORE_PACKAGE}/theme' {
|
|
492
|
+
// interface ThemePalette {
|
|
493
|
+
// brand: PaletteEntry
|
|
494
|
+
// }
|
|
495
|
+
// }
|
|
496
|
+
`;
|
|
497
|
+
const REGISTRATION = `
|
|
498
|
+
declare module '${CORE_PACKAGE}/theme' {
|
|
499
|
+
interface Register {
|
|
500
|
+
themes: typeof themes
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
`;
|
|
504
|
+
/**
|
|
505
|
+
* The app's themes. The default export is what `defineThemes` returns: named themes, each a
|
|
506
|
+
* `createTheme` call with a literal object last, the shape tools that edit a theme read and write.
|
|
507
|
+
* `{}` is the components' customization, the same in every theme.
|
|
508
|
+
*/
|
|
509
|
+
function createThemesSource({ isTypeScript }) {
|
|
510
|
+
return `${MARKER} Your themes: change any value, or add a theme.
|
|
511
|
+
// Every token is listed at ${THEMING_DOCS}
|
|
512
|
+
import { baseTheme, createTheme, defineThemes } from '${CORE_PACKAGE}/theme'
|
|
513
|
+
${isTypeScript ? `import type { ThemeComponents } from '${APP_PACKAGE}'
|
|
514
|
+
` : ""}${isTypeScript ? AUGMENTATION_STUB : ""}
|
|
515
|
+
const themes = defineThemes(
|
|
516
|
+
{
|
|
517
|
+
light: createTheme(baseTheme, {
|
|
518
|
+
name: 'light',
|
|
519
|
+
colorScheme: 'light',
|
|
520
|
+
logoFilter: 'brightness(0)',
|
|
521
|
+
portraitBlend: 'multiply',
|
|
522
|
+
portraitOpacity: 1,
|
|
523
|
+
palette: {
|
|
524
|
+
default: { main: '#5E6065', light: '#8F9094', dark: '#111214', contrastText: '#FFFFFF' },
|
|
525
|
+
primary: { main: '#006E17', light: '#D4F9D2', dark: '#00530F', contrastText: '#FFFFFF' },
|
|
526
|
+
secondary: { main: '#5ACC57', light: '#D4F9D2', dark: '#3AAA37', contrastText: '#FFFFFF' },
|
|
527
|
+
success: { main: '#009928', light: '#E8FFE5', dark: '#006413', contrastText: '#FFFFFF' },
|
|
528
|
+
error: { main: '#BA1A1A', light: '#FFDAD6', dark: '#93000A', contrastText: '#FFFFFF' },
|
|
529
|
+
info: { main: '#0071A4', light: '#E0FAFF', dark: '#004D70', contrastText: '#FFFFFF' },
|
|
530
|
+
warning: { main: '#CCA800', light: '#FFF0A0', dark: '#8C6D00', contrastText: '#FFFFFF' },
|
|
531
|
+
},
|
|
532
|
+
background: {
|
|
533
|
+
backdrop: '#00000080',
|
|
534
|
+
appBar: '#FFFFFFD9',
|
|
535
|
+
glass: '#FFFFFF4D',
|
|
536
|
+
modal: '#FFFFFF',
|
|
537
|
+
default: '#EEEEEE',
|
|
538
|
+
primary: '#F9F9F9',
|
|
539
|
+
secondary: '#F3F3F3',
|
|
540
|
+
paper: '#FFFFFF',
|
|
541
|
+
terminal: '#EEEEEE',
|
|
542
|
+
grid: '#5ACC5733',
|
|
543
|
+
transparent: '#00000000',
|
|
544
|
+
scrollbar: '#0000004D',
|
|
545
|
+
scrollbarTrack: '#F3F3F380',
|
|
546
|
+
},
|
|
547
|
+
text: {
|
|
548
|
+
inherit: 'inherit',
|
|
549
|
+
initial: '#1A1C1C',
|
|
550
|
+
primary: '#006E17',
|
|
551
|
+
secondary: '#444748',
|
|
552
|
+
disabled: '#1A1C1C73',
|
|
553
|
+
error: '#BA1A1A',
|
|
554
|
+
success: '#009928',
|
|
555
|
+
info: '#0071A4',
|
|
556
|
+
warning: '#8C6D00',
|
|
557
|
+
},
|
|
558
|
+
border: {
|
|
559
|
+
default: '#1A1C1C24',
|
|
560
|
+
light: '#0073181A',
|
|
561
|
+
primary: '#006E17',
|
|
562
|
+
dark: '#003D0B',
|
|
563
|
+
},
|
|
564
|
+
skeleton: {
|
|
565
|
+
highlight: '#FFFFFFA6',
|
|
566
|
+
},
|
|
567
|
+
}),
|
|
568
|
+
dark: createTheme(baseTheme, {
|
|
569
|
+
name: 'dark',
|
|
570
|
+
colorScheme: 'dark',
|
|
571
|
+
}),
|
|
572
|
+
},
|
|
573
|
+
{}${isTypeScript ? " satisfies ThemeComponents" : ""}
|
|
574
|
+
)
|
|
575
|
+
${isTypeScript ? REGISTRATION : ""}
|
|
576
|
+
export default themes
|
|
577
|
+
`;
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* The providers the app's root renders inside: the theme, and the package's base page styles.
|
|
581
|
+
* `scheme` picks the theme, `scheme` by default, so an app can switch it. It holds no JSX, so it
|
|
582
|
+
* needs none of the app's JSX settings.
|
|
583
|
+
*/
|
|
584
|
+
function createProvidersSource({ isTypeScript, scheme, themesImport }) {
|
|
585
|
+
const typeImport = isTypeScript ? `import type { ReactNode } from 'react'
|
|
586
|
+
` : "";
|
|
587
|
+
const props = isTypeScript ? `{
|
|
588
|
+
children,
|
|
589
|
+
scheme = '${scheme}',
|
|
590
|
+
}: {
|
|
591
|
+
readonly children?: ReactNode
|
|
592
|
+
/** The theme to draw with, by its name in themes. */
|
|
593
|
+
readonly scheme?: keyof typeof themes
|
|
594
|
+
}` : `{ children, scheme = '${scheme}' }`;
|
|
595
|
+
return `${MARKER} The app's root renders inside Providers.
|
|
596
|
+
import { createElement } from 'react'
|
|
597
|
+
${typeImport}import { Global, ThemeProvider } from '${APP_PACKAGE}'
|
|
598
|
+
import { globalStyles } from '${APP_PACKAGE}/engine'
|
|
599
|
+
import themes from '${themesImport}'
|
|
600
|
+
|
|
601
|
+
/** Gives every component its theme, and draws the page's base styles. */
|
|
602
|
+
export function Providers(${props}) {
|
|
603
|
+
return createElement(
|
|
604
|
+
ThemeProvider,
|
|
605
|
+
{ theme: themes[scheme] },
|
|
606
|
+
createElement(Global, { styles: globalStyles }),
|
|
607
|
+
children
|
|
608
|
+
)
|
|
609
|
+
}
|
|
610
|
+
`;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* The one module that configures the engine, for the whole program: `setup()` gives it the theme
|
|
614
|
+
* the app starts in, which is what a server component reads with no provider above it, and what the
|
|
615
|
+
* page shows until the browser hydrates. Each entry of the app that runs first calls it (the root of
|
|
616
|
+
* a Vite app, `+onCreateGlobalContext` of Vike, an Astro integration, `instrumentation.ts` of
|
|
617
|
+
* Next.js); the same call again does nothing. `lead` is its first line, `themes` the binding of
|
|
618
|
+
* the themes module (`themes` is the default export, or a name it exports) and `theme` the theme
|
|
619
|
+
* the app starts in, as an expression over it.
|
|
620
|
+
*/
|
|
621
|
+
function createSetupSource({ isTypeScript, lead = MARKER, themesImport, themes = {
|
|
622
|
+
name: "themes",
|
|
623
|
+
isDefault: true
|
|
624
|
+
}, theme }) {
|
|
625
|
+
const binding = themes.isDefault ? themes.name : `{ ${themes.name} }`;
|
|
626
|
+
return `${lead} Configures the engine once for the whole program.
|
|
627
|
+
// What a server component reads with no provider above it, and what the page shows until the
|
|
628
|
+
// browser hydrates, is the theme the app starts in. Every entry of the app calls setup() first; the
|
|
629
|
+
// same call again does nothing.
|
|
630
|
+
import { configure } from '${APP_PACKAGE}/engine'
|
|
631
|
+
import ${binding} from '${themesImport}'
|
|
632
|
+
|
|
633
|
+
export function setup()${isTypeScript ? ": void" : ""} {
|
|
634
|
+
configure({ serverTheme: ${theme} })
|
|
635
|
+
}
|
|
636
|
+
`;
|
|
637
|
+
}
|
|
638
|
+
// src/plan/importPath.ts
|
|
639
|
+
const RELATIVE_SPECIFIER = /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g;
|
|
640
|
+
/**
|
|
641
|
+
* The extension style of a file's relative imports of code, so a new import matches its
|
|
642
|
+
* neighbours: `./App.tsx` means the app imports TypeScript files by their own extension, `./App.js`
|
|
643
|
+
* the Node style, and `./App` none.
|
|
644
|
+
*/
|
|
645
|
+
function readExtensionStyle(source) {
|
|
646
|
+
for (const [, specifier] of source.matchAll(RELATIVE_SPECIFIER)) {
|
|
647
|
+
const extension = /\.(m?[jt]sx?)$/.exec(specifier)?.[1];
|
|
648
|
+
if (extension) return extension.includes("t") ? ".ts" : ".js";
|
|
649
|
+
}
|
|
650
|
+
return "";
|
|
651
|
+
}
|
|
652
|
+
/** The specifier `fromFile` imports `toFile` by, both relative to the app's root, in `style`. */
|
|
653
|
+
function toImportSpecifier(fromFile, toFile, style) {
|
|
654
|
+
const target = toFile.replace(/\.[^./]+$/, style);
|
|
655
|
+
const specifier = posix.relative(posix.dirname(fromFile), target);
|
|
656
|
+
return specifier.startsWith(".") ? specifier : `./${specifier}`;
|
|
657
|
+
}
|
|
658
|
+
// src/migrate/versions.ts
|
|
659
|
+
function parseVersion(version) {
|
|
660
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(version);
|
|
661
|
+
if (!match) throw new Error(`migrate cannot read the version ${version}`);
|
|
662
|
+
return {
|
|
663
|
+
core: [
|
|
664
|
+
Number(match[1]),
|
|
665
|
+
Number(match[2]),
|
|
666
|
+
Number(match[3])
|
|
667
|
+
],
|
|
668
|
+
pre: match[4] ? match[4].split(".") : []
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
function comparePreIdentifiers(a, b) {
|
|
672
|
+
const isNumericA = /^\d+$/.test(a);
|
|
673
|
+
const isNumericB = /^\d+$/.test(b);
|
|
674
|
+
if (isNumericA && isNumericB) return Math.sign(Number(a) - Number(b));
|
|
675
|
+
if (isNumericA !== isNumericB) return isNumericA ? -1 : 1;
|
|
676
|
+
return a.localeCompare(b);
|
|
677
|
+
}
|
|
678
|
+
/** Negative when `a` is before `b`, positive when after, 0 when equal; a prerelease is before its release. */
|
|
679
|
+
function compareVersions(a, b) {
|
|
680
|
+
const left = parseVersion(a);
|
|
681
|
+
const right = parseVersion(b);
|
|
682
|
+
for (let index = 0; index < 3; index += 1) {
|
|
683
|
+
const difference = left.core[index] - right.core[index];
|
|
684
|
+
if (difference !== 0) return Math.sign(difference);
|
|
685
|
+
}
|
|
686
|
+
if (left.pre.length === 0 || right.pre.length === 0) return Math.sign(right.pre.length - left.pre.length);
|
|
687
|
+
const shared = Math.min(left.pre.length, right.pre.length);
|
|
688
|
+
for (let index = 0; index < shared; index += 1) {
|
|
689
|
+
const result = comparePreIdentifiers(left.pre[index], right.pre[index]);
|
|
690
|
+
if (result !== 0) return Math.sign(result);
|
|
691
|
+
}
|
|
692
|
+
return Math.sign(left.pre.length - right.pre.length);
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Whether `version` is in `range`: a version with `x` in the places that may vary - `2.x`,
|
|
696
|
+
* `0.1.x` - or one exact version. A prerelease is matched by its release's numbers. Any other
|
|
697
|
+
* shape throws.
|
|
698
|
+
*/
|
|
699
|
+
function matchesRange(version, range) {
|
|
700
|
+
if (!/^(\d+|x)(\.(\d+|x)){0,2}$/.test(range)) throw new Error(`migrate cannot read the range ${range}`);
|
|
701
|
+
const { core } = parseVersion(version);
|
|
702
|
+
return range.split(".").every((part, index) => part === "x" || Number(part) === core[index]);
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* The lowest version a declared range names, from its first version: `^2.1.0` is `2.1.0`,
|
|
706
|
+
* `~0.1.0-alpha.2` is `0.1.0-alpha.2`. A range with no version in it - `latest`, `workspace:*` -
|
|
707
|
+
* gives `undefined`.
|
|
708
|
+
*/
|
|
709
|
+
function readRangeMinimum(range) {
|
|
710
|
+
const match = /^[\^~>=<v\s]*(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?/.exec(range);
|
|
711
|
+
if (!match) return void 0;
|
|
712
|
+
const pre = match[4] && match[3] !== void 0 ? `-${match[4]}` : "";
|
|
713
|
+
return `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}${pre}`;
|
|
714
|
+
}
|
|
715
|
+
/** The range an app declares for `version`: a prerelease exactly, a release as `^version`. */
|
|
716
|
+
const toDeclaredRange = (version) => version.includes("-") ? version : `^${version}`;
|
|
717
|
+
// src/plan/setupWiring.ts
|
|
718
|
+
const isSource = (path) => /\.[cm]?[jt]sx?$/.test(path) && !/\.(test|spec|stories)\./.test(path);
|
|
719
|
+
const isWired = (source, specifier) => source.includes(`'${specifier}'`) || source.includes(`"${specifier}"`);
|
|
720
|
+
const importOf = (specifier) => `import { setup } from '${specifier}'`;
|
|
721
|
+
/** The lines a developer adds by hand: the import and the call. */
|
|
722
|
+
const linesFor = (specifier) => `${importOf(specifier)}\n\nsetup()`;
|
|
723
|
+
/**
|
|
724
|
+
* The file with the import of `setup` after its last import, and the call after that: the first
|
|
725
|
+
* thing the file does. The file itself when it already imports the module.
|
|
726
|
+
*/
|
|
727
|
+
function addSetupCall(source, specifier) {
|
|
728
|
+
if (isWired(source, specifier)) return source;
|
|
729
|
+
const imported = insertImport(source, importOf(specifier));
|
|
730
|
+
const lineEnd = imported.indexOf("\n", imported.indexOf("import { setup } from"));
|
|
731
|
+
const end = lineEnd === -1 ? imported.length : lineEnd;
|
|
732
|
+
const semicolon = imported.slice(0, end).endsWith(";") ? ";" : "";
|
|
733
|
+
return `${imported.slice(0, end)}\n\nsetup()${semicolon}${imported.slice(end)}`;
|
|
734
|
+
}
|
|
735
|
+
const functionOpening = (name) => new RegExp(String.raw`export\s+(?:async\s+)?function\s+${name}\s*\([^)]*\)[^{;=]*\{|export\s+const\s+${name}\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*(?::[^=]+?)?=>\s*\{`);
|
|
736
|
+
/**
|
|
737
|
+
* The file with the import of `setup` and, as the first statement of its exported function `name`,
|
|
738
|
+
* the call. `undefined` when the file has no such function: it is not the standard shape. The file
|
|
739
|
+
* itself when it already imports the module.
|
|
740
|
+
*/
|
|
741
|
+
function addSetupToFunction(source, name, specifier) {
|
|
742
|
+
if (isWired(source, specifier)) return source;
|
|
743
|
+
const opening = functionOpening(name).exec(source);
|
|
744
|
+
if (!opening) return void 0;
|
|
745
|
+
const brace = opening.index + opening[0].length;
|
|
746
|
+
const indentation = /\n([ \t]+)\S/.exec(source.slice(brace))?.[1] ?? " ";
|
|
747
|
+
const semicolon = /;[ \t]*(?:\n|$)/.test(source) ? ";" : "";
|
|
748
|
+
const closing = source[brace] === "}" ? "\n" : "";
|
|
749
|
+
const edited = `${source.slice(0, brace)}\n${indentation}setup()${semicolon}${closing}${source.slice(brace)}`;
|
|
750
|
+
if (!/^import\b/m.test(source)) return `${importOf(specifier)}\n\n${edited}`;
|
|
751
|
+
return insertImport(edited, importOf(specifier));
|
|
752
|
+
}
|
|
753
|
+
const depth = (path) => path.split("/").length;
|
|
754
|
+
/** The shallowest of some paths, the first by name among equals, or `undefined` for none. */
|
|
755
|
+
const shallowest = (paths) => [...paths].sort((a, b) => depth(a) - depth(b) || compareText(a, b))[0];
|
|
756
|
+
var Writer = class {
|
|
757
|
+
app;
|
|
758
|
+
setupPath;
|
|
759
|
+
wiring = {
|
|
760
|
+
creates: [],
|
|
761
|
+
edits: [],
|
|
762
|
+
manual: []
|
|
763
|
+
};
|
|
764
|
+
constructor(app, setupPath) {
|
|
765
|
+
this.app = app;
|
|
766
|
+
this.setupPath = setupPath;
|
|
767
|
+
}
|
|
768
|
+
/** The specifier of the setup module from `path`, in the style of the imports `source` has. */
|
|
769
|
+
specifier(path, source = "") {
|
|
770
|
+
return toImportSpecifier(path, this.setupPath, readExtensionStyle(source));
|
|
771
|
+
}
|
|
772
|
+
/** The extension of the files it creates: the setup module's own language. */
|
|
773
|
+
get extension() {
|
|
774
|
+
return /\.[cm]?tsx?$/.test(this.setupPath) ? "ts" : "js";
|
|
775
|
+
}
|
|
776
|
+
get types() {
|
|
777
|
+
return this.extension === "ts" ? ": void" : "";
|
|
778
|
+
}
|
|
779
|
+
create(path, content) {
|
|
780
|
+
this.wiring.creates.push({
|
|
781
|
+
path,
|
|
782
|
+
content
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Edits `path` with `change`. When it answers `undefined` the file is not the standard shape:
|
|
787
|
+
* `lines` (with `<specifier>` filled in) go to the developer instead.
|
|
788
|
+
*/
|
|
789
|
+
edit(path, change, lines) {
|
|
790
|
+
const before = this.app.readFile(path);
|
|
791
|
+
const specifier = this.specifier(path, before);
|
|
792
|
+
const after = change(before, specifier);
|
|
793
|
+
if (after === void 0) this.wiring.manual.push({
|
|
794
|
+
path,
|
|
795
|
+
text: lines.replaceAll("<specifier>", specifier)
|
|
796
|
+
});
|
|
797
|
+
else if (after !== before) this.wiring.edits.push({
|
|
798
|
+
path,
|
|
799
|
+
before,
|
|
800
|
+
after
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
manual(path, text) {
|
|
804
|
+
this.wiring.manual.push({
|
|
805
|
+
path,
|
|
806
|
+
text
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
/** Whether the app's Next.js reads `instrumentation-client`: a range or tag it cannot read is taken as recent. */
|
|
811
|
+
const hasClientInstrumentation = (packageJson) => {
|
|
812
|
+
const lowest = readRangeMinimum(getDependency(packageJson, "next"));
|
|
813
|
+
return lowest === void 0 || compareVersions(lowest, CLIENT_INSTRUMENTATION) >= 0;
|
|
814
|
+
};
|
|
815
|
+
const matching = (files, pattern) => files.filter((path) => pattern.test(path));
|
|
816
|
+
function wireVike(writer, files) {
|
|
817
|
+
const hooks = matching(files, /(?:^|\/)\+onCreateGlobalContext\.(?:server\.|client\.)?[cm]?[jt]sx?$/);
|
|
818
|
+
const hookLines = `\n\nexport function onCreateGlobalContext() {\n setup()\n}`;
|
|
819
|
+
const [hook] = hooks;
|
|
820
|
+
if (hook) {
|
|
821
|
+
if (hooks.length > 1 || /\.(?:server|client)\.[^.]+$/.test(hook)) {
|
|
822
|
+
writer.manual(hook, `The engine is configured once for the whole program, on the server and in the browser, so one +onCreateGlobalContext file with no .server or .client in its name calls setup():\n\n${linesFor(writer.specifier(hook))}${hookLines}`);
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
writer.edit(hook, (source, specifier) => addSetupToFunction(source, "onCreateGlobalContext", specifier), `Call setup() in onCreateGlobalContext, in ${hook}:\n\n${linesFor("<specifier>")}${hookLines}`);
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
const anchor = shallowest(matching(files, /(?:^|\/)\+(?:config|onRenderHtml|onRenderClient)\.[cm]?[jt]sx?$/));
|
|
829
|
+
if (anchor === void 0) {
|
|
830
|
+
writer.manual("package.json", `Add a +onCreateGlobalContext.${writer.extension} next to your global Vike files, which calls setup() on the server and in the browser:\n\n${linesFor(writer.specifier("src/pages/+onCreateGlobalContext.ts"))}${hookLines}`);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const path = posix.join(posix.dirname(anchor), `+onCreateGlobalContext.${writer.extension}`);
|
|
834
|
+
writer.create(path, `${importOf(writer.specifier(path))}
|
|
835
|
+
|
|
836
|
+
// Vike runs this once when the server starts (the development server, the prerender) and once in
|
|
837
|
+
// the browser, before any page renders: the engine is configured once for the whole program.
|
|
838
|
+
export function onCreateGlobalContext()${writer.types} {
|
|
839
|
+
setup()
|
|
840
|
+
}
|
|
841
|
+
`);
|
|
842
|
+
}
|
|
843
|
+
const CLIENT_INSTRUMENTATION = "15.3.0";
|
|
844
|
+
function wireNext(writer, files, packageJson) {
|
|
845
|
+
const base = files.some((path) => /^src\/(?:app|pages)\//.test(path)) ? "src/" : "";
|
|
846
|
+
const [instrumentation] = matching(files, new RegExp(String.raw`^${base}instrumentation\.[cm]?[jt]s$`));
|
|
847
|
+
if (instrumentation) writer.edit(instrumentation, (source, specifier) => addSetupToFunction(source, "register", specifier), `Call setup() first in register(), in ${instrumentation}:\n\n${linesFor("<specifier>")}\n\nexport function register() {\n setup()\n}`);
|
|
848
|
+
else {
|
|
849
|
+
const path = `${base}instrumentation.${writer.extension}`;
|
|
850
|
+
writer.create(path, `${importOf(writer.specifier(path))}
|
|
851
|
+
|
|
852
|
+
/** Next.js calls it once when the server starts (\`next start\`, \`next dev\`). */
|
|
853
|
+
export function register()${writer.types} {
|
|
854
|
+
setup()
|
|
855
|
+
}
|
|
856
|
+
`);
|
|
857
|
+
}
|
|
858
|
+
const [client] = matching(files, new RegExp(String.raw`^${base}instrumentation-client\.[cm]?[jt]s$`));
|
|
859
|
+
if (client) writer.edit(client, addSetupCall, `Call setup() in ${client}:\n\n${linesFor("<specifier>")}`);
|
|
860
|
+
else if (!hasClientInstrumentation(packageJson)) {
|
|
861
|
+
const providers = linesFor(writer.specifier(`${base}app/Providers.tsx`));
|
|
862
|
+
writer.manual("package.json", `This Next.js version does not run instrumentation-client (15.3 or later does), so call setup() in the root client component of the app (the one with 'use client' that renders ThemeProvider), before anything renders:
|
|
863
|
+
|
|
864
|
+
${providers}`);
|
|
865
|
+
} else {
|
|
866
|
+
const path = `${base}instrumentation-client.${writer.extension}`;
|
|
867
|
+
writer.create(path, `${importOf(writer.specifier(path))}
|
|
868
|
+
|
|
869
|
+
// Next.js runs this file in the browser before the app hydrates.
|
|
870
|
+
setup()
|
|
871
|
+
`);
|
|
872
|
+
}
|
|
873
|
+
const [layout] = matching(files, new RegExp(String.raw`^${base}app/layout\.[jt]sx?$`));
|
|
874
|
+
if (layout) writer.edit(layout, addSetupCall, `Call setup() at the top of the root layout, ${layout}:\n\n${linesFor("<specifier>")}`);
|
|
875
|
+
else {
|
|
876
|
+
const rootLayout = linesFor(writer.specifier(`${base}app/layout.tsx`));
|
|
877
|
+
writer.manual("package.json", `next build prerenders without calling register(), so the module every page loads calls setup() too: the root layout, or with the pages router pages/_app:\n\n${rootLayout}`);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
const ASTRO_INTEGRATION = (setupPath) => `// Configures the engine once for the whole program (${setupPath}): in the browser before the
|
|
881
|
+
// islands hydrate, and on the server before a page is rendered.
|
|
882
|
+
function setupEngine() {
|
|
883
|
+
const run = "import { setup } from '/${setupPath}'; setup()"
|
|
884
|
+
return {
|
|
885
|
+
name: 'setup-engine',
|
|
886
|
+
hooks: {
|
|
887
|
+
'astro:config:setup': ({ injectScript }) => {
|
|
888
|
+
injectScript('before-hydration', run)
|
|
889
|
+
injectScript('page-ssr', run)
|
|
890
|
+
},
|
|
891
|
+
},
|
|
892
|
+
}
|
|
893
|
+
}`;
|
|
894
|
+
/** The Astro config with the integration after its imports, and listed first in `integrations`. */
|
|
895
|
+
function addAstroIntegration(source, setupPath) {
|
|
896
|
+
if (source.includes("setupEngine")) return source;
|
|
897
|
+
const list = /integrations:\s*\[(?:\s*\])?/.exec(source);
|
|
898
|
+
if (!list) return void 0;
|
|
899
|
+
const listed = list[0].endsWith("]") ? `${list[0].slice(0, list[0].indexOf("[") + 1)}setupEngine()]` : `${list[0]}setupEngine(), `;
|
|
900
|
+
const edited = source.replace(list[0], listed);
|
|
901
|
+
const lastImport = [...edited.matchAll(/^import[\s\S]*?['"];?[^\S\n]*$/gm)].at(-1);
|
|
902
|
+
if (!lastImport) return `${ASTRO_INTEGRATION(setupPath)}\n\n${edited}`;
|
|
903
|
+
const end = lastImport.index + lastImport[0].length;
|
|
904
|
+
return `${edited.slice(0, end)}\n\n${ASTRO_INTEGRATION(setupPath)}${edited.slice(end)}`;
|
|
905
|
+
}
|
|
906
|
+
function wireAstro(writer, files) {
|
|
907
|
+
const [config] = matching(files, /^astro\.config\.[cm]?[jt]s$/);
|
|
908
|
+
const lines = `Add this integration to ${config ?? "astro.config.mjs"}, and list setupEngine() in integrations:\n\n${ASTRO_INTEGRATION(writer.setupPath)}`;
|
|
909
|
+
if (config) writer.edit(config, (source) => addAstroIntegration(source, writer.setupPath), lines);
|
|
910
|
+
else writer.manual("package.json", lines);
|
|
911
|
+
}
|
|
912
|
+
function wireClient(writer, files, app) {
|
|
913
|
+
const roots = files.filter((path) => isSource(path) && isRootSource(app.readFile(path)));
|
|
914
|
+
if (roots.length === 1) writer.edit(roots[0], addSetupCall, `Call setup() before anything renders, in ${roots[0]}:\n\n${linesFor("<specifier>")}`);
|
|
915
|
+
else {
|
|
916
|
+
const found = roots.length === 0 ? "No file that starts your app was found." : `More than one file starts your app (${roots.join(", ")}).`;
|
|
917
|
+
writer.manual("package.json", `${found} Call setup() before anything renders, in each file that runs first:\n\n${linesFor(writer.specifier("src/main.tsx"))}`);
|
|
918
|
+
}
|
|
919
|
+
for (const entry of matching(files, /(?:^|\/)entry-server\.[cm]?[jt]sx?$/)) writer.edit(entry, addSetupCall, `Call setup() at the top of the server entry, ${entry}:\n\n${linesFor("<specifier>")}`);
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Wires `setup` (the module at `setupPath`) into the entries of the framework the app uses: where
|
|
923
|
+
* it runs first, so the engine is configured before anything renders. An entry that exists is
|
|
924
|
+
* edited and one that does not is created; what is not the standard shape is returned with the
|
|
925
|
+
* lines to add.
|
|
926
|
+
*/
|
|
927
|
+
function wireSetup(app, setupPath) {
|
|
928
|
+
const writer = new Writer(app, setupPath);
|
|
929
|
+
const files = app.listFiles();
|
|
930
|
+
const framework = findFramework(app.packageJson)?.[0];
|
|
931
|
+
if (framework === "next") wireNext(writer, files, app.packageJson);
|
|
932
|
+
else if (framework === "vike") wireVike(writer, files);
|
|
933
|
+
else if (framework === "astro") wireAstro(writer, files);
|
|
934
|
+
else if (framework) writer.manual("package.json", `Call setup() before anything renders, in each entry of your app that runs first (on the server and in the browser):\n\n${linesFor(writer.specifier("src/entry.ts"))}`);
|
|
935
|
+
else wireClient(writer, files, app);
|
|
936
|
+
return writer.wiring;
|
|
937
|
+
}
|
|
938
|
+
const SETUP_FILES = /setupFiles(?:AfterEnv|AfterEach)?\s*:\s*(\[[^\]]*\]|'[^']*'|"[^"]*")/g;
|
|
939
|
+
const RUNNER_CONFIG = /(?:^|\/)(?:vitest|vite|jest)\.(?:config|workspace)\.[cm]?[jt]s$/;
|
|
940
|
+
const SETUP_FILE_NAME = /(?:^|\/)(?:setupTests?|setup-tests|vitest\.setup|jest\.setup)(?:\.[a-z]+)?\.[cm]?[jt]sx?$/;
|
|
941
|
+
const STORYBOOK_PREVIEW = /(?:^|\/)\.storybook\/preview\.[cm]?[jt]sx?$/;
|
|
942
|
+
/** The files of the app that every test and every story runs first. */
|
|
943
|
+
function findTestEntries(app, files) {
|
|
944
|
+
const entries = new Set(matching(files, SETUP_FILE_NAME));
|
|
945
|
+
for (const config of matching(files, RUNNER_CONFIG)) for (const [list] of app.readFile(config).matchAll(SETUP_FILES)) for (const [, name] of list.matchAll(/['"]([^'"]+)['"]/g)) {
|
|
946
|
+
const path = posix.normalize(posix.join(posix.dirname(config), name.replace("<rootDir>/", "")));
|
|
947
|
+
if (files.includes(path) && /\.[cm]?[jt]sx?$/.test(path)) entries.add(path);
|
|
948
|
+
}
|
|
949
|
+
for (const path of matching(files, STORYBOOK_PREVIEW)) entries.add(path);
|
|
950
|
+
return [...entries].sort(compareText);
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Wires `setup` into what runs before the tests and the stories: the setup files the runner config
|
|
954
|
+
* names (or that are named so) and the Storybook preview. A file written with `require` is not
|
|
955
|
+
* edited: the line to add is returned.
|
|
956
|
+
*/
|
|
957
|
+
function wireTestEntries(app, setupPath) {
|
|
958
|
+
const writer = new Writer(app, setupPath);
|
|
959
|
+
for (const path of findTestEntries(app, app.listFiles())) {
|
|
960
|
+
const source = app.readFile(path);
|
|
961
|
+
if (!/^[ \t]*import\s/m.test(source) && /require\(|module\.exports/.test(source)) {
|
|
962
|
+
const specifier = writer.specifier(path, source);
|
|
963
|
+
if (!isWired(source, specifier)) writer.manual(path, `Call setup() first in ${path}:\n\nrequire('${specifier}').setup()`);
|
|
964
|
+
} else writer.edit(path, addSetupCall, `Call setup() first in ${path}:\n\n${linesFor("<specifier>")}`);
|
|
965
|
+
}
|
|
966
|
+
return writer.wiring;
|
|
967
|
+
}
|
|
968
|
+
// src/plan/planInit.ts
|
|
969
|
+
const SETUP_DOCS = "https://gild-ui.soroush.design/react/installation/";
|
|
970
|
+
/** The command that adds Gild UI with the app's own package manager, running no scripts. */
|
|
971
|
+
function createInstallCommand({ name, isYarnBerry }, version) {
|
|
972
|
+
const range = version.includes("-") ? version : `^${version}`;
|
|
973
|
+
const specs = [`${APP_PACKAGE}@${range}`, `${CORE_PACKAGE}@${range}`];
|
|
974
|
+
if (name === "yarn" && isYarnBerry) return {
|
|
975
|
+
command: "yarn",
|
|
976
|
+
args: ["add", ...specs],
|
|
977
|
+
env: { YARN_ENABLE_SCRIPTS: "false" }
|
|
978
|
+
};
|
|
979
|
+
return {
|
|
980
|
+
command: name,
|
|
981
|
+
args: [
|
|
982
|
+
name === "npm" ? "install" : "add",
|
|
983
|
+
...specs,
|
|
984
|
+
"--ignore-scripts"
|
|
985
|
+
],
|
|
986
|
+
env: {}
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
/** The command that installs what package.json lists, with the app's package manager, running no scripts. */
|
|
990
|
+
function createInstallAllCommand({ name, isYarnBerry }) {
|
|
991
|
+
if (name === "yarn" && isYarnBerry) return {
|
|
992
|
+
command: "yarn",
|
|
993
|
+
args: ["install"],
|
|
994
|
+
env: { YARN_ENABLE_SCRIPTS: "false" }
|
|
995
|
+
};
|
|
996
|
+
return {
|
|
997
|
+
command: name,
|
|
998
|
+
args: ["install", "--ignore-scripts"],
|
|
999
|
+
env: {}
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
function describeRootProblem(facts) {
|
|
1003
|
+
if (facts.rootCandidates.length === 0) return "init found no file that calls createRoot(...).render( or ReactDOM.render(.";
|
|
1004
|
+
return `init found more than one root (${facts.rootCandidates.join(", ")}) and edits none.`;
|
|
1005
|
+
}
|
|
1006
|
+
/** Works out the changes, reading files through `facts.readFile` and writing nothing. */
|
|
1007
|
+
function planInit(facts) {
|
|
1008
|
+
const plan = {
|
|
1009
|
+
creates: [],
|
|
1010
|
+
edits: [],
|
|
1011
|
+
skips: [],
|
|
1012
|
+
manual: [],
|
|
1013
|
+
install: void 0
|
|
1014
|
+
};
|
|
1015
|
+
const extension = facts.isTypeScript ? "ts" : "js";
|
|
1016
|
+
const themeDir = facts.hasSrcFolder || !facts.root ? "src/theme" : posix.join(posix.dirname(facts.root.path), "theme");
|
|
1017
|
+
const themesPath = `${themeDir}/themes.${extension}`;
|
|
1018
|
+
const providersPath = `${themeDir}/Providers.${extension}`;
|
|
1019
|
+
const setupPath = `${themeDir}/setup.${extension}`;
|
|
1020
|
+
const style = facts.root ? readExtensionStyle(facts.root.source) : "";
|
|
1021
|
+
if (planThemeFiles(plan, facts, {
|
|
1022
|
+
themesPath,
|
|
1023
|
+
providersPath,
|
|
1024
|
+
setupPath,
|
|
1025
|
+
style
|
|
1026
|
+
})) planRootEdit(plan, facts, {
|
|
1027
|
+
providersPath,
|
|
1028
|
+
setupPath: getOwnership(facts, setupPath) === "ours" || plan.creates.some((file) => file.path === setupPath) ? setupPath : void 0
|
|
1029
|
+
}, style);
|
|
1030
|
+
else plan.manual.push(`Set up the theme by hand: ${SETUP_DOCS}`);
|
|
1031
|
+
if (facts.needsParcelPackageExports) plan.manual.push(`Parcel finds ${CORE_PACKAGE}/theme and the subpaths of ${APP_PACKAGE} only once it reads package exports. Add to package.json: "@parcel/resolver-default": { "packageExports": true }`);
|
|
1032
|
+
if (!facts.hasDesignSystem) plan.install = createInstallCommand(facts.packageManager, facts.version);
|
|
1033
|
+
return plan;
|
|
1034
|
+
}
|
|
1035
|
+
/** Whether a file is missing, was written by init, or by someone else. */
|
|
1036
|
+
function getOwnership(facts, path) {
|
|
1037
|
+
const content = facts.readFile(path);
|
|
1038
|
+
if (content === void 0) return "missing";
|
|
1039
|
+
return isSetUpByInit(content) ? "ours" : "theirs";
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Plans the themes and the providers, never over a file init did not write. Returns whether the
|
|
1043
|
+
* app ends up with init's providers.
|
|
1044
|
+
*/
|
|
1045
|
+
function planThemeFiles(plan, facts, { themesPath, providersPath, setupPath, style }) {
|
|
1046
|
+
const themes = getOwnership(facts, themesPath);
|
|
1047
|
+
const providers = getOwnership(facts, providersPath);
|
|
1048
|
+
const setup = getOwnership(facts, setupPath);
|
|
1049
|
+
if (themes === "missing") plan.creates.push({
|
|
1050
|
+
path: themesPath,
|
|
1051
|
+
content: createThemesSource(facts)
|
|
1052
|
+
});
|
|
1053
|
+
else if (themes === "theirs") plan.skips.push({
|
|
1054
|
+
path: themesPath,
|
|
1055
|
+
reason: "exists, and init did not write it"
|
|
1056
|
+
});
|
|
1057
|
+
if (providers === "theirs") plan.skips.push({
|
|
1058
|
+
path: providersPath,
|
|
1059
|
+
reason: "exists, and init did not write it"
|
|
1060
|
+
});
|
|
1061
|
+
else if (providers === "missing" && themes === "theirs") plan.skips.push({
|
|
1062
|
+
path: providersPath,
|
|
1063
|
+
reason: `would read ${themesPath}, which init did not write`
|
|
1064
|
+
});
|
|
1065
|
+
else if (providers === "missing") {
|
|
1066
|
+
const themesImport = toImportSpecifier(providersPath, themesPath, style);
|
|
1067
|
+
plan.creates.push({
|
|
1068
|
+
path: providersPath,
|
|
1069
|
+
content: createProvidersSource({
|
|
1070
|
+
...facts,
|
|
1071
|
+
themesImport
|
|
1072
|
+
})
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
if (setup === "theirs") plan.skips.push({
|
|
1076
|
+
path: setupPath,
|
|
1077
|
+
reason: "exists, and init did not write it"
|
|
1078
|
+
});
|
|
1079
|
+
else if (setup === "missing" && themes === "theirs") plan.skips.push({
|
|
1080
|
+
path: setupPath,
|
|
1081
|
+
reason: `would read ${themesPath}, which init did not write`
|
|
1082
|
+
});
|
|
1083
|
+
else if (setup === "missing") plan.creates.push({
|
|
1084
|
+
path: setupPath,
|
|
1085
|
+
content: createSetupSource({
|
|
1086
|
+
...facts,
|
|
1087
|
+
themesImport: toImportSpecifier(setupPath, themesPath, style),
|
|
1088
|
+
theme: `themes.${facts.scheme}`
|
|
1089
|
+
})
|
|
1090
|
+
});
|
|
1091
|
+
return providers === "ours" || plan.creates.some((file) => file.path === providersPath);
|
|
1092
|
+
}
|
|
1093
|
+
/** Plans the root's edit, or the lines to add by hand when init cannot make it. */
|
|
1094
|
+
function planRootEdit(plan, facts, { providersPath, setupPath }, style) {
|
|
1095
|
+
if (!facts.root) {
|
|
1096
|
+
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>).`);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
const specifier = toImportSpecifier(facts.root.path, providersPath, style);
|
|
1100
|
+
const statement = `import { Providers } from '${specifier}'`;
|
|
1101
|
+
const { path, source } = facts.root;
|
|
1102
|
+
const wrapped = source.includes(`'${specifier}'`) || source.includes(`"${specifier}"`) ? source : wrapRoot(source, statement, /\.[jt]sx$/.test(path));
|
|
1103
|
+
const after = wrapped !== null && setupPath ? addSetupCall(wrapped, toImportSpecifier(path, setupPath, style)) : wrapped;
|
|
1104
|
+
if (after === null) {
|
|
1105
|
+
const call = setupPath ? `, import { setup } from '${toImportSpecifier(path, setupPath, style)}' and call setup() before anything renders` : "";
|
|
1106
|
+
plan.manual.push(`${path} is not the standard shape, so init leaves it as it is. Add ${statement} to it${call}, and wrap the tree it renders: render(<Providers><App /></Providers>).`);
|
|
1107
|
+
} else if (after !== source) plan.edits.push({
|
|
1108
|
+
path,
|
|
1109
|
+
before: source,
|
|
1110
|
+
after
|
|
1111
|
+
});
|
|
1112
|
+
}
|
|
1113
|
+
/** Whether the plan has nothing to write or install. */
|
|
1114
|
+
function isPlanEmpty(plan) {
|
|
1115
|
+
return plan.creates.length === 0 && plan.edits.length === 0 && !plan.install;
|
|
1116
|
+
}
|
|
1117
|
+
// src/init.ts
|
|
1118
|
+
function formatClosing({ creates, manual }) {
|
|
1119
|
+
const themes = creates.find((file) => /\/themes\.[jt]s$/.test(file.path));
|
|
1120
|
+
const themesStep = themes ? `\n - Make the themes your own in ${themes.path}.` : "";
|
|
1121
|
+
const steps = manual.map((step) => ` - ${step}`).join("\n");
|
|
1122
|
+
return `Done: Gild UI is set up.
|
|
1123
|
+
${manual.length > 0 ? `\nStill left to you:\n${steps}\n` : ""}
|
|
1124
|
+
Next:
|
|
1125
|
+
- Use a component: import { Button } from '${APP_PACKAGE}/Button'${themesStep}
|
|
1126
|
+
${FONTS_STEP}
|
|
1127
|
+
|
|
1128
|
+
${AGENT_STEPS}`;
|
|
1129
|
+
}
|
|
1130
|
+
/** Why init refuses this app, or `undefined` when it can set it up. */
|
|
1131
|
+
function findRefusal(root, packageJson, reactRange) {
|
|
1132
|
+
const framework = findUnsupportedFramework(packageJson);
|
|
1133
|
+
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}`;
|
|
1134
|
+
const reactVersion = findReactVersion(root, packageJson);
|
|
1135
|
+
if (!reactVersion) return "init found no React in this app. Add react and react-dom first.";
|
|
1136
|
+
if (!satisfiesRange(reactVersion, reactRange)) return `This app has React ${reactVersion}, and Gild UI needs React ${reactRange}. init changes nothing, and never upgrades React.`;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* The app init sets up from `cwd`: the folder itself, or - in a workspace's root - the one package
|
|
1140
|
+
* in it that starts an app. A string says why there is none. A file in a nested package is never
|
|
1141
|
+
* taken for the app's own.
|
|
1142
|
+
*/
|
|
1143
|
+
function findApp(cwd) {
|
|
1144
|
+
const packageJson = readPackageJson(cwd);
|
|
1145
|
+
if (!packageJson) return "There is no package.json in this folder. Run init in your app's folder.";
|
|
1146
|
+
const rootFilesByFolder = /* @__PURE__ */ new Map();
|
|
1147
|
+
for (const path of findRootFiles(cwd)) {
|
|
1148
|
+
const folder = findPackageFolder(cwd, path);
|
|
1149
|
+
rootFilesByFolder.set(folder, [...rootFilesByFolder.get(folder) ?? [], path]);
|
|
1150
|
+
}
|
|
1151
|
+
if (!isWorkspaceRoot(cwd, packageJson)) return {
|
|
1152
|
+
root: cwd,
|
|
1153
|
+
packageJson,
|
|
1154
|
+
rootCandidates: rootFilesByFolder.get("") ?? [],
|
|
1155
|
+
folder: ""
|
|
1156
|
+
};
|
|
1157
|
+
const folders = [...rootFilesByFolder.keys()];
|
|
1158
|
+
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.";
|
|
1159
|
+
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)}`;
|
|
1160
|
+
const [folder] = folders;
|
|
1161
|
+
const root = join(cwd, folder);
|
|
1162
|
+
const rootCandidates = rootFilesByFolder.get(folder).map((path) => folder ? path.slice(folder.length + 1) : path);
|
|
1163
|
+
return {
|
|
1164
|
+
root,
|
|
1165
|
+
packageJson: readPackageJson(root),
|
|
1166
|
+
rootCandidates,
|
|
1167
|
+
folder
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
/** Asks for the default color scheme, starting on light. */
|
|
1171
|
+
async function askScheme(io) {
|
|
1172
|
+
return await io.select("Default color scheme", [{
|
|
1173
|
+
value: "light",
|
|
1174
|
+
label: "light"
|
|
1175
|
+
}, {
|
|
1176
|
+
value: "dark",
|
|
1177
|
+
label: "dark"
|
|
1178
|
+
}]);
|
|
1179
|
+
}
|
|
1180
|
+
function collectFacts(app, scheme) {
|
|
1181
|
+
const { root, packageJson, rootCandidates } = app;
|
|
1182
|
+
const rootPath = rootCandidates.length === 1 ? rootCandidates[0] : void 0;
|
|
1183
|
+
return {
|
|
1184
|
+
isTypeScript: rootPath ? /\.m?tsx?$/.test(rootPath) : existsSync(join(root, "tsconfig.json")),
|
|
1185
|
+
hasSrcFolder: existsSync(join(root, "src")),
|
|
1186
|
+
root: rootPath ? {
|
|
1187
|
+
path: rootPath,
|
|
1188
|
+
source: readText(join(root, rootPath))
|
|
1189
|
+
} : void 0,
|
|
1190
|
+
rootCandidates,
|
|
1191
|
+
hasDesignSystem: Boolean(getDependency(packageJson, APP_PACKAGE)),
|
|
1192
|
+
needsParcelPackageExports: needsParcelPackageExports(packageJson),
|
|
1193
|
+
packageManager: detectPackageManager(root, packageJson),
|
|
1194
|
+
version: APP_PACKAGE_VERSION,
|
|
1195
|
+
scheme: scheme ?? "light",
|
|
1196
|
+
readFile: (path) => readText(join(root, path))
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
/** Plans, asking for the default scheme first when init creates the providers and may ask. */
|
|
1200
|
+
async function planWithScheme(facts, canAsk, io) {
|
|
1201
|
+
const plan = planInit(facts);
|
|
1202
|
+
return plan.creates.some((file) => /\/Providers\.[jt]s$/.test(file.path)) && canAsk ? planInit({
|
|
1203
|
+
...facts,
|
|
1204
|
+
scheme: await askScheme(io)
|
|
1205
|
+
}) : plan;
|
|
1206
|
+
}
|
|
1207
|
+
/** Whether to apply the plan: never on a dry run or with no terminal, else on --yes or a yes. */
|
|
1208
|
+
async function isApproved(options, isPreviewOnly, io) {
|
|
1209
|
+
if (options.isDryRun) {
|
|
1210
|
+
io.write("Dry run: nothing was changed.\n");
|
|
1211
|
+
return false;
|
|
1212
|
+
}
|
|
1213
|
+
if (isPreviewOnly) {
|
|
1214
|
+
io.write("Preview only: there is no terminal to answer in. Run again with --yes to apply.\n");
|
|
1215
|
+
return false;
|
|
1216
|
+
}
|
|
1217
|
+
if (options.isConfirmed) return true;
|
|
1218
|
+
const isYes = /^y(es)?$/i.test((await io.ask("Apply these changes? (y/N) ")).trim());
|
|
1219
|
+
if (!isYes) io.write("Nothing was changed.\n");
|
|
1220
|
+
return isYes;
|
|
1221
|
+
}
|
|
1222
|
+
/** Writes the plan, then installs the package. Returns the exit code. */
|
|
1223
|
+
function applyAndInstall(plan, root, io, fileSystem) {
|
|
1224
|
+
try {
|
|
1225
|
+
applyPlan(plan, root, fileSystem);
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
const { message, isUndone } = error;
|
|
1228
|
+
const outcome = isUndone ? "Every change it made was taken back." : "It could not take back every change: check the files.";
|
|
1229
|
+
io.write(`init stopped: ${message}. ${outcome}\n`);
|
|
1230
|
+
return 1;
|
|
1231
|
+
}
|
|
1232
|
+
if (plan.install) {
|
|
1233
|
+
const { command, args, env } = plan.install;
|
|
1234
|
+
io.write(`\nInstalling with ${command}:\n`);
|
|
1235
|
+
if (io.run(command, args, {
|
|
1236
|
+
cwd: root,
|
|
1237
|
+
env,
|
|
1238
|
+
showOutput: true
|
|
1239
|
+
}).status !== 0) {
|
|
1240
|
+
const commandLine = [command, ...args].join(" ");
|
|
1241
|
+
io.write(`\nThe install failed. The files are written; install the package yourself:\n ${commandLine}\n`);
|
|
1242
|
+
return 1;
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
io.write(formatClosing(plan));
|
|
1246
|
+
return 0;
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Sets up Gild UI in the app in `io.cwd`: checks, plans, shows the plan, and applies it
|
|
1250
|
+
* only after a yes. It installs `@gild-ui/react` and `@gild-ui/core`; `designSystem` is
|
|
1251
|
+
* the React package, whose peer range for React the app is checked against. Returns the
|
|
1252
|
+
* exit code.
|
|
1253
|
+
*/
|
|
1254
|
+
async function runInit(options, io, designSystem, fileSystem = nodeFileSystem) {
|
|
1255
|
+
const app = findApp(realpathSync(io.cwd));
|
|
1256
|
+
if (typeof app === "string") {
|
|
1257
|
+
io.write(`${app}\n`);
|
|
1258
|
+
return 1;
|
|
1259
|
+
}
|
|
1260
|
+
const { root, packageJson, folder } = app;
|
|
1261
|
+
if (folder) io.write(`This is a workspace's root: init sets up the app in ${folder}.\n\n`);
|
|
1262
|
+
const refusal = findRefusal(root, packageJson, designSystem.peerDependencies.react);
|
|
1263
|
+
if (refusal) {
|
|
1264
|
+
io.write(`${refusal}\n`);
|
|
1265
|
+
return 1;
|
|
1266
|
+
}
|
|
1267
|
+
const isPreviewOnly = options.isDryRun || !io.isInteractive && !options.isConfirmed;
|
|
1268
|
+
const plan = await planWithScheme(collectFacts(app, options.scheme), !options.scheme && !isPreviewOnly && !options.isConfirmed, io);
|
|
1269
|
+
if (isPlanEmpty(plan)) {
|
|
1270
|
+
const leftovers = plan.skips.length + plan.manual.length > 0 ? `\n${formatPlan(plan)}` : "";
|
|
1271
|
+
io.write(`Gild UI is already set up here: init has nothing to change.\n${leftovers}`);
|
|
1272
|
+
return 0;
|
|
1273
|
+
}
|
|
1274
|
+
const appName = packageJson.name ?? "this app";
|
|
1275
|
+
io.write(`init will set up ${APP_PACKAGE} in ${appName}:\n\n${formatPlan(plan)}\n`);
|
|
1276
|
+
if (!await isApproved(options, isPreviewOnly, io)) return 0;
|
|
1277
|
+
return applyAndInstall(plan, root, io, fileSystem);
|
|
1278
|
+
}
|
|
1279
|
+
export { APP_PACKAGE as A, readText as C, applyPlan as D, FONTS_STEP as E, CORE_PACKAGE as M, name as N, applyPlans as O, peerDependencies as P, readPackageJson as S, AGENT_STEPS as T, diffLines as _, wireSetup as a, getDependency as b, matchesRange as c, readExtensionStyle as d, toImportSpecifier as f, formatPlan as g, createThemesSource as h, createInstallAllCommand as i, APP_PACKAGE_VERSION as j, nodeFileSystem as k, readRangeMinimum as l, createSetupSource as m, isApproved as n, wireTestEntries as o, createProvidersSource as p, runInit as r, compareVersions as s, askScheme as t, toDeclaredRange as u, detectPackageManager as v, compareText as w, listAppFiles as x, findInstalledVersion as y };
|