@conloca/astro-cms 0.2.5 → 0.3.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 (97) hide show
  1. package/README.md +169 -22
  2. package/dist/internal/PageRoot.astro +10 -0
  3. package/dist/internal/page-handler.astro +46 -13
  4. package/dist/internal/preview-page-handler.astro +359 -0
  5. package/dist/ts/.build-inputs.json +20 -15
  6. package/dist/ts/src/build/check-fragment-components.d.ts +18 -0
  7. package/dist/ts/src/build/check-fragment-components.d.ts.map +1 -0
  8. package/dist/ts/src/build/check-fragment-components.js +70 -0
  9. package/dist/ts/src/build/check-fragment-components.js.map +1 -0
  10. package/dist/ts/src/build/fragment-manifest.d.ts +35 -0
  11. package/dist/ts/src/build/fragment-manifest.d.ts.map +1 -0
  12. package/dist/ts/src/build/fragment-manifest.js +138 -0
  13. package/dist/ts/src/build/fragment-manifest.js.map +1 -0
  14. package/dist/ts/src/build/fragment-render-load.d.ts +17 -0
  15. package/dist/ts/src/build/fragment-render-load.d.ts.map +1 -0
  16. package/dist/ts/src/build/fragment-render-load.js +51 -0
  17. package/dist/ts/src/build/fragment-render-load.js.map +1 -0
  18. package/dist/ts/src/cms-handler.d.ts +6 -0
  19. package/dist/ts/src/cms-handler.d.ts.map +1 -1
  20. package/dist/ts/src/cms-handler.js +3 -5
  21. package/dist/ts/src/cms-handler.js.map +1 -1
  22. package/dist/ts/src/components/FragmentIsland.d.ts +17 -0
  23. package/dist/ts/src/components/FragmentIsland.d.ts.map +1 -0
  24. package/dist/ts/src/components/FragmentIsland.js +78 -0
  25. package/dist/ts/src/components/FragmentIsland.js.map +1 -0
  26. package/dist/ts/src/components/IslandSlot.d.ts +14 -0
  27. package/dist/ts/src/components/IslandSlot.d.ts.map +1 -0
  28. package/dist/ts/src/components/IslandSlot.js +19 -0
  29. package/dist/ts/src/components/IslandSlot.js.map +1 -0
  30. package/dist/ts/src/components/RenderWithFragments.d.ts +3 -1
  31. package/dist/ts/src/components/RenderWithFragments.d.ts.map +1 -1
  32. package/dist/ts/src/components/RenderWithFragments.js +1 -1
  33. package/dist/ts/src/components/RenderWithFragments.js.map +1 -1
  34. package/dist/ts/src/discovery/merge-registry.js +6 -2
  35. package/dist/ts/src/discovery/merge-registry.js.map +1 -1
  36. package/dist/ts/src/editor-descriptors.d.ts +4 -0
  37. package/dist/ts/src/editor-descriptors.d.ts.map +1 -1
  38. package/dist/ts/src/editor-descriptors.js +11 -0
  39. package/dist/ts/src/editor-descriptors.js.map +1 -1
  40. package/dist/ts/src/handlers/collection-content-api.d.ts +3 -1
  41. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -1
  42. package/dist/ts/src/handlers/collection-content-api.js +13 -2
  43. package/dist/ts/src/handlers/collection-content-api.js.map +1 -1
  44. package/dist/ts/src/handlers/page-render-core.d.ts +36 -7
  45. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -1
  46. package/dist/ts/src/handlers/page-render-core.js +97 -18
  47. package/dist/ts/src/handlers/page-render-core.js.map +1 -1
  48. package/dist/ts/src/lib/hydration-scanner.d.ts +21 -0
  49. package/dist/ts/src/lib/hydration-scanner.d.ts.map +1 -1
  50. package/dist/ts/src/lib/hydration-scanner.js +50 -0
  51. package/dist/ts/src/lib/hydration-scanner.js.map +1 -1
  52. package/dist/ts/src/lib/hydration-script.d.ts +13 -5
  53. package/dist/ts/src/lib/hydration-script.d.ts.map +1 -1
  54. package/dist/ts/src/lib/hydration-script.js +74 -36
  55. package/dist/ts/src/lib/hydration-script.js.map +1 -1
  56. package/dist/ts/src/lib/routing-config.d.ts +1 -1
  57. package/dist/ts/src/lib/routing-config.d.ts.map +1 -1
  58. package/dist/ts/src/lib/routing-config.js +5 -2
  59. package/dist/ts/src/lib/routing-config.js.map +1 -1
  60. package/dist/ts/src/lib/unknown-components.d.ts +1 -2
  61. package/dist/ts/src/lib/unknown-components.d.ts.map +1 -1
  62. package/dist/ts/src/lib/virtual-module-generators.d.ts +37 -0
  63. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -1
  64. package/dist/ts/src/lib/virtual-module-generators.js +86 -0
  65. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -1
  66. package/dist/ts/src/plugin-spa.d.ts +24 -0
  67. package/dist/ts/src/plugin-spa.d.ts.map +1 -1
  68. package/dist/ts/src/plugin-spa.js +136 -69
  69. package/dist/ts/src/plugin-spa.js.map +1 -1
  70. package/dist/ts/src/puck-manifest/types.d.ts +4 -0
  71. package/dist/ts/src/puck-manifest/types.d.ts.map +1 -1
  72. package/dist/ts/src/types.d.ts +14 -2
  73. package/dist/ts/src/types.d.ts.map +1 -1
  74. package/dist/virtual-modules.d.ts +26 -0
  75. package/package.json +10 -4
  76. package/src/build/check-fragment-components.ts +82 -0
  77. package/src/build/fragment-manifest.ts +163 -0
  78. package/src/build/fragment-render-load.ts +64 -0
  79. package/src/cms-handler.ts +3 -6
  80. package/src/components/FragmentIsland.tsx +97 -0
  81. package/src/components/IslandSlot.tsx +28 -0
  82. package/src/components/PageRoot.astro +10 -0
  83. package/src/components/RenderWithFragments.tsx +4 -1
  84. package/src/discovery/merge-registry.ts +8 -3
  85. package/src/editor-descriptors.ts +17 -0
  86. package/src/handlers/collection-content-api.ts +15 -2
  87. package/src/handlers/page-handler.astro +46 -13
  88. package/src/handlers/page-render-core.ts +132 -21
  89. package/src/lib/hydration-scanner.ts +65 -0
  90. package/src/lib/hydration-script.ts +83 -40
  91. package/src/lib/routing-config.ts +7 -3
  92. package/src/lib/unknown-components.ts +1 -1
  93. package/src/lib/virtual-module-generators.ts +106 -0
  94. package/src/plugin-spa.ts +182 -76
  95. package/src/puck-manifest/types.ts +8 -0
  96. package/src/types.ts +15 -1
  97. package/src/virtual-modules.d.ts +26 -0
