@conloca/cloud-astro 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +75 -24
  2. package/dist/.build-inputs.json +47 -29
  3. package/dist/src/component-manifest.d.ts +11 -0
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +20 -2
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +4 -4
  8. package/dist/src/constants.js +4 -4
  9. package/dist/src/d3-build.d.ts +6 -2
  10. package/dist/src/d3-build.d.ts.map +1 -1
  11. package/dist/src/d3-build.js +15 -11
  12. package/dist/src/d3-build.js.map +1 -1
  13. package/dist/src/d8-adapters.d.ts +10 -0
  14. package/dist/src/d8-adapters.d.ts.map +1 -0
  15. package/dist/src/d8-adapters.js +19 -0
  16. package/dist/src/d8-adapters.js.map +1 -0
  17. package/dist/src/d8-build.d.ts +99 -0
  18. package/dist/src/d8-build.d.ts.map +1 -0
  19. package/dist/src/d8-build.js +265 -0
  20. package/dist/src/d8-build.js.map +1 -0
  21. package/dist/src/d8-guards.d.ts +29 -0
  22. package/dist/src/d8-guards.d.ts.map +1 -0
  23. package/dist/src/d8-guards.js +145 -0
  24. package/dist/src/d8-guards.js.map +1 -0
  25. package/dist/src/d8-middleware.d.ts +7 -0
  26. package/dist/src/d8-middleware.d.ts.map +1 -0
  27. package/dist/src/d8-middleware.js +15 -0
  28. package/dist/src/d8-middleware.js.map +1 -0
  29. package/dist/src/d8-render.d.ts +9 -0
  30. package/dist/src/d8-render.d.ts.map +1 -0
  31. package/dist/src/d8-render.js +52 -0
  32. package/dist/src/d8-render.js.map +1 -0
  33. package/dist/src/descriptors.d.ts.map +1 -1
  34. package/dist/src/descriptors.js +6 -2
  35. package/dist/src/descriptors.js.map +1 -1
  36. package/dist/src/doctor/ancestor-chain.d.ts +14 -0
  37. package/dist/src/doctor/ancestor-chain.d.ts.map +1 -0
  38. package/dist/src/doctor/ancestor-chain.js +57 -0
  39. package/dist/src/doctor/ancestor-chain.js.map +1 -0
  40. package/dist/src/doctor/checks-d8.d.ts +7 -0
  41. package/dist/src/doctor/checks-d8.d.ts.map +1 -0
  42. package/dist/src/doctor/checks-d8.js +240 -0
  43. package/dist/src/doctor/checks-d8.js.map +1 -0
  44. package/dist/src/doctor/checks-frames.d.ts +5 -0
  45. package/dist/src/doctor/checks-frames.d.ts.map +1 -0
  46. package/dist/src/doctor/checks-frames.js +78 -0
  47. package/dist/src/doctor/checks-frames.js.map +1 -0
  48. package/dist/src/doctor/checks-live.d.ts +5 -14
  49. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  50. package/dist/src/doctor/checks-live.js +9 -21
  51. package/dist/src/doctor/checks-live.js.map +1 -1
  52. package/dist/src/doctor/checks-offline.d.ts +2 -0
  53. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  54. package/dist/src/doctor/checks-offline.js +17 -8
  55. package/dist/src/doctor/checks-offline.js.map +1 -1
  56. package/dist/src/doctor/checks-preview-live.d.ts +7 -2
  57. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -1
  58. package/dist/src/doctor/checks-preview-live.js +107 -7
  59. package/dist/src/doctor/checks-preview-live.js.map +1 -1
  60. package/dist/src/doctor/checks-preview.d.ts.map +1 -1
  61. package/dist/src/doctor/checks-preview.js +9 -4
  62. package/dist/src/doctor/checks-preview.js.map +1 -1
  63. package/dist/src/doctor/config-scan.d.ts +24 -6
  64. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  65. package/dist/src/doctor/config-scan.js +89 -18
  66. package/dist/src/doctor/config-scan.js.map +1 -1
  67. package/dist/src/doctor/request.d.ts +14 -0
  68. package/dist/src/doctor/request.d.ts.map +1 -0
  69. package/dist/src/doctor/request.js +17 -0
  70. package/dist/src/doctor/request.js.map +1 -0
  71. package/dist/src/doctor/run.d.ts.map +1 -1
  72. package/dist/src/doctor/run.js +2 -0
  73. package/dist/src/doctor/run.js.map +1 -1
  74. package/dist/src/doctor/types.d.ts +8 -0
  75. package/dist/src/doctor/types.d.ts.map +1 -1
  76. package/dist/src/doctor/types.js +8 -0
  77. package/dist/src/doctor/types.js.map +1 -1
  78. package/dist/src/editor-page/bundle.d.ts +4 -0
  79. package/dist/src/editor-page/bundle.d.ts.map +1 -1
  80. package/dist/src/editor-page/bundle.js +55 -7
  81. package/dist/src/editor-page/bundle.js.map +1 -1
  82. package/dist/src/editor-page/data-schemas.d.ts +19 -5
  83. package/dist/src/editor-page/data-schemas.d.ts.map +1 -1
  84. package/dist/src/editor-page/data-schemas.js +17 -13
  85. package/dist/src/editor-page/data-schemas.js.map +1 -1
  86. package/dist/src/editor-page/emit.d.ts +7 -3
  87. package/dist/src/editor-page/emit.d.ts.map +1 -1
  88. package/dist/src/editor-page/emit.js +36 -19
  89. package/dist/src/editor-page/emit.js.map +1 -1
  90. package/dist/src/editor-page/frame-chains.d.ts +51 -0
  91. package/dist/src/editor-page/frame-chains.d.ts.map +1 -0
  92. package/dist/src/editor-page/frame-chains.js +121 -0
  93. package/dist/src/editor-page/frame-chains.js.map +1 -0
  94. package/dist/src/editor-page/page.d.ts +1 -3
  95. package/dist/src/editor-page/page.d.ts.map +1 -1
  96. package/dist/src/editor-page/page.js +3 -5
  97. package/dist/src/editor-page/page.js.map +1 -1
  98. package/dist/src/integration.d.ts.map +1 -1
  99. package/dist/src/integration.js +231 -124
  100. package/dist/src/integration.js.map +1 -1
  101. package/dist/src/node.d.ts +2 -0
  102. package/dist/src/node.d.ts.map +1 -1
  103. package/dist/src/node.js +4 -0
  104. package/dist/src/node.js.map +1 -1
  105. package/dist/src/preview/_resolve-opts.d.ts +26 -1
  106. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  107. package/dist/src/preview/_resolve-opts.js.map +1 -1
  108. package/dist/src/preview/banner.d.ts +3 -2
  109. package/dist/src/preview/banner.d.ts.map +1 -1
  110. package/dist/src/preview/banner.js +15 -6
  111. package/dist/src/preview/banner.js.map +1 -1
  112. package/dist/src/preview/content-api.d.ts +23 -1
  113. package/dist/src/preview/content-api.d.ts.map +1 -1
  114. package/dist/src/preview/content-api.js +73 -7
  115. package/dist/src/preview/content-api.js.map +1 -1
  116. package/dist/src/preview/d8-middleware.d.ts +25 -0
  117. package/dist/src/preview/d8-middleware.d.ts.map +1 -0
  118. package/dist/src/preview/d8-middleware.js +94 -0
  119. package/dist/src/preview/d8-middleware.js.map +1 -0
  120. package/dist/src/preview/dispatcher.d.ts +3 -16
  121. package/dist/src/preview/dispatcher.d.ts.map +1 -1
  122. package/dist/src/preview/dispatcher.js +54 -136
  123. package/dist/src/preview/dispatcher.js.map +1 -1
  124. package/dist/src/preview/headers.d.ts +3 -0
  125. package/dist/src/preview/headers.d.ts.map +1 -1
  126. package/dist/src/preview/headers.js +10 -1
  127. package/dist/src/preview/headers.js.map +1 -1
  128. package/dist/src/preview/links.d.ts +23 -0
  129. package/dist/src/preview/links.d.ts.map +1 -0
  130. package/dist/src/preview/links.js +168 -0
  131. package/dist/src/preview/links.js.map +1 -0
  132. package/dist/src/preview/middleware.d.ts +9 -3
  133. package/dist/src/preview/middleware.d.ts.map +1 -1
  134. package/dist/src/preview/middleware.js +36 -16
  135. package/dist/src/preview/middleware.js.map +1 -1
  136. package/dist/src/preview/prefix-router.d.ts +67 -0
  137. package/dist/src/preview/prefix-router.d.ts.map +1 -0
  138. package/dist/src/preview/prefix-router.js +153 -0
  139. package/dist/src/preview/prefix-router.js.map +1 -0
  140. package/dist/src/preview/preview-path.d.ts +8 -3
  141. package/dist/src/preview/preview-path.d.ts.map +1 -1
  142. package/dist/src/preview/preview-path.js +16 -4
  143. package/dist/src/preview/preview-path.js.map +1 -1
  144. package/dist/src/preview/site-middleware.d.ts +8 -2
  145. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  146. package/dist/src/preview/site-middleware.js +95 -31
  147. package/dist/src/preview/site-middleware.js.map +1 -1
  148. package/dist/src/preview/site-page-sources.d.ts +21 -0
  149. package/dist/src/preview/site-page-sources.d.ts.map +1 -0
  150. package/dist/src/preview/site-page-sources.js +129 -0
  151. package/dist/src/preview/site-page-sources.js.map +1 -0
  152. package/dist/src/preview/site-pages.d.ts +18 -0
  153. package/dist/src/preview/site-pages.d.ts.map +1 -0
  154. package/dist/src/preview/site-pages.js +7 -0
  155. package/dist/src/preview/site-pages.js.map +1 -0
  156. package/dist/src/preview/unready-pages.d.ts +21 -0
  157. package/dist/src/preview/unready-pages.d.ts.map +1 -0
  158. package/dist/src/preview/unready-pages.js +54 -0
  159. package/dist/src/preview/unready-pages.js.map +1 -0
  160. package/dist/src/preview-build.d.ts +17 -16
  161. package/dist/src/preview-build.d.ts.map +1 -1
  162. package/dist/src/preview-build.js +37 -40
  163. package/dist/src/preview-build.js.map +1 -1
  164. package/dist/src/preview-image-endpoint.d.ts +8 -0
  165. package/dist/src/preview-image-endpoint.d.ts.map +1 -0
  166. package/dist/src/preview-image-endpoint.js +34 -0
  167. package/dist/src/preview-image-endpoint.js.map +1 -0
  168. package/dist/src/preview-render-seams.d.ts +7 -0
  169. package/dist/src/preview-render-seams.d.ts.map +1 -0
  170. package/dist/src/preview-render-seams.js +27 -0
  171. package/dist/src/preview-render-seams.js.map +1 -0
  172. package/dist/src/site-middleware.d.ts +2 -4
  173. package/dist/src/site-middleware.d.ts.map +1 -1
  174. package/dist/src/site-middleware.js +6 -22
  175. package/dist/src/site-middleware.js.map +1 -1
  176. package/dist/src/types.d.ts +15 -16
  177. package/dist/src/types.d.ts.map +1 -1
  178. package/package.json +138 -6
  179. package/src/component-manifest.ts +30 -4
  180. package/src/constants.ts +4 -4
  181. package/src/d3-build.ts +20 -14
  182. package/src/d8-adapters.ts +19 -0
  183. package/src/d8-build.ts +356 -0
  184. package/src/d8-guards.ts +177 -0
  185. package/src/d8-middleware.ts +17 -0
  186. package/src/d8-render.ts +61 -0
  187. package/src/descriptors.ts +6 -2
  188. package/src/doctor/ancestor-chain.ts +58 -0
  189. package/src/doctor/checks-d8.ts +256 -0
  190. package/src/doctor/checks-frames.ts +84 -0
  191. package/src/doctor/checks-live.ts +10 -39
  192. package/src/doctor/checks-offline.ts +21 -8
  193. package/src/doctor/checks-preview-live.ts +114 -8
  194. package/src/doctor/checks-preview.ts +9 -4
  195. package/src/doctor/config-scan.ts +86 -15
  196. package/src/doctor/request.ts +27 -0
  197. package/src/doctor/run.ts +2 -0
  198. package/src/doctor/types.ts +9 -0
  199. package/src/editor-page/bundle.ts +65 -7
  200. package/src/editor-page/data-schemas.ts +30 -16
  201. package/src/editor-page/emit.ts +52 -24
  202. package/src/editor-page/frame-chains.ts +143 -0
  203. package/src/editor-page/page.ts +3 -4
  204. package/src/integration.ts +277 -135
  205. package/src/node.ts +4 -0
  206. package/src/preview/_resolve-opts.ts +17 -1
  207. package/src/preview/banner.ts +17 -4
  208. package/src/preview/content-api.ts +78 -6
  209. package/src/preview/d8-middleware.ts +124 -0
  210. package/src/preview/dispatcher.ts +63 -153
  211. package/src/preview/headers.ts +10 -1
  212. package/src/preview/links.ts +175 -0
  213. package/src/preview/middleware.ts +41 -19
  214. package/src/preview/prefix-router.ts +197 -0
  215. package/src/preview/preview-path.ts +24 -6
  216. package/src/preview/site-middleware.ts +114 -38
  217. package/src/preview/site-page-sources.ts +146 -0
  218. package/src/preview/site-pages.ts +22 -0
  219. package/src/preview/unready-pages.ts +65 -0
  220. package/src/preview-build.ts +43 -42
  221. package/src/preview-image-endpoint.ts +35 -0
  222. package/src/preview-render-seams.ts +31 -0
  223. package/src/site-middleware.ts +6 -24
  224. package/src/skill/SKILL.md +25 -2
  225. package/src/types.ts +15 -16
  226. package/src/virtual-modules.d.ts +17 -2
