@conloca/astro-cms 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/README.md +259 -247
  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/ts/src/cms-handler.d.ts +18 -0
  21. package/dist/ts/src/cms-handler.d.ts.map +1 -0
  22. package/dist/ts/src/cms-handler.js +245 -0
  23. package/dist/ts/src/cms-handler.js.map +1 -0
  24. package/dist/ts/src/collections.d.ts +160 -0
  25. package/dist/ts/src/collections.d.ts.map +1 -0
  26. package/dist/ts/src/collections.js +170 -0
  27. package/dist/ts/src/collections.js.map +1 -0
  28. package/dist/ts/src/components/HydrationWrapper.d.ts +18 -0
  29. package/dist/ts/src/components/HydrationWrapper.d.ts.map +1 -0
  30. package/dist/ts/src/components/HydrationWrapper.js +22 -0
  31. package/dist/ts/src/components/HydrationWrapper.js.map +1 -0
  32. package/dist/ts/src/components/RenderWithFragments.d.ts +27 -0
  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/ts/src/components/RenderWithHydration.d.ts +21 -0
  37. package/dist/ts/src/components/RenderWithHydration.d.ts.map +1 -0
  38. package/dist/ts/src/components/RenderWithHydration.js +39 -0
  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 +18 -0
  45. package/dist/ts/src/discovery/astro-frontmatter.d.ts.map +1 -0
  46. package/dist/ts/src/discovery/astro-frontmatter.js +25 -0
  47. package/dist/ts/src/discovery/astro-frontmatter.js.map +1 -0
  48. package/dist/ts/src/discovery/discover.d.ts +43 -0
  49. package/dist/ts/src/discovery/discover.d.ts.map +1 -0
  50. package/dist/ts/src/discovery/discover.js +87 -0
  51. package/dist/ts/src/discovery/discover.js.map +1 -0
  52. package/dist/ts/src/discovery/extract-props-ts.d.ts +41 -0
  53. package/dist/ts/src/discovery/extract-props-ts.d.ts.map +1 -0
  54. package/dist/ts/src/discovery/extract-props-ts.js +232 -0
  55. package/dist/ts/src/discovery/extract-props-ts.js.map +1 -0
  56. package/dist/ts/src/discovery/merge-registry.d.ts +58 -0
  57. package/dist/ts/src/discovery/merge-registry.d.ts.map +1 -0
  58. package/dist/ts/src/discovery/merge-registry.js +333 -0
  59. package/dist/ts/src/discovery/merge-registry.js.map +1 -0
  60. package/dist/ts/src/discovery/registry-endpoint.d.ts +27 -0
  61. package/dist/ts/src/discovery/registry-endpoint.d.ts.map +1 -0
  62. package/dist/ts/src/discovery/registry-endpoint.js +76 -0
  63. package/dist/ts/src/discovery/registry-endpoint.js.map +1 -0
  64. package/dist/ts/src/discovery/scan-components.d.ts +94 -0
  65. package/dist/ts/src/discovery/scan-components.d.ts.map +1 -0
  66. package/dist/ts/src/discovery/scan-components.js +397 -0
  67. package/dist/ts/src/discovery/scan-components.js.map +1 -0
  68. package/dist/ts/src/discovery/scan-mdx.d.ts +63 -0
  69. package/dist/ts/src/discovery/scan-mdx.d.ts.map +1 -0
  70. package/dist/ts/src/discovery/scan-mdx.js +113 -0
  71. package/dist/ts/src/discovery/scan-mdx.js.map +1 -0
  72. package/dist/ts/src/discovery/scan-overrides.d.ts +71 -0
  73. package/dist/ts/src/discovery/scan-overrides.d.ts.map +1 -0
  74. package/dist/ts/src/discovery/scan-overrides.js +34 -0
  75. package/dist/ts/src/discovery/scan-overrides.js.map +1 -0
  76. package/dist/ts/src/editor-descriptors.d.ts +31 -0
  77. package/dist/ts/src/editor-descriptors.d.ts.map +1 -0
  78. package/dist/ts/src/editor-descriptors.js +84 -0
  79. package/dist/ts/src/editor-descriptors.js.map +1 -0
  80. package/dist/ts/src/handlers/collection-content-api.d.ts +32 -0
  81. package/dist/ts/src/handlers/collection-content-api.d.ts.map +1 -0
  82. package/dist/ts/src/handlers/collection-content-api.js +166 -0
  83. package/dist/ts/src/handlers/collection-content-api.js.map +1 -0
  84. package/dist/ts/src/handlers/page-render-core.d.ts +137 -0
  85. package/dist/ts/src/handlers/page-render-core.d.ts.map +1 -0
  86. package/dist/ts/src/handlers/page-render-core.js +315 -0
  87. package/dist/ts/src/handlers/page-render-core.js.map +1 -0
  88. package/dist/ts/src/hydration.d.ts +4 -0
  89. package/dist/ts/src/hydration.d.ts.map +1 -0
  90. package/dist/ts/src/hydration.js +5 -0
  91. package/dist/ts/src/hydration.js.map +1 -0
  92. package/dist/ts/src/index.d.ts +21 -0
  93. package/dist/ts/src/index.d.ts.map +1 -0
  94. package/dist/ts/src/index.js +45 -0
  95. package/dist/ts/src/index.js.map +1 -0
  96. package/dist/ts/src/internal/declared-collections.d.ts +30 -0
  97. package/dist/ts/src/internal/declared-collections.d.ts.map +1 -0
  98. package/dist/ts/src/internal/declared-collections.js +84 -0
  99. package/dist/ts/src/internal/declared-collections.js.map +1 -0
  100. package/dist/ts/src/internal/page-collection-schema.d.ts +44 -0
  101. package/dist/ts/src/internal/page-collection-schema.d.ts.map +1 -0
  102. package/dist/ts/src/internal/page-collection-schema.js +152 -0
  103. package/dist/ts/src/internal/page-collection-schema.js.map +1 -0
  104. package/dist/ts/src/lib/content-config-guard.d.ts +11 -0
  105. package/dist/ts/src/lib/content-config-guard.d.ts.map +1 -0
  106. package/dist/ts/src/lib/content-config-guard.js +41 -0
  107. package/dist/ts/src/lib/content-config-guard.js.map +1 -0
  108. package/dist/ts/src/lib/hydration-scanner.d.ts +47 -0
  109. package/dist/ts/src/lib/hydration-scanner.d.ts.map +1 -0
  110. package/dist/ts/src/lib/hydration-scanner.js +136 -0
  111. package/dist/ts/src/lib/hydration-scanner.js.map +1 -0
  112. package/dist/{lib/hydration-script.d.mts → ts/src/lib/hydration-script.d.ts} +7 -10
  113. package/dist/ts/src/lib/hydration-script.d.ts.map +1 -0
  114. package/dist/ts/src/lib/hydration-script.js +89 -0
  115. package/dist/ts/src/lib/hydration-script.js.map +1 -0
  116. package/dist/ts/src/lib/hydration-utils.d.ts +51 -0
  117. package/dist/ts/src/lib/hydration-utils.d.ts.map +1 -0
  118. package/dist/ts/src/lib/hydration-utils.js +84 -0
  119. package/dist/ts/src/lib/hydration-utils.js.map +1 -0
  120. package/dist/ts/src/lib/resolve-locale.d.ts +15 -0
  121. package/dist/ts/src/lib/resolve-locale.d.ts.map +1 -0
  122. package/dist/ts/src/lib/resolve-locale.js +16 -0
  123. package/dist/ts/src/lib/resolve-locale.js.map +1 -0
  124. package/dist/ts/src/lib/resolve-site-name.d.ts +8 -0
  125. package/dist/ts/src/lib/resolve-site-name.d.ts.map +1 -0
  126. package/dist/ts/src/lib/resolve-site-name.js +12 -0
  127. package/dist/ts/src/lib/resolve-site-name.js.map +1 -0
  128. package/dist/ts/src/lib/route-utils.d.ts +61 -0
  129. package/dist/ts/src/lib/route-utils.d.ts.map +1 -0
  130. package/dist/ts/src/lib/route-utils.js +96 -0
  131. package/dist/ts/src/lib/route-utils.js.map +1 -0
  132. package/dist/ts/src/lib/routing-config.d.ts +38 -0
  133. package/dist/ts/src/lib/routing-config.d.ts.map +1 -0
  134. package/dist/ts/src/lib/routing-config.js +106 -0
  135. package/dist/ts/src/lib/routing-config.js.map +1 -0
  136. package/dist/ts/src/lib/serialize-props.d.ts +6 -0
  137. package/dist/ts/src/lib/serialize-props.d.ts.map +1 -0
  138. package/dist/ts/src/lib/serialize-props.js +8 -0
  139. package/dist/ts/src/lib/serialize-props.js.map +1 -0
  140. package/dist/ts/src/lib/unknown-components.d.ts +21 -0
  141. package/dist/ts/src/lib/unknown-components.d.ts.map +1 -0
  142. package/dist/ts/src/lib/unknown-components.js +49 -0
  143. package/dist/ts/src/lib/unknown-components.js.map +1 -0
  144. package/dist/ts/src/lib/virtual-module-generators.d.ts +33 -0
  145. package/dist/ts/src/lib/virtual-module-generators.d.ts.map +1 -0
  146. package/dist/ts/src/lib/virtual-module-generators.js +51 -0
  147. package/dist/ts/src/lib/virtual-module-generators.js.map +1 -0
  148. package/dist/{withHydration-HIvO9ysY.d.mts → ts/src/lib/withHydration.d.ts} +7 -11
  149. package/dist/ts/src/lib/withHydration.d.ts.map +1 -0
  150. package/dist/ts/src/lib/withHydration.js +50 -0
  151. package/dist/ts/src/lib/withHydration.js.map +1 -0
  152. package/dist/ts/src/loader.d.ts +27 -0
  153. package/dist/ts/src/loader.d.ts.map +1 -0
  154. package/dist/ts/src/loader.js +118 -0
  155. package/dist/ts/src/loader.js.map +1 -0
  156. package/dist/ts/src/locales-helpers.d.ts +61 -0
  157. package/dist/ts/src/locales-helpers.d.ts.map +1 -0
  158. package/dist/ts/src/locales-helpers.js +50 -0
  159. package/dist/ts/src/locales-helpers.js.map +1 -0
  160. package/dist/ts/src/mime-types.d.ts +3 -0
  161. package/dist/ts/src/mime-types.d.ts.map +1 -0
  162. package/dist/ts/src/mime-types.js +20 -0
  163. package/dist/ts/src/mime-types.js.map +1 -0
  164. package/dist/ts/src/page-feed.d.ts +13 -0
  165. package/dist/ts/src/page-feed.d.ts.map +1 -0
  166. package/dist/ts/src/page-feed.js +20 -0
  167. package/dist/ts/src/page-feed.js.map +1 -0
  168. package/dist/ts/src/page-schemas.d.ts +6 -0
  169. package/dist/ts/src/page-schemas.d.ts.map +1 -0
  170. package/dist/ts/src/page-schemas.js +6 -0
  171. package/dist/ts/src/page-schemas.js.map +1 -0
  172. package/dist/ts/src/path-validation.d.ts +8 -0
  173. package/dist/ts/src/path-validation.d.ts.map +1 -0
  174. package/dist/ts/src/path-validation.js +13 -0
  175. package/dist/ts/src/path-validation.js.map +1 -0
  176. package/dist/ts/src/plugin-spa.d.ts +182 -0
  177. package/dist/ts/src/plugin-spa.d.ts.map +1 -0
  178. package/dist/ts/src/plugin-spa.js +1165 -0
  179. package/dist/ts/src/plugin-spa.js.map +1 -0
  180. package/dist/ts/src/puck-manifest/components-endpoint.d.ts +30 -0
  181. package/dist/ts/src/puck-manifest/components-endpoint.d.ts.map +1 -0
  182. package/dist/ts/src/puck-manifest/components-endpoint.js +54 -0
  183. package/dist/ts/src/puck-manifest/components-endpoint.js.map +1 -0
  184. package/dist/ts/src/puck-manifest/field-projection.d.ts +91 -0
  185. package/dist/ts/src/puck-manifest/field-projection.d.ts.map +1 -0
  186. package/dist/ts/src/puck-manifest/field-projection.js +422 -0
  187. package/dist/ts/src/puck-manifest/field-projection.js.map +1 -0
  188. package/dist/ts/src/puck-manifest/index.d.ts +4 -0
  189. package/dist/ts/src/puck-manifest/index.d.ts.map +1 -0
  190. package/dist/ts/src/puck-manifest/index.js +3 -0
  191. package/dist/ts/src/puck-manifest/index.js.map +1 -0
  192. package/dist/ts/src/puck-manifest/literal.d.ts +163 -0
  193. package/dist/ts/src/puck-manifest/literal.d.ts.map +1 -0
  194. package/dist/ts/src/puck-manifest/literal.js +354 -0
  195. package/dist/ts/src/puck-manifest/literal.js.map +1 -0
  196. package/dist/ts/src/puck-manifest/read-config.d.ts +42 -0
  197. package/dist/ts/src/puck-manifest/read-config.d.ts.map +1 -0
  198. package/dist/ts/src/puck-manifest/read-config.js +517 -0
  199. package/dist/ts/src/puck-manifest/read-config.js.map +1 -0
  200. package/dist/ts/src/puck-manifest/read-field.d.ts +7 -0
  201. package/dist/ts/src/puck-manifest/read-field.d.ts.map +1 -0
  202. package/dist/ts/src/puck-manifest/read-field.js +11 -0
  203. package/dist/ts/src/puck-manifest/read-field.js.map +1 -0
  204. package/dist/ts/src/puck-manifest/read-wrapper.d.ts +147 -0
  205. package/dist/ts/src/puck-manifest/read-wrapper.d.ts.map +1 -0
  206. package/dist/ts/src/puck-manifest/read-wrapper.js +889 -0
  207. package/dist/ts/src/puck-manifest/read-wrapper.js.map +1 -0
  208. package/dist/ts/src/puck-manifest/reading-budget.d.ts +50 -0
  209. package/dist/ts/src/puck-manifest/reading-budget.d.ts.map +1 -0
  210. package/dist/ts/src/puck-manifest/reading-budget.js +113 -0
  211. package/dist/ts/src/puck-manifest/reading-budget.js.map +1 -0
  212. package/dist/ts/src/puck-manifest/resolve-reference.d.ts +4 -0
  213. package/dist/ts/src/puck-manifest/resolve-reference.d.ts.map +1 -0
  214. package/dist/ts/src/puck-manifest/resolve-reference.js +4 -0
  215. package/dist/ts/src/puck-manifest/resolve-reference.js.map +1 -0
  216. package/dist/ts/src/puck-manifest/source-reference.d.ts +96 -0
  217. package/dist/ts/src/puck-manifest/source-reference.d.ts.map +1 -0
  218. package/dist/ts/src/puck-manifest/source-reference.js +424 -0
  219. package/dist/ts/src/puck-manifest/source-reference.js.map +1 -0
  220. package/dist/ts/src/puck-manifest/syntax.d.ts +29 -0
  221. package/dist/ts/src/puck-manifest/syntax.d.ts.map +1 -0
  222. package/dist/ts/src/puck-manifest/syntax.js +79 -0
  223. package/dist/ts/src/puck-manifest/syntax.js.map +1 -0
  224. package/dist/ts/src/puck-manifest/types.d.ts +145 -0
  225. package/dist/ts/src/puck-manifest/types.d.ts.map +1 -0
  226. package/dist/ts/src/puck-manifest/types.js +2 -0
  227. package/dist/ts/src/puck-manifest/types.js.map +1 -0
  228. package/dist/ts/src/safe-json-stringify.d.ts +13 -0
  229. package/dist/ts/src/safe-json-stringify.d.ts.map +1 -0
  230. package/dist/ts/src/safe-json-stringify.js +7 -0
  231. package/dist/ts/src/safe-json-stringify.js.map +1 -0
  232. package/dist/ts/src/sandbox-frame-handler.d.ts +19 -0
  233. package/dist/ts/src/sandbox-frame-handler.d.ts.map +1 -0
  234. package/dist/ts/src/sandbox-frame-handler.js +27 -0
  235. package/dist/ts/src/sandbox-frame-handler.js.map +1 -0
  236. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts +73 -0
  237. package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  238. package/dist/ts/src/site-styles/content-wrapper-endpoint.js +224 -0
  239. package/dist/ts/src/site-styles/content-wrapper-endpoint.js.map +1 -0
  240. package/dist/ts/src/site-styles/render-endpoint.d.ts +50 -0
  241. package/dist/ts/src/site-styles/render-endpoint.d.ts.map +1 -0
  242. package/dist/ts/src/site-styles/render-endpoint.js +264 -0
  243. package/dist/ts/src/site-styles/render-endpoint.js.map +1 -0
  244. package/dist/ts/src/site-styles/styles-endpoint.d.ts +59 -0
  245. package/dist/ts/src/site-styles/styles-endpoint.d.ts.map +1 -0
  246. package/dist/ts/src/site-styles/styles-endpoint.js +156 -0
  247. package/dist/ts/src/site-styles/styles-endpoint.js.map +1 -0
  248. package/dist/ts/src/sitemap-options.d.ts +21 -0
  249. package/dist/ts/src/sitemap-options.d.ts.map +1 -0
  250. package/dist/ts/src/sitemap-options.js +92 -0
  251. package/dist/ts/src/sitemap-options.js.map +1 -0
  252. package/dist/ts/src/tiptap-html-static.d.ts +15 -0
  253. package/dist/ts/src/tiptap-html-static.d.ts.map +1 -0
  254. package/dist/ts/src/tiptap-html-static.js +67 -0
  255. package/dist/ts/src/tiptap-html-static.js.map +1 -0
  256. package/dist/ts/src/types.d.ts +543 -0
  257. package/dist/ts/src/types.d.ts.map +1 -0
  258. package/dist/ts/src/types.js +2 -0
  259. package/dist/ts/src/types.js.map +1 -0
  260. package/dist/virtual-modules.d.ts +74 -0
  261. package/node/content.ts +14 -0
  262. package/node/index.ts +22 -0
  263. package/package.json +198 -56
  264. package/src/asset-ref-base.ts +48 -0
  265. package/src/checks.ts +10 -0
  266. package/src/cms-handler.ts +280 -0
  267. package/src/collections.ts +262 -0
  268. package/src/components/HydrationWrapper.tsx +41 -0
  269. package/src/components/RenderWithFragments.tsx +204 -0
  270. package/src/components/RenderWithHydration.tsx +55 -0
  271. package/src/components.ts +3 -0
  272. package/src/discovery/astro-frontmatter.ts +24 -0
  273. package/src/discovery/discover.ts +108 -0
  274. package/src/discovery/extract-props-ts.ts +255 -0
  275. package/src/discovery/merge-registry.ts +411 -0
  276. package/src/discovery/registry-endpoint.ts +80 -0
  277. package/src/discovery/scan-components.ts +458 -0
  278. package/src/discovery/scan-mdx.ts +190 -0
  279. package/src/discovery/scan-overrides.ts +92 -0
  280. package/src/editor-descriptors.ts +96 -0
  281. package/src/env.d.ts +31 -0
  282. package/src/handlers/collection-content-api.ts +196 -0
  283. package/src/handlers/page-handler.astro +320 -0
  284. package/src/handlers/page-render-core.ts +456 -0
  285. package/src/hydration.ts +7 -0
  286. package/src/index.ts +111 -0
  287. package/src/internal/acorn-default.mjs +37 -0
  288. package/src/internal/declared-collections.ts +98 -0
  289. package/src/internal/page-collection-schema.ts +210 -0
  290. package/src/lib/content-config-guard.ts +48 -0
  291. package/src/lib/hydration-scanner.ts +176 -0
  292. package/src/lib/hydration-script.ts +126 -0
  293. package/src/lib/hydration-utils.ts +120 -0
  294. package/src/lib/resolve-locale.ts +22 -0
  295. package/src/lib/resolve-site-name.ts +10 -0
  296. package/src/lib/route-utils.ts +106 -0
  297. package/src/lib/routing-config.ts +126 -0
  298. package/src/lib/serialize-props.ts +7 -0
  299. package/src/lib/unknown-components.ts +64 -0
  300. package/src/lib/virtual-module-generators.ts +58 -0
  301. package/src/lib/withHydration.ts +71 -0
  302. package/src/loader.ts +145 -0
  303. package/src/locales-helpers.ts +68 -0
  304. package/src/mime-types.ts +19 -0
  305. package/src/page-feed.ts +26 -0
  306. package/src/page-schemas.ts +19 -0
  307. package/src/path-validation.ts +13 -0
  308. package/src/plugin-spa.ts +1480 -0
  309. package/src/puck-manifest/components-endpoint.ts +55 -0
  310. package/src/puck-manifest/field-projection.ts +510 -0
  311. package/src/puck-manifest/index.ts +3 -0
  312. package/src/puck-manifest/literal.ts +459 -0
  313. package/src/puck-manifest/read-config.ts +577 -0
  314. package/src/puck-manifest/read-field.ts +19 -0
  315. package/src/puck-manifest/read-wrapper.ts +1056 -0
  316. package/src/puck-manifest/reading-budget.ts +127 -0
  317. package/src/puck-manifest/resolve-reference.ts +9 -0
  318. package/src/puck-manifest/source-reference.ts +484 -0
  319. package/src/puck-manifest/syntax.ts +104 -0
  320. package/src/puck-manifest/types.ts +139 -0
  321. package/src/safe-json-stringify.ts +17 -0
  322. package/src/sandbox-frame-handler.ts +31 -0
  323. package/src/site-styles/content-wrapper-endpoint.ts +327 -0
  324. package/src/site-styles/render-endpoint.ts +331 -0
  325. package/src/site-styles/styles-endpoint.ts +184 -0
  326. package/src/sitemap-options.ts +115 -0
  327. package/src/tiptap-html-static.ts +84 -0
  328. package/{dist/types-CVQNmPxF.d.mts → src/types.ts} +232 -79
  329. package/src/virtual-modules.d.ts +74 -0
  330. package/dist/collections.d.mts +0 -36
  331. package/dist/collections.d.mts.map +0 -1
  332. package/dist/collections.mjs +0 -65
  333. package/dist/collections.mjs.map +0 -1
  334. package/dist/components.d.mts +0 -46
  335. package/dist/components.d.mts.map +0 -1
  336. package/dist/components.mjs +0 -226
  337. package/dist/components.mjs.map +0 -1
  338. package/dist/hydration-scanner-B0NjYkZ_.mjs +0 -109
  339. package/dist/hydration-scanner-B0NjYkZ_.mjs.map +0 -1
  340. package/dist/hydration.d.mts +0 -4
  341. package/dist/hydration.mjs +0 -3
  342. package/dist/index.d.mts +0 -139
  343. package/dist/index.d.mts.map +0 -1
  344. package/dist/index.mjs +0 -66
  345. package/dist/index.mjs.map +0 -1
  346. package/dist/internal/cms-handler.d.mts +0 -26
  347. package/dist/internal/cms-handler.d.mts.map +0 -1
  348. package/dist/internal/cms-handler.mjs +0 -267
  349. package/dist/internal/cms-handler.mjs.map +0 -1
  350. package/dist/lib/hydration-script.d.mts.map +0 -1
  351. package/dist/lib/hydration-script.mjs +0 -85
  352. package/dist/lib/hydration-script.mjs.map +0 -1
  353. package/dist/loader-By-AQWHc.mjs +0 -68
  354. package/dist/loader-By-AQWHc.mjs.map +0 -1
  355. package/dist/node/content.d.mts +0 -19
  356. package/dist/node/content.d.mts.map +0 -1
  357. package/dist/node/content.mjs +0 -4
  358. package/dist/node/index.d.mts +0 -52
  359. package/dist/node/index.d.mts.map +0 -1
  360. package/dist/node/index.mjs +0 -753
  361. package/dist/node/index.mjs.map +0 -1
  362. package/dist/serialize-props-Dhv_MnkY.mjs +0 -73
  363. package/dist/serialize-props-Dhv_MnkY.mjs.map +0 -1
  364. package/dist/types-CVQNmPxF.d.mts.map +0 -1
  365. package/dist/withHydration-EzyzBQ-Y.mjs +0 -49
  366. package/dist/withHydration-EzyzBQ-Y.mjs.map +0 -1
  367. package/dist/withHydration-HIvO9ysY.d.mts.map +0 -1
