@conloca/cloud-astro 0.2.5 → 0.2.6

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 (171) hide show
  1. package/README.md +69 -22
  2. package/dist/.build-inputs.json +36 -23
  3. package/dist/src/constants.d.ts +4 -4
  4. package/dist/src/constants.js +4 -4
  5. package/dist/src/d3-build.d.ts +6 -2
  6. package/dist/src/d3-build.d.ts.map +1 -1
  7. package/dist/src/d3-build.js +15 -11
  8. package/dist/src/d3-build.js.map +1 -1
  9. package/dist/src/d8-adapters.d.ts +10 -0
  10. package/dist/src/d8-adapters.d.ts.map +1 -0
  11. package/dist/src/d8-adapters.js +19 -0
  12. package/dist/src/d8-adapters.js.map +1 -0
  13. package/dist/src/d8-build.d.ts +99 -0
  14. package/dist/src/d8-build.d.ts.map +1 -0
  15. package/dist/src/d8-build.js +265 -0
  16. package/dist/src/d8-build.js.map +1 -0
  17. package/dist/src/d8-guards.d.ts +29 -0
  18. package/dist/src/d8-guards.d.ts.map +1 -0
  19. package/dist/src/d8-guards.js +145 -0
  20. package/dist/src/d8-guards.js.map +1 -0
  21. package/dist/src/d8-middleware.d.ts +7 -0
  22. package/dist/src/d8-middleware.d.ts.map +1 -0
  23. package/dist/src/d8-middleware.js +15 -0
  24. package/dist/src/d8-middleware.js.map +1 -0
  25. package/dist/src/d8-render.d.ts +9 -0
  26. package/dist/src/d8-render.d.ts.map +1 -0
  27. package/dist/src/d8-render.js +52 -0
  28. package/dist/src/d8-render.js.map +1 -0
  29. package/dist/src/doctor/checks-d8.d.ts +7 -0
  30. package/dist/src/doctor/checks-d8.d.ts.map +1 -0
  31. package/dist/src/doctor/checks-d8.js +240 -0
  32. package/dist/src/doctor/checks-d8.js.map +1 -0
  33. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  34. package/dist/src/doctor/checks-live.js +3 -5
  35. package/dist/src/doctor/checks-live.js.map +1 -1
  36. package/dist/src/doctor/checks-offline.d.ts +2 -0
  37. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  38. package/dist/src/doctor/checks-offline.js +17 -8
  39. package/dist/src/doctor/checks-offline.js.map +1 -1
  40. package/dist/src/doctor/checks-preview-live.d.ts +7 -2
  41. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -1
  42. package/dist/src/doctor/checks-preview-live.js +107 -7
  43. package/dist/src/doctor/checks-preview-live.js.map +1 -1
  44. package/dist/src/doctor/checks-preview.d.ts.map +1 -1
  45. package/dist/src/doctor/checks-preview.js +9 -4
  46. package/dist/src/doctor/checks-preview.js.map +1 -1
  47. package/dist/src/doctor/config-scan.d.ts +24 -6
  48. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  49. package/dist/src/doctor/config-scan.js +89 -18
  50. package/dist/src/doctor/config-scan.js.map +1 -1
  51. package/dist/src/doctor/run.d.ts.map +1 -1
  52. package/dist/src/doctor/run.js +2 -0
  53. package/dist/src/doctor/run.js.map +1 -1
  54. package/dist/src/doctor/types.d.ts +7 -0
  55. package/dist/src/doctor/types.d.ts.map +1 -1
  56. package/dist/src/doctor/types.js +7 -0
  57. package/dist/src/doctor/types.js.map +1 -1
  58. package/dist/src/editor-page/emit.d.ts +4 -3
  59. package/dist/src/editor-page/emit.d.ts.map +1 -1
  60. package/dist/src/editor-page/emit.js +9 -9
  61. package/dist/src/editor-page/emit.js.map +1 -1
  62. package/dist/src/integration.d.ts.map +1 -1
  63. package/dist/src/integration.js +228 -124
  64. package/dist/src/integration.js.map +1 -1
  65. package/dist/src/node.d.ts +2 -0
  66. package/dist/src/node.d.ts.map +1 -1
  67. package/dist/src/node.js +4 -0
  68. package/dist/src/node.js.map +1 -1
  69. package/dist/src/preview/_resolve-opts.d.ts +26 -1
  70. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  71. package/dist/src/preview/_resolve-opts.js.map +1 -1
  72. package/dist/src/preview/content-api.d.ts +15 -0
  73. package/dist/src/preview/content-api.d.ts.map +1 -1
  74. package/dist/src/preview/content-api.js +57 -6
  75. package/dist/src/preview/content-api.js.map +1 -1
  76. package/dist/src/preview/d8-middleware.d.ts +25 -0
  77. package/dist/src/preview/d8-middleware.d.ts.map +1 -0
  78. package/dist/src/preview/d8-middleware.js +94 -0
  79. package/dist/src/preview/d8-middleware.js.map +1 -0
  80. package/dist/src/preview/dispatcher.d.ts +3 -16
  81. package/dist/src/preview/dispatcher.d.ts.map +1 -1
  82. package/dist/src/preview/dispatcher.js +46 -134
  83. package/dist/src/preview/dispatcher.js.map +1 -1
  84. package/dist/src/preview/headers.d.ts +3 -0
  85. package/dist/src/preview/headers.d.ts.map +1 -1
  86. package/dist/src/preview/headers.js +10 -1
  87. package/dist/src/preview/headers.js.map +1 -1
  88. package/dist/src/preview/links.d.ts +23 -0
  89. package/dist/src/preview/links.d.ts.map +1 -0
  90. package/dist/src/preview/links.js +168 -0
  91. package/dist/src/preview/links.js.map +1 -0
  92. package/dist/src/preview/middleware.d.ts +9 -3
  93. package/dist/src/preview/middleware.d.ts.map +1 -1
  94. package/dist/src/preview/middleware.js +36 -16
  95. package/dist/src/preview/middleware.js.map +1 -1
  96. package/dist/src/preview/prefix-router.d.ts +67 -0
  97. package/dist/src/preview/prefix-router.d.ts.map +1 -0
  98. package/dist/src/preview/prefix-router.js +153 -0
  99. package/dist/src/preview/prefix-router.js.map +1 -0
  100. package/dist/src/preview/preview-path.d.ts +8 -3
  101. package/dist/src/preview/preview-path.d.ts.map +1 -1
  102. package/dist/src/preview/preview-path.js +16 -4
  103. package/dist/src/preview/preview-path.js.map +1 -1
  104. package/dist/src/preview/site-middleware.d.ts +8 -2
  105. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  106. package/dist/src/preview/site-middleware.js +90 -31
  107. package/dist/src/preview/site-middleware.js.map +1 -1
  108. package/dist/src/preview/site-page-sources.d.ts +21 -0
  109. package/dist/src/preview/site-page-sources.d.ts.map +1 -0
  110. package/dist/src/preview/site-page-sources.js +129 -0
  111. package/dist/src/preview/site-page-sources.js.map +1 -0
  112. package/dist/src/preview/site-pages.d.ts +18 -0
  113. package/dist/src/preview/site-pages.d.ts.map +1 -0
  114. package/dist/src/preview/site-pages.js +7 -0
  115. package/dist/src/preview/site-pages.js.map +1 -0
  116. package/dist/src/preview-build.d.ts +17 -16
  117. package/dist/src/preview-build.d.ts.map +1 -1
  118. package/dist/src/preview-build.js +37 -40
  119. package/dist/src/preview-build.js.map +1 -1
  120. package/dist/src/preview-image-endpoint.d.ts +8 -0
  121. package/dist/src/preview-image-endpoint.d.ts.map +1 -0
  122. package/dist/src/preview-image-endpoint.js +34 -0
  123. package/dist/src/preview-image-endpoint.js.map +1 -0
  124. package/dist/src/preview-render-seams.d.ts +7 -0
  125. package/dist/src/preview-render-seams.d.ts.map +1 -0
  126. package/dist/src/preview-render-seams.js +27 -0
  127. package/dist/src/preview-render-seams.js.map +1 -0
  128. package/dist/src/site-middleware.d.ts +2 -4
  129. package/dist/src/site-middleware.d.ts.map +1 -1
  130. package/dist/src/site-middleware.js +6 -22
  131. package/dist/src/site-middleware.js.map +1 -1
  132. package/dist/src/types.d.ts +15 -16
  133. package/dist/src/types.d.ts.map +1 -1
  134. package/package.json +138 -6
  135. package/src/constants.ts +4 -4
  136. package/src/d3-build.ts +20 -14
  137. package/src/d8-adapters.ts +19 -0
  138. package/src/d8-build.ts +356 -0
  139. package/src/d8-guards.ts +177 -0
  140. package/src/d8-middleware.ts +17 -0
  141. package/src/d8-render.ts +61 -0
  142. package/src/doctor/checks-d8.ts +256 -0
  143. package/src/doctor/checks-live.ts +3 -4
  144. package/src/doctor/checks-offline.ts +21 -8
  145. package/src/doctor/checks-preview-live.ts +114 -8
  146. package/src/doctor/checks-preview.ts +9 -4
  147. package/src/doctor/config-scan.ts +86 -15
  148. package/src/doctor/run.ts +2 -0
  149. package/src/doctor/types.ts +8 -0
  150. package/src/editor-page/emit.ts +23 -14
  151. package/src/integration.ts +274 -135
  152. package/src/node.ts +4 -0
  153. package/src/preview/_resolve-opts.ts +17 -1
  154. package/src/preview/content-api.ts +60 -5
  155. package/src/preview/d8-middleware.ts +124 -0
  156. package/src/preview/dispatcher.ts +55 -150
  157. package/src/preview/headers.ts +10 -1
  158. package/src/preview/links.ts +175 -0
  159. package/src/preview/middleware.ts +41 -19
  160. package/src/preview/prefix-router.ts +197 -0
  161. package/src/preview/preview-path.ts +24 -6
  162. package/src/preview/site-middleware.ts +109 -38
  163. package/src/preview/site-page-sources.ts +146 -0
  164. package/src/preview/site-pages.ts +22 -0
  165. package/src/preview-build.ts +43 -42
  166. package/src/preview-image-endpoint.ts +35 -0
  167. package/src/preview-render-seams.ts +31 -0
  168. package/src/site-middleware.ts +6 -24
  169. package/src/skill/SKILL.md +19 -1
  170. package/src/types.ts +15 -16
  171. package/src/virtual-modules.d.ts +17 -2
