@conloca/astro-cms 0.1.0 → 0.1.2

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
- import { FileSystemContentAPI, createContentAPI, createContentAPIRouter, validateCFAccessRequest } from "@conloca/content-api/node";
3
- import { dirname, join } from "node:path";
4
2
  import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { FileSystemContentAPI, createContentAPI, createContentAPIRouter, validateCFAccessRequest } from "@conloca/content-api/node";
5
5
  import spaConfig from "virtual:conloca-config";
6
6
  import { contentOptions, getDataCollection, getPagesByPrefix } from "virtual:conloca-page-api";
7
7
  import routingConfig from "virtual:conloca-routing-config";
@@ -1,4 +1,4 @@
1
- import { t as conlocaLoader } from "./loader-C6JF2toW.mjs";
1
+ import { t as conlocaLoader } from "./loader-BYmsavWc.mjs";
2
2
  import { blockMetaSchema, dataMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
3
3
  import { createContentAPI } from "@conloca/content-api/node";
4
4
  import { defineCollection } from "astro:content";
@@ -1,4 +1,5 @@
1
1
  import { Config, Data } from "@measured/puck";
2
+ import * as react_jsx_runtime0 from "react/jsx-runtime";
2
3
  import { ComponentType } from "react";
3
4
 
4
5
  //#region src/components/RenderWithBlocks.d.ts
@@ -42,5 +43,24 @@ interface MDXComponent {
42
43
  */
43
44
  declare function createPageRendererWithBlocks(config: Config, data: Data, mdxComponents: MDXComponent[]): ComponentType;
44
45
  //#endregion
45
- export { createPageRendererWithBlocks };
46
+ //#region src/components/RenderWithHydration.d.ts
47
+ interface RenderWithHydrationProps {
48
+ config: Config;
49
+ data: Data;
50
+ }
51
+ /**
52
+ * Wrapper around Puck's Render component that adds hydration support.
53
+ *
54
+ * For each component with a hydration strategy configured, wraps the
55
+ * component's render output with HydrationWrapper to add data-hydrate
56
+ * attributes for browser-side hydration.
57
+ *
58
+ * Non-hydratable components render without any wrapper overhead.
59
+ */
60
+ declare function RenderWithHydration({
61
+ config,
62
+ data
63
+ }: RenderWithHydrationProps): react_jsx_runtime0.JSX.Element;
64
+ //#endregion
65
+ export { RenderWithHydration, createPageRendererWithBlocks };
46
66
  //# sourceMappingURL=components.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"components.d.mts","names":[],"sources":["../src/components/RenderWithBlocks.tsx"],"sourcesContent":[],"mappings":";;;;UAMU,YAAA;;EAAA,KAAA,EAAA,MAAA;EA8HM,SAAA,EA3HH,aA2HG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAA,4BAAA,SAAqC,cAAc,qBAAqB,iBAAiB"}
1
+ {"version":3,"file":"components.d.mts","names":[],"sources":["../src/components/RenderWithBlocks.tsx","../src/components/RenderWithHydration.tsx"],"sourcesContent":[],"mappings":";;;;;UAMU,YAAA;;;EAAA,SAAA,EAGG,aAHS;AA8HtB;;;;;;;;;ACnIkD;AAkBlD;;;;;;;;;;;;;;;;;;;;;;;;iBDiHgB,4BAAA,SAAqC,cAAc,qBAAqB,iBAAiB;;;UC/H/F,wBAAA;UACA;QACF;;ADLmC;AAkI3C;;;;;;;;iBCjHgB,mBAAA;;;GAAsC,2BAAwB,kBAAA,CAAA,GAAA,CAAA"}
@@ -1,4 +1,4 @@
1
- import { i as isHydratable, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-BryTdVgJ.mjs";
1
+ import { i as isHydratable, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-CQDv661k.mjs";
2
2
  import { Render } from "@measured/puck";
3
3
  import { Fragment, jsx } from "react/jsx-runtime";
4
4
 
@@ -163,5 +163,5 @@ function createPageRendererWithBlocks(config, data, mdxComponents) {
163
163
  }
164
164
 
165
165
  //#endregion
166
- export { createPageRendererWithBlocks };
166
+ export { RenderWithHydration, createPageRendererWithBlocks };
167
167
  //# sourceMappingURL=components.mjs.map
@@ -15,11 +15,11 @@ import type { ComponentType } from 'react';
15
15
  // MDX evaluation imports
16
16
  import { createContentAPI } from '@conloca/content-api/node';
17
17
  import { evaluateMDXBlocks } from '@conloca/mdx/node';
18
- import { createPageRendererWithBlocks } from '../components/RenderWithBlocks.js';
18
+ import { createPageRendererWithBlocks, RenderWithHydration } from '@conloca/astro-cms/components';
19
19
 
20
20
  // Hydration support
21
- import { hasHydratableComponents } from '../lib/hydration-utils.js';
22
- import { RenderWithHydration } from '../components/RenderWithHydration.js';
21
+ import { hasHydratableComponents, extractSlugFromPathname } from '@conloca/astro-cms';
22
+ import type { DataCollectionEntry, DataContext, PageData, PageReference, ResolvedRoutingConfig } from '@conloca/astro-cms';
23
23
 
24
24
  // Virtual modules configured by the Vite plugin
25
25
  import routingConfig from 'virtual:conloca-routing-config';
@@ -27,11 +27,7 @@ import Layout from 'virtual:conloca-layout';
27
27
  import { getAllPages, getPage, getDataCollection, getPagesByPrefix, contentOptions } from 'virtual:conloca-page-api';
28
28
  import puckConfig from 'virtual:conloca-puck-config';
29
29
 
30
- // Route utilities for slug extraction
31
- import { extractSlugFromPathname } from '../lib/route-utils.js';
32
-
33
30
  import type { GetStaticPaths } from 'astro';
34
- import type { DataCollectionEntry, DataContext, PageData, PageReference, ResolvedRoutingConfig } from '../types.js';
35
31
 
36
32
  // Default to prerender: true for static site generation
37
33
  export const prerender = true;
@@ -1,3 +1,3 @@
1
- import { t as withHydration } from "./withHydration-DAkXCF9z.mjs";
1
+ import { t as withHydration } from "./withHydration-DfAwNHmI.mjs";
2
2
 
3
3
  export { withHydration };
package/dist/index.d.mts CHANGED
@@ -6,53 +6,38 @@ import { AstroIntegration } from "astro";
6
6
  import { Loader } from "astro/loaders";
7
7
  import { UIConfig } from "@conloca/cms-spa";
8
8
 
9
- //#region src/loader.d.ts
10
- interface ConlocaLoaderOptions {
11
- collection: string;
12
- contentRoot: string;
13
- site?: string;
14
- /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */
15
- kind?: 'page' | 'block' | 'data';
16
- }
9
+ //#region src/lib/hydration-scanner.d.ts
17
10
  /**
18
- * Custom Astro content loader for Conloca CMS.
19
- * Loads content from the Conloca content directory into Astro collections.
11
+ * Result of scanning a component file for withHydration usage.
20
12
  */
21
- declare function conlocaLoader(options: ConlocaLoaderOptions): Loader;
22
- //#endregion
23
- //#region src/plugin-spa.d.ts
24
- interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {
25
- contentRoot: string;
26
- canvasDir?: string;
27
- route?: string;
28
- puckConfigPath: string;
29
- schemasPath?: string;
30
- /**
31
- * Default layout for content pages.
32
- * When provided without routing config, enables routing with catch-all pattern.
33
- * For multi-route setups, use routing.routes.{name}.layout instead.
34
- *
35
- * @example './src/layouts/Layout.astro'
36
- */
37
- layout?: string;
38
- routing?: RoutingConfigInput;
39
- templates?: Record<string, TemplateConfig>;
40
- /**
41
- * Paths to scan for hydratable components.
42
- * Components using withHydration() in these directories are auto-discovered.
43
- *
44
- * @example ['src/components/puck']
45
- */
46
- componentPaths?: string[];
47
- /**
48
- * Path to the assets directory for image uploads.
49
- * When provided, enables the Media Library and asset upload API routes.
50
- *
51
- * @example 'src/assets/uploads'
52
- */
53
- assetsPath?: string;
13
+ interface HydrationDiscovery {
14
+ /** Component name derived from filename (PascalCase) */
15
+ componentName: string;
16
+ /** Absolute path to the component file */
17
+ filePath: string;
18
+ /** Hydration strategy extracted from withHydration call */
19
+ strategy: 'load' | 'visible' | 'idle';
54
20
  }
55
- declare function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration;
21
+ /**
22
+ * Scans component directories for files using withHydration wrapper.
23
+ *
24
+ * This function performs static analysis to discover components marked
25
+ * for hydration, without executing any component code.
26
+ *
27
+ * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])
28
+ * @param projectRoot - Absolute path to the project root
29
+ * @returns Array of discovered hydratable components with their strategies
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const discoveries = await scanForHydratableComponents(
34
+ * ['src/components/puck'],
35
+ * '/path/to/project'
36
+ * )
37
+ * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]
38
+ * ```
39
+ */
40
+ declare function scanForHydratableComponents(componentPaths: string[], projectRoot: string): Promise<HydrationDiscovery[]>;
56
41
  //#endregion
57
42
  //#region src/lib/hydration-utils.d.ts
58
43
  /**
@@ -104,6 +89,41 @@ declare function findHydratableComponents(data: Data, config: Config): Hydratabl
104
89
  */
105
90
  declare function hasHydratableComponents(data: Data, config: Config): boolean;
106
91
  //#endregion
92
+ //#region src/lib/route-utils.d.ts
93
+ /**
94
+ * Extract slug from pathname given a route pattern.
95
+ *
96
+ * The slug is the portion of the pathname that comes after the
97
+ * static prefix of the pattern.
98
+ *
99
+ * @param pathname - URL pathname (e.g., '/about', '/blog/post-1')
100
+ * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')
101
+ * @returns The extracted slug, or undefined for root paths
102
+ *
103
+ * @example
104
+ * extractSlugFromPathname('/about', '/[...slug]') // 'about'
105
+ * extractSlugFromPathname('/blog/post-1', '/blog/[...slug]') // 'post-1'
106
+ * extractSlugFromPathname('/', '/[...slug]') // undefined
107
+ * extractSlugFromPathname('/blog', '/blog/[...slug]') // undefined
108
+ */
109
+ declare function extractSlugFromPathname(pathname: string, pattern: string): string | undefined;
110
+ /**
111
+ * Convert a slug back to a pathname given a route pattern.
112
+ *
113
+ * The inverse of extractSlugFromPathname.
114
+ *
115
+ * @param slug - The page slug (e.g., 'about', 'post-1'), or undefined for root
116
+ * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')
117
+ * @returns Full URL pathname
118
+ *
119
+ * @example
120
+ * pathnameFromSlug('about', '/[...slug]') // '/about'
121
+ * pathnameFromSlug('post-1', '/blog/[...slug]') // '/blog/post-1'
122
+ * pathnameFromSlug(undefined, '/[...slug]') // '/'
123
+ * pathnameFromSlug(undefined, '/blog/[...slug]') // '/blog'
124
+ */
125
+ declare function pathnameFromSlug(slug: string | undefined, pattern: string): string;
126
+ //#endregion
107
127
  //#region src/lib/serialize-props.d.ts
108
128
  /**
109
129
  * Safely serialize props for embedding in HTML data attributes.
@@ -111,38 +131,53 @@ declare function hasHydratableComponents(data: Data, config: Config): boolean;
111
131
  */
112
132
  declare function serializeProps(props: Record<string, unknown>): string;
113
133
  //#endregion
114
- //#region src/lib/hydration-scanner.d.ts
115
- /**
116
- * Result of scanning a component file for withHydration usage.
117
- */
118
- interface HydrationDiscovery {
119
- /** Component name derived from filename (PascalCase) */
120
- componentName: string;
121
- /** Absolute path to the component file */
122
- filePath: string;
123
- /** Hydration strategy extracted from withHydration call */
124
- strategy: 'load' | 'visible' | 'idle';
134
+ //#region src/loader.d.ts
135
+ interface ConlocaLoaderOptions {
136
+ collection: string;
137
+ contentRoot: string;
138
+ site?: string;
139
+ /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */
140
+ kind?: 'page' | 'block' | 'data';
125
141
  }
126
142
  /**
127
- * Scans component directories for files using withHydration wrapper.
128
- *
129
- * This function performs static analysis to discover components marked
130
- * for hydration, without executing any component code.
131
- *
132
- * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])
133
- * @param projectRoot - Absolute path to the project root
134
- * @returns Array of discovered hydratable components with their strategies
135
- *
136
- * @example
137
- * ```typescript
138
- * const discoveries = await scanForHydratableComponents(
139
- * ['src/components/puck'],
140
- * '/path/to/project'
141
- * )
142
- * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]
143
- * ```
143
+ * Custom Astro content loader for Conloca CMS.
144
+ * Loads content from the Conloca content directory into Astro collections.
144
145
  */
145
- declare function scanForHydratableComponents(componentPaths: string[], projectRoot: string): Promise<HydrationDiscovery[]>;
146
+ declare function conlocaLoader(options: ConlocaLoaderOptions): Loader;
147
+ //#endregion
148
+ //#region src/plugin-spa.d.ts
149
+ interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {
150
+ contentRoot: string;
151
+ canvasDir?: string;
152
+ route?: string;
153
+ puckConfigPath: string;
154
+ schemasPath?: string;
155
+ /**
156
+ * Default layout for content pages.
157
+ * When provided without routing config, enables routing with catch-all pattern.
158
+ * For multi-route setups, use routing.routes.{name}.layout instead.
159
+ *
160
+ * @example './src/layouts/Layout.astro'
161
+ */
162
+ layout?: string;
163
+ routing?: RoutingConfigInput;
164
+ templates?: Record<string, TemplateConfig>;
165
+ /**
166
+ * Paths to scan for hydratable components.
167
+ * Components using withHydration() in these directories are auto-discovered.
168
+ *
169
+ * @example ['src/components/puck']
170
+ */
171
+ componentPaths?: string[];
172
+ /**
173
+ * Path to the assets directory for image uploads.
174
+ * When provided, enables the Media Library and asset upload API routes.
175
+ *
176
+ * @example 'src/assets/uploads'
177
+ */
178
+ assetsPath?: string;
179
+ }
180
+ declare function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration;
146
181
  //#endregion
147
- export { type BlockMeta, type ComponentRegistry, type ConlocaCMSOptions, type ConlocaLoaderOptions, type HydratableComponent, type HydratableComponentConfig, type HydrationDiscovery, type HydrationMeta, type HydrationStrategy, type PageMeta, type TemplateConfig, type WithHydrationStrategy, blockMetaSchema, conlocaCMS, conlocaLoader, findHydratableComponents, hasHydratableComponents, isHydratable, pageMetaSchema, scanForHydratableComponents, serializeProps, withHydration };
182
+ export { type BlockMeta, type ComponentRegistry, type ConlocaCMSOptions, type ConlocaLoaderOptions, type HydratableComponent, type HydratableComponentConfig, type HydrationDiscovery, type HydrationMeta, type HydrationStrategy, type PageMeta, type TemplateConfig, type WithHydrationStrategy, blockMetaSchema, conlocaCMS, conlocaLoader, extractSlugFromPathname, findHydratableComponents, hasHydratableComponents, isHydratable, pageMetaSchema, pathnameFromSlug, scanForHydratableComponents, serializeProps, withHydration };
148
183
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/loader.ts","../src/plugin-spa.ts","../src/lib/hydration-utils.ts","../src/lib/serialize-props.ts","../src/lib/hydration-scanner.ts"],"sourcesContent":[],"mappings":";;;;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[],"sources":["../src/lib/hydration-scanner.ts","../src/lib/hydration-utils.ts","../src/lib/route-utils.ts","../src/lib/serialize-props.ts","../src/loader.ts","../src/plugin-spa.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;UAOiB,kBAAA;;;;;;EAAA,QAAA,EAAA,MAAA,GAAA,SAAkB,GAAA,MAAA;AA0FnC;;;ACYA;;;;AC7FA;AAkCA;;;;AC9CA;;;;ACDA;AAYA;;;iBJkFsB,2BAAA,iDAGnB,QAAQ;;;;;;;UC5FM,yBAAA;;cAEH;EDHG,MAAA,CAAA,EAAA,CAAA,KAAA,EAAA,OAAkB,EAAA,GAAA,OAAA;AA0FnC;;;;ACzFA;AAUiB,UAAA,mBAAA,CAAmB;EAI3B;EAEW,IAAA,EAAA,MAAA;EAAR;EAAO,KAAA,EAFV,MAEU,CAAA,MAAA,EAAA,OAAA,CAAA;EAeH;EAyBA,QAAA,EAxCJ,OAwCI,CAxCI,iBAwCoB,EAAA,MAAA,CAAA;EAChC;EACE,EAAA,EAAA,MAAA;;;AA2CV;;;;AC7FA;AAkCA;;;;AC9CgB,iBFmCA,YAAA,CEnCsB,aAAM,EAAA,MAAA,EAAA,MAAA,EFqClC,MErCkC,CAAA,EFsCzC,iBEtCyC;;;;ACD5C;AAYA;;;;ACoCiB,iBJaD,wBAAA,CIbmB,IAAA,EJc3B,IId2B,EAAA,MAAA,EJezB,MIfyB,CAAA,EJgBhC,mBIhBgC,EAAA;;;;;AAAQ,iBJ0D3B,uBAAA,CI1D2B,IAAA,EJ0DG,II1DH,EAAA,MAAA,EJ0DiB,MI1DjB,CAAA,EAAA,OAAA;;;;;;;;;;;;AL5C3C;AA0FA;;;;ACzFA;AAUA;AAIS,iBCNO,uBAAA,CDMP,QAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;;;AAiBT;AAyBA;;;;;AA6CA;;;;AC7FA;AAkCA;iBAAgB,gBAAA;;;;;;;iBC9CA,cAAA,QAAsB;;;UCDrB,oBAAA;;;;;;;;AJIjB;AA0FA;;iBIlFgB,aAAA,UAAuB,uBAAuB;;;UCoC7C,iBAAA,SAA0B,KAAK;;;;;;EL5C/B;AA0FjB;;;;ACzFA;AAUA;EAIS,MAAA,CAAA,EAAA,MAAA;EAEW,OAAA,CAAA,EI2CR,kBJ3CQ;EAAR,SAAA,CAAA,EI4CE,MJ5CF,CAAA,MAAA,EI4CiB,cJ5CjB,CAAA;EAAO;AAenB;AAyBA;;;;EAGsB,cAAA,CAAA,EAAA,MAAA,EAAA;EA0CN;;;;AC7FhB;AAkCA;;;iBGyHgB,UAAA,UAAoB,oBAAoB"}
package/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import { t as conlocaLoader } from "./loader-C6JF2toW.mjs";
2
- import { i as isHydratable, n as findHydratableComponents, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-BryTdVgJ.mjs";
3
- import { t as withHydration } from "./withHydration-DAkXCF9z.mjs";
1
+ import { i as isHydratable, n as findHydratableComponents, r as hasHydratableComponents, t as serializeProps } from "./serialize-props-CQDv661k.mjs";
2
+ import { t as withHydration } from "./withHydration-DfAwNHmI.mjs";
3
+ import { t as conlocaLoader } from "./loader-BYmsavWc.mjs";
4
4
  import { blockMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
5
- import { createContentAPI, createContentWatchHandlers } from "@conloca/content-api/node";
5
+ import { readFile } from "node:fs/promises";
6
6
  import { basename, dirname, extname, join, resolve } from "node:path";
7
+ import fg from "fast-glob";
8
+ import { createContentAPI, createContentWatchHandlers } from "@conloca/content-api/node";
9
+ import { existsSync } from "node:fs";
7
10
  import { fileURLToPath } from "node:url";
8
11
  import viteReact from "@vitejs/plugin-react";
9
12
  import { searchForWorkspaceRoot } from "vite";
10
- import { readFile } from "node:fs/promises";
11
- import fg from "fast-glob";
12
13
 
13
14
  //#region src/lib/hydration-scanner.ts
14
15
  const HYDRATION_IMPORT_PATTERN = /import\s+\{[^}]*withHydration[^}]*\}\s+from\s+['"]@conloca\/astro-cms(?:\/hydration)?['"]/;
@@ -112,6 +113,51 @@ async function scanForHydratableComponents(componentPaths, projectRoot) {
112
113
  return discoveries;
113
114
  }
114
115
 
116
+ //#endregion
117
+ //#region src/lib/route-utils.ts
118
+ /**
119
+ * Extract slug from pathname given a route pattern.
120
+ *
121
+ * The slug is the portion of the pathname that comes after the
122
+ * static prefix of the pattern.
123
+ *
124
+ * @param pathname - URL pathname (e.g., '/about', '/blog/post-1')
125
+ * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')
126
+ * @returns The extracted slug, or undefined for root paths
127
+ *
128
+ * @example
129
+ * extractSlugFromPathname('/about', '/[...slug]') // 'about'
130
+ * extractSlugFromPathname('/blog/post-1', '/blog/[...slug]') // 'post-1'
131
+ * extractSlugFromPathname('/', '/[...slug]') // undefined
132
+ * extractSlugFromPathname('/blog', '/blog/[...slug]') // undefined
133
+ */
134
+ function extractSlugFromPathname(pathname, pattern) {
135
+ const prefixMatch = pattern.match(/^(.*?)\[/);
136
+ const prefix = prefixMatch ? prefixMatch[1].replace(/\/$/, "") : "";
137
+ return pathname.slice(prefix.length).replace(/^\//, "") || void 0;
138
+ }
139
+ /**
140
+ * Convert a slug back to a pathname given a route pattern.
141
+ *
142
+ * The inverse of extractSlugFromPathname.
143
+ *
144
+ * @param slug - The page slug (e.g., 'about', 'post-1'), or undefined for root
145
+ * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')
146
+ * @returns Full URL pathname
147
+ *
148
+ * @example
149
+ * pathnameFromSlug('about', '/[...slug]') // '/about'
150
+ * pathnameFromSlug('post-1', '/blog/[...slug]') // '/blog/post-1'
151
+ * pathnameFromSlug(undefined, '/[...slug]') // '/'
152
+ * pathnameFromSlug(undefined, '/blog/[...slug]') // '/blog'
153
+ */
154
+ function pathnameFromSlug(slug, pattern) {
155
+ const prefixMatch = pattern.match(/^(.*?)\[/);
156
+ const prefix = prefixMatch ? prefixMatch[1].replace(/\/$/, "") : "";
157
+ if (!slug) return prefix || "/";
158
+ return `${prefix}/${slug}`;
159
+ }
160
+
115
161
  //#endregion
116
162
  //#region src/lib/routing-config.ts
117
163
  /**
@@ -426,8 +472,7 @@ function generatePuckConfigModule(puckConfigPath) {
426
472
 
427
473
  //#endregion
428
474
  //#region src/plugin-spa.ts
429
- const __dirname = dirname(fileURLToPath(import.meta.url));
430
- const PAGE_HANDLER_PATH = __dirname.endsWith("/dist") || __dirname.includes("/dist/") ? join(dirname(__dirname), "src", "handlers", "page-handler.astro") : join(__dirname, "handlers", "page-handler.astro");
475
+ const PAGE_HANDLER_PATH = join(dirname(fileURLToPath(import.meta.url)), "handlers", "page-handler.astro");
431
476
  const VIRTUAL_CONFIG_MODULE = "virtual:conloca-config";
432
477
  const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
433
478
  const VIRTUAL_ROUTING_CONFIG = "virtual:conloca-routing-config";
@@ -679,19 +724,31 @@ initHydration(componentRegistry)
679
724
  if (options.schemasPath) return schemasLoader(options.schemasPath.startsWith(".") ? `/${options.schemasPath.slice(2)}` : options.schemasPath);
680
725
  return "export default {};";
681
726
  }
682
- if (id === RESOLVED_CMS_SPA_ENTRY) return `
727
+ if (id === RESOLVED_CMS_SPA_ENTRY) {
728
+ const preambleCode = viteReact.preambleCode.replace("__BASE__", "/");
729
+ let cmsSpaImport;
730
+ try {
731
+ const cmsSpaPackageJsonPath = import.meta.resolve("@conloca/cms-spa/package.json");
732
+ const srcMainPath = join(dirname(cmsSpaPackageJsonPath.startsWith("file://") ? fileURLToPath(cmsSpaPackageJsonPath) : cmsSpaPackageJsonPath), "src", "main.tsx");
733
+ if (existsSync(srcMainPath)) cmsSpaImport = `import '${srcMainPath}';`;
734
+ else cmsSpaImport = "import '@conloca/cms-spa';";
735
+ } catch {
736
+ cmsSpaImport = "import '@conloca/cms-spa';";
737
+ }
738
+ return `
683
739
  // Import and execute React refresh preamble first (from @vitejs/plugin-react)
684
- ${viteReact.preambleCode.replace("__BASE__", "/")}
740
+ ${preambleCode}
685
741
 
686
- // Import cms-spa main.tsx directly through Vite
742
+ // Import cms-spa through Vite
687
743
  // Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
688
- import '@conloca/cms-spa/src/main.tsx';
744
+ ${cmsSpaImport}
689
745
 
690
746
  // Accept HMR
691
747
  if (import.meta.hot) {
692
748
  import.meta.hot.accept();
693
749
  }
694
750
  `;
751
+ }
695
752
  return null;
696
753
  }
697
754
  }, {
@@ -766,5 +823,5 @@ if (import.meta.hot) {
766
823
  }
767
824
 
768
825
  //#endregion
769
- export { blockMetaSchema, conlocaCMS, conlocaLoader, findHydratableComponents, hasHydratableComponents, isHydratable, pageMetaSchema, scanForHydratableComponents, serializeProps, withHydration };
826
+ export { blockMetaSchema, conlocaCMS, conlocaLoader, extractSlugFromPathname, findHydratableComponents, hasHydratableComponents, isHydratable, pageMetaSchema, pathnameFromSlug, scanForHydratableComponents, serializeProps, withHydration };
770
827
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["discoveries: HydrationDiscovery[]","hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]>","resolvedRoutingConfig: ResolvedRoutingConfig | undefined","resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>>","astroRoot","contentAbsolute","resolve","conflicts: { injected: string; fileBased: string }[]"],"sources":["../src/lib/hydration-scanner.ts","../src/lib/routing-config.ts","../src/lib/virtual-module-generators.ts","../src/plugin-spa.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport fg from 'fast-glob'\n\n/**\n * Result of scanning a component file for withHydration usage.\n */\nexport interface HydrationDiscovery {\n /** Component name derived from filename (PascalCase) */\n componentName: string\n /** Absolute path to the component file */\n filePath: string\n /** Hydration strategy extracted from withHydration call */\n strategy: 'load' | 'visible' | 'idle'\n}\n\n// Regex to check if file imports withHydration from @conloca/astro-cms or @conloca/astro-cms/hydration\n// This is faster than es-module-lexer for JSX files and avoids parse errors\nconst HYDRATION_IMPORT_PATTERN = /import\\s+\\{[^}]*withHydration[^}]*\\}\\s+from\\s+['\"]@conloca\\/astro-cms(?:\\/hydration)?['\"]/\n\n// Regex to find withHydration calls and extract strategy\n// Matches: withHydration(ComponentName, 'strategy') or withHydration(ComponentName, \"strategy\")\nconst HYDRATION_PATTERN = /withHydration\\s*\\(\\s*\\w+\\s*,\\s*['\"](\\w+)['\"]\\s*\\)/g\n\n// Valid hydration strategies\nconst VALID_STRATEGIES = new Set(['load', 'visible', 'idle'])\n\n/**\n * Derives component scan paths from puckConfigPath.\n *\n * Convention: puckConfigPath directory + '/components/puck'\n * Example: './src/puck.config.tsx' -> './src/components/puck'\n *\n * If explicitPaths provided, they extend (not replace) the auto-discovered path.\n *\n * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')\n * @param explicitPaths - Optional additional paths to scan\n * @returns Array of paths to scan for hydratable components\n */\nexport function deriveComponentPaths(\n puckConfigPath: string,\n explicitPaths?: string[]\n): string[] {\n const puckDir = dirname(puckConfigPath)\n const defaultScanPath = join(puckDir, 'components', 'puck')\n\n if (explicitPaths && explicitPaths.length > 0) {\n return [defaultScanPath, ...explicitPaths]\n }\n return [defaultScanPath]\n}\n\n/**\n * Derives a PascalCase component name from a file path.\n *\n * @param filePath - Absolute path to the component file\n * @returns Component name in PascalCase\n *\n * @example\n * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')\n * // => 'TestimonialGrid'\n *\n * deriveComponentName('/src/components/puck/blog-post-grid.tsx')\n * // => 'BlogPostGrid'\n */\nfunction deriveComponentName(filePath: string): string {\n const filename = basename(filePath, extname(filePath))\n // Convert kebab-case to PascalCase if needed\n if (filename.includes('-')) {\n return filename\n .split('-')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n }\n // Ensure first letter is uppercase\n return filename.charAt(0).toUpperCase() + filename.slice(1)\n}\n\n/**\n * Scans component directories for files using withHydration wrapper.\n *\n * This function performs static analysis to discover components marked\n * for hydration, without executing any component code.\n *\n * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])\n * @param projectRoot - Absolute path to the project root\n * @returns Array of discovered hydratable components with their strategies\n *\n * @example\n * ```typescript\n * const discoveries = await scanForHydratableComponents(\n * ['src/components/puck'],\n * '/path/to/project'\n * )\n * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]\n * ```\n */\nexport async function scanForHydratableComponents(\n componentPaths: string[],\n projectRoot: string\n): Promise<HydrationDiscovery[]> {\n const discoveries: HydrationDiscovery[] = []\n const seenNames = new Map<string, string>() // componentName -> first filePath\n\n for (const scanPath of componentPaths) {\n const absolutePath = resolve(projectRoot, scanPath)\n\n // Find all .tsx files in the directory and subdirectories\n const files = await fg('**/*.tsx', {\n cwd: absolutePath,\n absolute: true,\n onlyFiles: true,\n })\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8')\n\n // Fast path: check if file imports withHydration from @conloca/astro-cms\n // Using simple regex instead of es-module-lexer to avoid JSX parse errors\n if (!HYDRATION_IMPORT_PATTERN.test(content)) {\n continue\n }\n\n // Find withHydration calls with regex\n const matches = [...content.matchAll(HYDRATION_PATTERN)]\n\n if (matches.length === 0) {\n continue\n }\n\n if (matches.length > 1) {\n console.warn(\n `[Conloca Hydration] Multiple withHydration calls in ${filePath}. ` +\n 'Consider splitting into separate component files. Using first call.'\n )\n }\n\n const match = matches[0]\n const rawStrategy = match[1]\n\n // Validate strategy\n if (!VALID_STRATEGIES.has(rawStrategy)) {\n console.warn(\n `[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. ` +\n `Valid options: ${[...VALID_STRATEGIES].join(', ')}. Skipping component.`\n )\n continue\n }\n\n const strategy = rawStrategy as 'load' | 'visible' | 'idle'\n const componentName = deriveComponentName(filePath)\n\n // Check for naming conflicts\n const existingPath = seenNames.get(componentName)\n if (existingPath) {\n console.warn(\n `[Conloca Hydration] Duplicate component name '${componentName}'. ` +\n `Found in: ${existingPath} and ${filePath}. Using first occurrence.`\n )\n continue\n }\n\n seenNames.set(componentName, filePath)\n discoveries.push({\n componentName,\n filePath,\n strategy,\n })\n } catch (err) {\n // Log error but continue scanning other files\n console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err)\n }\n }\n }\n\n return discoveries\n}\n","import type { RouteConfig, RoutingConfig, RoutingConfigInput } from '../types.js';\n\n/**\n * Normalize routing config input to full RoutingConfig.\n *\n * Handles the `routing: true` shorthand, boolean values, and top-level layout option.\n *\n * @param input - The routing config input (boolean, object, or undefined)\n * @param topLevelLayout - Optional top-level layout path (enables routing when provided)\n * @returns Normalized RoutingConfig or undefined if not enabled\n */\nexport function normalizeRoutingConfig(\n input: RoutingConfigInput | undefined,\n topLevelLayout?: string\n): RoutingConfig | undefined {\n // If no routing config but layout provided, enable with defaults\n if (input === undefined && topLevelLayout) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n layout: topLevelLayout,\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === undefined) {\n return undefined;\n }\n\n if (input === true) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === false) {\n return { enabled: false };\n }\n\n return input;\n}\n\n/**\n * Apply defaults to a RouteConfig.\n *\n * Fills in missing optional fields with their default values.\n *\n * @param config - Partial route configuration\n * @returns Complete route configuration with all fields\n */\nexport function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {\n return {\n pattern: config.pattern,\n collection: config.collection ?? 'pages',\n layout: config.layout ?? '',\n prerender: config.prerender ?? true,\n meta: config.meta ?? {},\n dataBindings: config.dataBindings ?? { collections: [] },\n };\n}\n\n/**\n * Validate a route pattern.\n *\n * Ensures the pattern is a valid Astro route pattern.\n * Throws descriptive error if invalid.\n *\n * @param pattern - The route pattern to validate\n * @param routeName - Name of the route (for error messages)\n * @throws Error if pattern is invalid\n */\nexport function validateRoutePattern(pattern: string, routeName: string): void {\n if (!pattern.startsWith('/')) {\n throw new Error(`Route '${routeName}': pattern must start with '/', got '${pattern}'`);\n }\n\n // Check for valid Astro route syntax\n // Allow: a-zA-Z0-9, hyphen, underscore, slash, brackets, dots\n const invalidChars = pattern.match(/[^a-zA-Z0-9\\-_/[\\].]/g);\n if (invalidChars) {\n throw new Error(`Route '${routeName}': pattern contains invalid characters: ${invalidChars.join(', ')}`);\n }\n\n // Check for balanced brackets\n const openBrackets = (pattern.match(/\\[/g) || []).length;\n const closeBrackets = (pattern.match(/\\]/g) || []).length;\n if (openBrackets !== closeBrackets) {\n throw new Error(`Route '${routeName}': pattern has unbalanced brackets: '${pattern}'`);\n }\n}\n","import type { ResolvedRoutingConfig, RoutingConfig } from '../types.js';\n\n/**\n * Generate the virtual:conloca-routing-config module.\n *\n * Returns a module that exports the resolved routing configuration as default.\n *\n * @param config - Resolved routing configuration with all defaults applied\n * @returns JavaScript module code as a string\n */\nexport function generateRoutingConfigModule(config: ResolvedRoutingConfig): string {\n return `export default ${JSON.stringify(config, null, 2)};`;\n}\n\n/**\n * Generate the virtual:conloca-layout module.\n *\n * Returns a module that re-exports the layout component or exports undefined\n * if no layout is configured.\n *\n * Currently uses the first route's layout. Multi-layout support is future work.\n *\n * @param routing - Routing configuration (may be undefined if routing disabled)\n * @returns JavaScript module code as a string\n */\nexport function generateLayoutModule(routing: RoutingConfig | undefined): string {\n // Get layout from first route (for now - multi-layout is future work)\n const routes = routing?.routes || {};\n const firstRoute = Object.values(routes)[0];\n const layoutPath = firstRoute?.layout;\n\n if (layoutPath) {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = layoutPath.startsWith('.') ? `/${layoutPath.slice(2)}` : layoutPath;\n\n return `export { default } from '${absolutePath}';`;\n }\n\n return 'export default undefined;';\n}\n\n/**\n * Options for generating the page API module.\n */\nexport interface PageApiModuleOptions {\n contentRoot: string;\n canvasDir: string;\n /** Site name for content resolution. @default 'default' */\n siteName: string;\n /** Default locale for content resolution. @default 'en' */\n locale: string;\n}\n\n/**\n * Generate the virtual:conloca-page-api module.\n *\n * Returns a module that provides page loading functions wrapping ContentAPI:\n * - getAllPages(collection?) - For getStaticPaths()\n * - getPage(pathname, collection?) - For page data loading\n * - pageExists(pathname, collection?) - For 404 checks\n * - contentOptions - Configuration for ContentAPI (for MDX evaluation)\n *\n * @param options - Configuration for ContentAPI initialization\n * @returns JavaScript module code as a string\n */\nexport function generatePageApiModule(options: PageApiModuleOptions): string {\n return `\nimport { createContentAPI } from '@conloca/content-api/node';\n\n// Export content options for MDX evaluation and other ContentAPI uses\nexport const contentOptions = {\n contentRoot: '${options.contentRoot}',\n canvasDir: '${options.canvasDir}',\n siteName: '${options.siteName}',\n locale: '${options.locale}',\n};\n\n// Initialize ContentAPI with configured paths\nconst contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n});\n\n// Get site instance for page operations (configured via routing.siteName)\nconst site = contentApi.getSite(contentOptions.siteName);\nconst locale = contentOptions.locale; // Configured via routing.locale\n\n/**\n * Get all pages for static path generation.\n * @param collection - Optional collection filter\n */\nexport async function getAllPages(collection) {\n const pages = [];\n\n // listPages is a generator that yields ContentManifest objects\n for (const manifest of site.listPages(locale)) {\n // Get the localized data for pathname/title\n const localeData = manifest.locales[locale];\n if (!localeData) continue;\n\n const pathname = localeData.pathname || '/' + manifest.id.replace(/^index$/, '');\n\n // Collection resolution: explicit collection in manifest, or default 'pages'\n const resolvedCollection = manifest.collection || 'pages';\n\n // Filter by requested collection\n if (collection && resolvedCollection !== collection) continue;\n\n pages.push({\n id: manifest.id,\n pathname: pathname,\n title: localeData.meta?.title || manifest.id,\n collection: resolvedCollection,\n meta: localeData.meta || {},\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n });\n }\n\n return pages;\n}\n\n/**\n * Get pages matching a path prefix.\n * @param prefix - Path prefix to match (e.g., '/blog/')\n * @param options - Optional sort and limit settings\n * @returns Array of PageReference objects\n */\nexport async function getPagesByPrefix(prefix, options = {}) {\n const allPages = await getAllPages();\n\n let filtered = allPages.filter(page =>\n page.pathname.startsWith(prefix) &&\n page.pathname !== prefix && // Exclude the listing page itself\n page.pathname !== prefix.slice(0, -1) // Exclude without trailing slash\n );\n\n // Sort by date (newest first by default)\n if (options.sort === 'date-desc' || !options.sort) {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateB).getTime() - new Date(dateA).getTime();\n });\n } else if (options.sort === 'date-asc') {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateA).getTime() - new Date(dateB).getTime();\n });\n } else if (options.sort === 'title') {\n filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));\n }\n\n if (options.limit && options.limit > 0) {\n filtered = filtered.slice(0, options.limit);\n }\n\n return filtered;\n}\n\n/**\n * Load full page data for rendering.\n * @param pathname - URL pathname (e.g., '/about')\n * @param collection - Optional collection to search in\n */\nexport async function getPage(pathname, collection) {\n // Use site.getByPathname which returns ContentManifest (metadata only)\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Optionally filter by collection\n if (collection && manifest.collection !== collection) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Get the full content with locale data\n const content = await contentApi.getLocalized(manifest.id, locale);\n\n if (!content) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n const localeData = content.localized;\n const meta = localeData.meta || {};\n\n return {\n id: manifest.id,\n title: meta.title || manifest.id,\n description: meta.description,\n pathname: pathname,\n puckData: localeData.content?.puckData,\n collection: manifest.collection || collection || 'pages',\n route: {\n name: 'pages', // Will be set by caller\n pattern: '/[...slug]',\n meta: {},\n },\n meta: meta,\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n };\n}\n\n/**\n * Check if a page exists without loading full data.\n * @param pathname - URL pathname\n * @param collection - Optional collection filter\n */\nexport function pageExists(pathname, collection) {\n // getByPathname is synchronous - returns ContentManifest | null\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n return false;\n }\n\n // If collection filter specified, verify it matches\n if (collection && manifest.collection !== collection) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get all entries from a data collection.\n * @param collection - Data collection name\n * @param localeOverride - Optional locale override (defaults to configured locale)\n * @returns Array of DataCollectionEntry objects\n */\nexport async function getDataCollection(collection, localeOverride) {\n const targetLocale = localeOverride || locale;\n const entries = [];\n\n // List all manifests in the collection\n for (const manifest of contentApi.data.listContent({ collection })) {\n // Get localized data for each entry\n const localized = await contentApi.getLocalized(manifest.id, targetLocale);\n if (localized) {\n entries.push({\n id: manifest.id,\n name: manifest.name,\n data: localized.content?.data || {},\n meta: manifest.meta || {},\n });\n }\n }\n\n return entries;\n}\n`;\n}\n\n/**\n * Generate the virtual:conloca-puck-config module.\n *\n * Returns a module that re-exports the Puck configuration.\n * This is separate from the HMR-enabled puck-entry.js used by the CMS SPA.\n *\n * @param puckConfigPath - Path to the puck config module\n * @returns JavaScript module code as a string\n */\nexport function generatePuckConfigModule(puckConfigPath: string): string {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = puckConfigPath.startsWith('.') ? `/${puckConfigPath.slice(2)}` : puckConfigPath\n\n return `export { default } from '${absolutePath}';`\n}\n","import { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { UIConfig } from '@conloca/cms-spa';\nimport { createContentAPI, createContentWatchHandlers } from '@conloca/content-api/node';\nimport viteReact from '@vitejs/plugin-react';\nimport type { AstroIntegration } from 'astro';\nimport { searchForWorkspaceRoot } from 'vite';\n\nimport { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';\nimport { normalizeRoutingConfig, resolveRouteConfig } from './lib/routing-config.js';\n\n// Get the directory of this module to resolve page-handler.astro\n// In development, __dirname points to src/. In production, it points to dist/.\n// The handlers directory is always in src/, so we need to handle both cases.\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst isInDist = __dirname.endsWith('/dist') || __dirname.includes('/dist/');\nconst PAGE_HANDLER_PATH = isInDist\n ? join(dirname(__dirname), 'src', 'handlers', 'page-handler.astro')\n : join(__dirname, 'handlers', 'page-handler.astro');\n\nimport {\n generateLayoutModule,\n generatePageApiModule,\n generatePuckConfigModule,\n generateRoutingConfigModule,\n} from './lib/virtual-module-generators.js';\nimport type { ResolvedRoutingConfig, RoutingConfigInput, TemplateConfig } from './types.js';\n\n// Virtual module for passing config from plugin to route handler\nconst VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';\nconst RESOLVED_VIRTUAL_CONFIG = `\\0${VIRTUAL_CONFIG_MODULE}`;\n\n// Virtual module IDs for routing system\nconst VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';\nconst VIRTUAL_LAYOUT = 'virtual:conloca-layout';\nconst VIRTUAL_PAGE_API = 'virtual:conloca-page-api';\nconst VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';\n\n// Resolved IDs (with \\0 prefix to prevent file resolution)\nconst RESOLVED_ROUTING_CONFIG = `\\0${VIRTUAL_ROUTING_CONFIG}`;\nconst RESOLVED_LAYOUT = `\\0${VIRTUAL_LAYOUT}`;\nconst RESOLVED_PAGE_API = `\\0${VIRTUAL_PAGE_API}`;\nconst RESOLVED_PUCK_CONFIG = `\\0${VIRTUAL_PUCK_CONFIG}`;\n\n// Virtual modules for hydration system\nconst VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';\nconst VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';\nconst RESOLVED_HYDRATION_REGISTRY = `\\0${VIRTUAL_HYDRATION_REGISTRY}`;\nconst RESOLVED_HYDRATION_ENTRY = `\\0${VIRTUAL_HYDRATION_ENTRY}`;\n\n// Virtual module for CMS SPA source loading (dev only)\nconst VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';\nconst RESOLVED_CMS_SPA_ENTRY = `\\0${VIRTUAL_CMS_SPA_ENTRY}`;\n\nexport interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {\n contentRoot: string;\n canvasDir?: string;\n route?: string; // Default: /__cms\n puckConfigPath: string; // Path to the puck config module (should be .tsx file with React components)\n schemasPath?: string; // Path to the schemas module (exports { dataSchemas, pageSchemas })\n\n /**\n * Default layout for content pages.\n * When provided without routing config, enables routing with catch-all pattern.\n * For multi-route setups, use routing.routes.{name}.layout instead.\n *\n * @example './src/layouts/Layout.astro'\n */\n layout?: string;\n\n routing?: RoutingConfigInput; // Content page routing configuration\n templates?: Record<string, TemplateConfig>; // Page creation templates\n\n /**\n * Paths to scan for hydratable components.\n * Components using withHydration() in these directories are auto-discovered.\n *\n * @example ['src/components/puck']\n */\n componentPaths?: string[];\n\n /**\n * Path to the assets directory for image uploads.\n * When provided, enables the Media Library and asset upload API routes.\n *\n * @example 'src/assets/uploads'\n */\n assetsPath?: string;\n}\n\n// Template for content change listener virtual module\nconst contentChangeListener = () => {\n return `\n// Content change listener that uses Vite HMR\nif (import.meta.hot) {\n import.meta.hot.on('conloca:content-update', (data) => {\n console.log('[Conloca CMS] Content updated, invalidating cache:', data);\n \n // Get the query client from the global scope and invalidate\n if (window.__QUERY_CLIENT__) {\n window.__QUERY_CLIENT__.invalidateQueries();\n }\n });\n}\n\nexport default {};\n`;\n};\n\n// Template for the puck config loader virtual module\nconst puckConfigLoader = (absolutePuckPath: string) => {\n // Get the exact preamble code from the React plugin\n // The base needs to be '/' so the import becomes '/@react-refresh'\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\n // We need to ensure the preamble executes before ANY module evaluation\n // So we'll use a dynamic import after the preamble is set up\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${preambleCode}\n\n// Import the setPuckConfig function from cms-spa\nimport { setPuckConfig } from '@conloca/cms-spa/puck-config';\n\n// Now dynamically import the config after preamble is ready\nconst puckConfigPromise = import('${absolutePuckPath}');\n\n// Handle the initial load\npuckConfigPromise.then(module => {\n const puckConfig = module.default;\n setPuckConfig(puckConfig);\n\n // Hook into React Fast Refresh to detect component updates\n if (window.__registerBeforePerformReactRefresh) {\n window.__registerBeforePerformReactRefresh(async () => {\n // Re-import the config module to get updated components\n const newModule = await import('${absolutePuckPath}');\n setPuckConfig(newModule.default);\n });\n }\n});\n\n// Accept HMR for this module itself\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\n// Export the promise so the module has a default export\nexport default puckConfigPromise.then(m => m.default);\n`;\n};\n\n// Template for the schemas loader virtual module\nconst schemasLoader = (absoluteSchemasPath: string) => {\n return `\nimport { setPageSchemas } from '@conloca/cms-spa/page-schemas';\nimport * as schemas from '${absoluteSchemasPath}';\n\nif (schemas.pageSchemas) {\n setPageSchemas(schemas.pageSchemas);\n}\n\nif (import.meta.hot) {\n import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {\n if (newModule?.pageSchemas) {\n setPageSchemas(newModule.pageSchemas);\n }\n });\n}\n\nexport default schemas;\n`;\n};\n\nexport function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {\n const cmsRoute = options.route || '/__cms';\n\n // Normalize routing config and resolve defaults\n // Pass top-level layout to enable routing when layout provided without explicit routing config\n const routingConfig = normalizeRoutingConfig(options.routing, options.layout);\n\n // Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths\n // Scanner handles missing directories gracefully (fast-glob returns empty array)\n const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);\n\n // Scan for hydratable components - this promise is awaited in the virtual module loader\n const hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]> = scanForHydratableComponents(\n componentPaths,\n process.cwd(),\n ).then((discoveries) => {\n if (discoveries.length > 0) {\n console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);\n }\n return discoveries;\n });\n\n // Build resolved routing config with all defaults applied\n let resolvedRoutingConfig: ResolvedRoutingConfig | undefined;\n if (routingConfig?.enabled !== false && routingConfig) {\n const resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>> = {};\n for (const [name, config] of Object.entries(routingConfig.routes || {})) {\n resolvedRoutes[name] = resolveRouteConfig(config);\n }\n resolvedRoutingConfig = {\n enabled: routingConfig.enabled ?? true,\n routes: resolvedRoutes,\n fallback: routingConfig.fallback ?? '404',\n onConflict: routingConfig.onConflict ?? 'warn',\n siteName: routingConfig.siteName ?? 'default',\n locale: routingConfig.locale ?? 'en',\n };\n }\n\n // SPA config passed to route handler via virtual module\n // This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true\n const spaConfig = {\n basename: cmsRoute,\n apiBaseUrl: `${cmsRoute}/api`,\n siteBaseUrl: options.siteBaseUrl,\n enableDevtools: options.enableDevtools ?? true,\n queryClientOptions: options.queryClientOptions,\n schemasPath: options.schemasPath,\n projectRoot: process.cwd(),\n templates: options.templates,\n };\n\n return {\n name: '@conloca/astro-cms',\n hooks: {\n 'astro:config:setup': ({ updateConfig, injectRoute, command, logger }) => {\n // Auto-inject fs.allow for external contentRoot (dev mode only)\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n\n if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {\n logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);\n\n updateConfig({\n vite: {\n server: {\n fs: {\n allow: [\n searchForWorkspaceRoot(process.cwd()), // Preserve Vite default\n contentAbsolute,\n ],\n },\n },\n },\n });\n }\n\n // Always apply SSR externalization for native modules (needed for both dev and build)\n // This must be outside the dev-only block to fix build errors\n updateConfig({\n vite: {\n ssr: {\n // Force these packages through Vite's resolver during SSR\n // This ensures symlinked packages use the consumer's React, not their own\n // Without this, symlinked packages resolve React from their node_modules\n noExternal: ['@conloca/astro-cms', '@conloca/cms-spa'],\n // Externalize native Node modules for SSR builds\n // These cannot be bundled and must be available at runtime\n external: ['@node-rs/xxhash'],\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\n {\n name: 'conloca-routing-virtual-modules',\n resolveId(id) {\n // Routing virtual modules (work in both dev and build)\n if (id === VIRTUAL_ROUTING_CONFIG) {\n return RESOLVED_ROUTING_CONFIG;\n }\n if (id === VIRTUAL_LAYOUT) {\n return RESOLVED_LAYOUT;\n }\n if (id === VIRTUAL_PAGE_API) {\n return RESOLVED_PAGE_API;\n }\n if (id === VIRTUAL_PUCK_CONFIG) {\n return RESOLVED_PUCK_CONFIG;\n }\n // Hydration virtual modules\n if (id === VIRTUAL_HYDRATION_REGISTRY) {\n return RESOLVED_HYDRATION_REGISTRY;\n }\n if (id === VIRTUAL_HYDRATION_ENTRY) {\n return RESOLVED_HYDRATION_ENTRY;\n }\n return null;\n },\n async load(id) {\n // Routing virtual modules\n if (id === RESOLVED_ROUTING_CONFIG) {\n if (resolvedRoutingConfig) {\n return generateRoutingConfigModule(resolvedRoutingConfig);\n }\n // Return disabled config if routing not configured\n return 'export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };';\n }\n if (id === RESOLVED_LAYOUT) {\n return generateLayoutModule(routingConfig);\n }\n if (id === RESOLVED_PAGE_API) {\n return generatePageApiModule({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n siteName: resolvedRoutingConfig?.siteName ?? 'default',\n locale: resolvedRoutingConfig?.locale ?? 'en',\n });\n }\n if (id === RESOLVED_PUCK_CONFIG) {\n return generatePuckConfigModule(options.puckConfigPath);\n }\n // Hydration virtual modules\n if (id === RESOLVED_HYDRATION_REGISTRY) {\n // Always scan - paths are auto-derived from puckConfigPath\n const discoveries = await hydrationDiscoveriesPromise;\n if (discoveries.length > 0) {\n const entries = discoveries.map((d) => {\n // Convert absolute path to Vite-friendly path\n const relativePath = d.filePath.replace(process.cwd(), '');\n return ` '${d.componentName}': {\n loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),\n strategy: '${d.strategy}',\n }`;\n });\n return `// Generated by @conloca/astro-cms scanner\nexport const componentRegistry = {\n${entries.join(',\\n')}\n};`;\n }\n\n // No hydratable components found - return empty registry\n return 'export const componentRegistry = {};';\n }\n if (id === RESOLVED_HYDRATION_ENTRY) {\n // Generate entry point that imports registry and calls initHydration\n return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'\nimport { componentRegistry } from 'virtual:conloca-hydration-registry'\n\n// Auto-initialize hydration when this module loads\ninitHydration(componentRegistry)\n`;\n }\n return null;\n },\n },\n ],\n },\n });\n\n // Content page routes - works in both dev and build\n if (resolvedRoutingConfig?.enabled) {\n for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {\n logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);\n injectRoute({\n pattern: routeConfig.pattern,\n entrypoint: PAGE_HANDLER_PATH,\n prerender: routeConfig.prerender,\n });\n }\n }\n\n // Only inject CMS admin routes and dev-specific config in dev mode\n if (command !== 'dev') return;\n\n // Pass options via Vite define for API routes\n updateConfig({\n vite: {\n define: {\n 'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),\n 'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),\n 'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),\n 'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),\n },\n resolve: {\n // Dedupe React to avoid multiple instances when using symlinked packages\n // This prevents \"Cannot read properties of null (reading 'useMemo')\" errors\n dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', '@measured/puck'],\n },\n optimizeDeps: {\n // Exclude the puck config from optimization to avoid the outdated dep error\n exclude: [options.puckConfigPath],\n // Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization\n // which causes React dual-instance issues when Vite discovers new deps dynamically\n include: [\n // React core - must be pre-bundled together\n 'react',\n 'react-dom',\n 'react-dom/client',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n // CMS dependencies\n '@mdxeditor/editor',\n '@measured/puck',\n '@tanstack/react-query',\n '@tanstack/react-query-devtools',\n 'react-router-dom',\n '@radix-ui/react-dialog',\n '@radix-ui/react-select',\n 'lucide-react',\n 'clsx',\n 'tailwind-merge',\n // Content processing\n 'zod',\n 'yaml',\n 'nanoid',\n 'sort-keys',\n // MDX processing\n '@mdx-js/mdx',\n 'remark-frontmatter',\n 'remark-gfm',\n 'remark-mdx-frontmatter',\n ],\n },\n plugins: [\n {\n name: 'conloca-dev-virtual-modules',\n resolveId(id) {\n // Dev-only config module for cms-handler.ts\n if (id === VIRTUAL_CONFIG_MODULE) {\n return RESOLVED_VIRTUAL_CONFIG;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n return id;\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return id;\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n return id;\n }\n if (id === VIRTUAL_CMS_SPA_ENTRY) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n if (id === `${cmsRoute}/cms-spa-entry.js`) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n return null;\n },\n load(id) {\n // Dev-only config module for cms-handler.ts\n if (id === RESOLVED_VIRTUAL_CONFIG) {\n return `export default ${JSON.stringify(spaConfig)};`;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n const absolutePuckPath = options.puckConfigPath.startsWith('.')\n ? `/${options.puckConfigPath.slice(2)}`\n : options.puckConfigPath;\n\n return puckConfigLoader(absolutePuckPath);\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return contentChangeListener();\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n if (options.schemasPath) {\n const absoluteSchemasPath = options.schemasPath.startsWith('.')\n ? `/${options.schemasPath.slice(2)}`\n : options.schemasPath;\n return schemasLoader(absoluteSchemasPath);\n }\n return 'export default {};';\n }\n if (id === RESOLVED_CMS_SPA_ENTRY) {\n // Get React refresh preamble (same pattern as puckConfigLoader)\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${preambleCode}\n\n// Import cms-spa main.tsx directly through Vite\n// Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)\nimport '@conloca/cms-spa/src/main.tsx';\n\n// Accept HMR\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n`;\n }\n return null;\n },\n },\n {\n name: 'conloca-content-watcher',\n async configureServer(server) {\n // Initialize content API using the extracted function\n const contentApi = await createContentAPI({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n });\n\n // Only add explicit watchers if content is outside the Astro project\n const { resolve } = await import('node:path');\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n const canvasAbsolute = resolve(options.canvasDir || './canvas');\n\n const foldersToWatch = [];\n\n if (!contentAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`,\n );\n foldersToWatch.push(options.contentRoot);\n } else {\n console.log(\n `[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`,\n );\n }\n\n if (!canvasAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`,\n );\n foldersToWatch.push(options.canvasDir || './canvas');\n } else {\n console.log(\n `[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`,\n );\n }\n\n if (foldersToWatch.length > 0) {\n server.watcher.add(foldersToWatch);\n }\n\n // Set up HMR for content changes using extracted handlers\n const handlers = createContentWatchHandlers(\n contentApi,\n {\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n },\n server.ws,\n );\n\n server.watcher.on('change', handlers.onChange);\n server.watcher.on('add', handlers.onAdd);\n server.watcher.on('unlink', handlers.onUnlink);\n },\n },\n ],\n },\n });\n\n // Inject unified CMS handler for all CMS routes\n // Single handler validates auth once, then routes to appropriate sub-handler\n injectRoute({\n pattern: `${cmsRoute}/[...path]`,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\n },\n\n 'astro:routes:resolved': ({ routes, logger }) => {\n // Check for route conflicts when routing is enabled\n if (!resolvedRoutingConfig?.enabled) return;\n\n const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));\n\n // Find file-based routes that may conflict with injected routes\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n // Skip routes from integrations (including our own)\n if (route.origin === 'internal') continue;\n\n // Skip our own injected page handler route\n const entrypoint = route.entrypoint || '';\n if (entrypoint.includes('page-handler.astro')) continue;\n\n // Check if this file-based route pattern matches any injected pattern\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: entrypoint || pattern,\n });\n }\n }\n\n if (conflicts.length === 0) return;\n\n // Handle conflicts based on onConflict setting\n const onConflict = resolvedRoutingConfig.onConflict;\n\n for (const conflict of conflicts) {\n const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;\n\n if (onConflict === 'error') {\n throw new Error(`[Conloca] ${message}`);\n }\n if (onConflict === 'warn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OACjB,QAAO,KAAK,QAAQ;;;GAK3B;EACF"}
1
+ {"version":3,"file":"index.mjs","names":["discoveries: HydrationDiscovery[]","hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]>","resolvedRoutingConfig: ResolvedRoutingConfig | undefined","resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>>","cmsSpaImport: string","astroRoot","contentAbsolute","resolve","conflicts: { injected: string; fileBased: string }[]"],"sources":["../src/lib/hydration-scanner.ts","../src/lib/route-utils.ts","../src/lib/routing-config.ts","../src/lib/virtual-module-generators.ts","../src/plugin-spa.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { basename, dirname, extname, join, resolve } from 'node:path'\nimport fg from 'fast-glob'\n\n/**\n * Result of scanning a component file for withHydration usage.\n */\nexport interface HydrationDiscovery {\n /** Component name derived from filename (PascalCase) */\n componentName: string\n /** Absolute path to the component file */\n filePath: string\n /** Hydration strategy extracted from withHydration call */\n strategy: 'load' | 'visible' | 'idle'\n}\n\n// Regex to check if file imports withHydration from @conloca/astro-cms or @conloca/astro-cms/hydration\n// This is faster than es-module-lexer for JSX files and avoids parse errors\nconst HYDRATION_IMPORT_PATTERN = /import\\s+\\{[^}]*withHydration[^}]*\\}\\s+from\\s+['\"]@conloca\\/astro-cms(?:\\/hydration)?['\"]/\n\n// Regex to find withHydration calls and extract strategy\n// Matches: withHydration(ComponentName, 'strategy') or withHydration(ComponentName, \"strategy\")\nconst HYDRATION_PATTERN = /withHydration\\s*\\(\\s*\\w+\\s*,\\s*['\"](\\w+)['\"]\\s*\\)/g\n\n// Valid hydration strategies\nconst VALID_STRATEGIES = new Set(['load', 'visible', 'idle'])\n\n/**\n * Derives component scan paths from puckConfigPath.\n *\n * Convention: puckConfigPath directory + '/components/puck'\n * Example: './src/puck.config.tsx' -> './src/components/puck'\n *\n * If explicitPaths provided, they extend (not replace) the auto-discovered path.\n *\n * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')\n * @param explicitPaths - Optional additional paths to scan\n * @returns Array of paths to scan for hydratable components\n */\nexport function deriveComponentPaths(\n puckConfigPath: string,\n explicitPaths?: string[]\n): string[] {\n const puckDir = dirname(puckConfigPath)\n const defaultScanPath = join(puckDir, 'components', 'puck')\n\n if (explicitPaths && explicitPaths.length > 0) {\n return [defaultScanPath, ...explicitPaths]\n }\n return [defaultScanPath]\n}\n\n/**\n * Derives a PascalCase component name from a file path.\n *\n * @param filePath - Absolute path to the component file\n * @returns Component name in PascalCase\n *\n * @example\n * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')\n * // => 'TestimonialGrid'\n *\n * deriveComponentName('/src/components/puck/blog-post-grid.tsx')\n * // => 'BlogPostGrid'\n */\nfunction deriveComponentName(filePath: string): string {\n const filename = basename(filePath, extname(filePath))\n // Convert kebab-case to PascalCase if needed\n if (filename.includes('-')) {\n return filename\n .split('-')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n }\n // Ensure first letter is uppercase\n return filename.charAt(0).toUpperCase() + filename.slice(1)\n}\n\n/**\n * Scans component directories for files using withHydration wrapper.\n *\n * This function performs static analysis to discover components marked\n * for hydration, without executing any component code.\n *\n * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])\n * @param projectRoot - Absolute path to the project root\n * @returns Array of discovered hydratable components with their strategies\n *\n * @example\n * ```typescript\n * const discoveries = await scanForHydratableComponents(\n * ['src/components/puck'],\n * '/path/to/project'\n * )\n * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]\n * ```\n */\nexport async function scanForHydratableComponents(\n componentPaths: string[],\n projectRoot: string\n): Promise<HydrationDiscovery[]> {\n const discoveries: HydrationDiscovery[] = []\n const seenNames = new Map<string, string>() // componentName -> first filePath\n\n for (const scanPath of componentPaths) {\n const absolutePath = resolve(projectRoot, scanPath)\n\n // Find all .tsx files in the directory and subdirectories\n const files = await fg('**/*.tsx', {\n cwd: absolutePath,\n absolute: true,\n onlyFiles: true,\n })\n\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8')\n\n // Fast path: check if file imports withHydration from @conloca/astro-cms\n // Using simple regex instead of es-module-lexer to avoid JSX parse errors\n if (!HYDRATION_IMPORT_PATTERN.test(content)) {\n continue\n }\n\n // Find withHydration calls with regex\n const matches = [...content.matchAll(HYDRATION_PATTERN)]\n\n if (matches.length === 0) {\n continue\n }\n\n if (matches.length > 1) {\n console.warn(\n `[Conloca Hydration] Multiple withHydration calls in ${filePath}. ` +\n 'Consider splitting into separate component files. Using first call.'\n )\n }\n\n const match = matches[0]\n const rawStrategy = match[1]\n\n // Validate strategy\n if (!VALID_STRATEGIES.has(rawStrategy)) {\n console.warn(\n `[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. ` +\n `Valid options: ${[...VALID_STRATEGIES].join(', ')}. Skipping component.`\n )\n continue\n }\n\n const strategy = rawStrategy as 'load' | 'visible' | 'idle'\n const componentName = deriveComponentName(filePath)\n\n // Check for naming conflicts\n const existingPath = seenNames.get(componentName)\n if (existingPath) {\n console.warn(\n `[Conloca Hydration] Duplicate component name '${componentName}'. ` +\n `Found in: ${existingPath} and ${filePath}. Using first occurrence.`\n )\n continue\n }\n\n seenNames.set(componentName, filePath)\n discoveries.push({\n componentName,\n filePath,\n strategy,\n })\n } catch (err) {\n // Log error but continue scanning other files\n console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err)\n }\n }\n }\n\n return discoveries\n}\n","/**\n * Extract slug from pathname given a route pattern.\n *\n * The slug is the portion of the pathname that comes after the\n * static prefix of the pattern.\n *\n * @param pathname - URL pathname (e.g., '/about', '/blog/post-1')\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns The extracted slug, or undefined for root paths\n *\n * @example\n * extractSlugFromPathname('/about', '/[...slug]') // 'about'\n * extractSlugFromPathname('/blog/post-1', '/blog/[...slug]') // 'post-1'\n * extractSlugFromPathname('/', '/[...slug]') // undefined\n * extractSlugFromPathname('/blog', '/blog/[...slug]') // undefined\n */\nexport function extractSlugFromPathname(pathname: string, pattern: string): string | undefined {\n // Pattern: /[...slug] -> prefix: ''\n // Pattern: /blog/[...slug] -> prefix: '/blog'\n // Pattern: /docs/[...path] -> prefix: '/docs'\n\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n // Remove prefix from pathname\n const slugPart = pathname.slice(prefix.length);\n\n // Remove leading slash\n const slug = slugPart.replace(/^\\//, '');\n\n // Empty string means root page (e.g., /blog for /blog/[...slug])\n // Return undefined for root to match [...slug] behavior\n return slug || undefined;\n}\n\n/**\n * Convert a slug back to a pathname given a route pattern.\n *\n * The inverse of extractSlugFromPathname.\n *\n * @param slug - The page slug (e.g., 'about', 'post-1'), or undefined for root\n * @param pattern - Route pattern (e.g., '/[...slug]', '/blog/[...slug]')\n * @returns Full URL pathname\n *\n * @example\n * pathnameFromSlug('about', '/[...slug]') // '/about'\n * pathnameFromSlug('post-1', '/blog/[...slug]') // '/blog/post-1'\n * pathnameFromSlug(undefined, '/[...slug]') // '/'\n * pathnameFromSlug(undefined, '/blog/[...slug]') // '/blog'\n */\nexport function pathnameFromSlug(slug: string | undefined, pattern: string): string {\n // Extract the static prefix before the dynamic segment\n const prefixMatch = pattern.match(/^(.*?)\\[/);\n const prefix = prefixMatch ? prefixMatch[1].replace(/\\/$/, '') : '';\n\n if (!slug) {\n // No slug means root of this pattern\n return prefix || '/';\n }\n\n // Combine prefix and slug\n return `${prefix}/${slug}`;\n}\n","import type { RouteConfig, RoutingConfig, RoutingConfigInput } from '../types.js';\n\n/**\n * Normalize routing config input to full RoutingConfig.\n *\n * Handles the `routing: true` shorthand, boolean values, and top-level layout option.\n *\n * @param input - The routing config input (boolean, object, or undefined)\n * @param topLevelLayout - Optional top-level layout path (enables routing when provided)\n * @returns Normalized RoutingConfig or undefined if not enabled\n */\nexport function normalizeRoutingConfig(\n input: RoutingConfigInput | undefined,\n topLevelLayout?: string\n): RoutingConfig | undefined {\n // If no routing config but layout provided, enable with defaults\n if (input === undefined && topLevelLayout) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n layout: topLevelLayout,\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === undefined) {\n return undefined;\n }\n\n if (input === true) {\n return {\n enabled: true,\n routes: {\n pages: {\n pattern: '/[...slug]',\n collection: 'pages',\n prerender: true,\n },\n },\n fallback: '404',\n onConflict: 'warn',\n };\n }\n\n if (input === false) {\n return { enabled: false };\n }\n\n return input;\n}\n\n/**\n * Apply defaults to a RouteConfig.\n *\n * Fills in missing optional fields with their default values.\n *\n * @param config - Partial route configuration\n * @returns Complete route configuration with all fields\n */\nexport function resolveRouteConfig(config: RouteConfig): Required<RouteConfig> {\n return {\n pattern: config.pattern,\n collection: config.collection ?? 'pages',\n layout: config.layout ?? '',\n prerender: config.prerender ?? true,\n meta: config.meta ?? {},\n dataBindings: config.dataBindings ?? { collections: [] },\n };\n}\n\n/**\n * Validate a route pattern.\n *\n * Ensures the pattern is a valid Astro route pattern.\n * Throws descriptive error if invalid.\n *\n * @param pattern - The route pattern to validate\n * @param routeName - Name of the route (for error messages)\n * @throws Error if pattern is invalid\n */\nexport function validateRoutePattern(pattern: string, routeName: string): void {\n if (!pattern.startsWith('/')) {\n throw new Error(`Route '${routeName}': pattern must start with '/', got '${pattern}'`);\n }\n\n // Check for valid Astro route syntax\n // Allow: a-zA-Z0-9, hyphen, underscore, slash, brackets, dots\n const invalidChars = pattern.match(/[^a-zA-Z0-9\\-_/[\\].]/g);\n if (invalidChars) {\n throw new Error(`Route '${routeName}': pattern contains invalid characters: ${invalidChars.join(', ')}`);\n }\n\n // Check for balanced brackets\n const openBrackets = (pattern.match(/\\[/g) || []).length;\n const closeBrackets = (pattern.match(/\\]/g) || []).length;\n if (openBrackets !== closeBrackets) {\n throw new Error(`Route '${routeName}': pattern has unbalanced brackets: '${pattern}'`);\n }\n}\n","import type { ResolvedRoutingConfig, RoutingConfig } from '../types.js';\n\n/**\n * Generate the virtual:conloca-routing-config module.\n *\n * Returns a module that exports the resolved routing configuration as default.\n *\n * @param config - Resolved routing configuration with all defaults applied\n * @returns JavaScript module code as a string\n */\nexport function generateRoutingConfigModule(config: ResolvedRoutingConfig): string {\n return `export default ${JSON.stringify(config, null, 2)};`;\n}\n\n/**\n * Generate the virtual:conloca-layout module.\n *\n * Returns a module that re-exports the layout component or exports undefined\n * if no layout is configured.\n *\n * Currently uses the first route's layout. Multi-layout support is future work.\n *\n * @param routing - Routing configuration (may be undefined if routing disabled)\n * @returns JavaScript module code as a string\n */\nexport function generateLayoutModule(routing: RoutingConfig | undefined): string {\n // Get layout from first route (for now - multi-layout is future work)\n const routes = routing?.routes || {};\n const firstRoute = Object.values(routes)[0];\n const layoutPath = firstRoute?.layout;\n\n if (layoutPath) {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = layoutPath.startsWith('.') ? `/${layoutPath.slice(2)}` : layoutPath;\n\n return `export { default } from '${absolutePath}';`;\n }\n\n return 'export default undefined;';\n}\n\n/**\n * Options for generating the page API module.\n */\nexport interface PageApiModuleOptions {\n contentRoot: string;\n canvasDir: string;\n /** Site name for content resolution. @default 'default' */\n siteName: string;\n /** Default locale for content resolution. @default 'en' */\n locale: string;\n}\n\n/**\n * Generate the virtual:conloca-page-api module.\n *\n * Returns a module that provides page loading functions wrapping ContentAPI:\n * - getAllPages(collection?) - For getStaticPaths()\n * - getPage(pathname, collection?) - For page data loading\n * - pageExists(pathname, collection?) - For 404 checks\n * - contentOptions - Configuration for ContentAPI (for MDX evaluation)\n *\n * @param options - Configuration for ContentAPI initialization\n * @returns JavaScript module code as a string\n */\nexport function generatePageApiModule(options: PageApiModuleOptions): string {\n return `\nimport { createContentAPI } from '@conloca/content-api/node';\n\n// Export content options for MDX evaluation and other ContentAPI uses\nexport const contentOptions = {\n contentRoot: '${options.contentRoot}',\n canvasDir: '${options.canvasDir}',\n siteName: '${options.siteName}',\n locale: '${options.locale}',\n};\n\n// Initialize ContentAPI with configured paths\nconst contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n});\n\n// Get site instance for page operations (configured via routing.siteName)\nconst site = contentApi.getSite(contentOptions.siteName);\nconst locale = contentOptions.locale; // Configured via routing.locale\n\n/**\n * Get all pages for static path generation.\n * @param collection - Optional collection filter\n */\nexport async function getAllPages(collection) {\n const pages = [];\n\n // listPages is a generator that yields ContentManifest objects\n for (const manifest of site.listPages(locale)) {\n // Get the localized data for pathname/title\n const localeData = manifest.locales[locale];\n if (!localeData) continue;\n\n const pathname = localeData.pathname || '/' + manifest.id.replace(/^index$/, '');\n\n // Collection resolution: explicit collection in manifest, or default 'pages'\n const resolvedCollection = manifest.collection || 'pages';\n\n // Filter by requested collection\n if (collection && resolvedCollection !== collection) continue;\n\n pages.push({\n id: manifest.id,\n pathname: pathname,\n title: localeData.meta?.title || manifest.id,\n collection: resolvedCollection,\n meta: localeData.meta || {},\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n });\n }\n\n return pages;\n}\n\n/**\n * Get pages matching a path prefix.\n * @param prefix - Path prefix to match (e.g., '/blog/')\n * @param options - Optional sort and limit settings\n * @returns Array of PageReference objects\n */\nexport async function getPagesByPrefix(prefix, options = {}) {\n const allPages = await getAllPages();\n\n let filtered = allPages.filter(page =>\n page.pathname.startsWith(prefix) &&\n page.pathname !== prefix && // Exclude the listing page itself\n page.pathname !== prefix.slice(0, -1) // Exclude without trailing slash\n );\n\n // Sort by date (newest first by default)\n if (options.sort === 'date-desc' || !options.sort) {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateB).getTime() - new Date(dateA).getTime();\n });\n } else if (options.sort === 'date-asc') {\n filtered.sort((a, b) => {\n const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);\n const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);\n return new Date(dateA).getTime() - new Date(dateB).getTime();\n });\n } else if (options.sort === 'title') {\n filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));\n }\n\n if (options.limit && options.limit > 0) {\n filtered = filtered.slice(0, options.limit);\n }\n\n return filtered;\n}\n\n/**\n * Load full page data for rendering.\n * @param pathname - URL pathname (e.g., '/about')\n * @param collection - Optional collection to search in\n */\nexport async function getPage(pathname, collection) {\n // Use site.getByPathname which returns ContentManifest (metadata only)\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Optionally filter by collection\n if (collection && manifest.collection !== collection) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n // Get the full content with locale data\n const content = await contentApi.getLocalized(manifest.id, locale);\n\n if (!content) {\n const error = new Error(\\`Page not found: \\${pathname}\\`);\n error.code = 'PAGE_NOT_FOUND';\n throw error;\n }\n\n const localeData = content.localized;\n const meta = localeData.meta || {};\n\n return {\n id: manifest.id,\n title: meta.title || manifest.id,\n description: meta.description,\n pathname: pathname,\n puckData: localeData.content?.puckData,\n collection: manifest.collection || collection || 'pages',\n route: {\n name: 'pages', // Will be set by caller\n pattern: '/[...slug]',\n meta: {},\n },\n meta: meta,\n timestamps: {\n created: localeData.created,\n modified: localeData.modified,\n },\n };\n}\n\n/**\n * Check if a page exists without loading full data.\n * @param pathname - URL pathname\n * @param collection - Optional collection filter\n */\nexport function pageExists(pathname, collection) {\n // getByPathname is synchronous - returns ContentManifest | null\n const manifest = site.getByPathname(pathname, locale);\n\n if (!manifest) {\n return false;\n }\n\n // If collection filter specified, verify it matches\n if (collection && manifest.collection !== collection) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get all entries from a data collection.\n * @param collection - Data collection name\n * @param localeOverride - Optional locale override (defaults to configured locale)\n * @returns Array of DataCollectionEntry objects\n */\nexport async function getDataCollection(collection, localeOverride) {\n const targetLocale = localeOverride || locale;\n const entries = [];\n\n // List all manifests in the collection\n for (const manifest of contentApi.data.listContent({ collection })) {\n // Get localized data for each entry\n const localized = await contentApi.getLocalized(manifest.id, targetLocale);\n if (localized) {\n entries.push({\n id: manifest.id,\n name: manifest.name,\n data: localized.content?.data || {},\n meta: manifest.meta || {},\n });\n }\n }\n\n return entries;\n}\n`;\n}\n\n/**\n * Generate the virtual:conloca-puck-config module.\n *\n * Returns a module that re-exports the Puck configuration.\n * This is separate from the HMR-enabled puck-entry.js used by the CMS SPA.\n *\n * @param puckConfigPath - Path to the puck config module\n * @returns JavaScript module code as a string\n */\nexport function generatePuckConfigModule(puckConfigPath: string): string {\n // Convert relative path to absolute for Vite resolution\n // ./src/... -> /src/...\n const absolutePath = puckConfigPath.startsWith('.') ? `/${puckConfigPath.slice(2)}` : puckConfigPath\n\n return `export { default } from '${absolutePath}';`\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { UIConfig } from '@conloca/cms-spa';\nimport { createContentAPI, createContentWatchHandlers } from '@conloca/content-api/node';\nimport viteReact from '@vitejs/plugin-react';\nimport type { AstroIntegration } from 'astro';\nimport { searchForWorkspaceRoot } from 'vite';\n\nimport { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';\nimport { normalizeRoutingConfig, resolveRouteConfig } from './lib/routing-config.js';\n\n// Get the directory of this module to resolve page-handler.astro\n// Works from both src/ (dev) and dist/ (published) since build copies the file\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst PAGE_HANDLER_PATH = join(__dirname, 'handlers', 'page-handler.astro');\n\nimport {\n generateLayoutModule,\n generatePageApiModule,\n generatePuckConfigModule,\n generateRoutingConfigModule,\n} from './lib/virtual-module-generators.js';\nimport type { ResolvedRoutingConfig, RoutingConfigInput, TemplateConfig } from './types.js';\n\n// Virtual module for passing config from plugin to route handler\nconst VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';\nconst RESOLVED_VIRTUAL_CONFIG = `\\0${VIRTUAL_CONFIG_MODULE}`;\n\n// Virtual module IDs for routing system\nconst VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';\nconst VIRTUAL_LAYOUT = 'virtual:conloca-layout';\nconst VIRTUAL_PAGE_API = 'virtual:conloca-page-api';\nconst VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';\n\n// Resolved IDs (with \\0 prefix to prevent file resolution)\nconst RESOLVED_ROUTING_CONFIG = `\\0${VIRTUAL_ROUTING_CONFIG}`;\nconst RESOLVED_LAYOUT = `\\0${VIRTUAL_LAYOUT}`;\nconst RESOLVED_PAGE_API = `\\0${VIRTUAL_PAGE_API}`;\nconst RESOLVED_PUCK_CONFIG = `\\0${VIRTUAL_PUCK_CONFIG}`;\n\n// Virtual modules for hydration system\nconst VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';\nconst VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';\nconst RESOLVED_HYDRATION_REGISTRY = `\\0${VIRTUAL_HYDRATION_REGISTRY}`;\nconst RESOLVED_HYDRATION_ENTRY = `\\0${VIRTUAL_HYDRATION_ENTRY}`;\n\n// Virtual module for CMS SPA source loading (dev only)\nconst VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';\nconst RESOLVED_CMS_SPA_ENTRY = `\\0${VIRTUAL_CMS_SPA_ENTRY}`;\n\nexport interface ConlocaCMSOptions extends Omit<UIConfig, 'basename'> {\n contentRoot: string;\n canvasDir?: string;\n route?: string; // Default: /__cms\n puckConfigPath: string; // Path to the puck config module (should be .tsx file with React components)\n schemasPath?: string; // Path to the schemas module (exports { dataSchemas, pageSchemas })\n\n /**\n * Default layout for content pages.\n * When provided without routing config, enables routing with catch-all pattern.\n * For multi-route setups, use routing.routes.{name}.layout instead.\n *\n * @example './src/layouts/Layout.astro'\n */\n layout?: string;\n\n routing?: RoutingConfigInput; // Content page routing configuration\n templates?: Record<string, TemplateConfig>; // Page creation templates\n\n /**\n * Paths to scan for hydratable components.\n * Components using withHydration() in these directories are auto-discovered.\n *\n * @example ['src/components/puck']\n */\n componentPaths?: string[];\n\n /**\n * Path to the assets directory for image uploads.\n * When provided, enables the Media Library and asset upload API routes.\n *\n * @example 'src/assets/uploads'\n */\n assetsPath?: string;\n}\n\n// Template for content change listener virtual module\nconst contentChangeListener = () => {\n return `\n// Content change listener that uses Vite HMR\nif (import.meta.hot) {\n import.meta.hot.on('conloca:content-update', (data) => {\n console.log('[Conloca CMS] Content updated, invalidating cache:', data);\n \n // Get the query client from the global scope and invalidate\n if (window.__QUERY_CLIENT__) {\n window.__QUERY_CLIENT__.invalidateQueries();\n }\n });\n}\n\nexport default {};\n`;\n};\n\n// Template for the puck config loader virtual module\nconst puckConfigLoader = (absolutePuckPath: string) => {\n // Get the exact preamble code from the React plugin\n // The base needs to be '/' so the import becomes '/@react-refresh'\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\n // We need to ensure the preamble executes before ANY module evaluation\n // So we'll use a dynamic import after the preamble is set up\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${preambleCode}\n\n// Import the setPuckConfig function from cms-spa\nimport { setPuckConfig } from '@conloca/cms-spa/puck-config';\n\n// Now dynamically import the config after preamble is ready\nconst puckConfigPromise = import('${absolutePuckPath}');\n\n// Handle the initial load\npuckConfigPromise.then(module => {\n const puckConfig = module.default;\n setPuckConfig(puckConfig);\n\n // Hook into React Fast Refresh to detect component updates\n if (window.__registerBeforePerformReactRefresh) {\n window.__registerBeforePerformReactRefresh(async () => {\n // Re-import the config module to get updated components\n const newModule = await import('${absolutePuckPath}');\n setPuckConfig(newModule.default);\n });\n }\n});\n\n// Accept HMR for this module itself\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\n// Export the promise so the module has a default export\nexport default puckConfigPromise.then(m => m.default);\n`;\n};\n\n// Template for the schemas loader virtual module\nconst schemasLoader = (absoluteSchemasPath: string) => {\n return `\nimport { setPageSchemas } from '@conloca/cms-spa/page-schemas';\nimport * as schemas from '${absoluteSchemasPath}';\n\nif (schemas.pageSchemas) {\n setPageSchemas(schemas.pageSchemas);\n}\n\nif (import.meta.hot) {\n import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {\n if (newModule?.pageSchemas) {\n setPageSchemas(newModule.pageSchemas);\n }\n });\n}\n\nexport default schemas;\n`;\n};\n\nexport function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {\n const cmsRoute = options.route || '/__cms';\n\n // Normalize routing config and resolve defaults\n // Pass top-level layout to enable routing when layout provided without explicit routing config\n const routingConfig = normalizeRoutingConfig(options.routing, options.layout);\n\n // Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths\n // Scanner handles missing directories gracefully (fast-glob returns empty array)\n const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);\n\n // Scan for hydratable components - this promise is awaited in the virtual module loader\n const hydrationDiscoveriesPromise: Promise<HydrationDiscovery[]> = scanForHydratableComponents(\n componentPaths,\n process.cwd(),\n ).then((discoveries) => {\n if (discoveries.length > 0) {\n console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);\n }\n return discoveries;\n });\n\n // Build resolved routing config with all defaults applied\n let resolvedRoutingConfig: ResolvedRoutingConfig | undefined;\n if (routingConfig?.enabled !== false && routingConfig) {\n const resolvedRoutes: Record<string, Required<import('./types.js').RouteConfig>> = {};\n for (const [name, config] of Object.entries(routingConfig.routes || {})) {\n resolvedRoutes[name] = resolveRouteConfig(config);\n }\n resolvedRoutingConfig = {\n enabled: routingConfig.enabled ?? true,\n routes: resolvedRoutes,\n fallback: routingConfig.fallback ?? '404',\n onConflict: routingConfig.onConflict ?? 'warn',\n siteName: routingConfig.siteName ?? 'default',\n locale: routingConfig.locale ?? 'en',\n };\n }\n\n // SPA config passed to route handler via virtual module\n // This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true\n const spaConfig = {\n basename: cmsRoute,\n apiBaseUrl: `${cmsRoute}/api`,\n siteBaseUrl: options.siteBaseUrl,\n enableDevtools: options.enableDevtools ?? true,\n queryClientOptions: options.queryClientOptions,\n schemasPath: options.schemasPath,\n projectRoot: process.cwd(),\n templates: options.templates,\n };\n\n return {\n name: '@conloca/astro-cms',\n hooks: {\n 'astro:config:setup': ({ updateConfig, injectRoute, command, logger }) => {\n // Auto-inject fs.allow for external contentRoot (dev mode only)\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n\n if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {\n logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);\n\n updateConfig({\n vite: {\n server: {\n fs: {\n allow: [\n searchForWorkspaceRoot(process.cwd()), // Preserve Vite default\n contentAbsolute,\n ],\n },\n },\n },\n });\n }\n\n // Always apply SSR externalization for native modules (needed for both dev and build)\n // This must be outside the dev-only block to fix build errors\n updateConfig({\n vite: {\n ssr: {\n // Force these packages through Vite's resolver during SSR\n // This ensures symlinked packages use the consumer's React, not their own\n // Without this, symlinked packages resolve React from their node_modules\n noExternal: ['@conloca/astro-cms', '@conloca/cms-spa'],\n // Externalize native Node modules for SSR builds\n // These cannot be bundled and must be available at runtime\n external: ['@node-rs/xxhash'],\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\n {\n name: 'conloca-routing-virtual-modules',\n resolveId(id) {\n // Routing virtual modules (work in both dev and build)\n if (id === VIRTUAL_ROUTING_CONFIG) {\n return RESOLVED_ROUTING_CONFIG;\n }\n if (id === VIRTUAL_LAYOUT) {\n return RESOLVED_LAYOUT;\n }\n if (id === VIRTUAL_PAGE_API) {\n return RESOLVED_PAGE_API;\n }\n if (id === VIRTUAL_PUCK_CONFIG) {\n return RESOLVED_PUCK_CONFIG;\n }\n // Hydration virtual modules\n if (id === VIRTUAL_HYDRATION_REGISTRY) {\n return RESOLVED_HYDRATION_REGISTRY;\n }\n if (id === VIRTUAL_HYDRATION_ENTRY) {\n return RESOLVED_HYDRATION_ENTRY;\n }\n return null;\n },\n async load(id) {\n // Routing virtual modules\n if (id === RESOLVED_ROUTING_CONFIG) {\n if (resolvedRoutingConfig) {\n return generateRoutingConfigModule(resolvedRoutingConfig);\n }\n // Return disabled config if routing not configured\n return 'export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };';\n }\n if (id === RESOLVED_LAYOUT) {\n return generateLayoutModule(routingConfig);\n }\n if (id === RESOLVED_PAGE_API) {\n return generatePageApiModule({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n siteName: resolvedRoutingConfig?.siteName ?? 'default',\n locale: resolvedRoutingConfig?.locale ?? 'en',\n });\n }\n if (id === RESOLVED_PUCK_CONFIG) {\n return generatePuckConfigModule(options.puckConfigPath);\n }\n // Hydration virtual modules\n if (id === RESOLVED_HYDRATION_REGISTRY) {\n // Always scan - paths are auto-derived from puckConfigPath\n const discoveries = await hydrationDiscoveriesPromise;\n if (discoveries.length > 0) {\n const entries = discoveries.map((d) => {\n // Convert absolute path to Vite-friendly path\n const relativePath = d.filePath.replace(process.cwd(), '');\n return ` '${d.componentName}': {\n loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),\n strategy: '${d.strategy}',\n }`;\n });\n return `// Generated by @conloca/astro-cms scanner\nexport const componentRegistry = {\n${entries.join(',\\n')}\n};`;\n }\n\n // No hydratable components found - return empty registry\n return 'export const componentRegistry = {};';\n }\n if (id === RESOLVED_HYDRATION_ENTRY) {\n // Generate entry point that imports registry and calls initHydration\n return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'\nimport { componentRegistry } from 'virtual:conloca-hydration-registry'\n\n// Auto-initialize hydration when this module loads\ninitHydration(componentRegistry)\n`;\n }\n return null;\n },\n },\n ],\n },\n });\n\n // Content page routes - works in both dev and build\n if (resolvedRoutingConfig?.enabled) {\n for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {\n logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);\n injectRoute({\n pattern: routeConfig.pattern,\n entrypoint: PAGE_HANDLER_PATH,\n prerender: routeConfig.prerender,\n });\n }\n }\n\n // Only inject CMS admin routes and dev-specific config in dev mode\n if (command !== 'dev') return;\n\n // Pass options via Vite define for API routes\n updateConfig({\n vite: {\n define: {\n 'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),\n 'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),\n 'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),\n 'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),\n },\n resolve: {\n // Dedupe React to avoid multiple instances when using symlinked packages\n // This prevents \"Cannot read properties of null (reading 'useMemo')\" errors\n dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime', '@measured/puck'],\n },\n optimizeDeps: {\n // Exclude the puck config from optimization to avoid the outdated dep error\n exclude: [options.puckConfigPath],\n // Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization\n // which causes React dual-instance issues when Vite discovers new deps dynamically\n include: [\n // React core - must be pre-bundled together\n 'react',\n 'react-dom',\n 'react-dom/client',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n // CMS dependencies\n '@mdxeditor/editor',\n '@measured/puck',\n '@tanstack/react-query',\n '@tanstack/react-query-devtools',\n 'react-router-dom',\n '@radix-ui/react-dialog',\n '@radix-ui/react-select',\n 'lucide-react',\n 'clsx',\n 'tailwind-merge',\n // Content processing\n 'zod',\n 'yaml',\n 'nanoid',\n 'sort-keys',\n // MDX processing\n '@mdx-js/mdx',\n 'remark-frontmatter',\n 'remark-gfm',\n 'remark-mdx-frontmatter',\n ],\n },\n plugins: [\n {\n name: 'conloca-dev-virtual-modules',\n resolveId(id) {\n // Dev-only config module for cms-handler.ts\n if (id === VIRTUAL_CONFIG_MODULE) {\n return RESOLVED_VIRTUAL_CONFIG;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n return id;\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return id;\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n return id;\n }\n if (id === VIRTUAL_CMS_SPA_ENTRY) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n if (id === `${cmsRoute}/cms-spa-entry.js`) {\n return RESOLVED_CMS_SPA_ENTRY;\n }\n return null;\n },\n load(id) {\n // Dev-only config module for cms-handler.ts\n if (id === RESOLVED_VIRTUAL_CONFIG) {\n return `export default ${JSON.stringify(spaConfig)};`;\n }\n if (id === `${cmsRoute}/puck-entry.js`) {\n const absolutePuckPath = options.puckConfigPath.startsWith('.')\n ? `/${options.puckConfigPath.slice(2)}`\n : options.puckConfigPath;\n\n return puckConfigLoader(absolutePuckPath);\n }\n if (id === `${cmsRoute}/content-listener.js`) {\n return contentChangeListener();\n }\n if (id === `${cmsRoute}/schemas-entry.js`) {\n if (options.schemasPath) {\n const absoluteSchemasPath = options.schemasPath.startsWith('.')\n ? `/${options.schemasPath.slice(2)}`\n : options.schemasPath;\n return schemasLoader(absoluteSchemasPath);\n }\n return 'export default {};';\n }\n if (id === RESOLVED_CMS_SPA_ENTRY) {\n const preambleCode = viteReact.preambleCode.replace('__BASE__', '/');\n\n // Detect whether cms-spa source is available (workspace mode)\n // vs only dist/ (npm install)\n let cmsSpaImport: string;\n try {\n const cmsSpaPackageJsonPath = import.meta.resolve('@conloca/cms-spa/package.json');\n const cmsSpaDir = dirname(\n cmsSpaPackageJsonPath.startsWith('file://')\n ? fileURLToPath(cmsSpaPackageJsonPath)\n : cmsSpaPackageJsonPath,\n );\n const srcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\n\n if (existsSync(srcMainPath)) {\n // Workspace mode: import source for HMR\n cmsSpaImport = `import '${srcMainPath}';`;\n } else {\n // npm mode: import pre-built SPA entry\n cmsSpaImport = \"import '@conloca/cms-spa';\";\n }\n } catch {\n // Fallback: use package import\n cmsSpaImport = \"import '@conloca/cms-spa';\";\n }\n\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${preambleCode}\n\n// Import cms-spa through Vite\n// Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)\n${cmsSpaImport}\n\n// Accept HMR\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n`;\n }\n return null;\n },\n },\n {\n name: 'conloca-content-watcher',\n async configureServer(server) {\n // Initialize content API using the extracted function\n const contentApi = await createContentAPI({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n });\n\n // Only add explicit watchers if content is outside the Astro project\n const { resolve } = await import('node:path');\n const astroRoot = process.cwd();\n const contentAbsolute = resolve(options.contentRoot);\n const canvasAbsolute = resolve(options.canvasDir || './canvas');\n\n const foldersToWatch = [];\n\n if (!contentAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`,\n );\n foldersToWatch.push(options.contentRoot);\n } else {\n console.log(\n `[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`,\n );\n }\n\n if (!canvasAbsolute.startsWith(astroRoot)) {\n console.log(\n `[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`,\n );\n foldersToWatch.push(options.canvasDir || './canvas');\n } else {\n console.log(\n `[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`,\n );\n }\n\n if (foldersToWatch.length > 0) {\n server.watcher.add(foldersToWatch);\n }\n\n // Set up HMR for content changes using extracted handlers\n const handlers = createContentWatchHandlers(\n contentApi,\n {\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n },\n server.ws,\n );\n\n server.watcher.on('change', handlers.onChange);\n server.watcher.on('add', handlers.onAdd);\n server.watcher.on('unlink', handlers.onUnlink);\n },\n },\n ],\n },\n });\n\n // Inject unified CMS handler for all CMS routes\n // Single handler validates auth once, then routes to appropriate sub-handler\n injectRoute({\n pattern: `${cmsRoute}/[...path]`,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: '@conloca/astro-cms/cms-handler',\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\n },\n\n 'astro:routes:resolved': ({ routes, logger }) => {\n // Check for route conflicts when routing is enabled\n if (!resolvedRoutingConfig?.enabled) return;\n\n const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));\n\n // Find file-based routes that may conflict with injected routes\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n // Skip routes from integrations (including our own)\n if (route.origin === 'internal') continue;\n\n // Skip our own injected page handler route\n const entrypoint = route.entrypoint || '';\n if (entrypoint.includes('page-handler.astro')) continue;\n\n // Check if this file-based route pattern matches any injected pattern\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: entrypoint || pattern,\n });\n }\n }\n\n if (conflicts.length === 0) return;\n\n // Handle conflicts based on onConflict setting\n const onConflict = resolvedRoutingConfig.onConflict;\n\n for (const conflict of conflicts) {\n const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;\n\n if (onConflict === 'error') {\n throw new Error(`[Conloca] ${message}`);\n }\n if (onConflict === 'warn') {\n logger.warn(message);\n }\n // 'silent' - do nothing\n }\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAM,2BAA2B;AAIjC,MAAM,oBAAoB;AAG1B,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAO,CAAC;;;;;;;;;;;;;AAc7D,SAAgB,qBACd,gBACA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KAGjC,MAAM,aAAa,MAAM,cAAc;AACvC,SAAI,WAAW,SAAS,qBAAqB,CAAE;KAG/C,MAAM,UAAU,MAAM;AACtB,SAAI,iBAAiB,IAAI,QAAQ,CAC/B,WAAU,KAAK;MACb,UAAU;MACV,WAAW,cAAc;MAC1B,CAAC;;AAIN,QAAI,UAAU,WAAW,EAAG;IAG5B,MAAM,aAAa,sBAAsB;AAEzC,SAAK,MAAM,YAAY,WAAW;KAChC,MAAM,UAAU,oBAAoB,SAAS,SAAS,uBAAuB,SAAS,UAAU;AAEhG,SAAI,eAAe,QACjB,OAAM,IAAI,MAAM,aAAa,UAAU;AAEzC,SAAI,eAAe,OACjB,QAAO,KAAK,QAAQ;;;GAK3B;EACF"}
@@ -58,4 +58,4 @@ function conlocaLoader(options) {
58
58
 
59
59
  //#endregion
60
60
  export { conlocaLoader as t };
61
- //# sourceMappingURL=loader-C6JF2toW.mjs.map
61
+ //# sourceMappingURL=loader-BYmsavWc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader-C6JF2toW.mjs","names":["dataContent: Record<string, unknown> | undefined","puckData: unknown | undefined","data: Record<string, unknown>"],"sources":["../src/loader.ts"],"sourcesContent":["import { createContentAPI } from '@conloca/content-api/node';\nimport type { Loader, LoaderContext } from 'astro/loaders';\n\nexport interface ConlocaLoaderOptions {\n collection: string;\n contentRoot: string;\n site?: string;\n /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */\n kind?: 'page' | 'block' | 'data';\n}\n\n/**\n * Custom Astro content loader for Conloca CMS.\n * Loads content from the Conloca content directory into Astro collections.\n */\nexport function conlocaLoader(options: ConlocaLoaderOptions): Loader {\n return {\n name: 'conloca-loader',\n async load(context: LoaderContext): Promise<void> {\n const { store, parseData, generateDigest, logger } = context;\n\n // Create content API instance\n const api = await createContentAPI({ contentRoot: options.contentRoot });\n\n // Use provided kind, or fall back to inferring from collection name\n const kind = options.kind ?? (options.collection === 'blocks' ? 'block' : 'page');\n\n // List all content for this collection\n // Note: blocks and data don't have a site, so only pass site for pages\n const content = Array.from(\n api.listAllContent({\n collection: options.collection,\n kind,\n site: kind === 'page' ? options.site : undefined,\n }),\n );\n\n store.clear();\n\n for (const manifest of content) {\n for (const [locale, localeVersion] of Object.entries(manifest.locales)) {\n if (!localeVersion) continue;\n\n const entryId = `${manifest.id}/${locale}`;\n\n // For data and page collections, fetch full content to get the actual content fields\n let dataContent: Record<string, unknown> | undefined;\n let puckData: unknown | undefined;\n\n if (kind === 'data') {\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.data) {\n dataContent = fullContent.localized.content.data;\n }\n } else if (kind === 'page') {\n // For page collections, fetch full content to get puckData\n // This enables getCollection('pages') to return entries with puckData included\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.puckData) {\n puckData = fullContent.localized.content.puckData;\n }\n }\n\n const data: Record<string, unknown> = {\n id: manifest.id,\n locale,\n ...(localeVersion.pathname && { pathname: localeVersion.pathname }),\n ...(localeVersion.name && { name: localeVersion.name }),\n ...localeVersion.meta,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n // Include the data content for data collections\n ...(dataContent && { data: dataContent }),\n };\n\n // Include puckData for page collections (added separately to avoid spread type issues)\n if (puckData !== undefined) {\n data.puckData = puckData;\n }\n\n const parsedData = await parseData({ id: entryId, data });\n\n store.set({\n id: entryId,\n data: parsedData,\n digest: generateDigest(localeVersion.etag),\n });\n }\n }\n\n logger.info(`Loaded ${store.keys().length} entries from ${options.collection}`);\n },\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,cAAc,SAAuC;AACnE,QAAO;EACL,MAAM;EACN,MAAM,KAAK,SAAuC;GAChD,MAAM,EAAE,OAAO,WAAW,gBAAgB,WAAW;GAGrD,MAAM,MAAM,MAAM,iBAAiB,EAAE,aAAa,QAAQ,aAAa,CAAC;GAGxE,MAAM,OAAO,QAAQ,SAAS,QAAQ,eAAe,WAAW,UAAU;GAI1E,MAAM,UAAU,MAAM,KACpB,IAAI,eAAe;IACjB,YAAY,QAAQ;IACpB;IACA,MAAM,SAAS,SAAS,QAAQ,OAAO;IACxC,CAAC,CACH;AAED,SAAM,OAAO;AAEb,QAAK,MAAM,YAAY,QACrB,MAAK,MAAM,CAAC,QAAQ,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,EAAE;AACtE,QAAI,CAAC,cAAe;IAEpB,MAAM,UAAU,GAAG,SAAS,GAAG,GAAG;IAGlC,IAAIA;IACJ,IAAIC;AAEJ,QAAI,SAAS,QAAQ;KACnB,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,KAClC,eAAc,YAAY,UAAU,QAAQ;eAErC,SAAS,QAAQ;KAG1B,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,SAClC,YAAW,YAAY,UAAU,QAAQ;;IAI7C,MAAMC,OAAgC;KACpC,IAAI,SAAS;KACb;KACA,GAAI,cAAc,YAAY,EAAE,UAAU,cAAc,UAAU;KAClE,GAAI,cAAc,QAAQ,EAAE,MAAM,cAAc,MAAM;KACtD,GAAG,cAAc;KACjB,WAAW,cAAc;KACzB,aAAa,cAAc;KAE3B,GAAI,eAAe,EAAE,MAAM,aAAa;KACzC;AAGD,QAAI,aAAa,OACf,MAAK,WAAW;IAGlB,MAAM,aAAa,MAAM,UAAU;KAAE,IAAI;KAAS;KAAM,CAAC;AAEzD,UAAM,IAAI;KACR,IAAI;KACJ,MAAM;KACN,QAAQ,eAAe,cAAc,KAAK;KAC3C,CAAC;;AAIN,UAAO,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,gBAAgB,QAAQ,aAAa;;EAElF"}
1
+ {"version":3,"file":"loader-BYmsavWc.mjs","names":["dataContent: Record<string, unknown> | undefined","puckData: unknown | undefined","data: Record<string, unknown>"],"sources":["../src/loader.ts"],"sourcesContent":["import { createContentAPI } from '@conloca/content-api/node';\nimport type { Loader, LoaderContext } from 'astro/loaders';\n\nexport interface ConlocaLoaderOptions {\n collection: string;\n contentRoot: string;\n site?: string;\n /** Collection kind. If not provided, defaults to 'block' for 'blocks' collection, 'page' otherwise. */\n kind?: 'page' | 'block' | 'data';\n}\n\n/**\n * Custom Astro content loader for Conloca CMS.\n * Loads content from the Conloca content directory into Astro collections.\n */\nexport function conlocaLoader(options: ConlocaLoaderOptions): Loader {\n return {\n name: 'conloca-loader',\n async load(context: LoaderContext): Promise<void> {\n const { store, parseData, generateDigest, logger } = context;\n\n // Create content API instance\n const api = await createContentAPI({ contentRoot: options.contentRoot });\n\n // Use provided kind, or fall back to inferring from collection name\n const kind = options.kind ?? (options.collection === 'blocks' ? 'block' : 'page');\n\n // List all content for this collection\n // Note: blocks and data don't have a site, so only pass site for pages\n const content = Array.from(\n api.listAllContent({\n collection: options.collection,\n kind,\n site: kind === 'page' ? options.site : undefined,\n }),\n );\n\n store.clear();\n\n for (const manifest of content) {\n for (const [locale, localeVersion] of Object.entries(manifest.locales)) {\n if (!localeVersion) continue;\n\n const entryId = `${manifest.id}/${locale}`;\n\n // For data and page collections, fetch full content to get the actual content fields\n let dataContent: Record<string, unknown> | undefined;\n let puckData: unknown | undefined;\n\n if (kind === 'data') {\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.data) {\n dataContent = fullContent.localized.content.data;\n }\n } else if (kind === 'page') {\n // For page collections, fetch full content to get puckData\n // This enables getCollection('pages') to return entries with puckData included\n const fullContent = await api.getLocalized(manifest.id, locale);\n if (fullContent?.localized.content?.puckData) {\n puckData = fullContent.localized.content.puckData;\n }\n }\n\n const data: Record<string, unknown> = {\n id: manifest.id,\n locale,\n ...(localeVersion.pathname && { pathname: localeVersion.pathname }),\n ...(localeVersion.name && { name: localeVersion.name }),\n ...localeVersion.meta,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n // Include the data content for data collections\n ...(dataContent && { data: dataContent }),\n };\n\n // Include puckData for page collections (added separately to avoid spread type issues)\n if (puckData !== undefined) {\n data.puckData = puckData;\n }\n\n const parsedData = await parseData({ id: entryId, data });\n\n store.set({\n id: entryId,\n data: parsedData,\n digest: generateDigest(localeVersion.etag),\n });\n }\n }\n\n logger.info(`Loaded ${store.keys().length} entries from ${options.collection}`);\n },\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,cAAc,SAAuC;AACnE,QAAO;EACL,MAAM;EACN,MAAM,KAAK,SAAuC;GAChD,MAAM,EAAE,OAAO,WAAW,gBAAgB,WAAW;GAGrD,MAAM,MAAM,MAAM,iBAAiB,EAAE,aAAa,QAAQ,aAAa,CAAC;GAGxE,MAAM,OAAO,QAAQ,SAAS,QAAQ,eAAe,WAAW,UAAU;GAI1E,MAAM,UAAU,MAAM,KACpB,IAAI,eAAe;IACjB,YAAY,QAAQ;IACpB;IACA,MAAM,SAAS,SAAS,QAAQ,OAAO;IACxC,CAAC,CACH;AAED,SAAM,OAAO;AAEb,QAAK,MAAM,YAAY,QACrB,MAAK,MAAM,CAAC,QAAQ,kBAAkB,OAAO,QAAQ,SAAS,QAAQ,EAAE;AACtE,QAAI,CAAC,cAAe;IAEpB,MAAM,UAAU,GAAG,SAAS,GAAG,GAAG;IAGlC,IAAIA;IACJ,IAAIC;AAEJ,QAAI,SAAS,QAAQ;KACnB,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,KAClC,eAAc,YAAY,UAAU,QAAQ;eAErC,SAAS,QAAQ;KAG1B,MAAM,cAAc,MAAM,IAAI,aAAa,SAAS,IAAI,OAAO;AAC/D,SAAI,aAAa,UAAU,SAAS,SAClC,YAAW,YAAY,UAAU,QAAQ;;IAI7C,MAAMC,OAAgC;KACpC,IAAI,SAAS;KACb;KACA,GAAI,cAAc,YAAY,EAAE,UAAU,cAAc,UAAU;KAClE,GAAI,cAAc,QAAQ,EAAE,MAAM,cAAc,MAAM;KACtD,GAAG,cAAc;KACjB,WAAW,cAAc;KACzB,aAAa,cAAc;KAE3B,GAAI,eAAe,EAAE,MAAM,aAAa;KACzC;AAGD,QAAI,aAAa,OACf,MAAK,WAAW;IAGlB,MAAM,aAAa,MAAM,UAAU;KAAE,IAAI;KAAS;KAAM,CAAC;AAEzD,UAAM,IAAI;KACR,IAAI;KACJ,MAAM;KACN,QAAQ,eAAe,cAAc,KAAK;KAC3C,CAAC;;AAIN,UAAO,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,gBAAgB,QAAQ,aAAa;;EAElF"}
@@ -70,4 +70,4 @@ function serializeProps(props) {
70
70
 
71
71
  //#endregion
72
72
  export { isHydratable as i, findHydratableComponents as n, hasHydratableComponents as r, serializeProps as t };
73
- //# sourceMappingURL=serialize-props-BryTdVgJ.mjs.map
73
+ //# sourceMappingURL=serialize-props-CQDv661k.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"serialize-props-BryTdVgJ.mjs","names":["hydratable: HydratableComponent[]"],"sources":["../src/lib/hydration-utils.ts","../src/lib/serialize-props.ts"],"sourcesContent":["import type { Config, Data } from '@measured/puck'\nimport type { HydrationStrategy } from '../types.js'\nimport type { HydrationMeta } from './withHydration.js'\n\n/**\n * Extended ComponentConfig with hydration support.\n * @deprecated Use withHydration() wrapper instead of hydration property.\n */\nexport interface HydratableComponentConfig {\n /** @deprecated Use withHydration() wrapper on render function instead */\n hydration?: HydrationStrategy\n render?: (props: unknown) => unknown\n}\n\n/**\n * Component instance requiring hydration.\n * Contains the component name, props, and hydration strategy.\n */\nexport interface HydratableComponent {\n /** Component type name from Puck config */\n type: string\n /** Props to pass to the component */\n props: Record<string, unknown>\n /** Hydration strategy from ComponentConfig */\n strategy: Exclude<HydrationStrategy, 'none'>\n /** Unique ID from Puck data (for keying) */\n id: string\n}\n\n/**\n * Check if a component type has hydration enabled.\n *\n * First checks for __hydration metadata on the render function (new withHydration API),\n * then falls back to hydration property on ComponentConfig (deprecated).\n *\n * @param componentType - The component type name from Puck data\n * @param config - The Puck config with component definitions\n * @returns The hydration strategy ('none', 'load', 'visible', 'idle')\n */\nexport function isHydratable(\n componentType: string,\n config: Config\n): HydrationStrategy {\n const componentConfig = config.components[componentType] as HydratableComponentConfig | undefined\n if (!componentConfig?.render) return 'none'\n\n // New API: Check for __hydration metadata attached by withHydration()\n const render = componentConfig.render as { __hydration?: HydrationMeta }\n if (render.__hydration?.__isHydratable) {\n return render.__hydration.strategy\n }\n\n // Deprecated: Check hydration property on ComponentConfig\n return componentConfig?.hydration ?? 'none'\n}\n\n/**\n * Find all components in a Puck data tree that require hydration.\n * Walks the content array and zones recursively.\n *\n * @param data - Puck data object containing content tree\n * @param config - Puck config with component definitions\n * @returns Array of components that need hydration\n */\nexport function findHydratableComponents(\n data: Data,\n config: Config\n): HydratableComponent[] {\n const hydratable: HydratableComponent[] = []\n\n // Walk content array\n if (data.content) {\n for (const item of data.content) {\n const strategy = isHydratable(item.type, config)\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?._id ?? item.type,\n })\n }\n }\n }\n\n // Walk zones (named drop zones with nested content)\n if (data.zones) {\n for (const [zoneName, zoneContent] of Object.entries(data.zones)) {\n for (const item of zoneContent) {\n const strategy = isHydratable(item.type, config)\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?._id ?? `${zoneName}-${item.type}`,\n })\n }\n }\n }\n }\n\n return hydratable\n}\n\n/**\n * Check if Puck data contains any hydratable components.\n * Quick check before more expensive operations.\n */\nexport function hasHydratableComponents(data: Data, config: Config): boolean {\n // Check content\n if (data.content?.some(item => isHydratable(item.type, config) !== 'none')) {\n return true\n }\n\n // Check zones\n if (data.zones) {\n for (const zoneContent of Object.values(data.zones)) {\n if (zoneContent.some(item => isHydratable(item.type, config) !== 'none')) {\n return true\n }\n }\n }\n\n return false\n}\n","/**\n * Safely serialize props for embedding in HTML data attributes.\n * Escapes < to prevent XSS when JSON is parsed in browser.\n */\nexport function serializeProps(props: Record<string, unknown>): string {\n return JSON.stringify(props).replace(/</g, '\\\\u003c')\n}\n"],"mappings":";;;;;;;;;;;AAuCA,SAAgB,aACd,eACA,QACmB;CACnB,MAAM,kBAAkB,OAAO,WAAW;AAC1C,KAAI,CAAC,iBAAiB,OAAQ,QAAO;CAGrC,MAAM,SAAS,gBAAgB;AAC/B,KAAI,OAAO,aAAa,eACtB,QAAO,OAAO,YAAY;AAI5B,QAAO,iBAAiB,aAAa;;;;;;;;;;AAWvC,SAAgB,yBACd,MACA,QACuB;CACvB,MAAMA,aAAoC,EAAE;AAG5C,KAAI,KAAK,QACP,MAAK,MAAM,QAAQ,KAAK,SAAS;EAC/B,MAAM,WAAW,aAAa,KAAK,MAAM,OAAO;AAChD,MAAI,aAAa,OACf,YAAW,KAAK;GACd,MAAM,KAAK;GACX,OAAO,KAAK,SAAS,EAAE;GACvB;GACA,IAAI,KAAK,OAAO,OAAO,KAAK;GAC7B,CAAC;;AAMR,KAAI,KAAK,MACP,MAAK,MAAM,CAAC,UAAU,gBAAgB,OAAO,QAAQ,KAAK,MAAM,CAC9D,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,WAAW,aAAa,KAAK,MAAM,OAAO;AAChD,MAAI,aAAa,OACf,YAAW,KAAK;GACd,MAAM,KAAK;GACX,OAAO,KAAK,SAAS,EAAE;GACvB;GACA,IAAI,KAAK,OAAO,OAAO,GAAG,SAAS,GAAG,KAAK;GAC5C,CAAC;;AAMV,QAAO;;;;;;AAOT,SAAgB,wBAAwB,MAAY,QAAyB;AAE3E,KAAI,KAAK,SAAS,MAAK,SAAQ,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CACxE,QAAO;AAIT,KAAI,KAAK,OACP;OAAK,MAAM,eAAe,OAAO,OAAO,KAAK,MAAM,CACjD,KAAI,YAAY,MAAK,SAAQ,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CACtE,QAAO;;AAKb,QAAO;;;;;;;;;ACxHT,SAAgB,eAAe,OAAwC;AACrE,QAAO,KAAK,UAAU,MAAM,CAAC,QAAQ,MAAM,UAAU"}
1
+ {"version":3,"file":"serialize-props-CQDv661k.mjs","names":["hydratable: HydratableComponent[]"],"sources":["../src/lib/hydration-utils.ts","../src/lib/serialize-props.ts"],"sourcesContent":["import type { Config, Data } from '@measured/puck'\nimport type { HydrationStrategy } from '../types.js'\nimport type { HydrationMeta } from './withHydration.js'\n\n/**\n * Extended ComponentConfig with hydration support.\n * @deprecated Use withHydration() wrapper instead of hydration property.\n */\nexport interface HydratableComponentConfig {\n /** @deprecated Use withHydration() wrapper on render function instead */\n hydration?: HydrationStrategy\n render?: (props: unknown) => unknown\n}\n\n/**\n * Component instance requiring hydration.\n * Contains the component name, props, and hydration strategy.\n */\nexport interface HydratableComponent {\n /** Component type name from Puck config */\n type: string\n /** Props to pass to the component */\n props: Record<string, unknown>\n /** Hydration strategy from ComponentConfig */\n strategy: Exclude<HydrationStrategy, 'none'>\n /** Unique ID from Puck data (for keying) */\n id: string\n}\n\n/**\n * Check if a component type has hydration enabled.\n *\n * First checks for __hydration metadata on the render function (new withHydration API),\n * then falls back to hydration property on ComponentConfig (deprecated).\n *\n * @param componentType - The component type name from Puck data\n * @param config - The Puck config with component definitions\n * @returns The hydration strategy ('none', 'load', 'visible', 'idle')\n */\nexport function isHydratable(\n componentType: string,\n config: Config\n): HydrationStrategy {\n const componentConfig = config.components[componentType] as HydratableComponentConfig | undefined\n if (!componentConfig?.render) return 'none'\n\n // New API: Check for __hydration metadata attached by withHydration()\n const render = componentConfig.render as { __hydration?: HydrationMeta }\n if (render.__hydration?.__isHydratable) {\n return render.__hydration.strategy\n }\n\n // Deprecated: Check hydration property on ComponentConfig\n return componentConfig?.hydration ?? 'none'\n}\n\n/**\n * Find all components in a Puck data tree that require hydration.\n * Walks the content array and zones recursively.\n *\n * @param data - Puck data object containing content tree\n * @param config - Puck config with component definitions\n * @returns Array of components that need hydration\n */\nexport function findHydratableComponents(\n data: Data,\n config: Config\n): HydratableComponent[] {\n const hydratable: HydratableComponent[] = []\n\n // Walk content array\n if (data.content) {\n for (const item of data.content) {\n const strategy = isHydratable(item.type, config)\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?._id ?? item.type,\n })\n }\n }\n }\n\n // Walk zones (named drop zones with nested content)\n if (data.zones) {\n for (const [zoneName, zoneContent] of Object.entries(data.zones)) {\n for (const item of zoneContent) {\n const strategy = isHydratable(item.type, config)\n if (strategy !== 'none') {\n hydratable.push({\n type: item.type,\n props: item.props ?? {},\n strategy,\n id: item.props?._id ?? `${zoneName}-${item.type}`,\n })\n }\n }\n }\n }\n\n return hydratable\n}\n\n/**\n * Check if Puck data contains any hydratable components.\n * Quick check before more expensive operations.\n */\nexport function hasHydratableComponents(data: Data, config: Config): boolean {\n // Check content\n if (data.content?.some(item => isHydratable(item.type, config) !== 'none')) {\n return true\n }\n\n // Check zones\n if (data.zones) {\n for (const zoneContent of Object.values(data.zones)) {\n if (zoneContent.some(item => isHydratable(item.type, config) !== 'none')) {\n return true\n }\n }\n }\n\n return false\n}\n","/**\n * Safely serialize props for embedding in HTML data attributes.\n * Escapes < to prevent XSS when JSON is parsed in browser.\n */\nexport function serializeProps(props: Record<string, unknown>): string {\n return JSON.stringify(props).replace(/</g, '\\\\u003c')\n}\n"],"mappings":";;;;;;;;;;;AAuCA,SAAgB,aACd,eACA,QACmB;CACnB,MAAM,kBAAkB,OAAO,WAAW;AAC1C,KAAI,CAAC,iBAAiB,OAAQ,QAAO;CAGrC,MAAM,SAAS,gBAAgB;AAC/B,KAAI,OAAO,aAAa,eACtB,QAAO,OAAO,YAAY;AAI5B,QAAO,iBAAiB,aAAa;;;;;;;;;;AAWvC,SAAgB,yBACd,MACA,QACuB;CACvB,MAAMA,aAAoC,EAAE;AAG5C,KAAI,KAAK,QACP,MAAK,MAAM,QAAQ,KAAK,SAAS;EAC/B,MAAM,WAAW,aAAa,KAAK,MAAM,OAAO;AAChD,MAAI,aAAa,OACf,YAAW,KAAK;GACd,MAAM,KAAK;GACX,OAAO,KAAK,SAAS,EAAE;GACvB;GACA,IAAI,KAAK,OAAO,OAAO,KAAK;GAC7B,CAAC;;AAMR,KAAI,KAAK,MACP,MAAK,MAAM,CAAC,UAAU,gBAAgB,OAAO,QAAQ,KAAK,MAAM,CAC9D,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,WAAW,aAAa,KAAK,MAAM,OAAO;AAChD,MAAI,aAAa,OACf,YAAW,KAAK;GACd,MAAM,KAAK;GACX,OAAO,KAAK,SAAS,EAAE;GACvB;GACA,IAAI,KAAK,OAAO,OAAO,GAAG,SAAS,GAAG,KAAK;GAC5C,CAAC;;AAMV,QAAO;;;;;;AAOT,SAAgB,wBAAwB,MAAY,QAAyB;AAE3E,KAAI,KAAK,SAAS,MAAK,SAAQ,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CACxE,QAAO;AAIT,KAAI,KAAK,OACP;OAAK,MAAM,eAAe,OAAO,OAAO,KAAK,MAAM,CACjD,KAAI,YAAY,MAAK,SAAQ,aAAa,KAAK,MAAM,OAAO,KAAK,OAAO,CACtE,QAAO;;AAKb,QAAO;;;;;;;;;ACxHT,SAAgB,eAAe,OAAwC;AACrE,QAAO,KAAK,UAAU,MAAM,CAAC,QAAQ,MAAM,UAAU"}
@@ -42,4 +42,4 @@ function withHydration(Component, strategy) {
42
42
 
43
43
  //#endregion
44
44
  export { withHydration as t };
45
- //# sourceMappingURL=withHydration-DAkXCF9z.mjs.map
45
+ //# sourceMappingURL=withHydration-DfAwNHmI.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"withHydration-DAkXCF9z.mjs","names":[],"sources":["../src/lib/withHydration.ts"],"sourcesContent":["import type React from 'react'\n\n/**\n * Metadata attached to components marked for hydration.\n * Used by the build-time scanner and runtime hydration system.\n */\nexport interface HydrationMeta {\n strategy: 'load' | 'visible' | 'idle'\n __isHydratable: true\n}\n\n/**\n * Hydration strategy for the withHydration wrapper.\n * Does not include 'none' since wrapping implies hydration is desired.\n */\nexport type WithHydrationStrategy = 'load' | 'visible' | 'idle'\n\n/**\n * Marks a component's render function for client-side hydration.\n *\n * This wrapper attaches metadata to the component function, enabling:\n * 1. Build-time discovery via static analysis of source files\n * 2. Runtime hydration strategy determination\n *\n * The wrapper does NOT create a new component or add runtime overhead.\n * It simply attaches a `__hydration` property to the existing function.\n *\n * @param Component - The React component to mark for hydration\n * @param strategy - When to hydrate: 'load', 'visible', or 'idle'\n * @returns The same component with hydration metadata attached\n *\n * @example\n * ```tsx\n * // In a Puck component file (e.g., TestimonialGrid.tsx)\n * import { withHydration } from '@conloca/astro-cms'\n *\n * const TestimonialGridComponent = ({ title, testimonials }) => {\n * const [currentPage, setCurrentPage] = useState(0)\n * // ... interactive logic\n * }\n *\n * export const TestimonialGrid: ComponentConfig<Props> = {\n * fields: { ... },\n * defaultProps: { ... },\n * render: withHydration(TestimonialGridComponent, 'visible'),\n * }\n * ```\n */\nexport function withHydration<T extends (props: any) => React.ReactNode>(\n Component: T,\n strategy: WithHydrationStrategy\n): T {\n // Environment variable escape hatch for debugging\n if (typeof process !== 'undefined' && process.env?.CONLOCA_DISABLE_HYDRATION === 'true') {\n return Component\n }\n\n // Attach metadata directly to the function object\n // This avoids creating a wrapper component and keeps bundle size minimal\n const HydratableComponent = Component as T & { __hydration: HydrationMeta }\n HydratableComponent.__hydration = {\n strategy,\n __isHydratable: true,\n }\n\n return HydratableComponent\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,cACd,WACA,UACG;AAEH,KAAI,OAAO,YAAY,eAAe,QAAQ,KAAK,8BAA8B,OAC/E,QAAO;CAKT,MAAM,sBAAsB;AAC5B,qBAAoB,cAAc;EAChC;EACA,gBAAgB;EACjB;AAED,QAAO"}
1
+ {"version":3,"file":"withHydration-DfAwNHmI.mjs","names":[],"sources":["../src/lib/withHydration.ts"],"sourcesContent":["import type React from 'react'\n\n/**\n * Metadata attached to components marked for hydration.\n * Used by the build-time scanner and runtime hydration system.\n */\nexport interface HydrationMeta {\n strategy: 'load' | 'visible' | 'idle'\n __isHydratable: true\n}\n\n/**\n * Hydration strategy for the withHydration wrapper.\n * Does not include 'none' since wrapping implies hydration is desired.\n */\nexport type WithHydrationStrategy = 'load' | 'visible' | 'idle'\n\n/**\n * Marks a component's render function for client-side hydration.\n *\n * This wrapper attaches metadata to the component function, enabling:\n * 1. Build-time discovery via static analysis of source files\n * 2. Runtime hydration strategy determination\n *\n * The wrapper does NOT create a new component or add runtime overhead.\n * It simply attaches a `__hydration` property to the existing function.\n *\n * @param Component - The React component to mark for hydration\n * @param strategy - When to hydrate: 'load', 'visible', or 'idle'\n * @returns The same component with hydration metadata attached\n *\n * @example\n * ```tsx\n * // In a Puck component file (e.g., TestimonialGrid.tsx)\n * import { withHydration } from '@conloca/astro-cms'\n *\n * const TestimonialGridComponent = ({ title, testimonials }) => {\n * const [currentPage, setCurrentPage] = useState(0)\n * // ... interactive logic\n * }\n *\n * export const TestimonialGrid: ComponentConfig<Props> = {\n * fields: { ... },\n * defaultProps: { ... },\n * render: withHydration(TestimonialGridComponent, 'visible'),\n * }\n * ```\n */\nexport function withHydration<T extends (props: any) => React.ReactNode>(\n Component: T,\n strategy: WithHydrationStrategy\n): T {\n // Environment variable escape hatch for debugging\n if (typeof process !== 'undefined' && process.env?.CONLOCA_DISABLE_HYDRATION === 'true') {\n return Component\n }\n\n // Attach metadata directly to the function object\n // This avoids creating a wrapper component and keeps bundle size minimal\n const HydratableComponent = Component as T & { __hydration: HydrationMeta }\n HydratableComponent.__hydration = {\n strategy,\n __isHydratable: true,\n }\n\n return HydratableComponent\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,cACd,WACA,UACG;AAEH,KAAI,OAAO,YAAY,eAAe,QAAQ,KAAK,8BAA8B,OAC/E,QAAO;CAKT,MAAM,sBAAsB;AAC5B,qBAAoB,cAAc;EAChC;EACA,gBAAgB;EACjB;AAED,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conloca/astro-cms",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -16,25 +16,21 @@
16
16
  "exports": {
17
17
  "./package.json": "./package.json",
18
18
  ".": {
19
- "development": "./src/index.ts",
20
19
  "types": "./dist/index.d.mts",
21
20
  "import": "./dist/index.mjs",
22
21
  "default": "./dist/index.mjs"
23
22
  },
24
23
  "./components": {
25
- "development": "./src/components.ts",
26
24
  "types": "./dist/components.d.mts",
27
25
  "import": "./dist/components.mjs",
28
26
  "default": "./dist/components.mjs"
29
27
  },
30
28
  "./cms-handler": {
31
- "development": "./src/cms-handler.ts",
32
29
  "types": "./dist/cms-handler.d.mts",
33
30
  "import": "./dist/cms-handler.mjs",
34
31
  "default": "./dist/cms-handler.mjs"
35
32
  },
36
33
  "./collections": {
37
- "development": "./src/collections.ts",
38
34
  "types": "./dist/collections.d.mts",
39
35
  "import": "./dist/collections.mjs",
40
36
  "default": "./dist/collections.mjs"
@@ -43,32 +39,27 @@
43
39
  "types": "./src/virtual-modules.d.ts"
44
40
  },
45
41
  "./page-handler": {
46
- "development": "./src/handlers/page-handler.astro",
47
42
  "import": "./dist/handlers/page-handler.astro",
48
43
  "default": "./dist/handlers/page-handler.astro"
49
44
  },
50
45
  "./lib/hydration-script": {
51
- "development": "./src/lib/hydration-script.ts",
52
46
  "types": "./dist/lib/hydration-script.d.mts",
53
47
  "import": "./dist/lib/hydration-script.mjs",
54
48
  "default": "./dist/lib/hydration-script.mjs"
55
49
  },
56
50
  "./hydration": {
57
- "development": "./src/hydration.ts",
58
51
  "types": "./dist/hydration.d.mts",
59
52
  "import": "./dist/hydration.mjs",
60
53
  "default": "./dist/hydration.mjs"
61
54
  }
62
55
  },
63
56
  "scripts": {
64
- "build": "tsdown",
57
+ "build": "tsdown && mkdir -p dist/handlers && cp src/handlers/page-handler.astro dist/handlers/",
65
58
  "test": "tsc-bun-test",
66
59
  "test:watch": "bun test --watch"
67
60
  },
68
61
  "files": [
69
62
  "dist",
70
- "src/handlers",
71
- "src/virtual-modules.d.ts",
72
63
  "!**/*.tsbuildinfo"
73
64
  ],
74
65
  "dependencies": {
@@ -1,144 +0,0 @@
1
- /**
2
- * Type declarations for Conloca virtual modules.
3
- *
4
- * These modules are generated at build/dev time by the Vite plugin
5
- * and provide routing configuration, layout components, page API,
6
- * and Puck config to page handlers.
7
- */
8
-
9
- import type { Config } from '@measured/puck';
10
-
11
- import type { LayoutProps, PageData, PageReference, ResolvedRoutingConfig } from './types.js';
12
-
13
- /**
14
- * Virtual module: virtual:conloca-routing-config
15
- *
16
- * Provides resolved routing configuration to page handlers.
17
- * All defaults are applied before this module is generated.
18
- */
19
- declare module 'virtual:conloca-routing-config' {
20
- const config: ResolvedRoutingConfig;
21
- export default config;
22
- }
23
-
24
- /**
25
- * Virtual module: virtual:conloca-layout
26
- *
27
- * Provides the layout component for content pages.
28
- * Returns undefined if no layout is configured.
29
- *
30
- * Currently uses the first route's layout - multi-layout support
31
- * is planned for future versions.
32
- */
33
- declare module 'virtual:conloca-layout' {
34
- type LayoutComponent = ((props: LayoutProps) => unknown) | undefined;
35
-
36
- const Layout: LayoutComponent;
37
- export default Layout;
38
- }
39
-
40
- /**
41
- * Virtual module: virtual:conloca-page-api
42
- *
43
- * Provides page loading functions wrapping ContentAPI.
44
- * Used by page-handler.astro for:
45
- * - getStaticPaths(): getAllPages()
46
- * - Page rendering: getPage()
47
- * - 404 checks: pageExists()
48
- * - MDX evaluation: contentOptions
49
- */
50
- declare module 'virtual:conloca-page-api' {
51
- /**
52
- * Content configuration options for ContentAPI initialization.
53
- * Useful for creating additional ContentAPI instances (e.g., for MDX evaluation).
54
- */
55
- export const contentOptions: {
56
- /** Path to content directory */
57
- contentRoot: string;
58
- /** Path to canvas/puck directory */
59
- canvasDir: string;
60
- /** Site name for content resolution */
61
- siteName: string;
62
- /** Default locale for content resolution */
63
- locale: string;
64
- };
65
-
66
- /**
67
- * Get all pages for static path generation.
68
- * @param collection - Optional collection filter (defaults to all collections)
69
- * @returns Array of page references with id, pathname, title, collection
70
- */
71
- export function getAllPages(collection?: string): Promise<PageReference[]>;
72
-
73
- /**
74
- * Load full page data for rendering.
75
- * @param pathname - URL pathname (e.g., '/about')
76
- * @param collection - Optional collection to search in
77
- * @returns Full page data including puckData for rendering
78
- * @throws Error with code 'PAGE_NOT_FOUND' if page doesn't exist
79
- */
80
- export function getPage(pathname: string, collection?: string): Promise<PageData>;
81
-
82
- /**
83
- * Check if a page exists without loading full data.
84
- * @param pathname - URL pathname
85
- * @param collection - Optional collection filter
86
- * @returns true if page exists, false otherwise
87
- */
88
- export function pageExists(pathname: string, collection?: string): Promise<boolean>;
89
-
90
- /**
91
- * Get all entries from a data collection.
92
- *
93
- * Fetches all entries from a data collection and returns them as
94
- * simplified DataCollectionEntry objects for use in Puck component resolvers.
95
- *
96
- * @param collection - Data collection name
97
- * @param locale - Optional locale override (defaults to configured locale)
98
- * @returns Array of DataCollectionEntry objects with id, name, data, and meta
99
- */
100
- export function getDataCollection(
101
- collection: string,
102
- locale?: string,
103
- ): Promise<import('./types').DataCollectionEntry[]>;
104
-
105
- /**
106
- * Get pages matching a path prefix.
107
- *
108
- * Filters all pages by pathname prefix and returns them sorted.
109
- * Excludes the listing page itself (exact prefix match).
110
- *
111
- * @param prefix - Path prefix to match (e.g., '/blog/')
112
- * @param options - Optional sort and limit settings
113
- * @returns Array of PageReference objects with meta and timestamps
114
- *
115
- * @example Get latest 10 blog posts
116
- * ```typescript
117
- * const posts = await getPagesByPrefix('/blog/', {
118
- * sort: 'date-desc',
119
- * limit: 10,
120
- * });
121
- * ```
122
- */
123
- export function getPagesByPrefix(
124
- prefix: string,
125
- options?: {
126
- sort?: 'date-desc' | 'date-asc' | 'title';
127
- limit?: number;
128
- },
129
- ): Promise<PageReference[]>;
130
- }
131
-
132
- /**
133
- * Virtual module: virtual:conloca-puck-config
134
- *
135
- * Provides Puck configuration for static page rendering.
136
- *
137
- * This is separate from the HMR-enabled puck-entry.js used by
138
- * the CMS SPA. It's a simple re-export without React refresh
139
- * preamble since it's used for SSG builds.
140
- */
141
- declare module 'virtual:conloca-puck-config' {
142
- const config: Config;
143
- export default config;
144
- }