@@ -27,19 +27,26 @@
27
27
  */
28
28
 
29
29
  import type { ContentAPI } from '@conloca/content-api';
30
+ import { isSluggedPreviewMode } from '@conloca/content-api/editor-host';
30
31
  import { fetchPageStatus, isShareEndedKind, type PageStatus } from './_dispatch.js';
32
+ import type { BakedPreviewOpts } from './_resolve-opts.js';
31
33
  import { injectPreviewBanner } from './banner.js';
32
34
  import { PreviewContentAPI } from './content-api.js';
33
35
  import { applyPreviewHeaders, PREVIEW_CACHE_HEADERS } from './headers.js';
34
36
  import { renderPreviewUnavailable, renderShareEnded } from './landing.js';
37
+ import { rewritePreviewLinks } from './links.js';
35
38
  import { handlePreviewRequest, type PreviewContext, type PreviewMiddlewareOptions } from './middleware.js';
39
+ import { finishEntry, routePrefixed } from './prefix-router.js';
36
40
  import {
41
+ cleanPagePath,
37
42
  normalizeTrailingSlash,
38
43
  PREVIEW_SLUG_HEADER,
39
44
  pathUnderBase,
40
45
  previewScope,
41
46
  stripPreviewPrefix,
42
47
  } from './preview-path.js';