@@ -1,19 +1,57 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
1
2
  import { createRequire } from 'node:module';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import type { AstroI18nLocales } from '@conloca/astro-cms/checks';
4
5
  import { readEditorDescriptors } from '@conloca/astro-cms/node';
5
6
  import { DEFAULT_EDITOR_ENDPOINT, editorUiOrigin } from '@conloca/content-api/editor-host';
6
- import type { AstroIntegration } from 'astro';
7
+ import type { AstroConfig, AstroIntegration, IntegrationResolvedRoute } from 'astro';
7
8
  import type { UserConfig as ViteUserConfig } from 'vite';
8
9
  import { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './constants.js';
9
- import { finishD3Build, onDemandPatterns, workerFirstPattern, writePreviewRoutes } from './d3-build.js';
10
- import { emitEditorPage, emitPreviewServerInfo, mirrorEditorPage } from './editor-page/emit.js';
11
- import { gitOutput, resolveBuildRef, resolveRepositoryUri } from './git.js';
10
+ import {
11
+ finishD3Build,
12
+ onDemandPatterns,
13
+ workerFirstPattern,
14
+ writePreviewRoutes,
15
+ writeWorkerFirst,
16
+ } from './d3-build.js';
17
+ import {
18
+ bakedIdentity,
19
+ bakedMedia,
20
+ bakesMedia,
21
+ cloudflareD8Problems,
22
+ d8Baked,
23
+ d8ImageEndpoint,
24
+ hasOnDemandRoutes,
25
+ knownImageService,
26
+ narrowVercelCatchAll,
27
+ previewPageHandlerPath,
28
+ siteOnDemand,
29
+ sitePagesOf,
30
+ writeSitePagesList,
31
+ } from './d8-build.js';
32
+ import {
33
+ adapterMiddlewareMode,
34
+ D8_EDGE_REFUSAL,
35
+ d8ConfigRefusal,
36
+ d8EdgeRefusal,
37
+ d8IsrRefusal,
38
+ darkenIsrPrefix,
39
+ readAstroConfigText,
40
+ vercelIsrCatchesPrefix,
41
+ } from './d8-guards.js';
42
+ import { emitEditorPage, emitPreviewServerInfo } from './editor-page/emit.js';
43
+ import { resolveRepositoryUri } from './git.js';
12
44
  import { messageOf } from './message-of.js';
13
45
  import type { BakedPreviewOpts } from './preview/_resolve-opts.js';
14
46
  import { cloudflareAdapter, resolveCloudflareAdapter } from './preview/cloudflare-adapter.js';
15
- import type { DispatcherExit } from './preview/dispatcher.js';
16
- import { normalizeTrailingSlash, PREVIEW_ROUTE_SEGMENT, type PreviewServeMode } from './preview/preview-path.js';
47
+ import type { PreviewExit } from './preview/prefix-router.js';
48
+ import {
49
+ imageEndpointEntry,
50
+ normalizeTrailingSlash,
51
+ PREVIEW_ROUTE_SEGMENT,
52
+ type PreviewServeMode,
53
+ previewOwnEntries,
54
+ } from './preview/preview-path.js';
17
55
  import {
18
56
  prerenderedKey,
19
57
  previewBuildMode,
@@ -22,7 +60,6 @@ import {
22
60
  spawnPreviewBuild,
23
61
  } from './preview-build.js';
24
62
  import { type InheritedOptions, resolveInheritedOptions } from './resolve-options.js';
25
- import { resolveBuildSiteId } from './site-id.js';
26
63
  import { scaffoldSkill } from './skill.js';
27
64
  import type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';
28
65
 
@@ -41,11 +78,11 @@ export { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG };
41
78
  * 0. Write the editor page to `dist/_conloca/editor/`: `index.html`, the
42
79
  * site's compiled puck config and styles, the MDX sandbox frame and
43
80
  * `conloca.json`. Every build does this; the page carries no credential.
44
- * 1. Only when `previewBuild` is given as an object: D2 spawns the recursive preview build and mirrors the editor
45
- * page into its client folder; D3 spawns it next to the static site and writes the dispatcher (`d3-build.ts`),
46
- * failing the build when a failed preview build would leave the site's own on-demand routes unserved; D4 builds
47
- * it in a separate deploy, not here. The preview build mounts `/_conloca/preview/` and bakes in the repository,
48
- * site and branch it serves (every pass must match them), Astro's base and the commit it was built from.
81
+ * 1. Only when `previewBuild` is given as an object: D3 spawns the recursive preview build next to the static site
82
+ * and writes the dispatcher (`d3-build.ts`), failing the build when a failed preview build would leave the
83
+ * site's own on-demand routes unserved; D4 builds it in a separate deploy, not here; D8 spawns nothing: config:setup
84
+ * mounts `/_conloca/preview/` in the site's own build (`d8-build.ts`). Every preview build bakes in the
85
+ * repository, site and branch it serves (every pass must match them), Astro's base and the commit it was built from.
49
86
  */
50
87
  const VIRTUAL_PREVIEW_OPTS = 'virtual:conloca-preview-opts';
51
88
  const RESOLVED_PREVIEW_OPTS = `\0${VIRTUAL_PREVIEW_OPTS}`;
@@ -62,18 +99,14 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
62
99
  // module below. Server-only — never reaches a browser bundle.
63
100
  let previewOptsModule: BakedPreviewOpts | undefined;
64
101
  // The exit values the preview build baked (its config:setup), reported to the site's build for the dispatcher.
65
- let childExit: DispatcherExit | undefined;
102
+ let childExit: PreviewExit | undefined;
66
103
  // The Astro command, recorded in config:setup: only `astro build` starts
67
104
  // the preview build, so only it checks the preview adapter at config:done.
68
105
  let astroCommand: string | undefined;
69
106
  // The project root, captured in config:setup: astro:build:done only hands
70
107
  // over the build's own outDir, but the siteStyles resolve against the root,
71
- // and locating the CHILD build's client dir (for the editor page mirror)
72
- // needs the root the child resolves against.
108
+ // and locating the preview build's output needs the root it resolves against.
73
109
  let projectRoot: URL | undefined;
74
- // Adapter name, finalized only at config:done: the preview build reads it
75
- // when previewBuild names no adapter of its own.
76
- let adapterName: string | undefined;
77
110
  // The site's Vite config, finalized at config:done: the editor page and the
78
111
  // siteStyles compile through it, as they do in conlocaCMS's dev editor. It
79
112
  // holds the site's and integrations' plugins only; Astro adds its own core
@@ -88,21 +121,44 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
88
121
  // The editor options, settled at config:done: conlocaCMS publishes its
89
122
  // channel from its own config:setup, which may run after ours.
90
123
  let inherited: InheritedOptions | undefined;
91
- // Whether the parent build starts the preview build, read with the adapter
92
- // the child will use: previewBuild.adapter, else the project's own.
93
- const previewMode = () =>
94
- previewBuildMode(options.previewBuild, (options.previewBuild || undefined)?.adapter?.name ?? adapterName);
124
+ // How the site's build serves drafts, settled once in config:setup: an option that cannot work turns preview off
125
+ // for this build with a warning rather than failing the deploy.
126
+ let siteMode: 'off' | 'd3' | 'd4' | 'd8' = 'off';
95
127
  // Whether the project has no adapter of its own, read in config:setup before the preview build switches to
96
128
  // server output: such a site can use no server islands, so its dispatcher never runs on their route.
97
129
  let projectStatic = false;
130
+ // The site's adapter, read in config:setup: the d8 edge and isr guards depend on it.
131
+ let adapterName: string | undefined;
98
132
  // The routes the preview build renders on demand (astro:routes:resolved), as Astro patterns.
99
133
  let onDemand: string[] = [];
100
134
  // The site's build: the routes it prerendered (astro:routes:resolved), handed to a D3 child.
101
135
  let sitePrerendered: string[] = [];
136
+ // The site's build: its own on-demand routes (astro:routes:resolved); none means it would be static without preview,
137
+ // undefined that the hook never ran, so nothing is known.
138
+ let siteRoutesOnDemand: string[] | undefined;
139
+ // d8 moved the image endpoint under the preview route (config:setup): only a site with no on-demand page.
140
+ let imageMoved = false;
141
+ // Where the adapter writes its server build (config:done): the Cloudflare adapter's wrangler.json is there.
142
+ let buildServer: URL | undefined;
143
+ // The site's build: its resolved routes (astro:routes:resolved) and config (config:done), for the d8 site-pages list.
144
+ let siteRoutes: IntegrationResolvedRoute[] = [];
145
+ let astroConfig: AstroConfig | undefined;
102
146
  // A D3 child: the routes its site's build prerendered, which it keeps prerendered (config:setup).
103
147
  let keepPrerendered = new Set<string>();
104
148
  // The preview build's mode (config:setup): a D4 child of a static site has no site build to ask.
105
149
  let childServeMode: PreviewServeMode = 'd4';
150
+ // Serves the baked options as `virtual:conloca-preview-opts`, read lazily so the values config:setup bakes are
151
+ // captured.
152
+ const previewOptsPlugin = {
153
+ name: 'conloca-preview-opts',
154
+ resolveId(id: string) {
155
+ return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
156
+ },
157
+ load(id: string) {
158
+ if (id !== RESOLVED_PREVIEW_OPTS) return undefined;
159
+ return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
160
+ },
161
+ };
106
162
 
107
163
  return {
108
164
  name: PACKAGE_NAME,
@@ -112,41 +168,90 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
112
168
  projectRoot = config?.root;
113
169
  astroCommand = command;
114
170
  projectStatic = config?.adapter === undefined;
171
+ adapterName = config?.adapter?.name;
115
172
  // The agent skill: write-if-not-exists, fail-soft, and
116
173
  // never from the recursive preview child (it would race the parent).
117
174
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1' && config?.root) {
118
175
  scaffoldSkill(fileURLToPath(config.root), logger);
119
176
  }
120
177
  logger.info(`integration registered (endpoint=${options.endpoint ?? DEFAULT_EDITOR_ENDPOINT})`);
178
+ if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
179
+ const previewBuild = options.previewBuild || undefined;
180
+ let mode: typeof siteMode = 'off';
181
+ try {
182
+ mode = previewBuildMode(previewBuild, config?.adapter?.name, previewBuild?.adapter?.name);
183
+ // §4.6: refused before anything registers, since d8's own middleware is what breaks an edge build.
184
+ if (mode === 'd8' && command === 'build') {
185
+ const text = readAstroConfigText(config.root);
186
+ const name = config.adapter?.name ?? '';
187
+ let refusal = d8ConfigRefusal(text, name, config.base);
188
+ // Only these adapters' config:done merely stores state, so only they may be called out of order.
189
+ if (refusal === null && config.adapter && (name === '@astrojs/vercel' || name === '@astrojs/netlify')) {
190
+ refusal = d8EdgeRefusal(await adapterMiddlewareMode(config.adapter, config), text, name);
191
+ }
192
+ if (refusal !== null) {
193
+ logger.warn(`preview is off for this build: ${refusal}`);
194
+ mode = 'off';
195
+ }
196
+ }
197
+ if (mode !== 'off' && command === 'build' && previewBuild?.required !== undefined) {
198
+ logger.warn('previewBuild.required has no effect: a failed preview build is handled the same either way');
199
+ }
200
+ // Only `astro build` serves d8 drafts: dev, sync, check and preview read no git or sites.json for it.
201
+ if (mode === 'd8' && command === 'build') {
202
+ for (const name of ['config', 'outDir'] as const) {
203
+ if (previewBuild?.[name] !== undefined) {
204
+ logger.warn(`previewBuild.${name} has no effect on this site: drafts render in the site's own build`);
205
+ }
206
+ }
207
+ previewOptsModule = await d8Baked({ options, config, repoUri, env: process.env });
208
+ // The draft preview renders in this build, at the preview route its own copy of the page handler
209
+ // serves. A site without a recent astro-cms throws here, before anything is injected.
210
+ const entrypoint = previewPageHandlerPath(config.root);
211
+ // A hybrid site keeps its `/_image` for drafts too: Astro reads `image.endpoint` once, before routes
212
+ // exist, and its on-demand pages need the real one. A third-party service may build live `<Image>` URLs
213
+ // from the route, so only known services move it. Read before registering: nothing below may throw.
214
+ const moveImage =
215
+ knownImageService(config.image?.service?.entrypoint) && !(await hasOnDemandRoutes(config));
216
+ injectRoute({ pattern: `${PREVIEW_ROUTE_SEGMENT}/[...path]`, entrypoint, prerender: false });
217
+ addMiddleware({ entrypoint: '@conloca/cloud-astro/d8-middleware', order: 'pre' });
218
+ // The middleware's Cloudflare runtime import, as in the preview build below.
219
+ updateConfig({
220
+ vite: { build: { rollupOptions: { external: [/^cloudflare:/] } }, plugins: [previewOptsPlugin] },
221
+ });
222
+ // Last, so a refusal or throw above never moves it.
223
+ if (moveImage) {
224
+ updateConfig({
225
+ image: {
226
+ endpoint: {
227
+ route: `${PREVIEW_ROUTE_SEGMENT}/_image`,
228
+ entrypoint: d8ImageEndpoint(config.adapter?.name ?? ''),
229
+ },
230
+ },
231
+ });
232
+ imageMoved = true;
233
+ }
234
+ }
235
+ siteMode = mode;
236
+ } catch (error) {
237
+ // conlocaCMS publishes the content root from its own config:setup, which runs first only when listed first.
238
+ const hint =
239
+ mode === 'd8' && !process.env.CONLOCA_CONTENT_ROOT
240
+ ? '; list conlocaCloud() after conlocaCMS() in astro.config'
241
+ : '';
242
+ logger.warn(`preview is off for this build: ${messageOf(error)}${hint}`);
243
+ }
244
+ }
121
245
 
122
246
  // Only the recursive preview build (which sets PREVIEW_BUILD_ENV_FLAG)
123
247
  // mounts the SSR catch-all that renders previews; a site's normal
124
248
  // build never exposes it. The route is fixed and public: the signed
125
249
  // pass, checked against what this build bakes in, is the lock.
126
250
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
127
- if (!repoUri) {
128
- throw new Error(
129
- `${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
130
- '(build in a Git checkout or set repoUri as an advanced override)',
131
- );
132
- }
133
- // The project's own checkout answers git, not the directory the
134
- // build was started from.
135
- const projectGit = (args: string[]) => gitOutput(args, fileURLToPath(config.root));
136
- const buildRef = resolveBuildRef(process.env, projectGit);
137
- if (!buildRef.branch) {
138
- throw new Error(
139
- `${PACKAGE_NAME}: could not determine the branch the preview build serves (set CF_PAGES_BRANCH, ` +
140
- 'WORKERS_CI_BRANCH, VERCEL_GIT_COMMIT_REF or GITHUB_REF_NAME, or build in a git checkout on a branch)',
141
- );
142
- }
251
+ const baked = bakedIdentity({ options, config, repoUri, env: process.env });
143
252
  const childMode = previewChildMode(process.env);
144
253
  childServeMode = childMode;
145
254
  keepPrerendered = previewChildPrerendered(process.env);
146
- const siteId = resolveBuildSiteId({
147
- contentRoot: process.env.CONLOCA_CONTENT_ROOT,
148
- override: options.siteId,
149
- });
150
255
  injectRoute({
151
256
  pattern: `${PREVIEW_ROUTE_SEGMENT}/[...path]`,
152
257
  entrypoint: '@conloca/cloud-astro/preview-handler',
@@ -160,39 +265,13 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
160
265
  // published content after one page view. Fail-open — an
161
266
  // uncredentialed visitor gets the ordinary page.
162
267
  addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware', order: 'pre' });
163
- // The commit this preview build's checkout holds: a PR build may
164
- // check out a merge commit rather than the commit CI hands over.
165
- // Page-status compares the branch's latest commit with it, so the
166
- // endpoint diffs against the content actually serving, not a newer
167
- // commit whose deploy never landed. A checkout commit the
168
- // endpoint does not have makes it render from the branch instead.
169
- const buildCommit = projectGit(['rev-parse', 'HEAD']) ?? buildRef.gitSha;
170
- // Bake the middleware's configuration into the artifact. Every value
171
- // is already known here — endpoint and audience are integration
172
- // options; repository, site, branch, base and commit are what this
173
- // build was made from, and every pass must match the first three —
174
- // so a correctly built preview deployment needs NO env vars set on
175
- // it. `saasIssuer` stays unbaked unless configured: it is a property
176
- // of the endpoint, not of the site.
177
- previewOptsModule = {
178
- saasEndpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
179
- // The token's `aud` is the repo URI this build resolved.
180
- saasAudience: repoUri,
181
- ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
182
- ...(buildCommit ? { buildCommit } : {}),
183
- repo: repoUri,
184
- siteId,
185
- branch: buildRef.branch,
186
- base: config.base ?? '/',
187
- mode: childMode,
188
- };
189
- // The dispatcher's exit route answers with these: the values every pass is checked against, already
190
- // narrowed by the two throws above.
268
+ previewOptsModule = { ...baked, mode: childMode };
269
+ // The dispatcher's exit route answers with these: the values every pass is checked against.
191
270
  childExit = {
192
- repo: repoUri,
193
- siteId,
194
- branch: buildRef.branch,
195
- audience: repoUri,
271
+ repo: baked.repo,
272
+ siteId: baked.siteId,
273
+ branch: baked.branch,
274
+ audience: baked.repo,
196
275
  ...(options.saasIssuer ? { issuer: options.saasIssuer } : {}),
197
276
  };
198
277
  // Preview-build path: the child build must emit an SSR
@@ -201,27 +280,16 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
201
280
  // adapter stays in force when it already has one), and write to a
202
281
  // SEPARATE outDir so the child never clobbers the primary dist/.
203
282
  const previewBuild = options.previewBuild || {};
283
+ // The site's build settled its own mode; a build started with the flag alone is a separate preview deploy,
284
+ // so it is checked as one: refused under an adapter that deploys from the project root, and with
285
+ // previewBuild.adapter.
286
+ previewBuildMode(
287
+ childMode === 'd4' ? { ...previewBuild, separate: true } : previewBuild,
288
+ config.adapter?.name,
289
+ previewBuild.adapter?.name,
290
+ );
204
291
  // A site that names no adapter builds its preview server for Cloudflare Workers: next to it (D3) or apart (D4).
205
- const adapter =
206
- previewBuild.adapter ??
207
- config.adapter ??
208
- (childMode === 'd2' ? undefined : await cloudflareAdapter(config.root, childMode));
209
- // Throws for a refused adapter — the parent already checked, this keeps the child honest.
210
- previewBuildMode(previewBuild, adapter?.name);
211
- // Astro allows exactly one deployment integration. Adding
212
- // previewBuild.adapter next to the project's own would make the
213
- // child build die on Astro's adapter-conflict error, which names
214
- // neither this integration nor the option — fail here with the
215
- // actual cause. The child inherits the project adapter, so the
216
- // option is unnecessary on SSR projects.
217
- if (previewBuild.adapter && config.adapter) {
218
- const projectAdapterName = config.adapter.name;
219
- throw new Error(
220
- `${PACKAGE_NAME}: previewBuild.adapter conflicts with the project's own adapter ` +
221
- `(${projectAdapterName}) — Astro allows only one deployment integration per build. ` +
222
- 'Remove previewBuild.adapter; the preview build inherits the project adapter.',
223
- );
224
- }
292
+ const adapter = config.adapter ?? (await cloudflareAdapter(config.root, childMode));
225
293
  // Trailing slash so URL-joining treats it as a directory. Astro
226
294
  // derives build.client/build.server from outDir BEFORE hooks run,
227
295
  // so overriding outDir alone still writes into the primary dist/ —
@@ -273,19 +341,7 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
273
341
  },
274
342
  }
