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