@@ -36,7 +36,6 @@ import type {
36
36
  } from '@conloca/content-api';
37
37
  import type { ResolvedRoutingConfig } from '../types.js';
38
38
  import { ALL_FRAGMENTS_COLLECTION } from './collection-names.js';
39
- import { rememberBuiltRecord } from './page-render-core.js';
40
39
 
41
40
  interface CollectionEntry {
42
41
  data: Record<string, unknown>;
@@ -46,6 +45,20 @@ type ContentKind = 'fragment' | 'page' | 'data';
46
45
 
47
46
  const WRITE_REJECTED = 'collection-backed ContentAPI is read-only';
48
47
 
48
+ /**
49
+ * The build's parsed record behind each entry a collection-backed ContentAPI
50
+ * hands out. A preview reader serves unchanged entries from that API, and
51
+ * the reader source uses the record the build already made instead of
52
+ * reshaping and parsing it again. Kept here, not in the render core, so the
53
+ * root entry never loads the render core and its server-only imports.
54
+ */
55
+ const builtRecords = new WeakMap<LocalizedEntry, CollectionEntry['data']>();
56
+
57
+ /** The build's parsed record behind `entry`, if a collection-backed ContentAPI handed it out. */
58
+ export function builtRecordOf(entry: LocalizedEntry) {
59
+ return builtRecords.get(entry);
60
+ }
61
+
49
62
  function str(value: unknown): string | undefined {
50
63
  return typeof value === 'string' ? value : undefined;
51
64
  }
@@ -130,7 +143,7 @@ export async function createCollectionBackedContentAPI(opts: CollectionBackedCon
130
143
  const entry: LocalizedEntry = { ...identity, localized: { ...version, content } };
131
144
  // The record is the build's parse output; a reader source hands it
132
145
  // out as is instead of parsing what was reconstructed from it.
133
- rememberBuiltRecord(entry, record);
146
+ builtRecords.set(entry, record);
134
147
  entries.set(`${id} ${locale}`, entry);
135
148
  }
136
149
  manifests.push({ ...identity, locales });
@@ -11,6 +11,11 @@
11
11
 
12
12
  import { getCollection } from 'astro:content';
13
13
  import { loadContentSchemas } from 'virtual:conloca-content-schemas';
14
+ import {
15
+ fragmentComponentsPath,
16
+ fragmentIslandLoaders,
17
+ loadFragmentComponents,
18
+ } from 'virtual:conloca-fragment-components';
14
19
  import Layout from 'virtual:conloca-layout';
15
20
  import puckConfig from 'virtual:conloca-puck-config';
16
21
  import routingConfig from 'virtual:conloca-routing-config';
@@ -30,15 +35,19 @@ import {
30
35
  createReaderContentSource,
31
36
  findUnknownComponentTypes,
32
37
  getPageEntries,
38
+ loadFragmentVocabulary,
33
39
  loadMdxComponents,
40
+ type MdxFragmentComponent,
34
41
  normalizePathname,
35
42
  type PageContentSource,
36
43
  type PageEntryData,
37
44
  type PageEntryRecord,
45
+ pageHasFragmentIslands,
38
46
  pageNotFoundResponse,
39
47
  resolvePuckData,
40
48
  } from '../ts/src/handlers/page-render-core.js';
41
49
  import { previewEntryParsers } from '../ts/src/internal/collection-parsers.js';
50
+ import PageRoot from './PageRoot.astro';
42
51
 
43
52
  // prerender is controlled by injectRoute({ prerender }) in plugin-spa.ts
44
53
  // Do not hardcode here — it overrides the route-level config
@@ -210,6 +219,9 @@ try {
210
219
  throw error;
211
220
  }
212
221
 
222
+ // A route with an editor frame marks where page content starts, which the canvas drift check stops at.
223
+ const framed = page !== undefined && config.routes[routeName]?.editorFrame !== undefined;
224
+
213
225
  const dataContext = await buildDataContext(source, config.routes[routeName], config, matchedPage);
214
226
 
215
227
  const hasPuckData = !!page?.puckData && Object.keys(page.puckData).length > 0;
@@ -230,28 +242,46 @@ if (hasPuckData && resolvedPuckData) {
230
242
  }
231
243
  }
