@conloca/cloud-astro 0.2.1 → 0.2.3

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