@conloca/cloud-astro 0.0.0-stage → 0.2.2

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 (196) hide show
  1. package/README.md +328 -2
  2. package/dist/src/build-commit.d.ts +19 -0
  3. package/dist/src/build-commit.d.ts.map +1 -0
  4. package/dist/src/build-commit.js +6 -0
  5. package/dist/src/build-commit.js.map +1 -0
  6. package/dist/src/bundle.d.ts +181 -0
  7. package/dist/src/bundle.d.ts.map +1 -0
  8. package/dist/src/bundle.js +413 -0
  9. package/dist/src/bundle.js.map +1 -0
  10. package/dist/src/component-manifest.d.ts +29 -0
  11. package/dist/src/component-manifest.d.ts.map +1 -0
  12. package/dist/src/component-manifest.js +53 -0
  13. package/dist/src/component-manifest.js.map +1 -0
  14. package/dist/src/constants.d.ts +26 -0
  15. package/dist/src/constants.d.ts.map +1 -0
  16. package/dist/src/constants.js +26 -0
  17. package/dist/src/constants.js.map +1 -0
  18. package/dist/src/descriptors.d.ts +25 -0
  19. package/dist/src/descriptors.d.ts.map +1 -0
  20. package/dist/src/descriptors.js +65 -0
  21. package/dist/src/descriptors.js.map +1 -0
  22. package/dist/src/discovery.d.ts +58 -0
  23. package/dist/src/discovery.d.ts.map +1 -0
  24. package/dist/src/discovery.js +133 -0
  25. package/dist/src/discovery.js.map +1 -0
  26. package/dist/src/doctor/checks-live.d.ts +15 -0
  27. package/dist/src/doctor/checks-live.d.ts.map +1 -0
  28. package/dist/src/doctor/checks-live.js +229 -0
  29. package/dist/src/doctor/checks-live.js.map +1 -0
  30. package/dist/src/doctor/checks-offline.d.ts +36 -0
  31. package/dist/src/doctor/checks-offline.d.ts.map +1 -0
  32. package/dist/src/doctor/checks-offline.js +301 -0
  33. package/dist/src/doctor/checks-offline.js.map +1 -0
  34. package/dist/src/doctor/config-scan.d.ts +55 -0
  35. package/dist/src/doctor/config-scan.d.ts.map +1 -0
  36. package/dist/src/doctor/config-scan.js +178 -0
  37. package/dist/src/doctor/config-scan.js.map +1 -0
  38. package/dist/src/doctor/run.d.ts +4 -0
  39. package/dist/src/doctor/run.d.ts.map +1 -0
  40. package/dist/src/doctor/run.js +29 -0
  41. package/dist/src/doctor/run.js.map +1 -0
  42. package/dist/src/doctor/types.d.ts +60 -0
  43. package/dist/src/doctor/types.d.ts.map +1 -0
  44. package/dist/src/doctor/types.js +18 -0
  45. package/dist/src/doctor/types.js.map +1 -0
  46. package/dist/src/doctor.d.ts +9 -0
  47. package/dist/src/doctor.d.ts.map +1 -0
  48. package/dist/src/doctor.js +12 -0
  49. package/dist/src/doctor.js.map +1 -0
  50. package/dist/src/git.d.ts +38 -0
  51. package/dist/src/git.d.ts.map +1 -0
  52. package/dist/src/git.js +43 -0
  53. package/dist/src/git.js.map +1 -0
  54. package/dist/src/index.d.ts +3 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/index.js +7 -0
  57. package/dist/src/index.js.map +1 -0
  58. package/dist/src/integration.d.ts +6 -0
  59. package/dist/src/integration.d.ts.map +1 -0
  60. package/dist/src/integration.js +544 -0
  61. package/dist/src/integration.js.map +1 -0
  62. package/dist/src/message-of.d.ts +3 -0
  63. package/dist/src/message-of.d.ts.map +1 -0
  64. package/dist/src/message-of.js +5 -0
  65. package/dist/src/message-of.js.map +1 -0
  66. package/dist/src/node.d.ts +3 -0
  67. package/dist/src/node.d.ts.map +1 -0
  68. package/dist/src/node.js +4 -0
  69. package/dist/src/node.js.map +1 -0
  70. package/dist/src/package-version.d.ts +7 -0
  71. package/dist/src/package-version.d.ts.map +1 -0
  72. package/dist/src/package-version.js +17 -0
  73. package/dist/src/package-version.js.map +1 -0
  74. package/dist/src/preview/_dispatch.d.ts +55 -0
  75. package/dist/src/preview/_dispatch.d.ts.map +1 -0
  76. package/dist/src/preview/_dispatch.js +72 -0
  77. package/dist/src/preview/_dispatch.js.map +1 -0
  78. package/dist/src/preview/_resolve-opts.d.ts +30 -0
  79. package/dist/src/preview/_resolve-opts.d.ts.map +1 -0
  80. package/dist/src/preview/_resolve-opts.js +73 -0
  81. package/dist/src/preview/_resolve-opts.js.map +1 -0
  82. package/dist/src/preview/banner.d.ts +29 -0
  83. package/dist/src/preview/banner.d.ts.map +1 -0
  84. package/dist/src/preview/banner.js +94 -0
  85. package/dist/src/preview/banner.js.map +1 -0
  86. package/dist/src/preview/content-api.d.ts +110 -0
  87. package/dist/src/preview/content-api.d.ts.map +1 -0
  88. package/dist/src/preview/content-api.js +216 -0
  89. package/dist/src/preview/content-api.js.map +1 -0
  90. package/dist/src/preview/cookie.d.ts +36 -0
  91. package/dist/src/preview/cookie.d.ts.map +1 -0
  92. package/dist/src/preview/cookie.js +59 -0
  93. package/dist/src/preview/cookie.js.map +1 -0
  94. package/dist/src/preview/headers.d.ts +25 -0
  95. package/dist/src/preview/headers.d.ts.map +1 -0
  96. package/dist/src/preview/headers.js +31 -0
  97. package/dist/src/preview/headers.js.map +1 -0
  98. package/dist/src/preview/landing.d.ts +22 -0
  99. package/dist/src/preview/landing.d.ts.map +1 -0
  100. package/dist/src/preview/landing.js +70 -0
  101. package/dist/src/preview/landing.js.map +1 -0
  102. package/dist/src/preview/middleware.d.ts +118 -0
  103. package/dist/src/preview/middleware.d.ts.map +1 -0
  104. package/dist/src/preview/middleware.js +197 -0
  105. package/dist/src/preview/middleware.js.map +1 -0
  106. package/dist/src/preview/preview-path.d.ts +21 -0
  107. package/dist/src/preview/preview-path.d.ts.map +1 -0
  108. package/dist/src/preview/preview-path.js +29 -0
  109. package/dist/src/preview/preview-path.js.map +1 -0
  110. package/dist/src/preview/satteri-workerd.d.ts +17 -0
  111. package/dist/src/preview/satteri-workerd.d.ts.map +1 -0
  112. package/dist/src/preview/satteri-workerd.js +18 -0
  113. package/dist/src/preview/satteri-workerd.js.map +1 -0
  114. package/dist/src/preview/site-middleware.d.ts +69 -0
  115. package/dist/src/preview/site-middleware.d.ts.map +1 -0
  116. package/dist/src/preview/site-middleware.js +160 -0
  117. package/dist/src/preview/site-middleware.js.map +1 -0
  118. package/dist/src/preview/workerd-shim.d.ts +19 -0
  119. package/dist/src/preview/workerd-shim.d.ts.map +1 -0
  120. package/dist/src/preview/workerd-shim.js +33 -0
  121. package/dist/src/preview/workerd-shim.js.map +1 -0
  122. package/dist/src/preview-build.d.ts +71 -0
  123. package/dist/src/preview-build.d.ts.map +1 -0
  124. package/dist/src/preview-build.js +115 -0
  125. package/dist/src/preview-build.js.map +1 -0
  126. package/dist/src/preview.d.ts +6 -0
  127. package/dist/src/preview.d.ts.map +1 -0
  128. package/dist/src/preview.js +12 -0
  129. package/dist/src/preview.js.map +1 -0
  130. package/dist/src/register.d.ts +98 -0
  131. package/dist/src/register.d.ts.map +1 -0
  132. package/dist/src/register.js +103 -0
  133. package/dist/src/register.js.map +1 -0
  134. package/dist/src/repository.d.ts +18 -0
  135. package/dist/src/repository.d.ts.map +1 -0
  136. package/dist/src/repository.js +46 -0
  137. package/dist/src/repository.js.map +1 -0
  138. package/dist/src/site-id.d.ts +18 -0
  139. package/dist/src/site-id.d.ts.map +1 -0
  140. package/dist/src/site-id.js +70 -0
  141. package/dist/src/site-id.js.map +1 -0
  142. package/dist/src/site-middleware.d.ts +18 -0
  143. package/dist/src/site-middleware.d.ts.map +1 -0
  144. package/dist/src/site-middleware.js +47 -0
  145. package/dist/src/site-middleware.js.map +1 -0
  146. package/dist/src/skill.d.ts +26 -0
  147. package/dist/src/skill.d.ts.map +1 -0
  148. package/dist/src/skill.js +67 -0
  149. package/dist/src/skill.js.map +1 -0
  150. package/dist/src/types.d.ts +135 -0
  151. package/dist/src/types.d.ts.map +1 -0
  152. package/dist/src/types.js +2 -0
  153. package/dist/src/types.js.map +1 -0
  154. package/package.json +182 -4
  155. package/src/build-commit.ts +22 -0
  156. package/src/bundle.ts +570 -0
  157. package/src/component-manifest.ts +75 -0
  158. package/src/constants.ts +28 -0
  159. package/src/descriptors.ts +92 -0
  160. package/src/discovery.ts +183 -0
  161. package/src/doctor/checks-live.ts +324 -0
  162. package/src/doctor/checks-offline.ts +325 -0
  163. package/src/doctor/config-scan.ts +205 -0
  164. package/src/doctor/run.ts +39 -0
  165. package/src/doctor/types.ts +71 -0
  166. package/src/doctor.ts +14 -0
  167. package/src/git.ts +66 -0
  168. package/src/index.ts +8 -0
  169. package/src/integration.ts +607 -0
  170. package/src/message-of.ts +4 -0
  171. package/src/node.ts +5 -0
  172. package/src/package-version.ts +16 -0
  173. package/src/preview/_dispatch.ts +105 -0
  174. package/src/preview/_resolve-opts.ts +89 -0
  175. package/src/preview/banner.ts +96 -0
  176. package/src/preview/content-api.ts +293 -0
  177. package/src/preview/cookie.ts +54 -0
  178. package/src/preview/headers.ts +30 -0
  179. package/src/preview/landing.ts +73 -0
  180. package/src/preview/middleware.ts +309 -0
  181. package/src/preview/preview-path.ts +28 -0
  182. package/src/preview/satteri-workerd.ts +24 -0
  183. package/src/preview/site-middleware.ts +210 -0
  184. package/src/preview/workerd-shim.ts +31 -0
  185. package/src/preview-build.ts +147 -0
  186. package/src/preview-handler.astro +55 -0
  187. package/src/preview-handler.d.ts +6 -0
  188. package/src/preview.ts +22 -0
  189. package/src/register.ts +180 -0
  190. package/src/repository.ts +54 -0
  191. package/src/site-id.ts +86 -0
  192. package/src/site-middleware.ts +55 -0
  193. package/src/skill/SKILL.md +69 -0
  194. package/src/skill.ts +66 -0
  195. package/src/types.ts +137 -0
  196. package/src/virtual-modules.d.ts +52 -0