232
244
 
233
- const needsHydration = hasPuckData && resolvedPuckData && hasHydratableComponents(resolvedPuckData, puckConfig);
234
-
235
245
  let PageRenderer: ComponentType | undefined;
246
+ let mdxComponents: MdxFragmentComponent[] = [];
236
247
 
237
248
  if (hasPuckData && page && resolvedPuckData) {
238
- try {
239
- const mdxComponents = await loadMdxComponents(
240
- source,
241
- config.locale,
242
- await loadEvaluateMDXToComponent(),
243
- import.meta.env.DEV,
244
- );
245
- PageRenderer = createPageRendererWithFragments(puckConfig, resolvedPuckData, mdxComponents, dataContext);
246
- } catch (error) {
247
- console.error('[Conloca] MDX evaluation failed, falling back to plain render:', error);
248
- PageRenderer = undefined;
249
+ const showErrors = import.meta.env.DEV || previewContentApi !== undefined;
250
+ // A broken render module fails the static build and shows in previews, but must not take down a live SSR site.
251
+ const fragmentVocabulary = await loadFragmentVocabulary(
252
+ loadFragmentComponents,
253
+ Astro.isPrerendered || showErrors,
254
+ fragmentComponentsPath,
255
+ fragmentIslandLoaders,
256
+ );
257
+ if (fragmentVocabulary) {
258
+ try {
259
+ mdxComponents = await loadMdxComponents(
260
+ source,
261
+ config.locale,
262
+ await loadEvaluateMDXToComponent(),
263
+ import.meta.env.DEV,
264
+ fragmentVocabulary,
265
+ showErrors,
266
+ );
267
+ PageRenderer = createPageRendererWithFragments(puckConfig, resolvedPuckData, mdxComponents, dataContext);
268
+ } catch (error) {
269
+ console.error('[Conloca] MDX evaluation failed, falling back to plain render:', error);
270
+ PageRenderer = undefined;
271
+ }
249
272
  }
250
273
  }
274
+
275
+ const needsHydration =
276
+ hasPuckData &&
277
+ resolvedPuckData &&
278
+ (hasHydratableComponents(resolvedPuckData, puckConfig) ||
279
+ (PageRenderer !== undefined && pageHasFragmentIslands(resolvedPuckData, mdxComponents)));
251
280
  ---
252
281
 
253
282
  {Layout && page ? (
254
283
  <Layout title={page.title ?? 'Page'} description={page.description} page={dataContext.page}>
284
+ <PageRoot framed={framed}>
255
285
  {hasPuckData && PageRenderer ? (
256
286
  <PageRenderer />
257
287
  ) : hasPuckData && resolvedPuckData ? (
@@ -265,6 +295,7 @@ if (hasPuckData && page && resolvedPuckData) {
265
295
  <p>This page has no content yet.</p>
266
296
  </div>
267
297
  )}
298
+ </PageRoot>
268
299
  </Layout>
269
300
  ) : page ? (
270
301
  <html lang={config.locale || 'en'}>
@@ -276,6 +307,7 @@ if (hasPuckData && page && resolvedPuckData) {
276
307
  {needsHydration && <script>import 'virtual:conloca-hydration-entry'</script>}
277
308
  </head>
278
309
  <body>
310
+ <PageRoot framed={framed}>
279
311
  {hasPuckData && PageRenderer ? (
280
312
  <PageRenderer />
281
313
  ) : hasPuckData && resolvedPuckData ? (
@@ -289,6 +321,7 @@ if (hasPuckData && page && resolvedPuckData) {
289
321
  <p>This page has no content yet.</p>
290
322
  </div>
291
323
  )}
324
+ </PageRoot>
292
325
  </body>
293
326
  </html>
294
327
  ) : (
@@ -17,18 +17,26 @@ import {
17
17
  type ContentManifest,
18
18
  type ContentMeta,
19
19
  isContentPublished,
20
- type LocalizedEntry,
21
20
  type MDXHeading,
22
21
  pageTimestampsOf,
23
22
  selectPagesByPrefix,
24
23
  } from '@conloca/content-api';
24
+ import {
25
+ EMPTY_FRAGMENT_VOCABULARY,
26
+ type FragmentOutlineComponent,
27
+ type FragmentVocabulary,
28
+ isFragmentVocabulary,
29
+ } from '@conloca/mdx/render';
25
30
  import type { Config } from '@puckeditor/core';
26
31
  import { type Data, resolveAllData } from '@puckeditor/core';
27
32
  import type { ComponentType } from 'react';
28
33
  import React from 'react';
34
+ import { isFragmentIsland, islandVocabulary } from '../components/FragmentIsland.js';
29
35
  import { describeEntryIssues } from '../internal/entry-issues.js';
30
36
  import type { EntryParser } from '../internal/entry-validation.js';
37
+ import { isSlotContent, type PuckItem } from '../lib/unknown-components.js';
31
38
  import type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from '../types.js';
39
+ import { builtRecordOf } from './collection-content-api.js';
32
40
  import { ALL_FRAGMENTS_COLLECTION } from './collection-names.js';
33
41
 
34
42
  // Re-exported so the copied `dist/internal/page-handler.astro` reaches
@@ -85,6 +93,9 @@ export interface MdxFragmentComponent {
85
93
  title: string;
86
94
  Component: ComponentType;
87
95
  outline: readonly MDXHeading[];
96
+ componentOutline: readonly FragmentOutlineComponent[];
97
+ /** Whether the fragment renders a `withHydration()` component, so the page needs the hydration script. */
98
+ islands: boolean;
88
99
  }
89
100
 
90
101
  type EvaluateMDXToComponentFn = typeof import('@conloca/mdx/node')['evaluateMDXToComponent'];
@@ -254,16 +265,103 @@ export async function getDataCollectionEntries(
254
265
  })) satisfies DataCollectionEntry[];
255
266
  }
256
267
 
268
+ /** A site's `fragmentComponentsPath` module, as loaded: its export is checked by {@link fragmentVocabularyOf}. */
269
+ export interface FragmentComponentsModule {
270
+ readonly fragmentComponents?: unknown;
271
+ }
272
+
273
+ /**
274
+ * The vocabulary a site's `fragmentComponentsPath` module exports; the empty
275
+ * vocabulary when it exports none.
276
+ */
277
+ export function fragmentVocabularyOf(module: FragmentComponentsModule, path: string | undefined): FragmentVocabulary {
278
+ if (!('fragmentComponents' in module)) return EMPTY_FRAGMENT_VOCABULARY;
279
+ if (!isFragmentVocabulary(module.fragmentComponents)) {
280
+ throw new TypeError(`${path} must export fragmentComponents = defineFragmentComponents(...)`);
281
+ }
282
+ return module.fragmentComponents;
283
+ }
284
+
285
+ /** A loaded vocabulary; `mappingError` is set when a hydrated value has no island, and `vocabulary` renders it static. */
286
+ interface LoadedFragmentVocabulary {
287
+ vocabulary: FragmentVocabulary;
288
+ mappingError?: unknown;
289
+ }
290
+
291
+ // Module state, not .astro frontmatter state: frontmatter re-runs on every render.
292
+ const fragmentVocabularies = new WeakMap<() => Promise<FragmentComponentsModule>, Promise<LoadedFragmentVocabulary>>();
293
+ const reportedFragmentVocabularyFailures = new WeakSet<() => Promise<FragmentComponentsModule>>();
294
+
295
+ /**
296
+ * The site's fragment vocabulary, loaded once per server instance, with each
297
+ * hydrated component the build discovered wrapped as an island. A broken
298
+ * render module throws when `failHard` (prerender, dev, draft preview); a live
299
+ * on-demand page gets `undefined`, renders without fragments, and the failure
300
+ * is logged once. A hydrated component the build could not map throws the same
301
+ * way when `failHard`; a live on-demand page renders it without hydration,
302
+ * keeps every other fragment and island, and logs that once.
303
+ *
304
+ * @param islandLoaders - Registry key → loader of each discovered hydrated component (`fragmentIslandLoaders`)
305
+ */
306
+ export async function loadFragmentVocabulary(
307
+ load: () => Promise<FragmentComponentsModule>,
308
+ failHard: boolean,
309
+ path: string | undefined,
310
+ islandLoaders: Readonly<Record<string, () => Promise<object | undefined>>>,
311
+ ): Promise<FragmentVocabulary | undefined> {
312
+ let loading = fragmentVocabularies.get(load);
313
+ if (!loading) {
314
+ loading = load().then(
315
+ async (module): Promise<LoadedFragmentVocabulary> => {
316
+ const vocabulary = fragmentVocabularyOf(module, path);
317
+ const keys = new Map(
318
+ await Promise.all(Object.entries(islandLoaders).map(async ([key, loader]) => [await loader(), key] as const)),
319
+ );
320
+ try {
321
+ return { vocabulary: islandVocabulary(vocabulary, keys) };
322
+ } catch (mappingError) {
323
+ return { vocabulary: islandVocabulary(vocabulary, keys, 'static'), mappingError };
324
+ }
325
+ },
326
+ (error: unknown) => {
327
+ throw new Error(`[Conloca] The module named by fragmentComponentsPath failed to load: ${String(error)}`);
328
+ },
329
+ );
330
+ fragmentVocabularies.set(load, loading);
331
+ }
332
+ let loaded: LoadedFragmentVocabulary;
333
+ try {
334
+ loaded = await loading;
335
+ } catch (error) {
336
+ if (failHard) throw error;
337
+ if (!reportedFragmentVocabularyFailures.has(load)) {
338
+ reportedFragmentVocabularyFailures.add(load);
339
+ console.error('[Conloca] Rendering pages without fragments:', error);
340
+ }
341
+ return undefined;
342
+ }
343
+ if (loaded.mappingError === undefined) return loaded.vocabulary;
344
+ if (failHard) throw loaded.mappingError;
345
+ if (!reportedFragmentVocabularyFailures.has(load)) {
346
+ reportedFragmentVocabularyFailures.add(load);
347
+ console.error('[Conloca] Rendering hydrated fragment components without hydration:', loaded.mappingError);
348
+ }
349
+ return loaded.vocabulary;
350
+ }
351
+
257
352
  /**
258
353
  * Evaluate every published MDX fragment for a locale into a renderable React
259
- * component. `evaluateMDXToComponent` and `isDev` are injected so the core
260
- * stays astro/vite-free.
354
+ * component, with the site's fragment `vocabulary`. `evaluateMDXToComponent`
355
+ * and `isDev` are injected so the core stays astro/vite-free; `showErrors`
356
+ * renders a failing fragment's error card (dev and draft previews).
261
357
  */
262
358
  export async function loadMdxComponents(
263
359
  source: PageContentSource,
264
360
  locale: string,
265
361
  evaluateMDXToComponent: EvaluateMDXToComponentFn,
266
362
  isDev: boolean,
363
+ vocabulary: FragmentVocabulary = EMPTY_FRAGMENT_VOCABULARY,
364
+ showErrors: boolean = isDev,
267
365
  ): Promise<MdxFragmentComponent[]> {
268
366
  const entries = (await source.listEntries(ALL_FRAGMENTS_COLLECTION)).map(
269
367
  (data) => data as Partial<FragmentEntryData>,
@@ -288,19 +386,24 @@ export async function loadMdxComponents(
288
386
  title,
289
387
  Component: () => null,
290
388
  outline: [],
389
+ componentOutline: [],
390
+ islands: false,
291
391
  };
292
392
  }
293
393
 
294
- const { Component, error, outline } = await evaluateMDXToComponent(mdx);
394
+ const { Component, error, outline, componentOutline, componentNames } = await evaluateMDXToComponent(
395
+ mdx,
396
+ vocabulary,
397
+ );
295
398
 
296
399
  if (!Component || error) {
297
400
  const errorMessage = error?.message || 'MDX evaluation failed';
298
- console.error(`[Conloca] MDX compilation error in fragment "${title}": ${errorMessage}`);
401
+ console.error(`[Conloca] Fragment ${data.id} (${locale}, "${title}") failed to render: ${errorMessage}`);
299
402
 
300
403
  return {
301
404
  id: data.id || title,
302
405
  title,
303
- Component: isDev
406
+ Component: showErrors
304
407
  ? () =>
305
408
  React.createElement(
306
409
  'div',
@@ -311,6 +414,8 @@ export async function loadMdxComponents(
311
414
  )
312
415
  : () => null,
313
416
  outline: [],
417
+ componentOutline: [],
418
+ islands: false,
314
419
  };
315
420
  }
316
421
 
@@ -319,11 +424,30 @@ export async function loadMdxComponents(
319
424
  title,
320
425
  Component,
321
426
  outline,
427
+ componentOutline,
428
+ islands: componentNames.some((name) => isFragmentIsland(vocabulary.components[name])),
322
429
  };
323
430
  }),
324
431
  );
325
432
  }
326
433
 
434
+ /**
435
+ * Whether `data` places a fragment that renders an island, as a `Fragment_<id>`
436
+ * block or a `ContentFragmentSection`, anywhere: content, zones or slot props.
437
+ */
438
+ export function pageHasFragmentIslands(data: Data, fragments: readonly MdxFragmentComponent[]): boolean {
439
+ const islandIds = new Set(fragments.filter((fragment) => fragment.islands).map((fragment) => fragment.id));
440
+ if (islandIds.size === 0) return false;
441
+ const placesIsland = (items: readonly PuckItem[]): boolean =>
442
+ items.some(
443
+ ({ type = '', props }) =>
444
+ (type.startsWith('Fragment_') && islandIds.has(type.slice('Fragment_'.length))) ||
445
+ (type === 'ContentFragmentSection' && islandIds.has(String(props?.fragmentId))) ||
446
+ Object.values(props ?? {}).some((value) => isSlotContent(value) && placesIsland(value)),
447
+ );
448
+ return placesIsland(data.content ?? []) || Object.values(data.zones ?? {}).some(placesIsland);
449
+ }
450
+
327
451
  /**
328
452
  * Assemble the data context every block of `entry` is rendered with: the page
329
453
  * itself, plus the collections and pages-by-prefix its route's data bindings
@@ -408,25 +532,12 @@ export interface ReaderContentSourceOptions {
408
532
  * where the published one gets Dates. A collection absent here has no
409
533
  * parser to run; its records pass through.
410
534
  * An entry the reader serves from the build's own parsed collections (see
411
- * {@link rememberBuiltRecord}) is not parsed again: it already is what the
535
+ * {@link builtRecordOf}) is not parsed again: it already is what the
412
536
  * build made of it.
413
537
  */
414
538
  parsers: Readonly<Record<string, EntryParser<Record<string, unknown>>>>;
415
539
  }