275
343
  : {}),
276
- plugins: [
277
- {
278
- name: 'conloca-preview-opts',
279
- resolveId(id: string) {
280
- return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
281
- },
282
- load(id: string) {
283
- if (id !== RESOLVED_PREVIEW_OPTS) return undefined;
284
- // Read lazily so the values assigned above are captured.
285
- return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
286
- },
287
- },
288
- ],
344
+ plugins: [previewOptsPlugin],
289
345
  },
290
346
  // The adapter must ride in BOTH ways: as `adapter` because the
291
347
  // build gate checks `config.adapter` before creating the SSR
@@ -330,7 +386,7 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
330
386
  const pattern = 'route' in route && typeof route.route === 'string' ? route.route : '';
331
387
  // A D3 child keeps prerendered what its static site's build prerendered, endpoints included: on demand, a
332
388
  // getStaticPaths route would lose its props, and the dispatcher would have to run on it in production. Its
333
- // own on-demand routes (and every route of a D2 child) keep their own setting.
389
+ // own on-demand routes keep their own setting.
334
390
  if (!cms && keepPrerendered.has(prerenderedKey(pattern, route.component))) {
335
391
  route.prerender = true;
336
392
  return;
@@ -363,11 +419,20 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
363
419
  route.prerender = false;
364
420
  logger.debug(`preview build: forcing on-demand rendering for ${route.component}`);
365
421
  },
