@conloca/cloud-astro 0.2.2 → 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 (176) hide show
  1. package/README.md +261 -208
  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 -408
  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/_resolve-opts.d.ts +16 -10
  73. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  74. package/dist/src/preview/_resolve-opts.js +21 -10
  75. package/dist/src/preview/_resolve-opts.js.map +1 -1
  76. package/dist/src/preview/banner.d.ts.map +1 -1
  77. package/dist/src/preview/banner.js +2 -4
  78. package/dist/src/preview/banner.js.map +1 -1
  79. package/dist/src/preview/cookie.d.ts +5 -2
  80. package/dist/src/preview/cookie.d.ts.map +1 -1
  81. package/dist/src/preview/cookie.js +5 -2
  82. package/dist/src/preview/cookie.js.map +1 -1
  83. package/dist/src/preview/label.d.ts +8 -0
  84. package/dist/src/preview/label.d.ts.map +1 -0
  85. package/dist/src/preview/label.js +14 -0
  86. package/dist/src/preview/label.js.map +1 -0
  87. package/dist/src/preview/landing.d.ts +2 -2
  88. package/dist/src/preview/landing.js +2 -2
  89. package/dist/src/preview/middleware.d.ts +25 -20
  90. package/dist/src/preview/middleware.d.ts.map +1 -1
  91. package/dist/src/preview/middleware.js +56 -51
  92. package/dist/src/preview/middleware.js.map +1 -1
  93. package/dist/src/preview/preview-path.d.ts +18 -5
  94. package/dist/src/preview/preview-path.d.ts.map +1 -1
  95. package/dist/src/preview/preview-path.js +24 -8
  96. package/dist/src/preview/preview-path.js.map +1 -1
  97. package/dist/src/preview/site-middleware.d.ts +5 -5
  98. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  99. package/dist/src/preview/site-middleware.js +16 -16
  100. package/dist/src/preview/site-middleware.js.map +1 -1
  101. package/dist/src/preview-build.d.ts +18 -15
  102. package/dist/src/preview-build.d.ts.map +1 -1
  103. package/dist/src/preview-build.js +36 -21
  104. package/dist/src/preview-build.js.map +1 -1
  105. package/dist/src/preview.d.ts +1 -1
  106. package/dist/src/preview.d.ts.map +1 -1
  107. package/dist/src/preview.js +1 -1
  108. package/dist/src/preview.js.map +1 -1
  109. package/dist/src/repository.d.ts +1 -1
  110. package/dist/src/repository.js +1 -1
  111. package/dist/src/resolve-options.d.ts +17 -0
  112. package/dist/src/resolve-options.d.ts.map +1 -0
  113. package/dist/src/resolve-options.js +21 -0
  114. package/dist/src/resolve-options.js.map +1 -0
  115. package/dist/src/site-id.d.ts +0 -2
  116. package/dist/src/site-id.d.ts.map +1 -1
  117. package/dist/src/site-id.js +2 -3
  118. package/dist/src/site-id.js.map +1 -1
  119. package/dist/src/types.d.ts +21 -69
  120. package/dist/src/types.d.ts.map +1 -1
  121. package/package.json +37 -13
  122. package/src/component-manifest.ts +11 -8
  123. package/src/constants.ts +5 -14
  124. package/src/descriptors.ts +2 -2
  125. package/src/doctor/checks-address.ts +190 -0
  126. package/src/doctor/checks-live.ts +256 -268
  127. package/src/doctor/checks-offline.ts +24 -262
  128. package/src/doctor/config-scan.ts +21 -9
  129. package/src/doctor/run.ts +14 -16
  130. package/src/doctor/types.ts +7 -7
  131. package/src/editor-page/bundle.ts +482 -0
  132. package/src/editor-page/emit.ts +246 -0
  133. package/src/editor-page/framing.ts +62 -0
  134. package/src/editor-page/page.ts +37 -0
  135. package/src/editor-page/site-base.ts +11 -0
  136. package/src/git.ts +29 -10
  137. package/src/index.ts +20 -6
  138. package/src/integration.ts +255 -461
  139. package/src/node.ts +18 -2
  140. package/src/preview/_resolve-opts.ts +29 -11
  141. package/src/preview/banner.ts +2 -4
  142. package/src/preview/cookie.ts +5 -2
  143. package/src/preview/label.ts +12 -0
  144. package/src/preview/landing.ts +2 -2
  145. package/src/preview/middleware.ts +77 -66
  146. package/src/preview/preview-path.ts +26 -8
  147. package/src/preview/site-middleware.ts +16 -21
  148. package/src/preview-build.ts +42 -26
  149. package/src/preview-handler.astro +10 -8
  150. package/src/preview.ts +0 -1
  151. package/src/repository.ts +1 -1
  152. package/src/resolve-options.ts +37 -0
  153. package/src/site-id.ts +2 -4
  154. package/src/skill/SKILL.md +51 -55
  155. package/src/types.ts +21 -70
  156. package/src/virtual-modules.d.ts +4 -1
  157. package/dist/src/build-commit.d.ts +0 -19
  158. package/dist/src/build-commit.d.ts.map +0 -1
  159. package/dist/src/build-commit.js +0 -6
  160. package/dist/src/build-commit.js.map +0 -1
  161. package/dist/src/bundle.d.ts +0 -181
  162. package/dist/src/bundle.d.ts.map +0 -1
  163. package/dist/src/bundle.js +0 -413
  164. package/dist/src/bundle.js.map +0 -1
  165. package/dist/src/discovery.d.ts +0 -58
  166. package/dist/src/discovery.d.ts.map +0 -1
  167. package/dist/src/discovery.js +0 -133
  168. package/dist/src/discovery.js.map +0 -1
  169. package/dist/src/register.d.ts +0 -98
  170. package/dist/src/register.d.ts.map +0 -1
  171. package/dist/src/register.js +0 -103
  172. package/dist/src/register.js.map +0 -1
  173. package/src/build-commit.ts +0 -22
  174. package/src/bundle.ts +0 -570
  175. package/src/discovery.ts +0 -183
  176. package/src/register.ts +0 -180