@@ -0,0 +1,1165 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { readSitesConfig } from '@conloca/content-api/node';
5
+ import viteReact from '@vitejs/plugin-react';
6
+ import { searchForWorkspaceRoot } from 'vite';
7
+ import { deriveAssetRefBase } from './asset-ref-base.js';
8
+ import { createRegistryEndpoint } from './discovery/registry-endpoint.js';
9
+ import { EDITOR_DESCRIPTORS_ENV_VAR } from './editor-descriptors.js';
10
+ import { CONTENT_CONFIG_SNIPPET, findContentConfigProblem } from './lib/content-config-guard.js';
11
+ import { deriveComponentPaths, scanForHydratableComponents } from './lib/hydration-scanner.js';
12
+ import { resolveLocale } from './lib/resolve-locale.js';
13
+ import { resolveSiteName } from './lib/resolve-site-name.js';
14
+ import { normalizeRoutingConfig, resolveRouteConfig, toEditorDataBindings } from './lib/routing-config.js';
15
+ import { createComponentsEndpoint, endpointReaderOptions } from './puck-manifest/components-endpoint.js';
16
+ import { createContentWrapperEndpoint } from './site-styles/content-wrapper-endpoint.js';
17
+ import { createRenderEndpoint } from './site-styles/render-endpoint.js';
18
+ import { createStylesEndpoint } from './site-styles/styles-endpoint.js';
19
+ // FRAGILE: viteReact.preambleCode is an undocumented internal API of @vitejs/plugin-react.
20
+ // It provides the React Fast Refresh preamble script needed for HMR in virtual modules.
21
+ // If @vitejs/plugin-react removes or renames this property, the assertion below will
22
+ // fail immediately at dev startup. Test after any @vitejs/plugin-react update.
23
+ if (typeof viteReact.preambleCode !== 'string') {
24
+ throw new Error('@vitejs/plugin-react internal API changed: viteReact.preambleCode is no longer a string. ' +
25
+ 'This is an undocumented API used by @conloca/astro-cms for React Fast Refresh in virtual modules. ' +
26
+ 'Check @vitejs/plugin-react release notes and update the preamble injection logic.');
27
+ }
28
+ const reactRefreshPreamble = viteReact.preambleCode.replace('__BASE__', '/');
29
+ // The preamble is served as a module of its own rather than pasted into each
30
+ // dev virtual module below. A module's static imports all evaluate before its
31
+ // own body runs, so inlined preamble statements always lose to the cms-spa
32
+ // import underneath them — and cms-spa's built entries are plain `.js`, which
33
+ // Vite's React plugin rewrites with Fast Refresh, throwing on evaluation while
34
+ // `window.$RefreshReg$` is still unset. Imported first, the preamble wins.
35
+ const VIRTUAL_REFRESH_PREAMBLE = 'virtual:conloca-react-refresh-preamble';
36
+ const RESOLVED_REFRESH_PREAMBLE = `\0${VIRTUAL_REFRESH_PREAMBLE}`;
37
+ // Get the directory of this module to resolve the copied handler assets.
38
+ // Compiled, this file sits in dist/ts/src/, the copied Astro handler in
39
+ // dist/internal/, and the emitted handler modules right next to this file.
40
+ const __dirname = dirname(fileURLToPath(import.meta.url));
41
+ const PAGE_HANDLER_PATH = join(__dirname, '..', '..', 'internal', 'page-handler.astro');
42
+ const CMS_HANDLER_PATH = join(__dirname, 'cms-handler.js');
43
+ const SANDBOX_FRAME_HANDLER_PATH = join(__dirname, 'sandbox-frame-handler.js');
44
+ const ACORN_DEFAULT_SHIM_PATH = join(__dirname, '..', '..', 'internal', 'acorn-default.mjs');
45
+ const TIPTAP_HTML_SHIM_PATH = join(__dirname, 'tiptap-html-static.js');
46
+ import { generateLayoutModule, generatePuckConfigModule, generateRoutingConfigModule, } from './lib/virtual-module-generators.js';
47
+ // Virtual module for passing config from plugin to route handler
48
+ const VIRTUAL_CONFIG_MODULE = 'virtual:conloca-config';
49
+ const RESOLVED_VIRTUAL_CONFIG = `\0${VIRTUAL_CONFIG_MODULE}`;
50
+ // Virtual module IDs for routing system
51
+ const VIRTUAL_ROUTING_CONFIG = 'virtual:conloca-routing-config';
52
+ const VIRTUAL_LAYOUT = 'virtual:conloca-layout';
53
+ const VIRTUAL_PUCK_CONFIG = 'virtual:conloca-puck-config';
54
+ // Resolved IDs (with \0 prefix to prevent file resolution)
55
+ const RESOLVED_ROUTING_CONFIG = `\0${VIRTUAL_ROUTING_CONFIG}`;
56
+ const RESOLVED_LAYOUT = `\0${VIRTUAL_LAYOUT}`;
57
+ const RESOLVED_PUCK_CONFIG = `\0${VIRTUAL_PUCK_CONFIG}`;
58
+ // Virtual modules for hydration system
59
+ const VIRTUAL_HYDRATION_REGISTRY = 'virtual:conloca-hydration-registry';
60
+ const VIRTUAL_HYDRATION_ENTRY = 'virtual:conloca-hydration-entry';
61
+ const RESOLVED_HYDRATION_REGISTRY = `\0${VIRTUAL_HYDRATION_REGISTRY}`;
62
+ const RESOLVED_HYDRATION_ENTRY = `\0${VIRTUAL_HYDRATION_ENTRY}`;
63
+ /** Vite payloads whose browser-side effects would overwrite the editor's own save update. */
64
+ function dropsEditorSaveUpdate(payload) {
65
+ if (payload.type === 'full-reload')
66
+ return true;
67
+ return payload.type === 'custom' && payload.event === 'conloca:content-update';
68
+ }
69
+ // Virtual module for CMS SPA source loading (dev only)
70
+ const VIRTUAL_CMS_SPA_ENTRY = 'virtual:conloca-cms-spa-entry';
71
+ const RESOLVED_CMS_SPA_ENTRY = `\0${VIRTUAL_CMS_SPA_ENTRY}`;
72
+ async function loadContentApiNode() {
73
+ return import('@conloca/content-api/node');
74
+ }
75
+ // Template for content change listener virtual module
76
+ const contentChangeListener = () => {
77
+ return `
78
+ // Content change listener that uses Vite HMR
79
+ if (import.meta.hot) {
80
+ import.meta.hot.on('conloca:content-update', (data) => {
81
+ console.log('[Conloca CMS] Content updated, invalidating cache:', data);
82
+
83
+ // Get the query client from the global scope and invalidate
84
+ if (window.__QUERY_CLIENT__) {
85
+ window.__QUERY_CLIENT__.invalidateQueries();
86
+ }
87
+ });
88
+ }
89
+
90
+ export default {};
91
+ `;
92
+ };
93
+ // Template for the puck config loader virtual module
94
+ const puckConfigLoader = (absolutePuckPath, cmsSpaDistDir) => {
95
+ // We need to ensure the preamble executes before ANY module evaluation
96
+ // So we'll use a dynamic import after the preamble is set up
97
+ const puckConfigImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/puck-config.js` : '@conloca/cms-spa/puck-config';
98
+ return `
99
+ // React refresh preamble first — it must be the first import, see its module
100
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
101
+
102
+ // Import the setPuckConfig function from cms-spa
103
+ import { setPuckConfig } from '${puckConfigImport}';
104
+
105
+ // Now dynamically import the config after preamble is ready
106
+ const puckConfigPromise = import('${absolutePuckPath}');
107
+
108
+ // Handle the initial load
109
+ puckConfigPromise.then(module => {
110
+ const puckConfig = module.default;
111
+ setPuckConfig(puckConfig);
112
+
113
+ // Hook into React Fast Refresh to detect component updates
114
+ if (window.__registerBeforePerformReactRefresh) {
115
+ window.__registerBeforePerformReactRefresh(async () => {
116
+ // Re-import the config module to get updated components
117
+ const newModule = await import('${absolutePuckPath}');
118
+ setPuckConfig(newModule.default);
119
+ });
120
+ }
121
+ });
122
+
123
+ // Accept HMR for this module itself
124
+ if (import.meta.hot) {
125
+ import.meta.hot.accept();
126
+ }
127
+
128
+ // Export the promise so the module has a default export
129
+ export default puckConfigPromise.then(m => m.default);
130
+ `;
131
+ };
132
+ // Template for the schemas loader virtual module
133
+ const schemasLoader = (absoluteSchemasPath, cmsSpaDistDir) => {
134
+ const pageSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/page-schemas.js` : '@conloca/cms-spa/page-schemas';
135
+ const mdxComponentsImport = cmsSpaDistDir
136
+ ? `${cmsSpaDistDir}/ts/mdx-components.js`
137
+ : '@conloca/cms-spa/mdx-components';
138
+ const dataSchemasImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/data-schemas.js` : '@conloca/cms-spa/data-schemas';
139
+ // The host's schemas file may transitively import React components (the
140
+ // `Editor` field on an MdxComponentDescriptor can be a JSX/TSX
141
+ // component), and so does cms-spa's own mdx-components entry. Vite's React
142
+ // plugin requires the Fast Refresh preamble to run before any such module
143
+ // is evaluated, so we import it first and then dynamically import the
144
+ // schemas file — matching the pattern used by the Puck config loader above.
145
+ return `
146
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
147
+
148
+ import { setPageSchemas } from '${pageSchemasImport}';
149
+ import { installHostAuthoredMdxComponents } from '${mdxComponentsImport}';
150
+ import { setDataSchemas } from '${dataSchemasImport}';
151
+
152
+ const schemasPromise = import('${absoluteSchemasPath}');
153
+
154
+ schemasPromise.then((schemas) => {
155
+ if (schemas.pageSchemas) {
156
+ setPageSchemas(schemas.pageSchemas);
157
+ }
158
+ if (schemas.mdxComponents) {
159
+ // Slotted installer, not setMdxComponents: this module and the SPA's
160
+ // /api/registry fetch settle in either order, and a bare set from the
161
+ // late one would overwrite the other's components.
162
+ installHostAuthoredMdxComponents(schemas.mdxComponents);
163
+ }
164
+ if (schemas.dataSchemas) {
165
+ setDataSchemas(schemas.dataSchemas);
166
+ }
167
+ });
168
+
169
+ if (import.meta.hot) {
170
+ import.meta.hot.accept('${absoluteSchemasPath}', async (newModule) => {
171
+ if (newModule?.pageSchemas) {
172
+ setPageSchemas(newModule.pageSchemas);
173
+ }
174
+ if (newModule?.mdxComponents) {
175
+ installHostAuthoredMdxComponents(newModule.mdxComponents);
176
+ }
177
+ if (newModule?.dataSchemas) {
178
+ setDataSchemas(newModule.dataSchemas);
179
+ }
180
+ });
181
+ }
182
+
183
+ export default schemasPromise;
184
+ `;
185
+ };
186
+ // Template for the site styles loader virtual module.
187
+ //
188
+ // Each CSS file is imported with Vite's `?inline` query so the full CSS
189
+ // pipeline (Tailwind, PostCSS, etc.) runs and returns the processed stylesheet
190
+ // as a string — no `<style>` tag is injected into the CMS admin's parent
191
+ // `<head>`. The strings are handed to `@conloca/cms-spa`'s site-styles
192
+ // registry; the editor's iframe bridge then injects them directly into
193
+ // Puck's preview iframe `<head>`. This keeps host-site CSS out of the CMS
194
+ // chrome and confines it to the intended consumer (the preview).
195
+ const siteStylesLoader = (cssPaths, cmsSpaDistDir) => {
196
+ const imports = cssPaths
197
+ .map((p, i) => {
198
+ const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
199
+ return `import css${i} from '${absolutePath}?inline';`;
200
+ })
201
+ .join('\n');
202
+ const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
203
+ const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/site-styles.js` : '@conloca/cms-spa/site-styles';
204
+ return `
205
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
206
+ ${imports}
207
+ import { setSiteStyles } from '${siteStylesImport}';
208
+
209
+ setSiteStyles([${vars}]);
210
+
211
+ if (import.meta.hot) {
212
+ import.meta.hot.accept();
213
+ }
214
+
215
+ export default {};
216
+ `;
217
+ };
218
+ // Template for the editor styles loader virtual module — same shape as
219
+ // siteStylesLoader but feeds a different registry (`setEditorStyles`),
220
+ // consumed by the MDX editor's `useInjectHostStyles` call. Kept separate
221
+ // from `siteStyles` because the two surfaces have opposite cascade needs;
222
+ // see `packages/cms-spa/src/site-styles.ts` for the rationale.
223
+ const editorStylesLoader = (cssPaths, cmsSpaDistDir) => {
224
+ const imports = cssPaths
225
+ .map((p, i) => {
226
+ const absolutePath = p.startsWith('./') ? `/${p.slice(2)}` : p;
227
+ return `import css${i} from '${absolutePath}?inline';`;
228
+ })
229
+ .join('\n');
230
+ const vars = cssPaths.map((_, i) => `css${i}`).join(', ');
231
+ const siteStylesImport = cmsSpaDistDir ? `${cmsSpaDistDir}/ts/site-styles.js` : '@conloca/cms-spa/site-styles';
232
+ return `
233
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
234
+ ${imports}
235
+ import { setEditorStyles } from '${siteStylesImport}';
236
+
237
+ setEditorStyles([${vars}]);
238
+
239
+ if (import.meta.hot) {
240
+ import.meta.hot.accept();
241
+ }
242
+
243
+ export default {};
244
+ `;
245
+ };
246
+ /**
247
+ * Whether a resolved package directory came from the registry rather than from
248
+ * a workspace. @conloca/cms-spa ships its sources so source maps resolve, so
249
+ * the files on disk no longer tell the two apart — the location does. Node
250
+ * resolves symlinks, so a registry install always sits under a node_modules
251
+ * directory (hoisted `<consumer>/node_modules/@conloca/cms-spa`, or isolated
252
+ * `…/node_modules/.bun/…/node_modules/@conloca/cms-spa`), while a workspace
253
+ * package or a cross-repo `bun link` resolves to its own checkout.
254
+ */
255
+ export function isRegistryInstall(packageDir) {
256
+ return packageDir.split(/[\\/]/).includes('node_modules');
257
+ }
258
+ export function conlocaCMS(options) {
259
+ const cmsRoute = options.route || '/__cms';
260
+ // Resolve @conloca/cms-spa package directory for absolute imports in virtual
261
+ // module templates. Bare specifiers like '@conloca/cms-spa/puck-config'
262
+ // resolve from the Vite project root, which works when deps are hoisted
263
+ // (npm consumers) but fails with isolated linkers (e.g. bun). Using the
264
+ // resolved absolute path bypasses the project-root lookup entirely.
265
+ let cmsSpaDir;
266
+ try {
267
+ const pkgUrl = import.meta.resolve('@conloca/cms-spa/package.json');
268
+ cmsSpaDir = dirname(pkgUrl.startsWith('file://') ? fileURLToPath(pkgUrl) : pkgUrl);
269
+ }
270
+ catch {
271
+ // Package not resolvable — virtual modules will fall back to bare specifiers
272
+ }
273
+ const cmsSpaDistDir = cmsSpaDir ? join(cmsSpaDir, 'dist') : undefined;
274
+ // Normalize routing config and resolve defaults
275
+ // Pass top-level layout to enable routing when layout provided without explicit routing config
276
+ const routingConfig = normalizeRoutingConfig(options.routing, options.layout);
277
+ // Always derive component paths - auto-discover from puckConfigPath + extend with explicit paths
278
+ // Scanner handles missing directories gracefully (fast-glob returns empty array)
279
+ const componentPaths = deriveComponentPaths(options.puckConfigPath, options.componentPaths);
280
+ // Scan for hydratable components - this promise is awaited in the virtual module loader
281
+ const hydrationDiscoveriesPromise = scanForHydratableComponents(componentPaths, process.cwd()).then((discoveries) => {
282
+ if (discoveries.length > 0) {
283
+ console.log(`[Conloca] Found ${discoveries.length} hydratable component(s)`);
284
+ }
285
+ return discoveries;
286
+ });
287
+ // Build resolved routing config with all defaults applied
288
+ let resolvedRoutingConfig;
289
+ // The site's final output mode, read at config:done because integrations
290
+ // that run after this one may still switch it. The duplicate-route-name check
291
+ // below keys on it.
292
+ let outputMode;
293
+ if (routingConfig?.enabled !== false && routingConfig) {
294
+ const resolvedRoutes = {};
295
+ for (const [name, config] of Object.entries(routingConfig.routes || {})) {
296
+ resolvedRoutes[name] = resolveRouteConfig(config);
297
+ }
298
+ resolvedRoutingConfig = {
299
+ enabled: routingConfig.enabled ?? true,
300
+ routes: resolvedRoutes,
301
+ fallback: routingConfig.fallback ?? '404',
302
+ onConflict: routingConfig.onConflict ?? 'warn',
303
+ // Both provisional. sites.json cannot be read here — integration
304
+ // construction is synchronous — so `astro:config:setup` below
305
+ // re-resolves them against the declared sites before any consumer
306
+ // loads. See `resolveSiteName` and `resolveLocale`.
307
+ siteName: routingConfig.siteName ?? 'default',
308
+ locale: routingConfig.locale ?? 'en',
309
+ };
310
+ }
311
+ // SPA config passed to route handler via virtual module
312
+ // This is only served in dev mode (CMS admin is dev-only), so enableDevtools defaults to true
313
+ // `mdxPagesEnabled` and `resolvedMdxPages` start uninitialized; the
314
+ // `astro:config:setup` hook reads sites.json (the canonical home for
315
+ // per-site `mdxPages` paths) and mutates them before any virtual
316
+ // module load fires — `load(id)` runs at request time, after the
317
+ // hook completes.
318
+ const spaConfig = {
319
+ basename: cmsRoute,
320
+ apiBaseUrl: `${cmsRoute}/api`,
321
+ siteBaseUrl: options.siteBaseUrl,
322
+ enableDevtools: options.enableDevtools ?? true,
323
+ queryClientOptions: options.queryClientOptions,
324
+ schemasPath: options.schemasPath,
325
+ projectRoot: process.cwd(),
326
+ templates: options.templates,
327
+ // True when at least one site in sites.json declares an `mdxPages`
328
+ // path. Drives the "Document page" option in the create-page dialog.
329
+ // Initialized in the `astro:config:setup` hook below.
330
+ mdxPagesEnabled: false,
331
+ // Forward the locale list so the SPA stops hardcoding en/nl/fr in
332
+ // the create-page dialog. The integration receives this from the
333
+ // top-level `locales` option, which can in turn be produced by
334
+ // `localesFromAstroI18n` / `localesFromStarlight`.
335
+ locales: options.locales ? { list: options.locales.list, defaultLocale: options.locales.defaultLocale } : undefined,
336
+ };
337
+ // Resolved mdxPages path, populated from sites.json in the
338
+ // config:setup hook. Used by the registry endpoint and content
339
+ // watcher. `null` means no site declares an `mdxPages` path — .mdx
340
+ // files (if any) fall back to living alongside Puck pages.
341
+ let resolvedMdxPages = null;
342
+ // One root for every path this plugin resolves against, so a scan and an
343
+ // endpoint can never disagree about where the project is.
344
+ const projectRoot = process.cwd();
345
+ // Registry scan inputs, resolved ONCE: the dev endpoint below and anything
346
+ // that reads them off the descriptor channel must never disagree about which
347
+ // folders and content root were scanned.
348
+ // `contentRoot` is re-pointed at sites.json's `mdxPages` in config:setup,
349
+ // once that file has been read.
350
+ let registryScan = {
351
+ contentRoot: options.contentRoot,
352
+ componentFolders: options.mdxComponentFolders ?? ['src/components/mdx'],
353
+ projectRoot,
354
+ };
355
+ let refreshConlocaContent;
356
+ return {
357
+ name: '@conloca/astro-cms',
358
+ hooks: {
359
+ 'astro:config:setup': async ({ config, updateConfig, injectRoute, command, logger }) => {
360
+ // Publish the content root for createConlocaCollections(): the
361
+ // content config loads later in this same process, so the contentRoot
362
+ // configured here is the single source of truth. Raw on purpose —
363
+ // FileSystemContentAPI keys its process-wide index cache on the
364
+ // string as-passed, and the dev content watcher uses the raw option;
365
+ // resolving here would split one cache into two and dev refreshes
366
+ // would read stale content.
367
+ process.env.CONLOCA_CONTENT_ROOT = options.contentRoot;
368
+ // Read sites.json — the canonical home for per-site config
369
+ // including the optional `mdxPages` field. Reading it here (once,
370
+ // at integration setup) gives us a single source of truth for
371
+ // the rest of the hook. `readSitesConfig` returns a safe default
372
+ // when the file is missing or malformed.
373
+ const sitesConfig = await readSitesConfig(options.contentRoot);
374
+ // Now that sites.json is known, replace the provisional site name and
375
+ // locale built at construction time. Resolving from the raw options
376
+ // (not the already-defaulted resolved config) is what makes the
377
+ // sites.json fallbacks reachable. Every consumer — the routing
378
+ // virtual module, the editor's data bindings below, and
379
+ // `astro:routes:resolved` — reads them after this, so they all
380
+ // observe the resolved values.
381
+ if (resolvedRoutingConfig) {
382
+ resolvedRoutingConfig.siteName = resolveSiteName(routingConfig?.siteName, sitesConfig.sites);
383
+ resolvedRoutingConfig.locale = resolveLocale(routingConfig?.locale, options.locales?.defaultLocale, resolvedRoutingConfig.siteName, sitesConfig);
384
+ }
385
+ // Pick the first site that declares an `mdxPages` path. Today's
386
+ // integration supports a single `mdxPages` per project;
387
+ // multi-site `mdxPages` is a future expansion (would require
388
+ // fanning the watcher and registry scanner across all roots).
389
+ const firstSiteWithMdxPages = Object.values(sitesConfig.sites).find((s) => s?.mdxPages);
390
+ resolvedMdxPages = firstSiteWithMdxPages?.mdxPages ?? null;
391
+ spaConfig.mdxPagesEnabled = Boolean(resolvedMdxPages);
392
+ // The editor builds each page's data context in the browser from
393
+ // these, the same bindings the published page resolves with.
394
+ spaConfig.dataBindings = resolvedRoutingConfig?.enabled
395
+ ? toEditorDataBindings(resolvedRoutingConfig)
396
+ : undefined;
397
+ registryScan = { ...registryScan, contentRoot: resolvedMdxPages ?? options.contentRoot };
398
+ // Publish the resolved editor descriptors for other integrations in
399
+ // this build (see EDITOR_DESCRIPTORS_ENV_VAR): they read the same
400
+ // descriptors dev loads from `schemasPath`, `/api/registry` and
401
+ // `virtual:conloca-config` instead of taking these options again.
402
+ // schemasPath is absolutized because a reader may use it as an import
403
+ // specifier.
404
+ const editorDescriptors = {
405
+ ...(options.schemasPath ? { schemasPath: resolve(options.schemasPath) } : {}),
406
+ registry: registryScan,
407
+ ...(options.templates ? { templates: options.templates } : {}),
408
+ ...(spaConfig.dataBindings ? { dataBindings: spaConfig.dataBindings } : {}),
409
+ };
410
+ process.env[EDITOR_DESCRIPTORS_ENV_VAR] = JSON.stringify(editorDescriptors);
411
+ // Auto-inject fs.allow for external contentRoot (dev mode only)
412
+ const astroRoot = process.cwd();
413
+ const contentAbsolute = resolve(options.contentRoot);
414
+ // A missing content root used to produce an empty site that 404'd
415
+ // every page with no hint. Fail the build loudly; in dev (and sync)
416
+ // only warn — a brand-new project boots with an empty site and the
417
+ // CMS creates the directory on first save.
418
+ if (!existsSync(contentAbsolute)) {
419
+ const hint = `Content root not found: ${contentAbsolute}. Create the directory ` +
420
+ '(git cannot track empty folders — add a .gitkeep) or fix contentRoot in conlocaCMS().';
421
+ if (command === 'build') {
422
+ throw new Error(`[Conloca] ${hint}`);
423
+ }
424
+ logger.warn(`${hint} Starting with an empty site.`);
425
+ }
426
+ // A content config that never declares Conloca collections yields
427
+ // an empty Astro collection, so the injected route resolves nothing
428
+ // and every page 404s with no other symptom. Astro exposes no hook
429
+ // that reveals resolved collections, so check the file itself.
430
+ const contentConfigProblem = findContentConfigProblem(astroRoot);
431
+ if (contentConfigProblem) {
432
+ const cause = contentConfigProblem === 'missing'
433
+ ? 'No content config found.'
434
+ : 'Your content config does not declare Conloca collections.';
435
+ const hint = `${cause} Conloca pages will 404 until it does. Add this:\n\n${CONTENT_CONFIG_SNIPPET}\n`;
436
+ if (command === 'build') {
437
+ throw new Error(`[Conloca] ${hint}`);
438
+ }
439
+ logger.warn(hint);
440
+ }
441
+ // Every image the editor picks is stored under this base and served
442
+ // as-is by the published site. Derived in build too, so a media
443
+ // folder the site cannot serve fails there as well as in dev.
444
+ if (options.assetsPath) {
445
+ spaConfig.assetRefBase = deriveAssetRefBase(options.assetsPath, config.publicDir, config.base);
446
+ }
447
+ if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {
448
+ logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
449
+ updateConfig({
450
+ vite: {
451
+ server: {
452
+ fs: {
453
+ allow: [
454
+ searchForWorkspaceRoot(process.cwd()), // Preserve Vite default
455
+ contentAbsolute,
456
+ ],
457
+ },
458
+ },
459
+ },
460
+ });
461
+ }
462
+ // @puckeditor/core (and its zustand dependency) must always go through Vite's
463
+ // SSR resolver, in dev AND build. SSR-external modules are require()'d directly
464
+ // by Node, bypassing Vite's resolver — and `resolve.dedupe` below — entirely,
465
+ // which risks pulling in a stray React copy from outside the workspace.
466
+ const alwaysSsrNoExternal = ['@puckeditor/core'];
467
+ // In dev, linked workspace packages also need to be bundled so React resolves
468
+ // through Vite and HMR works from source (build mode uses their compiled dist output).
469
+ const devOnlySsrNoExternal = [/^@conloca\//];
470
+ const serverOnlyExternal = [
471
+ '@conloca/content-api',
472
+ '@conloca/content-api/node',
473
+ '@conloca/content-api/reader',
474
+ '@conloca/content-api/schemas',
475
+ '@conloca/mdx',
476
+ '@conloca/mdx/node',
477
+ ];
478
+ updateConfig({
479
+ vite: {
480
+ ssr: {
481
+ noExternal: command === 'dev' ? [...devOnlySsrNoExternal, ...alwaysSsrNoExternal] : alwaysSsrNoExternal,
482
+ // Keep Node-only content packages (content-api, mdx) external so SSR
483
+ // builds do not try to bundle their server-only surfaces.
484
+ external: serverOnlyExternal,
485
+ },
486
+ resolve: {
487
+ // Dedupe React to avoid multiple instances when CMS SPA source is
488
+ // loaded from a workspace sibling package. Only list packages the
489
+ // consumer project declares directly — with bun's isolated linker,
490
+ // transitive deps (e.g. @tanstack/react-query) live in the owning
491
+ // package's node_modules and must NOT be forced to resolve from the
492
+ // consumer root (which would fail).
493
+ dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
494
+ alias: [
495
+ // Puck's richtext field render imports @tiptap/html. Its browser
496
+ // build throws off-browser ("generateHTML can only be used in a
497
+ // browser environment"), and its /server build fakes a browser
498
+ // with happy-dom — whose Window constructor reaches for
499
+ // node:vm's Script.runInContext, a stub on workerd, so every
500
+ // richtext section died there with "The 'contextifiedObject'
501
+ // argument must be an vm.Context". Both specifiers resolve to a
502
+ // shim that writes the markup as a string, with no DOM and no
503
+ // vm, so the same output comes out on every engine.
504
+ { find: /^@tiptap\/html(\/server)?$/, replacement: TIPTAP_HTML_SHIM_PATH },
505
+ ],
506
+ },
507
+ // react-dom@19 ships ./server as CJS under the workerd exports
508
+ // condition; without pre-bundling, the Cloudflare adapter's type-gen
509
+ // phase evaluates it raw in workerd ("require is not defined").
510
+ // Inert for Node builds.
511
+ optimizeDeps: { include: ['react-dom/server'] },
512
+ // Virtual modules for routing - needed in both dev and build
513
+ plugins: [
514
+ // Public page rendering should use Puck's server entry, not the full editor.
515
+ // The full editor pulls client-only store code into Astro prerendering.
516
+ {
517
+ name: 'conloca-puck-ssr-render-alias',
518
+ enforce: 'pre',
519
+ async resolveId(id, importer, options) {
520
+ if (id === '@puckeditor/core' && options?.ssr) {
521
+ return this.resolve('@puckeditor/core/rsc', importer, { ...options, skipSelf: true });
522
+ }
523
+ return null;
524
+ },
525
+ },
526
+ // Alias acorn to a default+named shim only during SSR (page
527
+ // builds). Must NOT apply to the browser bundle, and must NOT
528
+ // apply to the shim's own `import ... from 'acorn'` — that
529
+ // static import has to reach the real package, not recurse.
530
+ {
531
+ name: 'conloca-acorn-ssr-alias',
532
+ enforce: 'pre',
533
+ resolveId(id, importer, options) {
534
+ if (id === 'acorn' && options?.ssr && !importer?.endsWith('acorn-default.mjs')) {
535
+ return ACORN_DEFAULT_SHIM_PATH;
536
+ }
537
+ return null;
538
+ },
539
+ },
540
+ {
541
+ name: 'conloca-routing-virtual-modules',
542
+ resolveId(id) {
543
+ // Routing virtual modules (work in both dev and build)
544
+ if (id === VIRTUAL_ROUTING_CONFIG) {
545
+ return RESOLVED_ROUTING_CONFIG;
546
+ }
547
+ if (id === VIRTUAL_LAYOUT) {
548
+ return RESOLVED_LAYOUT;
549
+ }
550
+ if (id === VIRTUAL_PUCK_CONFIG) {
551
+ return RESOLVED_PUCK_CONFIG;
552
+ }
553
+ // Hydration virtual modules
554
+ if (id === VIRTUAL_HYDRATION_REGISTRY) {
555
+ return RESOLVED_HYDRATION_REGISTRY;
556
+ }
557
+ if (id === VIRTUAL_HYDRATION_ENTRY) {
558
+ return RESOLVED_HYDRATION_ENTRY;
559
+ }
560
+ return null;
561
+ },
562
+ async load(id) {
563
+ // Routing virtual modules
564
+ if (id === RESOLVED_ROUTING_CONFIG) {
565
+ if (resolvedRoutingConfig) {
566
+ return generateRoutingConfigModule(resolvedRoutingConfig);
567
+ }
568
+ // Return disabled config if routing not configured
569
+ return 'export default { enabled: false, routes: {}, fallback: "404", onConflict: "warn" };';
570
+ }
571
+ if (id === RESOLVED_LAYOUT) {
572
+ return generateLayoutModule(routingConfig);
573
+ }
574
+ if (id === RESOLVED_PUCK_CONFIG) {
575
+ return generatePuckConfigModule(options.puckConfigPath);
576
+ }
577
+ // Hydration virtual modules
578
+ if (id === RESOLVED_HYDRATION_REGISTRY) {
579
+ // Always scan - paths are auto-derived from puckConfigPath
580
+ const discoveries = await hydrationDiscoveriesPromise;
581
+ if (discoveries.length > 0) {
582
+ const entries = discoveries.map((d) => {
583
+ // Convert absolute path to Vite-friendly path
584
+ const relativePath = d.filePath.replace(process.cwd(), '');
585
+ return ` '${d.componentName}': {
586
+ loader: () => import('${relativePath}').then(m => m.${d.componentName}.render),
587
+ strategy: '${d.strategy}',
588
+ }`;
589
+ });
590
+ return `// Generated by @conloca/astro-cms scanner
591
+ export const componentRegistry = {
592
+ ${entries.join(',\n')}
593
+ };`;
594
+ }
595
+ // No hydratable components found - return empty registry
596
+ return 'export const componentRegistry = {};';
597
+ }
598
+ if (id === RESOLVED_HYDRATION_ENTRY) {
599
+ // Generate entry point that imports registry and calls initHydration
600
+ return `import { initHydration } from '@conloca/astro-cms/lib/hydration-script'
601
+ import { componentRegistry } from 'virtual:conloca-hydration-registry'
602
+
603
+ // Auto-initialize hydration when this module loads
604
+ initHydration(componentRegistry)
605
+ `;
606
+ }
607
+ return null;
608
+ },
609
+ },
610
+ ],
611
+ },
612
+ });
613
+ // Content page routes - works in both dev and build
614
+ if (resolvedRoutingConfig?.enabled) {
615
+ for (const [routeName, routeConfig] of Object.entries(resolvedRoutingConfig.routes)) {
616
+ logger.info(`Injecting content route: ${routeConfig.pattern} (${routeName})`);
617
+ injectRoute({
618
+ pattern: routeConfig.pattern,
619
+ entrypoint: PAGE_HANDLER_PATH,
620
+ prerender: routeConfig.prerender,
621
+ });
622
+ }
623
+ }
624
+ // The sandbox frame document ContentSandbox loads for MDX previews.
625
+ // Root-absolute by contract (SANDBOX_FRAME_PATH in @conloca/mdx) and
626
+ // needed wherever the editor runs — anything that serves the editor
627
+ // serves the same path. Injected outside the dev-only block: a
628
+ // production editor build needs the frame too.
629
+ //
630
+ // On-demand by necessity — the response carries the sandbox CSP, which
631
+ // a prerendered file cannot — so injecting it into a fully static site
632
+ // fails that build with NoAdapterInstalled. Such a site has no runtime
633
+ // editor to serve it to; dev serves it whatever the output mode.
634
+ if (command === 'dev' || config.output !== 'static') {
635
+ injectRoute({
636
+ pattern: '/api/v1/mdx/sandbox-frame',
637
+ entrypoint: SANDBOX_FRAME_HANDLER_PATH,
638
+ prerender: false,
639
+ });
640
+ }
641
+ // Only inject CMS admin routes and dev-specific config in dev mode
642
+ if (command !== 'dev')
643
+ return;
644
+ // Pass options via Vite define for API routes
645
+ updateConfig({
646
+ vite: {
647
+ define: {
648
+ 'import.meta.env.CONLOCA_CONTENT_ROOT': JSON.stringify(options.contentRoot),
649
+ 'import.meta.env.CONLOCA_CANVAS_DIR': JSON.stringify(options.canvasDir || './canvas'),
650
+ 'import.meta.env.CONLOCA_PUCK_CONFIG_PATH': JSON.stringify(options.puckConfigPath),
651
+ 'import.meta.env.CONLOCA_ASSETS_PATH': JSON.stringify(options.assetsPath || ''),
652
+ // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are no
653
+ // longer surfaced as env vars — the content-api reads them
654
+ // directly from sites.json under `contentRoot` at request
655
+ // time. See `readSitesConfig()` and `SitesConfig.sites[name].mdxPages`.
656
+ // Default route URL the fragment editor uses for style /
657
+ // wrapper discovery. See `fragmentPreviewRoute` option doc
658
+ // above. `/` is a sane fallback for most layouts.
659
+ 'import.meta.env.CONLOCA_FRAGMENT_PREVIEW_ROUTE': JSON.stringify(options.fragmentPreviewRoute || '/'),
660
+ // Raw CSS the host wants injected into the editor's
661
+ // `conloca-host-preview` layer for visual overrides.
662
+ // See `editorCSS` option doc above for use cases.
663
+ 'import.meta.env.CONLOCA_EDITOR_CSS': JSON.stringify(options.editorCSS || ''),
664
+ // Top-level locales. Vite `define` does literal text
665
+ // substitution, so this inlines as either a JS array or `null`.
666
+ // The runtime handler reads it as-is — no JSON.parse needed.
667
+ 'import.meta.env.CONLOCA_LOCALES': JSON.stringify(options.locales?.list ?? null),
668
+ 'import.meta.env.CONLOCA_DEFAULT_LOCALE': JSON.stringify(options.locales?.defaultLocale || ''),
669
+ },
670
+ optimizeDeps: {
671
+ // Exclude the puck config from optimization to avoid the outdated dep error
672
+ exclude: [options.puckConfigPath],
673
+ // Pre-bundle ALL CMS dependencies upfront to prevent mid-session re-optimization
674
+ // which causes React dual-instance issues when Vite discovers new deps dynamically
675
+ include: [
676
+ // React core - must be pre-bundled together
677
+ 'react',
678
+ 'react-dom',
679
+ 'react-dom/client',
680
+ 'react/jsx-runtime',
681
+ 'react/jsx-dev-runtime',
682
+ // CMS dependencies
683
+ '@mdxeditor/editor',
684
+ '@puckeditor/core',
685
+ '@tanstack/react-query',
686
+ '@tanstack/react-query-devtools',
687
+ 'react-router-dom',
688
+ '@radix-ui/react-dialog',
689
+ '@radix-ui/react-select',
690
+ 'lucide-react',
691
+ 'clsx',
692
+ 'tailwind-merge',
693
+ // Content processing
694
+ 'zod',
695
+ 'yaml',
696
+ 'nanoid',
697
+ 'sort-keys',
698
+ // MDX processing
699
+ '@mdx-js/mdx',
700
+ 'remark-frontmatter',
701
+ 'remark-gfm',
702
+ 'remark-mdx-frontmatter',
703
+ ],
704
+ },
705
+ plugins: [
706
+ // Normalize @conloca/* imports from symlinked source files (bun link).
707
+ // When main.tsx is loaded via /@fs/<real-path>, its @conloca/* imports
708
+ // resolve relative to the real filesystem location, creating duplicate
709
+ // module instances. This plugin re-resolves them from the consumer
710
+ // project root so all @conloca packages use the same module identity.
711
+ {
712
+ name: 'conloca-resolve-normalizer',
713
+ enforce: 'pre',
714
+ async resolveId(source, importer) {
715
+ // Only normalize @conloca/* bare specifiers
716
+ if (!source.startsWith('@conloca/'))
717
+ return null;
718
+ // Only when imported from outside the project (symlinked source files)
719
+ if (!importer || importer.startsWith(astroRoot))
720
+ return null;
721
+ // Skip virtual modules (prefixed with \0)
722
+ if (importer.startsWith('\0'))
723
+ return null;
724
+ // Re-resolve from project root to ensure consumer's node_modules is used
725
+ const resolved = await this.resolve(source, join(astroRoot, '_resolveAnchor.js'), { skipSelf: true });
726
+ return resolved;
727
+ },
728
+ },
729
+ {
730
+ name: 'conloca-dev-virtual-modules',
731
+ resolveId(id) {
732
+ // Dev-only config module for cms-handler.ts
733
+ if (id === VIRTUAL_CONFIG_MODULE) {
734
+ return RESOLVED_VIRTUAL_CONFIG;
735
+ }
736
+ if (id === VIRTUAL_REFRESH_PREAMBLE) {
737
+ return RESOLVED_REFRESH_PREAMBLE;
738
+ }
739
+ if (id === `${cmsRoute}/puck-entry.js`) {
740
+ return id;
741
+ }
742
+ if (id === `${cmsRoute}/content-listener.js`) {
743
+ return id;
744
+ }
745
+ if (id === `${cmsRoute}/schemas-entry.js`) {
746
+ return id;
747
+ }
748
+ if (id === `${cmsRoute}/site-styles.js`) {
749
+ return id;
750
+ }
751
+ if (id === `${cmsRoute}/editor-styles.js`) {
752
+ return id;
753
+ }
754
+ if (id === VIRTUAL_CMS_SPA_ENTRY) {
755
+ return RESOLVED_CMS_SPA_ENTRY;
756
+ }
757
+ if (id === `${cmsRoute}/cms-spa-entry.js`) {
758
+ return RESOLVED_CMS_SPA_ENTRY;
759
+ }
760
+ return null;
761
+ },
762
+ load(id) {
763
+ // Dev-only config module for cms-handler.ts
764
+ if (id === RESOLVED_VIRTUAL_CONFIG) {
765
+ return `export default ${JSON.stringify(spaConfig)};`;
766
+ }
767
+ if (id === RESOLVED_REFRESH_PREAMBLE) {
768
+ return reactRefreshPreamble;
769
+ }
770
+ if (id === `${cmsRoute}/puck-entry.js`) {
771
+ const absolutePuckPath = options.puckConfigPath.startsWith('.')
772
+ ? `/${options.puckConfigPath.slice(2)}`
773
+ : options.puckConfigPath;
774
+ return puckConfigLoader(absolutePuckPath, cmsSpaDistDir);
775
+ }
776
+ if (id === `${cmsRoute}/content-listener.js`) {
777
+ return contentChangeListener();
778
+ }
779
+ if (id === `${cmsRoute}/schemas-entry.js`) {
780
+ if (options.schemasPath) {
781
+ const absoluteSchemasPath = options.schemasPath.startsWith('.')
782
+ ? `/${options.schemasPath.slice(2)}`
783
+ : options.schemasPath;
784
+ return schemasLoader(absoluteSchemasPath, cmsSpaDistDir);
785
+ }
786
+ return 'export default {};';
787
+ }
788
+ if (id === `${cmsRoute}/site-styles.js`) {
789
+ if (options.siteStyles) {
790
+ const paths = Array.isArray(options.siteStyles) ? options.siteStyles : [options.siteStyles];
791
+ return siteStylesLoader(paths, cmsSpaDistDir);
792
+ }
793
+ return 'export default {};';
794
+ }
795
+ if (id === `${cmsRoute}/editor-styles.js`) {
796
+ if (options.editorStyles) {
797
+ const paths = Array.isArray(options.editorStyles) ? options.editorStyles : [options.editorStyles];
798
+ return editorStylesLoader(paths, cmsSpaDistDir);
799
+ }
800
+ return 'export default {};';
801
+ }
802
+ if (id === RESOLVED_CMS_SPA_ENTRY) {
803
+ // Detect whether cms-spa is a workspace checkout (import its
804
+ // source for HMR) or a registry install (import its built
805
+ // entry). Reuses `cmsSpaDir` resolved at plugin setup time.
806
+ let cmsSpaImport;
807
+ if (cmsSpaDir && !isRegistryInstall(cmsSpaDir)) {
808
+ const realSrcMainPath = join(cmsSpaDir, 'src', 'main.tsx');
809
+ // Prefer the consumer-side symlink path when @conloca/cms-spa is
810
+ // linked in from another workspace (e.g. cross-repo `bun link`).
811
+ // Importing via the symlink path keeps `react`/`react-dom`
812
+ // resolving through the consumer's node_modules walk, which
813
+ // prevents duplicate React instances inside the CMS SPA.
814
+ // Same-workspace installs either don't expose this path or
815
+ // point at the same underlying file, so behavior and HMR
816
+ // are preserved.
817
+ const linkedSrcMainPath = join(astroRoot, 'node_modules', '@conloca', 'cms-spa', 'src', 'main.tsx');
818
+ // Workspace mode: import source for HMR
819
+ cmsSpaImport = `import '${existsSync(linkedSrcMainPath) ? linkedSrcMainPath : realSrcMainPath}';`;
820
+ }
821
+ else {
822
+ // npm mode, and the fallback when the package cannot be
823
+ // resolved: import the pre-built SPA mounting entry
824
+ cmsSpaImport = "import '@conloca/cms-spa/main';";
825
+ }
826
+ return `
827
+ // React refresh preamble first — it must be the first import, see its module
828
+ import '${VIRTUAL_REFRESH_PREAMBLE}';
829
+
830
+ // Import cms-spa through Vite
831
+ // Vite will resolve React from its pre-bundled deps (same instance as puck.config.tsx)
832
+ ${cmsSpaImport}
833
+
834
+ // Accept HMR
835
+ if (import.meta.hot) {
836
+ import.meta.hot.accept();
837
+ }
838
+ `;
839
+ }
840
+ return null;
841
+ },
842
+ },
843
+ {
844
+ // Per-page styles endpoint. Fetches the live HTML for the
845
+ // route and returns every `<style>` block and `<link
846
+ // rel="stylesheet">` it lists — the same set of stylesheets
847
+ // the browser paints with.
848
+ name: 'conloca-styles-endpoint',
849
+ apply: 'serve',
850
+ configureServer(server) {
851
+ server.middlewares.use(`${cmsRoute}/api/styles`, createStylesEndpoint());
852
+ },
853
+ },
854
+ {
855
+ // Per-route content-wrapper endpoint. Fetches the live page
856
+ // HTML and returns the host's content-root element shape
857
+ // (`{ tagName, className }`) so the editor can render its
858
+ // contenteditable inside a clone of that wrapper — letting
859
+ // the host's CSS (eg `article.card { background: … }`) paint
860
+ // the editor's content surface naturally, with no per-color
861
+ // bridging.
862
+ name: 'conloca-content-wrapper-endpoint',
863
+ apply: 'serve',
864
+ configureServer(server) {
865
+ server.middlewares.use(`${cmsRoute}/api/content-wrapper`, createContentWrapperEndpoint());
866
+ },
867
+ },
868
+ {
869
+ // Registry + render endpoints are paired: the registry
870
+ // builds the list of legal component sources, and the
871
+ // render endpoint validates every incoming `source`
872
+ // against that list before passing it to ssrLoadModule.
873
+ // Constructing both in one configureServer hook means
874
+ // they share the same memoized scan — no cross-plugin
875
+ // state, no startup-order race.
876
+ //
877
+ // - Registry: scans MDX content for imports + usages and
878
+ // the configured local component folders for
879
+ // `interface Props { ... }`, merges into a single
880
+ // descriptor list, returns it as JSON. The SPA fetches
881
+ // this on mount and seeds `setMdxComponents`,
882
+ // replacing the hand-written `mdx-components.tsx` flow.
883
+ // - Render: renders a single MDX component (Aside,
884
+ // Card, …) via Astro's Container API so the CMS editor
885
+ // can display the real framework markup, paired with
886
+ // the per-page CSS from the styles endpoint above.
887
+ name: 'conloca-registry-and-render-endpoints',
888
+ apply: 'serve',
889
+ configureServer(server) {
890
+ const registry = createRegistryEndpoint(registryScan);
891
+ server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
892
+ server.middlewares.use(`${cmsRoute}/api/render`, createRenderEndpoint(server, registry.getAllowedSources));
893
+ // Invalidate the cached scan whenever an .mdx file or
894
+ // any component file changes. Coarse for now — every
895
+ // change re-scans everything; cheap enough for typical
896
+ // project sizes. `.cms.json` sidecars also trigger
897
+ // invalidation so host overrides apply live without a
898
+ // dev-server restart.
899
+ const onFsChange = (filepath) => {
900
+ if (/\.(mdx|astro|tsx|d\.ts|cms\.json)$/.test(filepath))
901
+ registry.invalidate();
902
+ };
903
+ server.watcher.on('add', onFsChange);
904
+ server.watcher.on('change', onFsChange);
905
+ server.watcher.on('unlink', onFsChange);
906
+ },
907
+ },
908
+ {
909
+ // The Puck component vocabulary: every component the config
910
+ // declares, with its fields, read from source and never
911
+ // executed — so an agent editing a page can find out what it
912
+ // may compose with. A build that publishes the vocabulary
913
+ // reads the same config through the same entry
914
+ // (`./puck-manifest`), never describing components a second
915
+ // way.
916
+ name: 'conloca-components-endpoint',
917
+ apply: 'serve',
918
+ configureServer(server) {
919
+ server.middlewares.use(`${cmsRoute}/api/components`, createComponentsEndpoint(endpointReaderOptions({ puckConfigPath: options.puckConfigPath, projectRoot })));
920
+ },
921
+ },
922
+ {
923
+ name: 'conloca-content-watcher',
924
+ async configureServer(server) {
925
+ const { createContentAPI, createContentWatchHandlers } = await loadContentApiNode();
926
+ // Initialize content API using the extracted function.
927
+ // mdxPages / mdxPagesSite / mdxPagesDefaultLocale are
928
+ // read from sites.json by the content-api itself; we
929
+ // don't pass them here.
930
+ const contentApi = await createContentAPI({
931
+ contentRoot: options.contentRoot,
932
+ canvasDir: options.canvasDir || './canvas',
933
+ ...(options.locales && {
934
+ availableLocales: options.locales.list,
935
+ defaultLocale: options.locales.defaultLocale,
936
+ }),
937
+ });
938
+ // Only add explicit watchers if content is outside the Astro project
939
+ const { resolve } = await import('node:path');
940
+ const astroRoot = process.cwd();
941
+ const contentAbsolute = resolve(options.contentRoot);
942
+ const canvasAbsolute = resolve(options.canvasDir || './canvas');
943
+ const foldersToWatch = [];
944
+ if (!contentAbsolute.startsWith(astroRoot)) {
945
+ console.log(`[Astro Integration] Content outside project, adding to watcher: ${options.contentRoot}`);
946
+ foldersToWatch.push(options.contentRoot);
947
+ }
948
+ else {
949
+ console.log(`[Astro Integration] Content inside project, Vite will watch automatically: ${options.contentRoot}`);
950
+ }
951
+ if (!canvasAbsolute.startsWith(astroRoot)) {
952
+ console.log(`[Astro Integration] Canvas outside project, adding to watcher: ${options.canvasDir || './canvas'}`);
953
+ foldersToWatch.push(options.canvasDir || './canvas');
954
+ }
955
+ else {
956
+ console.log(`[Astro Integration] Canvas inside project, Vite will watch automatically: ${options.canvasDir || './canvas'}`);
957
+ }
958
+ if (foldersToWatch.length > 0) {
959
+ server.watcher.add(foldersToWatch);
960
+ }
961
+ // Set up HMR for content changes using extracted handlers.
962
+ // The watcher uses `mdxPagesRoot` to flag events under
963
+ // the mdx tree (so docs-loader can refresh). The value
964
+ // comes from sites.json via `resolvedMdxPages`.
965
+ const handlers = createContentWatchHandlers(contentApi, {
966
+ contentRoot: options.contentRoot,
967
+ canvasDir: options.canvasDir || './canvas',
968
+ ...(resolvedMdxPages && { mdxPagesRoot: resolvedMdxPages }),
969
+ }, server.ws, async (event) => {
970
+ await refreshConlocaContent?.();
971
+ // Astro 6's content-virtual-mod plugin registers an explicit
972
+ // file watcher on `.astro/data-store.json` only (see
973
+ // dist/content/vite-plugin-content-virtual-mod.js: `devServer.watcher.add(dataStoreFile)`).
974
+ // It does NOT watch the sibling `content-modules.mjs` (file
975
+ // path → render function map). When Starlight's docsLoader
976
+ // adds a new MDX entry at runtime, that file IS rewritten on
977
+ // disk, but Vite's SSR moduleGraph keeps the stale module
978
+ // and `renderEntry` throws UnknownContentCollectionError.
979
+ // Force-reload the file ourselves; `reloadModule` is the
980
+ // Vite API that re-runs the load hook on next SSR import.
981
+ if (event.inMdxRoot) {
982
+ const dotAstroModulesFile = resolve(astroRoot, '.astro', 'content-modules.mjs');
983
+ const dotAstroAssetsFile = resolve(astroRoot, '.astro', 'content-assets.mjs');
984
+ for (const env of Object.values(server.environments ?? {})) {
985
+ if (!env?.moduleGraph)
986
+ continue;
987
+ for (const filePath of [dotAstroModulesFile, dotAstroAssetsFile]) {
988
+ const mod = env.moduleGraph.getModuleById(filePath);
989
+ if (!mod)
990
+ continue;
991
+ const envWithReload = env;
992
+ if (typeof envWithReload.reloadModule === 'function') {
993
+ void Promise.resolve(envWithReload.reloadModule(mod)).catch(() => undefined);
994
+ }
995
+ else {
996
+ env.moduleGraph.invalidateModule(mod, undefined, Date.now(), true);
997
+ }
998
+ }
999
+ env.hot?.send('astro:content-changed', {});
1000
+ }
1001
+ }
1002
+ });
1003
+ server.watcher.on('change', handlers.onChange);
1004
+ server.watcher.on('add', handlers.onAdd);
1005
+ server.watcher.on('unlink', handlers.onUnlink);
1006
+ },
1007
+ },
1008
+ {
1009
+ name: 'conloca-suppress-cms-save-reload',
1010
+ apply: 'serve',
1011
+ configureServer(server) {
1012
+ let suppressUntil = 0;
1013
+ const WINDOW_MS = 2000;
1014
+ const cmsContentPrefix = `${cmsRoute}/api/content`;
1015
+ server.middlewares.use((req, _res, next) => {
1016
+ const isWrite = req.method === 'POST' ||
1017
+ req.method === 'PUT' ||
1018
+ req.method === 'PATCH' ||
1019
+ req.method === 'DELETE';
1020
+ if (isWrite && req.url?.startsWith(cmsContentPrefix)) {
1021
+ suppressUntil = Date.now() + WINDOW_MS;
1022
+ }
1023
+ next();
1024
+ });
1025
+ // During a CMS save window, drop two server→client signals that
1026
+ // would otherwise stomp on the CMS's own optimistic cache updates:
1027
+ //
1028
+ // 1. Vite `full-reload` — emitted by Astro 6.2.1's invalidateDataStore()
1029
+ // in dist/content/vite-plugin-content-virtual-mod.js. The call site
1030
+ // is in a configureServer watcher callback, outside the
1031
+ // handleHotUpdate pipeline, so wrapping hot.send is the only intercept.
1032
+ //
1033
+ // 2. `conloca:content-update` custom event — emitted by
1034
+ // conloca-content-watcher above. The client listener (template at
1035
+ // `contentChangeListener` in this file) reacts by calling
1036
+ // queryClient.invalidateQueries() with NO args, refetching every
1037
+ // query and visibly blinking lists. CMS mutation hooks already do
1038
+ // optimistic setQueryData, so this event is redundant for
1039
+ // CMS-originated writes. External edits (outside the save window)
1040
+ // still pass through normally.
1041
+ const patchedChannels = new WeakSet();
1042
+ const patchSend = (target) => {
1043
+ if (!target || patchedChannels.has(target))
1044
+ return;
1045
+ const origSend = target.send.bind(target);
1046
+ function send(payloadOrEvent, payload) {
1047
+ if (typeof payloadOrEvent === 'string') {
1048
+ origSend(payloadOrEvent, payload);
1049
+ return;
1050
+ }
1051
+ if (dropsEditorSaveUpdate(payloadOrEvent) && Date.now() < suppressUntil) {
1052
+ server.config.logger.info(`[conloca] suppressed ${payloadOrEvent.type} during CMS save window`, { timestamp: true });
1053
+ return;
1054
+ }
1055
+ origSend(payloadOrEvent);
1056
+ }
1057
+ target.send = send;
1058
+ patchedChannels.add(target);
1059
+ };
1060
+ // Astro's content plugin sends `full-reload` via environments.client.hot.
1061
+ // Conloca's content watcher sends custom events via server.ws (legacy API).
1062
+ // Patch both; idempotent per-target via __conlocaPatched.
1063
+ patchSend(server.environments?.client?.hot);
1064
+ patchSend(server.ws);
1065
+ },
1066
+ },
1067
+ ],
1068
+ },
1069
+ });
1070
+ // Inject unified CMS handler for all CMS routes
1071
+ // Single handler validates auth once, then routes to appropriate sub-handler
1072
+ injectRoute({
1073
+ pattern: `${cmsRoute}/[...path]`,
1074
+ entrypoint: CMS_HANDLER_PATH,
1075
+ prerender: false,
1076
+ });
1077
+ // Also handle the root CMS route
1078
+ injectRoute({
1079
+ pattern: cmsRoute,
1080
+ entrypoint: CMS_HANDLER_PATH,
1081
+ prerender: false,
1082
+ });
1083
+ },
1084
+ 'astro:config:done': ({ config }) => {
1085
+ outputMode = config.output;
1086
+ },
1087
+ 'astro:server:setup': ({ logger, refreshContent }) => {
1088
+ logger.info(`Conloca CMS available at ${cmsRoute}`);
1089
+ let refreshChain = Promise.resolve();
1090
+ refreshConlocaContent = async () => {
1091
+ if (!refreshContent) {
1092
+ return;
1093
+ }
1094
+ refreshChain = refreshChain
1095
+ .catch(() => undefined)
1096
+ .then(async () => {
1097
+ await refreshContent({ loaders: ['conloca-loader'] });
1098
+ });
1099
+ await refreshChain;
1100
+ };
1101
+ // Register dev-time content refresh after the Vite server exists.
1102
+ // This keeps Astro collections in sync with Conloca's own file watcher.
1103
+ logger.debug('Registering Conloca content refresh handler');
1104
+ },
1105
+ 'astro:routes:resolved': ({ routes, logger }) => {
1106
+ // Check for route conflicts when routing is enabled
1107
+ if (!resolvedRoutingConfig?.enabled)
1108
+ return;
1109
+ const injectedPatterns = new Set(Object.values(resolvedRoutingConfig.routes).map((r) => r.pattern));
1110
+ // Another integration's route with the SAME NAME as a Conloca route is
1111
+ // fatal, whatever `onConflict` says: routing copes (Astro falls through
1112
+ // a prerendered match to the on-demand twin), but Astro's runtime app
1113
+ // resolves a page's stylesheets by route name and takes the first
1114
+ // match, so the twins swap or lose their styles — silently, and only
1115
+ // in the built site. That app renders every page of a server-output
1116
+ // build (prerendering included) and the on-demand pages of a static
1117
+ // one; fully static generation resolves by route and component, where
1118
+ // twins are harmless, so such a site is left alone. Starlight's docs
1119
+ // route is the usual twin: it is named /[...slug] too. The fix is a
1120
+ // different parameter name.
1121
+ const isConlocaHandler = (route) => route.entrypoint?.endsWith('/internal/page-handler.astro') ?? false;
1122
+ const ownRoutes = routes.filter(isConlocaHandler);
1123
+ for (const route of routes) {
1124
+ if (route.origin !== 'external' || !injectedPatterns.has(route.pattern) || isConlocaHandler(route))
1125
+ continue;
1126
+ const own = ownRoutes.find((candidate) => candidate.pattern === route.pattern);
1127
+ const stylesResolvedByName = outputMode === 'server' || !route.isPrerendered || own?.isPrerendered === false;
1128
+ if (!stylesResolvedByName)
1129
+ continue;
1130
+ throw new Error(`[Conloca] Route '${route.pattern}' is registered by Conloca routing and by ${route.entrypoint}. ` +
1131
+ 'Astro resolves stylesheets by route name, so two routes with the same name lose their styles. ' +
1132
+ "Give the Conloca route a parameter name of its own, e.g. '/[...page]'.");
1133
+ }
1134
+ // Find file-based project routes that conflict with injected routes.
1135
+ const conflicts = [];
1136
+ for (const route of routes) {
1137
+ if (route.origin !== 'project')
1138
+ continue;
1139
+ const pattern = route.pattern;
1140
+ if (injectedPatterns.has(pattern)) {
1141
+ conflicts.push({
1142
+ injected: pattern,
1143
+ fileBased: route.entrypoint || pattern,
1144
+ });
1145
+ }
1146
+ }
1147
+ if (conflicts.length === 0)
1148
+ return;
1149
+ // Handle conflicts based on onConflict setting
1150
+ const onConflict = resolvedRoutingConfig.onConflict;
1151
+ for (const conflict of conflicts) {
1152
+ const message = `Route conflict: '${conflict.injected}' is defined both in ${conflict.fileBased} and injected by Conloca routing. Conloca route will take precedence.`;
1153
+ if (onConflict === 'error') {
1154
+ throw new Error(`[Conloca] ${message}`);
1155
+ }
1156
+ if (onConflict === 'warn') {
1157
+ logger.warn(message);
1158
+ }
1159
+ // 'silent' - do nothing
1160
+ }
1161
+ },
1162
+ },
1163
+ };
1164
+ }
1165
+ //# sourceMappingURL=plugin-spa.js.map