416
540
 
417
- /**
418
- * The build's parsed record behind each entry a collection-backed ContentAPI
419
- * hands out. A preview reader serves unchanged entries from that API, and
420
- * the reader source uses the record the build already made instead of
421
- * reshaping and parsing it again.
422
- */
423
- const builtRecords = new WeakMap<LocalizedEntry, Record<string, unknown>>();
424
-
425
- /** Mark `entry` as projected from the build's parsed collection record `record`. */
426
- export function rememberBuiltRecord(entry: LocalizedEntry, record: Record<string, unknown>): void {
427
- builtRecords.set(entry, record);
428
- }
429
-
430
541
  /**
431
542
  * Reader-backed {@link PageContentSource} over a {@link ContentAPI}, the one a
432
543
  * caller installs on `Astro.locals.contentApi`. It projects the reader's
@@ -465,7 +576,7 @@ export function createReaderContentSource(api: ContentAPI, options: ReaderConten
465
576
  const localeVersion = manifest.locales[locale];
466
577
  if (!localeVersion) return null;
467
578
  const localized = await api.getLocalized(manifest.id, locale);
468
- const built = localized ? builtRecords.get(localized) : undefined;
579
+ const built = localized ? builtRecordOf(localized) : undefined;
469
580
  if (built) return built;
470
581
  const content = localized?.localized.content;
471
582
  const record: Record<string, unknown> = {
@@ -26,6 +26,71 @@ export const HYDRATION_PATTERN = /withHydration\s*\(\s*\w+\s*,\s*['"](\w+)['"]\s
26
26
  // Valid hydration strategies
27
27
  const VALID_STRATEGIES = new Set(['load', 'visible', 'idle']);
28
28
 
29
+ /** A value the render module imports from a module that calls `withHydration`. */
30
+ export interface FragmentIslandDiscovery {
31
+ /** The binding the render module imports: the island's registry key. */
32
+ key: string;
33
+ /** The resolved module the binding comes from. */
34
+ filePath: string;
35
+ /** The imported name; `'default'` for a default import. */
36
+ exportName: string;
37
+ }
38
+
39
+ // Static import declarations with bindings: `import <clause> from '<specifier>'`, single- or multi-line.
40
+ const IMPORT_DECLARATION = /^\s*import\s+(?!type\s)([\w$\s{},]*?)\s+from\s+['"]([^'"]+)['"]/gm;
41
+
42
+ /** The value bindings of an import clause, as `[localName, exportName]`. */
43
+ function importBindings(clause: string): [string, string][] {
44
+ const braceAt = clause.indexOf('{');
45
+ const defaultName = (braceAt === -1 ? clause : clause.slice(0, braceAt)).replace(',', '').trim();
46
+ const bindings: [string, string][] = defaultName ? [[defaultName, 'default']] : [];
47
+ if (braceAt === -1) return bindings;
48
+ for (const specifier of clause.slice(braceAt + 1, clause.indexOf('}')).split(',')) {
49
+ const parts = specifier.trim().split(/\s+/);
50
+ if (parts[0] === '' || parts[0] === 'type') continue;
51
+ bindings.push([parts[2] ?? parts[0], parts[0]]);
52
+ }
53
+ return bindings;
54
+ }
55
+
56
+ /**
57
+ * Finds the hydrated fragment components the render module imports: every value binding imported from a module
58
+ * that imports `withHydration`, in import order. Type-only, namespace and side-effect-only imports never match.
59
+ *
60
+ * @param renderModulePath - Absolute path of the site's render module
61
+ * @param resolveImport - Resolves a specifier from an importer (Vite's `this.resolve` in the plugin); an externalized
62
+ * result is a package the build never bundles, so it is skipped unread
63
+ */
64
+ export async function discoverFragmentIslands(
65
+ renderModulePath: string,
66
+ resolveImport: (
67
+ specifier: string,
68
+ importer: string,
69
+ ) => Promise<{ id: string; external?: boolean | 'absolute' | 'relative' } | null | undefined>,
70
+ ): Promise<FragmentIslandDiscovery[]> {
71
+ const source = await readFile(renderModulePath, 'utf-8');
72
+ const declarations = [...source.matchAll(IMPORT_DECLARATION)].map(([, clause, specifier]) => ({
73
+ bindings: importBindings(clause),
74
+ specifier,
75
+ }));
76
+ const perDeclaration = await Promise.all(
77
+ declarations.map(async ({ bindings, specifier }): Promise<FragmentIslandDiscovery[]> => {
78
+ if (bindings.length === 0) return [];
79
+ const resolved = await resolveImport(specifier, renderModulePath);
80
+ if (!resolved || resolved.external || resolved.id.startsWith('\0')) return [];
81
+ const filePath = resolved.id;
82
+ try {
83
+ if (!HYDRATION_IMPORT_PATTERN.test(await readFile(filePath, 'utf-8'))) return [];
84
+ } catch (err) {
85
+ console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err);
86
+ return [];
87
+ }
88
+ return bindings.map(([key, exportName]) => ({ key, filePath, exportName }));
89
+ }),
90
+ );
91
+ return perDeclaration.flat();
92
+ }
93
+
29
94
  /**
30
95
  * Derives component scan paths from puckConfigPath.
31
96
  *
@@ -1,6 +1,6 @@
1
- import { createElement } from 'react';
1
+ import { type ComponentType, createElement } from 'react';
2
2
  import { hydrateRoot } from 'react-dom/client';
3
-
3
+ import { IslandSlot } from '../components/IslandSlot.js';
4
4
  import type { HydrationStrategy } from '../types.js';
5
5
 
6
6
  /**
@@ -51,49 +51,105 @@ async function hydrateElement(element: HTMLElement, entry: ComponentRegistryEntr
51
51
  }
52
52
 
53
53
  /**
54
- * Hydrate immediately on page load.
54
+ * Hydrate when the element becomes visible in the viewport. A `display:contents`
55
+ * wrapper has no box and never intersects, so its element children are observed
56
+ * instead (the wrapper itself only when it has none), as Astro's `client:visible` does.
55
57
  */
