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,1061 @@
1
+ // skills/editlet/scripts/guard.ts
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync } from "node:fs";
4
+ import { basename, dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
5
+
6
+ // skills/editlet/scripts/shell.ts
7
+ function splitCommands(command) {
8
+ const commands = [];
9
+ const nested = [];
10
+ const substitution = (i) => {
11
+ let end;
12
+ if (command[i] === "`") {
13
+ end = i + 1;
14
+ while (end < command.length && command[end] !== "`") end += command[end] === "\\" ? 2 : 1;
15
+ } else if (command[i] === "$" && command[i + 1] === "(") {
16
+ let depth = 1;
17
+ end = i + 2;
18
+ for (; end < command.length; end++) {
19
+ if (command[end] === "(") depth++;
20
+ else if (command[end] === ")" && --depth === 0) break;
21
+ }
22
+ } else return null;
23
+ const stop = Math.min(end, command.length);
24
+ nested.push(...splitCommands(command.slice(i + (command[i] === "`" ? 1 : 2), stop)));
25
+ return stop;
26
+ };
27
+ let words = [];
28
+ let word = "";
29
+ let inWord = false;
30
+ const endWord = () => {
31
+ if (inWord) words.push(word);
32
+ word = "";
33
+ inWord = false;
34
+ };
35
+ const endCommand = () => {
36
+ endWord();
37
+ if (words.length > 0) commands.push(words);
38
+ words = [];
39
+ };
40
+ for (let i = 0; i < command.length; i++) {
41
+ const ch = command[i];
42
+ const sub = ch === "$" || ch === "`" ? substitution(i) : null;
43
+ if (sub !== null) {
44
+ inWord = true;
45
+ i = sub;
46
+ } else if (ch === "\\") {
47
+ if (command[i + 1] === "\n") i++;
48
+ else if (i + 1 < command.length) {
49
+ word += command[++i];
50
+ inWord = true;
51
+ }
52
+ } else if (ch === "'") {
53
+ const end = command.indexOf("'", i + 1);
54
+ const stop = end === -1 ? command.length : end;
55
+ word += command.slice(i + 1, stop);
56
+ inWord = true;
57
+ i = stop;
58
+ } else if (ch === '"') {
59
+ inWord = true;
60
+ for (i++; i < command.length && command[i] !== '"'; i++) {
61
+ if (command[i] === "\\" && i + 1 < command.length) i++;
62
+ else {
63
+ const inner = command[i] === "$" || command[i] === "`" ? substitution(i) : null;
64
+ if (inner !== null) {
65
+ i = inner;
66
+ continue;
67
+ }
68
+ }
69
+ word += command[i];
70
+ }
71
+ } else if (ch === " " || ch === " ") {
72
+ endWord();
73
+ } else if (ch === "\n" || ch === ";" || ch === "|" || ch === "(" || ch === ")") {
74
+ endCommand();
75
+ } else if (ch === "&") {
76
+ if (word.endsWith(">") || word.endsWith("<") || command[i + 1] === ">") {
77
+ word += ch;
78
+ inWord = true;
79
+ } else {
80
+ endCommand();
81
+ }
82
+ } else {
83
+ word += ch;
84
+ inWord = true;
85
+ }
86
+ }
87
+ endCommand();
88
+ return [...commands, ...nested];
89
+ }
90
+
91
+ // core/issues.ts
92
+ var EditletError = class extends Error {
93
+ issues;
94
+ constructor(issues, message) {
95
+ super(message ?? issues.map((i) => i.path ? `${i.path}: ${i.message}` : i.message).join("; "));
96
+ this.name = "EditletError";
97
+ this.issues = issues;
98
+ }
99
+ };
100
+
101
+ // core/paths.ts
102
+ var SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
103
+ function isValidSlug(slug) {
104
+ return SLUG_RE.test(slug);
105
+ }
106
+ function hasCollection(schema, collection) {
107
+ return Object.hasOwn(schema.collections, collection);
108
+ }
109
+ function entryFilePath(schema, collection, slug) {
110
+ const singleton = hasCollection(schema, collection) && schema.collections[collection].singleton;
111
+ return `${schema.contentDir}/${collection}/${singleton ? "index" : slug}.md`;
112
+ }
113
+ function isCanonicalPath(path) {
114
+ if (path === "" || /[\\\0:]/.test(path)) return false;
115
+ return path.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
116
+ }
117
+ function isHiddenContentPath(schema, path) {
118
+ const prefix = `${schema.contentDir}/`;
119
+ const rest = path.startsWith(prefix) ? path.slice(prefix.length) : path;
120
+ return rest.split("/").some((seg) => seg.startsWith("."));
121
+ }
122
+ function parseEntryPath(schema, path) {
123
+ const prefix = `${schema.contentDir}/`;
124
+ if (!path.startsWith(prefix) || !isCanonicalPath(path)) return null;
125
+ const parts = path.slice(prefix.length).split("/");
126
+ if (parts.length !== 2) return null;
127
+ const [collection, file] = parts;
128
+ if (!hasCollection(schema, collection) || !file.endsWith(".md")) return null;
129
+ const name = file.slice(0, -3);
130
+ if (name === "") return null;
131
+ if (schema.collections[collection].singleton) return file === "index.md" ? { collection, slug: "index" } : null;
132
+ return { collection, slug: name };
133
+ }
134
+ function resolveAssetPath(schema, entryFile, src) {
135
+ if (src === "" || src.startsWith("/") || src.includes("\\") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(src)) return null;
136
+ const srcSegs = src.split("/");
137
+ const last = srcSegs[srcSegs.length - 1];
138
+ if (last === "" || last === "." || last === "..") return null;
139
+ const out = entryFile.split("/").slice(0, -1);
140
+ for (const seg of srcSegs) {
141
+ if (seg === "" || seg === ".") continue;
142
+ if (seg === "..") {
143
+ if (out.length === 0) return null;
144
+ out.pop();
145
+ } else out.push(seg);
146
+ }
147
+ const result = out.join("/");
148
+ return result.startsWith(`${schema.contentDir}/`) ? result : null;
149
+ }
150
+ function refKey(collection, slug) {
151
+ return `${collection}/${slug}`;
152
+ }
153
+ var IMAGE_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "avif", "gif", "svg"];
154
+ function isImagePath(path) {
155
+ const name = path.slice(path.lastIndexOf("/") + 1);
156
+ const dot = name.lastIndexOf(".");
157
+ return dot > 0 && IMAGE_EXTENSIONS.includes(name.slice(dot + 1).toLowerCase());
158
+ }
159
+
160
+ // core/schema.ts
161
+ import { z as z2 } from "zod";
162
+
163
+ // core/fields.ts
164
+ import { z } from "zod";
165
+ function isStringValued(field) {
166
+ switch (field.type) {
167
+ case "string":
168
+ return !field.list;
169
+ case "select":
170
+ case "reference":
171
+ return !field.multiple;
172
+ case "text":
173
+ case "datetime":
174
+ case "url":
175
+ case "color":
176
+ return true;
177
+ default:
178
+ return false;
179
+ }
180
+ }
181
+ function isAbsentValue(field, value) {
182
+ return value === void 0 || value === null || value === "" && isStringValued(field);
183
+ }
184
+ function err(field, message) {
185
+ return (iss) => field.required && isAbsentValue(field, iss.input) ? "Required" : message;
186
+ }
187
+ function optional(field, schema, message) {
188
+ if (field.required) return schema;
189
+ return isStringValued(field) ? z.union([schema, z.literal("")], { error: message }).nullish() : schema.nullish();
190
+ }
191
+ function isUrl(v) {
192
+ return v.startsWith("/") || URL.canParse(v);
193
+ }
194
+ function noRepeats(message) {
195
+ return (items, ctx) => {
196
+ const seen = /* @__PURE__ */ new Set();
197
+ items.forEach((item, i) => {
198
+ if (seen.has(item)) ctx.addIssue({ code: "custom", path: [i], message: message(item) });
199
+ seen.add(item);
200
+ });
201
+ };
202
+ }
203
+ function listField(field, item, min, max, unique) {
204
+ const effective = Math.max(field.required ? 1 : 0, min);
205
+ let arr = z.array(item, { error: err(field, "Expected a list") });
206
+ if (effective > 0) {
207
+ arr = arr.min(effective, {
208
+ error: (iss) => Array.isArray(iss.input) && iss.input.length === 0 && field.required ? "Required" : `Must have at least ${effective}`
209
+ });
210
+ }
211
+ if (max !== void 0) arr = arr.max(max, { error: `Must have at most ${max}` });
212
+ return optional(field, unique ? arr.superRefine(noRepeats(unique)) : arr, "Expected a list");
213
+ }
214
+ var escapeRegex = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
215
+ function fieldsShape(fields) {
216
+ const shape = {};
217
+ for (const [key, field] of Object.entries(fields)) shape[key] = nestedValueSchema(field);
218
+ return shape;
219
+ }
220
+ function nestedValueSchema(field) {
221
+ if (field.type !== "markdown") return fieldValueSchema(field);
222
+ const base2 = z.string({ error: err(field, "Expected text") });
223
+ return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
224
+ }
225
+ function fieldValueSchema(field) {
226
+ switch (field.type) {
227
+ case "markdown":
228
+ return null;
229
+ case "object": {
230
+ const obj = z.strictObject(fieldsShape(field.fields), { error: err(field, "Expected an object") });
231
+ if (field.list) return listField(field, obj, field.min ?? 0, field.max);
232
+ return optional(field, obj, "");
233
+ }
234
+ case "blocks": {
235
+ const kinds = Object.keys(field.blocks);
236
+ const message = `Expected ${BLOCK_KEY}: ${kinds.join(", ")}`;
237
+ const options = Object.entries(field.blocks).map(
238
+ ([kind, block]) => z.strictObject({ [BLOCK_KEY]: z.literal(kind), ...fieldsShape(block.fields) })
239
+ );
240
+ const item = z.discriminatedUnion(BLOCK_KEY, options, {
241
+ error: message
242
+ });
243
+ return listField(field, item, field.min ?? 0, field.max);
244
+ }
245
+ case "string":
246
+ case "text": {
247
+ if (field.type === "string" && field.list) return listField(field, z.string({ error: "Expected text" }), 0);
248
+ const base2 = z.string({ error: err(field, "Expected text") });
249
+ return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
250
+ }
251
+ case "boolean":
252
+ return optional(field, z.boolean({ error: err(field, "Expected true or false") }), "");
253
+ case "select": {
254
+ const values = field.options.map((o) => o.value);
255
+ const message = `Expected one of: ${values.join(", ")}`;
256
+ if (field.multiple) return listField(field, z.enum(values, { error: message }), 0);
257
+ return optional(field, z.enum(values, { error: err(field, message) }), message);
258
+ }
259
+ case "number": {
260
+ let n = z.number({ error: err(field, "Expected a number") });
261
+ if (field.integer) n = n.int("Must be a whole number");
262
+ if (field.min !== void 0) n = n.min(field.min, `Must be at least ${field.min}`);
263
+ if (field.max !== void 0) n = n.max(field.max, `Must be at most ${field.max}`);
264
+ return optional(field, n, "");
265
+ }
266
+ case "datetime": {
267
+ const base2 = field.dateOnly ? z.iso.date({ error: err(field, "Invalid date") }) : z.iso.datetime({ offset: true, local: true, error: err(field, "Invalid date") });
268
+ return optional(field, base2, "Invalid date");
269
+ }
270
+ case "json": {
271
+ if (!field.required) return z.unknown().optional();
272
+ return z.union([z.string(), z.number(), z.boolean(), z.array(z.unknown()), z.record(z.string(), z.unknown())], {
273
+ error: "Required"
274
+ });
275
+ }
276
+ case "url": {
277
+ const message = "Must be an http(s) URL or start with /";
278
+ const base2 = z.string({ error: err(field, "Expected text") }).regex(/^(?:https?:\/\/|\/(?!\/))/i, { error: err(field, message) }).refine(isUrl, { error: message });
279
+ return optional(field, base2, message);
280
+ }
281
+ case "color": {
282
+ const message = "Must be a hex color like #a1b2c3";
283
+ const base2 = z.string({ error: err(field, "Expected text") }).regex(/^#[0-9a-fA-F]{6}$/, { error: err(field, message) });
284
+ return optional(field, base2, message);
285
+ }
286
+ case "image": {
287
+ const nonEmpty = z.string({ error: (iss) => iss.input === void 0 || iss.input === null ? "Required" : "Expected text" }).regex(/\S/, "Required");
288
+ const obj = z.strictObject({ src: nonEmpty, alt: nonEmpty }, { error: err(field, "Expected { src, alt }") });
289
+ return optional(field, obj, "");
290
+ }
291
+ case "reference": {
292
+ const message = `Must reference an entry in: ${field.collections.join(", ")}`;
293
+ const slug = SLUG_RE.source.slice(1, -1);
294
+ const ref = z.string({ error: err(field, 'Expected a reference like "collection/slug"') }).regex(new RegExp(`^(?:${field.collections.map(escapeRegex).join("|")})/${slug}$`), {
295
+ error: err(field, message)
296
+ });
297
+ if (field.multiple) return listField(field, ref, field.min ?? 0, field.max, (r) => `Duplicate reference: ${r}`);
298
+ return optional(field, ref, message);
299
+ }
300
+ }
301
+ }
302
+
303
+ // core/schema.ts
304
+ var BLOCK_KEY = "block";
305
+ var COMMIT_PLACEHOLDERS = ["action", "Action", "collection", "slug", "target"];
306
+ var TITLE_PLACEHOLDERS = ["branch", "name", "login"];
307
+ var REF_SEGMENTS = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
308
+ function isRefPath(value) {
309
+ return REF_SEGMENTS.test(value) && !value.includes("..") && !value.split("/").some((s) => s.endsWith(".lock"));
310
+ }
311
+ function template(placeholders, max) {
312
+ return z2.string().trim().min(1).max(max).refine((t) => !/[\r\n]/.test(t), "must be one line").superRefine((t, ctx) => {
313
+ for (const [, name] of t.matchAll(/\{([^{}]*)\}/g)) {
314
+ if (!placeholders.includes(name)) {
315
+ ctx.addIssue({
316
+ code: "custom",
317
+ message: `unknown placeholder "{${name}}" (use ${placeholders.map((p) => `{${p}}`).join(", ")})`
318
+ });
319
+ }
320
+ }
321
+ });
322
+ }
323
+ var gitSchema = z2.strictObject({
324
+ baseBranch: z2.string().min(1),
325
+ branchPrefix: z2.string().refine(
326
+ (p) => p.endsWith("/") && isRefPath(p.slice(0, -1)),
327
+ 'must be branch name segments ending in "/", for example "editlet/"'
328
+ ).optional(),
329
+ commitMessage: template(COMMIT_PLACEHOLDERS, 200).optional(),
330
+ pullRequest: z2.strictObject({
331
+ title: template(TITLE_PLACEHOLDERS, 256).optional(),
332
+ labels: z2.array(
333
+ z2.string().trim().min(1).max(50).refine((l) => !l.includes(","), 'must not contain ","')
334
+ ).max(10).optional(),
335
+ draft: z2.boolean().optional()
336
+ }).optional()
337
+ });
338
+ var IDENT = /^[a-zA-Z][a-zA-Z0-9]*$/;
339
+ var identMsg = "must start with a letter and contain only letters and digits";
340
+ var base = {
341
+ label: z2.string(),
342
+ hint: z2.string().optional(),
343
+ required: z2.boolean().optional()
344
+ };
345
+ var strOrList = z2.union([z2.string(), z2.array(z2.string())]);
346
+ var nestedFields = z2.lazy(
347
+ () => z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema).refine((o) => Object.keys(o).length > 0, "fields must not be empty")
348
+ );
349
+ var fieldSchema = z2.discriminatedUnion("type", [
350
+ z2.strictObject({ ...base, type: z2.literal("string"), list: z2.boolean().optional(), default: strOrList.optional() }),
351
+ z2.strictObject({
352
+ ...base,
353
+ type: z2.literal("text"),
354
+ rows: z2.number().int().positive().optional(),
355
+ default: z2.string().optional()
356
+ }),
357
+ z2.strictObject({ ...base, type: z2.literal("markdown") }),
358
+ z2.strictObject({
359
+ ...base,
360
+ type: z2.literal("boolean"),
361
+ default: z2.boolean().optional(),
362
+ labels: z2.strictObject({ true: z2.string(), false: z2.string() }).optional()
363
+ }),
364
+ z2.strictObject({
365
+ ...base,
366
+ type: z2.literal("select"),
367
+ options: z2.array(z2.strictObject({ label: z2.string(), value: z2.string() })).min(1, "options must not be empty"),
368
+ multiple: z2.boolean().optional(),
369
+ default: strOrList.optional()
370
+ }),
371
+ z2.strictObject({
372
+ ...base,
373
+ type: z2.literal("number"),
374
+ min: z2.number().optional(),
375
+ max: z2.number().optional(),
376
+ step: z2.number().optional(),
377
+ integer: z2.boolean().optional(),
378
+ default: z2.number().optional()
379
+ }),
380
+ z2.strictObject({
381
+ ...base,
382
+ type: z2.literal("datetime"),
383
+ dateOnly: z2.boolean().optional(),
384
+ defaultNow: z2.boolean().optional()
385
+ }),
386
+ z2.strictObject({ ...base, type: z2.literal("json") }),
387
+ z2.strictObject({ ...base, type: z2.literal("url") }),
388
+ z2.strictObject({ ...base, type: z2.literal("color"), default: z2.string().optional() }),
389
+ z2.strictObject({ ...base, type: z2.literal("image") }),
390
+ z2.strictObject({
391
+ ...base,
392
+ type: z2.literal("reference"),
393
+ collections: z2.array(z2.string()).min(1, "collections must not be empty"),
394
+ multiple: z2.boolean().optional(),
395
+ min: z2.number().int().nonnegative().optional(),
396
+ max: z2.number().int().nonnegative().optional()
397
+ }),
398
+ z2.strictObject({
399
+ ...base,
400
+ type: z2.literal("object"),
401
+ fields: nestedFields,
402
+ list: z2.boolean().optional(),
403
+ min: z2.number().int().nonnegative().optional(),
404
+ max: z2.number().int().nonnegative().optional()
405
+ }),
406
+ z2.strictObject({
407
+ ...base,
408
+ type: z2.literal("blocks"),
409
+ blocks: z2.record(
410
+ z2.string().regex(IDENT, `block key ${identMsg}`),
411
+ z2.strictObject({ label: z2.string(), fields: nestedFields })
412
+ ).refine((o) => Object.keys(o).length > 0, "blocks must not be empty"),
413
+ min: z2.number().int().nonnegative().optional(),
414
+ max: z2.number().int().nonnegative().optional()
415
+ })
416
+ ]);
417
+ var collectionSchema = z2.strictObject({
418
+ label: z2.string(),
419
+ singleton: z2.boolean().optional(),
420
+ titleField: z2.string().optional(),
421
+ slugFrom: z2.string().optional(),
422
+ fields: z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema)
423
+ });
424
+ function checkFields(schema, fields, at, nested, add) {
425
+ for (const [fk, f] of Object.entries(fields)) {
426
+ const path = [...at, fk];
427
+ if (fk === "draft" && !nested) add(path, 'field key "draft" is reserved for the draft flag');
428
+ if ("default" in f && f.default !== void 0) {
429
+ const checked = fieldValueSchema(f)?.safeParse(f.default);
430
+ for (const issue of checked?.success === false ? checked.error.issues : []) {
431
+ add([...path, "default", ...issue.path.map(String)], `default: ${issue.message}`);
432
+ }
433
+ }
434
+ if (f.type === "reference") {
435
+ f.collections.forEach((target, i) => {
436
+ if (!Object.hasOwn(schema.collections, target))
437
+ add([...path, "collections", i], `unknown collection "${target}"`);
438
+ });
439
+ if (!f.multiple && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require multiple: true");
440
+ }
441
+ if (f.type === "object") {
442
+ if (!f.list && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require list: true");
443
+ checkFields(schema, f.fields, [...path, "fields"], true, add);
444
+ }
445
+ if (f.type === "blocks") {
446
+ for (const [bk, block] of Object.entries(f.blocks)) {
447
+ if (Object.hasOwn(block.fields, BLOCK_KEY)) {
448
+ add([...path, "blocks", bk, "fields", BLOCK_KEY], `field key "${BLOCK_KEY}" is reserved for the block type`);
449
+ }
450
+ checkFields(schema, block.fields, [...path, "blocks", bk, "fields"], true, add);
451
+ }
452
+ }
453
+ if ((f.type === "reference" || f.type === "object" || f.type === "blocks") && f.min !== void 0 && f.max !== void 0 && f.min > f.max) {
454
+ add([...path, "min"], "min must not exceed max");
455
+ }
456
+ }
457
+ }
458
+ var schemaSchema = z2.strictObject({
459
+ $schema: z2.string().optional(),
460
+ contentDir: z2.string().min(1).refine(
461
+ isCanonicalPath,
462
+ 'must be a relative posix path without empty, "." or ".." segments, backslashes, NUL or ":"'
463
+ ),
464
+ git: gitSchema,
465
+ collections: z2.record(z2.string().regex(IDENT, `collection key ${identMsg}`), collectionSchema)
466
+ }).superRefine((schema, ctx) => {
467
+ const add = (path, message) => ctx.addIssue({ code: "custom", path, message });
468
+ const { baseBranch, branchPrefix } = schema.git;
469
+ if (branchPrefix !== void 0 && (baseBranch.startsWith(branchPrefix) || branchPrefix.startsWith(`${baseBranch}/`))) {
470
+ add(["git", "branchPrefix"], `branchPrefix "${branchPrefix}" clashes with the base branch "${baseBranch}"`);
471
+ }
472
+ const lowerKeys = /* @__PURE__ */ new Map();
473
+ for (const [ck, col] of Object.entries(schema.collections)) {
474
+ const other = lowerKeys.get(ck.toLowerCase());
475
+ if (other !== void 0) add(["collections", ck], `collection key "${ck}" differs from "${other}" only in case`);
476
+ else lowerKeys.set(ck.toLowerCase(), ck);
477
+ const fields = Object.entries(col.fields);
478
+ if (fields.filter(([, f]) => f.type === "markdown").length > 1) {
479
+ add(["collections", ck, "fields"], "a collection can have at most one markdown field");
480
+ }
481
+ if (col.titleField !== void 0 && !Object.hasOwn(col.fields, col.titleField)) {
482
+ add(["collections", ck, "titleField"], `titleField "${col.titleField}" is not a field of ${ck}`);
483
+ }
484
+ if (col.slugFrom !== void 0 && !Object.hasOwn(col.fields, col.slugFrom)) {
485
+ add(["collections", ck, "slugFrom"], `slugFrom "${col.slugFrom}" is not a field of ${ck}`);
486
+ }
487
+ checkFields(schema, col.fields, ["collections", ck, "fields"], false, add);
488
+ }
489
+ });
490
+ function toIssues(error) {
491
+ const out = [];
492
+ for (const issue of error.issues) {
493
+ let path = issue.path.map(String);
494
+ let message = issue.message;
495
+ if (issue.code === "invalid_union" && ("discriminator" in issue || path.at(-1) !== "type")) {
496
+ if (path.at(-1) !== "type") path = [...path, "type"];
497
+ message = "unknown field type";
498
+ }
499
+ if (issue.code === "unrecognized_keys") {
500
+ for (const key of issue.keys) out.push({ path: [...path, key].join("."), message: `unknown key "${key}"` });
501
+ continue;
502
+ }
503
+ out.push({ path: path.join("."), message });
504
+ }
505
+ return out;
506
+ }
507
+ function loadSchema(input) {
508
+ const parsed = schemaSchema.safeParse(input);
509
+ if (!parsed.success) throw new EditletError(toIssues(parsed.error));
510
+ return parsed.data;
511
+ }
512
+ function parseSchemaText(text, file) {
513
+ let json;
514
+ try {
515
+ json = JSON.parse(text);
516
+ } catch (error) {
517
+ throw new EditletError([
518
+ { file, path: "", message: `Invalid JSON: ${error instanceof Error ? error.message : error}` }
519
+ ]);
520
+ }
521
+ try {
522
+ return loadSchema(json);
523
+ } catch (error) {
524
+ if (error instanceof EditletError) throw new EditletError(error.issues.map((issue) => ({ ...issue, file })));
525
+ throw error;
526
+ }
527
+ }
528
+ function markdownFieldKey(collection) {
529
+ return Object.entries(collection.fields).find(([, f]) => f.type === "markdown")?.[0];
530
+ }
531
+
532
+ // core/gitStyle.ts
533
+ var DEFAULT_BRANCH_PREFIX = "editlet/";
534
+ var DEFAULT_COMMIT_MESSAGE = "{Action} {target}";
535
+ var DEFAULT_PULL_REQUEST_TITLE = "Update {branch}";
536
+ var DEFAULT_LABELS = ["editlet"];
537
+ function resolveGitStyle(git2) {
538
+ return {
539
+ branchPrefix: git2?.branchPrefix ?? DEFAULT_BRANCH_PREFIX,
540
+ commitMessage: git2?.commitMessage ?? DEFAULT_COMMIT_MESSAGE,
541
+ pullRequest: {
542
+ title: git2?.pullRequest?.title ?? DEFAULT_PULL_REQUEST_TITLE,
543
+ labels: [...git2?.pullRequest?.labels ?? DEFAULT_LABELS],
544
+ draft: git2?.pullRequest?.draft ?? false
545
+ }
546
+ };
547
+ }
548
+
549
+ // node/fs.ts
550
+ import { readdir, readFile } from "node:fs/promises";
551
+ import { join, resolve } from "node:path";
552
+ var DEFAULT_SCHEMA_PATH = "cms/schema.json";
553
+ async function loadProjectSchema(root, schemaPath) {
554
+ let raw;
555
+ try {
556
+ raw = await readFile(join(root, schemaPath), "utf8");
557
+ } catch (error) {
558
+ throw new EditletError([
559
+ { file: schemaPath, path: "", message: `Cannot read schema: ${error instanceof Error ? error.message : error}` }
560
+ ]);
561
+ }
562
+ return parseSchemaText(raw, schemaPath);
563
+ }
564
+ async function listFiles(root, contentDir) {
565
+ let dirents;
566
+ try {
567
+ dirents = await readdir(join(root, contentDir), { recursive: true, withFileTypes: true });
568
+ } catch (error) {
569
+ if (error.code === "ENOENT") return [];
570
+ throw error;
571
+ }
572
+ return dirents.filter((d) => d.isFile()).map((d) => `${relativeDir(root, d.parentPath)}/${d.name}`.split("\\").join("/")).toSorted();
573
+ }
574
+ function relativeDir(root, dir) {
575
+ return resolve(dir).slice(resolve(root).length + 1);
576
+ }
577
+
578
+ // node/project.ts
579
+ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
580
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
581
+
582
+ // core/generate.ts
583
+ import { z as z4 } from "zod";
584
+
585
+ // core/validate.ts
586
+ import { z as z3 } from "zod";
587
+
588
+ // core/walk.ts
589
+ var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
590
+ function blockFields(field, item) {
591
+ if (!isPlainObject(item)) return void 0;
592
+ const kind = item[BLOCK_KEY];
593
+ return typeof kind === "string" && Object.hasOwn(field.blocks, kind) ? field.blocks[kind].fields : void 0;
594
+ }
595
+ function children(field, value, path) {
596
+ if (field.type === "object") {
597
+ if (!field.list) return isPlainObject(value) ? [[field.fields, value, path]] : [];
598
+ if (!Array.isArray(value)) return [];
599
+ return value.flatMap((item, i) => isPlainObject(item) ? [[field.fields, item, [...path, i]]] : []);
600
+ }
601
+ if (field.type === "blocks") {
602
+ if (!Array.isArray(value)) return [];
603
+ return value.flatMap((item, i) => {
604
+ const fields = blockFields(field, item);
605
+ return fields ? [[fields, item, [...path, i]]] : [];
606
+ });
607
+ }
608
+ return [];
609
+ }
610
+ var isContainer = (field) => field.type === "object" || field.type === "blocks";
611
+ function visitFields(fields, data, visit, at = []) {
612
+ for (const [key, field] of Object.entries(fields)) {
613
+ if (!Object.hasOwn(data, key)) continue;
614
+ const path = [...at, key];
615
+ if (!isContainer(field)) {
616
+ visit(field, data[key], path);
617
+ continue;
618
+ }
619
+ for (const [childFields, child, childPath] of children(field, data[key], path)) {
620
+ visitFields(childFields, child, visit, childPath);
621
+ }
622
+ }
623
+ }
624
+
625
+ // core/validate.ts
626
+ function buildDataSchema(collection) {
627
+ const shape = {};
628
+ for (const [key, field] of Object.entries(collection.fields)) {
629
+ const s = fieldValueSchema(field);
630
+ if (s) shape[key] = s;
631
+ }
632
+ shape.draft = z3.boolean({ error: "Expected true or false" }).optional();
633
+ return z3.strictObject(shape);
634
+ }
635
+ function toIssues2(error, file) {
636
+ const out = [];
637
+ for (const issue of error.issues) {
638
+ const path = issue.path.map(String);
639
+ if (issue.code === "unrecognized_keys") {
640
+ for (const key of issue.keys) out.push({ file, path: [...path, key].join("."), message: "Unknown field" });
641
+ continue;
642
+ }
643
+ out.push({ file, path: path.join("."), message: issue.message });
644
+ }
645
+ return out;
646
+ }
647
+ function validateEntry(schema, entry, ctx = {}) {
648
+ if (!Object.hasOwn(schema.collections, entry.collection)) {
649
+ return [{ path: "", message: `Unknown collection "${entry.collection}"` }];
650
+ }
651
+ const collection = schema.collections[entry.collection];
652
+ const file = entryFilePath(schema, entry.collection, entry.slug);
653
+ if (collection.singleton ? entry.slug !== "index" : !isValidSlug(entry.slug)) {
654
+ const message = collection.singleton ? 'Slug of a singleton must be "index"' : `Invalid slug "${entry.slug}": use lowercase letters, digits and single hyphens`;
655
+ return [{ file, path: "", message }];
656
+ }
657
+ if (typeof entry.data !== "object" || entry.data === null || Array.isArray(entry.data)) {
658
+ return [{ file, path: "", message: "Entry data must be an object" }];
659
+ }
660
+ const parsed = buildDataSchema(collection).safeParse(entry.data);
661
+ const issues = parsed.success ? [] : toIssues2(parsed.error, file);
662
+ const mdKey = markdownFieldKey(collection);
663
+ if (mdKey === void 0) {
664
+ if (entry.body.trim() !== "") {
665
+ issues.push({ file, path: "", message: "This collection has no markdown field, but the entry has body content" });
666
+ }
667
+ } else if (collection.fields[mdKey].required && entry.body.trim() === "") {
668
+ issues.push({ file, path: mdKey, message: "Required" });
669
+ }
670
+ const shapeIssues = [...issues];
671
+ const bad = (key) => shapeIssues.some((i) => i.path === key || i.path.startsWith(`${key}.`) || key.startsWith(`${i.path}.`));
672
+ visitFields(collection.fields, entry.data, (field, value, at) => {
673
+ const key = at.join(".");
674
+ if (bad(key)) return;
675
+ if (field.type === "image" && value !== null && value !== void 0) {
676
+ const src = value.src;
677
+ const resolved = resolveAssetPath(schema, file, src);
678
+ if (resolved === null) {
679
+ issues.push({ file, path: `${key}.src`, message: "Image path points outside the content directory" });
680
+ } else if (!isImagePath(resolved)) {
681
+ issues.push({ file, path: `${key}.src`, message: "Image path must end in an image extension" });
682
+ } else if (isHiddenContentPath(schema, resolved)) {
683
+ issues.push({ file, path: `${key}.src`, message: 'Image path must not be hidden (a segment starts with ".")' });
684
+ } else if (ctx.fileExists?.(resolved) === false) {
685
+ issues.push({ file, path: `${key}.src`, message: `Image file not found: ${resolved}` });
686
+ }
687
+ } else if (field.type === "reference" && !isAbsentValue(field, value)) {
688
+ const refs = Array.isArray(value) ? value : [value];
689
+ refs.forEach((ref, i) => {
690
+ if (ctx.entryExists?.(ref) === false) {
691
+ issues.push({
692
+ file,
693
+ path: Array.isArray(value) ? `${key}.${i}` : key,
694
+ message: `Referenced entry not found: ${ref}`
695
+ });
696
+ }
697
+ });
698
+ }
699
+ });
700
+ return issues;
701
+ }
702
+
703
+ // core/entryFile.ts
704
+ import { parse, Schema as YamlSchema, stringify } from "yaml";
705
+ var YAML_11_SCALARS = new YamlSchema({ schema: "yaml-1.1" }).tags.filter((tag) => !tag.collection);
706
+ function fail(message) {
707
+ throw new EditletError([{ path: "", message }]);
708
+ }
709
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
710
+ function decodeUtf8(content, file) {
711
+ if (typeof content === "string") return { text: content };
712
+ try {
713
+ return { text: utf8.decode(content) };
714
+ } catch {
715
+ return { issue: { file, path: "", message: "File is not valid UTF-8" } };
716
+ }
717
+ }
718
+ function parseEntryFile(source) {
719
+ let text = source.startsWith("\uFEFF") ? source.slice(1) : source;
720
+ text = text.replace(/\r\n/g, "\n");
721
+ if (!text.startsWith("---\n")) return { data: {}, body: text };
722
+ const rest = text.slice(4);
723
+ const lines = rest.split("\n");
724
+ const close = lines.indexOf("---");
725
+ if (close === -1) fail('Frontmatter is not closed with a "---" line');
726
+ const yamlSrc = lines.slice(0, close).join("\n");
727
+ let body = lines.slice(close + 1).join("\n");
728
+ if (body.startsWith("\n")) body = body.slice(1);
729
+ let data;
730
+ try {
731
+ data = parse(yamlSrc, { schema: "core", logLevel: "error" });
732
+ } catch (error) {
733
+ fail(`Invalid YAML frontmatter: ${error instanceof Error ? error.message : String(error)}`);
734
+ }
735
+ if (data === null || data === void 0) data = {};
736
+ if (typeof data !== "object" || Array.isArray(data)) fail("Frontmatter must be a YAML mapping");
737
+ return { data, body };
738
+ }
739
+
740
+ // core/project.ts
741
+ var byFile = (a, b) => (a.file ?? "").localeCompare(b.file ?? "");
742
+ function isSkippedPath(schema, schemaPath, file) {
743
+ return file === schemaPath || isHiddenContentPath(schema, file) || isImagePath(file);
744
+ }
745
+ function entryCandidate(schema, file) {
746
+ return file.endsWith(".md") ? parseEntryPath(schema, file) : null;
747
+ }
748
+ function entriesFromFiles(schema, schemaPath, files) {
749
+ const entries = [];
750
+ const issues = [];
751
+ for (const [file, content] of files) {
752
+ if (isSkippedPath(schema, schemaPath, file)) continue;
753
+ const parsed = entryCandidate(schema, file);
754
+ if (!parsed) {
755
+ issues.push({ file, path: "", message: "Not an entry file" });
756
+ continue;
757
+ }
758
+ const decoded = decodeUtf8(content, file);
759
+ if ("issue" in decoded) {
760
+ issues.push(decoded.issue);
761
+ continue;
762
+ }
763
+ try {
764
+ const { data, body } = parseEntryFile(decoded.text);
765
+ entries.push({ collection: parsed.collection, slug: parsed.slug, data, body });
766
+ } catch (error) {
767
+ if (!(error instanceof EditletError)) throw error;
768
+ issues.push(...error.issues.map((issue) => ({ ...issue, file })));
769
+ }
770
+ }
771
+ const fileOf = (e) => entryFilePath(schema, e.collection, e.slug);
772
+ return {
773
+ entries: entries.toSorted((a, b) => fileOf(a).localeCompare(fileOf(b))),
774
+ issues: issues.toSorted(byFile)
775
+ };
776
+ }
777
+
778
+ // node/project.ts
779
+ async function readProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
780
+ const schema = await loadProjectSchema(root, schemaPath);
781
+ const files = await listFiles(root, schema.contentDir);
782
+ const contents = /* @__PURE__ */ new Map();
783
+ for (const file of files) {
784
+ if (isSkippedPath(schema, schemaPath, file)) continue;
785
+ contents.set(
786
+ file,
787
+ entryCandidate(schema, file) ? new Uint8Array(await readFile2(join2(root, file))) : new Uint8Array()
788
+ );
789
+ }
790
+ return { root, schema, ...entriesFromFiles(schema, schemaPath, contents) };
791
+ }
792
+ async function validateProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
793
+ const project = await readProject(root, schemaPath);
794
+ const { schema, entries } = project;
795
+ const refs = new Set(entries.map((e) => refKey(e.collection, e.slug)));
796
+ const files = new Set(await listFiles(root, schema.contentDir));
797
+ const issues = [...project.issues];
798
+ for (const entry of entries) {
799
+ issues.push(
800
+ ...validateEntry(schema, entry, { entryExists: (ref) => refs.has(ref), fileExists: (p) => files.has(p) })
801
+ );
802
+ }
803
+ return issues.toSorted(byFile);
804
+ }
805
+
806
+ // skills/editlet/scripts/guard.ts
807
+ var MAX_LINES = 20;
808
+ var GIT_GLOBAL_WITH_VALUE = /* @__PURE__ */ new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix"]);
809
+ var PUSH_WITH_VALUE = /* @__PURE__ */ new Set(["-o", "--push-option", "--repo", "--receive-pack", "--exec"]);
810
+ var KEYWORDS = /* @__PURE__ */ new Set([
811
+ "if",
812
+ "while",
813
+ "until",
814
+ "then",
815
+ "do",
816
+ "else",
817
+ "elif",
818
+ "!",
819
+ "time",
820
+ "nohup",
821
+ "command",
822
+ "exec",
823
+ "nice",
824
+ "xargs"
825
+ ]);
826
+ var WRAPPER_VALUE_FLAGS = {
827
+ sudo: ["-u", "-g", "-h", "-p", "-C", "-D", "-R", "-T", "-U"],
828
+ nice: ["-n"],
829
+ env: ["-u", "-C", "-S", "--unset", "--chdir"],
830
+ xargs: ["-n", "-I", "-L", "-P", "-s", "-d", "-E"],
831
+ timeout: ["-s", "-k"]
832
+ };
833
+ var deny = (reason) => ({ decision: "deny", reason });
834
+ function programOf(words) {
835
+ let i = 0;
836
+ for (; ; ) {
837
+ const raw = words[i];
838
+ if (raw === void 0) return null;
839
+ const word = raw.replace(/^[({]+/, "");
840
+ if (word === "" || word === "}" || KEYWORDS.has(word) || word === "sudo" || word === "env" || word === "timeout") {
841
+ i++;
842
+ if (word === "" || word === "}") continue;
843
+ const valueFlags = WRAPPER_VALUE_FLAGS[word] ?? [];
844
+ while (words[i]?.startsWith("-") || /^[A-Za-z_]\w*=/.test(words[i] ?? "")) {
845
+ i += valueFlags.includes(words[i]) ? 2 : 1;
846
+ }
847
+ if (word === "timeout" && /^[\d.]+[smhd]?$/.test(words[i] ?? "")) i++;
848
+ } else if (/^[A-Za-z_]\w*=/.test(word)) i++;
849
+ else return { program: basename(word), args: words.slice(i + 1) };
850
+ }
851
+ }
852
+ function formatIssue(issue) {
853
+ if (!issue.file) return `${issue.path || "(schema)"} \u2014 ${issue.message}`;
854
+ return issue.path ? `${issue.file}: ${issue.path} \u2014 ${issue.message}` : `${issue.file} \u2014 ${issue.message}`;
855
+ }
856
+ function commitDecision(env) {
857
+ const lines = env.validateCommit();
858
+ if (!lines) return null;
859
+ if (lines.length > 0) {
860
+ const shown = lines.slice(0, MAX_LINES);
861
+ if (lines.length > MAX_LINES) shown.push(`\u2026and ${lines.length - MAX_LINES} more`);
862
+ return deny(`Editlet content is invalid; fix these before committing:
863
+ ${shown.join("\n")}`);
864
+ }
865
+ const branch = env.currentBranch;
866
+ if (branch && !env.protectedBranches.includes(branch) && !branch.startsWith(env.branchPrefix)) {
867
+ return {
868
+ decision: "ask",
869
+ reason: `Editlet content change sets go to ${env.branchPrefix}<name> branches, and this commit is on ${branch}.`
870
+ };
871
+ }
872
+ return null;
873
+ }
874
+ function pushDecision(args, env) {
875
+ const positional = [];
876
+ let hasRepo = false;
877
+ let deleting = false;
878
+ for (let i = 0; i < args.length; i++) {
879
+ const arg = args[i];
880
+ if (arg === "--mirror" || arg === "--all") {
881
+ return deny(
882
+ `git push ${arg} is blocked by Editlet: it can overwrite protected branches. Push a ${env.branchPrefix}<name> branch.`
883
+ );
884
+ }
885
+ if (arg === "--delete" || arg === "-d") deleting = true;
886
+ if (arg === "--repo" || arg.startsWith("--repo=")) hasRepo = true;
887
+ if (PUSH_WITH_VALUE.has(arg)) i++;
888
+ else if (!arg.startsWith("-")) positional.push(arg);
889
+ }
890
+ const refspecs = hasRepo ? positional : positional.slice(1);
891
+ const targets = refspecs.length === 0 ? [env.currentBranch ?? ""] : refspecs.map((spec) => destination(spec, env));
892
+ for (const target of targets) {
893
+ const hit = target.includes("*") ? globMatches(target, env.protectedBranches) : env.protectedBranches.includes(target);
894
+ if (hit) {
895
+ const verb = deleting || refspecs.some((s) => s.startsWith(":")) ? "Deleting" : "Pushing to";
896
+ return deny(
897
+ `${verb} ${target} is blocked by Editlet: publish through a ${env.branchPrefix}<name> branch and a pull request.`
898
+ );
899
+ }
900
+ }
901
+ return null;
902
+ }
903
+ function globMatches(pattern, branches) {
904
+ const re = new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
905
+ return branches.some((branch) => re.test(branch));
906
+ }
907
+ function destination(spec, env) {
908
+ const stripped = spec.replace(/^\+/, "");
909
+ const colon = stripped.indexOf(":");
910
+ const dest = (colon === -1 ? stripped : stripped.slice(colon + 1)).replace(/^(refs\/)?heads\//, "");
911
+ return dest === "HEAD" ? env.currentBranch ?? "" : dest;
912
+ }
913
+ function gitDecision(args, env) {
914
+ let i = 0;
915
+ while (i < args.length && args[i].startsWith("-")) i += GIT_GLOBAL_WITH_VALUE.has(args[i]) ? 2 : 1;
916
+ const sub = args[i];
917
+ const rest = args.slice(i + 1);
918
+ if (sub === "push") return pushDecision(rest, env);
919
+ if (sub === "commit") return commitDecision(env);
920
+ return null;
921
+ }
922
+ var GH_GLOBAL_WITH_VALUE = /* @__PURE__ */ new Set(["-R", "--repo", "--hostname"]);
923
+ var GH_BODY_FLAGS = /* @__PURE__ */ new Set(["-f", "-F", "--field", "--raw-field", "--input"]);
924
+ function ghDecision(all) {
925
+ let i = 0;
926
+ while (i < all.length && all[i].startsWith("-")) i += GH_GLOBAL_WITH_VALUE.has(all[i]) ? 2 : 1;
927
+ const args = all.slice(i);
928
+ const [group, action] = args;
929
+ if (group === "pr" && action === "merge") {
930
+ if (args.some((a) => a === "--admin" || a.startsWith("--admin=") && a !== "--admin=false")) {
931
+ return deny("gh pr merge --admin bypasses branch protection and is blocked by Editlet.");
932
+ }
933
+ return {
934
+ decision: "ask",
935
+ reason: "Merging publishes the change. Merge only after the human explicitly approved this PR in chat."
936
+ };
937
+ }
938
+ if (group === "api") {
939
+ let method = null;
940
+ let body = false;
941
+ for (let j = 1; j < args.length; j++) {
942
+ const arg = args[j];
943
+ if (arg === "-X" || arg === "--method") method = args[++j] ?? method;
944
+ else if (arg.startsWith("--method=")) method = arg.slice("--method=".length);
945
+ else if (/^-X./.test(arg)) method = arg.slice(2);
946
+ else if (GH_BODY_FLAGS.has(arg) || /^(-f|-F).|^--(field|raw-field|input)=/.test(arg)) body = true;
947
+ }
948
+ const effective = (method ?? (body ? "POST" : "GET")).toUpperCase();
949
+ if (effective !== "GET" && args.slice(1).some((a) => a.includes("/protection"))) {
950
+ return deny("Changing branch protection through gh api is blocked by Editlet.");
951
+ }
952
+ }
953
+ return null;
954
+ }
955
+ function decide(command, env) {
956
+ let ask = null;
957
+ for (const words of splitCommands(command)) {
958
+ const parsed = programOf(words);
959
+ if (!parsed) continue;
960
+ const result = parsed.program === "git" ? gitDecision(parsed.args, env) : parsed.program === "gh" ? ghDecision(parsed.args) : null;
961
+ if (result?.decision === "deny") return result;
962
+ ask ??= result;
963
+ }
964
+ return ask;
965
+ }
966
+ function gitRaw(cwd, args) {
967
+ try {
968
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
969
+ } catch {
970
+ return null;
971
+ }
972
+ }
973
+ var git = (cwd, ...args) => gitRaw(cwd, args)?.trim() ?? null;
974
+ function findProjectRoot(cwd) {
975
+ const top = git(cwd, "rev-parse", "--show-toplevel");
976
+ let dir = resolve3(cwd);
977
+ for (; ; ) {
978
+ if (existsSync(join3(dir, DEFAULT_SCHEMA_PATH))) return dir;
979
+ if (top && dir === resolve3(top) || dirname2(dir) === dir) return null;
980
+ dir = dirname2(dir);
981
+ }
982
+ }
983
+ async function resolveEnv(cwd, command) {
984
+ const root = findProjectRoot(cwd);
985
+ const protectedBranches = /* @__PURE__ */ new Set(["main", "master"]);
986
+ let contentDir = null;
987
+ let branchPrefix = DEFAULT_BRANCH_PREFIX;
988
+ if (root) {
989
+ try {
990
+ const schema = await loadProjectSchema(root, DEFAULT_SCHEMA_PATH);
991
+ protectedBranches.add(schema.git.baseBranch);
992
+ contentDir = schema.contentDir;
993
+ branchPrefix = resolveGitStyle(schema.git).branchPrefix;
994
+ } catch {
995
+ }
996
+ }
997
+ const commitLines = root && /\bcommit\b/.test(command) ? await commitIssues(root, contentDir) : null;
998
+ const branch = git(cwd, "rev-parse", "--abbrev-ref", "HEAD");
999
+ return {
1000
+ protectedBranches: [...protectedBranches],
1001
+ currentBranch: branch && branch !== "HEAD" ? branch : null,
1002
+ branchPrefix,
1003
+ validateCommit: () => commitLines
1004
+ };
1005
+ }
1006
+ async function commitIssues(root, contentDir) {
1007
+ const status = gitRaw(root, ["status", "--porcelain", "--untracked-files=all", "--", "."]);
1008
+ if (status === null) return null;
1009
+ const prefix = git(root, "rev-parse", "--show-prefix") ?? "";
1010
+ const paths = status.split("\n").filter(Boolean).flatMap((line) => line.slice(3).split(" -> ")).map((p) => p.replace(/^"|"$/g, "")).map((p) => prefix && p.startsWith(prefix) ? p.slice(prefix.length) : p);
1011
+ const touches = paths.some(
1012
+ (p) => p === DEFAULT_SCHEMA_PATH || contentDir !== null && p.startsWith(`${contentDir.replace(/\/$/, "")}/`)
1013
+ );
1014
+ if (!touches) return null;
1015
+ try {
1016
+ return (await validateProject(root)).map(formatIssue);
1017
+ } catch (error) {
1018
+ if (error instanceof EditletError) return error.issues.map(formatIssue);
1019
+ throw error;
1020
+ }
1021
+ }
1022
+ function emit(d) {
1023
+ process.stdout.write(
1024
+ `${JSON.stringify({
1025
+ hookSpecificOutput: {
1026
+ hookEventName: "PreToolUse",
1027
+ permissionDecision: d.decision,
1028
+ permissionDecisionReason: d.reason
1029
+ }
1030
+ })}
1031
+ `
1032
+ );
1033
+ }
1034
+ async function readStdin() {
1035
+ const chunks = [];
1036
+ for await (const chunk of process.stdin) chunks.push(chunk);
1037
+ return Buffer.concat(chunks).toString("utf8");
1038
+ }
1039
+ async function main() {
1040
+ let input;
1041
+ try {
1042
+ input = JSON.parse(await readStdin());
1043
+ if (typeof input !== "object" || input === null) throw new Error("not an object");
1044
+ } catch {
1045
+ return emit(deny("Editlet guard could not read the hook input"));
1046
+ }
1047
+ if (input.tool_name !== "Bash") return;
1048
+ const command = input.tool_input?.command;
1049
+ if (typeof command !== "string") return emit(deny("Editlet guard could not read the hook input"));
1050
+ const cwd = typeof input.cwd === "string" ? input.cwd : process.cwd();
1051
+ try {
1052
+ const decision = decide(command, await resolveEnv(cwd, command));
1053
+ if (decision) emit(decision);
1054
+ } catch (error) {
1055
+ emit(deny(`Editlet guard failed: ${error instanceof Error ? error.message : String(error)}`));
1056
+ }
1057
+ }
1058
+ if (/^guard\.(ts|mjs)$/.test(basename(process.argv[1] ?? ""))) await main();
1059
+ export {
1060
+ decide
1061
+ };