@@ -0,0 +1,482 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, extname, join, resolve } from 'node:path';
4
+ import type { TemplateConfig } from '@conloca/astro-cms';
5
+ import type { EditorDataBindings } from '@conloca/content-api';
6
+ import { compile as compileSass } from 'sass';
7
+ import { build as buildWithVite, mergeConfig, type Plugin, 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 page maps them to
13
+ * the workspace editor's own copies, so the site's components
14
+ * execute on the editor's 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 `EDITOR_UI_MODULE_FILES`: every specifier externalized
19
+ * here needs a file there or the site's bundle fails bare-specifier resolution
20
+ * in the browser. The editor page tests pin the two lists to each other.
21
+ */
22
+ export const EDITOR_BUNDLE_EXTERNALS = [
23
+ 'react',
24
+ 'react-dom',
25
+ 'react/jsx-runtime',
26
+ 'react/jsx-dev-runtime',
27
+ 'react-dom/client',
28
+ '@puckeditor/core',
29
+ ] as const;
30
+
31
+ /**
32
+ * Editor descriptors compiled into the bundle, next to the puck config and
33
+ * the site styles. Sourced from what `conlocaCMS` resolved and published —
34
+ * this package never grows its own option for them.
35
+ */
36
+ export interface EditorBundleDescriptors {
37
+ /**
38
+ * Absolute path of the host's schemas module (conlocaCMS `schemasPath`).
39
+ * Its `pageSchemas` / `dataSchemas` / `mdxComponents` exports are
40
+ * re-exported by the bundle.
41
+ */
42
+ schemasPath?: string;
43
+ /**
44
+ * Auto-discovered MDX descriptors (conlocaCMS `mdxComponentFolders`),
45
+ * serialized into the bundle verbatim. Opaque here on purpose: the shape
46
+ * is cms-spa's contract and this package only transports it.
47
+ */
48
+ discoveredMdxComponents?: readonly unknown[];
49
+ /**
50
+ * Page-creation templates (conlocaCMS `templates`), serialized into the
51
+ * bundle verbatim. Typed by the `@conloca/astro-cms` peer, whose
52
+ * `readEditorDescriptors` produced the value this package transports.
53
+ */
54
+ templates?: Record<string, TemplateConfig>;
55
+ /**
56
+ * The routing data bindings (conlocaCMS `routing`), serialized into the
57
+ * bundle verbatim, so the editor builds each page's data context from the
58
+ * same routes the published page resolves with.
59
+ */
60
+ dataBindings?: EditorDataBindings;
61
+ }
62
+
63
+ export interface EditorPageBundleInput {
64
+ /** Build output directory (Astro's `dir`, as a filesystem path). */
65
+ dir: string;
66
+ /** The Astro project root, as a filesystem path: styles resolve against it. */
67
+ root: string;
68
+ /** The site's Vite config, including the transforms needed by components and schemas. */
69
+ vite: UserConfig;
70
+ /** Entry module of the site's puck config. */
71
+ puckConfigPath: string;
72
+ /**
73
+ * Stylesheets for the editing canvas, siteStyles then editorStyles, compiled
74
+ * in this order ahead of the component modules so component rules keep the
75
+ * final word.
76
+ */
77
+ styles: string[];
78
+ /** Editor descriptors published by conlocaCMS for this build. */
79
+ descriptors?: EditorBundleDescriptors;
80
+ logger: { info(message: string): void; warn(message: string): void };
81
+ }
82
+
83
+ export interface EditorPageBundle {
84
+ /** File name in `<dir>/_conloca/editor/`, `site.<first 16 hex of its sha-256>.js`. */
85
+ site: string;
86
+ /** `site.<first 16 hex of its sha-256>.css` in the same folder, or null when there is no CSS. */
87
+ css: string | null;
88
+ }
89
+
90
+ /** File extensions a component imports as a file, written beside the bundle. */
91
+ const EDITOR_ASSET_EXTENSIONS: readonly string[] = [
92
+ 'woff',
93
+ 'woff2',
94
+ 'ttf',
95
+ 'otf',
96
+ 'eot',
97
+ 'png',
98
+ 'jpg',
99
+ 'jpeg',
100
+ 'gif',
101
+ 'svg',
102
+ 'webp',
103
+ 'avif',
104
+ ];
105
+
106
+ /** The asset extensions a component imports as an image, which the site's build hands over as Astro's image object. */
107
+ const IMAGE_EXTENSIONS: ReadonlySet<string> = new Set(['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'avif']);
108
+
109
+ /**
110
+ * Optional exports transported from the site's schemas module to the editor.
111
+ * A namespace copy keeps absent names optional without generating missing-export
112
+ * diagnostics; the build plugin reports a module that declares none of them.
113
+ */
114
+ const SCHEMA_MODULE_EXPORTS = ['pageSchemas', 'dataSchemas', 'mdxComponents'] as const;
115
+
116
+ /** The folder, relative to the build output, that holds every file of the editor page. */
117
+ const EDITOR_DIR = '_conloca/editor';
118
+
119
+ /** Where Vite writes the files the bundle and its stylesheets reference. */
120
+ const EDITOR_ASSETS_DIR = `${EDITOR_DIR}/assets`;
121
+
122
+ /** A file the bundle's JavaScript imports, written as `assets/<sha256>.<ext>` beside the bundle. */
123
+ interface EditorAsset {
124
+ /** Full sha-256 hex of the bytes. */
125
+ sha256: string;
126
+ /** Lower-case extension, without the dot. */
127
+ ext: string;
128
+ bytes: Uint8Array;
129
+ }
130
+
131
+ interface PreRenderedAssetNames {
132
+ names: readonly string[];
133
+ }
134
+
135
+ /** Stylesheets go beside the bundle, where the combined stylesheet is written, so their relative `url()`s stay valid. */
136
+ function editorAssetFileNames(info: PreRenderedAssetNames): string {
137
+ return info.names.some((name) => name.endsWith('.css'))
138
+ ? `${EDITOR_DIR}/[name][extname]`
139
+ : `${EDITOR_ASSETS_DIR}/[name]-[hash][extname]`;
140
+ }
141
+
142
+ /**
143
+ * Compiles the puck config, its components and the schemas module through the
144
+ * site's Vite config into `<dir>/_conloca/editor/`: one ESM file plus, when the
145
+ * graph or `styles` carry CSS, one stylesheet, each named by the first 16 hex
146
+ * chars of its sha-256. Every file they reference is written under
147
+ * `_conloca/editor/assets/` and addressed relative to them. Content-file and
148
+ * `astro:` imports are refused.
149
+ *
150
+ * `styles` compile first so component rules keep the final word. Component Sass
151
+ * keeps its warn-and-strip fallback; configured JavaScript transforms and
152
+ * `styles` failures fail the build.
153
+ */
154
+ export async function bundleEditorPage(input: EditorPageBundleInput): Promise<EditorPageBundle> {
155
+ const stylesCss = await compileSiteStyles({
156
+ root: input.root,
157
+ vite: input.vite,
158
+ styles: input.styles,
159
+ dir: input.dir,
160
+ });
161
+
162
+ const entryPath = resolve(input.root, input.puckConfigPath);
163
+ const descriptors = input.descriptors;
164
+ const discovered = descriptors?.discoveredMdxComponents ?? [];
165
+ const virtualEntry = [
166
+ `export { default } from ${JSON.stringify(entryPath)};`,
167
+ // Copy the namespace before selecting optional names: a direct named
168
+ // re-export would reject schemas modules that declare only some of them.
169
+ ...(descriptors?.schemasPath
170
+ ? [
171
+ `import * as __conlocaSchemas from ${JSON.stringify(resolve(descriptors.schemasPath))};`,
172
+ 'const __conlocaDescriptors = { ...__conlocaSchemas };',
173
+ ...SCHEMA_MODULE_EXPORTS.map((name) => `export const ${name} = __conlocaDescriptors.${name};`),
174
+ ]
175
+ : []),
176
+ ...(discovered.length > 0 ? [`export const discoveredMdxComponents = ${JSON.stringify(discovered)};`] : []),
177
+ ...(descriptors?.templates ? [`export const templates = ${JSON.stringify(descriptors.templates)};`] : []),
178
+ ...(descriptors?.dataBindings ? [`export const dataBindings = ${JSON.stringify(descriptors.dataBindings)};`] : []),
179
+ ].join('\n');
180
+
181
+ const jsAssets: EditorAsset[] = [];
182
+ const entryId = '\0conloca-editor-page-entry.js';
183
+ const bundlePlugin: Plugin = {
184
+ name: 'conloca-editor-entry',
185
+ resolveId(id) {
186
+ return id === entryId ? id : null;
187
+ },
188
+ load(id) {
189
+ return id === entryId ? virtualEntry : null;
190
+ },
191
+ async generateBundle() {
192
+ if (!descriptors?.schemasPath) return;
193
+ // Vite resolves symlinks (macOS's /var → /private/var), so look the module up by its resolved id.
194
+ const schemasId = (await this.resolve(resolve(descriptors.schemasPath)))?.id;
195
+ const exports = (schemasId && this.getModuleInfo(schemasId)?.exports) || [];
196
+ if (!SCHEMA_MODULE_EXPORTS.some((name) => exports.includes(name))) {
197
+ input.logger.warn(
198
+ `${PACKAGE_NAME}: the schemas module at ${descriptors.schemasPath} exports none of ` +
199
+ 'pageSchemas, dataSchemas or mdxComponents — check the path and the export names.',
200
+ );
201
+ }
202
+ },
203
+ };
204
+ const siteConfig = {
205
+ ...normalizeBundlerOptions(input.vite),
206
+ plugins: [importedFiles(jsAssets), componentStyles(input.logger), bundlePlugin, ...(input.vite.plugins ?? [])],
207
+ };
208
+ const config = mergeConfig(siteConfig, {
209
+ configFile: false,
210
+ root: input.root,
211
+ base: './',
212
+ logLevel: 'warn',
213
+ oxc: { jsx: { runtime: 'automatic' } },
214
+ build: {
215
+ write: false,
216
+ copyPublicDir: false,
217
+ outDir: input.dir,
218
+ assetsDir: EDITOR_ASSETS_DIR,
219
+ assetsInlineLimit: 0,
220
+ cssCodeSplit: false,
221
+ minify: true,
222
+ sourcemap: false,
223
+ ssr: false,
224
+ watch: null,
225
+ lib: false,
226
+ manifest: false,
227
+ ssrManifest: false,
228
+ rolldownOptions: {
229
+ preserveEntrySignatures: 'strict',
230
+ onwarn(warning: { message: string }) {
231
+ input.logger.warn(`vite: ${warning.message}`);
232
+ },
233
+ },
234
+ },
235
+ });
236
+ // The editor page is one browser entry, not the site's configured app or
237
+ // library outputs. Keep all site plugins, but replace its output topology.
238
+ config.build.rolldownOptions.input = entryId;
239
+ config.build.rolldownOptions.external = editorExternal;
240
+ const configuredOutput = config.build.rolldownOptions.output;
241
+ if (Array.isArray(configuredOutput) && configuredOutput.length > 1) {
242
+ throw new Error(`${PACKAGE_NAME}: the editor page bundle requires a single Vite output configuration.`);
243
+ }
244
+ const output = Array.isArray(configuredOutput) ? configuredOutput[0] : configuredOutput;
245
+ config.build.rolldownOptions.output = {
246
+ plugins: output?.plugins,
247
+ format: 'es',
248
+ codeSplitting: false,
249
+ entryFileNames: `${EDITOR_DIR}/site.js`,
250
+ assetFileNames: editorAssetFileNames,
251
+ };
252
+ const result = await buildWithVite(config);
253
+ const files = [result].flat().flatMap((bundle) => ('output' in bundle ? bundle.output : []));
254
+ type BuiltAsset = Extract<(typeof files)[number], { type: 'asset' }>;
255
+ const jsFiles = files.filter((file) => file.type === 'chunk');
256
+ const cssFiles = files.filter((file): file is BuiltAsset => file.type === 'asset' && file.fileName.endsWith('.css'));
257
+ const assetFiles = files.filter(
258
+ (file): file is BuiltAsset => file.type === 'asset' && !file.fileName.endsWith('.css'),
259
+ );
260
+ if (jsFiles.length !== 1 || cssFiles.length > 1) {
261
+ throw new Error(
262
+ `${PACKAGE_NAME}: expected the puck config to bundle to one ESM file (plus at most one stylesheet), ` +
263
+ `got ${files.map((file) => file.fileName).join(', ')}.`,
264
+ );
265
+ }
266
+
267
+ const outDir = join(input.dir, EDITOR_DIR);
268
+ await mkdir(outDir, { recursive: true });
269
+ await Promise.all([
270
+ ...assetFiles.map((file) => writeOutputFile(join(input.dir, file.fileName), file.source)),
271
+ ...jsAssets.map((asset) =>
272
+ writeOutputFile(join(input.dir, EDITOR_ASSETS_DIR, `${asset.sha256}.${asset.ext}`), asset.bytes),
273
+ ),
274
+ ]);
275
+
276
+ const bytes = new TextEncoder().encode(jsFiles[0].code);
277
+ const site = `site.${createHash('sha256').update(bytes).digest('hex').slice(0, 16)}.js`;
278
+ await writeFile(join(outDir, site), bytes);
279
+ input.logger.info(`editor page bundle written: ${EDITOR_DIR}/${site} (${bytes.byteLength} bytes)`);
280
+
281
+ const cssSource = cssFiles[0]?.source;
282
+ const componentCss = typeof cssSource === 'string' ? cssSource : new TextDecoder().decode(cssSource);
283
+ // Styles first, so component rules keep the final word.
284
+ const rawCss = [stylesCss, componentCss].filter(Boolean).join('\n');
285
+ if (rawCss === '') return { site, css: null };
286
+ const cssBytes = new TextEncoder().encode(rawCss);
287
+ const css = `site.${createHash('sha256').update(cssBytes).digest('hex').slice(0, 16)}.css`;
288
+ await writeFile(join(outDir, css), cssBytes);
289
+ input.logger.info(`editor page stylesheet written: ${EDITOR_DIR}/${css} (${cssBytes.byteLength} bytes)`);
290
+ return { site, css };
291
+ }
292
+
293
+ async function writeOutputFile(path: string, source: string | Uint8Array): Promise<void> {
294
+ await mkdir(dirname(path), { recursive: true });
295
+ await writeFile(path, source);
296
+ }
297
+
298
+ /** The virtual module for a file a component imports. */
299
+ const ASSET_MODULE_PREFIX = '\0conloca-editor-file:';
300
+
301
+ /** MDX pages and content files are user content, never bundle code. */
302
+ const CONTENT_FILE = /\.(mdx|vxjson)$/i;
303
+
304
+ /**
305
+ * Rolldown checks unresolved imports before calling resolvers, then resolved
306
+ * imports too. Reject content and Astro's virtual modules here so a site's pre
307
+ * resolver or Vite alias cannot turn them into executable JavaScript first.
308
+ */
309
+ function editorExternal(id: string, importer: string | undefined): boolean {
310
+ if (CONTENT_FILE.test(id)) {
311
+ throw new Error(
312
+ `${PACKAGE_NAME}: ${id} is an MDX page or a content file, which the editor's users write; ` +
313
+ 'the editor page never runs one as code. Keep it out of the puck config graph.',
314
+ );
315
+ }
316
+ if (id.startsWith('astro:')) {
317
+ throw new Error(
318
+ `${PACKAGE_NAME}: ${importer ?? 'the puck config'} imports ${id}, an Astro module that exists only inside ` +
319
+ "Astro's own build. The editor page cannot load it; keep it out of the puck config graph.",
320
+ );
321
+ }
322
+ return EDITOR_BUNDLE_EXTERNALS.some((specifier) => specifier === id);
323
+ }
324
+
325
+ /**
326
+ * Turns a file a component imports into a module that addresses it beside the
327
+ * bundle, the way Astro hands an image import over as an image object.
328
+ * Stylesheet references stay with Vite's CSS pipeline.
329
+ */
330
+ function importedFiles(collected: EditorAsset[]): Plugin {
331
+ const assetFile = new RegExp(`\\.(${EDITOR_ASSET_EXTENSIONS.join('|')})$`, 'i');
332
+ return {
333
+ name: 'conloca-editor-files',
334
+ enforce: 'pre',
335
+ async resolveId(id, importer) {
336
+ if (!assetFile.test(id) || (importer && /\.(css|scss|sass|less|styl)(?:\?|$)/.test(importer))) return null;
337
+ const resolved = await this.resolve(id, importer, { skipSelf: true });
338
+ if (!resolved) throw new Error(`${PACKAGE_NAME}: cannot resolve editor asset ${id}`);
339
+ if (resolved.external) return resolved;
340
+ return ASSET_MODULE_PREFIX + resolved.id;
341
+ },
342
+ async load(id) {
343
+ return id.startsWith(ASSET_MODULE_PREFIX) ? assetModule(id.slice(ASSET_MODULE_PREFIX.length), collected) : null;
344
+ },
345
+ };
346
+ }
347
+
348
+ /**
349
+ * Preserve the component-style contract: Sass compiles once, failing softly;
350
+ * unsupported Less/Stylus imports remain empty. Give the resulting CSS to Vite
351
+ * at the original directory so CSS modules and relative assets resolve together.
352
+ * `styles` do not pass through this plugin.
353
+ */
354
+ function componentStyles(logger: EditorPageBundleInput['logger']): Plugin {
355
+ const suffix = '.conloca-editor.css';
356
+ const moduleSuffix = '.conloca-editor.module.css';
357
+ return {
358
+ name: 'conloca-editor-component-styles',
359
+ enforce: 'pre',
360
+ async resolveId(id, importer) {
361
+ if (!/\.(scss|sass|less|styl)$/.test(id)) return null;
362
+ const resolved = await this.resolve(id, importer, { skipSelf: true });
363
+ if (!resolved || resolved.external) return resolved;
364
+ return resolved.id + (/\.module\.(scss|sass|less|styl)$/.test(id) ? moduleSuffix : suffix);
365
+ },
366
+ async load(id) {
367
+ const ending = id.endsWith(moduleSuffix) ? moduleSuffix : id.endsWith(suffix) ? suffix : undefined;
368
+ if (!ending) return null;
369
+ const path = id.slice(0, -ending.length);
370
+ if (/\.(less|styl)$/.test(path)) return '';
371
+ try {
372
+ return compileSass(path, { style: 'expanded' }).css;
373
+ } catch (error) {
374
+ logger.warn(`stylesheet stripped from the editor page (${path}): ${messageOf(error)}`);
375
+ return '';
376
+ }
377
+ },
378
+ };
379
+ }
380
+
381
+ /** The module a file import evaluates to: its address, resolved against the bundle's own URL. */
382
+ async function assetModule(path: string, collected: EditorAsset[]): Promise<string> {
383
+ const bytes = new Uint8Array(await readFile(path));
384
+ const ext = extname(path).slice(1).toLowerCase();
385
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
386
+ if (!collected.some((asset) => asset.sha256 === sha256 && asset.ext === ext)) collected.push({ sha256, ext, bytes });
387
+ // @vite-ignore keeps Vite from resolving the name against this virtual module at build time.
388
+ const lines = [
389
+ `const src = new URL(/* @vite-ignore */ ${JSON.stringify(`./assets/${sha256}.${ext}`)}, import.meta.url).href;`,
390
+ ];
391
+ if (IMAGE_EXTENSIONS.has(ext)) {
392
+ lines.push(`export default { src, ...${JSON.stringify(await imageFacts(bytes, path))} };`);
393
+ } else {
394
+ lines.push('export default src;');
395
+ }
396
+ return lines.join('\n');
397
+ }
398
+
399
+ /** An image's width, height and format as Astro reports them for an import; none of them when unreadable. */
400
+ async function imageFacts(
401
+ bytes: Uint8Array,
402
+ path: string,
403
+ ): Promise<{ width?: number; height?: number; format?: string }> {
404
+ const { imageMetadata } = await import('astro/assets/utils');
405
+ try {
406
+ const { width, height, format } = await imageMetadata(bytes, path);
407
+ return { width, height, format };
408
+ } catch {
409
+ return {};
410
+ }
411
+ }
412
+
413
+ /** Normalize Vite's deprecated alias before adding either editor build's options. */
414
+ function normalizeBundlerOptions(vite: UserConfig): UserConfig {
415
+ const { rollupOptions, ...build } = vite.build ?? {};
416
+ return { ...vite, build: { ...build, rolldownOptions: build.rolldownOptions ?? rollupOptions } };
417
+ }
418
+
419
+ /**
420
+ * Compiles `styles` through the site's own Vite pipeline (its plugins, PostCSS
421
+ * config and preprocessors) in a CSS-only build. The only files it writes are
422
+ * the assets the stylesheets reference (fonts, images), under
423
+ * `<dir>/_conloca/editor/assets/`, addressed relative to the stylesheet.
424
+ * Returns the compiled CSS with the entries in listed order.
425
+ *
426
+ * A failure is rethrown naming the entries: the site's own build fails on the
427
+ * same stylesheet, and a canvas stylesheet silently missing its site styles
428
+ * must not ship.
429
+ */
430
+ async function compileSiteStyles({
431
+ root,
432
+ vite,
433
+ styles,
434
+ dir,
435
+ }: {
436
+ root: string;
437
+ vite: UserConfig;
438
+ styles: string[];
439
+ dir: string;
440
+ }): Promise<string> {
441
+ if (styles.length === 0) return '';
442
+ const entryNames = styles.map((_, index) => `site-style-${index}`);
443
+ let result: Awaited<ReturnType<typeof buildWithVite>>;
444
+ try {
445
+ result = await buildWithVite(
446
+ mergeConfig(normalizeBundlerOptions(vite), {
447
+ configFile: false,
448
+ root,
449
+ base: './',
450
+ logLevel: 'warn',
451
+ build: {
452
+ write: false,
453
+ copyPublicDir: false,
454
+ assetsDir: EDITOR_ASSETS_DIR,
455
+ rolldownOptions: {
456
+ input: Object.fromEntries(styles.map((entry, index) => [entryNames[index], resolve(root, entry)])),
457
+ output: { assetFileNames: editorAssetFileNames },
458
+ },
459
+ },
460
+ }),
461
+ );
462
+ } catch (cause) {
463
+ throw new Error(`${PACKAGE_NAME}: siteStyles failed to compile (${styles.join(', ')}): ${messageOf(cause)}`, {
464
+ cause,
465
+ });
466
+ }
467
+
468
+ const assets = [result]
469
+ .flat()
470
+ .flatMap((bundle) => ('output' in bundle ? bundle.output : []))
471
+ .filter((file) => file.type === 'asset');
472
+ await Promise.all(
473
+ assets
474
+ .filter((asset) => !asset.fileName.endsWith('.css'))
475
+ .map((asset) => writeOutputFile(join(dir, asset.fileName), asset.source)),
476
+ );
477
+ return entryNames
478
+ .map((name) => assets.find((asset) => asset.names.includes(`${name}.css`))?.source)
479
+ .map((source) => (source instanceof Uint8Array ? new TextDecoder().decode(source) : (source ?? '')))
480
+ .filter(Boolean)
481
+ .join('\n');
482
+ }