56
- function hydrateOnLoad(element: HTMLElement, entry: ComponentRegistryEntry): void {
57
- hydrateElement(element, entry);
58
- }
59
-
60
- /**
61
- * Hydrate when element becomes visible in viewport.
62
- */
63
- function hydrateOnVisible(element: HTMLElement, entry: ComponentRegistryEntry): void {
58
+ function hydrateOnVisible(element: HTMLElement, hydrate: () => void): void {
64
59
  const observer = new IntersectionObserver(
65
60
  (entries, obs) => {
66
- for (const ioEntry of entries) {
67
- if (ioEntry.isIntersecting) {
68
- obs.unobserve(ioEntry.target);
69
- hydrateElement(ioEntry.target as HTMLElement, entry);
70
- }
71
- }
61
+ if (!entries.some((ioEntry) => ioEntry.isIntersecting)) return;
62
+ obs.disconnect();
63
+ hydrate();
72
64
  },
73
65
  { rootMargin: '50px' },
74
66
  );
75
- observer.observe(element);
67
+ const targets = element.children.length > 0 ? [...element.children] : [element];
68
+ for (const target of targets) observer.observe(target);
76
69
  }
77
70
 
78
71
  /**
79
72
  * Hydrate when browser is idle.
80
73
  * Uses requestIdleCallback with setTimeout fallback for Safari.
81
74
  */
82
- function hydrateOnIdle(element: HTMLElement, entry: ComponentRegistryEntry): void {
75
+ function hydrateOnIdle(hydrate: () => void): void {
83
76
  const scheduleIdle =
84
77
  window.requestIdleCallback ??
85
78
  ((cb: IdleRequestCallback) => window.setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 50 }), 1));
