@conloca/astro-cms 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,770 @@
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";
4
+ import { blockMetaSchema, pageMetaSchema } from "@conloca/content-api/schemas";
5
+ import { createContentAPI, createContentWatchHandlers } from "@conloca/content-api/node";
6
+ import { basename, dirname, extname, join, resolve } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import viteReact from "@vitejs/plugin-react";
9
+ import { searchForWorkspaceRoot } from "vite";
10
+ import { readFile } from "node:fs/promises";
11
+ import fg from "fast-glob";
12
+
13
+ //#region src/lib/hydration-scanner.ts
14
+ const HYDRATION_IMPORT_PATTERN = /import\s+\{[^}]*withHydration[^}]*\}\s+from\s+['"]@conloca\/astro-cms(?:\/hydration)?['"]/;
15
+ const HYDRATION_PATTERN = /withHydration\s*\(\s*\w+\s*,\s*['"](\w+)['"]\s*\)/g;
16
+ const VALID_STRATEGIES = new Set([
17
+ "load",
18
+ "visible",
19
+ "idle"
20
+ ]);
21
+ /**
22
+ * Derives component scan paths from puckConfigPath.
23
+ *
24
+ * Convention: puckConfigPath directory + '/components/puck'
25
+ * Example: './src/puck.config.tsx' -> './src/components/puck'
26
+ *
27
+ * If explicitPaths provided, they extend (not replace) the auto-discovered path.
28
+ *
29
+ * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')
30
+ * @param explicitPaths - Optional additional paths to scan
31
+ * @returns Array of paths to scan for hydratable components
32
+ */
33
+ function deriveComponentPaths(puckConfigPath, explicitPaths) {
34
+ const defaultScanPath = join(dirname(puckConfigPath), "components", "puck");
35
+ if (explicitPaths && explicitPaths.length > 0) return [defaultScanPath, ...explicitPaths];
36
+ return [defaultScanPath];
37
+ }
38
+ /**
39
+ * Derives a PascalCase component name from a file path.
40
+ *
41
+ * @param filePath - Absolute path to the component file
42
+ * @returns Component name in PascalCase
43
+ *
44
+ * @example
45
+ * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')
46
+ * // => 'TestimonialGrid'
47
+ *
48
+ * deriveComponentName('/src/components/puck/blog-post-grid.tsx')
49
+ * // => 'BlogPostGrid'
50
+ */
51
+ function deriveComponentName(filePath) {
52
+ const filename = basename(filePath, extname(filePath));
53
+ if (filename.includes("-")) return filename.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
54
+ return filename.charAt(0).toUpperCase() + filename.slice(1);
55
+ }
56
+ /**
57
+ * Scans component directories for files using withHydration wrapper.
58
+ *
59
+ * This function performs static analysis to discover components marked
60
+ * for hydration, without executing any component code.
61
+ *
62
+ * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])
63
+ * @param projectRoot - Absolute path to the project root
64
+ * @returns Array of discovered hydratable components with their strategies
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * const discoveries = await scanForHydratableComponents(
69
+ * ['src/components/puck'],
70
+ * '/path/to/project'
71
+ * )
72
+ * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]
73
+ * ```
74
+ */
75
+ async function scanForHydratableComponents(componentPaths, projectRoot) {
76
+ const discoveries = [];
77
+ const seenNames = /* @__PURE__ */ new Map();
78
+ for (const scanPath of componentPaths) {
79
+ const files = await fg("**/*.tsx", {
80
+ cwd: resolve(projectRoot, scanPath),
81
+ absolute: true,
82
+ onlyFiles: true
83
+ });
84
+ for (const filePath of files) try {
85
+ const content = await readFile(filePath, "utf-8");
86
+ if (!HYDRATION_IMPORT_PATTERN.test(content)) continue;
87
+ const matches = [...content.matchAll(HYDRATION_PATTERN)];
88
+ if (matches.length === 0) continue;
89
+ if (matches.length > 1) console.warn(`[Conloca Hydration] Multiple withHydration calls in ${filePath}. Consider splitting into separate component files. Using first call.`);
90
+ const rawStrategy = matches[0][1];
91
+ if (!VALID_STRATEGIES.has(rawStrategy)) {
92
+ console.warn(`[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. Valid options: ${[...VALID_STRATEGIES].join(", ")}. Skipping component.`);
93
+ continue;
94
+ }
95
+ const strategy = rawStrategy;
96
+ const componentName = deriveComponentName(filePath);
97
+ const existingPath = seenNames.get(componentName);
98
+ if (existingPath) {
99
+ console.warn(`[Conloca Hydration] Duplicate component name '${componentName}'. Found in: ${existingPath} and ${filePath}. Using first occurrence.`);
100
+ continue;
101
+ }
102
+ seenNames.set(componentName, filePath);
103
+ discoveries.push({
104
+ componentName,
105
+ filePath,
106
+ strategy
107
+ });
108
+ } catch (err) {
109
+ console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err);
110
+ }
111
+ }
112
+ return discoveries;
113
+ }
114
+
115
+ //#endregion
116
+ //#region src/lib/routing-config.ts
117
+ /**
118
+ * Normalize routing config input to full RoutingConfig.
119
+ *
120
+ * Handles the `routing: true` shorthand, boolean values, and top-level layout option.
121
+ *
122
+ * @param input - The routing config input (boolean, object, or undefined)
123
+ * @param topLevelLayout - Optional top-level layout path (enables routing when provided)
124
+ * @returns Normalized RoutingConfig or undefined if not enabled
125
+ */
126
+ function normalizeRoutingConfig(input, topLevelLayout) {
127
+ if (input === void 0 && topLevelLayout) return {
128
+ enabled: true,
129
+ routes: { pages: {
130
+ pattern: "/[...slug]",
131
+ collection: "pages",
132
+ layout: topLevelLayout,
133
+ prerender: true
134
+ } },
135
+ fallback: "404",
136
+ onConflict: "warn"
137
+ };
138
+ if (input === void 0) return;
139
+ if (input === true) return {
140
+ enabled: true,
141
+ routes: { pages: {
142
+ pattern: "/[...slug]",
143
+ collection: "pages",
144
+ prerender: true
145
+ } },
146
+ fallback: "404",
147
+ onConflict: "warn"
148
+ };
149
+ if (input === false) return { enabled: false };
150
+ return input;
151
+ }
152
+ /**
153
+ * Apply defaults to a RouteConfig.
154
+ *
155
+ * Fills in missing optional fields with their default values.
156
+ *
157
+ * @param config - Partial route configuration
158
+ * @returns Complete route configuration with all fields
159
+ */
160
+ function resolveRouteConfig(config) {
161
+ return {
162
+ pattern: config.pattern,
163
+ collection: config.collection ?? "pages",
164
+ layout: config.layout ?? "",
165
+ prerender: config.prerender ?? true,
166
+ meta: config.meta ?? {},
167
+ dataBindings: config.dataBindings ?? { collections: [] }
168
+ };
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/lib/virtual-module-generators.ts
173
+ /**
174
+ * Generate the virtual:conloca-routing-config module.
175
+ *
176
+ * Returns a module that exports the resolved routing configuration as default.
177
+ *
178
+ * @param config - Resolved routing configuration with all defaults applied
179
+ * @returns JavaScript module code as a string
180
+ */
181
+ function generateRoutingConfigModule(config) {
182
+ return `export default ${JSON.stringify(config, null, 2)};`;
183
+ }
184
+ /**
185
+ * Generate the virtual:conloca-layout module.
186
+ *
187
+ * Returns a module that re-exports the layout component or exports undefined
188
+ * if no layout is configured.
189
+ *
190
+ * Currently uses the first route's layout. Multi-layout support is future work.
191
+ *
192
+ * @param routing - Routing configuration (may be undefined if routing disabled)
193
+ * @returns JavaScript module code as a string
194
+ */
195
+ function generateLayoutModule(routing) {
196
+ const routes = routing?.routes || {};
197
+ const layoutPath = Object.values(routes)[0]?.layout;
198
+ if (layoutPath) return `export { default } from '${layoutPath.startsWith(".") ? `/${layoutPath.slice(2)}` : layoutPath}';`;
199
+ return "export default undefined;";
200
+ }
201
+ /**
202
+ * Generate the virtual:conloca-page-api module.
203
+ *
204
+ * Returns a module that provides page loading functions wrapping ContentAPI:
205
+ * - getAllPages(collection?) - For getStaticPaths()
206
+ * - getPage(pathname, collection?) - For page data loading
207
+ * - pageExists(pathname, collection?) - For 404 checks
208
+ * - contentOptions - Configuration for ContentAPI (for MDX evaluation)
209
+ *
210
+ * @param options - Configuration for ContentAPI initialization
211
+ * @returns JavaScript module code as a string
212
+ */
213
+ function generatePageApiModule(options) {
214
+ return `
215
+ import { createContentAPI } from '@conloca/content-api/node';
216
+
217
+ // Export content options for MDX evaluation and other ContentAPI uses
218
+ export const contentOptions = {
219
+ contentRoot: '${options.contentRoot}',
220
+ canvasDir: '${options.canvasDir}',
221
+ siteName: '${options.siteName}',
222
+ locale: '${options.locale}',
223
+ };
224
+
225
+ // Initialize ContentAPI with configured paths
226
+ const contentApi = await createContentAPI({
227
+ contentRoot: contentOptions.contentRoot,
228
+ canvasDir: contentOptions.canvasDir,
229
+ });
230
+
231
+ // Get site instance for page operations (configured via routing.siteName)
232
+ const site = contentApi.getSite(contentOptions.siteName);
233
+ const locale = contentOptions.locale; // Configured via routing.locale
234
+
235
+ /**
236
+ * Get all pages for static path generation.
237
+ * @param collection - Optional collection filter
238
+ */
239
+ export async function getAllPages(collection) {
240
+ const pages = [];
241
+
242
+ // listPages is a generator that yields ContentManifest objects
243
+ for (const manifest of site.listPages(locale)) {
244
+ // Get the localized data for pathname/title
245
+ const localeData = manifest.locales[locale];
246
+ if (!localeData) continue;
247
+
248
+ const pathname = localeData.pathname || '/' + manifest.id.replace(/^index$/, '');
249
+
250
+ // Collection resolution: explicit collection in manifest, or default 'pages'
251
+ const resolvedCollection = manifest.collection || 'pages';
252
+
253
+ // Filter by requested collection
254
+ if (collection && resolvedCollection !== collection) continue;
255
+
256
+ pages.push({
257
+ id: manifest.id,
258
+ pathname: pathname,
259
+ title: localeData.meta?.title || manifest.id,
260
+ collection: resolvedCollection,
261
+ meta: localeData.meta || {},
262
+ timestamps: {
263
+ created: localeData.created,
264
+ modified: localeData.modified,
265
+ },
266
+ });
267
+ }
268
+
269
+ return pages;
270
+ }
271
+
272
+ /**
273
+ * Get pages matching a path prefix.
274
+ * @param prefix - Path prefix to match (e.g., '/blog/')
275
+ * @param options - Optional sort and limit settings
276
+ * @returns Array of PageReference objects
277
+ */
278
+ export async function getPagesByPrefix(prefix, options = {}) {
279
+ const allPages = await getAllPages();
280
+
281
+ let filtered = allPages.filter(page =>
282
+ page.pathname.startsWith(prefix) &&
283
+ page.pathname !== prefix && // Exclude the listing page itself
284
+ page.pathname !== prefix.slice(0, -1) // Exclude without trailing slash
285
+ );
286
+
287
+ // Sort by date (newest first by default)
288
+ if (options.sort === 'date-desc' || !options.sort) {
289
+ filtered.sort((a, b) => {
290
+ const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);
291
+ const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);
292
+ return new Date(dateB).getTime() - new Date(dateA).getTime();
293
+ });
294
+ } else if (options.sort === 'date-asc') {
295
+ filtered.sort((a, b) => {
296
+ const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);
297
+ const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);
298
+ return new Date(dateA).getTime() - new Date(dateB).getTime();
299
+ });
300
+ } else if (options.sort === 'title') {
301
+ filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
302
+ }
303
+
304
+ if (options.limit && options.limit > 0) {
305
+ filtered = filtered.slice(0, options.limit);
306
+ }
307
+
308
+ return filtered;
309
+ }
310
+
311
+ /**
312
+ * Load full page data for rendering.
313
+ * @param pathname - URL pathname (e.g., '/about')
314
+ * @param collection - Optional collection to search in
315
+ */
316
+ export async function getPage(pathname, collection) {
317
+ // Use site.getByPathname which returns ContentManifest (metadata only)
318
+ const manifest = site.getByPathname(pathname, locale);
319
+
320
+ if (!manifest) {
321
+ const error = new Error(\`Page not found: \${pathname}\`);
322
+ error.code = 'PAGE_NOT_FOUND';
323
+ throw error;
324
+ }
325
+
326
+ // Optionally filter by collection
327
+ if (collection && manifest.collection !== collection) {
328
+ const error = new Error(\`Page not found: \${pathname}\`);
329
+ error.code = 'PAGE_NOT_FOUND';
330
+ throw error;
331
+ }
332
+
333
+ // Get the full content with locale data
334
+ const content = await contentApi.getLocalized(manifest.id, locale);
335
+
336
+ if (!content) {
337
+ const error = new Error(\`Page not found: \${pathname}\`);
338
+ error.code = 'PAGE_NOT_FOUND';
339
+ throw error;
340
+ }
341
+
342
+ const localeData = content.localized;
343
+ const meta = localeData.meta || {};
344
+
345
+ return {
346
+ id: manifest.id,
347
+ title: meta.title || manifest.id,
348
+ description: meta.description,
349
+ pathname: pathname,
350
+ puckData: localeData.content?.puckData,
351
+ collection: manifest.collection || collection || 'pages',
352
+ route: {
353
+ name: 'pages', // Will be set by caller
354
+ pattern: '/[...slug]',
355
+ meta: {},
356
+ },
357
+ meta: meta,
358
+ timestamps: {
359
+ created: localeData.created,
360
+ modified: localeData.modified,
361
+ },
362
+ };
363
+ }
364
+
365
+ /**
366
+ * Check if a page exists without loading full data.
367
+ * @param pathname - URL pathname
368
+ * @param collection - Optional collection filter
369
+ */
370
+ export function pageExists(pathname, collection) {
371
+ // getByPathname is synchronous - returns ContentManifest | null
372
+ const manifest = site.getByPathname(pathname, locale);
373
+
374
+ if (!manifest) {
375
+ return false;
376
+ }
377
+
378
+ // If collection filter specified, verify it matches
379
+ if (collection && manifest.collection !== collection) {
380
+ return false;
381
+ }
382
+
383
+ return true;
384
+ }
385
+
386
+ /**
387
+ * Get all entries from a data collection.
388
+ * @param collection - Data collection name
389
+ * @param localeOverride - Optional locale override (defaults to configured locale)
390
+ * @returns Array of DataCollectionEntry objects
391
+ */
392
+ export async function getDataCollection(collection, localeOverride) {
393
+ const targetLocale = localeOverride || locale;
394
+ const entries = [];
395
+
396
+ // List all manifests in the collection
397
+ for (const manifest of contentApi.data.listContent({ collection })) {
398
+ // Get localized data for each entry
399
+ const localized = await contentApi.getLocalized(manifest.id, targetLocale);
400
+ if (localized) {
401
+ entries.push({
402
+ id: manifest.id,
403
+ name: manifest.name,
404
+ data: localized.content?.data || {},
405
+ meta: manifest.meta || {},
406
+ });
407
+ }
408
+ }
409
+
410
+ return entries;
411
+ }
412
+ `;
413
+ }
414
+ /**
415
+ * Generate the virtual:conloca-puck-config module.
416
+ *
417
+ * Returns a module that re-exports the Puck configuration.
418
+ * This is separate from the HMR-enabled puck-entry.js used by the CMS SPA.
419
+ *
420
+ * @param puckConfigPath - Path to the puck config module
421
+ * @returns JavaScript module code as a string
422
+ */
423
+ function generatePuckConfigModule(puckConfigPath) {
424
+ return `export { default } from '${puckConfigPath.startsWith(".") ? `/${puckConfigPath.slice(2)}` : puckConfigPath}';`;
425
+ }
426
+
427
+ //#endregion
428
+ //#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");
431
+ const VIRTUAL_CONFIG_MODULE = "virtual:conloca-config";
432
+ const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
433
+ const VIRTUAL_ROUTING_CONFIG = "virtual:conloca-routing-config";
434
+ const VIRTUAL_LAYOUT = "virtual:conloca-layout";
435
+ const VIRTUAL_PAGE_API = "virtual:conloca-page-api";
436
+ const VIRTUAL_PUCK_CONFIG = "virtual:conloca-puck-config";
437
+ const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
438
+ const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
439
+ const RESOLVED_PAGE_API = `\0${VIRTUAL_PAGE_API}`;
440
+ const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
441
+ const VIRTUAL_HYDRATION_REGISTRY = "virtual:conloca-hydration-registry";
442
+ const VIRTUAL_HYDRATION_ENTRY = "virtual:conloca-hydration-entry";
443
+ const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
444
+ const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
445
+ const VIRTUAL_CMS_SPA_ENTRY = "virtual:conloca-cms-spa-entry";
446
+ const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
447
+ const contentChangeListener = () => {
448
+ return `
449
+ // Content change listener that uses Vite HMR
450
+ if (import.meta.hot) {
451
+ import.meta.hot.on('conloca:content-update', (data) => {
452
+ console.log('[Conloca CMS] Content updated, invalidating cache:', data);
453
+
454
+ // Get the query client from the global scope and invalidate
455
+ if (window.__QUERY_CLIENT__) {
456
+ window.__QUERY_CLIENT__.invalidateQueries();
457
+ }
458
+ });
459
+ }
460
+
461
+ export default {};
462
+ `;
463
+ };
464
+ const puckConfigLoader = (absolutePuckPath) => {
465
+ return `
466
+ // Import and execute React refresh preamble first (from @vitejs/plugin-react)
467
+ ${viteReact.preambleCode.replace("__BASE__", "/")}
468
+
469
+ // Import the setPuckConfig function from cms-spa
470
+ import { setPuckConfig } from '@conloca/cms-spa/puck-config';
471
+
472
+ // Now dynamically import the config after preamble is ready
473
+ const puckConfigPromise = import('${absolutePuckPath}');
474
+
475
+ // Handle the initial load
476
+ puckConfigPromise.then(module => {
477
+ const puckConfig = module.default;
478
+ setPuckConfig(puckConfig);
479
+
480
+ // Hook into React Fast Refresh to detect component updates
481
+ if (window.__registerBeforePerformReactRefresh) {
482
+ window.__registerBeforePerformReactRefresh(async () => {
483
+ // Re-import the config module to get updated components
484
+ const newModule = await import('${absolutePuckPath}');
485
+ setPuckConfig(newModule.default);
486
+ });
487
+ }
488
+ });
489
+
490
+ // Accept HMR for this module itself
491
+ if (import.meta.hot) {
492
+ import.meta.hot.accept();
493
+ }
494
+
495
+ // Export the promise so the module has a default export
496
+ export default puckConfigPromise.then(m => m.default);
497
+ `;
498
+ };
499
+ const schemasLoader = (absoluteSchemasPath) => {
500
+ return `
501
+ import { setPageSchemas } from '@conloca/cms-spa/page-schemas';
502
+ import * as schemas from '${absoluteSchemasPath}';
503
+
504
+ if (schemas.pageSchemas) {
505
+ setPageSchemas(schemas.pageSchemas);
506
+ }
507
+
508
+ if (import.meta.hot) {
509
+ import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
510
+ if (newModule?.pageSchemas) {
511
+ setPageSchemas(newModule.pageSchemas);
512
+ }
513
+ });
514
+ }
515
+
516
+ export default schemas;
517
+ `;
518
+ };
519
+ function conlocaCMS(options) {
520
+ const cmsRoute = options.route || "/__cms";
521
+ const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
522
+ const hydrationDiscoveriesPromise = scanForHydratableComponents(deriveComponentPaths(options.puckConfigPath, options.componentPaths), process.cwd()).then((discoveries) => {
523
+ if (discoveries.length > 0) console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
524
+ return discoveries;
525
+ });
526
+ let resolvedRoutingConfig;
527
+ if (routingConfig?.enabled !== false && routingConfig) {
528
+ const resolvedRoutes = {};
529
+ for (const [name, config] of Object.entries(routingConfig.routes || {})) resolvedRoutes[name] = resolveRouteConfig(config);
530
+ resolvedRoutingConfig = {
531
+ enabled: routingConfig.enabled ?? true,
532
+ routes: resolvedRoutes,
533
+ fallback: routingConfig.fallback ?? "404",
534
+ onConflict: routingConfig.onConflict ?? "warn",
535
+ siteName: routingConfig.siteName ?? "default",
536
+ locale: routingConfig.locale ?? "en"
537
+ };
538
+ }
539
+ const spaConfig = {
540
+ basename: cmsRoute,
541
+ apiBaseUrl: `${cmsRoute}/api`,
542
+ siteBaseUrl: options.siteBaseUrl,
543
+ enableDevtools: options.enableDevtools ?? true,
544
+ queryClientOptions: options.queryClientOptions,
545
+ schemasPath: options.schemasPath,
546
+ projectRoot: process.cwd(),
547
+ templates: options.templates
548
+ };
549
+ return {
550
+ name: "@conloca/astro-cms",
551
+ hooks: {
552
+ "astro:config:setup": ({ updateConfig, injectRoute, command, logger }) => {
553
+ const astroRoot = process.cwd();
554
+ const contentAbsolute = resolve(options.contentRoot);
555
+ if (command === "dev" && !contentAbsolute.startsWith(astroRoot)) {
556
+ logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
557
+ updateConfig({ vite: { server: { fs: { allow: [searchForWorkspaceRoot(process.cwd()), contentAbsolute] } } } });
558
+ }
559
+ updateConfig({ vite: {
560
+ ssr: {
561
+ noExternal: ["@conloca/astro-cms", "@conloca/cms-spa"],
562
+ external: ["@node-rs/xxhash"]
563
+ },
564
+ plugins: [{
565
+ name: "conloca-routing-virtual-modules",
566
+ resolveId(id) {
567
+ if (id === VIRTUAL_ROUTING_CONFIG) return RESOLVED_ROUTING_CONFIG;
568
+ if (id === VIRTUAL_LAYOUT) return RESOLVED_LAYOUT;
569
+ if (id === VIRTUAL_PAGE_API) return RESOLVED_PAGE_API;
570
+ if (id === VIRTUAL_PUCK_CONFIG) return RESOLVED_PUCK_CONFIG;
571
+ if (id === VIRTUAL_HYDRATION_REGISTRY) return RESOLVED_HYDRATION_REGISTRY;
572
+ if (id === VIRTUAL_HYDRATION_ENTRY) return RESOLVED_HYDRATION_ENTRY;
573
+ return null;
574
+ },
575
+ async load(id) {
576
+ if (id === RESOLVED_ROUTING_CONFIG) {
577
+ if (resolvedRoutingConfig) return generateRoutingConfigModule(resolvedRoutingConfig);
578
+ return "export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };";
579
+ }
580
+ if (id === RESOLVED_LAYOUT) return generateLayoutModule(routingConfig);
581
+ if (id === RESOLVED_PAGE_API) return generatePageApiModule({
582
+ contentRoot: options.contentRoot,
583
+ canvasDir: options.canvasDir || "./canvas",
584
+ siteName: resolvedRoutingConfig?.siteName ?? "default",
585
+ locale: resolvedRoutingConfig?.locale ?? "en"
586
+ });
587
+ if (id === RESOLVED_PUCK_CONFIG) return generatePuckConfigModule(options.puckConfigPath);
588
+ if (id === RESOLVED_HYDRATION_REGISTRY) {
589
+ const discoveries = await hydrationDiscoveriesPromise;
590
+ if (discoveries.length > 0) return `// Generated by @conloca/astro-cms scanner
591
+ export const componentRegistry = {
592
+ ${discoveries.map((d) => {
593
+ const relativePath = d.filePath.replace(process.cwd(), "");
594
+ return ` '${d.componentName}': {
595
+ loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
596
+ strategy: '${d.strategy}',
597
+ }`;
598
+ }).join(",\n")}
599
+ };`;
600
+ return "export const componentRegistry = {};";
601
+ }
602
+ if (id === RESOLVED_HYDRATION_ENTRY) return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
603
+ import { componentRegistry } from 'virtual:conloca-hydration-registry'
604
+
605
+ // Auto-initialize hydration when this module loads
606
+ initHydration(componentRegistry)
607
+ `;
608
+ return null;
609
+ }
610
+ }]
611
+ } });
612
+ if (resolvedRoutingConfig?.enabled) for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
613
+ logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
614
+ injectRoute({
615
+ pattern: routeConfig.pattern,
616
+ entrypoint: PAGE_HANDLER_PATH,
617
+ prerender: routeConfig.prerender
618
+ });
619
+ }
620
+ if (command !== "dev") return;
621
+ updateConfig({ vite: {
622
+ define: {
623
+ "import.meta.env.CONLOCA_CONTENT_ROOT": JSON.stringify(options.contentRoot),
624
+ "import.meta.env.CONLOCA_CANVAS_DIR": JSON.stringify(options.canvasDir || "./canvas"),
625
+ "import.meta.env.CONLOCA_PUCK_CONFIG_PATH": JSON.stringify(options.puckConfigPath),
626
+ "import.meta.env.CONLOCA_ASSETS_PATH": JSON.stringify(options.assetsPath || "")
627
+ },
628
+ resolve: { dedupe: [
629
+ "react",
630
+ "react-dom",
631
+ "react/jsx-runtime",
632
+ "react/jsx-dev-runtime",
633
+ "@measured/puck"
634
+ ] },
635
+ optimizeDeps: {
636
+ exclude: [options.puckConfigPath],
637
+ include: [
638
+ "react",
639
+ "react-dom",
640
+ "react-dom/client",
641
+ "react/jsx-runtime",
642
+ "react/jsx-dev-runtime",
643
+ "@mdxeditor/editor",
644
+ "@measured/puck",
645
+ "@tanstack/react-query",
646
+ "@tanstack/react-query-devtools",
647
+ "react-router-dom",
648
+ "@radix-ui/react-dialog",
649
+ "@radix-ui/react-select",
650
+ "lucide-react",
651
+ "clsx",
652
+ "tailwind-merge",
653
+ "zod",
654
+ "yaml",
655
+ "nanoid",
656
+ "sort-keys",
657
+ "@mdx-js/mdx",
658
+ "remark-frontmatter",
659
+ "remark-gfm",
660
+ "remark-mdx-frontmatter"
661
+ ]
662
+ },
663
+ plugins: [{
664
+ name: "conloca-dev-virtual-modules",
665
+ resolveId(id) {
666
+ if (id === VIRTUAL_CONFIG_MODULE) return RESOLVED_VIRTUAL_CONFIG;
667
+ if (id === `${cmsRoute}/puck-entry.js`) return id;
668
+ if (id === `${cmsRoute}/content-listener.js`) return id;
669
+ if (id === `${cmsRoute}/schemas-entry.js`) return id;
670
+ if (id === VIRTUAL_CMS_SPA_ENTRY) return RESOLVED_CMS_SPA_ENTRY;
671
+ if (id === `${cmsRoute}/cms-spa-entry.js`) return RESOLVED_CMS_SPA_ENTRY;
672
+ return null;
673
+ },
674
+ load(id) {
675
+ if (id === RESOLVED_VIRTUAL_CONFIG) return `export default ${JSON.stringify(spaConfig)};`;
676
+ if (id === `${cmsRoute}/puck-entry.js`) return puckConfigLoader(options.puckConfigPath.startsWith(".") ? `/${options.puckConfigPath.slice(2)}` : options.puckConfigPath);
677
+ if (id === `${cmsRoute}/content-listener.js`) return contentChangeListener();
678
+ if (id === `${cmsRoute}/schemas-entry.js`) {
679
+ if (options.schemasPath) return schemasLoader(options.schemasPath.startsWith(".") ? `/${options.schemasPath.slice(2)}` : options.schemasPath);
680
+ return "export default {};";
681
+ }
682
+ if (id === RESOLVED_CMS_SPA_ENTRY) return `
683
+ // Import and execute React refresh preamble first (from @vitejs/plugin-react)
684
+ ${viteReact.preambleCode.replace("__BASE__", "/")}
685
+
686
+ // Import cms-spa main.tsx directly through Vite
687
+ // Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
688
+ import '@conloca/cms-spa/src/main.tsx';
689
+
690
+ // Accept HMR
691
+ if (import.meta.hot) {
692
+ import.meta.hot.accept();
693
+ }
694
+ `;
695
+ return null;
696
+ }
697
+ }, {
698
+ name: "conloca-content-watcher",
699
+ async configureServer(server) {
700
+ const contentApi = await createContentAPI({
701
+ contentRoot: options.contentRoot,
702
+ canvasDir: options.canvasDir || "./canvas"
703
+ });
704
+ const { resolve: resolve$1 } = await import("node:path");
705
+ const astroRoot$1 = process.cwd();
706
+ const contentAbsolute$1 = resolve$1(options.contentRoot);
707
+ const canvasAbsolute = resolve$1(options.canvasDir || "./canvas");
708
+ const foldersToWatch = [];
709
+ if (!contentAbsolute$1.startsWith(astroRoot$1)) {
710
+ console.log(`[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`);
711
+ foldersToWatch.push(options.contentRoot);
712
+ } else console.log(`[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`);
713
+ if (!canvasAbsolute.startsWith(astroRoot$1)) {
714
+ console.log(`[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || "./canvas"}`);
715
+ foldersToWatch.push(options.canvasDir || "./canvas");
716
+ } else console.log(`[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || "./canvas"}`);
717
+ if (foldersToWatch.length > 0) server.watcher.add(foldersToWatch);
718
+ const handlers = createContentWatchHandlers(contentApi, {
719
+ contentRoot: options.contentRoot,
720
+ canvasDir: options.canvasDir || "./canvas"
721
+ }, server.ws);
722
+ server.watcher.on("change", handlers.onChange);
723
+ server.watcher.on("add", handlers.onAdd);
724
+ server.watcher.on("unlink", handlers.onUnlink);
725
+ }
726
+ }]
727
+ } });
728
+ injectRoute({
729
+ pattern: `${cmsRoute}/[...path]`,
730
+ entrypoint: "@conloca/astro-cms/cms-handler",
731
+ prerender: false
732
+ });
733
+ injectRoute({
734
+ pattern: cmsRoute,
735
+ entrypoint: "@conloca/astro-cms/cms-handler",
736
+ prerender: false
737
+ });
738
+ },
739
+ "astro:server:setup": ({ logger }) => {
740
+ logger.info(`Conloca CMS available at ${cmsRoute}`);
741
+ },
742
+ "astro:routes:resolved": ({ routes, logger }) => {
743
+ if (!resolvedRoutingConfig?.enabled) return;
744
+ const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));
745
+ const conflicts = [];
746
+ for (const route of routes) {
747
+ if (route.origin === "internal") continue;
748
+ const entrypoint = route.entrypoint || "";
749
+ if (entrypoint.includes("page-handler.astro")) continue;
750
+ const pattern = route.pattern;
751
+ if (injectedPatterns.has(pattern)) conflicts.push({
752
+ injected: pattern,
753
+ fileBased: entrypoint || pattern
754
+ });
755
+ }
756
+ if (conflicts.length === 0) return;
757
+ const onConflict = resolvedRoutingConfig.onConflict;
758
+ for (const conflict of conflicts) {
759
+ const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;
760
+ if (onConflict === "error") throw new Error(`[Conloca] ${message}`);
761
+ if (onConflict === "warn") logger.warn(message);
762
+ }
763
+ }
764
+ }
765
+ };
766
+ }
767
+
768
+ //#endregion
769
+ export { blockMetaSchema, conlocaCMS, conlocaLoader, findHydratableComponents, hasHydratableComponents, isHydratable, pageMetaSchema, scanForHydratableComponents, serializeProps, withHydration };
770
+ //# sourceMappingURL=index.mjs.map