astronaut-cms 0.0.1 → 1.1.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -3
  3. package/dist/admin/THIRD_PARTY_LICENSES.md +7646 -0
  4. package/dist/admin/assets/assistant-DTlSNidc.js +235 -0
  5. package/dist/admin/assets/badge-BfN73-be.js +1 -0
  6. package/dist/admin/assets/changes-h1lmD7AA.js +1 -0
  7. package/dist/admin/assets/client-B4PWCmC4.js +5 -0
  8. package/dist/admin/assets/clsx-DB0hHKMi.js +1 -0
  9. package/dist/admin/assets/collapsible-item-zlnNAUdM.js +1 -0
  10. package/dist/admin/assets/collapsible-mcJ6G3X4.js +1 -0
  11. package/dist/admin/assets/collections._collection-D-rC9E9v.js +1 -0
  12. package/dist/admin/assets/collections._collection._entry-UD8hLmC1.js +52 -0
  13. package/dist/admin/assets/collections._collection.index-Cgc93hCD.js +1 -0
  14. package/dist/admin/assets/component-lookup-8lVQh8pl.js +4 -0
  15. package/dist/admin/assets/config-Pm_BHLNT.js +1 -0
  16. package/dist/admin/assets/copy-DxuErr3x.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-DVv3ALC7.js +1 -0
  21. package/dist/admin/assets/dist-Dpyc1riS.js +1 -0
  22. package/dist/admin/assets/docx-BctAmX91.js +56 -0
  23. package/dist/admin/assets/editor-BauN0yXd.js +2 -0
  24. package/dist/admin/assets/empty-DAOUBpWb.js +1 -0
  25. package/dist/admin/assets/entry-link-DhcL6M5c.js +158 -0
  26. package/dist/admin/assets/error-banner-CNWZU5u_.js +161 -0
  27. package/dist/admin/assets/errors-DkJ5E_ak.js +1 -0
  28. package/dist/admin/assets/field-CbbZZGxO.js +41 -0
  29. package/dist/admin/assets/field-schema-CacrjSYw.js +1 -0
  30. package/dist/admin/assets/file-text-Ciz5Mr4S.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-D1bycIV3.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-CC_S4yjQ.js +21 -0
  40. package/dist/admin/assets/library-Da82FNwp.js +1 -0
  41. package/dist/admin/assets/list-skeleton-BXLP4Fak.js +1 -0
  42. package/dist/admin/assets/markdown-BYOwaDjH.js +1 -0
  43. package/dist/admin/assets/matchContext-BjW1F-Cq.js +2 -0
  44. package/dist/admin/assets/media-browser-DeKpWCUD.js +1 -0
  45. package/dist/admin/assets/media._library-DGnXJc0I.js +1 -0
  46. package/dist/admin/assets/mermaid-WFAXDIZX-CqFnahFh.js +1 -0
  47. package/dist/admin/assets/page-header-C2Uwa_yv.js +1 -0
  48. package/dist/admin/assets/pdf-BSEX-sd8.js +106 -0
  49. package/dist/admin/assets/python-gzcpVVnB.js +1 -0
  50. package/dist/admin/assets/react-CXnqG51l.js +1 -0
  51. package/dist/admin/assets/rolldown-runtime-BWaJ3C7D.js +1 -0
  52. package/dist/admin/assets/routes-Bx9rPcHA.js +1 -0
  53. package/dist/admin/assets/routes-D7tEdYGV.js +1 -0
  54. package/dist/admin/assets/save-actions-DrVgh3KH.js +32 -0
  55. package/dist/admin/assets/select-CMV39q80.js +1 -0
  56. package/dist/admin/assets/separator-C9bNKNSU.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-DTwTUSqm.js +1 -0
  60. package/dist/admin/assets/sql-CEbI0hMM.js +1 -0
  61. package/dist/admin/assets/syntax-DDPd1mQn.js +8 -0
  62. package/dist/admin/assets/toggle-B6ASf-kL.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-BdAmwQeM.js +56 -0
  67. package/dist/admin/assets/use-entries-CrNqaMfa.js +1 -0
  68. package/dist/admin/assets/useSelector-Cs39W18m.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 +1065 -0
  74. package/dist/admin/editor.js +1 -0
  75. package/dist/server/THIRD_PARTY_LICENSES.md +49 -0
  76. package/dist/server/assets.d.ts +30 -0
  77. package/dist/server/assets.js +30 -0
  78. package/dist/server/chunks/anchors-DuZ1fokt.js +86 -0
  79. package/dist/server/chunks/auth-DJP9ryVd.js +44 -0
  80. package/dist/server/chunks/cms-markers-CUqrOnfA.js +78 -0
  81. package/dist/server/chunks/component-lookup-DAFg_Qg8.js +128 -0
  82. package/dist/server/chunks/config-BsOYly9a.d.ts +1210 -0
  83. package/dist/server/chunks/digest-tkKu_Wj5.js +753 -0
  84. package/dist/server/chunks/entry-checks-3SxhoHwH.js +608 -0
  85. package/dist/server/chunks/field-schema-CfdN75jT.js +48 -0
  86. package/dist/server/chunks/http-BnsNh57m.d.ts +35 -0
  87. package/dist/server/chunks/i18n-BPmx7ESy.d.ts +15 -0
  88. package/dist/server/chunks/index-CYbkNvu5.d.ts +22 -0
  89. package/dist/server/chunks/media-BhqUVVYY.js +223 -0
  90. package/dist/server/chunks/paths-CEW9fvg8.js +17 -0
  91. package/dist/server/chunks/paths-Dztx2eUw.js +13 -0
  92. package/dist/server/chunks/types-DkkewFTT.js +418 -0
  93. package/dist/server/chunks/types-Dkx4Xovf.d.ts +359 -0
  94. package/dist/server/chunks/types-Jew_-Qpp.d.ts +273 -0
  95. package/dist/server/chunks/user-config-CqNK-Ebs.js +292 -0
  96. package/dist/server/chunks/xml-D8qPILJU.js +81 -0
  97. package/dist/server/config.d.ts +3 -0
  98. package/dist/server/config.js +22 -0
  99. package/dist/server/content.d.ts +58 -0
  100. package/dist/server/content.js +83 -0
  101. package/dist/server/endpoint.d.ts +16 -0
  102. package/dist/server/endpoint.js +2726 -0
  103. package/dist/server/integration.d.ts +7 -0
  104. package/dist/server/integration.js +1187 -0
  105. package/dist/server/internal.d.ts +100 -0
  106. package/dist/server/internal.js +30 -0
  107. package/dist/server/server-local.d.ts +453 -0
  108. package/dist/server/server-local.js +336 -0
  109. package/dist/styles/THIRD_PARTY_LICENSES.md +193 -0
  110. package/dist/styles/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  111. package/dist/styles/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  112. package/dist/styles/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  113. package/dist/styles/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  114. package/dist/styles/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  115. package/dist/styles/styles.css +3 -0
  116. package/package.json +151 -5
  117. package/src/astro/Image.astro +28 -0
  118. package/src/astro/Video.astro +44 -0
  119. package/src/astro/admin.astro +137 -0
  120. package/src/astro/licenses.ts +5 -0
