@nuasite/cms-sidecar 0.64.3 → 0.65.1

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 (39) hide show
  1. package/dist/cli.bundle.js +28455 -0
  2. package/dist/cli.d.ts.map +1 -0
  3. package/dist/cli.js +78 -28442
  4. package/dist/{types/concurrency.d.ts → concurrency.d.ts} +1 -1
  5. package/dist/concurrency.d.ts.map +1 -0
  6. package/dist/concurrency.js +75 -0
  7. package/dist/index.d.ts +3 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +2 -0
  10. package/dist/media-from-env.d.ts.map +1 -0
  11. package/dist/media-from-env.js +57 -0
  12. package/dist/{types/portable.d.ts → portable.d.ts} +4 -4
  13. package/dist/portable.d.ts.map +1 -0
  14. package/dist/portable.js +11 -0
  15. package/dist/server.d.ts.map +1 -0
  16. package/dist/server.js +1100 -0
  17. package/dist/tsconfig.tsbuildinfo +1 -0
  18. package/dist/types.d.ts.map +1 -0
  19. package/dist/types.js +10 -0
  20. package/package.json +11 -11
  21. package/src/cli.ts +2 -2
  22. package/src/concurrency.ts +5 -1
  23. package/src/index.ts +2 -2
  24. package/src/portable.ts +4 -4
  25. package/src/server.ts +2 -2
  26. package/src/tsconfig.json +5 -1
  27. package/dist/types/cli.d.ts.map +0 -1
  28. package/dist/types/concurrency.d.ts.map +0 -1
  29. package/dist/types/index.d.ts +0 -3
  30. package/dist/types/index.d.ts.map +0 -1
  31. package/dist/types/media-from-env.d.ts.map +0 -1
  32. package/dist/types/portable.d.ts.map +0 -1
  33. package/dist/types/server.d.ts.map +0 -1
  34. package/dist/types/tsconfig.tsbuildinfo +0 -1
  35. package/dist/types/types.d.ts.map +0 -1
  36. /package/dist/{types/cli.d.ts → cli.d.ts} +0 -0
  37. /package/dist/{types/media-from-env.d.ts → media-from-env.d.ts} +0 -0
  38. /package/dist/{types/server.d.ts → server.d.ts} +0 -0
  39. /package/dist/{types/types.d.ts → types.d.ts} +0 -0