366
- 'astro:routes:resolved': ({ routes }) => {
422
+ 'astro:routes:resolved': ({ routes, logger }) => {
367
423
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
368
424
  sitePrerendered = routes
369
425
  .filter((route) => route.isPrerendered)
370
426
  .map((route) => prerenderedKey(route.pattern, route.entrypoint));
427
+ siteRoutesOnDemand = siteOnDemand(routes, PREVIEW_ROUTE_SEGMENT);
428
+ siteRoutes = routes;
429
+ if (imageMoved) {
430
+ for (const route of siteRoutesOnDemand) {
431
+ logger.warn(
432
+ `preview moved the image endpoint, but ${route} renders on demand and was not visible when astro.config was read: its images are served untransformed while preview is on`,
433
+ );
434
+ }
435
+ }
371
436
  return;
372
437
  }
373
438
  // Astro injects the server-islands route whenever an adapter is set, but refuses islands without one: a static
@@ -376,30 +441,46 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
376
441
  onDemand = onDemandPatterns(used);
377
442
  },
378
443
  'astro:config:done': ({ config, logger }) => {
379
- adapterName = config.adapter?.name;
380
444
  viteConfig = config.vite;
381
445
  astroBase = config.base ?? '/';
382
446
  srcDir = config.srcDir;
383
447
  serverOutput = config.output === 'server';
384
448
  i18n = config.i18n;
449
+ // Optional-chained: unit tests drive this hook with a partial config.
450
+ buildServer = config.build?.server;
451
+ astroConfig = config;
385
452
  inherited = resolveInheritedOptions(options, readEditorDescriptors());
386
- // A refused or missing preview adapter fails `astro build` here,
387
- // before the site builds, rather than after it. `astro dev`, `sync`
388
- // and `preview` never start the preview build, so they are left
389
- // alone. The child build checks its own.
390
- if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
391
- const mode = previewMode();
392
- // D3 builds its preview server with @astrojs/cloudflare: missing, the build fails here, before the site builds.
393
- if (mode === 'd3' && projectRoot !== undefined) resolveCloudflareAdapter(fileURLToPath(projectRoot));
394
- if (mode === 'd2' && adapterName === undefined) {
453
+ // d8 and D3 child builds: the media folder conlocaCMS settled in its config:setup, listed as this build deploys it.
454
+ if (previewOptsModule !== undefined && bakesMedia(previewOptsModule.mode)) {
455
+ try {
456
+ const media = bakedMedia(readEditorDescriptors(), config.root);
457
+ if (media !== undefined) previewOptsModule = { ...previewOptsModule, media };
458
+ } catch (error) {
459
+ // Never fail the site's build over it: draft uploads still show, images committed on the branch don't.
395
460
  logger.warn(
396
- 'previewBuild.adapter on a static site serves drafts from the deployed preview server; remove ' +
397
- 'previewBuild.adapter to serve them next to the static site on Cloudflare Workers instead',
461
+ `drafts won't show images committed on the branch: can't list the media folder: ${messageOf(error)}`,
398
462
  );
399
463
  }
400
464
  }
465
+ // A missing Cloudflare adapter fails `astro build` here, before the
466
+ // site builds, rather than after it. `astro dev`, `sync` and
467
+ // `preview` never start the preview build, so they are left alone.
468
+ if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
469
+ // D3 builds its preview server with @astrojs/cloudflare: missing, the build fails here, before the site builds.
470
+ if (siteMode === 'd3' && projectRoot !== undefined) resolveCloudflareAdapter(fileURLToPath(projectRoot));
471
+ }
401
472
  },
