@velastack/patterns 0.2.1 → 0.2.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/dist/chunks/{collections-wIKcIKzY.js → collections-1Z0NCLM-.js} +2 -2
- package/dist/chunks/{collections-wIKcIKzY.js.map → collections-1Z0NCLM-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CQWygx-F.js → generate.runtime-BHoIbpFW.js} +2 -2
- package/dist/chunks/{generate.runtime-CQWygx-F.js.map → generate.runtime-BHoIbpFW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BlK7yHff.js → generate.runtime-BhgkUhnZ.js} +2 -2
- package/dist/chunks/{generate.runtime-BlK7yHff.js.map → generate.runtime-BhgkUhnZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-4QI3es6J.js → generate.runtime-BiQzi7ie.js} +2 -2
- package/dist/chunks/{generate.runtime-4QI3es6J.js.map → generate.runtime-BiQzi7ie.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CNrtLDCf.js → generate.runtime-C3kgmLls.js} +2 -2
- package/dist/chunks/{generate.runtime-CNrtLDCf.js.map → generate.runtime-C3kgmLls.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C4wcEIc9.js → generate.runtime-CbSifpZG.js} +3 -3
- package/dist/chunks/{generate.runtime-C4wcEIc9.js.map → generate.runtime-CbSifpZG.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BX0QcpGg.js → generate.runtime-CflCO_6s.js} +2 -2
- package/dist/chunks/{generate.runtime-BX0QcpGg.js.map → generate.runtime-CflCO_6s.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CQ0Veyk4.js → generate.runtime-CqOjFGKT.js} +3 -3
- package/dist/chunks/{generate.runtime-CQ0Veyk4.js.map → generate.runtime-CqOjFGKT.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DOBfTVW3.js → generate.runtime-DUFPsIYY.js} +3 -3
- package/dist/chunks/{generate.runtime-DOBfTVW3.js.map → generate.runtime-DUFPsIYY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CAzHPuHk.js → generate.runtime-DYySjH4f.js} +2 -2
- package/dist/chunks/{generate.runtime-CAzHPuHk.js.map → generate.runtime-DYySjH4f.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BmW0th7X.js → generate.runtime-JtRQn3Yl.js} +2 -2
- package/dist/chunks/{generate.runtime-BmW0th7X.js.map → generate.runtime-JtRQn3Yl.js.map} +1 -1
- package/dist/chunks/pocketbase-059B1oot.js +228 -0
- package/dist/chunks/pocketbase-059B1oot.js.map +1 -0
- package/dist/chunks/{shared-BZlvCHX8.js → shared-CaHmNkZE.js} +2 -2
- package/dist/chunks/{shared-BZlvCHX8.js.map → shared-CaHmNkZE.js.map} +1 -1
- package/dist/chunks/{ui-DZS2SAQg.js → ui-DAtVMiVs.js} +2 -2
- package/dist/chunks/{ui-DZS2SAQg.js.map → ui-DAtVMiVs.js.map} +1 -1
- package/dist/chunks/{write-result-Cb3r0sCO.js → write-result-BHCOxcsA.js} +2 -2
- package/dist/chunks/{write-result-Cb3r0sCO.js.map → write-result-BHCOxcsA.js.map} +1 -1
- package/dist/index.js +50 -50
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/pocketbase-fERkp8b8.js +0 -123
- package/dist/chunks/pocketbase-fERkp8b8.js.map +0 -1
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { i as e, n as t } from "./constants-PBCzh8eY.js";
|
|
2
|
+
import n from "node:path";
|
|
3
|
+
import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
|
|
4
|
+
import o from "pocketbase";
|
|
5
|
+
import { detect as s } from "package-manager-detector";
|
|
6
|
+
import { resolveCommand as c } from "package-manager-detector/commands";
|
|
7
|
+
import l from "cross-spawn";
|
|
8
|
+
import u from "node:net";
|
|
9
|
+
//#region src/runtime/net.ts
|
|
10
|
+
var d = /* @__PURE__ */ new Set([
|
|
11
|
+
1,
|
|
12
|
+
7,
|
|
13
|
+
9,
|
|
14
|
+
11,
|
|
15
|
+
13,
|
|
16
|
+
15,
|
|
17
|
+
17,
|
|
18
|
+
19,
|
|
19
|
+
20,
|
|
20
|
+
21,
|
|
21
|
+
22,
|
|
22
|
+
23,
|
|
23
|
+
25,
|
|
24
|
+
37,
|
|
25
|
+
42,
|
|
26
|
+
43,
|
|
27
|
+
53,
|
|
28
|
+
69,
|
|
29
|
+
77,
|
|
30
|
+
79,
|
|
31
|
+
87,
|
|
32
|
+
95,
|
|
33
|
+
101,
|
|
34
|
+
102,
|
|
35
|
+
103,
|
|
36
|
+
104,
|
|
37
|
+
109,
|
|
38
|
+
110,
|
|
39
|
+
111,
|
|
40
|
+
113,
|
|
41
|
+
115,
|
|
42
|
+
117,
|
|
43
|
+
119,
|
|
44
|
+
123,
|
|
45
|
+
135,
|
|
46
|
+
137,
|
|
47
|
+
139,
|
|
48
|
+
143,
|
|
49
|
+
161,
|
|
50
|
+
179,
|
|
51
|
+
389,
|
|
52
|
+
427,
|
|
53
|
+
465,
|
|
54
|
+
512,
|
|
55
|
+
513,
|
|
56
|
+
514,
|
|
57
|
+
515,
|
|
58
|
+
526,
|
|
59
|
+
530,
|
|
60
|
+
531,
|
|
61
|
+
532,
|
|
62
|
+
540,
|
|
63
|
+
548,
|
|
64
|
+
554,
|
|
65
|
+
556,
|
|
66
|
+
563,
|
|
67
|
+
587,
|
|
68
|
+
601,
|
|
69
|
+
636,
|
|
70
|
+
989,
|
|
71
|
+
990,
|
|
72
|
+
993,
|
|
73
|
+
995,
|
|
74
|
+
1719,
|
|
75
|
+
1720,
|
|
76
|
+
1723,
|
|
77
|
+
2049,
|
|
78
|
+
3659,
|
|
79
|
+
4045,
|
|
80
|
+
4190,
|
|
81
|
+
5060,
|
|
82
|
+
5061,
|
|
83
|
+
6e3,
|
|
84
|
+
6566,
|
|
85
|
+
6665,
|
|
86
|
+
6666,
|
|
87
|
+
6667,
|
|
88
|
+
6668,
|
|
89
|
+
6669,
|
|
90
|
+
6679,
|
|
91
|
+
6697,
|
|
92
|
+
10080
|
|
93
|
+
]);
|
|
94
|
+
function f(e) {
|
|
95
|
+
return new Promise((t, n) => {
|
|
96
|
+
let r = u.createServer();
|
|
97
|
+
r.unref(), r.once("error", n), r.listen(0, e, () => {
|
|
98
|
+
let { port: e } = r.address();
|
|
99
|
+
r.close(() => t(e));
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async function p(e) {
|
|
104
|
+
for (;;) {
|
|
105
|
+
let t = await f(e);
|
|
106
|
+
if (!d.has(t)) return t;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function m(e, t, n = 60) {
|
|
110
|
+
return new Promise((r, i) => {
|
|
111
|
+
let a = 0, o = () => {
|
|
112
|
+
a++;
|
|
113
|
+
let s = new u.Socket();
|
|
114
|
+
s.once("error", () => {
|
|
115
|
+
if (s.destroy(), a === n) {
|
|
116
|
+
i(/* @__PURE__ */ Error(`Timed out waiting for port ${e} to be available`));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
setTimeout(o, 500);
|
|
120
|
+
}), s.connect(e, t, () => {
|
|
121
|
+
s.destroy(), r();
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
o();
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function h(e) {
|
|
128
|
+
if (!(e instanceof Error)) return String(e);
|
|
129
|
+
let { cause: t } = e;
|
|
130
|
+
return t instanceof Error ? t.code || t.message || e.message : t === void 0 ? e.message : String(t);
|
|
131
|
+
}
|
|
132
|
+
function g(e, t = 60) {
|
|
133
|
+
return new Promise((n, r) => {
|
|
134
|
+
let i = 0, a = "no attempt made", o = async () => {
|
|
135
|
+
i++;
|
|
136
|
+
try {
|
|
137
|
+
let t = await fetch(`${e}/api/health`);
|
|
138
|
+
if (t.status === 200) {
|
|
139
|
+
n();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
a = `HTTP ${t.status}`;
|
|
143
|
+
} catch (e) {
|
|
144
|
+
a = h(e);
|
|
145
|
+
}
|
|
146
|
+
if (i === t) {
|
|
147
|
+
r(/* @__PURE__ */ Error(`Timed out waiting for health check at ${e}/api/health (last attempt: ${a})`));
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
setTimeout(o, 500);
|
|
151
|
+
};
|
|
152
|
+
o();
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/runtime/pocketbase.ts
|
|
157
|
+
var _ = 1100;
|
|
158
|
+
function v() {
|
|
159
|
+
return new Promise((e) => setTimeout(e, _));
|
|
160
|
+
}
|
|
161
|
+
function y(t, r, i) {
|
|
162
|
+
let o = `${r}_${t}.js`, s = a(n.join(i.root, e)).filter((e) => e.endsWith(o)).sort().pop();
|
|
163
|
+
if (s) return n.join(i.root, e, s);
|
|
164
|
+
}
|
|
165
|
+
function b(e) {
|
|
166
|
+
let t = n.join(e, "node_modules", ".vite", "_pocketbase_metadata.json");
|
|
167
|
+
return r(t) ? JSON.parse(i(t, "utf8")) : null;
|
|
168
|
+
}
|
|
169
|
+
async function x(e, t, n) {
|
|
170
|
+
let r = !1;
|
|
171
|
+
for (let i = 1; i <= 3; i++) try {
|
|
172
|
+
await e.collection("_superusers").authWithPassword(t, n), r = !0;
|
|
173
|
+
break;
|
|
174
|
+
} catch {
|
|
175
|
+
i < 3 && await new Promise((e) => setTimeout(e, 100));
|
|
176
|
+
}
|
|
177
|
+
if (!r) throw Error("Failed to authenticate with PocketBase. Check your superuser credentials.");
|
|
178
|
+
}
|
|
179
|
+
async function S(i, a) {
|
|
180
|
+
let u = n.join(i, t), d = n.join(i, e), f = "localhost";
|
|
181
|
+
if (!r(u)) throw Error("PocketBase data directory does not exist");
|
|
182
|
+
let h = b(i);
|
|
183
|
+
if (h && h.pocketbaseUrl) {
|
|
184
|
+
let e = new o(h.pocketbaseUrl);
|
|
185
|
+
await x(e, process.env.POCKETBASE_SUPERUSER_EMAIL, process.env.POCKETBASE_SUPERUSER_PASSWORD), await a(e);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
let _ = await p(f), v = [
|
|
189
|
+
"pocketbase-server",
|
|
190
|
+
"serve",
|
|
191
|
+
"--dir",
|
|
192
|
+
u,
|
|
193
|
+
"--migrationsDir",
|
|
194
|
+
d,
|
|
195
|
+
"--http",
|
|
196
|
+
`${f}:${_}`
|
|
197
|
+
], y = (await s({ cwd: i }))?.name ?? "npm", { command: S, args: w } = c(y, "execute", v);
|
|
198
|
+
y === "npm" && w.unshift("--yes");
|
|
199
|
+
let T = process.platform !== "win32", E = l(S, w, {
|
|
200
|
+
cwd: i,
|
|
201
|
+
stdio: "ignore",
|
|
202
|
+
detached: T
|
|
203
|
+
}), D = new Promise((e, t) => {
|
|
204
|
+
E.once("exit", (e, n) => {
|
|
205
|
+
t(/* @__PURE__ */ Error(`pocketbase-server exited before listening on ${f}:${_} (${n ?? `code ${e}`})`));
|
|
206
|
+
}), E.once("error", t);
|
|
207
|
+
});
|
|
208
|
+
try {
|
|
209
|
+
await Promise.race([(async () => {
|
|
210
|
+
await m(_, f), await g(`http://${f}:${_}`);
|
|
211
|
+
})(), D]);
|
|
212
|
+
let e = new o(`http://${f}:${_}`);
|
|
213
|
+
await x(e, process.env.POCKETBASE_SUPERUSER_EMAIL, process.env.POCKETBASE_SUPERUSER_PASSWORD), await a(e);
|
|
214
|
+
} finally {
|
|
215
|
+
C(E, T);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function C(e, t) {
|
|
219
|
+
if (t && e.pid) try {
|
|
220
|
+
process.kill(-e.pid, "SIGTERM");
|
|
221
|
+
return;
|
|
222
|
+
} catch {}
|
|
223
|
+
e.kill();
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
export { y as getMigrationFile, v as migrationDelay, S as withPocketbase };
|
|
227
|
+
|
|
228
|
+
//# sourceMappingURL=pocketbase-059B1oot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pocketbase-059B1oot.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC;AAED,SAAS,EAAe,GAA+B;CACrD,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAM,IAAS,EAAI,aAAa;EAGhC,AAFA,EAAO,MAAM,GACb,EAAO,KAAK,SAAS,CAAM,GAC3B,EAAO,OAAO,GAAG,SAAY;GAC3B,IAAM,EAAE,YAAS,EAAO,QAAQ;GAChC,EAAO,YAAY,EAAQ,CAAI,CAAC;EAClC,CAAC;CACH,CAAC;AACH;AAQA,eAAsB,EAAS,GAA+B;CAC5D,SAAS;EACP,IAAM,IAAO,MAAM,EAAe,CAAI;EACtC,IAAI,CAAC,EAAU,IAAI,CAAI,GAAG,OAAO;CACnC;AACF;AAIA,SAAgB,EACd,GACA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AAK,GAAG;CACb,GAEM,KAAkB,MAAM,EAAO,EAAE,OAAI,CAAC,EAAA,EAAI,QAAQ,OAClD,EAAE,YAAS,YAAS,EACxB,GACA,WACA,CACF;CAGA,AAAI,MAAmB,SAAO,EAAK,QAAQ,OAAO;CAMlD,IAAM,IAAW,QAAQ,aAAa,SAChC,IAAgB,EAAM,GAAS,GAAM;EACzC;EACA,OAAO;EACP;CACF,CAAC,GAIK,IAAS,IAAI,SAAgB,GAAG,MAAW;EAQ/C,AAPA,EAAc,KAAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,gDAAgD,EAAK,GAAG,EAAK,IAAI,KAAU,QAAQ,IAAO,EAC5F,CACF;EACF,CAAC,GACD,EAAc,KAAK,SAAS,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAM,EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAC9C,EAAA,CAAG,GACH,CACF,CAAC;EAED,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
@@ -15,7 +15,7 @@ async function n(e, t) {
|
|
|
15
15
|
exists: !0,
|
|
16
16
|
rowCount: 0
|
|
17
17
|
}));
|
|
18
|
-
let { withPocketbase: n } = await import("./pocketbase-
|
|
18
|
+
let { withPocketbase: n } = await import("./pocketbase-059B1oot.js"), { planCollectionDrops: r } = await import("./collections-1Z0NCLM-.js"), i = [];
|
|
19
19
|
return await n(t.root, async (t) => {
|
|
20
20
|
let n = await r(t, e);
|
|
21
21
|
i.push(...n);
|
|
@@ -24,4 +24,4 @@ async function n(e, t) {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { t as n, n as t };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=shared-
|
|
27
|
+
//# sourceMappingURL=shared-CaHmNkZE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-CaHmNkZE.js","names":[],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,6BAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as e, t } from "./errors-D6gyegUK.js";
|
|
2
2
|
import { n } from "./logger-CQONztPm.js";
|
|
3
|
-
import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-
|
|
3
|
+
import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-BHCOxcsA.js";
|
|
4
4
|
import f from "node:path";
|
|
5
5
|
import { existsSync as p, readFileSync as m, writeFileSync as h } from "node:fs";
|
|
6
6
|
import { createRequire as g } from "node:module";
|
|
@@ -170,4 +170,4 @@ async function N(e, t) {
|
|
|
170
170
|
//#endregion
|
|
171
171
|
export { M as applyBaseColor, N as applyTheme, C as listComponents, D as switchStyle };
|
|
172
172
|
|
|
173
|
-
//# sourceMappingURL=ui-
|
|
173
|
+
//# sourceMappingURL=ui-DAtVMiVs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui-DZS2SAQg.js","names":[],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;AA2CA,eAAsB,EAAW,GAAqC;CACpE,IAAI;CACJ,IAAI;EACF,IAAW,EAAc,EAAK,KAAK,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAAS,GAAO;EACd,IAAM,IAAS,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK;EACpE,MAAU,MACR,4CAA4C,EAAK,IAAI,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACT,EAAc,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAa,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,aAAa;CAAmB;CAC3D,MAAM,EAAE,MAAM,QAAQ;AACxB;AASA,eAAsB,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiB,KAAW,MAAM,EAAW,CAAI,GACnD,IAAS,EAAqB,CAAI,GAClC,IAAiC,EAAE,OAAO,EAAO,MAAM;CAK7D,OAJI,EAAO,cAAW,EAAQ,YAAY,EAAO,YAC7C,EAAO,gBAAa,EAAQ,cAAc,EAAO,cACjD,EAAO,cAAW,EAAQ,YAAY,EAAO,YAC7C,EAAO,eAAY,EAAQ,aAAa,EAAO,aAC5C,EAAa;EAAE,GAAG;EAAS,GAAG;CAAU,CAAC;AAClD;AAUA,eAAsB,EACpB,GACA,GACA,GACA,GACe;CAOf,AANA,MAAM,EACJ,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ACL,EAAQ,MACR;EAAE,WAAW,EAAQ;EAAO,OAAO,EAAQ;CAAM,GACjD,CACF;AACF;AAGA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EAAY,EAAQ,MAAM,EAAE,OAAO,EAAQ,MAAM,GAAG,CAAO;AACpE"}
|
|
1
|
+
{"version":3,"file":"ui-DAtVMiVs.js","names":[],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;AA2CA,eAAsB,EAAW,GAAqC;CACpE,IAAI;CACJ,IAAI;EACF,IAAW,EAAc,EAAK,KAAK,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAAS,GAAO;EACd,IAAM,IAAS,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK;EACpE,MAAU,MACR,4CAA4C,EAAK,IAAI,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACT,EAAc,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAa,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,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,EACb,GACA,GACA,GAC4B;CAC5B,IAAM,IAAS,MAAM,EAAW,CAAI;CAgBpC,AAfI,EAAU,aACZ,EACE,cACA,EAAU,WACV,EAAO,sBACT,GAEF,EAAY,SAAS,EAAU,OAAO,EAAO,iBAAiB,GAQ9D,MAAM,EAAY,GAAM,MALL,EACjB,GACA;EAAE,GAAG;EAAW,YAAY,EAAU;CAAM,GAC5C,CACF,GAC8B,CAAC,OAAO,GAAG,CAAO;CAEhD,IAAM,IAAS,EAAqB,CAAI;CACxC,OAAO;EACL,WAAW,EAAO,aAAa,EAAU,aAAa;EACtD,OAAO,EAAU;EACjB,eAAe,CAAC,EAAO,SAAS,CAAe;CACjD;AACF;AAOA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EACL,EAAQ,MACR;EAAE,WAAW,EAAQ;EAAO,OAAO,EAAQ;CAAM,GACjD,CACF;AACF;AAGA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EAAY,EAAQ,MAAM,EAAE,OAAO,EAAQ,MAAM,GAAG,CAAO;AACpE"}
|
|
@@ -375,7 +375,7 @@ async function nt(e, t, n) {
|
|
|
375
375
|
collectionDrops: []
|
|
376
376
|
}, o = [];
|
|
377
377
|
if (e.collectionDrops.length > 0) {
|
|
378
|
-
let { dropCollections: n } = await import("./collections-
|
|
378
|
+
let { dropCollections: n } = await import("./collections-1Z0NCLM-.js");
|
|
379
379
|
o = await n(e.collectionDrops, t);
|
|
380
380
|
}
|
|
381
381
|
let s = await Y(t.root, e.packages, n, r), l = await $({
|
|
@@ -442,4 +442,4 @@ async function nt(e, t, n) {
|
|
|
442
442
|
//#endregion
|
|
443
443
|
export { q as executeCommand, Z as formatPaths, H as getAllCustomComponents, $ as installComponents, $e as installedComponents, J as installedPackagesFromProject, X as isCustomComponent, b as n, C as t, nt as writeResult };
|
|
444
444
|
|
|
445
|
-
//# sourceMappingURL=write-result-
|
|
445
|
+
//# sourceMappingURL=write-result-BHCOxcsA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-result-Cb3r0sCO.js","names":[],"sources":["../../src/runtime/registry.ts","../../src/runtime/write-result.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type {\n Component,\n InstallComponentsOptions,\n InstallComponentsResult,\n Options,\n PackageManagerOperation,\n Result,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { formatSource } from \"../core/format-result\";\nimport { FORMSNAP, TANSTACK_TABLE_CORE } from \"../core/constants\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\n\ntype CustomNpmPackages = Record<string, string[]>;\n\n/**\n * The components under `src/ui/components` are copied into a project rather\n * than fetched from the shadcn-svelte registry, so their dependencies have to\n * be declared here: every `$lib/components/ui/<x>` import a component makes\n * must appear in `customDependencies`, and every npm package that no shadcn\n * item installs for it must appear in `customNpmPackages`.\n */\nconst customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\"],\n multiselect: [\"command\", \"popover\", \"button\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [\"badge\"],\n \"data-table\": [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n pagination: [\"button\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [FORMSNAP],\n multiselect: [FORMSNAP],\n geopoint: [],\n cells: [],\n // shadcn-svelte >= 1.2.0 resolves items from the style-scoped registry\n // (/registry/styles/<style>/), which has no `data-table` item, so the\n // TanStack helpers ship from here instead.\n \"data-table\": [TANSTACK_TABLE_CORE],\n \"column-header\": [TANSTACK_TABLE_CORE],\n \"faceted-filter\": [TANSTACK_TABLE_CORE],\n pagination: [TANSTACK_TABLE_CORE],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The components this package ships, by directory name, sorted. */\nexport function getAllCustomComponents(): Component[] {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string, root: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n pruneEmptyDirectories(path.dirname(filePath), root);\n}\n\n/**\n * Deleting a feature's files must also delete the directories it added, up\n * to the first one that still has content. The CLI detects features by\n * directory (`src/routes/(app)` means auth is on), so an empty leftover\n * directory keeps a disabled feature \"enabled\".\n */\nfunction pruneEmptyDirectories(dir: string, root: string): void {\n const stop = path.resolve(root);\n let current = path.resolve(dir);\n while (current !== stop && current.startsWith(stop)) {\n if (!existsSync(current) || readdirSync(current).length > 0) {\n return;\n }\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const resolved = resolveCommand(packageManager, operation, args);\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nexport async function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n if (runtime?.executeCommand) {\n await runtime.executeCommand(cwd, operation, args);\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args);\n}\n\n/** Package names `package.json` records, whichever dependency block they sit in. */\nexport function installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\n/**\n * Splits an npm install spec into its package name, dropping any range.\n * `wuchale@^0.26.3` -> `wuchale`, `@wuchale/svelte@^0.21.1` -> `@wuchale/svelte`.\n *\n * The name is what `package.json` records, so it -- not the full spec -- is what\n * the already-installed check has to compare against.\n */\nexport function packageName(spec: string): string {\n const at = spec.indexOf(\"@\", spec.startsWith(\"@\") ? 1 : 0);\n return at === -1 ? spec : spec.slice(0, at);\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter(\n (pkg) => !installed.has(packageName(pkg)),\n );\n if (toInstall.length === 0) {\n return [];\n }\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n await executeCommand(root, \"install\", toInstall, runtime);\n return toInstall;\n}\n\nexport function isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\nconst FORMATTABLE_EXTENSIONS = new Set([\n \".ts\",\n \".js\",\n \".svelte\",\n \".json\",\n \".css\",\n]);\n\nfunction* filesUnder(target: string): Generator<string> {\n if (!existsSync(target)) {\n return;\n }\n if (statSync(target).isFile()) {\n yield target;\n return;\n }\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n yield path.join(entry.parentPath, entry.name);\n }\n }\n}\n\n/**\n * `shadcn-svelte add` and `apply` write files in the registry's style and the\n * bundled components carry this repo's; the project's `npm run lint` expects\n * its own. Runs the project's prettier over the given files and directories\n * (relative to the root or absolute) and returns the relative paths it\n * changed. Paths that do not exist are skipped.\n */\nexport async function formatPaths(\n root: string,\n paths: string[],\n): Promise<string[]> {\n const context = { env: \"runtime\" as const, root };\n const changed: string[] = [];\n for (const target of paths) {\n for (const filePath of filesUnder(toTargetPath(root, target))) {\n if (!FORMATTABLE_EXTENSIONS.has(path.extname(filePath))) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const formatted = await formatSource(content, filePath, context);\n if (formatted !== content) {\n writeFileSync(filePath, formatted, \"utf8\");\n changed.push(path.relative(root, filePath));\n }\n }\n }\n return changed;\n}\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * the way SvelteKit resolves `$lib` (`src/lib`). Anything else (a custom\n * `kit.alias`, a missing or unreadable config) falls back to the default so\n * the existence check here and shadcn's own target agree for every project\n * the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n if (alias === \"$lib\") {\n return path.join(root, \"src\", \"lib\");\n }\n if (alias?.startsWith(\"$lib/\")) {\n return path.join(root, \"src\", \"lib\", ...alias.slice(5).split(\"/\"));\n }\n return path.join(root, ...DEFAULT_UI_DIR);\n}\n\n/** The component directories a project has, sorted. */\nexport function installedComponents(root: string): Component[] {\n const uiDir = resolveUiDir(root);\n if (!existsSync(uiDir)) {\n return [];\n }\n return readdirSync(uiDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Bare item names are checked against the index; URLs and `@scope/item` are shadcn's to resolve. */\nconst BARE_ITEM_NAME = /^[a-z0-9][a-z0-9-]*$/i;\n\n/**\n * A name the style's registry does not list would otherwise reach\n * `shadcn-svelte add`, which fails after a fetch with a message that never\n * mentions the style. Skipped when the registry cannot be read: shadcn will\n * report that itself.\n */\nasync function assertKnownRegistryItems(\n root: string,\n components: Component[],\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n const bare = components.filter((component) => BARE_ITEM_NAME.test(component));\n if (bare.length === 0) {\n return;\n }\n let known: Set<string>;\n try {\n const index = await fetchRegistryIndex(root, { runtime });\n known = new Set(index.map((item) => item.name));\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n logger.info(`${error.message}; leaving component names to shadcn-svelte`);\n return;\n }\n const unknown = bare.filter((component) => !known.has(component));\n if (unknown.length === 0) {\n return;\n }\n const { style } = readComponentsConfig(root);\n const names = unknown.map((component) => `\"${component}\"`).join(\", \");\n throw new InvalidArgumentError(\n `Unknown component${unknown.length > 1 ? \"s\" : \"\"} ${names} for style ${style}. Run \\`vela ui list\\` to see what is available.`,\n );\n}\n\nexport async function installComponents(\n options: InstallComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<InstallComponentsResult> {\n const { root, components, overwrite = false } = options;\n const logger = getLogger(options);\n\n const requested = [...new Set(components)];\n if (requested.length === 0) {\n return { installed: [], skipped: [], packages: [] };\n }\n\n const componentsDir = resolveUiDir(root);\n mkdirSync(componentsDir, { recursive: true });\n const isPresent = (component: string) =>\n existsSync(path.join(componentsDir, component));\n\n const skipped = overwrite ? [] : requested.filter(isPresent);\n const toInstall = requested.filter(\n (component) => !skipped.includes(component),\n );\n if (skipped.length > 0) {\n logger.info(`Already present: ${skipped.join(\", \")}`);\n }\n if (toInstall.length === 0) {\n return { installed: [], skipped, packages: [] };\n }\n\n const customToInstall = new Set(toInstall.filter(isCustomComponent));\n const publicToInstall = new Set(\n toInstall.filter((component) => !isCustomComponent(component)),\n );\n\n // Dependencies are added only when missing, even under `overwrite`:\n // re-adding `button` because `pagination` was re-added would clobber edits\n // the user never asked to lose.\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (isPresent(dependency)) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n const installed: string[] = [];\n const customList = [...customToInstall].sort();\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installed.push(component);\n publicToInstall.delete(component);\n }\n\n const packages = await installPackages(\n root,\n customNpmPackagesFor(customList),\n runtime,\n logger,\n );\n\n const publicList = [...publicToInstall].sort();\n if (publicList.length > 0) {\n await assertKnownRegistryItems(root, publicList, runtime, logger);\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"add\", \"--yes\", \"--overwrite\", ...publicList],\n runtime,\n );\n installed.push(...publicList);\n }\n\n const installedList = [...new Set(installed)].sort();\n await formatPaths(\n root,\n installedList.map((component) => path.join(componentsDir, component)),\n );\n\n return { installed: installedList, skipped, packages };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n dropMigrationCreates = await dropCollections(\n result.collectionDrops,\n options,\n );\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await installComponents(\n { root: options.root, components: result.components, logger },\n runtime,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") {\n // A modifier that could not recognise the file it was asked to edit\n // reports `failed` / `not-found` with a paste-ready remediation snippet.\n // Nothing is written, but the entry has to survive into the result: this\n // loop used to `continue` before pushing, so the entry never reached the\n // caller at all and the snippet was lost. The pattern reported success\n // and simply said nothing about the file it had given up on.\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (readFileSync(target, \"utf8\") !== file.content) {\n writeFile(target, file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (file.status !== \"success\") {\n // Carried through unwritten, so the caller can report the failure. See\n // the note in the creates loop above.\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") {\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path), options.root);\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.installed,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n };\n}\n"],"mappings":";;;;;;;;;AAcA,IAAM,IAAsB;AAwB5B,SAAS,EAAe,GAAoC;CAC1D,OAAO,OAAO,KAAU,YAAY,EAAM,SAAS,IAAI,IAAQ,KAAA;AACjE;AAOA,SAAgB,EAAqB,GAAgC;CACnE,IAAI,IAA2B,CAAC,GAC1B,IAAa,EAAK,KAAK,GAAM,iBAAiB;CACpD,IAAI,EAAW,CAAU,GACvB,IAAI;EACF,IAAM,IAAkB,KAAK,MAAM,EAAa,GAAY,MAAM,CAAC;EACnE,AAAI,KAAU,OAAO,KAAW,aAC9B,IAAM;CAEV,QAAQ;EACN,IAAM,CAAC;CACT;CAGF,IAAM,IAAkC,CAAC;CACzC,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,EAAI,WAAW,CAAC,CAAC,GAAG;EAC5D,IAAM,IAAQ,EAAe,CAAK;EAClC,AAAI,MAAO,EAAQ,KAAO;CAC5B;CAEA,OAAO;EACL,OAAO,EAAe,EAAI,KAAK,KAAA;EAC/B,UAAU,EAAe,EAAI,QAAQ,KAAA;EACrC,WAAW,EAAe,EAAI,UAAU,SAAS;EACjD,aAAa,EAAe,EAAI,WAAW;EAC3C,WAAW,EAAe,EAAI,SAAS;EACvC,YAAY,EAAe,EAAI,UAAU;EACzC;EACA,SAAS,EAAe,EAAI,UAAU,GAAG,KAAA;CAC3C;AACF;AAGA,SAAgB,EAAiB,GAAkB,GAAuB;CACxE,OAAO,GAAG,EAAS,QAAQ,QAAQ,EAAE,EAAE,UAAU,mBAAmB,CAAK,EAAE;AAC7E;AAOA,IAAM,oBAAa,IAAI,QAGrB;AAEF,SAAS,GAAW,GAA+B;CACjD,IAAI,CAAC,MAAM,QAAQ,CAAI,GACrB,MAAU,MAAM,yBAAyB;CAE3C,IAAM,IAAwB,CAAC;CAC/B,KAAK,IAAM,KAAS,G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AC9B,EAAc,SAAS,KAAK;GAC1B,GAAG;GACH,MAAM,EAAe,EAAQ,MAAM,EAAK,IAAI;EAC9C,CAAC;CAEL;CAEA,KAAK,IAAM,KAAQ,EAAO,UAAU;EAClC,IAAI,EAAK,WAAW,WAAW;GAG7B,EAAc,SAAS,KAAK;IAC1B,GAAG;IACH,MAAM,EAAe,EAAQ,MAAM,EAAK,IAAI;GAC9C,CAAC;GACD;EACF;EAEA,AADA,EAAU,EAAa,EAAQ,MAAM,EAAK,IAAI,GAAG,EAAK,OAAO,GAC7D,EAAc,SAAS,KAAK;GAC1B,GAAG;GACH,MAAM,EAAe,EAAQ,MAAM,EAAK,IAAI;EAC9C,CAAC;CACH;CAEA,KAAK,IAAM,KAAQ,EAAO,SAAS;EACjC,IAAI,EAAK,WAAW,WAAW;GAC7B,EAAc,QAAQ,KAAK;IACzB,GAAG;IACH,MAAM,EAAe,EAAQ,MAAM,EAAK,IAAI;GAC9C,CAAC;GACD;EACF;EACA,AAAI,EAAW,EAAa,EAAQ,MAAM,EAAK,IAAI,CAAC,MAClD,GAAW,EAAa,EAAQ,MAAM,EAAK,IAAI,GAAG,EAAQ,IAAI,GAC9D,EAAc,QAAQ,KAAK;GACzB,GAAG;GACH,MAAM,EAAe,EAAQ,MAAM,EAAK,IAAI;EAC9C,CAAC;CAEL;CAEA,OAAO;EACL,GAAG;EACH,SAAS,EAAc;EACvB,UAAU,EAAc;EACxB,SAAS,EAAc;EACvB,YAAY,EAAkB;EAC9B,UAAU,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,GAAiB,GAAG,EAAkB,QAAQ,CAAC,CAAC;CAC5E;AACF"}
|
|
1
|
+
{"version":3,"file":"write-result-BHCOxcsA.js","names":[],"sources":["../../src/runtime/registry.ts","../../src/runtime/write-result.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type {\n Component,\n InstallComponentsOptions,\n InstallComponentsResult,\n Options,\n PackageManagerOperation,\n Result,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { formatSource } from \"../core/format-result\";\nimport { FORMSNAP, TANSTACK_TABLE_CORE } from \"../core/constants\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\n\ntype CustomNpmPackages = Record<string, string[]>;\n\n/**\n * The components under `src/ui/components` are copied into a project rather\n * than fetched from the shadcn-svelte registry, so their dependencies have to\n * be declared here: every `$lib/components/ui/<x>` import a component makes\n * must appear in `customDependencies`, and every npm package that no shadcn\n * item installs for it must appear in `customNpmPackages`.\n */\nconst customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\"],\n multiselect: [\"command\", \"popover\", \"button\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [\"badge\"],\n \"data-table\": [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n pagination: [\"button\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [FORMSNAP],\n multiselect: [FORMSNAP],\n geopoint: [],\n cells: [],\n // shadcn-svelte >= 1.2.0 resolves items from the style-scoped registry\n // (/registry/styles/<style>/), which has no `data-table` item, so the\n // TanStack helpers ship from here instead.\n \"data-table\": [TANSTACK_TABLE_CORE],\n \"column-header\": [TANSTACK_TABLE_CORE],\n \"faceted-filter\": [TANSTACK_TABLE_CORE],\n pagination: [TANSTACK_TABLE_CORE],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The components this package ships, by directory name, sorted. */\nexport function getAllCustomComponents(): Component[] {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string, root: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n pruneEmptyDirectories(path.dirname(filePath), root);\n}\n\n/**\n * Deleting a feature's files must also delete the directories it added, up\n * to the first one that still has content. The CLI detects features by\n * directory (`src/routes/(app)` means auth is on), so an empty leftover\n * directory keeps a disabled feature \"enabled\".\n */\nfunction pruneEmptyDirectories(dir: string, root: string): void {\n const stop = path.resolve(root);\n let current = path.resolve(dir);\n while (current !== stop && current.startsWith(stop)) {\n if (!existsSync(current) || readdirSync(current).length > 0) {\n return;\n }\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const resolved = resolveCommand(packageManager, operation, args);\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nexport async function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n if (runtime?.executeCommand) {\n await runtime.executeCommand(cwd, operation, args);\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args);\n}\n\n/** Package names `package.json` records, whichever dependency block they sit in. */\nexport function installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\n/**\n * Splits an npm install spec into its package name, dropping any range.\n * `wuchale@^0.26.3` -> `wuchale`, `@wuchale/svelte@^0.21.1` -> `@wuchale/svelte`.\n *\n * The name is what `package.json` records, so it -- not the full spec -- is what\n * the already-installed check has to compare against.\n */\nexport function packageName(spec: string): string {\n const at = spec.indexOf(\"@\", spec.startsWith(\"@\") ? 1 : 0);\n return at === -1 ? spec : spec.slice(0, at);\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter(\n (pkg) => !installed.has(packageName(pkg)),\n );\n if (toInstall.length === 0) {\n return [];\n }\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n await executeCommand(root, \"install\", toInstall, runtime);\n return toInstall;\n}\n\nexport function isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\nconst FORMATTABLE_EXTENSIONS = new Set([\n \".ts\",\n \".js\",\n \".svelte\",\n \".json\",\n \".css\",\n]);\n\nfunction* filesUnder(target: string): Generator<string> {\n if (!existsSync(target)) {\n return;\n }\n if (statSync(target).isFile()) {\n yield target;\n return;\n }\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n yield path.join(entry.parentPath, entry.name);\n }\n }\n}\n\n/**\n * `shadcn-svelte add` and `apply` write files in the registry's style and the\n * bundled components carry this repo's; the project's `npm run lint` expects\n * its own. Runs the project's prettier over the given files and directories\n * (relative to the root or absolute) and returns the relative paths it\n * changed. Paths that do not exist are skipped.\n */\nexport async function formatPaths(\n root: string,\n paths: string[],\n): Promise<string[]> {\n const context = { env: \"runtime\" as const, root };\n const changed: string[] = [];\n for (const target of paths) {\n for (const filePath of filesUnder(toTargetPath(root, target))) {\n if (!FORMATTABLE_EXTENSIONS.has(path.extname(filePath))) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const formatted = await formatSource(content, filePath, context);\n if (formatted !== content) {\n writeFileSync(filePath, formatted, \"utf8\");\n changed.push(path.relative(root, filePath));\n }\n }\n }\n return changed;\n}\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * the way SvelteKit resolves `$lib` (`src/lib`). Anything else (a custom\n * `kit.alias`, a missing or unreadable config) falls back to the default so\n * the existence check here and shadcn's own target agree for every project\n * the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n if (alias === \"$lib\") {\n return path.join(root, \"src\", \"lib\");\n }\n if (alias?.startsWith(\"$lib/\")) {\n return path.join(root, \"src\", \"lib\", ...alias.slice(5).split(\"/\"));\n }\n return path.join(root, ...DEFAULT_UI_DIR);\n}\n\n/** The component directories a project has, sorted. */\nexport function installedComponents(root: string): Component[] {\n const uiDir = resolveUiDir(root);\n if (!existsSync(uiDir)) {\n return [];\n }\n return readdirSync(uiDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Bare item names are checked against the index; URLs and `@scope/item` are shadcn's to resolve. */\nconst BARE_ITEM_NAME = /^[a-z0-9][a-z0-9-]*$/i;\n\n/**\n * A name the style's registry does not list would otherwise reach\n * `shadcn-svelte add`, which fails after a fetch with a message that never\n * mentions the style. Skipped when the registry cannot be read: shadcn will\n * report that itself.\n */\nasync function assertKnownRegistryItems(\n root: string,\n components: Component[],\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n const bare = components.filter((component) => BARE_ITEM_NAME.test(component));\n if (bare.length === 0) {\n return;\n }\n let known: Set<string>;\n try {\n const index = await fetchRegistryIndex(root, { runtime });\n known = new Set(index.map((item) => item.name));\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n logger.info(`${error.message}; leaving component names to shadcn-svelte`);\n return;\n }\n const unknown = bare.filter((component) => !known.has(component));\n if (unknown.length === 0) {\n return;\n }\n const { style } = readComponentsConfig(root);\n const names = unknown.map((component) => `\"${component}\"`).join(\", \");\n throw new InvalidArgumentError(\n `Unknown component${unknown.length > 1 ? \"s\" : \"\"} ${names} for style ${style}. Run \\`vela ui list\\` to see what is available.`,\n );\n}\n\nexport async function installComponents(\n options: InstallComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<InstallComponentsResult> {\n const { root, components, overwrite = false } = options;\n const logger = getLogger(options);\n\n const requested = [...new Set(components)];\n if (requested.length === 0) {\n return { installed: [], skipped: [], packages: [] };\n }\n\n const componentsDir = resolveUiDir(root);\n mkdirSync(componentsDir, { recursive: true });\n const isPresent = (component: string) =>\n existsSync(path.join(componentsDir, component));\n\n const skipped = overwrite ? [] : requested.filter(isPresent);\n const toInstall = requested.filter(\n (component) => !skipped.includes(component),\n );\n if (skipped.length > 0) {\n logger.info(`Already present: ${skipped.join(\", \")}`);\n }\n if (toInstall.length === 0) {\n return { installed: [], skipped, packages: [] };\n }\n\n const customToInstall = new Set(toInstall.filter(isCustomComponent));\n const publicToInstall = new Set(\n toInstall.filter((component) => !isCustomComponent(component)),\n );\n\n // Dependencies are added only when missing, even under `overwrite`:\n // re-adding `button` because `pagination` was re-added would clobber edits\n // the user never asked to lose.\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (isPresent(dependency)) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n const installed: string[] = [];\n const customList = [...customToInstall].sort();\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installed.push(component);\n publicToInstall.delete(component);\n }\n\n const packages = await installPackages(\n root,\n customNpmPackagesFor(customList),\n runtime,\n logger,\n );\n\n const publicList = [...publicToInstall].sort();\n if (publicList.length > 0) {\n await assertKnownRegistryItems(root, publicList, runtime, logger);\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"add\", \"--yes\", \"--overwrite\", ...publicList],\n runtime,\n );\n installed.push(...publicList);\n }\n\n const installedList = [...new Set(installed)].sort();\n await formatPaths(\n root,\n installedList.map((component) => path.join(componentsDir, component)),\n );\n\n return { installed: installedList, skipped, packages };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n dropMigrationCreates = await dropCollections(\n result.collectionDrops,\n options,\n );\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await installComponents(\n { root: options.root, components: result.components, logger },\n runtime,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") {\n // A modifier that could not recognise the file it was asked to edit\n // reports `failed` / `not-found` with a paste-ready remediation snippet.\n // Nothing is written, but the entry has to survive into the result: this\n // loop used to `continue` before pushing, so the entry never reached the\n // caller at all and the snippet was lost. The pattern reported success\n // and simply said nothing about the file it had given up on.\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (readFileSync(target, \"utf8\") !== file.content) {\n writeFile(target, file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (file.status !== \"success\") {\n // Carried through unwritten, so the caller can report the failure. See\n // the note in the creates loop above.\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") {\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path), options.root);\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.installed,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n };\n}\n"],"mappings":";;;;;;;;;AAcA,IAAM,IAAsB;AAwB5B,SAAS,EAAe,GAAoC;CAC1D,OAAO,OAAO,KAAU,YAAY,EAAM,SAAS,IAAI,IAAQ,KAAA;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