@conloca/astro-cms 0.1.16 → 0.2.1

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 (422) hide show
  1. package/README.md +254 -301
  2. package/dist/internal/acorn-default.mjs +11 -3
  3. package/dist/internal/page-handler.astro +137 -358
  4. package/dist/ts/node/content.d.ts +4 -0
  5. package/dist/ts/node/content.d.ts.map +1 -0
  6. package/dist/ts/node/content.js +3 -0
  7. package/dist/ts/node/content.js.map +1 -0
  8. package/dist/ts/node/index.d.ts +9 -0
  9. package/dist/ts/node/index.d.ts.map +1 -0
  10. package/dist/ts/node/index.js +14 -0
  11. package/dist/ts/node/index.js.map +1 -0
  12. package/dist/ts/src/asset-ref-base.d.ts +3 -0
  13. package/dist/ts/src/asset-ref-base.d.ts.map +1 -0
  14. package/dist/ts/src/asset-ref-base.js +48 -0
  15. package/dist/ts/src/asset-ref-base.js.map +1 -0
  16. package/dist/ts/src/checks.d.ts +7 -0
  17. package/dist/ts/src/checks.d.ts.map +1 -0
  18. package/dist/ts/src/checks.js +7 -0
  19. package/dist/ts/src/checks.js.map +1 -0
  20. package/dist/{src → ts/src}/cms-handler.d.ts +0 -1
  21. package/dist/ts/src/cms-handler.d.ts.map +1 -0
  22. package/dist/{src → ts/src}/cms-handler.js +11 -131
  23. package/dist/ts/src/cms-handler.js.map +1 -0
  24. package/dist/ts/src/collections.d.ts +161 -0
  25. package/dist/ts/src/collections.d.ts.map +1 -0
  26. package/dist/ts/src/collections.js +178 -0
  27. package/dist/ts/src/collections.js.map +1 -0
  28. package/dist/{src → ts/src}/components/HydrationWrapper.d.ts +1 -1
  29. package/dist/ts/src/components/HydrationWrapper.d.ts.map +1 -0
  30. package/dist/{src → ts/src}/components/HydrationWrapper.js +1 -0
  31. package/dist/ts/src/components/HydrationWrapper.js.map +1 -0
  32. package/dist/{src/components/RenderWithBlocks.d.ts → ts/src/components/RenderWithFragments.d.ts} +8 -4
  33. package/dist/ts/src/components/RenderWithFragments.d.ts.map +1 -0
  34. package/dist/ts/src/components/RenderWithFragments.js +133 -0
  35. package/dist/ts/src/components/RenderWithFragments.js.map +1 -0
  36. package/dist/{src → ts/src}/components/RenderWithHydration.d.ts +6 -2
  37. package/dist/ts/src/components/RenderWithHydration.d.ts.map +1 -0
  38. package/dist/{src → ts/src}/components/RenderWithHydration.js +6 -3
  39. package/dist/ts/src/components/RenderWithHydration.js.map +1 -0
  40. package/dist/ts/src/components.d.ts +4 -0
  41. package/dist/ts/src/components.d.ts.map +1 -0
  42. package/dist/ts/src/components.js +4 -0
  43. package/dist/ts/src/components.js.map +1 -0
  44. package/dist/ts/src/discovery/astro-frontmatter.d.ts.map +1 -0
  45. package/dist/{src → ts/src}/discovery/astro-frontmatter.js +1 -0
  46. package/dist/ts/src/discovery/astro-frontmatter.js.map +1 -0
  47. package/dist/ts/src/discovery/discover.d.ts +43 -0
  48. package/dist/ts/src/discovery/discover.d.ts.map +1 -0
  49. package/dist/ts/src/discovery/discover.js +87 -0
  50. package/dist/ts/src/discovery/discover.js.map +1 -0
  51. package/dist/ts/src/discovery/extract-props-ts.d.ts.map +1 -0
  52. package/dist/{src → ts/src}/discovery/extract-props-ts.js +1 -0
  53. package/dist/ts/src/discovery/extract-props-ts.js.map +1 -0
  54. package/dist/{src → ts/src}/discovery/merge-registry.d.ts +3 -3
  55. package/dist/ts/src/discovery/merge-registry.d.ts.map +1 -0
  56. package/dist/{src → ts/src}/discovery/merge-registry.js +1 -0
  57. package/dist/ts/src/discovery/merge-registry.js.map +1 -0
  58. package/dist/ts/src/discovery/registry-endpoint.d.ts +27 -0
  59. package/dist/ts/src/discovery/registry-endpoint.d.ts.map +1 -0
  60. package/dist/ts/src/discovery/registry-endpoint.js +76 -0
  61. package/dist/ts/src/discovery/registry-endpoint.js.map +1 -0
  62. package/dist/{src → ts/src}/discovery/scan-components.d.ts +3 -7
  63. package/dist/ts/src/discovery/scan-components.d.ts.map +1 -0
  64. package/dist/{src → ts/src}/discovery/scan-components.js +4 -6
  65. package/dist/ts/src/discovery/scan-components.js.map +1 -0
  66. package/dist/ts/src/discovery/scan-mdx.d.ts.map +1 -0
  67. package/dist/{src → ts/src}/discovery/scan-mdx.js +1 -0
  68. package/dist/ts/src/discovery/scan-mdx.js.map +1 -0
  69. package/dist/ts/src/discovery/scan-overrides.d.ts.map +1 -0
  70. package/dist/{src → ts/src}/discovery/scan-overrides.js +1 -0
  71. package/dist/ts/src/discovery/scan-overrides.js.map +1 -0
  72. package/dist/ts/src/editor-descriptors.d.ts +31 -0
  73. package/dist/ts/src/editor-descriptors.d.ts.map +1 -0
  74. package/dist/ts/src/editor-descriptors.js +84 -0
  75. package/dist/ts/src/editor-descriptors.js.map +1 -0
  76. package/dist/ts/src/handlers/collection-content-api.d.ts +32 -0
  77. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -0
  78. package/dist/ts/src/handlers/collection-content-api.js +166 -0
  79. package/dist/ts/src/handlers/collection-content-api.js.map +1 -0
  80. package/dist/ts/src/handlers/page-render-core.d.ts +137 -0
  81. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -0
  82. package/dist/ts/src/handlers/page-render-core.js +315 -0
  83. package/dist/ts/src/handlers/page-render-core.js.map +1 -0
  84. package/dist/ts/src/hydration.d.ts.map +1 -0
  85. package/dist/{src → ts/src}/hydration.js +1 -0
  86. package/dist/ts/src/hydration.js.map +1 -0
  87. package/dist/ts/src/index.d.ts +21 -0
  88. package/dist/ts/src/index.d.ts.map +1 -0
  89. package/dist/ts/src/index.js +45 -0
  90. package/dist/ts/src/index.js.map +1 -0
  91. package/dist/ts/src/internal/declared-collections.d.ts +30 -0
  92. package/dist/ts/src/internal/declared-collections.d.ts.map +1 -0
  93. package/dist/ts/src/internal/declared-collections.js +84 -0
  94. package/dist/ts/src/internal/declared-collections.js.map +1 -0
  95. package/dist/ts/src/internal/page-collection-schema.d.ts +44 -0
  96. package/dist/ts/src/internal/page-collection-schema.d.ts.map +1 -0
  97. package/dist/ts/src/internal/page-collection-schema.js +152 -0
  98. package/dist/ts/src/internal/page-collection-schema.js.map +1 -0
  99. package/dist/ts/src/lib/content-config-guard.d.ts +13 -0
  100. package/dist/ts/src/lib/content-config-guard.d.ts.map +1 -0
  101. package/dist/ts/src/lib/content-config-guard.js +45 -0
  102. package/dist/ts/src/lib/content-config-guard.js.map +1 -0
  103. package/dist/ts/src/lib/hydration-scanner.d.ts.map +1 -0
  104. package/dist/{src → ts/src}/lib/hydration-scanner.js +1 -0
  105. package/dist/ts/src/lib/hydration-scanner.js.map +1 -0
  106. package/dist/ts/src/lib/hydration-script.d.ts.map +1 -0
  107. package/dist/{src → ts/src}/lib/hydration-script.js +1 -0
  108. package/dist/ts/src/lib/hydration-script.js.map +1 -0
  109. package/dist/ts/src/lib/hydration-utils.d.ts.map +1 -0
  110. package/dist/{src → ts/src}/lib/hydration-utils.js +1 -0
  111. package/dist/ts/src/lib/hydration-utils.js.map +1 -0
  112. package/dist/ts/src/lib/resolve-locale.d.ts +15 -0
  113. package/dist/ts/src/lib/resolve-locale.d.ts.map +1 -0
  114. package/dist/ts/src/lib/resolve-locale.js +16 -0
  115. package/dist/ts/src/lib/resolve-locale.js.map +1 -0
  116. package/dist/ts/src/lib/resolve-site-name.d.ts +8 -0
  117. package/dist/ts/src/lib/resolve-site-name.d.ts.map +1 -0
  118. package/dist/ts/src/lib/resolve-site-name.js +12 -0
  119. package/dist/ts/src/lib/resolve-site-name.js.map +1 -0
  120. package/dist/{src → ts/src}/lib/route-utils.d.ts +26 -6
  121. package/dist/ts/src/lib/route-utils.d.ts.map +1 -0
  122. package/dist/{src → ts/src}/lib/route-utils.js +33 -15
  123. package/dist/ts/src/lib/route-utils.js.map +1 -0
  124. package/dist/{src → ts/src}/lib/routing-config.d.ts +7 -1
  125. package/dist/ts/src/lib/routing-config.d.ts.map +1 -0
  126. package/dist/{src → ts/src}/lib/routing-config.js +13 -0
  127. package/dist/ts/src/lib/routing-config.js.map +1 -0
  128. package/dist/ts/src/lib/serialize-props.d.ts.map +1 -0
  129. package/dist/{src → ts/src}/lib/serialize-props.js +1 -0
  130. package/dist/ts/src/lib/serialize-props.js.map +1 -0
  131. package/dist/ts/src/lib/unknown-components.d.ts +21 -0
  132. package/dist/ts/src/lib/unknown-components.d.ts.map +1 -0
  133. package/dist/ts/src/lib/unknown-components.js +49 -0
  134. package/dist/ts/src/lib/unknown-components.js.map +1 -0
  135. package/dist/{src → ts/src}/lib/virtual-module-generators.d.ts +0 -24
  136. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -0
  137. package/dist/ts/src/lib/virtual-module-generators.js +51 -0
  138. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -0
  139. package/dist/ts/src/lib/withHydration.d.ts.map +1 -0
  140. package/dist/{src → ts/src}/lib/withHydration.js +1 -0
  141. package/dist/ts/src/lib/withHydration.js.map +1 -0
  142. package/dist/ts/src/loader.d.ts +27 -0
  143. package/dist/ts/src/loader.d.ts.map +1 -0
  144. package/dist/{src → ts/src}/loader.js +33 -4
  145. package/dist/ts/src/loader.js.map +1 -0
  146. package/dist/ts/src/locales-helpers.d.ts.map +1 -0
  147. package/dist/{src → ts/src}/locales-helpers.js +1 -0
  148. package/dist/ts/src/locales-helpers.js.map +1 -0
  149. package/dist/ts/src/mime-types.d.ts.map +1 -0
  150. package/dist/{src → ts/src}/mime-types.js +1 -0
  151. package/dist/ts/src/mime-types.js.map +1 -0
  152. package/dist/ts/src/page-feed.d.ts +13 -0
  153. package/dist/ts/src/page-feed.d.ts.map +1 -0
  154. package/dist/ts/src/page-feed.js +20 -0
  155. package/dist/ts/src/page-feed.js.map +1 -0
  156. package/dist/ts/src/page-schemas.d.ts +6 -0
  157. package/dist/ts/src/page-schemas.d.ts.map +1 -0
  158. package/dist/ts/src/page-schemas.js +6 -0
  159. package/dist/ts/src/page-schemas.js.map +1 -0
  160. package/dist/ts/src/path-validation.d.ts.map +1 -0
  161. package/dist/{src → ts/src}/path-validation.js +1 -0
  162. package/dist/ts/src/path-validation.js.map +1 -0
  163. package/dist/{src → ts/src}/plugin-spa.d.ts +28 -10
  164. package/dist/ts/src/plugin-spa.d.ts.map +1 -0
  165. package/dist/{src → ts/src}/plugin-spa.js +301 -88
  166. package/dist/ts/src/plugin-spa.js.map +1 -0
  167. package/dist/ts/src/puck-manifest/components-endpoint.d.ts +30 -0
  168. package/dist/ts/src/puck-manifest/components-endpoint.d.ts.map +1 -0
  169. package/dist/ts/src/puck-manifest/components-endpoint.js +54 -0
  170. package/dist/ts/src/puck-manifest/components-endpoint.js.map +1 -0
  171. package/dist/ts/src/puck-manifest/field-projection.d.ts +91 -0
  172. package/dist/ts/src/puck-manifest/field-projection.d.ts.map +1 -0
  173. package/dist/ts/src/puck-manifest/field-projection.js +422 -0
  174. package/dist/ts/src/puck-manifest/field-projection.js.map +1 -0
  175. package/dist/ts/src/puck-manifest/index.d.ts +4 -0
  176. package/dist/ts/src/puck-manifest/index.d.ts.map +1 -0
  177. package/dist/ts/src/puck-manifest/index.js +3 -0
  178. package/dist/ts/src/puck-manifest/index.js.map +1 -0
  179. package/dist/ts/src/puck-manifest/literal.d.ts +163 -0
  180. package/dist/ts/src/puck-manifest/literal.d.ts.map +1 -0
  181. package/dist/ts/src/puck-manifest/literal.js +354 -0
  182. package/dist/ts/src/puck-manifest/literal.js.map +1 -0
  183. package/dist/ts/src/puck-manifest/read-config.d.ts +42 -0
  184. package/dist/ts/src/puck-manifest/read-config.d.ts.map +1 -0
  185. package/dist/ts/src/puck-manifest/read-config.js +517 -0
  186. package/dist/ts/src/puck-manifest/read-config.js.map +1 -0
  187. package/dist/ts/src/puck-manifest/read-field.d.ts +7 -0
  188. package/dist/ts/src/puck-manifest/read-field.d.ts.map +1 -0
  189. package/dist/ts/src/puck-manifest/read-field.js +11 -0
  190. package/dist/ts/src/puck-manifest/read-field.js.map +1 -0
  191. package/dist/ts/src/puck-manifest/read-wrapper.d.ts +147 -0
  192. package/dist/ts/src/puck-manifest/read-wrapper.d.ts.map +1 -0
  193. package/dist/ts/src/puck-manifest/read-wrapper.js +889 -0
  194. package/dist/ts/src/puck-manifest/read-wrapper.js.map +1 -0
  195. package/dist/ts/src/puck-manifest/reading-budget.d.ts +50 -0
  196. package/dist/ts/src/puck-manifest/reading-budget.d.ts.map +1 -0
  197. package/dist/ts/src/puck-manifest/reading-budget.js +113 -0
  198. package/dist/ts/src/puck-manifest/reading-budget.js.map +1 -0
  199. package/dist/ts/src/puck-manifest/resolve-reference.d.ts +4 -0
  200. package/dist/ts/src/puck-manifest/resolve-reference.d.ts.map +1 -0
  201. package/dist/ts/src/puck-manifest/resolve-reference.js +4 -0
  202. package/dist/ts/src/puck-manifest/resolve-reference.js.map +1 -0
  203. package/dist/ts/src/puck-manifest/source-reference.d.ts +96 -0
  204. package/dist/ts/src/puck-manifest/source-reference.d.ts.map +1 -0
  205. package/dist/ts/src/puck-manifest/source-reference.js +424 -0
  206. package/dist/ts/src/puck-manifest/source-reference.js.map +1 -0
  207. package/dist/ts/src/puck-manifest/syntax.d.ts +29 -0
  208. package/dist/ts/src/puck-manifest/syntax.d.ts.map +1 -0
  209. package/dist/ts/src/puck-manifest/syntax.js +79 -0
  210. package/dist/ts/src/puck-manifest/syntax.js.map +1 -0
  211. package/dist/ts/src/puck-manifest/types.d.ts +145 -0
  212. package/dist/ts/src/puck-manifest/types.d.ts.map +1 -0
  213. package/dist/ts/src/puck-manifest/types.js +2 -0
  214. package/dist/ts/src/puck-manifest/types.js.map +1 -0
  215. package/dist/ts/src/safe-json-stringify.d.ts.map +1 -0
  216. package/dist/{src → ts/src}/safe-json-stringify.js +1 -0
  217. package/dist/ts/src/safe-json-stringify.js.map +1 -0
  218. package/dist/ts/src/sandbox-frame-handler.d.ts +19 -0
  219. package/dist/ts/src/sandbox-frame-handler.d.ts.map +1 -0
  220. package/dist/ts/src/sandbox-frame-handler.js +27 -0
  221. package/dist/ts/src/sandbox-frame-handler.js.map +1 -0
  222. package/dist/{src → ts/src}/site-styles/content-wrapper-endpoint.d.ts +2 -5
  223. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  224. package/dist/{src → ts/src}/site-styles/content-wrapper-endpoint.js +5 -8
  225. package/dist/ts/src/site-styles/content-wrapper-endpoint.js.map +1 -0
  226. package/dist/{src → ts/src}/site-styles/render-endpoint.d.ts +4 -9
  227. package/dist/ts/src/site-styles/render-endpoint.d.ts.map +1 -0
  228. package/dist/{src → ts/src}/site-styles/render-endpoint.js +1 -0
  229. package/dist/ts/src/site-styles/render-endpoint.js.map +1 -0
  230. package/dist/{src → ts/src}/site-styles/styles-endpoint.d.ts +2 -4
  231. package/dist/ts/src/site-styles/styles-endpoint.d.ts.map +1 -0
  232. package/dist/{src → ts/src}/site-styles/styles-endpoint.js +3 -5
  233. package/dist/ts/src/site-styles/styles-endpoint.js.map +1 -0
  234. package/dist/ts/src/sitemap-options.d.ts +21 -0
  235. package/dist/ts/src/sitemap-options.d.ts.map +1 -0
  236. package/dist/ts/src/sitemap-options.js +92 -0
  237. package/dist/ts/src/sitemap-options.js.map +1 -0
  238. package/dist/ts/src/tiptap-html-static.d.ts +16 -0
  239. package/dist/ts/src/tiptap-html-static.d.ts.map +1 -0
  240. package/dist/ts/src/tiptap-html-static.js +117 -0
  241. package/dist/ts/src/tiptap-html-static.js.map +1 -0
  242. package/dist/{src → ts/src}/types.d.ts +26 -110
  243. package/dist/ts/src/types.d.ts.map +1 -0
  244. package/dist/ts/src/types.js +2 -0
  245. package/dist/ts/src/types.js.map +1 -0
  246. package/dist/virtual-modules.d.ts +12 -93
  247. package/node/content.ts +14 -0
  248. package/node/index.ts +22 -0
  249. package/package.json +161 -73
  250. package/src/asset-ref-base.ts +48 -0
  251. package/src/checks.ts +11 -0
  252. package/src/cms-handler.ts +281 -0
  253. package/src/collections.ts +271 -0
  254. package/src/components/HydrationWrapper.tsx +41 -0
  255. package/src/components/RenderWithFragments.tsx +204 -0
  256. package/src/components/RenderWithHydration.tsx +55 -0
  257. package/src/components.ts +3 -0
  258. package/src/discovery/astro-frontmatter.ts +24 -0
  259. package/src/discovery/discover.ts +108 -0
  260. package/src/discovery/extract-props-ts.ts +255 -0
  261. package/src/discovery/merge-registry.ts +411 -0
  262. package/src/discovery/registry-endpoint.ts +80 -0
  263. package/src/discovery/scan-components.ts +458 -0
  264. package/src/discovery/scan-mdx.ts +190 -0
  265. package/src/discovery/scan-overrides.ts +92 -0
  266. package/src/editor-descriptors.ts +96 -0
  267. package/src/env.d.ts +31 -0
  268. package/src/handlers/collection-content-api.ts +196 -0
  269. package/src/handlers/page-handler.astro +320 -0
  270. package/src/handlers/page-render-core.ts +456 -0
  271. package/src/hydration.ts +7 -0
  272. package/src/index.ts +111 -0
  273. package/src/internal/acorn-default.mjs +37 -0
  274. package/src/internal/declared-collections.ts +98 -0
  275. package/src/internal/page-collection-schema.ts +210 -0
  276. package/src/lib/content-config-guard.ts +53 -0
  277. package/src/lib/hydration-scanner.ts +176 -0
  278. package/src/lib/hydration-script.ts +126 -0
  279. package/src/lib/hydration-utils.ts +120 -0
  280. package/src/lib/resolve-locale.ts +22 -0
  281. package/src/lib/resolve-site-name.ts +10 -0
  282. package/src/lib/route-utils.ts +106 -0
  283. package/src/lib/routing-config.ts +126 -0
  284. package/src/lib/serialize-props.ts +7 -0
  285. package/src/lib/unknown-components.ts +64 -0
  286. package/src/lib/virtual-module-generators.ts +58 -0
  287. package/{dist/withHydration-DkKpkmzJ.d.mts → src/lib/withHydration.ts} +25 -8
  288. package/src/loader.ts +145 -0
  289. package/{dist/locales-helpers-BvYYqnJ5.d.mts → src/locales-helpers.ts} +21 -17
  290. package/src/mime-types.ts +19 -0
  291. package/src/page-feed.ts +26 -0
  292. package/src/page-schemas.ts +19 -0
  293. package/src/path-validation.ts +13 -0
  294. package/src/plugin-spa.ts +1496 -0
  295. package/src/puck-manifest/components-endpoint.ts +55 -0
  296. package/src/puck-manifest/field-projection.ts +510 -0
  297. package/src/puck-manifest/index.ts +3 -0
  298. package/src/puck-manifest/literal.ts +459 -0
  299. package/src/puck-manifest/read-config.ts +577 -0
  300. package/src/puck-manifest/read-field.ts +19 -0
  301. package/src/puck-manifest/read-wrapper.ts +1056 -0
  302. package/src/puck-manifest/reading-budget.ts +127 -0
  303. package/src/puck-manifest/resolve-reference.ts +9 -0
  304. package/src/puck-manifest/source-reference.ts +484 -0
  305. package/src/puck-manifest/syntax.ts +104 -0
  306. package/src/puck-manifest/types.ts +139 -0
  307. package/src/safe-json-stringify.ts +17 -0
  308. package/src/sandbox-frame-handler.ts +31 -0
  309. package/src/site-styles/content-wrapper-endpoint.ts +327 -0
  310. package/src/site-styles/render-endpoint.ts +331 -0
  311. package/src/site-styles/styles-endpoint.ts +184 -0
  312. package/src/sitemap-options.ts +115 -0
  313. package/src/tiptap-html-static.ts +134 -0
  314. package/{dist/types-CS9neadI.d.mts → src/types.ts} +87 -124
  315. package/src/virtual-modules.d.ts +74 -0
  316. package/dist/collections-Bd7EME4b.mjs +0 -129
  317. package/dist/collections-Bd7EME4b.mjs.map +0 -1
  318. package/dist/collections.d.mts +0 -35
  319. package/dist/collections.d.mts.map +0 -1
  320. package/dist/collections.mjs +0 -2
  321. package/dist/components.d.mts +0 -41
  322. package/dist/components.d.mts.map +0 -1
  323. package/dist/components.mjs +0 -223
  324. package/dist/components.mjs.map +0 -1
  325. package/dist/hydration.d.mts +0 -4
  326. package/dist/hydration.mjs +0 -2
  327. package/dist/index.d.mts +0 -108
  328. package/dist/index.d.mts.map +0 -1
  329. package/dist/index.mjs +0 -67
  330. package/dist/index.mjs.map +0 -1
  331. package/dist/internal/cms-handler.d.mts +0 -25
  332. package/dist/internal/cms-handler.d.mts.map +0 -1
  333. package/dist/internal/cms-handler.mjs +0 -314
  334. package/dist/internal/cms-handler.mjs.map +0 -1
  335. package/dist/lib/hydration-script.d.mts +0 -30
  336. package/dist/lib/hydration-script.d.mts.map +0 -1
  337. package/dist/lib/hydration-script.mjs +0 -84
  338. package/dist/lib/hydration-script.mjs.map +0 -1
  339. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +0 -1
  340. package/dist/locales-helpers-qiwh7nxS.mjs +0 -54
  341. package/dist/locales-helpers-qiwh7nxS.mjs.map +0 -1
  342. package/dist/node/content.d.mts +0 -18
  343. package/dist/node/content.d.mts.map +0 -1
  344. package/dist/node/content.d.ts +0 -3
  345. package/dist/node/content.d.ts.map +0 -1
  346. package/dist/node/content.js +0 -2
  347. package/dist/node/content.mjs +0 -2
  348. package/dist/node/index.d.mts +0 -200
  349. package/dist/node/index.d.mts.map +0 -1
  350. package/dist/node/index.d.ts +0 -4
  351. package/dist/node/index.d.ts.map +0 -1
  352. package/dist/node/index.js +0 -3
  353. package/dist/node/index.mjs +0 -2513
  354. package/dist/node/index.mjs.map +0 -1
  355. package/dist/serialize-props-BHoNpzH6.mjs +0 -72
  356. package/dist/serialize-props-BHoNpzH6.mjs.map +0 -1
  357. package/dist/src/cms-handler.d.ts.map +0 -1
  358. package/dist/src/collections.d.ts +0 -32
  359. package/dist/src/collections.d.ts.map +0 -1
  360. package/dist/src/collections.js +0 -50
  361. package/dist/src/components/HydrationWrapper.d.ts.map +0 -1
  362. package/dist/src/components/RenderWithBlocks.d.ts.map +0 -1
  363. package/dist/src/components/RenderWithBlocks.js +0 -129
  364. package/dist/src/components/RenderWithHydration.d.ts.map +0 -1
  365. package/dist/src/components.d.ts +0 -4
  366. package/dist/src/components.d.ts.map +0 -1
  367. package/dist/src/components.js +0 -3
  368. package/dist/src/discovery/astro-frontmatter.d.ts.map +0 -1
  369. package/dist/src/discovery/extract-props-ts.d.ts.map +0 -1
  370. package/dist/src/discovery/merge-registry.d.ts.map +0 -1
  371. package/dist/src/discovery/registry-endpoint.d.ts +0 -42
  372. package/dist/src/discovery/registry-endpoint.d.ts.map +0 -1
  373. package/dist/src/discovery/registry-endpoint.js +0 -81
  374. package/dist/src/discovery/scan-components.d.ts.map +0 -1
  375. package/dist/src/discovery/scan-mdx.d.ts.map +0 -1
  376. package/dist/src/discovery/scan-overrides.d.ts.map +0 -1
  377. package/dist/src/hydration.d.ts.map +0 -1
  378. package/dist/src/index.d.ts +0 -11
  379. package/dist/src/index.d.ts.map +0 -1
  380. package/dist/src/index.js +0 -25
  381. package/dist/src/lib/hydration-scanner.d.ts.map +0 -1
  382. package/dist/src/lib/hydration-script.d.ts.map +0 -1
  383. package/dist/src/lib/hydration-utils.d.ts.map +0 -1
  384. package/dist/src/lib/page-api.d.ts +0 -77
  385. package/dist/src/lib/page-api.d.ts.map +0 -1
  386. package/dist/src/lib/page-api.js +0 -121
  387. package/dist/src/lib/route-utils.d.ts.map +0 -1
  388. package/dist/src/lib/routing-config.d.ts.map +0 -1
  389. package/dist/src/lib/serialize-props.d.ts.map +0 -1
  390. package/dist/src/lib/virtual-module-generators.d.ts.map +0 -1
  391. package/dist/src/lib/virtual-module-generators.js +0 -263
  392. package/dist/src/lib/withHydration.d.ts.map +0 -1
  393. package/dist/src/loader.d.ts +0 -14
  394. package/dist/src/loader.d.ts.map +0 -1
  395. package/dist/src/locales-helpers.d.ts.map +0 -1
  396. package/dist/src/mime-types.d.ts.map +0 -1
  397. package/dist/src/path-validation.d.ts.map +0 -1
  398. package/dist/src/plugin-spa.d.ts.map +0 -1
  399. package/dist/src/safe-json-stringify.d.ts.map +0 -1
  400. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +0 -1
  401. package/dist/src/site-styles/render-endpoint.d.ts.map +0 -1
  402. package/dist/src/site-styles/styles-endpoint.d.ts.map +0 -1
  403. package/dist/src/types.d.ts.map +0 -1
  404. package/dist/src/types.js +0 -1
  405. package/dist/types-CS9neadI.d.mts.map +0 -1
  406. package/dist/withHydration-C256ox_6.mjs +0 -49
  407. package/dist/withHydration-C256ox_6.mjs.map +0 -1
  408. package/dist/withHydration-DkKpkmzJ.d.mts.map +0 -1
  409. /package/dist/{src → ts/src}/discovery/astro-frontmatter.d.ts +0 -0
  410. /package/dist/{src → ts/src}/discovery/extract-props-ts.d.ts +0 -0
  411. /package/dist/{src → ts/src}/discovery/scan-mdx.d.ts +0 -0
  412. /package/dist/{src → ts/src}/discovery/scan-overrides.d.ts +0 -0
  413. /package/dist/{src → ts/src}/hydration.d.ts +0 -0
  414. /package/dist/{src → ts/src}/lib/hydration-scanner.d.ts +0 -0
  415. /package/dist/{src → ts/src}/lib/hydration-script.d.ts +0 -0
  416. /package/dist/{src → ts/src}/lib/hydration-utils.d.ts +0 -0
  417. /package/dist/{src → ts/src}/lib/serialize-props.d.ts +0 -0
  418. /package/dist/{src → ts/src}/lib/withHydration.d.ts +0 -0
  419. /package/dist/{src → ts/src}/locales-helpers.d.ts +0 -0
  420. /package/dist/{src → ts/src}/mime-types.d.ts +0 -0
  421. /package/dist/{src → ts/src}/path-validation.d.ts +0 -0
  422. /package/dist/{src → ts/src}/safe-json-stringify.d.ts +0 -0
