@conloca/astro-cms 0.1.15 → 0.1.16

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 (160) hide show
  1. package/README.md +65 -5
  2. package/dist/collections-Bd7EME4b.mjs +129 -0
  3. package/dist/collections-Bd7EME4b.mjs.map +1 -0
  4. package/dist/collections.d.mts +0 -1
  5. package/dist/collections.d.mts.map +1 -1
  6. package/dist/collections.mjs +1 -64
  7. package/dist/components.d.mts +2 -7
  8. package/dist/components.d.mts.map +1 -1
  9. package/dist/components.mjs +3 -6
  10. package/dist/components.mjs.map +1 -1
  11. package/dist/hydration.d.mts +2 -2
  12. package/dist/hydration.mjs +2 -3
  13. package/dist/index.d.mts +6 -37
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +7 -6
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/internal/cms-handler.d.mts +0 -1
  18. package/dist/internal/cms-handler.d.mts.map +1 -1
  19. package/dist/internal/cms-handler.mjs +55 -8
  20. package/dist/internal/cms-handler.mjs.map +1 -1
  21. package/dist/lib/hydration-script.d.mts +1 -2
  22. package/dist/lib/hydration-script.d.mts.map +1 -1
  23. package/dist/lib/hydration-script.mjs +1 -2
  24. package/dist/lib/hydration-script.mjs.map +1 -1
  25. package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
  26. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
  27. package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
  28. package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
  29. package/dist/node/content.d.mts +0 -1
  30. package/dist/node/content.d.mts.map +1 -1
  31. package/dist/node/content.d.ts +3 -0
  32. package/dist/node/content.d.ts.map +1 -0
  33. package/dist/node/content.js +2 -0
  34. package/dist/node/content.mjs +2 -4
  35. package/dist/node/index.d.mts +151 -3
  36. package/dist/node/index.d.mts.map +1 -1
  37. package/dist/node/index.d.ts +4 -0
  38. package/dist/node/index.d.ts.map +1 -0
  39. package/dist/node/index.js +3 -0
  40. package/dist/node/index.mjs +1857 -97
  41. package/dist/node/index.mjs.map +1 -1
  42. package/dist/{serialize-props-Dhv_MnkY.mjs → serialize-props-BHoNpzH6.mjs} +2 -3
  43. package/dist/{serialize-props-Dhv_MnkY.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
  44. package/dist/src/cms-handler.d.ts +19 -0
  45. package/dist/src/cms-handler.d.ts.map +1 -0
  46. package/dist/src/cms-handler.js +366 -0
  47. package/dist/src/collections.d.ts +32 -0
  48. package/dist/src/collections.d.ts.map +1 -0
  49. package/dist/src/collections.js +50 -0
  50. package/dist/src/components/HydrationWrapper.d.ts +18 -0
  51. package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
  52. package/dist/src/components/HydrationWrapper.js +21 -0
  53. package/dist/src/components/RenderWithBlocks.d.ts +23 -0
  54. package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
  55. package/dist/src/components/RenderWithBlocks.js +129 -0
  56. package/dist/src/components/RenderWithHydration.d.ts +17 -0
  57. package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
  58. package/dist/src/components/RenderWithHydration.js +36 -0
  59. package/dist/src/components.d.ts +4 -0
  60. package/dist/src/components.d.ts.map +1 -0
  61. package/dist/src/components.js +3 -0
  62. package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
  63. package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
  64. package/dist/src/discovery/astro-frontmatter.js +24 -0
  65. package/dist/src/discovery/extract-props-ts.d.ts +41 -0
  66. package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
  67. package/dist/src/discovery/extract-props-ts.js +231 -0
  68. package/dist/src/discovery/merge-registry.d.ts +58 -0
  69. package/dist/src/discovery/merge-registry.d.ts.map +1 -0
  70. package/dist/src/discovery/merge-registry.js +332 -0
  71. package/dist/src/discovery/registry-endpoint.d.ts +42 -0
  72. package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
  73. package/dist/src/discovery/registry-endpoint.js +81 -0
  74. package/dist/src/discovery/scan-components.d.ts +98 -0
  75. package/dist/src/discovery/scan-components.d.ts.map +1 -0
  76. package/dist/src/discovery/scan-components.js +399 -0
  77. package/dist/src/discovery/scan-mdx.d.ts +63 -0
  78. package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
  79. package/dist/src/discovery/scan-mdx.js +112 -0
  80. package/dist/src/discovery/scan-overrides.d.ts +71 -0
  81. package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
  82. package/dist/src/discovery/scan-overrides.js +33 -0
  83. package/dist/src/hydration.d.ts +4 -0
  84. package/dist/src/hydration.d.ts.map +1 -0
  85. package/dist/src/hydration.js +4 -0
  86. package/dist/src/index.d.ts +11 -0
  87. package/dist/src/index.d.ts.map +1 -0
  88. package/dist/src/index.js +25 -0
  89. package/dist/src/lib/hydration-scanner.d.ts +47 -0
  90. package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
  91. package/dist/src/lib/hydration-scanner.js +135 -0
  92. package/dist/src/lib/hydration-script.d.ts +28 -0
  93. package/dist/src/lib/hydration-script.d.ts.map +1 -0
  94. package/dist/src/lib/hydration-script.js +88 -0
  95. package/dist/src/lib/hydration-utils.d.ts +51 -0
  96. package/dist/src/lib/hydration-utils.d.ts.map +1 -0
  97. package/dist/src/lib/hydration-utils.js +83 -0
  98. package/dist/src/lib/page-api.d.ts +77 -0
  99. package/dist/src/lib/page-api.d.ts.map +1 -0
  100. package/dist/src/lib/page-api.js +121 -0
  101. package/dist/src/lib/route-utils.d.ts +41 -0
  102. package/dist/src/lib/route-utils.d.ts.map +1 -0
  103. package/dist/src/lib/route-utils.js +78 -0
  104. package/dist/src/lib/routing-config.d.ts +32 -0
  105. package/dist/src/lib/routing-config.d.ts.map +1 -0
  106. package/dist/src/lib/routing-config.js +93 -0
  107. package/dist/src/lib/serialize-props.d.ts +6 -0
  108. package/dist/src/lib/serialize-props.d.ts.map +1 -0
  109. package/dist/src/lib/serialize-props.js +7 -0
  110. package/dist/src/lib/virtual-module-generators.d.ts +57 -0
  111. package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
  112. package/dist/src/lib/virtual-module-generators.js +263 -0
  113. package/dist/src/lib/withHydration.d.ts +51 -0
  114. package/dist/src/lib/withHydration.d.ts.map +1 -0
  115. package/dist/src/lib/withHydration.js +49 -0
  116. package/dist/src/loader.d.ts +14 -0
  117. package/dist/src/loader.d.ts.map +1 -0
  118. package/dist/src/loader.js +89 -0
  119. package/dist/src/locales-helpers.d.ts +61 -0
  120. package/dist/src/locales-helpers.d.ts.map +1 -0
  121. package/dist/src/locales-helpers.js +49 -0
  122. package/dist/src/mime-types.d.ts +3 -0
  123. package/dist/src/mime-types.d.ts.map +1 -0
  124. package/dist/src/mime-types.js +19 -0
  125. package/dist/src/path-validation.d.ts +8 -0
  126. package/dist/src/path-validation.d.ts.map +1 -0
  127. package/dist/src/path-validation.js +12 -0
  128. package/dist/src/plugin-spa.d.ts +164 -0
  129. package/dist/src/plugin-spa.d.ts.map +1 -0
  130. package/dist/src/plugin-spa.js +972 -0
  131. package/dist/src/safe-json-stringify.d.ts +13 -0
  132. package/dist/src/safe-json-stringify.d.ts.map +1 -0
  133. package/dist/src/safe-json-stringify.js +6 -0
  134. package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
  135. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  136. package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
  137. package/dist/src/site-styles/render-endpoint.d.ts +55 -0
  138. package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
  139. package/dist/src/site-styles/render-endpoint.js +263 -0
  140. package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
  141. package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
  142. package/dist/src/site-styles/styles-endpoint.js +158 -0
  143. package/dist/src/types.d.ts +627 -0
  144. package/dist/src/types.d.ts.map +1 -0
  145. package/dist/src/types.js +1 -0
  146. package/dist/{types-CVQNmPxF.d.mts → types-CS9neadI.d.mts} +193 -3
  147. package/dist/types-CS9neadI.d.mts.map +1 -0
  148. package/dist/virtual-modules.d.ts +155 -0
  149. package/dist/{withHydration-EzyzBQ-Y.mjs → withHydration-C256ox_6.mjs} +2 -2
  150. package/dist/{withHydration-EzyzBQ-Y.mjs.map → withHydration-C256ox_6.mjs.map} +1 -1
  151. package/dist/{withHydration-HIvO9ysY.d.mts → withHydration-DkKpkmzJ.d.mts} +1 -2
  152. package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
  153. package/package.json +82 -26
  154. package/dist/collections.mjs.map +0 -1
  155. package/dist/hydration-scanner-B0NjYkZ_.mjs +0 -109
  156. package/dist/hydration-scanner-B0NjYkZ_.mjs.map +0 -1
  157. package/dist/loader-By-AQWHc.mjs +0 -68
  158. package/dist/loader-By-AQWHc.mjs.map +0 -1
  159. package/dist/types-CVQNmPxF.d.mts.map +0 -1
  160. package/dist/withHydration-HIvO9ysY.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/lib/routing-config.ts","../../src/lib/virtual-module-generators.ts","../../src/plugin-spa.ts"],"sourcesContent":["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/reader';\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 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// FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.\n// It provides the React Fast Refresh preamble script needed for HMR in virtual modules.\n// If @vitejs/plugin-react removes or renames this property, the assertion below will\n// fail immediately at dev startup. Test after any @vitejs/plugin-react update.\nif (typeof viteReact.preambleCode !== 'string') {\n throw new Error(\n '@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +\n 'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +\n 'Check @vitejs/plugin-react release notes and update the preamble injection logic.',\n );\n}\n\nconst reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');\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, '..', 'internal', 'page-handler.astro');\nconst CMS_HANDLER_PATH = join(__dirname, '..', 'internal', 'cms-handler.mjs');\nconst ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', 'internal', 'acorn-default.mjs');\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\nasync function loadContentApiNode() {\n return import('@conloca/content-api/node');\n}\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 * CSS files to load in the CMS editor for component preview styling.\n *\n * Each file is processed by Vite (Tailwind, PostCSS, etc.) and injected\n * directly into Puck's preview iframe `<head>`. Site CSS never enters the\n * CMS admin's parent document, so host-site styles cannot bleed into the\n * CMS chrome (drawer, sidebar, etc.).\n *\n * @example './src/styles/global.css'\n * @example ['./src/styles/global.css', './src/styles/theme.css']\n */\n siteStyles?: string | 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 // 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${reactRefreshPreamble}\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\n// Template for the site styles loader virtual module.\n//\n// Each CSS file is imported with Vite's `?inline` query so the full CSS\n// pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet\n// as a string — no `<style>` tag is injected into the CMS admin's parent\n// `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles\n// registry; the editor's iframe bridge then injects them directly into\n// Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS\n// chrome and confines it to the intended consumer (the preview).\nconst siteStylesLoader = (cssPaths: string[]) => {\n const imports = cssPaths\n .map((p, i) => {\n const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;\n return `import css${i} from '${absolutePath}?inline';`;\n })\n .join('\\n');\n const vars = cssPaths.map((_, i) => `css${i}`).join(', ');\n\n return `\n${imports}\nimport { setSiteStyles } from '@conloca/cms-spa/site-styles';\n\nsetSiteStyles([${vars}]);\n\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\nexport default {};\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 let refreshConlocaContent: (() => Promise<void>) | undefined;\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 const devSsrNoExternal = [/^@conloca\\//, '@puckeditor/core'];\n const serverOnlyExternal = [\n '@conloca/content-api',\n '@conloca/content-api/node',\n '@conloca/content-api/reader',\n '@conloca/content-api/schemas',\n '@conloca/mdx',\n '@conloca/mdx/node',\n '@node-rs/xxhash',\n '@node-rs/xxhash-linux-x64-gnu',\n '@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node',\n ];\n updateConfig({\n vite: {\n ssr: {\n // In dev, linked workspace packages need to be bundled so React resolves\n // through Vite and HMR works from source.\n noExternal: command === 'dev' ? devSsrNoExternal : [],\n // Keep Node-only content processing packages external so SSR builds do not\n // try to bundle native dependencies like xxhash.\n external: serverOnlyExternal,\n },\n build: {\n rollupOptions: {\n external: [\n '@node-rs/xxhash',\n '@node-rs/xxhash-linux-x64-gnu',\n '@node-rs/xxhash-linux-x64-gnu/xxhash.linux-x64-gnu.node',\n ],\n },\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\n // Alias acorn to a CJS shim only during SSR (static page builds).\n // Must NOT apply to the browser bundle — the shim uses createRequire\n // which is Node.js-only and crashes in the browser.\n {\n name: 'conloca-acorn-ssr-alias',\n enforce: 'pre' as const,\n resolveId(id, _importer, options) {\n if (id === 'acorn' && options?.ssr) {\n return ACORN_DEFAULT_SHIM_PATH;\n }\n return null;\n },\n },\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_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_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 and React Query to avoid multiple instances when using symlinked packages.\n // Without this, bun link causes esbuild to find nested copies in the symlink target's\n // node_modules, creating separate React.createContext() calls = broken context sharing.\n dedupe: [\n 'react',\n 'react-dom',\n 'react/jsx-runtime',\n 'react/jsx-dev-runtime',\n '@puckeditor/core',\n '@tanstack/react-query',\n ],\n // Prevent symlinked packages (via bun link) from resolving dependencies\n // from their real path. Ensures @conloca packages find React from the\n // consumer project's node_modules, not from their source repo.\n preserveSymlinks: true,\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 '@puckeditor/core',\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 // Normalize @conloca/* imports from symlinked source files (bun link).\n // When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports\n // resolve relative to the real filesystem location, creating duplicate\n // module instances. This plugin re-resolves them from the consumer\n // project root so all @conloca packages use the same module identity.\n {\n name: 'conloca-resolve-normalizer',\n enforce: 'pre' as const,\n async resolveId(source, importer) {\n // Only normalize @conloca/* bare specifiers\n if (!source.startsWith('@conloca/')) return null;\n // Only when imported from outside the project (symlinked source files)\n if (!importer || importer.startsWith(astroRoot)) return null;\n // Skip virtual modules (prefixed with \\0)\n if (importer.startsWith('\\0')) return null;\n // Re-resolve from project root to ensure consumer's node_modules is used\n const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });\n return resolved;\n },\n },\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 === `${cmsRoute}/site-styles.js`) {\n return id;\n }\n if (id === VIRTUAL_PAGE_API) {\n return RESOLVED_PAGE_API;\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 === `${cmsRoute}/site-styles.js`) {\n if (options.siteStyles) {\n const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];\n return siteStylesLoader(paths);\n }\n return 'export default {};';\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_CMS_SPA_ENTRY) {\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 realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\n // Prefer the consumer-side symlink path when @conloca/cms-spa is\n // linked in from another workspace (e.g. cross-repo `bun link`).\n // Importing via the symlink path keeps `react`/`react-dom`\n // resolving through the consumer's node_modules walk under\n // `preserveSymlinks: true`, which prevents duplicate React\n // instances inside the CMS SPA. Same-workspace installs either\n // don't expose this path or point at the same underlying file,\n // so behavior and HMR are preserved.\n const linkedSrcMainPath = join(\n astroRoot,\n 'node_modules',\n '@conloca',\n 'cms-spa',\n 'src',\n 'main.tsx',\n );\n const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;\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 mounting entry\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n } catch {\n // Fallback: use package import\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${reactRefreshPreamble}\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 const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();\n\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 async () => {\n await refreshConlocaContent?.();\n },\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: CMS_HANDLER_PATH,\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: CMS_HANDLER_PATH,\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger, refreshContent }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\n\n let refreshChain = Promise.resolve();\n\n refreshConlocaContent = async () => {\n if (!refreshContent) {\n return;\n }\n\n refreshChain = refreshChain\n .catch(() => undefined)\n .then(async () => {\n await refreshContent({ loaders: ['conloca-loader'] });\n });\n\n await refreshChain;\n };\n\n // Register dev-time content refresh after the Vite server exists.\n // This keeps Astro collections in sync with Conloca's own file watcher.\n logger.debug('Registering Conloca content refresh handler');\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 project routes that conflict with injected routes.\n // Integration routes (origin: 'external') sharing the same catch-all pattern\n // is expected — Astro's prerender fallthrough handles coexistence automatically.\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n if (route.origin !== 'project') continue;\n\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: route.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":";;;;;;;;;;;;;;;;;AAWA,SAAgB,uBACd,OACA,gBAC2B;AAE3B,KAAI,UAAU,UAAa,eACzB,QAAO;EACL,SAAS;EACT,QAAQ,EACN,OAAO;GACL,SAAS;GACT,YAAY;GACZ,QAAQ;GACR,WAAW;GACZ,EACF;EACD,UAAU;EACV,YAAY;EACb;AAGH,KAAI,UAAU,OACZ;AAGF,KAAI,UAAU,KACZ,QAAO;EACL,SAAS;EACT,QAAQ,EACN,OAAO;GACL,SAAS;GACT,YAAY;GACZ,WAAW;GACZ,EACF;EACD,UAAU;EACV,YAAY;EACb;AAGH,KAAI,UAAU,MACZ,QAAO,EAAE,SAAS,OAAO;AAG3B,QAAO;;;;;;;;;;AAWT,SAAgB,mBAAmB,QAA4C;AAC7E,QAAO;EACL,SAAS,OAAO;EAChB,YAAY,OAAO,cAAc;EACjC,QAAQ,OAAO,UAAU;EACzB,WAAW,OAAO,aAAa;EAC/B,MAAM,OAAO,QAAQ,EAAE;EACvB,cAAc,OAAO,gBAAgB,EAAE,aAAa,EAAE,EAAE;EACzD;;;;;;;;;;;;;AChEH,SAAgB,4BAA4B,QAAuC;AACjF,QAAO,kBAAkB,KAAK,UAAU,QAAQ,MAAM,EAAE,CAAC;;;;;;;;;;;;;AAc3D,SAAgB,qBAAqB,SAA4C;CAE/E,MAA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AKnG,MAAM,YAAuD,EAAE;AAE/D,SAAK,MAAM,SAAS,QAAQ;AAC1B,SAAI,MAAM,WAAW,UAAW;KAEhC,MAAM,UAAU,MAAM;AACtB,SAAI,iBAAiB,IAAI,QAAQ,CAC/B,WAAU,KAAK;MACb,UAAU;MACV,WAAW,MAAM,cAAc;MAChC,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"}
