editlet 0.0.0-stage → 0.1.0-alpha.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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -2
  3. package/dist/admin/config.d.ts +22 -0
  4. package/dist/admin/config.js +75 -0
  5. package/dist/admin/dist/assets/RichEditor-BlaCRrEX.css +1 -0
  6. package/dist/admin/dist/assets/RichEditor-IZKdt6MK.js +42 -0
  7. package/dist/admin/dist/assets/blank-line-CbGzlqBI.js +1 -0
  8. package/dist/admin/dist/assets/channel-CljeMIwA.js +1 -0
  9. package/dist/admin/dist/assets/db-CCMyPgQa.js +1 -0
  10. package/dist/admin/dist/assets/index-CWoJh4H8.js +257 -0
  11. package/dist/admin/dist/assets/index-DkRMnD_M.css +1 -0
  12. package/dist/admin/dist/assets/mdast-util-from-markdown-C79q1_d8.js +3 -0
  13. package/dist/admin/dist/assets/mdast-util-gfm-cM-_xFJE.js +19 -0
  14. package/dist/admin/dist/assets/micromark-extension-gfm-Wz6-oszS.js +1 -0
  15. package/dist/admin/dist/assets/micromark-util-classify-character-BgXaGAja.js +1 -0
  16. package/dist/admin/dist/assets/micromark-util-html-tag-name-B61T18yC.js +1 -0
  17. package/dist/admin/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  18. package/dist/admin/dist/index.html +16 -0
  19. package/dist/admin/dist/preview.js +1 -0
  20. package/dist/admin/dist/window.js +1 -0
  21. package/dist/astro/content.d.ts +21 -0
  22. package/dist/astro/content.js +235 -0
  23. package/dist/astro/devServer.js +89 -0
  24. package/dist/astro/index.d.ts +15 -0
  25. package/dist/astro/index.js +98 -0
  26. package/dist/astro/nodeBridge.js +36 -0
  27. package/dist/astro/shared.js +10 -0
  28. package/dist/astro/stub/index.html +71 -0
  29. package/dist/auth/client.d.ts +24 -0
  30. package/dist/auth/client.js +120 -0
  31. package/dist/auth/handler.d.ts +16 -0
  32. package/dist/auth/handler.js +281 -0
  33. package/dist/auth/protocol.d.ts +25 -0
  34. package/dist/auth/protocol.js +3 -0
  35. package/dist/core/assets.d.ts +73 -0
  36. package/dist/core/assets.js +405 -0
  37. package/dist/core/devApi.d.ts +28 -0
  38. package/dist/core/devApi.js +3 -0
  39. package/dist/core/entryFile.d.ts +13 -0
  40. package/dist/core/entryFile.js +81 -0
  41. package/dist/core/fields.js +147 -0
  42. package/dist/core/generate.d.ts +3 -0
  43. package/dist/core/generate.js +70 -0
  44. package/dist/core/gitStyle.d.ts +92 -0
  45. package/dist/core/gitStyle.js +206 -0
  46. package/dist/core/index.d.ts +16 -0
  47. package/dist/core/index.js +16 -0
  48. package/dist/core/issues.d.ts +10 -0
  49. package/dist/core/issues.js +10 -0
  50. package/dist/core/paths.d.ts +31 -0
  51. package/dist/core/paths.js +114 -0
  52. package/dist/core/project.js +56 -0
  53. package/dist/core/references.d.ts +68 -0
  54. package/dist/core/references.js +103 -0
  55. package/dist/core/rename.d.ts +60 -0
  56. package/dist/core/rename.js +133 -0
  57. package/dist/core/schema.d.ts +117 -0
  58. package/dist/core/schema.js +299 -0
  59. package/dist/core/sha.d.ts +2 -0
  60. package/dist/core/sha.js +13 -0
  61. package/dist/core/source.d.ts +48 -0
  62. package/dist/core/source.js +57 -0
  63. package/dist/core/validate.d.ts +22 -0
  64. package/dist/core/validate.js +148 -0
  65. package/dist/core/walk.d.ts +23 -0
  66. package/dist/core/walk.js +94 -0
  67. package/dist/core/writes.d.ts +37 -0
  68. package/dist/core/writes.js +166 -0
  69. package/dist/github/base64.js +16 -0
  70. package/dist/github/cache.d.ts +34 -0
  71. package/dist/github/cache.js +126 -0
  72. package/dist/github/client.d.ts +38 -0
  73. package/dist/github/client.js +228 -0
  74. package/dist/github/codeowners.d.ts +23 -0
  75. package/dist/github/codeowners.js +96 -0
  76. package/dist/github/commitReader.d.ts +25 -0
  77. package/dist/github/commitReader.js +38 -0
  78. package/dist/github/deploy.d.ts +15 -0
  79. package/dist/github/deploy.js +33 -0
  80. package/dist/github/index.d.ts +9 -0
  81. package/dist/github/index.js +8 -0
  82. package/dist/github/repo.d.ts +95 -0
  83. package/dist/github/repo.js +375 -0
  84. package/dist/github/source.d.ts +115 -0
  85. package/dist/github/source.js +558 -0
  86. package/dist/loader/index.d.ts +27 -0
  87. package/dist/loader/index.js +151 -0
  88. package/dist/loader/protocol.d.ts +95 -0
  89. package/dist/loader/protocol.js +120 -0
  90. package/dist/loader/window/geometry.js +9 -0
  91. package/dist/next/EditletLoader.d.ts +5 -0
  92. package/dist/next/EditletLoader.js +33 -0
  93. package/dist/next/assetUrl.d.ts +9 -0
  94. package/dist/next/assetUrl.js +13 -0
  95. package/dist/next/buildGuard.js +26 -0
  96. package/dist/next/config.d.ts +18 -0
  97. package/dist/next/config.js +255 -0
  98. package/dist/next/devServer.js +70 -0
  99. package/dist/next/editletField.d.ts +7 -0
  100. package/dist/next/editletField.js +7 -0
  101. package/dist/next/index.d.ts +8 -0
  102. package/dist/next/index.js +6 -0
  103. package/dist/next/preview.d.ts +18 -0
  104. package/dist/next/preview.js +100 -0
  105. package/dist/next/previewCookie.d.ts +5 -0
  106. package/dist/next/previewCookie.js +72 -0
  107. package/dist/next/previewEnv.js +25 -0
  108. package/dist/next/previewRef.d.ts +8 -0
  109. package/dist/next/previewRef.js +17 -0
  110. package/dist/next/publicDir.js +65 -0
  111. package/dist/next/reader.d.ts +49 -0
  112. package/dist/next/reader.js +161 -0
  113. package/dist/next/stub/index.html +56 -0
  114. package/dist/node/devHandler.d.ts +6 -0
  115. package/dist/node/devHandler.js +430 -0
  116. package/dist/node/fs.js +37 -0
  117. package/dist/node/index.d.ts +3 -0
  118. package/dist/node/index.js +3 -0
  119. package/dist/node/project.d.ts +12 -0
  120. package/dist/node/project.js +43 -0
  121. package/package.json +187 -4
  122. package/skills/README.md +84 -0
  123. package/skills/editlet/SKILL.md +119 -0
  124. package/skills/editlet/references/content-format.md +191 -0
  125. package/skills/editlet/references/preview.md +75 -0
  126. package/skills/editlet/references/publishing.md +137 -0
  127. package/skills/editlet/references/schema-changes.md +127 -0
  128. package/skills/editlet/scripts/guard.mjs +1061 -0
  129. package/skills/editlet/scripts/link.mjs +193 -0
  130. package/skills/editlet/scripts/refs.mjs +1480 -0
  131. package/skills/editlet/scripts/schema.mjs +1340 -0
  132. package/skills/editlet/scripts/style.mjs +657 -0
  133. package/skills/editlet/scripts/types.mjs +525 -0
  134. package/skills/editlet/scripts/validate.mjs +724 -0
  135. package/skills/editlet-migrate/SKILL.md +92 -0
  136. package/skills/editlet-migrate/references/mapping.md +73 -0
  137. package/skills/editlet-migrate/references/sources.md +70 -0
  138. package/skills/editlet-setup/SKILL.md +108 -0
  139. package/skills/editlet-setup/references/astro.md +83 -0
  140. package/skills/editlet-setup/references/doctor.md +89 -0
  141. package/skills/editlet-setup/references/next.md +140 -0
  142. package/skills/editlet-setup/references/preview.md +54 -0
  143. package/skills/editlet-setup/references/production.md +153 -0
  144. package/skills/editlet-setup/references/roles.md +238 -0
  145. package/skills/editlet-setup/references/skills.md +99 -0
  146. package/skills/editlet-setup/scripts/doctor.mjs +1378 -0
