@eldrajs/theme-cli 0.2.7 → 0.2.8

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 (50) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/package.json +3 -3
  3. package/template/.eldra/manifest.json +160 -132
  4. package/template/.eldra/previews.json +35 -35
  5. package/template/blocks/announcement-bar/preview.png +0 -0
  6. package/template/blocks/article/preview.png +0 -0
  7. package/template/blocks/article-list/preview.png +0 -0
  8. package/template/blocks/breadcrumbs/preview.png +0 -0
  9. package/template/blocks/cart/preview.png +0 -0
  10. package/template/blocks/collection-grid/preview.png +0 -0
  11. package/template/blocks/collection-header/preview.png +0 -0
  12. package/template/blocks/contact/preview.png +0 -0
  13. package/template/blocks/cta/preview.png +0 -0
  14. package/template/blocks/faq/preview.png +0 -0
  15. package/template/blocks/feature-grid/preview.png +0 -0
  16. package/template/blocks/footer/preview.png +0 -0
  17. package/template/blocks/form/preview.png +0 -0
  18. package/template/blocks/gallery/preview.png +0 -0
  19. package/template/blocks/hero/preview.png +0 -0
  20. package/template/blocks/image/preview.png +0 -0
  21. package/template/blocks/logo-cloud/preview.png +0 -0
  22. package/template/blocks/navigation/Block.vue +54 -11
  23. package/template/blocks/navigation/__tests__/Block.spec.ts +91 -8
  24. package/template/blocks/navigation/block.json +11 -3
  25. package/template/blocks/navigation/mock.json +134 -129
  26. package/template/blocks/navigation/preview.png +0 -0
  27. package/template/blocks/newsletter/preview.png +0 -0
  28. package/template/blocks/order-status/preview.png +0 -0
  29. package/template/blocks/pricing-table/preview.png +0 -0
  30. package/template/blocks/product-carousel/preview.png +0 -0
  31. package/template/blocks/product-detail/preview.png +0 -0
  32. package/template/blocks/quote/preview.png +0 -0
  33. package/template/blocks/rich-text/preview.png +0 -0
  34. package/template/blocks/search/preview.png +0 -0
  35. package/template/blocks/split-content/preview.png +0 -0
  36. package/template/blocks/stats/preview.png +0 -0
  37. package/template/blocks/tabs/preview.png +0 -0
  38. package/template/blocks/team/preview.png +0 -0
  39. package/template/blocks/testimonials/preview.png +0 -0
  40. package/template/blocks/timeline/preview.png +0 -0
  41. package/template/blocks/trust-strip/preview.png +0 -0
  42. package/template/blocks/video-embed/preview.png +0 -0
  43. package/template/blocks/wishlist/preview.png +0 -0
  44. package/template/package.json +1 -1
  45. package/template/public/images/bowl.webp +0 -0
  46. package/template/test/prerenderFailure.spec.ts +4 -3
  47. package/template/test/previewParity.browser.spec.ts +1152 -0
  48. package/template/test/starter.spec.ts +6 -1
  49. package/template/test/support/previewParity.ts +302 -0
  50. package/template/test/support/previewParityContent.ts +726 -0