48
+ import { NO_SITE_PAGES, type SitePageSource } from './site-pages.js';
49
+ import { loadUnreadyPages, type UnreadyPage } from './unready-pages.js';
43
50
 
44
51
  /** The subset of Astro's middleware context this middleware touches. */
45
52
  export interface PreviewMiddlewareContext {
@@ -54,7 +61,7 @@ export type PreviewMiddlewareNext = () => Promise<Response>;
54
61
  * Render dependencies the binding entry supplies. A seam object (not module
55
62
  * imports) because the collection-backed baseline needs `astro:content` and
56
63
  * the routing config — both exist only inside the site's own build graph,
57
- * which the entry module (`src/site-middleware.ts`) is compiled into.
64
+ * which the seams module (`src/preview-render-seams.ts`) is compiled into.
58
65
  */
59
66
  export interface PreviewRenderSeams {
60
67
  /** Lazily builds the collection-backed baseline reader. Called per preview render. */
@@ -70,6 +77,10 @@ export interface PreviewRenderSeams {
70
77
  * with a plain fetch by hostname.
71
78
  */
72
79
  fetchFn?: typeof fetch;
80
+ /** D3 and D8: the baked routing values the clean page path and the moved links follow, and the deployed media. */
81
+ baked?: Pick<BakedPreviewOpts, 'trailingSlash' | 'buildFormat' | 'domains' | 'media'>;
82
+ /** D8: pages the site prerendered itself, kept inside the preview. Defaults to none. */
83
+ sitePages?: SitePageSource;
73
84
  }
74
85
 
75
86
  /**
@@ -80,7 +91,11 @@ export interface PreviewRenderSeams {
80
91
  * request with a diagnosable error, not prevent the whole site from booting.
81
92
  */
82
93
  export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddlewareOptions, seams: PreviewRenderSeams) {
83
- return async function onRequest(context: PreviewMiddlewareContext, next: PreviewMiddlewareNext): Promise<Response> {
94
+ return async function onRequest(
95
+ context: PreviewMiddlewareContext,
96
+ next: PreviewMiddlewareNext,
97
+ slugFromPath?: string,
98
+ ): Promise<Response> {
84
99
  // Already inside a preview render — don't re-run the credential check.
85
100
  if (context.locals.conlocaPreview) return next();
86
101
 
@@ -98,8 +113,9 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
98
113
  return next();
99
114
  }
100
115
 
101
- // Under D3 the dispatcher names the requested branch's slug, after stripping any the browser sent.
102
- const slug = opts.mode === 'd3' ? (context.request.headers.get(PREVIEW_SLUG_HEADER) ?? undefined) : undefined;
116
+ // Under D3 the dispatcher names the requested branch's slug, after stripping any the browser sent. Under D8 the
117
+ // front parses it from the path; D8 trusts no header.
118
+ const slug = opts.mode === 'd3' ? (context.request.headers.get(PREVIEW_SLUG_HEADER) ?? undefined) : slugFromPath;
103
119
  const verdict = await handlePreviewRequest(context.request, {
104
120
  ...opts,
105
121
  ...(slug === undefined ? {} : { slug }),
@@ -111,19 +127,41 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
111
127
  if (verdict.kind === 'response') return verdict.response;
112
128
  if (verdict.kind !== 'preview') return next();
113
129
  // A preview verdict under D3 means the slug was named, so the scope always resolves.
114
- const exitPath = `${previewScope(opts.mode ?? 'd2', opts.base, slug).route}/__exit`;
130
+ const route = previewScope(opts.mode ?? 'd2', opts.base, slug).route;
131
+ const exitPath = `${route}/__exit`;
115
132
 
116
- // A valid credential on the preview route itself: canonicalize to the
117
- // clean site path instead of rendering under the route — links, assets
118
- // and the page lookup all assume clean paths.
133
+ // D8 serves the draft under the route: `rawPath` (captured before the path changes below) keeps the prefix for
134
+ // Retry, `pagePath` is the page's own.
119
135
  const rawPath = context.url.pathname;
120
- const path = normalizeTrailingSlash(stripPreviewPrefix(rawPath, opts.base));
121
- if (stripPreviewPrefix(rawPath, opts.base) !== rawPath) {
136
+ const d8 = opts.mode === 'd8' ? routePrefixed(context.url, opts.base, 'd8') : null;
137
+ if (d8 !== null && d8.kind !== 'slugged') return next();
138
+ const pagePath = d8?.inner ?? rawPath;
139
+ const path = normalizeTrailingSlash(stripPreviewPrefix(pagePath, opts.base));
140
+ // D2/D4 with a valid credential on the preview route itself: canonicalize to the clean site path instead of
141
+ // rendering under the route — links, assets and the page lookup all assume clean paths.
142
+ if (!isSluggedPreviewMode(opts.mode ?? 'd2') && stripPreviewPrefix(rawPath, opts.base) !== rawPath) {
122
143
  return new Response(null, {
123
144
  status: 302,
124
145
  headers: { location: path, ...PREVIEW_CACHE_HEADERS },
125
146
  });
126
147
  }
148
+ // Before anything reads `currentLocale`: the render sees the live page's `Astro.url`, canonical and locale.
149
+ if (d8 !== null) {
150
+ context.url.pathname = cleanPagePath(
151
+ d8.inner,
152
+ seams.baked?.trailingSlash ?? 'ignore',
153
+ seams.baked?.buildFormat ?? 'directory',
154
+ );
155
+ }
156
+ // D8 has no dispatcher: whatever the render answers stays under the route, HTML links and same-site `Location`.
157
+ const root = opts.base.replace(/\/+$/u, '');
158
+ const hosts = new Set(seams.baked?.domains ?? []);
159
+ const stay = (response: Response, html?: string): Response => {
160
+ const init = { status: response.status, headers: response.headers };
161
+ if (d8 === null) return applyPreviewHeaders(html === undefined ? response : new Response(html, init));
162
+ if (html === undefined) return finishEntry(response, d8.page, d8.route, root, hosts);
163
+ return applyPreviewHeaders(new Response(rewritePreviewLinks(html, d8.page, d8.route, root, hosts), init));
164
+ };
127
165
 
128
166
  context.locals.conlocaPreview = verdict.ctx;
129
167
  // An endpoint failure (5xx mid-deploy, auth envelope, network) must neither
@@ -149,7 +187,7 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
149
187
  return renderPreviewUnavailable({
150
188
  // Collapse leading slashes: `//evil.test/x` would otherwise be a cross-origin link.
151
189
  retryHref: `/${rawPath.replace(/^\/+/u, '')}${context.url.search}`,
152
- exitHref: `${exitPath}?to=${encodeURIComponent(rawPath)}`,
190
+ exitHref: `${exitPath}?to=${encodeURIComponent(pagePath)}`,
153
191
  });
154
192
  }
155
193
 
@@ -160,20 +198,53 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
160
198
  });
161
199
  }
162
200
 
163
- if (status.kind === 'unchanged') {
164
- // Production-equivalent bytes: render the ordinary route against the
165
- // build's own collections. No banner — same delegated semantics as
166
- // before — but preview responses always carry the robots/cache headers.
167
- return applyPreviewHeaders(await next());
168
- }
201
+ // The banner the draft and a site-authored page both carry.
202
+ const banner = (html: string, held: readonly UnreadyPage[] = []): string => {
203
+ let shareUrl: string | undefined;
204
+ if (verdict.ctx.editorUrl !== undefined) {
205
+ const url = new URL(verdict.ctx.editorUrl);
206
+ url.searchParams.set('share', pathUnderBase(path, opts.base));
207
+ shareUrl = url.toString();
208
+ }
209
+ // The page's own path: under D3 and D8 the address bar holds the route, which Edit and Exit must not carry.
210
+ return injectPreviewBanner(html, verdict.ctx, opts.saasEndpoint, exitPath, shareUrl, pagePath, held);
211
+ };
169
212
 
170
213
  if (status.kind === 'redirect') {
171
214
  // Always 302 (fetchPageStatus already downgraded 301) so a stale preview
172
215
  // redirect can never be cached by intermediaries.
173
- return new Response(null, {
174
- status: 302,
175
- headers: { location: status.target, ...PREVIEW_CACHE_HEADERS },
176
- });
216
+ return stay(new Response(null, { status: 302, headers: { location: status.target } }));
217
+ }
218
+
219
+ // A page the site prerendered itself stays in the preview with its published bytes; unreadable, it goes out. With
220
+ // draft changes at the path, only a site route's own file stays (production serves it there by route priority); a
221
+ // page the list only matched to a route may be a CMS page listed by mistake, so its draft renders.
222
+ const sitePages = seams.sitePages ?? NO_SITE_PAGES;
223
+ const sitePage =
224
+ d8 !== null && (status.kind === 'changed' ? await sitePages.exact(path) : await sitePages.has(path));
225
+ if (d8 !== null && sitePage) {
226
+ const page = await sitePages.read(path);
227
+ const type = page?.headers.get('content-type') ?? '';
228
+ if (page === null || page.status !== 200 || !type.includes('text/html')) {
229
+ return applyPreviewHeaders(
230
+ new Response(null, { status: 302, headers: { location: `${d8.page.pathname}${d8.page.search}` } }),
231
+ );
232
+ }
233
+ // Only the type carries over: production's encoding, length, cookies and validators don't fit the rewritten bytes.
234
+ const [html, held] = await Promise.all([
235
+ page.text(),
236
+ loadUnreadyPages(seams.fetchFn ?? fetch.bind(globalThis), opts.saasEndpoint, verdict.ctx.jwt),
237
+ ]);
238
+ return stay(new Response(null, { headers: { 'content-type': type } }), banner(html, held));
239
+ }
240
+
241
+ if (status.kind === 'unchanged') {
242
+ // Production-equivalent bytes: render the ordinary route against the
243
+ // build's own collections. No banner — same delegated semantics as
244
+ // before — but preview responses always carry the robots/cache headers.
245
+ const live = await next();
246
+ const liveHtml = d8 !== null && (live.headers.get('content-type') ?? '').includes('text/html');
247
+ return stay(live, liveHtml ? await live.text() : undefined);
177
248
  }
178
249
 
179
250
  // 'changed' and 'deleted' both render through the site's own route with
@@ -187,6 +258,15 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
187
258
  baselineApi: await seams.baselineApi(),
188
259
  embeddedPayloads: status.kind === 'changed' ? status.embedded : new Map(),
189
260
  fetchFn: seams.fetchFn,
261
+ // Only the slugged modes serve `<route>/__media/`.
262
+ ...(isSluggedPreviewMode(opts.mode ?? 'd2')
263
+ ? {
264
+ media:
265
+ seams.baked?.media === undefined
266
+ ? { route }
267
+ : { route, refBase: seams.baked.media.refBase, deployed: deployedSet(seams.baked.media.deployed) },
268
+ }
269
+ : {}),
190
270
  });