package/dist/server.js ADDED
@@ -0,0 +1,1100 @@
1
+ import { CmsCommitConflictError, isUnsafeFolder, listFilteredMedia, listProjectImages, MEDIA_CURSOR_TYPE_MISMATCH, MEDIA_INVALID_FOLDER, MediaCursorError, mediaErrorStatus, parseMediaTypeFilter, parseProjectCmsConfig, resolveByteRange, resolvePathnameFromSpec, scanRouteCollections, } from '@nuasite/cms-core';
2
+ import { filterMediaItems } from '@nuasite/cms-types';
3
+ import { hashContent, hashSource, KeyedMutex, SharedRun } from "./concurrency.js";
4
+ import { STATUS_BY_CODE, } from "./types.js";
5
+ /** Features the sidecar advertises so older/newer clients can degrade gracefully. */
6
+ export const SIDECAR_FEATURES = [
7
+ 'collections',
8
+ 'entries.fields-projection',
9
+ 'entries.draft-filter',
10
+ 'entries.pagination',
11
+ 'entry.crud',
12
+ 'entry.rename',
13
+ 'entry.array',
14
+ 'entry.asset',
15
+ 'project.asset',
16
+ 'entry.optimistic-concurrency',
17
+ 'pages.crud',
18
+ 'pages.list',
19
+ 'pages.layouts',
20
+ 'redirects.crud',
21
+ 'media',
22
+ 'media.project-images',
23
+ 'media.type-filter',
24
+ 'components',
25
+ 'config',
26
+ ];
27
+ const API_PREFIX = '/cms/v1';
28
+ const DEFAULT_LIMIT = 50;
29
+ const MAX_LIMIT = 1000;
30
+ // ============================================================================
31
+ // Response helpers
32
+ // ============================================================================
33
+ function json(body, status = 200) {
34
+ return new Response(JSON.stringify(body), {
35
+ status,
36
+ headers: { 'content-type': 'application/json; charset=utf-8' },
37
+ });
38
+ }
39
+ function error(code, message, sourcePath) {
40
+ const body = { error: message, code };
41
+ if (sourcePath !== undefined)
42
+ body.sourcePath = sourcePath;
43
+ return json(body, STATUS_BY_CODE[code]);
44
+ }
45
+ /** An asset's bytes, or the slice a `Range` request asked for — what a `<video>` preview needs to seek. */
46
+ function assetBytesResponse(asset, req) {
47
+ const size = asset.bytes.byteLength;
48
+ const headers = { 'content-type': asset.contentType, 'cache-control': 'no-cache', 'accept-ranges': 'bytes' };
49
+ const range = resolveByteRange(req.headers.get('range'), size);
50
+ if (range === null)
51
+ return new Response(asset.bytes, { headers });
52
+ if (range === 'unsatisfiable')
53
+ return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } });
54
+ return new Response(asset.bytes.subarray(range.start, range.end + 1), {
55
+ status: 206,
56
+ headers: { ...headers, 'content-range': `bytes ${range.start}-${range.end}/${size}` },
57
+ });
58
+ }
59
+ /**
60
+ * Map a cms-core `MutationResult` to an HTTP response. A failed result becomes a
61
+ * typed `ApiError`: "not found" → 404, everything else (validation, already
62
+ * exists, write failures) → the supplied default code.
63
+ */
64
+ function mutationResponse(result, fallback = 'validation') {
65
+ if (result.success)
66
+ return json(result);
67
+ const message = result.error ?? 'Mutation failed';
68
+ const code = /not found/i.test(message) ? 'not_found' : fallback;
69
+ return error(code, message, result.sourcePath);
70
+ }
71
+ /**
72
+ * Map a failed media adapter result to an HTTP response. An id or folder the adapter
73
+ * refuses is the caller's mistake → 400, a file that is not there → 404; everything
74
+ * else is a storage failure → 500. The adapter says which by answering with one of
75
+ * cms-core's exact strings (`mediaErrorStatus`): the text of any other error decides
76
+ * nothing, since it may come from an SDK or an upstream service.
77
+ */
78
+ function mediaFailure(message) {
79
+ const status = mediaErrorStatus(message);
80
+ const code = status === 400 ? 'validation' : status === 404 ? 'not_found' : 'io_error';
81
+ return error(code, message);
82
+ }
83
+ async function parseJson(req) {
84
+ try {
85
+ // `JSON.parse` returns `any`, which flows to `T` without a cast. Body shapes
86
+ // are field-validated per route before use, never trusted blindly.
87
+ const text = await req.text();
88
+ const value = JSON.parse(text);
89
+ return { ok: true, value };
90
+ }
91
+ catch {
92
+ return { ok: false, response: error('validation', 'Invalid JSON body') };
93
+ }
94
+ }
95
+ function parseEntriesQuery(url) {
96
+ const fields = url.searchParams.get('fields') ?? undefined;
97
+ const rawDraft = url.searchParams.get('draft');
98
+ const draft = rawDraft === 'true' || rawDraft === 'all' ? rawDraft : 'false';
99
+ const rawLimit = url.searchParams.get('limit');
100
+ let limit;
101
+ if (rawLimit !== null) {
102
+ const parsed = Number.parseInt(rawLimit, 10);
103
+ if (Number.isFinite(parsed) && parsed > 0)
104
+ limit = Math.min(parsed, MAX_LIMIT);
105
+ }
106
+ const cursor = url.searchParams.get('cursor') ?? undefined;
107
+ return { fields, draft, limit, cursor };
108
+ }
109
+ const MEDIA_CURSOR_VERSION = 1;
110
+ /** The tab a decoded cursor belongs to; absent has always meant "the whole listing". */
111
+ function cursorType(state) {
112
+ return state.type ?? 'all';
113
+ }
114
+ /** A merged-listing cursor followed somewhere the merge does not run: without the flag, or in a folder. */
115
+ const MERGED_CURSOR_OUTSIDE_MERGE = 'This cursor continues an ?includeProjectImages listing: keep the flag set and drop ?folder when following it';
116
+ function encodeMediaCursor(state) {
117
+ return Buffer.from(JSON.stringify({ v: MEDIA_CURSOR_VERSION, ...state }), 'utf8').toString('base64url');
118
+ }
119
+ function parseCursorFolders(value) {
120
+ if (!Array.isArray(value))
121
+ return null;
122
+ const entries = value;
123
+ const folders = [];
124
+ for (const entry of entries) {
125
+ if (typeof entry !== 'object' || entry === null)
126
+ return null;
127
+ if (!('name' in entry) || typeof entry.name !== 'string')
128
+ return null;
129
+ if (!('path' in entry) || typeof entry.path !== 'string')
130
+ return null;
131
+ folders.push({ name: entry.name, path: entry.path });
132
+ }
133
+ return folders;
134
+ }
135
+ /**
136
+ * Decode a merge cursor. Anything that is not a cursor *we* minted is rejected —
137
+ * including a well-formed but positionless one (`{}`, `[]`, `{"foo":1}`), which
138
+ * would otherwise silently restart the listing at page 1.
139
+ */
140
+ function decodeMediaCursor(raw) {
141
+ if (raw === undefined)
142
+ return { ok: true, state: {} };
143
+ let parsed;
144
+ try {
145
+ parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
146
+ }
147
+ catch {
148
+ return { ok: false };
149
+ }
150
+ if (typeof parsed !== 'object' || parsed === null)
151
+ return { ok: false };
152
+ if (!('v' in parsed) || parsed.v !== MEDIA_CURSOR_VERSION)
153
+ return { ok: false };
154
+ const state = {};
155
+ if ('adapter' in parsed) {
156
+ if (typeof parsed.adapter !== 'string')
157
+ return { ok: false };
158
+ state.adapter = parsed.adapter;
159
+ }
160
+ if ('project' in parsed) {
161
+ if (typeof parsed.project !== 'number' || !Number.isInteger(parsed.project) || parsed.project < 0)
162
+ return { ok: false };
163
+ state.project = parsed.project;
164
+ }
165
+ if ('folders' in parsed) {
166
+ const folders = parseCursorFolders(parsed.folders);
167
+ if (folders === null)
168
+ return { ok: false };
169
+ state.folders = folders;
170
+ }
171
+ if ('type' in parsed) {
172
+ if (typeof parsed.type !== 'string')
173
+ return { ok: false };
174
+ const type = parseMediaTypeFilter(parsed.type);
175
+ if (type === null)
176
+ return { ok: false };
177
+ state.type = type;
178
+ }
179
+ // We only ever mint a cursor that carries a position; one without is malformed.
180
+ if (state.adapter === undefined && state.project === undefined)
181
+ return { ok: false };
182
+ return { ok: true, state };
183
+ }
184
+ /**
185
+ * `?includeProjectImages` — present with no value, `true` or `1` enable it; `false`
186
+ * or `0` disable it. `null` means the caller sent something else, which is a client
187
+ * error: silently ignoring e.g. `TRUE` would drop the project images without a word.
188
+ */
189
+ function parseIncludeProjectImages(raw) {
190
+ if (raw === null)
191
+ return false;
192
+ if (raw === '' || raw === 'true' || raw === '1')
193
+ return true;
194
+ if (raw === 'false' || raw === '0')
195
+ return false;
196
+ return null;
197
+ }
198
+ // ============================================================================
199
+ // Entry projection (fields)
200
+ // ============================================================================
201
+ /**
202
+ * Project a scanned `CollectionEntryInfo` down to the requested `fields`.
203
+ *
204
+ * - absent: light header (slug/title/draft/pathname/previewPathname/sourcePath), never the body.
205
+ * - `*`: all frontmatter (via `data`), still no body.
206
+ * - `a,b`: those frontmatter keys (plus the always-present slug/sourcePath).
207
+ *
208
+ * The body lives only behind the entry-detail route, so a list stays small even
209
+ * for large/data collections.
210
+ */
211
+ function projectEntry(entry, fields) {
212
+ if (fields === '*') {
213
+ // All frontmatter, still no body. `data` already carries the full frontmatter.
214
+ const projected = { slug: entry.slug, sourcePath: entry.sourcePath };
215
+ if (entry.title !== undefined)
216
+ projected.title = entry.title;
217
+ if (entry.draft !== undefined)
218
+ projected.draft = entry.draft;
219
+ if (entry.pathname !== undefined)
220
+ projected.pathname = entry.pathname;
221
+ if (entry.previewPathname !== undefined)
222
+ projected.previewPathname = entry.previewPathname;
223
+ if (entry.data !== undefined)
224
+ projected.data = entry.data;
225
+ return projected;
226
+ }
227
+ if (fields === undefined || fields.trim() === '') {
228
+ const projected = { slug: entry.slug, sourcePath: entry.sourcePath };
229
+ if (entry.title !== undefined)
230
+ projected.title = entry.title;
231
+ if (entry.draft !== undefined)
232
+ projected.draft = entry.draft;
233
+ if (entry.pathname !== undefined)
234
+ projected.pathname = entry.pathname;
235
+ if (entry.previewPathname !== undefined)
236
+ projected.previewPathname = entry.previewPathname;
237
+ return projected;
238
+ }
239
+ const keys = fields.split(',').map(k => k.trim()).filter(Boolean);
240
+ // slug + sourcePath are always-present identity fields.
241
+ const projected = { slug: entry.slug, sourcePath: entry.sourcePath };
242
+ const data = {};
243
+ for (const key of keys) {
244
+ switch (key) {
245
+ case 'slug':
246
+ case 'sourcePath':
247
+ break;
248
+ case 'title':
249
+ if (entry.title !== undefined)
250
+ projected.title = entry.title;
251
+ break;
252
+ case 'draft':
253
+ if (entry.draft !== undefined)
254
+ projected.draft = entry.draft;
255
+ break;
256
+ case 'pathname':
257
+ if (entry.pathname !== undefined)
258
+ projected.pathname = entry.pathname;
259
+ break;
260
+ case 'previewPathname':
261
+ if (entry.previewPathname !== undefined)
262
+ projected.previewPathname = entry.previewPathname;
263
+ break;
264
+ default: {
265
+ const value = entry.data?.[key];
266
+ if (value !== undefined)
267
+ data[key] = value;
268
+ }
269
+ }
270
+ }
271
+ if (Object.keys(data).length > 0)
272
+ projected.data = data;
273
+ return projected;
274
+ }
275
+ /** Apply the draft filter to a scanned entry list. */
276
+ function filterByDraft(entries, draft) {
277
+ if (draft === 'all')
278
+ return entries;
279
+ const wantDraft = draft === 'true';
280
+ return entries.filter(e => (e.draft === true) === wantDraft);
281
+ }
282
+ /**
283
+ * Opaque-but-real cursor: a base64url offset into the (stably scan-ordered) entry
284
+ * list. We never silently cap — when more remain, the next cursor is returned and
285
+ * `hasMore` is set; absent a cursor we start at offset 0.
286
+ */
287
+ function decodeCursor(cursor) {
288
+ if (!cursor)
289
+ return 0;
290
+ try {
291
+ const decoded = Buffer.from(cursor, 'base64url').toString('utf-8');
292
+ const offset = Number.parseInt(decoded, 10);
293
+ return Number.isFinite(offset) && offset >= 0 ? offset : 0;
294
+ }
295
+ catch {
296
+ return 0;
297
+ }
298
+ }
299
+ function encodeCursor(offset) {
300
+ return Buffer.from(String(offset), 'utf-8').toString('base64url');
301
+ }
302
+ // ============================================================================
303
+ // Page list (sidecar-layer fs walk; cms-core has no page-listing capability)
304
+ // ============================================================================
305
+ const PAGE_EXTENSIONS = ['.astro', '.md', '.mdx'];
306
+ /**
307
+ * Walk `src/pages` through the `CmsFileSystem` port and derive static page
308
+ * routes. Skips underscore/dot files, dynamic segments (`[...]`) and non-page
309
+ * extensions — mirroring the dev server's filesystem page discovery. Yields
310
+ * `pathname` only; an SEO `title` would require the render manifest (out of scope).
311
+ */
312
+ async function listPages(fs) {
313
+ const pathnames = [];
314
+ async function walk(dir, urlPrefix) {
315
+ const entries = await fs.list(dir);
316
+ for (const entry of entries) {
317
+ if (entry.name.startsWith('_') || entry.name.startsWith('.'))
318
+ continue;
319
+ if (entry.name.includes('['))
320
+ continue;
321
+ const full = `${dir}/${entry.name}`;
322
+ if (entry.isDirectory) {
323
+ await walk(full, `${urlPrefix}${entry.name}/`);
324
+ continue;
325
+ }
326
+ const dot = entry.name.lastIndexOf('.');
327
+ const ext = dot >= 0 ? entry.name.slice(dot) : '';
328
+ if (!PAGE_EXTENSIONS.includes(ext))
329
+ continue;
330
+ const baseName = entry.name.slice(0, entry.name.length - ext.length);
331
+ const pathname = baseName === 'index'
332
+ ? (urlPrefix.replace(/\/$/, '') || '/')
333
+ : `${urlPrefix}${baseName}`;
334
+ pathnames.push(pathname);
335
+ }
336
+ }
337
+ await walk('src/pages', '/');
338
+ pathnames.sort((a, b) => a.localeCompare(b));
339
+ return pathnames.map(pathname => ({ pathname }));
340
+ }
341
+ /**
342
+ * Map each collection to the route that renders it, by parsing the Astro pages under
343
+ * `src/pages` with {@link scanRouteCollections}. This is the only reliable source for an
344
+ * entry's URL: it comes from the route, not the collection name (a `product` collection
345
+ * can live at `/products`, an `faq` collection on a single `/faq` page).
346
+ *
347
+ * - A *dynamic* route (`[...slug].astro`, or a `[slug]/index.astro` directory) renders one
348
+ * page per entry; the URL base is the path up to its dynamic segment. Every collection
349
+ * its `getStaticPaths` enumerates is page-per-item here — a single `[slug]` detail may
350
+ * drive several (a shared detail for `products` + `references` + …). Render-body
351
+ * `getCollection` lookups (e.g. an author on a post page) are excluded; when there is no
352
+ * `getStaticPaths` block to read, only the first `getCollection` counts.
353
+ * - A *static* page renders every collection it reads on that one shared URL.
354
+ * - A per-item (dynamic) route wins over a shared page if a collection has both.
355
+ *
356
+ * Collections rendered nowhere are absent: their entries get no `pathname`, so a
357
+ * consumer knows there is no page to open.
358
+ */
359
+ async function resolveCollectionRoutes(fs) {
360
+ const routes = new Map();
361
+ const consider = (name, route) => {
362
+ const existing = routes.get(name);
363
+ // Per-item routes win over a shared page; otherwise the first match wins.
364
+ if (!existing || (route.perItem && !existing.perItem))
365
+ routes.set(name, route);
366
+ };
367
+ async function walk(dir, urlPrefix) {
368
+ const entries = await fs.list(dir);
369
+ for (const entry of entries) {
370
+ if (entry.name.startsWith('_') || entry.name.startsWith('.'))
371
+ continue;
372
+ const full = `${dir}/${entry.name}`;
373
+ if (entry.isDirectory) {
374
+ await walk(full, `${urlPrefix}${entry.name}/`);
375
+ continue;
376
+ }
377
+ // `getCollection` lives in Astro page frontmatter.
378
+ if (!entry.name.endsWith('.astro'))
379
+ continue;
380
+ let content;
381
+ try {
382
+ content = await fs.readFile(full);
383
+ }
384
+ catch {
385
+ continue;
386
+ }
387
+ const { staticPaths, all } = scanRouteCollections(content);
388
+ if (all.length === 0)
389
+ continue;
390
+ // Full route path: directory prefix + file segment (Astro drops `index`).
391
+ const baseName = entry.name.slice(0, -'.astro'.length);
392
+ const routePath = baseName === 'index' ? urlPrefix : `${urlPrefix}${baseName}`;
393
+ // A dynamic segment (`[slug]`, `[...slug]`) anywhere in the path makes this a
394
+ // page-per-item route — whether it comes from the filename (`[...slug].astro`) or
395
+ // a parent directory (`[slug]/index.astro`). Its base is the path up to the first
396
+ // dynamic segment (Astro segments are always whole, so `/[` is the marker).
397
+ const dynamicIdx = routePath.indexOf('/[');
398
+ if (dynamicIdx !== -1) {
399
+ const base = routePath.slice(0, dynamicIdx) || '/';
400
+ // Every collection the route's getStaticPaths enumerates is page-per-item; a single
401
+ // [slug] detail may drive several. Fall back to the first getCollection when there
402
+ // is no getStaticPaths block to read (e.g. an SSR route).
403
+ const drivers = staticPaths.length > 0 ? staticPaths : all.slice(0, 1);
404
+ for (const name of drivers)
405
+ consider(name, { base, perItem: true });
406
+ }
407
+ else {
408
+ // Static page: every collection it lists shares this page's URL.
409
+ const pathname = routePath.replace(/\/$/, '') || '/';
410
+ for (const name of all)
411
+ consider(name, { base: pathname, perItem: false });
412
+ }
413
+ }
414
+ }
415
+ await walk('src/pages', '/');
416
+ return routes;
417
+ }
418
+ /** Build an entry's page URL from its collection route (see {@link CollectionRoute}). */
419
+ function entryPathname(route, slug) {
420
+ if (!route.perItem)
421
+ return route.base || '/';
422
+ // A root-level `[slug]` route has base `/`; joining naively would double the slash.
423
+ return `${route.base === '/' ? '' : route.base}/${slug}`;
424
+ }
425
+ /**
426
+ * Tag one scanned entry with the page it lives at. This is the sidecar's half of the same
427
+ * rule `buildCollectionManifestPages` applies in `@nuasite/cms`'s dev middleware — the two
428
+ * surfaces must answer "where does this entry live?" identically, or the dash and the
429
+ * preview disagree about a collection:
430
+ *
431
+ * - a `fragment` collection owns no page, so the *whole* chain is suppressed rather than
432
+ * just its route-prefix arm. An already-present pathname is no better: it can only have
433
+ * come from the page that renders the fragment, which belongs to that page. The
434
+ * collection's `previewOf` travels as `previewPathname` instead — a preview target, never
435
+ * a URL the entry claims.
436
+ * - otherwise: an already-resolved pathname wins, then the declarative `cms.pathname` rule
437
+ * (authoritative — it composes the URL from fields, e.g. topic/urlFamily + slug, matching
438
+ * the site's forward resolver, so an entry whose URL segment differs from its filename
439
+ * slug still opens the right page), then the discovered route prefix + slug.
440
+ *
441
+ * Entries are copied rather than mutated, and only when something actually changes, so the
442
+ * cached scan keeps its own identity.
443
+ */
444
+ function entryWithPageUrl(def, entry, route) {
445
+ // The fragment short-circuit sits above every pathname source, so a source added below
446
+ // can never fabricate a URL for a collection that has no page.
447
+ if (def.fragment) {
448
+ if (entry.pathname === undefined && entry.previewPathname === def.previewOf)
449
+ return entry;
450
+ const { pathname: _pathname, previewPathname: _previewPathname, ...rest } = entry;
451
+ const projected = { ...rest };
452
+ if (def.previewOf !== undefined)
453
+ projected.previewPathname = def.previewOf;
454
+ return projected;
455
+ }
456
+ if (entry.pathname !== undefined)
457
+ return entry;
458
+ const fromSpec = resolvePathnameFromSpec(def, entry.data);
459
+ if (fromSpec !== undefined)
460
+ return { ...entry, pathname: fromSpec };
461
+ if (route !== undefined)
462
+ return { ...entry, pathname: entryPathname(route, entry.slug) };
463
+ return entry;
464
+ }
465
+ export function createServer(opts) {
466
+ const { core, fs, root, coreVersion } = opts;
467
+ const contentDir = opts.contentDir ?? 'src/content';
468
+ const maxUploadSize = opts.maxUploadSize ?? 20 * 1024 * 1024;
469
+ const mutex = new KeyedMutex();
470
+ // A client may ask for the entries of every collection at once, and each scan reads and parses
471
+ // all of the project's content: without sharing, N concurrent requests hold N full scans in memory.
472
+ const collectionsScan = new SharedRun(() => core.scanCollections({ report: false }));
473
+ // `GET /project` alone answers with the scan report, so it alone pays for building one. Its
474
+ // collections come from that same scan, so the two always describe one state of the disk.
475
+ const reportedScan = new SharedRun(() => core.scanCollections({ report: true }));
476
+ const collectionRoutes = new SharedRun(() => resolveCollectionRoutes(fs));
477
+ async function scanList() {
478
+ const map = await collectionsScan.get();
479
+ return Object.values(map);
480
+ }
481
+ async function resolveCollection(name) {
482
+ const map = await collectionsScan.get();
483
+ return map[name] ?? null;
484
+ }
485
+ // Astro component definitions used by the headless MDX body editor (block picker
486
+ // + block-card prop labels). Same scan that feeds updateEntry's MDX import injection.
487
+ async function scanComponentsList() {
488
+ const map = await core.scanComponents();
489
+ return Object.values(map).sort((a, b) => a.name.localeCompare(b.name));
490
+ }
491
+ async function readConfig() {
492
+ return parseProjectCmsConfig(fs);
493
+ }
494
+ // --- Entry detail (assembles the CollectionEntry wire shape) ---
495
+ async function entryDetail(collection, slug) {
496
+ const result = await core.getEntry(collection, slug);
497
+ if (!result)
498
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
499
+ const def = await resolveCollection(collection);
500
+ // frontmatter values are stringified for the line-keyed wire shape; line
501
+ // numbers are not tracked headlessly (the inline widget owns line-precise edits).
502
+ const frontmatter = {};
503
+ for (const [key, value] of Object.entries(result.frontmatter)) {
504
+ frontmatter[key] = { value: typeof value === 'string' ? value : JSON.stringify(value), line: 0 };
505
+ }
506
+ const entry = {
507
+ collectionName: def?.name ?? collection,
508
+ collectionSlug: slug,
509
+ sourcePath: result.sourcePath,
510
+ frontmatter,
511
+ body: result.content,
512
+ bodyStartLine: 0,
513
+ };
514
+ return json(entry);
515
+ }
516
+ // --- GET entry asset (resolve an image/file value relative to the entry source, stream the bytes) ---
517
+ async function assetResponse(collection, slug, req, url) {
518
+ const assetPath = url.searchParams.get('path');
519
+ if (assetPath === null || assetPath === '')
520
+ return error('validation', 'A "path" query parameter is required');
521
+ const asset = await core.getEntryAsset(collection, slug, assetPath);
522
+ if (!asset)
523
+ return error('not_found', `Asset not found for ${collection}/${slug}: ${assetPath}`);
524
+ return assetBytesResponse(asset, req);
525
+ }
526
+ // --- GET project asset (resolve a root-relative /assets|/uploads value with no owning entry) ---
527
+ async function projectAssetResponse(req, url) {
528
+ const assetPath = url.searchParams.get('path');
529
+ if (assetPath === null || assetPath === '')
530
+ return error('validation', 'A "path" query parameter is required');
531
+ const asset = await core.getProjectAsset(assetPath);
532
+ if (!asset)
533
+ return error('not_found', `Asset not found: ${assetPath}`);
534
+ return assetBytesResponse(asset, req);
535
+ }
536
+ // --- PATCH entry (optimistic concurrency + per-file mutex) ---
537
+ async function patchEntry(collection, slug, body) {
538
+ const existing = await core.getEntry(collection, slug);
539
+ if (!existing)
540
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
541
+ const sourcePath = existing.sourcePath;
542
+ const existingFrontmatter = existing.frontmatter;
543
+ /** The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". */
544
+ async function conflictResponse(serverHash) {
545
+ const current = await core.getEntry(collection, slug);
546
+ const conflict = {
547
+ code: 'conflict',
548
+ serverHash,
549
+ serverFrontmatter: current?.frontmatter ?? existingFrontmatter,
550
+ };
551
+ if (current && current.content !== '')
552
+ conflict.serverBody = current.content;
553
+ return json(conflict, STATUS_BY_CODE.conflict);
554
+ }
555
+ return mutex.runExclusive(sourcePath, async () => {
556
+ // Re-hash under the lock so a concurrent writer cannot slip in between.
557
+ const serverHash = await hashSource(fs, sourcePath);
558
+ if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
559
+ return conflictResponse(serverHash);
560
+ }
561
+ let result;
562
+ try {
563
+ result = await core.updateEntry({
564
+ collection,
565
+ slug,
566
+ frontmatter: body.frontmatter,
567
+ body: body.body,
568
+ });
569
+ }
570
+ catch (cause) {
571
+ // The core's commit found the file changed by a writer outside this server's lock.
572
+ if (!(cause instanceof CmsCommitConflictError))
573
+ throw cause;
574
+ const currentHash = await hashSource(fs, sourcePath);
575
+ // Removed meanwhile: there is no server version to offer, only the plain conflict.
576
+ if (currentHash === null)
577
+ throw cause;
578
+ return conflictResponse(currentHash);
579
+ }
580
+ if (!result.success)
581
+ return mutationResponse(result);
582
+ const newHash = await hashSource(fs, result.sourcePath ?? sourcePath);
583
+ const enriched = { ...result };
584
+ if (newHash !== null)
585
+ enriched.sourceHash = newHash;
586
+ return json(enriched);
587
+ });
588
+ }
589
+ async function fetchHandler(req) {
590
+ const url = new URL(req.url);
591
+ let pathname = url.pathname;
592
+ if (pathname.length > 1 && pathname.endsWith('/'))
593
+ pathname = pathname.slice(0, -1);
594
+ // /health is unversioned (liveness probe).
595
+ if (pathname === '/health' && req.method === 'GET') {
596
+ return json({ ok: true, coreVersion, root });
597
+ }
598
+ if (!pathname.startsWith(API_PREFIX)) {
599
+ return error('not_found', `No route: ${req.method} ${pathname}`);
600
+ }
601
+ const rest = pathname.slice(API_PREFIX.length) || '/';
602
+ let segments;
603
+ try {
604
+ segments = rest.split('/').filter(Boolean).map(decodeURIComponent);
605
+ }
606
+ catch {
607
+ return error('validation', 'Malformed percent-encoding in the request path');
608
+ }
609
+ const method = req.method;
610
+ try {
611
+ return await route(method, segments, req, url);
612
+ }
613
+ catch (cause) {
614
+ if (cause instanceof CmsCommitConflictError)
615
+ return error('conflict', cause.message);
616
+ throw cause;
617
+ }
618
+ finally {
619
+ // Any write may change what the shared scans read.
620
+ if (method !== 'GET') {
621
+ collectionsScan.invalidate();
622
+ reportedScan.invalidate();
623
+ collectionRoutes.invalidate();
624
+ }
625
+ }
626
+ }
627
+ async function route(method, segments, req, url) {
628
+ const [head, ...tail] = segments;
629
+ switch (head) {
630
+ case 'health':
631
+ if (method === 'GET')
632
+ return json({ ok: true, coreVersion, root });
633
+ break;
634
+ case 'project':
635
+ if (method === 'GET') {
636
+ const [scanned, pages] = await Promise.all([reportedScan.get(), listPages(fs)]);
637
+ const capabilities = { coreVersion, features: [...SIDECAR_FEATURES] };
638
+ const model = { collections: Object.values(scanned), pages, capabilities };
639
+ // The report of the very scan `collections` came from. Left out, not sent empty,
640
+ // when the core has none: a client must be able to tell the two apart.
641
+ const collectionScan = core.collectionScanReport?.(scanned);
642
+ if (collectionScan !== undefined)
643
+ model.collectionScan = collectionScan;
644
+ return json(model);
645
+ }
646
+ break;
647
+ case 'components':
648
+ if (method === 'GET')
649
+ return json(await scanComponentsList());
650
+ break;
651
+ case 'config':
652
+ if (method === 'GET')
653
+ return json(await readConfig());
654
+ break;
655
+ case 'asset':
656
+ if (method === 'GET')
657
+ return projectAssetResponse(req, url);
658
+ break;
659
+ case 'collections':
660
+ return routeCollections(method, tail, req, url);
661
+ case 'pages':
662
+ return routePages(method, tail, req);
663
+ case 'redirects':
664
+ return routeRedirects(method, tail, req);
665
+ case 'media':
666
+ return routeMedia(method, tail, req, url);
667
+ }
668
+ return error('not_found', `No route: ${method} /cms/v1/${segments.join('/')}`);
669
+ }
670
+ async function routeCollections(method, tail, req, url) {
671
+ // GET /collections
672
+ if (tail.length === 0) {
673
+ if (method === 'GET')
674
+ return json(await scanList());
675
+ return error('unsupported', `Unsupported: ${method} /collections`);
676
+ }
677
+ const [collection, sub, slug, action] = tail;
678
+ // /collections/:c/entries[...]
679
+ if (sub === 'entries' && collection) {
680
+ // GET /collections/:c/entries (sparse list)
681
+ if (slug === undefined) {
682
+ if (method === 'GET')
683
+ return listEntries(collection, url);
684
+ if (method === 'POST')
685
+ return createEntry(collection, req);
686
+ return error('unsupported', `Unsupported: ${method} /collections/${collection}/entries`);
687
+ }
688
+ // /collections/:c/entries/:slug[...]
689
+ if (action === undefined) {
690
+ if (method === 'GET')
691
+ return entryDetail(collection, slug);
692
+ if (method === 'PATCH')
693
+ return updateEntryRoute(collection, slug, req);
694
+ if (method === 'DELETE')
695
+ return deleteEntryRoute(collection, slug);
696
+ return error('unsupported', `Unsupported: ${method} /collections/${collection}/entries/${slug}`);
697
+ }
698
+ if (action === 'rename' && method === 'POST')
699
+ return renameEntryRoute(collection, slug, req);
700
+ if (action === 'array' && method === 'POST')
701
+ return addArrayRoute(collection, slug, req);
702
+ if (action === 'array' && method === 'DELETE')
703
+ return removeArrayRoute(collection, slug, req);
704
+ if (action === 'asset' && method === 'GET')
705
+ return assetResponse(collection, slug, req, url);
706
+ }
707
+ return error('not_found', `No route: ${method} /cms/v1/collections/${tail.join('/')}`);
708
+ }
709
+ async function listEntries(collection, url) {
710
+ const def = await resolveCollection(collection);
711
+ if (!def)
712
+ return error('not_found', `Collection not found: ${collection}`);
713
+ const query = parseEntriesQuery(url);
714
+ // Tag entries with the URL of their rendered page (when the collection has a route),
715
+ // so a consumer can sync a preview to the entry being edited. Falls back to no
716
+ // pathname on any fs error — better absent than wrong.
717
+ const routes = await collectionRoutes.get().catch(() => new Map());
718
+ const route = routes.get(collection);
719
+ const all = (def.entries ?? []).map(e => entryWithPageUrl(def, e, route));
720
+ const filtered = filterByDraft(all, query.draft);
721
+ const offset = decodeCursor(query.cursor);
722
+ const limit = query.limit ?? DEFAULT_LIMIT;
723
+ const page = filtered.slice(offset, offset + limit);
724
+ const hasMore = offset + limit < filtered.length;
725
+ const entries = page.map(e => projectEntry(e, query.fields));
726
+ const result = { entries, hasMore };
727
+ if (hasMore)
728
+ result.cursor = encodeCursor(offset + limit);
729
+ return json(result);
730
+ }
731
+ async function createEntry(collection, req) {
732
+ const parsed = await parseJson(req);
733
+ if (!parsed.ok)
734
+ return parsed.response;
735
+ const body = parsed.value;
736
+ if (typeof body.slug !== 'string' || body.slug.trim() === '') {
737
+ return error('validation', 'A non-empty "slug" is required');
738
+ }
739
+ if (body.frontmatter === undefined || typeof body.frontmatter !== 'object') {
740
+ return error('validation', 'A "frontmatter" object is required');
741
+ }
742
+ const result = await core.createEntry({
743
+ collection,
744
+ slug: body.slug,
745
+ frontmatter: body.frontmatter,
746
+ body: body.body,
747
+ fileExtension: body.fileExtension,
748
+ });
749
+ if (!result.success)
750
+ return mutationResponse(result);
751
+ const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null;
752
+ const enriched = { ...result };
753
+ if (newHash !== null)
754
+ enriched.sourceHash = newHash;
755
+ return json(enriched);
756
+ }
757
+ async function updateEntryRoute(collection, slug, req) {
758
+ const parsed = await parseJson(req);
759
+ if (!parsed.ok)
760
+ return parsed.response;
761
+ return patchEntry(collection, slug, parsed.value);
762
+ }
763
+ async function deleteEntryRoute(collection, slug) {
764
+ const existing = await core.getEntry(collection, slug);
765
+ if (!existing)
766
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
767
+ return mutex.runExclusive(existing.sourcePath, async () => {
768
+ const result = await core.deleteEntry(collection, slug);
769
+ return mutationResponse(result);
770
+ });
771
+ }
772
+ async function renameEntryRoute(collection, slug, req) {
773
+ const parsed = await parseJson(req);
774
+ if (!parsed.ok)
775
+ return parsed.response;
776
+ if (typeof parsed.value.to !== 'string' || parsed.value.to.trim() === '') {
777
+ return error('validation', 'A non-empty "to" slug is required');
778
+ }
779
+ const existing = await core.getEntry(collection, slug);
780
+ if (!existing)
781
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
782
+ return mutex.runExclusive(existing.sourcePath, async () => {
783
+ const result = await core.renameEntry(collection, slug, parsed.value.to);
784
+ if (!result.success)
785
+ return mutationResponse(result);
786
+ const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null;
787
+ const enriched = { ...result };
788
+ if (newHash !== null)
789
+ enriched.sourceHash = newHash;
790
+ return json(enriched);
791
+ });
792
+ }
793
+ async function addArrayRoute(collection, slug, req) {
794
+ const parsed = await parseJson(req);
795
+ if (!parsed.ok)
796
+ return parsed.response;
797
+ const body = parsed.value;
798
+ if (typeof body.field !== 'string' || body.field.trim() === '') {
799
+ return error('validation', 'A non-empty "field" is required');
800
+ }
801
+ const existing = await core.getEntry(collection, slug);
802
+ if (!existing)
803
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
804
+ return mutex.runExclusive(existing.sourcePath, async () => {
805
+ const result = await core.addArrayItem({ collection, slug, field: body.field, value: body.value, index: body.index });
806
+ return mutationResponse(result);
807
+ });
808
+ }
809
+ async function removeArrayRoute(collection, slug, req) {
810
+ const parsed = await parseJson(req);
811
+ if (!parsed.ok)
812
+ return parsed.response;
813
+ const body = parsed.value;
814
+ if (typeof body.field !== 'string' || body.field.trim() === '') {
815
+ return error('validation', 'A non-empty "field" is required');
816
+ }
817
+ if (typeof body.index !== 'number' || !Number.isInteger(body.index)) {
818
+ return error('validation', 'An integer "index" is required');
819
+ }
820
+ const existing = await core.getEntry(collection, slug);
821
+ if (!existing)
822
+ return error('not_found', `Entry not found: ${collection}/${slug}`);
823
+ return mutex.runExclusive(existing.sourcePath, async () => {
824
+ const result = await core.removeArrayItem({ collection, slug, field: body.field, index: body.index });
825
+ return mutationResponse(result);
826
+ });
827
+ }
828
+ async function routePages(method, tail, req) {
829
+ const [sub] = tail;
830
+ // GET /pages → fs-derived page list (cms-core has no page listing).
831
+ if (sub === undefined) {
832
+ if (method === 'GET')
833
+ return json({ pages: await listPages(fs) });
834
+ if (method === 'POST') {
835
+ const parsed = await parseJson(req);
836
+ if (!parsed.ok)
837
+ return parsed.response;
838
+ const result = await core.createPage(parsed.value);
839
+ return result.success ? json(result) : error('validation', result.error ?? 'Failed to create page');
840
+ }
841
+ if (method === 'DELETE') {
842
+ const parsed = await parseJson(req);
843
+ if (!parsed.ok)
844
+ return parsed.response;
845
+ const result = await core.deletePage(parsed.value);
846
+ if (result.success)
847
+ return json(result);
848
+ const code = /not found/i.test(result.error ?? '') ? 'not_found' : 'validation';
849
+ return error(code, result.error ?? 'Failed to delete page');
850
+ }
851
+ return error('unsupported', `Unsupported: ${method} /pages`);
852
+ }
853
+ // GET /pages/layouts
854
+ if (sub === 'layouts' && method === 'GET') {
855
+ return json({ layouts: await core.getLayouts() });
856
+ }
857
+ // POST /pages/duplicate
858
+ if (sub === 'duplicate' && method === 'POST') {
859
+ const parsed = await parseJson(req);
860
+ if (!parsed.ok)
861
+ return parsed.response;
862
+ const result = await core.duplicatePage(parsed.value);
863
+ if (result.success)
864
+ return json(result);
865
+ const code = /not found/i.test(result.error ?? '') ? 'not_found' : 'validation';
866
+ return error(code, result.error ?? 'Failed to duplicate page');
867
+ }
868
+ return error('not_found', `No route: ${method} /cms/v1/pages/${tail.join('/')}`);
869
+ }
870
+ async function routeRedirects(method, tail, req) {
871
+ const [sub] = tail;
872
+ if (sub === undefined) {
873
+ if (method === 'GET')
874
+ return json(await core.listRedirects());
875
+ if (method === 'POST') {
876
+ const parsed = await parseJson(req);
877
+ if (!parsed.ok)
878
+ return parsed.response;
879
+ const result = await core.addRedirect(parsed.value);
880
+ return result.success ? json(result) : error('validation', result.error ?? 'Failed to add redirect');
881
+ }
882
+ if (method === 'PATCH') {
883
+ const parsed = await parseJson(req);
884
+ if (!parsed.ok)
885
+ return parsed.response;
886
+ const result = await core.updateRedirect(parsed.value);
887
+ return result.success ? json(result) : error('validation', result.error ?? 'Failed to update redirect');
888
+ }
889
+ if (method === 'DELETE') {
890
+ const parsed = await parseJson(req);
891
+ if (!parsed.ok)
892
+ return parsed.response;
893
+ const result = await core.deleteRedirect(parsed.value);
894
+ return result.success ? json(result) : error('validation', result.error ?? 'Failed to delete redirect');
895
+ }
896
+ return error('unsupported', `Unsupported: ${method} /redirects`);
897
+ }
898
+ return error('not_found', `No route: ${method} /cms/v1/redirects/${tail.join('/')}`);
899
+ }
900
+ /**
901
+ * One page over both media sources: the storage adapter (uploads) and the project
902
+ * scan (images committed under `public/` and `src/`, e.g. by an agent). The two
903
+ * are listed in phases, never interleaved — the adapter is drained first, then the
904
+ * scan tops the page up — so a caller that keeps following `cursor` sees every
905
+ * item exactly once, in the scan's stable total order (filename, then URL).
906
+ *
907
+ * What it costs and what it does not promise:
908
+ * - the scan is unpaginated by nature, so it re-walks `public/` and `src/` on
909
+ * every page that reaches the scan phase, plus once at the end of the adapter
910
+ * phase to top that page up;
911
+ * - a page holds at most `limit` items as long as the adapter honours `limit`; an
912
+ * over-returning adapter makes it longer. Paging terminates either way, because
913
+ * the scan slice is bounded by the room the adapter left;
914
+ * - `folders` is the adapter's, carried through the cursor so that every page —
915
+ * including the scan-only ones, which never call the adapter — reports it.
916
+ */
917
+ async function listMergedMedia(adapter, limit, rawCursor, type) {
918
+ const decoded = decodeMediaCursor(rawCursor);
919
+ if (!decoded.ok)
920
+ return error('validation', 'Invalid media cursor');
921
+ if (rawCursor !== undefined && cursorType(decoded.state) !== type)
922
+ return error('validation', MEDIA_CURSOR_TYPE_MISMATCH);
923
+ const { adapter: adapterCursor, project: projectOffset, folders: carriedFolders } = decoded.state;
924
+ const items = [];
925
+ let folders = carriedFolders ?? [];
926
+ // A `project` offset in the cursor means the adapter pages are already spent.
927
+ if (projectOffset === undefined) {
928
+ // Filtered above the adapter, which cannot do it itself — see `listFilteredMedia`. The
929
+ // cursor it hands back is still one the adapter minted, so the phase resumes normally.
930
+ const page = await listFilteredMedia(options => adapter.list(options), { limit, cursor: adapterCursor, type });
931
+ items.push(...page.items);
932
+ folders = page.folders;
933
+ // An adapter that reports more pages but hands back no cursor cannot be advanced. Stop
934
+ // here anyway — falling through to the scan would silently drop the rest of its items.
935
+ if (page.hasMore) {
936
+ const cursor = page.cursor === undefined ? undefined : encodeMediaCursor({ adapter: page.cursor, folders, type });
937
+ const more = { items, folders, hasMore: true, cursor, appliedType: type };
938
+ return json(more);
939
+ }
940
+ }
941
+ // The scan is one unpaginated list, so its filter is a plain one — and the offset the cursor
942
+ // carries indexes the *filtered* list, which is stable for as long as the tree is.
943
+ const offset = projectOffset ?? 0;
944
+ const projectImages = filterMediaItems(await listProjectImages(fs, { exclude: { dir: adapter.staticFiles?.dir, root } }), type);
945
+ const slice = projectImages.slice(offset, offset + Math.max(0, limit - items.length));
946
+ items.push(...slice);
947
+ const next = offset + slice.length;
948
+ const hasMore = next < projectImages.length;
949
+ const result = {
950
+ items,
951
+ folders,
952
+ hasMore,
953
+ cursor: hasMore ? encodeMediaCursor({ project: next, folders, type }) : undefined,
954
+ appliedType: type,
955
+ };
956
+ return json(result);
957
+ }
958
+ /** The media routes, with anything an adapter throws answered as a path-free `io_error`. */
959
+ async function routeMedia(method, tail, req, url) {
960
+ try {
961
+ return await answerMedia(method, tail, req, url);
962
+ }
963
+ catch (cause) {
964
+ // A filtered cursor `listFilteredMedia` refused is the caller's mistake, not storage's.
965
+ if (cause instanceof MediaCursorError)
966
+ return error('validation', cause.message);
967
+ // Whatever an adapter throws may spell out a filesystem path, and left uncaught it
968
+ // is rendered by the runtime's error page. The detail goes to the log instead.
969
+ console.error('[cms-sidecar] media request failed:', cause);
970
+ return error('io_error', 'Media storage failed');
971
+ }
972
+ }
973
+ /**
974
+ * `GET /media` lists the storage adapter alone by default. `?includeProjectImages`
975
+ * (bare, or `=true` / `=1`; root only, no `folder`) merges in the project scan behind
976
+ * a composite cursor — see `listMergedMedia`. Advertised as the `media.project-images`
977
+ * feature. An unrecognised flag value, or a merge cursor followed without the flag,
978
+ * is a 400 rather than a silently different listing.
979
+ */
980
+ async function answerMedia(method, tail, req, url) {
981
+ const adapter = core.media;
982
+ if (!adapter)
983
+ return error('unsupported', 'Media storage not configured');
984
+ // An id is one path segment, with any `/` in it encoded. More segments would otherwise
985
+ // act on the first one alone — `DELETE /media/photos/a.png` deleting `photos`.
986
+ if (tail.length > 1)
987
+ return error('not_found', `No route: ${method} /cms/v1/media/${tail.join('/')}`);
988
+ const [id] = tail;
989
+ // GET /media
990
+ if (id === undefined && method === 'GET') {
991
+ const rawLimit = url.searchParams.get('limit');
992
+ const parsedLimit = rawLimit !== null ? Number.parseInt(rawLimit, 10) : Number.NaN;
993
+ const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? Math.min(parsedLimit, MAX_LIMIT) : DEFAULT_LIMIT;
994
+ const folder = url.searchParams.get('folder') ?? undefined;
995
+ const cursor = url.searchParams.get('cursor') ?? undefined;
996
+ const includeProjectImages = parseIncludeProjectImages(url.searchParams.get('includeProjectImages'));
997
+ if (includeProjectImages === null) {
998
+ return error('validation', 'includeProjectImages accepts no value, "true", "1", "false" or "0"');
999
+ }
1000
+ const type = parseMediaTypeFilter(url.searchParams.get('type'));
1001
+ if (type === null) {
1002
+ return error('validation', 'type accepts "all", "photo", "graphic", "video" or "document"');
1003
+ }
1004
+ // The project scan has no folder structure, so it only makes sense at the
1005
+ // media root — inside a folder the adapter stays the only source.
1006
+ if (!includeProjectImages || folder !== undefined) {
1007
+ if (type === 'all') {
1008
+ // Our own cursor means nothing to the adapter, which would parse it as an
1009
+ // offset of NaN and answer with an empty, hasMore:false page — the library
1010
+ // would look empty. Say what actually went wrong instead.
1011
+ if (cursor !== undefined && decodeMediaCursor(cursor).ok)
1012
+ return error('validation', MERGED_CURSOR_OUTSIDE_MERGE);
1013
+ return json(await adapter.list({ limit, cursor, folder }));
1014
+ }
1015
+ // A filtered page ends wherever the source happened to be once the page was full, so
1016
+ // the position it hands back belongs to this tab. Wrap the adapter's cursor in ours
1017
+ // to say so, and refuse one minted under another tab rather than answering from the
1018
+ // wrong place in the listing.
1019
+ const decoded = decodeMediaCursor(cursor);
1020
+ if (!decoded.ok)
1021
+ return error('validation', 'Invalid media cursor');
1022
+ if (cursor !== undefined && cursorType(decoded.state) !== type)
1023
+ return error('validation', MEDIA_CURSOR_TYPE_MISMATCH);
1024
+ // The cursors minted here carry only `adapter` and `type`. One with a project offset or
1025
+ // the carried root folders comes from the merged listing, and its `adapter` (if any)
1026
+ // is a position in the root's stream: following it here would restart the listing or
1027
+ // answer from another folder's offset.
1028
+ const { adapter: adapterCursor, project, folders: carried } = decoded.state;
1029
+ if (cursor !== undefined && (project !== undefined || carried !== undefined || adapterCursor === undefined)) {
1030
+ return error('validation', MERGED_CURSOR_OUTSIDE_MERGE);
1031
+ }
1032
+ const page = await listFilteredMedia(options => adapter.list(options), { limit, cursor: adapterCursor, folder, type });
1033
+ return json({
1034
+ ...page,
1035
+ cursor: page.cursor === undefined ? undefined : encodeMediaCursor({ adapter: page.cursor, type }),
1036
+ });
1037
+ }
1038
+ return listMergedMedia(adapter, limit, cursor, type);
1039
+ }
1040
+ // POST /media (multipart upload, or JSON create-folder)
1041
+ if (id === undefined && method === 'POST') {
1042
+ const contentType = req.headers.get('content-type') ?? '';
1043
+ if (contentType.includes('application/json')) {
1044
+ const parsed = await parseJson(req);
1045
+ if (!parsed.ok)
1046
+ return parsed.response;
1047
+ if (!adapter.createFolder)
1048
+ return error('unsupported', 'Folder creation not supported by this adapter');
1049
+ // The body is whatever JSON the caller sent, `null` included.
1050
+ const body = parsed.value;
1051
+ const folder = body?.folder;
1052
+ if (typeof folder !== 'string')
1053
+ return error('validation', 'A valid "folder" is required');
1054
+ // Held to the same rule as the bundled adapters for whatever adapter is configured.
1055
+ if (isUnsafeFolder(folder))
1056
+ return error('validation', MEDIA_INVALID_FOLDER);
1057
+ const result = await adapter.createFolder(folder);
1058
+ return result.success ? json(result) : mediaFailure(result.error ?? 'Failed to create folder');
1059
+ }
1060
+ if (!contentType.includes('multipart/form-data')) {
1061
+ return error('validation', 'Expected multipart/form-data or application/json');
1062
+ }
1063
+ const form = await req.formData().catch(() => null);
1064
+ if (form === null)
1065
+ return error('validation', 'Malformed multipart/form-data body');
1066
+ const file = form.get('file');
1067
+ if (!(file instanceof File))
1068
+ return error('validation', 'No "file" found in the form data');
1069
+ if (file.size > maxUploadSize) {
1070
+ return error('validation', `File too large (max ${Math.round(maxUploadSize / (1024 * 1024))} MB)`);
1071
+ }
1072
+ const buffer = Buffer.from(await file.arrayBuffer());
1073
+ const folder = url.searchParams.get('folder') ?? undefined;
1074
+ const result = await adapter.upload(buffer, file.name, file.type || 'application/octet-stream', { folder });
1075
+ return result.success ? json(result) : mediaFailure(result.error ?? 'Upload failed');
1076
+ }
1077
+ // DELETE /media/:id
1078
+ if (id !== undefined && method === 'DELETE') {
1079
+ const result = await adapter.delete(id);
1080
+ return result.success ? json({ success: true }) : mediaFailure(result.error ?? 'Delete failed');
1081
+ }
1082
+ // PATCH /media/:id { annotation }
1083
+ if (id !== undefined && method === 'PATCH') {
1084
+ if (!adapter.updateAnnotation)
1085
+ return error('unsupported', 'Annotations are not supported by this adapter');
1086
+ const parsed = await parseJson(req);
1087
+ if (!parsed.ok)
1088
+ return parsed.response;
1089
+ // The body is whatever JSON the caller sent, `null` included.
1090
+ const body = parsed.value;
1091
+ const annotation = body?.annotation;
1092
+ if (typeof annotation !== 'string')
1093
+ return error('validation', 'A string "annotation" is required');
1094
+ const result = await adapter.updateAnnotation(id, annotation);
1095
+ return result.success ? json({ success: true }) : mediaFailure(result.error ?? 'Failed to update the annotation');
1096
+ }
1097
+ return error('not_found', `No route: ${method} /cms/v1/media${id ? `/${id}` : ''}`);
1098
+ }
1099
+ return { fetch: fetchHandler };
1100
+ }