@leotang92/dsh-claude-slides 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +27 -0
  2. package/NOTICE.md +25 -0
  3. package/README.md +21 -2
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +26 -0
  6. package/docs/DETAIL.zh.md +16 -0
  7. package/icon.svg +9 -0
  8. package/lib/client.js +1800 -0
  9. package/lib/index.js +878 -0
  10. package/locale/en.json +7 -0
  11. package/locale/zh.json +7 -0
  12. package/package.json +68 -4
  13. package/skills/claude-slides/SKILL.md +224 -0
  14. package/skills/claude-slides/artifact-type/reference/craft.md +185 -0
  15. package/skills/claude-slides/artifact-type/reference/deck-files.md +48 -0
  16. package/skills/claude-slides/artifact-type/reference/diagram-recipes.md +60 -0
  17. package/skills/claude-slides/artifact-type/reference/diagrams.md +109 -0
  18. package/skills/claude-slides/artifact-type/reference/fonts.md +91 -0
  19. package/skills/claude-slides/artifact-type/reference/format.md +95 -0
  20. package/skills/claude-slides/artifact-type/reference/google-fonts-families.json +1 -0
  21. package/skills/claude-slides/artifact-type/reference/google-fonts-notices.json +1 -0
  22. package/skills/claude-slides/artifact-type/reference/google-fonts-reserved.json +1 -0
  23. package/skills/claude-slides/artifact-type/reference/images.md +77 -0
  24. package/skills/claude-slides/artifact-type/reference/layout.md +100 -0
  25. package/skills/claude-slides/artifact-type/reference/photo-library.md +32 -0
  26. package/skills/claude-slides/artifact-type/reference/questions.md +72 -0
  27. package/skills/claude-slides/artifact-type/reference/styles.md +41 -0
  28. package/skills/claude-slides/artifact-type/reference/view-state.md +77 -0
  29. package/skills/claude-slides/scripts/artifact.mjs +3785 -0
  30. package/skills/claude-slides/scripts/editor/artifact-type/reference/google-fonts-families.json +1 -0
  31. package/skills/claude-slides/scripts/editor/artifact-type/reference/google-fonts-notices.json +1 -0
  32. package/skills/claude-slides/scripts/editor/artifact-type/reference/google-fonts-reserved.json +1 -0
  33. package/skills/claude-slides/scripts/editor/assets/anthropicons-fizzy-lake-D4byUNVq.woff2 +0 -0
  34. package/skills/claude-slides/scripts/editor/assets/index-7OEzB54c.js +3778 -0
  35. package/skills/claude-slides/scripts/editor/assets/index-DX-X-CY8.css +1 -0
  36. package/skills/claude-slides/scripts/editor/assets/woff2-decoder-BvG5IStQ.js +17 -0
  37. package/skills/claude-slides/scripts/editor/index.html +17 -0
  38. package/skills/claude-slides/scripts/editor/node/compiler.cjs +284636 -0
  39. package/skills/claude-slides/scripts/editor/node/third-party-licenses.txt +1926 -0
  40. package/skills/claude-slides/scripts/editor/share-ui.js +208 -0
  41. package/skills/claude-slides/scripts/editor/third-party-licenses.txt +1693 -0
  42. package/skills/claude-slides/scripts/server.mjs +5195 -0
