@conloca/astro-cms 0.1.14 → 0.1.15

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