402
- 'astro:build:done': async ({ dir, logger, pages }) => {
473
+ // Can't happen: config:setup turns d8 off for edge middleware before registering any; reaching this is a guard bug.
474
+ 'astro:build:ssr': ({ middlewareEntryPoint }) => {
475
+ if (
476
+ siteMode === 'd8' &&
477
+ middlewareEntryPoint !== undefined &&
478
+ (adapterName === '@astrojs/vercel' || adapterName === '@astrojs/netlify')
479
+ ) {
480
+ throw new Error(`${PACKAGE_NAME}: ${D8_EDGE_REFUSAL}`);
481
+ }
482
+ },
483
+ 'astro:build:done': async ({ dir, logger, pages, assets }) => {
403
484
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
404
485
  // The recursive preview build sets this flag on the child Astro process. Writing the editor page there
405
486
  // again would race the parent, which writes its own; the child reports only what the parent reads.
@@ -435,7 +516,66 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
435
516
  );
436
517
  }
437
518
 
438
- const mode = previewMode();
519
+ // §4.6 backstop for an isr config the text could not read (computed options): the adapter's build:done ran
520
+ // first, so its routes are written. The prefix answers a static 404, so no draft is ever cached.
521
+ const vercelConfig = new URL('.vercel/output/config.json', projectRoot);
522
+ if (siteMode === 'd8' && adapterName === '@astrojs/vercel') {
523
+ try {
524
+ const routes: unknown = existsSync(vercelConfig) ? JSON.parse(readFileSync(vercelConfig, 'utf8')) : null;
525
+ if (vercelIsrCatchesPrefix(routes, astroBase)) {
526
+ writeFileSync(vercelConfig, JSON.stringify(darkenIsrPrefix(routes, astroBase), null, 2));
527
+ logger.warn(`preview is off for this build: ${d8IsrRefusal(astroBase)}`);
528
+ siteMode = 'off';
529
+ }
530
+ } catch (error) {
531
+ // Decision (f): never fail the site build; with the routes unchecked, no draft may be served.
532
+ logger.warn(
533
+ `preview is off for this build: couldn't check .vercel/output/config.json: ${messageOf(error)}`,
534
+ );
535
+ siteMode = 'off';
536
+ }
537
+ }
538
+ // After the backstop, so a darkened prefix stays as it is: keep visitors' misses off the preview function.
539
+ if (siteMode === 'd8' && adapterName === '@astrojs/vercel' && existsSync(vercelConfig)) {
540
+ try {
541
+ const config: unknown = JSON.parse(readFileSync(vercelConfig, 'utf8'));
542
+ const narrowed = narrowVercelCatchAll(config, siteRoutesOnDemand?.length === 0);
543
+ if (narrowed !== null && 'config' in narrowed) {
544
+ writeFileSync(vercelConfig, JSON.stringify(narrowed.config, null, 2));
545
+ } else if (narrowed !== null) {
546
+ logger.warn(
547
+ `misses on this site run the preview function: add src/pages/404.astro (.vercel/output/config.json: ${narrowed.leave})`,
548
+ );
549
+ }
550
+ } catch (error) {
551
+ // Decision (f): drafts still render; only what a miss costs changes.
552
+ logger.warn(
553
+ `misses on this site run the preview function: couldn't narrow .vercel/output/config.json: ${messageOf(error)}`,
554
+ );
555
+ }
556
+ }
557
+ if (siteMode === 'd8' && adapterName === '@astrojs/cloudflare') {
558
+ try {
559
+ const expected = [
560
+ // A moved image endpoint is under `<prefix>/*`; `<base>_image` then serves nothing.
561
+ ...previewOwnEntries(astroBase).filter((entry) => !imageMoved || entry !== imageEndpointEntry(astroBase)),
562
+ // With not_found_handling "404-page", a static site's `server:defer` islands would get the 404 page.
563
+ workerFirstPattern('/_server-islands/[name]', astroBase),
564
+ ...(siteRoutesOnDemand ?? []).map((pattern) => workerFirstPattern(pattern, astroBase)),
565
+ ];
566
+ await writeWorkerFirst(fileURLToPath(projectRoot), expected);
567
+ // An SSR site's misses reached its Cloudflare Worker before preview, too.
568
+ if (siteRoutesOnDemand?.length === 0 && buildServer !== undefined) {
569
+ const wrangler: unknown = JSON.parse(readFileSync(new URL('wrangler.json', buildServer), 'utf8'));
570
+ for (const problem of cloudflareD8Problems(wrangler, expected)) {
571
+ logger.warn(`${problem} (\`conloca connect --update --yes\` applies this once the CLI supports d8)`);
572
+ }
573
+ }
574
+ } catch (error) {
575
+ logger.warn(`preview: couldn't check the Cloudflare routing: ${messageOf(error)}`);
576
+ }
577
+ }
578
+ const mode = siteMode;
439
579
  // The editor page: every build writes it.