@@ -0,0 +1,3785 @@
1
+ #!/usr/bin/env node
2
+ // claude-slides: local Artifact tool (prebuilt; do not edit).
3
+
4
+ import fs13 from "node:fs";
5
+ import fsp3 from "node:fs/promises";
6
+ import path15 from "node:path";
7
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
8
+
9
+ var BLOB_ID_PATTERN = /^[0-9a-f]{32}$/;
10
+ function isProjectPath(p) {
11
+ if (!p.startsWith("project/") || p.includes("\\") || p.includes("\0")) return false;
12
+ return p.split("/").every((part) => part !== "" && part !== "." && part !== "..");
13
+ }
14
+ function isWriteEntry(entry) {
15
+ return entry !== null && !("delete" in entry);
16
+ }
17
+
18
+ import fs from "node:fs/promises";
19
+ import path from "node:path";
20
+ function deckReferenceProblems(deck, slideFiles) {
21
+ const problems = [];
22
+ const seen = /* @__PURE__ */ new Set();
23
+ for (const id of deck.order) {
24
+ if (seen.has(id)) problems.push(`order \u91CC ${id} \u91CD\u590D`);
25
+ seen.add(id);
26
+ if (!slideFiles.has(id)) problems.push(`order \u91CC\u7684 ${id} \u6CA1\u6709\u5BF9\u5E94\u7684 slides/${id}.html`);
27
+ }
28
+ for (const [key, section] of Object.entries(deck.sections)) {
29
+ if (!seen.has(section.start)) problems.push(`\u7AE0\u8282 ${key} \u7684 start\u300C${section.start}\u300D\u4E0D\u5728 order \u91CC`);
30
+ }
31
+ if (deck.cover !== void 0 && !seen.has(deck.cover)) problems.push(`cover\u300C${deck.cover}\u300D\u4E0D\u5728 order \u91CC`);
32
+ return problems;
33
+ }
34
+ var DECK_FILE = "deck.json";
35
+ function isDeckMetadata(value) {
36
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
37
+ const deck = value;
38
+ return deck.v === 4 && Array.isArray(deck.order);
39
+ }
40
+ async function readDeckSummary(dir) {
41
+ const file = path.join(dir, DECK_FILE);
42
+ try {
43
+ const stat = await fs.lstat(file);
44
+ if (!stat.isFile() || stat.size > 4 * 1024 * 1024) return null;
45
+ const parsed = JSON.parse(await fs.readFile(file, "utf8"));
46
+ if (!isDeckMetadata(parsed)) return null;
47
+ const title = typeof parsed.title === "string" ? parsed.title.trim() : "";
48
+ return { title, slideCount: parsed.order.filter((id) => typeof id === "string").length };
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ import { createHash, randomUUID } from "node:crypto";
55
+ import { lstat, mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
56
+ import path2 from "node:path";
57
+ var MIME = {
58
+ html: "text/html",
59
+ htm: "text/html",
60
+ json: "application/json",
61
+ css: "text/css",
62
+ js: "text/javascript",
63
+ mjs: "text/javascript",
64
+ md: "text/markdown",
65
+ txt: "text/plain",
66
+ xml: "application/xml",
67
+ svg: "image/svg+xml",
68
+ png: "image/png",
69
+ jpg: "image/jpeg",
70
+ jpeg: "image/jpeg",
71
+ gif: "image/gif",
72
+ webp: "image/webp",
73
+ avif: "image/avif",
74
+ ico: "image/x-icon",
75
+ woff2: "font/woff2",
76
+ woff: "font/woff",
77
+ ttf: "font/ttf",
78
+ otf: "font/otf",
79
+ mp3: "audio/mpeg",
80
+ wav: "audio/wav",
81
+ mp4: "video/mp4",
82
+ webm: "video/webm",
83
+ mov: "video/quicktime",
84
+ pdf: "application/pdf",
85
+ wasm: "application/wasm"
86
+ };
87
+ var EXT_BY_MIME = {
88
+ "image/svg+xml": "svg",
89
+ "image/png": "png",
90
+ "image/jpeg": "jpg",
91
+ "image/gif": "gif",
92
+ "image/webp": "webp",
93
+ "image/avif": "avif",
94
+ "font/woff2": "woff2",
95
+ "font/woff": "woff",
96
+ "font/ttf": "ttf",
97
+ "font/otf": "otf",
98
+ "video/mp4": "mp4",
99
+ "video/webm": "webm",
100
+ "video/quicktime": "mov",
101
+ "image/x-icon": "ico",
102
+ "audio/mpeg": "mp3",
103
+ "audio/wav": "wav",
104
+ "application/pdf": "pdf"
105
+ };
106
+ var ASSETS_DIR = "assets";
107
+ var ASSET_INDEX = "index.json";
108
+ function contentTypeOf(file) {
109
+ const ext = file.slice(file.lastIndexOf(".") + 1).toLowerCase();
110
+ return MIME[ext] ?? "application/octet-stream";
111
+ }
112
+ function assetExtensionOf(contentType) {
113
+ return EXT_BY_MIME[contentType.split(";")[0].trim().toLowerCase()] ?? "bin";
114
+ }
115
+ function sha256(bytes) {
116
+ return createHash("sha256").update(bytes).digest("hex");
117
+ }
118
+ function isDeckFile(rel) {
119
+ const parts = rel.split("/");
120
+ if (parts.some((part) => part === "" || part === "." || part === ".." || part.startsWith("."))) return false;
121
+ if (rel === "deck.json") return true;
122
+ if (parts[0] === "slides") return parts.length === 2 && parts[1].endsWith(".html");
123
+ return parts[0] === "ds" && parts.length > 1;
124
+ }
125
+ var DECK_LAYOUT = {
126
+ isFile: isDeckFile,
127
+ roots: [
128
+ { rel: "", descend: false },
129
+ { rel: "slides", descend: false },
130
+ { rel: "ds", descend: true }
131
+ ],
132
+ watches: (rel) => rel === "slides" || rel === "ds" || isDeckFile(rel),
133
+ readOnlyMessage: (p) => `${p}: only deck.json, slides/*.html and ds/** can be written`
134
+ };
135
+ async function collectFiles(root, layout, limit) {
136
+ const rels = [];
137
+ const seen = /* @__PURE__ */ new Set();
138
+ let truncated = false;
139
+ const visit = async (relDir, descend) => {
140
+ const dir = relDir === "" ? root : path2.join(root, ...relDir.split("/"));
141
+ let entries;
142
+ try {
143
+ entries = await readdir(dir, { withFileTypes: true });
144
+ } catch {
145
+ return;
146
+ }
147
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
148
+ for (const entry of entries) {
149
+ if (truncated) return;
150
+ if (entry.name.startsWith(".")) continue;
151
+ const rel = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
152
+ if (entry.isDirectory()) {
153
+ if (descend && (layout.descendInto?.(rel) ?? true)) await visit(rel, true);
154
+ } else if (entry.isFile() && layout.isFile(rel) && !seen.has(rel)) {
155
+ if (rels.length >= limit) {
156
+ truncated = true;
157
+ return;
158
+ }
159
+ seen.add(rel);
160
+ rels.push(rel);
161
+ }
162
+ }
163
+ };
164
+ for (const start of layout.roots) {
165
+ if (truncated) break;
166
+ await visit(start.rel, start.descend);
167
+ }
168
+ return { rels, truncated };
169
+ }
170
+ async function writeFileAtomic(file, bytes) {
171
+ await mkdir(path2.dirname(file), { recursive: true });
172
+ const tmp = path2.join(path2.dirname(file), `.${path2.basename(file)}.${randomUUID()}.tmp`);
173
+ try {
174
+ await writeFile(tmp, bytes);
175
+ await rename(tmp, file);
176
+ } catch (error) {
177
+ await rm(tmp, { force: true }).catch(() => {
178
+ });
179
+ throw error;
180
+ }
181
+ }
182
+ var DeckStore = class {
183
+ /** deck 目录(含 deck.json 的那一层),或设计稿目录(含 canvas.json 的那一层)。 */
184
+ root;
185
+ layout;
186
+ /** 本进程刚写过的文件(运行时路径)→ 写入时的 sha(删除记为 ""),用来区分「编辑器自己保存」和「外部改动」。 */
187
+ ownWrites = /* @__PURE__ */ new Map();
188
+ queue = Promise.resolve();
189
+ seq = 0;
190
+ onTruncated;
191
+ truncationReported = false;
192
+ constructor(root, layout = DECK_LAYOUT, options = {}) {
193
+ this.root = root;
194
+ this.layout = layout;
195
+ this.onTruncated = options.onTruncated;
196
+ }
197
+ /** 上传素材所在的子目录。 */
198
+ get blobDir() {
199
+ return this.layout.blobDir ?? ASSETS_DIR;
200
+ }
201
+ /** 运行时路径 → 目录里的相对路径;不是这个布局可读写的文件时 null。 */
202
+ fileOf(runtimePath) {
203
+ if (!isProjectPath(runtimePath)) return null;
204
+ const rel = runtimePath.slice("project/".length);
205
+ return this.layout.isFile(rel) ? rel : null;
206
+ }
207
+ /**
208
+ * deck 目录里一个文件的磁盘路径(文件本身可以还不存在)。路径上任何一段是符号链接、或这个名字不是普通文件时 null。
209
+ */
210
+ async diskPath(rel) {
211
+ const realRoot = await realpath(this.root).catch(() => null);
212
+ if (realRoot === null) return null;
213
+ const file = path2.join(realRoot, ...rel.split("/"));
214
+ for (let dir = path2.dirname(file); ; dir = path2.dirname(dir)) {
215
+ const real = await realpath(dir).catch(() => null);
216
+ if (real === null) continue;
217
+ if (real !== dir) return null;
218
+ break;
219
+ }
220
+ const info = await lstat(file).catch(() => null);
221
+ return info && !info.isFile() ? null : file;
222
+ }
223
+ async listing() {
224
+ const limit = this.layout.maxFiles ?? Number.POSITIVE_INFINITY;
225
+ const { rels, truncated } = await collectFiles(this.root, this.layout, limit);
226
+ if (truncated && !this.truncationReported) {
227
+ this.truncationReported = true;
228
+ this.onTruncated?.(limit);
229
+ }
230
+ const files = {};
231
+ for (const rel of rels.sort()) {
232
+ const file = await this.diskPath(rel);
233
+ if (file === null) continue;
234
+ const bytes = await readFile(file).catch(() => null);
235
+ if (bytes === null) continue;
236
+ files[`project/${rel}`] = { sha256: sha256(bytes), size: bytes.length, contentType: contentTypeOf(rel) };
237
+ }
238
+ return { ver: versionOf(files), files };
239
+ }
240
+ async readProjectFile(p) {
241
+ const rel = this.fileOf(p);
242
+ const file = rel === null ? null : await this.diskPath(rel);
243
+ if (file === null) return null;
244
+ try {
245
+ return await readFile(file);
246
+ } catch {
247
+ return null;
248
+ }
249
+ }
250
+ /** 串行执行,保证 ifMatch 检查和写入之间没有交错。 */
251
+ publish(files) {
252
+ const run = this.queue.then(() => this.publishNow(files));
253
+ this.queue = run.catch(() => void 0);
254
+ return run;
255
+ }
256
+ async publishNow(batch) {
257
+ const files = /* @__PURE__ */ new Map();
258
+ let total = 0;
259
+ const maxFileBytes = this.layout.maxFileBytes;
260
+ for (const [p, entry] of Object.entries(batch)) {
261
+ const rel = this.fileOf(p);
262
+ const file = rel === null ? null : await this.diskPath(rel);
263
+ if (file === null) {
264
+ return { status: 400, body: { code: "read_only_path", message: this.layout.readOnlyMessage(p) } };
265
+ }
266
+ files.set(p, file);
267
+ if (!isWriteEntry(entry)) continue;
268
+ const bytes = Buffer.byteLength(entry.base64, "base64");
269
+ if (maxFileBytes !== void 0 && bytes > maxFileBytes) {
270
+ return { status: 413, body: { code: "too_large", message: `${p}: a file can be at most ${maxFileBytes} bytes` } };
271
+ }
272
+ total += bytes;
273
+ }
274
+ const maxBytes = this.layout.maxPublishBytes;
275
+ if (maxBytes !== void 0 && total > maxBytes) {
276
+ return { status: 413, body: { code: "too_large", message: `a publish can write at most ${maxBytes} bytes` } };
277
+ }
278
+ const before = await this.listing();
279
+ const conflicts = [];
280
+ for (const [p, entry] of Object.entries(batch)) {
281
+ const expected = entry?.ifMatch;
282
+ if (expected === void 0) continue;
283
+ const actual = before.files[p]?.sha256 ?? null;
284
+ if (actual !== expected) conflicts.push({ path: p, actual, expected });
285
+ }
286
+ if (conflicts.length > 0) {
287
+ return { status: 409, body: { code: "conflict", live: before.ver, paths: conflicts } };
288
+ }
289
+ const shas = {};
290
+ for (const [p, entry] of Object.entries(batch)) {
291
+ const file = files.get(p);
292
+ if (!isWriteEntry(entry)) {
293
+ this.ownWrites.set(p, "");
294
+ await rm(file, { force: true });
295
+ continue;
296
+ }
297
+ const bytes = Buffer.from(entry.base64, "base64");
298
+ const sha = sha256(bytes);
299
+ this.ownWrites.set(p, sha);
300
+ await writeFileAtomic(file, bytes);
301
+ shas[p] = sha;
302
+ }
303
+ const after = await this.listing();
304
+ this.seq += 1;
305
+ return { status: 200, body: { version: after.ver, seq: this.seq, shas } };
306
+ }
307
+ async assetIndex() {
308
+ try {
309
+ const file = await this.diskPath(`${this.blobDir}/${ASSET_INDEX}`);
310
+ if (file === null) return {};
311
+ const parsed = JSON.parse(await readFile(file, "utf8"));
312
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
313
+ } catch {
314
+ return {};
315
+ }
316
+ }
317
+ /** 素材按内容寻址:id 是 sha256 的前 32 位,同一张图只存一份。 */
318
+ putBlob(bytes, contentType) {
319
+ const run = this.queue.then(() => this.putBlobNow(bytes, contentType));
320
+ this.queue = run.catch(() => void 0);
321
+ return run;
322
+ }
323
+ async putBlobNow(bytes, contentType) {
324
+ const id = sha256(bytes).slice(0, 32);
325
+ const type = contentType.split(";")[0].trim().toLowerCase() || "application/octet-stream";
326
+ const existing = await this.findBlobFile(id);
327
+ if (existing === null) {
328
+ const file = await this.diskPath(`${this.blobDir}/${id}.${assetExtensionOf(type)}`);
329
+ if (file === null) throw new Error(`${this.blobDir} directory is not writable`);
330
+ await writeFileAtomic(file, bytes);
331
+ }
332
+ const index = await this.assetIndex();
333
+ const indexFile = await this.diskPath(`${this.blobDir}/${ASSET_INDEX}`);
334
+ if (index[id] !== type && indexFile !== null) {
335
+ index[id] = type;
336
+ await writeFileAtomic(indexFile, Buffer.from(JSON.stringify(index, null, 2) + "\n"));
337
+ }
338
+ return { id, url: `/_blob/${id}`, sizeBytes: bytes.byteLength };
339
+ }
340
+ /** 素材目录里以 `<id>.` 开头的那个文件。 */
341
+ async findBlobFile(id) {
342
+ try {
343
+ const name = (await readdir(path2.join(this.root, this.blobDir))).find((n) => n.startsWith(`${id}.`) && !n.endsWith(".tmp"));
344
+ if (name === void 0) return null;
345
+ const file = await this.diskPath(`${this.blobDir}/${name}`);
346
+ return file !== null && (await lstat(file).catch(() => null))?.isFile() ? file : null;
347
+ } catch {
348
+ return null;
349
+ }
350
+ }
351
+ async hasBlob(id) {
352
+ return BLOB_ID_PATTERN.test(id) && await this.findBlobFile(id) !== null;
353
+ }
354
+ /** 素材的磁盘文件与 Content-Type(路由按文件流式返回)。 */
355
+ async blobFile(id) {
356
+ if (!BLOB_ID_PATTERN.test(id)) return null;
357
+ const file = await this.findBlobFile(id);
358
+ if (file === null) return null;
359
+ return { file, contentType: (await this.assetIndex())[id] ?? contentTypeOf(file) };
360
+ }
361
+ async getBlob(id) {
362
+ const found = await this.blobFile(id);
363
+ if (found === null) return null;
364
+ try {
365
+ return { bytes: await readFile(found.file), contentType: found.contentType };
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
370
+ /**
371
+ * 这些运行时路径里,哪些的当前内容不是本进程写进去的。`seen` 是调用方已经知道的内容(开始监听时盘上的、报过的):
372
+ * 与它一致的也不算;查过的路径记成当前内容。
373
+ */
374
+ async externalChanges(paths, seen) {
375
+ const external = [];
376
+ for (const p of paths) {
377
+ const rel = this.fileOf(p);
378
+ if (rel === null) continue;
379
+ let sha = "";
380
+ try {
381
+ const file = await this.diskPath(rel);
382
+ if (file !== null && (await lstat(file)).isFile()) sha = sha256(await readFile(file));
383
+ } catch {
384
+ sha = "";
385
+ }
386
+ if (this.ownWrites.get(p) !== sha && seen?.get(p) !== sha) external.push(p);
387
+ seen?.set(p, sha);
388
+ }
389
+ return external;
390
+ }
391
+ };
392
+ function versionOf(files) {
393
+ const digest = sha256(
394
+ Object.entries(files).map(([p, f]) => `${p}:${f.sha256}`).join("\n")
395
+ );
396
+ return "local-" + digest.slice(0, 16);
397
+ }
398
+
399
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
400
+ import path3 from "node:path";
401
+ function problemCount(report) {
402
+ return report.deckProblems.length + report.slides.reduce((n, s) => n + s.problems.length, 0);
403
+ }
404
+ var IMAGE_REF_ADVICE = /(?: — URLs are not fetched| — a relative path under the deck's folder| is a file reference with no data).*$/;
405
+ var IMPORT_ADVICE = " \u2014 \u56FE\u7247\u5148\u7528 slides_import_asset \u5BFC\u5165\uFF0Csrc \u5199\u5B83\u8FD4\u56DE\u7684 /_blob/<id>";
406
+ var fmt = (d) => `${d.line}:${d.col} ${d.message.replace(IMAGE_REF_ADVICE, IMPORT_ADVICE)}`;
407
+ var CJK = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]/;
408
+ function isCjkWordBreakLint(message) {
409
+ if (!message.includes("break mid-word")) return false;
410
+ const quoted = /"([^"]*)" needs ~/.exec(message)?.[1] ?? "";
411
+ return CJK.test(quoted);
412
+ }
413
+ var FACE_FAMILY = /^[A-Za-z][A-Za-z0-9 _-]{0,39}$/;
414
+ var GOOGLE_FONTS_CSS = /^https:\/\/fonts\.googleapis\.com\/css2\?[A-Za-z0-9&=+,.:;@_-]+$/;
415
+ var MAX_FONT_HREF = 1024;
416
+ var BLOB_SRC = /^\/_blob\/([0-9a-f]{32})$/;
417
+ var DS_FONT_SRC = /^project\/(ds\/[a-z0-9][a-z0-9_-]{0,63}\/(?:[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/){0,8}[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:[Ww][Oo][Ff][Ff]2?|[Tt][Tt][Ff]|[Oo][Tt][Ff]))$/;
418
+ var MAX_FACES = 4;
419
+ var DS_DIR = "ds";
420
+ var DS_FOLDER = /^[a-z0-9][a-z0-9_-]{0,63}$/;
421
+ var MAX_DESIGN_SYSTEMS = 4;
422
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
423
+ function fontHead(deck) {
424
+ const parts = [];
425
+ for (const f of Object.values(deck.faces ?? {})) {
426
+ if (typeof f?.href === "string") {
427
+ parts.push(`<link rel="stylesheet" href="${f.href.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">`);
428
+ } else if (typeof f?.src === "string" && typeof f.family === "string" && FACE_FAMILY.test(f.family) && (BLOB_SRC.test(f.src) || DS_FONT_SRC.test(f.src))) {
429
+ parts.push(`<style>@font-face{font-family:'${f.family}';src:url(${f.src})}</style>`);
430
+ }
431
+ }
432
+ return `<head>${parts.join("")}</head>
433
+ `;
434
+ }
435
+ var facesOf = (r) => Array.isArray(r.content.faces) ? r.content.faces.length : 0;
436
+ var headFaceCounts = /* @__PURE__ */ new Map();
437
+ function headFaces(rt, head) {
438
+ let n = headFaceCounts.get(head);
439
+ if (n === void 0) {
440
+ n = facesOf(rt.compileSlideHtml(`${head}<section id="probe"></section>`));
441
+ if (headFaceCounts.size > 64) headFaceCounts.clear();
442
+ headFaceCounts.set(head, n);
443
+ }
444
+ return n;
445
+ }
446
+ function checkSlide(rt, id, html, options) {
447
+ const report = { id, problems: [], notes: [], roundTripDrift: false };
448
+ const r = rt.compileSlideHtml(options.head + html, { lists: options.lists });
449
+ for (const e of r.errors) report.problems.push(`\u9519\u8BEF ${fmt(e)}`);
450
+ if (r.hoisted > 0 || r.title !== void 0 || facesOf(r) > headFaces(rt, options.head)) {
451
+ report.problems.push("\u9519\u8BEF \u9875\u9762\u6587\u4EF6\u91CC\u4E0D\u80FD\u6709 <title>\u3001<link> \u6216 <style>\uFF1A\u6837\u5F0F\u5199\u8FDB style \u5C5E\u6027\uFF0C\u7F51\u7EDC\u5B57\u4F53\u767B\u8BB0\u5728 deck.json \u7684 faces");
452
+ }
453
+ for (const u of r.unsupported) report.problems.push(`\u4E0D\u652F\u6301 ${fmt(u)}`);
454
+ if (r.cellRemovals > 0) report.problems.push(`\u8868\u683C\u6709 ${r.cellRemovals} \u4E2A\u5355\u5143\u683C\u88AB\u5220\uFF08\u884C\u5217\u6570\u4E0D\u9F50\uFF09`);
455
+ if (r.content.order.length !== 1) report.problems.push(`\u5E94\u8BE5\u6070\u597D\u4E00\u4E2A <section>\uFF0C\u5B9E\u9645 ${r.content.order.length} \u4E2A`);
456
+ for (const w of r.warnings) report.notes.push(`\u8B66\u544A ${fmt(w)}`);
457
+ if (options.verbose) {
458
+ for (const l of r.lints) if (!isCjkWordBreakLint(l.message)) report.notes.push(`\u6392\u7248 ${fmt(l)}`);
459
+ }
460
+ if (options.blobExists) {
461
+ for (const ref of html.matchAll(/\/_blob\/([0-9a-f]{32})/g)) {
462
+ if (!options.blobExists(ref[1])) report.problems.push(`\u5F15\u7528\u7684 /_blob/${ref[1]} \u4E0D\u5B58\u5728`);
463
+ }
464
+ }
465
+ const slide = r.content.slides[r.content.order[0] ?? ""];
466
+ if (slide !== void 0) {
467
+ const once = rt.serializeSlideHtml(r.content, slide);
468
+ const again = rt.compileSlideHtml(options.head + once, { lists: options.lists });
469
+ const againSlide = again.content.slides[again.content.order[0] ?? ""];
470
+ report.roundTripDrift = againSlide === void 0 || rt.serializeSlideHtml(again.content, againSlide) !== once;
471
+ }
472
+ return report;
473
+ }
474
+ function checkDeck(rt, deckDir, options = {}) {
475
+ const raw = JSON.parse(readFileSync(path3.join(deckDir, "deck.json"), "utf8"));
476
+ const normalized = rt.normalizeDeckMetadata(raw);
477
+ const slidesDir = path3.join(deckDir, "slides");
478
+ const slideFiles = new Set(
479
+ existsSync(slidesDir) ? readdirSync(slidesDir).filter((f) => f.endsWith(".html")).map((f) => f.slice(0, -".html".length)) : []
480
+ );
481
+ const deckProblems = deckReferenceProblems(raw, slideFiles);
482
+ const dropped = (raw.order ?? []).length - normalized.order.length;
483
+ if (dropped > 0) deckProblems.push(`order \u91CC\u6709 ${dropped} \u4E2A\u65E0\u6548\u6216\u91CD\u590D\u7684 id \u4F1A\u88AB\u8FD0\u884C\u65F6\u4E22\u6389`);
484
+ const title = normalized.title.trim();
485
+ if (title === "" || title.toLowerCase() === "untitled") deckProblems.push("title \u4E3A\u7A7A\u6216\u662F Untitled\uFF1A\u7ED9\u8FD9\u4EFD\u6F14\u793A\u8D77\u4E2A\u540D\u5B57");
486
+ const head = fontHead(raw);
487
+ const assetsDir = path3.join(deckDir, ASSETS_DIR);
488
+ const assets = existsSync(assetsDir) ? readdirSync(assetsDir) : [];
489
+ const slides = normalized.order.filter((id) => slideFiles.has(id)).map(
490
+ (id) => checkSlide(rt, id, readFileSync(path3.join(slidesDir, `${id}.html`), "utf8"), {
491
+ head,
492
+ lists: raw.lists,
493
+ blobExists: (blobId) => assets.some((name) => name.startsWith(`${blobId}.`)),
494
+ verbose: options.verbose
495
+ })
496
+ );
497
+ return {
498
+ title: normalized.title,
499
+ deckProblems: [...deckProblems.map((p) => `deck.json: ${p}`), ...deckFileProblems(raw, deckDir)],
500
+ orphans: [...slideFiles].filter((id) => !normalized.order.includes(id)),
501
+ slides
502
+ };
503
+ }
504
+ function deckFileProblems(raw, deckDir) {
505
+ const problems = [];
506
+ const faces = raw.faces;
507
+ const fileExists = (rel) => {
508
+ try {
509
+ return statSync(path3.join(deckDir, rel)).isFile();
510
+ } catch {
511
+ return false;
512
+ }
513
+ };
514
+ const blobExists = (id) => {
515
+ try {
516
+ return readdirSync(path3.join(deckDir, ASSETS_DIR)).some((name) => name.startsWith(`${id}.`));
517
+ } catch {
518
+ return false;
519
+ }
520
+ };
521
+ if (faces !== void 0 && !isRecord(faces)) problems.push('deck.json: faces \u8981\u662F\u5BF9\u8C61\uFF1A{"<\u952E>": {"family": \u2026, "href" \u6216 "src": \u2026}}');
522
+ const entries = isRecord(faces) ? Object.entries(faces) : [];
523
+ if (entries.length > MAX_FACES) problems.push(`deck.json: faces \u6709 ${entries.length} \u9879\uFF0C\u7F16\u8F91\u5668\u53EA\u8BA4\u524D ${MAX_FACES} \u4E2A`);
524
+ const families = /* @__PURE__ */ new Set();
525
+ for (const [key, face] of entries) {
526
+ const where = `deck.json: faces.${key}`;
527
+ if (!isRecord(face) || typeof face.family !== "string") {
528
+ problems.push(`${where} \u8981\u5199\u6210 {"family": <\u9875\u9762 font-family \u91CC\u7684\u540D\u5B57>, "href": <Google Fonts \u94FE\u63A5>} \u6216 {"family": \u2026, "src": <slides_import_asset \u8FD4\u56DE\u7684 /_blob/<id>>}`);
529
+ continue;
530
+ }
531
+ if (!FACE_FAMILY.test(face.family)) problems.push(`${where}.family\u300C${face.family}\u300D\u7F16\u8F91\u5668\u8BA4\u4E0D\u5F97\uFF1A\u4EE5\u82F1\u6587\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u7528\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u7A7A\u683C\u3001- \u4E0E _\uFF0C\u81F3\u591A 40 \u4E2A\u5B57\u7B26`);
532
+ else if (families.has(face.family.toLowerCase())) problems.push(`${where}.family\u300C${face.family}\u300D\u91CD\u590D\u4E86\uFF0C\u7F16\u8F91\u5668\u53EA\u8BA4\u7B2C\u4E00\u4E2A`);
533
+ families.add(face.family.toLowerCase());
534
+ const { href, src } = face;
535
+ if (href !== void 0 && src !== void 0) problems.push(`${where} \u53EA\u5199 href \u6216 src \u4E2D\u7684\u4E00\u4E2A`);
536
+ else if (href !== void 0) {
537
+ if (typeof href !== "string" || !GOOGLE_FONTS_CSS.test(href)) problems.push(`${where}.href \u8981\u662F https://fonts.googleapis.com/css2?\u2026 \u7684\u94FE\u63A5`);
538
+ else if (href.length > MAX_FONT_HREF) problems.push(`${where}.href \u6709 ${href.length} \u4E2A\u5B57\u7B26\uFF0C\u7F16\u8F91\u5668\u53EA\u8BA4 ${MAX_FONT_HREF} \u4E2A\u4EE5\u5185\uFF1A\u5C11\u5217\u51E0\u4E2A\u5B57\u91CD`);
539
+ } else if (src !== void 0) {
540
+ const blob = typeof src === "string" ? BLOB_SRC.exec(src) : null;
541
+ const dsFile = typeof src === "string" ? DS_FONT_SRC.exec(src) : null;
542
+ if (blob) {
543
+ if (!blobExists(blob[1])) problems.push(`${where}.src \u5F15\u7528\u7684 /_blob/${blob[1]} \u4E0D\u5B58\u5728\uFF1A\u7528 slides_import_asset \u5BFC\u5165\u5B57\u4F53\u6587\u4EF6\uFF0C\u5199\u5B83\u8FD4\u56DE\u7684 src`);
544
+ } else if (dsFile) {
545
+ if (!fileExists(dsFile[1])) problems.push(`${where}.src \u6307\u5411\u7684 ${dsFile[1]} \u4E0D\u5728 deck \u91CC`);
546
+ } else {
547
+ problems.push(`${where}.src \u8981\u662F slides_import_asset \u8FD4\u56DE\u7684 /_blob/<id>\uFF08\u5B57\u4F53\u6587\u4EF6 woff2\u3001woff\u3001ttf\u3001otf \u5148\u5BFC\u5165\uFF09`);
548
+ }
549
+ } else {
550
+ problems.push(`${where} \u8981\u6709 href\uFF08Google Fonts \u94FE\u63A5\uFF09\u6216 src\uFF08slides_import_asset \u8FD4\u56DE\u7684 /_blob/<id>\uFF09`);
551
+ }
552
+ }
553
+ problems.push(...designSystemProblems(raw.designSystems, deckDir));
554
+ return problems;
555
+ }
556
+ function designSystemProblems(value, deckDir) {
557
+ const problems = [];
558
+ const folders = [];
559
+ let listing = [];
560
+ try {
561
+ listing = readdirSync(path3.join(deckDir, DS_DIR), { withFileTypes: true }).sort((x, y) => x.name < y.name ? -1 : x.name > y.name ? 1 : 0);
562
+ } catch {
563
+ }
564
+ for (const entry of listing) {
565
+ if (entry.name.startsWith(".")) continue;
566
+ if (!entry.isDirectory()) problems.push(`${DS_DIR}/${entry.name}: ${DS_DIR}/ \u4E0B\u53EA\u653E\u76EE\u5F55\uFF0C\u4E00\u4E2A\u8BBE\u8BA1\u7CFB\u7EDF\u4E00\u4E2A ${DS_DIR}/<folder>/`);
567
+ else if (!DS_FOLDER.test(entry.name)) problems.push(`${DS_DIR}/${entry.name}/: \u8BBE\u8BA1\u7CFB\u7EDF\u7684\u76EE\u5F55\u540D\u53EA\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u4E0E _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934\uFF0C\u81F3\u591A 64 \u4E2A\u5B57\u7B26`);
568
+ else folders.push(entry.name);
569
+ }
570
+ const records = Array.isArray(value) ? value : isRecord(value) ? Object.values(value) : value === void 0 ? [] : null;
571
+ if (records === null) problems.push('deck.json: designSystems \u8981\u662F\u6570\u7EC4\uFF1A[{"title","namespace","artifact","version","copiedAt"}]');
572
+ const recorded = /* @__PURE__ */ new Set();
573
+ if (records && records.length > MAX_DESIGN_SYSTEMS) problems.push(`deck.json: designSystems \u6709 ${records.length} \u9879\uFF0C\u4E00\u4EFD deck \u81F3\u591A ${MAX_DESIGN_SYSTEMS} \u4E2A`);
574
+ (records ?? []).forEach((record, i) => {
575
+ const where = `deck.json: designSystems[${i}]`;
576
+ if (!isRecord(record) || typeof record.title !== "string" || typeof record.namespace !== "string" || !DS_FOLDER.test(record.namespace) || typeof record.artifact !== "string" || !(record.version === void 0 || record.version === null || typeof record.version === "string") || !(record.copiedAt === void 0 || typeof record.copiedAt === "string")) {
577
+ problems.push(`${where} \u8981\u5199\u6210 {"title": <\u540D\u5B57>, "namespace": <ds/ \u4E0B\u7684\u76EE\u5F55\u540D>, "artifact": <\u4ECE\u54EA\u91CC\u62F7\u6765>, "version": <\u5B57\u7B26\u4E32\u6216 null>, "copiedAt": <RFC 3339 \u65F6\u95F4>}`);
578
+ return;
579
+ }
580
+ if (recorded.has(record.namespace)) problems.push(`${where}: namespace\u300C${record.namespace}\u300D\u51FA\u73B0\u4E86\u4E0D\u6B62\u4E00\u6B21`);
581
+ recorded.add(record.namespace);
582
+ });
583
+ for (const folder of folders) {
584
+ if (!recorded.has(folder)) problems.push(`${DS_DIR}/${folder}/ \u5728 designSystems \u91CC\u6CA1\u6709\u8BB0\u5F55\uFF1A\u7F16\u8F91\u5668\u8981\u4E24\u8005\u90FD\u5728\u624D\u63D0\u4F9B\u8FD9\u4E2A\u8BBE\u8BA1\u7CFB\u7EDF`);
585
+ }
586
+ return problems;
587
+ }
588
+
589
+ var MAX_PUBLISH_BYTES = 64 * 1024 * 1024;
590
+ var MAX_ASSET_BYTES = 256 * 1024 * 1024;
591
+
592
+ import fs2 from "node:fs";
593
+ import { createRequire } from "node:module";
594
+ import path4 from "node:path";
595
+ import { fileURLToPath } from "node:url";
596
+ var COMPILER_FILE = path4.join("node", "compiler.cjs");
597
+ function resolveSlidesEditorDist(env = process.env) {
598
+ const given = env.BAOCUT_SLIDES_EDITOR_DIST;
599
+ if (given) return fs2.existsSync(path4.join(given, "index.html")) ? given : null;
600
+ const resources = process.resourcesPath;
601
+ if (resources) {
602
+ const bundled = path4.join(resources, "slides-editor");
603
+ if (fs2.existsSync(path4.join(bundled, "index.html"))) return bundled;
604
+ }
605
+ let dir = path4.dirname(fileURLToPath(import.meta.url));
606
+ for (; ; ) {
607
+ const built = path4.join(dir, "apps", "slides-editor", "dist");
608
+ if (fs2.existsSync(path4.join(built, "index.html"))) return built;
609
+ const parent = path4.dirname(dir);
610
+ if (parent === dir) return null;
611
+ dir = parent;
612
+ }
613
+ }
614
+ var require2 = createRequire(import.meta.url);
615
+ var loaded = /* @__PURE__ */ new Map();
616
+ function compilerAvailable(dist = resolveSlidesEditorDist()) {
617
+ return dist !== null && fs2.existsSync(path4.join(dist, COMPILER_FILE));
618
+ }
619
+ function loadSlidesCompiler(dist = resolveSlidesEditorDist()) {
620
+ if (!compilerAvailable(dist)) throw new Error("slides compiler is not built");
621
+ const file = path4.join(dist, COMPILER_FILE);
622
+ let runtime = loaded.get(file);
623
+ if (!runtime) {
624
+ runtime = require2(file).runtime;
625
+ loaded.set(file, runtime);
626
+ }
627
+ return runtime;
628
+ }
629
+
630
+ import fs3 from "node:fs/promises";
631
+ import path5 from "node:path";
632
+ var CANVAS_FILE = "canvas.json";
633
+ var BOARD_SUFFIX = ".dc.html";
634
+ var DESIGN_SYSTEMS_DIR = "ds";
635
+ var CANVAS_LIMITS = {
636
+ files: 512,
637
+ totalBytes: 256 * 1024 * 1024,
638
+ publishBytes: 16 * 1024 * 1024
639
+ };
640
+ var SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
641
+ function isCanvasSegment(segment) {
642
+ return SEGMENT.test(segment);
643
+ }
644
+ function isCanvasFile(rel) {
645
+ const parts = rel.split("/");
646
+ if (parts[0] === ASSETS_DIR) return false;
647
+ return parts.every(isCanvasSegment);
648
+ }
649
+ function isBoardPath(rel) {
650
+ return rel.endsWith(BOARD_SUFFIX) && rel.split("/")[0] !== DESIGN_SYSTEMS_DIR;
651
+ }
652
+ var CANVAS_LAYOUT = {
653
+ isFile: isCanvasFile,
654
+ roots: [{ rel: "", descend: true }],
655
+ descendInto: (rel) => isCanvasFile(rel),
656
+ watches: (rel) => isCanvasFile(rel),
657
+ maxFiles: CANVAS_LIMITS.files,
658
+ maxPublishBytes: CANVAS_LIMITS.publishBytes,
659
+ readOnlyMessage: (p) => `${p}: files under assets/, hidden paths and path segments outside [A-Za-z0-9_][A-Za-z0-9_.-]* can't be written`
660
+ };
661
+ function isCanvasMetadata(value) {
662
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
663
+ const canvas = value;
664
+ return canvas.v === 3 && typeof canvas.boards === "object" && canvas.boards !== null && !Array.isArray(canvas.boards);
665
+ }
666
+ var MAX_CANVAS_JSON_BYTES = 4 * 1024 * 1024;
667
+ async function readCanvasJson(dir) {
668
+ const file = path5.join(dir, CANVAS_FILE);
669
+ try {
670
+ const stat = await fs3.lstat(file);
671
+ if (!stat.isFile() || stat.size > MAX_CANVAS_JSON_BYTES) return null;
672
+ return JSON.parse(await fs3.readFile(file, "utf8"));
673
+ } catch {
674
+ return null;
675
+ }
676
+ }
677
+ function canvasTitle(canvas, dir) {
678
+ const raw = canvas.title;
679
+ const title = typeof raw === "string" ? raw.trim() : "";
680
+ return title || path5.basename(dir);
681
+ }
682
+ async function readCanvasInfo(dir) {
683
+ const parsed = await readCanvasJson(dir);
684
+ if (!isCanvasMetadata(parsed)) return null;
685
+ return { title: canvasTitle(parsed, dir), boardCount: Object.keys(parsed.boards).length };
686
+ }
687
+
688
+ import fs4 from "node:fs/promises";
689
+ import path6 from "node:path";
690
+ var BOARD_SIZE = { min: 40, max: 8e3 };
691
+ var MAX_PAGES = 40;
692
+ var MAX_NOTES = 999;
693
+ var MAX_GUIDES = 6;
694
+ var ID_PATTERN = /^[A-Za-z0-9_-]{1,40}$/;
695
+ var MAX_BOARD_BYTES = 8 * 1024 * 1024;
696
+ var MAX_SCAN_ENTRIES = 2e4;
697
+ var SUPPORT_LINE = '<script src="./support.js"></script>';
698
+ var TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".html", ".css", ".js", ".mjs", ".json", ".svg", ".md", ".txt"]);
699
+ async function scanTree(dir, issues) {
700
+ const tree = { files: /* @__PURE__ */ new Map(), assets: /* @__PURE__ */ new Set(), totalBytes: 0, truncated: false };
701
+ let seen = 0;
702
+ const visit = async (rel) => {
703
+ const full = rel === "" ? dir : path6.join(dir, ...rel.split("/"));
704
+ const entries = await fs4.readdir(full, { withFileTypes: true }).catch(() => []);
705
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
706
+ for (const entry of entries) {
707
+ if (++seen > MAX_SCAN_ENTRIES) {
708
+ tree.truncated = true;
709
+ return;
710
+ }
711
+ if (entry.name.startsWith(".")) continue;
712
+ const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
713
+ if (rel === "" && entry.name === ASSETS_DIR && entry.isDirectory()) {
714
+ await scanAssets(path6.join(dir, ASSETS_DIR), tree);
715
+ continue;
716
+ }
717
+ if (entry.isSymbolicLink()) {
718
+ issues.push({ file: child, message: "is a symbolic link; the editor ignores symbolic links. Replace it with a regular file or folder" });
719
+ continue;
720
+ }
721
+ if (!isCanvasSegment(entry.name)) {
722
+ issues.push({
723
+ file: child,
724
+ message: `"${entry.name}" is not a valid path segment: start with a letter, digit or _, then use only letters, digits, _, . and - (no spaces). The editor can't see it`
725
+ });
726
+ continue;
727
+ }
728
+ if (entry.isDirectory()) await visit(child);
729
+ else if (entry.isFile()) {
730
+ const stat = await fs4.lstat(path6.join(full, entry.name)).catch(() => null);
731
+ const size = stat?.size ?? 0;
732
+ tree.files.set(child, size);
733
+ tree.totalBytes += size;
734
+ }
735
+ }
736
+ };
737
+ await visit("");
738
+ return tree;
739
+ }
740
+ async function scanAssets(dir, tree) {
741
+ const entries = await fs4.readdir(dir, { withFileTypes: true }).catch(() => []);
742
+ for (const entry of entries) {
743
+ if (!entry.isFile() || entry.name.startsWith(".")) continue;
744
+ const id = entry.name.split(".")[0];
745
+ if (BLOB_ID_PATTERN.test(id)) tree.assets.add(id);
746
+ const stat = await fs4.lstat(path6.join(dir, entry.name)).catch(() => null);
747
+ tree.totalBytes += stat?.size ?? 0;
748
+ }
749
+ }
750
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
751
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
752
+ function decodeEntities(text) {
753
+ return text.replace(/&(#x[0-9a-f]+|#\d+|amp|apos|quot|lt|gt);/gi, (whole, name) => {
754
+ const lower = name.toLowerCase();
755
+ if (lower.startsWith("#x")) return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
756
+ if (lower.startsWith("#")) return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
757
+ return { amp: "&", apos: "'", quot: '"', lt: "<", gt: ">" }[lower] ?? whole;
758
+ });
759
+ }
760
+ var isRemote = (url) => /^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(url.trim()) && !/^data:/i.test(url.trim());
761
+ var isGoogleFonts = (url) => /^(?:https?:)?\/\/fonts\.googleapis\.com\//i.test(url.trim());
762
+ function attr(attrs, name) {
763
+ const match = new RegExp(`\\b${name}\\s*=\\s*(?:'([^']*)'|"([^"]*)"|([^\\s>]+))`, "i").exec(attrs);
764
+ if (!match) return null;
765
+ if (match[1] !== void 0) return { value: match[1], quote: "'" };
766
+ if (match[2] !== void 0) return { value: match[2], quote: '"' };
767
+ return { value: match[3], quote: "" };
768
+ }
769
+ function checkBlobRefs(file, text, assets, issues) {
770
+ const reported = /* @__PURE__ */ new Set();
771
+ for (const match of text.matchAll(/\/_blob\/([^\s"'()<>?#]*)/g)) {
772
+ const id = match[1];
773
+ if (reported.has(id)) continue;
774
+ reported.add(id);
775
+ if (!BLOB_ID_PATTERN.test(id)) {
776
+ issues.push({ file, message: `/_blob/${id} is not a valid asset reference: use the /_blob/<id> that design_import_asset returned (32 lowercase hex digits)` });
777
+ } else if (!assets.has(id)) {
778
+ issues.push({ file, message: `/_blob/${id} is not in assets/: import the file with design_import_asset and use the src it returns` });
779
+ }
780
+ }
781
+ }
782
+ function checkCssImports(file, css, issues) {
783
+ for (const match of css.matchAll(/@import\s+(?:url\(\s*)?["']?([^"')\s;]+)/gi)) {
784
+ const url = match[1];
785
+ if (isRemote(url) && !isGoogleFonts(url)) {
786
+ issues.push({ file, message: `@import ${url} loads a stylesheet from the network; only Google Fonts (fonts.googleapis.com) is allowed. Keep styles inline or import the file with design_import_asset` });
787
+ }
788
+ }
789
+ }
790
+ var ATTRS = String.raw`((?:[^>"']|"[^"]*"|'[^']*')*)`;
791
+ var TAG = new RegExp(String.raw`<(\/?)([A-Za-z][A-Za-z0-9:-]*)` + ATTRS + ">", "g");
792
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
793
+ var RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
794
+ var PROP_EDITORS = /* @__PURE__ */ new Set(["text", "color", "int", "float", "range", "boolean", "enum"]);
795
+ var HOLE = /^\s*(?:[A-Za-z_$][\w$]*(?:\.[\w$]+)*|true|false|null|-?\d+(?:\.\d+)?|"[^"{}]*"|'[^'{}]*')\s*$/;
796
+ function attrList(attrs) {
797
+ const list = [];
798
+ for (const match of attrs.matchAll(/([^\s=/"']+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s"'>]+))?/g)) {
799
+ const raw = match[2];
800
+ if (raw === void 0) list.push({ name: match[1], value: null, quoted: false });
801
+ else {
802
+ const quoted = raw.startsWith('"') || raw.startsWith("'");
803
+ list.push({ name: match[1], value: quoted ? raw.slice(1, -1) : raw, quoted });
804
+ }
805
+ }
806
+ return list;
807
+ }
808
+ function resolveRelative(file, ref) {
809
+ const clean = ref.split(/[?#]/)[0];
810
+ const parts = clean.startsWith("/") ? [] : file.split("/").slice(0, -1);
811
+ for (const part of clean.split("/")) {
812
+ if (part === "" || part === ".") continue;
813
+ if (part === "..") {
814
+ if (parts.length === 0) return null;
815
+ parts.pop();
816
+ } else parts.push(part);
817
+ }
818
+ return parts.join("/");
819
+ }
820
+ var isBlobUrl = (url) => /^(?:\.{1,2}\/)*\/?_blob\//.test(url.trim());
821
+ function checkAssetUrl(ctx, url, where) {
822
+ const value = url.trim();
823
+ if (value === "" || value.startsWith("#") || /^\{\{[\s\S]*\}\}$/.test(value) || isBlobUrl(value)) return;
824
+ const add = (message) => ctx.issues.push({ file: ctx.file, message });
825
+ if (/^data:/i.test(value)) add(`${where} uses a data: URI; upload the file with design_import_asset and use its /_blob/<id>`);
826
+ else if (/^blob:/i.test(value)) add(`${where} uses a blob: URL, which only lives in one browser tab; upload the file with design_import_asset`);
827
+ else if (isRemote(value) || /^[a-z][a-z0-9+.-]*:/i.test(value)) {
828
+ if (!/^(?:https?:)?\/\/fonts\.gstatic\.com\//i.test(value)) add(`${where} loads ${value} from the network; upload the file with design_import_asset and use its /_blob/<id>`);
829
+ } else add(`${where} names the file ${value}; upload it with design_import_asset and use the /_blob/<id> it returns`);
830
+ }
831
+ function checkMarkup(ctx, markup) {
832
+ const add = (message) => ctx.issues.push({ file: ctx.file, message });
833
+ const text = markup.replace(/<!--[\s\S]*?-->/g, (comment) => " ".repeat(comment.length));
834
+ const stack = [];
835
+ const once = /* @__PURE__ */ new Set();
836
+ const addOnce = (key, message) => {
837
+ if (once.has(key)) return;
838
+ once.add(key);
839
+ add(message);
840
+ };
841
+ let svgDepth = 0;
842
+ TAG.lastIndex = 0;
843
+ for (let match = TAG.exec(text); match; match = TAG.exec(text)) {
844
+ const closing = match[1] === "/";
845
+ const name = match[2];
846
+ const lower = name.toLowerCase();
847
+ const attrs = match[3] ?? "";
848
+ if (closing) {
849
+ const at = stack.lastIndexOf(lower);
850
+ if (at < 0) {
851
+ addOnce(`stray:${lower}`, `</${name}> has no matching <${name}>`);
852
+ continue;
853
+ }
854
+ for (const unclosed of stack.splice(at).slice(1).reverse()) addOnce(`open:${unclosed}`, `<${unclosed}> is not closed before </${name}>; close every non-void element`);
855
+ if (lower === "svg") svgDepth = Math.max(0, svgDepth - 1);
856
+ continue;
857
+ }
858
+ if (svgDepth === 0 && /[A-Z]/.test(name)) {
859
+ addOnce(`case:${name}`, `<${name}>: tag names are lower case; mount another artboard with <dc-import name="${name}"></dc-import>`);
860
+ }
861
+ const list = attrList(attrs.replace(/\/\s*$/, ""));
862
+ for (const item of list) {
863
+ if (item.value !== null && !item.quoted) addOnce(`quote:${item.name}`, `the attribute ${item.name}=${item.value} is not quoted; quote every attribute`);
864
+ if (item.value !== null && /\{\{/.test(item.value)) {
865
+ for (const hole of item.value.matchAll(/\{\{([\s\S]*?)\}\}/g)) {
866
+ if (!HOLE.test(hole[1])) addOnce(`hole:${hole[1]}`, `{{${hole[1]}}} is an expression; a hole is a dotted lookup only: compute it in renderVals() and use its name`);
867
+ }
868
+ }
869
+ }
870
+ const style = list.find((item) => item.name.toLowerCase() === "style")?.value ?? "";
871
+ if (/url\(/i.test(style)) addOnce("inline-url", 'url(\u2026) in an inline style="\u2026"; put it in a <helmet><style> rule');
872
+ if (lower === "img" || lower === "source" && svgDepth === 0) {
873
+ const src = list.find((item) => item.name.toLowerCase() === "src")?.value;
874
+ if (src !== void 0 && src !== null) checkAssetUrl(ctx, src, `<${lower} src>`);
875
+ }
876
+ if (lower === "dc-import") {
877
+ const ref = list.find((item) => item.name.toLowerCase() === "name")?.value ?? list.find((item) => item.name.toLowerCase() === "component")?.value;
878
+ if (!ref) add('<dc-import> needs name="<artboard file name without .dc.html>"');
879
+ else if (!/\{\{/.test(ref) && !ctx.stems.has(ref) && !ctx.tree.files.has(resolveRelative(ctx.file, `${ref}${BOARD_SUFFIX}`) ?? "")) {
880
+ add(`<dc-import name="${ref}"> has no ${ref}${BOARD_SUFFIX} to mount`);
881
+ }
882
+ }
883
+ if (lower === "a") {
884
+ const href = list.find((item) => item.name.toLowerCase() === "href")?.value;
885
+ if (href && !/\{\{/.test(href) && !isRemote(href) && !/^[a-z][a-z0-9+.-]*:/i.test(href) && href.split(/[?#]/)[0].endsWith(BOARD_SUFFIX)) {
886
+ const target = resolveRelative(ctx.file, href);
887
+ if (target === null || !ctx.tree.files.has(target)) add(`<a href="${href}"> links to an artboard that does not exist; the href is the target's path relative to this artboard (a leading / is the canvas root)`);
888
+ }
889
+ }
890
+ const selfClosed = /\/\s*$/.test(attrs);
891
+ if (RAW_TEXT.has(lower) && !selfClosed) {
892
+ const end = new RegExp(`</${lower}\\s*>`, "ig");
893
+ end.lastIndex = TAG.lastIndex;
894
+ const found = end.exec(text);
895
+ if (!found) {
896
+ addOnce(`open:${lower}`, `<${lower}> is never closed`);
897
+ return;
898
+ }
899
+ if (lower === "style") checkStyle(ctx, text.slice(TAG.lastIndex, found.index));
900
+ TAG.lastIndex = end.lastIndex;
901
+ continue;
902
+ }
903
+ if (VOID_ELEMENTS.has(lower)) continue;
904
+ if (selfClosed) {
905
+ if (svgDepth === 0) addOnce(`self:${lower}`, `<${name} /> is self-closed; write <${name}></${name}>`);
906
+ continue;
907
+ }
908
+ stack.push(lower);
909
+ if (lower === "svg") svgDepth += 1;
910
+ }
911
+ for (const unclosed of stack.reverse()) addOnce(`open:${unclosed}`, `<${unclosed}> is never closed; close every non-void element`);
912
+ for (const hole of text.replace(/<[^>]*>/g, " ").matchAll(/\{\{([\s\S]*?)\}\}/g)) {
913
+ if (!HOLE.test(hole[1])) addOnce(`hole:${hole[1]}`, `{{${hole[1]}}} is an expression; a hole is a dotted lookup only: compute it in renderVals() and use its name`);
914
+ }
915
+ }
916
+ function checkStyle(ctx, css) {
917
+ checkCssImports(ctx.file, css, ctx.issues);
918
+ for (const match of css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi)) {
919
+ const url = match[1] ?? match[2] ?? match[3] ?? "";
920
+ if (/^(?:https?:)?\/\/fonts\.googleapis\.com\//i.test(url.trim())) continue;
921
+ checkAssetUrl(ctx, url, "url(\u2026)");
922
+ }
923
+ }
924
+ function checkScript(ctx, code, logic) {
925
+ const add = (message) => ctx.issues.push({ file: ctx.file, message });
926
+ if (logic) {
927
+ if (!/\bclass\s+Component\s+extends\s+DCLogic\b/.test(code)) add("the data-dc-script block must define class Component extends DCLogic");
928
+ if (/^\s*(?:import|export)\b/m.test(code)) add("the data-dc-script block is classic JS: no import or export");
929
+ }
930
+ if (/\.(?:inner|outer)HTML\s*=(?!=)|\binsertAdjacentHTML\s*\(|\.appendChild\s*\(|\bdocument\.write(?:ln)?\s*\(/.test(code)) {
931
+ add("builds UI from script (innerHTML / appendChild / document.write); all UI is <x-dc> markup");
932
+ }
933
+ if (/\bwindow\.[A-Za-z_$][\w$]*\s*=(?!=)/.test(code)) add("sets a window.X global; keep state in the component (state / setState)");
934
+ if (/\b(?:window|document|globalThis)\s*\.\s*(?:addEventListener\s*\(\s*['"`]key(?:down|up|press)['"`]|onkey(?:down|up|press)\s*=)/.test(code)) {
935
+ add("installs a global keyboard handler; artboards must not handle keys on window or document");
936
+ }
937
+ for (const match of code.matchAll(/\bfetch\s*\(\s*['"`]([^'"`]+)['"`]/g)) {
938
+ if (isRemote(match[1])) add(`fetch("${match[1]}") goes to the network; upload the data with design_import_asset and fetch its /_blob/<id>`);
939
+ }
940
+ if (/\bnew\s+(?:WebSocket|EventSource)\s*\(|\bXMLHttpRequest\b/.test(code)) add("opens a network connection (WebSocket / EventSource / XMLHttpRequest); artboards stay offline");
941
+ }
942
+ function checkBoardFile(ctx, html) {
943
+ const { file, size } = ctx;
944
+ const add = (message) => ctx.issues.push({ file, message });
945
+ const support = html.indexOf(SUPPORT_LINE);
946
+ const headEnd = html.search(/<\/head\s*>/i);
947
+ if (support < 0) add(`the <head> must contain the exact line ${SUPPORT_LINE}`);
948
+ else if (headEnd >= 0 && support > headEnd) add(`${SUPPORT_LINE} must be inside <head>`);
949
+ const open2 = /<x-dc\s*>/i.exec(html);
950
+ const close = /<\/x-dc\s*>/i.exec(html);
951
+ if (!open2 || !close || close.index < open2.index) add("the markup must be wrapped in <x-dc>\u2026</x-dc>");
952
+ else checkMarkup(ctx, html.slice(open2.index + open2[0].length, close.index));
953
+ const scripts = [...html.matchAll(new RegExp(String.raw`<script\b` + ATTRS + String.raw`>([\s\S]*?)<\/script\s*>`, "gi"))];
954
+ const blocks = scripts.filter((m) => attrList(m[1] ?? "").some((a) => a.name.toLowerCase() === "data-dc-script"));
955
+ if (blocks.length === 0) add(`missing the <script type="text/x-dc" data-dc-script data-props='\u2026'> block (class Component extends DCLogic)`);
956
+ else if (blocks.length > 1) add(`has ${blocks.length} data-dc-script blocks; an artboard has exactly one`);
957
+ const block = blocks[0];
958
+ if (block) {
959
+ const attrs = block[1] ?? "";
960
+ if (attr(attrs, "type")?.value.toLowerCase() !== "text/x-dc") add('the data-dc-script block must have type="text/x-dc"');
961
+ const props = attr(attrs, "data-props");
962
+ if (props === null) add(`the data-dc-script block needs data-props='{"$preview":{"width":\u2026,"height":\u2026}}'`);
963
+ else if (props.quote !== "'") add("data-props must be single-quoted: data-props='{\u2026}'");
964
+ else {
965
+ let parsed;
966
+ try {
967
+ parsed = JSON.parse(decodeEntities(props.value));
968
+ } catch (error) {
969
+ add(`data-props is not valid JSON (${error.message}); escape & as &amp; and ' as &#39;`);
970
+ }
971
+ if (parsed !== void 0) {
972
+ const preview = isRecord2(parsed) ? parsed.$preview : void 0;
973
+ if (!isRecord2(preview) || !isFiniteNumber(preview.width) || !isFiniteNumber(preview.height)) {
974
+ add(`data-props needs "$preview": {"width": <number>, "height": <number>} equal to the board's w and h`);
975
+ } else if (size && (preview.width !== size.w || preview.height !== size.h)) {
976
+ add(`$preview is ${preview.width}\xD7${preview.height} but canvas.json boards gives ${size.w}\xD7${size.h}; make them equal`);
977
+ }
978
+ if (isRecord2(parsed)) {
979
+ for (const [key, spec] of Object.entries(parsed)) {
980
+ if (key === "$preview" || !isRecord2(spec) || !("editor" in spec)) continue;
981
+ if (spec.editor !== null && !(typeof spec.editor === "string" && PROP_EDITORS.has(spec.editor))) {
982
+ add(`data-props "${key}": editor must be one of text, color, int, float, range, boolean, enum or null`);
983
+ }
984
+ }
985
+ }
986
+ }
987
+ }
988
+ checkScript(ctx, block[2] ?? "", true);
989
+ }
990
+ for (const script2 of scripts) {
991
+ if (script2 === block) continue;
992
+ const list = attrList(script2[1] ?? "");
993
+ const src = list.find((a) => a.name.toLowerCase() === "src")?.value;
994
+ if (typeof src === "string") {
995
+ if (src === "./support.js") continue;
996
+ if (isRemote(src)) add(`<script src="${src}"> loads a script from the network; import it with design_import_asset and use its /_blob/<id>`);
997
+ else if (!isBlobUrl(src)) checkRelativeFile(ctx, src, "<script src>");
998
+ } else checkScript(ctx, script2[2] ?? "", false);
999
+ }
1000
+ const embedded = new Set([...html.matchAll(/<(iframe|object|embed)\b/gi)].map((m) => m[1].toLowerCase()));
1001
+ for (const tag of embedded) add(`<${tag}> is not allowed in an artboard`);
1002
+ for (const match of html.matchAll(new RegExp(String.raw`<link\b` + ATTRS + ">", "gi"))) {
1003
+ const list = attrList(match[1] ?? "");
1004
+ const rel = list.find((a) => a.name.toLowerCase() === "rel")?.value?.toLowerCase() ?? "";
1005
+ const href = list.find((a) => a.name.toLowerCase() === "href")?.value;
1006
+ if (typeof href !== "string" || !rel.split(/\s+/).some((r) => r === "stylesheet" || r === "preload" || r === "modulepreload")) continue;
1007
+ if (isRemote(href)) {
1008
+ if (!isGoogleFonts(href)) add(`<link href="${href}"> loads from the network; only Google Fonts (fonts.googleapis.com) is allowed. Import the file with design_import_asset instead`);
1009
+ } else if (!isBlobUrl(href)) checkRelativeFile(ctx, href, "<link href>");
1010
+ }
1011
+ checkBlobRefs(file, html, ctx.tree.assets, ctx.issues);
1012
+ }
1013
+ function checkRelativeFile(ctx, ref, where) {
1014
+ const target = resolveRelative(ctx.file, ref);
1015
+ if (target === null || target === "" || !ctx.tree.files.has(target)) {
1016
+ ctx.issues.push({ file: ctx.file, message: `${where} "${ref}" is not a file in this design; write it there or upload it with design_import_asset` });
1017
+ }
1018
+ }
1019
+ var GUIDE_KINDS = /* @__PURE__ */ new Set(["columns", "rows", "grid"]);
1020
+ var NOTE_KINDS = /* @__PURE__ */ new Set(["title1", "rect", "oval", "pen", "line", "arrow", "image"]);
1021
+ var DS_FOLDER2 = /^[a-z0-9][a-z0-9_-]{0,63}$/;
1022
+ var MAX_DESIGN_SYSTEMS2 = 4;
1023
+ function checkDesignSystems(value, tree, add) {
1024
+ const folders = /* @__PURE__ */ new Set();
1025
+ for (const file of tree.files.keys()) {
1026
+ const parts = file.split("/");
1027
+ if (parts[0] === DESIGN_SYSTEMS_DIR && parts.length > 2) folders.add(parts[1]);
1028
+ else if (parts[0] === DESIGN_SYSTEMS_DIR && parts.length === 2) add(`${file}: files under ${DESIGN_SYSTEMS_DIR}/ belong in ${DESIGN_SYSTEMS_DIR}/<folder>/, one folder per design system`);
1029
+ }
1030
+ for (const folder of folders) {
1031
+ if (!DS_FOLDER2.test(folder)) add(`${DESIGN_SYSTEMS_DIR}/${folder}/: a design system folder is lower case letters, digits, - and _, starting with a letter or digit, 64 at most`);
1032
+ }
1033
+ const recorded = /* @__PURE__ */ new Set();
1034
+ if (value !== void 0) {
1035
+ if (!Array.isArray(value)) add('designSystems must be an array of {"title","namespace","artifact","version","copiedAt"}');
1036
+ else {
1037
+ if (value.length > MAX_DESIGN_SYSTEMS2) add(`designSystems has ${value.length} entries; a design uses at most ${MAX_DESIGN_SYSTEMS2}`);
1038
+ value.forEach((record, i) => {
1039
+ const where = `designSystems[${i}]`;
1040
+ if (!isRecord2(record) || typeof record.title !== "string" || typeof record.namespace !== "string" || typeof record.artifact !== "string" || !(record.version === null || typeof record.version === "string") || typeof record.copiedAt !== "string") {
1041
+ add(`${where} must be {"title": <string>, "namespace": <folder>, "artifact": <where it was copied from>, "version": <string or null>, "copiedAt": <RFC 3339 time>}`);
1042
+ return;
1043
+ }
1044
+ if (recorded.has(record.namespace)) add(`${where}: designSystems has the namespace "${record.namespace}" more than once`);
1045
+ recorded.add(record.namespace);
1046
+ });
1047
+ }
1048
+ }
1049
+ for (const folder of folders) {
1050
+ if (!recorded.has(folder)) add(`${DESIGN_SYSTEMS_DIR}/${folder}/ has no record in designSystems; the editor offers a design system only when both are there`);
1051
+ }
1052
+ }
1053
+ function checkIndex(canvas, tree, issues) {
1054
+ const add = (message) => issues.push({ file: CANVAS_FILE, message });
1055
+ if (canvas.title !== void 0 && typeof canvas.title !== "string") add("title must be a string");
1056
+ if (canvas.createdOnFiles !== void 0) {
1057
+ const created = canvas.createdOnFiles;
1058
+ if (!isRecord2(created) || created.v !== 1 || typeof created.at !== "string") add('createdOnFiles must be {"v":1,"at":"<ISO time>"}');
1059
+ }
1060
+ checkDesignSystems(canvas.designSystems, tree, add);
1061
+ const pageIds = /* @__PURE__ */ new Set();
1062
+ if (canvas.pages !== void 0) {
1063
+ if (!Array.isArray(canvas.pages)) add('pages must be an array of {"id","name"}');
1064
+ else {
1065
+ if (canvas.pages.length > MAX_PAGES) add(`pages has ${canvas.pages.length} entries; at most ${MAX_PAGES}`);
1066
+ canvas.pages.forEach((page, i) => {
1067
+ if (!isRecord2(page) || typeof page.id !== "string" || !ID_PATTERN.test(page.id) || typeof page.name !== "string") {
1068
+ add(`pages[${i}] must be {"id": [A-Za-z0-9_-]{1,40}, "name": <string>}`);
1069
+ return;
1070
+ }
1071
+ if (pageIds.has(page.id)) add(`pages has the id "${page.id}" more than once`);
1072
+ pageIds.add(page.id);
1073
+ });
1074
+ }
1075
+ }
1076
+ const boards = /* @__PURE__ */ new Map();
1077
+ for (const [key, value] of Object.entries(canvas.boards)) {
1078
+ const where = `boards["${key}"]`;
1079
+ if (!isCanvasFile(key) || !key.endsWith(BOARD_SUFFIX) || key.split("/")[0] === DESIGN_SYSTEMS_DIR) {
1080
+ add(`${where}: the key must be the artboard file's path, ending in ${BOARD_SUFFIX}, outside ${ASSETS_DIR}/ and ${DESIGN_SYSTEMS_DIR}/, with valid path segments`);
1081
+ } else if (!tree.files.has(key)) {
1082
+ add(`${where}: the file ${key} does not exist; write it or remove the entry`);
1083
+ }
1084
+ if (!isRecord2(value)) {
1085
+ add(`${where} must be an object with x, y, w and h`);
1086
+ boards.set(key, null);
1087
+ continue;
1088
+ }
1089
+ if (!isFiniteNumber(value.x) || !isFiniteNumber(value.y)) add(`${where}: x and y must be numbers`);
1090
+ const sizeOk = (n) => isFiniteNumber(n) && n >= BOARD_SIZE.min && n <= BOARD_SIZE.max;
1091
+ if (!sizeOk(value.w) || !sizeOk(value.h)) add(`${where}: w and h must be numbers from ${BOARD_SIZE.min} to ${BOARD_SIZE.max}`);
1092
+ boards.set(key, sizeOk(value.w) && sizeOk(value.h) ? { w: value.w, h: value.h } : null);
1093
+ if (value.title !== void 0 && typeof value.title !== "string") add(`${where}: title must be a string`);
1094
+ if (value.page !== void 0 && (typeof value.page !== "string" || !pageIds.has(value.page))) add(`${where}: page must be the id of an entry in pages`);
1095
+ if (value.expand !== void 0 && value.expand !== "fill") add(`${where}: expand can only be "fill"`);
1096
+ if (value.print !== void 0 && value.print !== "flow") add(`${where}: print can only be "flow"`);
1097
+ if (value.paper !== void 0 && value.paper !== "letter" && value.paper !== "a4") add(`${where}: paper must be "letter" or "a4"`);
1098
+ if (value.is_interactive !== void 0 && typeof value.is_interactive !== "boolean") add(`${where}: is_interactive must be true or false`);
1099
+ if (value.frameless !== void 0 && typeof value.frameless !== "boolean") add(`${where}: frameless must be true or false`);
1100
+ if (value.radius !== void 0 && !(isFiniteNumber(value.radius) && value.radius >= 0)) add(`${where}: radius must be a number of px, 0 or more`);
1101
+ if (value.guides !== void 0) {
1102
+ if (!Array.isArray(value.guides) || !value.guides.every(isRecord2)) add(`${where}: guides must be an array of guide objects`);
1103
+ else {
1104
+ if (value.guides.length > MAX_GUIDES) add(`${where}: guides has ${value.guides.length} entries; at most ${MAX_GUIDES}`);
1105
+ value.guides.forEach((guide, i) => {
1106
+ if (!GUIDE_KINDS.has(guide.kind)) add(`${where}: guides[${i}].kind must be "columns", "rows" or "grid"`);
1107
+ });
1108
+ }
1109
+ }
1110
+ }
1111
+ if (!Array.isArray(canvas.order)) add("order must be an array of the board paths, back to front");
1112
+ else {
1113
+ const listed = /* @__PURE__ */ new Set();
1114
+ canvas.order.forEach((item, i) => {
1115
+ if (typeof item !== "string" || !boards.has(item)) {
1116
+ add(`order[${i}] (${JSON.stringify(item)}) is not a key of boards`);
1117
+ return;
1118
+ }
1119
+ if (listed.has(item)) add(`order lists ${item} more than once`);
1120
+ listed.add(item);
1121
+ });
1122
+ for (const key of boards.keys()) if (!listed.has(key)) add(`${key} is in boards but not in order`);
1123
+ }
1124
+ if (canvas.notes !== void 0) {
1125
+ if (!isRecord2(canvas.notes)) add('notes must be an object {"<id>": {"x","y","text",\u2026}}');
1126
+ else {
1127
+ const entries = Object.entries(canvas.notes);
1128
+ if (entries.length > MAX_NOTES) add(`notes has ${entries.length} entries; it must stay under ${MAX_NOTES + 1}`);
1129
+ for (const [id, note] of entries) {
1130
+ if (!ID_PATTERN.test(id)) add(`notes: the id "${id}" must match [A-Za-z0-9_-]{1,40}`);
1131
+ if (!isRecord2(note) || !isFiniteNumber(note.x) || !isFiniteNumber(note.y) || typeof note.text !== "string") {
1132
+ add(`notes["${id}"] needs numbers x and y and a string text`);
1133
+ continue;
1134
+ }
1135
+ if (note.kind !== void 0 && !NOTE_KINDS.has(note.kind)) {
1136
+ add(`notes["${id}"].kind must be "title1" (a title over several artboards), left out (a sticky), or one of the user's rect, oval, pen, line, arrow, image`);
1137
+ }
1138
+ if (note.page !== void 0 && (typeof note.page !== "string" || !pageIds.has(note.page))) add(`notes["${id}"].page must be the id of an entry in pages`);
1139
+ }
1140
+ }
1141
+ }
1142
+ if (canvas.launch !== void 0) {
1143
+ const launch = canvas.launch;
1144
+ if (!isRecord2(launch)) add('launch must be {"view":"canvas"} or {"view":"focused","file":"<board path>"}');
1145
+ else if (launch.view === "canvas") {
1146
+ if (launch.page !== void 0 && (typeof launch.page !== "string" || !pageIds.has(launch.page))) add("launch.page must be the id of an entry in pages");
1147
+ } else if (launch.view === "focused") {
1148
+ if (typeof launch.file !== "string" || !boards.has(launch.file)) add("launch.file must be a key of boards");
1149
+ } else add('launch.view must be "canvas" or "focused"');
1150
+ }
1151
+ return boards;
1152
+ }
1153
+ async function checkCanvas(dir) {
1154
+ const issues = [];
1155
+ const tree = await scanTree(dir, issues);
1156
+ const fileCount = tree.files.size;
1157
+ if (tree.truncated || fileCount > CANVAS_LIMITS.files) {
1158
+ issues.push({
1159
+ file: ".",
1160
+ message: `${tree.truncated ? "more than" : "has"} ${tree.truncated ? MAX_SCAN_ENTRIES : fileCount} files outside assets/; a design holds at most ${CANVAS_LIMITS.files} (the editor lists only the first ${CANVAS_LIMITS.files})`
1161
+ });
1162
+ }
1163
+ if (tree.totalBytes > CANVAS_LIMITS.totalBytes) {
1164
+ issues.push({ file: ".", message: `files and assets add up to ${tree.totalBytes} bytes; a design holds at most ${CANVAS_LIMITS.totalBytes} (256 MB)` });
1165
+ }
1166
+ let raw = null;
1167
+ const indexFile = path6.join(dir, CANVAS_FILE);
1168
+ const indexStat = await fs4.lstat(indexFile).catch(() => null);
1169
+ if (indexStat?.isFile()) raw = await fs4.readFile(indexFile, "utf8").catch(() => null);
1170
+ let parsed;
1171
+ if (raw === null) issues.push({ file: CANVAS_FILE, message: 'missing: a design needs canvas.json with "v": 3 and "boards"' });
1172
+ else {
1173
+ try {
1174
+ parsed = JSON.parse(raw);
1175
+ } catch (error) {
1176
+ issues.push({ file: CANVAS_FILE, message: `is not valid JSON: ${error.message}` });
1177
+ }
1178
+ }
1179
+ if (raw !== null && parsed !== void 0 && !isCanvasMetadata(parsed)) {
1180
+ issues.push({ file: CANVAS_FILE, message: 'must be an object with "v": 3 and "boards" as an object keyed by artboard path' });
1181
+ }
1182
+ const canvas = isCanvasMetadata(parsed) ? parsed : null;
1183
+ const boards = canvas ? checkIndex(canvas, tree, issues) : /* @__PURE__ */ new Map();
1184
+ const stems = /* @__PURE__ */ new Map();
1185
+ for (const file of tree.files.keys()) {
1186
+ if (!isBoardPath(file)) continue;
1187
+ const stem = path6.basename(file).slice(0, -BOARD_SUFFIX.length);
1188
+ const other = stems.get(stem);
1189
+ if (other !== void 0) issues.push({ file, message: `has the same name as ${other}; artboard file names (without ${BOARD_SUFFIX}) must be unique` });
1190
+ else stems.set(stem, file);
1191
+ }
1192
+ for (const [file, bytes] of tree.files) {
1193
+ const ext = path6.extname(file).toLowerCase();
1194
+ const board = isBoardPath(file);
1195
+ if (file.split("/")[0] === DESIGN_SYSTEMS_DIR) continue;
1196
+ if (board) {
1197
+ if (canvas && !boards.has(file)) {
1198
+ issues.push({
1199
+ file,
1200
+ message: `is not in canvas.json boards; every ${BOARD_SUFFIX} outside ${DESIGN_SYSTEMS_DIR}/ shows on the canvas, so add a boards entry (w and h = its $preview) and its path in order`
1201
+ });
1202
+ }
1203
+ }
1204
+ if (!board && !TEXT_EXTENSIONS.has(ext)) continue;
1205
+ if (bytes > MAX_BOARD_BYTES) {
1206
+ if (board) issues.push({ file, message: `is ${bytes} bytes; an artboard file should stay well under ${MAX_BOARD_BYTES}` });
1207
+ continue;
1208
+ }
1209
+ const text = await fs4.readFile(path6.join(dir, ...file.split("/")), "utf8").catch(() => null);
1210
+ if (text === null) continue;
1211
+ if (board) checkBoardFile({ file, size: boards.get(file) ?? null, tree, stems, issues }, text);
1212
+ else {
1213
+ checkBlobRefs(file, text, tree.assets, issues);
1214
+ if (ext === ".css") checkCssImports(file, text, issues);
1215
+ }
1216
+ }
1217
+ return {
1218
+ title: canvas ? canvasTitle(canvas, dir) : path6.basename(dir),
1219
+ boardCount: canvas ? Object.keys(canvas.boards).length : 0,
1220
+ issues
1221
+ };
1222
+ }
1223
+
1224
+ import fs5 from "node:fs/promises";
1225
+ import path7 from "node:path";
1226
+ var DESIGN_SYSTEM_FILE = "design-system.json";
1227
+ var BLOBS_DIR = "_blobs";
1228
+ var DESIGN_SYSTEM_LIMITS = {
1229
+ files: 1024,
1230
+ ownFiles: 1008,
1231
+ totalBytes: 256 * 1024 * 1024,
1232
+ fileBytes: 15 * 1024 * 1024,
1233
+ publishBytes: 16 * 1024 * 1024,
1234
+ uploadBytes: 20 * 1024 * 1024,
1235
+ svgUploadBytes: 2 * 1024 * 1024
1236
+ };
1237
+ var DESIGN_SYSTEM_PATHS = {
1238
+ readme: "README.md",
1239
+ tokens: "tokens.json",
1240
+ manifest: "manifest.json",
1241
+ componentsDir: "components/",
1242
+ libDir: "components/lib/",
1243
+ bundleJs: "components/bundle.js",
1244
+ bundleCss: "components/bundle.css",
1245
+ indexDts: "components/index.d.ts",
1246
+ fontsDir: "fonts/",
1247
+ assetsDir: "assets/",
1248
+ archivedDir: "archived/"
1249
+ };
1250
+ var GENERATED_TOKENS_CSS_PATH = "tokens.css";
1251
+ var GENERATED_API_PATH_PATTERN = /^api\/(?:icons\.md|tokens\.md|(?:tokens|components|assets)\/[^/]+\.md)$/;
1252
+ var EDITOR_OWN_FILES = ["migration.json", "design-system.before-files.json", "publish-progress.json", "migration-map.json"];
1253
+ var WINDOW_NAMESPACE_PATTERN = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
1254
+ var COMPONENT_NAME_PATTERN = WINDOW_NAMESPACE_PATTERN;
1255
+ var MAX_DESIGN_SYSTEM_PATH_LENGTH = 300;
1256
+ var MAX_RUNTIME_PATH_UTF8_BYTES = 512;
1257
+ var UNSAFE_PATH_CHARACTER_PATTERN = /[\u0000-\u001f\u007f-\u009f\u200b\u200e\u200f\u202a-\u202e\u2028\u2029\u2060-\u206f\u2215\u2044\ufeff\uff0f]/;
1258
+ var RUNTIME_PATH_RESERVED_CHARACTERS = /[%;:\\]/;
1259
+ var INVISIBLE_PATH_CHARACTER_PATTERN = /[\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g;
1260
+ var RESERVED_PROTOTYPE_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1261
+ var REFUSED_TOOL_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules"]);
1262
+ var REFUSED_TOOL_FILENAMES = /* @__PURE__ */ new Set([
1263
+ "package.json",
1264
+ "package-lock.json",
1265
+ "yarn.lock",
1266
+ "pnpm-lock.yaml",
1267
+ "bun.lock",
1268
+ "bun.lockb",
1269
+ "bunfig.toml",
1270
+ "tsconfig.json",
1271
+ "jsconfig.json",
1272
+ "deno.json",
1273
+ "deno.jsonc",
1274
+ "claude.md",
1275
+ "claude.local.md",
1276
+ "agents.md"
1277
+ ]);
1278
+ var WINDOWS_SHORT_NAME_PATTERN = /~\d/;
1279
+ var IMAGE_SLOT_STATE_FILENAME = ".image-slots.state.json";
1280
+ function comparableSegment(segment) {
1281
+ let normalized = segment.replace(INVISIBLE_PATH_CHARACTER_PATTERN, "");
1282
+ const colon = normalized.indexOf(":");
1283
+ if (colon >= 0) normalized = normalized.slice(0, colon);
1284
+ return normalized.normalize("NFC").toUpperCase().toLowerCase().replace(/[. ]+$/, "");
1285
+ }
1286
+ function comparablePath(rel) {
1287
+ return rel.split("/").map(comparableSegment).join("/");
1288
+ }
1289
+ function isImageSlotStatePath(rel) {
1290
+ const parts = rel.split("/");
1291
+ return parts[parts.length - 1] === IMAGE_SLOT_STATE_FILENAME && !parts.slice(0, -1).some((p) => comparableSegment(p).startsWith("."));
1292
+ }
1293
+ function explainToolConfigurationPath(rel) {
1294
+ const parts = rel.split("/").map(comparableSegment);
1295
+ if (parts.some((p) => p.startsWith(".")) && !isImageSlotStatePath(rel)) {
1296
+ return "is a dot-file or dot-directory (tool, editor, VCS or agent configuration); never part of a design system";
1297
+ }
1298
+ if (REFUSED_TOOL_FILENAMES.has(parts[parts.length - 1] ?? "") || parts.some((p) => REFUSED_TOOL_DIRECTORIES.has(p))) {
1299
+ return "is a package-manager, toolchain or agent-instruction file that tools auto-load from a working directory; never part of a design system";
1300
+ }
1301
+ if (parts.some((p) => WINDOWS_SHORT_NAME_PATTERN.test(p))) {
1302
+ return 'has a path segment shaped like a Windows 8.3 short name (NAME~1); rename it without the "~digit"';
1303
+ }
1304
+ return null;
1305
+ }
1306
+ function explainReservedSystemPath(rel) {
1307
+ const normalized = comparablePath(rel);
1308
+ const under = (name) => normalized === name || normalized.startsWith(`${name}/`);
1309
+ if (under(DESIGN_SYSTEM_FILE)) return `is reserved: ${DESIGN_SYSTEM_FILE} is the index; rename the file`;
1310
+ if (under("index.html")) return "is reserved: index.html is the page itself in the original format; rename the file";
1311
+ if (under("skill.md") || under("artifact-type")) {
1312
+ return "is reserved: SKILL.md and artifact-type/ are the design system type\u2019s own files in the original format; rename the file";
1313
+ }
1314
+ return null;
1315
+ }
1316
+ function explainDesignSystemPath(rel) {
1317
+ if (rel.length === 0 || rel.length > MAX_DESIGN_SYSTEM_PATH_LENGTH || Buffer.byteLength(`project/${rel}`, "utf8") > MAX_RUNTIME_PATH_UTF8_BYTES) {
1318
+ return `is empty or longer than ${MAX_DESIGN_SYSTEM_PATH_LENGTH} characters; rename it`;
1319
+ }
1320
+ if (rel.startsWith("/") || UNSAFE_PATH_CHARACTER_PATTERN.test(rel) || RUNTIME_PATH_RESERVED_CHARACTERS.test(rel)) {
1321
+ return "has a character a design system path cannot hold (a control or invisible character, a look-alike slash, % ; : or \\); rename it";
1322
+ }
1323
+ if (rel.endsWith(".cmekshadow")) return "ends in .cmekshadow, which is reserved; rename it";
1324
+ for (const part of rel.split("/")) {
1325
+ if (part === "" || part === "." || part === "..") return "has an empty path segment or one that is only dots; rename it";
1326
+ if (RESERVED_PROTOTYPE_NAMES.has(part)) return `uses "${part}" as a path segment, which is reserved; rename it`;
1327
+ }
1328
+ return explainToolConfigurationPath(rel) ?? explainReservedSystemPath(rel);
1329
+ }
1330
+ function isBlobsPath(rel) {
1331
+ return rel === BLOBS_DIR || rel.startsWith(`${BLOBS_DIR}/`);
1332
+ }
1333
+ function isDesignSystemFile(rel) {
1334
+ if (rel === DESIGN_SYSTEM_FILE) return true;
1335
+ return !isBlobsPath(rel) && explainDesignSystemPath(rel) === null;
1336
+ }
1337
+ function descendInto(rel) {
1338
+ return !isBlobsPath(rel) && explainDesignSystemPath(rel) === null;
1339
+ }
1340
+ function designSystemUploadLimit(contentType) {
1341
+ const type = contentType.split(";")[0].trim().toLowerCase();
1342
+ return type === "image/svg+xml" ? DESIGN_SYSTEM_LIMITS.svgUploadBytes : DESIGN_SYSTEM_LIMITS.uploadBytes;
1343
+ }
1344
+ var DESIGN_SYSTEM_LAYOUT = {
1345
+ blobDir: BLOBS_DIR,
1346
+ isFile: isDesignSystemFile,
1347
+ roots: [{ rel: "", descend: true }],
1348
+ descendInto,
1349
+ watches: (rel) => isDesignSystemFile(rel) || descendInto(rel),
1350
+ maxFiles: DESIGN_SYSTEM_LIMITS.files,
1351
+ maxPublishBytes: DESIGN_SYSTEM_LIMITS.publishBytes,
1352
+ maxFileBytes: DESIGN_SYSTEM_LIMITS.fileBytes,
1353
+ maxBlobBytes: designSystemUploadLimit,
1354
+ readOnlyMessage: (p) => {
1355
+ const rel = p.startsWith("project/") ? p.slice("project/".length) : p;
1356
+ if (isBlobsPath(rel)) return `${p}: ${BLOBS_DIR}/ holds uploads and can't be written; upload the file instead`;
1357
+ return `${p}: ${explainDesignSystemPath(rel) ?? "is not a design system file"}`;
1358
+ }
1359
+ };
1360
+ var MAX_INDEX_BYTES = 8 * 1024 * 1024;
1361
+ var MAX_DESIGN_SYSTEM_INDEX_CHARS = 2e6;
1362
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1363
+ function isDesignSystemIndex(value) {
1364
+ return isRecord3(value) && !isRecord3(value.content) && (hasDesignSystemMarker(value) || typeof value.v === "number" && value.v >= 3 && value.layout === "files");
1365
+ }
1366
+ function hasDesignSystemMarker(index) {
1367
+ return isRecord3(index.createdOnFiles) || isRecord3(index.convertedFrom);
1368
+ }
1369
+ async function readDesignSystemJson(dir) {
1370
+ const file = path7.join(dir, DESIGN_SYSTEM_FILE);
1371
+ try {
1372
+ const stat = await fs5.lstat(file);
1373
+ if (!stat.isFile() || stat.size > MAX_INDEX_BYTES) return null;
1374
+ return JSON.parse(await fs5.readFile(file, "utf8"));
1375
+ } catch {
1376
+ return null;
1377
+ }
1378
+ }
1379
+ function designSystemTitle(index, dir) {
1380
+ const raw = index.title;
1381
+ const title = typeof raw === "string" ? raw.trim() : "";
1382
+ return title || path7.basename(dir);
1383
+ }
1384
+ function designSystemNamespace(index) {
1385
+ const raw = index.namespace;
1386
+ return typeof raw === "string" && WINDOW_NAMESPACE_PATTERN.test(raw) ? raw : null;
1387
+ }
1388
+ async function readDesignSystemInfo(dir) {
1389
+ const parsed = await readDesignSystemJson(dir);
1390
+ if (!isDesignSystemIndex(parsed)) return null;
1391
+ return { title: designSystemTitle(parsed, dir), namespace: designSystemNamespace(parsed) };
1392
+ }
1393
+
1394
+ var TOKENS_LIMITS = {
1395
+ bytes: 512 * 1024,
1396
+ themes: 8,
1397
+ colors: 600,
1398
+ fontFaces: 4096,
1399
+ fontFamilies: 12,
1400
+ typographyGroups: 12,
1401
+ typographyStyles: 80,
1402
+ tokensPerFamily: 60,
1403
+ extraFamilies: 12,
1404
+ colorAliasDepth: 16
1405
+ };
1406
+ var TOKEN_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
1407
+ var HEX_COLOR_PATTERN = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;
1408
+ var COLOR_ALIAS_PATTERN = /^\{([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\}$/;
1409
+ var EXTRA_TOKEN_FAMILY_PATTERN = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z][A-Za-z0-9_-]{0,31}$/;
1410
+ var BUILTIN_TOKEN_DOCUMENT_KEYS = ["version", "color", "type", "spacing", "radius", "shadow"];
1411
+ var COLOR_FUNCTION_PATTERN = /^(?:rgb|rgba|hsl|hsla|oklch|oklab|lab|lch|color)\([0-9a-z.,%/ \-]{1,60}\)$/;
1412
+ var CSS_LENGTH_PATTERN = /^-?\d{1,4}(?:\.\d{1,6})?(?:px|rem|em|%)$|^0$/;
1413
+ var FONT_STACK_PATTERN = /^[^;{}<>()\\\r\n\f]{1,200}$/;
1414
+ var BOX_SHADOW_PATTERN = /^[a-z0-9 #%(),./+-]{1,400}$/;
1415
+ var MOTION_DURATION_PATTERN = /^(?:\d{1,6}(?:\.\d{1,3})?|\.\d{1,3})m?s$/;
1416
+ var MOTION_EASING_PATTERN = /^(?:linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|cubic-bezier\([-\d., ]{1,60}\)|steps\([a-z0-9, -]{1,40}\))$/;
1417
+ var EXTRA_TOKEN_VALUE_PATTERN = /^[A-Za-z0-9 #%(),./+_-]{1,200}$/;
1418
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1419
+ var asArray = (value) => Array.isArray(value) ? value : [];
1420
+ function isSafeFontStack(stack) {
1421
+ if (!FONT_STACK_PATTERN.test(stack) || stack.includes("/*") || stack.includes("*/")) return false;
1422
+ let quote2 = null;
1423
+ for (const ch of stack) {
1424
+ if (quote2 === null) {
1425
+ if (ch === '"' || ch === "'") quote2 = ch;
1426
+ } else if (ch === quote2) quote2 = null;
1427
+ }
1428
+ return quote2 === null;
1429
+ }
1430
+ function isColorLiteral(value) {
1431
+ return typeof value === "string" && (HEX_COLOR_PATTERN.test(value) || COLOR_FUNCTION_PATTERN.test(value) && !/url|var|expression/.test(value));
1432
+ }
1433
+ function balanced(value) {
1434
+ let depth = 0;
1435
+ for (const ch of value) {
1436
+ if (ch === "(") depth++;
1437
+ else if (ch === ")" && --depth < 0) return false;
1438
+ }
1439
+ return depth === 0;
1440
+ }
1441
+ function normalizeBoxShadow(value) {
1442
+ if (typeof value !== "string") return void 0;
1443
+ const normalized = value.trim().toLowerCase().replace(/\s+/g, " ");
1444
+ if (!BOX_SHADOW_PATTERN.test(normalized) || /(?:url|var|expression|image|image-set|src)\s*\(/.test(normalized) || normalized === "") return void 0;
1445
+ return balanced(normalized) ? normalized : void 0;
1446
+ }
1447
+ function normalizeMotionValue(value) {
1448
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value < 1e6) return `${Math.round(value)}ms`;
1449
+ if (typeof value !== "string") return void 0;
1450
+ let normalized = value.trim().toLowerCase().replace(/\s+/g, " ");
1451
+ if (normalized.startsWith(".")) normalized = "0" + normalized;
1452
+ return MOTION_DURATION_PATTERN.test(normalized) || MOTION_EASING_PATTERN.test(normalized) ? normalized : void 0;
1453
+ }
1454
+ function normalizeExtraTokenValue(value) {
1455
+ if (typeof value === "number" && Number.isFinite(value) && Math.abs(value) < 1e6) return String(value);
1456
+ if (typeof value !== "string") return void 0;
1457
+ const normalized = value.trim().replace(/\s+/g, " ");
1458
+ if (!EXTRA_TOKEN_VALUE_PATTERN.test(normalized) || /(?:url|var|expression|image|image-set|src)\s*\(/i.test(normalized)) return void 0;
1459
+ return balanced(normalized) ? normalized : void 0;
1460
+ }
1461
+ function normalizeColorOrAlias(value) {
1462
+ if (typeof value !== "string") return void 0;
1463
+ const literal = value.trim().toLowerCase();
1464
+ if (isColorLiteral(literal)) return literal;
1465
+ const alias = value.trim().replace(/^\{--/, "{");
1466
+ return COLOR_ALIAS_PATTERN.test(alias) ? alias : void 0;
1467
+ }
1468
+ function normalizeCssLength(value, allowFullRadius) {
1469
+ if (typeof value === "number" && Number.isFinite(value)) {
1470
+ if (Math.abs(value) >= 1e4) return void 0;
1471
+ return value === 0 ? "0" : `${Math.round(value * 1e3) / 1e3}px`;
1472
+ }
1473
+ if (typeof value !== "string") return void 0;
1474
+ const normalized = value.trim().toLowerCase();
1475
+ if (allowFullRadius && normalized === "full") return "9999px";
1476
+ return CSS_LENGTH_PATTERN.test(normalized) ? normalized : void 0;
1477
+ }
1478
+ var colorAliasTarget = (value) => value === void 0 ? void 0 : COLOR_ALIAS_PATTERN.exec(value)?.[1];
1479
+ function explainColorAliasError(token2, themeId, baseThemeId, byName) {
1480
+ const seen = /* @__PURE__ */ new Set([token2.name]);
1481
+ let current = token2;
1482
+ for (let index = 0; index <= TOKENS_LIMITS.colorAliasDepth; index++) {
1483
+ const target = colorAliasTarget(current.value[themeId] ?? current.value[baseThemeId]);
1484
+ if (target === void 0) return void 0;
1485
+ const entry = byName.get(target);
1486
+ if (entry === void 0) return { why: `${index === 0 ? "" : `reaches {${target}}, which `}names no color token`, own: index === 0 };
1487
+ if (seen.has(target)) return { why: "is a cycle", own: target === token2.name };
1488
+ seen.add(target);
1489
+ current = entry;
1490
+ }
1491
+ return { why: `chains deeper than ${TOKENS_LIMITS.colorAliasDepth}`, own: true };
1492
+ }
1493
+ function removeInvalidColorAliases(themes, tokens, dropped) {
1494
+ const baseThemeId = themes[0].id;
1495
+ for (; ; ) {
1496
+ const byName = new Map(tokens.map((t) => [t.name, t]));
1497
+ const items = [];
1498
+ for (const token2 of tokens) {
1499
+ for (const theme of themes) {
1500
+ if (colorAliasTarget(token2.value[theme.id]) === void 0) continue;
1501
+ const error = explainColorAliasError(token2, theme.id, baseThemeId, byName);
1502
+ if (error !== void 0) items.push([token2, theme.id, error.why, error.own]);
1503
+ }
1504
+ }
1505
+ if (items.length === 0) return;
1506
+ const anyOwn = items.some((item) => item[3]);
1507
+ for (const [token2, themeId, why, own] of items) {
1508
+ if (anyOwn && !own) continue;
1509
+ dropped.push(`color ${token2.name} [${themeId}]: ${String(token2.value[themeId])} ${why}`);
1510
+ delete token2.value[themeId];
1511
+ }
1512
+ for (let index = 0; index < tokens.length; index++) {
1513
+ const token2 = tokens[index];
1514
+ if (Object.hasOwn(token2.value, baseThemeId)) continue;
1515
+ const theme = themes.find((t) => Object.hasOwn(token2.value, t.id));
1516
+ if (theme === void 0) {
1517
+ dropped.push(`color ${token2.name}: no valid value`);
1518
+ tokens.splice(index--, 1);
1519
+ } else {
1520
+ token2.value[baseThemeId] = token2.value[theme.id];
1521
+ delete token2.value[theme.id];
1522
+ }
1523
+ }
1524
+ }
1525
+ }
1526
+ function shapeProblem(key, value) {
1527
+ if (!isObject(value)) return `"${key}" must be an object {"tokens":[{"name","value","usage"}\u2026]}`;
1528
+ if (!Array.isArray(value.tokens)) {
1529
+ return `"${key}" is not shaped {"tokens":[{"name","value","usage"}\u2026]}: a name-to-value map is valid JSON the editor cannot read (the family shows empty and its entries leave the file at the first token edit); make it a list`;
1530
+ }
1531
+ return null;
1532
+ }
1533
+ function checkTokensText(text) {
1534
+ const problems = [];
1535
+ const notes = [];
1536
+ const dropped = [];
1537
+ let source;
1538
+ try {
1539
+ const parsed = JSON.parse(text);
1540
+ if (!isObject(parsed)) return { problems: ["is not a JSON object"], notes };
1541
+ source = parsed;
1542
+ } catch (error) {
1543
+ return { problems: [`is not valid JSON: ${String(error.message).slice(0, 120)}`], notes };
1544
+ }
1545
+ if (Object.hasOwn(source, "color") && !isObject(source.color)) problems.push('"color" must be an object {"themes":[\u2026],"tokens":[\u2026]}');
1546
+ const sourceColor = isObject(source.color) ? source.color : {};
1547
+ if (isObject(source.color) && !Array.isArray(sourceColor.tokens) && !Array.isArray(sourceColor.groups) && Object.hasOwn(sourceColor, "tokens")) {
1548
+ problems.push('"color.tokens" is not a list: a name-to-value map is valid JSON the editor cannot read; make it [{"name","value","usage"}\u2026]');
1549
+ }
1550
+ if (isObject(source.color) && !Object.hasOwn(sourceColor, "tokens") && !Object.hasOwn(sourceColor, "groups")) {
1551
+ const keys = Object.keys(sourceColor).filter((k) => k !== "themes" && k !== "note");
1552
+ if (keys.length > 0) problems.push('"color" has no "tokens" list: a name-to-value map is valid JSON the editor cannot read; make it {"themes":[\u2026],"tokens":[{"name","value","usage"}\u2026]}');
1553
+ }
1554
+ const sourceThemes = asArray(sourceColor.themes);
1555
+ if (sourceThemes.length > TOKENS_LIMITS.themes) problems.push(`color has ${sourceThemes.length} themes; at most ${TOKENS_LIMITS.themes} are read`);
1556
+ const themes = [];
1557
+ const themeIds = /* @__PURE__ */ new Set();
1558
+ for (const theme of sourceThemes) {
1559
+ if (themes.length >= TOKENS_LIMITS.themes) break;
1560
+ const id = isObject(theme) && typeof theme.id === "string" ? theme.id.trim().toLowerCase() : typeof theme === "string" ? theme.trim().toLowerCase() : "";
1561
+ if (!TOKEN_NAME_PATTERN.test(id) || themeIds.has(id) || id === "constructor" || id === "prototype" || Object.hasOwn(Object.prototype, id)) {
1562
+ dropped.push(`theme ${JSON.stringify(id)}: bad or duplicate id`);
1563
+ continue;
1564
+ }
1565
+ themeIds.add(id);
1566
+ themes.push({ id });
1567
+ }
1568
+ if (themes.length === 0) themes.push({ id: "light" });
1569
+ const baseThemeId = themes[0].id;
1570
+ const colorNames = /* @__PURE__ */ new Set();
1571
+ const colorTokens = [];
1572
+ const sourceColorTokens = Array.isArray(sourceColor.tokens) ? asArray(sourceColor.tokens) : asArray(sourceColor.groups).flatMap((group) => isObject(group) ? asArray(group.tokens) : []);
1573
+ if (Array.isArray(sourceColor.tokens) && Array.isArray(sourceColor.groups)) {
1574
+ problems.push('color has both "tokens" and a legacy "groups"; only "tokens" is read');
1575
+ }
1576
+ if (sourceColorTokens.length > TOKENS_LIMITS.colors) problems.push(`color tokens capped at ${TOKENS_LIMITS.colors}; the rest are ignored`);
1577
+ for (const token2 of sourceColorTokens) {
1578
+ if (colorTokens.length >= TOKENS_LIMITS.colors) break;
1579
+ if (!isObject(token2)) continue;
1580
+ const name = typeof token2.name === "string" ? token2.name.trim().replace(/^--/, "") : "";
1581
+ if (!TOKEN_NAME_PATTERN.test(name) || colorNames.has(name)) {
1582
+ dropped.push(`color ${JSON.stringify(name)}: bad or duplicate name`);
1583
+ continue;
1584
+ }
1585
+ const value = {};
1586
+ if (isObject(token2.value)) {
1587
+ for (const theme of themes) {
1588
+ const normalized = Object.hasOwn(token2.value, theme.id) ? normalizeColorOrAlias(token2.value[theme.id]) : void 0;
1589
+ if (normalized !== void 0) value[theme.id] = normalized;
1590
+ else if (Object.hasOwn(token2.value, theme.id)) dropped.push(`color ${name} [${theme.id}]: not a color value`);
1591
+ }
1592
+ } else {
1593
+ const normalized = normalizeColorOrAlias(token2.value);
1594
+ if (normalized !== void 0) value[baseThemeId] = normalized;
1595
+ }
1596
+ if (!Object.hasOwn(value, baseThemeId)) {
1597
+ const borrowed = themes.map((t) => value[t.id]).find((v) => v !== void 0);
1598
+ if (borrowed === void 0) {
1599
+ dropped.push(`color ${name}: no valid value`);
1600
+ continue;
1601
+ }
1602
+ value[baseThemeId] = borrowed;
1603
+ }
1604
+ colorNames.add(name);
1605
+ colorTokens.push({ name, value });
1606
+ }
1607
+ removeInvalidColorAliases(themes, colorTokens, dropped);
1608
+ if (Object.hasOwn(source, "type") && !isObject(source.type)) problems.push('"type" must be an object {"fonts":[\u2026],"families":{\u2026},"groups":[\u2026]}');
1609
+ const sourceType = isObject(source.type) ? source.type : {};
1610
+ for (const key of ["fonts", "groups"]) {
1611
+ if (Object.hasOwn(sourceType, key) && !Array.isArray(sourceType[key])) problems.push(`"type.${key}" must be a list`);
1612
+ }
1613
+ if (Object.hasOwn(sourceType, "families") && !isObject(sourceType.families)) problems.push('"type.families" must be an object {"<key>":"<font stack>"}');
1614
+ const sourceFonts = asArray(sourceType.fonts);
1615
+ if (sourceFonts.length > TOKENS_LIMITS.fontFaces) {
1616
+ notes.push(`type.fonts: ${sourceFonts.length - TOKENS_LIMITS.fontFaces} entries after the first ${TOKENS_LIMITS.fontFaces} fonts are kept in the file but not read`);
1617
+ }
1618
+ for (const font of sourceFonts.slice(0, TOKENS_LIMITS.fontFaces)) {
1619
+ if (!isObject(font)) continue;
1620
+ const family = typeof font.family === "string" ? font.family.trim() : "";
1621
+ const file = typeof font.file === "string" ? font.file.trim() : "";
1622
+ if (family === "" || !isSafeFontStack(family) || /["']/.test(family)) {
1623
+ dropped.push(`font ${JSON.stringify(file)}: bad family name`);
1624
+ continue;
1625
+ }
1626
+ if (file === "" || /^[a-z][a-z0-9+.-]*:/i.test(file)) {
1627
+ dropped.push(`font ${JSON.stringify(family)}: bad file path (a relative path into the system, e.g. fonts/Name.woff2)`);
1628
+ }
1629
+ }
1630
+ const families = {};
1631
+ if (isObject(sourceType.families)) {
1632
+ const keys = Object.keys(sourceType.families);
1633
+ if (keys.length > TOKENS_LIMITS.fontFamilies) problems.push(`type.families has ${keys.length} families; at most ${TOKENS_LIMITS.fontFamilies} are read`);
1634
+ let index = 0;
1635
+ for (const key of keys) {
1636
+ if (index >= TOKENS_LIMITS.fontFamilies) break;
1637
+ const id = key.trim().toLowerCase();
1638
+ const stack = sourceType.families[key];
1639
+ if (!TOKEN_NAME_PATTERN.test(id) || typeof stack !== "string" || !isSafeFontStack(stack.trim())) {
1640
+ dropped.push(`font family ${JSON.stringify(key)}: bad key or stack`);
1641
+ continue;
1642
+ }
1643
+ families[id] = stack.trim();
1644
+ index++;
1645
+ }
1646
+ }
1647
+ const sourceGroups = asArray(sourceType.groups);
1648
+ if (sourceGroups.length > TOKENS_LIMITS.typographyGroups) problems.push(`type.groups has ${sourceGroups.length} groups; at most ${TOKENS_LIMITS.typographyGroups} are read`);
1649
+ const styleNames = /* @__PURE__ */ new Set();
1650
+ let styleCount = 0;
1651
+ let stylesSeen = 0;
1652
+ for (const group of sourceGroups.slice(0, TOKENS_LIMITS.typographyGroups)) {
1653
+ if (!isObject(group)) continue;
1654
+ if (Object.hasOwn(group, "styles") && !Array.isArray(group.styles)) problems.push(`type group ${JSON.stringify(group.name ?? "")}: "styles" must be a list`);
1655
+ for (const style of asArray(group.styles)) {
1656
+ stylesSeen++;
1657
+ if (styleCount >= TOKENS_LIMITS.typographyStyles) continue;
1658
+ if (!isObject(style)) continue;
1659
+ const name = typeof style.name === "string" ? style.name.trim().replace(/^\./, "") : "";
1660
+ if (!TOKEN_NAME_PATTERN.test(name) || styleNames.has(name)) {
1661
+ dropped.push(`type style ${JSON.stringify(name)}: bad or duplicate name`);
1662
+ continue;
1663
+ }
1664
+ if (normalizeCssLength(style.fontSize, false) === void 0) {
1665
+ dropped.push(`type style ${name}: bad fontSize`);
1666
+ continue;
1667
+ }
1668
+ styleNames.add(name);
1669
+ styleCount++;
1670
+ }
1671
+ }
1672
+ if (stylesSeen > TOKENS_LIMITS.typographyStyles) problems.push(`type has ${stylesSeen} styles; at most ${TOKENS_LIMITS.typographyStyles} are read`);
1673
+ const familyOf = new Map(colorTokens.map((t) => [t.name, "color"]));
1674
+ const scalarFamily = (input, family, normalize) => {
1675
+ const tokens = asArray(isObject(input) ? input.tokens : void 0);
1676
+ if (tokens.length > TOKENS_LIMITS.tokensPerFamily) problems.push(`${family} has ${tokens.length} tokens; at most ${TOKENS_LIMITS.tokensPerFamily} are read`);
1677
+ let count = 0;
1678
+ for (const token2 of tokens) {
1679
+ if (count >= TOKENS_LIMITS.tokensPerFamily) break;
1680
+ if (!isObject(token2)) continue;
1681
+ const name = typeof token2.name === "string" ? token2.name.trim().replace(/^--/, "") : "";
1682
+ const other = familyOf.get(name);
1683
+ if (!TOKEN_NAME_PATTERN.test(name) || other === family) {
1684
+ dropped.push(`${family} ${JSON.stringify(name)}: bad or duplicate name`);
1685
+ continue;
1686
+ }
1687
+ if (other !== void 0) {
1688
+ dropped.push(`${family} ${name}: a ${other} token already has that name (one --${name} across every family)`);
1689
+ continue;
1690
+ }
1691
+ if (normalize(token2.value, name) === void 0) {
1692
+ dropped.push(`${family} ${name}: bad value`);
1693
+ continue;
1694
+ }
1695
+ familyOf.set(name, family);
1696
+ count++;
1697
+ }
1698
+ };
1699
+ const shadowValue = (input, name) => {
1700
+ const value = {};
1701
+ if (isObject(input)) {
1702
+ for (const theme of themes) {
1703
+ if (!Object.hasOwn(input, theme.id)) continue;
1704
+ const normalized = normalizeBoxShadow(input[theme.id]);
1705
+ if (normalized !== void 0) value[theme.id] = normalized;
1706
+ else dropped.push(`shadow ${name} [${theme.id}]: not a box-shadow value`);
1707
+ }
1708
+ } else {
1709
+ const normalized = normalizeBoxShadow(input);
1710
+ if (normalized !== void 0) value[baseThemeId] = normalized;
1711
+ }
1712
+ if (!Object.hasOwn(value, baseThemeId)) {
1713
+ const theme = themes.find((t) => Object.hasOwn(value, t.id));
1714
+ if (theme === void 0) return void 0;
1715
+ value[baseThemeId] = value[theme.id];
1716
+ }
1717
+ return value;
1718
+ };
1719
+ for (const key of ["spacing", "radius"]) {
1720
+ if (Object.hasOwn(source, key)) {
1721
+ const shape = shapeProblem(key, source[key]);
1722
+ if (shape) problems.push(shape);
1723
+ }
1724
+ }
1725
+ scalarFamily(source.spacing, "spacing", (value) => normalizeCssLength(value, false));
1726
+ scalarFamily(source.radius, "radius", (value) => normalizeCssLength(value, true));
1727
+ scalarFamily(source.shadow, "shadow", shadowValue);
1728
+ if (Object.hasOwn(source, "shadow") && !(isObject(source.shadow) && Array.isArray(source.shadow.tokens))) {
1729
+ notes.push('"shadow" is not shaped {"tokens":[{name,value,usage}]}: kept in the file, not shown');
1730
+ }
1731
+ let extraCount = 0;
1732
+ for (const key of Object.keys(source)) {
1733
+ if (BUILTIN_TOKEN_DOCUMENT_KEYS.includes(key)) continue;
1734
+ const value = source[key];
1735
+ if (key === "name" && typeof value === "string") continue;
1736
+ if (!EXTRA_TOKEN_FAMILY_PATTERN.test(key) || !isObject(value) || !Array.isArray(value.tokens)) {
1737
+ notes.push(`${JSON.stringify(key.slice(0, 40))} is not a token family ({"tokens":[{name,value,usage}]}): kept in the file, not shown`);
1738
+ continue;
1739
+ }
1740
+ if (extraCount >= TOKENS_LIMITS.extraFamilies) {
1741
+ notes.push(`token families beyond the built-in ones are capped at ${TOKENS_LIMITS.extraFamilies}: ${JSON.stringify(key)} is kept in the file, not shown`);
1742
+ continue;
1743
+ }
1744
+ extraCount++;
1745
+ scalarFamily(value, key, key === "motion" ? (v) => normalizeMotionValue(v) ?? normalizeExtraTokenValue(v) : normalizeExtraTokenValue);
1746
+ }
1747
+ return { problems: [...problems, ...dropped], notes };
1748
+ }
1749
+ function tokenFontFiles(text) {
1750
+ try {
1751
+ const parsed = JSON.parse(text);
1752
+ if (!isObject(parsed) || !isObject(parsed.type)) return [];
1753
+ const files = [];
1754
+ for (const font of asArray(parsed.type.fonts)) {
1755
+ if (!isObject(font) || typeof font.file !== "string") continue;
1756
+ const file = font.file.trim();
1757
+ if (file === "" || /^[a-z][a-z0-9+.-]*:/i.test(file)) continue;
1758
+ files.push(file.includes("/") ? file : `fonts/${file}`);
1759
+ }
1760
+ return files;
1761
+ } catch {
1762
+ return [];
1763
+ }
1764
+ }
1765
+
1766
+ import fs6 from "node:fs/promises";
1767
+ import path8 from "node:path";
1768
+ var DESIGN_SYSTEM_NOT_CHECKED = [DESIGN_SYSTEM_PATHS.manifest, GENERATED_TOKENS_CSS_PATH, "api/"];
1769
+ var KIB = 1024;
1770
+ var MIB = 1024 * 1024;
1771
+ var DESIGN_SYSTEM_FILE_LIMITS = {
1772
+ readme: 200 * KIB,
1773
+ tokens: 512 * KIB,
1774
+ bundleJs: 6 * MIB,
1775
+ bundleCss: 2 * MIB,
1776
+ dtsTotal: 1.5 * MIB,
1777
+ preview: 256 * KIB,
1778
+ componentReadme: 64 * KIB,
1779
+ componentLib: 2 * MIB,
1780
+ asset: 12 * MIB,
1781
+ other: 512 * KIB
1782
+ };
1783
+ var MAX_SECTION_DOCUMENTS = 24;
1784
+ var MAX_SCAN_ENTRIES2 = 2e4;
1785
+ var MAX_READ_BYTES = 8 * MIB;
1786
+ var FONT_EXTENSIONS = {
1787
+ woff2: "WOFF2",
1788
+ woff: "WOFF",
1789
+ ttf: "TrueType",
1790
+ otf: "OpenType",
1791
+ ttc: "TrueType Collection"
1792
+ };
1793
+ var FORBIDDEN_PREVIEW_ELEMENTS = ["iframe", "frame", "object", "embed", "portal", "noscript"];
1794
+ var CARD_HEADER_PATTERN = /^[ \t]*<!--\s*@dsCard\b((?:(?!--)[^\r\n])*)(?:[\r\n]\s*)?-->/;
1795
+ var ASSET_TILE_SIZES = /* @__PURE__ */ new Set(["xs", "s", "m", "l", "xl"]);
1796
+ var MAX_ASSET_GROUP_NAME_LENGTH = 80;
1797
+ var RESERVED_PROTOTYPE_NAMES2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1798
+ var TEXT_EXTENSIONS2 = /* @__PURE__ */ new Set(["md", "mdx", "markdown", "txt", "json", "js", "mjs", "cjs", "jsx", "ts", "tsx", "css", "html", "htm", "svg", "xml", "csv", "yml", "yaml", "toml"]);
1799
+ var BLOB_ID = BLOB_ID_PATTERN;
1800
+ function extensionOf(rel) {
1801
+ const base = rel.slice(rel.lastIndexOf("/") + 1).toLowerCase();
1802
+ if (base.endsWith(".d.ts")) return "d.ts";
1803
+ const dot = base.lastIndexOf(".");
1804
+ return dot <= 0 ? "" : base.slice(dot + 1);
1805
+ }
1806
+ function isSectionDocument(rel) {
1807
+ return rel !== DESIGN_SYSTEM_PATHS.readme && !rel.startsWith(DESIGN_SYSTEM_PATHS.componentsDir) && !rel.startsWith(DESIGN_SYSTEM_PATHS.assetsDir) && !rel.startsWith(DESIGN_SYSTEM_PATHS.fontsDir) && !rel.startsWith(DESIGN_SYSTEM_PATHS.archivedDir) && !GENERATED_API_PATH_PATTERN.test(rel) && /\.(?:mdx?|markdown)$/i.test(rel);
1808
+ }
1809
+ function classify(rel) {
1810
+ if (rel === DESIGN_SYSTEM_FILE) return "index";
1811
+ if (EDITOR_OWN_FILES.includes(rel)) return "own";
1812
+ if (rel === DESIGN_SYSTEM_PATHS.manifest || rel === GENERATED_TOKENS_CSS_PATH || rel.startsWith("api/")) return "generated";
1813
+ if (rel === DESIGN_SYSTEM_PATHS.readme) return "readme";
1814
+ if (rel === DESIGN_SYSTEM_PATHS.tokens) return "tokens";
1815
+ if (rel.startsWith(DESIGN_SYSTEM_PATHS.archivedDir)) return "archived";
1816
+ if (isSectionDocument(rel)) return "doc";
1817
+ if (rel === DESIGN_SYSTEM_PATHS.bundleJs) return "bundleJs";
1818
+ if (rel === DESIGN_SYSTEM_PATHS.bundleCss) return "bundleCss";
1819
+ if (rel.startsWith(DESIGN_SYSTEM_PATHS.componentsDir)) {
1820
+ if (rel.startsWith(DESIGN_SYSTEM_PATHS.libDir)) return "componentLib";
1821
+ if (extensionOf(rel) === "d.ts") return "dts";
1822
+ const parts = rel.slice(DESIGN_SYSTEM_PATHS.componentsDir.length).split("/");
1823
+ if (parts.length === 2 && parts[1] === "preview.html") return "preview";
1824
+ if (parts.length === 2 && parts[1] === "README.md") return "componentReadme";
1825
+ if (parts[0] === "src" && parts.length >= 2) return "componentSource";
1826
+ return "componentOther";
1827
+ }
1828
+ if (rel.startsWith(DESIGN_SYSTEM_PATHS.fontsDir)) return "font";
1829
+ if (rel.startsWith(DESIGN_SYSTEM_PATHS.assetsDir)) return "asset";
1830
+ if (extensionOf(rel) === "d.ts") return "dts";
1831
+ return "other";
1832
+ }
1833
+ function limitOf(kind) {
1834
+ switch (kind) {
1835
+ case "readme":
1836
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.readme, label: "README.md" };
1837
+ case "tokens":
1838
+ return { bytes: TOKENS_LIMITS.bytes, label: "tokens.json" };
1839
+ case "doc":
1840
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.other, label: "a section document" };
1841
+ case "bundleJs":
1842
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.bundleJs, label: "bundle.js" };
1843
+ case "bundleCss":
1844
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.bundleCss, label: "bundle.css" };
1845
+ case "preview":
1846
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.preview, label: "a preview.html" };
1847
+ case "componentReadme":
1848
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.componentReadme, label: "a component's README.md" };
1849
+ case "componentLib":
1850
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.componentLib, label: "a components/lib/ file" };
1851
+ case "componentSource":
1852
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.other, label: "a components/src/ file" };
1853
+ case "componentOther":
1854
+ case "other":
1855
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.other, label: "a file the format has no place for" };
1856
+ case "asset":
1857
+ return { bytes: DESIGN_SYSTEM_FILE_LIMITS.asset, label: "an asset" };
1858
+ default:
1859
+ return null;
1860
+ }
1861
+ }
1862
+ async function scanTree2(dir, issues) {
1863
+ const tree = { files: /* @__PURE__ */ new Map(), blobs: /* @__PURE__ */ new Set(), totalBytes: 0, truncated: false };
1864
+ let seen = 0;
1865
+ const visit = async (rel) => {
1866
+ const full = rel === "" ? dir : path8.join(dir, ...rel.split("/"));
1867
+ const entries = await fs6.readdir(full, { withFileTypes: true }).catch(() => []);
1868
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1869
+ for (const entry of entries) {
1870
+ if (++seen > MAX_SCAN_ENTRIES2) {
1871
+ tree.truncated = true;
1872
+ return;
1873
+ }
1874
+ if (entry.name.startsWith(".")) continue;
1875
+ const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
1876
+ if (rel === "" && entry.name === BLOBS_DIR && entry.isDirectory()) {
1877
+ await scanBlobs(path8.join(dir, BLOBS_DIR), tree);
1878
+ continue;
1879
+ }
1880
+ if (entry.isSymbolicLink()) {
1881
+ issues.push({ file: child, message: "is a symbolic link; the editor ignores symbolic links. Replace it with a regular file or folder" });
1882
+ continue;
1883
+ }
1884
+ if (child !== DESIGN_SYSTEM_FILE) {
1885
+ const reason = explainDesignSystemPath(child);
1886
+ if (reason !== null) {
1887
+ issues.push({ file: child, message: `${reason}. The editor can't see it` });
1888
+ continue;
1889
+ }
1890
+ }
1891
+ if (entry.isDirectory()) await visit(child);
1892
+ else if (entry.isFile()) {
1893
+ const stat = await fs6.lstat(path8.join(full, entry.name)).catch(() => null);
1894
+ const size = stat?.size ?? 0;
1895
+ tree.files.set(child, size);
1896
+ tree.totalBytes += size;
1897
+ }
1898
+ }
1899
+ };
1900
+ await visit("");
1901
+ return tree;
1902
+ }
1903
+ async function scanBlobs(dir, tree) {
1904
+ const entries = await fs6.readdir(dir, { withFileTypes: true }).catch(() => []);
1905
+ for (const entry of entries) {
1906
+ if (!entry.isFile() || entry.name.startsWith(".")) continue;
1907
+ const id = entry.name.split(".")[0];
1908
+ if (BLOB_ID.test(id)) tree.blobs.add(id);
1909
+ }
1910
+ }
1911
+ var isRemote2 = (url) => /^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(url.trim()) && !/^data:/i.test(url.trim());
1912
+ var isGoogleFonts2 = (url) => /^(?:https?:)?\/\/fonts\.(?:googleapis|gstatic)\.com\//i.test(url.trim());
1913
+ function attr2(attrs, name) {
1914
+ const match = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:'([^']*)'|"([^"]*)"|([^\\s>]+))`, "i").exec(attrs);
1915
+ if (!match) return null;
1916
+ return match[1] ?? match[2] ?? match[3] ?? null;
1917
+ }
1918
+ function checkBlobRefs2(file, text, blobs, issues) {
1919
+ const reported = /* @__PURE__ */ new Set();
1920
+ for (const match of text.matchAll(/\/_blob\/([^\s"'()<>?#`\\]*)/g)) {
1921
+ const id = match[1];
1922
+ if (reported.has(id)) continue;
1923
+ reported.add(id);
1924
+ if (!BLOB_ID.test(id)) {
1925
+ issues.push({ file, message: `/_blob/${id} is not a valid upload reference: use the /_blob/<id> that design_system_import_asset returned (32 lowercase hex digits)` });
1926
+ } else if (!blobs.has(id)) {
1927
+ issues.push({ file, message: `/_blob/${id} is not in ${BLOBS_DIR}/: import the file with design_system_import_asset and use the src it returns` });
1928
+ }
1929
+ }
1930
+ }
1931
+ var NO_CDN = "BaoCut previews load nothing from the network but Google Fonts (no CDN in the page CSP)";
1932
+ function remoteScriptLoads(code) {
1933
+ const urls = [];
1934
+ const patterns = [
1935
+ /\bimport\s*\(\s*['"`]([^'"`]+)['"`]/g,
1936
+ /\bimportScripts\s*\(\s*['"`]([^'"`]+)['"`]/g,
1937
+ /\bfetch\s*\(\s*['"`]([^'"`]+)['"`]/g,
1938
+ /\.src\s*=\s*['"`]([^'"`]+)['"`]/g,
1939
+ /<script\b[^>]*\bsrc\s*=\s*\\?['"]([^'"\\]+)/gi,
1940
+ /^\s*import\s+(?:[\w$*{},\s]+\s+from\s+)?['"]([^'"]+)['"]/gm
1941
+ ];
1942
+ for (const pattern of patterns) {
1943
+ for (const match of code.matchAll(pattern)) {
1944
+ const url = match[1];
1945
+ if (isRemote2(url) && !isGoogleFonts2(url) && !urls.includes(url)) urls.push(url);
1946
+ }
1947
+ }
1948
+ return urls;
1949
+ }
1950
+ function remoteCssLoads(css) {
1951
+ const urls = [];
1952
+ for (const match of css.matchAll(/@import\s+(?:url\(\s*)?["']?([^"')\s;]+)/gi)) urls.push(match[1]);
1953
+ for (const match of css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi)) urls.push((match[1] ?? match[2] ?? match[3] ?? "").trim());
1954
+ return [...new Set(urls.filter((url) => isRemote2(url) && !isGoogleFonts2(url)))];
1955
+ }
1956
+ function checkPreview(file, html, issues) {
1957
+ const add = (message) => issues.push({ file, message });
1958
+ const text = html.replace(/^\uFEFF/, "");
1959
+ if (!CARD_HEADER_PATTERN.test(text)) {
1960
+ add('line 1 must be the marker <!-- @dsCard group="\u2026" height=N \u2026 --> (height 40\u20134000); without it the card has no group or height');
1961
+ }
1962
+ const markup = text.replace(/<!--[\s\S]*?-->/g, (comment) => " ".repeat(comment.length));
1963
+ const forbidden = /* @__PURE__ */ new Set();
1964
+ for (const match of markup.matchAll(/<([A-Za-z][A-Za-z0-9-]*)\b/g)) {
1965
+ const name = match[1].toLowerCase();
1966
+ if (FORBIDDEN_PREVIEW_ELEMENTS.includes(name)) forbidden.add(name);
1967
+ }
1968
+ for (const name of forbidden) add(`uses <${name}>; a preview may not contain <iframe>, <frame>, <object>, <embed>, <portal> or <noscript>`);
1969
+ for (const match of markup.matchAll(/<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script\s*>/gi)) {
1970
+ const src = attr2(match[1] ?? "", "src");
1971
+ if (src !== null) {
1972
+ const clean = src.trim();
1973
+ if (isRemote2(clean)) add(`loads the script ${clean} from the network; ${NO_CDN}. Copy the library into components/lib/ and list it in the index's libraries`);
1974
+ else if (/(?:^|\/)(?:bundle\.js|lib\/[^/]+\.js|_vendor\/)/.test(clean.split(/[?#]/)[0])) {
1975
+ add(`links ${clean}; bundle.js and the libraries are preloaded in every preview, and a preview that links them doesn't load. Remove the <script src>`);
1976
+ }
1977
+ }
1978
+ for (const url of remoteScriptLoads(match[2] ?? "")) add(`its script loads ${url} from the network; ${NO_CDN}`);
1979
+ }
1980
+ for (const match of markup.matchAll(/<link\b((?:[^>"']|"[^"]*"|'[^']*')*)>/gi)) {
1981
+ const href = attr2(match[1] ?? "", "href");
1982
+ if (href !== null && isRemote2(href) && !isGoogleFonts2(href)) add(`links ${href.trim()} from the network; ${NO_CDN}`);
1983
+ }
1984
+ for (const match of markup.matchAll(/<(?:img|source|video|audio)\b((?:[^>"']|"[^"]*"|'[^']*')*)>/gi)) {
1985
+ const src = attr2(match[1] ?? "", "src");
1986
+ if (src !== null && isRemote2(src)) add(`loads ${src.trim()} from the network; ${NO_CDN}. Put the file under assets/ and use a relative path, or import it with design_system_import_asset`);
1987
+ }
1988
+ for (const match of markup.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi)) {
1989
+ for (const url of remoteCssLoads(match[1] ?? "")) add(`its style loads ${url} from the network; ${NO_CDN}`);
1990
+ }
1991
+ }
1992
+ function bundleHeader(script2) {
1993
+ const prefix = script2.slice(0, 262144);
1994
+ const offset = prefix.indexOf("@ds-bundle:");
1995
+ if (offset < 0) return null;
1996
+ const start = prefix.lastIndexOf("/*", offset);
1997
+ const end = prefix.indexOf("*/", offset);
1998
+ if (start < 0 || end < 0 || prefix.slice(0, start).trim() !== "") return "invalid";
1999
+ try {
2000
+ const header = JSON.parse(prefix.slice(offset + 11, end).trim());
2001
+ if (!isRecord3(header)) return "invalid";
2002
+ const ns = header.namespace;
2003
+ return { namespace: typeof ns === "string" && WINDOW_NAMESPACE_PATTERN.test(ns) ? ns : null };
2004
+ } catch {
2005
+ return "invalid";
2006
+ }
2007
+ }
2008
+ function escapeRegExp(text) {
2009
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2010
+ }
2011
+ function checkBundle(file, code, namespace, issues) {
2012
+ const add = (message) => issues.push({ file, message });
2013
+ if (/^\s*import\s*(?:[\w$*{},\s]+\s*from\s*)?['"]|^\s*export\s+(?:default\b|\{|\*|const\b|let\b|var\b|function\b|class\b|async\b)|\bimport\.meta\b|\bimport\s*\(/m.test(code)) {
2014
+ add("is not a classic script: it uses import / export; bundle it into ONE classic script (an IIFE) that reads window.React and window.ReactDOM");
2015
+ }
2016
+ if (/<\/script/i.test(code)) add('contains a literal </script, which ends the inline <script> previews and consumers put it in; write it "<\\/script"');
2017
+ if (code.includes("<!--")) add('contains a literal <!--, which can escape the inline <script> previews and consumers put it in; write it "\\x3C!--"');
2018
+ if (/\bfetch\s*\(|\bXMLHttpRequest\b|\bnew\s+(?:WebSocket|EventSource)\s*\(|\bsendBeacon\s*\(|\bimportScripts\s*\(/.test(code)) {
2019
+ add("makes network requests (fetch / XMLHttpRequest / WebSocket / EventSource / sendBeacon); the bundle fetches nothing");
2020
+ }
2021
+ const header = bundleHeader(code);
2022
+ if (header === "invalid") add("line 1 has an @ds-bundle header that is not /* @ds-bundle: {JSON} */ at the very start; fix it or remove it");
2023
+ const declared = header !== null && header !== "invalid" ? header.namespace : null;
2024
+ if (declared !== null && namespace !== null && declared !== namespace) {
2025
+ add(`its @ds-bundle header names the namespace ${declared}, but design-system.json says ${namespace}; make them the same`);
2026
+ }
2027
+ const ns = namespace ?? declared;
2028
+ if (ns === null) return;
2029
+ const body = header !== null && header !== "invalid" ? code.slice(code.indexOf("*/") + 2) : code;
2030
+ const name = escapeRegExp(ns);
2031
+ if (!new RegExp(`\\.\\s*${name}\\b|\\[\\s*['"\`]${name}['"\`]\\s*\\]|\\bvar\\s+${name}\\b`).test(body)) {
2032
+ add(`never assigns window.${ns}: the bundle must set window.${ns} = { \u2026components } (the index's namespace)`);
2033
+ }
2034
+ }
2035
+ async function checkFont(dir, file, issues) {
2036
+ const ext = extensionOf(file);
2037
+ const format = FONT_EXTENSIONS[ext];
2038
+ if (format === void 0) {
2039
+ issues.push({ file, message: "fonts/ holds font files only (woff2, woff, ttf, otf, ttc); move it elsewhere" });
2040
+ return;
2041
+ }
2042
+ const handle = await fs6.open(path8.join(dir, ...file.split("/")), "r").catch(() => null);
2043
+ if (handle === null) return;
2044
+ try {
2045
+ const head = Buffer.alloc(4);
2046
+ const { bytesRead } = await handle.read(head, 0, 4, 0);
2047
+ const magic = head.subarray(0, bytesRead).toString("latin1");
2048
+ const sfnt = magic === "\0\0\0" || magic === "OTTO" || magic === "true" || magic === "typ1";
2049
+ const ok = ext === "woff2" ? magic === "wOF2" : ext === "woff" ? magic === "wOFF" : ext === "ttc" ? magic === "ttcf" : sfnt;
2050
+ if (!ok) issues.push({ file, message: `is not a ${format} font: its first bytes don't match a .${ext} file. Use the real font file` });
2051
+ } finally {
2052
+ await handle.close();
2053
+ }
2054
+ }
2055
+ function isAssetGroupName(name) {
2056
+ return typeof name === "string" && name.length > 0 && name.length <= MAX_ASSET_GROUP_NAME_LENGTH && !/[/\\\u0000-\u001f\u007f]/.test(name) && name !== "." && name !== ".." && !RESERVED_PROTOTYPE_NAMES2.has(name) && name.trim() === name;
2057
+ }
2058
+ function encodeIndexKey(key) {
2059
+ let encoded = "";
2060
+ for (const byte of Buffer.from(key, "utf8")) {
2061
+ const ch = String.fromCharCode(byte);
2062
+ encoded += byte < 128 && /[A-Za-z0-9_./-]/.test(ch) ? ch : `~${byte.toString(16).padStart(2, "0")}`;
2063
+ }
2064
+ return encoded;
2065
+ }
2066
+ function decodeIndexKey(key) {
2067
+ if (!key.includes("~")) return key;
2068
+ const bytes = [];
2069
+ for (let i = 0; i < key.length; i++) {
2070
+ const hex = key[i] === "~" ? key.slice(i + 1, i + 3) : "";
2071
+ if (/^[0-9a-f]{2}$/.test(hex)) {
2072
+ bytes.push(parseInt(hex, 16));
2073
+ i += 2;
2074
+ } else {
2075
+ for (const byte of Buffer.from(key[i], "utf8")) bytes.push(byte);
2076
+ }
2077
+ }
2078
+ return Buffer.from(bytes).toString("utf8");
2079
+ }
2080
+ function checkRecord(ctx, where, record, filePath) {
2081
+ const { add, shadowed, restored, tree } = ctx;
2082
+ if (!isRecord3(record)) {
2083
+ add(`${where}: each record is {"name","blob","size","type"}`);
2084
+ return;
2085
+ }
2086
+ const { name, blob, size, type } = record;
2087
+ if (typeof name !== "string" || name === "") {
2088
+ add(`${where}: "name" must be the file's path (below the group folder for a group's files)`);
2089
+ return;
2090
+ }
2091
+ const target = filePath(name);
2092
+ const reason = explainDesignSystemPath(target);
2093
+ if (reason !== null) add(`${where}: ${target} ${reason}; the editor skips the record`);
2094
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) add(`${where}: "size" must be the file's size in bytes`);
2095
+ if (typeof type !== "string" || !/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type)) add(`${where}: "type" must be the file's media type`);
2096
+ if (reason === null && tree.files.has(target)) {
2097
+ shadowed.push(target);
2098
+ return;
2099
+ }
2100
+ if (typeof blob !== "string" || !BLOB_ID.test(blob)) {
2101
+ add(`${where}: "blob" must be the upload's id (the 32 hex digits after /_blob/ that design_system_import_asset returned)`);
2102
+ } else if (tree.blobs.has(blob)) {
2103
+ if (reason === null) restored.add(target);
2104
+ } else {
2105
+ add(
2106
+ `${where}: the upload ${blob} is not in ${BLOBS_DIR}/ and there is no file at ${target}, so the asset can't be shown. Put the file at ${target} (and delete the record), or import it with design_system_import_asset`,
2107
+ "ASSET_RECORD_MISSING_UPLOAD"
2108
+ );
2109
+ }
2110
+ }
2111
+ function checkIndex2(index, ctx, note) {
2112
+ checkIndexFields(index, ctx, note);
2113
+ const { shadowed } = ctx;
2114
+ if (shadowed.length > 0) {
2115
+ note(
2116
+ `${shadowed.length} asset ${shadowed.length === 1 ? "record points" : "records point"} at a path that is a file (${shadowed.slice(0, 3).join(", ")}${shadowed.length > 3 ? ", \u2026" : ""}): the files are used and the records ignored, as in an exported system; the editor drops the records when it next rewrites the index`
2117
+ );
2118
+ }
2119
+ }
2120
+ function checkIndexFields(index, ctx, note) {
2121
+ const { add, tree } = ctx;
2122
+ if (isRecord3(index.content)) {
2123
+ add('has a "content" object: that is the old one-file envelope, not a files index. Move the files out of it into the folder');
2124
+ }
2125
+ if (!hasDesignSystemMarker(index)) {
2126
+ add('has no createdOnFiles or convertedFrom marker: the editor opens it read-only. A system you start gets "createdOnFiles": {"v": 1, "at": "<ISO time>"}');
2127
+ }
2128
+ if (Object.hasOwn(index, "title") && typeof index.title !== "string") add(`"title" must be a string (the system's name)`);
2129
+ else if (typeof index.title !== "string" || index.title.trim() === "") note(`has no "title": the system is shown under its folder name; the title is the system's name`);
2130
+ if (Object.hasOwn(index, "namespace") && (typeof index.namespace !== "string" || !WINDOW_NAMESPACE_PATTERN.test(index.namespace))) {
2131
+ add(`"namespace" must be the bundle's global: a JavaScript identifier of at most 64 characters (not __proto__, constructor or prototype)`);
2132
+ }
2133
+ if (Object.hasOwn(index, "libraries") && !Array.isArray(index.libraries)) add('"libraries" must be a list ([] when there is no bundle)');
2134
+ else if (Array.isArray(index.libraries)) {
2135
+ index.libraries.forEach((library, i) => {
2136
+ const where = `libraries[${i}]`;
2137
+ if (!isRecord3(library) || typeof library.name !== "string" || typeof library.version !== "string") {
2138
+ add(`${where}: each library is {"name","version","global"?,"file"?}`);
2139
+ return;
2140
+ }
2141
+ const file = library.file;
2142
+ if (file !== void 0) {
2143
+ if (typeof file !== "string" || !file.startsWith(DESIGN_SYSTEM_PATHS.libDir)) add(`${where}: "file" must be a path under ${DESIGN_SYSTEM_PATHS.libDir}`);
2144
+ else if (!tree.files.has(file)) add(`${where}: ${file} is not in the system`);
2145
+ if (library.global !== void 0 && (typeof library.global !== "string" || !WINDOW_NAMESPACE_PATTERN.test(library.global))) {
2146
+ add(`${where}: "global" must be the window global the library defines`);
2147
+ }
2148
+ } else if (library.name !== "react" && library.name !== "react-dom") {
2149
+ add(`${where}: ${library.name} has no "file", so previews can't load it (${NO_CDN}); copy it into ${DESIGN_SYSTEM_PATHS.libDir} and set "file" and "global"`);
2150
+ }
2151
+ });
2152
+ }
2153
+ if (Object.hasOwn(index, "sections") && (!isRecord3(index.sections) || Object.values(index.sections).some((v) => typeof v !== "string"))) {
2154
+ add('"sections" must be an object of card titles ({} in a new index)');
2155
+ }
2156
+ if (Object.hasOwn(index, "groups") && (!Array.isArray(index.groups) || index.groups.some((g) => typeof g !== "string"))) {
2157
+ add('"groups" must be a list of asset group keys');
2158
+ }
2159
+ if (Object.hasOwn(index, "assetGroups") && !isRecord3(index.assetGroups)) add('"assetGroups" must be an object keyed by group');
2160
+ for (const [key, group] of Object.entries(isRecord3(index.assetGroups) ? index.assetGroups : {})) {
2161
+ const where = `assetGroups.${key}`;
2162
+ if (!isRecord3(group)) {
2163
+ add(`${where}: each group is {"name","order","files","tile"?}`);
2164
+ continue;
2165
+ }
2166
+ const name = group.name === void 0 ? decodeIndexKey(key) : group.name;
2167
+ if (!isAssetGroupName(name)) {
2168
+ add(`${where}: "name" must be the group folder's name (at most ${MAX_ASSET_GROUP_NAME_LENGTH} characters, no slashes or control characters)`);
2169
+ continue;
2170
+ }
2171
+ if (group.order !== void 0 && (!Array.isArray(group.order) || group.order.some((n) => typeof n !== "string"))) add(`${where}: "order" must be a list of file names`);
2172
+ if (group.tile !== void 0 && !ASSET_TILE_SIZES.has(group.tile)) add(`${where}: "tile" is one of "xs", "s", "m", "l", "xl"`);
2173
+ if (group.files === void 0) continue;
2174
+ if (!isRecord3(group.files)) {
2175
+ add(`${where}: "files" must be an object of upload records ({} when the group's files are files)`);
2176
+ continue;
2177
+ }
2178
+ for (const [fileKey, record] of Object.entries(group.files)) {
2179
+ checkRecord(ctx, `${where}.files.${fileKey}`, record, (n) => `${DESIGN_SYSTEM_PATHS.assetsDir}${name}/${n}`);
2180
+ }
2181
+ }
2182
+ if (Object.hasOwn(index, "blobs") && !isRecord3(index.blobs)) add('"blobs" must be an object ({} in a new index)');
2183
+ for (const [key, record] of Object.entries(isRecord3(index.blobs) ? index.blobs : {})) checkRecord(ctx, `blobs.${key}`, record, (n) => n);
2184
+ const docs = index.docs;
2185
+ if (docs !== void 0 && (!isRecord3(docs) || docs.sections !== void 0 && (!Array.isArray(docs.sections) || docs.sections.some((s) => typeof s !== "string")) || docs.readme !== void 0 && typeof docs.readme !== "string")) {
2186
+ add('"docs" must be {"readme"?, "sections": [\u2026]} ({"sections": []} in a new index)');
2187
+ }
2188
+ }
2189
+ async function readText(dir, rel) {
2190
+ return fs6.readFile(path8.join(dir, ...rel.split("/")), "utf8").catch(() => null);
2191
+ }
2192
+ async function checkDesignSystem(dir) {
2193
+ const issues = [];
2194
+ const notes = [];
2195
+ const tree = await scanTree2(dir, issues);
2196
+ const notChecked = [...DESIGN_SYSTEM_NOT_CHECKED];
2197
+ let index = null;
2198
+ const indexText = tree.files.has(DESIGN_SYSTEM_FILE) ? await readText(dir, DESIGN_SYSTEM_FILE) : null;
2199
+ const addIndex = (message, code) => issues.push({ file: DESIGN_SYSTEM_FILE, message, ...code ? { code } : {} });
2200
+ const noteIndex = (message) => notes.push({ file: DESIGN_SYSTEM_FILE, message });
2201
+ if (indexText === null) {
2202
+ addIndex('missing: a design system needs design-system.json with "v": 3, "layout": "files" and a createdOnFiles marker, written last');
2203
+ } else {
2204
+ let parsed;
2205
+ try {
2206
+ parsed = JSON.parse(indexText);
2207
+ } catch (error) {
2208
+ addIndex(`is not valid JSON: ${error.message}`);
2209
+ }
2210
+ const envelope = isRecord3(parsed) && isRecord3(parsed.content);
2211
+ const fields = isRecord3(parsed) && (envelope || isDesignSystemIndex(parsed)) ? parsed : null;
2212
+ if (parsed !== void 0 && (!fields || typeof fields.v !== "number" || fields.v < 3 || fields.layout !== "files")) {
2213
+ addIndex('must be an object with "v": 3 and "layout": "files"');
2214
+ }
2215
+ if (fields) index = fields;
2216
+ if (indexText.length > MAX_DESIGN_SYSTEM_INDEX_CHARS) addIndex(`has ${indexText.length} characters; the editor reads at most ${MAX_DESIGN_SYSTEM_INDEX_CHARS}`);
2217
+ }
2218
+ const restored = /* @__PURE__ */ new Set();
2219
+ if (index) checkIndex2(index, { tree, add: addIndex, shadowed: [], restored }, noteIndex);
2220
+ const namespace = index && typeof index.namespace === "string" && WINDOW_NAMESPACE_PATTERN.test(index.namespace) ? index.namespace : null;
2221
+ let ownFiles = 0;
2222
+ let dtsTotal = 0;
2223
+ const sections = [];
2224
+ for (const [file, bytes] of tree.files) {
2225
+ const kind = classify(file);
2226
+ ownFiles++;
2227
+ if (bytes > DESIGN_SYSTEM_LIMITS.fileBytes) {
2228
+ issues.push({ file, message: `is ${bytes} bytes; a file can be at most ${DESIGN_SYSTEM_LIMITS.fileBytes} (15 MiB)` });
2229
+ continue;
2230
+ }
2231
+ if (kind === "dts") dtsTotal += bytes;
2232
+ if (kind === "doc") sections.push(file);
2233
+ const limit = limitOf(kind);
2234
+ if (limit !== null && bytes > limit.bytes) issues.push({ file, message: `is ${bytes} bytes; ${limit.label} can be at most ${limit.bytes}` });
2235
+ }
2236
+ if (tree.truncated || ownFiles > DESIGN_SYSTEM_LIMITS.ownFiles) {
2237
+ issues.push({
2238
+ file: ".",
2239
+ message: `${tree.truncated ? `has more than ${MAX_SCAN_ENTRIES2}` : `has ${ownFiles}`} files outside ${BLOBS_DIR}/; a design system holds at most ${DESIGN_SYSTEM_LIMITS.ownFiles} (the editor lists only the first ${DESIGN_SYSTEM_LIMITS.files})`
2240
+ });
2241
+ }
2242
+ if (tree.totalBytes > DESIGN_SYSTEM_LIMITS.totalBytes) {
2243
+ issues.push({ file: ".", message: `files outside ${BLOBS_DIR}/ add up to ${tree.totalBytes} bytes; a design system holds at most ${DESIGN_SYSTEM_LIMITS.totalBytes} (256 MiB)` });
2244
+ }
2245
+ if (dtsTotal > DESIGN_SYSTEM_FILE_LIMITS.dtsTotal) {
2246
+ issues.push({ file: DESIGN_SYSTEM_PATHS.componentsDir.slice(0, -1), message: `the .d.ts files add up to ${dtsTotal} bytes; at most ${DESIGN_SYSTEM_FILE_LIMITS.dtsTotal} (1.5 MB)` });
2247
+ }
2248
+ if (sections.length > MAX_SECTION_DOCUMENTS) {
2249
+ issues.push({ file: ".", message: `has ${sections.length} section documents (*.md outside components/, assets/, fonts/ and archived/); the editor shows at most ${MAX_SECTION_DOCUMENTS}, the rest stay files` });
2250
+ }
2251
+ for (const file of tree.files.keys()) {
2252
+ if (!file.startsWith(DESIGN_SYSTEM_PATHS.componentsDir)) continue;
2253
+ const parts = file.slice(DESIGN_SYSTEM_PATHS.componentsDir.length).split("/");
2254
+ if (parts.length === 2 && (parts[1] === "preview.html" || parts[1] === "README.md") && !COMPONENT_NAME_PATTERN.test(parts[0])) {
2255
+ issues.push({ file, message: `components/${parts[0]}/ is not a component name: an ASCII JavaScript identifier of at most 64 characters` });
2256
+ }
2257
+ }
2258
+ const tokensText = tree.files.has(DESIGN_SYSTEM_PATHS.tokens) ? await readText(dir, DESIGN_SYSTEM_PATHS.tokens) : null;
2259
+ if (tokensText !== null && (tree.files.get(DESIGN_SYSTEM_PATHS.tokens) ?? 0) <= TOKENS_LIMITS.bytes) {
2260
+ const tokens = checkTokensText(tokensText);
2261
+ for (const message of tokens.problems) issues.push({ file: DESIGN_SYSTEM_PATHS.tokens, message });
2262
+ for (const message of tokens.notes) notes.push({ file: DESIGN_SYSTEM_PATHS.tokens, message });
2263
+ }
2264
+ const listedFonts = new Set(tokensText === null ? [] : tokenFontFiles(tokensText));
2265
+ for (const font of listedFonts) {
2266
+ if (!tree.files.has(font) && !restored.has(font)) issues.push({ file: DESIGN_SYSTEM_PATHS.tokens, message: `type.fonts names ${font}, which is not in the system` });
2267
+ }
2268
+ for (const file of tree.files.keys()) {
2269
+ if (classify(file) !== "font") continue;
2270
+ await checkFont(dir, file, issues);
2271
+ if (FONT_EXTENSIONS[extensionOf(file)] !== void 0 && !listedFonts.has(file)) {
2272
+ issues.push({ file, message: 'is not listed in tokens.json type.fonts, so it gets no @font-face; list it ({"family","file","weight","style"})' });
2273
+ }
2274
+ }
2275
+ for (const file of tree.files.keys()) {
2276
+ if (!file.startsWith(DESIGN_SYSTEM_PATHS.assetsDir)) continue;
2277
+ const rest = file.slice(DESIGN_SYSTEM_PATHS.assetsDir.length);
2278
+ const slash = rest.indexOf("/");
2279
+ if (slash > 0 && !isAssetGroupName(rest.slice(0, slash))) {
2280
+ issues.push({ file, message: `assets/${rest.slice(0, slash)}/ is not a valid group name (at most ${MAX_ASSET_GROUP_NAME_LENGTH} characters, no leading or trailing spaces)` });
2281
+ }
2282
+ }
2283
+ for (const [file, bytes] of tree.files) {
2284
+ const kind = classify(file);
2285
+ if (kind === "generated" || kind === "own" || kind === "archived" || bytes > MAX_READ_BYTES || bytes > DESIGN_SYSTEM_LIMITS.fileBytes) continue;
2286
+ if (!TEXT_EXTENSIONS2.has(extensionOf(file)) && kind !== "componentLib") continue;
2287
+ const text = await readText(dir, file);
2288
+ if (text === null) continue;
2289
+ if (kind !== "componentLib" && kind !== "bundleJs") checkBlobRefs2(file, text, tree.blobs, issues);
2290
+ if (kind === "preview") checkPreview(file, text, issues);
2291
+ else if (kind === "bundleJs") checkBundle(file, text, namespace, issues);
2292
+ else if (kind === "bundleCss") {
2293
+ if (/<\/style/i.test(text)) issues.push({ file, message: "contains a literal </style, which ends the inline <style> previews put it in" });
2294
+ for (const url of remoteCssLoads(text)) issues.push({ file, message: `loads ${url} from the network; ${NO_CDN}` });
2295
+ } else if (kind === "componentLib" && /\.m?js$/i.test(file)) {
2296
+ if (/<\/script/i.test(text)) issues.push({ file, message: "contains a literal </script, which ends the inline <script> previews put it in" });
2297
+ for (const url of remoteScriptLoads(text)) issues.push({ file, message: `loads ${url} from the network; ${NO_CDN}. Copy what it loads into components/lib/` });
2298
+ }
2299
+ }
2300
+ if (tree.files.has(DESIGN_SYSTEM_PATHS.bundleJs) && namespace === null && index !== null) {
2301
+ const bundle = await readText(dir, DESIGN_SYSTEM_PATHS.bundleJs);
2302
+ const header = bundle === null ? null : bundleHeader(bundle);
2303
+ if (header === null || header === "invalid" || header.namespace === null) {
2304
+ addIndex(`has no "namespace", and bundle.js has no @ds-bundle header naming one: set "namespace" to the bundle's window global`);
2305
+ }
2306
+ }
2307
+ return { title: index ? designSystemTitle(index, dir) : path8.basename(dir), namespace, issues, notes, notChecked };
2308
+ }
2309
+
2310
+ var COMMENTS_FILE = "comments.json";
2311
+ var COMMENTS_VERSION = 1;
2312
+ var LIMITS = { text: 1e4, label: 1e3, detail: 4e3, anchor: 2048, section: 200, name: 100 };
2313
+ var AGENT_AUTHOR = { kind: "agent", name: "agent" };
2314
+ var CommentsError = class extends Error {
2315
+ code;
2316
+ status;
2317
+ constructor(code, message, status = 400) {
2318
+ super(message);
2319
+ this.code = code;
2320
+ this.status = status;
2321
+ }
2322
+ };
2323
+ var emptyDoc = () => ({ version: COMMENTS_VERSION, threads: [] });
2324
+ function randomHex(bytes) {
2325
+ const buf = new Uint8Array(bytes);
2326
+ globalThis.crypto.getRandomValues(buf);
2327
+ return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
2328
+ }
2329
+ var newId = (prefix) => `${prefix}_${randomHex(5)}`;
2330
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2331
+ function parseDoc(text) {
2332
+ const data = JSON.parse(text);
2333
+ if (!isRecord4(data) || data.version !== COMMENTS_VERSION || !Array.isArray(data.threads)) {
2334
+ throw new CommentsError("COMMENTS_FILE_INVALID", `not a version ${COMMENTS_VERSION} comments file (expected {"version": 1, "threads": [...]})`, 500);
2335
+ }
2336
+ const threads = data.threads.filter(
2337
+ (t) => isRecord4(t) && typeof t.id === "string" && typeof t.anchor === "string" && typeof t.label === "string" && (t.status === "open" || t.status === "resolved") && Array.isArray(t.messages) && t.messages.every((m) => isRecord4(m) && typeof m.text === "string" && isRecord4(m.author) && (m.author.kind === "user" || m.author.kind === "agent"))
2338
+ );
2339
+ for (const t of threads) {
2340
+ if (!isRecord4(t.location)) t.location = {};
2341
+ for (const m of t.messages) if (m.author.principal !== void 0 && typeof m.author.principal !== "string") delete m.author.principal;
2342
+ }
2343
+ return { version: COMMENTS_VERSION, threads };
2344
+ }
2345
+ var formatDoc = (doc) => `${JSON.stringify(doc, null, 2)}
2346
+ `;
2347
+ function addMessage(thread, author, text, now) {
2348
+ const message = { id: newId("m"), author, text, at: now };
2349
+ thread.messages.push(message);
2350
+ thread.updatedAt = now;
2351
+ if (author.kind === "agent") {
2352
+ if (thread.agent) thread.agent = { ...thread.agent, status: "replied", repliedAt: now };
2353
+ } else if (thread.status === "resolved") {
2354
+ thread.status = "open";
2355
+ delete thread.resolvedAt;
2356
+ }
2357
+ return message;
2358
+ }
2359
+ function setStatus(thread, status, now) {
2360
+ if (thread.status === status) return;
2361
+ thread.status = status;
2362
+ thread.updatedAt = now;
2363
+ if (status === "resolved") thread.resolvedAt = now;
2364
+ else delete thread.resolvedAt;
2365
+ }
2366
+ function findThread(doc, ref) {
2367
+ const exact = doc.threads.find((t) => t.id === ref);
2368
+ if (exact) return exact;
2369
+ const matches = ref.length >= 3 ? doc.threads.filter((t) => t.id.startsWith(ref)) : [];
2370
+ if (matches.length === 1) return matches[0];
2371
+ throw new CommentsError(
2372
+ matches.length ? "AMBIGUOUS_COMMENT" : "COMMENT_NOT_FOUND",
2373
+ matches.length ? `${ref} matches ${matches.length} comments; give more of the id.` : `No comment ${ref}.`,
2374
+ 404
2375
+ );
2376
+ }
2377
+ function openThreads(doc) {
2378
+ return doc.threads.filter((t) => t.status === "open").sort((a, b) => a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0);
2379
+ }
2380
+ function agentView(thread, n) {
2381
+ return {
2382
+ id: thread.id,
2383
+ ...n !== void 0 ? { n } : {},
2384
+ status: thread.status,
2385
+ ...thread.location.file ? { file: thread.location.file } : {},
2386
+ where: thread.label,
2387
+ ...thread.detail ? { detail: thread.detail } : {},
2388
+ location: thread.location,
2389
+ anchor: thread.anchor,
2390
+ ...thread.agent ? { agent: thread.agent } : {},
2391
+ messages: thread.messages.map((m) => ({ from: m.author.kind, name: m.author.name, text: m.text, at: m.at, ...m.editedAt ? { editedAt: m.editedAt } : {} }))
2392
+ };
2393
+ }
2394
+ function agentViews(doc, threads) {
2395
+ const open2 = openThreads(doc);
2396
+ return threads.map((t) => {
2397
+ const i = open2.indexOf(t);
2398
+ return agentView(t, i >= 0 ? i + 1 : void 0);
2399
+ });
2400
+ }
2401
+
2402
+ import fs7 from "node:fs";
2403
+ import fsp from "node:fs/promises";
2404
+ import path9 from "node:path";
2405
+ var LOCK_STALE_MS = 1e4;
2406
+ var LOCK_WAIT_MS = 5e3;
2407
+ var LOCK_RETRY_MS = 20;
2408
+ var commentsPath = (root) => path9.join(root, COMMENTS_FILE);
2409
+ async function readComments(root) {
2410
+ let text;
2411
+ try {
2412
+ text = await fsp.readFile(commentsPath(root), "utf8");
2413
+ } catch (error) {
2414
+ if (error.code === "ENOENT") return emptyDoc();
2415
+ throw error;
2416
+ }
2417
+ if (text.trim() === "") return emptyDoc();
2418
+ try {
2419
+ return parseDoc(text);
2420
+ } catch (error) {
2421
+ if (error instanceof CommentsError) throw new CommentsError(error.code, `${commentsPath(root)}: ${error.message}`, 500);
2422
+ throw new CommentsError("COMMENTS_FILE_INVALID", `${commentsPath(root)} is not valid JSON: ${error.message}`, 500);
2423
+ }
2424
+ }
2425
+ async function lock(root) {
2426
+ const file = `${commentsPath(root)}.lock`;
2427
+ const deadline = Date.now() + LOCK_WAIT_MS;
2428
+ for (; ; ) {
2429
+ try {
2430
+ const handle = await fsp.open(file, "wx");
2431
+ await handle.writeFile(`${process.pid}
2432
+ `);
2433
+ await handle.close();
2434
+ return () => fsp.rm(file, { force: true });
2435
+ } catch (error) {
2436
+ if (error.code !== "EEXIST") throw error;
2437
+ }
2438
+ const info = await fsp.stat(file).catch(() => null);
2439
+ if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
2440
+ await fsp.rm(file, { force: true });
2441
+ continue;
2442
+ }
2443
+ if (Date.now() > deadline) throw new CommentsError("COMMENTS_LOCKED", `${file} is held by another process; try again (or delete it if nothing is running).`, 503);
2444
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
2445
+ }
2446
+ }
2447
+ async function writeAtomic(file, text) {
2448
+ const temp = path9.join(path9.dirname(file), `.${path9.basename(file)}.${process.pid}.${Date.now().toString(36)}.tmp`);
2449
+ await fsp.writeFile(temp, text);
2450
+ try {
2451
+ await fsp.rename(temp, file);
2452
+ } catch (error) {
2453
+ await fsp.rm(temp, { force: true });
2454
+ throw error;
2455
+ }
2456
+ }
2457
+ async function updateComments(root, change) {
2458
+ const unlock = await lock(root);
2459
+ try {
2460
+ const doc = await readComments(root);
2461
+ const before = formatDoc(doc);
2462
+ const result = await change(doc);
2463
+ const after = formatDoc(doc);
2464
+ const exists = fs7.existsSync(commentsPath(root));
2465
+ if (after !== before && (exists || doc.threads.length > 0)) await writeAtomic(commentsPath(root), after);
2466
+ return result;
2467
+ } finally {
2468
+ await unlock();
2469
+ }
2470
+ }
2471
+
2472
+ import fs8 from "node:fs";
2473
+ import net from "node:net";
2474
+ import path10 from "node:path";
2475
+ var STATE_FILE = ".artifact-server.json";
2476
+ var LOG_FILE = ".artifact-server.log";
2477
+ var EXPORTS_DIR = "exports";
2478
+ function readState(root) {
2479
+ try {
2480
+ return JSON.parse(fs8.readFileSync(path10.join(root, STATE_FILE), "utf8"));
2481
+ } catch {
2482
+ return null;
2483
+ }
2484
+ }
2485
+ function alive(pid) {
2486
+ try {
2487
+ process.kill(pid, 0);
2488
+ return true;
2489
+ } catch (error) {
2490
+ return error.code === "EPERM";
2491
+ }
2492
+ }
2493
+ async function runningServer(root, kind, probe) {
2494
+ const state = readState(root);
2495
+ if (!state || state.kind !== kind || !alive(state.pid)) return null;
2496
+ try {
2497
+ const response = await fetch(new URL(probe, state.url), { signal: AbortSignal.timeout(2e3) });
2498
+ return response.ok ? state : null;
2499
+ } catch {
2500
+ return null;
2501
+ }
2502
+ }
2503
+ var DEFAULT_PORTS = { slides: 4710, design: 4720, "design-system": 4730, dashboard: 4740, docs: 4750, motion: 4760 };
2504
+ var PORT_TRIES = 100;
2505
+ var NetworkBlocked = class extends Error {
2506
+ code = "NETWORK_BLOCKED";
2507
+ constructor() {
2508
+ super(
2509
+ "A sandbox blocks local network here (127.0.0.1), so the server cannot start and no port is really in use. Run this same command with local network allowed, outside the sandbox, asking for that permission if your commands need approval."
2510
+ );
2511
+ }
2512
+ };
2513
+ function loopbackBlocked(port) {
2514
+ return new Promise((resolve) => {
2515
+ const socket = net.connect({ host: "127.0.0.1", port });
2516
+ const done = (blocked) => {
2517
+ socket.destroy();
2518
+ resolve(blocked);
2519
+ };
2520
+ socket.setTimeout(300, () => done(false));
2521
+ socket.once("connect", () => done(false));
2522
+ socket.once("error", (error) => done(error.code === "EPERM" || error.code === "EACCES"));
2523
+ });
2524
+ }
2525
+ function serverOrigin(host, port) {
2526
+ const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host.includes(":") ? `[${host}]` : host;
2527
+ return `http://${shown}:${port}`;
2528
+ }
2529
+
2530
+ import { spawn } from "node:child_process";
2531
+ import fs10 from "node:fs";
2532
+ import path12 from "node:path";
2533
+
2534
+ import crypto from "node:crypto";
2535
+ import fs9 from "node:fs";
2536
+ import path11 from "node:path";
2537
+ var GUEST_ROLES = ["editor", "commenter", "viewer"];
2538
+ var isGuestRole = (value) => typeof value === "string" && GUEST_ROLES.includes(value);
2539
+ var SHARING_FILE = ".sharing.json";
2540
+ var MAX_GUESTS = 200;
2541
+ var MAX_NAME = 40;
2542
+ var token = (bytes = 18) => crypto.randomBytes(bytes).toString("base64url");
2543
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2544
+ function fresh() {
2545
+ return { lan: false, links: { editor: { token: token(), on: true }, commenter: { token: token(), on: true }, viewer: { token: token(), on: true } }, guests: [] };
2546
+ }
2547
+ function cleanName(raw) {
2548
+ const name = typeof raw === "string" ? raw.replace(/[\u0000-\u001f\u007f@<>]/g, "").replace(/\s+/g, " ").trim() : "";
2549
+ return [...name].slice(0, MAX_NAME).join("");
2550
+ }
2551
+ var Sharing = class _Sharing {
2552
+ file;
2553
+ state;
2554
+ constructor(root) {
2555
+ this.file = path11.join(root, SHARING_FILE);
2556
+ this.state = _Sharing.read(this.file);
2557
+ }
2558
+ static read(file) {
2559
+ let raw;
2560
+ try {
2561
+ raw = JSON.parse(fs9.readFileSync(file, "utf8"));
2562
+ } catch {
2563
+ return fresh();
2564
+ }
2565
+ const state = fresh();
2566
+ if (!isRecord5(raw)) return state;
2567
+ state.lan = raw.lan === true;
2568
+ if (typeof raw.port === "number" && Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) state.port = raw.port;
2569
+ if (isRecord5(raw.links)) {
2570
+ for (const role of GUEST_ROLES) {
2571
+ const link = raw.links[role];
2572
+ if (isRecord5(link) && typeof link.token === "string" && link.token.length >= 16) state.links[role] = { token: link.token, on: link.on !== false };
2573
+ }
2574
+ }
2575
+ if (Array.isArray(raw.guests)) {
2576
+ for (const g of raw.guests) {
2577
+ if (!isRecord5(g) || typeof g.id !== "string" || typeof g.secret !== "string" || !isGuestRole(g.role) || typeof g.link !== "string") continue;
2578
+ state.guests.push({
2579
+ id: g.id,
2580
+ secret: g.secret,
2581
+ name: cleanName(g.name) || "Guest",
2582
+ role: g.role,
2583
+ link: g.link,
2584
+ joined: typeof g.joined === "string" ? g.joined : (/* @__PURE__ */ new Date(0)).toISOString(),
2585
+ ...typeof g.seen === "string" ? { seen: g.seen } : {}
2586
+ });
2587
+ }
2588
+ }
2589
+ return state;
2590
+ }
2591
+ save() {
2592
+ const tmp = `${this.file}.${process.pid}.tmp`;
2593
+ fs9.writeFileSync(tmp, `${JSON.stringify(this.state, null, 2)}
2594
+ `, { mode: 384 });
2595
+ fs9.renameSync(tmp, this.file);
2596
+ }
2597
+ /** The role whose link has this token, while that link is on. */
2598
+ linkRole(tokenGiven) {
2599
+ for (const role of GUEST_ROLES) {
2600
+ const link = this.state.links[role];
2601
+ if (link.on && tokenGiven.length === link.token.length && crypto.timingSafeEqual(Buffer.from(tokenGiven), Buffer.from(link.token))) return role;
2602
+ }
2603
+ return null;
2604
+ }
2605
+ /** The guest a cookie names, if they still have access (their link on and not reset). */
2606
+ guest(secret) {
2607
+ if (!secret) return null;
2608
+ const guest = this.state.guests.find((g) => g.secret === secret);
2609
+ return guest && this.valid(guest) ? guest : null;
2610
+ }
2611
+ valid(guest) {
2612
+ const link = this.state.links[guest.role];
2613
+ return link.on && link.token === guest.link && this.state.guests.includes(guest);
2614
+ }
2615
+ join(role, name) {
2616
+ const guest = { id: token(4), secret: token(24), name: cleanName(name) || "Guest", role, link: this.state.links[role].token, joined: (/* @__PURE__ */ new Date()).toISOString() };
2617
+ this.state.guests.push(guest);
2618
+ if (this.state.guests.length > MAX_GUESTS) this.state.guests.splice(0, this.state.guests.length - MAX_GUESTS);
2619
+ this.save();
2620
+ return guest;
2621
+ }
2622
+ /** Marks a guest seen now (saved at most once a minute per guest). */
2623
+ seen(guest) {
2624
+ const now = /* @__PURE__ */ new Date();
2625
+ if (guest.seen && now.getTime() - Date.parse(guest.seen) < 6e4) return;
2626
+ guest.seen = now.toISOString();
2627
+ this.save();
2628
+ }
2629
+ setLan(on, port) {
2630
+ this.state.lan = on;
2631
+ if (on && port) this.state.port = port;
2632
+ this.save();
2633
+ }
2634
+ setLink(role, on) {
2635
+ this.state.links[role].on = on;
2636
+ this.save();
2637
+ }
2638
+ /** A new token for the link: the old link stops working and the guests who came through it are dropped. */
2639
+ resetLink(role) {
2640
+ const old = this.state.links[role].token;
2641
+ this.state.links[role] = { token: token(), on: this.state.links[role].on };
2642
+ this.state.guests = this.state.guests.filter((g) => g.link !== old);
2643
+ this.save();
2644
+ }
2645
+ /**
2646
+ * Gives a guest another role. They now hang on that role's link (turning it off or resetting it drops them), so a role
2647
+ * whose link is off would shut them out: false then, as for a guest who isn't there.
2648
+ */
2649
+ setRole(id, role) {
2650
+ const guest = this.state.guests.find((g) => g.id === id);
2651
+ if (!guest || !this.state.links[role].on) return false;
2652
+ guest.role = role;
2653
+ guest.link = this.state.links[role].token;
2654
+ this.save();
2655
+ return true;
2656
+ }
2657
+ removeGuest(id) {
2658
+ const before = this.state.guests.length;
2659
+ this.state.guests = this.state.guests.filter((g) => g.id !== id);
2660
+ if (this.state.guests.length === before) return false;
2661
+ this.save();
2662
+ return true;
2663
+ }
2664
+ };
2665
+
2666
+ var MAX_MESSAGE = 64 * 1024 * 1024;
2667
+
2668
+ var HUB_ROUTE = "/__hub";
2669
+ function buildOf(script2) {
2670
+ const real = fs10.realpathSync(script2);
2671
+ const { mtimeMs, size } = fs10.statSync(real);
2672
+ return `${real}:${mtimeMs}:${size}`;
2673
+ }
2674
+ async function hubAt(origin) {
2675
+ try {
2676
+ const response = await fetch(`${origin}${HUB_ROUTE}`, { signal: AbortSignal.timeout(1e3) });
2677
+ if (!response.ok) return null;
2678
+ const info = await response.json();
2679
+ return info.hub === 1 ? info : null;
2680
+ } catch {
2681
+ return null;
2682
+ }
2683
+ }
2684
+ async function joinHub(call, below = Infinity) {
2685
+ if (call.port === 0) return null;
2686
+ const ports = call.portGiven ? [call.port] : Array.from({ length: PORT_TRIES }, (_, i) => call.port + i).filter((port) => port <= 65535 && port < below);
2687
+ const build = buildOf(call.script);
2688
+ const origins = ports.map((port) => serverOrigin(call.host, port));
2689
+ const infos = await Promise.all(origins.map(hubAt));
2690
+ for (const [i, info] of infos.entries()) {
2691
+ if (!info || info.kind !== call.kind || info.build !== build || info.host !== call.host) continue;
2692
+ const response = await fetch(`${origins[i]}${HUB_ROUTE}`, {
2693
+ method: "POST",
2694
+ headers: { "Content-Type": "application/json" },
2695
+ body: JSON.stringify({ action: "mount", root: call.root, ...call.agentHook ? { agentHook: call.agentHook } : {}, lan: call.lan === true }),
2696
+ signal: AbortSignal.timeout(2e4)
2697
+ }).catch(() => null);
2698
+ if (!response) continue;
2699
+ const body = await response.json().catch(() => ({}));
2700
+ if (response.ok && body.state) return body.state;
2701
+ if (response.status === 409) continue;
2702
+ throw Object.assign(new Error(body.message ?? `the server answered ${response.status}`), { code: body.code ?? "SERVER_FAILED" });
2703
+ }
2704
+ return null;
2705
+ }
2706
+ async function leaveHub(state) {
2707
+ let remaining = 0;
2708
+ const response = await fetch(`${new URL(state.url).origin}${HUB_ROUTE}`, {
2709
+ method: "POST",
2710
+ headers: { "Content-Type": "application/json" },
2711
+ body: JSON.stringify({ action: "unmount", root: state.root }),
2712
+ signal: AbortSignal.timeout(5e3)
2713
+ }).catch(() => null);
2714
+ const body = response ? await response.json().catch(() => null) : null;
2715
+ if (body?.hub === 1) remaining = Number(body.remaining ?? 0);
2716
+ else if (alive(state.pid)) process.kill(state.pid, "SIGTERM");
2717
+ const deadline = Date.now() + 5e3;
2718
+ while (remaining === 0 && alive(state.pid) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 100));
2719
+ if (remaining === 0 && alive(state.pid)) return false;
2720
+ fs10.rmSync(path12.join(state.root, STATE_FILE), { force: true });
2721
+ return true;
2722
+ }
2723
+ async function openOnHub(call) {
2724
+ if (await loopbackBlocked(call.port || 1)) throw new NetworkBlocked();
2725
+ const joined = await joinHub(call);
2726
+ if (joined) return { state: joined };
2727
+ const logFile = path12.join(call.root, LOG_FILE);
2728
+ const fd = fs10.openSync(logFile, "a");
2729
+ const child = spawn(process.execPath, [...call.command, "--background"], { detached: true, stdio: ["ignore", "ignore", fd] });
2730
+ child.unref();
2731
+ fs10.closeSync(fd);
2732
+ let exited = false;
2733
+ child.once("exit", () => exited = true);
2734
+ const deadline = Date.now() + 15e3;
2735
+ while (Date.now() < deadline) {
2736
+ await new Promise((resolve) => setTimeout(resolve, 120));
2737
+ const state = await call.running();
2738
+ if (state) return { state };
2739
+ if (exited && !readState(call.root)) break;
2740
+ }
2741
+ return { tail: fs10.existsSync(logFile) ? fs10.readFileSync(logFile, "utf8").split("\n").slice(-12).join("\n") : "" };
2742
+ }
2743
+
2744
+ import fs11 from "node:fs";
2745
+ import fsp2 from "node:fs/promises";
2746
+ import path13 from "node:path";
2747
+ import { promisify } from "node:util";
2748
+ import zlib from "node:zlib";
2749
+ var LOCAL_FILES = /* @__PURE__ */ new Set([STATE_FILE, LOG_FILE, SHARING_FILE]);
2750
+ var LOCAL_DIRS = /* @__PURE__ */ new Set([EXPORTS_DIR]);
2751
+ var JUNK_FILES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
2752
+ var isTemp = (name) => name.endsWith(".tmp") || name.startsWith(".tmp-");
2753
+ var STORED = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".heic", ".mp4", ".m4v", ".mov", ".webm", ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".flac", ".woff", ".woff2", ".zip", ".gz", ".br", ".zst", ".7z"]);
2754
+ var MAX_ENTRIES = 65535;
2755
+ var MAX_BYTES = 4294967295;
2756
+ var ArchiveTooLarge = class extends Error {
2757
+ code = "TOO_LARGE";
2758
+ };
2759
+ async function archiveEntries(root, skip = []) {
2760
+ const folder = path13.basename(path13.resolve(root)) || "artifact";
2761
+ const skipped = new Set(skip.map((file) => path13.resolve(file)));
2762
+ const entries = [];
2763
+ const walk2 = async (dir, rel) => {
2764
+ let names;
2765
+ try {
2766
+ names = await fsp2.readdir(dir, { withFileTypes: true });
2767
+ } catch (error) {
2768
+ if (rel && error.code === "ENOENT") return;
2769
+ throw error;
2770
+ }
2771
+ for (const dirent of names.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
2772
+ const name = dirent.name;
2773
+ if (JUNK_FILES.has(name) || isTemp(name) || !rel && (LOCAL_FILES.has(name) || LOCAL_DIRS.has(name) && dirent.isDirectory())) continue;
2774
+ const file = path13.join(dir, name);
2775
+ if (skipped.has(file)) continue;
2776
+ const inner = rel ? `${rel}/${name}` : name;
2777
+ if (dirent.isDirectory()) await walk2(file, inner);
2778
+ else if (dirent.isFile()) {
2779
+ const stat = await fsp2.stat(file).catch(() => null);
2780
+ if (stat?.isFile()) entries.push({ name: `${folder}/${inner}`, file, size: stat.size, mode: stat.mode & 511, mtime: stat.mtime });
2781
+ }
2782
+ }
2783
+ };
2784
+ await walk2(path13.resolve(root), "");
2785
+ if (entries.length > MAX_ENTRIES) throw new ArchiveTooLarge(`The folder holds ${entries.length} files, more than a zip holds (${MAX_ENTRIES}); copy the folder itself instead.`);
2786
+ const bound = entries.reduce((sum, entry) => sum + entry.size + 2 * (46 + Buffer.byteLength(entry.name)), 22);
2787
+ if (bound > MAX_BYTES) throw new ArchiveTooLarge(`The folder holds ${(bound / 2 ** 30).toFixed(1)} GiB, more than a zip holds (4 GiB); copy the folder itself instead.`);
2788
+ return entries;
2789
+ }
2790
+ var CRC_TABLE = (() => {
2791
+ const table = new Uint32Array(256);
2792
+ for (let n = 0; n < 256; n++) {
2793
+ let c = n;
2794
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
2795
+ table[n] = c >>> 0;
2796
+ }
2797
+ return table;
2798
+ })();
2799
+ function crc32(bytes) {
2800
+ let crc = 4294967295;
2801
+ for (let i = 0; i < bytes.length; i++) crc = CRC_TABLE[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
2802
+ return (crc ^ 4294967295) >>> 0;
2803
+ }
2804
+ function dosTime(date) {
2805
+ const year = date.getFullYear();
2806
+ if (year < 1980) return { time: 0, date: 1 << 5 | 1 };
2807
+ if (year > 2107) return { time: 23 << 11 | 59 << 5 | 29, date: 127 << 9 | 12 << 5 | 31 };
2808
+ return {
2809
+ time: date.getHours() << 11 | date.getMinutes() << 5 | date.getSeconds() >> 1,
2810
+ date: year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
2811
+ };
2812
+ }
2813
+ var deflateRaw = promisify(zlib.deflateRaw);
2814
+ var UTF8 = 1 << 11;
2815
+ async function writeZip(entries, write) {
2816
+ const central = [];
2817
+ let offset = 0;
2818
+ const put = async (chunk) => {
2819
+ await write(chunk);
2820
+ offset += chunk.length;
2821
+ };
2822
+ for (const entry of entries) {
2823
+ let data;
2824
+ try {
2825
+ data = await fsp2.readFile(entry.file);
2826
+ } catch (error) {
2827
+ if (error.code === "ENOENT") continue;
2828
+ throw error;
2829
+ }
2830
+ const crc = crc32(data);
2831
+ let method = 0;
2832
+ let body = data;
2833
+ if (data.length > 0 && !STORED.has(path13.extname(entry.name).toLowerCase())) {
2834
+ const deflated = await deflateRaw(data);
2835
+ if (deflated.length < data.length) {
2836
+ method = 8;
2837
+ body = deflated;
2838
+ }
2839
+ }
2840
+ if (offset + body.length > MAX_BYTES) throw new ArchiveTooLarge("The folder grew past what a zip holds (4 GiB) while it was being zipped.");
2841
+ const name = Buffer.from(entry.name, "utf8");
2842
+ const { time, date } = dosTime(entry.mtime);
2843
+ const local = Buffer.alloc(30);
2844
+ local.writeUInt32LE(67324752, 0);
2845
+ local.writeUInt16LE(20, 4);
2846
+ local.writeUInt16LE(UTF8, 6);
2847
+ local.writeUInt16LE(method, 8);
2848
+ local.writeUInt16LE(time, 10);
2849
+ local.writeUInt16LE(date, 12);
2850
+ local.writeUInt32LE(crc, 14);
2851
+ local.writeUInt32LE(body.length, 18);
2852
+ local.writeUInt32LE(data.length, 22);
2853
+ local.writeUInt16LE(name.length, 26);
2854
+ local.writeUInt16LE(0, 28);
2855
+ const header = Buffer.alloc(46);
2856
+ header.writeUInt32LE(33639248, 0);
2857
+ header.writeUInt16LE(3 << 8 | 20, 4);
2858
+ header.writeUInt16LE(20, 6);
2859
+ header.writeUInt16LE(UTF8, 8);
2860
+ header.writeUInt16LE(method, 10);
2861
+ header.writeUInt16LE(time, 12);
2862
+ header.writeUInt16LE(date, 14);
2863
+ header.writeUInt32LE(crc, 16);
2864
+ header.writeUInt32LE(body.length, 20);
2865
+ header.writeUInt32LE(data.length, 24);
2866
+ header.writeUInt16LE(name.length, 28);
2867
+ header.writeUInt32LE((32768 | (entry.mode || 420) | 384) << 16 >>> 0, 38);
2868
+ header.writeUInt32LE(offset, 42);
2869
+ central.push(header, name);
2870
+ await put(Buffer.concat([local, name]));
2871
+ await put(body);
2872
+ }
2873
+ const start = offset;
2874
+ const directory = Buffer.concat(central);
2875
+ await put(directory);
2876
+ const end = Buffer.alloc(22);
2877
+ end.writeUInt32LE(101010256, 0);
2878
+ end.writeUInt16LE(central.length / 2, 8);
2879
+ end.writeUInt16LE(central.length / 2, 10);
2880
+ end.writeUInt32LE(directory.length, 12);
2881
+ end.writeUInt32LE(start, 16);
2882
+ await put(end);
2883
+ return offset;
2884
+ }
2885
+ function archiveFileName(root, now = /* @__PURE__ */ new Date()) {
2886
+ const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
2887
+ return `${path13.basename(path13.resolve(root)) || "artifact"}-${day}.zip`;
2888
+ }
2889
+ async function writeArchive(root, out) {
2890
+ const file = path13.resolve(out);
2891
+ const entries = await archiveEntries(root, [file]);
2892
+ const tmp = path13.join(path13.dirname(file), `.${path13.basename(file)}.${process.pid}.tmp`);
2893
+ const handle = await fsp2.open(tmp, "w");
2894
+ let bytes;
2895
+ try {
2896
+ bytes = await writeZip(entries, async (chunk) => {
2897
+ await handle.write(chunk);
2898
+ });
2899
+ await handle.close();
2900
+ } catch (error) {
2901
+ await handle.close().catch(() => {
2902
+ });
2903
+ await fsp2.rm(tmp, { force: true });
2904
+ throw error;
2905
+ }
2906
+ await fsp2.rename(tmp, file);
2907
+ return { file, files: entries.length, bytes };
2908
+ }
2909
+ async function archiveCommand(root, out) {
2910
+ const where = out ? path13.resolve(out) : path13.dirname(path13.resolve(root));
2911
+ const target = fs11.statSync(where, { throwIfNoEntry: false })?.isDirectory() ? path13.join(where, archiveFileName(root)) : where;
2912
+ const { file, files, bytes } = await writeArchive(root, target);
2913
+ return { file, folder: path13.basename(path13.resolve(root)), files, bytes, leftOut: [...LOCAL_FILES] };
2914
+ }
2915
+
2916
+ import fs12 from "node:fs";
2917
+ import path14 from "node:path";
2918
+ var FOLDER = /^[a-z0-9][a-z0-9_-]{0,63}$/;
2919
+ var MAX_FILES = 2e3;
2920
+ var MAX_FILE_BYTES = 64 * 1024 * 1024;
2921
+ var DESIGN_SYSTEM_FILE2 = "design-system.json";
2922
+ function readRecords(project, indexFile) {
2923
+ let index;
2924
+ try {
2925
+ index = JSON.parse(fs12.readFileSync(path14.join(project, indexFile), "utf8"));
2926
+ } catch {
2927
+ return [];
2928
+ }
2929
+ const list = index?.designSystems;
2930
+ const records = Array.isArray(list) ? list : list && typeof list === "object" ? Object.values(list) : [];
2931
+ const out = [];
2932
+ for (const raw of records) {
2933
+ const r = raw;
2934
+ if (typeof r?.namespace !== "string" || !FOLDER.test(r.namespace)) continue;
2935
+ out.push({
2936
+ namespace: r.namespace,
2937
+ title: typeof r.title === "string" ? r.title : r.namespace,
2938
+ artifact: typeof r.artifact === "string" ? r.artifact : ""
2939
+ });
2940
+ }
2941
+ return out;
2942
+ }
2943
+ function plain(p, want) {
2944
+ const stat = fs12.lstatSync(p, { throwIfNoEntry: false });
2945
+ return Boolean(stat && !stat.isSymbolicLink() && (want === "file" ? stat.isFile() : stat.isDirectory()));
2946
+ }
2947
+ function walk(dir, prefix = "", out = []) {
2948
+ for (const entry of fs12.readdirSync(path14.join(dir, prefix), { withFileTypes: true })) {
2949
+ if (out.length >= MAX_FILES) break;
2950
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
2951
+ if (entry.isDirectory()) walk(dir, rel, out);
2952
+ else if (entry.isFile()) out.push(rel);
2953
+ }
2954
+ return out;
2955
+ }
2956
+ var projectOf = (candidate) => path14.basename(candidate) === "project" ? candidate : path14.join(candidate, "project");
2957
+ function sourceProject(artifact, root, from) {
2958
+ const given = from ?? artifact;
2959
+ if (!given) return { reason: "the record names no source folder", kind: "none" };
2960
+ if (!from && /^[a-z][a-z0-9+.-]*:\/\//i.test(given)) return { reason: `its source is ${given}, which is not a folder on this machine`, kind: "remote" };
2961
+ const candidates = path14.isAbsolute(given) ? [given] : [path14.resolve(given), path14.resolve(root, given), path14.resolve(root, "..", given)];
2962
+ for (const candidate of candidates) {
2963
+ const project = projectOf(candidate);
2964
+ if (plain(project, "dir")) return { project };
2965
+ }
2966
+ if (!from && !path14.isAbsolute(given)) {
2967
+ let dir = path14.resolve(root, "..");
2968
+ for (let up = path14.dirname(dir); up !== dir; up = path14.dirname(dir)) {
2969
+ dir = up;
2970
+ const project = projectOf(path14.resolve(dir, given));
2971
+ if (plain(path14.join(project, DESIGN_SYSTEM_FILE2), "file")) return { project };
2972
+ }
2973
+ }
2974
+ return { reason: `its source folder ${given} was not found${from ? "" : ` (tried from ${process.cwd()} and the folders above the artifact); pass --from <folder>`}`, kind: "not-found" };
2975
+ }
2976
+ function compareSystem(project, root, record, from) {
2977
+ const diff = { namespace: record.namespace, title: record.title, changed: [], removed: [] };
2978
+ const found = sourceProject(record.artifact, root, from);
2979
+ if (!found.project) return { ...diff, skipped: found.reason, skippedKind: found.kind };
2980
+ diff.source = path14.dirname(found.project);
2981
+ const copy = path14.join(project, "ds", record.namespace);
2982
+ if (!plain(copy, "dir")) return { ...diff, missing: true };
2983
+ for (const rel of walk(copy)) {
2984
+ const mine = path14.join(copy, rel);
2985
+ const theirs = path14.join(found.project, rel);
2986
+ if (!plain(mine, "file")) continue;
2987
+ if (!plain(theirs, "file")) {
2988
+ diff.removed.push(rel);
2989
+ continue;
2990
+ }
2991
+ const a = fs12.statSync(mine);
2992
+ const b = fs12.statSync(theirs);
2993
+ if (a.size > MAX_FILE_BYTES || b.size > MAX_FILE_BYTES) continue;
2994
+ if (a.size !== b.size || !fs12.readFileSync(mine).equals(fs12.readFileSync(theirs))) diff.changed.push(rel);
2995
+ }
2996
+ return diff;
2997
+ }
2998
+ function pick(records, namespace) {
2999
+ if (namespace === void 0) return records;
3000
+ const one = records.filter((r) => r.namespace === namespace);
3001
+ if (one.length === 0) {
3002
+ const names = records.map((r) => r.namespace);
3003
+ throw new Error(`No designSystems record has namespace ${JSON.stringify(namespace)}${names.length ? ` (it has: ${names.join(", ")})` : ""}.`);
3004
+ }
3005
+ return one;
3006
+ }
3007
+ function compareSystems(project, root, indexFile, namespace, from) {
3008
+ return pick(readRecords(project, indexFile), namespace).map((r) => compareSystem(project, root, r, from));
3009
+ }
3010
+ function staleNotes(project, root, indexFile, command) {
3011
+ const notes = [];
3012
+ for (const diff of compareSystems(project, root, indexFile)) {
3013
+ if (diff.changed.length === 0 && diff.removed.length === 0) continue;
3014
+ const parts = [];
3015
+ if (diff.changed.length > 0) parts.push(`${diff.changed.length} changed (${diff.changed.slice(0, 3).join(", ")}${diff.changed.length > 3 ? ", \u2026" : ""})`);
3016
+ if (diff.removed.length > 0) parts.push(`${diff.removed.length} gone from the source`);
3017
+ notes.push(
3018
+ `project/ds/${diff.namespace}/ is behind its source system ${diff.source}: ${parts.join(", ")}. A copy never changes by itself: run \`${command(diff.namespace, false)}\` to copy the changed files again (\`${command(diff.namespace, true)}\` lists them).`
3019
+ );
3020
+ }
3021
+ return notes;
3022
+ }
3023
+ function stamp(project, indexFile, namespaces, now) {
3024
+ const file = path14.join(project, indexFile);
3025
+ const text = fs12.readFileSync(file, "utf8");
3026
+ const index = JSON.parse(text);
3027
+ const list = index.designSystems;
3028
+ const records = Array.isArray(list) ? list : list && typeof list === "object" ? Object.values(list) : [];
3029
+ for (const r of records) {
3030
+ const record = r;
3031
+ if (record && typeof record.namespace === "string" && namespaces.has(record.namespace)) record.copiedAt = now;
3032
+ }
3033
+ const indent = /^\{\n/.test(text) ? /\n( +|\t)"/.exec(text)?.[1] ?? 2 : void 0;
3034
+ const out = JSON.stringify(index, null, indent);
3035
+ const tmp = `${file}.${process.pid}.tmp`;
3036
+ fs12.writeFileSync(tmp, text.endsWith("\n") ? `${out}
3037
+ ` : out);
3038
+ fs12.renameSync(tmp, file);
3039
+ }
3040
+ function syncSystems(project, root, indexFile, opts) {
3041
+ const diffs = compareSystems(project, root, indexFile, opts.namespace, opts.from);
3042
+ const results = [];
3043
+ const synced = /* @__PURE__ */ new Set();
3044
+ const now = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
3045
+ for (const diff of diffs) {
3046
+ const result = { ...diff, copied: [] };
3047
+ if (!opts.check && diff.source && !diff.missing) {
3048
+ for (const rel of diff.changed) {
3049
+ const target = path14.join(project, "ds", diff.namespace, rel);
3050
+ const tmp = `${target}.${process.pid}.tmp`;
3051
+ fs12.copyFileSync(path14.join(diff.source, "project", rel), tmp);
3052
+ fs12.renameSync(tmp, target);
3053
+ result.copied.push(rel);
3054
+ }
3055
+ if (diff.changed.length > 0) synced.add(diff.namespace);
3056
+ }
3057
+ results.push(result);
3058
+ }
3059
+ if (synced.size > 0) {
3060
+ stamp(project, indexFile, synced, now);
3061
+ for (const r of results) if (synced.has(r.namespace)) r.copiedAt = now;
3062
+ }
3063
+ return results;
3064
+ }
3065
+
3066
+ async function shareCall(url, action, fail2) {
3067
+ const response = await fetch(new URL("__share", url), action ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(action) } : {});
3068
+ const body = await response.json().catch(() => ({}));
3069
+ if (!response.ok) fail2("SHARE_REFUSED", String(body.message ?? `the server answered ${response.status}`));
3070
+ return body;
3071
+ }
3072
+ function rolesOf(flags, key, fail2) {
3073
+ const given = flags.get(key);
3074
+ if (given === void 0) return [];
3075
+ const roles = given === "all" || given === "true" ? [...GUEST_ROLES] : given.split(",").map((r) => r.trim());
3076
+ for (const role of roles) if (!isGuestRole(role)) fail2("INVALID_ROLE", `--${key}: editor, commenter, viewer or all (got ${role}).`);
3077
+ return roles;
3078
+ }
3079
+ function guestRoles(flags, fail2) {
3080
+ const given = flags.get("role");
3081
+ if (given === void 0) return [];
3082
+ return given.split(",").map((pair) => {
3083
+ const [guest = "", role = ""] = pair.split("=").map((part) => part.trim());
3084
+ if (!guest || !isGuestRole(role)) fail2("INVALID_ROLE", `--role: <guest id>=editor|commenter|viewer, comma separated (got ${pair}).`);
3085
+ return { action: "role", guest, role };
3086
+ });
3087
+ }
3088
+ async function shareCommand(o) {
3089
+ const off = o.flags.has("off");
3090
+ const changes = [
3091
+ ...rolesOf(o.flags, "reset", o.fail).map((role) => ({ action: "reset", role })),
3092
+ ...rolesOf(o.flags, "enable", o.fail).map((role) => ({ action: "link", role, on: true })),
3093
+ ...rolesOf(o.flags, "disable", o.fail).map((role) => ({ action: "link", role, on: false })),
3094
+ ...guestRoles(o.flags, o.fail)
3095
+ ];
3096
+ const open2 = !off && changes.length === 0;
3097
+ let server = await o.running();
3098
+ if (!server) {
3099
+ const sharing = new Sharing(o.root);
3100
+ for (const change of changes) {
3101
+ if (change.action === "reset") sharing.resetLink(change.role);
3102
+ else if (change.action === "role") {
3103
+ if (!sharing.setRole(String(change.guest), change.role)) o.fail("SHARE_REFUSED", `No guest ${String(change.guest)}, or the ${String(change.role)} link is off.`);
3104
+ } else sharing.setLink(change.role, change.on === true);
3105
+ }
3106
+ if (off) {
3107
+ sharing.setLan(false);
3108
+ return { lan: false, message: "Not shared on the local network. Guests already in get their place back when it is shared again (unless their link was reset)." };
3109
+ }
3110
+ if (!open2 && !sharing.state.lan) {
3111
+ return {
3112
+ lan: false,
3113
+ links: Object.fromEntries(GUEST_ROLES.map((role) => [role, sharing.state.links[role].on ? "on" : "off"])),
3114
+ message: `Links changed. Not shared on the local network: ${NOT_SHARED_HINT}`
3115
+ };
3116
+ }
3117
+ server = await o.startShared();
3118
+ if (!server) o.fail("SERVER_FAILED", `The server did not start. Run ${o.serveCommand} in the foreground to see why.`);
3119
+ }
3120
+ let view = await shareCall(server.url, null, o.fail);
3121
+ for (const change of changes) view = await shareCall(server.url, change, o.fail);
3122
+ if (off || open2 && !view.lan) view = await shareCall(server.url, { action: "lan", on: !off }, o.fail);
3123
+ const links = view.links;
3124
+ const shown = (list) => Object.fromEntries(Object.entries(list).map(([role, link]) => [role, link.on ? link.url : "off"]));
3125
+ const tailnet = view.lan ? view.tailnet : void 0;
3126
+ return {
3127
+ lan: view.lan,
3128
+ ...view.lan ? { addresses: lanUrls(view) } : {},
3129
+ links: shown(links),
3130
+ ...tailnet ? {
3131
+ tailscale: shown(tailnet.links),
3132
+ tailscaleNote: `This computer has a Tailscale address (${tailnet.address}): the tailscale links open the same roles for people on your tailnet, from any network. Use the links above for people on this Wi-Fi or LAN.`
3133
+ } : {},
3134
+ guests: view.guests,
3135
+ ...view.lan ? {
3136
+ note: "Send the link for the role you want to give: editor edits, commenter comments, viewer reads. Anyone on this network with a link joins under a name they type. The owner (this computer) shares from the Share button too.",
3137
+ security: "It is plain http: others on the network can read what passes. A link is the permission: whoever has it gets its role, so send it only to the people meant to have it, and reset a role's link if it went further.",
3138
+ stop: o.offCommand
3139
+ } : { note: `Not shared on the network: the links work on this computer only. ${NOT_SHARED_HINT}` }
3140
+ };
3141
+ }
3142
+ var NOT_SHARED_HINT = "share <root> with no options shares it.";
3143
+ var lanUrls = (view) => (Array.isArray(view.addresses) ? view.addresses : []).map((a) => `http://${String(a)}:${String(view.port)}${String(view.page ?? "/")}`);
3144
+ async function lanOn(url, flags, fail2) {
3145
+ if (!flags.has("lan")) return {};
3146
+ return { lan: lanUrls(await shareCall(url, { action: "lan", on: true }, fail2)) };
3147
+ }
3148
+
3149
+ var emitWarning = process.emitWarning.bind(process);
3150
+ process.emitWarning = ((warning, ...rest) => {
3151
+ if (String(typeof warning === "string" ? warning : warning.message).includes("localStorage")) return;
3152
+ emitWarning(warning, ...rest);
3153
+ });
3154
+ var KIND = "slides";
3155
+ var SCRIPT = fileURLToPath2(import.meta.url);
3156
+ var EDITOR_DIR = path15.join(path15.dirname(SCRIPT), "editor");
3157
+ var SERVER_SCRIPT = path15.join(path15.dirname(SCRIPT), "server.mjs");
3158
+ var MAX_LISTED = 200;
3159
+ var UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
3160
+ var INDEX_FILE = KIND === "slides" ? "deck.json" : KIND === "design" ? CANVAS_FILE : DESIGN_SYSTEM_FILE;
3161
+ var LAYOUT = KIND === "slides" ? DECK_LAYOUT : KIND === "design" ? CANVAS_LAYOUT : DESIGN_SYSTEM_LAYOUT;
3162
+ var NOUN = KIND === "slides" ? "deck" : KIND === "design" ? "design" : "design system";
3163
+ var CliError = class extends Error {
3164
+ code;
3165
+ constructor(code, message) {
3166
+ super(message);
3167
+ this.code = code;
3168
+ }
3169
+ };
3170
+ var SWITCHES = /* @__PURE__ */ new Set(["all", "wait", "resolve", "reopen", "lan", "off", "check"]);
3171
+ function parseArgs(argv) {
3172
+ const positional = [];
3173
+ const flags = /* @__PURE__ */ new Map();
3174
+ for (let i = 0; i < argv.length; i++) {
3175
+ const arg = argv[i];
3176
+ if (arg.startsWith("--")) {
3177
+ const eq = arg.indexOf("=");
3178
+ if (eq > 0) flags.set(arg.slice(2, eq), arg.slice(eq + 1));
3179
+ else if (SWITCHES.has(arg.slice(2))) flags.set(arg.slice(2), "true");
3180
+ else if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) flags.set(arg.slice(2), argv[++i]);
3181
+ else flags.set(arg.slice(2), "true");
3182
+ } else positional.push(arg);
3183
+ }
3184
+ return { positional, flags };
3185
+ }
3186
+ function print(value) {
3187
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
3188
+ `);
3189
+ }
3190
+ var script = (cmd, ...args) => ["node", quote(SCRIPT), cmd, ...args.map(quote)].join(" ");
3191
+ function quote(s) {
3192
+ return /^[A-Za-z0-9_./:@%+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
3193
+ }
3194
+ function resolveArtifact(given, mustExist = true) {
3195
+ if (!given) throw new CliError("MISSING_ROOT", `Give the artifact folder: the one that holds project/${INDEX_FILE}.`);
3196
+ let root = path15.resolve(given);
3197
+ if (path15.basename(root) === "project" && fs13.existsSync(path15.join(root, INDEX_FILE)) && !fs13.existsSync(path15.join(root, "project"))) {
3198
+ root = path15.dirname(root);
3199
+ }
3200
+ const project = path15.join(root, "project");
3201
+ if (mustExist) {
3202
+ const stat = fs13.statSync(project, { throwIfNoEntry: false });
3203
+ if (!stat?.isDirectory()) {
3204
+ throw new CliError("NOT_FOUND", `${project} does not exist. Write project/${INDEX_FILE} and the other files under ${root} first.`);
3205
+ }
3206
+ }
3207
+ return { root, project };
3208
+ }
3209
+ async function readInfo(project) {
3210
+ if (KIND === "slides") return await readDeckSummary(project);
3211
+ if (KIND === "design") return await readCanvasInfo(project);
3212
+ return await readDesignSystemInfo(project);
3213
+ }
3214
+ function localize(value) {
3215
+ const text = JSON.stringify(value).replace(/\b(?:design_system|design|slides)_import_asset\b/g, "artifact.mjs upload").replace(/\b(?:design_system|design|slides)_check\b/g, "artifact.mjs check").replace(
3216
+ /BaoCut previews load nothing from the network but Google Fonts \(no CDN in the page CSP\)/g,
3217
+ "previews here load nothing from the network but Google Fonts: make the library a file in components/lib/ with a libraries entry (format.md); React 18 comes with the page"
3218
+ );
3219
+ return JSON.parse(text);
3220
+ }
3221
+ function designSystemNotes(project, indexFile) {
3222
+ let index;
3223
+ try {
3224
+ index = JSON.parse(fs13.readFileSync(path15.join(project, indexFile), "utf8"));
3225
+ } catch {
3226
+ return [];
3227
+ }
3228
+ const list = index?.designSystems;
3229
+ const records = Array.isArray(list) ? list : list && typeof list === "object" ? Object.values(list) : [];
3230
+ const notes = [];
3231
+ for (const record of records) {
3232
+ const ns = record?.namespace;
3233
+ if (typeof ns !== "string") continue;
3234
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(ns)) {
3235
+ notes.push(`designSystems namespace ${JSON.stringify(ns)} is not a folder name ([a-z0-9][a-z0-9_-]{0,63}): the page skips it. Use the lower-case folder (list prints it as folder), the same in the record and in project/ds/<folder>/.`);
3236
+ continue;
3237
+ }
3238
+ const folder = path15.join(project, "ds", ns);
3239
+ if (!fs13.existsSync(folder)) {
3240
+ notes.push(`designSystems names "${ns}" but project/ds/${ns}/ does not exist: copy the system's project/tokens.json (and the files you use) there, or take the record out.`);
3241
+ } else if (!fs13.existsSync(path15.join(folder, "tokens.json"))) {
3242
+ notes.push(`project/ds/${ns}/ has no tokens.json, so the Theme and color menus show bare hexes: copy the system's project/tokens.json there (a system with none: nothing to do).`);
3243
+ }
3244
+ }
3245
+ const root = path15.dirname(project);
3246
+ return [...notes, ...staleNotes(project, root, indexFile, (ns, listOnly) => script("ds-sync", root, ns, ...listOnly ? ["--check"] : []))];
3247
+ }
3248
+ async function check(a) {
3249
+ if (KIND === "slides") {
3250
+ let rt;
3251
+ try {
3252
+ rt = loadSlidesCompiler(EDITOR_DIR);
3253
+ } catch {
3254
+ throw new CliError("COMPILER_MISSING", `The slides compiler is missing (${path15.join(EDITOR_DIR, "node", "compiler.cjs")}); reinstall the skill.`);
3255
+ }
3256
+ if (!fs13.existsSync(path15.join(a.project, "deck.json"))) {
3257
+ return {
3258
+ problems: 1,
3259
+ result: {
3260
+ root: a.root,
3261
+ slideCount: 0,
3262
+ problems: 1,
3263
+ deckProblems: ['deck.json: missing: a deck needs project/deck.json with "v": 4, "title" and "order" (Creating, step 4)'],
3264
+ next: "Write project/deck.json and the slides, then run check again until problems is 0."
3265
+ }
3266
+ };
3267
+ }
3268
+ let report;
3269
+ try {
3270
+ report = checkDeck(rt, a.project, { verbose: true });
3271
+ } catch (error) {
3272
+ throw new CliError("CHECK_FAILED", `The check did not finish: ${error.message}. Is project/deck.json valid JSON?`);
3273
+ }
3274
+ const problems2 = problemCount(report);
3275
+ const slides = report.slides.filter((s) => s.problems.length > 0 || s.notes.length > 0 || s.roundTripDrift).map((s) => ({
3276
+ id: s.id,
3277
+ ...s.problems.length > 0 ? { problems: s.problems } : {},
3278
+ ...s.notes.length > 0 ? { notes: s.notes } : {},
3279
+ ...s.roundTripDrift ? { roundTripDrift: true } : {}
3280
+ }));
3281
+ const layoutNotes = slides.some((s) => s.notes?.some((n) => n.startsWith("\u6392\u7248") || n.startsWith("\u8B66\u544A")));
3282
+ const dsNotes = designSystemNotes(a.project, "deck.json");
3283
+ return {
3284
+ problems: problems2,
3285
+ result: {
3286
+ root: a.root,
3287
+ title: report.title,
3288
+ slideCount: report.slides.length,
3289
+ problems: problems2,
3290
+ ...report.deckProblems.length > 0 ? { deckProblems: report.deckProblems } : {},
3291
+ ...report.orphans.length > 0 ? { orphans: report.orphans } : {},
3292
+ ...slides.length > 0 ? { slides } : {},
3293
+ ...dsNotes.length > 0 ? { designSystemNotes: dsNotes } : {},
3294
+ notChecked: "Text sizes, contrast, whether a section id matches its file name and whether an image path exists are not checked (nothing is rendered).",
3295
+ next: problems2 > 0 ? `Fix the files named in deckProblems and in each slide's problems (paths are under project/), then run check again until problems is 0. notes are hints and lose no content; fix the layout ones (starting "\u6392\u7248") and the warnings (starting "\u8B66\u544A": a font or image falls back) too.` : `No problems. Show it to the user: ${script("open", a.root)} prints the editor URL.` + (layoutNotes ? ' Some slides carry layout notes ("\u6392\u7248": content may overflow or overlap) or warnings ("\u8B66\u544A": a font or image falls back); fix them and check again.' : "") + (report.orphans.length > 0 ? " orphans are slide files missing from order: they do not show; delete the unneeded ones." : "") + (dsNotes.length > 0 ? " Read designSystemNotes: a design system install looks incomplete or behind its source." : "")
3296
+ }
3297
+ };
3298
+ }
3299
+ if (KIND === "design") {
3300
+ const r2 = await checkCanvas(a.project);
3301
+ const problems2 = r2.issues.length;
3302
+ const dsNotes = designSystemNotes(a.project, CANVAS_FILE);
3303
+ return {
3304
+ problems: problems2,
3305
+ result: {
3306
+ root: a.root,
3307
+ title: r2.title,
3308
+ boardCount: r2.boardCount,
3309
+ problems: problems2,
3310
+ ...problems2 > 0 ? { issues: r2.issues.slice(0, MAX_LISTED) } : {},
3311
+ ...problems2 > MAX_LISTED ? { more: `${problems2 - MAX_LISTED} more not listed: fix these, then check again` } : {},
3312
+ ...dsNotes.length > 0 ? { designSystemNotes: dsNotes } : {},
3313
+ notChecked: "Whether the artboard scripts run, and how the layout looks, is not checked (nothing is rendered).",
3314
+ next: problems2 > 0 ? 'Fix the files per issues (file is a path under project/; "." is the whole folder), then run check again until problems is 0.' : `No problems. Show it to the user: ${script("open", a.root)} prints the editor URL.` + (dsNotes.length > 0 ? " Read designSystemNotes: a design system install looks incomplete or behind its source." : "")
3315
+ }
3316
+ };
3317
+ }
3318
+ const r = await checkDesignSystem(a.project);
3319
+ const problems = r.issues.length;
3320
+ if (fs13.existsSync(path15.join(a.project, DESIGN_SYSTEM_FILE))) {
3321
+ if (!fs13.existsSync(path15.join(a.project, "README.md"))) {
3322
+ r.notes.push({ file: "README.md", message: "missing: every system includes project/README.md; every reader starts there (Creating, step 1)" });
3323
+ }
3324
+ if (!fs13.existsSync(path15.join(a.project, "components", "Cover", "preview.html"))) {
3325
+ r.notes.push({ file: "components/Cover/preview.html", message: "missing: every system gets a cover, written last before the index (cover.md)" });
3326
+ }
3327
+ }
3328
+ return {
3329
+ problems,
3330
+ result: {
3331
+ root: a.root,
3332
+ title: r.title,
3333
+ namespace: r.namespace,
3334
+ problems,
3335
+ ...problems > 0 ? { issues: r.issues.slice(0, MAX_LISTED) } : {},
3336
+ ...r.notes.length > 0 ? { notes: r.notes.slice(0, 50) } : {},
3337
+ ...problems > MAX_LISTED ? { more: `${problems - MAX_LISTED} more not listed: fix these, then check again` } : {},
3338
+ notChecked: `${r.notChecked.join(", ")} are generated by the editor when it saves and are not checked; whether components render is not checked (nothing is rendered).`,
3339
+ next: problems > 0 ? 'Fix the files per issues (file is a path under project/; "." is the whole folder), then run check again until problems is 0. Read the notes too: most need no change, but one naming a missing README or cover, or a file that hides an asset record, means a file to write or remove.' : `No problems. ${r.notes.length > 0 ? "Read the notes: most need no change, but one naming a missing README or cover, or a file that hides an asset record, means a file to write or remove. " : ""}Show it to the user: ${script("open", a.root)} prints the editor URL.`
3340
+ }
3341
+ };
3342
+ }
3343
+ var DESIGN_SYSTEM_UPLOAD_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "mp4", "webm", "pdf", "woff2", "woff", "ttf", "otf"]);
3344
+ var CANVAS_TEXT_UPLOADS = /* @__PURE__ */ new Set(["css", "js", "mjs", "json"]);
3345
+ function formatBytes(n) {
3346
+ return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`;
3347
+ }
3348
+ async function upload(a, given, group) {
3349
+ if (!given) throw new CliError("MISSING_FILE", "Give the file to upload.");
3350
+ const file = path15.resolve(given);
3351
+ const stat = await fsp3.stat(file).catch(() => null);
3352
+ if (!stat) throw new CliError("FILE_NOT_FOUND", `No such file: ${given}`);
3353
+ if (!stat.isFile()) throw new CliError("NOT_A_FILE", `${given} is not a regular file.`);
3354
+ const ext = path15.extname(file).slice(1).toLowerCase();
3355
+ const type = contentTypeOf(file);
3356
+ const isMedia = type.startsWith("image/") || type.startsWith("font/");
3357
+ let limit = UPLOAD_MAX_BYTES;
3358
+ if (KIND === "slides") {
3359
+ if (!isMedia) throw new CliError("UNSUPPORTED_TYPE", "Only images (png, jpg, gif, webp, avif, svg) and fonts (woff2, woff, ttf, otf) can be uploaded, judged by extension. Convert other images to png first.");
3360
+ } else if (KIND === "design") {
3361
+ if (!isMedia && !CANVAS_TEXT_UPLOADS.has(ext)) {
3362
+ throw new CliError("UNSUPPORTED_TYPE", "Only images (png, jpg, gif, webp, avif, svg), fonts (woff2, woff, ttf, otf) and .css .js .json files can be uploaded, judged by extension.");
3363
+ }
3364
+ } else {
3365
+ if (!DESIGN_SYSTEM_UPLOAD_EXTENSIONS.has(ext)) {
3366
+ throw new CliError("UNSUPPORTED_TYPE", `Only ${[...DESIGN_SYSTEM_UPLOAD_EXTENSIONS].join(", ")} files can be uploaded, judged by extension. Text files (README.md, .json, .css, .js) are files, not uploads.`);
3367
+ }
3368
+ if (group === void 0) {
3369
+ throw new CliError("MISSING_GROUP", "Give --group <Group>: a design system's uploads sit in an asset group (assets/<Group>/<file>). Fonts are files: copy them to project/fonts/ instead.");
3370
+ }
3371
+ if (!isAssetGroupName(group)) {
3372
+ throw new CliError("INVALID_GROUP", "--group is an asset group folder name: at most 80 characters, no / \\ or control characters, no surrounding spaces, not . or ..");
3373
+ }
3374
+ limit = designSystemUploadLimit(type);
3375
+ }
3376
+ if (stat.size > limit) throw new CliError("FILE_TOO_LARGE", `${given} is ${formatBytes(stat.size)}, over the ${formatBytes(limit)} limit: compress or shrink it first.`);
3377
+ const bytes = await fsp3.readFile(file);
3378
+ const uploaded = await new DeckStore(a.project, LAYOUT).putBlob(bytes, type);
3379
+ const base = path15.basename(file);
3380
+ if (KIND !== "design-system") {
3381
+ return {
3382
+ url: uploaded.url,
3383
+ id: uploaded.id,
3384
+ bytes: uploaded.sizeBytes,
3385
+ contentType: type,
3386
+ next: KIND === "slides" ? type.startsWith("font/") ? 'Put url verbatim as the src of its face in project/deck.json "faces", then run check once the deck is written.' : 'Put url verbatim in <img src="\u2026">, then run check once project/deck.json is written.' : type.startsWith("font/") ? "Use url verbatim in an @font-face src: url(\u2026) in the <helmet><style> of the artboards that use it, then run check once project/canvas.json is written." : "Use url verbatim where this file is named (<img src>, url(\u2026) in a <helmet><style> rule, fetch(\u2026), <link href>, <script src>), never its filename, a path to it or a data: URI; then run check once project/canvas.json is written. (A design system's files are not uploads: they are copied under project/ds/<folder>/ and linked relatively.)"
3387
+ };
3388
+ }
3389
+ const groupName = group;
3390
+ const key = encodeIndexKey(base);
3391
+ const groupKey = encodeIndexKey(groupName);
3392
+ const record = { name: base, blob: uploaded.id, size: uploaded.sizeBytes, type };
3393
+ const shownAs = `${DESIGN_SYSTEM_PATHS.assetsDir}${groupName}/${base}`;
3394
+ return {
3395
+ url: uploaded.url,
3396
+ id: uploaded.id,
3397
+ bytes: uploaded.sizeBytes,
3398
+ contentType: type,
3399
+ record,
3400
+ indexPath: ["assetGroups", groupKey, "files", key],
3401
+ shownAs,
3402
+ next: `Write record into project/design-system.json at assetGroups.${groupKey}.files.${key} and add ${JSON.stringify(base)} to that group's order (no such group yet: add {"name": ${JSON.stringify(groupName)}, "tile": "m", "order": [], "files": {}} and put ${JSON.stringify(groupName)} in groups). The page shows it as ${shownAs}; write no file at that path (a file wins over the record). Previews and other files reference it as url, verbatim. Then run check.`
3403
+ };
3404
+ }
3405
+ function folderName(name) {
3406
+ const folder = name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[-_]+/, "").slice(0, 64).replace(/-+$/, "");
3407
+ return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(folder) ? folder : "ds";
3408
+ }
3409
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "vendor", "target"]);
3410
+ async function listSystems(dirs) {
3411
+ const extra = (process.env.CLAUDE_DESIGN_SYSTEMS ?? "").split(path15.delimiter).filter(Boolean);
3412
+ const starts = [...dirs.length > 0 ? dirs : [process.cwd()], ...extra].map((d) => path15.resolve(d));
3413
+ const found = /* @__PURE__ */ new Map();
3414
+ const visit = async (dir, depth) => {
3415
+ const project = path15.join(dir, "project");
3416
+ if (fs13.existsSync(path15.join(project, DESIGN_SYSTEM_FILE)) && !found.has(dir)) {
3417
+ const info = await readDesignSystemInfo(project).catch(() => null);
3418
+ if (info) {
3419
+ const namespace = info.namespace;
3420
+ found.set(dir, {
3421
+ title: info.title,
3422
+ namespace: namespace ?? null,
3423
+ folder: folderName(typeof namespace === "string" && namespace.trim() ? namespace : String(info.title ?? "")),
3424
+ root: dir,
3425
+ readme: fs13.existsSync(path15.join(project, "README.md")) ? path15.join(project, "README.md") : null,
3426
+ tokens: fs13.existsSync(path15.join(project, "tokens.json")) ? path15.join(project, "tokens.json") : null
3427
+ });
3428
+ return;
3429
+ }
3430
+ }
3431
+ if (depth <= 0) return;
3432
+ const entries = await fsp3.readdir(dir, { withFileTypes: true }).catch(() => []);
3433
+ for (const entry of entries) {
3434
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIP_DIRS.has(entry.name) || entry.name === "project") continue;
3435
+ await visit(path15.join(dir, entry.name), depth - 1);
3436
+ }
3437
+ };
3438
+ for (const start of starts) await visit(start, 4);
3439
+ return [...found.values()];
3440
+ }
3441
+ var runningServer2 = (root) => runningServer(root, KIND, "__deck/session");
3442
+ function serverArgs(flags) {
3443
+ const out = [];
3444
+ if (flags.has("port")) out.push("--port", flags.get("port"));
3445
+ if (flags.has("host")) out.push("--host", flags.get("host"));
3446
+ if (flags.get("agent-hook")) out.push("--agent-hook", flags.get("agent-hook"));
3447
+ if (flags.has("lan")) out.push("--lan");
3448
+ return out;
3449
+ }
3450
+ var fail = (code, message) => {
3451
+ throw new CliError(code, message);
3452
+ };
3453
+ var shareCall2 = (url, action) => shareCall(url, action, fail);
3454
+ var lanOn2 = (url, flags) => lanOn(url, flags, fail);
3455
+ function reusedNote(a, flags) {
3456
+ return flags.get("agent-hook") ? { note: `--agent-hook was not applied: the server was already running. To use it: ${script("stop", a.root)}, then open again.` } : {};
3457
+ }
3458
+ function assertServerFiles() {
3459
+ if (!fs13.existsSync(path15.join(EDITOR_DIR, "index.html"))) {
3460
+ throw new CliError("EDITOR_MISSING", `The editor page is missing (${EDITOR_DIR}); reinstall the skill.`);
3461
+ }
3462
+ if (!fs13.existsSync(SERVER_SCRIPT)) {
3463
+ throw new CliError("EDITOR_MISSING", `The editor server is missing (${SERVER_SCRIPT}); reinstall the skill.`);
3464
+ }
3465
+ }
3466
+ async function serve(a, flags) {
3467
+ if (!await readInfo(a.project)) {
3468
+ throw new CliError("NOT_A_" + KIND.toUpperCase().replace("-", "_"), `project/${INDEX_FILE} is missing or not a valid ${NOUN} index; write it, then run ${script("check", a.root)}.`);
3469
+ }
3470
+ assertServerFiles();
3471
+ const existing = await runningServer2(a.root);
3472
+ if (existing && existing.pid !== process.pid) {
3473
+ print({ url: existing.url, root: a.root, pid: existing.pid, reused: true, ...await lanOn2(existing.url, flags), ...reusedNote(a, flags) });
3474
+ return;
3475
+ }
3476
+ const host = flags.get("host") ?? "127.0.0.1";
3477
+ const port = flags.has("port") ? Number(flags.get("port")) : DEFAULT_PORTS[KIND];
3478
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError("INVALID_PORT", "--port is a number from 0 to 65535.");
3479
+ const server = await import(pathToFileURL(SERVER_SCRIPT).href);
3480
+ const state = await server.serveForeground({ root: a.root, port, host, agentHook: flags.get("agent-hook") || void 0, lan: flags.has("lan"), portGiven: flags.has("port") });
3481
+ print({ url: state.url, root: a.root, pid: state.pid, ...state.lan ? { lan: state.lan } : {} });
3482
+ }
3483
+ async function open(a, flags) {
3484
+ if (!await readInfo(a.project)) {
3485
+ throw new CliError("NOT_A_" + KIND.toUpperCase().replace("-", "_"), `project/${INDEX_FILE} is missing or not a valid ${NOUN} index; write it, then run ${script("check", a.root)}.`);
3486
+ }
3487
+ assertServerFiles();
3488
+ const existing = await runningServer2(a.root);
3489
+ if (existing) {
3490
+ print({ url: existing.url, root: a.root, pid: existing.pid, reused: true, ...await lanOn2(existing.url, flags), log: path15.join(a.root, LOG_FILE), stop: script("stop", a.root), ...reusedNote(a, flags) });
3491
+ return;
3492
+ }
3493
+ const state = await startBackground(a, flags);
3494
+ print({ url: state.url, root: a.root, pid: state.pid, ...state.lan?.length ? { lan: state.lan } : {}, log: path15.join(a.root, LOG_FILE), stop: script("stop", a.root) });
3495
+ }
3496
+ async function startBackground(a, flags) {
3497
+ const host = flags.get("host") ?? "127.0.0.1";
3498
+ const port = flags.has("port") ? Number(flags.get("port")) : DEFAULT_PORTS[KIND];
3499
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError("INVALID_PORT", "--port is a number from 0 to 65535.");
3500
+ const hook = flags.get("agent-hook") || void 0;
3501
+ const opened = await openOnHub({
3502
+ kind: KIND,
3503
+ script: SERVER_SCRIPT,
3504
+ root: a.root,
3505
+ port,
3506
+ portGiven: flags.has("port"),
3507
+ host,
3508
+ ...hook ? { agentHook: hook } : {},
3509
+ lan: flags.has("lan"),
3510
+ command: [SERVER_SCRIPT, a.root, ...serverArgs(flags)],
3511
+ running: () => runningServer2(a.root)
3512
+ });
3513
+ if ("state" in opened) {
3514
+ const view = await shareCall2(opened.state.url, null).catch(() => null);
3515
+ return { ...opened.state, ...view?.lan ? { lan: lanUrls(view) } : {} };
3516
+ }
3517
+ throw new CliError("SERVER_FAILED", `The editor server did not start. Run ${script("serve", a.root)} in the foreground to see why.${opened.tail ? `
3518
+ ${opened.tail}` : ""}`);
3519
+ }
3520
+ async function stop(a) {
3521
+ const state = readState(a.root);
3522
+ if (!state || !alive(state.pid)) {
3523
+ fs13.rmSync(path15.join(a.root, STATE_FILE), { force: true });
3524
+ print({ stopped: false, message: "No editor server is running for this folder." });
3525
+ return;
3526
+ }
3527
+ if (!await leaveHub(state)) {
3528
+ print({ stopped: false, pid: state.pid, message: `The server did not exit within 5 s; end it with: kill ${state.pid}` });
3529
+ return;
3530
+ }
3531
+ fs13.rmSync(path15.join(a.root, STATE_FILE), { force: true });
3532
+ print({ stopped: true, pid: state.pid });
3533
+ }
3534
+ async function share(a, flags) {
3535
+ if (!await readInfo(a.project)) {
3536
+ throw new CliError("NOT_A_" + KIND.toUpperCase().replace("-", "_"), `project/${INDEX_FILE} is missing or not a valid ${NOUN} index; write it, then run ${script("check", a.root)}.`);
3537
+ }
3538
+ print(
3539
+ await shareCommand({
3540
+ root: a.root,
3541
+ flags,
3542
+ running: () => runningServer2(a.root),
3543
+ startShared: async () => {
3544
+ assertServerFiles();
3545
+ return startBackground(a, new Map([...flags, ["lan", "true"]]));
3546
+ },
3547
+ offCommand: script("share", a.root, "--off"),
3548
+ serveCommand: script("serve", a.root, "--lan"),
3549
+ fail
3550
+ })
3551
+ );
3552
+ }
3553
+ var WAIT_CHUNK_S = 300;
3554
+ function commentHints(a) {
3555
+ return {
3556
+ reply: script("comment-reply", a.root, "<id>", "<text>"),
3557
+ resolve: script("comment-resolve", a.root, "<id>")
3558
+ };
3559
+ }
3560
+ async function listComments(a, all) {
3561
+ const doc = await readComments(a.root);
3562
+ const threads = all ? [...doc.threads].sort((x, y) => x.createdAt.localeCompare(y.createdAt)) : openThreads(doc);
3563
+ const resolved = doc.threads.filter((t) => t.status === "resolved").length;
3564
+ return {
3565
+ root: a.root,
3566
+ file: commentsPath(a.root),
3567
+ threads: agentViews(doc, threads),
3568
+ ...all || !resolved ? {} : { resolved: `${resolved} resolved, not shown (--all shows them)` },
3569
+ ...threads.length ? commentHints(a) : {}
3570
+ };
3571
+ }
3572
+ async function artifactTitle(a) {
3573
+ const info = await readInfo(a.project).catch(() => null);
3574
+ const title = typeof info?.title === "string" ? info.title.trim() : "";
3575
+ return title && title !== "project" ? title : path15.basename(a.root);
3576
+ }
3577
+ async function waitComments(a, flags) {
3578
+ const timeout = flags.has("timeout") ? Number(flags.get("timeout")) : Infinity;
3579
+ if (!(timeout > 0)) throw new CliError("INVALID_TIMEOUT", "--timeout is a number of seconds above 0.");
3580
+ const deadline = Date.now() + timeout * 1e3;
3581
+ let failures = 0;
3582
+ for (; ; ) {
3583
+ const state = await runningServer2(a.root);
3584
+ if (!state) {
3585
+ throw new CliError("NO_SERVER", `No editor server is running for this folder: start it with ${script("open", a.root)}, then wait again.`);
3586
+ }
3587
+ const left = Math.min(WAIT_CHUNK_S, (deadline - Date.now()) / 1e3);
3588
+ if (left <= 0) return { root: a.root, threads: [], timedOut: true, next: script("comments", a.root, "--wait") };
3589
+ let body;
3590
+ try {
3591
+ const response = await fetch(new URL(`__comments/agent/wait?timeout=${Math.max(1, Math.round(left))}`, state.url), {
3592
+ // A whole number of ms: AbortSignal.timeout refuses a fraction (and --timeout leaves one in `left`).
3593
+ signal: AbortSignal.timeout(Math.ceil((left + 30) * 1e3))
3594
+ });
3595
+ if (response.status === 404) {
3596
+ throw new CliError(
3597
+ "SERVER_OUTDATED",
3598
+ `The running editor server has no comments (an older version started it). Restart it: ${script("stop", a.root)}, then ${script("open", a.root)}.`
3599
+ );
3600
+ }
3601
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
3602
+ body = await response.json();
3603
+ failures = 0;
3604
+ } catch (error) {
3605
+ if (error instanceof CliError) throw error;
3606
+ if (++failures >= 3) throw new CliError("SERVER_GONE", `Lost the editor server: ${error.message}`);
3607
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
3608
+ continue;
3609
+ }
3610
+ if (body.closed) continue;
3611
+ const threads = body.threads ?? [];
3612
+ if (threads.length) {
3613
+ return {
3614
+ root: a.root,
3615
+ url: state.url,
3616
+ title: await artifactTitle(a),
3617
+ file: commentsPath(a.root),
3618
+ threads,
3619
+ ...commentHints(a),
3620
+ next: script("comments", a.root, "--wait")
3621
+ };
3622
+ }
3623
+ }
3624
+ }
3625
+ async function readStdin() {
3626
+ if (process.stdin.isTTY) return "";
3627
+ const chunks = [];
3628
+ for await (const chunk of process.stdin) chunks.push(chunk);
3629
+ return Buffer.concat(chunks).toString("utf8");
3630
+ }
3631
+ async function replyComment(a, id, words, resolve) {
3632
+ if (!id) throw new CliError("MISSING_ID", `Give the comment id: ${script("comment-reply", a.root, "<id>", "<text>")}`);
3633
+ const given = words.join(" ");
3634
+ const text = (given === "" || given === "-" ? await readStdin() : given).replace(/\r\n?/g, "\n").trim();
3635
+ if (!text) throw new CliError("EMPTY_REPLY", "The reply is empty: pass it as an argument, or as - with the text on stdin.");
3636
+ if (text.length > LIMITS.text) throw new CliError("REPLY_TOO_LONG", `A reply is at most ${LIMITS.text} characters.`);
3637
+ const thread = await updateComments(a.root, (doc) => {
3638
+ const found = findThread(doc, id);
3639
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3640
+ addMessage(found, AGENT_AUTHOR, text, now);
3641
+ if (resolve) setStatus(found, "resolved", now);
3642
+ return found;
3643
+ });
3644
+ return { replied: thread.id, status: thread.status, file: commentsPath(a.root) };
3645
+ }
3646
+ async function resolveComment(a, id, reopen) {
3647
+ if (!id) throw new CliError("MISSING_ID", `Give the comment id: ${script("comment-resolve", a.root, "<id>")}`);
3648
+ const thread = await updateComments(a.root, (doc) => {
3649
+ const found = findThread(doc, id);
3650
+ setStatus(found, reopen ? "open" : "resolved", (/* @__PURE__ */ new Date()).toISOString());
3651
+ return found;
3652
+ });
3653
+ return { id: thread.id, status: thread.status, file: commentsPath(a.root) };
3654
+ }
3655
+ var USAGE = `${"claude-slides"} \u2014 local Artifact tool for the ${NOUN} type
3656
+
3657
+ Usage:
3658
+ node scripts/artifact.mjs open <root> [--port n] [--host h] start the editor in the background; prints {"url"}
3659
+ node scripts/artifact.mjs serve <root> [--port n] [--host h] run the editor server in the foreground
3660
+ [--agent-hook "<command>"] open/serve: run this for each comment sent to the agent
3661
+ (the comment as JSON on stdin)
3662
+ [--lan] open/serve: also share on the local network, as share does
3663
+ node scripts/artifact.mjs stop <root> stop the background editor server
3664
+ node scripts/artifact.mjs share <root> share on the local network; prints a link per role
3665
+ [--reset R] [--enable R] [--disable R] R: editor, commenter, viewer (comma list) or all
3666
+ [--role G=R,...] give guest G (an id it prints) role R
3667
+ (these change links only: shared or not stays as it was)
3668
+ [--off] stop sharing (guests keep their place for next time)
3669
+ node scripts/artifact.mjs check <root> validate project/; exit 1 while problems remain
3670
+ node scripts/artifact.mjs upload <root> <file>${KIND === "design-system" ? " --group G " : " "} store an upload; prints its /_blob/<id> url
3671
+ node scripts/artifact.mjs list [dir \u2026] find design systems (folders holding project/design-system.json)
3672
+ ${KIND === "design-system" ? "" : ` node scripts/artifact.mjs ds-sync <root> [namespace] [--check] an installed design system is a copy: copy its changed files again
3673
+ from the system's folder and stamp copiedAt (--check: list only;
3674
+ --from <folder>: the source, when the record's path is not found)
3675
+ `} node scripts/artifact.mjs comments <root> [--all] the open comments people left in the editor (--all: resolved too)
3676
+ node scripts/artifact.mjs comments <root> --wait [--timeout s] wait for a comment sent to the agent from the open editor
3677
+ node scripts/artifact.mjs comment-reply <root> <id> <text|-> reply as the agent (-: text on stdin) [--resolve]
3678
+ node scripts/artifact.mjs comment-resolve <root> <id> [--reopen] mark a comment resolved (or open again)
3679
+ node scripts/artifact.mjs archive <root> [--out file.zip|dir] the whole folder as one zip (backup, another computer,
3680
+ someone else); beside the folder unless --out says
3681
+
3682
+ <root> is the artifact folder: its files live at <root>/project/<path> (project/${INDEX_FILE}, \u2026).`;
3683
+ async function main() {
3684
+ const [command, ...rest] = process.argv.slice(2);
3685
+ const { positional, flags } = parseArgs(rest);
3686
+ switch (command) {
3687
+ case "open":
3688
+ await open(resolveArtifact(positional[0]), flags);
3689
+ return 0;
3690
+ case "serve":
3691
+ await serve(resolveArtifact(positional[0]), flags);
3692
+ return -1;
3693
+ case "stop":
3694
+ await stop(resolveArtifact(positional[0], false));
3695
+ return 0;
3696
+ case "share":
3697
+ await share(resolveArtifact(positional[0]), flags);
3698
+ return 0;
3699
+ case "check": {
3700
+ const { result, problems } = await check(resolveArtifact(positional[0]));
3701
+ print(localize(result));
3702
+ return problems > 0 ? 1 : 0;
3703
+ }
3704
+ case "upload": {
3705
+ const a = resolveArtifact(positional[0], false);
3706
+ if (!fs13.statSync(a.root, { throwIfNoEntry: false })?.isDirectory()) {
3707
+ throw new CliError("NOT_FOUND", `${a.root} does not exist. Make the artifact folder first.`);
3708
+ }
3709
+ fs13.mkdirSync(a.project, { recursive: true });
3710
+ print(await upload(a, positional[1], flags.get("group")));
3711
+ return 0;
3712
+ }
3713
+ case "list":
3714
+ print(await listSystems(positional));
3715
+ return 0;
3716
+ case "ds-sync": {
3717
+ if (KIND === "design-system") throw new CliError("NOT_APPLICABLE", "A design system has no installed design systems: ds-sync is for decks and canvases.");
3718
+ const a = resolveArtifact(positional[0]);
3719
+ const check2 = flags.has("check");
3720
+ let results;
3721
+ try {
3722
+ results = syncSystems(a.project, a.root, INDEX_FILE, { namespace: positional[1], from: flags.get("from"), check: check2 });
3723
+ } catch (error) {
3724
+ throw new CliError("NO_SUCH_SYSTEM", error.message);
3725
+ }
3726
+ const behind = results.filter((r) => r.changed.length > 0 || r.removed.length > 0);
3727
+ print({
3728
+ root: a.root,
3729
+ systems: results.map((r) => ({
3730
+ namespace: r.namespace,
3731
+ title: r.title,
3732
+ ...r.skipped ? { skipped: r.skipped } : {},
3733
+ ...r.missing ? { skipped: `project/ds/${r.namespace}/ does not exist: install it first (SKILL.md, Creating, step 4)` } : {},
3734
+ ...r.source ? { source: r.source } : {},
3735
+ changed: r.changed,
3736
+ ...r.removed.length > 0 ? { goneFromSource: r.removed } : {},
3737
+ ...check2 ? {} : { copied: r.copied, ...r.copiedAt ? { copiedAt: r.copiedAt } : {} }
3738
+ })),
3739
+ next: check2 ? behind.length > 0 ? `Behind its source. Run ${script("ds-sync", a.root)} to copy the changed files again.` : "Every copy matches its source (or its source was not found: see skipped)." : results.some((r) => r.copied.length > 0) ? "Copied. The open editor shows the new files at once (a file over 2 MB, or a types file, after a reload). Files the source dropped stay in the copy: remove one, and change the artboards that load it, if the source no longer has it. Files the source gained are not copied: compare its README with project/ds/<folder>/." : "Nothing to copy."
3740
+ });
3741
+ return check2 && behind.some((r) => r.changed.length > 0) ? 1 : 0;
3742
+ }
3743
+ case "comments": {
3744
+ const a = resolveArtifact(positional[0]);
3745
+ print(flags.has("wait") ? await waitComments(a, flags) : await listComments(a, flags.has("all")));
3746
+ return 0;
3747
+ }
3748
+ case "comment-reply":
3749
+ print(await replyComment(resolveArtifact(positional[0]), positional[1], positional.slice(2), flags.has("resolve")));
3750
+ return 0;
3751
+ case "comment-resolve":
3752
+ print(await resolveComment(resolveArtifact(positional[0]), positional[1], flags.has("reopen")));
3753
+ return 0;
3754
+ case "archive": {
3755
+ const a = resolveArtifact(positional[0]);
3756
+ const made = await archiveCommand(a.root, flags.get("out"));
3757
+ print({ ...made, open: `unzip it anywhere, then ${script("open", `<there>/${made.folder}`)}` });
3758
+ return 0;
3759
+ }
3760
+ case void 0:
3761
+ case "help":
3762
+ case "--help":
3763
+ case "-h":
3764
+ process.stdout.write(`${USAGE}
3765
+ `);
3766
+ return command === void 0 ? 2 : 0;
3767
+ default:
3768
+ process.stderr.write(`Unknown command: ${command}
3769
+
3770
+ ${USAGE}
3771
+ `);
3772
+ return 2;
3773
+ }
3774
+ }
3775
+ main().then(
3776
+ (code) => {
3777
+ if (code >= 0) process.exitCode = code;
3778
+ },
3779
+ (error) => {
3780
+ const e = error;
3781
+ process.stderr.write(`${JSON.stringify({ error: e.code ?? "ERROR", message: e.message })}
3782
+ `);
3783
+ process.exitCode = 2;
3784
+ }
3785
+ );