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,235 @@
1
+ import { getAstroState } from "./shared.js";
2
+ import { EditletError } from "../core/issues.js";
3
+ import { entryFilePath, parseRefKey, refKey } from "../core/paths.js";
4
+ import { BLOCK_KEY, parseSchemaText } from "../core/schema.js";
5
+ import { normalizeData, validateEntry } from "../core/validate.js";
6
+ import { mapFields } from "../core/walk.js";
7
+ import { listFiles } from "../node/fs.js";
8
+ import { readProject } from "../node/project.js";
9
+ import { z } from "zod";
10
+ import { readFile } from "node:fs/promises";
11
+ import { join, resolve, sep } from "node:path";
12
+ import { readFileSync } from "node:fs";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import { defineCollection } from "astro/content/config";
15
+ // astro/content.ts
16
+ /**
17
+ * Astro content layer for Editlet (`editlet/astro/content`): one loader per schema collection. Entries are
18
+ * validated with the core rules (the same as the admin and `editlet:validate`), not with Astro's `parseData`.
19
+ */
20
+ function toAstroRef(ref) {
21
+ if (typeof ref !== "string") return ref;
22
+ const parsed = parseRefKey(ref);
23
+ return parsed ? {
24
+ collection: parsed.collection,
25
+ id: parsed.slug
26
+ } : ref;
27
+ }
28
+ /**
29
+ * `normalizeData` output in the shape Astro expects: image `src` becomes an `__ASTRO_IMAGE_` import (resolved by the
30
+ * store relative to the entry file), references become `{ collection, id }` like Astro's `reference()`.
31
+ */
32
+ function toAstroData(collection, data) {
33
+ return mapFields(collection.fields, normalizeData(collection, data), (field, value) => {
34
+ if (field.type === "image" && typeof value === "object" && value !== null) {
35
+ const image = value;
36
+ if (typeof image.src !== "string") return value;
37
+ const src = image.src.startsWith(".") ? image.src : `./${image.src}`;
38
+ return {
39
+ ...image,
40
+ src: `__ASTRO_IMAGE_${src}`
41
+ };
42
+ }
43
+ if (field.type === "reference") return Array.isArray(value) ? value.map(toAstroRef) : toAstroRef(value);
44
+ return value;
45
+ });
46
+ }
47
+ const quote = (v) => `'${v.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
48
+ const array = (type) => type.includes(" | ") ? `(${type})[]` : `${type}[]`;
49
+ function fieldType(field) {
50
+ switch (field.type) {
51
+ case "string": return field.list ? "string[]" : "string";
52
+ case "text":
53
+ case "url":
54
+ case "color":
55
+ case "datetime":
56
+ case "markdown": return "string";
57
+ case "boolean": return "boolean";
58
+ case "number": return "number";
59
+ case "json": return "unknown";
60
+ case "select": {
61
+ const union = field.options.map((o) => quote(o.value)).join(" | ");
62
+ return field.multiple ? array(union) : union;
63
+ }
64
+ case "image": return "{ src: import('astro').ImageMetadata; alt: string }";
65
+ case "reference": {
66
+ const union = field.collections.map((c) => `{ collection: ${quote(c)}; id: string }`).join(" | ");
67
+ return field.multiple ? array(union) : union;
68
+ }
69
+ case "object": {
70
+ const type = objectType(field.fields);
71
+ return field.list ? `${type}[]` : type;
72
+ }
73
+ case "blocks": return array(Object.entries(field.blocks).map(([kind, block]) => objectType(block.fields, `${BLOCK_KEY}: ${quote(kind)}`)).join(" | "));
74
+ }
75
+ }
76
+ /** Inline type of nested fields; a nested `markdown` is a string. */
77
+ function objectType(fields, first) {
78
+ const parts = first === void 0 ? [] : [first];
79
+ for (const [key, field] of Object.entries(fields)) parts.push(`${key}${field.required ? "" : "?"}: ${fieldType(field)}`);
80
+ return `{ ${parts.join("; ")} }`;
81
+ }
82
+ /** TS module source for `createSchema().types`: the `Entry` type is what `CollectionEntry<…>['data']` becomes. */
83
+ function astroTypes(collection) {
84
+ const lines = ["export type Entry = {"];
85
+ for (const [key, field] of Object.entries(collection.fields)) {
86
+ if (field.type === "markdown") continue;
87
+ lines.push(` ${key}${field.required ? "" : "?"}: ${fieldType(field)};`);
88
+ }
89
+ lines.push(" draft?: boolean;", "};");
90
+ return `${lines.join("\n")}\n`;
91
+ }
92
+ function formatIssue(issue) {
93
+ if (!issue.file) return `${issue.path || "(schema)"} — ${issue.message}`;
94
+ return issue.path ? `${issue.file}: ${issue.path} — ${issue.message}` : `${issue.file} — ${issue.message}`;
95
+ }
96
+ /** One issue per line, `<file>: <path> — <message>` (the `editlet:validate` format). */
97
+ function formatIssues(issues) {
98
+ return issues.map(formatIssue).join("\n");
99
+ }
100
+ function schemaPathOf(options) {
101
+ return options.schemaPath ?? getAstroState()?.schemaPath ?? "cms/schema.json";
102
+ }
103
+ function schemaError(issues) {
104
+ return /* @__PURE__ */ new Error(`Editlet: invalid schema\n${formatIssues(issues)}`);
105
+ }
106
+ function readSchemaSync(root, schemaPath) {
107
+ let text;
108
+ try {
109
+ text = readFileSync(join(root, schemaPath), "utf8");
110
+ } catch (error) {
111
+ throw new Error(`Editlet: cannot read schema ${schemaPath}: ${error instanceof Error ? error.message : error}`, { cause: error });
112
+ }
113
+ try {
114
+ return parseSchemaText(text, schemaPath);
115
+ } catch (error) {
116
+ if (error instanceof EditletError) throw schemaError(error.issues);
117
+ throw error;
118
+ }
119
+ }
120
+ function collectionOf(schema, collection, schemaPath) {
121
+ if (!Object.hasOwn(schema.collections, collection)) throw new Error(`Editlet: unknown collection "${collection}" in ${schemaPath}`);
122
+ return schema.collections[collection];
123
+ }
124
+ /** Per watcher: one set of listeners, re-sync callbacks keyed by Astro collection (repeated `load()` replaces). */
125
+ const watched = /* @__PURE__ */ new WeakMap();
126
+ function watch(watcher, key, dir, resync) {
127
+ let subs = watched.get(watcher);
128
+ if (!subs) {
129
+ const all = /* @__PURE__ */ new Map();
130
+ const onEvent = (path) => {
131
+ const abs = resolve(path);
132
+ for (const sub of all.values()) if (abs === sub.dir || abs.startsWith(sub.dir + sep)) sub.resync();
133
+ };
134
+ for (const event of [
135
+ "add",
136
+ "change",
137
+ "unlink"
138
+ ]) watcher.on(event, onEvent);
139
+ watched.set(watcher, all);
140
+ subs = all;
141
+ }
142
+ subs.set(key, {
143
+ dir,
144
+ resync
145
+ });
146
+ watcher.add(dir);
147
+ }
148
+ /** Content loader for one Editlet collection. Do not give the Astro collection a `schema`. */
149
+ function editletLoader(collection, options = {}) {
150
+ /** Absolute content directory, known once the schema has been read (even if the entries then fail). */
151
+ let contentDir;
152
+ async function sync(ctx, root) {
153
+ const schemaPath = schemaPathOf(options);
154
+ let project;
155
+ try {
156
+ project = await readProject(root, schemaPath);
157
+ } catch (error) {
158
+ if (error instanceof EditletError) throw schemaError(error.issues);
159
+ throw error;
160
+ }
161
+ const { schema } = project;
162
+ contentDir = join(root, schema.contentDir);
163
+ const col = collectionOf(schema, collection, schemaPath);
164
+ const prefix = `${schema.contentDir}/${collection}/`;
165
+ const refs = new Set(project.entries.map((e) => refKey(e.collection, e.slug)));
166
+ const files = new Set(await listFiles(root, schema.contentDir));
167
+ const own = project.entries.filter((e) => e.collection === collection);
168
+ const issues = project.issues.filter((i) => i.file?.startsWith(prefix));
169
+ for (const entry of own) issues.push(...validateEntry(schema, entry, {
170
+ entryExists: (ref) => refs.has(ref),
171
+ fileExists: (p) => files.has(p)
172
+ }));
173
+ if (issues.length > 0) {
174
+ const sorted = issues.toSorted((a, b) => (a.file ?? "").localeCompare(b.file ?? ""));
175
+ throw new Error(`Editlet: invalid content in "${collection}"\n${formatIssues(sorted)}`);
176
+ }
177
+ const dev = getAstroState()?.command === "dev";
178
+ const schemaText = JSON.stringify(col);
179
+ const records = [];
180
+ for (const entry of own) {
181
+ if (entry.data.draft === true && !dev) continue;
182
+ const filePath = entryFilePath(schema, collection, entry.slug);
183
+ const fileText = await readFile(join(root, filePath), "utf8");
184
+ const rendered = entry.body.trim() !== "" ? await ctx.renderMarkdown(entry.body, { fileURL: pathToFileURL(join(root, filePath)) }) : void 0;
185
+ records.push({
186
+ id: entry.slug,
187
+ data: toAstroData(col, entry.data),
188
+ body: entry.body,
189
+ filePath,
190
+ digest: ctx.generateDigest(`${schemaText}\n${fileText}`),
191
+ rendered,
192
+ assetImports: rendered?.metadata?.imagePaths
193
+ });
194
+ }
195
+ const seen = new Set(records.map((r) => r.id));
196
+ for (const record of records) {
197
+ const old = ctx.store.get(record.id);
198
+ if (old?.assetImports?.length && old.digest !== record.digest) ctx.store.delete(record.id);
199
+ ctx.store.set(record);
200
+ }
201
+ for (const id of ctx.store.keys()) if (!seen.has(id)) ctx.store.delete(id);
202
+ }
203
+ return {
204
+ name: "editlet",
205
+ createSchema: async () => {
206
+ const root = getAstroState()?.root ?? process.cwd();
207
+ const schemaPath = schemaPathOf(options);
208
+ const col = collectionOf(readSchemaSync(root, schemaPath), collection, schemaPath);
209
+ return {
210
+ schema: z.record(z.string(), z.unknown()),
211
+ types: astroTypes(col)
212
+ };
213
+ },
214
+ load: async (ctx) => {
215
+ const root = fileURLToPath(ctx.config.root);
216
+ try {
217
+ await sync(ctx, root);
218
+ } finally {
219
+ if (ctx.watcher && contentDir !== void 0) {
220
+ let queue = Promise.resolve();
221
+ const resync = () => {
222
+ queue = queue.then(() => sync(ctx, root).catch((error) => ctx.logger.error(error instanceof Error ? error.message : String(error))));
223
+ };
224
+ watch(ctx.watcher, ctx.collection, contentDir, resync);
225
+ }
226
+ }
227
+ }
228
+ };
229
+ }
230
+ /** One Astro collection per schema collection, for `export const collections = editletCollections()`. */
231
+ function editletCollections(options = {}) {
232
+ const schema = readSchemaSync(getAstroState()?.root ?? process.cwd(), schemaPathOf(options));
233
+ return Object.fromEntries(Object.keys(schema.collections).map((key) => [key, defineCollection({ loader: editletLoader(key, options) })]));
234
+ }
235
+ export { astroTypes, editletCollections, editletLoader, formatIssues, toAstroData };
@@ -0,0 +1,89 @@
1
+ import { sendWebResponse, toWebRequest } from "./nodeBridge.js";
2
+ import { createDevHandler } from "../node/devHandler.js";
3
+ import "../core/devApi.js";
4
+ import { DEFAULT_ADMIN_URL } from "../loader/protocol.js";
5
+ import "../node/index.js";
6
+ import { readFile, realpath, stat } from "node:fs/promises";
7
+ import { extname, join, resolve, sep } from "node:path";
8
+ import { existsSync } from "node:fs";
9
+ // astro/devServer.ts
10
+ /** `DEFAULT_ADMIN_URL` without its trailing slash: `/editlet`. */
11
+ const CONTENT_TYPES = {
12
+ ".html": "text/html; charset=utf-8",
13
+ ".js": "text/javascript; charset=utf-8",
14
+ ".css": "text/css; charset=utf-8",
15
+ ".json": "application/json",
16
+ ".map": "application/json",
17
+ ".svg": "image/svg+xml",
18
+ ".png": "image/png",
19
+ ".webp": "image/webp",
20
+ ".woff2": "font/woff2"
21
+ };
22
+ /** Folder served at `/editlet/`: the built admin (`admin/dist/`) when it has an `index.html`, else the stub page. */
23
+ function adminDir() {
24
+ const dist = join(import.meta.dirname, "../admin/dist");
25
+ return existsSync(join(dist, "index.html")) ? dist : join(import.meta.dirname, "stub");
26
+ }
27
+ /**
28
+ * Connect-style middleware for `astro dev`: `/__editlet[/*]` → the dev file API, `/editlet/*` → static
29
+ * files of `adminDir`. Everything else goes to `next`.
30
+ */
31
+ function createDevMiddleware(opts) {
32
+ let handler;
33
+ const api = () => handler ??= createDevHandler({
34
+ root: opts.root,
35
+ schemaPath: opts.schemaPath
36
+ });
37
+ return (req, res, next) => {
38
+ const path = (req.url ?? "/").split("?")[0];
39
+ if (path === "/__editlet" || path.startsWith(`/__editlet/`)) devApi(api(), req, res).catch(next);
40
+ else if (path.startsWith("/editlet/")) adminFile(opts.adminDir, path.slice(DEFAULT_ADMIN_URL.length), req, res).catch(next);
41
+ else next();
42
+ };
43
+ }
44
+ async function devApi(handler, req, res) {
45
+ const abort = new AbortController();
46
+ res.on("close", () => {
47
+ if (!res.writableFinished) abort.abort();
48
+ });
49
+ await sendWebResponse(res, await handler(toWebRequest(req, abort.signal)));
50
+ }
51
+ function notFound(res) {
52
+ res.statusCode = 404;
53
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
54
+ res.end("Not found");
55
+ }
56
+ /** Absolute path of `rel` (URL-encoded) inside `dir`, or `null` when it is malformed or escapes `dir`. */
57
+ async function resolveInside(dir, rel) {
58
+ let decoded;
59
+ try {
60
+ decoded = decodeURIComponent(rel === "" ? "index.html" : rel);
61
+ } catch {
62
+ return null;
63
+ }
64
+ if (decoded.includes("\0")) return null;
65
+ const base = await realpath(dir);
66
+ try {
67
+ const file = await realpath(resolve(base, decoded));
68
+ return file.startsWith(base + sep) ? file : null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+ async function adminFile(dir, rel, req, res) {
74
+ if (req.method !== "GET" && req.method !== "HEAD") {
75
+ res.statusCode = 405;
76
+ res.setHeader("Allow", "GET, HEAD");
77
+ res.end();
78
+ return;
79
+ }
80
+ const file = await resolveInside(dir, rel);
81
+ if (file === null || !(await stat(file)).isFile()) return notFound(res);
82
+ const body = await readFile(file);
83
+ res.statusCode = 200;
84
+ res.setHeader("Content-Type", CONTENT_TYPES[extname(file).toLowerCase()] ?? "application/octet-stream");
85
+ res.setHeader("Content-Length", body.length);
86
+ res.setHeader("Cache-Control", "no-cache");
87
+ res.end(req.method === "HEAD" ? void 0 : body);
88
+ }
89
+ export { adminDir, createDevMiddleware };
@@ -0,0 +1,15 @@
1
+ import { AdminConfigOptions } from "../admin/config.js";
2
+ import { AstroIntegration } from "astro";
3
+ export interface EditletAstroOptions {
4
+ /** Schema file relative to the Astro project root. Default `cms/schema.json`. */
5
+ schemaPath?: string;
6
+ /** Public admin config (`config.json` in the build). Everything here ends up public. */
7
+ admin?: AdminConfigOptions;
8
+ }
9
+ /**
10
+ * Page script: the loader on the site's query parameter (`editlet` unless `admin.param` or `EDITLET_PARAM` says
11
+ * otherwise), re-synced after every client-side navigation (`<ClientRouter />`).
12
+ */
13
+ export declare function loaderScript(param: string): string;
14
+ /** Astro integration: the `?editlet` loader on every page, dev file API + admin in `astro dev`, admin folder in the build. */
15
+ export default function editlet(options?: EditletAstroOptions): AstroIntegration;
@@ -0,0 +1,98 @@
1
+ import { adminDir, createDevMiddleware } from "./devServer.js";
2
+ import { setAstroState } from "./shared.js";
3
+ import { ADMIN_CONFIG_FILE, buildAdminConfig, resolveParam } from "../admin/config.js";
4
+ import { DEFAULT_ADMIN_URL } from "../loader/protocol.js";
5
+ import { loadProjectSchema } from "../node/fs.js";
6
+ import { readFile, readdir } from "node:fs/promises";
7
+ import { join, relative, resolve, sep } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ // astro/index.ts
10
+ /**
11
+ * Page script: the loader on the site's query parameter (`editlet` unless `admin.param` or `EDITLET_PARAM` says
12
+ * otherwise), re-synced after every client-side navigation (`<ClientRouter />`).
13
+ */
14
+ function loaderScript(param) {
15
+ return `import { mountEditletLoader } from 'editlet/loader'; const l = mountEditletLoader({ param: ${JSON.stringify(param)} }); document.addEventListener('astro:page-load', () => l.sync());`;
16
+ }
17
+ /** `DEFAULT_ADMIN_URL` without slashes: the build output folder of the admin (`editlet`). */
18
+ const ADMIN_OUT_DIR = DEFAULT_ADMIN_URL.replace(/^\/|\/$/g, "");
19
+ function adminEmitPlugin(config) {
20
+ return {
21
+ name: "editlet:admin",
22
+ apply: "build",
23
+ applyToEnvironment: (env) => env.name === "client",
24
+ async generateBundle() {
25
+ const dir = adminDir();
26
+ const entries = await readdir(dir, {
27
+ recursive: true,
28
+ withFileTypes: true
29
+ });
30
+ for (const entry of entries) {
31
+ if (!entry.isFile()) continue;
32
+ const file = join(entry.parentPath, entry.name);
33
+ const rel = relative(dir, file).split(sep).join("/");
34
+ this.emitFile({
35
+ type: "asset",
36
+ fileName: `${ADMIN_OUT_DIR}/${rel}`,
37
+ source: await readFile(file)
38
+ });
39
+ }
40
+ this.emitFile({
41
+ type: "asset",
42
+ fileName: `${ADMIN_OUT_DIR}/${ADMIN_CONFIG_FILE}`,
43
+ source: `${JSON.stringify(config, null, 2)}\n`
44
+ });
45
+ }
46
+ };
47
+ }
48
+ /**
49
+ * `.env*` of the project for `mode` (Astro does not load them into `process.env` at config time), with `process.env`
50
+ * on top. Through Astro's own `vite`; without it, `process.env` alone.
51
+ */
52
+ async function buildEnv(mode, root) {
53
+ try {
54
+ const { loadEnv } = await import("vite");
55
+ return {
56
+ ...loadEnv(mode, root, ""),
57
+ ...process.env
58
+ };
59
+ } catch {
60
+ return process.env;
61
+ }
62
+ }
63
+ /** Astro integration: the `?editlet` loader on every page, dev file API + admin in `astro dev`, admin folder in the build. */
64
+ function editlet(options = {}) {
65
+ const schemaPath = options.schemaPath ?? "cms/schema.json";
66
+ let root = process.cwd();
67
+ return {
68
+ name: "editlet",
69
+ hooks: {
70
+ "astro:config:setup": async ({ command, config, injectScript, addWatchFile, updateConfig }) => {
71
+ root = resolve(fileURLToPath(config.root));
72
+ setAstroState({
73
+ root,
74
+ schemaPath,
75
+ command
76
+ });
77
+ const env = await buildEnv(command === "build" ? "production" : "development", root);
78
+ injectScript("page", loaderScript(resolveParam(options.admin, env)));
79
+ addWatchFile(pathToFileURL(join(root, schemaPath)));
80
+ if (command === "build") {
81
+ const baseBranch = (await loadProjectSchema(root, schemaPath)).git.baseBranch;
82
+ updateConfig({ vite: { plugins: [adminEmitPlugin(buildAdminConfig(options.admin, {
83
+ baseBranch,
84
+ env
85
+ }))] } });
86
+ }
87
+ },
88
+ "astro:server:setup": ({ server }) => {
89
+ server.middlewares.use(createDevMiddleware({
90
+ root,
91
+ schemaPath,
92
+ adminDir: adminDir()
93
+ }));
94
+ }
95
+ }
96
+ };
97
+ }
98
+ export { editlet as default, loaderScript };
@@ -0,0 +1,36 @@
1
+ import { Readable } from "node:stream";
2
+ // astro/nodeBridge.ts
3
+ /**
4
+ * Web `Request` for a Node request. The URL is built from the real `Host` header (the dev API's DNS-rebinding guard
5
+ * reads the host from the URL), and the body is streamed for methods that carry one. `signal` lets the caller abort
6
+ * the request when the client goes away.
7
+ */
8
+ function toWebRequest(req, signal) {
9
+ const headers = new Headers();
10
+ for (const [key, value] of Object.entries(req.headers)) {
11
+ if (value === void 0 || key.startsWith(":")) continue;
12
+ for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
13
+ }
14
+ const method = req.method ?? "GET";
15
+ const hasBody = method !== "GET" && method !== "HEAD";
16
+ const host = req.headers.host ?? req.headers[":authority"] ?? "invalid.invalid";
17
+ const proto = req.socket?.encrypted ? "https" : "http";
18
+ return new Request(new URL(req.url ?? "/", `${proto}://${host}`), {
19
+ method,
20
+ headers,
21
+ signal,
22
+ body: hasBody ? Readable.toWeb(req) : void 0,
23
+ duplex: hasBody ? "half" : void 0
24
+ });
25
+ }
26
+ /** Writes a Web `Response` to a Node response (every `Set-Cookie` kept as its own header). */
27
+ async function sendWebResponse(res, response) {
28
+ res.statusCode = response.status;
29
+ response.headers.forEach((value, key) => {
30
+ if (key !== "set-cookie") res.setHeader(key, value);
31
+ });
32
+ const cookies = response.headers.getSetCookie();
33
+ if (cookies.length > 0) res.setHeader("set-cookie", cookies);
34
+ res.end(response.body ? Buffer.from(await response.arrayBuffer()) : void 0);
35
+ }
36
+ export { sendWebResponse, toWebRequest };
@@ -0,0 +1,10 @@
1
+ // astro/shared.ts
2
+ const DEFAULT_SCHEMA_PATH = "cms/schema.json";
3
+ const SLOT = Symbol.for("editlet.astro");
4
+ function setAstroState(s) {
5
+ globalThis[SLOT] = s;
6
+ }
7
+ function getAstroState() {
8
+ return globalThis[SLOT];
9
+ }
10
+ export { DEFAULT_SCHEMA_PATH, getAstroState, setAstroState };
@@ -0,0 +1,71 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Editlet</title>
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ padding: 2rem;
11
+ font:
12
+ 15px/1.5 system-ui,
13
+ sans-serif;
14
+ background: #fff;
15
+ color: #222;
16
+ }
17
+ code {
18
+ background: #f2f2f2;
19
+ padding: 0 0.25em;
20
+ border-radius: 4px;
21
+ }
22
+ button {
23
+ font: inherit;
24
+ padding: 0.4rem 0.9rem;
25
+ }
26
+ </style>
27
+ </head>
28
+ <body>
29
+ <h1>Editlet admin</h1>
30
+ <p>
31
+ This is a placeholder. The real admin is not built yet: run the admin build so
32
+ <code>editlet/admin/dist/</code> exists, and the adapter serves it here instead.
33
+ </p>
34
+ <p>Mode: <b id="mode">…</b> · Route: <b id="route">…</b></p>
35
+ <button id="close" type="button">Close</button>
36
+ <script type="module">
37
+ // Minimal admin side of the frozen loader protocol (packages/editlet/loader/protocol.ts), inlined so the
38
+ // placeholder needs no build step.
39
+ const SOURCE = 'editlet';
40
+ const V = 1;
41
+ const embedded = window.parent !== window;
42
+ const $ = (id) => document.getElementById(id);
43
+ let pinned = null;
44
+
45
+ const send = (body) => {
46
+ if (embedded && pinned) window.parent.postMessage({ source: SOURCE, v: V, ...body }, pinned);
47
+ };
48
+ const showRoute = (route) => ($('route').textContent = route === '' ? '(root)' : route);
49
+ showRoute(new URL(location.href).searchParams.get('editlet') ?? '');
50
+
51
+ fetch('/__editlet/files').then(
52
+ (res) => ($('mode').textContent = res.ok ? 'local (dev file API)' : 'github'),
53
+ () => ($('mode').textContent = 'github'),
54
+ );
55
+
56
+ $('close').addEventListener('click', () => send({ type: 'close' }));
57
+ window.addEventListener('keydown', (e) => e.key === 'Escape' && send({ type: 'close' }));
58
+ window.addEventListener('message', (e) => {
59
+ const m = e.data;
60
+ if (!embedded || e.source !== window.parent || m?.source !== SOURCE || m.v !== V) return;
61
+ if (pinned === null) {
62
+ if (m.type !== 'init' || e.origin !== location.origin) return;
63
+ pinned = e.origin;
64
+ } else if (e.origin !== pinned) return;
65
+ if (m.type === 'init' || m.type === 'navigate') showRoute(m.route);
66
+ else if (m.type === 'close-request') send({ type: 'close' });
67
+ });
68
+ if (embedded) window.parent.postMessage({ source: SOURCE, v: V, type: 'ready' }, '*');
69
+ </script>
70
+ </body>
71
+ </html>
@@ -0,0 +1,24 @@
1
+ export interface AuthSession {
2
+ accessToken: string;
3
+ tokenType: string;
4
+ /** Epoch ms on the browser clock. `null` means the token never expires. */
5
+ expiresAt: number | null;
6
+ refreshToken: string | null;
7
+ refreshTokenExpiresAt: number | null;
8
+ }
9
+ export declare class AuthError extends Error {
10
+ code: string;
11
+ description?: string;
12
+ constructor(code: string, description?: string);
13
+ }
14
+ /** Call synchronously from a click handler, before any `await`, or popup blockers will stop it. */
15
+ export declare function startLogin(options: {
16
+ workerUrl: string;
17
+ timeoutMs?: number;
18
+ }): Promise<AuthSession>;
19
+ /** Refresh tokens are single-use: store the returned session, including its new refresh token. */
20
+ export declare function refresh(options: {
21
+ workerUrl: string;
22
+ refreshToken: string;
23
+ }): Promise<AuthSession>;
24
+ export declare function needsRefresh(session: AuthSession, now?: number): boolean;