191
271
  // Prime the branch page listing before the renderer enumerates content:
192
272
  // `listAllContent` is synchronous, and a page created on the branch is
@@ -199,27 +279,23 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
199
279
  if (!contentType.includes('text/html')) {
200
280
  // Redirects (e.g. the not-found fallback) and non-HTML responses pass
201
281
  // through with the preview headers only.
202
- return applyPreviewHeaders(rendered);
203
- }
204
- let shareUrl: string | undefined;
205
- if (verdict.ctx.editorUrl !== undefined) {
206
- const url = new URL(verdict.ctx.editorUrl);
207
- url.searchParams.set('share', pathUnderBase(path, opts.base));
208
- shareUrl = url.toString();
282
+ return stay(rendered);
209
283
  }
210
- const html = injectPreviewBanner(
211
- await rendered.text(),
212
- verdict.ctx,
213
- opts.saasEndpoint,
214
- exitPath,
215
- shareUrl,
216
- // The page's own path: under D3 the address bar holds the route, which Edit and Exit must not carry.
217
- rawPath,
218
- );
219
- return applyPreviewHeaders(new Response(html, { status: rendered.status, headers: rendered.headers }));
284
+ return stay(rendered, banner(await rendered.text(), previewApi.unreadyPages()));
220
285
  };