package/src/bundle.ts ADDED
@@ -0,0 +1,570 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import type { TemplateConfig } from '@conloca/astro-cms';
5
+ import type { EditorDataBindings } from '@conloca/content-api';
6
+ import { build, type Plugin } from 'esbuild';
7
+ import { build as buildWithVite, mergeConfig, type UserConfig } from 'vite';
8
+ import { PACKAGE_NAME } from './constants.js';
9
+ import { messageOf } from './message-of.js';
10
+
11
+ /**
12
+ * Modules the editor bundle must NEVER contain. The editor (served from
13
+ * `endpoint`) supplies them at runtime so the site's components
14
+ * execute on the editor's own React instance — a second bundled React breaks
15
+ * hooks/context. `@puckeditor/core` is the puck editor package the site's
16
+ * config builds its component definitions against.
17
+ *
18
+ * KEEP IN SYNC with the modules the editor at the endpoint supplies: the two lists
19
+ * are one contract, so every specifier externalized here needs an entry there
20
+ * or the site's bundle fails bare-specifier resolution in the browser. Each side
21
+ * pins the list in its own tests.
22
+ */
23
+ export const EDITOR_BUNDLE_EXTERNALS = [
24
+ 'react',
25
+ 'react-dom',
26
+ 'react/jsx-runtime',
27
+ 'react/jsx-dev-runtime',
28
+ 'react-dom/client',
29
+ '@puckeditor/core',
30
+ ] as const;
31
+
32
+ /**
33
+ * Asset references inside component stylesheets are never pulled INTO the
34
+ * bundle — inlining would balloon the registered stylesheet and drag binary
35
+ * assets through the hash pipeline. They are instead re-pointed at the
36
+ * deployed site (see `rewriteStylesheetAssetUrls`), because the registered
37
+ * stylesheet is injected as text into the editor's canvas: left as-authored, a
38
+ * root-relative `url(/fonts/x.otf)` would resolve against the EDITOR's origin
39
+ * and 404.
40
+ */
41
+ const STYLESHEET_ASSET_EXTERNALS = [
42
+ '*.woff',
43
+ '*.woff2',
44
+ '*.ttf',
45
+ '*.otf',
46
+ '*.eot',
47
+ '*.png',
48
+ '*.jpg',
49
+ '*.jpeg',
50
+ '*.gif',
51
+ '*.svg',
52
+ '*.webp',
53
+ '*.avif',
54
+ ] as const;
55
+
56
+ /**
57
+ * Cloudflare Pages `_headers` rule that lets the editor load an asset
58
+ * cross-origin. Part of the site-side contract: without it the browser
59
+ * blocks the fetch from the editor's origin. Applied to `/_conloca/*` for the
60
+ * bundle itself, and to the directories the stylesheet's assets live in —
61
+ * webfonts are CORS-gated, so a 200 without this header still renders the
62
+ * fallback face.
63
+ */
64
+ function corsRule(path: string): string {
65
+ return `${path}\n Access-Control-Allow-Origin: *\n`;
66
+ }
67
+
68
+ const BUNDLE_CORS_PATH = '/_conloca/*';
69
+
70
+ /**
71
+ * The named exports the bundle re-exports from the host's schemas module
72
+ * (conlocaCMS `schemasPath`). One list drives the virtual entry's re-export
73
+ * lines, the always-undefined warning absorption, and the all-absent check —
74
+ * three places that must never disagree on a name.
75
+ */
76
+ const SCHEMA_MODULE_EXPORTS = ['pageSchemas', 'dataSchemas', 'mdxComponents'] as const;
77
+
78
+ /** esbuild's per-name notice for a schemas-module export the module doesn't declare (absorbed below). */
79
+ const SCHEMA_EXPORT_ABSENCE = new RegExp(`^Import "(${SCHEMA_MODULE_EXPORTS.join('|')})" will always be undefined\\b`);
80
+
81
+ /**
82
+ * Editor descriptors compiled into the bundle, next to the puck config and
83
+ * the site styles. Sourced from what `conlocaCMS` resolved and published —
84
+ * this package never grows its own option for them.
85
+ */
86
+ export interface EditorBundleDescriptors {
87
+ /**
88
+ * Absolute path of the host's schemas module (conlocaCMS `schemasPath`).
89
+ * Its `pageSchemas` / `dataSchemas` / `mdxComponents` exports are
90
+ * re-exported by the bundle, so the editor at the endpoint reads them off bytes it
91
+ * already hash-verified — no second fetch, no second trust decision.
92
+ */
93
+ schemasPath?: string;
94
+ /**
95
+ * Auto-discovered MDX descriptors (conlocaCMS `mdxComponentFolders`),
96
+ * serialized into the bundle verbatim. Opaque here on purpose: the shape
97
+ * is cms-spa's contract and this package only transports it.
98
+ */
99
+ discoveredMdxComponents?: readonly unknown[];
100
+ /**
101
+ * Page-creation templates (conlocaCMS `templates`), serialized into the
102
+ * bundle verbatim. Typed by the `@conloca/astro-cms` peer, whose
103
+ * `readEditorDescriptors` produced the value this package transports.
104
+ */
105
+ templates?: Record<string, TemplateConfig>;
106
+ /**
107
+ * The routing data bindings (conlocaCMS `routing`), serialized into the
108
+ * bundle verbatim, so the editor at the endpoint builds each page's data context from
109
+ * the same routes the published page resolves with.
110
+ */
111
+ dataBindings?: EditorDataBindings;
112
+ }
113
+
114
+ export interface BundleEditorAssetsInput {
115
+ /** Build output directory (Astro's `dir`, as a filesystem path). */
116
+ dir: string;
117
+ /** The Astro project root, as a filesystem path: siteStyles resolve against it. */
118
+ root: string;
119
+ /** The site's own Vite config (Astro's `config.vite`), which compiles siteStyles. */
120
+ vite: UserConfig;
121
+ /** Entry module of the site's puck config (same option name as @conloca/astro-cms). */
122
+ puckConfigPath: string;
123
+ /**
124
+ * Site CSS for accurate preview rendering (the `siteStyles` option),
125
+ * compiled by the site's own Vite pipeline into the same registered
126
+ * stylesheet AHEAD of the component modules, so component rules keep the
127
+ * final word.
128
+ */
129
+ siteStyles?: string | string[];
130
+ /**
131
+ * Public origin the deployed site answers on (the `publicBaseUrl` option).
132
+ * Root-relative asset URLs in the registered stylesheet are absolutized
133
+ * against it, since that stylesheet is applied inside the editor's canvas
134
+ * rather than on the site. Omitted: URLs stay as authored.
135
+ */
136
+ publicBaseUrl?: string;
137
+ /**
138
+ * Editor descriptors published by conlocaCMS for this build. Absent for a
139
+ * CMS-less build, or when there is nothing to carry (no schemas module,
140
+ * discoverable MDX component, page template or data binding) — in which case
141
+ * the emitted bytes are identical to a pre-descriptor build (no gratuitous
142
+ * hash churn).
143
+ */
144
+ descriptors?: EditorBundleDescriptors;
145
+ /**
146
+ * Extra esbuild plugins for the editor bundle (the `editorBundlePlugins`
147
+ * option), run after the built-in stylesheet compiler: the site's own Vite
148
+ * plugins never see this graph, so a source transform the schemas module or
149
+ * a component needs (e.g. Typia's) has to be supplied in esbuild form.
150
+ */
151
+ plugins?: Plugin[];
152
+ logger: { info(message: string): void; warn(message: string): void };
153
+ }
154
+
155
+ export interface BundledStylesheet {
156
+ /** Site-relative URL of the emitted stylesheet, e.g. `/_conloca/editor-bundle.<hash16>.css`. */
157
+ url: string;
158
+ /** FULL sha-256 hex of the stylesheet bytes — the editor hash-verifies against this. */
159
+ hash: string;
160
+ /** The emitted stylesheet bytes. */
161
+ bytes: Uint8Array;
162
+ }
163
+
164
+ export interface BundleEditorAssetsResult {
165
+ /** Site-relative URL of the emitted bundle, e.g. `/_conloca/editor-bundle.<hash16>.js`. */
166
+ url: string;
167
+ /** FULL sha-256 hex of the bundle bytes — the editor hash-verifies against this. */
168
+ hash: string;
169
+ /** The emitted bundle bytes. */
170
+ bytes: Uint8Array;
171
+ /**
172
+ * Companion stylesheet for the editing canvas (styled canvas):
173
+ * any siteStyles, then the config graph's compiled CSS/SCSS modules.
174
+ * Absent when neither carries styles.
175
+ */
176
+ stylesheet?: BundledStylesheet;
177
+ /**
178
+ * `_headers` paths granted CORS for the stylesheet's own assets, so the
179
+ * mirrored asset set (a deployment that serves the site and the preview from
180
+ * one Cloudflare Worker) can be given the same rules.
181
+ */
182
+ assetCorsPaths: string[];
183
+ }
184
+
185
+ /**
186
+ * Bundles the site's puck config into a browser ESM file plus (when the
187
+ * graph carries styles) a companion stylesheet, both under `<dir>/_conloca/`,
188
+ * content-addressed by the first 16 hex chars of their sha-256, and ensures
189
+ * `<dir>/_headers` carries the CORS rule the editor needs to load them
190
+ * cross-origin.
191
+ *
192
+ * The siteStyles compile first, through the site's own Vite pipeline (see
193
+ * `compileSiteStyles`); one that fails to compile fails the build.
194
+ *
195
+ * Component styles compile in the SAME esbuild pass as the JS: CSS-module
196
+ * class names are hashed consistently across both outputs, so `styles.foo` in
197
+ * a component always matches a selector in the emitted stylesheet. SCSS
198
+ * compiles through `sass`; a component stylesheet that fails to compile is
199
+ * stripped with a warning instead of failing the build (one broken component
200
+ * stylesheet must not cost the site its registration).
201
+ */
202
+ export async function bundleEditorAssets(input: BundleEditorAssetsInput): Promise<BundleEditorAssetsResult> {
203
+ const siteCss = await compileSiteStyles({
204
+ root: input.root,
205
+ vite: input.vite,
206
+ siteStyles: typeof input.siteStyles === 'string' ? [input.siteStyles] : (input.siteStyles ?? []),
207
+ dir: input.dir,
208
+ });
209
+
210
+ const entryPath = resolve(input.puckConfigPath);
211
+ const descriptors = input.descriptors;
212
+ const discovered = descriptors?.discoveredMdxComponents ?? [];
213
+ const virtualEntry = [
214
+ `export { default } from ${JSON.stringify(entryPath)};`,
215
+ // Third bundle leg: editor descriptors ride next to the puck
216
+ // config as named exports. The namespace import is deliberate — an
217
+ // `export { x } from` of a name the host's schemas module doesn't
218
+ // declare fails esbuild, so a partial module cannot fail the
219
+ // site's build; missing names just export undefined.
220
+ ...(descriptors?.schemasPath
221
+ ? [
222
+ `import * as __conlocaSchemas from ${JSON.stringify(resolve(descriptors.schemasPath))};`,
223
+ ...SCHEMA_MODULE_EXPORTS.map((name) => `export const ${name} = __conlocaSchemas.${name};`),
224
+ ]
225
+ : []),
226
+ ...(discovered.length > 0 ? [`export const discoveredMdxComponents = ${JSON.stringify(discovered)};`] : []),
227
+ ...(descriptors?.templates ? [`export const templates = ${JSON.stringify(descriptors.templates)};`] : []),
228
+ ...(descriptors?.dataBindings ? [`export const dataBindings = ${JSON.stringify(descriptors.dataBindings)};`] : []),
229
+ ].join('\n');
230
+
231
+ const result = await build({
232
+ stdin: {
233
+ contents: virtualEntry,
234
+ resolveDir: dirname(entryPath),
235
+ sourcefile: 'conloca-canvas-entry.js',
236
+ loader: 'js',
237
+ },
238
+ bundle: true,
239
+ format: 'esm',
240
+ platform: 'browser',
241
+ minify: true,
242
+ treeShaking: true,
243
+ write: false,
244
+ // Never written (write: false) — gives the stdin entry's outputs real
245
+ // .js/.css extensions so they can be told apart.
246
+ outdir: join(input.dir, '_conloca'),
247
+ // Automatic JSX so .tsx configs compile against react/jsx-runtime —
248
+ // which is externalized and supplied by the editor.
249
+ jsx: 'automatic',
250
+ external: [...EDITOR_BUNDLE_EXTERNALS, ...STYLESHEET_ASSET_EXTERNALS],
251
+ plugins: [sassCompiler(input.logger), ...(input.plugins ?? [])],
252
+ // No compiler is wired for these preprocessors in the component graph;
253
+ // strip them like all stylesheets used to be stripped (`{}` module, no
254
+ // rules) rather than failing the site's registration over one exotic
255
+ // import. siteStyles never reach here: the site's Vite pipeline compiles them.
256
+ loader: { '.less': 'empty', '.styl': 'empty' },
257
+ // esbuild would print warnings straight to stderr, outside the build's
258
+ // log stream; silence it and forward them through the Astro logger below.
259
+ logLevel: 'silent',
260
+ });
261
+
262
+ // The virtual entry re-exports the three descriptor names through a
263
+ // namespace import so a schemas module that declares only some of them
264
+ // cannot fail the site's build — absent names export undefined by
265
+ // design, and esbuild flags each one with an always-undefined warning on
266
+ // every build. Absence of an OPTIONAL name is the contract working, not a
267
+ // diagnostic; a schemas module yielding NONE of the names is one (a wrong
268
+ // path, or misspelled exports), so exactly that case is reported once, in
269
+ // this package's own words.
270
+ const softContractAbsences = new Set<string>();
271
+ for (const warning of result.warnings) {
272
+ const absentName = warning.location?.file.endsWith('conloca-canvas-entry.js')
273
+ ? SCHEMA_EXPORT_ABSENCE.exec(warning.text)?.[1]
274
+ : undefined;
275
+ if (absentName) {
276
+ softContractAbsences.add(absentName);
277
+ continue;
278
+ }
279
+ const location = warning.location;
280
+ input.logger.warn(
281
+ `esbuild: ${warning.text}${location ? ` (${location.file}:${location.line}:${location.column})` : ''}`,
282
+ );
283
+ }
284
+ if (softContractAbsences.size === SCHEMA_MODULE_EXPORTS.length && descriptors?.schemasPath) {
285
+ input.logger.warn(
286
+ `${PACKAGE_NAME}: the schemas module at ${descriptors.schemasPath} exports none of ` +
287
+ 'pageSchemas, dataSchemas or mdxComponents — check the path and the export names.',
288
+ );
289
+ }
290
+
291
+ const jsFiles = result.outputFiles.filter((file) => file.path.endsWith('.js'));
292
+ const cssFiles = result.outputFiles.filter((file) => file.path.endsWith('.css'));
293
+ if (jsFiles.length !== 1 || cssFiles.length > 1 || jsFiles.length + cssFiles.length !== result.outputFiles.length) {
294
+ throw new Error(
295
+ `${PACKAGE_NAME}: expected the puck config to bundle to one ESM file (plus at most one stylesheet), ` +
296
+ `got ${result.outputFiles.map((file) => file.path).join(', ')}. A non-JS import that esbuild emits ` +
297
+ 'as its own asset (e.g. an image or font) is not supported in the editor bundle ' +
298
+ '— keep it out of the puck config graph.',
299
+ );
300
+ }
301
+
302
+ const outDir = join(input.dir, '_conloca');
303
+ await mkdir(outDir, { recursive: true });
304
+
305
+ const bytes = jsFiles[0].contents;
306
+ const hash = createHash('sha256').update(bytes).digest('hex');
307
+ const filename = `editor-bundle.${hash.slice(0, 16)}.js`;
308
+ await writeFile(join(outDir, filename), bytes);
309
+
310
+ let stylesheet: BundledStylesheet | undefined;
311
+ let assetCorsPaths: string[] = [];
312
+ const componentCss = cssFiles[0] ? new TextDecoder().decode(cssFiles[0].contents) : '';
313
+ // Site styles first, so component rules keep the final word. esbuild emits
314
+ // an empty CSS file when every component stylesheet was stripped, and an
315
+ // empty registered stylesheet would only add a wasted fetch.
316
+ const rawCss = [siteCss, componentCss].filter(Boolean).join('\n');
317
+ if (rawCss !== '') {
318
+ // Asset URLs are rewritten BEFORE hashing: the editor hash-verifies the
319
+ // stylesheet it fetches, so the rewrite has to be part of the bytes that
320
+ // get hashed, written, and registered.
321
+ let css = rawCss;
322
+ if (input.publicBaseUrl) {
323
+ const rewritten = rewriteStylesheetAssetUrls(rawCss, input.publicBaseUrl, input.logger);
324
+ css = rewritten.css;
325
+ assetCorsPaths = rewritten.assetCorsPaths;
326
+ }
327
+ const cssBytes = new TextEncoder().encode(css);
328
+ const cssHash = createHash('sha256').update(cssBytes).digest('hex');
329
+ const cssFilename = `editor-bundle.${cssHash.slice(0, 16)}.css`;
330
+ await writeFile(join(outDir, cssFilename), cssBytes);
331
+ stylesheet = { url: `/_conloca/${cssFilename}`, hash: cssHash, bytes: cssBytes };
332
+ input.logger.info(`editor stylesheet written: ${stylesheet.url} (${cssBytes.byteLength} bytes)`);
333
+ }
334
+
335
+ await ensureCorsHeaders(input.dir, assetCorsPaths);
336
+
337
+ const url = `/_conloca/${filename}`;
338
+ input.logger.info(`editor bundle written: ${url} (${bytes.byteLength} bytes)`);
339
+ return { url, hash, bytes, stylesheet, assetCorsPaths };
340
+ }
341
+
342
+ /**
343
+ * Compiles the siteStyles through the site's own Vite pipeline (its plugins,
344
+ * PostCSS config and preprocessors), the way conlocaCMS's dev editor compiles
345
+ * the same option, in a CSS-only build. The only files it writes are the
346
+ * assets the stylesheets reference (fonts, images), under `<dir>/_conloca/`.
347
+ * Returns the compiled CSS with the entries in listed order.
348
+ *
349
+ * A failure is rethrown naming the entries: the site's own build fails on the
350
+ * same stylesheet, and a canvas stylesheet silently missing its site styles
351
+ * must not register.
352
+ */
353
+ async function compileSiteStyles({
354
+ root,
355
+ vite,
356
+ siteStyles,
357
+ dir,
358
+ }: {
359
+ root: string;
360
+ vite: UserConfig;
361
+ siteStyles: string[];
362
+ dir: string;
363
+ }): Promise<string> {
364
+ if (siteStyles.length === 0) return '';
365
+ const entryNames = siteStyles.map((_, index) => `site-style-${index}`);
366
+ let result: Awaited<ReturnType<typeof buildWithVite>>;
367
+ try {
368
+ result = await buildWithVite(
369
+ mergeConfig(vite, {
370
+ configFile: false,
371
+ root,
372
+ // The assets are written under `dir`, which the site serves at its
373
+ // origin root, so the URLs pointing at them must start there too.
374
+ base: '/',
375
+ logLevel: 'warn',
376
+ build: {
377
+ write: false,
378
+ copyPublicDir: false,
379
+ assetsDir: '_conloca',
380
+ rolldownOptions: {
381
+ input: Object.fromEntries(siteStyles.map((entry, index) => [entryNames[index], resolve(root, entry)])),
382
+ },
383
+ },
384
+ }),
385
+ );
386
+ } catch (cause) {
387
+ throw new Error(`${PACKAGE_NAME}: siteStyles failed to compile (${siteStyles.join(', ')}): ${messageOf(cause)}`, {
388
+ cause,
389
+ });
390
+ }
391
+
392
+ const assets = [result]
393
+ .flat()
394
+ .flatMap((bundle) => ('output' in bundle ? bundle.output : []))
395
+ .filter((file) => file.type === 'asset');
396
+ await Promise.all(
397
+ assets
398
+ .filter((asset) => !asset.fileName.endsWith('.css'))
399
+ .map(async (asset) => {
400
+ const target = join(dir, asset.fileName);
401
+ await mkdir(dirname(target), { recursive: true });
402
+ await writeFile(target, asset.source);
403
+ }),
404
+ );
405
+ return entryNames
406
+ .map((name) => assets.find((asset) => asset.names.includes(`${name}.css`))?.source)
407
+ .map((source) => (source instanceof Uint8Array ? new TextDecoder().decode(source) : (source ?? '')))
408
+ .filter(Boolean)
409
+ .join('\n');
410
+ }
411
+
412
+ /** Matches one `url(…)` token, with or without quotes (esbuild's minifier
413
+ * drops the quotes, but an unminified or quote-requiring value keeps them). */
414
+ const CSS_URL_TOKEN = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g;
415
+
416
+ /**
417
+ * Re-points the registered stylesheet's asset references at the deployed site.
418
+ *
419
+ * Only ROOT-relative URLs (`/fonts/x.otf`) are rewritten — those name a path
420
+ * on the site and nothing else. That includes the `/_conloca/` assets the
421
+ * siteStyles build emitted, since Vite resolves their relative references.
422
+ * Path-relative ones (`./x.otf`, `../x.otf`, `x.otf`) cannot be resolved here
423
+ * and are reported instead of guessed: esbuild flattens every component
424
+ * stylesheet into ONE output and copies url() paths through verbatim, so by
425
+ * this point the emitted text no longer records WHICH source directory each
426
+ * one was relative to. Absolute, protocol-relative, `data:` and fragment
427
+ * (`#filter`) refs already resolve correctly and are left alone.
428
+ *
429
+ * Returns the rewritten CSS plus the `_headers` globs its assets need — one
430
+ * per distinct directory rather than one per file, which keeps a font family
431
+ * of forty weights to a single rule.
432
+ */
433
+ export function rewriteStylesheetAssetUrls(
434
+ css: string,
435
+ publicBaseUrl: string,
436
+ logger: BundleEditorAssetsInput['logger'],
437
+ ): { css: string; assetCorsPaths: string[] } {
438
+ const base = publicBaseUrl.replace(/\/+$/, '');
439
+ const dirs = new Set<string>();
440
+ const unresolved = new Set<string>();
441
+
442
+ const rewritten = css.replace(CSS_URL_TOKEN, (token, _quote: string, ref: string) => {
443
+ const value = ref.trim();
444
+ if (value.startsWith('//') || value.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(value)) return token;
445
+ if (!value.startsWith('/')) {
446
+ unresolved.add(value);
447
+ return token;
448
+ }
449
+ const dir = value.slice(0, value.lastIndexOf('/'));
450
+ dirs.add(`${dir === '' ? '' : dir}/*`);
451
+ return `url(${base}${value})`;
452
+ });
453
+
454
+ if (unresolved.size > 0) {
455
+ logger.warn(
456
+ 'path-relative asset URLs in the registered stylesheet cannot be pointed at the deployed ' +
457
+ `site and will not load in the editing canvas — make them root-relative: ${[...unresolved].join(', ')}`,
458
+ );
459
+ }
460
+
461
+ return { css: rewritten, assetCorsPaths: [...dirs] };
462
+ }
463
+
464
+ /**
465
+ * Compiles the component graph's `.scss`/`.sass` imports with `sass`, mapping
466
+ * `*.module.*` files to esbuild's local-css semantics (hashed class names
467
+ * exported to the JS side). A file that fails to compile degrades to the
468
+ * pre-styled-canvas behavior — `{}` for a module (classNames become
469
+ * undefined), no rules for a global — with a warning naming the file and the
470
+ * compiler's reason. siteStyles never reach it: the site's Vite pipeline
471
+ * compiles them, and a failure there fails the build.
472
+ */
473
+ function sassCompiler(logger: BundleEditorAssetsInput['logger']): Plugin {
474
+ return {
475
+ name: 'conloca-sass',
476
+ setup(build) {
477
+ build.onLoad({ filter: /\.(scss|sass)$/ }, async (args) => {
478
+ const isModule = /\.module\.(scss|sass)$/.test(args.path);
479
+ try {
480
+ const sass = await import('sass');
481
+ const compiled = sass.compile(args.path, { style: 'expanded' });
482
+ return { contents: compiled.css, loader: isModule ? 'local-css' : 'css' };
483
+ } catch (error) {
484
+ logger.warn(
485
+ `stylesheet stripped from the editor bundle (${args.path}): ` +
486
+ (error instanceof Error ? error.message : String(error)),
487
+ );
488
+ return isModule ? { contents: '', loader: 'empty' } : { contents: '', loader: 'css' };
489
+ }
490
+ });
491
+ },
492
+ };
493
+ }
494
+
495
+ /**
496
+ * Writes the discovery route's collected CSS as a content-addressed artifact
497
+ * next to the editor bundle: `_conloca/route-css.<hash16>.css`.
498
+ * Same serving story as the editor stylesheet — the `/_conloca/*` CORS rule
499
+ * already covers it, and `mirrorEditorAssets` copies the whole dir.
500
+ */
501
+ export async function emitRouteCssArtifact(
502
+ dir: string,
503
+ css: string,
504
+ publicBaseUrl: string | undefined,
505
+ logger: BundleEditorAssetsInput['logger'],
506
+ ): Promise<{ stylesheet: BundledStylesheet; assetCorsPaths: string[] } | undefined> {
507
+ if (css.trim() === '') return undefined;
508
+ // The discovered CSS is the site's FULL page CSS, so it carries the
509
+ // site's asset URLs (fonts especially) as authored — root-relative. Applied
510
+ // in the editor those resolve against the EDITOR's origin and 404, the same
511
+ // failure the editor stylesheet had; same fix, same helper, and the same
512
+ // CORS grant for the directories they live in.
513
+ let assetCorsPaths: string[] = [];
514
+ let text = css;
515
+ if (publicBaseUrl) {
516
+ const rewritten = rewriteStylesheetAssetUrls(css, publicBaseUrl, logger);
517
+ text = rewritten.css;
518
+ assetCorsPaths = rewritten.assetCorsPaths;
519
+ }
520
+ const bytes = new TextEncoder().encode(text);
521
+ const outDir = join(dir, '_conloca');
522
+ await mkdir(outDir, { recursive: true });
523
+ const hash = createHash('sha256').update(bytes).digest('hex');
524
+ const filename = `route-css.${hash.slice(0, 16)}.css`;
525
+ await writeFile(join(outDir, filename), bytes);
526
+ await ensureCorsHeaders(dir, assetCorsPaths);
527
+ logger.info(`discovered route CSS written: /_conloca/${filename} (${bytes.byteLength} bytes)`);
528
+ return { stylesheet: { url: `/_conloca/${filename}`, hash, bytes }, assetCorsPaths };
529
+ }
530
+
531
+ /**
532
+ * Mirrors the emitted editor assets (`_conloca/` + the CORS rule) from the
533
+ * primary build's output into another asset directory — the recursive preview
534
+ * build's client dir. The bundle is only ever compiled into the PRIMARY
535
+ * build's dist (the child build short-circuits `astro:build:done` to avoid
536
+ * registration recursion), but in a deployment that serves the site and the
537
+ * preview from one Cloudflare Worker, the child's client dir is the asset set
538
+ * that actually serves the site, so without this mirror the editor at the
539
+ * endpoint cannot load its component bundle.
540
+ */
541
+ export async function mirrorEditorAssets(fromDir: string, toDir: string, assetCorsPaths: string[] = []): Promise<void> {
542
+ await cp(join(fromDir, '_conloca'), join(toDir, '_conloca'), { recursive: true });
543
+ await ensureCorsHeaders(toDir, assetCorsPaths);
544
+ }
545
+
546
+ /**
547
+ * Adds the bundle's CORS rule — plus one per stylesheet asset directory — to
548
+ * `<dir>/_headers`, appending to an existing file without clobbering other
549
+ * rules and without duplicating any of ours. Each rule is checked
550
+ * individually, so a dist that already carries `/_conloca/*` from an earlier
551
+ * build still picks up newly referenced asset directories.
552
+ */
553
+ async function ensureCorsHeaders(dir: string, assetCorsPaths: string[] = []): Promise<void> {
554
+ const headersPath = join(dir, '_headers');
555
+ let existing = '';
556
+ try {
557
+ existing = await readFile(headersPath, 'utf8');
558
+ } catch (error) {
559
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
560
+ }
561
+
562
+ let updated = existing;
563
+ for (const path of [BUNDLE_CORS_PATH, ...assetCorsPaths]) {
564
+ if (updated.includes(`${path}\n`)) continue;
565
+ const separator = updated === '' || updated.endsWith('\n') ? '' : '\n';
566
+ updated = `${updated}${separator}${corsRule(path)}`;
567
+ }
568
+ if (updated === existing) return;
569
+ await writeFile(headersPath, updated);
570
+ }
@@ -0,0 +1,75 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { endpointReaderOptions, type PuckManifest, readPuckConfig } from '@conloca/astro-cms/puck-manifest';
5
+ import { COMPONENT_MANIFEST_LIMITS, measureJson } from '@conloca/content-api/component-vocabulary';
6
+
7
+ /** The emitted manifest: its site-relative URL and the full sha-256 hex of its bytes. */
8
+ export interface ComponentManifestArtifact {
9
+ url: string;
10
+ hash: string;
11
+ }
12
+
13
+ /** Metadata transport ceiling; larger metadata must not be registered as a usable artifact. */
14
+ const MAX_MANIFEST_BYTES = COMPONENT_MANIFEST_LIMITS.bytes;
15
+
16
+ type Logger = { info(message: string): void; warn(message: string): void };
17
+
18
+ /**
19
+ * Writes the site's component vocabulary — every Puck component the config
20
+ * declares and what each accepts, read from source and never executed — as a
21
+ * content-addressed artifact beside the editor bundle:
22
+ * `_conloca/component-manifest.<hash16>.json`. The `/_conloca/*` CORS rule the
23
+ * bundle wrote already covers it, and `mirrorEditorAssets` copies the dir.
24
+ *
25
+ * Fail-soft: the manifest is metadata for agents, so a failure costs the
26
+ * manifest and warns — never the build. A config the reader cannot fully read
27
+ * still ships its manifest, because the admissions are the answer, and the
28
+ * build log names what could not be read, where the developer looks.
29
+ */
30
+ export async function emitComponentManifest(input: {
31
+ dir: string;
32
+ puckConfigPath: string;
33
+ projectRoot: string;
34
+ logger: Logger;
35
+ }): Promise<ComponentManifestArtifact | undefined> {
36
+ try {
37
+ const manifest = readPuckConfig(
38
+ endpointReaderOptions({ puckConfigPath: input.puckConfigPath, projectRoot: input.projectRoot }),
39
+ );
40
+ const bytes = new TextEncoder().encode(JSON.stringify(manifest));
41
+ if (bytes.byteLength > MAX_MANIFEST_BYTES) {
42
+ input.logger.warn(
43
+ `component manifest skipped — ${bytes.byteLength} bytes exceeds the metadata limit of ${MAX_MANIFEST_BYTES} bytes`,
44
+ );
45
+ return undefined;
46
+ }
47
+ measureJson(manifest, COMPONENT_MANIFEST_LIMITS);
48
+ const hash = createHash('sha256').update(bytes).digest('hex');
49
+ const filename = `component-manifest.${hash.slice(0, 16)}.json`;
50
+ await mkdir(join(input.dir, '_conloca'), { recursive: true });
51
+ await writeFile(join(input.dir, '_conloca', filename), bytes);
52
+ reportManifest(manifest, `/_conloca/${filename}`, input.logger);
53
+ return { url: `/_conloca/${filename}`, hash };
54
+ } catch (error) {
55
+ input.logger.warn(
56
+ 'component manifest skipped — agents get no component vocabulary from this build ' +
57
+ `(${error instanceof Error ? error.message : String(error)})`,
58
+ );
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ /** One info line for the artifact, and a warning for everything the reader could not read. */
64
+ function reportManifest(manifest: PuckManifest, url: string, logger: Logger): void {
65
+ logger.info(`component manifest written: ${url} (${Object.keys(manifest.components).length} components)`);
66
+ if (manifest.unreadable) {
67
+ logger.warn(
68
+ `component manifest is incomplete: ${manifest.unreadableReason ?? 'the config could not be fully read'}`,
69
+ );
70
+ }
71
+ for (const name of manifest.unresolved) {
72
+ const reason = manifest.unresolvedReasons?.[name];
73
+ logger.warn(`component ${name} could not be read${reason === undefined ? '' : `: ${reason}`}`);
74
+ }
75
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Stable package name used as the Astro integration id, for logger scoping,
3
+ * and in user-facing error messages. Single source of truth.
4
+ */
5
+ export const PACKAGE_NAME = '@conloca/cloud-astro';
6
+
7
+ /**
8
+ * Environment variable that the recursive preview build sets on the child
9
+ * Astro process so the integration's own `astro:build:done` hook can detect
10
+ * it and skip re-registration / further recursion.
11
+ */
12
+ export const PREVIEW_BUILD_ENV_FLAG = 'CONLOCA_PREVIEW_BUILD';
13
+
14
+ /**
15
+ * Environment variable consumed by the recursive preview build to discover
16
+ * the per-branch preview secret needed to construct the secret-scoped Astro
17
+ * route (`/conloca_preview_<secret>/[...path]`).
18
+ */
19
+ export const PREVIEW_SECRET_ENV_FLAG = 'CONLOCA_PREVIEW_SECRET';
20
+
21
+ /**
22
+ * Environment variable carrying the build token (`cbt_<id>.<secret>`),
23
+ * issued by the endpoint, that authenticates the site's build to the
24
+ * endpoint's registration route.
25
+ * Read when {@link ConlocaCloudOptions.buildToken} is not set, so CI can
26
+ * inject the credential without committing it to `astro.config.mjs`.
27
+ */
28
+ export const BUILD_TOKEN_ENV_VAR = 'CONLOCA_BUILD_TOKEN';