86
79
 
87
- scheduleIdle(() => hydrateElement(element, entry), { timeout: 2000 });
80
+ scheduleIdle(hydrate, { timeout: 2000 });
81
+ }
82
+
83
+ /** Run `hydrate` for `element` by its strategy: now (`load` and unknown strategies), when visible, or when idle. */
84
+ function schedule(element: HTMLElement, strategy: string | undefined, hydrate: () => void): void {
85
+ if (strategy === 'visible') hydrateOnVisible(element, hydrate);
86
+ else if (strategy === 'idle') hydrateOnIdle(hydrate);
87
+ else hydrate();
88
+ }
89
+
90
+ /** One hydrated fragment component's chunk, loading. */
91
+ // biome-ignore lint/suspicious/noExplicitAny: island props are whatever JSON the server wrote
92
+ type FragmentLoad = Promise<ComponentType<any>>;
93
+ type FragmentLoader = () => FragmentLoad;
94
+
95
+ /**
96
+ * Registry key → loader of each hydrated fragment component, one chunk each.
97
+ * Generated by virtual:conloca-hydration-registry at build time.
98
+ */
99
+ export type FragmentRegistry = Readonly<Record<string, FragmentLoader>>;
100
+
101
+ /** The children HTML the server left for island `id`: its slot inside the island, else its `<template>` sibling. */
102
+ function islandChildrenHtml(island: HTMLElement, id: string): string | undefined {
103
+ for (const slot of island.querySelectorAll<HTMLElement>('conloca-island-slot')) {
104
+ if (slot.dataset.conlocaIslandSlot === id) return slot.innerHTML;
105
+ }
106
+ const next = island.nextElementSibling;
107
+ return next instanceof HTMLTemplateElement && next.dataset.conlocaIslandSlot === id ? next.innerHTML : undefined;
108
+ }
109
+
110
+ /** Hydrate one island in its own root, with the id prefix its server root used, reusing its children's HTML. */
111
+ async function hydrateIsland(island: HTMLElement, id: string, key: string, load: FragmentLoader): Promise<void> {
112
+ try {
113
+ const Component = await load();
114
+ const props = JSON.parse(island.dataset.props ?? '{}');
115
+ const html = islandChildrenHtml(island, id);
116
+ const children = html === undefined ? undefined : createElement(IslandSlot, { id, html });
117
+ hydrateRoot(island, createElement(Component, children === undefined ? props : { ...props, children }), {
118
+ identifierPrefix: id,
119
+ });
120
+ } catch (error) {
121
+ console.error(`[Conloca Hydration] Failed to hydrate ${key}:`, error);
122
+ }
123
+ }
124
+
125
+ /** Schedule every fragment island on the page; each key's loader runs at most once, when its first island hydrates. */
126
+ function initFragmentIslands(fragmentRegistry: FragmentRegistry): void {
127
+ const loads = new Map<string, FragmentLoad>();
128
+ // Own keys only: a page's `data-conloca-component` must never reach `constructor` or other prototype members.
129
+ const loaders = new Map(Object.entries(fragmentRegistry));
130
+ for (const island of document.querySelectorAll<HTMLElement>('conloca-island[data-conloca-island]')) {
131
+ const id = island.dataset.conlocaIsland ?? '';
132
+ const key = island.dataset.conlocaComponent ?? '';
133
+ const loader = loaders.get(key);
134
+ if (!loader) {
135
+ console.warn(`[Conloca Hydration] Unknown fragment component: ${key}`);
136
+ continue;
137
+ }
138
+ const loadOnce = () => {
139
+ const loading = loads.get(key) ?? loader();
140
+ loads.set(key, loading);
141
+ return loading;
142
+ };
143
+ schedule(island, island.dataset.hydrateStrategy, () => void hydrateIsland(island, id, key, loadOnce));
144
+ }
88
145
  }