221
286
  }
222
287
 
288
+ /** The baked list is one array per process: its Set is built once, not per render. */
289
+ const deployedSets = new WeakMap<readonly string[], ReadonlySet<string>>();
290
+ function deployedSet(deployed: readonly string[]): ReadonlySet<string> {
291
+ let set = deployedSets.get(deployed);
292
+ if (set === undefined) {
293
+ set = new Set(deployed);
294
+ deployedSets.set(deployed, set);
295
+ }
296
+ return set;
297
+ }
298
+
223
299
  /**
224
300
  * Warn once per process that the middleware is inert.
225
301
  *
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Where each adapter's d8 render reads the pages the site prerendered itself: Node from its own `dist`, Vercel and
3
+ * Netlify from the list in the function bundle plus a fetch of production, Cloudflare through `env.ASSETS`. The build
4
+ * writes the list (`writeSitePagesList`, `d8-build.ts`).
5
+ */
6
+
7
+ import type * as Fs from 'node:fs/promises';
8
+ import { normalizeTrailingSlash } from './preview-path.js';
9
+ import type { SitePageSource } from './site-pages.js';
10
+
11
+ // A variable specifier keeps node:fs out of the bundle's static graph: the same render runs in workerd, which has none.
12
+ const NODE_FS = 'node:fs/promises';
13
+ const nodeFs = (): Promise<typeof Fs> => import(/* @vite-ignore */ NODE_FS);
14
+
15
+ const LIST_FILE = 'site-pages.json';
16
+
17
+ interface List {
18
+ pages: Set<string>;
19
+ /** Pages a site route wrote as its own file (`sitePagesOf`, `d8-build.ts`). */
20
+ exact: Set<string>;
21
+ }
22
+
23
+ const EMPTY: List = { pages: new Set(), exact: new Set() };
24
+
25
+ /** The pages a `site-pages.json` lists, and which are exact; anything else lists none. */
26
+ function listOf(json: unknown): List {
27
+ const strings = (key: string): Set<string> => {
28
+ const value = typeof json === 'object' && json !== null && key in json ? Reflect.get(json, key) : undefined;
29
+ return new Set(Array.isArray(value) ? value.filter((page): page is string => typeof page === 'string') : []);
30
+ };
31
+ const pages = strings('pages');
32
+ // Exact only among the listed pages.
33
+ return { pages, exact: new Set([...strings('exact')].filter((page) => pages.has(page))) };
34
+ }
35
+
36
+ /** `has` and `exact` over a list, in normalizeTrailingSlash form. */
37
+ function lookups(list: () => Promise<List>): Pick<SitePageSource, 'has' | 'exact'> {
38
+ return {
39
+ has: async (page) => (await list()).pages.has(normalizeTrailingSlash(page)),
40
+ exact: async (page) => (await list()).exact.has(normalizeTrailingSlash(page)),
41
+ };
42
+ }
43
+
44
+ /** The list beside the server entry, read once; missing, unreadable or malformed, it lists nothing. */
45
+ function diskList(serverDir: URL): () => Promise<List> {
46
+ let list: Promise<List> | undefined;
47
+ return () => {
48
+ list ??= nodeFs()
49
+ .then(({ readFile }) => readFile(new URL(LIST_FILE, serverDir), 'utf8'))
50
+ .then((text) => JSON.parse(text))
51
+ .then(listOf, () => EMPTY);
52
+ return list;
53
+ };
54
+ }
55
+
56
+ /** A 200 for `url`, following one redirect to its own trailing-slash variant; anything else is null. */
57
+ async function fetchPage(get: (url: URL) => Promise<Response>, url: URL): Promise<Response | null> {
58
+ let response = await get(url);
59
+ const location = response.headers.get('location');
60
+ if (response.status >= 300 && response.status < 400 && location !== null) {
61
+ await response.body?.cancel();
62
+ const next = new URL(location, url);
63
+ const variant = url.pathname.endsWith('/') ? url.pathname.slice(0, -1) : `${url.pathname}/`;
64
+ if (next.origin !== url.origin || next.pathname !== variant) return null;
65
+ response = await get(next);
66
+ }
67
+ return response.status === 200 ? response : null;
68
+ }
69
+
70
+ /** The nearest ancestor folder of `moduleUrl` holding a file named `serverEntry`: the server build's own folder. */
71
+ export async function serverDirOf(moduleUrl: string, serverEntry: string): Promise<URL> {
72
+ const { stat } = await nodeFs();
73
+ for (let dir = new URL('./', moduleUrl); ; dir = new URL('../', dir)) {
74
+ // oxlint-disable-next-line no-await-in-loop -- in order: the nearest folder wins.
75
+ if ((await stat(new URL(serverEntry, dir)).catch(() => null))?.isFile()) return dir;
76
+ if (new URL('../', dir).href === dir.href) throw new Error(`no ${serverEntry} above ${moduleUrl}`);
77
+ }
78
+ }
79
+
80
+ /** Node: the list beside the server entry, each page's HTML from the client build next to it. */
81
+ export function diskSitePages(serverDir: URL, base: string): SitePageSource {
82
+ const list = diskList(serverDir);
83
+ // The client build holds pages without the base.
84
+ const root = base.replace(/\/+$/u, '');
85
+ const { has, exact } = lookups(list);
86
+ return {
87
+ has,
88
+ exact,
89
+ read: async (page) => {
90
+ if (!(await has(page))) return null;
91
+ const { readFile } = await nodeFs();
92
+ const path = page.slice(root.length).replace(/\/$/u, '');
93
+ for (const file of path === '' ? ['/index.html'] : [`${path}/index.html`, `${path}.html`]) {
94
+ // oxlint-disable-next-line no-await-in-loop -- in order: the page's own folder wins over a same-named file.
95
+ const html = await readFile(new URL(`../client${file}`, serverDir)).catch(() => null);
96
+ if (html !== null) return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } });
97
+ }
98
+ return null;
99
+ },
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Vercel and Netlify: the list from the function bundle; the page from production, at the baked origin. A null
105
+ * origin (no `site`, or a branch deploy, whose production is another build) fetches nothing. The URL is the baked
106
+ * origin plus the listed page, never the request's host, and the fetch carries no request headers, so no cookie.
107
+ */
108
+ export function functionSitePages(
109
+ serverDir: URL,
110
+ origin: string | null,
111
+ fetchFn: (url: string, init: RequestInit) => Promise<Response>,
112
+ ): SitePageSource {
113
+ const list = diskList(serverDir);
114
+ const { has, exact } = lookups(list);
115
+ return {
116
+ has,
117
+ exact,
118
+ read: async (page) => {
119
+ if (origin === null || !(await has(page))) return null;
120
+ const signal = AbortSignal.timeout(2000);
121
+ // Raced too: a fetch that ignores its signal must not hold the render.
122
+ const timedOut = new Promise<null>((resolve) => signal.addEventListener('abort', () => resolve(null)));
123
+ const get = (url: URL) => fetchFn(url.href, { redirect: 'manual', signal });
124
+ return Promise.race([fetchPage(get, new URL(origin + page)), timedOut]).catch(() => null);
125
+ },
126
+ };
127
+ }
128
+
129
+ /** Cloudflare: the list and each page through the static assets binding. */
130
+ export function assetsSitePages(assets: { fetch(request: Request): Promise<Response> }, base: string): SitePageSource {
131
+ // The binding serves the client build at any origin.
132
+ const origin = 'https://assets.invalid';
133
+ const get = (url: URL) => assets.fetch(new Request(url.href));
134
+ let list: Promise<List> | undefined;
135
+ const { has, exact } = lookups(() => {
136
+ list ??= get(new URL(`${base.replace(/\/*$/u, '/')}_conloca/editor/${LIST_FILE}`, origin))
137
+ .then((response) => (response.ok ? response.json() : null))
138
+ .then(listOf, () => EMPTY);
139
+ return list;
140
+ });
141
+ return {
142
+ has,
143
+ exact,
144
+ read: async (page) => ((await has(page)) ? fetchPage(get, new URL(page, origin)).catch(() => null) : null),
145
+ };
146
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Pages the site itself prerendered (no CMS entry behind them). Under d8 they stay inside the preview: the render
3
+ * serves their published bytes with the banner and links kept under the route. Each adapter supplies its own source.
4
+ */
5
+ export interface SitePageSource {
6
+ /** Whether `page` (base included, normalizeTrailingSlash form) is a page the site itself prerendered. */
7
+ has(page: string): Promise<boolean>;
8
+ /**
9
+ * Whether a site route wrote `page` as its own file: production serves the site page there by route priority, so the
10
+ * preview keeps it even when a CMS draft exists at that path. A page only matched to a route is not exact.
11
+ */
12
+ exact(page: string): Promise<boolean>;
13
+ /** That page's published HTML, or null when it can't be read (the caller sends a 302 out). */
14
+ read(page: string): Promise<Response | null>;
15
+ }
16
+
17
+ /** No site pages known: every path goes to the CMS render. */
18
+ export const NO_SITE_PAGES: SitePageSource = {
19
+ has: async () => false,
20
+ exact: async () => false,
21
+ read: async () => null,
22
+ };
@@ -0,0 +1,65 @@
1
+ import type { ContentManifest } from '@conloca/content-api';
2
+
3
+ /** A page a push would hold back, as the preview banner names it. */
4
+ export type UnreadyPage = { title: string; path?: string; reason: 'conflict' | 'lfs' };
5
+ export type UnreadyKey = { id: string; locale: string; reason: 'conflict' | 'lfs' };
6
+
7
+ function isUnreadyKey(value: unknown): value is UnreadyKey {
8
+ if (typeof value !== 'object' || value === null || !('id' in value && 'locale' in value && 'reason' in value))
9
+ return false;
10
+ return (
11
+ typeof value.id === 'string' &&
12
+ typeof value.locale === 'string' &&
13
+ (value.reason === 'conflict' || value.reason === 'lfs')
14
+ );
15
+ }
16
+
17
+ /** The pages `/preview/unready-pages` names; `[]` on any failure, so the page renders without the banner line. */
18
+ export async function fetchUnreadyKeys(fetchImpl: typeof fetch, endpoint: string, jwt: string): Promise<UnreadyKey[]> {
19
+ try {
20
+ const response = await fetchImpl(`${endpoint}/preview/unready-pages`, {
21
+ headers: { authorization: `Bearer ${jwt}` },
22
+ });
23
+ if (!response.ok) return [];
24
+ const body: unknown = await response.json();
25
+ const pages = typeof body === 'object' && body !== null && 'pages' in body ? body.pages : undefined;
26
+ return Array.isArray(pages) ? pages.filter(isUnreadyKey) : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ export function titleUnreadyPages(keys: readonly UnreadyKey[], manifests: readonly ContentManifest[]): UnreadyPage[] {
33
+ return keys.map(({ id, locale, reason }) => {
34
+ const entry = manifests.find((m) => m.id === id)?.locales[locale];
35
+ const path = entry?.pathname;
36
+ return { title: entry?.meta?.title || entry?.name || id, ...(path === undefined ? {} : { path }), reason };
37
+ });
38
+ }
39
+
40
+ /**
41
+ * The pages a push would hold back, for a page served without a {@link PreviewContentAPI} (one the preview build
42
+ * prerendered). `[]` on any failure.
43
+ */
44
+ export async function loadUnreadyPages(fetchImpl: typeof fetch, endpoint: string, jwt: string): Promise<UnreadyPage[]> {
45
+ const listing = fetchImpl(`${endpoint}/preview/manifests`, { headers: { authorization: `Bearer ${jwt}` } })
46
+ .then(async (r) => {
47
+ const data: unknown = r.ok ? await r.json() : [];
48
+ return Array.isArray(data) ? data.filter(isListed) : [];
49
+ })
50
+ .catch((): ContentManifest[] => []);
51
+ const [keys, manifests] = await Promise.all([fetchUnreadyKeys(fetchImpl, endpoint, jwt), listing]);
52
+ return titleUnreadyPages(keys, manifests);
53
+ }
54
+
55
+ /** Enough of a manifest for {@link titleUnreadyPages}: an id and its locales. */
56
+ function isListed(value: unknown): value is ContentManifest {
57
+ return (
58
+ typeof value === 'object' &&
59
+ value !== null &&
60
+ 'id' in value &&
61
+ 'locales' in value &&
62
+ typeof value.locales === 'object' &&
63
+ value.locales !== null
64
+ );
65
+ }
@@ -8,36 +8,51 @@ import {
8
8
  PREVIEW_PRERENDERED_ENV,
9
9
  REFUSED_PREVIEW_ADAPTERS,
10
10
  } from './constants.js';
11
- import type { PreviewServeMode } from './preview/preview-path.js';
12
11
  import type { PreviewBuildOptions } from './types.js';
13
12
 
13
+ /** Why `separate: true` cannot work under an adapter that deploys from the project root. Doctor's CC26 reuses it. */
14
+ export function separateRefusal(adapterName: string): string {
15
+ return (
16
+ `previewBuild.separate is not supported with ${adapterName}: the separate preview build would write its output ` +
17
+ `where ${adapterName} deploys the live site. Remove separate: true; with ${adapterName} drafts render in the ` +
18
+ "site's own build."
19
+ );
20
+ }
21
+
14
22
  /**
15
- * How the preview build serves, from the options and the adapter the preview server would build with
16
- * (`previewBuild.adapter`, else the project's own): off unless `previewBuild` is given as an object; D4 with
17
- * `separate: true`; D3 for a static site, whose preview server runs next to it on Cloudflare Workers; D2 when an
18
- * adapter is named, since the site's own server deploy serves the drafts. Throws for a refused adapter, so the build
19
- * fails before it deploys anything.
23
+ * How drafts are served, from the options and the project's adapter: off unless `previewBuild` is given as an
24
+ * object; D4 with `separate: true`; D3 for a static site, whose preview server runs next to it on Cloudflare
25
+ * Workers; D8 when an adapter is named, since drafts render in the site's own build. Throws for options that cannot
26
+ * work: `separate` under an adapter that deploys from the project root, and `previewBuild.adapter`
27
+ * (`previewAdapterName`) at all.
20
28
  */
21
29
  export function previewBuildMode(
22
30
  previewBuild: PreviewBuildOptions | false | undefined,
23
31
  adapterName: string | undefined,
24
- ): 'off' | PreviewServeMode {
32
+ previewAdapterName?: string,
33
+ ): 'off' | 'd3' | 'd4' | 'd8' {
25
34
  if (!previewBuild) return 'off';
26
- if (adapterName !== undefined && REFUSED_PREVIEW_ADAPTERS.includes(adapterName)) {
35
+ if (previewAdapterName !== undefined) {
27
36
  throw new Error(
28
- `${PACKAGE_NAME}: previewBuild is not supported with ${adapterName} yet: that adapter writes its deployable ` +
29
- 'output at the project root, so the preview build could replace the live site. ' +
30
- 'Remove previewBuild from conlocaCloud(...).',
37
+ `${PACKAGE_NAME}: previewBuild.adapter has no effect: drafts render in the site's own build, through the ` +
38
+ 'adapter in astro.config. Remove previewBuild.adapter.',
31
39
  );
32
40
  }
33
- if (previewBuild.separate === true) return 'd4';
34
- return adapterName === undefined ? 'd3' : 'd2';
41
+ if (previewBuild.separate === true) {
42
+ if (adapterName !== undefined && REFUSED_PREVIEW_ADAPTERS.includes(adapterName)) {
43
+ throw new Error(`${PACKAGE_NAME}: ${separateRefusal(adapterName)}`);
44
+ }
45
+ return 'd4';
46
+ }
47
+ return adapterName === undefined ? 'd3' : 'd8';
35
48
  }
36
49
 
37
- /** The mode a preview build serves in: the site's build names D2 or D3; the flag alone is a separate preview deploy (D4). */
38
- export function previewChildMode(env: NodeJS.ProcessEnv): PreviewServeMode {
39
- const named = env[PREVIEW_MODE_ENV];
40
- return named === 'd2' || named === 'd3' ? named : 'd4';
50
+ /**
51
+ * The mode a preview build serves in: the site's build names D3; anything else is a separate preview deploy (D4),
52
+ * the flag alone included. A `d2` from an older release's parent is no child mode any more.
53
+ */
54
+ export function previewChildMode(env: NodeJS.ProcessEnv): 'd3' | 'd4' {
55
+ return env[PREVIEW_MODE_ENV] === 'd3' ? 'd3' : 'd4';
41
56
  }
42
57
 
43
58
  /**
@@ -90,14 +105,15 @@ export type PreviewBuildSpawn = (
90
105
  */
91
106
  export function buildPreviewChildEnv(
92
107
  parentEnv: NodeJS.ProcessEnv,
93
- mode: 'd2' | 'd3' = 'd2',
108
+ mode: 'd3',
94
109
  prerendered: readonly string[] = [],
95
110
  ): NodeJS.ProcessEnv {
96
- const env: NodeJS.ProcessEnv = { ...parentEnv, [PREVIEW_BUILD_ENV_FLAG]: '1', [PREVIEW_MODE_ENV]: mode };
97
- // Only a D3 child reads it; a stale one from the environment must not reach a D2 child.
98
- delete env[PREVIEW_PRERENDERED_ENV];
99
- if (mode === 'd3') env[PREVIEW_PRERENDERED_ENV] = JSON.stringify(prerendered);
100
- return env;
111
+ return {
112
+ ...parentEnv,
113
+ [PREVIEW_BUILD_ENV_FLAG]: '1',
114
+ [PREVIEW_MODE_ENV]: mode,
115
+ [PREVIEW_PRERENDERED_ENV]: JSON.stringify(prerendered),
116
+ };
101
117
  }
102
118
 
103
119
  /**
@@ -140,14 +156,11 @@ export function resolveAstroBin(cwd: string = process.cwd()): string {
140
156
  * env flag is already set to `'1'`), it returns immediately without spawning,
141
157
  * which is the outermost layer of the recursion guard.
142
158
  *
143
- * On a non-zero child exit, behaviour depends on {@link PreviewBuildOptions.required}:
144
- * - `true` (default) → rejects with an error naming the exit code.
145
- * - `false` → resolves and logs a warning so onboarding setups can continue
146
- * when the preview build is not yet wired correctly.
159
+ * A non-zero child exit rejects with an error naming the exit code; the caller decides whether the site's build fails.
147
160
  */
148
161
  export async function spawnPreviewBuild(
149
162
  opts: PreviewBuildOptions,
150
- mode: 'd2' | 'd3' = 'd2',
163
+ mode: 'd3',
151
164
  prerendered: readonly string[] = [],
152
165
  ): Promise<void> {
153
166
  await _spawnPreviewBuildWith(spawn, opts, mode, prerendered);
@@ -165,7 +178,7 @@ export async function spawnPreviewBuild(
165
178
  export async function _spawnPreviewBuildWith(
166
179
  spawnFn: PreviewBuildSpawn,
167
180
  opts: PreviewBuildOptions,
168
- mode: 'd2' | 'd3' = 'd2',
181
+ mode: 'd3',
169
182
  prerendered: readonly string[] = [],
170
183
  ): Promise<void> {
171
184
  // Recursion guard: bail out before doing any work if we're already inside
@@ -175,8 +188,6 @@ export async function _spawnPreviewBuildWith(
175
188
  return;
176
189
  }
177
190
 
178
- const required = opts.required ?? true;
179
-
180
191
  const astroBin = resolveAstroBin();
181
192
  const child = spawnFn(astroBin, ['build'], {
182
193
  env: buildPreviewChildEnv(process.env, mode, prerendered),
@@ -190,17 +201,7 @@ export async function _spawnPreviewBuildWith(
190
201
  return;
191
202
  }
192
203
  const reason = code === null ? 'signal' : `exit ${code}`;
193
- if (required) {
194
- reject(new Error(`${PACKAGE_NAME}: preview build failed (${reason})`));
195
- return;
196
- }
197
- // Soft-fail path — opt-in via `previewBuild.required = false`. Use
198
- // console.warn rather than the Astro logger because the spawn helper is
199
- // pure: the integration's `astro:build:done` may evolve to pass a
200
- // logger down, but until it does, warn keeps the signal
201
- // visible without leaking a logger dependency into the spawn module.
202
- console.warn(`${PACKAGE_NAME}: preview build failed (${reason}); previewBuild.required=false, continuing`);
203
- resolve();
204
+ reject(new Error(`${PACKAGE_NAME}: preview build failed (${reason})`));
204
205
  });
205
206
  });
206
207
  }