440
580
  await emitEditorPage({
441
581
  dir: fileURLToPath(dir),
@@ -452,22 +592,21 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
452
592
  i18n,
453
593
  logger,
454
594
  });
595
+ // After the editor page: on Cloudflare the list goes in its folder, which the editor page must create.
596
+ if (mode === 'd8' && adapterName !== undefined && astroConfig !== undefined) {
597
+ try {
598
+ const sitePages = sitePagesOf(pages ?? [], assets ?? new Map(), siteRoutes, dir, astroBase);
599
+ await writeSitePagesList(adapterName, astroConfig, sitePages);
600
+ } catch (error) {
601
+ // Decision (f): drafts still render; the site's own pages just aren't kept inside the preview.
602
+ logger.warn(`preview: the site-pages list failed: ${messageOf(error)}`);
603
+ }
604
+ }
455
605
 
456
606
  // Strict opt-in: only a previewBuild given as an object starts the second build. D4 builds it elsewhere.
457
607
  const previewBuild = options.previewBuild || undefined;
458
- if (previewBuild === undefined || mode === 'off' || mode === 'd4') return;
608
+ if (previewBuild === undefined || mode !== 'd3') return;
459
609
  const previewOut = previewOutDir(previewBuild, projectRoot);
460
- if (mode === 'd2') {
461
- await spawnPreviewBuild(previewBuild, 'd2');
462
- // The child build cannot write the editor files itself (it
463
- // short-circuits this hook — see the recursion guard above), but in
464
- // a deployment that serves the site and the preview from one
465
- // Cloudflare Worker its client dir is THE asset set serving the site,
466
- // so the editor files must be there too. Mirror them from this build's dist.
467
- await mirrorEditorPage(fileURLToPath(dir), fileURLToPath(new URL('client/', previewOut)));
468
- logger.info('editor page mirrored into the preview client dir');
469
- return;
470
- }
471
610
  // D3: a failed preview build is isolated unless its server also serves the live site (finishD3Build decides).