@@ -0,0 +1,2726 @@
1
+ import { c as GITLAB_CLIENT_SECRET_ENV, i as API_LOGIN, n as API_BASE, r as API_CALLBACK, s as GITHUB_CLIENT_SECRET_ENV, u as PROVIDERS } from "./chunks/auth-DJP9ryVd.js";
2
+ import { d as diagnostic, u as ContentValidationError } from "./chunks/field-schema-CfdN75jT.js";
3
+ import { a as HARDENING_HEADERS, c as partialContent, d as readBytes, i as BodyTooLargeError, l as rangeHeader, s as parseByteRange, u as readBody } from "./chunks/component-lookup-DAFg_Qg8.js";
4
+ import { _ as assertLibraryPath, a as fromBase64, b as checked, c as MergeConflictError, f as getErrorStatus, g as versioned, h as staleWrite, l as StaleWriteError, m as satisfies, o as memoized, r as BranchedStorage, s as validateReorder, t as changesetDigest, u as exists, v as ApiError, y as HttpError } from "./chunks/digest-tkKu_Wj5.js";
5
+ import { C as joinUrl, S as conformTrailingSlash, T as withoutTrailingSlash, _ as remoteMediaUrl, a as assertWithinSizeLimit, b as servedContentType, c as isActiveContentType, d as mediaContentType, f as mediaLibraries, g as parseMediaLibrary, i as S3_SESSION_TOKEN_ENV, l as isLibraryFile, m as mediaPath, n as S3_ACCESS_KEY_ID_ENV, p as mediaLibrary, r as S3_SECRET_ACCESS_KEY_ENV, s as encodeKeyPath, y as s3BaseUrl } from "./chunks/media-BhqUVVYY.js";
6
+ import { a as gatewayAddress, i as NETLIFY_GATEWAY_ENV, n as xmlList, r as parseRepo, t as parseXml } from "./chunks/xml-D8qPILJU.js";
7
+ import { c as validateBody, f as errorMessage, l as dataLeaves, o as mediaPathError, r as collectionEnum, u as isAsset } from "./chunks/entry-checks-3SxhoHwH.js";
8
+ import { d as inGlobRoot, p as orderEntries, r as DEFAULT_SORT, t as ALL_FORMATS, u as globRoots } from "./chunks/types-DkkewFTT.js";
9
+ import { t as projectPath } from "./chunks/paths-CEW9fvg8.js";
10
+ import { dirname, join } from "pathe";
11
+ import { z } from "zod";
12
+ import { client, components, server } from "virtual:astronaut-cms/server";
13
+ import { getSecret } from "astro:env/server";
14
+ import { AwsClient } from "aws4fetch";
15
+ import { LocalStorage } from "virtual:astronaut-cms/local-storage";
16
+ import { encode } from "jose/base64url";
17
+ import { EncryptJWT } from "jose/jwt/encrypt";
18
+ import { jwtDecrypt } from "jose/jwt/decrypt";
19
+ // src/shared/operations.ts
20
+ /**
21
+ * Which operations only read.
22
+ *
23
+ * Everything the CMS does goes through one POST, so the HTTP method no longer
24
+ * says whether a request changed anything. Two things need to know: the dev
25
+ * server, which suppresses the reload a content write triggers, and the
26
+ * assistant, which neither invalidates caches nor reports a change for a read.
27
+ */
28
+ var READ_ONLY_OPERATIONS = /* @__PURE__ */ new Set([
29
+ "listEntries",
30
+ "getEntry",
31
+ "getFileLayout",
32
+ "getStatus",
33
+ "getChanges",
34
+ "listMedia",
35
+ "getReferences",
36
+ "listTrash"
37
+ ]);
38
+ var isWriteOperation = (name) => !READ_ONLY_OPERATIONS.has(name);
39
+ // src/server/ranges.ts
40
+ /**
41
+ * Reading a range of a file from an upstream source, shared by every backend
42
+ * that streams its bytes through the media route (GitLab's raw endpoint) and by
43
+ * the route itself when it proxies a download URL (GitHub). One policy for
44
+ * forwarding the range, refusing a failed answer and relaying what came back,
45
+ * so the forges cannot drift apart.
46
+ */
47
+ /**
48
+ * Sends a request with `range` forwarded and relays the answer, along with the
49
+ * answer's headers for whatever else the caller reads off them. `send` makes
50
+ * the request with the headers it is handed, and may add its own credentials.
51
+ */
52
+ async function fetchRange(send, range) {
53
+ const response = await send(range ? { range: rangeHeader(range) } : {});
54
+ if (response.status !== 416 && (!response.ok || !response.body)) throw new HttpError(`Could not read the media file (${response.status}).`, 502);
55
+ if (response.status === 206 && !response.headers.has("content-range")) {
56
+ await response.body?.cancel();
57
+ throw new HttpError("The media source returned partial bytes without a content range.", 502);
58
+ }
59
+ return {
60
+ ...relayRange(response, range ?? null),
61
+ headers: response.headers
62
+ };
63
+ }
64
+ /** The bytes `start` through `end` (inclusive) of a stream, cancelling the rest unread. */
65
+ function sliceStream(stream, { start, end }) {
66
+ const reader = stream.getReader();
67
+ let position = 0;
68
+ return new ReadableStream({
69
+ async pull(controller) {
70
+ const { done, value } = await reader.read();
71
+ if (done) return controller.close();
72
+ const from = Math.max(start - position, 0);
73
+ const to = Math.min(end + 1 - position, value.length);
74
+ position += value.length;
75
+ if (from < to) controller.enqueue(value.subarray(from, to));
76
+ if (position > end) {
77
+ controller.close();
78
+ await reader.cancel();
79
+ }
80
+ },
81
+ cancel: (reason) => reader.cancel(reason)
82
+ });
83
+ }
84
+ /**
85
+ * An upstream answer to a request that forwarded `range`, as the media route
86
+ * relays it. A source that honoured the range is passed through. One that sent
87
+ * the whole file is cut here while streaming, so memory stays at one chunk
88
+ * whether or not the source supports ranges.
89
+ */
90
+ function relayRange(response, range) {
91
+ const { body, status } = response;
92
+ const contentRange = response.headers.get("content-range");
93
+ if (status === 416) {
94
+ body?.cancel();
95
+ return {
96
+ body: null,
97
+ partial: {
98
+ status,
99
+ contentRange: contentRange ?? void 0
100
+ }
101
+ };
102
+ }
103
+ if (status === 206 && contentRange) return {
104
+ body,
105
+ partial: {
106
+ status,
107
+ contentRange
108
+ }
109
+ };
110
+ const size = Number(response.headers.get("content-length") ?? NaN);
111
+ if (!range || !body || status !== 200 || !Number.isSafeInteger(size)) return { body };
112
+ const partial = partialContent(range, size);
113
+ if (!partial.span) {
114
+ body.cancel();
115
+ return {
116
+ body: null,
117
+ partial
118
+ };
119
+ }
120
+ return {
121
+ body: sliceStream(body, partial.span),
122
+ partial
123
+ };
124
+ }
125
+ // src/shared/rate-limit.ts
126
+ /** How many tracked callers it takes before expiry is worth scanning for. */
127
+ var SWEEP_THRESHOLD$1 = 64;
128
+ var RateLimiter = class {
129
+ config;
130
+ callers = /* @__PURE__ */ new Map();
131
+ constructor(config) {
132
+ this.config = config;
133
+ }
134
+ /**
135
+ * Claims a slot for `caller`, or names why it could not. A granted slot must
136
+ * be released with the returned callback once the request is done, whether it
137
+ * succeeded or not, which `using` does on leaving its scope.
138
+ *
139
+ * `cost` is what the request spends of the per-window budget, for a request
140
+ * that carries more than one thing to do: a batch of operations occupies one
141
+ * slot but must not count as one operation, or batching would be a way around
142
+ * the budget rather than a way to spend fewer invocations on it.
143
+ */
144
+ acquire(caller, cost = 1) {
145
+ const now = Date.now();
146
+ const state = this.caller(caller, now);
147
+ const denial = (reason) => ({
148
+ ok: false,
149
+ reason,
150
+ [Symbol.dispose]: () => {}
151
+ });
152
+ if (state.inFlight >= this.config.concurrency) return denial("concurrency");
153
+ if (state.count + cost > this.config.requests) return denial("rate");
154
+ state.count += cost;
155
+ state.inFlight++;
156
+ let released = false;
157
+ const release = () => {
158
+ if (released) return;
159
+ released = true;
160
+ state.inFlight--;
161
+ };
162
+ return {
163
+ ok: true,
164
+ release,
165
+ [Symbol.dispose]: release
166
+ };
167
+ }
168
+ caller(caller, now) {
169
+ if (this.callers.size > SWEEP_THRESHOLD$1) {
170
+ for (const [key, value] of this.callers) if (value.until <= now && value.inFlight === 0) this.callers.delete(key);
171
+ }
172
+ const existing = this.callers.get(caller);
173
+ if (existing) {
174
+ if (existing.until <= now) {
175
+ existing.until = now + this.config.windowMs;
176
+ existing.count = 0;
177
+ }
178
+ return existing;
179
+ }
180
+ const fresh = {
181
+ until: now + this.config.windowMs,
182
+ count: 0,
183
+ inFlight: 0
184
+ };
185
+ this.callers.set(caller, fresh);
186
+ return fresh;
187
+ }
188
+ };
189
+ /**
190
+ * Runs `work` in a slot, releasing it however the work ends. For a streaming
191
+ * response the slot has to outlive the handler, so the AI relay holds its own
192
+ * (see `ai/handler.ts`); everything else is a request that finishes.
193
+ */
194
+ async function limited(limiter, caller, denied, work, cost = 1) {
195
+ using slot = limiter.acquire(caller, cost);
196
+ if (!slot.ok) throw denied();
197
+ return await work();
198
+ }
199
+ // src/shared/coalesce.ts
200
+ /** How many tracked keys it takes before expiry is worth scanning for. */
201
+ var SWEEP_THRESHOLD = 64;
202
+ /** And how rarely, so a burst of misses does not each pay for the scan. */
203
+ var SWEEP_INTERVAL_MS = 1e4;
204
+ var Coalesced = class {
205
+ ttlMs;
206
+ entries = /* @__PURE__ */ new Map();
207
+ lastSweep = 0;
208
+ constructor(ttlMs) {
209
+ this.ttlMs = ttlMs;
210
+ }
211
+ /**
212
+ * The result for `key`, computing it only when nothing recent enough is
213
+ * already on its way. The *promise* is kept rather than its value, so a caller
214
+ * arriving mid-flight joins the call in progress instead of starting a second.
215
+ */
216
+ run(key, work) {
217
+ const now = Date.now();
218
+ const cached = this.entries.get(key);
219
+ if (cached && cached.expiry > now) return cached.value;
220
+ if (this.entries.size > SWEEP_THRESHOLD && now - this.lastSweep >= SWEEP_INTERVAL_MS) {
221
+ this.lastSweep = now;
222
+ for (const [other, entry] of this.entries) if (entry.expiry <= now) this.entries.delete(other);
223
+ }
224
+ const entry = {
225
+ expiry: this.ttlMs > 0 ? now + this.ttlMs : Infinity,
226
+ value: Promise.try(work)
227
+ };
228
+ this.entries.set(key, entry);
229
+ const forget = () => {
230
+ if (this.entries.get(key) === entry) this.entries.delete(key);
231
+ };
232
+ entry.value.then(() => {
233
+ if (this.ttlMs <= 0) forget();
234
+ }, forget);
235
+ return entry.value;
236
+ }
237
+ };
238
+ // src/ai/handler.ts
239
+ var requestBodySchema = z.record(z.string(), z.unknown());
240
+ /** The `Authorization` header for a gateway credential, or none when it has none. */
241
+ var bearer = (token) => token ? { authorization: `Bearer ${token}` } : {};
242
+ /**
243
+ * Assistant turns one editor may start per minute, which is how the request
244
+ * ceiling is expressed. A turn is up to `maxSteps` relay requests, so a rate
245
+ * configured beside `maxSteps` could contradict it: raise `maxSteps` past the
246
+ * per-minute budget and a single turn throttles itself halfway through. Deriving
247
+ * the one from the other removes both the knob and the contradiction.
248
+ */
249
+ var TURNS_PER_MINUTE = 4;
250
+ /** Requests one editor may have in flight at once. Streaming, so each is held for a while. */
251
+ var CONCURRENCY$1 = 4;
252
+ var limiter = null;
253
+ function rateLimiter({ maxSteps }) {
254
+ limiter ??= new RateLimiter({
255
+ requests: maxSteps * TURNS_PER_MINUTE,
256
+ windowMs: 6e4,
257
+ concurrency: CONCURRENCY$1
258
+ });
259
+ return limiter;
260
+ }
261
+ /**
262
+ * The request as it is forwarded: the caller's own body with an output ceiling
263
+ * imposed on it. A completion the caller sizes is a bill the caller sizes, so
264
+ * the limit is applied whether or not one was asked for.
265
+ */
266
+ function bounded(body, maxOutputTokens) {
267
+ const field = "max_completion_tokens" in body ? "max_completion_tokens" : "max_tokens";
268
+ const asked = body[field];
269
+ return {
270
+ ...body,
271
+ [field]: typeof asked === "number" ? Math.min(asked, maxOutputTokens) : maxOutputTokens
272
+ };
273
+ }
274
+ function resolveGateway(gateway, request) {
275
+ const address = gatewayAddress(gateway);
276
+ if (!address) {
277
+ const [base, key] = NETLIFY_GATEWAY_ENV.map((name) => getSecret(name));
278
+ if (!base || !key) throw new Error(`Netlify AI Gateway needs ${NETLIFY_GATEWAY_ENV.join(" and ")} together. Unset both to use the injected pair, or set both.`);
279
+ return {
280
+ url: joinUrl(base, "v1/chat/completions"),
281
+ headers: bearer(key)
282
+ };
283
+ }
284
+ const key = address.keys.map((source) => "env" in source ? getSecret(source.env) : request.headers.get(source.header) ?? void 0).find(Boolean);
285
+ return {
286
+ url: joinUrl(address.baseUrl, "chat/completions"),
287
+ headers: {
288
+ ...bearer(key),
289
+ ...address.headers
290
+ }
291
+ };
292
+ }
293
+ async function relay(options) {
294
+ const { ai, caller, fail } = options;
295
+ const slot = rateLimiter(ai).acquire(caller);
296
+ if (!slot.ok) return fail(slot.reason === "concurrency" ? "Too many assistant requests at once. Wait for the current one to finish." : "Too many assistant requests. Wait a moment and try again.", 429);
297
+ options.request.signal.addEventListener("abort", slot.release, { once: true });
298
+ let response;
299
+ try {
300
+ response = await forward(options);
301
+ } catch (err) {
302
+ slot.release();
303
+ throw err;
304
+ }
305
+ if (!response.ok || !response.body) {
306
+ slot.release();
307
+ return response;
308
+ }
309
+ const reader = response.body.getReader();
310
+ const body = new ReadableStream({
311
+ async pull(controller) {
312
+ try {
313
+ const { done, value } = await reader.read();
314
+ if (done) {
315
+ slot.release();
316
+ controller.close();
317
+ return;
318
+ }
319
+ controller.enqueue(value);
320
+ } catch (err) {
321
+ slot.release();
322
+ controller.error(err);
323
+ }
324
+ },
325
+ async cancel(reason) {
326
+ slot.release();
327
+ await reader.cancel(reason);
328
+ }
329
+ });
330
+ return new Response(body, response);
331
+ }
332
+ async function forward({ request, ai, models, fail }) {
333
+ const { limits } = ai;
334
+ let parsed;
335
+ try {
336
+ parsed = JSON.parse(await readBody(request, limits.maxRequestBytes));
337
+ } catch (err) {
338
+ if (err instanceof BodyTooLargeError) return fail(err.message, 413);
339
+ return fail("Malformed request body.", 400);
340
+ }
341
+ const result = requestBodySchema.safeParse(parsed);
342
+ if (!result.success) return fail("A request object is required.", 400);
343
+ const body = result.data;
344
+ const model = body.model;
345
+ if (typeof model !== "string") return fail("A model is required.", 400);
346
+ if (!models.includes(model)) return fail(`Model not allowed: ${model}`, 400);
347
+ let gateway;
348
+ try {
349
+ gateway = resolveGateway(ai.gateway, request);
350
+ } catch (err) {
351
+ console.error("[astronaut-cms] Failed to resolve AI gateway:", err);
352
+ return fail(errorMessage(err, "Gateway not configured"), 500);
353
+ }
354
+ let upstream;
355
+ try {
356
+ upstream = await fetch(gateway.url, {
357
+ method: "POST",
358
+ headers: {
359
+ "content-type": "application/json",
360
+ ...gateway.headers
361
+ },
362
+ body: JSON.stringify(bounded(body, limits.maxOutputTokens)),
363
+ signal: request.signal
364
+ });
365
+ } catch (err) {
366
+ if (request.signal.aborted) return fail("The request was cancelled.", 499);
367
+ console.error(`[astronaut-cms] Failed to reach AI gateway at ${gateway.url}:`, err);
368
+ return fail(`Could not reach the AI gateway at ${gateway.url}.`, 502);
369
+ }
370
+ if (!upstream.ok) {
371
+ const detail = await upstream.text();
372
+ console.error(`[astronaut-cms] AI gateway returned HTTP ${upstream.status}: ${detail}`);
373
+ return new Response(detail, {
374
+ status: upstream.status,
375
+ headers: { "content-type": upstream.headers.get("content-type") ?? "application/json" }
376
+ });
377
+ }
378
+ return new Response(upstream.body, {
379
+ status: upstream.status,
380
+ headers: {
381
+ "content-type": upstream.headers.get("content-type") ?? "text/event-stream",
382
+ "cache-control": "no-cache"
383
+ }
384
+ });
385
+ }
386
+ // src/media/s3-store.ts
387
+ /**
388
+ * The object store a media library lives in, reached through its S3 API with
389
+ * plain `fetch` requests signed by `aws4fetch`, which is small enough to load
390
+ * with the route itself.
391
+ */
392
+ /** How long a presigned upload URL stays valid. Long enough for a slow upload of a large file. */
393
+ var UPLOAD_EXPIRY_SECONDS = 900;
394
+ var MAX_KEYS = 1e3;
395
+ /** A key ending in a slash is a directory placeholder some tools write, never a library file. */
396
+ var isFileKey = (key) => !key.endsWith("/");
397
+ /** An entity tag as a version: unquoted, and absent rather than empty. */
398
+ var versionOf = (etag) => etag?.replace(/^(W\/)?"|"$/g, "") || void 0;
399
+ var ListBucketResult = z.object({ ListBucketResult: z.object({
400
+ Contents: xmlList(z.object({
401
+ Key: z.string(),
402
+ Size: z.coerce.number(),
403
+ ETag: z.string().optional()
404
+ })),
405
+ IsTruncated: z.string().optional(),
406
+ NextContinuationToken: z.string().optional()
407
+ }) });
408
+ /** A copy answers with either its result or, even after a 200, an error. */
409
+ var CopyResponse = z.object({ Error: z.unknown().optional() });
410
+ /** The response itself, or an error carrying what the store said. */
411
+ async function ensureOk(response, action) {
412
+ if (response.ok) return response;
413
+ throw new ApiError(response.status, `S3 ${action} failed: ${await response.text()}`);
414
+ }
415
+ var S3Store = class S3Store {
416
+ client;
417
+ bucket;
418
+ /** The bucket's URL, which keys are joined onto. */
419
+ base;
420
+ constructor(target, credentials) {
421
+ this.bucket = target.bucket;
422
+ this.base = s3BaseUrl(target).href;
423
+ this.client = new AwsClient({
424
+ ...credentials,
425
+ service: "s3",
426
+ region: target.region,
427
+ retries: 2
428
+ });
429
+ }
430
+ /** The store a library names, with the credential from the server's environment. */
431
+ static fromEnv(target) {
432
+ const accessKeyId = getSecret(S3_ACCESS_KEY_ID_ENV);
433
+ const secretAccessKey = getSecret(S3_SECRET_ACCESS_KEY_ENV);
434
+ if (!accessKeyId || !secretAccessKey) throw new Error(`Media storage credentials are missing: set ${S3_ACCESS_KEY_ID_ENV} and ${S3_SECRET_ACCESS_KEY_ENV}.`);
435
+ return new S3Store(target, {
436
+ accessKeyId,
437
+ secretAccessKey,
438
+ sessionToken: getSecret(S3_SESSION_TOKEN_ENV)
439
+ });
440
+ }
441
+ url(key) {
442
+ return new URL(remoteMediaUrl(key, this.base));
443
+ }
444
+ async list(prefix) {
445
+ const objects = [];
446
+ let cursor;
447
+ do {
448
+ const query = {
449
+ "list-type": "2",
450
+ prefix: prefix || void 0,
451
+ "continuation-token": cursor,
452
+ "max-keys": String(MAX_KEYS)
453
+ };
454
+ const url = new URL(this.base);
455
+ url.search = Object.entries(query).flatMap(([name, value]) => value === void 0 ? [] : [`${name}=${encodeURIComponent(value)}`]).join("&");
456
+ const response = await ensureOk(await this.client.fetch(url), `list of "${prefix}"`);
457
+ const { ListBucketResult: result } = parseXml(await response.text(), ListBucketResult);
458
+ for (const { Key: key, Size: size, ETag: etag } of result.Contents) if (key && isFileKey(key)) objects.push({
459
+ key,
460
+ size,
461
+ version: versionOf(etag)
462
+ });
463
+ cursor = result.IsTruncated === "true" ? result.NextContinuationToken : void 0;
464
+ } while (cursor);
465
+ return objects;
466
+ }
467
+ async head(key) {
468
+ const response = await this.client.fetch(this.url(key), { method: "HEAD" });
469
+ if (response.status === 404) return null;
470
+ await ensureOk(response, `HEAD ${key}`);
471
+ return {
472
+ key,
473
+ size: Number(response.headers.get("content-length") ?? 0),
474
+ version: versionOf(response.headers.get("etag") ?? void 0)
475
+ };
476
+ }
477
+ /**
478
+ * Bytes go browser-to-store, so an upload is not bounded by the platform's
479
+ * request-body limit (4.5 MB on Vercel, 6 MB on Netlify). Every term is signed
480
+ * into the URL, which is what makes the route's decisions bind the upload the
481
+ * browser actually makes rather than merely precede it: the URL is usable for
482
+ * that byte count, that type and that precondition and no other. A caller can
483
+ * neither understate a file's size to get an unrestricted PUT, nor choose how
484
+ * the store will serve the bytes back, nor take a destination the route
485
+ * refused it.
486
+ *
487
+ * A type a browser would run as a document gets `Content-Disposition:
488
+ * attachment` signed in too, which the store keeps and serves back.
489
+ */
490
+ async presignUpload(key, terms) {
491
+ const headers = {
492
+ "content-type": terms.contentType,
493
+ ...terms.attachment && { "content-disposition": "attachment" },
494
+ ...terms.ifAbsent && { "if-none-match": "*" }
495
+ };
496
+ const url = this.url(key);
497
+ url.searchParams.set("X-Amz-Expires", String(UPLOAD_EXPIRY_SECONDS));
498
+ return {
499
+ url: (await this.client.sign(url, {
500
+ method: "PUT",
501
+ headers: {
502
+ ...headers,
503
+ "content-length": String(terms.length)
504
+ },
505
+ aws: {
506
+ signQuery: true,
507
+ allHeaders: true
508
+ }
509
+ })).url,
510
+ headers
511
+ };
512
+ }
513
+ async copy(from, to, ifAbsent = false) {
514
+ const body = await (await ensureOk(await this.client.fetch(this.url(to), {
515
+ method: "PUT",
516
+ headers: {
517
+ "x-amz-copy-source": `${this.bucket}/${encodeKeyPath(from)}`,
518
+ ...ifAbsent && { "if-none-match": "*" }
519
+ }
520
+ }), `copy of ${from} to ${to}`)).text();
521
+ if (body && parseXml(body, CopyResponse).Error !== void 0) throw new Error(`S3 copy of ${from} to ${to} failed: ${body}`);
522
+ }
523
+ async remove(key) {
524
+ await ensureOk(await this.client.fetch(this.url(key), { method: "DELETE" }), `DELETE ${key}`);
525
+ }
526
+ };
527
+ // src/server/media.ts
528
+ /**
529
+ * Where a deletion goes instead of being dropped, and what `listTrash` reads
530
+ * back out.
531
+ *
532
+ * An object store keeps no history, so a delete is final in a way a repository
533
+ * delete is not. What may safely be deleted also depends on what content
534
+ * references it, and that is a precondition the store cannot check, so rather
535
+ * than pretend the check is airtight, the operation is made undoable: a stale
536
+ * reference scan, a mis-click or an assistant that read the wrong thing costs a
537
+ * restore rather than the file.
538
+ *
539
+ * The prefix cannot be addressed as a library path, since `toKey` refuses every
540
+ * hidden segment, so it is reachable only through the three methods below.
541
+ * Give it a lifecycle rule to decide how long a deletion stays undoable. Note
542
+ * that a public bucket serves these keys too, so a deleted file stays readable
543
+ * to anyone who knows one until that rule expires it.
544
+ */
545
+ var TRASH_SEGMENT = ".trash";
546
+ /**
547
+ * A trash id is `.trash/<deleted-at>-<original path>`, which carries everything
548
+ * a restore needs without a second place to look it up. The timestamp is all
549
+ * digits and a path cannot start with `-`, so the split is unambiguous even for
550
+ * a file named `2024-notes.png`.
551
+ */
552
+ var trashId = (path, at) => `${TRASH_SEGMENT}/${at}-${path}`;
553
+ var TRASH_ID = /^\.trash\/(\d+)-(.+)$/;
554
+ /**
555
+ * The deletion an id names, or null for anything `trashId` could not have
556
+ * issued. The path has to be one a library file could have had, so a stored key
557
+ * or a caller's id cannot traverse, or point back into a hidden prefix, and the
558
+ * id has to be the exact spelling `trashId` produces for it.
559
+ */
560
+ function parseTrashId(id) {
561
+ const match = TRASH_ID.exec(id);
562
+ if (!match) return null;
563
+ const [, stamp = "", path = ""] = match;
564
+ const deletedAt = Number(stamp);
565
+ return mediaPathError(path) === null && isLibraryFile(path, null) && trashId(path, deletedAt) === id ? {
566
+ deletedAt,
567
+ path
568
+ } : null;
569
+ }
570
+ var ObjectStoreLibrary = class {
571
+ store;
572
+ config;
573
+ library;
574
+ constructor(store, config, library) {
575
+ this.store = store;
576
+ this.config = config;
577
+ this.library = library;
578
+ }
579
+ /** A library path, checked and lowered to the store key it addresses. */
580
+ toKey(path) {
581
+ assertLibraryPath(path, this.library.extensions);
582
+ return `${this.config.prefix}${path}`;
583
+ }
584
+ /**
585
+ * What an upload is allowed to be, settled from the path alone. A store serves
586
+ * back whatever type it was given, so letting the caller choose it is letting
587
+ * the caller choose how the bytes are interpreted.
588
+ */
589
+ terms(path, length, overwrite) {
590
+ checked(413, () => assertWithinSizeLimit(length, this.library));
591
+ const contentType = mediaContentType(path);
592
+ return {
593
+ length,
594
+ contentType,
595
+ attachment: isActiveContentType(contentType),
596
+ ifAbsent: !overwrite
597
+ };
598
+ }
599
+ /**
600
+ * A destination the caller is entitled to write. Only ever the second half of
601
+ * a claim: the write that follows carries the same condition, so this exists
602
+ * to name the conflict rather than to prevent it.
603
+ */
604
+ async assertWritable(key, path, overwrite) {
605
+ if (overwrite || !await this.store.head(key)) return;
606
+ throw new HttpError(`A file already exists at "${path}". Use a different name, or replace it deliberately.`, 409);
607
+ }
608
+ /**
609
+ * Moves an object onto a library key. Conditional in the store, so a
610
+ * destination taken in between refuses rather than being quietly replaced,
611
+ * and the refusal is then named.
612
+ */
613
+ async moveInto(from, key, path) {
614
+ try {
615
+ await this.store.copy(from, key, true);
616
+ } catch (err) {
617
+ await this.assertWritable(key, path, false);
618
+ throw err;
619
+ }
620
+ await this.store.remove(from);
621
+ }
622
+ /** A store's listing carries sizes anyway. */
623
+ listPaths() {
624
+ return this.listMedia();
625
+ }
626
+ async listMedia() {
627
+ return (await this.store.list(this.config.prefix)).map(({ key, size, version }) => ({
628
+ path: key.slice(this.config.prefix.length),
629
+ size,
630
+ ...version && { version }
631
+ })).filter((file) => isLibraryFile(file.path, this.library.extensions));
632
+ }
633
+ /**
634
+ * The public URL a library file is served under. The admin addresses it there
635
+ * directly (see `client/lib/media.ts`), so this only answers a caller that
636
+ * asked the route anyway.
637
+ */
638
+ async readMedia(path) {
639
+ this.toKey(path);
640
+ return { redirect: remoteMediaUrl(path, this.config.publicUrl) };
641
+ }
642
+ async beginUpload(path, size, overwrite) {
643
+ const key = this.toKey(path);
644
+ return {
645
+ direct: true,
646
+ ...await this.store.presignUpload(key, this.terms(path, size, overwrite))
647
+ };
648
+ }
649
+ async renameMedia(from, to) {
650
+ const source = this.toKey(from);
651
+ const target = this.toKey(to);
652
+ await this.moveInto(source, target, to);
653
+ }
654
+ async deleteMedia(path) {
655
+ const key = this.toKey(path);
656
+ await this.store.copy(key, `${this.config.prefix}${trashId(path, Date.now())}`, true);
657
+ await this.store.remove(key);
658
+ }
659
+ /** Newest first, since a restore is nearly always undoing the last thing done. */
660
+ async listTrash() {
661
+ return (await this.store.list(`${this.config.prefix}${TRASH_SEGMENT}/`)).map(({ key, size }) => {
662
+ const id = key.slice(this.config.prefix.length);
663
+ const parsed = parseTrashId(id);
664
+ return parsed && {
665
+ id,
666
+ size,
667
+ ...parsed
668
+ };
669
+ }).filter((file) => file !== null).sort((a, b) => b.deletedAt - a.deletedAt);
670
+ }
671
+ async restoreMedia(id) {
672
+ const { path } = this.parsed(id);
673
+ const key = this.toKey(path);
674
+ await this.moveInto(`${this.config.prefix}${id}`, key, path);
675
+ }
676
+ async purgeTrash(id) {
677
+ this.parsed(id);
678
+ await this.store.remove(`${this.config.prefix}${id}`);
679
+ }
680
+ /** A trash id the library actually issued, rather than any key a caller spells. */
681
+ parsed(id) {
682
+ const parsed = parseTrashId(id);
683
+ if (!parsed) throw new HttpError(`"${id}" is not a deleted file.`, 400);
684
+ return parsed;
685
+ }
686
+ };
687
+ // src/server/storage/api.ts
688
+ /**
689
+ * A REST client for one Git provider, over `fetch` and nothing else.
690
+ *
691
+ * The provider SDKs were 1.1 MB of runtime JavaScript for the twenty-nine
692
+ * endpoints the CMS actually calls, and `@gitbeaker` in particular drags in a
693
+ * Node-only rate limiter and a query-string library that have no business in a
694
+ * Workers bundle. This is the whole of what they were used for.
695
+ *
696
+ * Errors carry the HTTP status, which is the only thing any caller reads off
697
+ * them (see `getErrorStatus`).
698
+ */
699
+ var ApiClient = class {
700
+ baseUrl;
701
+ headers;
702
+ constructor(baseUrl, headers) {
703
+ this.baseUrl = baseUrl;
704
+ this.headers = headers;
705
+ }
706
+ async send({ path, method = "GET", query, body, accept, headers, allow }) {
707
+ const url = new URL(joinUrl(this.baseUrl, path));
708
+ for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
709
+ const response = await fetch(url, {
710
+ method,
711
+ headers: {
712
+ ...this.headers,
713
+ ...headers,
714
+ ...accept && { accept },
715
+ ...body !== void 0 && { "content-type": "application/json" }
716
+ },
717
+ ...body !== void 0 && { body: JSON.stringify(body) }
718
+ });
719
+ if (!response.ok && !allow?.includes(response.status)) throw new ApiError(response.status, await describe(response));
720
+ return response;
721
+ }
722
+ async json(request) {
723
+ return (await this.send(request)).json();
724
+ }
725
+ async text(request) {
726
+ return (await this.send(request)).text();
727
+ }
728
+ async bytes(request) {
729
+ return new Uint8Array(await (await this.send(request)).arrayBuffer());
730
+ }
731
+ /** A call made for its effect, whose body is of no interest. */
732
+ async run(request) {
733
+ await this.send(request);
734
+ }
735
+ };
736
+ var failureSchema = z.object({
737
+ message: z.string().optional(),
738
+ error: z.string().optional()
739
+ });
740
+ /** Both providers answer a failure with `{ message }`; the status is the fallback. */
741
+ async function describe(response) {
742
+ const body = failureSchema.safeParse(await response.json().catch(() => null)).data;
743
+ return body?.message ?? body?.error ?? `${response.status} ${response.statusText}`;
744
+ }
745
+ // src/server/storage/github.ts
746
+ var GITHUB_API = "https://api.github.com";
747
+ /** The GitHub API as the CMS addresses it, with the caller's token attached. */
748
+ function githubClient(token) {
749
+ return new ApiClient(GITHUB_API, {
750
+ authorization: `Bearer ${token}`,
751
+ accept: "application/vnd.github+json",
752
+ "x-github-api-version": "2022-11-28",
753
+ "user-agent": "astronaut-cms"
754
+ });
755
+ }
756
+ var FILE_STATUS = {
757
+ added: "added",
758
+ removed: "deleted",
759
+ modified: "modified",
760
+ renamed: "renamed",
761
+ copied: "added",
762
+ changed: "modified",
763
+ unchanged: "modified"
764
+ };
765
+ var GitHubStorage = class extends BranchedStorage {
766
+ config;
767
+ api;
768
+ treeCache = null;
769
+ constructor(config, options, token) {
770
+ super(options, config.publishMode);
771
+ this.config = config;
772
+ this.api = githubClient(token);
773
+ }
774
+ /** The `repos/owner/repo` prefix every call repeats. */
775
+ get repo() {
776
+ return `repos/${this.config.owner}/${this.config.repo}`;
777
+ }
778
+ get defaultBranch() {
779
+ return this.config.branch;
780
+ }
781
+ async checkBranchExists(branch) {
782
+ return exists(this.api.send({ path: `${this.repo}/git/ref/heads/${branch}` }));
783
+ }
784
+ /**
785
+ * The recursive tree of the current ref. It is the whole repository listing,
786
+ * and every collection and the media library are filtered out of the same one,
787
+ * so it is fetched once per request rather than once per caller.
788
+ */
789
+ async tree() {
790
+ const ref = await this.readRef();
791
+ if (this.treeCache?.ref === ref) return this.treeCache.entries;
792
+ const cache = {
793
+ ref,
794
+ entries: this.api.json({
795
+ path: `${this.repo}/git/trees/${ref}`,
796
+ query: { recursive: "1" }
797
+ }).then(({ tree, truncated }) => {
798
+ if (truncated) throw new Error("GitHub returned an incomplete repository tree.");
799
+ return tree.filter((item) => item.type === "blob").map((item) => ({
800
+ path: item.path,
801
+ size: item.size ?? 0,
802
+ version: item.sha
803
+ }));
804
+ }).catch((error) => {
805
+ if (this.treeCache === cache) this.treeCache = null;
806
+ throw error;
807
+ })
808
+ };
809
+ this.treeCache = cache;
810
+ return cache.entries;
811
+ }
812
+ async globPaths(col) {
813
+ const roots = globRoots(col);
814
+ return (await this.tree()).values().map((item) => item.path).filter((path) => roots.some((root) => inGlobRoot(path, root)));
815
+ }
816
+ /**
817
+ * The contents API narrowed to the one file it was asked for. The `object`
818
+ * media type is what raises the 1 MB ceiling to 100 MB and guarantees an
819
+ * object rather than a directory array, so it is what a `download_url` needs.
820
+ */
821
+ async getRepoFile(path, asObject = false, ref) {
822
+ const file = await this.api.json({
823
+ path: `${this.repo}/contents/${encodeKeyPath(path)}`,
824
+ query: { ref: ref ?? await this.readRef() },
825
+ ...asObject && { accept: "application/vnd.github.object+json" }
826
+ });
827
+ if (file.type !== "file") throw new Error(`Expected file at ${path}`);
828
+ return file;
829
+ }
830
+ async fetchFileContent(path) {
831
+ const file = await this.getRepoFile(path);
832
+ if (file.encoding === "base64") return {
833
+ content: fromBase64(file.content ?? ""),
834
+ version: file.sha
835
+ };
836
+ const blob = await this.api.json({ path: `${this.repo}/git/blobs/${file.sha}` });
837
+ if (blob.encoding !== "base64") throw new Error(`Unsupported encoding for ${path}`);
838
+ return {
839
+ content: fromBase64(blob.content),
840
+ version: file.sha
841
+ };
842
+ }
843
+ /**
844
+ * The blob hash at `path` on one commit, or undefined when it holds no such
845
+ * file. Read against the commit the write will be based on rather than against
846
+ * the branch, so what is checked and what is committed cannot be two different
847
+ * states.
848
+ */
849
+ async blobShaAt(path, ref) {
850
+ try {
851
+ return (await this.getRepoFile(path, false, ref)).sha;
852
+ } catch (err) {
853
+ if (getErrorStatus(err) === 404) return void 0;
854
+ throw err;
855
+ }
856
+ }
857
+ async listMedia() {
858
+ return this.mediaFiles(await this.tree());
859
+ }
860
+ async commitFile(path, content, message, precondition) {
861
+ return this.commitBlob(path, content, "utf-8", message, precondition);
862
+ }
863
+ async removeFile(path, message, expectedVersion) {
864
+ await this.commitTree([{
865
+ path,
866
+ mode: "100644",
867
+ type: "blob",
868
+ sha: null
869
+ }], message, void 0, preconditionsFor(path, versioned(expectedVersion)));
870
+ }
871
+ async writeMedia(repoPath, bytes, overwrite) {
872
+ await this.commitBlob(repoPath, bytes.toBase64(), "base64", `Upload ${repoPath}`, overwrite ? void 0 : { absent: true });
873
+ }
874
+ /**
875
+ * A repository file has no public URL. The contents API answers with a
876
+ * `download_url` carrying its own short-lived token for a private repository,
877
+ * so the browser loads the bytes itself rather than through this server,
878
+ * except when the caller addressed a version, which a redirect cannot promise
879
+ * to keep and which the route therefore serves itself. The blob hash comes
880
+ * back from the same call, so naming it costs nothing.
881
+ */
882
+ async readMedia(path) {
883
+ const { download_url, sha } = await this.getRepoFile(this.mediaRepoPath(path), true);
884
+ if (!download_url) throw new Error(`No download URL for ${path}`);
885
+ return {
886
+ redirect: download_url,
887
+ version: sha
888
+ };
889
+ }
890
+ async moveMedia(from, to) {
891
+ const { sha } = await this.getRepoFile(from);
892
+ await this.commitTree([{
893
+ path: to,
894
+ mode: "100644",
895
+ type: "blob",
896
+ sha
897
+ }, {
898
+ path: from,
899
+ mode: "100644",
900
+ type: "blob",
901
+ sha: null
902
+ }], `Rename ${from} to ${to}`, void 0, [{
903
+ path: from,
904
+ precondition: { version: sha }
905
+ }, {
906
+ path: to,
907
+ precondition: { absent: true }
908
+ }]);
909
+ }
910
+ async removeMedia(repoPath) {
911
+ await this.removeFile(repoPath, `Delete ${repoPath}`);
912
+ }
913
+ async doUpdate(branch) {
914
+ this.treeCache = null;
915
+ try {
916
+ await this.api.run({
917
+ path: `${this.repo}/merges`,
918
+ method: "POST",
919
+ body: {
920
+ base: branch,
921
+ head: this.config.branch,
922
+ commit_message: `Merge ${this.config.branch} into ${branch}`
923
+ }
924
+ });
925
+ } catch (err) {
926
+ const status = getErrorStatus(err);
927
+ if (status === 405 || status === 409) throw new MergeConflictError();
928
+ throw err;
929
+ }
930
+ }
931
+ async compare(branch) {
932
+ return this.api.json({ path: `${this.repo}/compare/${this.config.branch}...${branch}` });
933
+ }
934
+ async computeBehind(branch) {
935
+ return (await this.compare(branch)).behind_by;
936
+ }
937
+ async diffAgainstDefault(branch) {
938
+ return ((await this.compare(branch)).files ?? []).map((file) => ({
939
+ path: file.filename,
940
+ kind: FILE_STATUS[file.status] ?? "modified",
941
+ previousPath: file.previous_filename,
942
+ patch: file.patch,
943
+ version: file.sha
944
+ }));
945
+ }
946
+ async findOpenChangeRequest(branch) {
947
+ const [first] = await this.api.json({
948
+ path: `${this.repo}/pulls`,
949
+ query: {
950
+ state: "open",
951
+ head: `${this.config.owner}:${branch}`
952
+ }
953
+ });
954
+ return first ? summarize$1(first) : null;
955
+ }
956
+ async createChangeRequest(branch) {
957
+ return summarize$1(await this.api.json({
958
+ path: `${this.repo}/pulls`,
959
+ method: "POST",
960
+ body: {
961
+ title: this.changeRequestTitle(branch),
962
+ head: branch,
963
+ base: this.config.branch,
964
+ body: this.changeRequestBody(branch)
965
+ }
966
+ }));
967
+ }
968
+ async closeChangeRequest(id) {
969
+ await this.api.run({
970
+ path: `${this.repo}/pulls/${id}`,
971
+ method: "PATCH",
972
+ body: { state: "closed" }
973
+ });
974
+ }
975
+ async acceptChangeRequest(request) {
976
+ await this.api.run({
977
+ path: `${this.repo}/pulls/${request.id}/merge`,
978
+ method: "PUT",
979
+ body: {
980
+ merge_method: "squash",
981
+ commit_title: `${request.title} (#${request.id})`
982
+ }
983
+ });
984
+ }
985
+ async deleteUserBranch(branch) {
986
+ await this.api.run({
987
+ path: `${this.repo}/git/refs/heads/${branch}`,
988
+ method: "DELETE"
989
+ });
990
+ }
991
+ /**
992
+ * A file's new content, uploaded as a blob and committed in one tree entry.
993
+ * The upload and the parent lookup are independent, so they overlap: this is
994
+ * the path every content save and every repository media upload takes.
995
+ */
996
+ async commitBlob(path, content, encoding, message, precondition) {
997
+ const [blob, parentSha] = await Promise.all([this.api.json({
998
+ path: `${this.repo}/git/blobs`,
999
+ method: "POST",
1000
+ body: {
1001
+ content,
1002
+ encoding
1003
+ }
1004
+ }), this.parentSha()]);
1005
+ await this.commitTree([{
1006
+ path,
1007
+ mode: "100644",
1008
+ type: "blob",
1009
+ sha: blob.sha
1010
+ }], message, parentSha, preconditionsFor(path, precondition));
1011
+ return blob.sha;
1012
+ }
1013
+ /** The commit the next one builds on: the draft branch's tip, or the default branch's. */
1014
+ async parentSha() {
1015
+ const branchExists = await this.branchExists();
1016
+ return (await this.api.json({ path: `${this.repo}/git/ref/heads/${branchExists ? this.branch : this.config.branch}` })).object.sha;
1017
+ }
1018
+ /** The commit funnel, and therefore where the cached tree stops being current. */
1019
+ async commitTree(treeEntries, message, knownParent, preconditions = []) {
1020
+ const parentSha = knownParent ?? await this.parentSha();
1021
+ const [checked, parentCommit] = await Promise.all([Promise.all(preconditions.map(async (required) => ({
1022
+ ...required,
1023
+ actual: await this.blobShaAt(required.path, parentSha)
1024
+ }))), this.api.json({ path: `${this.repo}/git/commits/${parentSha}` })]);
1025
+ const failed = checked.find(({ actual, precondition }) => !satisfies(actual, precondition));
1026
+ if (failed) throw staleWrite(failed.path);
1027
+ const tree = await this.api.json({
1028
+ path: `${this.repo}/git/trees`,
1029
+ method: "POST",
1030
+ body: {
1031
+ base_tree: parentCommit.tree.sha,
1032
+ tree: treeEntries
1033
+ }
1034
+ });
1035
+ const commit = await this.api.json({
1036
+ path: `${this.repo}/git/commits`,
1037
+ method: "POST",
1038
+ body: {
1039
+ message,
1040
+ tree: tree.sha,
1041
+ parents: [parentSha]
1042
+ }
1043
+ });
1044
+ if (await this.branchExists()) await this.api.run({
1045
+ path: `${this.repo}/git/refs/heads/${this.branch}`,
1046
+ method: "PATCH",
1047
+ body: { sha: commit.sha }
1048
+ });
1049
+ else {
1050
+ await this.api.run({
1051
+ path: `${this.repo}/git/refs`,
1052
+ method: "POST",
1053
+ body: {
1054
+ ref: `refs/heads/${this.branch}`,
1055
+ sha: commit.sha
1056
+ }
1057
+ });
1058
+ this.markBranchExists(true);
1059
+ }
1060
+ this.treeCache = null;
1061
+ }
1062
+ };
1063
+ /** One path's precondition in the shape `commitTree` checks, or nothing to check. */
1064
+ var preconditionsFor = (path, precondition) => precondition === void 0 ? [] : [{
1065
+ path,
1066
+ precondition
1067
+ }];
1068
+ var summarize$1 = (pull) => ({
1069
+ id: pull.number,
1070
+ title: pull.title,
1071
+ url: pull.html_url
1072
+ });
1073
+ // src/server/storage/gitlab.ts
1074
+ /** The GitLab API of one instance, with the caller's token attached. */
1075
+ function gitlabClient(instanceUrl, token, api = "api/v4") {
1076
+ return new ApiClient(joinUrl(instanceUrl, api), { authorization: `Bearer ${token}` });
1077
+ }
1078
+ /** A page of the repository tree API. */
1079
+ var treeSchema = z.array(z.object({
1080
+ type: z.string(),
1081
+ path: z.string(),
1082
+ id: z.string()
1083
+ }));
1084
+ /**
1085
+ * The tree API reports no sizes, so they come from GraphQL, which names many
1086
+ * blobs per request. `rawSize` is the file itself where the blob is an LFS
1087
+ * pointer. Both are `BigInt` scalars, which GitLab serializes as strings.
1088
+ */
1089
+ var BLOB_SIZES = `query ($project: ID!, $ref: String!, $paths: [String!]!) {
1090
+ project(fullPath: $project) {
1091
+ repository { blobs(ref: $ref, paths: $paths) { nodes { path size rawSize } } }
1092
+ }
1093
+ }`;
1094
+ var blobSizesSchema = z.object({
1095
+ data: z.object({ project: z.object({ repository: z.object({ blobs: z.object({ nodes: z.array(z.object({
1096
+ path: z.string(),
1097
+ size: z.coerce.number(),
1098
+ rawSize: z.coerce.number().nullish()
1099
+ })) }) }) }).nullable() }).nullish(),
1100
+ errors: z.array(z.object({ message: z.string() })).optional()
1101
+ });
1102
+ /** How many blobs one size query names, well inside GitLab's query complexity limit. */
1103
+ var BLOB_BATCH = 100;
1104
+ var summarize = (mr) => ({
1105
+ id: mr.iid,
1106
+ title: mr.title,
1107
+ url: mr.web_url
1108
+ });
1109
+ var GitLabStorage = class extends BranchedStorage {
1110
+ config;
1111
+ api;
1112
+ graphql;
1113
+ /**
1114
+ * Listings already made this request, keyed by ref and path. Every collection
1115
+ * and the media library walk the tree separately, and the walk is paginated,
1116
+ * so a reference scan would otherwise re-page the same subtree once per
1117
+ * collection. GitHub's `treeCache` is the same idea over one whole-repository
1118
+ * listing; GitLab has no recursive-everything endpoint worth the payload.
1119
+ */
1120
+ trees = /* @__PURE__ */ new Map();
1121
+ constructor(config, options, token) {
1122
+ super(options, config.publishMode);
1123
+ this.config = config;
1124
+ this.api = gitlabClient(config.instanceUrl, token);
1125
+ this.graphql = gitlabClient(config.instanceUrl, token, "api/graphql");
1126
+ }
1127
+ /** The `projects/<id>` prefix every call repeats; the id is a path, so it is encoded whole. */
1128
+ get project() {
1129
+ return `projects/${encodeURIComponent(this.config.project)}`;
1130
+ }
1131
+ get defaultBranch() {
1132
+ return this.config.branch;
1133
+ }
1134
+ async checkBranchExists(branch) {
1135
+ return exists(this.api.send({ path: `${this.project}/repository/branches/${encodeURIComponent(branch)}` }));
1136
+ }
1137
+ /**
1138
+ * Every blob below `path`, or only those directly in it. GitLab pages this
1139
+ * endpoint and reports the next page in a header, so a repository larger than
1140
+ * one page would otherwise be listed down to its first hundred files.
1141
+ */
1142
+ async listTree(path, recursive = true) {
1143
+ const ref = await this.readRef();
1144
+ return memoized(this.trees, `${ref}:${recursive}:${path}`, () => this.walkTree(path, ref, recursive));
1145
+ }
1146
+ async walkTree(path, ref, recursive) {
1147
+ const found = [];
1148
+ let page = "1";
1149
+ while (page) {
1150
+ const response = await this.api.send({
1151
+ path: `${this.project}/repository/tree`,
1152
+ query: {
1153
+ path,
1154
+ ref,
1155
+ recursive,
1156
+ per_page: 100,
1157
+ page
1158
+ }
1159
+ });
1160
+ const items = treeSchema.parse(await response.json());
1161
+ found.push(...items.filter((item) => item.type === "blob").map((item) => ({
1162
+ path: item.path,
1163
+ version: item.id
1164
+ })));
1165
+ page = response.headers.get("x-next-page") ?? "";
1166
+ }
1167
+ return found;
1168
+ }
1169
+ async globPaths(col) {
1170
+ return (await Promise.all(globRoots(col).map(({ path, file }) => file ? this.listTree(projectPath(dirname(path)), false) : this.listTree(path)))).flat().map((item) => item.path);
1171
+ }
1172
+ /** A repository file's own bytes. GitLab encodes the whole path as one segment. */
1173
+ filePath(path) {
1174
+ return `${this.project}/repository/files/${encodeURIComponent(path)}`;
1175
+ }
1176
+ /**
1177
+ * The JSON form rather than `/raw`: it carries `last_commit_id` beside the
1178
+ * bytes, so a read costs one request and still knows what state it saw.
1179
+ */
1180
+ async fetchFileContent(path) {
1181
+ const file = await this.api.json({
1182
+ path: this.filePath(path),
1183
+ query: { ref: await this.readRef() }
1184
+ });
1185
+ return {
1186
+ content: fromBase64(file.content),
1187
+ version: file.last_commit_id
1188
+ };
1189
+ }
1190
+ /** The tree alone, which names every file but none of their sizes. */
1191
+ async listPaths() {
1192
+ return this.mediaFiles(await this.listTree(this.mediaDirectory));
1193
+ }
1194
+ async listMedia() {
1195
+ const files = await this.listPaths();
1196
+ const repoPath = (file) => join(this.mediaDirectory, file.path);
1197
+ const sizes = await this.blobSizes(files.map(repoPath));
1198
+ return files.map((file) => ({
1199
+ ...file,
1200
+ size: sizes.get(repoPath(file)) ?? 0
1201
+ }));
1202
+ }
1203
+ /** The size of each blob at `paths`, batched, since a size is what an upload limit is checked against. */
1204
+ async blobSizes(paths) {
1205
+ const ref = await this.readRef();
1206
+ const batches = await Promise.all(Array.from({ length: Math.ceil(paths.length / BLOB_BATCH) }, async (_, i) => {
1207
+ const { data, errors } = blobSizesSchema.parse(await this.graphql.json({
1208
+ path: "",
1209
+ method: "POST",
1210
+ body: {
1211
+ query: BLOB_SIZES,
1212
+ variables: {
1213
+ project: this.config.project,
1214
+ ref,
1215
+ paths: paths.slice(i * BLOB_BATCH, (i + 1) * BLOB_BATCH)
1216
+ }
1217
+ }
1218
+ }));
1219
+ if (errors?.length) throw new Error(`GitLab: ${errors.map((e) => e.message).join("; ")}`);
1220
+ return data?.project?.repository.blobs.nodes ?? [];
1221
+ }));
1222
+ return new Map(batches.flat().map((blob) => [blob.path, blob.rawSize ?? blob.size]));
1223
+ }
1224
+ async commitFile(path, content, message, precondition) {
1225
+ return this.commitUpsert(path, content, message, void 0, precondition);
1226
+ }
1227
+ async removeFile(path, message, expectedVersion) {
1228
+ await this.commit({
1229
+ action: "delete",
1230
+ file_path: path,
1231
+ ...expectedVersion !== void 0 && { last_commit_id: expectedVersion }
1232
+ }, message);
1233
+ }
1234
+ async writeMedia(repoPath, bytes, overwrite) {
1235
+ await this.commitUpsert(repoPath, bytes.toBase64(), `Upload ${repoPath}`, "base64", overwrite ? void 0 : { absent: true });
1236
+ }
1237
+ /**
1238
+ * GitLab has no pre-signed download URL, so the bytes travel through this
1239
+ * server, streamed and relayed through {@link fetchRange} exactly as GitHub's
1240
+ * are when the route proxies its download URL.
1241
+ */
1242
+ async readMedia(path, range) {
1243
+ const ref = await this.readRef();
1244
+ const { headers, ...bytes } = await fetchRange((forwarded) => this.api.send({
1245
+ path: `${this.filePath(this.mediaRepoPath(path))}/raw`,
1246
+ query: { ref },
1247
+ headers: forwarded,
1248
+ allow: [416]
1249
+ }), range);
1250
+ return {
1251
+ ...bytes,
1252
+ version: headers.get("x-gitlab-blob-id") ?? void 0
1253
+ };
1254
+ }
1255
+ async moveMedia(from, to) {
1256
+ await this.commit({
1257
+ action: "move",
1258
+ file_path: to,
1259
+ previous_path: from
1260
+ }, `Rename ${from} to ${to}`);
1261
+ }
1262
+ async removeMedia(repoPath) {
1263
+ await this.removeFile(repoPath, `Delete ${repoPath}`);
1264
+ }
1265
+ async doUpdate(branch) {
1266
+ if (await this.computeBehind(branch) === 0) return;
1267
+ let iid;
1268
+ try {
1269
+ iid = (await this.createMergeRequest(this.config.branch, branch, `Sync ${this.config.branch} into ${branch}`, "Auto-merge from Astronaut CMS update.")).iid;
1270
+ } catch (err) {
1271
+ if (getErrorStatus(err) === 409) return;
1272
+ throw err;
1273
+ }
1274
+ try {
1275
+ await this.acceptMergeRequest(iid, {});
1276
+ } catch (err) {
1277
+ await this.api.run({
1278
+ path: `${this.project}/merge_requests/${iid}`,
1279
+ method: "DELETE"
1280
+ }).catch(() => void 0);
1281
+ throw err;
1282
+ }
1283
+ }
1284
+ async compare(from, to) {
1285
+ return this.api.json({
1286
+ path: `${this.project}/repository/compare`,
1287
+ query: {
1288
+ from,
1289
+ to
1290
+ }
1291
+ });
1292
+ }
1293
+ async diffAgainstDefault(branch) {
1294
+ const cmp = await this.compare(this.config.branch, branch);
1295
+ return (cmp.diffs ?? []).map((diff) => ({
1296
+ path: diff.new_path,
1297
+ kind: diff.new_file ? "added" : diff.deleted_file ? "deleted" : diff.renamed_file ? "renamed" : "modified",
1298
+ previousPath: diff.renamed_file ? diff.old_path : void 0,
1299
+ patch: diff.diff || void 0,
1300
+ version: diff.diff ? void 0 : cmp.commit?.id
1301
+ }));
1302
+ }
1303
+ async computeBehind(branch) {
1304
+ return (await this.compare(branch, this.config.branch)).commits?.length ?? 0;
1305
+ }
1306
+ async findOpenChangeRequest(branch) {
1307
+ const [first] = await this.api.json({
1308
+ path: `${this.project}/merge_requests`,
1309
+ query: {
1310
+ source_branch: branch,
1311
+ state: "opened"
1312
+ }
1313
+ });
1314
+ return first ? summarize(first) : null;
1315
+ }
1316
+ async createMergeRequest(source, target, title, description) {
1317
+ return this.api.json({
1318
+ path: `${this.project}/merge_requests`,
1319
+ method: "POST",
1320
+ body: {
1321
+ source_branch: source,
1322
+ target_branch: target,
1323
+ title,
1324
+ description
1325
+ }
1326
+ });
1327
+ }
1328
+ async createChangeRequest(branch) {
1329
+ return summarize(await this.createMergeRequest(branch, this.config.branch, this.changeRequestTitle(branch), this.changeRequestBody(branch)));
1330
+ }
1331
+ async closeChangeRequest(id) {
1332
+ await this.api.run({
1333
+ path: `${this.project}/merge_requests/${id}`,
1334
+ method: "PUT",
1335
+ body: { state_event: "close" }
1336
+ });
1337
+ }
1338
+ async acceptChangeRequest(request) {
1339
+ await this.acceptMergeRequest(request.id, {
1340
+ squash: true,
1341
+ should_remove_source_branch: true,
1342
+ squash_commit_message: request.title
1343
+ });
1344
+ }
1345
+ async deleteUserBranch(branch) {
1346
+ await this.api.run({
1347
+ path: `${this.project}/repository/branches/${encodeURIComponent(branch)}`,
1348
+ method: "DELETE"
1349
+ });
1350
+ }
1351
+ async commitUpsert(path, content, message, encoding, precondition) {
1352
+ const version = precondition && "version" in precondition ? precondition.version : void 0;
1353
+ const present = precondition === void 0 ? await exists(this.api.send({
1354
+ path: this.filePath(path),
1355
+ query: { ref: await this.readRef() }
1356
+ })) : version !== void 0;
1357
+ return this.commit({
1358
+ action: present ? "update" : "create",
1359
+ file_path: path,
1360
+ content,
1361
+ encoding,
1362
+ ...present && version !== void 0 && { last_commit_id: version }
1363
+ }, message);
1364
+ }
1365
+ async commit(action, message) {
1366
+ const branchExists = await this.branchExists();
1367
+ this.trees.clear();
1368
+ let created;
1369
+ try {
1370
+ created = await this.api.json({
1371
+ path: `${this.project}/repository/commits`,
1372
+ method: "POST",
1373
+ body: {
1374
+ branch: this.branch,
1375
+ commit_message: message,
1376
+ actions: [action],
1377
+ ...branchExists ? {} : { start_branch: this.config.branch }
1378
+ }
1379
+ });
1380
+ } catch (err) {
1381
+ if ((action.action === "create" || action.last_commit_id !== void 0) && getErrorStatus(err) === 400) throw staleWrite(action.file_path);
1382
+ throw err;
1383
+ }
1384
+ if (!branchExists) this.markBranchExists(true);
1385
+ return created.id;
1386
+ }
1387
+ async acceptMergeRequest(iid, options) {
1388
+ try {
1389
+ await this.api.run({
1390
+ path: `${this.project}/merge_requests/${iid}/merge`,
1391
+ method: "PUT",
1392
+ body: options
1393
+ });
1394
+ } catch (err) {
1395
+ const mr = await this.api.json({ path: `${this.project}/merge_requests/${iid}` }).catch(() => null);
1396
+ if (mr?.merge_status === "cannot_be_merged" || mr?.merge_status === "cannot_be_merged_recheck") throw new MergeConflictError(mr.merge_error ?? void 0);
1397
+ throw err;
1398
+ }
1399
+ }
1400
+ };
1401
+ // src/shared/unreachable.ts
1402
+ /** Compile-time exhaustiveness for a closed union, and a fail-closed throw if one grows. */
1403
+ function unreachable(value, message) {
1404
+ throw new Error(`${message}: ${JSON.stringify(value)}`);
1405
+ }
1406
+ // src/server/storage/index.ts
1407
+ /**
1408
+ * The backend for one request, built from the session that request carries.
1409
+ *
1410
+ * Constructed per request on purpose. A serverless instance is shared between
1411
+ * editors or discarded between clicks, so a backend that outlived a request
1412
+ * would either leak one editor's token into another's call or cache a listing
1413
+ * nobody can trust. Everything it memoizes (the repository tree, whether the
1414
+ * draft branch exists) is therefore scoped to the request that needs it.
1415
+ */
1416
+ function createStorage(session, library = "repo") {
1417
+ const { storage } = server;
1418
+ const options = {
1419
+ collections: client.collections,
1420
+ media: client.media,
1421
+ library: workingTreeLibrary(library),
1422
+ components,
1423
+ login: session.login
1424
+ };
1425
+ switch (storage.type) {
1426
+ case "github": return new GitHubStorage(storage, options, session.token);
1427
+ case "gitlab": return new GitLabStorage(storage, options, session.token);
1428
+ case "local":
1429
+ if (!LocalStorage) throw new Error("Local storage is only available in `astro dev`.");
1430
+ return new LocalStorage(storage, options);
1431
+ default: return unreachable(storage, "Unknown storage type");
1432
+ }
1433
+ }
1434
+ /**
1435
+ * The library a backend instance serves from the working tree or repository:
1436
+ * the repository library, or the object store's stand-in during a dev run.
1437
+ */
1438
+ function workingTreeLibrary(id) {
1439
+ const library = mediaLibrary(client.media, id);
1440
+ if (library.directory == null) throw new Error(`The ${id} media library is not kept in the project.`);
1441
+ return {
1442
+ ...library,
1443
+ directory: library.directory
1444
+ };
1445
+ }
1446
+ // src/server/context.ts
1447
+ /**
1448
+ * Everything one request is allowed to touch, assembled from the session it
1449
+ * carries. An operation receives this and nothing else, so it cannot reach a
1450
+ * credential, an environment variable or a store the request did not earn.
1451
+ */
1452
+ /**
1453
+ * The object store for this request: the bucket, or, in a dev run, a second
1454
+ * working-tree backend rooted at the store's dev directory.
1455
+ */
1456
+ function openObjectStore(session) {
1457
+ const s3 = client.media.s3;
1458
+ if (!s3) throw new HttpError("No object-store media library is configured.", 404);
1459
+ if (s3.directory != null) return createStorage(session, "s3");
1460
+ if (!server.media) throw new Error("The object store is not configured for this server.");
1461
+ return new ObjectStoreLibrary(S3Store.fromEnv(server.media.s3), server.media, s3);
1462
+ }
1463
+ function createContext(session) {
1464
+ const storage = createStorage(session);
1465
+ let objectStore = null;
1466
+ const media = (library) => library === "repo" ? storage : objectStore ??= openObjectStore(session);
1467
+ storage.useMediaLibraries(media);
1468
+ return {
1469
+ session,
1470
+ storage,
1471
+ media
1472
+ };
1473
+ }
1474
+ // src/shared/references.ts
1475
+ /**
1476
+ * What the reference scan produces and how the admin reads it. The index is
1477
+ * built on the server (see `server/references.ts`) and travels as JSON, so it is
1478
+ * a list of pairs rather than a Map; everything derived from it is a pure
1479
+ * function and lives here, where both sides can reach it.
1480
+ */
1481
+ /** A reference an entry holds. */
1482
+ var assetReferenceSchema = z.object({
1483
+ collection: z.string(),
1484
+ entryId: z.string(),
1485
+ /** The field or prop holding it, or the body it was found in. */
1486
+ where: z.string(),
1487
+ /** False when only a textual match backs it, e.g. a markdown image. */
1488
+ declared: z.boolean()
1489
+ });
1490
+ /** Library and path, as one key. */
1491
+ var fileKey = (library, path) => `${library}:${path}`;
1492
+ /** How a reference reads wherever one is shown. */
1493
+ function describeReference(reference) {
1494
+ return `${reference.collection} / ${reference.entryId} (${reference.where})`;
1495
+ }
1496
+ /** What reaches one file, from an index the caller already has. */
1497
+ function referencesFor(index, { library, path }) {
1498
+ return index.find((file) => file.library === library && file.path === path)?.references ?? [];
1499
+ }
1500
+ // src/server/parallel.ts
1501
+ /** How many reads may be in flight at once, which keeps a provider's rate limit in reach. */
1502
+ var CONCURRENCY = 10;
1503
+ /** A worker pool: a fixed number of readers sharing one iterator, with no barriers. */
1504
+ async function inParallel(items, fn) {
1505
+ const cursor = items.values();
1506
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {
1507
+ for (const item of cursor) await fn(item);
1508
+ }));
1509
+ }
1510
+ // src/server/references.ts
1511
+ /**
1512
+ * What reaches which library file.
1513
+ *
1514
+ * The authoritative half is schema-driven: a value is an asset because its
1515
+ * schema says so, never because the string looks like a path. That misses prose
1516
+ * and Markdoc tags, which a textual pass covers too.
1517
+ * A hit there is reported as undeclared: it means "something mentions this",
1518
+ * which is all that is needed to stop a deletion.
1519
+ *
1520
+ * It runs here rather than in the admin because it is what a rename or a
1521
+ * deletion is refused on. A precondition only the caller checks is caller
1522
+ * discipline; this one is a rule of the library.
1523
+ */
1524
+ /**
1525
+ * Paths and object-store URLs a body mentions with no schema to declare them.
1526
+ * Only a match under a library counts, with an extension that library admits,
1527
+ * so ordinary prose cannot produce one. Bounded as well to a path-sized run:
1528
+ * the leading class contains `.` too, so an unbounded one backtracks
1529
+ * quadratically over a long stretch of dots that ends in no extension.
1530
+ */
1531
+ function* textualPaths(body) {
1532
+ for (const [match] of body.matchAll(/(?:https?:)?[\w@.%/-]{1,200}\.[a-zA-Z0-9]+/g)) yield match;
1533
+ }
1534
+ function indexEntry(index, col, entry) {
1535
+ const base = entry.path;
1536
+ const declared = /* @__PURE__ */ new Set();
1537
+ const add = (value, where, isDeclared) => {
1538
+ const location = mediaPath(value, client.media, base);
1539
+ if (location == null) return;
1540
+ const key = fileKey(location.library, location.path);
1541
+ if (isDeclared) declared.add(key);
1542
+ else {
1543
+ const { extensions } = mediaLibrary(client.media, location.library);
1544
+ if (declared.has(key) || !isLibraryFile(location.path, extensions)) return;
1545
+ }
1546
+ const reference = {
1547
+ collection: col.name,
1548
+ entryId: entry.id,
1549
+ where,
1550
+ declared: isDeclared
1551
+ };
1552
+ const existing = index.get(key);
1553
+ if (existing) existing.references.push(reference);
1554
+ else index.set(key, {
1555
+ ...location,
1556
+ references: [reference]
1557
+ });
1558
+ };
1559
+ const body = validateBody(entry.body, entry.format, components);
1560
+ for (const leaf of [...dataLeaves(col.schema, entry.data), ...body.leaves]) if (isAsset(leaf)) add(leaf.value, leaf.path, true);
1561
+ for (const url of body.images) add(url, "markdown image", true);
1562
+ for (const value of textualPaths(entry.body)) add(value, "body", false);
1563
+ }
1564
+ /**
1565
+ * Walks every entry of every collection: one read per entry, so it is built on
1566
+ * demand rather than refreshed eagerly. Collections are listed together, then
1567
+ * their entries read through one bounded pool.
1568
+ *
1569
+ * A read that fails takes the whole scan with it. The index is what deletions
1570
+ * and renames are checked against, and an entry that could not be read cannot be
1571
+ * shown to reference nothing: skipping it would turn a transient provider error
1572
+ * into a file classified as unused and a destructive operation waved through.
1573
+ */
1574
+ async function buildReferenceIndex(storage) {
1575
+ const index = /* @__PURE__ */ new Map();
1576
+ await inParallel((await Promise.all(Object.values(client.collections).map(async (col) => (await storage.listEntries(col.name)).map((meta) => ({
1577
+ col,
1578
+ meta
1579
+ }))))).flat(), async ({ col, meta }) => {
1580
+ indexEntry(index, col, await storage.readEntry(meta));
1581
+ });
1582
+ return [...index.values()];
1583
+ }
1584
+ // src/server/operations.ts
1585
+ /**
1586
+ * Everything the CMS can do, in one place.
1587
+ *
1588
+ * This registry is the security boundary, not the session cookie. A cookie
1589
+ * decides *who* is asking; this decides what asking can accomplish. Every
1590
+ * operation names a CMS capability (an entry in a collection, a file in the
1591
+ * library), and none of them takes a repository path, a ref, a commit or a
1592
+ * provider parameter, so a browser that has been fully compromised can still
1593
+ * only do the things an editor could have done through the UI, and nothing
1594
+ * wider.
1595
+ *
1596
+ * It is also the only contract: the typed client, the assistant's tools and (in
1597
+ * time) an MCP adapter are all projections of this object, so none of them can
1598
+ * drift from what the server actually accepts.
1599
+ */
1600
+ function op(schema, handler) {
1601
+ return {
1602
+ schema,
1603
+ run: (ctx, raw) => {
1604
+ const parsed = schema.safeParse(raw);
1605
+ if (!parsed.success) throw new ContentValidationError(parsed.error.issues.map((issue) => diagnostic(issue.message, issue.path.join(".") || void 0)));
1606
+ return handler(ctx, parsed.data);
1607
+ }
1608
+ };
1609
+ }
1610
+ var ok = { ok: true };
1611
+ var none = z.object({});
1612
+ var collection = collectionEnum(client.collections);
1613
+ var entryRef = z.object({
1614
+ collection,
1615
+ id: z.string()
1616
+ });
1617
+ /**
1618
+ * The version the caller read, echoed back so a write cannot silently discard
1619
+ * one that landed in between. Opaque here: it is handed straight to the backend,
1620
+ * which compares it, so nothing in between ever treats it as a ref.
1621
+ */
1622
+ var expectedVersion = z.string().optional();
1623
+ var rename = entryRef.extend({ newId: z.string() });
1624
+ var saveRequest = z.object({
1625
+ data: z.record(z.string(), z.unknown()),
1626
+ body: z.string(),
1627
+ format: z.enum(ALL_FORMATS),
1628
+ createOnly: z.boolean().optional(),
1629
+ expectedVersion
1630
+ });
1631
+ var mediaPathSchema = z.string().min(1);
1632
+ /** Which library a media operation addresses, refused where the site has no object store. */
1633
+ var library = z.enum(mediaLibraries(client.media));
1634
+ var mediaFile = z.object({
1635
+ library,
1636
+ path: mediaPathSchema
1637
+ });
1638
+ /**
1639
+ * The reference scan reads every entry of every collection, which is by a wide
1640
+ * margin the most expensive thing a signed-in caller can ask for: one provider
1641
+ * request per entry, against a quota the editor's own token is charged for. The
1642
+ * general request budget is far too loose to bound it, so it gets its own,
1643
+ * serialized, and rare enough that a person never notices.
1644
+ *
1645
+ * The admin caches its index for display, but a mutation scans again so its
1646
+ * acknowledgement is checked against current references. In practice only the
1647
+ * assistant reaches this repeatedly.
1648
+ */
1649
+ var scans = new RateLimiter({
1650
+ requests: 10,
1651
+ windowMs: 6e4,
1652
+ concurrency: 1
1653
+ });
1654
+ function scan(ctx) {
1655
+ return limited(scans, ctx.session.login, () => new HttpError("A reference scan is already running. Try again in a moment.", 429), () => buildReferenceIndex(ctx.storage));
1656
+ }
1657
+ /** The references a human saw before accepting a destructive media action. */
1658
+ var acknowledgedReferences = z.array(assetReferenceSchema).optional();
1659
+ function assertValid(diagnostics) {
1660
+ if (diagnostics.length > 0) throw new ContentValidationError(diagnostics);
1661
+ }
1662
+ /** The single-finding form, which is what every guard below reports. */
1663
+ function refuse(message) {
1664
+ throw new ContentValidationError([diagnostic(message)]);
1665
+ }
1666
+ /**
1667
+ * The path names a file the library actually holds. Both callers are about to
1668
+ * act on it destructively, and "no such key" from a store reads as a failure
1669
+ * rather than as the correctable mistake it usually is.
1670
+ */
1671
+ async function assertInLibrary(ctx, { library, path }) {
1672
+ if ((await ctx.media(library).listPaths()).some((file) => file.path === path)) return;
1673
+ refuse(`"${path}" is not in the ${library} media library. Use a path listMedia reports.`);
1674
+ }
1675
+ async function assertReferencesAcknowledged(ctx, location, acknowledged) {
1676
+ const references = referencesFor(await scan(ctx), location);
1677
+ if (acknowledged !== void 0) {
1678
+ const keys = (items) => items.map(({ collection, entryId, where, declared }) => JSON.stringify([
1679
+ collection,
1680
+ entryId,
1681
+ where,
1682
+ declared
1683
+ ])).sort();
1684
+ if (JSON.stringify(keys(references)) !== JSON.stringify(keys(acknowledged))) throw new HttpError("References to this file changed. Review them again.", 412);
1685
+ return;
1686
+ }
1687
+ if (references.length === 0) return;
1688
+ refuse(`"${location.path}" is still referenced by ${references.map(describeReference).join(", ")}. Update them first.`);
1689
+ }
1690
+ /** In sequence, so a path outside the library never spends the scan budget. */
1691
+ async function assertMovable(ctx, file, acknowledged) {
1692
+ await assertInLibrary(ctx, file);
1693
+ await assertReferencesAcknowledged(ctx, file, acknowledged);
1694
+ }
1695
+ /**
1696
+ * A collection's entries in its order, so no client sorts them again. A field
1697
+ * order needs every entry read, and a file() collection lists in file order.
1698
+ */
1699
+ async function listInOrder(ctx, collection) {
1700
+ const entries = await ctx.storage.listEntries(collection);
1701
+ const sort = client.collections[collection]?.sort ?? DEFAULT_SORT;
1702
+ const values = /* @__PURE__ */ new Map();
1703
+ if (sort.by === "field") await inParallel(entries, async (entry) => {
1704
+ values.set(entry.id, (await ctx.storage.readEntry(entry)).data[sort.field]);
1705
+ });
1706
+ return orderEntries(entries, sort, (entry) => values.get(entry.id), entries.map((entry) => entry.id));
1707
+ }
1708
+ var operations = {
1709
+ listEntries: op(z.object({ collection }), (ctx, input) => listInOrder(ctx, input.collection)),
1710
+ getEntry: op(entryRef, (ctx, { collection, id }) => ctx.storage.getEntry(collection, id)),
1711
+ /**
1712
+ * Answers with the entry's new version rather than a bare acknowledgement, so
1713
+ * the editor that saved can save again without re-reading: without it, its
1714
+ * next write would carry the version from before this one and be refused as
1715
+ * stale.
1716
+ */
1717
+ saveEntry: op(entryRef.extend({ entry: saveRequest }), async (ctx, { collection, id, entry }) => {
1718
+ const version = await ctx.storage.saveEntry(collection, id, entry);
1719
+ return {
1720
+ ...ok,
1721
+ ...version && { version }
1722
+ };
1723
+ }),
1724
+ deleteEntry: op(entryRef.extend({ expectedVersion }), async (ctx, input) => {
1725
+ await ctx.storage.deleteEntry(input.collection, input.id, input.expectedVersion);
1726
+ return ok;
1727
+ }),
1728
+ renameEntry: op(rename.extend({ expectedVersion }), async (ctx, input) => {
1729
+ await ctx.storage.renameEntry(input.collection, input.id, input.newId, input.expectedVersion);
1730
+ return ok;
1731
+ }),
1732
+ /**
1733
+ * No `expectedVersion`: the copy lands at an id nothing has read, so there is
1734
+ * no version a caller could honestly name. What a duplicate has to be safe
1735
+ * against is an occupied destination, which the backend checks. (A rename is
1736
+ * the case where one *is* meaningful, and it carries its own.)
1737
+ */
1738
+ duplicateEntry: op(rename, async (ctx, { collection, id, newId }) => {
1739
+ await ctx.storage.duplicateEntry(collection, id, newId);
1740
+ return ok;
1741
+ }),
1742
+ reorderEntries: op(z.object({
1743
+ collection,
1744
+ ids: z.array(z.string()),
1745
+ expectedVersion
1746
+ }), async (ctx, input) => {
1747
+ const existing = (await ctx.storage.listEntries(input.collection)).map((entry) => entry.id);
1748
+ assertValid(validateReorder(existing, input.ids));
1749
+ await ctx.storage.reorderEntries(input.collection, input.ids, input.expectedVersion);
1750
+ return ok;
1751
+ }),
1752
+ getFileLayout: op(z.object({ collection }), (ctx, input) => ctx.storage.getFileLayout(input.collection)),
1753
+ getStatus: op(none, (ctx) => ctx.storage.getStatus()),
1754
+ getChanges: op(none, (ctx) => ctx.storage.getChanges()),
1755
+ publish: op(z.object({ digest: z.string() }), async (ctx, input) => {
1756
+ if (input.digest !== await changesetDigest(await ctx.storage.getChanges())) throw new HttpError("The changes were updated after your review. Review them again.", 412);
1757
+ await ctx.storage.publish();
1758
+ return ok;
1759
+ }),
1760
+ update: op(none, async (ctx) => {
1761
+ await ctx.storage.update();
1762
+ return ok;
1763
+ }),
1764
+ discard: op(none, async (ctx) => {
1765
+ await ctx.storage.discard();
1766
+ return ok;
1767
+ }),
1768
+ listMedia: op(z.object({ library }), async (ctx, input) => (await ctx.media(input.library).listMedia()).toSorted((a, b) => a.path.localeCompare(b.path))),
1769
+ beginUpload: op(mediaFile.extend({
1770
+ size: z.number().int().nonnegative(),
1771
+ overwrite: z.boolean().default(false)
1772
+ }), async (ctx, { library, path, size, overwrite }) => ctx.media(library).beginUpload(path, size, overwrite)),
1773
+ /** Within one library: a file never moves to the other, whose references are spelled differently. */
1774
+ renameMedia: op(z.object({
1775
+ library,
1776
+ from: mediaPathSchema,
1777
+ to: mediaPathSchema,
1778
+ acknowledgedReferences
1779
+ }), async (ctx, { library, from, to, acknowledgedReferences }) => {
1780
+ await assertMovable(ctx, {
1781
+ library,
1782
+ path: from
1783
+ }, acknowledgedReferences);
1784
+ await ctx.media(library).renameMedia(from, to);
1785
+ return ok;
1786
+ }),
1787
+ deleteMedia: op(mediaFile.extend({ acknowledgedReferences }), async (ctx, { acknowledgedReferences, ...file }) => {
1788
+ await assertMovable(ctx, file, acknowledgedReferences);
1789
+ await ctx.media(file.library).deleteMedia(file.path);
1790
+ return ok;
1791
+ }),
1792
+ /**
1793
+ * The deletions still undoable. A repository library answers with none, so the
1794
+ * admin can ask unconditionally and show a trash only where there is one.
1795
+ */
1796
+ listTrash: op(z.object({ library }), async (ctx, input) => ctx.media(input.library).listTrash()),
1797
+ restoreMedia: op(z.object({
1798
+ library,
1799
+ id: z.string()
1800
+ }), async (ctx, { library, id }) => {
1801
+ await ctx.media(library).restoreMedia(id);
1802
+ return ok;
1803
+ }),
1804
+ /**
1805
+ * Deleting for good, which is the one media call nothing undoes. Offered to
1806
+ * the media view alone: the assistant's tools are enumerated by hand, and this
1807
+ * is not among them.
1808
+ */
1809
+ purgeTrash: op(z.object({
1810
+ library,
1811
+ id: z.string()
1812
+ }), async (ctx, { library, id }) => {
1813
+ await ctx.media(library).purgeTrash(id);
1814
+ return ok;
1815
+ }),
1816
+ /** Every entry read once, so the admin can show what reaches each library file. */
1817
+ getReferences: op(none, scan)
1818
+ };
1819
+ /**
1820
+ * Runs one named operation. The name is checked against the registry's own keys
1821
+ * rather than looked up directly, so no property of `Object.prototype` can be
1822
+ * reached as an operation.
1823
+ */
1824
+ async function dispatch(ctx, name, input) {
1825
+ if (!Object.hasOwn(operations, name)) throw new HttpError(`Unknown operation: ${name}`, 404);
1826
+ return operations[name].run(ctx, input);
1827
+ }
1828
+ // src/server/oauth.ts
1829
+ /**
1830
+ * The sign-in dance, run entirely on the server. The browser never sees an
1831
+ * authorization code, a client secret or the resulting token: it is redirected
1832
+ * out, redirected back, and handed a sealed cookie.
1833
+ *
1834
+ * Both providers run the same authorization-code flow with PKCE, so only the
1835
+ * endpoints, the identity lookup and the write-access check differ. PKCE is not
1836
+ * here to stand in for a client secret, since the CMS is a confidential client
1837
+ * and both providers still demand the secret at the exchange,
1838
+ * but because it binds a code to the browser that asked for it,
1839
+ * which a confidential client gets no other way. The verifier never leaves the server: it travels in a short-lived
1840
+ * sealed cookie rather than in `sessionStorage`, where script could read it or
1841
+ * plant one.
1842
+ *
1843
+ * That binding is also the whole of the callback's CSRF defence, which is why
1844
+ * there is no separate `state` secret to keep in step with it. `state` carries
1845
+ * the challenge, so a callback can be refused against the cookie before any
1846
+ * authorization code is spent; the verifier behind it is what makes the refusal
1847
+ * mean something.
1848
+ */
1849
+ /** GitLab access levels: 30 = Developer, the lowest that may push and open MRs. */
1850
+ var MIN_GITLAB_ACCESS_LEVEL = 30;
1851
+ /** Where a GitLab backend points when the deployment does not host its own. */
1852
+ var GITLAB_CLOUD = "https://gitlab.com";
1853
+ /** The GitLab instance this deployment talks to. */
1854
+ var gitlabUrl = (config) => config.instanceUrl ?? GITLAB_CLOUD;
1855
+ function endpoints(config) {
1856
+ if (config.provider === "github") return {
1857
+ authorize: "https://github.com/login/oauth/authorize",
1858
+ token: "https://github.com/login/oauth/access_token",
1859
+ secretEnv: GITHUB_CLIENT_SECRET_ENV
1860
+ };
1861
+ return {
1862
+ authorize: joinUrl(gitlabUrl(config), "oauth/authorize"),
1863
+ token: joinUrl(gitlabUrl(config), "oauth/token"),
1864
+ secretEnv: GITLAB_CLIENT_SECRET_ENV
1865
+ };
1866
+ }
1867
+ var OAuthError = class extends Error {};
1868
+ /**
1869
+ * The OAuth client secret, which is also what the session cookie's key is
1870
+ * derived from (see `sessionSecret`). Missing, it names itself rather than
1871
+ * failing somewhere downstream.
1872
+ */
1873
+ function clientSecret(config) {
1874
+ const { secretEnv } = endpoints(config);
1875
+ const secret = getSecret(secretEnv);
1876
+ if (!secret) throw new OAuthError(`Sign-in is not configured: set ${secretEnv} on the server.`);
1877
+ return secret;
1878
+ }
1879
+ /**
1880
+ * A fresh PKCE verifier: 32 random bytes, which encode to the 43 characters both
1881
+ * providers accept, and the only secret the sign-in cookie carries.
1882
+ */
1883
+ function createVerifier() {
1884
+ return encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
1885
+ }
1886
+ /**
1887
+ * What a verifier proves. `S256` is the only method either provider implements,
1888
+ * so there is nothing to negotiate and nothing to read back off the callback.
1889
+ */
1890
+ async function challengeFor(verifier) {
1891
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
1892
+ return encode(new Uint8Array(digest));
1893
+ }
1894
+ /** Where the provider sends the editor to approve, for a given challenge. */
1895
+ function authorizationUrl(config, redirectUri, challenge) {
1896
+ const url = new URL(endpoints(config).authorize);
1897
+ url.searchParams.set("client_id", config.clientId);
1898
+ url.searchParams.set("redirect_uri", redirectUri);
1899
+ url.searchParams.set("response_type", "code");
1900
+ url.searchParams.set("code_challenge", challenge);
1901
+ url.searchParams.set("code_challenge_method", "S256");
1902
+ url.searchParams.set("state", challenge);
1903
+ if (config.scopes.length) url.searchParams.set("scope", config.scopes.join(" "));
1904
+ return url.href;
1905
+ }
1906
+ var tokenSchema = z.object({
1907
+ access_token: z.string().min(1),
1908
+ refresh_token: z.string().optional(),
1909
+ expires_in: z.number().optional(),
1910
+ error: z.never().optional()
1911
+ });
1912
+ var tokenErrorSchema = z.object({
1913
+ error: z.string().optional(),
1914
+ error_description: z.string().optional()
1915
+ });
1916
+ async function postToken(config, params) {
1917
+ const body = await (await fetch(endpoints(config).token, {
1918
+ method: "POST",
1919
+ headers: {
1920
+ "content-type": "application/x-www-form-urlencoded",
1921
+ accept: "application/json"
1922
+ },
1923
+ body: new URLSearchParams({
1924
+ ...params,
1925
+ client_id: config.clientId,
1926
+ client_secret: clientSecret(config)
1927
+ })
1928
+ })).json().catch(() => ({}));
1929
+ const token = tokenSchema.safeParse(body);
1930
+ if (token.success) return token.data;
1931
+ const { error, error_description } = tokenErrorSchema.safeParse(body).data ?? {};
1932
+ throw new OAuthError(error_description ?? error ?? "Sign-in failed.");
1933
+ }
1934
+ function toSession(provider, token, login) {
1935
+ return {
1936
+ provider,
1937
+ token: token.access_token,
1938
+ ...token.refresh_token && { refreshToken: token.refresh_token },
1939
+ ...token.expires_in != null && { expiresAt: Date.now() + token.expires_in * 1e3 },
1940
+ login
1941
+ };
1942
+ }
1943
+ /** Redeems the callback's code, then refuses an editor who cannot write to the target. */
1944
+ async function exchangeCode(config, code, redirectUri, verifier) {
1945
+ const token = await postToken(config, {
1946
+ grant_type: "authorization_code",
1947
+ code,
1948
+ redirect_uri: redirectUri,
1949
+ code_verifier: verifier
1950
+ });
1951
+ return toSession(config.provider, token, await verifyAccess(config, token.access_token));
1952
+ }
1953
+ /**
1954
+ * A lapsed token replaced in place, so an open tab never has to sign in again.
1955
+ * Write access is not re-checked here: the provider enforces it on every call
1956
+ * this token makes, which is a stronger check than asking it once.
1957
+ *
1958
+ * The refresh token is a parameter rather than something read off the session
1959
+ * because both providers rotate it: spending one invalidates it, so the caller
1960
+ * has to hold it to keep two requests from spending the same one (see
1961
+ * `refreshes` in `handler.ts`).
1962
+ */
1963
+ async function refreshSession(config, refreshToken, login) {
1964
+ try {
1965
+ const token = await postToken(config, {
1966
+ grant_type: "refresh_token",
1967
+ refresh_token: refreshToken
1968
+ });
1969
+ return toSession(config.provider, token, login);
1970
+ } catch {
1971
+ return null;
1972
+ }
1973
+ }
1974
+ /**
1975
+ * Ends the provider's side of the session, so signing out is not only local.
1976
+ *
1977
+ * Without it the cookie goes and the token lives on for the hours it has left,
1978
+ * which is the one window in which a session outlasts the editor's intent to end
1979
+ * it. Both providers revoke the grant rather than the one credential, so the
1980
+ * refresh token goes with it.
1981
+ *
1982
+ * Best effort by construction: the cookie is cleared whatever happens here, and
1983
+ * someone who asked to sign out is not the person to tell that the provider did
1984
+ * not answer.
1985
+ */
1986
+ async function revokeSession(config, session) {
1987
+ try {
1988
+ const secret = clientSecret(config);
1989
+ if (config.provider === "github") {
1990
+ await fetch(`${GITHUB_API}/applications/${config.clientId}/token`, {
1991
+ method: "DELETE",
1992
+ headers: {
1993
+ authorization: `Basic ${btoa(`${config.clientId}:${secret}`)}`,
1994
+ accept: "application/vnd.github+json",
1995
+ "content-type": "application/json",
1996
+ "user-agent": "astronaut-cms"
1997
+ },
1998
+ body: JSON.stringify({ access_token: session.token })
1999
+ });
2000
+ return;
2001
+ }
2002
+ await fetch(joinUrl(gitlabUrl(config), "oauth/revoke"), {
2003
+ method: "POST",
2004
+ headers: { "content-type": "application/x-www-form-urlencoded" },
2005
+ body: new URLSearchParams({
2006
+ client_id: config.clientId,
2007
+ client_secret: secret,
2008
+ token: session.token
2009
+ })
2010
+ });
2011
+ } catch {}
2012
+ }
2013
+ /** A lookup whose failure means "not permitted" rather than "broken". */
2014
+ var optional = (lookup) => lookup.catch(() => null);
2015
+ /**
2016
+ * The editor's username, once it is established they may write to the target.
2017
+ *
2018
+ * At sign-in this turns "every write fails" into one clear message at the door.
2019
+ * It is also what a live session is re-checked against, for the reason given by
2020
+ * `checkAccess` in `handler.ts`.
2021
+ */
2022
+ async function verifyAccess(config, token) {
2023
+ return config.provider === "github" ? verifyGitHub(token, config.target) : verifyGitLab(token, config.target, gitlabUrl(config));
2024
+ }
2025
+ async function verifyGitHub(token, repo) {
2026
+ const { owner, repo: name } = parseRepo(repo);
2027
+ const api = githubClient(token);
2028
+ const [user, repository] = await Promise.all([optional(api.json({ path: "user" })), optional(api.json({ path: `repos/${owner}/${name}` }))]);
2029
+ if (!repository?.permissions?.push || !user) throw new OAuthError(`You need write access to ${repo} to use this CMS.`);
2030
+ return user.login;
2031
+ }
2032
+ async function verifyGitLab(token, project, instanceUrl) {
2033
+ const api = gitlabClient(instanceUrl, token);
2034
+ const [user, repository] = await Promise.all([optional(api.json({ path: "user" })), optional(api.json({ path: `projects/${encodeURIComponent(project)}` }))]);
2035
+ if (Math.max(repository?.permissions?.project_access?.access_level ?? 0, repository?.permissions?.group_access?.access_level ?? 0) < MIN_GITLAB_ACCESS_LEVEL || !user) throw new OAuthError(`You need write access to ${project} to use this CMS.`);
2036
+ return user.username;
2037
+ }
2038
+ // src/server/session.ts
2039
+ /**
2040
+ * The editor's session, sealed into a cookie the browser cannot read.
2041
+ *
2042
+ * The provider token lives here and nowhere else: it is encrypted with a key the
2043
+ * deployment derives, handed back as an HttpOnly cookie, and only ever decrypted
2044
+ * inside a server route. That is the whole point of the architecture. Script
2045
+ * running in the admin can act as the editor while the tab is open, but it has
2046
+ * nothing portable to steal.
2047
+ *
2048
+ * Stateless on purpose. A serverless deployment needs no KV, no database and no
2049
+ * sticky instance, and the cost is that the cookie itself cannot be torn up
2050
+ * before it expires. What it grants can be: see `checkAccess` in `handler.ts`.
2051
+ *
2052
+ * The format is a JWE (`dir` + A256GCM) rather than a bare AES-GCM blob. Same
2053
+ * primitive, standard envelope, which buys the two things a hand-rolled seal
2054
+ * has to be talked into: an `exp` the *server* enforces, so a copied cookie
2055
+ * value stops working whatever the browser does with `Max-Age`, and an `aud`
2056
+ * that makes each kind of token structurally unusable as another. It is also
2057
+ * what MCP's authorization codes and access tokens will be issued as, so there
2058
+ * is one token mechanism rather than two.
2059
+ */
2060
+ var SESSION_COOKIE = "astronaut_cms_session";
2061
+ /** Cookie lifetime. A session outlives a lapsed token, which is refreshed in place. */
2062
+ var SESSION_TTL = 2592e3;
2063
+ /** Renewed this long before the provider token lapses, so a request never races it. */
2064
+ var REFRESH_MARGIN_MS = 6e4;
2065
+ /** Hostnames as `URL` spells them, IPv6 in brackets. */
2066
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
2067
+ "localhost",
2068
+ "127.0.0.1",
2069
+ "[::1]"
2070
+ ]);
2071
+ /** Who issued the token, so one verifier can refuse a well-formed foreign one. */
2072
+ var ISSUER = "astronaut-cms";
2073
+ var sessionSchema = z.object({
2074
+ provider: z.enum(PROVIDERS),
2075
+ /** The provider API credential. The only thing here worth protecting. */
2076
+ token: z.string(),
2077
+ /** Present when the provider issues expiring tokens (a GitHub App always does). */
2078
+ refreshToken: z.string().optional(),
2079
+ /** Epoch milliseconds, absent when the token does not expire. */
2080
+ expiresAt: z.number().optional(),
2081
+ /** Provider username. Cached here so the draft branch costs no round trip. */
2082
+ login: z.string(),
2083
+ /**
2084
+ * When the editor's repository access was last confirmed, in epoch
2085
+ * milliseconds. Carried in the cookie rather than in instance memory so the
2086
+ * check is made once per editor per window across the whole deployment, not
2087
+ * once per warm instance. On a serverless host most requests land somewhere
2088
+ * cold, and the check is an outbound round trip on the critical path of every
2089
+ * one of them. See `checkAccess` in `handler.ts`.
2090
+ */
2091
+ checkedAt: z.number().optional()
2092
+ });
2093
+ /**
2094
+ * What the sign-in cookie carries. The verifier alone: the challenge derived
2095
+ * from it is what the provider echoes back as `state`, so there is no second
2096
+ * secret to mint, to carry, or to keep in step with it.
2097
+ */
2098
+ var loginSchema = z.object({ verifier: z.string() });
2099
+ /**
2100
+ * Separates this key from whatever else the same secret is used for. The secret
2101
+ * is normally the OAuth client secret, which the deployment already holds and
2102
+ * already spends at the provider; HKDF is what makes reusing it sound, since the
2103
+ * derived key reveals nothing about the input.
2104
+ */
2105
+ var KEY_INFO = new TextEncoder().encode("astronaut-cms session v1");
2106
+ var cachedKey = null;
2107
+ function sealingKey(secret) {
2108
+ if (cachedKey?.secret !== secret) cachedKey = {
2109
+ secret,
2110
+ key: crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveKey"]).then((material) => crypto.subtle.deriveKey({
2111
+ name: "HKDF",
2112
+ hash: "SHA-256",
2113
+ salt: /* @__PURE__ */ new Uint8Array(0),
2114
+ info: KEY_INFO
2115
+ }, material, {
2116
+ name: "AES-GCM",
2117
+ length: 256
2118
+ }, false, ["encrypt", "decrypt"]))
2119
+ };
2120
+ return cachedKey.key;
2121
+ }
2122
+ /** Encrypts a payload so the browser can carry it but never read it. */
2123
+ async function issue(audience, claims, secret, ttlSeconds) {
2124
+ return new EncryptJWT(claims).setProtectedHeader({
2125
+ alg: "dir",
2126
+ enc: "A256GCM"
2127
+ }).setIssuer(ISSUER).setAudience(audience).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + ttlSeconds).encrypt(await sealingKey(secret));
2128
+ }
2129
+ /**
2130
+ * What a token carries, or null when it carries nothing this deployment issued
2131
+ * for this purpose. Every failure reads the same way. Tampered, expired, sealed
2132
+ * with a rotated secret, issued for another audience, or not matching the schema
2133
+ * are all "nothing there", because telling them apart is a way to probe the key.
2134
+ */
2135
+ async function verify(audience, token, secret, schema) {
2136
+ try {
2137
+ const { payload } = await jwtDecrypt(token, await sealingKey(secret), {
2138
+ issuer: ISSUER,
2139
+ audience
2140
+ });
2141
+ return schema.parse(payload);
2142
+ } catch {
2143
+ return null;
2144
+ }
2145
+ }
2146
+ function readCookie(request, name) {
2147
+ for (const part of request.headers.get("cookie")?.split(";") ?? []) {
2148
+ const [key, ...rest] = part.trim().split("=");
2149
+ if (key === name) return rest.join("=");
2150
+ }
2151
+ }
2152
+ /**
2153
+ * The site's `base`, recovered from the request rather than configured.
2154
+ *
2155
+ * Astro prepends `base` to an injected route, so at runtime it appears only as
2156
+ * whatever precedes the mounted path being answered. The cookie's scope and the
2157
+ * sign-in link both hang off it, and both are built from an API request, which
2158
+ * is the one path guaranteed to carry it.
2159
+ */
2160
+ function basePath(pathname, mounted) {
2161
+ const index = pathname.lastIndexOf(mounted);
2162
+ return index > 0 ? pathname.slice(0, index) : "";
2163
+ }
2164
+ /**
2165
+ * A `Set-Cookie` for one of the CMS's own cookies. `SameSite=Lax` so it survives
2166
+ * the top-level redirect back from the provider but not a cross-site form post.
2167
+ *
2168
+ * `path` is the caller's to decide; both callers scope it to the CMS API, so the
2169
+ * cookie is never attached to a request for the site's own pages. That is only
2170
+ * possible because the admin page reads no session (see `astro/admin.astro`): a
2171
+ * page that had to would need the cookie scoped wide enough to reach it.
2172
+ */
2173
+ function cmsCookie({ name, url, path, value, maxAge }) {
2174
+ const attributes = [
2175
+ `${name}=${value ?? ""}`,
2176
+ `Path=${path}`,
2177
+ "HttpOnly",
2178
+ "SameSite=Lax",
2179
+ `Max-Age=${value ? maxAge ?? 2592e3 : 0}`
2180
+ ];
2181
+ if (!LOOPBACK_HOSTS.has(url.hostname)) attributes.push("Secure");
2182
+ return attributes.join("; ");
2183
+ }
2184
+ /** Whether the provider token is close enough to lapsing to be renewed now. */
2185
+ function needsRefresh(session) {
2186
+ return session.expiresAt != null && session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
2187
+ }
2188
+ /**
2189
+ * Refuses a request that a third-party page made on the editor's behalf.
2190
+ *
2191
+ * Cookie authentication is ambient: unlike the bearer token this replaced, the
2192
+ * browser attaches it to any request to this origin, whoever caused it.
2193
+ * `SameSite=Lax` already blocks a cross-site POST, and this is the explicit
2194
+ * check behind it, for the browsers and proxies that do not, and so the rule is
2195
+ * stated where it is enforced rather than assumed from a cookie attribute.
2196
+ */
2197
+ function isSameOrigin(request, url) {
2198
+ const site = request.headers.get("sec-fetch-site");
2199
+ if (site) return site === "same-origin";
2200
+ const origin = request.headers.get("origin");
2201
+ return origin == null || origin === url.origin;
2202
+ }
2203
+ // src/server/handler.ts
2204
+ /**
2205
+ * The whole CMS server, as one handler over Web `Request` and `Response`.
2206
+ * `endpoint.ts` is the thin Astro route around it. It reads only the build-time
2207
+ * config and `astro:env`, which every adapter provides, so it runs unchanged on
2208
+ * Node, serverless functions and Workers.
2209
+ *
2210
+ * Everything the browser can reach is here, and it is a short list: find out
2211
+ * whether there is a session, start one, end one, run one named operation, and
2212
+ * move media bytes. Content, media and the changeset are all the single `rpc`
2213
+ * path into {@link dispatch}, so the reachable surface is the operation registry
2214
+ * rather than one route per thing the CMS happens to do.
2215
+ */
2216
+ /** An RPC body is entry data, which is text. A media upload takes its own route. */
2217
+ var MAX_RPC_BYTES = 4194304;
2218
+ /** Carries the PKCE verifier between the redirect out and the redirect back. */
2219
+ var LOGIN_COOKIE = "astronaut_cms_login";
2220
+ var LOGIN_MAX_AGE = 600;
2221
+ /**
2222
+ * Sign-in, the only work an unauthenticated caller can cause, per client
2223
+ * address. Generous against real use: one sign-in per editor per session.
2224
+ */
2225
+ var signIn = new RateLimiter({
2226
+ requests: 20,
2227
+ windowMs: 6e4,
2228
+ concurrency: 4
2229
+ });
2230
+ /**
2231
+ * Code exchanges, which call the provider, charged to everybody at once so a
2232
+ * flood cannot get the deployment's address rate-limited there. Behind
2233
+ * {@link signIn}, so no single caller can spend it.
2234
+ */
2235
+ var exchanges = new RateLimiter({
2236
+ requests: 120,
2237
+ windowMs: 6e4,
2238
+ concurrency: 16
2239
+ });
2240
+ /**
2241
+ * Operations and uploads per editor, well above what a person produces, to
2242
+ * bound a runaway agent loop or a compromised tab.
2243
+ */
2244
+ var rpc = new RateLimiter({
2245
+ requests: 300,
2246
+ windowMs: 6e4,
2247
+ concurrency: 12
2248
+ });
2249
+ /** Media reads per editor, higher since a media page asks for a thumbnail per file. */
2250
+ var mediaReads = new RateLimiter({
2251
+ requests: 1200,
2252
+ windowMs: 6e4,
2253
+ concurrency: 24
2254
+ });
2255
+ var tooMany = (message) => () => new HttpError(message, 429);
2256
+ var tooManySignIns = tooMany("Too many sign-in attempts. Wait a moment and try again.");
2257
+ var tooManyRequests = tooMany("Too many requests. Wait a moment and try again.");
2258
+ function json(data, status = 200, headers = {}) {
2259
+ return new Response(JSON.stringify(data), {
2260
+ status,
2261
+ headers: {
2262
+ "content-type": "application/json",
2263
+ "cache-control": "no-store",
2264
+ ...HARDENING_HEADERS,
2265
+ ...headers
2266
+ }
2267
+ });
2268
+ }
2269
+ function fail(message, status, validation) {
2270
+ return json({ error: {
2271
+ message,
2272
+ ...validation && { validation }
2273
+ } }, status);
2274
+ }
2275
+ /** The site's `base`, read off the API path every CMS request is under. */
2276
+ var sitePath = (url) => basePath(url.pathname, API_BASE);
2277
+ /**
2278
+ * Where the CMS's cookies apply: its own API routes and nothing else, so they are
2279
+ * never attached to a request for the site's own pages. The admin page is a
2280
+ * static shell that reads no session (see `astro/admin.astro`), which is what
2281
+ * lets the scope stay this narrow.
2282
+ */
2283
+ var cookieScope = (url) => `${sitePath(url)}${API_BASE}`;
2284
+ /** The session cookie, or the expired form of it that signing out sets. */
2285
+ function sessionCookie(url, value) {
2286
+ return cmsCookie({
2287
+ name: SESSION_COOKIE,
2288
+ url,
2289
+ path: cookieScope(url),
2290
+ value
2291
+ });
2292
+ }
2293
+ /**
2294
+ * The sign-in cookie, or the expired form of it every callback sets. A verifier
2295
+ * is spent on the one code it was minted for, so it is torn up whichever way the
2296
+ * callback ends rather than left to time out.
2297
+ */
2298
+ function loginCookie(url, value) {
2299
+ return cmsCookie({
2300
+ name: LOGIN_COOKIE,
2301
+ url,
2302
+ path: cookieScope(url),
2303
+ value,
2304
+ maxAge: LOGIN_MAX_AGE
2305
+ });
2306
+ }
2307
+ /** The token inside it, whose own `exp` matches the cookie's `Max-Age`. */
2308
+ var issueSession = (session, secret) => issue("session", session, secret, SESSION_TTL);
2309
+ /** The CMS's own absolute URL for a path under {@link API_BASE} or the admin. */
2310
+ function siteUrl(url, path) {
2311
+ return conformTrailingSlash(new URL(`${sitePath(url)}${path}`, url.origin).href, server.trailingSlash);
2312
+ }
2313
+ /**
2314
+ * What the session cookie is encrypted with.
2315
+ *
2316
+ * By default the OAuth client secret the deployment already holds: it is high
2317
+ * entropy, server-only, identical across every instance, and stable across
2318
+ * deploys, which is exactly what a cookie key has to be. The key itself is
2319
+ * derived from it (HKDF, see `sealingKey`), so the two are separate keys that
2320
+ * happen to share one input, and rotating the client secret, the thing you do
2321
+ * on compromise anyway, invalidates every session with it.
2322
+ *
2323
+ * `ASTRONAUT_CMS_SESSION_SECRET` overrides it, for a deployment that wants to
2324
+ * expire sessions without touching its OAuth app, or to share one session across
2325
+ * several services.
2326
+ */
2327
+ function sessionSecret(provider) {
2328
+ return getSecret("ASTRONAUT_CMS_SESSION_SECRET") ?? clientSecret(provider);
2329
+ }
2330
+ /** The configured provider, or null when this deployment stores content locally. */
2331
+ function providerConfig() {
2332
+ const { storage } = server;
2333
+ if (storage.type === "github") return {
2334
+ provider: "github",
2335
+ clientId: storage.clientId,
2336
+ target: storage.repo,
2337
+ scopes: []
2338
+ };
2339
+ if (storage.type === "gitlab") return {
2340
+ provider: "gitlab",
2341
+ clientId: storage.clientId,
2342
+ target: storage.project,
2343
+ instanceUrl: storage.instanceUrl,
2344
+ scopes: storage.scopes
2345
+ };
2346
+ return null;
2347
+ }
2348
+ /**
2349
+ * `astro dev` against the working tree has no provider and therefore no sign-in:
2350
+ * the editor is whoever can reach the dev server, which is the same trust
2351
+ * boundary the dev server itself has.
2352
+ */
2353
+ var LOCAL_SESSION = {
2354
+ provider: "local",
2355
+ token: "",
2356
+ login: "local"
2357
+ };
2358
+ /**
2359
+ * Who a request is from, and whether they may still act.
2360
+ *
2361
+ * Linear on purpose: the session is read, renewed if its token has lapsed, and
2362
+ * re-checked against the provider if that has not been done lately. Each step
2363
+ * replaces the session rather than branching, so the cookie is re-issued once at
2364
+ * the end for whatever actually changed.
2365
+ */
2366
+ async function authenticate(request, url, provider) {
2367
+ if (!provider) return {
2368
+ kind: "session",
2369
+ session: LOCAL_SESSION
2370
+ };
2371
+ const raw = readCookie(request, SESSION_COOKIE);
2372
+ if (!raw) return { kind: "anonymous" };
2373
+ let secret;
2374
+ try {
2375
+ secret = sessionSecret(provider);
2376
+ } catch (err) {
2377
+ return {
2378
+ kind: "misconfigured",
2379
+ error: describeFailure(err)
2380
+ };
2381
+ }
2382
+ const stored = await verify("session", raw, secret, sessionSchema);
2383
+ if (!stored || stored.provider !== provider.provider) return { kind: "anonymous" };
2384
+ let session = stored;
2385
+ if (needsRefresh(session)) {
2386
+ const { refreshToken } = session;
2387
+ if (!refreshToken) return { kind: "anonymous" };
2388
+ const renewed = await refreshes.run(refreshToken, () => refreshSession(provider, refreshToken, session.login));
2389
+ if (!renewed) return { kind: "anonymous" };
2390
+ session = {
2391
+ ...renewed,
2392
+ ...session.checkedAt != null && { checkedAt: session.checkedAt }
2393
+ };
2394
+ }
2395
+ if (session.checkedAt == null || session.checkedAt + ACCESS_TTL_MS <= Date.now()) {
2396
+ const { error, at } = await checkAccess(provider, session.token);
2397
+ if (error) return {
2398
+ kind: "revoked",
2399
+ error,
2400
+ session
2401
+ };
2402
+ session = {
2403
+ ...session,
2404
+ checkedAt: at
2405
+ };
2406
+ }
2407
+ const cookie = session === stored ? void 0 : sessionCookie(url, await issueSession(session, secret));
2408
+ return {
2409
+ kind: "session",
2410
+ session,
2411
+ cookie
2412
+ };
2413
+ }
2414
+ var describeFailure = (err) => err instanceof OAuthError ? err.message : "Sign-in is unavailable.";
2415
+ /** How long a confirmed authorization stands before the provider is asked again. */
2416
+ var ACCESS_TTL_MS = 3e5;
2417
+ /**
2418
+ * Token to its latest check, kept for the window so a client replaying a cookie
2419
+ * with a lapsed `checkedAt` cannot make every request a provider round trip.
2420
+ * The session takes the check's own time, so the window is not doubled.
2421
+ */
2422
+ var checks = new Coalesced(ACCESS_TTL_MS);
2423
+ /** Refresh token to the session that replaced it. */
2424
+ var refreshes = new Coalesced(6e4);
2425
+ /**
2426
+ * Whether this token may still be used.
2427
+ *
2428
+ * Every call the CMS makes on the editor's own token is re-decided by the
2429
+ * provider, so for the repository a stale session is already harmless. The
2430
+ * surfaces that are not are the reason this exists: the assistant relay and an
2431
+ * object-store media library both spend the *deployment's* credentials and ask
2432
+ * the provider nothing, so without this, losing access would still leave someone
2433
+ * able to spend the AI account and rewrite the bucket until their cookie expired
2434
+ * thirty days later.
2435
+ *
2436
+ * Called from `authenticate` rather than from a route, so a route added later
2437
+ * cannot forget it.
2438
+ */
2439
+ function checkAccess(provider, token) {
2440
+ return checks.run(token, async () => {
2441
+ const error = await verifyAccess(provider, token).then(() => void 0, describeFailure);
2442
+ return {
2443
+ ...error && { error },
2444
+ at: Date.now()
2445
+ };
2446
+ });
2447
+ }
2448
+ /**
2449
+ * Answers the shell's one anonymous question: is there a session, and if so,
2450
+ * what is this deployment?
2451
+ *
2452
+ * The only route that answers without one, which is what lets the admin page be
2453
+ * a static shell. An anonymous caller learns whether it is signed in and where
2454
+ * to go to change that, and nothing else.
2455
+ */
2456
+ function sessionState(request, url, authenticated) {
2457
+ return {
2458
+ loginUrl: siteUrl(url, API_LOGIN),
2459
+ autoLogin: request.headers.get("cf-access-jwt-assertion") != null && readCookie(request, LOGIN_COOKIE) == null,
2460
+ ..."error" in authenticated && { error: authenticated.error },
2461
+ ...authenticated.kind === "session" && { config: client }
2462
+ };
2463
+ }
2464
+ /**
2465
+ * The whole API for one request. `clientAddress` is the caller's address as the
2466
+ * adapter determined it, which trusts a forwarded header only where the
2467
+ * platform sets one.
2468
+ */
2469
+ async function handle(request, clientAddress) {
2470
+ const url = new URL(request.url);
2471
+ const path = withoutTrailingSlash(url.pathname.slice(sitePath(url).length + API_BASE.length));
2472
+ try {
2473
+ return await route$1(path, request, url, clientAddress);
2474
+ } catch (err) {
2475
+ return toResponse(err);
2476
+ }
2477
+ }
2478
+ async function route$1(path, request, url, clientAddress) {
2479
+ if (request.method !== "GET" && !isSameOrigin(request, url)) return fail("Cross-origin request blocked.", 403);
2480
+ if (path === "/login" || path === "/callback") return limited(signIn, clientAddress ?? "anonymous", tooManySignIns, () => path === "/login" ? startLogin(url) : completeLogin(request, url));
2481
+ const provider = providerConfig();
2482
+ const authenticated = await authenticate(request, url, provider);
2483
+ const renewed = authenticated.kind === "session" ? authenticated.cookie : void 0;
2484
+ const extra = renewed ? { "set-cookie": renewed } : {};
2485
+ if (path === "/session" && request.method === "GET") return json(sessionState(request, url, authenticated), 200, extra);
2486
+ if (path === "/logout" && request.method === "POST") {
2487
+ if (provider && "session" in authenticated) await revokeSession(provider, authenticated.session);
2488
+ return json({ ok: true }, 200, { "set-cookie": sessionCookie(url) });
2489
+ }
2490
+ if (authenticated.kind === "revoked") return fail(authenticated.error, 403);
2491
+ if (authenticated.kind !== "session") return fail("Not signed in.", 401);
2492
+ const { session } = authenticated;
2493
+ const ctx = createContext(session);
2494
+ if (path === "/rpc" && request.method === "POST") {
2495
+ const body = await readBody(request, MAX_RPC_BYTES);
2496
+ let parsed;
2497
+ try {
2498
+ parsed = JSON.parse(body);
2499
+ } catch {
2500
+ return fail("Malformed request body.", 400);
2501
+ }
2502
+ const { data: calls } = batchSchema.safeParse(parsed);
2503
+ if (!calls) return fail("A batch of operations is required.", 400);
2504
+ if (calls.length > 20) return fail(`A batch may carry at most 20 operations.`, 400);
2505
+ return json(await limited(rpc, session.login, tooManyRequests, () => runBatch(ctx, calls), calls.length), 200, extra);
2506
+ }
2507
+ if (path.startsWith("/media/") && request.method === "GET") return limited(mediaReads, session.login, tooManyRequests, () => serveMedia(ctx, path.slice(7), request, url, extra));
2508
+ if (path === "/ai/chat/completions" && request.method === "POST") {
2509
+ const { ai } = server;
2510
+ if (!ai) return fail("The assistant is not configured.", 404);
2511
+ const response = await relay({
2512
+ request,
2513
+ ai,
2514
+ models: client.ai?.models ?? [],
2515
+ caller: session.login,
2516
+ fail
2517
+ });
2518
+ for (const [name, value] of Object.entries(extra)) response.headers.set(name, value);
2519
+ return response;
2520
+ }
2521
+ if (path === "/upload" && request.method === "PUT") return limited(rpc, session.login, tooManyRequests, () => upload(ctx, request, url, extra));
2522
+ return fail("Not found.", 404);
2523
+ }
2524
+ /** One media file, `path` being the library id followed by the file's path within it. */
2525
+ async function serveMedia(ctx, path, request, url, extra) {
2526
+ const [id = "", ...segments] = path.split("/");
2527
+ const libraryId = parseMediaLibrary(client.media, id);
2528
+ if (!libraryId) return fail("Unknown media library.", 404);
2529
+ let filePath;
2530
+ try {
2531
+ filePath = decodeURIComponent(segments.join("/"));
2532
+ } catch {
2533
+ return fail("Invalid media path.", 400);
2534
+ }
2535
+ const library = ctx.media(libraryId);
2536
+ const range = parseByteRange(request.headers.get("range"));
2537
+ const content = await library.readMedia(filePath, range ?? void 0);
2538
+ const addressed = content.version != null && url.searchParams.get("v") === content.version;
2539
+ if ("redirect" in content && !addressed) return new Response(null, {
2540
+ status: 302,
2541
+ headers: {
2542
+ location: content.redirect,
2543
+ "cache-control": "private, max-age=300",
2544
+ ...extra
2545
+ }
2546
+ });
2547
+ const etag = content.version == null ? void 0 : `"${content.version}"`;
2548
+ const caching = {
2549
+ "cache-control": addressed ? "private, max-age=31536000, immutable" : "private, max-age=300",
2550
+ ...etag && { etag }
2551
+ };
2552
+ if (etag && request.headers.get("if-none-match") === etag) {
2553
+ if ("body" in content && content.body instanceof ReadableStream) content.body.cancel();
2554
+ return new Response(null, {
2555
+ status: 304,
2556
+ headers: {
2557
+ ...caching,
2558
+ ...extra
2559
+ }
2560
+ });
2561
+ }
2562
+ const source = "redirect" in content ? await fetchRange((headers) => fetch(content.redirect, { headers }), range) : content;
2563
+ return new Response(source.body, {
2564
+ status: source.partial?.status ?? 200,
2565
+ headers: {
2566
+ "content-type": servedContentType(filePath),
2567
+ "accept-ranges": "bytes",
2568
+ ...source.partial?.contentRange && { "content-range": source.partial.contentRange },
2569
+ "content-security-policy": "sandbox",
2570
+ ...caching,
2571
+ ...HARDENING_HEADERS,
2572
+ ...extra
2573
+ }
2574
+ });
2575
+ }
2576
+ /** A file uploaded through the server, for a library that commits it rather than a store. */
2577
+ async function upload(ctx, request, url, extra) {
2578
+ const params = url.searchParams;
2579
+ const uploadPath = params.get("path");
2580
+ const libraryId = parseMediaLibrary(client.media, params.get("library"));
2581
+ if (!uploadPath) return fail("An upload path is required.", 400);
2582
+ if (!libraryId) return fail("Unknown media library.", 404);
2583
+ const library = ctx.media(libraryId);
2584
+ const { maxFileSize } = mediaLibrary(client.media, libraryId);
2585
+ if (!library.uploadMedia || maxFileSize == null) return fail("This library takes uploads directly.", 400);
2586
+ const bytes = await readBytes(request, maxFileSize);
2587
+ await library.uploadMedia(uploadPath, bytes, params.get("overwrite") === "true");
2588
+ return json({ ok: true }, 200, extra);
2589
+ }
2590
+ async function startLogin(url) {
2591
+ const provider = providerConfig();
2592
+ if (!provider) return fail("This deployment does not sign in.", 400);
2593
+ const verifier = createVerifier();
2594
+ const redirectUri = siteUrl(url, API_CALLBACK);
2595
+ return new Response(null, {
2596
+ status: 302,
2597
+ headers: {
2598
+ location: authorizationUrl(provider, redirectUri, await challengeFor(verifier)),
2599
+ "set-cookie": loginCookie(url, await issue("oauth-login", { verifier }, sessionSecret(provider), LOGIN_MAX_AGE)),
2600
+ "cache-control": "no-store"
2601
+ }
2602
+ });
2603
+ }
2604
+ async function completeLogin(request, url) {
2605
+ const provider = providerConfig();
2606
+ if (!provider) return fail("This deployment does not sign in.", 400);
2607
+ const admin = siteUrl(url, client.mountPoint);
2608
+ const redirect = (location, session) => {
2609
+ const headers = new Headers({
2610
+ location,
2611
+ "cache-control": "no-store"
2612
+ });
2613
+ headers.append("set-cookie", loginCookie(url));
2614
+ if (session) headers.append("set-cookie", session);
2615
+ return new Response(null, {
2616
+ status: 302,
2617
+ headers
2618
+ });
2619
+ };
2620
+ const failed = (message) => redirect(`${admin}?error=${encodeURIComponent(message)}`);
2621
+ const error = url.searchParams.get("error_description") ?? url.searchParams.get("error");
2622
+ if (error) return failed(error);
2623
+ const secret = sessionSecret(provider);
2624
+ const cookie = readCookie(request, LOGIN_COOKIE);
2625
+ const login = cookie ? await verify("oauth-login", cookie, secret, loginSchema) : null;
2626
+ const code = url.searchParams.get("code");
2627
+ if (!code || !login || url.searchParams.get("state") !== await challengeFor(login.verifier)) return failed("The sign-in link expired. Try again.");
2628
+ return redirect(admin, sessionCookie(url, await issueSession(await limited(exchanges, "all", tooManySignIns, () => exchangeCode(provider, code, siteUrl(url, API_CALLBACK), login.verifier)), secret)));
2629
+ }
2630
+ /** Operations of a batch, before anything has been checked about each one. */
2631
+ var batchSchema = z.array(z.object({
2632
+ op: z.unknown(),
2633
+ input: z.unknown()
2634
+ })).min(1);
2635
+ /**
2636
+ * Every operation of a batch, against the one context the request built, which
2637
+ * is what makes batching worth doing: the repository tree, the file collection
2638
+ * containers and whether the draft branch exists are each resolved once for the
2639
+ * whole batch rather than once per invocation.
2640
+ *
2641
+ * Reads run at once. The admin only ever groups calls that were already in
2642
+ * flight together, and every one of those caches is a *promise*, so concurrent
2643
+ * reads share the lookups instead of repeating them. Batching would otherwise
2644
+ * buy an invocation by turning a navigation's latency from the slowest call into
2645
+ * the sum of them. A write makes order matter, so a batch carrying one runs in
2646
+ * the order it was sent.
2647
+ *
2648
+ * Each operation is answered on its own either way. A batch is a way to spend
2649
+ * one invocation instead of five, not a transaction, and one failing does not
2650
+ * mean the rest should not run.
2651
+ */
2652
+ function runBatch(ctx, calls) {
2653
+ if (calls.every(({ op }) => typeof op === "string" && !isWriteOperation(op))) return Promise.all(calls.map((call) => runOne(ctx, call)));
2654
+ return serially(ctx, calls);
2655
+ }
2656
+ /** One call at a time, since `Array.fromAsync` awaits each mapped value before the next. */
2657
+ var serially = (ctx, calls) => Array.fromAsync(calls, (call) => runOne(ctx, call));
2658
+ async function runOne(ctx, { op, input }) {
2659
+ if (typeof op !== "string") return {
2660
+ ok: false,
2661
+ error: {
2662
+ status: 400,
2663
+ message: "An operation name is required."
2664
+ }
2665
+ };
2666
+ try {
2667
+ return {
2668
+ ok: true,
2669
+ data: await dispatch(ctx, op, input ?? {})
2670
+ };
2671
+ } catch (err) {
2672
+ return {
2673
+ ok: false,
2674
+ error: errorOf(err)
2675
+ };
2676
+ }
2677
+ }
2678
+ /**
2679
+ * How a thrown failure reads, whether it ends the request or one operation
2680
+ * inside a batch. The status is part of it either way: it is what the admin
2681
+ * branches on (a merge conflict, a lapsed session), and inside a batch there is
2682
+ * no HTTP status left to carry it.
2683
+ */
2684
+ function errorOf(err) {
2685
+ if (err instanceof HttpError) return {
2686
+ status: err.status,
2687
+ message: err.message
2688
+ };
2689
+ if (err instanceof StaleWriteError) return {
2690
+ status: 412,
2691
+ message: err.message
2692
+ };
2693
+ if (err instanceof MergeConflictError) return {
2694
+ status: 409,
2695
+ message: err.message
2696
+ };
2697
+ if (err instanceof ContentValidationError) return {
2698
+ status: 422,
2699
+ message: err.message,
2700
+ validation: err.diagnostics
2701
+ };
2702
+ if (err instanceof BodyTooLargeError) return {
2703
+ status: 413,
2704
+ message: err.message
2705
+ };
2706
+ if (err instanceof OAuthError) return {
2707
+ status: 400,
2708
+ message: err.message
2709
+ };
2710
+ console.error("[astronaut-cms] Request failed:", err);
2711
+ return {
2712
+ status: 500,
2713
+ message: errorMessage(err, "Request failed")
2714
+ };
2715
+ }
2716
+ function toResponse(err) {
2717
+ const { status, message, validation } = errorOf(err);
2718
+ return fail(message, status, validation);
2719
+ }
2720
+ // src/server/endpoint.ts
2721
+ var prerender = false;
2722
+ var route = ({ request, clientAddress }) => handle(request, clientAddress);
2723
+ var GET = route;
2724
+ var POST = route;
2725
+ var PUT = route;
2726
+ export { GET, POST, PUT, handle, prerender };