@@ -0,0 +1,1480 @@
1
+ // skills/editlet/scripts/refs.ts
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, join as join3, resolve as resolve2 } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+
6
+ // skills/editlet/scripts/issues.ts
7
+ function format(issue) {
8
+ if (!issue.file) return `${issue.path || "(schema)"} \u2014 ${issue.message}`;
9
+ return issue.path ? `${issue.file}: ${issue.path} \u2014 ${issue.message}` : `${issue.file} \u2014 ${issue.message}`;
10
+ }
11
+ function reportIssues(issues) {
12
+ for (const issue of issues) process.stderr.write(`${format(issue)}
13
+ `);
14
+ process.exitCode = 1;
15
+ }
16
+
17
+ // skills/editlet/scripts/refsOps.ts
18
+ import { isDeepStrictEqual } from "node:util";
19
+
20
+ // skills/editlet/scripts/schemaOps.ts
21
+ import { readFile as readFile2 } from "node:fs/promises";
22
+ import { join as join2 } from "node:path";
23
+
24
+ // core/entryFile.ts
25
+ import { parse, Schema as YamlSchema, stringify } from "yaml";
26
+
27
+ // core/issues.ts
28
+ var EditletError = class extends Error {
29
+ issues;
30
+ constructor(issues, message) {
31
+ super(message ?? issues.map((i) => i.path ? `${i.path}: ${i.message}` : i.message).join("; "));
32
+ this.name = "EditletError";
33
+ this.issues = issues;
34
+ }
35
+ };
36
+
37
+ // core/entryFile.ts
38
+ var YAML_11_SCALARS = new YamlSchema({ schema: "yaml-1.1" }).tags.filter((tag) => !tag.collection);
39
+ function fail(message) {
40
+ throw new EditletError([{ path: "", message }]);
41
+ }
42
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
43
+ function decodeUtf8(content, file) {
44
+ if (typeof content === "string") return { text: content };
45
+ try {
46
+ return { text: utf8.decode(content) };
47
+ } catch {
48
+ return { issue: { file, path: "", message: "File is not valid UTF-8" } };
49
+ }
50
+ }
51
+ function parseEntryFile(source) {
52
+ let text = source.startsWith("\uFEFF") ? source.slice(1) : source;
53
+ text = text.replace(/\r\n/g, "\n");
54
+ if (!text.startsWith("---\n")) return { data: {}, body: text };
55
+ const rest = text.slice(4);
56
+ const lines = rest.split("\n");
57
+ const close = lines.indexOf("---");
58
+ if (close === -1) fail('Frontmatter is not closed with a "---" line');
59
+ const yamlSrc = lines.slice(0, close).join("\n");
60
+ let body = lines.slice(close + 1).join("\n");
61
+ if (body.startsWith("\n")) body = body.slice(1);
62
+ let data;
63
+ try {
64
+ data = parse(yamlSrc, { schema: "core", logLevel: "error" });
65
+ } catch (error) {
66
+ fail(`Invalid YAML frontmatter: ${error instanceof Error ? error.message : String(error)}`);
67
+ }
68
+ if (data === null || data === void 0) data = {};
69
+ if (typeof data !== "object" || Array.isArray(data)) fail("Frontmatter must be a YAML mapping");
70
+ return { data, body };
71
+ }
72
+ function serializeEntryFile(file, fieldOrder = []) {
73
+ const keys = Object.keys(file.data).filter((k) => file.data[k] !== void 0);
74
+ const rank = (k) => {
75
+ const i = fieldOrder.indexOf(k);
76
+ return i === -1 ? Infinity : i;
77
+ };
78
+ keys.sort((a, b) => {
79
+ const d = rank(a) - rank(b);
80
+ if (d !== 0 && !(rank(a) === Infinity && rank(b) === Infinity)) return d;
81
+ return a < b ? -1 : a > b ? 1 : 0;
82
+ });
83
+ const ordered = {};
84
+ for (const k of keys) ordered[k] = file.data[k];
85
+ const yaml = keys.length === 0 ? "" : stringify(ordered, {
86
+ version: "1.1",
87
+ schema: "core",
88
+ customTags: (tags) => [...tags, ...YAML_11_SCALARS],
89
+ lineWidth: 0,
90
+ logLevel: "error"
91
+ });
92
+ const head = `---
93
+ ${yaml}---
94
+ `;
95
+ return file.body === "" ? head : `${head}
96
+ ${file.body}`;
97
+ }
98
+
99
+ // core/paths.ts
100
+ var SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
101
+ function isValidSlug(slug) {
102
+ return SLUG_RE.test(slug);
103
+ }
104
+ function hasCollection(schema, collection) {
105
+ return Object.hasOwn(schema.collections, collection);
106
+ }
107
+ function entryFilePath(schema, collection, slug) {
108
+ const singleton = hasCollection(schema, collection) && schema.collections[collection].singleton;
109
+ return `${schema.contentDir}/${collection}/${singleton ? "index" : slug}.md`;
110
+ }
111
+ function isCanonicalPath(path) {
112
+ if (path === "" || /[\\\0:]/.test(path)) return false;
113
+ return path.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
114
+ }
115
+ function isHiddenContentPath(schema, path) {
116
+ const prefix = `${schema.contentDir}/`;
117
+ const rest = path.startsWith(prefix) ? path.slice(prefix.length) : path;
118
+ return rest.split("/").some((seg) => seg.startsWith("."));
119
+ }
120
+ function parseEntryPath(schema, path) {
121
+ const prefix = `${schema.contentDir}/`;
122
+ if (!path.startsWith(prefix) || !isCanonicalPath(path)) return null;
123
+ const parts = path.slice(prefix.length).split("/");
124
+ if (parts.length !== 2) return null;
125
+ const [collection, file] = parts;
126
+ if (!hasCollection(schema, collection) || !file.endsWith(".md")) return null;
127
+ const name = file.slice(0, -3);
128
+ if (name === "") return null;
129
+ if (schema.collections[collection].singleton) return file === "index.md" ? { collection, slug: "index" } : null;
130
+ return { collection, slug: name };
131
+ }
132
+ function resolveAssetPath(schema, entryFile, src) {
133
+ if (src === "" || src.startsWith("/") || src.includes("\\") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(src)) return null;
134
+ const srcSegs = src.split("/");
135
+ const last = srcSegs[srcSegs.length - 1];
136
+ if (last === "" || last === "." || last === "..") return null;
137
+ const out = entryFile.split("/").slice(0, -1);
138
+ for (const seg of srcSegs) {
139
+ if (seg === "" || seg === ".") continue;
140
+ if (seg === "..") {
141
+ if (out.length === 0) return null;
142
+ out.pop();
143
+ } else out.push(seg);
144
+ }
145
+ const result = out.join("/");
146
+ return result.startsWith(`${schema.contentDir}/`) ? result : null;
147
+ }
148
+ function relativeAssetSrc(entryFile, assetPath) {
149
+ const from = entryFile.split("/").slice(0, -1);
150
+ const to = assetPath.split("/");
151
+ let common = 0;
152
+ while (common < from.length && common < to.length - 1 && from[common] === to[common]) common++;
153
+ return "../".repeat(from.length - common) + to.slice(common).join("/");
154
+ }
155
+ function refKey(collection, slug) {
156
+ return `${collection}/${slug}`;
157
+ }
158
+ function parseRefKey(ref) {
159
+ const parts = ref.split("/");
160
+ if (parts.length !== 2) return null;
161
+ const [collection, slug] = parts;
162
+ if (collection === "" || !isValidSlug(slug)) return null;
163
+ return { collection, slug };
164
+ }
165
+ var IMAGE_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "avif", "gif", "svg"];
166
+ function isImagePath(path) {
167
+ const name = path.slice(path.lastIndexOf("/") + 1);
168
+ const dot = name.lastIndexOf(".");
169
+ return dot > 0 && IMAGE_EXTENSIONS.includes(name.slice(dot + 1).toLowerCase());
170
+ }
171
+
172
+ // core/schema.ts
173
+ import { z as z2 } from "zod";
174
+
175
+ // core/fields.ts
176
+ import { z } from "zod";
177
+ function isStringValued(field) {
178
+ switch (field.type) {
179
+ case "string":
180
+ return !field.list;
181
+ case "select":
182
+ case "reference":
183
+ return !field.multiple;
184
+ case "text":
185
+ case "datetime":
186
+ case "url":
187
+ case "color":
188
+ return true;
189
+ default:
190
+ return false;
191
+ }
192
+ }
193
+ function isAbsentValue(field, value) {
194
+ return value === void 0 || value === null || value === "" && isStringValued(field);
195
+ }
196
+ function err(field, message) {
197
+ return (iss) => field.required && isAbsentValue(field, iss.input) ? "Required" : message;
198
+ }
199
+ function optional(field, schema, message) {
200
+ if (field.required) return schema;
201
+ return isStringValued(field) ? z.union([schema, z.literal("")], { error: message }).nullish() : schema.nullish();
202
+ }
203
+ function isUrl(v) {
204
+ return v.startsWith("/") || URL.canParse(v);
205
+ }
206
+ function noRepeats(message) {
207
+ return (items, ctx) => {
208
+ const seen = /* @__PURE__ */ new Set();
209
+ items.forEach((item, i) => {
210
+ if (seen.has(item)) ctx.addIssue({ code: "custom", path: [i], message: message(item) });
211
+ seen.add(item);
212
+ });
213
+ };
214
+ }
215
+ function listField(field, item, min, max, unique) {
216
+ const effective = Math.max(field.required ? 1 : 0, min);
217
+ let arr = z.array(item, { error: err(field, "Expected a list") });
218
+ if (effective > 0) {
219
+ arr = arr.min(effective, {
220
+ error: (iss) => Array.isArray(iss.input) && iss.input.length === 0 && field.required ? "Required" : `Must have at least ${effective}`
221
+ });
222
+ }
223
+ if (max !== void 0) arr = arr.max(max, { error: `Must have at most ${max}` });
224
+ return optional(field, unique ? arr.superRefine(noRepeats(unique)) : arr, "Expected a list");
225
+ }
226
+ var escapeRegex = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
227
+ function fieldsShape(fields) {
228
+ const shape = {};
229
+ for (const [key, field] of Object.entries(fields)) shape[key] = nestedValueSchema(field);
230
+ return shape;
231
+ }
232
+ function nestedValueSchema(field) {
233
+ if (field.type !== "markdown") return fieldValueSchema(field);
234
+ const base2 = z.string({ error: err(field, "Expected text") });
235
+ return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
236
+ }
237
+ function fieldValueSchema(field) {
238
+ switch (field.type) {
239
+ case "markdown":
240
+ return null;
241
+ case "object": {
242
+ const obj = z.strictObject(fieldsShape(field.fields), { error: err(field, "Expected an object") });
243
+ if (field.list) return listField(field, obj, field.min ?? 0, field.max);
244
+ return optional(field, obj, "");
245
+ }
246
+ case "blocks": {
247
+ const kinds = Object.keys(field.blocks);
248
+ const message = `Expected ${BLOCK_KEY}: ${kinds.join(", ")}`;
249
+ const options = Object.entries(field.blocks).map(
250
+ ([kind, block]) => z.strictObject({ [BLOCK_KEY]: z.literal(kind), ...fieldsShape(block.fields) })
251
+ );
252
+ const item = z.discriminatedUnion(BLOCK_KEY, options, {
253
+ error: message
254
+ });
255
+ return listField(field, item, field.min ?? 0, field.max);
256
+ }
257
+ case "string":
258
+ case "text": {
259
+ if (field.type === "string" && field.list) return listField(field, z.string({ error: "Expected text" }), 0);
260
+ const base2 = z.string({ error: err(field, "Expected text") });
261
+ return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
262
+ }
263
+ case "boolean":
264
+ return optional(field, z.boolean({ error: err(field, "Expected true or false") }), "");
265
+ case "select": {
266
+ const values = field.options.map((o) => o.value);
267
+ const message = `Expected one of: ${values.join(", ")}`;
268
+ if (field.multiple) return listField(field, z.enum(values, { error: message }), 0);
269
+ return optional(field, z.enum(values, { error: err(field, message) }), message);
270
+ }
271
+ case "number": {
272
+ let n = z.number({ error: err(field, "Expected a number") });
273
+ if (field.integer) n = n.int("Must be a whole number");
274
+ if (field.min !== void 0) n = n.min(field.min, `Must be at least ${field.min}`);
275
+ if (field.max !== void 0) n = n.max(field.max, `Must be at most ${field.max}`);
276
+ return optional(field, n, "");
277
+ }
278
+ case "datetime": {
279
+ const base2 = field.dateOnly ? z.iso.date({ error: err(field, "Invalid date") }) : z.iso.datetime({ offset: true, local: true, error: err(field, "Invalid date") });
280
+ return optional(field, base2, "Invalid date");
281
+ }
282
+ case "json": {
283
+ if (!field.required) return z.unknown().optional();
284
+ return z.union([z.string(), z.number(), z.boolean(), z.array(z.unknown()), z.record(z.string(), z.unknown())], {
285
+ error: "Required"
286
+ });
287
+ }
288
+ case "url": {
289
+ const message = "Must be an http(s) URL or start with /";
290
+ const base2 = z.string({ error: err(field, "Expected text") }).regex(/^(?:https?:\/\/|\/(?!\/))/i, { error: err(field, message) }).refine(isUrl, { error: message });
291
+ return optional(field, base2, message);
292
+ }
293
+ case "color": {
294
+ const message = "Must be a hex color like #a1b2c3";
295
+ const base2 = z.string({ error: err(field, "Expected text") }).regex(/^#[0-9a-fA-F]{6}$/, { error: err(field, message) });
296
+ return optional(field, base2, message);
297
+ }
298
+ case "image": {
299
+ const nonEmpty = z.string({ error: (iss) => iss.input === void 0 || iss.input === null ? "Required" : "Expected text" }).regex(/\S/, "Required");
300
+ const obj = z.strictObject({ src: nonEmpty, alt: nonEmpty }, { error: err(field, "Expected { src, alt }") });
301
+ return optional(field, obj, "");
302
+ }
303
+ case "reference": {
304
+ const message = `Must reference an entry in: ${field.collections.join(", ")}`;
305
+ const slug = SLUG_RE.source.slice(1, -1);
306
+ const ref = z.string({ error: err(field, 'Expected a reference like "collection/slug"') }).regex(new RegExp(`^(?:${field.collections.map(escapeRegex).join("|")})/${slug}$`), {
307
+ error: err(field, message)
308
+ });
309
+ if (field.multiple) return listField(field, ref, field.min ?? 0, field.max, (r) => `Duplicate reference: ${r}`);
310
+ return optional(field, ref, message);
311
+ }
312
+ }
313
+ }
314
+
315
+ // core/schema.ts
316
+ var BLOCK_KEY = "block";
317
+ var COMMIT_PLACEHOLDERS = ["action", "Action", "collection", "slug", "target"];
318
+ var TITLE_PLACEHOLDERS = ["branch", "name", "login"];
319
+ var REF_SEGMENTS = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
320
+ function isRefPath(value) {
321
+ return REF_SEGMENTS.test(value) && !value.includes("..") && !value.split("/").some((s) => s.endsWith(".lock"));
322
+ }
323
+ function template(placeholders, max) {
324
+ return z2.string().trim().min(1).max(max).refine((t) => !/[\r\n]/.test(t), "must be one line").superRefine((t, ctx) => {
325
+ for (const [, name] of t.matchAll(/\{([^{}]*)\}/g)) {
326
+ if (!placeholders.includes(name)) {
327
+ ctx.addIssue({
328
+ code: "custom",
329
+ message: `unknown placeholder "{${name}}" (use ${placeholders.map((p) => `{${p}}`).join(", ")})`
330
+ });
331
+ }
332
+ }
333
+ });
334
+ }
335
+ var gitSchema = z2.strictObject({
336
+ baseBranch: z2.string().min(1),
337
+ branchPrefix: z2.string().refine(
338
+ (p) => p.endsWith("/") && isRefPath(p.slice(0, -1)),
339
+ 'must be branch name segments ending in "/", for example "editlet/"'
340
+ ).optional(),
341
+ commitMessage: template(COMMIT_PLACEHOLDERS, 200).optional(),
342
+ pullRequest: z2.strictObject({
343
+ title: template(TITLE_PLACEHOLDERS, 256).optional(),
344
+ labels: z2.array(
345
+ z2.string().trim().min(1).max(50).refine((l) => !l.includes(","), 'must not contain ","')
346
+ ).max(10).optional(),
347
+ draft: z2.boolean().optional()
348
+ }).optional()
349
+ });
350
+ var IDENT = /^[a-zA-Z][a-zA-Z0-9]*$/;
351
+ var identMsg = "must start with a letter and contain only letters and digits";
352
+ var base = {
353
+ label: z2.string(),
354
+ hint: z2.string().optional(),
355
+ required: z2.boolean().optional()
356
+ };
357
+ var strOrList = z2.union([z2.string(), z2.array(z2.string())]);
358
+ var nestedFields = z2.lazy(
359
+ () => z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema).refine((o) => Object.keys(o).length > 0, "fields must not be empty")
360
+ );
361
+ var fieldSchema = z2.discriminatedUnion("type", [
362
+ z2.strictObject({ ...base, type: z2.literal("string"), list: z2.boolean().optional(), default: strOrList.optional() }),
363
+ z2.strictObject({
364
+ ...base,
365
+ type: z2.literal("text"),
366
+ rows: z2.number().int().positive().optional(),
367
+ default: z2.string().optional()
368
+ }),
369
+ z2.strictObject({ ...base, type: z2.literal("markdown") }),
370
+ z2.strictObject({
371
+ ...base,
372
+ type: z2.literal("boolean"),
373
+ default: z2.boolean().optional(),
374
+ labels: z2.strictObject({ true: z2.string(), false: z2.string() }).optional()
375
+ }),
376
+ z2.strictObject({
377
+ ...base,
378
+ type: z2.literal("select"),
379
+ options: z2.array(z2.strictObject({ label: z2.string(), value: z2.string() })).min(1, "options must not be empty"),
380
+ multiple: z2.boolean().optional(),
381
+ default: strOrList.optional()
382
+ }),
383
+ z2.strictObject({
384
+ ...base,
385
+ type: z2.literal("number"),
386
+ min: z2.number().optional(),
387
+ max: z2.number().optional(),
388
+ step: z2.number().optional(),
389
+ integer: z2.boolean().optional(),
390
+ default: z2.number().optional()
391
+ }),
392
+ z2.strictObject({
393
+ ...base,
394
+ type: z2.literal("datetime"),
395
+ dateOnly: z2.boolean().optional(),
396
+ defaultNow: z2.boolean().optional()
397
+ }),
398
+ z2.strictObject({ ...base, type: z2.literal("json") }),
399
+ z2.strictObject({ ...base, type: z2.literal("url") }),
400
+ z2.strictObject({ ...base, type: z2.literal("color"), default: z2.string().optional() }),
401
+ z2.strictObject({ ...base, type: z2.literal("image") }),
402
+ z2.strictObject({
403
+ ...base,
404
+ type: z2.literal("reference"),
405
+ collections: z2.array(z2.string()).min(1, "collections must not be empty"),
406
+ multiple: z2.boolean().optional(),
407
+ min: z2.number().int().nonnegative().optional(),
408
+ max: z2.number().int().nonnegative().optional()
409
+ }),
410
+ z2.strictObject({
411
+ ...base,
412
+ type: z2.literal("object"),
413
+ fields: nestedFields,
414
+ list: z2.boolean().optional(),
415
+ min: z2.number().int().nonnegative().optional(),
416
+ max: z2.number().int().nonnegative().optional()
417
+ }),
418
+ z2.strictObject({
419
+ ...base,
420
+ type: z2.literal("blocks"),
421
+ blocks: z2.record(
422
+ z2.string().regex(IDENT, `block key ${identMsg}`),
423
+ z2.strictObject({ label: z2.string(), fields: nestedFields })
424
+ ).refine((o) => Object.keys(o).length > 0, "blocks must not be empty"),
425
+ min: z2.number().int().nonnegative().optional(),
426
+ max: z2.number().int().nonnegative().optional()
427
+ })
428
+ ]);
429
+ var collectionSchema = z2.strictObject({
430
+ label: z2.string(),
431
+ singleton: z2.boolean().optional(),
432
+ titleField: z2.string().optional(),
433
+ slugFrom: z2.string().optional(),
434
+ fields: z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema)
435
+ });
436
+ function checkFields(schema, fields, at, nested, add) {
437
+ for (const [fk, f] of Object.entries(fields)) {
438
+ const path = [...at, fk];
439
+ if (fk === "draft" && !nested) add(path, 'field key "draft" is reserved for the draft flag');
440
+ if ("default" in f && f.default !== void 0) {
441
+ const checked = fieldValueSchema(f)?.safeParse(f.default);
442
+ for (const issue of checked?.success === false ? checked.error.issues : []) {
443
+ add([...path, "default", ...issue.path.map(String)], `default: ${issue.message}`);
444
+ }
445
+ }
446
+ if (f.type === "reference") {
447
+ f.collections.forEach((target, i) => {
448
+ if (!Object.hasOwn(schema.collections, target))
449
+ add([...path, "collections", i], `unknown collection "${target}"`);
450
+ });
451
+ if (!f.multiple && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require multiple: true");
452
+ }
453
+ if (f.type === "object") {
454
+ if (!f.list && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require list: true");
455
+ checkFields(schema, f.fields, [...path, "fields"], true, add);
456
+ }
457
+ if (f.type === "blocks") {
458
+ for (const [bk, block] of Object.entries(f.blocks)) {
459
+ if (Object.hasOwn(block.fields, BLOCK_KEY)) {
460
+ add([...path, "blocks", bk, "fields", BLOCK_KEY], `field key "${BLOCK_KEY}" is reserved for the block type`);
461
+ }
462
+ checkFields(schema, block.fields, [...path, "blocks", bk, "fields"], true, add);
463
+ }
464
+ }
465
+ if ((f.type === "reference" || f.type === "object" || f.type === "blocks") && f.min !== void 0 && f.max !== void 0 && f.min > f.max) {
466
+ add([...path, "min"], "min must not exceed max");
467
+ }
468
+ }
469
+ }
470
+ var schemaSchema = z2.strictObject({
471
+ $schema: z2.string().optional(),
472
+ contentDir: z2.string().min(1).refine(
473
+ isCanonicalPath,
474
+ 'must be a relative posix path without empty, "." or ".." segments, backslashes, NUL or ":"'
475
+ ),
476
+ git: gitSchema,
477
+ collections: z2.record(z2.string().regex(IDENT, `collection key ${identMsg}`), collectionSchema)
478
+ }).superRefine((schema, ctx) => {
479
+ const add = (path, message) => ctx.addIssue({ code: "custom", path, message });
480
+ const { baseBranch, branchPrefix } = schema.git;
481
+ if (branchPrefix !== void 0 && (baseBranch.startsWith(branchPrefix) || branchPrefix.startsWith(`${baseBranch}/`))) {
482
+ add(["git", "branchPrefix"], `branchPrefix "${branchPrefix}" clashes with the base branch "${baseBranch}"`);
483
+ }
484
+ const lowerKeys = /* @__PURE__ */ new Map();
485
+ for (const [ck, col] of Object.entries(schema.collections)) {
486
+ const other = lowerKeys.get(ck.toLowerCase());
487
+ if (other !== void 0) add(["collections", ck], `collection key "${ck}" differs from "${other}" only in case`);
488
+ else lowerKeys.set(ck.toLowerCase(), ck);
489
+ const fields = Object.entries(col.fields);
490
+ if (fields.filter(([, f]) => f.type === "markdown").length > 1) {
491
+ add(["collections", ck, "fields"], "a collection can have at most one markdown field");
492
+ }
493
+ if (col.titleField !== void 0 && !Object.hasOwn(col.fields, col.titleField)) {
494
+ add(["collections", ck, "titleField"], `titleField "${col.titleField}" is not a field of ${ck}`);
495
+ }
496
+ if (col.slugFrom !== void 0 && !Object.hasOwn(col.fields, col.slugFrom)) {
497
+ add(["collections", ck, "slugFrom"], `slugFrom "${col.slugFrom}" is not a field of ${ck}`);
498
+ }
499
+ checkFields(schema, col.fields, ["collections", ck, "fields"], false, add);
500
+ }
501
+ });
502
+ function toIssues(error) {
503
+ const out = [];
504
+ for (const issue of error.issues) {
505
+ let path = issue.path.map(String);
506
+ let message = issue.message;
507
+ if (issue.code === "invalid_union" && ("discriminator" in issue || path.at(-1) !== "type")) {
508
+ if (path.at(-1) !== "type") path = [...path, "type"];
509
+ message = "unknown field type";
510
+ }
511
+ if (issue.code === "unrecognized_keys") {
512
+ for (const key of issue.keys) out.push({ path: [...path, key].join("."), message: `unknown key "${key}"` });
513
+ continue;
514
+ }
515
+ out.push({ path: path.join("."), message });
516
+ }
517
+ return out;
518
+ }
519
+ function loadSchema(input) {
520
+ const parsed = schemaSchema.safeParse(input);
521
+ if (!parsed.success) throw new EditletError(toIssues(parsed.error));
522
+ return parsed.data;
523
+ }
524
+ function parseSchemaText(text, file) {
525
+ let json;
526
+ try {
527
+ json = JSON.parse(text);
528
+ } catch (error) {
529
+ throw new EditletError([
530
+ { file, path: "", message: `Invalid JSON: ${error instanceof Error ? error.message : error}` }
531
+ ]);
532
+ }
533
+ try {
534
+ return loadSchema(json);
535
+ } catch (error) {
536
+ if (error instanceof EditletError) throw new EditletError(error.issues.map((issue) => ({ ...issue, file })));
537
+ throw error;
538
+ }
539
+ }
540
+ function markdownFieldKey(collection) {
541
+ return Object.entries(collection.fields).find(([, f]) => f.type === "markdown")?.[0];
542
+ }
543
+
544
+ // core/validate.ts
545
+ import { z as z3 } from "zod";
546
+
547
+ // core/walk.ts
548
+ var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
549
+ function blockFields(field, item) {
550
+ if (!isPlainObject(item)) return void 0;
551
+ const kind = item[BLOCK_KEY];
552
+ return typeof kind === "string" && Object.hasOwn(field.blocks, kind) ? field.blocks[kind].fields : void 0;
553
+ }
554
+ function children(field, value, path) {
555
+ if (field.type === "object") {
556
+ if (!field.list) return isPlainObject(value) ? [[field.fields, value, path]] : [];
557
+ if (!Array.isArray(value)) return [];
558
+ return value.flatMap((item, i) => isPlainObject(item) ? [[field.fields, item, [...path, i]]] : []);
559
+ }
560
+ if (field.type === "blocks") {
561
+ if (!Array.isArray(value)) return [];
562
+ return value.flatMap((item, i) => {
563
+ const fields = blockFields(field, item);
564
+ return fields ? [[fields, item, [...path, i]]] : [];
565
+ });
566
+ }
567
+ return [];
568
+ }
569
+ var isContainer = (field) => field.type === "object" || field.type === "blocks";
570
+ function visitFields(fields, data, visit, at = []) {
571
+ for (const [key, field] of Object.entries(fields)) {
572
+ if (!Object.hasOwn(data, key)) continue;
573
+ const path = [...at, key];
574
+ if (!isContainer(field)) {
575
+ visit(field, data[key], path);
576
+ continue;
577
+ }
578
+ for (const [childFields, child, childPath] of children(field, data[key], path)) {
579
+ visitFields(childFields, child, visit, childPath);
580
+ }
581
+ }
582
+ }
583
+ function mapFields(fields, data, map, at = []) {
584
+ const out = { ...data };
585
+ for (const [key, field] of Object.entries(fields)) {
586
+ if (!Object.hasOwn(data, key)) continue;
587
+ const path = [...at, key];
588
+ const value = data[key];
589
+ let next;
590
+ if (field.type === "object" && !field.list) {
591
+ next = isPlainObject(value) ? mapFields(field.fields, value, map, path) : value;
592
+ } else if (field.type === "object" && Array.isArray(value)) {
593
+ next = value.map((item, i) => isPlainObject(item) ? mapFields(field.fields, item, map, [...path, i]) : item);
594
+ } else if (field.type === "blocks" && Array.isArray(value)) {
595
+ next = value.map((item, i) => {
596
+ const child = blockFields(field, item);
597
+ return child ? mapFields(child, item, map, [...path, i]) : item;
598
+ });
599
+ } else if (isContainer(field)) {
600
+ next = value;
601
+ } else {
602
+ next = map(field, value, path);
603
+ }
604
+ if (next === void 0) delete out[key];
605
+ else out[key] = next;
606
+ }
607
+ return out;
608
+ }
609
+
610
+ // core/validate.ts
611
+ function buildDataSchema(collection) {
612
+ const shape = {};
613
+ for (const [key, field] of Object.entries(collection.fields)) {
614
+ const s = fieldValueSchema(field);
615
+ if (s) shape[key] = s;
616
+ }
617
+ shape.draft = z3.boolean({ error: "Expected true or false" }).optional();
618
+ return z3.strictObject(shape);
619
+ }
620
+ function toIssues2(error, file) {
621
+ const out = [];
622
+ for (const issue of error.issues) {
623
+ const path = issue.path.map(String);
624
+ if (issue.code === "unrecognized_keys") {
625
+ for (const key of issue.keys) out.push({ file, path: [...path, key].join("."), message: "Unknown field" });
626
+ continue;
627
+ }
628
+ out.push({ file, path: path.join("."), message: issue.message });
629
+ }
630
+ return out;
631
+ }
632
+ function validateEntry(schema, entry, ctx = {}) {
633
+ if (!Object.hasOwn(schema.collections, entry.collection)) {
634
+ return [{ path: "", message: `Unknown collection "${entry.collection}"` }];
635
+ }
636
+ const collection = schema.collections[entry.collection];
637
+ const file = entryFilePath(schema, entry.collection, entry.slug);
638
+ if (collection.singleton ? entry.slug !== "index" : !isValidSlug(entry.slug)) {
639
+ const message = collection.singleton ? 'Slug of a singleton must be "index"' : `Invalid slug "${entry.slug}": use lowercase letters, digits and single hyphens`;
640
+ return [{ file, path: "", message }];
641
+ }
642
+ if (typeof entry.data !== "object" || entry.data === null || Array.isArray(entry.data)) {
643
+ return [{ file, path: "", message: "Entry data must be an object" }];
644
+ }
645
+ const parsed = buildDataSchema(collection).safeParse(entry.data);
646
+ const issues = parsed.success ? [] : toIssues2(parsed.error, file);
647
+ const mdKey = markdownFieldKey(collection);
648
+ if (mdKey === void 0) {
649
+ if (entry.body.trim() !== "") {
650
+ issues.push({ file, path: "", message: "This collection has no markdown field, but the entry has body content" });
651
+ }
652
+ } else if (collection.fields[mdKey].required && entry.body.trim() === "") {
653
+ issues.push({ file, path: mdKey, message: "Required" });
654
+ }
655
+ const shapeIssues = [...issues];
656
+ const bad = (key) => shapeIssues.some((i) => i.path === key || i.path.startsWith(`${key}.`) || key.startsWith(`${i.path}.`));
657
+ visitFields(collection.fields, entry.data, (field, value, at) => {
658
+ const key = at.join(".");
659
+ if (bad(key)) return;
660
+ if (field.type === "image" && value !== null && value !== void 0) {
661
+ const src = value.src;
662
+ const resolved = resolveAssetPath(schema, file, src);
663
+ if (resolved === null) {
664
+ issues.push({ file, path: `${key}.src`, message: "Image path points outside the content directory" });
665
+ } else if (!isImagePath(resolved)) {
666
+ issues.push({ file, path: `${key}.src`, message: "Image path must end in an image extension" });
667
+ } else if (isHiddenContentPath(schema, resolved)) {
668
+ issues.push({ file, path: `${key}.src`, message: 'Image path must not be hidden (a segment starts with ".")' });
669
+ } else if (ctx.fileExists?.(resolved) === false) {
670
+ issues.push({ file, path: `${key}.src`, message: `Image file not found: ${resolved}` });
671
+ }
672
+ } else if (field.type === "reference" && !isAbsentValue(field, value)) {
673
+ const refs = Array.isArray(value) ? value : [value];
674
+ refs.forEach((ref, i) => {
675
+ if (ctx.entryExists?.(ref) === false) {
676
+ issues.push({
677
+ file,
678
+ path: Array.isArray(value) ? `${key}.${i}` : key,
679
+ message: `Referenced entry not found: ${ref}`
680
+ });
681
+ }
682
+ });
683
+ }
684
+ });
685
+ return issues;
686
+ }
687
+
688
+ // core/writes.ts
689
+ function isWritablePath(schema, schemaPath, path) {
690
+ if (!isCanonicalPath(path)) return false;
691
+ if (path === schemaPath) return true;
692
+ if (!path.startsWith(`${schema.contentDir}/`) || isHiddenContentPath(schema, path)) return false;
693
+ if (path.endsWith(".md")) return parseEntryPath(schema, path) !== null;
694
+ return isImagePath(path);
695
+ }
696
+ function issuesOf(error, file) {
697
+ if (!(error instanceof EditletError)) throw error;
698
+ return error.issues.map((issue) => ({ ...issue, file: issue.file ?? file }));
699
+ }
700
+ var issueKey = (i) => `${i.file}|${i.path}|${i.message}`;
701
+ function refExists(schema, fileExists) {
702
+ return (ref) => {
703
+ const parsed = parseRefKey(ref);
704
+ if (!parsed || !Object.hasOwn(schema.collections, parsed.collection)) return false;
705
+ const { collection, slug } = parsed;
706
+ if (schema.collections[collection].singleton && slug !== "index") return false;
707
+ const path = entryFilePath(schema, collection, slug);
708
+ return parseEntryPath(schema, path) !== null && fileExists(path);
709
+ };
710
+ }
711
+ function checkEntry(state, path, entry, content) {
712
+ const decoded = decodeUtf8(content, path);
713
+ if ("issue" in decoded) return [decoded.issue];
714
+ let file;
715
+ try {
716
+ file = parseEntryFile(decoded.text);
717
+ } catch (error) {
718
+ return issuesOf(error, path);
719
+ }
720
+ const { schema, ...ctx } = state;
721
+ return validateEntry(schema, { ...entry, data: file.data, body: file.body }, ctx);
722
+ }
723
+ function validateChanges(current, changes) {
724
+ const { schemaPath } = current;
725
+ const latest = /* @__PURE__ */ new Map();
726
+ const duplicates = /* @__PURE__ */ new Set();
727
+ for (const change of changes) {
728
+ if (latest.has(change.path)) duplicates.add(change.path);
729
+ latest.set(change.path, change.content);
730
+ }
731
+ if (duplicates.size > 0) {
732
+ return [...duplicates].map((file) => ({ file, path: "", message: "Duplicate path in changes" }));
733
+ }
734
+ let schema = current.schema;
735
+ if (latest.has(schemaPath)) {
736
+ const content = latest.get(schemaPath) ?? null;
737
+ if (content === null) return [{ file: schemaPath, path: "", message: "The schema file cannot be deleted" }];
738
+ const decoded = decodeUtf8(content, schemaPath);
739
+ if ("issue" in decoded) return [decoded.issue];
740
+ try {
741
+ schema = parseSchemaText(decoded.text, schemaPath);
742
+ } catch (error) {
743
+ return issuesOf(error, schemaPath);
744
+ }
745
+ }
746
+ const issues = [];
747
+ if (current.schema === null) {
748
+ for (const path of latest.keys()) {
749
+ if (path === schemaPath) continue;
750
+ issues.push({ file: path, path: "", message: `The schema (${schemaPath}) is invalid; fix it first` });
751
+ }
752
+ return issues;
753
+ }
754
+ const prev = current.schema;
755
+ const effective = schema ?? prev;
756
+ const fileExists = (path) => latest.has(path) ? latest.get(path) !== null : current.exists(path);
757
+ const after = { schema: effective, fileExists, entryExists: refExists(effective, fileExists) };
758
+ for (const [path, content] of latest) {
759
+ if (path === schemaPath) continue;
760
+ if (!isWritablePath(effective, schemaPath, path)) {
761
+ issues.push({ file: path, path: "", message: "Path not writable" });
762
+ continue;
763
+ }
764
+ const parsed = content === null ? null : parseEntryPath(effective, path);
765
+ if (content !== null && parsed !== null) issues.push(...checkEntry(after, path, parsed, content));
766
+ }
767
+ const { read, list } = current;
768
+ const wide = latest.has(schemaPath) || [...latest.values()].includes(null);
769
+ if (!wide || read === void 0 || list === void 0) return issues;
770
+ const before = { schema: prev, fileExists: current.exists, entryExists: refExists(prev, current.exists) };
771
+ for (const path of list()) {
772
+ if (latest.has(path) || path === schemaPath || !path.endsWith(".md")) continue;
773
+ const owner = [effective, prev].find((s) => path.startsWith(`${s.contentDir}/`));
774
+ if (owner === void 0 || isHiddenContentPath(owner, path)) continue;
775
+ const wasEntry = parseEntryPath(prev, path);
776
+ const isEntry = parseEntryPath(effective, path);
777
+ if (isEntry === null) {
778
+ if (wasEntry !== null) issues.push({ file: path, path: "", message: "Not an entry file" });
779
+ continue;
780
+ }
781
+ const text = read(path);
782
+ if (text === void 0) continue;
783
+ const known = new Set(wasEntry === null ? [] : checkEntry(before, path, wasEntry, text).map(issueKey));
784
+ issues.push(...checkEntry(after, path, isEntry, text).filter((i) => !known.has(issueKey(i))));
785
+ }
786
+ return issues;
787
+ }
788
+
789
+ // node/fs.ts
790
+ import { readdir, readFile } from "node:fs/promises";
791
+ import { join, resolve } from "node:path";
792
+ var DEFAULT_SCHEMA_PATH = "cms/schema.json";
793
+ async function loadProjectSchema(root, schemaPath) {
794
+ let raw;
795
+ try {
796
+ raw = await readFile(join(root, schemaPath), "utf8");
797
+ } catch (error) {
798
+ throw new EditletError([
799
+ { file: schemaPath, path: "", message: `Cannot read schema: ${error instanceof Error ? error.message : error}` }
800
+ ]);
801
+ }
802
+ return parseSchemaText(raw, schemaPath);
803
+ }
804
+ async function listFiles(root, contentDir) {
805
+ let dirents;
806
+ try {
807
+ dirents = await readdir(join(root, contentDir), { recursive: true, withFileTypes: true });
808
+ } catch (error) {
809
+ if (error.code === "ENOENT") return [];
810
+ throw error;
811
+ }
812
+ return dirents.filter((d) => d.isFile()).map((d) => `${relativeDir(root, d.parentPath)}/${d.name}`.split("\\").join("/")).toSorted();
813
+ }
814
+ function relativeDir(root, dir) {
815
+ return resolve(dir).slice(resolve(root).length + 1);
816
+ }
817
+
818
+ // skills/editlet/scripts/schemaOps.ts
819
+ async function addFiles(root, dir, files) {
820
+ for (const path of await listFiles(root, dir)) {
821
+ if (!files.has(path)) files.set(path, await readFile2(join2(root, path)));
822
+ }
823
+ }
824
+ async function loadContext(root) {
825
+ const schemaPath = DEFAULT_SCHEMA_PATH;
826
+ const schema = await loadProjectSchema(root, schemaPath);
827
+ const schemaBytes = await readFile2(join2(root, schemaPath));
828
+ const files = /* @__PURE__ */ new Map([[schemaPath, schemaBytes]]);
829
+ await addFiles(root, schema.contentDir, files);
830
+ return {
831
+ root,
832
+ schemaPath,
833
+ schemaText: schemaBytes.toString("utf8"),
834
+ schema,
835
+ files,
836
+ context: contextOf(schema, schemaPath, files)
837
+ };
838
+ }
839
+ function contextOf(schema, schemaPath, files) {
840
+ const decoder = new TextDecoder("utf-8", { fatal: true });
841
+ return {
842
+ schema,
843
+ schemaPath,
844
+ exists: (path) => files.has(path),
845
+ read: (path) => {
846
+ const bytes = files.get(path);
847
+ if (!bytes) return void 0;
848
+ try {
849
+ return decoder.decode(bytes);
850
+ } catch {
851
+ return void 0;
852
+ }
853
+ },
854
+ list: () => files.keys()
855
+ };
856
+ }
857
+ var UsageError = class extends Error {
858
+ };
859
+
860
+ // core/references.ts
861
+ function entryReferences(collection, data) {
862
+ const out = [];
863
+ visitFields(collection.fields, data, (field, value, at) => {
864
+ if (field.type !== "reference") return;
865
+ for (const ref of Array.isArray(value) ? value : [value]) {
866
+ if (typeof ref === "string" && ref !== "") out.push({ field: at.join("."), ref });
867
+ }
868
+ });
869
+ return out;
870
+ }
871
+ function replaceReference(collection, data, from, to) {
872
+ let changed = false;
873
+ const out = mapFields(collection.fields, data, (field, value) => {
874
+ if (field.type !== "reference") return value;
875
+ if (Array.isArray(value)) {
876
+ if (!value.includes(from)) return value;
877
+ changed = true;
878
+ if (to !== null) return value.map((r) => r === from ? to : r);
879
+ const rest = value.filter((r) => r !== from);
880
+ return rest.length > 0 ? rest : void 0;
881
+ }
882
+ if (value !== from) return value;
883
+ changed = true;
884
+ return to ?? void 0;
885
+ });
886
+ return changed ? out : null;
887
+ }
888
+ function findReferrers(schema, entries, ref) {
889
+ const out = [];
890
+ for (const entry of entries) {
891
+ if (!Object.hasOwn(schema.collections, entry.collection)) continue;
892
+ const fields = entryReferences(schema.collections[entry.collection], entry.data).filter((r) => r.ref === ref).map((r) => r.field);
893
+ if (fields.length > 0) out.push({ entry, fields: [...new Set(fields)] });
894
+ }
895
+ return out;
896
+ }
897
+
898
+ // core/assets.ts
899
+ function codeRanges(text) {
900
+ const out = [];
901
+ const lines = text.split("\n");
902
+ let pos = 0;
903
+ let fence = null;
904
+ let indented = null;
905
+ let previousBlank = true;
906
+ for (const line of lines) {
907
+ const end = pos + line.length;
908
+ const blank = line.trim() === "";
909
+ if (fence) {
910
+ const close = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(line);
911
+ if (close && close[1][0] === fence.char && close[1].length >= fence.length) {
912
+ out.push([fence.start, end]);
913
+ fence = null;
914
+ }
915
+ } else {
916
+ const open = /^ {0,3}(`{3,}|~{3,})/.exec(line);
917
+ const isIndented = /^(?: {4}|\t)/.test(line) && !blank;
918
+ if (indented !== null && !isIndented && !blank) {
919
+ out.push([indented, pos]);
920
+ indented = null;
921
+ }
922
+ if (open && indented === null) fence = { char: open[1][0], length: open[1].length, start: pos };
923
+ else if (isIndented && indented === null && previousBlank) indented = pos;
924
+ }
925
+ previousBlank = blank;
926
+ pos = end + 1;
927
+ }
928
+ if (fence) out.push([fence.start, text.length]);
929
+ if (indented !== null) out.push([indented, text.length]);
930
+ const inside = (i) => out.some(([s, e]) => i >= s && i < e);
931
+ const inline = [];
932
+ const spans = /(`+)|<!--/g;
933
+ let m;
934
+ while (m = spans.exec(text)) {
935
+ if (inside(m.index)) continue;
936
+ if (m[0] === "<!--") {
937
+ const close2 = text.indexOf("-->", m.index + 4);
938
+ const stop = close2 === -1 ? text.length : close2 + 3;
939
+ inline.push([m.index, stop]);
940
+ spans.lastIndex = stop;
941
+ continue;
942
+ }
943
+ const run = m[1];
944
+ const closer = new RegExp(`(?<!\`)${run}(?!\`)`, "g");
945
+ closer.lastIndex = m.index + run.length;
946
+ const close = closer.exec(text);
947
+ if (!close) continue;
948
+ inline.push([m.index, close.index + run.length]);
949
+ spans.lastIndex = close.index + run.length;
950
+ }
951
+ return [...out, ...inline];
952
+ }
953
+ function maskCode(text) {
954
+ let masked = text;
955
+ for (const [s, e] of codeRanges(text)) {
956
+ masked = masked.slice(0, s) + masked.slice(s, e).replace(/[^\n]/g, " ") + masked.slice(e);
957
+ }
958
+ return masked;
959
+ }
960
+ var isEscaped = (text, i) => {
961
+ let n = 0;
962
+ while (i - 1 - n >= 0 && text[i - 1 - n] === "\\") n++;
963
+ return n % 2 === 1;
964
+ };
965
+ var unescapeMarkdown = (s) => s.replace(/\\([!-/:-@[-`{-~])/g, "$1");
966
+ var decodeEntities = (s) => s.replace(
967
+ /&(quot|amp|lt|gt|#39|apos);/g,
968
+ (_, e) => e === "quot" ? '"' : e === "amp" ? "&" : e === "lt" ? "<" : e === "gt" ? ">" : "'"
969
+ );
970
+ var normalizeLabel = (s) => s.trim().replace(/\s+/g, " ").toLowerCase();
971
+ function closingBracket(text, open) {
972
+ let depth = 0;
973
+ for (let i = open; i < text.length; i++) {
974
+ const c = text[i];
975
+ if (c === "\n" && text[i + 1] === "\n") return -1;
976
+ if (isEscaped(text, i)) continue;
977
+ if (c === "[") depth++;
978
+ else if (c === "]" && --depth === 0) return i;
979
+ }
980
+ return -1;
981
+ }
982
+ function inlineDestination(text, open) {
983
+ let i = open + 1;
984
+ while (text[i] === " " || text[i] === " " || text[i] === "\n") i++;
985
+ let start = i;
986
+ let stop;
987
+ if (text[i] === "<") {
988
+ const close = text.indexOf(">", i);
989
+ if (close === -1 || text.slice(i, close).includes("\n")) return null;
990
+ start = i + 1;
991
+ stop = close;
992
+ i = close + 1;
993
+ } else {
994
+ let depth = 0;
995
+ while (i < text.length && !/\s/.test(text[i])) {
996
+ if (text[i] === "(" && !isEscaped(text, i)) depth++;
997
+ else if (text[i] === ")" && !isEscaped(text, i)) {
998
+ if (depth === 0) break;
999
+ depth--;
1000
+ }
1001
+ i++;
1002
+ }
1003
+ stop = i;
1004
+ }
1005
+ while (text[i] === " " || text[i] === " " || text[i] === "\n") i++;
1006
+ const quote = text[i];
1007
+ if (quote === '"' || quote === "'" || quote === "(") {
1008
+ const closeChar = quote === "(" ? ")" : quote;
1009
+ let j = i + 1;
1010
+ while (j < text.length && (text[j] !== closeChar || isEscaped(text, j))) j++;
1011
+ if (j >= text.length) return null;
1012
+ i = j + 1;
1013
+ while (text[i] === " " || text[i] === " " || text[i] === "\n") i++;
1014
+ }
1015
+ if (text[i] !== ")") return null;
1016
+ return { range: [start, stop], src: unescapeMarkdown(text.slice(start, stop)), end: i + 1 };
1017
+ }
1018
+ function definitions(masked) {
1019
+ const out = /* @__PURE__ */ new Map();
1020
+ const re = /^ {0,3}\[((?:\\.|[^\]\\])+)\]:[ \t]*(?:\n[ \t]*)?(<[^>\n]*>|\S+)/gm;
1021
+ let m;
1022
+ while (m = re.exec(masked)) {
1023
+ const label = normalizeLabel(m[1]);
1024
+ if (label === "" || out.has(label)) continue;
1025
+ const raw = m[2];
1026
+ const destStart = m.index + m[0].length - raw.length;
1027
+ const angle = raw.startsWith("<");
1028
+ const start = angle ? destStart + 1 : destStart;
1029
+ const stop = angle ? destStart + raw.length - 1 : destStart + raw.length;
1030
+ out.set(label, { range: [start, stop], src: unescapeMarkdown(masked.slice(start, stop)) });
1031
+ }
1032
+ return out;
1033
+ }
1034
+ function markdownImages(masked, defs) {
1035
+ const out = [];
1036
+ let from = 0;
1037
+ for (; ; ) {
1038
+ const at = masked.indexOf("![", from);
1039
+ if (at === -1) return out;
1040
+ from = at + 2;
1041
+ if (isEscaped(masked, at)) continue;
1042
+ const close = closingBracket(masked, at + 1);
1043
+ if (close === -1) continue;
1044
+ const altRange = [at + 2, close];
1045
+ const altText = masked.slice(at + 2, close);
1046
+ const alt = unescapeMarkdown(altText);
1047
+ const next = masked[close + 1];
1048
+ if (next === "(") {
1049
+ const dest = inlineDestination(masked, close + 1);
1050
+ if (dest) {
1051
+ out.push({ kind: "inline", src: dest.src, alt, range: [at, dest.end], altRange, srcRange: dest.range });
1052
+ from = dest.end;
1053
+ continue;
1054
+ }
1055
+ }
1056
+ let label;
1057
+ let end = close + 1;
1058
+ if (next === "[") {
1059
+ const labelClose = closingBracket(masked, close + 1);
1060
+ if (labelClose !== -1) {
1061
+ const text = masked.slice(close + 2, labelClose);
1062
+ label = text.trim() === "" ? { text: altText, form: "collapsed" } : { text, form: "full" };
1063
+ end = labelClose + 1;
1064
+ }
1065
+ }
1066
+ label ??= { text: altText, form: "shortcut" };
1067
+ const def = defs.get(normalizeLabel(label.text));
1068
+ if (!def) continue;
1069
+ out.push({ kind: "reference", src: def.src, alt, range: [at, end], altRange, srcRange: def.range, label });
1070
+ from = end;
1071
+ }
1072
+ }
1073
+ function htmlImages(masked) {
1074
+ const out = [];
1075
+ const tags = /<img\b[^>]*>/gi;
1076
+ let m;
1077
+ while (m = tags.exec(masked)) {
1078
+ const tag = m[0];
1079
+ const attrs = /\s(src|alt)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
1080
+ let src;
1081
+ let alt;
1082
+ let a;
1083
+ while (a = attrs.exec(tag)) {
1084
+ const value = a[2] ?? a[3] ?? a[4] ?? "";
1085
+ const quoted = a[2] !== void 0 || a[3] !== void 0;
1086
+ const valueStart = m.index + a.index + a[0].length - value.length - (quoted ? 1 : 0);
1087
+ const entry = { range: [valueStart, valueStart + value.length], value: decodeEntities(value) };
1088
+ if (a[1].toLowerCase() === "src") src ??= entry;
1089
+ else alt ??= entry;
1090
+ }
1091
+ if (!src) continue;
1092
+ out.push({
1093
+ kind: "html",
1094
+ src: src.value,
1095
+ alt: alt?.value ?? "",
1096
+ range: [m.index, m.index + tag.length],
1097
+ altRange: alt?.range ?? null,
1098
+ srcRange: src.range
1099
+ });
1100
+ }
1101
+ return out;
1102
+ }
1103
+ function findBodyImages(body) {
1104
+ const masked = maskCode(body);
1105
+ const images = [...markdownImages(masked, definitions(masked)), ...htmlImages(masked)];
1106
+ return images.toSorted((a, b) => a.range[0] - b.range[0]);
1107
+ }
1108
+ function findImageRefs(schema, collection, entryPath, data, body) {
1109
+ const out = [];
1110
+ visitFields(collection.fields, data, (field, v, at) => {
1111
+ const nested = at.length > 1 ? { at, label: `${field.label} (${at.slice(0, -1).join(".")})` } : {};
1112
+ if (field.type === "markdown" && typeof v === "string") {
1113
+ for (const image of findBodyImages(v)) {
1114
+ const use = {
1115
+ src: image.src,
1116
+ alt: image.alt,
1117
+ path: resolveAssetPath(schema, entryPath, image.src),
1118
+ body: image
1119
+ };
1120
+ out.push({ field: at.join("."), ...nested, at, ...use });
1121
+ }
1122
+ return;
1123
+ }
1124
+ if (field.type !== "image" || typeof v !== "object" || v === null) return;
1125
+ const { src, alt } = v;
1126
+ if (typeof src !== "string" || src === "") return;
1127
+ out.push({
1128
+ field: at.join("."),
1129
+ ...nested,
1130
+ src,
1131
+ alt: typeof alt === "string" ? alt : "",
1132
+ path: resolveAssetPath(schema, entryPath, src)
1133
+ });
1134
+ });
1135
+ const bodyField = markdownFieldKey(collection) ?? "body";
1136
+ for (const image of findBodyImages(body)) {
1137
+ out.push({
1138
+ field: bodyField,
1139
+ src: image.src,
1140
+ alt: image.alt,
1141
+ path: resolveAssetPath(schema, entryPath, image.src),
1142
+ body: image
1143
+ });
1144
+ }
1145
+ return out;
1146
+ }
1147
+ var escapeAlt = (alt) => alt.replace(/[\\[\]]/g, "\\$&");
1148
+ var escapeAttr = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1149
+ var markdownDestination = (src) => /[\s()<>]/.test(src) ? `<${src.replace(/[<>]/g, "\\$&")}>` : src;
1150
+ function altSplice(image, alt) {
1151
+ if (image.kind === "html") {
1152
+ if (image.altRange) return { range: image.altRange, text: escapeAttr(alt) };
1153
+ const at = image.range[0] + 4;
1154
+ return { range: [at, at], text: ` alt="${escapeAttr(alt)}"` };
1155
+ }
1156
+ if (image.kind === "reference" && image.label && image.label.form !== "full") {
1157
+ return { range: image.range, text: `![${escapeAlt(alt)}][${image.label.text}]` };
1158
+ }
1159
+ return { range: image.altRange, text: escapeAlt(alt) };
1160
+ }
1161
+ function srcSplice(body, image, src) {
1162
+ if (image.kind === "html") return { range: image.srcRange, text: escapeAttr(src) };
1163
+ const [s, e] = image.srcRange;
1164
+ const angled = body[s - 1] === "<" && body[e] === ">";
1165
+ const text = angled ? src.replace(/[<>]/g, "\\$&") : markdownDestination(src);
1166
+ return { range: image.srcRange, text };
1167
+ }
1168
+ function editBodyImages(body, edits) {
1169
+ const splices = /* @__PURE__ */ new Map();
1170
+ for (const { image, alt, src } of edits) {
1171
+ for (const splice of [
1172
+ alt === void 0 ? null : altSplice(image, alt),
1173
+ src === void 0 ? null : srcSplice(body, image, src)
1174
+ ]) {
1175
+ if (splice) splices.set(`${splice.range[0]}:${splice.range[1]}`, splice);
1176
+ }
1177
+ }
1178
+ const ordered = [...splices.values()].toSorted((a, b) => b.range[0] - a.range[0] || b.range[1] - a.range[1]);
1179
+ let out = body;
1180
+ let floor = Infinity;
1181
+ for (const { range, text } of ordered) {
1182
+ if (range[1] > floor) continue;
1183
+ out = out.slice(0, range[0]) + text + out.slice(range[1]);
1184
+ floor = range[0];
1185
+ }
1186
+ return out;
1187
+ }
1188
+ function getAt(data, path) {
1189
+ return path.reduce(
1190
+ (v, k) => v !== null && typeof v === "object" ? v[k] : void 0,
1191
+ data
1192
+ );
1193
+ }
1194
+ function setAt(data, path, value) {
1195
+ if (path.length === 0) return value;
1196
+ const [head, ...rest] = path;
1197
+ const copy = Array.isArray(data) ? [...data] : { ...data };
1198
+ copy[head] = setAt(copy[head], rest, value);
1199
+ return copy;
1200
+ }
1201
+ function applyImageEdits(data, body, edits) {
1202
+ let out = { ...data };
1203
+ const bodyEdits = [];
1204
+ const textEdits = /* @__PURE__ */ new Map();
1205
+ for (const { use, alt, src } of edits) {
1206
+ if (use.body && use.at) {
1207
+ const key = use.at.join(".");
1208
+ const group = textEdits.get(key) ?? { at: use.at, edits: [] };
1209
+ group.edits.push({ image: use.body, alt, src });
1210
+ textEdits.set(key, group);
1211
+ } else if (use.body) bodyEdits.push({ image: use.body, alt, src });
1212
+ else {
1213
+ const at = use.at ?? [use.field];
1214
+ const value = getAt(out, at);
1215
+ const next = { ...value, ...src === void 0 ? {} : { src }, ...alt === void 0 ? {} : { alt } };
1216
+ out = setAt(out, at, next);
1217
+ }
1218
+ }
1219
+ for (const { at, edits: group } of textEdits.values()) {
1220
+ out = setAt(out, at, editBodyImages(String(getAt(out, at)), group));
1221
+ }
1222
+ return { data: out, body: bodyEdits.length > 0 ? editBodyImages(body, bodyEdits) : body };
1223
+ }
1224
+
1225
+ // core/rename.ts
1226
+ var fail2 = (message) => {
1227
+ throw new EditletError([{ path: "", message }]);
1228
+ };
1229
+ function entryOf(schema, entries, ref) {
1230
+ const i = ref.indexOf("/");
1231
+ const collection = ref.slice(0, i);
1232
+ const slug = ref.slice(i + 1);
1233
+ if (!Object.hasOwn(schema.collections, collection)) fail2(`Unknown collection "${collection}"`);
1234
+ const entry = entries.find((e) => e.collection === collection && e.slug === slug);
1235
+ return entry ?? fail2(`Entry not found: ${ref}`);
1236
+ }
1237
+ function planRename(schema, entries, files, ref, to) {
1238
+ const entry = entryOf(schema, entries, ref);
1239
+ const { collection, slug } = entry;
1240
+ if (schema.collections[collection].singleton) fail2('A singleton cannot be renamed: its slug is always "index"');
1241
+ if (!isValidSlug(to)) fail2(`Invalid slug "${to}": use lowercase letters, digits and single hyphens`);
1242
+ if (to === slug) fail2("The new slug is the same as the old one");
1243
+ const oldPath = entryFilePath(schema, collection, slug);
1244
+ const newPath = entryFilePath(schema, collection, to);
1245
+ const oldDir = `${schema.contentDir}/${collection}/${slug}/`;
1246
+ const newDir = `${schema.contentDir}/${collection}/${to}/`;
1247
+ const paths = [...files];
1248
+ if (paths.some((p) => p === newPath || p.startsWith(newDir))) fail2(`${collection}/${to} is taken`);
1249
+ const move = paths.filter((p) => p.startsWith(oldDir)).map((p) => ({ from: p, to: newDir + p.slice(oldDir.length) }));
1250
+ const moved = new Map(move.map((m) => [m.from, m.to]));
1251
+ const newRef = refKey(collection, to);
1252
+ const write = [];
1253
+ for (const e of entries) {
1254
+ const isSelf = e === entry;
1255
+ const path = isSelf ? newPath : entryFilePath(schema, e.collection, e.slug);
1256
+ const def = schema.collections[e.collection];
1257
+ if (!def) continue;
1258
+ const reasons = isSelf ? ["renamed"] : [];
1259
+ const replacements = [];
1260
+ let data = e.data;
1261
+ const replaced = replaceReference(def, data, ref, newRef);
1262
+ if (replaced) {
1263
+ data = replaced;
1264
+ reasons.push("references");
1265
+ replacements.push({ from: ref, to: newRef });
1266
+ }
1267
+ const edits = findImageRefs(schema, def, isSelf ? oldPath : path, data, e.body).flatMap((use) => {
1268
+ const target = use.path === null ? void 0 : moved.get(use.path);
1269
+ return target === void 0 ? [] : [{ use, src: relativeAssetSrc(path, target) }];
1270
+ });
1271
+ let body = e.body;
1272
+ if (edits.length > 0) {
1273
+ ({ data, body } = applyImageEdits(data, body, edits));
1274
+ reasons.push("images");
1275
+ for (const { use, src } of edits) {
1276
+ if (!replacements.some((r) => r.from === use.src)) replacements.push({ from: use.src, to: src });
1277
+ }
1278
+ }
1279
+ if (reasons.length > 0) write.push({ entry: e, path, data, body, reasons, replacements });
1280
+ }
1281
+ write.sort((a, b) => Number(b.entry === entry) - Number(a.entry === entry));
1282
+ return { from: ref, to: newRef, write, remove: [oldPath], move };
1283
+ }
1284
+ function planRemove(schema, entries, ref) {
1285
+ const entry = entryOf(schema, entries, ref);
1286
+ const write = [];
1287
+ for (const e of entries) {
1288
+ if (e === entry) continue;
1289
+ const def = schema.collections[e.collection];
1290
+ const data = def ? replaceReference(def, e.data, ref, null) : null;
1291
+ if (data) {
1292
+ const path = entryFilePath(schema, e.collection, e.slug);
1293
+ write.push({
1294
+ entry: e,
1295
+ path,
1296
+ data,
1297
+ body: e.body,
1298
+ reasons: ["references"],
1299
+ replacements: [{ from: ref, to: null }]
1300
+ });
1301
+ }
1302
+ }
1303
+ return { ref, write, remove: [entryFilePath(schema, entry.collection, entry.slug)] };
1304
+ }
1305
+
1306
+ // skills/editlet/scripts/refsOps.ts
1307
+ function projectEntries(ctx) {
1308
+ const out = [];
1309
+ for (const [path, bytes] of ctx.files) {
1310
+ const parsed = parseEntryPath(ctx.schema, path);
1311
+ if (!parsed) continue;
1312
+ const decoded = decodeUtf8(bytes, path);
1313
+ if (!("text" in decoded)) continue;
1314
+ try {
1315
+ out.push({ ...parsed, path, text: decoded.text, ...parseEntryFile(decoded.text) });
1316
+ } catch {
1317
+ }
1318
+ }
1319
+ return out.toSorted((a, b) => a.path.localeCompare(b.path));
1320
+ }
1321
+ var escape = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1322
+ function replaceToken(text, from, to) {
1323
+ return text.replace(new RegExp(`(?<![\\w./-])${escape(from)}(?![\\w./-])`, "g"), to);
1324
+ }
1325
+ function removeLines(text, from) {
1326
+ const end = text.indexOf("\n---", 4);
1327
+ if (!text.startsWith("---") || end === -1) return text;
1328
+ const line = new RegExp(`^\\s*(?:-|[A-Za-z][A-Za-z0-9]*:)\\s+['"]?${escape(from)}['"]?\\s*$`);
1329
+ const head = text.slice(0, end).split("\n").filter((l) => !line.test(l)).join("\n");
1330
+ const emptied = head.replace(/^([A-Za-z][A-Za-z0-9]*):[ \t]*\n(?=[A-Za-z]|$)/gm, "").replace(/^([A-Za-z][A-Za-z0-9]*):[ \t]*$(?![\s\S])/m, "");
1331
+ return emptied + text.slice(end);
1332
+ }
1333
+ function rewriteText(write) {
1334
+ let text = write.entry.text;
1335
+ for (const { from, to } of write.replacements)
1336
+ text = to === null ? removeLines(text, from) : replaceToken(text, from, to);
1337
+ try {
1338
+ const back = parseEntryFile(text);
1339
+ if (isDeepStrictEqual(back.data, write.data) && back.body === write.body) return { text, rewritten: false };
1340
+ } catch {
1341
+ }
1342
+ const order = Object.keys(write.entry.data);
1343
+ return { text: serializeEntryFile({ data: write.data, body: write.body }, order), rewritten: true };
1344
+ }
1345
+ function planned(fn) {
1346
+ try {
1347
+ return fn();
1348
+ } catch (error) {
1349
+ if (error instanceof EditletError) throw new UsageError(error.issues.map((i) => i.message).join("; "));
1350
+ throw error;
1351
+ }
1352
+ }
1353
+ function check(ctx, changes) {
1354
+ return validateChanges(ctx.context, changes);
1355
+ }
1356
+ function entryLines(writes, changes) {
1357
+ return writes.map((w) => {
1358
+ const { text, rewritten } = rewriteText(w);
1359
+ changes.push({ path: w.path, content: text });
1360
+ const what = w.reasons.filter((r) => r !== "renamed").join(", ");
1361
+ return `entry: ${w.path}${w.reasons.includes("renamed") ? " (new path)" : ""}${what ? ` (${what})` : ""}${rewritten ? " (rewritten in standard format)" : ""}`;
1362
+ });
1363
+ }
1364
+ function planRenameRef(ctx, ref, to) {
1365
+ return planned(() => {
1366
+ const entries = projectEntries(ctx);
1367
+ const plan = planRename(ctx.schema, entries, ctx.files.keys(), ref, to);
1368
+ const changes = [];
1369
+ const lines = [`rename: ${plan.from} \u2192 ${plan.to}`, ...entryLines(plan.write, changes)];
1370
+ for (const path of plan.remove) {
1371
+ changes.push({ path, content: null });
1372
+ lines.push(`delete: ${path}`);
1373
+ }
1374
+ for (const { from, to: target } of plan.move) {
1375
+ changes.push({ path: target, content: ctx.files.get(from) }, { path: from, content: null });
1376
+ lines.push(`move: ${from} \u2192 ${target}`);
1377
+ }
1378
+ return { changes, lines, issues: check(ctx, changes) };
1379
+ });
1380
+ }
1381
+ function planRemoveRef(ctx, ref) {
1382
+ return planned(() => {
1383
+ const entries = projectEntries(ctx);
1384
+ const plan = planRemove(ctx.schema, entries, ref);
1385
+ const changes = [];
1386
+ const lines = [`remove: ${ref}`, ...entryLines(plan.write, changes)];
1387
+ for (const path of plan.remove) {
1388
+ changes.push({ path, content: null });
1389
+ lines.push(`delete: ${path}`);
1390
+ }
1391
+ return { changes, lines, issues: check(ctx, changes) };
1392
+ });
1393
+ }
1394
+ function usedBy(ctx, ref) {
1395
+ const entries = projectEntries(ctx);
1396
+ if (!entries.some((e) => refKey(e.collection, e.slug) === ref)) throw new UsageError(`Entry not found: ${ref}`);
1397
+ return findReferrers(ctx.schema, entries, ref).map((r) => `${r.entry.path}: ${r.fields.join(", ")}`);
1398
+ }
1399
+
1400
+ // skills/editlet/scripts/refs.ts
1401
+ var USAGE = `Usage: refs <command> [args] [--root <dir>] [--apply]
1402
+
1403
+ Commands:
1404
+ used-by <collection/slug> list the entries that reference it, with the fields
1405
+ rename <collection/slug> <new-slug> rename the entry: its file and folder move, every reference and image src
1406
+ follows (dry run; --apply writes)
1407
+ remove <collection/slug> delete the entry and remove every reference to it; its images stay
1408
+ (dry run; --apply writes)
1409
+ `;
1410
+ async function runPlan(root, plan, apply) {
1411
+ if (plan.issues.length > 0) return reportIssues(plan.issues);
1412
+ const out = [...plan.lines];
1413
+ if (apply) {
1414
+ const ordered = [
1415
+ ...plan.changes.filter((c) => c.content !== null),
1416
+ ...plan.changes.filter((c) => c.content === null)
1417
+ ];
1418
+ const done = [];
1419
+ for (const { path, content } of ordered) {
1420
+ const file = join3(root, path);
1421
+ try {
1422
+ if (content === null) await rm(file, { force: true });
1423
+ else {
1424
+ await mkdir(dirname(file), { recursive: true });
1425
+ await writeFile(file, content);
1426
+ }
1427
+ } catch (error) {
1428
+ process.stderr.write(`write failed: ${path}: ${error instanceof Error ? error.message : error}
1429
+ `);
1430
+ if (done.length > 0) process.stderr.write(`already written: ${done.join(", ")}
1431
+ `);
1432
+ process.exitCode = 1;
1433
+ return;
1434
+ }
1435
+ done.push(path);
1436
+ }
1437
+ out.push(`applied: ${plan.changes.length} file changes`);
1438
+ } else out.push("dry run: nothing written; add --apply to write");
1439
+ process.stdout.write(`${out.join("\n")}
1440
+ `);
1441
+ }
1442
+ var handlers = {
1443
+ async "used-by"([ref], root) {
1444
+ if (!ref) throw new UsageError("used-by: missing <collection/slug>");
1445
+ const lines = usedBy(await loadContext(root), ref);
1446
+ process.stdout.write(lines.length > 0 ? `${lines.join("\n")}
1447
+ ` : `no entry references ${ref}
1448
+ `);
1449
+ },
1450
+ async rename([ref, slug], root, apply) {
1451
+ if (!ref || !slug) throw new UsageError("rename: expected <collection/slug> <new-slug>");
1452
+ await runPlan(root, planRenameRef(await loadContext(root), ref, slug), apply);
1453
+ },
1454
+ async remove([ref], root, apply) {
1455
+ if (!ref) throw new UsageError("remove: missing <collection/slug>");
1456
+ await runPlan(root, planRemoveRef(await loadContext(root), ref), apply);
1457
+ }
1458
+ };
1459
+ function parseCli() {
1460
+ try {
1461
+ return parseArgs({ allowPositionals: true, options: { root: { type: "string" }, apply: { type: "boolean" } } });
1462
+ } catch (error) {
1463
+ throw new UsageError(error instanceof Error ? error.message : String(error));
1464
+ }
1465
+ }
1466
+ try {
1467
+ const { values, positionals } = parseCli();
1468
+ const [command, ...args] = positionals;
1469
+ if (!command || !Object.hasOwn(handlers, command))
1470
+ throw new UsageError(command ? `Unknown command "${command}"` : "");
1471
+ await handlers[command](args, resolve2(values.root ?? process.cwd()), values.apply === true);
1472
+ } catch (error) {
1473
+ if (error instanceof UsageError) {
1474
+ process.stderr.write(`${error.message ? `${error.message}
1475
+ ` : ""}${USAGE}`);
1476
+ process.exitCode = 2;
1477
+ } else if (error instanceof EditletError) {
1478
+ reportIssues(error.issues);
1479
+ } else throw error;
1480
+ }