472
611
  let built = true;
473
612
  try {
package/src/node.ts CHANGED
@@ -9,6 +9,10 @@ export {
9
9
  type EditorHostPageData,
10
10
  type EditorPageInfo,
11
11
  } from '@conloca/content-api/editor-host';
12
+ // The adapter releases and host rate-limit lines connect and doctor share.
13
+ export { D8_TESTED_ADAPTERS, d8RateLimitLines } from './d8-adapters.js';
14
+ // The d8 config-text refusals `conloca connect` checks before it writes an adapter's options.
15
+ export { d8ConfigRefusal, d8EdgeRefusal } from './d8-guards.js';
12
16
  // The /_conloca/editor/ header rules that `conloca connect` writes and doctor checks.
13
17
  export {
14
18
  type FramingBlocker,
@@ -14,10 +14,26 @@ export interface BakedPreviewOpts {
14
14
  branch?: string;
15
15
  /** Astro's `base` at build time. */
16
16
  base?: string;
17
- /** How this build serves previews (`d2` when not baked). */
17
+ /** How this build serves previews: `d2`, `d3`, `d4` or `d8` (`d2` when not baked). */
18
18
  mode?: PreviewServeMode;
19
+ /** D8: hosts sites.json declares, so links to them are links to this site. */
20
+ domains?: string[];
21
+ /** D8: Astro's `trailingSlash` and `build.format`, for the links the draft render moves under the route. */
22
+ trailingSlash?: 'always' | 'never' | 'ignore';
23
+ buildFormat?: 'directory' | 'file' | 'preserve';
24
+ /** D8: where the render reads the pages the site prerendered itself (`./site-page-sources.ts`). */
25
+ sitePages?: BakedSitePages;
26
+ /** D3 and D8: the media folder's link base and the images under it the build deployed, relative to it. */
27
+ media?: { refBase: string; deployed: string[] };
19
28
  }
20
29
 
30
+ /** Node reads its own disk; Cloudflare its assets; Vercel and Netlify the function's list and, on production, the site. */
31
+ export type BakedSitePages =
32
+ | { kind: 'disk'; serverEntry: string }
33
+ | { kind: 'assets' }
34
+ | { kind: 'function'; serverEntry: string; origin: string | null }
35
+ | { kind: 'none' };
36
+
21
37
  /** A value only the build can bake; the deployment cannot supply it. */
22
38
  function bakedOnly(name: string, bakedValue: string | undefined): string {
23
39
  if (bakedValue) return bakedValue;