astronaut-cms 0.0.1 → 1.0.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -3
  3. package/dist/admin/THIRD_PARTY_LICENSES.md +7598 -0
  4. package/dist/admin/assets/assistant-DkS355co.js +201 -0
  5. package/dist/admin/assets/badge-BXsOvOPX.js +1 -0
  6. package/dist/admin/assets/changes-Ba0G_GN1.js +1 -0
  7. package/dist/admin/assets/client-VKp75fDU.js +5 -0
  8. package/dist/admin/assets/clsx-DB0hHKMi.js +1 -0
  9. package/dist/admin/assets/collapsible-B6P_J0Bg.js +1 -0
  10. package/dist/admin/assets/collapsible-item-UaoJaaPw.js +1 -0
  11. package/dist/admin/assets/collections._collection-BE1enDCq.js +1 -0
  12. package/dist/admin/assets/collections._collection._entry-D3UksnCo.js +52 -0
  13. package/dist/admin/assets/collections._collection.index-BN5d8UIY.js +1 -0
  14. package/dist/admin/assets/component-lookup-CUCiK8Xh.js +4 -0
  15. package/dist/admin/assets/config-Pm_BHLNT.js +1 -0
  16. package/dist/admin/assets/copy-DezZzPMV.js +1 -0
  17. package/dist/admin/assets/css-BGIxQoYs.js +1 -0
  18. package/dist/admin/assets/css-DgaLhXQH.js +1 -0
  19. package/dist/admin/assets/diff-woXpYk--.js +1 -0
  20. package/dist/admin/assets/dist-DzkcSBZl.js +1 -0
  21. package/dist/admin/assets/dist-UbA1s2kM.js +1 -0
  22. package/dist/admin/assets/docx-BctAmX91.js +56 -0
  23. package/dist/admin/assets/editor-FGqMznBK.js +2 -0
  24. package/dist/admin/assets/empty-DSBYiI_7.js +1 -0
  25. package/dist/admin/assets/entry-link-CQLN2Zpf.js +158 -0
  26. package/dist/admin/assets/error-banner-yskeRXe8.js +159 -0
  27. package/dist/admin/assets/errors-DkJ5E_ak.js +1 -0
  28. package/dist/admin/assets/field-BDK5tt3J.js +41 -0
  29. package/dist/admin/assets/field-schema-CacrjSYw.js +1 -0
  30. package/dist/admin/assets/file-text-BzBif8ui.js +1 -0
  31. package/dist/admin/assets/github-dark-C-LZuMrd.js +1 -0
  32. package/dist/admin/assets/github-light-EUqPIrTm.js +1 -0
  33. package/dist/admin/assets/highlighted-body-JLMTFACH-CIQujGv2.js +1 -0
  34. package/dist/admin/assets/html-CvFb5cGI.js +1 -0
  35. package/dist/admin/assets/javascript-BzbQS41l.js +1 -0
  36. package/dist/admin/assets/javascript-CpIGwZ_Y.js +1 -0
  37. package/dist/admin/assets/json-qhed-kSA.js +1 -0
  38. package/dist/admin/assets/jsx-Bz0zcwM4.js +1 -0
  39. package/dist/admin/assets/lib-CMURo-7A.js +21 -0
  40. package/dist/admin/assets/library-Cr3f75Es.js +1 -0
  41. package/dist/admin/assets/list-skeleton-BdTNfVXs.js +1 -0
  42. package/dist/admin/assets/markdown-BYOwaDjH.js +1 -0
  43. package/dist/admin/assets/matchContext-Bq5Es9aD.js +2 -0
  44. package/dist/admin/assets/media-browser-9-CPTCks.js +1 -0
  45. package/dist/admin/assets/media._library-BfFaEZLR.js +1 -0
  46. package/dist/admin/assets/mermaid-WFAXDIZX-CJ3hhA0i.js +1 -0
  47. package/dist/admin/assets/page-header-B4nvAsVA.js +1 -0
  48. package/dist/admin/assets/pdf-DgessaF0.js +106 -0
  49. package/dist/admin/assets/python-gzcpVVnB.js +1 -0
  50. package/dist/admin/assets/react-kbcsfQYH.js +1 -0
  51. package/dist/admin/assets/rolldown-runtime-BWaJ3C7D.js +1 -0
  52. package/dist/admin/assets/routes-CBt04sNR.js +1 -0
  53. package/dist/admin/assets/routes-D7tEdYGV.js +1 -0
  54. package/dist/admin/assets/save-actions-Cz0TkpcP.js +32 -0
  55. package/dist/admin/assets/select-Bv2EoLhN.js +1 -0
  56. package/dist/admin/assets/separator-DlYj_PoQ.js +3 -0
  57. package/dist/admin/assets/shell-DBEiq06l.js +1 -0
  58. package/dist/admin/assets/shellscript-CLZ0U2zV.js +1 -0
  59. package/dist/admin/assets/skeleton-CKiqTaRh.js +1 -0
  60. package/dist/admin/assets/sql-CEbI0hMM.js +1 -0
  61. package/dist/admin/assets/syntax-BAXqRKRO.js +8 -0
  62. package/dist/admin/assets/toggle-Y2UpJZyU.js +1 -0
  63. package/dist/admin/assets/toml-BPTmHmyx.js +1 -0
  64. package/dist/admin/assets/tsx-udAQXfEw.js +1 -0
  65. package/dist/admin/assets/typescript-bsJCZSQ-.js +1 -0
  66. package/dist/admin/assets/ui.module.css-WaO_77ml.js +56 -0
  67. package/dist/admin/assets/use-entries-B2lsaiK9.js +1 -0
  68. package/dist/admin/assets/useSelector-CWr3iU9K.js +1 -0
  69. package/dist/admin/assets/yaml-rwi0_p6S.js +1 -0
  70. package/dist/admin/assets/zwitch-Wwuax-dJ.js +1 -0
  71. package/dist/admin/bootstrap.d.ts +1 -0
  72. package/dist/admin/bootstrap.js +1 -0
  73. package/dist/admin/editor.d.ts +57 -0
  74. package/dist/admin/editor.js +1 -0
  75. package/dist/server/assets.d.ts +2 -0
  76. package/dist/server/assets.js +30 -0
  77. package/dist/server/chunks/anchors-DuZ1fokt.js +86 -0
  78. package/dist/server/chunks/auth-DJP9ryVd.js +44 -0
  79. package/dist/server/chunks/cms-markers-CUqrOnfA.js +78 -0
  80. package/dist/server/chunks/component-lookup-DAFg_Qg8.js +128 -0
  81. package/dist/server/chunks/config-WQqG4mNH.d.ts +193 -0
  82. package/dist/server/chunks/digest-BYzWNJea.js +753 -0
  83. package/dist/server/chunks/entry-checks-CKMag1G4.js +608 -0
  84. package/dist/server/chunks/field-schema-CfdN75jT.js +48 -0
  85. package/dist/server/chunks/http-BnsNh57m.d.ts +35 -0
  86. package/dist/server/chunks/i18n-BPmx7ESy.d.ts +15 -0
  87. package/dist/server/chunks/index-CYbkNvu5.d.ts +22 -0
  88. package/dist/server/chunks/media-BhqUVVYY.js +223 -0
  89. package/dist/server/chunks/paths-CEW9fvg8.js +17 -0
  90. package/dist/server/chunks/paths-Dztx2eUw.js +13 -0
  91. package/dist/server/chunks/types-DOR5XaJO.js +397 -0
  92. package/dist/server/chunks/types-Dkx4Xovf.d.ts +359 -0
  93. package/dist/server/chunks/types-DwA-C6Br.d.ts +266 -0
  94. package/dist/server/chunks/user-config-DoypbpQf.js +283 -0
  95. package/dist/server/chunks/xml-D8qPILJU.js +81 -0
  96. package/dist/server/config.d.ts +3 -0
  97. package/dist/server/config.js +18 -0
  98. package/dist/server/content.d.ts +48 -0
  99. package/dist/server/content.js +89 -0
  100. package/dist/server/endpoint.d.ts +11 -0
  101. package/dist/server/endpoint.js +2712 -0
  102. package/dist/server/integration.d.ts +7 -0
  103. package/dist/server/integration.js +1174 -0
  104. package/dist/server/internal.d.ts +65 -0
  105. package/dist/server/internal.js +30 -0
  106. package/dist/server/server-local.d.ts +453 -0
  107. package/dist/server/server-local.js +336 -0
  108. package/dist/styles/THIRD_PARTY_LICENSES.md +193 -0
  109. package/dist/styles/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  110. package/dist/styles/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  111. package/dist/styles/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  112. package/dist/styles/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  113. package/dist/styles/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  114. package/dist/styles/styles.css +3 -0
  115. package/package.json +151 -5
  116. package/src/astro/Image.astro +28 -0
  117. package/src/astro/Video.astro +44 -0
  118. package/src/astro/admin.astro +137 -0
  119. package/src/astro/licenses.ts +5 -0
