@conloca/astro-cms 0.2.6 → 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 +46 -13
  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
@@ -1,5 +1,5 @@
1
1
  /** One entry in a Puck content array: a component type plus its props. */
2
- interface PuckItem {
2
+ export interface PuckItem {
3
3
  type?: string;
4
4
  props?: Record<string, unknown>;
5
5
  }
@@ -1,4 +1,15 @@
1
+ import { fileURLToPath } from 'node:url';
1
2
  import type { ResolvedRoutingConfig, RoutingConfig } from '../types.js';
3
+ import type { FragmentIslandDiscovery, HydrationDiscovery } from './hydration-scanner.js';
4
+
5
+ /** One `key: () => import(module).then((m) => m[export])` loader per island, so each island module is its own chunk. */
6
+ function islandLoaders(islands: readonly FragmentIslandDiscovery[]): string {
7
+ const entries = islands.map(
8
+ ({ key, filePath, exportName }) =>
9
+ ` ${JSON.stringify(key)}: () => import(${JSON.stringify(filePath)}).then((m) => m[${JSON.stringify(exportName)}])`,
10
+ );
11
+ return entries.length === 0 ? '{}' : `{\n${entries.join(',\n')}\n}`;
12
+ }
2
13
 
3
14
  /**
4
15
  * Generate the virtual:conloca-routing-config module.
@@ -76,3 +87,98 @@ export function generateContentSchemasModule(contentSchemasPath: string | undefi
76
87
 
77
88
  return `export function loadContentSchemas() { return import(${JSON.stringify(contentSchemasPath)}); }`;
78
89
  }
90
+
91
+ /**
92
+ * Generate the virtual:conloca-fragment-components module: the site's
93
+ * `fragmentComponentsPath` module, imported on the first call, and a loader per
94
+ * hydrated fragment component it imports. Mirrors {@link generateContentSchemasModule}.
95
+ *
96
+ * @param fragmentComponentsPath - Absolute path of the module, or undefined when the site names none
97
+ * @param islands - The render module's hydrated imports, from `discoverFragmentIslands`
98
+ * @returns JavaScript module code as a string
99
+ */
100
+ export function generateFragmentComponentsModule(
101
+ fragmentComponentsPath: string | undefined,
102
+ islands: readonly FragmentIslandDiscovery[],
103
+ ): string {
104
+ // JSON.stringify(undefined) is undefined, which interpolates as the literal `undefined`.
105
+ const pathExport = `export const fragmentComponentsPath = ${JSON.stringify(fragmentComponentsPath)};`;
106
+ const loadersExport = `export const fragmentIslandLoaders = ${islandLoaders(islands)};`;
107
+ if (fragmentComponentsPath === undefined) {
108
+ return `${pathExport}\n${loadersExport}\nexport function loadFragmentComponents() { return Promise.resolve({}); }`;
109
+ }
110
+
111
+ return `${pathExport}\n${loadersExport}\nexport function loadFragmentComponents() { return import(${JSON.stringify(fragmentComponentsPath)}); }`;
112
+ }
113
+
114
+ /**
115
+ * Generate the virtual:conloca-hydration-registry module: the Puck blocks'
116
+ * `componentRegistry` and the fragment islands' `fragmentRegistry`.
117
+ *
118
+ * @param discoveries - Hydrated Puck blocks, from `scanForHydratableComponents`
119
+ * @param projectRoot - Stripped from each block path to give a Vite root-relative path
120
+ * @param islands - The render module's hydrated imports, from `discoverFragmentIslands`
121
+ * @returns JavaScript module code as a string
122
+ */
123
+ export function generateHydrationRegistryModule(
124
+ discoveries: readonly HydrationDiscovery[],
125
+ projectRoot: string,
126
+ islands: readonly FragmentIslandDiscovery[],
127
+ ): string {
128
+ const fragmentRegistry = `export const fragmentRegistry = ${islandLoaders(islands)};`;
129
+ if (discoveries.length === 0) {
130
+ return `export const componentRegistry = {};\n${fragmentRegistry}`;
131
+ }
132
+ const entries = discoveries.map((d) => {
133
+ const relativePath = d.filePath.replace(projectRoot, '');
134
+ return ` '${d.componentName}': {
135
+ loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
136
+ strategy: '${d.strategy}',
137
+ }`;
138
+ });
139
+ return `// Generated by @conloca/astro-cms scanner
140
+ export const componentRegistry = {
141
+ ${entries.join(',\n')}
142
+ };
143
+ ${fragmentRegistry}`;
144
+ }
145
+
146
+ /**
147
+ * Generate the virtual:conloca-hydration-entry module the page handler loads on pages with islands or hydrated blocks.
148
+ * In dev it imports the React refresh preamble first: plugin-react rewrites the loaded `.tsx` with Fast Refresh calls
149
+ * that throw while `$RefreshSig$` is unset.
150
+ */
151
+ export function generateHydrationEntryModule(dev: boolean): string {
152
+ return `${dev ? "import 'virtual:conloca-react-refresh-preamble'\n" : ''}import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
153
+ import { componentRegistry, fragmentRegistry } from 'virtual:conloca-hydration-registry'
154
+
155
+ // Auto-initialize hydration when this module loads
156
+ initHydration(componentRegistry, fragmentRegistry)
157
+ `;
158
+ }
159
+
160
+ /**
161
+ * Generate the virtual:conloca-site-render module the dev editor's site-render
162
+ * entry reads: the site's fragment vocabulary, its editor frames and the
163
+ * fragment renderer, for `setSiteRender` in cms-spa.
164
+ *
165
+ * @param fragmentComponentsPath - Absolute path of the render module, or undefined when the site names none
166
+ * @param editorFrames - Route name → absolute path of that route's frame module
167
+ * @returns JavaScript module code as a string
168
+ */
169
+ export function generateSiteRenderModule(
170
+ fragmentComponentsPath: string | undefined,
171
+ editorFrames: Record<string, string>,
172
+ ): string {
173
+ const frames = Object.entries(editorFrames);
174
+ // Resolved from astro-cms, so a site need not depend on @conloca/mdx itself.
175
+ const renderPath = fileURLToPath(import.meta.resolve('@conloca/mdx/render'));
176
+ return [
177
+ fragmentComponentsPath === undefined
178
+ ? 'export const fragmentComponents = undefined;'
179
+ : `import * as fragmentRender from ${JSON.stringify(fragmentComponentsPath)};\nexport const fragmentComponents = fragmentRender.fragmentComponents;`,
180
+ ...frames.map(([, path], i) => `import * as frame${i} from ${JSON.stringify(path)};`),
181
+ `export const editorFrames = { ${frames.map(([name], i) => `${JSON.stringify(name)}: frame${i}.default`).join(', ')} };`,
182
+ `export { evaluateMDXToComponent } from ${JSON.stringify(renderPath)};`,
183
+ ].join('\n');
184
+ }
package/src/plugin-spa.ts CHANGED
@@ -4,14 +4,19 @@ import { fileURLToPath } from 'node:url';
4
4
  import type { UIConfig } from '@conloca/cms-spa';
5
5
  import { readSitesConfig } from '@conloca/content-api/node';
6
6
  import viteReact from '@vitejs/plugin-react';
7
- import type { AstroIntegration } from 'astro';
7
+ import type { AstroConfig, AstroIntegration } from 'astro';
8
8
  import { type HotPayload, type InferCustomEventPayload, type NormalizedHotChannel, searchForWorkspaceRoot } from 'vite';
9
9
  import { deriveAssetRefBase } from './asset-ref-base.js';
10
10
  import type { MdxRegistryScanOptions } from './discovery/discover.js';
11
11
  import { createRegistryEndpoint } from './discovery/registry-endpoint.js';
12
12
  import { EDITOR_DESCRIPTORS_ENV_VAR, type EditorDescriptorChannel } from './editor-descriptors.js';
13
13
  import { CONTENT_CONFIG_SNIPPET, findContentConfigProblem } from './lib/content-config-guard.js';
14
- import { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';
14
+ import {
15
+ deriveComponentPaths,
16
+ discoverFragmentIslands,
17
+ type HydrationDiscovery,
18
+ scanForHydratableComponents,
19
+ } from './lib/hydration-scanner.js';
15
20
  import { resolveLocale } from './lib/resolve-locale.js';
16
21
  import { resolveSiteName } from './lib/resolve-site-name.js';
17
22
  import { normalizeRoutingConfig, resolveRouteConfig, toEditorDataBindings } from './lib/routing-config.js';
@@ -58,9 +63,13 @@ const TIPTAP_HTML_SHIM_PATH = join(__dirname, 'tiptap-html-static.js');
58
63
 
59
64
  import {
60
65
  generateContentSchemasModule,
66
+ generateFragmentComponentsModule,
67
+ generateHydrationEntryModule,
68
+ generateHydrationRegistryModule,
61
69
  generateLayoutModule,
62
70
  generatePuckConfigModule,
63
71
  generateRoutingConfigModule,
72
+ generateSiteRenderModule,
64
73
  } from './lib/virtual-module-generators.js';
65
74
  import type { EditorDataBindings, ResolvedRoutingConfig, RoutingConfigInput, TemplateConfig } from './types.js';
66
75
 
@@ -73,12 +82,14 @@ const VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';
73
82
  const VIRTUAL_LAYOUT = 'virtual:conloca-layout';
74
83
  const VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';
75
84
  const VIRTUAL_CONTENT_SCHEMAS = 'virtual:conloca-content-schemas';
85
+ const VIRTUAL_FRAGMENT_COMPONENTS = 'virtual:conloca-fragment-components';
76
86
 
77
87
  // Resolved IDs (with \0 prefix to prevent file resolution)
78
88
  const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
79
89
  const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
80
90
  const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
81
91
  const RESOLVED_CONTENT_SCHEMAS = `\0${VIRTUAL_CONTENT_SCHEMAS}`;
92
+ const RESOLVED_FRAGMENT_COMPONENTS = `\0${VIRTUAL_FRAGMENT_COMPONENTS}`;
82
93
 
83
94
  // Virtual modules for hydration system
84
95
  const VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';
@@ -86,16 +97,44 @@ const VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';
86
97
  const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
87
98
  const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
88
99
 
89
- /** Vite payloads whose browser-side effects would overwrite the editor's own save update. */
90
- function dropsEditorSaveUpdate(payload: HotPayload): boolean {
91
- if (payload.type === 'full-reload') return true;
92
- return payload.type === 'custom' && payload.event === 'conloca:content-update';
100
+ /**
101
+ * Lets through every reload but the ones the editor's own writes cause: a content change is marked own or foreign
102
+ * when its watcher event fires, and the next `full-reload` consumes the marks. Dropped only when every change since
103
+ * the last reload was own, so a CLI write, a git checkout or another tab always reloads.
104
+ * Known limit: Astro may skip the reload of an own write; that mark then drops the next `full-reload`, unless a
105
+ * foreign change came first.
106
+ */
107
+ export interface EditorReloadGate {
108
+ noteContentChange(own: boolean): void;
109
+ shouldDrop(payload: HotPayload): boolean;
110
+ }
111
+
112
+ export function createEditorReloadGate(): EditorReloadGate {
113
+ let ownPending = false;
114
+ let foreignPending = false;
115
+ return {
116
+ noteContentChange(own) {
117
+ if (own) ownPending = true;
118
+ else foreignPending = true;
119
+ },
120
+ shouldDrop(payload) {
121
+ if (payload.type !== 'full-reload') return false;
122
+ const drop = ownPending && !foreignPending;
123
+ ownPending = false;
124
+ foreignPending = false;
125
+ return drop;
126
+ },
127
+ };
93
128
  }
94
129
 
95
130
  // Virtual module for CMS SPA source loading (dev only)
96
131
  const VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';
97
132
  const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
98
133
 
134
+ // The site's fragment vocabulary, editor frames and renderer (dev only)
135
+ const VIRTUAL_SITE_RENDER = 'virtual:conloca-site-render';
136
+ const RESOLVED_SITE_RENDER = `\0${VIRTUAL_SITE_RENDER}`;
137
+
99
138
  async function loadContentApiNode() {
100
139
  return import('@conloca/content-api/node');
101
140
  }
@@ -125,6 +164,18 @@ export interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {
125
164
  */
126
165
  contentSchemasPath?: string;
127
166
 
167
+ /**
168
+ * Path to a module exporting `fragmentComponents = defineFragmentComponents(...)`
169
+ * from `@conloca/mdx/render`: the components and element overrides content
170
+ * fragments may use on published pages and draft previews. It must load in a
171
+ * server runtime and import no editor code. In dev, a render module that is
172
+ * also in the client module graph may keep a cached load failure until the
173
+ * dev server restarts.
174
+ *
175
+ * @example './src/fragment-components.tsx'
176
+ */
177
+ fragmentComponentsPath?: string;
178
+
128
179
  /**
129
180
  * Default layout for content pages.
130
181
  * When provided without routing config, enables routing with catch-all pattern.
@@ -468,6 +519,31 @@ export default {};
468
519
  `;
469
520
  };
470
521
 
522
+ // Template for the site render loader virtual module: hands the site's
523
+ // fragment renderer, vocabulary and editor frames to cms-spa's site-render
524
+ // registry. The preamble comes first because frames and fragment components
525
+ // are React modules.
526
+ const siteRenderLoader = (cmsSpaDistDir?: string) => {
527
+ const siteRenderImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/site-render.js` : '@conloca/cms-spa/site-render';
528
+ return `
529
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
530
+ import { setSiteRender } from '${siteRenderImport}';
531
+ import * as site from '${VIRTUAL_SITE_RENDER}';
532
+
533
+ setSiteRender({ evaluate: site.evaluateMDXToComponent, vocabulary: site.fragmentComponents, frames: site.editorFrames });
534
+
535
+ if (import.meta.hot) {
536
+ import.meta.hot.accept('${VIRTUAL_SITE_RENDER}', (next) => {
537
+ if (next) {
538
+ setSiteRender({ evaluate: next.evaluateMDXToComponent, vocabulary: next.fragmentComponents, frames: next.editorFrames });
539
+ }
540
+ });
541
+ }
542
+
543
+ export default {};
544
+ `;
545
+ };
546
+
471
547
  /**
472
548
  * Whether a resolved package directory came from the registry rather than from
473
549
  * a workspace. @conloca/cms-spa ships its sources so source maps resolve, so
@@ -523,8 +599,10 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
523
599
  // that run after this one may still switch it. The duplicate-route-name check
524
600
  // below keys on it.
525
601
  let outputMode: 'static' | 'server' | undefined;
602
+ // The site's Vite config, kept for the build:done fragment check.
603
+ let siteConfig: Pick<AstroConfig, 'vite'> | undefined;
526
604
  if (routingConfig?.enabled !== false && routingConfig) {
527
- const resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>> = {};
605
+ const resolvedRoutes: ResolvedRoutingConfig['routes'] = {};
528
606
  for (const [name, config] of Object.entries(routingConfig.routes || {})) {
529
607
  resolvedRoutes[name] = resolveRouteConfig(config);
530
608
  }
@@ -618,6 +696,8 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
618
696
  });
619
697
 
620
698
  let refreshConlocaContent: (() => Promise<void>) | undefined;
699
+ // The content watcher's API, which the reload gate asks whether a changed file is the editor's own write.
700
+ let watchedContentApi: { isOwnWriteFile(filePath: string): boolean } | undefined;
621
701
 
622
702
  return {
623
703
  name: '@conloca/astro-cms',
@@ -671,7 +751,10 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
671
751
  // The editor builds each page's data context in the browser from
672
752
  // these, the same bindings the published page resolves with.
673
753
  spaConfig.dataBindings = resolvedRoutingConfig?.enabled
674
- ? toEditorDataBindings(resolvedRoutingConfig)
754
+ ? {
755
+ ...toEditorDataBindings(resolvedRoutingConfig),
756
+ ...(options.fragmentPreviewRoute ? { fragmentPreviewRoute: options.fragmentPreviewRoute } : {}),
757
+ }
675
758
  : undefined;
676
759
  // The editor's prompt for making existing Astro pages editable runs the
677
760
  // newest CLI against this site; the routes come from the dev server.
@@ -712,8 +795,17 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
712
795
  ? resolve(options.assetsPath)
713
796
  : join(fileURLToPath(config.publicDir), 'assets');
714
797
  const assetRefBase = deriveAssetRefBase(mediaFolder, config.publicDir, config.base);
798
+ // Route name → absolute frame module, for each route that declares an editor frame.
799
+ const frameEntries = Object.entries(resolvedRoutingConfig?.routes ?? {}).flatMap(([name, route]) =>
800
+ route.editorFrame === undefined ? [] : [[name, resolve(route.editorFrame)] as const],
801
+ );
802
+ const editorFrames = frameEntries.length > 0 ? Object.fromEntries(frameEntries) : undefined;
715
803
  const editorDescriptors: EditorDescriptorChannel = {
716
804
  ...(options.schemasPath ? { schemasPath: resolve(options.schemasPath) } : {}),
805
+ ...(options.fragmentComponentsPath
806
+ ? { fragmentComponentsPath: resolve(options.fragmentComponentsPath) }
807
+ : {}),
808
+ ...(editorFrames === undefined ? {} : { editorFrames }),
717
809
  puckConfigPath: resolve(options.puckConfigPath),
718
810
  ...(siteStyles === undefined ? {} : { siteStyles }),
719
811
  ...(editorStyles === undefined ? {} : { editorStyles }),
@@ -884,6 +976,9 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
884
976
  if (id === VIRTUAL_CONTENT_SCHEMAS) {
885
977
  return RESOLVED_CONTENT_SCHEMAS;
886
978
  }
979
+ if (id === VIRTUAL_FRAGMENT_COMPONENTS) {
980
+ return RESOLVED_FRAGMENT_COMPONENTS;
981
+ }
887
982
  // Hydration virtual modules
888
983
  if (id === VIRTUAL_HYDRATION_REGISTRY) {
889
984
  return RESOLVED_HYDRATION_REGISTRY;
@@ -894,6 +989,13 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
894
989
  return null;
895
990
  },
896
991
  async load(id) {
992
+ // The render module's hydrated imports; watched so a new import regenerates the loaders.
993
+ const fragmentIslands = async () => {
994
+ if (!options.fragmentComponentsPath) return [];
995
+ const renderModulePath = resolve(options.fragmentComponentsPath);
996
+ this.addWatchFile(renderModulePath);
997
+ return discoverFragmentIslands(renderModulePath, (s, i) => this.resolve(s, i));
998
+ };
897
999
  // Routing virtual modules
898
1000
  if (id === RESOLVED_ROUTING_CONFIG) {
899
1001
  if (resolvedRoutingConfig) {
@@ -913,36 +1015,23 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
913
1015
  options.contentSchemasPath ? resolve(options.contentSchemasPath) : undefined,
914
1016
  );
915
1017
  }
1018
+ if (id === RESOLVED_FRAGMENT_COMPONENTS) {
1019
+ return generateFragmentComponentsModule(
1020
+ options.fragmentComponentsPath ? resolve(options.fragmentComponentsPath) : undefined,
1021
+ await fragmentIslands(),
1022
+ );
1023
+ }
916
1024
  // Hydration virtual modules
917
1025
  if (id === RESOLVED_HYDRATION_REGISTRY) {
918
1026
  // Always scan - paths are auto-derived from puckConfigPath
919
- const discoveries = await hydrationDiscoveriesPromise;
920
- if (discoveries.length > 0) {
921
- const entries = discoveries.map((d) => {
922
- // Convert absolute path to Vite-friendly path
923
- const relativePath = d.filePath.replace(process.cwd(), '');
924
- return ` '${d.componentName}': {
925
- loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
926
- strategy: '${d.strategy}',
927
- }`;
928
- });
929
- return `// Generated by @conloca/astro-cms scanner
930
- export const componentRegistry = {
931
- ${entries.join(',\n')}
932
- };`;
933
- }
934
-
935
- // No hydratable components found - return empty registry
936
- return 'export const componentRegistry = {};';
1027
+ return generateHydrationRegistryModule(
1028
+ await hydrationDiscoveriesPromise,
1029
+ process.cwd(),
1030
+ await fragmentIslands(),
1031
+ );
937
1032
  }
938
1033
  if (id === RESOLVED_HYDRATION_ENTRY) {
939
- // Generate entry point that imports registry and calls initHydration
940
- return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
941
- import { componentRegistry } from 'virtual:conloca-hydration-registry'
942
-
943
- // Auto-initialize hydration when this module loads
944
- initHydration(componentRegistry)
945
- `;
1034
+ return generateHydrationEntryModule(command === 'dev');
946
1035
  }
947
1036
  return null;
948
1037
  },
@@ -1033,10 +1122,8 @@ initHydration(componentRegistry)
1033
1122
  'nanoid',
1034
1123
  'sort-keys',
1035
1124
  // MDX processing
1036
- '@mdx-js/mdx',
1037
1125
  'remark-frontmatter',
1038
1126
  'remark-gfm',
1039
- 'remark-mdx-frontmatter',
1040
1127
  ],
1041
1128
  },
1042
1129
  plugins: [
@@ -1085,6 +1172,12 @@ initHydration(componentRegistry)
1085
1172
  if (id === `${cmsRoute}/editor-styles.js`) {
1086
1173
  return id;
1087
1174
  }
1175
+ if (id === `${cmsRoute}/site-render-entry.js`) {
1176
+ return id;
1177
+ }
1178
+ if (id === VIRTUAL_SITE_RENDER) {
1179
+ return RESOLVED_SITE_RENDER;
1180
+ }
1088
1181
  if (id === VIRTUAL_CMS_SPA_ENTRY) {
1089
1182
  return RESOLVED_CMS_SPA_ENTRY;
1090
1183
  }
@@ -1134,6 +1227,15 @@ initHydration(componentRegistry)
1134
1227
  }
1135
1228
  return 'export default {};';
1136
1229
  }
1230
+ if (id === `${cmsRoute}/site-render-entry.js`) {
1231
+ return siteRenderLoader(cmsSpaDistDir);
1232
+ }
1233
+ if (id === RESOLVED_SITE_RENDER) {
1234
+ return generateSiteRenderModule(
1235
+ options.fragmentComponentsPath ? resolve(options.fragmentComponentsPath) : undefined,
1236
+ Object.fromEntries(frameEntries),
1237
+ );
1238
+ }
1137
1239
  if (id === RESOLVED_CMS_SPA_ENTRY) {
1138
1240
  // Detect whether cms-spa is a workspace checkout (import its
1139
1241
  // source for HMR) or a registry install (import its built
@@ -1292,6 +1394,7 @@ if (import.meta.hot) {
1292
1394
  defaultLocale: options.locales.defaultLocale,
1293
1395
  }),
1294
1396
  });
1397
+ watchedContentApi = contentApi;
1295
1398
 
1296
1399
  // Only add explicit watchers if content is outside the Astro project
1297
1400
  const { resolve } = await import('node:path');
@@ -1381,41 +1484,28 @@ if (import.meta.hot) {
1381
1484
  },
1382
1485
  },
1383
1486
  {
1384
- name: 'conloca-suppress-cms-save-reload',
1487
+ name: 'conloca-editor-reload-gate',
1385
1488
  apply: 'serve' as const,
1386
- configureServer(server) {
1387
- let suppressUntil = 0;
1388
- const WINDOW_MS = 2000;
1389
- const cmsContentPrefix = `${cmsRoute}/api/content`;
1390
-
1391
- server.middlewares.use((req, _res, next) => {
1392
- const isWrite =
1393
- req.method === 'POST' ||
1394
- req.method === 'PUT' ||
1395
- req.method === 'PATCH' ||
1396
- req.method === 'DELETE';
1397
- if (isWrite && req.url?.startsWith(cmsContentPrefix)) {
1398
- suppressUntil = Date.now() + WINDOW_MS;
1489
+ async configureServer(server) {
1490
+ const { isWatchedContentFile } = await loadContentApiNode();
1491
+ const gate = createEditorReloadGate();
1492
+
1493
+ // Marks each content change as the editor's own write or a foreign one when its watcher event
1494
+ // fires; Astro's reload for it comes later, after its loader re-syncs the data store.
1495
+ const noteChange = (file: string) => {
1496
+ if (watchedContentApi && isWatchedContentFile(file, { contentRoot: options.contentRoot })) {
1497
+ gate.noteContentChange(watchedContentApi.isOwnWriteFile(file));
1399
1498
  }
1400
- next();
1401
- });
1402
-
1403
- // During a CMS save window, drop two server→client signals that
1404
- // would otherwise stomp on the CMS's own optimistic cache updates:
1405
- //
1406
- // 1. Vite `full-reload` — emitted by Astro 6.2.1's invalidateDataStore()
1407
- // in dist/content/vite-plugin-content-virtual-mod.js. The call site
1408
- // is in a configureServer watcher callback, outside the
1409
- // handleHotUpdate pipeline, so wrapping hot.send is the only intercept.
1410
- //
1411
- // 2. `conloca:content-update` custom event — emitted by
1412
- // conloca-content-watcher above. The client listener (template at
1413
- // `contentChangeListener` in this file) reacts by calling
1414
- // queryClient.invalidateQueries() with NO args, refetching every
1415
- // query and visibly blinking lists. CMS mutation hooks already do
1416
- // optimistic setQueryData, so this event is redundant for
1417
- // CMS-originated writes. External edits (outside the save window)
1418
- // still pass through normally.
1499
+ };
1500
+ server.watcher.on('change', noteChange);
1501
+ server.watcher.on('add', noteChange);
1502
+ server.watcher.on('unlink', noteChange);
1503
+
1504
+ // Astro's `full-reload` (sent by invalidateDataStore in
1505
+ // dist/content/vite-plugin-content-virtual-mod.js, outside the
1506
+ // handleHotUpdate pipeline) would reload the CMS over the editor's
1507
+ // own save; wrapping hot.send is the only intercept. The content
1508
+ // watcher already skips its own `conloca:content-update`.
1419
1509
  const patchedChannels = new WeakSet();
1420
1510
  const patchSend = (target: NormalizedHotChannel | undefined) => {
1421
1511
  if (!target || patchedChannels.has(target)) return;
@@ -1431,11 +1521,10 @@ if (import.meta.hot) {
1431
1521
  origSend(payloadOrEvent, payload);
1432
1522
  return;
1433
1523
  }
1434
- if (dropsEditorSaveUpdate(payloadOrEvent) && Date.now() < suppressUntil) {
1435
- server.config.logger.info(
1436
- `[conloca] suppressed ${payloadOrEvent.type} during CMS save window`,
1437
- { timestamp: true },
1438
- );
1524
+ if (gate.shouldDrop(payloadOrEvent)) {
1525
+ server.config.logger.info(`[conloca] suppressed the reload of the editor's own save`, {
1526
+ timestamp: true,
1527
+ });
1439
1528
  return;
1440
1529
  }
1441
1530
  origSend(payloadOrEvent);
@@ -1445,9 +1534,8 @@ if (import.meta.hot) {
1445
1534
  patchedChannels.add(target);
1446
1535
  };
1447
1536
 
1448
- // Astro's content plugin sends `full-reload` via environments.client.hot.
1449
- // Conloca's content watcher sends custom events via server.ws (legacy API).
1450
- // Patch both; idempotent per-target via __conlocaPatched.
1537
+ // Astro's content plugin sends `full-reload` via environments.client.hot;
1538
+ // server.ws is the legacy API. Patch both; idempotent per target.
1451
1539
  patchSend(server.environments?.client?.hot);
1452
1540
  patchSend(server.ws);
1453
1541
  },
@@ -1474,6 +1562,24 @@ if (import.meta.hot) {
1474
1562
 
1475
1563
  'astro:config:done': ({ config }) => {
1476
1564
  outputMode = config.output;
1565
+ siteConfig = config;
1566
+ },
1567
+
1568
+ 'astro:build:done': async ({ logger }) => {
1569
+ if (!siteConfig) return;
1570
+ // Loaded here: the checker pulls in the page renderer (Puck, React), which a config load must not pay for.
1571
+ const { checkFragmentComponents } = await import('./build/check-fragment-components.js');
1572
+ const problems = await checkFragmentComponents({
1573
+ contentRoot: options.contentRoot,
1574
+ // projectRoot, not config.root: the plugin resolves contentRoot and fragmentComponentsPath against it.
1575
+ root: projectRoot,
1576
+ vite: siteConfig.vite,
1577
+ fragmentComponentsPath: options.fragmentComponentsPath,
1578
+ logger,
1579
+ });
1580
+ if (problems.length > 0) {
1581
+ throw new Error(`Fragments the site would fail to render:\n${problems.map((p) => ` ${p}`).join('\n')}`);
1582
+ }
1477
1583
  },
1478
1584
 
1479
1585
  'astro:server:setup': ({ logger, refreshContent }) => {
@@ -1,5 +1,11 @@
1
1
  import type { JsonValue } from '@conloca/content-api';
2
+ import type { FragmentManifest } from '@conloca/content-api/component-vocabulary';
2
3
 
4
+ export type {
5
+ FragmentManifest,
6
+ FragmentManifestComponent,
7
+ FragmentManifestProp,
8
+ } from '@conloca/content-api/component-vocabulary';
3
9
  export type { JsonValue };
4
10
 
5
11
  /**
@@ -57,6 +63,8 @@ export interface PuckManifest {
57
63
  * contract.
58
64
  */
59
65
  unreadableReason?: string;
66
+ /** The site's fragment vocabulary; absent from a manifest written before it was listed. */
67
+ fragments?: FragmentManifest;
60
68
  }
61
69
 
62
70
  export interface ManifestComponent {
package/src/types.ts CHANGED
@@ -254,6 +254,19 @@ export interface RouteConfig {
254
254
  */
255
255
  collection?: string;
256
256
 
257
+ /**
258
+ * Module whose default export renders `({ pathname, children })` with the markup the route's layout puts around
259
+ * page content. It may be the route's `.tsx` layout, if that layout has this signature.
260
+ *
261
+ * Applies to the editor canvas only. Declaring it wraps the route's published page content in
262
+ * `<div data-conloca-page-root="">`, so direct-child selectors from the layout may need adjusting.
263
+ *
264
+ * Resolved against the working directory, like `fragmentComponentsPath`; run Astro from the project root.
265
+ *
266
+ * @example './src/cms/blog-frame.tsx'
267
+ */
268
+ editorFrame?: string;
269
+
257
270
  /**
258
271
  * Path to the Astro layout component.
259
272
  *
@@ -521,7 +534,7 @@ export type LayoutComponent = (props: LayoutProps) => unknown;
521
534
  */
522
535
  export interface ResolvedRoutingConfig {
523
536
  enabled: boolean;
524
- routes: Record<string, Required<RouteConfig>>;
537
+ routes: Record<string, Required<Omit<RouteConfig, 'editorFrame'>> & Pick<RouteConfig, 'editorFrame'>>;
525
538
  fallback: '404' | 'passthrough';
526
539
  onConflict: 'warn' | 'error' | 'silent';
527
540
  /** Site name for content resolution. */
@@ -536,6 +549,7 @@ export type {
536
549
  DataCollectionEntry,
537
550
  DataContext,
538
551
  EditorDataBindings,
552
+ EditorRouteEntry,
539
553
  PageReference,
540
554
  } from '@conloca/content-api';
541
555
 
@@ -71,6 +71,32 @@ declare module 'virtual:conloca-content-schemas' {
71
71
  export function loadContentSchemas(): Promise<{ pageSchemas?: PageSchemas; dataSchemas?: DataSchemas }>;
72
72
  }
73
73
 
74
+ /**
75
+ * Virtual module: virtual:conloca-fragment-components
76
+ *
77
+ * The site's `fragmentComponentsPath` module, imported on the first call only;
78
+ * an empty object when the site names none.
79
+ */
80
+ declare module 'virtual:conloca-fragment-components' {
81
+ export function loadFragmentComponents(): Promise<{ fragmentComponents?: unknown }>;
82
+ /** The resolved absolute path of that module, or `undefined` when the site names none. */
83
+ export const fragmentComponentsPath: string | undefined;
84
+ /** Registry key → loader of each hydrated fragment component the render module imports. */
85
+ export const fragmentIslandLoaders: Readonly<Record<string, () => Promise<object | undefined>>>;
86
+ }
87
+
88
+ /**
89
+ * Virtual module: virtual:conloca-site-render (dev only)
90
+ *
91
+ * The site's fragment vocabulary, its editor frames (route name → frame) and
92
+ * the fragment renderer, handed to cms-spa's `setSiteRender`.
93
+ */
94
+ declare module 'virtual:conloca-site-render' {
95
+ export const fragmentComponents: unknown;
96
+ export const editorFrames: unknown;
97
+ export { evaluateMDXToComponent } from '@conloca/mdx/render';
98
+ }
99
+
74
100
  /**
75
101
  * Virtual module: virtual:conloca-hydration-entry
76
102
  *