@@ -0,0 +1,726 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ /**
7
+ * The content of the preview parity harness (WS-1358), and **Core's two read perspectives** over it:
8
+ * `coreRead(perspective, published, request)` answers a CMS request the way Core's public read does
9
+ * (what a build prerenders) or the way its preview read does (what a draft preview session reads
10
+ * through `X-Preview-Session`). It is the one module that knows Core's shapes, so it can be swapped
11
+ * for golden vectors recorded from Core's own read code without touching the servers or the spec.
12
+ *
13
+ * What it encodes of Core (`internal/modules/cms/service`):
14
+ * - every entry is `MergeData`'s envelope: `id`, `createdAt`, `updatedAt`, `schemaId`, `status`,
15
+ * `publishedAt`, `data`; a resolved reference (a block, a page's `parent`) also carries
16
+ * `_type: entry_<apiId>` and `schemaApiId` (`entry_preload.go`);
17
+ * - the public read expands each reusable placement in place (the component's root takes the
18
+ * placement id, every node inside it `r` + SHA-256) and, for a document that places one, puts
19
+ * `blocks` in the expanded layout's depth-first order and drops every node naming a block that
20
+ * does not resolve (`expandReusableComponentsForPublic`, `reorderResolvedLayoutBlocks`,
21
+ * `pruneUnresolvedLayoutBlocks`); a document without placements is served as stored;
22
+ * - the preview read keeps the placements, attaches a `reusableComponentProjection`, and serves
23
+ * `blocks` as the relation holds them — the stored mirror, not reordered, not pruned
24
+ * (`injectReusableComponentProjection`);
25
+ * - a top-level localized field is answered in the locale asked for, the default one otherwise;
26
+ * - the preview read's metadata is the draft's: `status` (`CHANGED`, or `DRAFT` for an entry never
27
+ * published, whose `publishedAt` is `null`) and its own `updatedAt`; the public read drops
28
+ * `status` and carries the published snapshot's `publishedAt` and `updatedAt`. `createdAt`,
29
+ * `id`, `schemaId`, `_type` and `schemaApiId` are the same in both;
30
+ * - a media item's `linkId` is its owner's link row, so it differs between the two reads.
31
+ */
32
+
33
+ const blocksDir = fileURLToPath(new URL('../../blocks', import.meta.url));
34
+
35
+ /** Every block type the starter ships, in name order. */
36
+ export const STARTER_BLOCK_TYPES: string[] = readdirSync(blocksDir, { withFileTypes: true })
37
+ .filter((entry) => entry.isDirectory() && existsSync(join(blocksDir, entry.name, 'block.json')))
38
+ .map((entry) => entry.name)
39
+ .sort();
40
+
41
+ /** A block's content as Studio's stories render it: what an insert seeds, plus the demo media. */
42
+ export function sampleData(apiId: string): Record<string, unknown> {
43
+ const read = (file: string): Record<string, unknown> => {
44
+ const path = join(blocksDir, apiId, file);
45
+ return existsSync(path)
46
+ ? (JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>)
47
+ : {};
48
+ };
49
+ return { ...read('mock.json'), ...read('preview.json') };
50
+ }
51
+
52
+ /** A v4-shaped uuid, stable per name: a layout node's `entryId` must be one. */
53
+ export function uuidFor(name: string): string {
54
+ const hex = createHash('sha256').update(name).digest('hex');
55
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
56
+ }
57
+
58
+ function expandedNodeId(placementId: string, nodeId: string): string {
59
+ return `r${createHash('sha256').update(`${placementId}\0${nodeId}`).digest('hex')}`;
60
+ }
61
+
62
+ /**
63
+ * Which version of the content: `next` is what the merchant is about to publish (the draft, and
64
+ * what a Publish rebuild bakes in); `pinned` is what was live when the deployment a session pins
65
+ * was built.
66
+ */
67
+ export type ContentVersion = 'next' | 'pinned';
68
+ export type Perspective = 'public' | 'draft';
69
+
70
+ export const SITE_ID = 'a1b2c3d4-0000-4000-8000-00000000c0de';
71
+ const LOCALES = ['en-US', 'is-IS'] as const;
72
+ const SCHEMA_IDS: Record<string, string> = {};
73
+ const schemaIdOf = (apiId: string): string => (SCHEMA_IDS[apiId] ??= uuidFor(`schema:${apiId}`));
74
+
75
+ /** When each version was written: the pinned build's content, the draft, and the Publish. */
76
+ const CREATED_AT = '2026-10-01T09:00:00Z';
77
+ const PINNED_AT = '2026-11-01T10:00:00Z';
78
+ const DRAFTED_AT = '2026-11-20T10:00:00Z';
79
+ const PUBLISHED_AT = '2026-11-21T10:00:00Z';
80
+
81
+ /**
82
+ * The envelope Core puts around an entry. The pinned build read the then-published snapshot; the
83
+ * session reads the draft, which was saved after it; the live build reads the snapshot Publish made
84
+ * of that draft.
85
+ */
86
+ function envelope(
87
+ perspective: Perspective,
88
+ version: ContentVersion,
89
+ everPublished: boolean
90
+ ): Record<string, unknown> {
91
+ if (perspective === 'draft') {
92
+ return {
93
+ createdAt: CREATED_AT,
94
+ updatedAt: DRAFTED_AT,
95
+ status: everPublished ? 'CHANGED' : 'DRAFT',
96
+ publishedAt: everPublished ? PINNED_AT : null,
97
+ };
98
+ }
99
+ // The public read drops `status` altogether.
100
+ const at = version === 'pinned' ? PINNED_AT : PUBLISHED_AT;
101
+ return { createdAt: CREATED_AT, updatedAt: at, publishedAt: at };
102
+ }
103
+
104
+ /**
105
+ * Every media item carries the `linkId` of asset-service's link row, one per owner — the draft and
106
+ * each published snapshot are different owners — so the same image has a different `linkId` in
107
+ * each read.
108
+ */
109
+ function withLinkIds(value: unknown, owner: string): unknown {
110
+ if (Array.isArray(value)) return value.map((item) => withLinkIds(item, owner));
111
+ if (typeof value !== 'object' || value === null) return value;
112
+ const record = value as Record<string, unknown>;
113
+ const walked = Object.fromEntries(
114
+ Object.entries(record).map(([key, child]) => [key, withLinkIds(child, owner)])
115
+ );
116
+ return typeof record.assetId === 'string' && typeof record.url === 'string'
117
+ ? { ...walked, linkId: `${owner}-${record.assetId}` }
118
+ : walked;
119
+ }
120
+
121
+ interface Block {
122
+ id: string;
123
+ schemaApiId: string;
124
+ data: Record<string, unknown>;
125
+ }
126
+
127
+ type LayoutNode = Record<string, unknown> & { id: string; type: string };
128
+
129
+ interface Component {
130
+ componentId: string;
131
+ revision: number;
132
+ root: LayoutNode & { children: LayoutNode[] };
133
+ blocks: Block[];
134
+ }
135
+
136
+ type Child =
137
+ | { block: Block; style?: Record<string, unknown> }
138
+ | { placement: string; component: Component }
139
+ /** A node naming a block entry that does not resolve (deleted, or unpublished since). */
140
+ | { dangling: string };
141
+
142
+ interface PageSource {
143
+ id: string;
144
+ slug: string;
145
+ title: string;
146
+ parent?: string;
147
+ /** Never published before this draft: the pinned build has no such page. */
148
+ draftOnly?: boolean;
149
+ children: Child[];
150
+ }
151
+
152
+ function block(name: string, apiId: string, data: Record<string, unknown>): Block {
153
+ return { id: uuidFor(`${name}:${apiId}`), schemaApiId: apiId, data };
154
+ }
155
+
156
+ function sharedComponents(next: boolean): { header: Component; footer: Component } {
157
+ const header: Component = {
158
+ componentId: 'c0ffee00-0000-4000-8000-0000000000a1',
159
+ revision: next ? 4 : 3,
160
+ root: {
161
+ id: 'header-root',
162
+ type: 'flex',
163
+ layout: { direction: { normal: 'column' } },
164
+ children: [{ id: 'header-nav', type: 'block', entryId: '' }],
165
+ },
166
+ blocks: [block('shared-header', 'navigation', sampleData('navigation'))],
167
+ };
168
+ const footer: Component = {
169
+ componentId: 'c0ffee00-0000-4000-8000-0000000000b2',
170
+ revision: 2,
171
+ root: {
172
+ id: 'footer-root',
173
+ type: 'flex',
174
+ layout: { direction: { normal: 'column' }, gap: { normal: '8px' } },
175
+ children: [{ id: 'footer-main', type: 'block', entryId: '' }],
176
+ },
177
+ blocks: [block('shared-footer', 'footer', sampleData('footer'))],
178
+ };
179
+ for (const component of [header, footer]) {
180
+ component.root.children[0]!.entryId = component.blocks[0]!.id;
181
+ }
182
+ return { header, footer };
183
+ }
184
+
185
+ /** A small page for one kind of edit: the same blocks in both versions unless the edit says so. */
186
+ function editPage(slug: string, title: string, blocks: Block[]): PageSource {
187
+ return { id: `page-${slug}`, slug, title, children: blocks.map((one) => ({ block: one })) };
188
+ }
189
+
190
+ const withItems = (apiId: 'faq' | 'tabs', extra: boolean): Record<string, unknown> => {
191
+ const data = sampleData(apiId);
192
+ const key = apiId === 'faq' ? 'items' : 'tabs';
193
+ const items = data[key] as Array<Record<string, unknown>>;
194
+ const added =
195
+ apiId === 'faq'
196
+ ? { ...items[0], question: 'Do you ship to Iceland?', open: false }
197
+ : { ...items[0], label: 'Linen', heading: 'Linen softens with every wash' };
198
+ return { ...data, [key]: extra ? [...items, added] : items };
199
+ };
200
+
201
+ function pageSources(version: ContentVersion): PageSource[] {
202
+ const next = version === 'next';
203
+ const { header, footer } = sharedComponents(next);
204
+ const hero = (name: string): Block =>
205
+ block(name, 'hero', {
206
+ ...sampleData('hero'),
207
+ heading: next ? `Made slowly, used daily (${name})` : `Pinned heading (${name})`,
208
+ });
209
+
210
+ // Every block type of the starter, `search` first, where its results-page variant stands on a
211
+ // real site: it focuses its field on mount, and the page scrolls to it.
212
+ const everyBlockData = (apiId: string): Record<string, unknown> => {
213
+ const data = sampleData(apiId);
214
+ if (apiId === 'hero') data.heading = next ? 'Made slowly, used daily' : 'Pinned build heading';
215
+ if (apiId === 'cta' && !next) data.heading = 'Pinned call to action';
216
+ if (apiId === 'faq' && !next) data.heading = 'Pinned questions';
217
+ return data;
218
+ };
219
+ const everyBlock: PageSource = {
220
+ id: 'page-every-block',
221
+ slug: 'home',
222
+ title: next ? 'Every block' : 'Every block (pinned)',
223
+ children: ['search', ...STARTER_BLOCK_TYPES.filter((apiId) => apiId !== 'search')].map(
224
+ (apiId) => ({ block: block('every', apiId, everyBlockData(apiId)) })
225
+ ),
226
+ };
227
+ // The same blocks in name order, so the search field stands mid-page.
228
+ const focusMid: PageSource = {
229
+ id: 'page-focus-mid',
230
+ slug: 'focus-mid',
231
+ title: 'Focus mid-page',
232
+ children: STARTER_BLOCK_TYPES.map((apiId) => ({
233
+ block: block('focus-mid', apiId, everyBlockData(apiId)),
234
+ })),
235
+ };
236
+
237
+ const shared: PageSource = {
238
+ id: 'page-shared',
239
+ slug: 'shared',
240
+ title: 'Shared component',
241
+ children: [
242
+ { placement: 'site-header', component: header },
243
+ {
244
+ block: block('shared-body', 'hero', {
245
+ ...sampleData('hero'),
246
+ heading: next ? 'Between the shared header and footer' : 'Pinned shared body',
247
+ }),
248
+ },
249
+ { placement: 'site-footer', component: footer },
250
+ ],
251
+ };
252
+ // A page under the shared page: its `parent` is that page, resolved as a nested entry.
253
+ const child: PageSource = {
254
+ id: 'page-shared-child',
255
+ slug: 'child',
256
+ title: 'Child',
257
+ parent: 'page-shared',
258
+ children: [{ block: hero('child') }],
259
+ };
260
+ // A page placing a component, one of whose block nodes names an entry that no longer resolves.
261
+ const dangling: PageSource = {
262
+ id: 'page-dangling',
263
+ slug: 'dangling',
264
+ title: 'Dangling',
265
+ children: [
266
+ { placement: 'site-header', component: header },
267
+ { block: hero('dangling') },
268
+ { dangling: uuidFor('deleted:quote') },
269
+ { block: block('dangling', 'cta', sampleData('cta')) },
270
+ ],
271
+ };
272
+
273
+ const localized: PageSource = {
274
+ id: 'page-localized',
275
+ slug: 'localized',
276
+ title: 'Localized',
277
+ children: [
278
+ {
279
+ block: block('localized', 'hero', {
280
+ ...sampleData('hero'),
281
+ eyebrow: { 'en-US': 'New season', 'is-IS': 'Ný árstíð' },
282
+ heading: next
283
+ ? { 'en-US': 'Made slowly', 'is-IS': 'Gert hægt' }
284
+ : { 'en-US': 'Pinned', 'is-IS': 'Fest' },
285
+ }),
286
+ },
287
+ {
288
+ block: block('localized', 'cta', {
289
+ ...sampleData('cta'),
290
+ eyebrow: { 'en-US': 'Visit the studio', 'is-IS': 'Heimsæktu verkstæðið' },
291
+ primaryCtaLabel: { 'en-US': 'Book a session', 'is-IS': 'Bóka tíma' },
292
+ }),
293
+ },
294
+ ],
295
+ };
296
+
297
+ /**
298
+ * The framed image is a photo, not the block's demo SVG. A blurred-gradient SVG is drawn with a
299
+ * dither that Chromium rasters differently depending on the image's paint history — a session
300
+ * draws it at zoom 1 from the pinned prerender, then at `scale(2)` from the draft; the live page
301
+ * draws it once — which no capture can normalise: on CI it differed in 5925 pixels of dither
302
+ * while the DOM, the layers and the paint were the same. A photo has no such dither. The framing
303
+ * values are the point of the page and stay as they are.
304
+ *
305
+ * `public/images/bowl.webp` is "Bowl of Eggs" by Cory Seward (Unsplash, via Wikimedia Commons),
306
+ * CC0; 1120×1400.
307
+ */
308
+ const image = {
309
+ ...(sampleData('image').image as Record<string, unknown>),
310
+ assetId: 'demo-bowl',
311
+ url: '/images/bowl.webp',
312
+ altText: 'White eggs, one cracked open, in a wooden bowl on a bamboo mat',
313
+ width: 1120,
314
+ height: 1400,
315
+ };
316
+ const heroImage = sampleData('hero').image as Record<string, unknown>;
317
+ const framing: PageSource = {
318
+ id: 'page-framing',
319
+ slug: 'framing',
320
+ title: 'Framing',
321
+ children: [
322
+ {
323
+ block: block('framing', 'image', {
324
+ ...sampleData('image'),
325
+ image: {
326
+ ...image,
327
+ framing: next ? { x: 0.2, y: 0.6, zoom: 2 } : { x: 0.5, y: 0.5, zoom: 1 },
328
+ },
329
+ }),
330
+ },
331
+ {
332
+ block: block('framing', 'hero', {
333
+ ...sampleData('hero'),
334
+ image: { ...heroImage, framing: next ? { x: 0.05, y: 0.95, zoom: 3.5 } : null },
335
+ }),
336
+ style: { width: { normal: '100%', mobile: '100%' } },
337
+ },
338
+ ],
339
+ };
340
+
341
+ // One page per kind of structural edit (`EDIT_CASES`).
342
+ const b = (page: string, apiId: string, data = sampleData(apiId)): Block =>
343
+ block(page, apiId, data);
344
+ const edits: PageSource[] = [
345
+ editPage('edit-add', 'Add', [
346
+ hero('edit-add'),
347
+ ...(next ? [b('edit-add', 'quote')] : []),
348
+ b('edit-add', 'tabs'),
349
+ b('edit-add', 'faq'),
350
+ ]),
351
+ editPage('edit-remove', 'Remove', [
352
+ hero('edit-remove'),
353
+ ...(next ? [] : [b('edit-remove', 'quote')]),
354
+ b('edit-remove', 'tabs'),
355
+ b('edit-remove', 'faq'),
356
+ ]),
357
+ editPage(
358
+ 'edit-reorder',
359
+ 'Reorder',
360
+ next
361
+ ? [hero('edit-reorder'), b('edit-reorder', 'faq'), b('edit-reorder', 'tabs')]
362
+ : [hero('edit-reorder'), b('edit-reorder', 'tabs'), b('edit-reorder', 'faq')]
363
+ ),
364
+ editPage('edit-type', 'Change type', [
365
+ hero('edit-type'),
366
+ next ? b('edit-type', 'cta') : b('edit-type', 'quote'),
367
+ b('edit-type', 'faq'),
368
+ ]),
369
+ editPage('edit-faq-item', 'FAQ item', [
370
+ hero('edit-faq-item'),
371
+ b('edit-faq-item', 'faq', withItems('faq', next)),
372
+ b('edit-faq-item', 'tabs'),
373
+ ]),
374
+ editPage('edit-tab-item', 'Tab item', [
375
+ hero('edit-tab-item'),
376
+ b('edit-tab-item', 'tabs', withItems('tabs', next)),
377
+ b('edit-tab-item', 'faq'),
378
+ ]),
379
+ {
380
+ ...editPage('draft-only', 'Draft only', [
381
+ hero('draft-only'),
382
+ b('draft-only', 'tabs'),
383
+ b('draft-only', 'faq'),
384
+ ]),
385
+ draftOnly: true,
386
+ },
387
+ ];
388
+
389
+ return [everyBlock, focusMid, shared, child, dangling, localized, framing, ...edits].filter(
390
+ (page) => next || page.draftOnly !== true
391
+ );
392
+ }
393
+
394
+ /** The paths whose session must be the live page exactly. */
395
+ export const PARITY_PATHS = [
396
+ '/',
397
+ '/shared',
398
+ '/shared/child',
399
+ '/dangling',
400
+ '/localized',
401
+ '/is-IS/localized',
402
+ '/framing',
403
+ '/journal/first-light',
404
+ ];
405
+
406
+ /**
407
+ * The structural edits, each a page whose draft differs from the pinned build's in one way. Which
408
+ * of them renumber `useId()` ids is pinned in the spec (`EDIT_EXPECTATIONS`).
409
+ */
410
+ export const EDIT_CASES = [
411
+ 'edit-add',
412
+ 'edit-remove',
413
+ 'edit-reorder',
414
+ 'edit-type',
415
+ 'edit-faq-item',
416
+ 'edit-tab-item',
417
+ 'draft-only',
418
+ ] as const;
419
+ export type EditCase = (typeof EDIT_CASES)[number];
420
+
421
+ /** The page whose search field focuses on mount mid-page. */
422
+ export const FOCUS_MID_PATH = '/focus-mid';
423
+
424
+ /** A block entry id on a page of the harness, by page slug and block type. */
425
+ export function blockIdOf(page: string, apiId: string): string {
426
+ return uuidFor(`${page}:${apiId}`);
427
+ }
428
+
429
+ // ---- the read shapes.
430
+
431
+ /** A layout's block entry ids, depth-first, slot children by sorted slot id. */
432
+ function layoutEntryIds(node: LayoutNode, into: string[] = []): string[] {
433
+ if (typeof node.entryId === 'string' && node.entryId !== '') into.push(node.entryId);
434
+ for (const child of (node.children as LayoutNode[] | undefined) ?? [])
435
+ layoutEntryIds(child, into);
436
+ const slots = node.slots as Record<string, LayoutNode[]> | undefined;
437
+ for (const slot of Object.keys(slots ?? {}).sort()) {
438
+ for (const child of slots![slot]!) layoutEntryIds(child, into);
439
+ }
440
+ return into;
441
+ }
442
+
443
+ function pruneLayout(node: LayoutNode, missing: ReadonlySet<string>): LayoutNode {
444
+ const children = node.children as LayoutNode[] | undefined;
445
+ if (children === undefined) return node;
446
+ return {
447
+ ...node,
448
+ children: children
449
+ .filter((child) => !(typeof child.entryId === 'string' && missing.has(child.entryId)))
450
+ .map((child) => pruneLayout(child, missing)),
451
+ };
452
+ }
453
+
454
+ function expandComponent(placement: string, component: Component): LayoutNode {
455
+ const clone = (node: LayoutNode, root: boolean): LayoutNode => {
456
+ const id = root ? placement : expandedNodeId(placement, node.id);
457
+ const children = node.children as LayoutNode[] | undefined;
458
+ return children === undefined
459
+ ? { ...node, id }
460
+ : { ...node, id, children: children.map((child) => clone(child, false)) };
461
+ };
462
+ return clone(component.root, true);
463
+ }
464
+
465
+ function blockEntry(
466
+ one: Block,
467
+ perspective: Perspective,
468
+ version: ContentVersion
469
+ ): Record<string, unknown> {
470
+ return {
471
+ id: one.id,
472
+ ...envelope(perspective, version, true),
473
+ schemaId: schemaIdOf(one.schemaApiId),
474
+ data: withLinkIds(one.data, `cms_entry-${perspective === 'draft' ? 'draft' : version}`),
475
+ _type: `entry_${one.schemaApiId}`,
476
+ schemaApiId: one.schemaApiId,
477
+ };
478
+ }
479
+
480
+ /**
481
+ * The layout and blocks of one layout document, in the perspective's shape. `children` are the root
482
+ * container's; `version` the document's.
483
+ */
484
+ function layoutAndBlocks(
485
+ children: Child[],
486
+ layoutVersion: 1 | 2,
487
+ perspective: Perspective,
488
+ version: ContentVersion,
489
+ extraBlocks: Block[] = [],
490
+ extraNodes: LayoutNode[] = []
491
+ ): { layout: Record<string, unknown>; blocks: unknown[]; projection?: Record<string, unknown> } {
492
+ const stored: Block[] = [];
493
+ const nodes: LayoutNode[] = [];
494
+ const components: Array<{ placement: string; component: Component }> = [];
495
+ for (const child of children) {
496
+ if ('block' in child) {
497
+ stored.push(child.block);
498
+ nodes.push({
499
+ id: `node-${child.block.id.slice(0, 8)}`,
500
+ type: 'block',
501
+ entryId: child.block.id,
502
+ ...(child.style === undefined ? {} : { style: child.style }),
503
+ });
504
+ } else if ('dangling' in child) {
505
+ nodes.push({
506
+ id: `node-${child.dangling.slice(0, 8)}`,
507
+ type: 'block',
508
+ entryId: child.dangling,
509
+ });
510
+ } else {
511
+ components.push(child);
512
+ nodes.push(
513
+ perspective === 'public'
514
+ ? expandComponent(child.placement, child.component)
515
+ : { id: child.placement, type: 'reusable', componentId: child.component.componentId }
516
+ );
517
+ }
518
+ }
519
+ nodes.push(...extraNodes);
520
+ // The relation as stored: the document's own blocks, then the components' — not layout order.
521
+ const relation = [
522
+ ...stored,
523
+ ...extraBlocks,
524
+ ...components.flatMap(({ component }) => component.blocks),
525
+ ];
526
+ const root: LayoutNode = {
527
+ id: 'root',
528
+ type: 'flex',
529
+ layout: { direction: { normal: 'column' } },
530
+ children: nodes,
531
+ };
532
+ const entries = relation.map((one) => blockEntry(one, perspective, version));
533
+ if (components.length === 0) {
534
+ return { layout: { version: layoutVersion, root }, blocks: entries };
535
+ }
536
+ if (perspective === 'draft') {
537
+ return {
538
+ layout: { version: layoutVersion, root },
539
+ blocks: entries,
540
+ projection: {
541
+ bindings: components.map(({ placement, component }) => ({
542
+ placementId: placement,
543
+ componentId: component.componentId,
544
+ siteId: SITE_ID,
545
+ revision: component.revision,
546
+ })),
547
+ revisions: components.map(({ component }) => ({
548
+ componentId: component.componentId,
549
+ siteId: SITE_ID,
550
+ revision: component.revision,
551
+ document: { version: 1, root: component.root },
552
+ })),
553
+ },
554
+ };
555
+ }
556
+ // Public: blocks in layout order; a node naming a block that does not resolve is dropped.
557
+ const byId = new Map(entries.map((entry) => [entry.id as string, entry]));
558
+ const missing = new Set(layoutEntryIds(root).filter((id) => !byId.has(id)));
559
+ const pruned = pruneLayout(root, missing);
560
+ return {
561
+ layout: { version: layoutVersion, root: pruned },
562
+ blocks: layoutEntryIds(pruned).map((id) => byId.get(id)!),
563
+ };
564
+ }
565
+
566
+ function pageEntry(
567
+ source: PageSource,
568
+ perspective: Perspective,
569
+ version: ContentVersion,
570
+ all: readonly PageSource[]
571
+ ): Record<string, unknown> {
572
+ const { layout, blocks, projection } = layoutAndBlocks(source.children, 2, perspective, version);
573
+ const parentSource = all.find((page) => page.id === source.parent);
574
+ const entry: Record<string, unknown> = {
575
+ id: source.id,
576
+ ...envelope(perspective, version, source.draftOnly !== true),
577
+ schemaId: schemaIdOf('page'),
578
+ data: {
579
+ title: source.title,
580
+ slug: source.slug,
581
+ ...(parentSource === undefined
582
+ ? {}
583
+ : {
584
+ parent: {
585
+ ...pageEntry(parentSource, perspective, version, all),
586
+ _type: 'entry_page',
587
+ schemaApiId: 'page',
588
+ },
589
+ }),
590
+ layout,
591
+ blocks,
592
+ },
593
+ };
594
+ if (projection !== undefined) entry.reusableComponentProjection = projection;
595
+ return entry;
596
+ }
597
+
598
+ // ---- a route template: a dynamic route placing the shared header.
599
+
600
+ const JOURNAL_HERO = block('journal', 'hero', sampleData('hero'));
601
+
602
+ function journalEntries(perspective: Perspective, version: ContentVersion): unknown[] {
603
+ const next = perspective === 'draft' || version === 'next';
604
+ return [
605
+ {
606
+ id: uuidFor('journal:first-light'),
607
+ ...envelope(perspective, version, true),
608
+ schemaId: schemaIdOf('journal'),
609
+ data: { slug: 'first-light', title: next ? 'First light' : 'First light (pinned)' },
610
+ },
611
+ ];
612
+ }
613
+
614
+ function routeTemplateEntries(perspective: Perspective, version: ContentVersion): unknown[] {
615
+ const { header } = sharedComponents(perspective === 'draft' || version === 'next');
616
+ const { layout, blocks, projection } = layoutAndBlocks(
617
+ [{ placement: 'journal-header', component: header }],
618
+ 1,
619
+ perspective,
620
+ version,
621
+ [JOURNAL_HERO],
622
+ [
623
+ {
624
+ id: 'journal-hero',
625
+ type: 'template-block',
626
+ apiId: 'hero',
627
+ entryId: JOURNAL_HERO.id,
628
+ templates: { heading: 'Journal: {{ title }}' },
629
+ },
630
+ ]
631
+ );
632
+ const entry: Record<string, unknown> = {
633
+ id: 'rt-journal',
634
+ ...envelope(perspective, version, true),
635
+ schemaId: schemaIdOf('route-template'),
636
+ data: {
637
+ title: 'Journal entry',
638
+ routePattern: '/journal/:slug',
639
+ schemaApiId: 'journal',
640
+ slugField: 'slug',
641
+ layout,
642
+ blocks,
643
+ },
644
+ };
645
+ if (projection !== undefined) entry.reusableComponentProjection = projection;
646
+ return [entry];
647
+ }
648
+
649
+ // ---- localized fields.
650
+
651
+ /**
652
+ * Core answers a top-level localized field in the locale asked for. The starter's sample data has no
653
+ * object whose keys are all locale tags (the spec asserts it), so this changes only the harness's
654
+ * own translated fields, never a block's stored shape.
655
+ */
656
+ export function inLocale(value: unknown, locale: string): unknown {
657
+ if (Array.isArray(value)) return value.map((item) => inLocale(item, locale));
658
+ if (typeof value !== 'object' || value === null) return value;
659
+ const record = value as Record<string, unknown>;
660
+ const keys = Object.keys(record);
661
+ if (keys.length > 0 && keys.every((key) => (LOCALES as readonly string[]).includes(key))) {
662
+ return record[locale] ?? record['en-US'];
663
+ }
664
+ return Object.fromEntries(keys.map((key) => [key, inLocale(record[key], locale)]));
665
+ }
666
+
667
+ function listResponse(data: unknown[]): Record<string, unknown> {
668
+ return {
669
+ data,
670
+ meta: {
671
+ hasNext: false,
672
+ hasPrev: false,
673
+ page: 1,
674
+ pageSize: 100,
675
+ rows: data.length,
676
+ total: data.length,
677
+ totalPages: 1,
678
+ },
679
+ };
680
+ }
681
+
682
+ /** Whether `coreRead` answers this path (the CMS reads); everything else is the starter's mock. */
683
+ export function isCoreRead(pathname: string): boolean {
684
+ return pathname.startsWith('/cms/v1/schema/');
685
+ }
686
+
687
+ /**
688
+ * One CMS read, answered as Core would: `perspective` is the read's (a request carrying
689
+ * `X-Preview-Session` reads `draft`, which is always the `next` content), `published` which version
690
+ * the public read currently serves.
691
+ */
692
+ export function coreRead(
693
+ perspective: Perspective,
694
+ published: ContentVersion,
695
+ url: URL
696
+ ): { status: number; body: unknown } {
697
+ const version: ContentVersion = perspective === 'draft' ? 'next' : published;
698
+ const locale = url.searchParams.get('locale') ?? 'en-US';
699
+ const local = (value: unknown): unknown => inLocale(value, locale);
700
+ const path = url.pathname;
701
+ const found = (entry: unknown): { status: number; body: unknown } =>
702
+ entry === undefined ? { status: 404, body: {} } : { status: 200, body: local(entry) };
703
+
704
+ if (path.startsWith('/cms/v1/schema/page/entry')) {
705
+ const sources = pageSources(version);
706
+ const entries = sources.map((source) => pageEntry(source, perspective, version, sources));
707
+ if (path === '/cms/v1/schema/page/entry')
708
+ return { status: 200, body: local(listResponse(entries)) };
709
+ return found(entries.find((entry) => entry.id === path.split('/').pop()));
710
+ }
711
+ if (path.startsWith('/cms/v1/schema/route-template/entry')) {
712
+ const templates = routeTemplateEntries(perspective, version);
713
+ if (path === '/cms/v1/schema/route-template/entry') {
714
+ return { status: 200, body: local(listResponse(templates)) };
715
+ }
716
+ return found(templates.find((entry) => (entry as { id: string }).id === path.split('/').pop()));
717
+ }
718
+ if (path.startsWith('/cms/v1/schema/journal/entry')) {
719
+ const entries = journalEntries(perspective, version);
720
+ if (path === '/cms/v1/schema/journal/entry')
721
+ return { status: 200, body: local(listResponse(entries)) };
722
+ const slug = decodeURIComponent(path.split('/').pop() ?? '');
723
+ return found(entries.find((entry) => (entry as { data: { slug: string } }).data.slug === slug));
724
+ }
725
+ return { status: 404, body: {} };
726
+ }