@@ -0,0 +1,753 @@
1
+ import { a as assertWithinSizeLimit, l as isLibraryFile, m as mediaPath, o as describeMediaRef, v as repoOnlyRefusal } from "./media-BhqUVVYY.js";
2
+ import { n as stripMediaPrefix } from "./paths-CEW9fvg8.js";
3
+ import { d as diagnostic, s as isRecord, u as ContentValidationError } from "./field-schema-CfdN75jT.js";
4
+ import { _ as getFileExtension, b as serializeContent, c as globEntry, o as entryFilePath, p as singletonIds, r as asEntryFormat, v as parseContent, x as serializeMultiEntryFile, y as parseMultiEntryFile } from "./types-DOR5XaJO.js";
5
+ import { a as libraryPathError, c as validateBody, d as activeVariant, f as errorMessage, s as validatePath, t as checkEntry, u as isAsset } from "./entry-checks-CKMag1G4.js";
6
+ import { join } from "pathe";
7
+ import { TomlDate } from "smol-toml";
8
+ // src/server/errors.ts
9
+ /** An error with the HTTP status it should reach the browser as. */
10
+ var HttpError = class extends Error {
11
+ status;
12
+ constructor(message, status) {
13
+ super(message);
14
+ this.name = "HttpError";
15
+ this.status = status;
16
+ }
17
+ };
18
+ /** Runs a check that throws a plain Error, and gives its failure an HTTP meaning. */
19
+ function checked(status, run) {
20
+ try {
21
+ return run();
22
+ } catch (err) {
23
+ throw new HttpError(errorMessage(err, "Invalid request."), status);
24
+ }
25
+ }
26
+ /** A failed call to an upstream API, a Git provider or the object store, with the status it answered. */
27
+ var ApiError = class extends Error {
28
+ status;
29
+ constructor(status, message) {
30
+ super(message);
31
+ this.name = "ApiError";
32
+ this.status = status;
33
+ }
34
+ };
35
+ // src/server/library-path.ts
36
+ /** Admit a path to a media library before reading or writing it. */
37
+ function assertLibraryPath(path, extensions) {
38
+ const error = libraryPathError(path, extensions);
39
+ if (error) throw new HttpError(error, 400);
40
+ }
41
+ // src/server/storage/types.ts
42
+ /**
43
+ * A write refused because the file moved under it: what the caller read is no
44
+ * longer what is there.
45
+ *
46
+ * Distinct from {@link MergeConflictError}, which is the provider declining to
47
+ * merge a branch. Both are the editor's to resolve, but only one of them is
48
+ * resolved by reloading the entry, so the admin has to be able to tell them
49
+ * apart, and the copy it shows is its own, translated, rather than a sentence
50
+ * composed here.
51
+ */
52
+ var StaleWriteError = class extends Error {
53
+ constructor(what) {
54
+ super(`${what} changed since it was read.`);
55
+ this.name = "StaleWriteError";
56
+ }
57
+ };
58
+ var staleWrite = (what) => new StaleWriteError(what);
59
+ var MergeConflictError = class extends Error {
60
+ constructor(message) {
61
+ super(message ?? "Merge conflict");
62
+ this.name = "MergeConflictError";
63
+ }
64
+ };
65
+ /** The HTTP status a failed provider call carried, if it was one (see `ApiError`). */
66
+ function getErrorStatus(err) {
67
+ const status = err.status;
68
+ return typeof status === "number" ? status : void 0;
69
+ }
70
+ function getErrorCode(err) {
71
+ return typeof err === "object" && err !== null && "code" in err ? err.code : void 0;
72
+ }
73
+ /** Absence, in the dialect of every backend: a provider 404 or a filesystem `ENOENT`. */
74
+ function isNotFound(err) {
75
+ return getErrorStatus(err) === 404 || getErrorCode(err) === "ENOENT";
76
+ }
77
+ /**
78
+ * Whether a lookup found its target. Only a provider 404 counts as absent:
79
+ * reading an auth failure, a rate limit or an outage that way would report a
80
+ * draft branch as missing, silently hiding its changes behind the default branch
81
+ * and letting a later write try to recreate a branch that already exists.
82
+ */
83
+ async function exists(lookup) {
84
+ try {
85
+ await lookup;
86
+ return true;
87
+ } catch (err) {
88
+ if (isNotFound(err)) return false;
89
+ throw err;
90
+ }
91
+ }
92
+ /** The precondition an optional version stands for: none at all when it is absent. */
93
+ function versioned(version) {
94
+ return version === void 0 ? void 0 : { version };
95
+ }
96
+ /** Whether the state a backend actually found satisfies the write's precondition. */
97
+ function satisfies(actual, precondition) {
98
+ return "absent" in precondition ? actual === void 0 : actual === precondition.version;
99
+ }
100
+ function mapMergeError(err) {
101
+ const status = getErrorStatus(err);
102
+ if (status === 405 || status === 406 || status === 409) return new MergeConflictError();
103
+ return Error.isError(err) ? err : new Error(String(err), { cause: err });
104
+ }
105
+ // src/server/validation.ts
106
+ /** An entry id must be a safe, slug-like path (the same rule the storage layer enforces). */
107
+ function validateEntryId(id) {
108
+ try {
109
+ validatePath(id, "entry id");
110
+ return [];
111
+ } catch (e) {
112
+ return [diagnostic(errorMessage(e))];
113
+ }
114
+ }
115
+ /** A reorder must list every existing id exactly once: no unknown, missing, or duplicate ids. */
116
+ function validateReorder(existing, ids) {
117
+ const existingSet = new Set(existing);
118
+ const seen = /* @__PURE__ */ new Set();
119
+ const duplicates = /* @__PURE__ */ new Set();
120
+ for (const id of ids) (seen.has(id) ? duplicates : seen).add(id);
121
+ const unknown = [...seen.difference(existingSet)];
122
+ const missing = [...existingSet.difference(seen)];
123
+ const diagnostics = [];
124
+ if (unknown.length) diagnostics.push(diagnostic(`Unknown entry id(s): ${unknown.join(", ")}.`));
125
+ if (missing.length) diagnostics.push(diagnostic(`Every entry must appear exactly once; missing: ${missing.join(", ")}.`));
126
+ if (duplicates.size) diagnostics.push(diagnostic(`Duplicate entry id(s): ${[...duplicates].join(", ")}.`));
127
+ return diagnostics;
128
+ }
129
+ async function checkReferences(source, references) {
130
+ const byCollection = Map.groupBy(references, (ref) => ref.collection ?? "");
131
+ return (await Promise.all([...byCollection].map(async ([collection, refs]) => {
132
+ const ids = new Set((await source.listEntries(collection)).map((e) => e.id));
133
+ return refs.filter((ref) => !ids.has(ref.value)).map((ref) => diagnostic(`references "${ref.value}", which does not exist in collection "${collection}".`, ref.path));
134
+ }))).flat();
135
+ }
136
+ /**
137
+ * An `image`/`file` field must name a file in the media library, and nothing
138
+ * else. This is not a house rule: the site resolves these values through the
139
+ * library alone, either a map rooted at the media directory or a URL under the
140
+ * configured public base (see `virtual:astronaut-cms/assets`), so a value that
141
+ * addresses anything else cannot resolve at render time no matter what the file
142
+ * system or the bucket holds. With a repository library a build takes it
143
+ * further and refuses to start, since the same walk decides what is bundled.
144
+ */
145
+ async function checkAssets(source, assets, base) {
146
+ if (assets.length === 0) return [];
147
+ const located = assets.map((asset) => ({
148
+ asset,
149
+ location: mediaPath(asset.value, source.media, base)
150
+ }));
151
+ const libraries = new Set(located.map(({ location }) => location?.library).filter((id) => id != null));
152
+ const paths = new Map(await Promise.all([...libraries].map(async (library) => [library, new Set((await source.listMedia(library)).map((m) => m.path))])));
153
+ return located.flatMap(({ asset, location }) => {
154
+ if (location == null) return diagnostic(`"${asset.value}" does not address a media library. An asset value must be ${describeMediaRef(source.media)}; upload the file there and use the reference the media library reports.`, asset.path);
155
+ if (asset.repoOnly && location.library !== "repo") return diagnostic(repoOnlyRefusal(asset.value), asset.path);
156
+ if (!paths.get(location.library)?.has(location.path)) return diagnostic(`"${asset.value}" is not in the media library. Use a path the media library reports.`, asset.path);
157
+ return [];
158
+ });
159
+ }
160
+ /**
161
+ * Cross-resource integrity for the fields the lowered schema can only type as
162
+ * `string`: a `reference` must resolve to an existing entry and an `image`/`file`
163
+ * to a file in the media library. These are the values a model can get past the
164
+ * tool's JSON Schema while still pointing at nothing, so they are checked here
165
+ * rather than by the schema.
166
+ */
167
+ async function checkResolvableLeaves(source, leaves, base) {
168
+ if (leaves.length === 0) return [];
169
+ const [references, assets] = await Promise.all([checkReferences(source, leaves.filter((l) => l.kind === "reference")), checkAssets(source, leaves.filter(isAsset), base)]);
170
+ return [...references, ...assets];
171
+ }
172
+ /**
173
+ * Everything that has to hold before an entry may be written: a slug-safe id,
174
+ * the rules of {@link checkEntry}, and every asset and reference, from the
175
+ * frontmatter and from the component props alike, resolving to something that
176
+ * exists. The two leaf sources are resolved together so the media library and
177
+ * each referenced collection are listed once per write.
178
+ */
179
+ async function validateEntryWrite(source, write) {
180
+ const { col, id, path, data, body, format } = write;
181
+ const { diagnostics, leaves } = checkEntry(col, {
182
+ id,
183
+ path,
184
+ data,
185
+ body: validateBody(body, format, source.components)
186
+ });
187
+ return [
188
+ ...validateEntryId(id),
189
+ ...singletonIdProblems(col, id),
190
+ ...diagnostics,
191
+ ...await checkResolvableLeaves(source, leaves, path)
192
+ ];
193
+ }
194
+ function singletonIdProblems(col, id) {
195
+ const ids = singletonIds(col);
196
+ if (ids.length === 0 || ids.includes(id)) return [];
197
+ return [diagnostic(`"${col.name}" is a singleton collection, whose only entries are ${ids.map((i) => `"${i}"`).join(", ")}.`)];
198
+ }
199
+ /** Throws {@link ContentValidationError} unless the entry is safe to write. */
200
+ async function assertEntryWritable(source, write) {
201
+ const diagnostics = await validateEntryWrite(source, write);
202
+ if (diagnostics.length > 0) throw new ContentValidationError(diagnostics);
203
+ }
204
+ /**
205
+ * Throws {@link ContentValidationError} for a singleton's main entry, which the
206
+ * site cannot do without. A translation of it may go.
207
+ */
208
+ function assertEntryDeletable(col, id) {
209
+ if (col.singleton?.main.id === id) throw new ContentValidationError([diagnostic(`"${col.name}" is a singleton collection, whose entry "${id}" cannot be deleted.`)]);
210
+ }
211
+ // src/server/storage/base.ts
212
+ var untrashable = "This library keeps its deletions in the changeset rather than a trash. Discard the pending changes to bring a deleted file back.";
213
+ var BRANCH_PREFIX = "cms/";
214
+ var occupied = (path) => new HttpError(`A file already exists at "${path}".`, 409);
215
+ /** The schema of the value at `key` inside a container that `field` describes. */
216
+ function childSchema(field, key) {
217
+ switch (field?.type) {
218
+ case "array": return typeof key === "number" ? field.element : void 0;
219
+ case "tuple": return typeof key === "number" ? field.items[key] : void 0;
220
+ case "object": return typeof key === "string" ? field.shape[key] : void 0;
221
+ case "record": return typeof key === "string" ? field.value : void 0;
222
+ default: return;
223
+ }
224
+ }
225
+ /** Restore TOML date types lost when entry data passed through the JSON API. */
226
+ function restoreTomlDates(value, previous, schema, path = "") {
227
+ const field = schema?.type === "union" ? activeVariant(schema, value) : schema ?? void 0;
228
+ const restore = (item, old, key) => restoreTomlDates(item, old, childSchema(field, key), path ? `${path}.${key}` : `${key}`);
229
+ if (typeof value === "string" && (previous instanceof Date || field?.type === "date")) {
230
+ const date = new TomlDate(value);
231
+ if (date.isValid()) return date;
232
+ const parsed = new Date(value);
233
+ if (!Number.isNaN(parsed.getTime())) return new TomlDate(parsed.toISOString());
234
+ if (field?.type !== "date") return value;
235
+ throw new ContentValidationError([diagnostic("Expected a TOML date.", path)]);
236
+ }
237
+ if (Array.isArray(value)) {
238
+ const old = Array.isArray(previous) ? previous : [];
239
+ return value.map((item, index) => restore(item, old[index], index));
240
+ }
241
+ if (isRecord(value)) {
242
+ const old = isRecord(previous) ? previous : {};
243
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, restore(item, old[key], key)]));
244
+ }
245
+ return value;
246
+ }
247
+ /** Both providers hand file contents back this way, whitespace and all. */
248
+ var fromBase64 = (content) => new TextDecoder().decode(Uint8Array.fromBase64(content));
249
+ /**
250
+ * What `load` answers for `key`, loaded at most once into `cache` and shared by
251
+ * every caller. A failure is dropped rather than kept, so the next caller
252
+ * retries instead of reading it.
253
+ */
254
+ function memoized(cache, key, load) {
255
+ const cached = cache.get(key);
256
+ if (cached) return cached;
257
+ const pending = load().catch((error) => {
258
+ if (cache.get(key) === pending) cache.delete(key);
259
+ throw error;
260
+ });
261
+ cache.set(key, pending);
262
+ return pending;
263
+ }
264
+ /**
265
+ * A Git storage backend is also the repository media library: media there is
266
+ * committed to the same draft branch as content. Entry validation checks assets
267
+ * against whichever library a reference names, which {@link useMediaLibraries}
268
+ * hands it.
269
+ *
270
+ * One instance serves one request. Nothing here is cached across requests, which
271
+ * is what makes it correct on a serverless runtime where an instance may be
272
+ * shared between editors or discarded between clicks.
273
+ */
274
+ var StorageBase = class {
275
+ options;
276
+ schemas;
277
+ mediaDirectory;
278
+ libraryOf = () => this;
279
+ /**
280
+ * The container file of each file collection, read at most once per request.
281
+ * Every entry of one lives in the same file, so a reference scan over an
282
+ * N-entry collection would otherwise fetch and re-parse it N times.
283
+ */
284
+ containers = /* @__PURE__ */ new Map();
285
+ /**
286
+ * Each collection's listing, made at most once between writes. Every entry
287
+ * read and write looks its entry up in it, so a rename would otherwise list
288
+ * the collection three times.
289
+ */
290
+ listings = /* @__PURE__ */ new Map();
291
+ constructor(options) {
292
+ this.options = options;
293
+ this.schemas = options.collections;
294
+ this.mediaDirectory = options.library.directory;
295
+ }
296
+ /** Only the listings are needed, so this never grants writes to a library it does not own. */
297
+ useMediaLibraries(libraryOf) {
298
+ this.libraryOf = libraryOf;
299
+ }
300
+ listEntries(collection) {
301
+ return memoized(this.listings, collection, async () => {
302
+ const col = this.schemas[collection];
303
+ if (!col) return [];
304
+ if (this.isFileCollection(collection)) return this.listFileCollectionEntries(collection);
305
+ return Iterator.from(await this.globPaths(col)).map((path) => globEntry(col, path)).filter((entry) => entry !== null).map((entry) => ({
306
+ ...entry,
307
+ collection
308
+ })).toArray();
309
+ });
310
+ }
311
+ /** A content write, after which what this request read is stale. */
312
+ async persist(path, content, message, precondition) {
313
+ try {
314
+ return await this.commitFile(path, content, message, precondition);
315
+ } finally {
316
+ this.invalidate();
317
+ }
318
+ }
319
+ /** Drops the listings and containers this request read, which a write has made stale. */
320
+ invalidate() {
321
+ this.containers.clear();
322
+ this.listings.clear();
323
+ }
324
+ async tomlEntryData(path, data, schema, createOnly) {
325
+ let previous;
326
+ try {
327
+ if (!createOnly) previous = parseContent((await this.fetchFileContent(path)).content, "toml").data;
328
+ } catch (err) {
329
+ if (!isNotFound(err)) throw err;
330
+ }
331
+ return restoreTomlDates(data, previous, schema);
332
+ }
333
+ /**
334
+ * The single funnel for content writes, and therefore where content validity is
335
+ * enforced: an entry that does not satisfy its collection's schema (or points
336
+ * at an asset or reference that does not exist) breaks the site's content sync,
337
+ * so it never reaches storage. Every other write composes this one.
338
+ */
339
+ async saveEntry(collection, id, data) {
340
+ const col = this.schema(collection);
341
+ const stored = this.isFileCollection(collection) ? void 0 : await this.storedEntry(collection, id);
342
+ const path = !data.createOnly && stored?.format === data.format ? stored.path : entryFilePath(col, id, data.format);
343
+ await assertEntryWritable(this.contentSource, {
344
+ col,
345
+ id,
346
+ path,
347
+ ...data
348
+ });
349
+ if (data.createOnly && stored && stored.path !== path) throw staleWrite(`${collection}/${id}`);
350
+ const edited = this.isFileCollection(collection) ? await this.editFileCollection(collection, (entries, format) => {
351
+ if (data.createOnly && entries.has(id)) throw staleWrite(`${collection}/${id}`);
352
+ entries.set(id, format === "toml" ? restoreTomlDates(data.data, entries.get(id), col.schema) : data.data);
353
+ }) : {
354
+ path,
355
+ content: serializeContent(data.format === "toml" ? await this.tomlEntryData(path, data.data, col.schema, data.createOnly ?? false) : data.data, data.body, data.format),
356
+ version: void 0
357
+ };
358
+ const version = data.createOnly ? data.expectedVersion ?? edited.version : data.expectedVersion;
359
+ const precondition = version !== void 0 ? { version } : data.createOnly ? { absent: true } : void 0;
360
+ return this.persist(edited.path, edited.content, `Update ${collection}/${id}`, precondition);
361
+ }
362
+ async deleteEntry(collection, id, expectedVersion) {
363
+ const message = `Delete ${collection}/${id}`;
364
+ assertEntryDeletable(this.schema(collection), id);
365
+ if (this.isFileCollection(collection)) {
366
+ const { path, content } = await this.editFileCollection(collection, (entries) => {
367
+ entries.delete(id);
368
+ });
369
+ await this.persist(path, content, message, versioned(expectedVersion));
370
+ return;
371
+ }
372
+ const stored = await this.storedEntry(collection, id);
373
+ if (!stored) throw new Error(`Entry not found: ${collection}/${id}`);
374
+ try {
375
+ await this.removeFile(stored.path, message, expectedVersion);
376
+ } finally {
377
+ this.invalidate();
378
+ }
379
+ }
380
+ /**
381
+ * Only a collection sorted by file order has an order to change, which only a
382
+ * file collection can be: a glob collection's entries are separate files. Any
383
+ * other order is the site's, so a rewrite would change nothing it renders.
384
+ */
385
+ async reorderEntries(collection, ids, expectedVersion) {
386
+ if (this.schemas[collection]?.sort !== "file") throw new Error(`Collection is not sorted by file order: ${collection}`);
387
+ const { path, content } = await this.editFileCollection(collection, (entries) => new Map(new Set(ids).union(entries).values().filter((id) => entries.has(id)).map((id) => [id, entries.get(id)])));
388
+ await this.persist(path, content, `Reorder ${collection}`, versioned(expectedVersion));
389
+ }
390
+ async getEntry(collection, id) {
391
+ const stored = await this.storedEntry(collection, id);
392
+ if (!stored) throw new Error(`Entry not found: ${collection}/${id}`);
393
+ return this.readEntry(stored);
394
+ }
395
+ async readEntry({ collection, id, path, format }) {
396
+ if (this.isFileCollection(collection)) {
397
+ const { entries, version } = await this.readFileCollection(collection);
398
+ const data = entries.get(id);
399
+ if (!data) throw new Error(`Entry not found: ${collection}/${id}`);
400
+ return {
401
+ id,
402
+ path,
403
+ data,
404
+ body: "",
405
+ format,
406
+ ...version && { version }
407
+ };
408
+ }
409
+ const { content, version } = await this.fetchFileContent(path);
410
+ const { data, body } = parseContent(content, format);
411
+ return {
412
+ id,
413
+ path,
414
+ data,
415
+ body,
416
+ format,
417
+ ...version && { version }
418
+ };
419
+ }
420
+ /** A copy under a new id, which works uniformly because saveEntry branches on layout. */
421
+ async duplicateEntry(collection, sourceId, targetId) {
422
+ const source = await this.getEntry(collection, sourceId);
423
+ await this.saveEntry(collection, targetId, {
424
+ data: source.data,
425
+ body: source.body,
426
+ format: source.format,
427
+ createOnly: true
428
+ });
429
+ }
430
+ /**
431
+ * In a glob collection two writes, a copy and the removal of the original, and
432
+ * the version describes the removal. In a file collection both entries share
433
+ * one container, so it is one rewrite that keeps the entry where it was, since
434
+ * its position may be the collection's order.
435
+ */
436
+ async renameEntry(collection, oldId, newId, expectedVersion) {
437
+ if (oldId === newId) return;
438
+ if (!this.isFileCollection(collection)) {
439
+ await this.duplicateEntry(collection, oldId, newId);
440
+ await this.deleteEntry(collection, oldId, expectedVersion);
441
+ return;
442
+ }
443
+ const entry = await this.getEntry(collection, oldId);
444
+ await assertEntryWritable(this.contentSource, {
445
+ ...entry,
446
+ col: this.schema(collection),
447
+ id: newId
448
+ });
449
+ const { path, content } = await this.editFileCollection(collection, (entries) => {
450
+ if (entries.has(newId)) throw staleWrite(`${collection}/${newId}`);
451
+ return new Map(entries.entries().map(([id, item]) => [id === oldId ? newId : id, item]));
452
+ });
453
+ await this.persist(path, content, `Rename ${collection}/${oldId} to ${newId}`, versioned(expectedVersion));
454
+ }
455
+ /** The entry as the memoized listing reports it, or undefined when there is none. */
456
+ async storedEntry(collection, id) {
457
+ return (await this.listEntries(collection)).find((entry) => entry.id === id);
458
+ }
459
+ /** The raw content of a repository file, by project-relative path. */
460
+ async fetchFileContent(_path) {
461
+ throw new Error("Not implemented");
462
+ }
463
+ /** What entry validation resolves references and assets against. */
464
+ get contentSource() {
465
+ return {
466
+ listEntries: (collection) => this.listEntries(collection),
467
+ listMedia: (library) => this.libraryOf(library).listPaths(),
468
+ media: this.options.media,
469
+ components: this.options.components
470
+ };
471
+ }
472
+ /** The repository path of a library file. */
473
+ mediaRepoPath(path) {
474
+ assertLibraryPath(path, this.options.library.extensions);
475
+ return join(this.mediaDirectory, path);
476
+ }
477
+ /**
478
+ * A repository library has no URL to hand out: its bytes become a commit, so
479
+ * they have to arrive here. The checks still run now rather than on arrival,
480
+ * so an oversized or occupied upload is refused before it is sent.
481
+ */
482
+ async beginUpload(path, size, overwrite) {
483
+ this.assertUploadable(path, size);
484
+ if (!overwrite && (await this.listPaths()).some((entry) => entry.path === path)) throw occupied(path);
485
+ return { direct: false };
486
+ }
487
+ assertUploadable(path, size) {
488
+ checked(413, () => assertWithinSizeLimit(size, this.options.library));
489
+ return this.mediaRepoPath(path);
490
+ }
491
+ /**
492
+ * Where a repository library's own writes are checked before bytes reach a backend.
493
+ * Every backend claims a new path atomically, so no listing is needed here.
494
+ */
495
+ async uploadMedia(path, bytes, overwrite) {
496
+ try {
497
+ await this.writeMedia(this.assertUploadable(path, bytes.byteLength), bytes, overwrite);
498
+ } catch (error) {
499
+ if (!overwrite && error instanceof StaleWriteError) throw occupied(path);
500
+ throw error;
501
+ }
502
+ }
503
+ async renameMedia(oldPath, newPath) {
504
+ const from = this.mediaRepoPath(oldPath);
505
+ const to = this.mediaRepoPath(newPath);
506
+ if (from === to) return;
507
+ return this.moveMedia(from, to);
508
+ }
509
+ async deleteMedia(path) {
510
+ return this.removeMedia(this.mediaRepoPath(path));
511
+ }
512
+ listPaths() {
513
+ return this.listMedia();
514
+ }
515
+ /**
516
+ * A repository library has no trash, and needs none: a deletion here is a
517
+ * commit on the draft branch, so the file is still in git, recoverable by
518
+ * discarding the changeset before it publishes, and in history for good
519
+ * afterwards. An object store keeps no history, which is the whole reason the
520
+ * other library has a trash at all.
521
+ */
522
+ async listTrash() {
523
+ return [];
524
+ }
525
+ restoreMedia() {
526
+ return Promise.reject(new HttpError(untrashable, 400));
527
+ }
528
+ purgeTrash() {
529
+ return Promise.reject(new HttpError(untrashable, 400));
530
+ }
531
+ /**
532
+ * Lowers repository paths into library files, dropping strays in the media
533
+ * directory. Takes the backend's own listing shape rather than `MediaFile`s, so
534
+ * a whole-repository tree costs no allocation for the paths it discards.
535
+ */
536
+ mediaFiles(files) {
537
+ return Iterator.from(files).flatMap((file) => {
538
+ const path = stripMediaPrefix(file.path, this.mediaDirectory);
539
+ return path != null && isLibraryFile(path, this.options.library.extensions) ? [{
540
+ path,
541
+ size: file.size ?? 0,
542
+ ...file.version && { version: file.version }
543
+ }] : [];
544
+ }).toArray();
545
+ }
546
+ schema(collection) {
547
+ const col = this.schemas[collection];
548
+ if (!col) throw new Error(`Unknown collection: ${collection}`);
549
+ return col;
550
+ }
551
+ isFileCollection(collection) {
552
+ return this.schemas[collection]?.loaderType === "file";
553
+ }
554
+ getFileLoaderPath(collection) {
555
+ return this.schemas[collection]?.loaderFileName ?? null;
556
+ }
557
+ /**
558
+ * The format of a file collection's container. It is the loader's own file
559
+ * name, so an unknown extension means the loader is one the CMS cannot read
560
+ * rather than a caller mistake; JSON is the reading that parses most of them.
561
+ */
562
+ containerFormat(loaderFileName) {
563
+ return asEntryFormat(getFileExtension(loaderFileName)) ?? "json";
564
+ }
565
+ /**
566
+ * The container file as it stands, or an empty one when it does not exist yet
567
+ * (or is not a file collection at all). Every read of one goes through here,
568
+ * so the listing, the layout and a write all see the same parse.
569
+ */
570
+ readFileCollection(collection) {
571
+ return memoized(this.containers, collection, () => this.loadFileCollection(collection));
572
+ }
573
+ async loadFileCollection(collection) {
574
+ const path = this.getFileLoaderPath(collection);
575
+ const format = path ? this.containerFormat(path) : "json";
576
+ const empty = {
577
+ path: path ?? "",
578
+ format,
579
+ entries: /* @__PURE__ */ new Map(),
580
+ layout: "object"
581
+ };
582
+ if (!path) return empty;
583
+ try {
584
+ const { content, version } = await this.fetchFileContent(path);
585
+ return {
586
+ path,
587
+ format,
588
+ version,
589
+ ...parseMultiEntryFile(content, format)
590
+ };
591
+ } catch (error) {
592
+ if (!isNotFound(error)) throw error;
593
+ return empty;
594
+ }
595
+ }
596
+ /**
597
+ * How a file collection stores its entries, which decides whether they can be
598
+ * reordered, and the version a reorder has to be based on.
599
+ */
600
+ async getFileLayout(collection) {
601
+ const { layout, version } = await this.readFileCollection(collection);
602
+ return {
603
+ layout,
604
+ ...version && { version }
605
+ };
606
+ }
607
+ async listFileCollectionEntries(collection) {
608
+ const { entries, format, path } = await this.readFileCollection(collection);
609
+ return entries.keys().map((id) => ({
610
+ id,
611
+ collection,
612
+ format,
613
+ path
614
+ })).toArray();
615
+ }
616
+ /**
617
+ * A file collection rewritten by `mutate`, as the path and content to write.
618
+ * All three ways to change one (upsert, remove, reorder) are the same
619
+ * read-modify-serialize, so they differ only in the mutation.
620
+ */
621
+ async editFileCollection(collection, mutate) {
622
+ const { path, format, version, ...file } = await this.readFileCollection(collection);
623
+ const edited = new Map(file.entries);
624
+ return {
625
+ path,
626
+ content: serializeMultiEntryFile({
627
+ ...file,
628
+ entries: mutate(edited, format) ?? edited
629
+ }, format),
630
+ version
631
+ };
632
+ }
633
+ };
634
+ /**
635
+ * Shared lifecycle for backends that commit to a per-user branch (cms/<username>)
636
+ * and integrate it into a default branch via a pull/merge request.
637
+ *
638
+ * The branch name comes from the session rather than from a provider lookup, and
639
+ * whether it exists is resolved at most once per request. There is no cross-request
640
+ * cache: an instance may be reused by a different editor, or not reused at all.
641
+ */
642
+ var BranchedStorage = class extends StorageBase {
643
+ /**
644
+ * The *lookup*, not its answer, so the several reads one batched request makes
645
+ * share it rather than each firing their own before the first resolves.
646
+ */
647
+ branchExistsCache = null;
648
+ publishMode;
649
+ branch;
650
+ constructor(options, publishMode) {
651
+ super(options);
652
+ this.publishMode = publishMode;
653
+ this.branch = `${BRANCH_PREFIX}${options.login}`;
654
+ }
655
+ changeRequestTitle(branch) {
656
+ return `CMS draft (${branch})`;
657
+ }
658
+ changeRequestBody(branch) {
659
+ return `Opened automatically by Astronaut CMS. Delete the \`${branch}\` branch to discard all pending changes.`;
660
+ }
661
+ markBranchExists(exists) {
662
+ this.branchExistsCache = Promise.resolve(exists);
663
+ }
664
+ branchExists() {
665
+ this.branchExistsCache ??= this.checkBranchExists(this.branch).catch((err) => {
666
+ this.branchExistsCache = null;
667
+ throw err;
668
+ });
669
+ return this.branchExistsCache;
670
+ }
671
+ async readRef() {
672
+ return await this.branchExists() ? this.branch : this.defaultBranch;
673
+ }
674
+ async publish() {
675
+ if (!await this.branchExists()) return;
676
+ const cr = await this.findOpenChangeRequest(this.branch) ?? await this.createChangeRequest(this.branch);
677
+ if (this.publishMode === "pull-request") return;
678
+ try {
679
+ await this.acceptChangeRequest(cr);
680
+ } catch (err) {
681
+ throw mapMergeError(err);
682
+ }
683
+ await this.dropBranch();
684
+ }
685
+ async update() {
686
+ if (!await this.branchExists()) return;
687
+ await this.doUpdate(this.branch);
688
+ this.invalidate();
689
+ }
690
+ async discard() {
691
+ if (await this.branchExists()) await this.dropBranch();
692
+ }
693
+ /**
694
+ * Retires the draft branch and any change request on it, which is what both
695
+ * discarding a changeset and publishing one come down to. Publishing has to
696
+ * ask for it too: only GitLab removes the source branch as part of accepting,
697
+ * so without this the branch would outlive the changeset on GitHub.
698
+ */
699
+ async dropBranch() {
700
+ const cr = await this.findOpenChangeRequest(this.branch);
701
+ if (cr) try {
702
+ await this.closeChangeRequest(cr.id);
703
+ } catch (err) {
704
+ if (await this.findOpenChangeRequest(this.branch)) throw err;
705
+ }
706
+ try {
707
+ await this.deleteUserBranch(this.branch);
708
+ } catch (err) {
709
+ if (await this.checkBranchExists(this.branch)) throw err;
710
+ }
711
+ this.markBranchExists(false);
712
+ this.invalidate();
713
+ }
714
+ async getChanges() {
715
+ return await this.branchExists() ? this.diffAgainstDefault(this.branch) : [];
716
+ }
717
+ async getStatus() {
718
+ if (!await this.branchExists()) return {
719
+ branch: "",
720
+ behind: 0
721
+ };
722
+ const status = {
723
+ branch: this.branch,
724
+ behind: await this.computeBehind(this.branch)
725
+ };
726
+ if (this.publishMode === "pull-request") {
727
+ const cr = await this.findOpenChangeRequest(this.branch);
728
+ if (cr) status.changeRequestUrl = cr.url;
729
+ }
730
+ return status;
731
+ }
732
+ };
733
+ // src/shared/digest.ts
734
+ /** A hex SHA-256 of a string, the same in the browser and on the server. */
735
+ async function sha256(content) {
736
+ const hashed = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(content));
737
+ return new Uint8Array(hashed).toHex();
738
+ }
739
+ /**
740
+ * Names a changeset as a reviewer saw it, so publishing can refuse a changeset
741
+ * that moved on after the review.
742
+ */
743
+ function changesetDigest(changes) {
744
+ const identities = changes.map(({ kind, path, previousPath, patch, version }) => JSON.stringify([
745
+ kind,
746
+ path,
747
+ previousPath,
748
+ patch,
749
+ version
750
+ ])).sort();
751
+ return sha256(JSON.stringify(identities));
752
+ }
753
+ export { assertLibraryPath as _, fromBase64 as a, checked as b, MergeConflictError as c, getErrorCode as d, getErrorStatus as f, versioned as g, staleWrite as h, StorageBase as i, StaleWriteError as l, satisfies as m, sha256 as n, memoized as o, isNotFound as p, BranchedStorage as r, validateReorder as s, changesetDigest as t, exists as u, ApiError as v, HttpError as y };