@@ -1,2513 +0,0 @@
1
- import { n as localesFromStarlight, t as localesFromAstroI18n } from "../locales-helpers-qiwh7nxS.mjs";
2
- import { createRequire } from "node:module";
3
- import { readFile } from "node:fs/promises";
4
- import { basename, dirname, extname, join, relative, resolve } from "node:path";
5
- import fg from "fast-glob";
6
- import { existsSync } from "node:fs";
7
- import { fileURLToPath } from "node:url";
8
- import { readSitesConfig } from "@conloca/content-api/node";
9
- import viteReact from "@vitejs/plugin-react";
10
- import { searchForWorkspaceRoot } from "vite";
11
- import { ModuleKind, ModuleResolutionKind, Project, ScriptTarget } from "ts-morph";
12
- import { fromMarkdown } from "mdast-util-from-markdown";
13
- import { mdxFromMarkdown } from "mdast-util-mdx";
14
- import { mdxjs } from "micromark-extension-mdxjs";
15
- import { experimental_AstroContainer } from "astro/container";
16
- //#region src/lib/hydration-scanner.ts
17
- const HYDRATION_IMPORT_PATTERN = /import\s+\{[^}]*withHydration[^}]*\}\s+from\s+['"]@conloca\/astro-cms(?:\/hydration)?['"]/;
18
- const HYDRATION_PATTERN = /withHydration\s*\(\s*\w+\s*,\s*['"](\w+)['"]\s*\)/g;
19
- const VALID_STRATEGIES = /* @__PURE__ */ new Set([
20
- "load",
21
- "visible",
22
- "idle"
23
- ]);
24
- /**
25
- * Derives component scan paths from puckConfigPath.
26
- *
27
- * Convention: puckConfigPath directory + '/components/puck'
28
- * Example: './src/puck.config.tsx' -> './src/components/puck'
29
- *
30
- * If explicitPaths provided, they extend (not replace) the auto-discovered path.
31
- *
32
- * @param puckConfigPath - Path to the puck config (e.g., './src/puck.config.tsx')
33
- * @param explicitPaths - Optional additional paths to scan
34
- * @returns Array of paths to scan for hydratable components
35
- */
36
- function deriveComponentPaths(puckConfigPath, explicitPaths) {
37
- const defaultScanPath = join(dirname(puckConfigPath), "components", "puck");
38
- if (explicitPaths && explicitPaths.length > 0) return [defaultScanPath, ...explicitPaths];
39
- return [defaultScanPath];
40
- }
41
- /**
42
- * Derives a PascalCase component name from a file path.
43
- *
44
- * @param filePath - Absolute path to the component file
45
- * @returns Component name in PascalCase
46
- *
47
- * @example
48
- * deriveComponentName('/src/components/puck/TestimonialGrid.tsx')
49
- * // => 'TestimonialGrid'
50
- *
51
- * deriveComponentName('/src/components/puck/blog-post-grid.tsx')
52
- * // => 'BlogPostGrid'
53
- */
54
- function deriveComponentName(filePath) {
55
- const filename = basename(filePath, extname(filePath));
56
- if (filename.includes("-")) return filename.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
57
- return filename.charAt(0).toUpperCase() + filename.slice(1);
58
- }
59
- /**
60
- * Scans component directories for files using withHydration wrapper.
61
- *
62
- * This function performs static analysis to discover components marked
63
- * for hydration, without executing any component code.
64
- *
65
- * @param componentPaths - Relative paths to scan (e.g., ['src/components/puck'])
66
- * @param projectRoot - Absolute path to the project root
67
- * @returns Array of discovered hydratable components with their strategies
68
- *
69
- * @example
70
- * ```typescript
71
- * const discoveries = await scanForHydratableComponents(
72
- * ['src/components/puck'],
73
- * '/path/to/project'
74
- * )
75
- * // => [{ componentName: 'TestimonialGrid', filePath: '...', strategy: 'visible' }]
76
- * ```
77
- */
78
- async function scanForHydratableComponents(componentPaths, projectRoot) {
79
- const discoveries = [];
80
- const seenNames = /* @__PURE__ */ new Map();
81
- for (const scanPath of componentPaths) {
82
- const files = await fg("**/*.tsx", {
83
- cwd: resolve(projectRoot, scanPath),
84
- absolute: true,
85
- onlyFiles: true
86
- });
87
- for (const filePath of files) try {
88
- const content = await readFile(filePath, "utf-8");
89
- if (!HYDRATION_IMPORT_PATTERN.test(content)) continue;
90
- const matches = [...content.matchAll(HYDRATION_PATTERN)];
91
- if (matches.length === 0) continue;
92
- if (matches.length > 1) console.warn(`[Conloca Hydration] Multiple withHydration calls in ${filePath}. Consider splitting into separate component files. Using first call.`);
93
- const rawStrategy = matches[0][1];
94
- if (!VALID_STRATEGIES.has(rawStrategy)) {
95
- console.warn(`[Conloca Hydration] Invalid strategy '${rawStrategy}' in ${filePath}. Valid options: ${[...VALID_STRATEGIES].join(", ")}. Skipping component.`);
96
- continue;
97
- }
98
- const strategy = rawStrategy;
99
- const componentName = deriveComponentName(filePath);
100
- const existingPath = seenNames.get(componentName);
101
- if (existingPath) {
102
- console.warn(`[Conloca Hydration] Duplicate component name '${componentName}'. Found in: ${existingPath} and ${filePath}. Using first occurrence.`);
103
- continue;
104
- }
105
- seenNames.set(componentName, filePath);
106
- discoveries.push({
107
- componentName,
108
- filePath,
109
- strategy
110
- });
111
- } catch (err) {
112
- console.warn(`[Conloca Hydration] Error reading ${filePath}:`, err);
113
- }
114
- }
115
- return discoveries;
116
- }
117
- //#endregion
118
- //#region src/discovery/merge-registry.ts
119
- function mergeRegistry(mdxScans, localComponents, overrides) {
120
- const byKey = /* @__PURE__ */ new Map();
121
- for (const comp of localComponents) {
122
- const key = `${comp.source}::${comp.name}`;
123
- byKey.set(key, new DescriptorBuilder({
124
- name: comp.name,
125
- source: comp.source,
126
- defaultExport: false,
127
- kind: comp.kind,
128
- propsFromInterface: comp.props
129
- }));
130
- }
131
- for (const scan of mdxScans) for (const usage of scan.usages) {
132
- const imp = scan.imports[usage.name];
133
- if (!imp) continue;
134
- const canonicalName = imp.exportName === "default" ? usage.name : imp.exportName;
135
- const key = `${imp.source}::${canonicalName}`;
136
- let builder = byKey.get(key);
137
- if (!builder) {
138
- builder = new DescriptorBuilder({
139
- name: canonicalName,
140
- source: imp.source,
141
- defaultExport: imp.defaultExport,
142
- kind: usage.kind
143
- });
144
- byKey.set(key, builder);
145
- }
146
- builder.observeUsage(usage.attrs, scan.filepath, usage.name, imp, usage.kind);
147
- }
148
- const grouped = /* @__PURE__ */ new Map();
149
- for (const builder of byKey.values()) {
150
- const arr = grouped.get(builder.name) ?? [];
151
- arr.push(builder);
152
- grouped.set(builder.name, arr);
153
- }
154
- const winners = [];
155
- for (const candidates of grouped.values()) {
156
- candidates.sort((a, b) => {
157
- if (a.usageCount !== b.usageCount) return b.usageCount - a.usageCount;
158
- const aHasSchema = a.hasInterfaceSchema();
159
- if (aHasSchema !== b.hasInterfaceSchema()) return aHasSchema ? -1 : 1;
160
- return 0;
161
- });
162
- let descriptor = candidates[0].toDescriptor();
163
- const override = overrides?.get(descriptor.name);
164
- if (override) descriptor = applyOverride(descriptor, override);
165
- winners.push(descriptor);
166
- }
167
- return winners;
168
- }
169
- /**
170
- * Apply a host-provided override to an auto-discovered descriptor.
171
- *
172
- * Three kinds of merges happen:
173
- *
174
- * 1. **Shallow object merges** for `insert` and `defaults` — host
175
- * fields overwrite inferred fields one key at a time, so a host
176
- * can tweak only the label without losing the inferred category.
177
- *
178
- * 2. **Per-prop merges** for the `props` array — match by `name`,
179
- * override individual fields (`required`, `label`, `help`,
180
- * `options`) while keeping the rest of the prop's inferred
181
- * schema (type, defaultValue). Props the override doesn't mention
182
- * stay untouched.
183
- *
184
- * 3. **Scalar overrides** for `hasChildren` and `kind` — host value
185
- * replaces inferred value directly.
186
- *
187
- * The override is INTENTIONALLY a subset of `MdxJsxComponentDescriptor`
188
- * — fields the host can sensibly customize. Things like `name` and
189
- * `import` come from the actual file system / MDX scan and can't be
190
- * meaningfully overridden by a sidecar JSON.
191
- */
192
- function applyOverride(descriptor, override) {
193
- const next = { ...descriptor };
194
- if (override.insert) next.insert = {
195
- ...descriptor.insert ?? { label: descriptor.name },
196
- ...override.insert
197
- };
198
- if (override.defaults) next.defaults = {
199
- ...descriptor.defaults ?? {},
200
- ...override.defaults,
201
- ...override.defaults.attributes ? { attributes: {
202
- ...descriptor.defaults?.attributes ?? {},
203
- ...override.defaults.attributes
204
- } } : {}
205
- };
206
- if (override.hasChildren !== void 0) next.hasChildren = override.hasChildren;
207
- if (override.kind) next.kind = override.kind;
208
- if (override.props && descriptor.props) {
209
- const overridesByName = override.props;
210
- next.props = descriptor.props.map((p) => {
211
- const o = overridesByName[p.name];
212
- if (!o) return p;
213
- const merged = { ...p };
214
- if (o.required !== void 0) merged.required = o.required;
215
- if (o.label !== void 0) merged.label = o.label;
216
- if (o.help !== void 0) merged.help = o.help;
217
- if (o.options && merged.type === "string") merged.options = o.options;
218
- return merged;
219
- });
220
- }
221
- return next;
222
- }
223
- /** Internal accumulator. Combines interface-derived schema with
224
- * usage-derived observations as scans arrive. */
225
- var DescriptorBuilder = class {
226
- name;
227
- source;
228
- defaultExport;
229
- /**
230
- * Component flow/text kind. Mutable across `observeUsage` calls
231
- * because mdast classifies the SAME component differently based on
232
- * how each instance is authored in source: `<Steps>...</Steps>` on
233
- * one line parses as `mdxJsxTextElement` (inline), but the same
234
- * component with blank-line-separated children parses as
235
- * `mdxJsxFlowElement` (block). The component's intrinsic nature is
236
- * "block" — so any single flow observation must promote the kind
237
- * from text to flow. Without this, one stray inline usage in a
238
- * fixture poisons the registry, MDXEditor mounts the JSX as inline,
239
- * and saves serialize block components as single-line MDX — which
240
- * Starlight's strict-slot validators (Steps wants `<ol>`, FileTree
241
- * wants `<ul>`) then reject at render time.
242
- *
243
- * Demotion in the other direction never happens: a component seen
244
- * as flow even once is intrinsically flow-capable, regardless of
245
- * other inline observations.
246
- */
247
- kind;
248
- propsFromInterface;
249
- /** propName → set of distinct string values observed in MDX. */
250
- observedValues = /* @__PURE__ */ new Map();
251
- /** filepath → local alias used in that file (when ≠ canonical). */
252
- aliases = {};
253
- /** Names of props we've seen in usage but that aren't in the
254
- * interface (or for npm components where there's no interface). */
255
- observedPropNames = /* @__PURE__ */ new Set();
256
- /** How many `<Foo>` usages of this component were seen across all
257
- * MDX files. Used to pick a winner on name collisions. */
258
- usageCount = 0;
259
- constructor(init) {
260
- this.name = init.name;
261
- this.source = init.source;
262
- this.defaultExport = init.defaultExport;
263
- this.kind = init.kind;
264
- this.propsFromInterface = init.propsFromInterface ?? [];
265
- }
266
- observeUsage(attrs, filepath, localName, imp, observedKind) {
267
- this.usageCount++;
268
- if (observedKind === "flow") this.kind = "flow";
269
- if (imp.aliasedFrom && localName !== this.name) this.aliases[filepath] = localName;
270
- for (const [propName, value] of Object.entries(attrs)) {
271
- this.observedPropNames.add(propName);
272
- if (!this.observedValues.has(propName)) this.observedValues.set(propName, /* @__PURE__ */ new Set());
273
- this.observedValues.get(propName).add(value);
274
- }
275
- }
276
- hasInterfaceSchema() {
277
- return this.propsFromInterface.length > 0;
278
- }
279
- toDescriptor() {
280
- const interfacePropNames = new Set(this.propsFromInterface.map((p) => p.name));
281
- const props = [];
282
- for (const ip of this.propsFromInterface) props.push(toMdxComponentProp(ip, this.observedValues.get(ip.name)));
283
- for (const name of this.observedPropNames) {
284
- if (interfacePropNames.has(name)) continue;
285
- props.push({
286
- name,
287
- type: "string"
288
- });
289
- }
290
- const requiredAttributes = {};
291
- for (const p of props) {
292
- if (!p.required) continue;
293
- requiredAttributes[p.name] = placeholderForProp(p, this.observedValues.get(p.name));
294
- }
295
- const descriptor = {
296
- name: this.name,
297
- kind: this.kind,
298
- hasChildren: true,
299
- props,
300
- import: {
301
- from: this.source,
302
- ...this.defaultExport ? { default: true } : {}
303
- },
304
- insert: {
305
- label: this.name,
306
- category: "Components"
307
- },
308
- ...Object.keys(requiredAttributes).length > 0 ? { defaults: { attributes: requiredAttributes } } : {}
309
- };
310
- if (Object.keys(this.aliases).length > 0) descriptor.aliases = this.aliases;
311
- return descriptor;
312
- }
313
- };
314
- /**
315
- * Pick a sensible starter value for a required prop so the insert flow
316
- * has something to put on the attribute. See the call site in
317
- * `DescriptorBuilder.toDescriptor` for the priority rationale; this
318
- * function just executes it.
319
- *
320
- * Number and boolean placeholders are intentionally trivial — `0` and
321
- * `true` — because numeric/boolean props are rare in MDX components and
322
- * any concrete value beats `undefined`. The interesting work is on the
323
- * string path, where union options and observed usage give us real
324
- * authored values to reuse.
325
- */
326
- function placeholderForProp(prop, observed) {
327
- if (prop.type === "number") return 0;
328
- if (prop.type === "boolean") return true;
329
- if (prop.options && prop.options.length > 0) return prop.options[0].value;
330
- if (observed && observed.size > 0) {
331
- const first = observed.values().next();
332
- if (!first.done) return first.value;
333
- }
334
- return prop.name.charAt(0).toUpperCase() + prop.name.slice(1);
335
- }
336
- function toMdxComponentProp(parsed, observed) {
337
- let optionStrings = parsed.options;
338
- if (optionStrings && observed && observed.size > 0) {
339
- const combined = new Set(optionStrings);
340
- for (const v of observed) combined.add(v);
341
- if (combined.size <= 5) optionStrings = Array.from(combined);
342
- }
343
- if (parsed.type === "number") return {
344
- name: parsed.name,
345
- type: "number",
346
- required: parsed.required
347
- };
348
- if (parsed.type === "boolean") return {
349
- name: parsed.name,
350
- type: "boolean",
351
- required: parsed.required
352
- };
353
- return {
354
- name: parsed.name,
355
- type: "string",
356
- required: parsed.required,
357
- ...optionStrings && optionStrings.length > 0 ? { options: optionStrings.map((v) => ({
358
- value: v,
359
- label: v
360
- })) } : {}
361
- };
362
- }
363
- //#endregion
364
- //#region src/discovery/astro-frontmatter.ts
365
- /**
366
- * Extract the frontmatter (the `---`-fenced TypeScript block) from
367
- * an `.astro` source file. Returns the inner text, or `null` if no
368
- * frontmatter is present (a valid Astro file shape — props-less
369
- * components without `<script>` of any kind).
370
- *
371
- * Astro's official compiler (`@astrojs/compiler`) exposes a full
372
- * parser, but for the props-extraction use case all we need is the
373
- * text between the opening and closing fences. A regex is sufficient
374
- * and keeps this synchronous (no WASM init cost, no async).
375
- *
376
- * The fence rule is simple: the file must start with `---\n` and
377
- * close with `\n---` followed by either a newline or end-of-file.
378
- * Whitespace before the opening fence is rejected — Astro itself
379
- * requires the fence at column 0.
380
- */
381
- function extractAstroFrontmatter(content) {
382
- const match = /^---\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/.exec(content);
383
- return match ? match[1] : null;
384
- }
385
- //#endregion
386
- //#region src/discovery/extract-props-ts.ts
387
- /**
388
- * TypeScript-aware extraction of a component's `Props` interface,
389
- * replacing the regex-based path in `scan-components.ts`. Uses
390
- * `ts-morph` (a thin wrapper over the TypeScript compiler API) so
391
- * derived types — `(typeof asideVariants)[number]`, mapped types,
392
- * imported aliases, conditional types — resolve to their concrete
393
- * literal-union values. The regex scanner couldn't follow any
394
- * indirection and silently dropped options for those props (Aside's
395
- * `type` being the canonical example).
396
- *
397
- * The output shape is identical to the regex path (`ParsedProp[]`)
398
- * so the rest of the discovery pipeline doesn't change.
399
- *
400
- * Astro files are handled by extracting the frontmatter block and
401
- * feeding it to the Project as a virtual `.ts` source — see
402
- * `extractAstroFrontmatter` in `astro-frontmatter.ts`.
403
- */
404
- /**
405
- * One Project per scan run, reused across `extractPropsViaTs` calls
406
- * within the same scan. Building the Project loads `lib.dom.d.ts`
407
- * etc. which dominates cold-start cost (~500ms-2s); sharing across
408
- * files in a scan amortises that. A fresh Project is built per scan
409
- * run so file changes are picked up — ts-morph's `addSourceFile`
410
- * caches by path and wouldn't see external edits otherwise.
411
- */
412
- function createScanProject(tsConfigFilePath) {
413
- if (tsConfigFilePath) try {
414
- return new Project({
415
- tsConfigFilePath,
416
- skipAddingFilesFromTsConfig: true
417
- });
418
- } catch {}
419
- return new Project({
420
- compilerOptions: {
421
- target: ScriptTarget.ES2022,
422
- module: ModuleKind.ESNext,
423
- moduleResolution: ModuleResolutionKind.Bundler,
424
- allowJs: true,
425
- esModuleInterop: true,
426
- skipLibCheck: true,
427
- strict: false
428
- },
429
- skipAddingFilesFromTsConfig: true
430
- });
431
- }
432
- /**
433
- * Extract the Props interface from a source string and return the
434
- * parsed prop list. `filepath` is used as the virtual file's path
435
- * inside the Project so error messages and source-map debugging
436
- * point back at the right file; the actual content comes from
437
- * `sourceText`. `.astro` callers pass the extracted frontmatter as
438
- * `sourceText` and `${filepath}.virtual.ts` as `filepath`.
439
- *
440
- * Returns `[]` when no Props interface is found — same contract as
441
- * the regex path so callers don't need a special-case branch.
442
- */
443
- function extractPropsViaTs(project, filepath, sourceText, componentName) {
444
- let sf;
445
- try {
446
- sf = project.createSourceFile(filepath, sourceText, { overwrite: true });
447
- } catch (err) {
448
- console.warn(`[conloca:ts-morph] parse failed for ${filepath}:`, err instanceof Error ? err.message : err);
449
- return [];
450
- }
451
- const candidates = [];
452
- if (componentName) candidates.push(`${componentName}Props`);
453
- candidates.push("Props");
454
- let propertySignatures = [];
455
- for (const name of candidates) {
456
- const iface = sf.getInterface(name);
457
- if (iface) {
458
- propertySignatures = collectLocalProperties(iface);
459
- break;
460
- }
461
- const alias = sf.getTypeAlias(name);
462
- if (alias) {
463
- propertySignatures = collectAliasProperties(alias);
464
- break;
465
- }
466
- }
467
- if (propertySignatures.length === 0) {
468
- project.removeSourceFile(sf);
469
- return [];
470
- }
471
- const props = [];
472
- for (const prop of propertySignatures) {
473
- const name = prop.getName();
474
- const type = prop.getType();
475
- const required = !prop.hasQuestionToken();
476
- props.push(parseType(name, type, required));
477
- }
478
- project.removeSourceFile(sf);
479
- return props;
480
- }
481
- /**
482
- * Get ONLY the locally-declared properties on an interface, NOT
483
- * properties inherited from `extends` clauses. This is the key choice
484
- * that keeps the side panel sane for components like Starlight's
485
- * `LinkCard` which declares `extends Omit<HTMLAttributes<'a'>, 'title'>`:
486
- * the type-level `Type.getProperties()` would include every HTML
487
- * attribute (~200 entries — `accesskey`, `aria-*`, `on*`, etc), making
488
- * the panel useless. The declaration-level `iface.getProperties()`
489
- * returns just the props the author explicitly wrote inside the
490
- * braces, which is the editor's intent.
491
- *
492
- * Trade-off: a property the author "overrides" via re-declaration
493
- * (eg LinkCard's local `title: string` overriding the inherited
494
- * `title?: string`) appears — good. A property the author NEVER
495
- * declared locally but the inherited interface defines (eg `href`
496
- * inherited from HTMLAttributes) does NOT appear — also good, the
497
- * panel stays focused on what the author wanted to expose. Hosts
498
- * who want a specific inherited prop surfaced can re-declare it
499
- * locally or use the sidecar `cmsConfig.props` override.
500
- */
501
- function collectLocalProperties(iface) {
502
- return iface.getProperties();
503
- }
504
- /**
505
- * Type-alias variant. For `type Props = { ... }`, the declaration
506
- * node is a TypeLiteralNode and we read its own member list. For
507
- * intersections (`type Props = A & { ... }`) or imported aliases,
508
- * we get an empty list rather than walking into the constituent
509
- * types — same author-intent rationale as the interface case.
510
- */
511
- function collectAliasProperties(alias) {
512
- const members = alias.getTypeNode()?.getMembers?.();
513
- if (!members) return [];
514
- return members.filter((m) => m.getKindName() === "PropertySignature");
515
- }
516
- /**
517
- * Map a resolved `Type` to a `ParsedProp`. Mirrors the kind of
518
- * branching the old regex did, but on real type information.
519
- */
520
- function parseType(name, type, required) {
521
- if (type.isString()) return {
522
- name,
523
- type: "string",
524
- required
525
- };
526
- if (type.isNumber()) return {
527
- name,
528
- type: "number",
529
- required
530
- };
531
- if (type.isBoolean()) return {
532
- name,
533
- type: "boolean",
534
- required
535
- };
536
- if (type.isUnion()) {
537
- const nonUndefined = type.getUnionTypes().filter((m) => !m.isUndefined());
538
- if (nonUndefined.length > 0 && nonUndefined.every((m) => m.isBooleanLiteral() || m.isBoolean())) return {
539
- name,
540
- type: "boolean",
541
- required
542
- };
543
- const stringLiterals = nonUndefined.filter((m) => m.isStringLiteral()).map((m) => m.getLiteralValue()).filter((v) => typeof v === "string");
544
- if (stringLiterals.length > 0) return {
545
- name,
546
- type: "string",
547
- required,
548
- options: stringLiterals
549
- };
550
- if (nonUndefined.length === 1) {
551
- const only = nonUndefined[0];
552
- if (only.isString()) return {
553
- name,
554
- type: "string",
555
- required
556
- };
557
- if (only.isNumber()) return {
558
- name,
559
- type: "number",
560
- required
561
- };
562
- if (only.isBoolean()) return {
563
- name,
564
- type: "boolean",
565
- required
566
- };
567
- if (only.isStringLiteral()) {
568
- const v = only.getLiteralValue();
569
- return {
570
- name,
571
- type: "string",
572
- required,
573
- options: typeof v === "string" ? [v] : void 0
574
- };
575
- }
576
- }
577
- }
578
- if (type.isStringLiteral()) {
579
- const v = type.getLiteralValue();
580
- return {
581
- name,
582
- type: "string",
583
- required,
584
- options: typeof v === "string" ? [v] : void 0
585
- };
586
- }
587
- if (type.isBooleanLiteral()) return {
588
- name,
589
- type: "boolean",
590
- required
591
- };
592
- return {
593
- name,
594
- type: "expression",
595
- required
596
- };
597
- }
598
- //#endregion
599
- //#region src/discovery/scan-components.ts
600
- /**
601
- * Scan every `.astro` / `.tsx` file under each configured folder.
602
- * Folder globs are resolved relative to `projectRoot`.
603
- */
604
- async function scanLocalComponents(folders, projectRoot) {
605
- if (folders.length === 0) return [];
606
- const sourcePatterns = folders.map((f) => `${f.replace(/\/+$/, "")}/**/*.{astro,tsx}`);
607
- const dtsPatterns = folders.map((f) => `${f.replace(/\/+$/, "")}/**/*.d.ts`);
608
- const sourceFiles = await fg(sourcePatterns, {
609
- cwd: projectRoot,
610
- absolute: true,
611
- dot: false
612
- });
613
- const dtsFiles = await fg(dtsPatterns, {
614
- cwd: projectRoot,
615
- absolute: true,
616
- dot: false
617
- });
618
- const seen = /* @__PURE__ */ new Set();
619
- const allFiles = [];
620
- for (const file of sourceFiles) {
621
- const name = componentNameFromPath(file);
622
- if (seen.has(name)) continue;
623
- seen.add(name);
624
- allFiles.push(file);
625
- }
626
- for (const file of dtsFiles) {
627
- const name = componentNameFromPath(file);
628
- if (seen.has(name)) continue;
629
- seen.add(name);
630
- allFiles.push(file);
631
- }
632
- const project = createScanProject(findTsConfig(projectRoot));
633
- const results = [];
634
- for (const file of allFiles) try {
635
- const r = await scanFile$1(file, projectRoot, project);
636
- if (r) results.push(r);
637
- } catch (err) {
638
- console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
639
- }
640
- return results;
641
- }
642
- async function scanFile$1(filepath, projectRoot, project) {
643
- const content = await readFile(filepath, "utf8");
644
- const name = componentNameFromPath(filepath);
645
- if (!/^[A-Z]/.test(name)) return null;
646
- const props = extractPropsForFile(project, filepath, content, name);
647
- return {
648
- filepath,
649
- name,
650
- source: filepath,
651
- importSpecifier: `/${relative(projectRoot, filepath).replace(/\\/g, "/")}`,
652
- kind: "flow",
653
- props
654
- };
655
- }
656
- /**
657
- * Bridge between the file-level scanner and the ts-morph extractor.
658
- * Handles the three file types we accept:
659
- * - `.astro` — extract the `---`-fenced frontmatter, feed it as
660
- * a virtual `.ts` source.
661
- * - `.tsx` / `.d.ts` — feed the whole file content directly.
662
- *
663
- * The virtual source path is the real filepath suffixed with
664
- * `.virtual.ts` for `.astro` files, so ts-morph's diagnostics still
665
- * point back at the right author file. For `.tsx` / `.d.ts` we use
666
- * the real path verbatim — ts-morph parses TS extensions natively.
667
- */
668
- function extractPropsForFile(project, filepath, content, componentName) {
669
- if (filepath.endsWith(".astro")) {
670
- const frontmatter = extractAstroFrontmatter(content);
671
- if (!frontmatter) return [];
672
- return extractPropsViaTs(project, `${filepath}.virtual.ts`, frontmatter, componentName);
673
- }
674
- return extractPropsViaTs(project, filepath, content, componentName);
675
- }
676
- /**
677
- * Locate the host's `tsconfig.json` so the ts-morph Project can
678
- * resolve cross-file `typeof` refs, path aliases, and node_modules
679
- * declarations the same way the author's IDE does. Walks up from
680
- * `projectRoot` looking for the closest tsconfig; returns `undefined`
681
- * if none found (the Project then uses permissive defaults).
682
- */
683
- function findTsConfig(projectRoot) {
684
- const candidate = resolve(projectRoot, "tsconfig.json");
685
- return existsSync(candidate) ? candidate : void 0;
686
- }
687
- /**
688
- * Derive the canonical component name from a file path.
689
- *
690
- * Two extension shapes:
691
- * - Single (`.astro`, `.tsx`) → strip with `extname`/`basename`.
692
- * - Compound (`.d.ts`) → strip `.d.ts` explicitly, since `extname`
693
- * would return only `.ts` and leave a trailing `.d` (`Card.d`).
694
- *
695
- * Keeps the rule simple and consistent: file basename === component
696
- * name. Multi-component files (a `.d.ts` exporting many React
697
- * components from one barrel) are NOT supported through this path —
698
- * the sidecar `cmsConfig` mechanism (future task) covers those.
699
- */
700
- function componentNameFromPath(filepath) {
701
- const base = basename(filepath);
702
- if (base.endsWith(".d.ts")) return base.slice(0, -5);
703
- return base.slice(0, -extname(base).length);
704
- }
705
- /**
706
- * Scan every npm-style import source referenced in the MDX usage scan
707
- * and treat any `.astro` / `.tsx` file inside the resolved package as a
708
- * candidate component. Resolves each unique specifier via Node's
709
- * `require.resolve` (run from `projectRoot` so packages are looked up
710
- * in the consumer's `node_modules`, not ours), walks up to the package
711
- * root, then globs the package for component-shaped files.
712
- *
713
- * The returned `source` on each result is the ORIGINAL specifier from
714
- * the MDX import (e.g. `@astrojs/starlight/components`) — not the
715
- * resolved file path. That's what makes the merge work: `scan-mdx`
716
- * records imports by their literal source string, so for the merge
717
- * registry to dedupe local-folder scan ⨯ MDX-usage scan we need both
718
- * sides to key on the same specifier. Vite's `ssrLoadModule` handles
719
- * the specifier itself at render time, so we don't need an absolute
720
- * file path on the descriptor.
721
- *
722
- * Caveats:
723
- * - Specifiers that look like local paths (`./foo`, `/abs/path`) are
724
- * intentionally skipped here — those are local components, already
725
- * covered by `scanLocalComponents`.
726
- * - One specifier per package: if a package is imported via two
727
- * different specifiers (`@pkg/components` and `@pkg`), we'll scan
728
- * it twice and emit two descriptor sets keyed on each specifier.
729
- * The merge layer's collision resolution picks the one with more
730
- * real usage, so this is self-correcting in practice.
731
- * - We cap glob depth at 4 to avoid walking into deeply-nested
732
- * library internals (most component packages put their exports
733
- * near the root). Components nested deeper won't surface; hosts
734
- * can either re-export them at a shallower path or add a sidecar
735
- * `cmsConfig` (when sidecar support lands).
736
- */
737
- async function scanExternalComponents(mdxScans, projectRoot) {
738
- const specifiers = collectExternalSpecifiers(mdxScans);
739
- if (specifiers.size === 0) return [];
740
- const project = createScanProject(findTsConfig(projectRoot));
741
- const results = [];
742
- const requireFromProject = createRequire(`${projectRoot.replace(/\/$/, "")}/package.json`);
743
- for (const specifier of specifiers) try {
744
- const resolved = requireFromProject.resolve(specifier);
745
- const packageRoot = findPackageRoot(resolved);
746
- if (!packageRoot) continue;
747
- const barrelFiles = await collectBarrelExports(resolved, packageRoot);
748
- let scanFiles;
749
- if (barrelFiles.length > 0) scanFiles = barrelFiles;
750
- else {
751
- const sourceFiles = await fg("**/*.{astro,tsx}", {
752
- cwd: packageRoot,
753
- absolute: true,
754
- dot: false,
755
- deep: 4
756
- });
757
- const dtsFiles = await fg("**/*.d.ts", {
758
- cwd: packageRoot,
759
- absolute: true,
760
- dot: false,
761
- deep: 4
762
- });
763
- const seen = /* @__PURE__ */ new Set();
764
- scanFiles = [];
765
- for (const file of [...sourceFiles, ...dtsFiles]) {
766
- const name = componentNameFromPath(file);
767
- if (seen.has(name)) continue;
768
- seen.add(name);
769
- scanFiles.push(file);
770
- }
771
- }
772
- for (const file of scanFiles) try {
773
- const r = await scanExternalFile(file, specifier, project);
774
- if (r) results.push(r);
775
- } catch (err) {
776
- console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
777
- }
778
- } catch (err) {
779
- console.warn(`[conloca:discovery] could not resolve '${specifier}' from ${projectRoot}:`, err instanceof Error ? err.message : err);
780
- }
781
- return results;
782
- }
783
- /**
784
- * Same parsing as `scanFile`, but with `source` set to the original
785
- * npm specifier instead of the absolute file path. See the function
786
- * doc on `scanExternalComponents` for why.
787
- */
788
- async function scanExternalFile(filepath, specifier, project) {
789
- const content = await readFile(filepath, "utf8");
790
- const name = componentNameFromPath(filepath);
791
- if (!/^[A-Z]/.test(name)) return null;
792
- return {
793
- filepath,
794
- name,
795
- source: specifier,
796
- importSpecifier: specifier,
797
- kind: "flow",
798
- props: extractPropsForFile(project, filepath, content, name)
799
- };
800
- }
801
- /**
802
- * Pick out unique npm-style specifiers from every import seen in the
803
- * MDX scan. Local paths (`./foo`, `/abs`) are dropped — `scanLocalComponents`
804
- * covers those via its folder glob.
805
- */
806
- function collectExternalSpecifiers(mdxScans) {
807
- const out = /* @__PURE__ */ new Set();
808
- for (const scan of mdxScans) for (const imp of Object.values(scan.imports)) {
809
- const src = imp.source;
810
- if (!src) continue;
811
- if (src.startsWith(".") || src.startsWith("/")) continue;
812
- out.add(src);
813
- }
814
- return out;
815
- }
816
- /**
817
- * If `resolvedFile` is a barrel (re-export aggregator), return the
818
- * absolute paths of every re-exported component file. Otherwise
819
- * return an empty array.
820
- *
821
- * Patterns recognized:
822
- * - `export { default as Foo } from './path/to/Foo.astro'`
823
- * - `export { Foo } from './path/to/Foo'`
824
- * - `export { Foo, Bar } from './path/to/m'`
825
- * - `export * from './path/to/m'` (treated as opaque — we
826
- * can't enumerate the
827
- * names without a real
828
- * parser, so we skip and
829
- * fall back to glob-all)
830
- *
831
- * The barrel must resolve to a real file we can re-resolve to one of
832
- * the supported extensions (`.astro`, `.tsx`, `.d.ts`). Missing or
833
- * unsupported targets are dropped quietly. Comments are stripped
834
- * first to avoid matching commented-out exports.
835
- *
836
- * Why this matters: Starlight's `@astrojs/starlight/components`
837
- * barrel lists exactly the 12 MDX-friendly components. Globbing the
838
- * whole package would also pull in ~30 internal layout components
839
- * (Banner, Hero, Pagination, ...) — they'd litter the slash menu
840
- * even though they're not meant for author use.
841
- */
842
- async function collectBarrelExports(resolvedFile, packageRoot) {
843
- if (!/\.(?:m?[jt]s)$/.test(resolvedFile)) return [];
844
- let content;
845
- try {
846
- content = await readFile(resolvedFile, "utf8");
847
- } catch {
848
- return [];
849
- }
850
- const cleaned = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
851
- const pathRe = /export\s*(?:\{[^}]*\}|\*)\s*from\s*['"]([^'"]+)['"]/g;
852
- const relPaths = /* @__PURE__ */ new Set();
853
- for (const m of cleaned.matchAll(pathRe)) {
854
- const rel = m[1];
855
- if (!rel) continue;
856
- relPaths.add(rel);
857
- }
858
- if (relPaths.size === 0) return [];
859
- const requireFromBarrel = createRequire(`${dirname(resolvedFile)}/_.js`);
860
- const resolved = [];
861
- for (const rel of relPaths) try {
862
- const target = requireFromBarrel.resolve(rel);
863
- if (!/\.(?:astro|tsx|d\.ts)$/.test(target)) continue;
864
- if (!target.startsWith(packageRoot)) continue;
865
- resolved.push(target);
866
- } catch {}
867
- return resolved;
868
- }
869
- /**
870
- * Walk up from a resolved file path until we find the directory that
871
- * contains the closest `package.json`. That's the package root we'll
872
- * glob for component files. Returns `null` if no package.json is found
873
- * within a reasonable depth (defensive — shouldn't happen for a real
874
- * resolution).
875
- */
876
- function findPackageRoot(resolvedPath) {
877
- let dir = dirname(resolvedPath);
878
- for (let i = 0; i < 10; i++) {
879
- if (existsSync(`${dir}/package.json`)) return dir;
880
- const parent = dirname(dir);
881
- if (parent === dir) return null;
882
- dir = parent;
883
- }
884
- return null;
885
- }
886
- //#endregion
887
- //#region src/discovery/scan-mdx.ts
888
- /**
889
- * Scan every `.mdx` file under `rootDir` (recursive). Returns one
890
- * result per file. Files that fail to parse are skipped with a
891
- * warning rather than throwing — the discovery flow shouldn't take
892
- * down the dev server on a single broken file.
893
- */
894
- async function scanMdxFiles(rootDir) {
895
- const files = await fg("**/*.mdx", {
896
- cwd: rootDir,
897
- absolute: true,
898
- dot: false
899
- });
900
- const results = [];
901
- for (const file of files) try {
902
- results.push(await scanFile(file));
903
- } catch (err) {
904
- console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
905
- }
906
- return results;
907
- }
908
- async function scanFile(filepath) {
909
- const tree = fromMarkdown(await readFile(filepath, "utf8"), {
910
- extensions: [mdxjs()],
911
- mdastExtensions: [mdxFromMarkdown()]
912
- });
913
- const imports = {};
914
- const usages = [];
915
- walk(tree, (node) => {
916
- if (isEsmNode(node)) collectImports(node, imports);
917
- else if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
918
- const name = typeof node.name === "string" ? node.name : "";
919
- if (!name) return;
920
- const attrs = {};
921
- const rawAttrs = node.attributes ?? [];
922
- for (const a of rawAttrs) {
923
- if (a.type !== "mdxJsxAttribute" || typeof a.name !== "string") continue;
924
- if (typeof a.value === "string") attrs[a.name] = a.value;
925
- }
926
- usages.push({
927
- name,
928
- attrs,
929
- kind: node.type === "mdxJsxFlowElement" ? "flow" : "text"
930
- });
931
- }
932
- });
933
- return {
934
- filepath,
935
- imports,
936
- usages
937
- };
938
- }
939
- function isEsmNode(node) {
940
- return node.type === "mdxjsEsm";
941
- }
942
- function collectImports(esmNode, out) {
943
- const estree = esmNode.data?.estree;
944
- if (!estree?.body) return;
945
- for (const stmt of estree.body) {
946
- if (stmt.type !== "ImportDeclaration") continue;
947
- const source = stmt.source?.value;
948
- if (typeof source !== "string") continue;
949
- for (const spec of stmt.specifiers ?? []) {
950
- const local = spec.local?.name;
951
- if (typeof local !== "string") continue;
952
- if (spec.type === "ImportDefaultSpecifier") out[local] = {
953
- source,
954
- defaultExport: true,
955
- exportName: "default"
956
- };
957
- else if (spec.type === "ImportSpecifier") {
958
- const exportName = spec.imported?.type === "Identifier" ? spec.imported.name : typeof spec.imported?.value === "string" ? spec.imported.value : local;
959
- out[local] = {
960
- source,
961
- defaultExport: false,
962
- exportName: exportName ?? local,
963
- ...exportName && exportName !== local ? { aliasedFrom: exportName } : {}
964
- };
965
- }
966
- }
967
- }
968
- }
969
- /** Depth-first walk; visits every node including the root. */
970
- function walk(node, fn) {
971
- fn(node);
972
- if (Array.isArray(node.children)) {
973
- for (const child of node.children) if (child && typeof child === "object") walk(child, fn);
974
- }
975
- }
976
- //#endregion
977
- //#region src/discovery/scan-overrides.ts
978
- /**
979
- * Read every `*.cms.json` file under `folder` (recursive) and return
980
- * the parsed overrides keyed by basename (`Card.cms.json` → `Card`).
981
- *
982
- * Failures are skipped with a warning — a broken JSON file shouldn't
983
- * take down the rest of the registry build. The folder being empty
984
- * (or not existing) returns an empty map silently; that's the
985
- * common zero-config case where the host hasn't added any
986
- * overrides yet.
987
- */
988
- async function loadCmsOverrides(folder, projectRoot) {
989
- const out = /* @__PURE__ */ new Map();
990
- if (!folder) return out;
991
- const files = await fg(`${folder.replace(/\/+$/, "")}/**/*.cms.json`, {
992
- cwd: projectRoot,
993
- absolute: true,
994
- dot: false
995
- });
996
- for (const file of files) try {
997
- const content = await readFile(file, "utf8");
998
- const parsed = JSON.parse(content);
999
- const name = basename(file).slice(0, -9);
1000
- out.set(name, parsed);
1001
- } catch (err) {
1002
- console.warn(`[conloca:discovery] failed to load override ${file}:`, err instanceof Error ? err.message : err);
1003
- }
1004
- return out;
1005
- }
1006
- //#endregion
1007
- //#region src/discovery/registry-endpoint.ts
1008
- function createRegistryEndpoint(options) {
1009
- const projectRoot = options.projectRoot ?? process.cwd();
1010
- const contentRoot = resolve(projectRoot, options.contentRoot);
1011
- let cached = null;
1012
- const compute = () => {
1013
- if (cached) return cached;
1014
- cached = (async () => {
1015
- const mdxScans = await scanMdxFiles(contentRoot);
1016
- const overridesFolder = options.overridesFolder ?? "src/cms-overrides";
1017
- const [localComponents, externalComponents, overrides] = await Promise.all([
1018
- scanLocalComponents(options.componentFolders, projectRoot),
1019
- scanExternalComponents(mdxScans, projectRoot),
1020
- loadCmsOverrides(overridesFolder, projectRoot)
1021
- ]);
1022
- return mergeRegistry(mdxScans, [...externalComponents, ...localComponents], overrides);
1023
- })();
1024
- return cached;
1025
- };
1026
- const handler = async (req, res, _next) => {
1027
- try {
1028
- const components = await compute();
1029
- res.statusCode = 200;
1030
- res.setHeader("content-type", "application/json; charset=utf-8");
1031
- res.setHeader("cache-control", "no-store");
1032
- res.end(JSON.stringify({ components }));
1033
- } catch (err) {
1034
- const message = err instanceof Error ? err.message : String(err);
1035
- console.warn("[conloca:discovery] registry endpoint failed:", message);
1036
- res.statusCode = 500;
1037
- res.setHeader("content-type", "application/json; charset=utf-8");
1038
- res.end(JSON.stringify({ error: message }));
1039
- }
1040
- };
1041
- return {
1042
- handler,
1043
- invalidate: () => {
1044
- cached = null;
1045
- },
1046
- /**
1047
- * Set of import sources the render endpoint is allowed to load.
1048
- *
1049
- * Reuses the same memoized scan as `handler`, so the allowlist stays
1050
- * in sync with the registry the SPA sees — invalidation in one place
1051
- * invalidates both. Failing closed (returning an empty set) on scan
1052
- * error is intentional: better to refuse all renders than to fall
1053
- * back to "trust the request body".
1054
- */
1055
- getAllowedSources: async () => {
1056
- try {
1057
- const components = await compute();
1058
- const sources = /* @__PURE__ */ new Set();
1059
- for (const c of components) if (c.import?.from) sources.add(c.import.from);
1060
- return sources;
1061
- } catch {
1062
- return /* @__PURE__ */ new Set();
1063
- }
1064
- }
1065
- };
1066
- }
1067
- //#endregion
1068
- //#region src/lib/routing-config.ts
1069
- /**
1070
- * Normalize routing config input to full RoutingConfig.
1071
- *
1072
- * Handles the `routing: true` shorthand, boolean values, and top-level layout option.
1073
- *
1074
- * @param input - The routing config input (boolean, object, or undefined)
1075
- * @param topLevelLayout - Optional top-level layout path (enables routing when provided)
1076
- * @returns Normalized RoutingConfig or undefined if not enabled
1077
- */
1078
- function normalizeRoutingConfig(input, topLevelLayout) {
1079
- if (input === void 0 && topLevelLayout) return {
1080
- enabled: true,
1081
- routes: { pages: {
1082
- pattern: "/[...slug]",
1083
- collection: "pages",
1084
- layout: topLevelLayout,
1085
- prerender: true
1086
- } },
1087
- fallback: "404",
1088
- onConflict: "warn"
1089
- };
1090
- if (input === void 0) return;
1091
- if (input === true) return {
1092
- enabled: true,
1093
- routes: { pages: {
1094
- pattern: "/[...slug]",
1095
- collection: "pages",
1096
- prerender: true
1097
- } },
1098
- fallback: "404",
1099
- onConflict: "warn"
1100
- };
1101
- if (input === false) return { enabled: false };
1102
- return input;
1103
- }
1104
- /**
1105
- * Apply defaults to a RouteConfig.
1106
- *
1107
- * Fills in missing optional fields with their default values.
1108
- *
1109
- * @param config - Partial route configuration
1110
- * @returns Complete route configuration with all fields
1111
- */
1112
- function resolveRouteConfig(config) {
1113
- return {
1114
- pattern: config.pattern,
1115
- collection: config.collection ?? "pages",
1116
- layout: config.layout ?? "",
1117
- prerender: config.prerender ?? true,
1118
- meta: config.meta ?? {},
1119
- dataBindings: config.dataBindings ?? { collections: [] }
1120
- };
1121
- }
1122
- //#endregion
1123
- //#region src/site-styles/content-wrapper-endpoint.ts
1124
- function createContentWrapperEndpoint() {
1125
- return async (req, res, _next) => {
1126
- try {
1127
- const routeUrl = new URL(req.url ?? "", "http://localhost").searchParams.get("url");
1128
- if (!routeUrl) {
1129
- res.statusCode = 400;
1130
- res.setHeader("content-type", "text/plain");
1131
- res.end("Missing required query parameter: url");
1132
- return;
1133
- }
1134
- const host = req.headers.host ?? "localhost:4321";
1135
- const liveUrl = `${req.headers["x-forwarded-proto"] ?? "http"}://${host}${routeUrl}`;
1136
- const wrappers = findContentWrapper(await fetch(liveUrl, { headers: req.headers.cookie ? { cookie: req.headers.cookie } : void 0 }).then((r) => r.text()));
1137
- res.statusCode = 200;
1138
- res.setHeader("content-type", "application/json; charset=utf-8");
1139
- res.setHeader("cache-control", "no-store");
1140
- res.end(JSON.stringify(wrappers));
1141
- } catch (err) {
1142
- res.statusCode = 500;
1143
- res.setHeader("content-type", "text/plain");
1144
- res.end(`Content-wrapper discovery failed: ${err instanceof Error ? err.message : String(err)}`);
1145
- }
1146
- };
1147
- }
1148
- /** Tags whose presence signals "this element holds prose content."
1149
- * We walk up from the first such element we find inside `<main>` to
1150
- * locate the wrapper. Headings + paragraphs cover every prose-styling
1151
- * convention we've seen — every CSS framework scopes typography
1152
- * through descendant selectors on `h1`–`h6` and `p`. */
1153
- const PROSE_TAGS = /* @__PURE__ */ new Set([
1154
- "h1",
1155
- "h2",
1156
- "h3",
1157
- "h4",
1158
- "h5",
1159
- "h6",
1160
- "p"
1161
- ]);
1162
- /** Tag that anchors code-block wrapper discovery. The host's code-
1163
- * block library (Starlight's expressive-code, Tailwind's `pre`
1164
- * styling, etc.) always renders a `<pre>` containing the code,
1165
- * often wrapped in additional classed elements. */
1166
- const CODE_BLOCK_ANCHOR = "pre";
1167
- /** HTML5 void elements — never push onto the open-tag stack since they
1168
- * have no closing tag. */
1169
- const VOID_TAGS = /* @__PURE__ */ new Set([
1170
- "area",
1171
- "base",
1172
- "br",
1173
- "col",
1174
- "embed",
1175
- "hr",
1176
- "img",
1177
- "input",
1178
- "link",
1179
- "meta",
1180
- "source",
1181
- "track",
1182
- "wbr"
1183
- ]);
1184
- /**
1185
- * Locate the host's content + code-block wrappers in raw HTML. Single-
1186
- * pass regex walk with a stack so we can recover ancestor chains for
1187
- * both prose tags and `<pre>` tags without a full DOM parser dep.
1188
- *
1189
- * Exported for unit testing.
1190
- */
1191
- function findContentWrapper(html) {
1192
- const cleaned = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "");
1193
- const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*)?)\s*(\/?)>/g;
1194
- const stack = [];
1195
- let explicit = null;
1196
- let mainEl = null;
1197
- const proseAncestorChains = [];
1198
- const preAncestorChains = [];
1199
- let match;
1200
- while ((match = tagRe.exec(cleaned)) !== null) {
1201
- const isClose = match[1] === "/";
1202
- const tagName = match[2].toLowerCase();
1203
- const attrBlob = match[3] ?? "";
1204
- const explicitlySelfClosing = match[4] === "/";
1205
- if (isClose) {
1206
- for (let i = stack.length - 1; i >= 0; i--) if (stack[i].tag === tagName) {
1207
- stack.length = i;
1208
- break;
1209
- }
1210
- continue;
1211
- }
1212
- const attrs = parseAttributes(attrBlob);
1213
- const className = attrs.class ?? "";
1214
- const el = {
1215
- tag: tagName,
1216
- className,
1217
- attrs
1218
- };
1219
- if (!explicit && "data-conloca-content-root" in attrs) explicit = {
1220
- tagName,
1221
- className
1222
- };
1223
- if (!mainEl && tagName === "main") mainEl = el;
1224
- if (mainEl && PROSE_TAGS.has(tagName)) {
1225
- const mainIdx = stack.indexOf(mainEl);
1226
- if (mainIdx >= 0) proseAncestorChains.push(stack.slice(mainIdx + 1));
1227
- }
1228
- if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
1229
- const mainIdx = stack.indexOf(mainEl);
1230
- if (mainIdx >= 0) preAncestorChains.push(stack.slice(mainIdx + 1));
1231
- }
1232
- if (!VOID_TAGS.has(tagName) && !explicitlySelfClosing) stack.push(el);
1233
- }
1234
- const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
1235
- return {
1236
- content,
1237
- codeBlock: resolveCodeBlockWrapper(content, preAncestorChains)
1238
- };
1239
- }
1240
- /**
1241
- * Pick the content wrapper from the walk's collected data.
1242
- *
1243
- * Priority: explicit opt-in > majority-prose-wrapper-inside-main >
1244
- * `<main>` fallback > null.
1245
- */
1246
- function resolveContentWrapper(explicit, mainEl, proseAncestorChains) {
1247
- if (explicit) return explicit;
1248
- if (!mainEl) return null;
1249
- if (proseAncestorChains.length === 0) return {
1250
- tagName: "main",
1251
- className: mainEl.className
1252
- };
1253
- const scores = /* @__PURE__ */ new Map();
1254
- for (const chain of proseAncestorChains) for (const ancestor of chain) {
1255
- if (!ancestor.className) continue;
1256
- scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
1257
- }
1258
- const threshold = proseAncestorChains.length / 2;
1259
- const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
1260
- if (candidates.length === 0) return {
1261
- tagName: "main",
1262
- className: mainEl.className
1263
- };
1264
- const maxChainIndex = (el) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
1265
- candidates.sort((a, b) => {
1266
- if (b[1] !== a[1]) return b[1] - a[1];
1267
- return maxChainIndex(b[0]) - maxChainIndex(a[0]);
1268
- });
1269
- const winner = candidates[0][0];
1270
- return {
1271
- tagName: winner.tag,
1272
- className: winner.className
1273
- };
1274
- }
1275
- /**
1276
- * Derive the code-block wrapper chain from a representative `<pre>`'s
1277
- * ancestor chain. We strip everything at or above the content wrapper
1278
- * (its styles are already handled by the content-wrapper mirror) and
1279
- * return the remaining classed elements in nesting order, outermost
1280
- * first.
1281
- *
1282
- * Returning a chain (instead of one collapsed element) preserves the
1283
- * shape host CSS expects:
1284
- *
1285
- * - Single-class selectors (`.frame { ... }`) hit on whichever link
1286
- * carries that class.
1287
- * - Descendant selectors (`.expressive-code .frame { ... }`,
1288
- * `.frame .header > .title`) hit because the editor's renderer
1289
- * materialises the chain as nested elements with the host's
1290
- * expected tag names.
1291
- *
1292
- * The editor's code-block frame component (`code-block-frame.tsx` in
1293
- * `@conloca/mdx`) treats the LAST link as the "frame" element (where
1294
- * figcaption/pre/copy children render) and wraps it with the earlier
1295
- * links from inside out. This matches the host's authoring shape for
1296
- * libraries like ExpressiveCode (`.expressive-code > figure.frame >
1297
- * figcaption + pre + .copy`).
1298
- */
1299
- function resolveCodeBlockWrapper(content, preAncestorChains) {
1300
- if (preAncestorChains.length === 0) return null;
1301
- const chain = preAncestorChains[0];
1302
- const contentIdx = content ? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className) : -1;
1303
- const classedAncestors = chain.slice(contentIdx + 1).filter((el) => el.className);
1304
- if (classedAncestors.length === 0) return null;
1305
- return classedAncestors.map((el) => ({
1306
- tagName: el.tag,
1307
- className: el.className
1308
- }));
1309
- }
1310
- /**
1311
- * Parse the attribute blob inside an opening tag. Handles `name="v"`,
1312
- * `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
1313
- * handle entity decoding (`&amp;` → `&`) since the values we read
1314
- * (tag name, class list, the marker attribute) don't carry entities
1315
- * in practice.
1316
- */
1317
- function parseAttributes(s) {
1318
- const out = {};
1319
- const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
1320
- let m;
1321
- while ((m = re.exec(s)) !== null) {
1322
- const name = m[1];
1323
- out[name] = m[2] ?? m[3] ?? m[4] ?? "";
1324
- }
1325
- return out;
1326
- }
1327
- //#endregion
1328
- //#region src/site-styles/render-endpoint.ts
1329
- /**
1330
- * Vite middleware that renders an MDX JSX subtree to HTML on demand.
1331
- *
1332
- * Container components (CardGrid, Tabs, …) have JSX children that on
1333
- * the published page render as direct DOM children of the parent —
1334
- * positional CSS (`:nth-child` colour cycling on Card grids, CSS-grid
1335
- * placement) depends on that DOM shape. Per-block isolated rendering
1336
- * breaks both: each child gets its own wrapper, and the parent's only
1337
- * direct child is a slot marker.
1338
- *
1339
- * This endpoint renders a recursive tree: each node provides its
1340
- * component name + source + props, optionally with its own `children`
1341
- * tree. The server renders leaves first and assembles parents by
1342
- * passing rendered children HTML as the parent's default slot, so the
1343
- * final markup matches what Astro would emit for the same MDX
1344
- * source — same DOM, same CSS context.
1345
- *
1346
- * Request shape (JSON body):
1347
- * {
1348
- * tree: {
1349
- * component: string,
1350
- * source: string,
1351
- * defaultExport?: boolean,
1352
- * props?: Record<string, unknown>,
1353
- * slotId: string,
1354
- * children?: RenderTreeNode[]
1355
- * },
1356
- * documentIndex?: number // wraps top-level output to fix
1357
- * // sibling-position CSS for root-level
1358
- * // blocks (see phantom-sibling fix).
1359
- * }
1360
- *
1361
- * Legacy shape (kept for backward compatibility):
1362
- * { component, source, defaultExport?, props?, documentIndex? }
1363
- *
1364
- * For each node, the rendered slot content is either:
1365
- * - The concatenated HTML of recursively-rendered children, if any.
1366
- * - `<conloca-slot data-slot-id="<id>"></conloca-slot>` placeholder
1367
- * otherwise (the SPA portals a Lexical editor into it).
1368
- *
1369
- * Returns 200 with `Content-Type: text/html` on success; 4xx with a
1370
- * plain-text error otherwise.
1371
- */
1372
- function createRenderEndpoint(server, getAllowedSources) {
1373
- let containerPromise = null;
1374
- const getContainer = () => {
1375
- if (!containerPromise) containerPromise = experimental_AstroContainer.create();
1376
- return containerPromise;
1377
- };
1378
- return async (req, res, _next) => {
1379
- if (req.method !== "POST") {
1380
- res.statusCode = 405;
1381
- res.setHeader("content-type", "text/plain");
1382
- res.end("Method not allowed");
1383
- return;
1384
- }
1385
- try {
1386
- const body = await readJson(req);
1387
- const tree = body.tree ?? {
1388
- component: body.component ?? "",
1389
- source: body.source ?? "",
1390
- defaultExport: body.defaultExport,
1391
- props: body.props,
1392
- slotId: "root"
1393
- };
1394
- if (!tree.component || !tree.source) {
1395
- res.statusCode = 400;
1396
- res.setHeader("content-type", "text/plain");
1397
- res.end("Missing required fields: tree.component, tree.source");
1398
- return;
1399
- }
1400
- const disallowed = collectDisallowedSources(tree, await getAllowedSources());
1401
- if (disallowed.length > 0) {
1402
- res.statusCode = 400;
1403
- res.setHeader("content-type", "text/plain");
1404
- res.end(`source not in registry: ${disallowed.join(", ")}`);
1405
- return;
1406
- }
1407
- const container = await getContainer();
1408
- let rendered;
1409
- try {
1410
- rendered = await renderTree(tree, container, server);
1411
- } catch (err) {
1412
- console.warn(`[conloca:render] <${tree.component}> failed:`, err instanceof Error ? err.message : err);
1413
- rendered = renderErrorStub(tree, err);
1414
- }
1415
- let html;
1416
- if (body.inline) html = rendered;
1417
- else {
1418
- const documentIndex = body.documentIndex;
1419
- const phantomCount = typeof documentIndex === "number" && documentIndex > 0 ? documentIndex - 1 : 0;
1420
- html = `<div class="sl-markdown-content">${phantomCount > 0 ? "<span hidden aria-hidden=\"true\"></span>".repeat(phantomCount) : ""}${rendered}</div>`;
1421
- }
1422
- res.statusCode = 200;
1423
- res.setHeader("content-type", "text/html; charset=utf-8");
1424
- res.setHeader("cache-control", "no-store");
1425
- res.end(html);
1426
- } catch (err) {
1427
- res.statusCode = 500;
1428
- res.setHeader("content-type", "text/plain");
1429
- res.end(`Render failed: ${err instanceof Error ? err.message : String(err)}`);
1430
- }
1431
- };
1432
- }
1433
- async function renderTree(node, container, server) {
1434
- const module = await server.ssrLoadModule(node.source);
1435
- const exportKey = node.defaultExport ? "default" : node.component;
1436
- const factory = module[exportKey];
1437
- if (typeof factory !== "function") throw new Error(`Component '${node.component}' not found at '${node.source}' (export '${exportKey}')`);
1438
- let slotContent;
1439
- if (node.children && node.children.length > 0) slotContent = (await Promise.all(node.children.map(async (child) => {
1440
- try {
1441
- return await renderTree(child, container, server);
1442
- } catch (err) {
1443
- console.warn(`[conloca:render] <${child.component}> failed:`, err instanceof Error ? err.message : err);
1444
- return renderErrorStub(child, err);
1445
- }
1446
- }))).join("");
1447
- else if (node.bodyHtml) slotContent = node.bodyHtml;
1448
- else {
1449
- const fallback = node.body ?? "";
1450
- slotContent = `<conloca-slot data-slot-id="${escapeHtml(node.slotId)}">${fallback}</conloca-slot>`;
1451
- }
1452
- const slots = {
1453
- default: slotContent,
1454
- ...node.namedSlots ?? {}
1455
- };
1456
- return container.renderToString(factory, {
1457
- props: node.props,
1458
- slots,
1459
- locals: { t: defaultI18nFallback }
1460
- });
1461
- }
1462
- /**
1463
- * Build a self-contained, editable error stub for one render failure.
1464
- *
1465
- * Three jobs:
1466
- * 1. Surface the error inline so the author sees *exactly* which
1467
- * component blew up and why, right where it sits in the document.
1468
- * No console-spelunking required.
1469
- * 2. Keep the slot id intact so GenericBlock's portal-discovery loop
1470
- * (`querySelectorAll('conloca-slot[data-slot-id]')`) still finds a
1471
- * mount point inside the stub. The body editor mounts as normal;
1472
- * the author can edit the children even though the parent
1473
- * component's own render failed — typically that's enough to fix
1474
- * whatever the validator was upset about.
1475
- * 3. Stay structurally innocuous. A `<div>` wrapper renders cleanly
1476
- * inside any parent slot that accepts arbitrary HTML, and a
1477
- * data-attribute on the wrapper lets host CSS style it however
1478
- * they like (yellow background, red border, whatever).
1479
- *
1480
- * Note: if the parent component itself has a strict-slot validator
1481
- * (eg `<Tabs>` rejects non-TabItem children), the stub will fail the
1482
- * parent's render too — but the recursion at the parent level then
1483
- * catches THAT failure and emits its own stub one level up. The
1484
- * worst case bubbles all the way to the top-level wrap in the
1485
- * endpoint handler. Errors never escape as 500s.
1486
- */
1487
- function renderErrorStub(node, err) {
1488
- const message = err instanceof Error ? err.message : String(err);
1489
- const name = node.component || "unknown";
1490
- return `<div class="conloca-render-error" data-component="${escapeHtml(name)}" data-slot-id="${escapeHtml(node.slotId)}" role="alert"><div class="conloca-render-error__label">&lt;${escapeHtml(name)}&gt; failed to render: ${escapeHtml(message)}</div><conloca-slot data-slot-id="${escapeHtml(node.slotId)}"></conloca-slot></div>`;
1491
- }
1492
- function collectDisallowedSources(node, allowed) {
1493
- const bad = [];
1494
- if (!allowed.has(node.source)) bad.push(node.source);
1495
- if (node.children) for (const child of node.children) bad.push(...collectDisallowedSources(child, allowed));
1496
- return bad;
1497
- }
1498
- function escapeHtml(s) {
1499
- return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1500
- }
1501
- function defaultI18nFallback(key) {
1502
- const leaf = key.split(".").pop() ?? key;
1503
- return leaf.charAt(0).toUpperCase() + leaf.slice(1);
1504
- }
1505
- async function readJson(req) {
1506
- return new Promise((resolve, reject) => {
1507
- let raw = "";
1508
- req.setEncoding("utf8");
1509
- req.on("data", (chunk) => {
1510
- raw += chunk;
1511
- });
1512
- req.on("end", () => {
1513
- try {
1514
- resolve(raw ? JSON.parse(raw) : {});
1515
- } catch (err) {
1516
- reject(err instanceof Error ? err : /* @__PURE__ */ new Error("Invalid JSON"));
1517
- }
1518
- });
1519
- req.on("error", reject);
1520
- });
1521
- }
1522
- //#endregion
1523
- //#region src/site-styles/styles-endpoint.ts
1524
- /**
1525
- * Vite middleware that returns the concatenated CSS for a route URL.
1526
- *
1527
- * Used by the CMS editor SPA to fetch the styles that apply to the page
1528
- * being edited so the editor renders content with the same CSS as the
1529
- * published page.
1530
- *
1531
- * Mechanism (host-agnostic):
1532
- *
1533
- * 1. HTTP-fetch the live HTML at the route URL from the running dev
1534
- * server. This is the same HTML a browser would receive — it lists
1535
- * every stylesheet the page actually loads.
1536
- * 2. Pull the content of every `<style>...</style>` block (where dev-
1537
- * mode Astro inlines its component / Tailwind / user CSS).
1538
- * 3. Pull every `<link rel="stylesheet" href="…">` (excluding
1539
- * `media="print"`) and fetch each one with `?direct` so the dev
1540
- * server returns the raw CSS instead of the HMR JS wrapper.
1541
- * 4. Concatenate in source order and return as `text/css`.
1542
- *
1543
- * Why this instead of Astro's `devCSSMap`:
1544
- *
1545
- * - `devCSSMap` is an Astro-internal virtual module. It only surfaces
1546
- * CSS that flows through Astro's `.astro` component graph. Anything
1547
- * emitted by an Astro integration as a STANDALONE asset (the
1548
- * canonical example is expressive-code's `/_astro/ec.*.css`) sits
1549
- * outside that graph and never reaches the editor through devCSSMap.
1550
- * - Scraping the live HTML reads what the published page actually
1551
- * paints with — the same stylesheets the user will see in the
1552
- * browser. No dependency on a specific framework's internal API.
1553
- *
1554
- * Known limitations (rare on Astro sites):
1555
- *
1556
- * - CSS injected by JavaScript at runtime (`document.head.appendChild`)
1557
- * isn't in the initial HTML, so we don't see it. Affects view-
1558
- * transition handlers and third-party widget snippets.
1559
- * - CSS-in-JS libraries (styled-components, emotion) generate styles
1560
- * during client render and have the same blind spot.
1561
- * - Cross-origin stylesheets the dev server can't reach get logged
1562
- * and skipped (graceful degradation, not silent failure).
1563
- */
1564
- function createStylesEndpoint() {
1565
- return async (req, res, _next) => {
1566
- try {
1567
- const routeUrl = new URL(req.url ?? "", "http://localhost").searchParams.get("url");
1568
- if (!routeUrl) {
1569
- res.statusCode = 400;
1570
- res.setHeader("content-type", "text/plain");
1571
- res.end("Missing required query parameter: url");
1572
- return;
1573
- }
1574
- const host = req.headers.host ?? "localhost:4321";
1575
- const origin = `${req.headers["x-forwarded-proto"] ?? "http"}://${host}`;
1576
- const cookie = req.headers.cookie;
1577
- const liveResponse = await fetch(`${origin}${routeUrl}`, { headers: cookie ? { cookie } : void 0 });
1578
- if (!liveResponse.ok) {
1579
- res.statusCode = liveResponse.status;
1580
- res.setHeader("content-type", "text/plain");
1581
- res.end(`Upstream route returned ${liveResponse.status}: ${routeUrl}`);
1582
- return;
1583
- }
1584
- const body = (await collectStylesFromHtml(await liveResponse.text(), origin, cookie)).map((s) => `/* ${s.url} */\n${s.css}`).join("\n\n");
1585
- res.statusCode = 200;
1586
- res.setHeader("content-type", "text/css; charset=utf-8");
1587
- res.setHeader("cache-control", "no-store");
1588
- res.end(body);
1589
- } catch (err) {
1590
- res.statusCode = 500;
1591
- res.setHeader("content-type", "text/plain");
1592
- res.end(`Styles discovery failed: ${err instanceof Error ? err.message : String(err)}`);
1593
- }
1594
- };
1595
- }
1596
- /**
1597
- * Read every `<style>` block and `<link rel="stylesheet">` from the
1598
- * HTML in their original source order. Inline `<style>` blocks are
1599
- * captured verbatim; link tags are fetched separately (raw CSS via
1600
- * `?direct`). Print-media stylesheets are skipped.
1601
- *
1602
- * Exported for unit testing.
1603
- */
1604
- async function collectStylesFromHtml(html, origin, cookie) {
1605
- const cleaned = html.replace(/<!--[\s\S]*?-->/g, "");
1606
- const entries = [];
1607
- const styleRe = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
1608
- let match;
1609
- while ((match = styleRe.exec(cleaned)) !== null) {
1610
- const attrs = match[1];
1611
- if (/media\s*=\s*["']?print/i.test(attrs)) continue;
1612
- const css = match[2];
1613
- const idAttr = attrs.match(/data-vite-dev-id="([^"]+)"/);
1614
- const captured = {
1615
- url: idAttr ? idAttr[1] : `<style#${match.index}>`,
1616
- css
1617
- };
1618
- entries.push({
1619
- index: match.index,
1620
- fetch: () => Promise.resolve(captured)
1621
- });
1622
- }
1623
- const linkRe = /<link\b([^>]*)\/?>/gi;
1624
- while ((match = linkRe.exec(cleaned)) !== null) {
1625
- const attrs = match[1];
1626
- if (!/rel\s*=\s*["']?stylesheet["']?/i.test(attrs)) continue;
1627
- if (/media\s*=\s*["']?print/i.test(attrs)) continue;
1628
- const hrefMatch = attrs.match(/href\s*=\s*"([^"]+)"|href\s*=\s*'([^']+)'/);
1629
- if (!hrefMatch) continue;
1630
- const href = hrefMatch[1] ?? hrefMatch[2];
1631
- const index = match.index;
1632
- entries.push({
1633
- index,
1634
- fetch: () => fetchStylesheet(href, origin, cookie)
1635
- });
1636
- }
1637
- entries.sort((a, b) => a.index - b.index);
1638
- return (await Promise.all(entries.map((e) => e.fetch()))).filter((r) => r !== null);
1639
- }
1640
- /**
1641
- * Fetch a stylesheet by href and return its raw CSS. Vite serves CSS
1642
- * files as JS HMR wrappers by default; `?direct` flips that to raw CSS
1643
- * output. Absolute URLs are fetched as-is; root-relative paths are
1644
- * resolved against the dev server origin so cross-page link tags work.
1645
- */
1646
- async function fetchStylesheet(href, origin, cookie) {
1647
- const target = !/^https?:\/\//i.test(href) || href.startsWith(origin) ? `${origin}${href.startsWith("/") ? href : `/${href}`}${href.includes("?") ? "&direct" : "?direct"}` : href;
1648
- try {
1649
- const res = await fetch(target, { headers: cookie ? { cookie } : void 0 });
1650
- if (!res.ok) {
1651
- console.warn(`[conloca:css] link fetch returned ${res.status} for ${href}`);
1652
- return null;
1653
- }
1654
- return {
1655
- url: href,
1656
- css: await res.text()
1657
- };
1658
- } catch (err) {
1659
- console.warn(`[conloca:css] link fetch failed for ${href}:`, err);
1660
- return null;
1661
- }
1662
- }
1663
- //#endregion
1664
- //#region src/lib/virtual-module-generators.ts
1665
- /**
1666
- * Generate the virtual:conloca-routing-config module.
1667
- *
1668
- * Returns a module that exports the resolved routing configuration as default.
1669
- *
1670
- * @param config - Resolved routing configuration with all defaults applied
1671
- * @returns JavaScript module code as a string
1672
- */
1673
- function generateRoutingConfigModule(config) {
1674
- return `export default ${JSON.stringify(config, null, 2)};`;
1675
- }
1676
- /**
1677
- * Generate the virtual:conloca-layout module.
1678
- *
1679
- * Returns a module that re-exports the layout component or exports undefined
1680
- * if no layout is configured.
1681
- *
1682
- * Currently uses the first route's layout. Multi-layout support is future work.
1683
- *
1684
- * @param routing - Routing configuration (may be undefined if routing disabled)
1685
- * @returns JavaScript module code as a string
1686
- */
1687
- function generateLayoutModule(routing) {
1688
- const routes = routing?.routes || {};
1689
- const layoutPath = Object.values(routes)[0]?.layout;
1690
- if (layoutPath) return `export { default } from '${layoutPath.startsWith(".") ? `/${layoutPath.slice(2)}` : layoutPath}';`;
1691
- return "export default undefined;";
1692
- }
1693
- /**
1694
- * Generate the virtual:conloca-page-api module.
1695
- *
1696
- * Returns a module that provides page loading functions wrapping ContentAPI:
1697
- * - getAllPages(collection?) - For getStaticPaths()
1698
- * - getPage(pathname, collection?) - For page data loading
1699
- * - pageExists(pathname, collection?) - For 404 checks
1700
- * - contentOptions - Configuration for ContentAPI (for MDX evaluation)
1701
- *
1702
- * @param options - Configuration for ContentAPI initialization
1703
- * @returns JavaScript module code as a string
1704
- */
1705
- function generatePageApiModule(options) {
1706
- return `
1707
- import { createContentAPI } from '@conloca/content-api/reader';
1708
-
1709
- // Export content options for MDX evaluation and other ContentAPI uses
1710
- export const contentOptions = {
1711
- contentRoot: '${options.contentRoot}',
1712
- canvasDir: '${options.canvasDir}',
1713
- siteName: '${options.siteName}',
1714
- locale: '${options.locale}',
1715
- };
1716
-
1717
- // Initialize ContentAPI with configured paths
1718
- const contentApi = await createContentAPI({
1719
- contentRoot: contentOptions.contentRoot,
1720
- canvasDir: contentOptions.canvasDir,
1721
- });
1722
-
1723
- // Get site instance for page operations (configured via routing.siteName)
1724
- const site = contentApi.getSite(contentOptions.siteName);
1725
- const locale = contentOptions.locale; // Configured via routing.locale
1726
-
1727
- /**
1728
- * Get all pages for static path generation.
1729
- * @param collection - Optional collection filter
1730
- */
1731
- export async function getAllPages(collection) {
1732
- const pages = [];
1733
-
1734
- // listPages is a generator that yields ContentManifest objects
1735
- for (const manifest of site.listPages(locale)) {
1736
- // Get the localized data for pathname/title
1737
- const localeData = manifest.locales[locale];
1738
- if (!localeData) continue;
1739
-
1740
- const pathname = localeData.pathname || '/' + manifest.id.replace(/^index$/, '');
1741
-
1742
- // Collection resolution: explicit collection in manifest, or default 'pages'
1743
- const resolvedCollection = manifest.collection || 'pages';
1744
-
1745
- // Filter by requested collection
1746
- if (collection && resolvedCollection !== collection) continue;
1747
-
1748
- pages.push({
1749
- id: manifest.id,
1750
- pathname: pathname,
1751
- title: localeData.meta?.title || manifest.id,
1752
- collection: resolvedCollection,
1753
- meta: localeData.meta || {},
1754
- timestamps: {
1755
- created: localeData.created,
1756
- modified: localeData.modified,
1757
- },
1758
- });
1759
- }
1760
-
1761
- return pages;
1762
- }
1763
-
1764
- /**
1765
- * Get pages matching a path prefix.
1766
- * @param prefix - Path prefix to match (e.g., '/blog/')
1767
- * @param options - Optional sort and limit settings
1768
- * @returns Array of PageReference objects
1769
- */
1770
- export async function getPagesByPrefix(prefix, options = {}) {
1771
- const allPages = await getAllPages();
1772
-
1773
- let filtered = allPages.filter(page =>
1774
- page.pathname.startsWith(prefix) &&
1775
- page.pathname !== prefix && // Exclude the listing page itself
1776
- page.pathname !== prefix.slice(0, -1) // Exclude without trailing slash
1777
- );
1778
-
1779
- // Sort by date (newest first by default)
1780
- if (options.sort === 'date-desc' || !options.sort) {
1781
- filtered.sort((a, b) => {
1782
- const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);
1783
- const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);
1784
- return new Date(dateB).getTime() - new Date(dateA).getTime();
1785
- });
1786
- } else if (options.sort === 'date-asc') {
1787
- filtered.sort((a, b) => {
1788
- const dateA = a.timestamps?.modified || a.timestamps?.created || new Date(0);
1789
- const dateB = b.timestamps?.modified || b.timestamps?.created || new Date(0);
1790
- return new Date(dateA).getTime() - new Date(dateB).getTime();
1791
- });
1792
- } else if (options.sort === 'title') {
1793
- filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
1794
- }
1795
-
1796
- if (options.limit && options.limit > 0) {
1797
- filtered = filtered.slice(0, options.limit);
1798
- }
1799
-
1800
- return filtered;
1801
- }
1802
-
1803
- /**
1804
- * Load full page data for rendering.
1805
- * @param pathname - URL pathname (e.g., '/about')
1806
- * @param collection - Optional collection to search in
1807
- */
1808
- export async function getPage(pathname, collection) {
1809
- // Use site.getByPathname which returns ContentManifest (metadata only)
1810
- const manifest = site.getByPathname(pathname, locale);
1811
-
1812
- if (!manifest) {
1813
- const error = new Error(\`Page not found: \${pathname}\`);
1814
- error.code = 'PAGE_NOT_FOUND';
1815
- throw error;
1816
- }
1817
-
1818
- // Optionally filter by collection
1819
- if (collection && manifest.collection !== collection) {
1820
- const error = new Error(\`Page not found: \${pathname}\`);
1821
- error.code = 'PAGE_NOT_FOUND';
1822
- throw error;
1823
- }
1824
-
1825
- // Get the full content with locale data
1826
- const content = await contentApi.getLocalized(manifest.id, locale);
1827
-
1828
- if (!content) {
1829
- const error = new Error(\`Page not found: \${pathname}\`);
1830
- error.code = 'PAGE_NOT_FOUND';
1831
- throw error;
1832
- }
1833
-
1834
- const localeData = content.localized;
1835
- const meta = localeData.meta || {};
1836
-
1837
- return {
1838
- id: manifest.id,
1839
- title: meta.title || manifest.id,
1840
- description: meta.description,
1841
- pathname: pathname,
1842
- puckData: localeData.content?.puckData,
1843
- collection: manifest.collection || collection || 'pages',
1844
- route: {
1845
- name: 'pages', // Will be set by caller
1846
- pattern: '/[...slug]',
1847
- meta: {},
1848
- },
1849
- meta: meta,
1850
- timestamps: {
1851
- created: localeData.created,
1852
- modified: localeData.modified,
1853
- },
1854
- };
1855
- }
1856
-
1857
- /**
1858
- * Check if a page exists without loading full data.
1859
- * @param pathname - URL pathname
1860
- * @param collection - Optional collection filter
1861
- */
1862
- export function pageExists(pathname, collection) {
1863
- // getByPathname is synchronous - returns ContentManifest | null
1864
- const manifest = site.getByPathname(pathname, locale);
1865
-
1866
- if (!manifest) {
1867
- return false;
1868
- }
1869
-
1870
- // If collection filter specified, verify it matches
1871
- if (collection && manifest.collection !== collection) {
1872
- return false;
1873
- }
1874
-
1875
- return true;
1876
- }
1877
-
1878
- /**
1879
- * Get all entries from a data collection.
1880
- * @param collection - Data collection name
1881
- * @param localeOverride - Optional locale override (defaults to configured locale)
1882
- * @returns Array of DataCollectionEntry objects
1883
- */
1884
- export async function getDataCollection(collection, localeOverride) {
1885
- const targetLocale = localeOverride || locale;
1886
- const entries = [];
1887
-
1888
- // List all manifests in the collection
1889
- for (const manifest of contentApi.data.listContent({ collection })) {
1890
- // Get localized data for each entry
1891
- const localized = await contentApi.getLocalized(manifest.id, targetLocale);
1892
- if (localized) {
1893
- entries.push({
1894
- id: manifest.id,
1895
- name: manifest.name,
1896
- data: localized.content?.data || {},
1897
- meta: manifest.meta || {},
1898
- });
1899
- }
1900
- }
1901
-
1902
- return entries;
1903
- }
1904
- `;
1905
- }
1906
- /**
1907
- * Generate the virtual:conloca-puck-config module.
1908
- *
1909
- * Returns a module that re-exports the Puck configuration.
1910
- * This is separate from the HMR-enabled puck-entry.js used by the CMS SPA.
1911
- *
1912
- * @param puckConfigPath - Path to the puck config module
1913
- * @returns JavaScript module code as a string
1914
- */
1915
- function generatePuckConfigModule(puckConfigPath) {
1916
- return `export { default } from '${puckConfigPath.startsWith(".") ? `/${puckConfigPath.slice(2)}` : puckConfigPath}';`;
1917
- }
1918
- //#endregion
1919
- //#region src/plugin-spa.ts
1920
- if (typeof viteReact.preambleCode !== "string") throw new Error("@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. Check @vitejs/plugin-react release notes and update the preamble injection logic.");
1921
- const reactRefreshPreamble = viteReact.preambleCode.replace("__BASE__", "/");
1922
- const __dirname = dirname(fileURLToPath(import.meta.url));
1923
- const PAGE_HANDLER_PATH = join(__dirname, "..", "internal", "page-handler.astro");
1924
- const CMS_HANDLER_PATH = join(__dirname, "..", "internal", "cms-handler.mjs");
1925
- const ACORN_DEFAULT_SHIM_PATH = join(__dirname, "..", "internal", "acorn-default.mjs");
1926
- const VIRTUAL_CONFIG_MODULE = "virtual:conloca-config";
1927
- const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
1928
- const VIRTUAL_ROUTING_CONFIG = "virtual:conloca-routing-config";
1929
- const VIRTUAL_LAYOUT = "virtual:conloca-layout";
1930
- const VIRTUAL_PAGE_API = "virtual:conloca-page-api";
1931
- const VIRTUAL_PUCK_CONFIG = "virtual:conloca-puck-config";
1932
- const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
1933
- const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
1934
- const RESOLVED_PAGE_API = `\0${VIRTUAL_PAGE_API}`;
1935
- const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
1936
- const VIRTUAL_HYDRATION_REGISTRY = "virtual:conloca-hydration-registry";
1937
- const VIRTUAL_HYDRATION_ENTRY = "virtual:conloca-hydration-entry";
1938
- const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
1939
- const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
1940
- const VIRTUAL_CMS_SPA_ENTRY = "virtual:conloca-cms-spa-entry";
1941
- const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
1942
- async function loadContentApiNode() {
1943
- return import("@conloca/content-api/node");
1944
- }
1945
- const contentChangeListener = () => {
1946
- return `
1947
- // Content change listener that uses Vite HMR
1948
- if (import.meta.hot) {
1949
- import.meta.hot.on('conloca:content-update', (data) => {
1950
- console.log('[Conloca CMS] Content updated, invalidating cache:', data);
1951
-
1952
- // Get the query client from the global scope and invalidate
1953
- if (window.__QUERY_CLIENT__) {
1954
- window.__QUERY_CLIENT__.invalidateQueries();
1955
- }
1956
- });
1957
- }
1958
-
1959
- export default {};
1960
- `;
1961
- };
1962
- const puckConfigLoader = (absolutePuckPath, cmsSpaDistDir) => {
1963
- const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/puck-config.mjs` : "@conloca/cms-spa/puck-config";
1964
- return `
1965
- // Import and execute React refresh preamble first (from @vitejs/plugin-react)
1966
- ${reactRefreshPreamble}
1967
-
1968
- // Import the setPuckConfig function from cms-spa
1969
- import { setPuckConfig } from '${puckConfigImport}';
1970
-
1971
- // Now dynamically import the config after preamble is ready
1972
- const puckConfigPromise = import('${absolutePuckPath}');
1973
-
1974
- // Handle the initial load
1975
- puckConfigPromise.then(module => {
1976
- const puckConfig = module.default;
1977
- setPuckConfig(puckConfig);
1978
-
1979
- // Hook into React Fast Refresh to detect component updates
1980
- if (window.__registerBeforePerformReactRefresh) {
1981
- window.__registerBeforePerformReactRefresh(async () => {
1982
- // Re-import the config module to get updated components
1983
- const newModule = await import('${absolutePuckPath}');
1984
- setPuckConfig(newModule.default);
1985
- });
1986
- }
1987
- });
1988
-
1989
- // Accept HMR for this module itself
1990
- if (import.meta.hot) {
1991
- import.meta.hot.accept();
1992
- }
1993
-
1994
- // Export the promise so the module has a default export
1995
- export default puckConfigPromise.then(m => m.default);
1996
- `;
1997
- };
1998
- const schemasLoader = (absoluteSchemasPath, cmsSpaDistDir) => {
1999
- const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/page-schemas.mjs` : "@conloca/cms-spa/page-schemas";
2000
- const mdxComponentsImport = cmsSpaDistDir ? `${cmsSpaDistDir}/mdx-components.mjs` : "@conloca/cms-spa/mdx-components";
2001
- return `
2002
- ${reactRefreshPreamble}
2003
-
2004
- import { setPageSchemas } from '${pageSchemasImport}';
2005
- import { setMdxComponents } from '${mdxComponentsImport}';
2006
-
2007
- const schemasPromise = import('${absoluteSchemasPath}');
2008
-
2009
- schemasPromise.then((schemas) => {
2010
- if (schemas.pageSchemas) {
2011
- setPageSchemas(schemas.pageSchemas);
2012
- }
2013
- if (schemas.mdxComponents) {
2014
- setMdxComponents(schemas.mdxComponents);
2015
- }
2016
- });
2017
-
2018
- if (import.meta.hot) {
2019
- import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
2020
- if (newModule?.pageSchemas) {
2021
- setPageSchemas(newModule.pageSchemas);
2022
- }
2023
- if (newModule?.mdxComponents) {
2024
- setMdxComponents(newModule.mdxComponents);
2025
- }
2026
- });
2027
- }
2028
-
2029
- export default schemasPromise;
2030
- `;
2031
- };
2032
- const siteStylesLoader = (cssPaths, cmsSpaDistDir) => {
2033
- const imports = cssPaths.map((p, i) => {
2034
- return `import css${i} from '${p.startsWith("./") ? `/${p.slice(2)}` : p}?inline';`;
2035
- }).join("\n");
2036
- const vars = cssPaths.map((_, i) => `css${i}`).join(", ");
2037
- return `
2038
- ${imports}
2039
- import { setSiteStyles } from '${cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : "@conloca/cms-spa/site-styles"}';
2040
-
2041
- setSiteStyles([${vars}]);
2042
-
2043
- if (import.meta.hot) {
2044
- import.meta.hot.accept();
2045
- }
2046
-
2047
- export default {};
2048
- `;
2049
- };
2050
- const editorStylesLoader = (cssPaths, cmsSpaDistDir) => {
2051
- const imports = cssPaths.map((p, i) => {
2052
- return `import css${i} from '${p.startsWith("./") ? `/${p.slice(2)}` : p}?inline';`;
2053
- }).join("\n");
2054
- const vars = cssPaths.map((_, i) => `css${i}`).join(", ");
2055
- return `
2056
- ${imports}
2057
- import { setEditorStyles } from '${cmsSpaDistDir ? `${cmsSpaDistDir}/site-styles.mjs` : "@conloca/cms-spa/site-styles"}';
2058
-
2059
- setEditorStyles([${vars}]);
2060
-
2061
- if (import.meta.hot) {
2062
- import.meta.hot.accept();
2063
- }
2064
-
2065
- export default {};
2066
- `;
2067
- };
2068
- function conlocaCMS(options) {
2069
- const cmsRoute = options.route || "/__cms";
2070
- let cmsSpaDir;
2071
- try {
2072
- const pkgUrl = import.meta.resolve("@conloca/cms-spa/package.json");
2073
- cmsSpaDir = dirname(pkgUrl.startsWith("file://") ? fileURLToPath(pkgUrl) : pkgUrl);
2074
- } catch {}
2075
- const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, "dist") : void 0;
2076
- const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
2077
- const hydrationDiscoveriesPromise = scanForHydratableComponents(deriveComponentPaths(options.puckConfigPath, options.componentPaths), process.cwd()).then((discoveries) => {
2078
- if (discoveries.length > 0) console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
2079
- return discoveries;
2080
- });
2081
- let resolvedRoutingConfig;
2082
- if (routingConfig?.enabled !== false && routingConfig) {
2083
- const resolvedRoutes = {};
2084
- for (const [name, config] of Object.entries(routingConfig.routes || {})) resolvedRoutes[name] = resolveRouteConfig(config);
2085
- resolvedRoutingConfig = {
2086
- enabled: routingConfig.enabled ?? true,
2087
- routes: resolvedRoutes,
2088
- fallback: routingConfig.fallback ?? "404",
2089
- onConflict: routingConfig.onConflict ?? "warn",
2090
- siteName: routingConfig.siteName ?? "default",
2091
- locale: routingConfig.locale ?? "en"
2092
- };
2093
- }
2094
- const spaConfig = {
2095
- basename: cmsRoute,
2096
- apiBaseUrl: `${cmsRoute}/api`,
2097
- siteBaseUrl: options.siteBaseUrl,
2098
- enableDevtools: options.enableDevtools ?? true,
2099
- queryClientOptions: options.queryClientOptions,
2100
- schemasPath: options.schemasPath,
2101
- projectRoot: process.cwd(),
2102
- templates: options.templates,
2103
- mdxPagesEnabled: false,
2104
- locales: options.locales ? {
2105
- list: options.locales.list,
2106
- defaultLocale: options.locales.defaultLocale
2107
- } : void 0
2108
- };
2109
- let resolvedMdxPages = null;
2110
- let refreshConlocaContent;
2111
- return {
2112
- name: "@conloca/astro-cms",
2113
- hooks: {
2114
- "astro:config:setup": async ({ updateConfig, injectRoute, command, logger }) => {
2115
- const sitesConfig = await readSitesConfig(options.contentRoot);
2116
- resolvedMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages)?.mdxPages ?? null;
2117
- spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);
2118
- const astroRoot = process.cwd();
2119
- const contentAbsolute = resolve(options.contentRoot);
2120
- if (command === "dev" && !contentAbsolute.startsWith(astroRoot)) {
2121
- logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
2122
- updateConfig({ vite: { server: { fs: { allow: [searchForWorkspaceRoot(process.cwd()), contentAbsolute] } } } });
2123
- }
2124
- const alwaysSsrNoExternal = ["@puckeditor/core"];
2125
- const devOnlySsrNoExternal = [/^@conloca\//];
2126
- const serverOnlyExternal = [
2127
- "@conloca/content-api",
2128
- "@conloca/content-api/node",
2129
- "@conloca/content-api/reader",
2130
- "@conloca/content-api/schemas",
2131
- "@conloca/mdx",
2132
- "@conloca/mdx/node"
2133
- ];
2134
- updateConfig({ vite: {
2135
- ssr: {
2136
- noExternal: command === "dev" ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,
2137
- external: serverOnlyExternal
2138
- },
2139
- resolve: { dedupe: [
2140
- "react",
2141
- "react-dom",
2142
- "react/jsx-runtime",
2143
- "react/jsx-dev-runtime"
2144
- ] },
2145
- plugins: [
2146
- {
2147
- name: "conloca-puck-ssr-render-alias",
2148
- enforce: "pre",
2149
- async resolveId(id, importer, options) {
2150
- if (id === "@puckeditor/core" && options?.ssr) return this.resolve("@puckeditor/core/rsc", importer, {
2151
- ...options,
2152
- skipSelf: true
2153
- });
2154
- return null;
2155
- }
2156
- },
2157
- {
2158
- name: "conloca-acorn-ssr-alias",
2159
- enforce: "pre",
2160
- resolveId(id, _importer, options) {
2161
- if (id === "acorn" && options?.ssr) return ACORN_DEFAULT_SHIM_PATH;
2162
- return null;
2163
- }
2164
- },
2165
- {
2166
- name: "conloca-routing-virtual-modules",
2167
- resolveId(id) {
2168
- if (id === VIRTUAL_ROUTING_CONFIG) return RESOLVED_ROUTING_CONFIG;
2169
- if (id === VIRTUAL_LAYOUT) return RESOLVED_LAYOUT;
2170
- if (id === VIRTUAL_PUCK_CONFIG) return RESOLVED_PUCK_CONFIG;
2171
- if (id === VIRTUAL_HYDRATION_REGISTRY) return RESOLVED_HYDRATION_REGISTRY;
2172
- if (id === VIRTUAL_HYDRATION_ENTRY) return RESOLVED_HYDRATION_ENTRY;
2173
- return null;
2174
- },
2175
- async load(id) {
2176
- if (id === RESOLVED_ROUTING_CONFIG) {
2177
- if (resolvedRoutingConfig) return generateRoutingConfigModule(resolvedRoutingConfig);
2178
- return "export default { enabled: false, routes: {}, fallback: \"404\", onConflict: \"warn\" };";
2179
- }
2180
- if (id === RESOLVED_LAYOUT) return generateLayoutModule(routingConfig);
2181
- if (id === RESOLVED_PUCK_CONFIG) return generatePuckConfigModule(options.puckConfigPath);
2182
- if (id === RESOLVED_HYDRATION_REGISTRY) {
2183
- const discoveries = await hydrationDiscoveriesPromise;
2184
- if (discoveries.length > 0) return `// Generated by @conloca/astro-cms scanner
2185
- export const componentRegistry = {
2186
- ${discoveries.map((d) => {
2187
- const relativePath = d.filePath.replace(process.cwd(), "");
2188
- return ` '${d.componentName}': {
2189
- loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
2190
- strategy: '${d.strategy}',
2191
- }`;
2192
- }).join(",\n")}
2193
- };`;
2194
- return "export const componentRegistry = {};";
2195
- }
2196
- if (id === RESOLVED_HYDRATION_ENTRY) return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
2197
- import { componentRegistry } from 'virtual:conloca-hydration-registry'
2198
-
2199
- // Auto-initialize hydration when this module loads
2200
- initHydration(componentRegistry)
2201
- `;
2202
- return null;
2203
- }
2204
- }
2205
- ]
2206
- } });
2207
- if (resolvedRoutingConfig?.enabled) for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
2208
- logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
2209
- injectRoute({
2210
- pattern: routeConfig.pattern,
2211
- entrypoint: PAGE_HANDLER_PATH,
2212
- prerender: routeConfig.prerender
2213
- });
2214
- }
2215
- if (command !== "dev") return;
2216
- updateConfig({ vite: {
2217
- define: {
2218
- "import.meta.env.CONLOCA_CONTENT_ROOT": JSON.stringify(options.contentRoot),
2219
- "import.meta.env.CONLOCA_CANVAS_DIR": JSON.stringify(options.canvasDir || "./canvas"),
2220
- "import.meta.env.CONLOCA_PUCK_CONFIG_PATH": JSON.stringify(options.puckConfigPath),
2221
- "import.meta.env.CONLOCA_ASSETS_PATH": JSON.stringify(options.assetsPath || ""),
2222
- "import.meta.env.CONLOCA_BLOCK_PREVIEW_ROUTE": JSON.stringify(options.blockPreviewRoute || "/"),
2223
- "import.meta.env.CONLOCA_EDITOR_CSS": JSON.stringify(options.editorCSS || ""),
2224
- "import.meta.env.CONLOCA_LOCALES": JSON.stringify(options.locales?.list ?? null),
2225
- "import.meta.env.CONLOCA_DEFAULT_LOCALE": JSON.stringify(options.locales?.defaultLocale || "")
2226
- },
2227
- optimizeDeps: {
2228
- exclude: [options.puckConfigPath],
2229
- include: [
2230
- "react",
2231
- "react-dom",
2232
- "react-dom/client",
2233
- "react/jsx-runtime",
2234
- "react/jsx-dev-runtime",
2235
- "@mdxeditor/editor",
2236
- "@puckeditor/core",
2237
- "@tanstack/react-query",
2238
- "@tanstack/react-query-devtools",
2239
- "react-router-dom",
2240
- "@radix-ui/react-dialog",
2241
- "@radix-ui/react-select",
2242
- "lucide-react",
2243
- "clsx",
2244
- "tailwind-merge",
2245
- "zod",
2246
- "yaml",
2247
- "nanoid",
2248
- "sort-keys",
2249
- "@mdx-js/mdx",
2250
- "remark-frontmatter",
2251
- "remark-gfm",
2252
- "remark-mdx-frontmatter"
2253
- ]
2254
- },
2255
- plugins: [
2256
- {
2257
- name: "conloca-resolve-normalizer",
2258
- enforce: "pre",
2259
- async resolveId(source, importer) {
2260
- if (!source.startsWith("@conloca/")) return null;
2261
- if (!importer || importer.startsWith(astroRoot)) return null;
2262
- if (importer.startsWith("\0")) return null;
2263
- return await this.resolve(source, join(astroRoot, "_resolveAnchor.js"), { skipSelf: true });
2264
- }
2265
- },
2266
- {
2267
- name: "conloca-dev-virtual-modules",
2268
- resolveId(id) {
2269
- if (id === VIRTUAL_CONFIG_MODULE) return RESOLVED_VIRTUAL_CONFIG;
2270
- if (id === `${cmsRoute}/puck-entry.js`) return id;
2271
- if (id === `${cmsRoute}/content-listener.js`) return id;
2272
- if (id === `${cmsRoute}/schemas-entry.js`) return id;
2273
- if (id === `${cmsRoute}/site-styles.js`) return id;
2274
- if (id === `${cmsRoute}/editor-styles.js`) return id;
2275
- if (id === VIRTUAL_PAGE_API) return RESOLVED_PAGE_API;
2276
- if (id === VIRTUAL_CMS_SPA_ENTRY) return RESOLVED_CMS_SPA_ENTRY;
2277
- if (id === `${cmsRoute}/cms-spa-entry.js`) return RESOLVED_CMS_SPA_ENTRY;
2278
- return null;
2279
- },
2280
- load(id) {
2281
- if (id === RESOLVED_VIRTUAL_CONFIG) return `export default ${JSON.stringify(spaConfig)};`;
2282
- if (id === `${cmsRoute}/puck-entry.js`) {
2283
- const absolutePuckPath = options.puckConfigPath.startsWith(".") ? `/${options.puckConfigPath.slice(2)}` : options.puckConfigPath;
2284
- return puckConfigLoader(absolutePuckPath, cmsSpaDistDir);
2285
- }
2286
- if (id === `${cmsRoute}/content-listener.js`) return contentChangeListener();
2287
- if (id === `${cmsRoute}/schemas-entry.js`) {
2288
- if (options.schemasPath) {
2289
- const absoluteSchemasPath = options.schemasPath.startsWith(".") ? `/${options.schemasPath.slice(2)}` : options.schemasPath;
2290
- return schemasLoader(absoluteSchemasPath, cmsSpaDistDir);
2291
- }
2292
- return "export default {};";
2293
- }
2294
- if (id === `${cmsRoute}/site-styles.js`) {
2295
- if (options.siteStyles) {
2296
- const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];
2297
- return siteStylesLoader(paths, cmsSpaDistDir);
2298
- }
2299
- return "export default {};";
2300
- }
2301
- if (id === `${cmsRoute}/editor-styles.js`) {
2302
- if (options.editorStyles) {
2303
- const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];
2304
- return editorStylesLoader(paths, cmsSpaDistDir);
2305
- }
2306
- return "export default {};";
2307
- }
2308
- if (id === RESOLVED_PAGE_API) return generatePageApiModule({
2309
- contentRoot: options.contentRoot,
2310
- canvasDir: options.canvasDir || "./canvas",
2311
- siteName: resolvedRoutingConfig?.siteName ?? "default",
2312
- locale: resolvedRoutingConfig?.locale ?? "en"
2313
- });
2314
- if (id === RESOLVED_CMS_SPA_ENTRY) {
2315
- let cmsSpaImport;
2316
- if (cmsSpaDir) {
2317
- const realSrcMainPath = join(cmsSpaDir, "src", "main.tsx");
2318
- const linkedSrcMainPath = join(astroRoot, "node_modules", "@conloca", "cms-spa", "src", "main.tsx");
2319
- const srcMainPath = existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath;
2320
- if (existsSync(srcMainPath)) cmsSpaImport = `import '${srcMainPath}';`;
2321
- else cmsSpaImport = "import '@conloca/cms-spa/main';";
2322
- } else cmsSpaImport = "import '@conloca/cms-spa/main';";
2323
- return `
2324
- // Import and execute React refresh preamble first (from @vitejs/plugin-react)
2325
- ${reactRefreshPreamble}
2326
-
2327
- // Import cms-spa through Vite
2328
- // Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
2329
- ${cmsSpaImport}
2330
-
2331
- // Accept HMR
2332
- if (import.meta.hot) {
2333
- import.meta.hot.accept();
2334
- }
2335
- `;
2336
- }
2337
- return null;
2338
- }
2339
- },
2340
- {
2341
- name: "conloca-styles-endpoint",
2342
- apply: "serve",
2343
- configureServer(server) {
2344
- server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());
2345
- }
2346
- },
2347
- {
2348
- name: "conloca-content-wrapper-endpoint",
2349
- apply: "serve",
2350
- configureServer(server) {
2351
- server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());
2352
- }
2353
- },
2354
- {
2355
- name: "conloca-registry-and-render-endpoints",
2356
- apply: "serve",
2357
- configureServer(server) {
2358
- const registry = createRegistryEndpoint({
2359
- contentRoot: resolvedMdxPages ?? options.contentRoot,
2360
- componentFolders: options.mdxComponentFolders ?? ["src/components/mdx"],
2361
- projectRoot: process.cwd()
2362
- });
2363
- server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
2364
- server.middlewares.use(`${cmsRoute}/api/render`, createRenderEndpoint(server, registry.getAllowedSources));
2365
- const onFsChange = (filepath) => {
2366
- if (/\.(mdx|astro|tsx|d\.ts|cms\.json)$/.test(filepath)) registry.invalidate();
2367
- };
2368
- server.watcher.on("add", onFsChange);
2369
- server.watcher.on("change", onFsChange);
2370
- server.watcher.on("unlink", onFsChange);
2371
- }
2372
- },
2373
- {
2374
- name: "conloca-content-watcher",
2375
- async configureServer(server) {
2376
- const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();
2377
- const contentApi = await createContentAPI({
2378
- contentRoot: options.contentRoot,
2379
- canvasDir: options.canvasDir || "./canvas",
2380
- ...options.locales && {
2381
- availableLocales: options.locales.list,
2382
- defaultLocale: options.locales.defaultLocale
2383
- }
2384
- });
2385
- const { resolve } = await import("node:path");
2386
- const astroRoot = process.cwd();
2387
- const contentAbsolute = resolve(options.contentRoot);
2388
- const canvasAbsolute = resolve(options.canvasDir || "./canvas");
2389
- const foldersToWatch = [];
2390
- if (!contentAbsolute.startsWith(astroRoot)) {
2391
- console.log(`[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`);
2392
- foldersToWatch.push(options.contentRoot);
2393
- } else console.log(`[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`);
2394
- if (!canvasAbsolute.startsWith(astroRoot)) {
2395
- console.log(`[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || "./canvas"}`);
2396
- foldersToWatch.push(options.canvasDir || "./canvas");
2397
- } else console.log(`[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || "./canvas"}`);
2398
- if (foldersToWatch.length > 0) server.watcher.add(foldersToWatch);
2399
- const handlers = createContentWatchHandlers(contentApi, {
2400
- contentRoot: options.contentRoot,
2401
- canvasDir: options.canvasDir || "./canvas",
2402
- ...resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }
2403
- }, server.ws, async (event) => {
2404
- await refreshConlocaContent?.();
2405
- if (event.inMdxRoot) {
2406
- const dotAstroModulesFile = resolve(astroRoot, ".astro", "content-modules.mjs");
2407
- const dotAstroAssetsFile = resolve(astroRoot, ".astro", "content-assets.mjs");
2408
- for (const env of Object.values(server.environments ?? {})) {
2409
- if (!env?.moduleGraph) continue;
2410
- for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {
2411
- const mod = env.moduleGraph.getModuleById(filePath);
2412
- if (!mod) continue;
2413
- const envWithReload = env;
2414
- if (typeof envWithReload.reloadModule === "function") Promise.resolve(envWithReload.reloadModule(mod)).catch(() => void 0);
2415
- else env.moduleGraph.invalidateModule(mod, void 0, Date.now(), true);
2416
- }
2417
- env.hot?.send("astro:content-changed", {});
2418
- }
2419
- }
2420
- });
2421
- server.watcher.on("change", handlers.onChange);
2422
- server.watcher.on("add", handlers.onAdd);
2423
- server.watcher.on("unlink", handlers.onUnlink);
2424
- }
2425
- },
2426
- {
2427
- name: "conloca-suppress-cms-save-reload",
2428
- apply: "serve",
2429
- configureServer(server) {
2430
- let suppressUntil = 0;
2431
- const WINDOW_MS = 2e3;
2432
- const cmsContentPrefix = `${cmsRoute}/api/content`;
2433
- server.middlewares.use((req, _res, next) => {
2434
- if ((req.method === "POST" || req.method === "PUT" || req.method === "PATCH" || req.method === "DELETE") && req.url?.startsWith(cmsContentPrefix)) suppressUntil = Date.now() + WINDOW_MS;
2435
- next();
2436
- });
2437
- const shouldDropDuringWindow = (payload) => {
2438
- if (!payload || typeof payload !== "object") return false;
2439
- const p = payload;
2440
- if (p.type === "full-reload") return true;
2441
- if (p.type === "custom" && p.event === "conloca:content-update") return true;
2442
- return false;
2443
- };
2444
- const patchSend = (target) => {
2445
- if (!target) return;
2446
- const marked = target;
2447
- if (marked.__conlocaPatched) return;
2448
- const origSend = target.send.bind(target);
2449
- target.send = ((payload, ...rest) => {
2450
- if (shouldDropDuringWindow(payload) && Date.now() < suppressUntil) {
2451
- server.config.logger.info(`[conloca] suppressed ${payload.type} during CMS save window`, { timestamp: true });
2452
- return;
2453
- }
2454
- return origSend(payload, ...rest);
2455
- });
2456
- marked.__conlocaPatched = true;
2457
- };
2458
- patchSend(server.environments?.client?.hot);
2459
- patchSend(server.ws);
2460
- }
2461
- }
2462
- ]
2463
- } });
2464
- injectRoute({
2465
- pattern: `${cmsRoute}/[...path]`,
2466
- entrypoint: CMS_HANDLER_PATH,
2467
- prerender: false
2468
- });
2469
- injectRoute({
2470
- pattern: cmsRoute,
2471
- entrypoint: CMS_HANDLER_PATH,
2472
- prerender: false
2473
- });
2474
- },
2475
- "astro:server:setup": ({ logger, refreshContent }) => {
2476
- logger.info(`Conloca CMS available at ${cmsRoute}`);
2477
- let refreshChain = Promise.resolve();
2478
- refreshConlocaContent = async () => {
2479
- if (!refreshContent) return;
2480
- refreshChain = refreshChain.catch(() => void 0).then(async () => {
2481
- await refreshContent({ loaders: ["conloca-loader"] });
2482
- });
2483
- await refreshChain;
2484
- };
2485
- logger.debug("Registering Conloca content refresh handler");
2486
- },
2487
- "astro:routes:resolved": ({ routes, logger }) => {
2488
- if (!resolvedRoutingConfig?.enabled) return;
2489
- const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));
2490
- const conflicts = [];
2491
- for (const route of routes) {
2492
- if (route.origin !== "project") continue;
2493
- const pattern = route.pattern;
2494
- if (injectedPatterns.has(pattern)) conflicts.push({
2495
- injected: pattern,
2496
- fileBased: route.entrypoint || pattern
2497
- });
2498
- }
2499
- if (conflicts.length === 0) return;
2500
- const onConflict = resolvedRoutingConfig.onConflict;
2501
- for (const conflict of conflicts) {
2502
- const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;
2503
- if (onConflict === "error") throw new Error(`[Conloca] ${message}`);
2504
- if (onConflict === "warn") logger.warn(message);
2505
- }
2506
- }
2507
- }
2508
- };
2509
- }
2510
- //#endregion
2511
- export { conlocaCMS, localesFromAstroI18n, localesFromStarlight, scanForHydratableComponents };
2512
-
2513
- //# sourceMappingURL=index.mjs.map