89
146
 
90
147
  /**
91
- * Initialize hydration for all marked components on the page.
92
- *
93
- * Finds all elements with [data-hydrate] attribute and hydrates them
94
- * according to their strategy from the registry.
148
+ * Initialize hydration for all marked components on the page: Puck blocks
149
+ * (`[data-hydrate]`, strategy from the registry) and fragment islands
150
+ * (`conloca-island`, strategy from the markup).
95
151
  */
96
- export function initHydration(registry: ComponentRegistry): void {
152
+ export function initHydration(registry: ComponentRegistry, fragmentRegistry: FragmentRegistry = {}): void {
97
153
  const elements = document.querySelectorAll<HTMLElement>('[data-hydrate]');
98
154
 
99
155
  for (const element of elements) {
@@ -107,20 +163,7 @@ export function initHydration(registry: ComponentRegistry): void {
107
163
  }
108
164
 
109
165
  // Use strategy from registry (set at build time via withHydration)
110
- const strategy = entry.strategy;
111
-
112
- switch (strategy) {
113
- case 'load':
114
- hydrateOnLoad(element, entry);
115
- break;
116
- case 'visible':
117
- hydrateOnVisible(element, entry);
118
- break;
119
- case 'idle':
120
- hydrateOnIdle(element, entry);
121
- break;
122
- default:
123
- hydrateOnLoad(element, entry);
124
- }
166
+ schedule(element, entry.strategy, () => void hydrateElement(element, entry));
125
167
  }
168
+ initFragmentIslands(fragmentRegistry);
126
169
  }
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  DataBindingConfig,
3
3
  EditorDataBindings,
4
+ EditorRouteEntry,
4
5
  ResolvedRoutingConfig,
5
6
  RouteConfig,
6
7
  RoutingConfig,
@@ -71,7 +72,7 @@ export function normalizeRoutingConfig(
71
72
  * @param config - Partial route configuration
72
73
  * @returns Complete route configuration with all fields
73
74
  */
74
- export function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {
75
+ export function resolveRouteConfig(config: RouteConfig): ResolvedRoutingConfig['routes'][string] {
75
76
  return {
76
77
  pattern: config.pattern,
77
78
  collection: config.collection ?? 'pages',
@@ -79,6 +80,7 @@ export function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {
79
80
  prerender: config.prerender ?? true,
80
81
  meta: config.meta ?? {},
81
82
  dataBindings: config.dataBindings ?? { collections: [] },
83
+ ...(config.editorFrame === undefined ? {} : { editorFrame: config.editorFrame }),
82
84
  };
83
85
  }
84
86
 
@@ -89,10 +91,12 @@ export function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {
89
91
  */
90
92
  export function toEditorDataBindings(resolved: ResolvedRoutingConfig): EditorDataBindings {
91
93
  const routes: Record<string, DataBindingConfig> = {};
92
- for (const route of Object.values(resolved.routes)) {
94
+ const entries: EditorRouteEntry[] = [];
95
+ for (const [name, route] of Object.entries(resolved.routes)) {
93
96
  routes[route.collection] ??= route.dataBindings;
97
+ entries.push({ name, collection: route.collection, ...(route.editorFrame === undefined ? {} : { frame: name }) });
94
98
  }
95
- return { siteName: resolved.siteName, locale: resolved.locale, routes };
99
+ return { siteName: resolved.siteName, locale: resolved.locale, routes, entries };
96
100
  }
97
101
 
98
102
  /**