1
+ {"version":3,"file":"index.mjs","names":["scanFile"],"sources":["../../src/lib/hydration-scanner.ts","../../src/discovery/merge-registry.ts","../../src/discovery/astro-frontmatter.ts","../../src/discovery/extract-props-ts.ts","../../src/discovery/scan-components.ts","../../src/discovery/scan-mdx.ts","../../src/discovery/scan-overrides.ts","../../src/discovery/registry-endpoint.ts","../../src/lib/routing-config.ts","../../src/site-styles/content-wrapper-endpoint.ts","../../src/site-styles/render-endpoint.ts","../../src/site-styles/styles-endpoint.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\nexport const HYDRATION_IMPORT_PATTERN =\n /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\")\nexport const 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(puckConfigPath: string, explicitPaths?: string[]): 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 { MdxComponentProp, MdxJsxComponentDescriptor } from '@conloca/cms-spa/mdx-components';\nimport type { LocalComponentScanResult, ParsedProp } from './scan-components';\nimport type { MdxImport, MdxScanResult } from './scan-mdx';\nimport type { CmsOverride } from './scan-overrides';\n\n/**\n * Combine the MDX usage scan with the local-component folder scan\n * into the final flat list of component descriptors the editor\n * registry consumes.\n *\n * Rules (chosen to match the decisions locked in earlier this\n * session — usage-only inference for npm, full interface schema\n * for local, per-file context wins on name collisions, aliases\n * preserved per file):\n *\n * 1. Every component referenced by an `import` in any MDX file\n * becomes a descriptor. The `name` is the canonical export\n * name (`Aside`, not `Callout`), the `source` is the import\n * path. This catches npm packages we can't statically scan.\n *\n * 2. Every component found by the local folder scan is also a\n * descriptor. Its props come from the parsed `Props` interface.\n * If the same canonical (name, source) was also seen in MDX,\n * we merge — interface props win on the schema, usage-observed\n * string values enrich `options`.\n *\n * 3. Components seen in MDX but never declared in any import\n * (raw HTML tags like `<div>` or unresolved names) are dropped —\n * `GenericBlock` already has its own HTML-passthrough path.\n *\n * 4. Across all usages, observed string values per attribute are\n * collected. When ≤5 distinct values are seen (and the prop\n * doesn't already have explicit options from the interface),\n * they're added as dropdown choices.\n *\n * 5. Aliases (file-local imports renaming the canonical export,\n * eg `import { Aside as Callout }`) are tracked on the\n * descriptor's `aliases` map keyed by file path. The save\n * serializer reads this to preserve the alias when writing\n * the file back out.\n *\n * 6. Name collisions across different sources (local `<Card>` vs\n * Starlight `<Card>`) — the higher-usage source wins; ties\n * break in favor of the source whose props came from an\n * interface schema. The dropped alternative isn't lost from\n * the merge itself — it just doesn't surface in the registry\n * until per-file disambiguation exists in the insert flow.\n */\n\n/** Same shape as `MdxJsxComponentDescriptor` from cms-spa, extended\n * with `aliases` so save serialization can preserve `import { X as Y }`\n * per file. Cms-spa's runtime type doesn't need to know about\n * aliases — they're picked up server-side at save time. */\nexport interface DiscoveredComponent extends MdxJsxComponentDescriptor {\n /** Per-file local alias (when the file uses `import { X as Y }`).\n * Map key is the absolute MDX file path. */\n aliases?: Record<string, string>;\n}\n\nexport function mergeRegistry(\n mdxScans: MdxScanResult[],\n localComponents: LocalComponentScanResult[],\n overrides?: Map<string, CmsOverride>,\n): DiscoveredComponent[] {\n // Key descriptors by `${source}::${exportName}` so we can merge\n // local-folder data with MDX-usage data and so two components\n // with the same name but different sources stay separate.\n const byKey = new Map<string, DescriptorBuilder>();\n\n // Pass 1: seed from local folder scan.\n for (const comp of localComponents) {\n const key = `${comp.source}::${comp.name}`;\n byKey.set(\n key,\n new DescriptorBuilder({\n name: comp.name,\n source: comp.source,\n defaultExport: false,\n kind: comp.kind,\n propsFromInterface: comp.props,\n }),\n );\n }\n\n // Pass 2: seed/enrich from MDX usage scans.\n for (const scan of mdxScans) {\n for (const usage of scan.usages) {\n const imp = scan.imports[usage.name];\n if (!imp) continue; // raw HTML tag or unresolved — skip.\n const canonicalName = imp.exportName === 'default' ? usage.name : imp.exportName;\n const key = `${imp.source}::${canonicalName}`;\n\n let builder = byKey.get(key);\n if (!builder) {\n builder = new DescriptorBuilder({\n name: canonicalName,\n source: imp.source,\n defaultExport: imp.defaultExport,\n kind: usage.kind,\n });\n byKey.set(key, builder);\n }\n builder.observeUsage(usage.attrs, scan.filepath, usage.name, imp, usage.kind);\n }\n }\n\n // Resolve name collisions: when two (source, name) pairs share a\n // `name`, the editor registry can only key one descriptor by that\n // name. Pick the source that has the most MDX usage; the dropped\n // alternative isn't lost forever — it just doesn't surface in the\n // registry until the disambiguation UI exists.\n const grouped = new Map<string, DescriptorBuilder[]>();\n for (const builder of byKey.values()) {\n const arr = grouped.get(builder.name) ?? [];\n arr.push(builder);\n grouped.set(builder.name, arr);\n }\n const winners: DiscoveredComponent[] = [];\n for (const candidates of grouped.values()) {\n candidates.sort((a, b) => {\n // Higher actual MDX usage wins.\n if (a.usageCount !== b.usageCount) return b.usageCount - a.usageCount;\n // Tie: prefer the one with an interface-derived schema (more\n // likely to be the right one).\n const aHasSchema = a.hasInterfaceSchema();\n const bHasSchema = b.hasInterfaceSchema();\n if (aHasSchema !== bHasSchema) return aHasSchema ? -1 : 1;\n return 0;\n });\n let descriptor = candidates[0].toDescriptor();\n const override = overrides?.get(descriptor.name);\n if (override) descriptor = applyOverride(descriptor, override);\n winners.push(descriptor);\n }\n return winners;\n}\n\n/**\n * Apply a host-provided override to an auto-discovered descriptor.\n *\n * Three kinds of merges happen:\n *\n * 1. **Shallow object merges** for `insert` and `defaults` — host\n * fields overwrite inferred fields one key at a time, so a host\n * can tweak only the label without losing the inferred category.\n *\n * 2. **Per-prop merges** for the `props` array — match by `name`,\n * override individual fields (`required`, `label`, `help`,\n * `options`) while keeping the rest of the prop's inferred\n * schema (type, defaultValue). Props the override doesn't mention\n * stay untouched.\n *\n * 3. **Scalar overrides** for `hasChildren` and `kind` — host value\n * replaces inferred value directly.\n *\n * The override is INTENTIONALLY a subset of `MdxJsxComponentDescriptor`\n * — fields the host can sensibly customize. Things like `name` and\n * `import` come from the actual file system / MDX scan and can't be\n * meaningfully overridden by a sidecar JSON.\n */\nfunction applyOverride(descriptor: DiscoveredComponent, override: CmsOverride): DiscoveredComponent {\n const next: DiscoveredComponent = { ...descriptor };\n\n if (override.insert) {\n next.insert = { ...(descriptor.insert ?? { label: descriptor.name }), ...override.insert };\n }\n if (override.defaults) {\n next.defaults = {\n ...(descriptor.defaults ?? {}),\n ...override.defaults,\n ...(override.defaults.attributes\n ? { attributes: { ...(descriptor.defaults?.attributes ?? {}), ...override.defaults.attributes } }\n : {}),\n };\n }\n if (override.hasChildren !== undefined) {\n next.hasChildren = override.hasChildren;\n }\n if (override.kind) {\n next.kind = override.kind;\n }\n if (override.props && descriptor.props) {\n const overridesByName = override.props;\n next.props = descriptor.props.map((p) => {\n const o = overridesByName[p.name];\n if (!o) return p;\n // Cast through string-type narrowing — `options` and `defaultValue`\n // shape vary per prop type, so we merge field-by-field and\n // preserve the discriminated union by keeping the original\n // `type` value.\n const merged: MdxComponentProp = { ...p };\n if (o.required !== undefined) merged.required = o.required;\n if (o.label !== undefined) merged.label = o.label;\n if (o.help !== undefined) merged.help = o.help;\n if (o.options && merged.type === 'string') {\n (merged as MdxComponentProp & { options?: ReadonlyArray<{ value: string; label: string }> }).options =\n o.options;\n }\n return merged;\n });\n }\n\n return next;\n}\n\n/** Internal accumulator. Combines interface-derived schema with\n * usage-derived observations as scans arrive. */\nclass DescriptorBuilder {\n readonly name: string;\n private readonly source: string;\n private readonly defaultExport: boolean;\n /**\n * Component flow/text kind. Mutable across `observeUsage` calls\n * because mdast classifies the SAME component differently based on\n * how each instance is authored in source: `<Steps>...</Steps>` on\n * one line parses as `mdxJsxTextElement` (inline), but the same\n * component with blank-line-separated children parses as\n * `mdxJsxFlowElement` (block). The component's intrinsic nature is\n * \"block\" — so any single flow observation must promote the kind\n * from text to flow. Without this, one stray inline usage in a\n * fixture poisons the registry, MDXEditor mounts the JSX as inline,\n * and saves serialize block components as single-line MDX — which\n * Starlight's strict-slot validators (Steps wants `<ol>`, FileTree\n * wants `<ul>`) then reject at render time.\n *\n * Demotion in the other direction never happens: a component seen\n * as flow even once is intrinsically flow-capable, regardless of\n * other inline observations.\n */\n private kind: 'flow' | 'text';\n private readonly propsFromInterface: ParsedProp[];\n /** propName → set of distinct string values observed in MDX. */\n private readonly observedValues = new Map<string, Set<string>>();\n /** filepath → local alias used in that file (when ≠ canonical). */\n private readonly aliases: Record<string, string> = {};\n /** Names of props we've seen in usage but that aren't in the\n * interface (or for npm components where there's no interface). */\n private readonly observedPropNames = new Set<string>();\n /** How many `<Foo>` usages of this component were seen across all\n * MDX files. Used to pick a winner on name collisions. */\n usageCount = 0;\n\n constructor(init: {\n name: string;\n source: string;\n defaultExport: boolean;\n kind: 'flow' | 'text';\n propsFromInterface?: ParsedProp[];\n }) {\n this.name = init.name;\n this.source = init.source;\n this.defaultExport = init.defaultExport;\n this.kind = init.kind;\n this.propsFromInterface = init.propsFromInterface ?? [];\n }\n\n observeUsage(\n attrs: Record<string, string>,\n filepath: string,\n localName: string,\n imp: MdxImport,\n observedKind: 'flow' | 'text',\n ): void {\n this.usageCount++;\n // Flow-wins promotion (see kind field doc above).\n if (observedKind === 'flow') this.kind = 'flow';\n if (imp.aliasedFrom && localName !== this.name) {\n this.aliases[filepath] = localName;\n }\n for (const [propName, value] of Object.entries(attrs)) {\n this.observedPropNames.add(propName);\n if (!this.observedValues.has(propName)) this.observedValues.set(propName, new Set());\n this.observedValues.get(propName)!.add(value);\n }\n }\n\n hasInterfaceSchema(): boolean {\n return this.propsFromInterface.length > 0;\n }\n\n toDescriptor(): DiscoveredComponent {\n const interfacePropNames = new Set(this.propsFromInterface.map((p) => p.name));\n\n const props: MdxComponentProp[] = [];\n\n // Interface props first — full schema with types and (interface-\n // declared) options.\n for (const ip of this.propsFromInterface) {\n props.push(toMdxComponentProp(ip, this.observedValues.get(ip.name)));\n }\n\n // Usage-observed props that weren't in the interface (or were\n // never in any interface — npm components). Inferred as plain\n // strings; we don't auto-promote observed values to a dropdown\n // because there's no interface declaration telling us the prop\n // is meant to be enum-like. Authors who want a curated picker\n // can declare options via the sidecar `cmsConfig` override\n // (see scan-overrides.ts).\n for (const name of this.observedPropNames) {\n if (interfacePropNames.has(name)) continue;\n props.push({ name, type: 'string' });\n }\n\n // Build `defaults.attributes` for every required prop. The insert\n // flow (buildInsertPayload) merges these as starter attributes when\n // a fresh `<Component>` is dropped in, so components like\n // `<TabItem label=\"...\">` never get inserted as `<TabItem />` and\n // immediately fail Astro's component validation at render time.\n //\n // Placeholder priority per prop:\n // 1. First literal-union option if the prop has one (Aside.type\n // → 'note'). The component's own type system says this is a\n // valid value, so it's the safest choice.\n // 2. First observed usage value if any author file already passes\n // something (TabItem.label → 'Bun' from a Starlight fixture).\n // Reuses authored content as the starter so the insert looks\n // stylistically consistent with the rest of the project.\n // 3. Title-cased prop name as final fallback (Card.title →\n // 'Title'). Always editable — the placeholder text becomes the\n // first thing the author clicks and overwrites.\n const requiredAttributes: Record<string, string | number | boolean> = {};\n for (const p of props) {\n if (!p.required) continue;\n requiredAttributes[p.name] = placeholderForProp(p, this.observedValues.get(p.name));\n }\n\n const descriptor: DiscoveredComponent = {\n name: this.name,\n kind: this.kind,\n hasChildren: true, // default — most components accept a body slot.\n props,\n import: { from: this.source, ...(this.defaultExport ? { default: true } : {}) },\n // Default `insert` metadata so the toolbar's \"Insert component\"\n // dropdown surfaces every auto-discovered component. Without\n // this, the toolbar's filter (`if (!d.insert) return false`)\n // hides the entry and users have no way to add the block from\n // the UI — only typed-out JSX would work. Hosts can still\n // override label/category via sidecar `cmsConfig` on the\n // component file (when that lands), but the sensible default\n // is the component's own name in a single \"Components\" bucket.\n insert: { label: this.name, category: 'Components' },\n ...(Object.keys(requiredAttributes).length > 0 ? { defaults: { attributes: requiredAttributes } } : {}),\n };\n if (Object.keys(this.aliases).length > 0) descriptor.aliases = this.aliases;\n return descriptor;\n }\n}\n\n/**\n * Pick a sensible starter value for a required prop so the insert flow\n * has something to put on the attribute. See the call site in\n * `DescriptorBuilder.toDescriptor` for the priority rationale; this\n * function just executes it.\n *\n * Number and boolean placeholders are intentionally trivial — `0` and\n * `true` — because numeric/boolean props are rare in MDX components and\n * any concrete value beats `undefined`. The interesting work is on the\n * string path, where union options and observed usage give us real\n * authored values to reuse.\n */\nfunction placeholderForProp(prop: MdxComponentProp, observed: Set<string> | undefined): string | number | boolean {\n if (prop.type === 'number') return 0;\n if (prop.type === 'boolean') return true;\n // string\n if (prop.options && prop.options.length > 0) return prop.options[0].value;\n if (observed && observed.size > 0) {\n const first = observed.values().next();\n if (!first.done) return first.value;\n }\n // Title-case the prop name (`label` → `Label`). The author sees this\n // as the placeholder text on first insert; one click selects it for\n // overwrite.\n return prop.name.charAt(0).toUpperCase() + prop.name.slice(1);\n}\n\nfunction toMdxComponentProp(parsed: ParsedProp, observed: Set<string> | undefined): MdxComponentProp {\n // Only emit dropdown `options` when the interface itself declared a\n // literal union (eg `type?: 'note' | 'tip' | 'caution' | 'danger'`).\n // Free-form string props like `title`, `description`, `href` have no\n // such union — emitting an `options` array based purely on what we\n // observed in usage would lock authors to past values when the field\n // is meant to accept any text. The side panel renders prop fields with\n // options as `<select>` and prop fields without as `<input type=text>`,\n // so this single switch decides which one shows up. Observed values\n // can still enrich a real enum: when `parsed.options` IS set, append\n // any usage-seen values the interface didn't list (capped at 5 distinct).\n let optionStrings: string[] | undefined = parsed.options;\n if (optionStrings && observed && observed.size > 0) {\n const combined = new Set<string>(optionStrings);\n for (const v of observed) combined.add(v);\n if (combined.size <= 5) optionStrings = Array.from(combined);\n }\n\n if (parsed.type === 'number') {\n return { name: parsed.name, type: 'number', required: parsed.required };\n }\n if (parsed.type === 'boolean') {\n return { name: parsed.name, type: 'boolean', required: parsed.required };\n }\n // 'string' and 'expression' both render as a text input by default.\n // Treat 'expression' as a free-form string for editor purposes —\n // it's an escape hatch already.\n return {\n name: parsed.name,\n type: 'string',\n required: parsed.required,\n ...(optionStrings && optionStrings.length > 0\n ? { options: optionStrings.map((v) => ({ value: v, label: v })) }\n : {}),\n };\n}\n","/**\n * Extract the frontmatter (the `---`-fenced TypeScript block) from\n * an `.astro` source file. Returns the inner text, or `null` if no\n * frontmatter is present (a valid Astro file shape — props-less\n * components without `<script>` of any kind).\n *\n * Astro's official compiler (`@astrojs/compiler`) exposes a full\n * parser, but for the props-extraction use case all we need is the\n * text between the opening and closing fences. A regex is sufficient\n * and keeps this synchronous (no WASM init cost, no async).\n *\n * The fence rule is simple: the file must start with `---\\n` and\n * close with `\\n---` followed by either a newline or end-of-file.\n * Whitespace before the opening fence is rejected — Astro itself\n * requires the fence at column 0.\n */\nexport function extractAstroFrontmatter(content: string): string | null {\n // `^---\\r?\\n` opens; `\\r?\\n---\\s*(?:\\r?\\n|$)` closes.\n // Capturing the inner content lazily so a body containing `---`\n // (eg a horizontal rule string inside a default-prop) doesn't\n // truncate. Astro itself uses the same \"first ---/--- pair\" rule.\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\s*(?:\\r?\\n|$)/.exec(content);\n return match ? match[1] : null;\n}\n","/**\n * TypeScript-aware extraction of a component's `Props` interface,\n * replacing the regex-based path in `scan-components.ts`. Uses\n * `ts-morph` (a thin wrapper over the TypeScript compiler API) so\n * derived types — `(typeof asideVariants)[number]`, mapped types,\n * imported aliases, conditional types — resolve to their concrete\n * literal-union values. The regex scanner couldn't follow any\n * indirection and silently dropped options for those props (Aside's\n * `type` being the canonical example).\n *\n * The output shape is identical to the regex path (`ParsedProp[]`)\n * so the rest of the discovery pipeline doesn't change.\n *\n * Astro files are handled by extracting the frontmatter block and\n * feeding it to the Project as a virtual `.ts` source — see\n * `extractAstroFrontmatter` in `astro-frontmatter.ts`.\n */\n\nimport {\n type InterfaceDeclaration,\n ModuleKind,\n ModuleResolutionKind,\n Project,\n type PropertySignature,\n ScriptTarget,\n type SourceFile,\n type Type,\n type TypeAliasDeclaration,\n type TypeLiteralNode,\n} from 'ts-morph';\nimport type { ParsedProp } from './scan-components.js';\n\n/**\n * One Project per scan run, reused across `extractPropsViaTs` calls\n * within the same scan. Building the Project loads `lib.dom.d.ts`\n * etc. which dominates cold-start cost (~500ms-2s); sharing across\n * files in a scan amortises that. A fresh Project is built per scan\n * run so file changes are picked up — ts-morph's `addSourceFile`\n * caches by path and wouldn't see external edits otherwise.\n */\nexport function createScanProject(tsConfigFilePath?: string): Project {\n // When the host has a tsconfig, use it — that's how cross-file\n // `typeof` refs and path mappings (`@/foo`) resolve. Without one,\n // fall back to permissive defaults that still handle the common\n // shapes (literal unions inside a single file, simple imports).\n if (tsConfigFilePath) {\n try {\n return new Project({\n tsConfigFilePath,\n // Add files explicitly per scan; don't auto-load every file\n // referenced by tsconfig.include — that would slow scans on\n // big projects.\n skipAddingFilesFromTsConfig: true,\n });\n } catch {\n // tsconfig parse failure — fall through to defaults\n }\n }\n return new Project({\n compilerOptions: {\n target: ScriptTarget.ES2022,\n module: ModuleKind.ESNext,\n moduleResolution: ModuleResolutionKind.Bundler,\n allowJs: true,\n esModuleInterop: true,\n skipLibCheck: true,\n strict: false,\n },\n skipAddingFilesFromTsConfig: true,\n });\n}\n\n/**\n * Extract the Props interface from a source string and return the\n * parsed prop list. `filepath` is used as the virtual file's path\n * inside the Project so error messages and source-map debugging\n * point back at the right file; the actual content comes from\n * `sourceText`. `.astro` callers pass the extracted frontmatter as\n * `sourceText` and `${filepath}.virtual.ts` as `filepath`.\n *\n * Returns `[]` when no Props interface is found — same contract as\n * the regex path so callers don't need a special-case branch.\n */\nexport function extractPropsViaTs(\n project: Project,\n filepath: string,\n sourceText: string,\n componentName?: string,\n): ParsedProp[] {\n let sf: SourceFile;\n try {\n sf = project.createSourceFile(filepath, sourceText, { overwrite: true });\n } catch (err) {\n // Source parse failure — eg the .astro frontmatter contained\n // syntax the TS compiler rejected (rare; most front-matter is\n // valid TS). Return empty so the merge layer can still surface\n // the component, just without prop schema.\n console.warn(`[conloca:ts-morph] parse failed for ${filepath}:`, err instanceof Error ? err.message : err);\n return [];\n }\n\n // Try `${ComponentName}Props` first (matches the convention\n // `interface CardProps {...}` used by some libraries), then the\n // bare `Props` name (Astro components and most React components).\n // Try interface declarations first, then type aliases — same\n // priority the regex scanner used.\n const candidates: string[] = [];\n if (componentName) candidates.push(`${componentName}Props`);\n candidates.push('Props');\n\n let propertySignatures: PropertySignature[] = [];\n for (const name of candidates) {\n const iface = sf.getInterface(name);\n if (iface) {\n propertySignatures = collectLocalProperties(iface);\n break;\n }\n const alias = sf.getTypeAlias(name);\n if (alias) {\n propertySignatures = collectAliasProperties(alias);\n break;\n }\n }\n if (propertySignatures.length === 0) {\n project.removeSourceFile(sf);\n return [];\n }\n\n const props: ParsedProp[] = [];\n for (const prop of propertySignatures) {\n const name = prop.getName();\n // `getType()` on the PropertySignature node resolves at the\n // declaration site — this is where `(typeof X)[number]` collapses\n // to its literal union, generics expand, conditional types branch.\n const type = prop.getType();\n const required = !prop.hasQuestionToken();\n props.push(parseType(name, type, required));\n }\n\n // Clean up the virtual source file so successive calls in the\n // same scan don't accumulate sources and bloat memory.\n project.removeSourceFile(sf);\n\n return props;\n}\n\n/**\n * Get ONLY the locally-declared properties on an interface, NOT\n * properties inherited from `extends` clauses. This is the key choice\n * that keeps the side panel sane for components like Starlight's\n * `LinkCard` which declares `extends Omit<HTMLAttributes<'a'>, 'title'>`:\n * the type-level `Type.getProperties()` would include every HTML\n * attribute (~200 entries — `accesskey`, `aria-*`, `on*`, etc), making\n * the panel useless. The declaration-level `iface.getProperties()`\n * returns just the props the author explicitly wrote inside the\n * braces, which is the editor's intent.\n *\n * Trade-off: a property the author \"overrides\" via re-declaration\n * (eg LinkCard's local `title: string` overriding the inherited\n * `title?: string`) appears — good. A property the author NEVER\n * declared locally but the inherited interface defines (eg `href`\n * inherited from HTMLAttributes) does NOT appear — also good, the\n * panel stays focused on what the author wanted to expose. Hosts\n * who want a specific inherited prop surfaced can re-declare it\n * locally or use the sidecar `cmsConfig.props` override.\n */\nfunction collectLocalProperties(iface: InterfaceDeclaration): PropertySignature[] {\n // PropertySignature[] — only what's between this interface's own\n // braces. Inherited properties from `extends` aren't included.\n return iface.getProperties();\n}\n\n/**\n * Type-alias variant. For `type Props = { ... }`, the declaration\n * node is a TypeLiteralNode and we read its own member list. For\n * intersections (`type Props = A & { ... }`) or imported aliases,\n * we get an empty list rather than walking into the constituent\n * types — same author-intent rationale as the interface case.\n */\nfunction collectAliasProperties(alias: TypeAliasDeclaration): PropertySignature[] {\n const node = alias.getTypeNode();\n // ts-morph's `asKind(SyntaxKind.TypeLiteral)` would narrow this\n // cleanly, but we only need the duck-typed check that the node\n // exposes `getMembers()`. A type literal does; an intersection or\n // imported reference doesn't — those return an empty list and the\n // alias is skipped by the caller.\n const members = (node as TypeLiteralNode | undefined)?.getMembers?.();\n if (!members) return [];\n return members.filter((m): m is PropertySignature => m.getKindName() === 'PropertySignature');\n}\n\n/**\n * Map a resolved `Type` to a `ParsedProp`. Mirrors the kind of\n * branching the old regex did, but on real type information.\n */\nfunction parseType(name: string, type: Type, required: boolean): ParsedProp {\n if (type.isString()) return { name, type: 'string', required };\n if (type.isNumber()) return { name, type: 'number', required };\n if (type.isBoolean()) return { name, type: 'boolean', required };\n\n if (type.isUnion()) {\n const members = type.getUnionTypes();\n // Filter out `undefined` (added by the compiler for `?` props\n // under strictNullChecks). The remaining members tell us what\n // the prop actually accepts.\n const nonUndefined = members.filter((m) => !m.isUndefined());\n\n // All-boolean-literal union (`true | false`, or even `true` alone,\n // or `false` alone) → boolean. Under strict mode, `boolean` is\n // canonicalised by the checker into the union `true | false`, so\n // `isBoolean()` on the original type returns false — we have to\n // detect the expanded form. This is the path that catches eg\n // CardGrid's `stagger?: boolean` (resolved as `true | false |\n // undefined`).\n if (nonUndefined.length > 0 && nonUndefined.every((m) => m.isBooleanLiteral() || m.isBoolean())) {\n return { name, type: 'boolean', required };\n }\n\n // String-literal union → string prop with `options`. Even when\n // the union also includes a non-literal `string`, surface the\n // literals as picker suggestions.\n const stringLiterals = nonUndefined\n .filter((m) => m.isStringLiteral())\n .map((m) => m.getLiteralValue())\n .filter((v): v is string => typeof v === 'string');\n if (stringLiterals.length > 0) {\n return { name, type: 'string', required, options: stringLiterals };\n }\n\n // Single non-undefined primitive after stripping the optional\n // undefined — eg `string | undefined` collapses to `string`.\n if (nonUndefined.length === 1) {\n const only = nonUndefined[0];\n if (only.isString()) return { name, type: 'string', required };\n if (only.isNumber()) return { name, type: 'number', required };\n if (only.isBoolean()) return { name, type: 'boolean', required };\n if (only.isStringLiteral()) {\n const v = only.getLiteralValue();\n return { name, type: 'string', required, options: typeof v === 'string' ? [v] : undefined };\n }\n }\n }\n\n if (type.isStringLiteral()) {\n const v = type.getLiteralValue();\n return { name, type: 'string', required, options: typeof v === 'string' ? [v] : undefined };\n }\n if (type.isBooleanLiteral()) {\n return { name, type: 'boolean', required };\n }\n\n // Anything else — function types, object types, branded types,\n // arrays, Records — render as a free-form expression input.\n return { name, type: 'expression', required };\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, extname, relative, resolve } from 'node:path';\nimport fg from 'fast-glob';\nimport type { Project } from 'ts-morph';\nimport { extractAstroFrontmatter } from './astro-frontmatter.js';\nimport { createScanProject, extractPropsViaTs } from './extract-props-ts.js';\nimport type { MdxScanResult } from './scan-mdx';\n\n/**\n * Walks configured folder globs for `.astro` and `.tsx` files,\n * extracts each component's `Props` interface, and returns a\n * descriptor-friendly schema. Used alongside `scan-mdx.ts` to\n * populate the CMS registry without the host hand-writing\n * `mdx-components.tsx`.\n *\n * Type extraction uses the TypeScript compiler API (via ts-morph,\n * see `./extract-props-ts.ts`). Derived types — `(typeof X)[number]`,\n * imported aliases, mapped types, conditional types — all resolve\n * to their concrete shape, which is what makes the registry feel\n * smart for real component libraries (eg Starlight's Aside, whose\n * `type` prop uses indexed access). For `.astro` files we extract\n * the leading `---` frontmatter block and feed it to the same\n * extractor as a virtual `.ts` source.\n *\n * A single ts-morph Project is built per scan run and shared across\n * every file in that run, so the per-file cost is small after the\n * initial type-checker warmup. Sidecar `cmsConfig` overrides still\n * apply (see `./scan-overrides.ts`) for components whose author\n * wants to override or annotate fields beyond what the type says.\n *\n * Component name = basename of the file without extension.\n * Component source = the resolved file path. The render endpoint\n * hands this to `server.ssrLoadModule`, which accepts absolute\n * paths in dev.\n */\nexport interface ParsedProp {\n name: string;\n /** Inferred from the TypeScript type annotation. `'string'` covers\n * literal-string unions too — `options` holds the union values\n * when applicable so the prop panel can render a dropdown. */\n type: 'string' | 'number' | 'boolean' | 'expression';\n /** True when the prop's TS field lacks a `?` modifier. */\n required: boolean;\n /** Literal-string union values, eg `'note' | 'tip' | 'caution'`. */\n options?: string[];\n}\n\nexport interface LocalComponentScanResult {\n /** Absolute file path of the component. */\n filepath: string;\n /** Component name (filename without extension). */\n name: string;\n /** Path to pass to `server.ssrLoadModule` — currently the absolute\n * file path. The path the import statement should use in MDX is\n * the project-relative form (so save serialization stays portable);\n * we keep both. */\n source: string;\n /** Project-relative path used when emitting `import` statements\n * for newly-inserted components. */\n importSpecifier: string;\n /** All components from this scanner are treated as flow (block).\n * Inline-only components are rare in authored libraries; if any\n * surface as text-level usage they get classified at merge time\n * from the MDX scan, not here. */\n kind: 'flow';\n props: ParsedProp[];\n}\n\n/**\n * Scan every `.astro` / `.tsx` file under each configured folder.\n * Folder globs are resolved relative to `projectRoot`.\n */\nexport async function scanLocalComponents(folders: string[], projectRoot: string): Promise<LocalComponentScanResult[]> {\n if (folders.length === 0) return [];\n // Source files (`.astro` for Astro, `.tsx` for React) first; `.d.ts`\n // declaration files only if no matching source file exists. Same\n // priority rationale as `scanExternalComponents` — host source is\n // ground truth, declarations are last-resort schema.\n const sourcePatterns = folders.map((f) => `${f.replace(/\\/+$/, '')}/**/*.{astro,tsx}`);\n const dtsPatterns = folders.map((f) => `${f.replace(/\\/+$/, '')}/**/*.d.ts`);\n const sourceFiles = await fg(sourcePatterns, { cwd: projectRoot, absolute: true, dot: false });\n const dtsFiles = await fg(dtsPatterns, { cwd: projectRoot, absolute: true, dot: false });\n const seen = new Set<string>();\n const allFiles: string[] = [];\n for (const file of sourceFiles) {\n const name = componentNameFromPath(file);\n if (seen.has(name)) continue;\n seen.add(name);\n allFiles.push(file);\n }\n for (const file of dtsFiles) {\n const name = componentNameFromPath(file);\n if (seen.has(name)) continue;\n seen.add(name);\n allFiles.push(file);\n }\n // One ts-morph Project per scan run, shared across every file\n // we extract from. Building the Project loads `lib.dom.d.ts` etc.\n // (the dominant cost ~500ms-2s); sharing across files amortises\n // it. Fed the host's tsconfig when present so cross-file `typeof`\n // refs and path mappings (`@/foo`) resolve as authored.\n const tsConfigFilePath = findTsConfig(projectRoot);\n const project = createScanProject(tsConfigFilePath);\n\n const results: LocalComponentScanResult[] = [];\n for (const file of allFiles) {\n try {\n const r = await scanFile(file, projectRoot, project);\n if (r) results.push(r);\n } catch (err) {\n console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);\n }\n }\n return results;\n}\n\nasync function scanFile(\n filepath: string,\n projectRoot: string,\n project: Project,\n): Promise<LocalComponentScanResult | null> {\n const content = await readFile(filepath, 'utf8');\n const name = componentNameFromPath(filepath);\n // Components typically start with a capital. Lowercase-named files\n // are usually utilities, not authorable components — skip them so\n // we don't pollute the registry with `helpers.ts` and friends.\n if (!/^[A-Z]/.test(name)) return null;\n const props = extractPropsForFile(project, filepath, content, name);\n const importSpecifier = `/${relative(projectRoot, filepath).replace(/\\\\/g, '/')}`;\n return {\n filepath,\n name,\n source: filepath,\n importSpecifier,\n kind: 'flow',\n props,\n };\n}\n\n/**\n * Bridge between the file-level scanner and the ts-morph extractor.\n * Handles the three file types we accept:\n * - `.astro` — extract the `---`-fenced frontmatter, feed it as\n * a virtual `.ts` source.\n * - `.tsx` / `.d.ts` — feed the whole file content directly.\n *\n * The virtual source path is the real filepath suffixed with\n * `.virtual.ts` for `.astro` files, so ts-morph's diagnostics still\n * point back at the right author file. For `.tsx` / `.d.ts` we use\n * the real path verbatim — ts-morph parses TS extensions natively.\n */\nfunction extractPropsForFile(project: Project, filepath: string, content: string, componentName: string): ParsedProp[] {\n if (filepath.endsWith('.astro')) {\n const frontmatter = extractAstroFrontmatter(content);\n if (!frontmatter) return [];\n return extractPropsViaTs(project, `${filepath}.virtual.ts`, frontmatter, componentName);\n }\n return extractPropsViaTs(project, filepath, content, componentName);\n}\n\n/**\n * Locate the host's `tsconfig.json` so the ts-morph Project can\n * resolve cross-file `typeof` refs, path aliases, and node_modules\n * declarations the same way the author's IDE does. Walks up from\n * `projectRoot` looking for the closest tsconfig; returns `undefined`\n * if none found (the Project then uses permissive defaults).\n */\nfunction findTsConfig(projectRoot: string): string | undefined {\n const candidate = resolve(projectRoot, 'tsconfig.json');\n return existsSync(candidate) ? candidate : undefined;\n}\n\n/**\n * Derive the canonical component name from a file path.\n *\n * Two extension shapes:\n * - Single (`.astro`, `.tsx`) → strip with `extname`/`basename`.\n * - Compound (`.d.ts`) → strip `.d.ts` explicitly, since `extname`\n * would return only `.ts` and leave a trailing `.d` (`Card.d`).\n *\n * Keeps the rule simple and consistent: file basename === component\n * name. Multi-component files (a `.d.ts` exporting many React\n * components from one barrel) are NOT supported through this path —\n * the sidecar `cmsConfig` mechanism (future task) covers those.\n */\nfunction componentNameFromPath(filepath: string): string {\n const base = basename(filepath);\n if (base.endsWith('.d.ts')) return base.slice(0, -'.d.ts'.length);\n return base.slice(0, -extname(base).length);\n}\n\n/**\n * Scan every npm-style import source referenced in the MDX usage scan\n * and treat any `.astro` / `.tsx` file inside the resolved package as a\n * candidate component. Resolves each unique specifier via Node's\n * `require.resolve` (run from `projectRoot` so packages are looked up\n * in the consumer's `node_modules`, not ours), walks up to the package\n * root, then globs the package for component-shaped files.\n *\n * The returned `source` on each result is the ORIGINAL specifier from\n * the MDX import (e.g. `@astrojs/starlight/components`) — not the\n * resolved file path. That's what makes the merge work: `scan-mdx`\n * records imports by their literal source string, so for the merge\n * registry to dedupe local-folder scan ⨯ MDX-usage scan we need both\n * sides to key on the same specifier. Vite's `ssrLoadModule` handles\n * the specifier itself at render time, so we don't need an absolute\n * file path on the descriptor.\n *\n * Caveats:\n * - Specifiers that look like local paths (`./foo`, `/abs/path`) are\n * intentionally skipped here — those are local components, already\n * covered by `scanLocalComponents`.\n * - One specifier per package: if a package is imported via two\n * different specifiers (`@pkg/components` and `@pkg`), we'll scan\n * it twice and emit two descriptor sets keyed on each specifier.\n * The merge layer's collision resolution picks the one with more\n * real usage, so this is self-correcting in practice.\n * - We cap glob depth at 4 to avoid walking into deeply-nested\n * library internals (most component packages put their exports\n * near the root). Components nested deeper won't surface; hosts\n * can either re-export them at a shallower path or add a sidecar\n * `cmsConfig` (when sidecar support lands).\n */\nexport async function scanExternalComponents(\n mdxScans: MdxScanResult[],\n projectRoot: string,\n): Promise<LocalComponentScanResult[]> {\n const specifiers = collectExternalSpecifiers(mdxScans);\n if (specifiers.size === 0) return [];\n\n // Same Project-per-scan rationale as scanLocalComponents — pay the\n // checker init cost once, share across every external file.\n const tsConfigFilePath = findTsConfig(projectRoot);\n const project = createScanProject(tsConfigFilePath);\n\n const results: LocalComponentScanResult[] = [];\n // `createRequire(projectRoot/package.json)` so resolution starts in\n // the consumer's tree. Without this, Node looks up modules relative\n // to wherever this file lives (our package), which would miss the\n // consumer's installed dependencies.\n const requireFromProject = createRequire(`${projectRoot.replace(/\\/$/, '')}/package.json`);\n\n for (const specifier of specifiers) {\n try {\n const resolved = requireFromProject.resolve(specifier);\n const packageRoot = findPackageRoot(resolved);\n if (!packageRoot) continue;\n\n // First try: parse the resolved file as a re-export barrel\n // (`export { default as Card } from './user-components/Card.astro'`).\n // If we find re-exports, scan ONLY those files — the package's\n // own author has declared the public surface, and everything\n // else is internal noise we don't want in the registry.\n //\n // This is the Starlight case: `@astrojs/starlight/components`\n // resolves to a barrel `.ts` listing exactly the 12 components\n // the package intends for MDX use, hiding ~30 internal layout\n // components in the same `node_modules` tree.\n const barrelFiles = await collectBarrelExports(resolved, packageRoot);\n let scanFiles: string[];\n if (barrelFiles.length > 0) {\n scanFiles = barrelFiles;\n } else {\n // Fallback: glob the whole package. Source files (`.astro`,\n // `.tsx`) first, then `.d.ts` as a last-resort schema source\n // for compiled packages. Dedupe by component name so a package\n // shipping BOTH `Card.tsx` and `Card.d.ts` uses the source\n // file (more reliable schema) and ignores the declaration.\n const sourceFiles = await fg('**/*.{astro,tsx}', {\n cwd: packageRoot,\n absolute: true,\n dot: false,\n deep: 4,\n });\n const dtsFiles = await fg('**/*.d.ts', {\n cwd: packageRoot,\n absolute: true,\n dot: false,\n deep: 4,\n });\n const seen = new Set<string>();\n scanFiles = [];\n for (const file of [...sourceFiles, ...dtsFiles]) {\n const name = componentNameFromPath(file);\n if (seen.has(name)) continue;\n seen.add(name);\n scanFiles.push(file);\n }\n }\n\n for (const file of scanFiles) {\n try {\n const r = await scanExternalFile(file, specifier, project);\n if (r) results.push(r);\n } catch (err) {\n console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);\n }\n }\n } catch (err) {\n // Resolution failures are common and expected — a `./local.css`\n // import or a missing optional peer dep both land here. Skip\n // quietly rather than failing the whole registry build.\n console.warn(\n `[conloca:discovery] could not resolve '${specifier}' from ${projectRoot}:`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n return results;\n}\n\n/**\n * Same parsing as `scanFile`, but with `source` set to the original\n * npm specifier instead of the absolute file path. See the function\n * doc on `scanExternalComponents` for why.\n */\nasync function scanExternalFile(\n filepath: string,\n specifier: string,\n project: Project,\n): Promise<LocalComponentScanResult | null> {\n const content = await readFile(filepath, 'utf8');\n const name = componentNameFromPath(filepath);\n if (!/^[A-Z]/.test(name)) return null;\n const props = extractPropsForFile(project, filepath, content, name);\n return {\n filepath,\n name,\n // CRITICAL: source = specifier (not filepath) so merge-registry\n // joins this entry with MDX-usage entries that key on the same\n // specifier. See the merge logic at `byKey` in merge-registry.ts.\n source: specifier,\n importSpecifier: specifier,\n kind: 'flow',\n props,\n };\n}\n\n/**\n * Pick out unique npm-style specifiers from every import seen in the\n * MDX scan. Local paths (`./foo`, `/abs`) are dropped — `scanLocalComponents`\n * covers those via its folder glob.\n */\nfunction collectExternalSpecifiers(mdxScans: MdxScanResult[]): Set<string> {\n const out = new Set<string>();\n for (const scan of mdxScans) {\n for (const imp of Object.values(scan.imports)) {\n const src = imp.source;\n if (!src) continue;\n // Local-path indicators per ESM spec: starts with `.` (`./foo`,\n // `../bar`) or `/` (absolute). Everything else is treated as\n // npm-resolvable.\n if (src.startsWith('.') || src.startsWith('/')) continue;\n out.add(src);\n }\n }\n return out;\n}\n\n/**\n * If `resolvedFile` is a barrel (re-export aggregator), return the\n * absolute paths of every re-exported component file. Otherwise\n * return an empty array.\n *\n * Patterns recognized:\n * - `export { default as Foo } from './path/to/Foo.astro'`\n * - `export { Foo } from './path/to/Foo'`\n * - `export { Foo, Bar } from './path/to/m'`\n * - `export * from './path/to/m'` (treated as opaque — we\n * can't enumerate the\n * names without a real\n * parser, so we skip and\n * fall back to glob-all)\n *\n * The barrel must resolve to a real file we can re-resolve to one of\n * the supported extensions (`.astro`, `.tsx`, `.d.ts`). Missing or\n * unsupported targets are dropped quietly. Comments are stripped\n * first to avoid matching commented-out exports.\n *\n * Why this matters: Starlight's `@astrojs/starlight/components`\n * barrel lists exactly the 12 MDX-friendly components. Globbing the\n * whole package would also pull in ~30 internal layout components\n * (Banner, Hero, Pagination, ...) — they'd litter the slash menu\n * even though they're not meant for author use.\n */\nasync function collectBarrelExports(resolvedFile: string, packageRoot: string): Promise<string[]> {\n // Only `.ts` / `.js` / `.mjs` source files can be barrels; an\n // `.astro` or `.tsx` file is the component itself, not an\n // aggregator. Bail early to avoid reading binary or unsupported\n // file types.\n if (!/\\.(?:m?[jt]s)$/.test(resolvedFile)) return [];\n\n let content: string;\n try {\n content = await readFile(resolvedFile, 'utf8');\n } catch {\n return [];\n }\n const cleaned = content.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/(^|[^:])\\/\\/[^\\n]*/g, '$1');\n\n // Collect the relative source paths from every `export {...} from '<path>'`.\n // We don't need the export names here — we just need the files to\n // scan. Each scanned file's component name comes from its own\n // basename, the same way local components work.\n const pathRe = /export\\s*(?:\\{[^}]*\\}|\\*)\\s*from\\s*['\"]([^'\"]+)['\"]/g;\n const relPaths = new Set<string>();\n for (const m of cleaned.matchAll(pathRe)) {\n const rel = m[1];\n // Skip `export *` — we can't enumerate without a real parser, and\n // re-running the barrel collector recursively would invite cycles.\n // Falls through to glob-all below if no other re-exports exist.\n if (!rel) continue;\n relPaths.add(rel);\n }\n if (relPaths.size === 0) return [];\n\n // Resolve each relative path. `import.meta.resolve` doesn't take a\n // base file, so use the barrel's directory as the resolution root.\n const barrelDir = dirname(resolvedFile);\n const requireFromBarrel = createRequire(`${barrelDir}/_.js`);\n const resolved: string[] = [];\n for (const rel of relPaths) {\n try {\n const target = requireFromBarrel.resolve(rel);\n // Only keep targets that look like component files we can\n // scan (extensions our extractor supports) AND live inside\n // the package root (defensive — barrels in the wild can\n // re-export from sibling packages, which we don't want to\n // descend into).\n if (!/\\.(?:astro|tsx|d\\.ts)$/.test(target)) continue;\n if (!target.startsWith(packageRoot)) continue;\n resolved.push(target);\n } catch {\n // Missing optional file or extension we don't handle — skip.\n }\n }\n return resolved;\n}\n\n/**\n * Walk up from a resolved file path until we find the directory that\n * contains the closest `package.json`. That's the package root we'll\n * glob for component files. Returns `null` if no package.json is found\n * within a reasonable depth (defensive — shouldn't happen for a real\n * resolution).\n */\nfunction findPackageRoot(resolvedPath: string): string | null {\n let dir = dirname(resolvedPath);\n for (let i = 0; i < 10; i++) {\n // Sync existsSync is fine here — the walk is at most ~10 hops per\n // package and runs once per unique specifier per scan.\n if (existsSync(`${dir}/package.json`)) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n return null;\n}\n\n// Prop extraction lives in `./extract-props-ts.ts` (TypeScript\n// compiler API via ts-morph). The previous regex-based scanner —\n// `extractPropsInterface` + `parseTypeExpr` — was removed in the\n// migration: it silently dropped options for derived types like\n// `(typeof asideVariants)[number]`, mapped types, conditional types,\n// and imported aliases. The ts-morph path resolves all of those.\n// Astro frontmatter extraction lives in `./astro-frontmatter.ts`.\n","import { readFile } from 'node:fs/promises';\nimport fg from 'fast-glob';\nimport { fromMarkdown } from 'mdast-util-from-markdown';\nimport { mdxFromMarkdown } from 'mdast-util-mdx';\nimport { mdxjs } from 'micromark-extension-mdxjs';\n\n/**\n * Walks the content directory for `.mdx` files, parses each one, and\n * returns a per-file record of:\n *\n * - **imports** — every `import { Foo, Bar as Baz } from 'pkg'` /\n * `import Default from 'pkg'` declaration in the file's ESM\n * header, keyed by the LOCAL name as seen in the JSX usages\n * below. The `aliasedFrom` field records when the local name\n * differs from the canonical export, so the save serializer can\n * preserve the alias when rewriting the file.\n *\n * - **usages** — every `<Foo>` / `<Foo />` element in the file's\n * body, in source order, with its observed string attributes.\n *\n * The merge step (downstream) joins each usage to its import via\n * the local name to build the final component descriptor list.\n *\n * Parsing uses `mdast-util-from-markdown` with the full MDX extension\n * bundle (`micromark-extension-mdxjs` + `mdast-util-mdx`) — the same\n * stack the editor uses on every save, so what we observe here is\n * exactly what the editor's save path can round-trip.\n */\nexport interface MdxImport {\n /** The npm-style or relative source path. */\n source: string;\n /** True for `import Foo from '...'`; false for named imports. */\n defaultExport: boolean;\n /** The canonical export name on the package side. For\n * `import { Aside as Callout }`, this is `'Aside'` while the\n * local key is `'Callout'`. For default imports this is `'default'`. */\n exportName: string;\n /** Local alias used in this file, if it differs from `exportName`.\n * `undefined` when the file uses the canonical name unchanged. */\n aliasedFrom?: string;\n}\n\nexport interface MdxUsage {\n /** The local name used in the JSX tag — `<Foo>` → `'Foo'`. */\n name: string;\n /** Observed attributes as raw strings. Expression-valued attrs\n * (`prop={42}`) and complex values are not captured here; this\n * field is for inferring \"values seen in real usage\" to populate\n * dropdown choices on the prop panel. */\n attrs: Record<string, string>;\n /** `'flow'` (block-level) or `'text'` (inline-level) — matches the\n * mdast node type. Used to set the descriptor's `kind`. */\n kind: 'flow' | 'text';\n}\n\nexport interface MdxScanResult {\n /** Absolute path of the scanned file. */\n filepath: string;\n /** Local name → import declaration. */\n imports: Record<string, MdxImport>;\n /** All JSX usages in document order. */\n usages: MdxUsage[];\n}\n\n/**\n * Scan every `.mdx` file under `rootDir` (recursive). Returns one\n * result per file. Files that fail to parse are skipped with a\n * warning rather than throwing — the discovery flow shouldn't take\n * down the dev server on a single broken file.\n */\nexport async function scanMdxFiles(rootDir: string): Promise<MdxScanResult[]> {\n const files = await fg('**/*.mdx', { cwd: rootDir, absolute: true, dot: false });\n const results: MdxScanResult[] = [];\n for (const file of files) {\n try {\n results.push(await scanFile(file));\n } catch (err) {\n console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);\n }\n }\n return results;\n}\n\nasync function scanFile(filepath: string): Promise<MdxScanResult> {\n const content = await readFile(filepath, 'utf8');\n const tree = fromMarkdown(content, {\n extensions: [mdxjs()],\n mdastExtensions: [mdxFromMarkdown()],\n });\n\n const imports: Record<string, MdxImport> = {};\n const usages: MdxUsage[] = [];\n\n walk(tree, (node) => {\n if (isEsmNode(node)) {\n collectImports(node, imports);\n } else if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {\n const name = typeof node.name === 'string' ? node.name : '';\n if (!name) return;\n const attrs: Record<string, string> = {};\n const rawAttrs = (node.attributes as Array<{ type?: string; name?: unknown; value?: unknown }> | undefined) ?? [];\n for (const a of rawAttrs) {\n if (a.type !== 'mdxJsxAttribute' || typeof a.name !== 'string') continue;\n if (typeof a.value === 'string') {\n attrs[a.name] = a.value;\n }\n // Expression values (`prop={...}`) and null (boolean\n // shorthand) are intentionally ignored here — they don't\n // contribute to the \"observed string values\" we use to\n // suggest dropdown options. The full attribute set per node\n // lives in the editor's mdast node anyway.\n }\n usages.push({\n name,\n attrs,\n kind: node.type === 'mdxJsxFlowElement' ? 'flow' : 'text',\n });\n }\n });\n\n return { filepath, imports, usages };\n}\n\nfunction isEsmNode(node: { type?: string }): node is EsmNode {\n return node.type === 'mdxjsEsm';\n}\n\ninterface EsmNode {\n type: 'mdxjsEsm';\n value?: string;\n data?: { estree?: { body?: EstreeStatement[] } };\n}\n\ninterface EstreeStatement {\n type: string;\n source?: { value?: string };\n specifiers?: EstreeImportSpec[];\n}\n\ninterface EstreeImportSpec {\n type: 'ImportDefaultSpecifier' | 'ImportSpecifier' | 'ImportNamespaceSpecifier';\n imported?: { type?: string; name?: string; value?: string };\n local: { name: string };\n}\n\nfunction collectImports(esmNode: EsmNode, out: Record<string, MdxImport>): void {\n const estree = esmNode.data?.estree;\n if (!estree?.body) return;\n for (const stmt of estree.body) {\n if (stmt.type !== 'ImportDeclaration') continue;\n const source = stmt.source?.value;\n if (typeof source !== 'string') continue;\n for (const spec of stmt.specifiers ?? []) {\n const local = spec.local?.name;\n if (typeof local !== 'string') continue;\n if (spec.type === 'ImportDefaultSpecifier') {\n out[local] = { source, defaultExport: true, exportName: 'default' };\n } else if (spec.type === 'ImportSpecifier') {\n const exportName =\n spec.imported?.type === 'Identifier'\n ? spec.imported.name\n : typeof spec.imported?.value === 'string'\n ? spec.imported.value\n : local;\n out[local] = {\n source,\n defaultExport: false,\n exportName: exportName ?? local,\n ...(exportName && exportName !== local ? { aliasedFrom: exportName } : {}),\n };\n }\n // ImportNamespaceSpecifier (`import * as X`) is rare in MDX and\n // wouldn't produce a usable component descriptor on its own —\n // we'd see `<X.Foo>` namespaced usages we don't model. Skip.\n }\n }\n}\n\n/** Depth-first walk; visits every node including the root. */\nfunction walk(\n node: { type?: string; children?: unknown[] },\n fn: (n: { type?: string } & Record<string, unknown>) => void,\n): void {\n fn(node as { type?: string } & Record<string, unknown>);\n if (Array.isArray((node as { children?: unknown[] }).children)) {\n for (const child of (node as { children?: unknown[] }).children!) {\n if (child && typeof child === 'object') walk(child as { type?: string; children?: unknown[] }, fn);\n }\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport fg from 'fast-glob';\n\n/**\n * Host-provided override for an auto-discovered component descriptor.\n *\n * Lives in a sidecar JSON file inside the configured overrides folder\n * (default `src/cms-overrides/`). One file per component, keyed by\n * basename: `Card.cms.json` overrides the auto-discovered `Card`.\n *\n * Why JSON, not TS:\n * - Zero tooling. The host doesn't need to import any types, set up\n * build steps, or worry about which export shape we expect.\n * - Static — we don't have to spin up Vite's SSR loader to read it.\n * - Survives copy/paste between projects.\n *\n * The shape is intentionally a flat subset of `MdxJsxComponentDescriptor` —\n * not the full union — because hosts only need to override the\n * fields that come up in practice (insert menu hints, prop schema\n * tweaks, defaults). New fields can be added later without breaking\n * existing JSON files.\n */\nexport interface CmsOverride {\n /** Override the slash-menu / toolbar entry (label, category, icon, etc.). */\n insert?: {\n label?: string;\n description?: string;\n category?: string;\n icon?: string;\n keywords?: string[];\n };\n /** Override the insert-time starter attribute values. Merges over\n * the auto-derived `defaults.attributes` so hosts can pin specific\n * placeholder text or set a default for a prop the inference missed. */\n defaults?: {\n attributes?: Record<string, string | number | boolean>;\n /** Raw MDX snippet parsed to mdast children at insert time. */\n children?: string;\n };\n /** Per-prop overrides keyed by prop name. Fields here merge over\n * the inferred prop schema (matched by `name`). Useful when:\n * - The interface scan missed `required` (rare type pattern).\n * - You want explicit help text or a friendly label.\n * - You want a curated `options` list instead of usage-observed values. */\n props?: Record<\n string,\n {\n required?: boolean;\n label?: string;\n help?: string;\n options?: Array<{ value: string; label: string }>;\n }\n >;\n /** Override whether the component accepts children. Inferred to\n * `true` by default; set to `false` for self-closing components. */\n hasChildren?: boolean;\n /** Override the flow/text kind. The flow-wins promotion in\n * `merge-registry.ts` usually gets this right, but a host can\n * pin the kind explicitly here if their fixtures don't exercise\n * the block-context usage. */\n kind?: 'flow' | 'text';\n}\n\n/**\n * Read every `*.cms.json` file under `folder` (recursive) and return\n * the parsed overrides keyed by basename (`Card.cms.json` → `Card`).\n *\n * Failures are skipped with a warning — a broken JSON file shouldn't\n * take down the rest of the registry build. The folder being empty\n * (or not existing) returns an empty map silently; that's the\n * common zero-config case where the host hasn't added any\n * overrides yet.\n */\nexport async function loadCmsOverrides(folder: string, projectRoot: string): Promise<Map<string, CmsOverride>> {\n const out = new Map<string, CmsOverride>();\n if (!folder) return out;\n const pattern = `${folder.replace(/\\/+$/, '')}/**/*.cms.json`;\n const files = await fg(pattern, { cwd: projectRoot, absolute: true, dot: false });\n for (const file of files) {\n try {\n const content = await readFile(file, 'utf8');\n const parsed = JSON.parse(content) as CmsOverride;\n const base = basename(file);\n const name = base.slice(0, -'.cms.json'.length);\n out.set(name, parsed);\n } catch (err) {\n console.warn(`[conloca:discovery] failed to load override ${file}:`, err instanceof Error ? err.message : err);\n }\n }\n return out;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { resolve } from 'node:path';\nimport { type DiscoveredComponent, mergeRegistry } from './merge-registry';\nimport { scanExternalComponents, scanLocalComponents } from './scan-components';\nimport { scanMdxFiles } from './scan-mdx';\nimport { loadCmsOverrides } from './scan-overrides';\n\n/** Connect-compatible middleware handler — see render-endpoint.ts. */\ntype NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;\n\n/**\n * Vite middleware that returns the auto-discovered MDX component\n * registry as JSON. The SPA fetches this on mount and seeds its\n * `setMdxComponents` registry — replacing the hand-written\n * `mdx-components.tsx` flow.\n *\n * Each call runs the three-stage pipeline (scan-mdx + scan-components\n * + merge-registry), with a memoized result keyed on the configured\n * inputs. The result is invalidated by an external watcher (set up\n * in `plugin-spa.ts`) any time a watched MDX or component file\n * changes — so editing a `.mdx` to use a new component refreshes\n * the registry without a manual reload.\n *\n * Errors are returned as JSON `{ error: \"...\" }` with 500 rather\n * than thrown — the SPA falls back to host-provided descriptors when\n * the endpoint fails, and a noisy stack trace would just spam the\n * dev console.\n */\nexport interface RegistryEndpointOptions {\n /** Absolute or project-relative path to the content directory. */\n contentRoot: string;\n /** Project-relative paths to scan for local components. */\n componentFolders: string[];\n /** Project-relative folder of `*.cms.json` sidecar override files,\n * keyed by component basename (`Card.cms.json` → overrides `Card`).\n * Defaults to `src/cms-overrides` — host can omit when they don't\n * need any overrides yet. */\n overridesFolder?: string;\n /** Used to resolve `componentFolders` relative to it. Defaults to\n * `process.cwd()`. */\n projectRoot?: string;\n}\n\nexport function createRegistryEndpoint(options: RegistryEndpointOptions): {\n handler: NextHandleFunction;\n invalidate: () => void;\n getAllowedSources: () => Promise<Set<string>>;\n} {\n const projectRoot = options.projectRoot ?? process.cwd();\n const contentRoot = resolve(projectRoot, options.contentRoot);\n\n let cached: Promise<DiscoveredComponent[]> | null = null;\n const compute = (): Promise<DiscoveredComponent[]> => {\n if (cached) return cached;\n cached = (async () => {\n // MDX scan first — its results feed BOTH the merge step AND the\n // external-package scan (which uses the imports to know what\n // packages to walk into).\n const mdxScans = await scanMdxFiles(contentRoot);\n const overridesFolder = options.overridesFolder ?? 'src/cms-overrides';\n const [localComponents, externalComponents, overrides] = await Promise.all([\n scanLocalComponents(options.componentFolders, projectRoot),\n scanExternalComponents(mdxScans, projectRoot),\n loadCmsOverrides(overridesFolder, projectRoot),\n ]);\n // External (npm) and local components live in disjoint key\n // spaces — external source strings are npm specifiers, local\n // source strings are absolute paths — so they never collide on\n // the `${source}::${name}` dedup key. The interesting collision\n // case is two sources sharing a `name`; that pass is resolved\n // inside `mergeRegistry` by usage count (see rule 6 in its top\n // doc). Host sidecar overrides apply last as the highest-priority\n // layer (see `applyOverride` in merge-registry).\n return mergeRegistry(mdxScans, [...externalComponents, ...localComponents], overrides);\n })();\n return cached;\n };\n\n const handler: NextHandleFunction = async (req, res, _next) => {\n try {\n const components = await compute();\n res.statusCode = 200;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(JSON.stringify({ components }));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.warn('[conloca:discovery] registry endpoint failed:', message);\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.end(JSON.stringify({ error: message }));\n }\n };\n\n return {\n handler,\n invalidate: () => {\n cached = null;\n },\n /**\n * Set of import sources the render endpoint is allowed to load.\n *\n * Reuses the same memoized scan as `handler`, so the allowlist stays\n * in sync with the registry the SPA sees — invalidation in one place\n * invalidates both. Failing closed (returning an empty set) on scan\n * error is intentional: better to refuse all renders than to fall\n * back to \"trust the request body\".\n */\n getAllowedSources: async (): Promise<Set<string>> => {\n try {\n const components = await compute();\n const sources = new Set<string>();\n for (const c of components) {\n if (c.import?.from) sources.add(c.import.from);\n }\n return sources;\n } catch {\n return new Set();\n }\n },\n };\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 { IncomingMessage, ServerResponse } from 'node:http';\n\n/** Connect-compatible middleware handler — see render-endpoint.ts. */\ntype NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;\n\n/**\n * Per-route content-wrapper discovery endpoint.\n *\n * The editor mirrors the host's content surface by rendering its\n * contenteditable inside a clone of whatever element the host wraps\n * its page content in. This endpoint fetches the live HTML the dev\n * server serves at `?url=<route>`, locates the relevant wrappers\n * (prose content + code-block chrome), and returns them as JSON.\n *\n * Returned shape:\n *\n * {\n * content: { tagName, className } | null,\n * codeBlock: { tagName, className }[] | null,\n * }\n *\n * - `content` is the wrapper for prose (h1-h6, p, lists, etc.). The\n * editor wraps its contenteditable in a clone so the host's prose\n * CSS reaches via the cascade.\n * - `codeBlock` is the ORDERED chain of classed wrappers around the\n * host's `<pre>`, outermost first. For Starlight's expressive-code:\n * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.\n * The editor's CodeMirror frame renders each link as a nested\n * element (outer→inner) so the host's code-block CSS reaches via\n * the cascade including descendant selectors (`.expressive-code\n * .frame .header`, etc.) — not just single-class targets.\n *\n * Discovery priorities (content):\n *\n * 1. `[data-conloca-content-root]` — explicit opt-in.\n * 2. The smallest classed wrapper inside `<main>` containing the\n * majority of prose tags.\n * 3. `<main>` itself.\n * 4. `null`.\n *\n * Discovery (codeBlock): walk up from a `<pre>` inside `<main>` and\n * collect classed ancestors between the content wrapper and `<pre>`,\n * preserving their nesting order. Returns null when no `<pre>` exists,\n * or when there are no classed wrappers between the prose wrapper and\n * the `<pre>`.\n */\nexport interface ContentWrapperInfo {\n /** Lower-case HTML tag name as it appeared in source, eg `'article'`. */\n tagName: string;\n /** Space-separated class list from the source element. Preserved\n * verbatim so Astro-scoped hashes (`astro-e3flfouy`) survive — host\n * scoped CSS only matches when those hashes are present on the\n * element. */\n className: string;\n}\n\nexport interface DiscoveredWrappers {\n /** The element wrapping the page's prose content (h1-h6, p, etc.).\n * For Starlight: `.sl-markdown-content`. For Tailwind Typography:\n * `.prose`. Null when no prose wrapper exists on the page. */\n content: ContentWrapperInfo | null;\n /** Ordered chain of classed wrappers between the content wrapper\n * and the `<pre>`, outermost first. For Starlight:\n * `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.\n * Null when the page has no code blocks or no classed wrappers\n * between the prose wrapper and the `<pre>`. */\n codeBlock: ContentWrapperInfo[] | null;\n}\n\nexport function createContentWrapperEndpoint(): NextHandleFunction {\n return async (req, res, _next) => {\n try {\n const parsed = new URL(req.url ?? '', 'http://localhost');\n const routeUrl = parsed.searchParams.get('url');\n if (!routeUrl) {\n res.statusCode = 400;\n res.setHeader('content-type', 'text/plain');\n res.end('Missing required query parameter: url');\n return;\n }\n\n const host = req.headers.host ?? 'localhost:4321';\n const protocol = (req.headers['x-forwarded-proto'] as string) ?? 'http';\n const liveUrl = `${protocol}://${host}${routeUrl}`;\n const html = await fetch(liveUrl, {\n headers: req.headers.cookie ? { cookie: req.headers.cookie } : undefined,\n }).then((r) => r.text());\n\n const wrappers = findContentWrapper(html);\n\n res.statusCode = 200;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(JSON.stringify(wrappers));\n } catch (err) {\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain');\n res.end(`Content-wrapper discovery failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n}\n\n/** Tags whose presence signals \"this element holds prose content.\"\n * We walk up from the first such element we find inside `<main>` to\n * locate the wrapper. Headings + paragraphs cover every prose-styling\n * convention we've seen — every CSS framework scopes typography\n * through descendant selectors on `h1`–`h6` and `p`. */\nconst PROSE_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p']);\n\n/** Tag that anchors code-block wrapper discovery. The host's code-\n * block library (Starlight's expressive-code, Tailwind's `pre`\n * styling, etc.) always renders a `<pre>` containing the code,\n * often wrapped in additional classed elements. */\nconst CODE_BLOCK_ANCHOR = 'pre';\n\n/** HTML5 void elements — never push onto the open-tag stack since they\n * have no closing tag. */\nconst VOID_TAGS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'source',\n 'track',\n 'wbr',\n]);\n\ninterface OpenTag {\n tag: string;\n className: string;\n attrs: Record<string, string>;\n}\n\n/**\n * Locate the host's content + code-block wrappers in raw HTML. Single-\n * pass regex walk with a stack so we can recover ancestor chains for\n * both prose tags and `<pre>` tags without a full DOM parser dep.\n *\n * Exported for unit testing.\n */\nexport function findContentWrapper(html: string): DiscoveredWrappers {\n // Strip comments and scripts so opening-tag-shaped strings inside\n // them don't pollute the walk.\n const cleaned = html\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, '');\n\n const tagRe = /<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\\s+[^>]*)?)\\s*(\\/?)>/g;\n const stack: OpenTag[] = [];\n\n let explicit: ContentWrapperInfo | null = null;\n let mainEl: OpenTag | null = null;\n const proseAncestorChains: OpenTag[][] = [];\n const preAncestorChains: OpenTag[][] = [];\n\n let match: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator\n while ((match = tagRe.exec(cleaned)) !== null) {\n const isClose = match[1] === '/';\n const tagName = match[2].toLowerCase();\n const attrBlob = match[3] ?? '';\n const explicitlySelfClosing = match[4] === '/';\n\n if (isClose) {\n for (let i = stack.length - 1; i >= 0; i--) {\n if (stack[i].tag === tagName) {\n stack.length = i;\n break;\n }\n }\n continue;\n }\n\n const attrs = parseAttributes(attrBlob);\n const className = attrs.class ?? '';\n const el: OpenTag = { tag: tagName, className, attrs };\n\n // Priority 1 (content only): explicit opt-in. Capture and keep\n // walking — we still need to discover the code-block wrapper.\n if (!explicit && 'data-conloca-content-root' in attrs) {\n explicit = { tagName, className };\n }\n\n if (!mainEl && tagName === 'main') {\n mainEl = el;\n }\n\n if (mainEl && PROSE_TAGS.has(tagName)) {\n const mainIdx = stack.indexOf(mainEl);\n if (mainIdx >= 0) {\n proseAncestorChains.push(stack.slice(mainIdx + 1));\n }\n }\n\n if (mainEl && tagName === CODE_BLOCK_ANCHOR) {\n const mainIdx = stack.indexOf(mainEl);\n if (mainIdx >= 0) {\n preAncestorChains.push(stack.slice(mainIdx + 1));\n }\n }\n\n const isVoid = VOID_TAGS.has(tagName);\n if (!isVoid && !explicitlySelfClosing) {\n stack.push(el);\n }\n }\n\n const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);\n const codeBlock = resolveCodeBlockWrapper(content, preAncestorChains);\n\n return { content, codeBlock };\n}\n\n/**\n * Pick the content wrapper from the walk's collected data.\n *\n * Priority: explicit opt-in > majority-prose-wrapper-inside-main >\n * `<main>` fallback > null.\n */\nfunction resolveContentWrapper(\n explicit: ContentWrapperInfo | null,\n mainEl: OpenTag | null,\n proseAncestorChains: OpenTag[][],\n): ContentWrapperInfo | null {\n if (explicit) return explicit;\n if (!mainEl) return null;\n\n if (proseAncestorChains.length === 0) {\n return { tagName: 'main', className: mainEl.className };\n }\n\n // Tally classed-ancestor occurrences across all prose chains.\n const scores = new Map<OpenTag, number>();\n for (const chain of proseAncestorChains) {\n for (const ancestor of chain) {\n if (!ancestor.className) continue;\n scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);\n }\n }\n\n // Majority threshold rules out partial-coverage classed ancestors\n // (single Cards holding one of many prose blocks).\n const threshold = proseAncestorChains.length / 2;\n const candidates = [...scores.entries()].filter(([, count]) => count > threshold);\n\n if (candidates.length === 0) {\n return { tagName: 'main', className: mainEl.className };\n }\n\n // Tie-break by depth: the candidate that appears deepest in any\n // chain is the most specific (closest to the prose tags).\n const maxChainIndex = (el: OpenTag) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));\n candidates.sort((a, b) => {\n if (b[1] !== a[1]) return b[1] - a[1];\n return maxChainIndex(b[0]) - maxChainIndex(a[0]);\n });\n\n const winner = candidates[0][0];\n return { tagName: winner.tag, className: winner.className };\n}\n\n/**\n * Derive the code-block wrapper chain from a representative `<pre>`'s\n * ancestor chain. We strip everything at or above the content wrapper\n * (its styles are already handled by the content-wrapper mirror) and\n * return the remaining classed elements in nesting order, outermost\n * first.\n *\n * Returning a chain (instead of one collapsed element) preserves the\n * shape host CSS expects:\n *\n * - Single-class selectors (`.frame { ... }`) hit on whichever link\n * carries that class.\n * - Descendant selectors (`.expressive-code .frame { ... }`,\n * `.frame .header > .title`) hit because the editor's renderer\n * materialises the chain as nested elements with the host's\n * expected tag names.\n *\n * The editor's code-block frame component (`code-block-frame.tsx` in\n * `@conloca/mdx`) treats the LAST link as the \"frame\" element (where\n * figcaption/pre/copy children render) and wraps it with the earlier\n * links from inside out. This matches the host's authoring shape for\n * libraries like ExpressiveCode (`.expressive-code > figure.frame >\n * figcaption + pre + .copy`).\n */\nfunction resolveCodeBlockWrapper(\n content: ContentWrapperInfo | null,\n preAncestorChains: OpenTag[][],\n): ContentWrapperInfo[] | null {\n if (preAncestorChains.length === 0) return null;\n\n // Pick the first <pre>'s chain as representative. Code blocks on a\n // single page are uniformly wrapped, so chains are interchangeable.\n const chain = preAncestorChains[0];\n\n // Strip everything at-or-above the content wrapper; the rest is\n // code-block-specific chrome that this endpoint is responsible for.\n const contentIdx = content\n ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className)\n : -1;\n const codeBlockChain = chain.slice(contentIdx + 1);\n\n const classedAncestors = codeBlockChain.filter((el) => el.className);\n if (classedAncestors.length === 0) return null;\n\n return classedAncestors.map((el) => ({ tagName: el.tag, className: el.className }));\n}\n\n/**\n * Parse the attribute blob inside an opening tag. Handles `name=\"v\"`,\n * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't\n * handle entity decoding (`&amp;` → `&`) since the values we read\n * (tag name, class list, the marker attribute) don't carry entities\n * in practice.\n */\nfunction parseAttributes(s: string): Record<string, string> {\n const out: Record<string, string> = {};\n const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|(\\S+)))?/g;\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator\n while ((m = re.exec(s)) !== null) {\n const name = m[1];\n const value = m[2] ?? m[3] ?? m[4] ?? '';\n out[name] = value;\n }\n return out;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { experimental_AstroContainer } from 'astro/container';\n\n/** Connect-compatible middleware handler. Avoids importing Vite's Connect\n * namespace so dual peer-hash installs of the same Vite version can't\n * produce cross-package `ViteDevServer` identity errors under tsc. */\ntype NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;\n\n/** Minimal surface used by the render tree — only ssrLoadModule. */\ninterface SsrModuleLoader {\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n}\n\n/**\n * Vite middleware that renders an MDX JSX subtree to HTML on demand.\n *\n * Container components (CardGrid, Tabs, …) have JSX children that on\n * the published page render as direct DOM children of the parent —\n * positional CSS (`:nth-child` colour cycling on Card grids, CSS-grid\n * placement) depends on that DOM shape. Per-block isolated rendering\n * breaks both: each child gets its own wrapper, and the parent's only\n * direct child is a slot marker.\n *\n * This endpoint renders a recursive tree: each node provides its\n * component name + source + props, optionally with its own `children`\n * tree. The server renders leaves first and assembles parents by\n * passing rendered children HTML as the parent's default slot, so the\n * final markup matches what Astro would emit for the same MDX\n * source — same DOM, same CSS context.\n *\n * Request shape (JSON body):\n * {\n * tree: {\n * component: string,\n * source: string,\n * defaultExport?: boolean,\n * props?: Record<string, unknown>,\n * slotId: string,\n * children?: RenderTreeNode[]\n * },\n * documentIndex?: number // wraps top-level output to fix\n * // sibling-position CSS for root-level\n * // blocks (see phantom-sibling fix).\n * }\n *\n * Legacy shape (kept for backward compatibility):\n * { component, source, defaultExport?, props?, documentIndex? }\n *\n * For each node, the rendered slot content is either:\n * - The concatenated HTML of recursively-rendered children, if any.\n * - `<conloca-slot data-slot-id=\"<id>\"></conloca-slot>` placeholder\n * otherwise (the SPA portals a Lexical editor into it).\n *\n * Returns 200 with `Content-Type: text/html` on success; 4xx with a\n * plain-text error otherwise.\n */\nexport function createRenderEndpoint(\n server: SsrModuleLoader,\n getAllowedSources: () => Promise<Set<string>>,\n): NextHandleFunction {\n let containerPromise: Promise<experimental_AstroContainer> | null = null;\n const getContainer = () => {\n if (!containerPromise) containerPromise = experimental_AstroContainer.create();\n return containerPromise;\n };\n\n return async (req, res, _next) => {\n if (req.method !== 'POST') {\n res.statusCode = 405;\n res.setHeader('content-type', 'text/plain');\n res.end('Method not allowed');\n return;\n }\n\n try {\n const body = (await readJson(req)) as RequestBody;\n\n // Normalize: accept either { tree } or the legacy flat shape.\n const tree: RenderTreeNode = body.tree ?? {\n component: body.component ?? '',\n source: body.source ?? '',\n defaultExport: body.defaultExport,\n props: body.props,\n slotId: 'root',\n };\n\n if (!tree.component || !tree.source) {\n res.statusCode = 400;\n res.setHeader('content-type', 'text/plain');\n res.end('Missing required fields: tree.component, tree.source');\n return;\n }\n\n // Allowlist check. `source` flows into `server.ssrLoadModule`,\n // which will load and execute ANY file Vite can resolve — so\n // accepting arbitrary strings here would let any localhost POST\n // (eg from a malicious tab visited during `bun dev`) run any\n // JS file on the developer's machine. The registry already knows\n // every legal component source; reject anything outside it.\n const allowed = await getAllowedSources();\n const disallowed = collectDisallowedSources(tree, allowed);\n if (disallowed.length > 0) {\n res.statusCode = 400;\n res.setHeader('content-type', 'text/plain');\n res.end(`source not in registry: ${disallowed.join(', ')}`);\n return;\n }\n\n const container = await getContainer();\n // Even the top-level render is wrapped: a hard failure here would\n // 500 the whole response and leave the editor with no usable\n // HTML to portal a body editor into. The stub keeps the surface\n // editable so the author can fix the broken prop in place.\n let rendered: string;\n try {\n rendered = await renderTree(tree, container, server);\n } catch (err) {\n console.warn(`[conloca:render] <${tree.component}> failed:`, err instanceof Error ? err.message : err);\n rendered = renderErrorStub(tree, err);\n }\n\n // Wrap top-level output in a host-marker parent (`.sl-markdown-content`)\n // with `(documentIndex - 1)` hidden phantom siblings so root-level\n // components match the live page's `:nth-child(N)` position. See\n // earlier commit for the rationale (Starlight Card cycle).\n //\n // Inline (text-kind) requests skip the wrapper entirely: the\n // rendered HTML is destined for inline text flow (eg an Icon's\n // `<svg>` inside a paragraph), where a block wrapper would force\n // a line break and phantom siblings make no sense (the node\n // isn't a root flow child).\n let html: string;\n if (body.inline) {\n html = rendered;\n } else {\n const documentIndex = body.documentIndex;\n const phantomCount = typeof documentIndex === 'number' && documentIndex > 0 ? documentIndex - 1 : 0;\n const phantoms = phantomCount > 0 ? '<span hidden aria-hidden=\"true\"></span>'.repeat(phantomCount) : '';\n html = `<div class=\"sl-markdown-content\">${phantoms}${rendered}</div>`;\n }\n\n res.statusCode = 200;\n res.setHeader('content-type', 'text/html; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(html);\n } catch (err) {\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain');\n res.end(`Render failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n}\n\ninterface RenderTreeNode {\n component: string;\n source: string;\n defaultExport?: boolean;\n props?: Record<string, unknown>;\n slotId: string;\n /** HTML-escaped text fallback for leaf body. Shown when no editor\n * is portaled into the slot (eg inside container-rendered children\n * before Phase 3 inline editing lands). */\n body?: string;\n /** Raw HTML that REPLACES the conloca-slot wrapper. Used for\n * components whose Astro implementation validates the slot element\n * type (Starlight's `<Steps>` requires `<ol>`, `<FileTree>` requires\n * `<ul>`) — wrapping in `<conloca-slot>` makes the Container API\n * render call throw. With `bodyHtml`, the validator sees the real\n * element. No inline editing possible until per-position slot\n * markers are added inside the rendered list. */\n bodyHtml?: string;\n children?: RenderTreeNode[];\n /** Named-slot HTML keyed by slot name. Passed as additional slots\n * to `container.renderToString`. Source MDX uses\n * `<Fragment slot=\"...\">…</Fragment>` to declare them. */\n namedSlots?: Record<string, string>;\n}\n\ninterface RequestBody {\n // New shape\n tree?: RenderTreeNode;\n // Legacy shape (one component, no children)\n component?: string;\n source?: string;\n defaultExport?: boolean;\n props?: Record<string, unknown>;\n // Top-level wrapping\n documentIndex?: number;\n /** When true, suppress the `<div class=\"sl-markdown-content\">` wrapper\n * and phantom siblings — the rendered HTML is destined for inline\n * text flow (eg `<Icon>`), where a block wrapper would force a line\n * break and phantom siblings make no sense (the node isn't a root\n * flow child). */\n inline?: boolean;\n}\n\nasync function renderTree(\n node: RenderTreeNode,\n container: experimental_AstroContainer,\n server: SsrModuleLoader,\n): Promise<string> {\n const module = (await server.ssrLoadModule(node.source)) as Record<string, unknown>;\n const exportKey = node.defaultExport ? 'default' : node.component;\n const factory = module[exportKey];\n\n if (typeof factory !== 'function') {\n throw new Error(`Component '${node.component}' not found at '${node.source}' (export '${exportKey}')`);\n }\n\n // Slot content priority:\n // 1. `children` (recursive tree) — pure-JSX container case.\n // 2. `bodyHtml` — raw HTML emitted as-is, no\n // conloca-slot wrapper. For\n // components whose Astro\n // implementation validates the\n // slot's element type.\n // 3. `<conloca-slot data-slot-id>{body}</conloca-slot>`\n // — default path for everything\n // else. The slot marker is the\n // portal target; `body` is the\n // static text fallback shown\n // when no portal is mounted.\n let slotContent: string;\n if (node.children && node.children.length > 0) {\n // Per-child error isolation: one broken `<Card>` no longer blanks\n // its sibling Cards. A failure to render any specific child\n // becomes an inline error stub (carrying that child's slot id so\n // the body editor still portals into it), and the parent goes on\n // to render with the stub HTML in that child's position.\n const renderedChildren = await Promise.all(\n node.children.map(async (child) => {\n try {\n return await renderTree(child, container, server);\n } catch (err) {\n // Log to the dev console so the failure isn't entirely\n // invisible — the inline stub is the author's surface, but\n // a dev tailing the terminal still wants the stack trace.\n console.warn(`[conloca:render] <${child.component}> failed:`, err instanceof Error ? err.message : err);\n return renderErrorStub(child, err);\n }\n }),\n );\n slotContent = renderedChildren.join('');\n } else if (node.bodyHtml) {\n slotContent = node.bodyHtml;\n } else {\n const fallback = node.body ?? '';\n slotContent = `<conloca-slot data-slot-id=\"${escapeHtml(node.slotId)}\">${fallback}</conloca-slot>`;\n }\n\n // Named slots (Astro's `<Fragment slot=\"header\">` pattern) are\n // passed alongside `default`. The client extracts them from mdast\n // and ships each as an HTML string keyed by slot name.\n const slots: Record<string, string> = { default: slotContent, ...(node.namedSlots ?? {}) };\n\n return container.renderToString(factory as Parameters<experimental_AstroContainer['renderToString']>[0], {\n props: node.props,\n slots,\n // Frameworks (Starlight, others) read content via `Astro.locals.t(...)`\n // set by their middleware. The bare container has none, so we\n // pass a fallback: strip namespace, capitalize the leaf\n // ('asides.note' → 'Note'). Real titles/body come from props.\n locals: { t: defaultI18nFallback } as App.Locals,\n });\n}\n\n/**\n * Build a self-contained, editable error stub for one render failure.\n *\n * Three jobs:\n * 1. Surface the error inline so the author sees *exactly* which\n * component blew up and why, right where it sits in the document.\n * No console-spelunking required.\n * 2. Keep the slot id intact so GenericBlock's portal-discovery loop\n * (`querySelectorAll('conloca-slot[data-slot-id]')`) still finds a\n * mount point inside the stub. The body editor mounts as normal;\n * the author can edit the children even though the parent\n * component's own render failed — typically that's enough to fix\n * whatever the validator was upset about.\n * 3. Stay structurally innocuous. A `<div>` wrapper renders cleanly\n * inside any parent slot that accepts arbitrary HTML, and a\n * data-attribute on the wrapper lets host CSS style it however\n * they like (yellow background, red border, whatever).\n *\n * Note: if the parent component itself has a strict-slot validator\n * (eg `<Tabs>` rejects non-TabItem children), the stub will fail the\n * parent's render too — but the recursion at the parent level then\n * catches THAT failure and emits its own stub one level up. The\n * worst case bubbles all the way to the top-level wrap in the\n * endpoint handler. Errors never escape as 500s.\n */\nfunction renderErrorStub(node: RenderTreeNode, err: unknown): string {\n const message = err instanceof Error ? err.message : String(err);\n const name = node.component || 'unknown';\n return (\n `<div class=\"conloca-render-error\" data-component=\"${escapeHtml(name)}\" data-slot-id=\"${escapeHtml(node.slotId)}\" role=\"alert\">` +\n `<div class=\"conloca-render-error__label\">&lt;${escapeHtml(name)}&gt; failed to render: ${escapeHtml(message)}</div>` +\n `<conloca-slot data-slot-id=\"${escapeHtml(node.slotId)}\"></conloca-slot>` +\n '</div>'\n );\n}\n\nfunction collectDisallowedSources(node: RenderTreeNode, allowed: Set<string>): string[] {\n const bad: string[] = [];\n if (!allowed.has(node.source)) bad.push(node.source);\n if (node.children) {\n for (const child of node.children) bad.push(...collectDisallowedSources(child, allowed));\n }\n return bad;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nfunction defaultI18nFallback(key: string): string {\n const leaf = key.split('.').pop() ?? key;\n return leaf.charAt(0).toUpperCase() + leaf.slice(1);\n}\n\nasync function readJson(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let raw = '';\n req.setEncoding('utf8');\n req.on('data', (chunk) => {\n raw += chunk;\n });\n req.on('end', () => {\n try {\n resolve(raw ? JSON.parse(raw) : {});\n } catch (err) {\n reject(err instanceof Error ? err : new Error('Invalid JSON'));\n }\n });\n req.on('error', reject);\n });\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\n\n/** Connect-compatible middleware handler — see render-endpoint.ts. */\ntype NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void;\n\n/**\n * Vite middleware that returns the concatenated CSS for a route URL.\n *\n * Used by the CMS editor SPA to fetch the styles that apply to the page\n * being edited so the editor renders content with the same CSS as the\n * published page.\n *\n * Mechanism (host-agnostic):\n *\n * 1. HTTP-fetch the live HTML at the route URL from the running dev\n * server. This is the same HTML a browser would receive — it lists\n * every stylesheet the page actually loads.\n * 2. Pull the content of every `<style>...</style>` block (where dev-\n * mode Astro inlines its component / Tailwind / user CSS).\n * 3. Pull every `<link rel=\"stylesheet\" href=\"…\">` (excluding\n * `media=\"print\"`) and fetch each one with `?direct` so the dev\n * server returns the raw CSS instead of the HMR JS wrapper.\n * 4. Concatenate in source order and return as `text/css`.\n *\n * Why this instead of Astro's `devCSSMap`:\n *\n * - `devCSSMap` is an Astro-internal virtual module. It only surfaces\n * CSS that flows through Astro's `.astro` component graph. Anything\n * emitted by an Astro integration as a STANDALONE asset (the\n * canonical example is expressive-code's `/_astro/ec.*.css`) sits\n * outside that graph and never reaches the editor through devCSSMap.\n * - Scraping the live HTML reads what the published page actually\n * paints with — the same stylesheets the user will see in the\n * browser. No dependency on a specific framework's internal API.\n *\n * Known limitations (rare on Astro sites):\n *\n * - CSS injected by JavaScript at runtime (`document.head.appendChild`)\n * isn't in the initial HTML, so we don't see it. Affects view-\n * transition handlers and third-party widget snippets.\n * - CSS-in-JS libraries (styled-components, emotion) generate styles\n * during client render and have the same blind spot.\n * - Cross-origin stylesheets the dev server can't reach get logged\n * and skipped (graceful degradation, not silent failure).\n */\nexport function createStylesEndpoint(): NextHandleFunction {\n return async (req, res, _next) => {\n try {\n const parsed = new URL(req.url ?? '', 'http://localhost');\n const routeUrl = parsed.searchParams.get('url');\n\n if (!routeUrl) {\n res.statusCode = 400;\n res.setHeader('content-type', 'text/plain');\n res.end('Missing required query parameter: url');\n return;\n }\n\n const host = req.headers.host ?? 'localhost:4321';\n const protocol = (req.headers['x-forwarded-proto'] as string) ?? 'http';\n const origin = `${protocol}://${host}`;\n const cookie = req.headers.cookie;\n\n const liveResponse = await fetch(`${origin}${routeUrl}`, {\n headers: cookie ? { cookie } : undefined,\n });\n\n // Propagate upstream non-200 status (eg 404 for unknown routes)\n // so the editor doesn't accidentally render a 404 page's CSS.\n if (!liveResponse.ok) {\n res.statusCode = liveResponse.status;\n res.setHeader('content-type', 'text/plain');\n res.end(`Upstream route returned ${liveResponse.status}: ${routeUrl}`);\n return;\n }\n\n const html = await liveResponse.text();\n const styles = await collectStylesFromHtml(html, origin, cookie);\n const body = styles.map((s) => `/* ${s.url} */\\n${s.css}`).join('\\n\\n');\n\n res.statusCode = 200;\n res.setHeader('content-type', 'text/css; charset=utf-8');\n // No-cache: dev HMR rewrites stylesheet contents in place; the\n // editor refetches on page switch, so cache invalidation is the\n // client's job, not the server's.\n res.setHeader('cache-control', 'no-store');\n res.end(body);\n } catch (err) {\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain');\n res.end(`Styles discovery failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n}\n\ninterface DiscoveredStyle {\n /** Diagnostic label — either an inline `<style>` marker or the link href. */\n url: string;\n /** Raw CSS text. */\n css: string;\n}\n\n/**\n * Read every `<style>` block and `<link rel=\"stylesheet\">` from the\n * HTML in their original source order. Inline `<style>` blocks are\n * captured verbatim; link tags are fetched separately (raw CSS via\n * `?direct`). Print-media stylesheets are skipped.\n *\n * Exported for unit testing.\n */\nexport async function collectStylesFromHtml(\n html: string,\n origin: string,\n cookie: string | undefined,\n): Promise<DiscoveredStyle[]> {\n // Strip comments first so opening-tag-shaped strings inside them\n // don't pollute the regex walk.\n const cleaned = html.replace(/<!--[\\s\\S]*?-->/g, '');\n\n // Iterate every <style> and <link> tag in source order. The naive\n // approach — scan once with a unified regex — is fragile for nested\n // attribute quoting. Two passes with positions, then merge sorted by\n // index, keeps the parsing simple AND preserves cascade order.\n type Entry = { index: number; fetch: () => Promise<DiscoveredStyle | null> };\n const entries: Entry[] = [];\n\n const styleRe = /<style\\b([^>]*)>([\\s\\S]*?)<\\/style>/gi;\n let match: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator\n while ((match = styleRe.exec(cleaned)) !== null) {\n const attrs = match[1];\n if (/media\\s*=\\s*[\"']?print/i.test(attrs)) continue;\n const css = match[2];\n const idAttr = attrs.match(/data-vite-dev-id=\"([^\"]+)\"/);\n const label = idAttr ? idAttr[1] : `<style#${match.index}>`;\n const captured = { url: label, css };\n entries.push({ index: match.index, fetch: () => Promise.resolve(captured) });\n }\n\n const linkRe = /<link\\b([^>]*)\\/?>/gi;\n // biome-ignore lint/suspicious/noAssignInExpressions: regex exec iterator\n while ((match = linkRe.exec(cleaned)) !== null) {\n const attrs = match[1];\n if (!/rel\\s*=\\s*[\"']?stylesheet[\"']?/i.test(attrs)) continue;\n if (/media\\s*=\\s*[\"']?print/i.test(attrs)) continue;\n const hrefMatch = attrs.match(/href\\s*=\\s*\"([^\"]+)\"|href\\s*=\\s*'([^']+)'/);\n if (!hrefMatch) continue;\n const href = hrefMatch[1] ?? hrefMatch[2];\n const index = match.index;\n entries.push({ index, fetch: () => fetchStylesheet(href, origin, cookie) });\n }\n\n // Source-order sort (style blocks and link tags interleave in HTML).\n entries.sort((a, b) => a.index - b.index);\n\n const results = await Promise.all(entries.map((e) => e.fetch()));\n return results.filter((r): r is DiscoveredStyle => r !== null);\n}\n\n/**\n * Fetch a stylesheet by href and return its raw CSS. Vite serves CSS\n * files as JS HMR wrappers by default; `?direct` flips that to raw CSS\n * output. Absolute URLs are fetched as-is; root-relative paths are\n * resolved against the dev server origin so cross-page link tags work.\n */\nasync function fetchStylesheet(\n href: string,\n origin: string,\n cookie: string | undefined,\n): Promise<DiscoveredStyle | null> {\n // Absolute URL (`https://…`) or relative — both need `?direct` only\n // when targeting our own dev server. External CDNs serve raw CSS\n // already; appending `?direct` would 404 there.\n const isLocal = !/^https?:\\/\\//i.test(href) || href.startsWith(origin);\n const target = isLocal\n ? `${origin}${href.startsWith('/') ? href : `/${href}`}${href.includes('?') ? '&direct' : '?direct'}`\n : href;\n try {\n const res = await fetch(target, { headers: cookie ? { cookie } : undefined });\n if (!res.ok) {\n console.warn(`[conloca:css] link fetch returned ${res.status} for ${href}`);\n return null;\n }\n const css = await res.text();\n return { url: href, css };\n } catch (err) {\n console.warn(`[conloca:css] link fetch failed for ${href}:`, err);\n return null;\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/reader';\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 { readSitesConfig } from '@conloca/content-api/node';\nimport viteReact from '@vitejs/plugin-react';\nimport type { AstroIntegration } from 'astro';\nimport { searchForWorkspaceRoot } from 'vite';\nimport { createRegistryEndpoint } from './discovery/registry-endpoint.js';\nimport { deriveComponentPaths, type HydrationDiscovery, scanForHydratableComponents } from './lib/hydration-scanner.js';\nimport { normalizeRoutingConfig, resolveRouteConfig } from './lib/routing-config.js';\nimport type { ConlocaLocales } from './locales-helpers.js';\nimport { createContentWrapperEndpoint } from './site-styles/content-wrapper-endpoint.js';\nimport { createRenderEndpoint } from './site-styles/render-endpoint.js';\nimport { createStylesEndpoint } from './site-styles/styles-endpoint.js';\n\n// FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.\n// It provides the React Fast Refresh preamble script needed for HMR in virtual modules.\n// If @vitejs/plugin-react removes or renames this property, the assertion below will\n// fail immediately at dev startup. Test after any @vitejs/plugin-react update.\nif (typeof viteReact.preambleCode !== 'string') {\n throw new Error(\n '@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +\n 'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +\n 'Check @vitejs/plugin-react release notes and update the preamble injection logic.',\n );\n}\n\nconst reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');\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, '..', 'internal', 'page-handler.astro');\nconst CMS_HANDLER_PATH = join(__dirname, '..', 'internal', 'cms-handler.mjs');\nconst ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', 'internal', 'acorn-default.mjs');\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\nasync function loadContentApiNode() {\n return import('@conloca/content-api/node');\n}\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 * Folders to scan for locally-authored MDX components. Their\n * `interface Props { ... }` is parsed into the editor's prop\n * panel automatically — no hand-written descriptors needed.\n *\n * Combined with the MDX usage scan (which picks up imports from\n * npm packages like `@astrojs/starlight/components`), this powers\n * the auto-discover registry served at `/__cms/api/registry`.\n *\n * Paths are project-relative. Defaults to `['src/components/mdx']`.\n *\n * @example ['src/components/mdx', 'src/components/blocks']\n */\n mdxComponentFolders?: 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 * CSS files to load in the CMS editor for component preview styling.\n *\n * Each file is processed by Vite (Tailwind, PostCSS, etc.) and injected\n * directly into Puck's preview iframe `<head>`. Site CSS never enters the\n * CMS admin's parent document, so host-site styles cannot bleed into the\n * CMS chrome (drawer, sidebar, etc.).\n *\n * @example './src/styles/global.css'\n * @example ['./src/styles/global.css', './src/styles/theme.css']\n */\n siteStyles?: string | string[];\n\n /**\n * Narrow CSS path injected into the MDX editor's admin document while the\n * editor is mounted. Use this to ship host-component styling\n * (`.conloca-aside`, `.conloca-card`, etc.) so the editor preview matches\n * the published surface, WITHOUT pulling in host Tailwind utilities or\n * `:root` token overrides that would collide with admin chrome.\n *\n * What belongs here: stylesheets that target only host-component class\n * selectors. Examples: `./src/styles/asides.css`,\n * `./src/styles/starlight-components.css`, `./src/styles/code-blocks.css`.\n *\n * What does NOT belong: the host's `global.css` (Tailwind base, theme,\n * utilities), `prose.css` (already loaded by `@conloca/mdx`), or any\n * stylesheet with `body`, `:root`, or `*` rules that would override\n * admin chrome. Those go in `siteStyles` instead — that path is only\n * injected into the Puck iframe, never the admin shell.\n *\n * @example ['./src/styles/asides.css', './src/styles/starlight-components.css']\n */\n editorStyles?: string | string[];\n\n /**\n * Route URL whose styles + content-wrapper shape get applied when\n * editing a standalone BLOCK (not a page). Blocks aren't tied to a\n * specific route, but they're consumed inside pages — so the\n * authoring experience should look like the user's actual site. The\n * editor fetches this route's CSS (via `/api/styles?url=…`) and its\n * content-root wrapper (via `/api/content-wrapper?url=…`) the same\n * way it does for pages, then renders the block inside that frame.\n *\n * Pick a representative content page on your site — typically the\n * site root or a docs landing page. Hosts that ship rich typography\n * benefit most; for hosts whose body bg matches the editor chrome,\n * the value barely matters. Defaults to `/` (site root).\n *\n * Per-block overrides via block frontmatter remain on the roadmap\n * for cases where one block ships only inside a specific layout.\n *\n * @example '/getting-started/'\n */\n blockPreviewRoute?: string;\n\n /**\n * Inline CSS to inject into the editor's `conloca-host-preview`\n * layer, applied AFTER auto-discovered host stylesheets. The\n * editor's content surround, prose card, and individual MDX\n * components all surface here; anything you write at this layer\n * wins on cascade order against the auto-discovery output (same\n * specificity, later layer position).\n *\n * Use for one-off overrides when:\n * - Your host body bg doesn't read well behind the editor chrome\n * and you want a specific color regardless.\n * - You want a different prose surface only inside the editor\n * (eg lighter for accessibility while authoring).\n * - A component renders correctly on the published page but\n * needs a small visual tweak in the editor — toolbar gutter,\n * focus ring, etc.\n *\n * Pure raw CSS. Conloca does no scoping or transformation, so any\n * selector you write needs to be specific enough not to leak into\n * the admin chrome (the chrome's selectors live in the `cms-admin`\n * layer, which sits LOWER in the cascade — so without explicitly\n * naming admin selectors, your CSS only reaches host components\n * and the content surround).\n *\n * @example `\n * /* Force a darker editor body even though the live page is light. *\\/\n * body { background-color: #0a0a0f; }\n * /* Custom focus ring for the prose surface. *\\/\n * .conloca-prose--editor:focus-within { outline: 2px solid hotpink; }\n * `\n */\n editorCSS?: string;\n\n /**\n * The site's supported locales and default locale.\n *\n * When set, Conloca uses this list as the single source of truth for\n * locale detection — folders or filename suffixes that don't match\n * one of these locales are left in the slug rather than silently\n * classified as a language. When omitted, falls back to the\n * `globalLocales` field in `<contentRoot>/sites.json` (the existing\n * behavior; preserved for backwards compatibility).\n *\n * Use one of the framework-bridge helpers exported from\n * `@conloca/astro-cms` to keep the declaration in a single spot:\n *\n * @example Pass Astro's i18n config directly:\n * ```ts\n * import { conlocaCMS, localesFromAstroI18n } from '@conloca/astro-cms';\n * const i18n = { defaultLocale: 'en', locales: ['en', 'de'] };\n * defineConfig({\n * i18n,\n * integrations: [conlocaCMS({ locales: localesFromAstroI18n(i18n) })],\n * });\n * ```\n *\n * @example Pass a literal list:\n * ```ts\n * conlocaCMS({ locales: { list: ['en', 'de'], defaultLocale: 'en' } });\n * ```\n */\n locales?: ConlocaLocales;\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, cmsSpaDistDir?: string) => {\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 const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/puck-config.mjs` : '@conloca/cms-spa/puck-config';\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${reactRefreshPreamble}\n\n// Import the setPuckConfig function from cms-spa\nimport { setPuckConfig } from '${puckConfigImport}';\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, cmsSpaDistDir?: string) => {\n const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/page-schemas.mjs` : '@conloca/cms-spa/page-schemas';\n const mdxComponentsImport = cmsSpaDistDir ? `${cmsSpaDistDir}/mdx-components.mjs` : '@conloca/cms-spa/mdx-components';\n // The host's schemas file may transitively import React components (the\n // `Editor` field on an MdxComponentDescriptor can be a JSX/TSX\n // component). Vite's React plugin requires the Fast Refresh preamble to\n // run before any TSX module is evaluated, so we emit it here and then\n // dynamically import the schemas file — matching the pattern used by\n // the Puck config loader above.\n return `\n${reactRefreshPreamble}\n\nimport { setPageSchemas } from '${pageSchemasImport}';\nimport { setMdxComponents } from '${mdxComponentsImport}';\n\nconst schemasPromise = import('${absoluteSchemasPath}');\n\nschemasPromise.then((schemas) => {\n if (schemas.pageSchemas) {\n setPageSchemas(schemas.pageSchemas);\n }\n if (schemas.mdxComponents) {\n setMdxComponents(schemas.mdxComponents);\n }\n});\n\nif (import.meta.hot) {\n import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {\n if (newModule?.pageSchemas) {\n setPageSchemas(newModule.pageSchemas);\n }\n if (newModule?.mdxComponents) {\n setMdxComponents(newModule.mdxComponents);\n }\n });\n}\n\nexport default schemasPromise;\n`;\n};\n\n// Template for the site styles loader virtual module.\n//\n// Each CSS file is imported with Vite's `?inline` query so the full CSS\n// pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet\n// as a string — no `<style>` tag is injected into the CMS admin's parent\n// `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles\n// registry; the editor's iframe bridge then injects them directly into\n// Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS\n// chrome and confines it to the intended consumer (the preview).\nconst siteStylesLoader = (cssPaths: string[], cmsSpaDistDir?: string) => {\n const imports = cssPaths\n .map((p, i) => {\n const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;\n return `import css${i} from '${absolutePath}?inline';`;\n })\n .join('\\n');\n const vars = cssPaths.map((_, i) => `css${i}`).join(', ');\n const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : '@conloca/cms-spa/site-styles';\n\n return `\n${imports}\nimport { setSiteStyles } from '${siteStylesImport}';\n\nsetSiteStyles([${vars}]);\n\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\nexport default {};\n`;\n};\n\n// Template for the editor styles loader virtual module — same shape as\n// siteStylesLoader but feeds a different registry (`setEditorStyles`),\n// consumed by the MDX editor's `useInjectHostStyles` call. Kept separate\n// from `siteStyles` because the two surfaces have opposite cascade needs;\n// see `packages/cms-spa/src/site-styles.ts` for the rationale.\nconst editorStylesLoader = (cssPaths: string[], cmsSpaDistDir?: string) => {\n const imports = cssPaths\n .map((p, i) => {\n const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;\n return `import css${i} from '${absolutePath}?inline';`;\n })\n .join('\\n');\n const vars = cssPaths.map((_, i) => `css${i}`).join(', ');\n const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : '@conloca/cms-spa/site-styles';\n\n return `\n${imports}\nimport { setEditorStyles } from '${siteStylesImport}';\n\nsetEditorStyles([${vars}]);\n\nif (import.meta.hot) {\n import.meta.hot.accept();\n}\n\nexport default {};\n`;\n};\n\nexport function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {\n const cmsRoute = options.route || '/__cms';\n\n // Resolve @conloca/cms-spa package directory for absolute imports in virtual\n // module templates. Bare specifiers like '@conloca/cms-spa/puck-config'\n // resolve from the Vite project root, which works when deps are hoisted\n // (npm consumers) but fails with isolated linkers (e.g. bun). Using the\n // resolved absolute path bypasses the project-root lookup entirely.\n let cmsSpaDir: string | undefined;\n try {\n const pkgUrl = import.meta.resolve('@conloca/cms-spa/package.json');\n cmsSpaDir = dirname(pkgUrl.startsWith('file://') ? fileURLToPath(pkgUrl) : pkgUrl);\n } catch {\n // Package not resolvable — virtual modules will fall back to bare specifiers\n }\n const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, 'dist') : undefined;\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 // `mdxPagesEnabled` and `resolvedMdxPages` start uninitialized; the\n // `astro:config:setup` hook reads sites.json (the canonical home for\n // per-site `mdxPages` paths) and mutates them before any virtual\n // module load fires — `load(id)` runs at request time, after the\n // hook completes.\n const spaConfig: {\n basename: string;\n apiBaseUrl: string;\n siteBaseUrl?: string;\n enableDevtools: boolean;\n queryClientOptions: unknown;\n schemasPath?: string;\n projectRoot: string;\n templates?: unknown;\n mdxPagesEnabled: boolean;\n locales?: { list: string[]; defaultLocale: string };\n } = {\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 // True when at least one site in sites.json declares an `mdxPages`\n // path. Drives the \"Document page\" option in the create-page dialog.\n // Initialized in the `astro:config:setup` hook below.\n mdxPagesEnabled: false,\n // Forward the locale list so the SPA stops hardcoding en/nl/fr in\n // the create-page dialog. The integration receives this from the\n // top-level `locales` option, which can in turn be produced by\n // `localesFromAstroI18n` / `localesFromStarlight`.\n locales: options.locales ? { list: options.locales.list, defaultLocale: options.locales.defaultLocale } : undefined,\n };\n\n // Resolved mdxPages path, populated from sites.json in the\n // config:setup hook. Used by the registry endpoint and content\n // watcher. `null` means no site declares an `mdxPages` path — .mdx\n // files (if any) fall back to living alongside Puck pages.\n let resolvedMdxPages: string | null = null;\n\n let refreshConlocaContent: (() => Promise<void>) | undefined;\n\n return {\n name: '@conloca/astro-cms',\n hooks: {\n 'astro:config:setup': async ({ updateConfig, injectRoute, command, logger }) => {\n // Read sites.json — the canonical home for per-site config\n // including the optional `mdxPages` field. Reading it here (once,\n // at integration setup) gives us a single source of truth for\n // the rest of the hook. `readSitesConfig` returns a safe default\n // when the file is missing or malformed.\n const sitesConfig = await readSitesConfig(options.contentRoot);\n // Pick the first site that declares an `mdxPages` path. Today's\n // integration supports a single `mdxPages` per project;\n // multi-site `mdxPages` is a future expansion (would require\n // fanning the watcher and registry scanner across all roots).\n const firstSiteWithMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages);\n resolvedMdxPages = firstSiteWithMdxPages?.mdxPages ?? null;\n spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);\n\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 // @puckeditor/core (and its zustand dependency) must always go through Vite's\n // SSR resolver, in dev AND build. SSR-external modules are require()'d directly\n // by Node, bypassing Vite's resolver — and `resolve.dedupe` below — entirely,\n // which risks pulling in a stray React copy from outside the workspace.\n const alwaysSsrNoExternal = ['@puckeditor/core'];\n // In dev, linked workspace packages also need to be bundled so React resolves\n // through Vite and HMR works from source (build mode uses their compiled dist output).\n const devOnlySsrNoExternal = [/^@conloca\\//];\n const serverOnlyExternal = [\n '@conloca/content-api',\n '@conloca/content-api/node',\n '@conloca/content-api/reader',\n '@conloca/content-api/schemas',\n '@conloca/mdx',\n '@conloca/mdx/node',\n ];\n updateConfig({\n vite: {\n ssr: {\n noExternal: command === 'dev' ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,\n // Keep Node-only content packages (content-api, mdx) external so SSR\n // builds do not try to bundle their server-only surfaces.\n external: serverOnlyExternal,\n },\n resolve: {\n // Dedupe React to avoid multiple instances when CMS SPA source is\n // loaded from a workspace sibling package. Only list packages the\n // consumer project declares directly — with bun's isolated linker,\n // transitive deps (e.g. @tanstack/react-query) live in the owning\n // package's node_modules and must NOT be forced to resolve from the\n // consumer root (which would fail).\n dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],\n },\n // Virtual modules for routing - needed in both dev and build\n plugins: [\n // Public page rendering should use Puck's server entry, not the full editor.\n // The full editor pulls client-only store code into Astro prerendering.\n {\n name: 'conloca-puck-ssr-render-alias',\n enforce: 'pre' as const,\n async resolveId(id, importer, options) {\n if (id === '@puckeditor/core' && options?.ssr) {\n return this.resolve('@puckeditor/core/rsc', importer, { ...options, skipSelf: true });\n }\n return null;\n },\n },\n // Alias acorn to a CJS shim only during SSR (static page builds).\n // Must NOT apply to the browser bundle — the shim uses createRequire\n // which is Node.js-only and crashes in the browser.\n {\n name: 'conloca-acorn-ssr-alias',\n enforce: 'pre' as const,\n resolveId(id, _importer, options) {\n if (id === 'acorn' && options?.ssr) {\n return ACORN_DEFAULT_SHIM_PATH;\n }\n return null;\n },\n },\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_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_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 // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are no\n // longer surfaced as env vars — the content-api reads them\n // directly from sites.json under `contentRoot` at request\n // time. See `readSitesConfig()` and `SitesConfig.sites[name].mdxPages`.\n // Default route URL the block editor uses for style /\n // wrapper discovery. See `blockPreviewRoute` option doc\n // above. `/` is a sane fallback for most layouts.\n 'import.meta.env.CONLOCA_BLOCK_PREVIEW_ROUTE': JSON.stringify(options.blockPreviewRoute || '/'),\n // Raw CSS the host wants injected into the editor's\n // `conloca-host-preview` layer for visual overrides.\n // See `editorCSS` option doc above for use cases.\n 'import.meta.env.CONLOCA_EDITOR_CSS': JSON.stringify(options.editorCSS || ''),\n // Top-level locales. Vite `define` does literal text\n // substitution, so this inlines as either a JS array or `null`.\n // The runtime handler reads it as-is — no JSON.parse needed.\n 'import.meta.env.CONLOCA_LOCALES': JSON.stringify(options.locales?.list ?? null),\n 'import.meta.env.CONLOCA_DEFAULT_LOCALE': JSON.stringify(options.locales?.defaultLocale || ''),\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 '@puckeditor/core',\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 // Normalize @conloca/* imports from symlinked source files (bun link).\n // When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports\n // resolve relative to the real filesystem location, creating duplicate\n // module instances. This plugin re-resolves them from the consumer\n // project root so all @conloca packages use the same module identity.\n {\n name: 'conloca-resolve-normalizer',\n enforce: 'pre' as const,\n async resolveId(source, importer) {\n // Only normalize @conloca/* bare specifiers\n if (!source.startsWith('@conloca/')) return null;\n // Only when imported from outside the project (symlinked source files)\n if (!importer || importer.startsWith(astroRoot)) return null;\n // Skip virtual modules (prefixed with \\0)\n if (importer.startsWith('\\0')) return null;\n // Re-resolve from project root to ensure consumer's node_modules is used\n const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });\n return resolved;\n },\n },\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 === `${cmsRoute}/site-styles.js`) {\n return id;\n }\n if (id === `${cmsRoute}/editor-styles.js`) {\n return id;\n }\n if (id === VIRTUAL_PAGE_API) {\n return RESOLVED_PAGE_API;\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, cmsSpaDistDir);\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, cmsSpaDistDir);\n }\n return 'export default {};';\n }\n if (id === `${cmsRoute}/site-styles.js`) {\n if (options.siteStyles) {\n const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];\n return siteStylesLoader(paths, cmsSpaDistDir);\n }\n return 'export default {};';\n }\n if (id === `${cmsRoute}/editor-styles.js`) {\n if (options.editorStyles) {\n const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];\n return editorStylesLoader(paths, cmsSpaDistDir);\n }\n return 'export default {};';\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_CMS_SPA_ENTRY) {\n // Detect whether cms-spa source is available (workspace mode)\n // vs only dist/ (npm install). Reuses `cmsSpaDir` resolved\n // at plugin setup time.\n let cmsSpaImport: string;\n if (cmsSpaDir) {\n const realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');\n // Prefer the consumer-side symlink path when @conloca/cms-spa is\n // linked in from another workspace (e.g. cross-repo `bun link`).\n // Importing via the symlink path keeps `react`/`react-dom`\n // resolving through the consumer's node_modules walk, which\n // prevents duplicate React instances inside the CMS SPA.\n // Same-workspace installs either don't expose this path or\n // point at the same underlying file, so behavior and HMR\n // are preserved.\n const linkedSrcMainPath = join(\n astroRoot,\n 'node_modules',\n '@conloca',\n 'cms-spa',\n 'src',\n 'main.tsx',\n );\n const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;\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 mounting entry\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n } else {\n // Fallback: use package import\n cmsSpaImport = \"import '@conloca/cms-spa/main';\";\n }\n\n return `\n// Import and execute React refresh preamble first (from @vitejs/plugin-react)\n${reactRefreshPreamble}\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 // Per-page styles endpoint. Fetches the live HTML for the\n // route and returns every `<style>` block and `<link\n // rel=\"stylesheet\">` it lists — the same set of stylesheets\n // the browser paints with.\n name: 'conloca-styles-endpoint',\n apply: 'serve' as const,\n configureServer(server) {\n server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());\n },\n },\n {\n // Per-route content-wrapper endpoint. Fetches the live page\n // HTML and returns the host's content-root element shape\n // (`{ tagName, className }`) so the editor can render its\n // contenteditable inside a clone of that wrapper — letting\n // the host's CSS (eg `article.card { background: … }`) paint\n // the editor's content surface naturally, with no per-color\n // bridging.\n name: 'conloca-content-wrapper-endpoint',\n apply: 'serve' as const,\n configureServer(server) {\n server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());\n },\n },\n {\n // Registry + render endpoints are paired: the registry\n // builds the list of legal component sources, and the\n // render endpoint validates every incoming `source`\n // against that list before passing it to ssrLoadModule.\n // Constructing both in one configureServer hook means\n // they share the same memoized scan — no cross-plugin\n // state, no startup-order race.\n //\n // - Registry: scans MDX content for imports + usages and\n // the configured local component folders for\n // `interface Props { ... }`, merges into a single\n // descriptor list, returns it as JSON. The SPA fetches\n // this on mount and seeds `setMdxComponents`,\n // replacing the hand-written `mdx-components.tsx` flow.\n // - Render: renders a single MDX component (Aside,\n // Card, …) via Astro's Container API so the CMS editor\n // can display the real framework markup, paired with\n // the per-page CSS from the styles endpoint above.\n name: 'conloca-registry-and-render-endpoints',\n apply: 'serve' as const,\n configureServer(server) {\n const registry = createRegistryEndpoint({\n contentRoot: resolvedMdxPages ?? options.contentRoot,\n componentFolders: options.mdxComponentFolders ?? ['src/components/mdx'],\n projectRoot: process.cwd(),\n });\n server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);\n server.middlewares.use(\n `${cmsRoute}/api/render`,\n createRenderEndpoint(server, registry.getAllowedSources),\n );\n\n // Invalidate the cached scan whenever an .mdx file or\n // any component file changes. Coarse for now — every\n // change re-scans everything; cheap enough for typical\n // project sizes. `.cms.json` sidecars also trigger\n // invalidation so host overrides apply live without a\n // dev-server restart.\n const onFsChange = (filepath: string) => {\n if (/\\.(mdx|astro|tsx|d\\.ts|cms\\.json)$/.test(filepath)) registry.invalidate();\n };\n server.watcher.on('add', onFsChange);\n server.watcher.on('change', onFsChange);\n server.watcher.on('unlink', onFsChange);\n },\n },\n {\n name: 'conloca-content-watcher',\n async configureServer(server) {\n const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();\n\n // Initialize content API using the extracted function.\n // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are\n // read from sites.json by the content-api itself; we\n // don't pass them here.\n const contentApi = await createContentAPI({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n ...(options.locales && {\n availableLocales: options.locales.list,\n defaultLocale: options.locales.defaultLocale,\n }),\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 // The watcher uses `mdxPagesRoot` to flag events under\n // the mdx tree (so docs-loader can refresh). The value\n // comes from sites.json via `resolvedMdxPages`.\n const handlers = createContentWatchHandlers(\n contentApi,\n {\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n ...(resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }),\n },\n server.ws,\n async (event) => {\n await refreshConlocaContent?.();\n\n // Astro 6's content-virtual-mod plugin registers an explicit\n // file watcher on `.astro/data-store.json` only (see\n // dist/content/vite-plugin-content-virtual-mod.js: `devServer.watcher.add(dataStoreFile)`).\n // It does NOT watch the sibling `content-modules.mjs` (file\n // path → render function map). When Starlight's docsLoader\n // adds a new MDX entry at runtime, that file IS rewritten on\n // disk, but Vite's SSR moduleGraph keeps the stale module\n // and `renderEntry` throws UnknownContentCollectionError.\n // Force-reload the file ourselves; `reloadModule` is the\n // Vite API that re-runs the load hook on next SSR import.\n if (event.inMdxRoot) {\n const dotAstroModulesFile = resolve(astroRoot, '.astro', 'content-modules.mjs');\n const dotAstroAssetsFile = resolve(astroRoot, '.astro', 'content-assets.mjs');\n for (const env of Object.values(server.environments ?? {})) {\n if (!env?.moduleGraph) continue;\n for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {\n const mod = env.moduleGraph.getModuleById(filePath);\n if (!mod) continue;\n const envWithReload = env as unknown as {\n reloadModule?: (m: unknown) => void | Promise<void>;\n };\n if (typeof envWithReload.reloadModule === 'function') {\n void Promise.resolve(envWithReload.reloadModule(mod)).catch(() => undefined);\n } else {\n env.moduleGraph.invalidateModule(mod, undefined, Date.now(), true);\n }\n }\n env.hot?.send('astro:content-changed', {});\n }\n }\n },\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 name: 'conloca-suppress-cms-save-reload',\n apply: 'serve' as const,\n configureServer(server) {\n let suppressUntil = 0;\n const WINDOW_MS = 2000;\n const cmsContentPrefix = `${cmsRoute}/api/content`;\n\n server.middlewares.use((req, _res, next) => {\n const isWrite =\n req.method === 'POST' ||\n req.method === 'PUT' ||\n req.method === 'PATCH' ||\n req.method === 'DELETE';\n if (isWrite && req.url?.startsWith(cmsContentPrefix)) {\n suppressUntil = Date.now() + WINDOW_MS;\n }\n next();\n });\n\n // During a CMS save window, drop two server→client signals that\n // would otherwise stomp on the CMS's own optimistic cache updates:\n //\n // 1. Vite `full-reload` — emitted by Astro 6.2.1's invalidateDataStore()\n // in dist/content/vite-plugin-content-virtual-mod.js. The call site\n // is in a configureServer watcher callback, outside the\n // handleHotUpdate pipeline, so wrapping hot.send is the only intercept.\n //\n // 2. `conloca:content-update` custom event — emitted by\n // conloca-content-watcher above. The client listener (template at\n // `contentChangeListener` in this file) reacts by calling\n // queryClient.invalidateQueries() with NO args, refetching every\n // query and visibly blinking lists. CMS mutation hooks already do\n // optimistic setQueryData, so this event is redundant for\n // CMS-originated writes. External edits (outside the save window)\n // still pass through normally.\n const shouldDropDuringWindow = (payload: unknown): boolean => {\n if (!payload || typeof payload !== 'object') return false;\n const p = payload as { type?: string; event?: string };\n if (p.type === 'full-reload') return true;\n if (p.type === 'custom' && p.event === 'conloca:content-update') return true;\n return false;\n };\n\n const patchSend = <T extends { send: (...a: never[]) => unknown }>(target: T | undefined) => {\n if (!target) return;\n const marked = target as unknown as { __conlocaPatched?: boolean };\n if (marked.__conlocaPatched) return;\n const origSend = target.send.bind(target);\n target.send = ((payload: unknown, ...rest: unknown[]) => {\n if (shouldDropDuringWindow(payload) && Date.now() < suppressUntil) {\n server.config.logger.info(\n `[conloca] suppressed ${(payload as { type: string }).type} during CMS save window`,\n { timestamp: true },\n );\n return;\n }\n return (origSend as (...a: unknown[]) => unknown)(payload, ...rest);\n }) as T['send'];\n marked.__conlocaPatched = true;\n };\n\n // Astro's content plugin sends `full-reload` via environments.client.hot.\n // Conloca's content watcher sends custom events via server.ws (legacy API).\n // Patch both; idempotent per-target via __conlocaPatched.\n patchSend(server.environments?.client?.hot);\n patchSend(server.ws);\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: CMS_HANDLER_PATH,\n prerender: false,\n });\n\n // Also handle the root CMS route\n injectRoute({\n pattern: cmsRoute,\n entrypoint: CMS_HANDLER_PATH,\n prerender: false,\n });\n },\n\n 'astro:server:setup': ({ logger, refreshContent }) => {\n logger.info(`Conloca CMS available at ${cmsRoute}`);\n\n let refreshChain = Promise.resolve();\n\n refreshConlocaContent = async () => {\n if (!refreshContent) {\n return;\n }\n\n refreshChain = refreshChain\n .catch(() => undefined)\n .then(async () => {\n await refreshContent({ loaders: ['conloca-loader'] });\n });\n\n await refreshChain;\n };\n\n // Register dev-time content refresh after the Vite server exists.\n // This keeps Astro collections in sync with Conloca's own file watcher.\n logger.debug('Registering Conloca content refresh handler');\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 project routes that conflict with injected routes.\n // Integration routes (origin: 'external') sharing the same catch-all pattern\n // is expected — Astro's prerender fallthrough handles coexistence automatically.\n const conflicts: { injected: string; fileBased: string }[] = [];\n\n for (const route of routes) {\n if (route.origin !== 'project') continue;\n\n const pattern = route.pattern;\n if (injectedPatterns.has(pattern)) {\n conflicts.push({\n injected: pattern,\n fileBased: route.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,MAAa,2BACX;AAIF,MAAa,oBAAoB;AAGjC,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAQ;CAAW;AAAM,CAAC;;;;;;;;;;;;;AAc5D,SAAgB,qBAAqB,gBAAwB,eAAoC;CAE/F,MAAM,kBAAkB,KADR,QAAQ,cACW,GAAG,cAAc,MAAM;CAE1D,IAAI,iBAAiB,cAAc,SAAS,GAC1C,OAAO,CAAC,iBAAiB,GAAG,aAAa;CAE3C,OAAO,CAAC,eAAe;AACzB;;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