@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
@@ -27,19 +27,25 @@
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';
43
49
 
44
50
  /** The subset of Astro's middleware context this middleware touches. */
45
51
  export interface PreviewMiddlewareContext {
@@ -54,7 +60,7 @@ export type PreviewMiddlewareNext = () => Promise<Response>;
54
60
  * Render dependencies the binding entry supplies. A seam object (not module
55
61
  * imports) because the collection-backed baseline needs `astro:content` and
56
62
  * 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.
63
+ * which the seams module (`src/preview-render-seams.ts`) is compiled into.
58
64
  */
59
65
  export interface PreviewRenderSeams {
60
66
  /** Lazily builds the collection-backed baseline reader. Called per preview render. */
@@ -70,6 +76,10 @@ export interface PreviewRenderSeams {
70
76
  * with a plain fetch by hostname.
71
77
  */
72
78
  fetchFn?: typeof fetch;
79
+ /** D3 and D8: the baked routing values the clean page path and the moved links follow, and the deployed media. */
80
+ baked?: Pick<BakedPreviewOpts, 'trailingSlash' | 'buildFormat' | 'domains' | 'media'>;
81
+ /** D8: pages the site prerendered itself, kept inside the preview. Defaults to none. */
82
+ sitePages?: SitePageSource;
73
83
  }
74
84
 
75
85
  /**
@@ -80,7 +90,11 @@ export interface PreviewRenderSeams {
80
90
  * request with a diagnosable error, not prevent the whole site from booting.
81
91
  */
82
92
  export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddlewareOptions, seams: PreviewRenderSeams) {
83
- return async function onRequest(context: PreviewMiddlewareContext, next: PreviewMiddlewareNext): Promise<Response> {
93
+ return async function onRequest(
94
+ context: PreviewMiddlewareContext,
95
+ next: PreviewMiddlewareNext,
96
+ slugFromPath?: string,
97
+ ): Promise<Response> {
84
98
  // Already inside a preview render — don't re-run the credential check.
85
99
  if (context.locals.conlocaPreview) return next();
86
100
 
@@ -98,8 +112,9 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
98
112
  return next();
99
113
  }
100
114
 
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;
115
+ // Under D3 the dispatcher names the requested branch's slug, after stripping any the browser sent. Under D8 the
116
+ // front parses it from the path; D8 trusts no header.
117
+ const slug = opts.mode === 'd3' ? (context.request.headers.get(PREVIEW_SLUG_HEADER) ?? undefined) : slugFromPath;
103
118
  const verdict = await handlePreviewRequest(context.request, {
104
119
  ...opts,
105
120
  ...(slug === undefined ? {} : { slug }),
@@ -111,19 +126,41 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
111
126
  if (verdict.kind === 'response') return verdict.response;
112
127
  if (verdict.kind !== 'preview') return next();
113
128
  // 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`;
129
+ const route = previewScope(opts.mode ?? 'd2', opts.base, slug).route;
130
+ const exitPath = `${route}/__exit`;
115
131
 
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.
132
+ // D8 serves the draft under the route: `rawPath` (captured before the path changes below) keeps the prefix for
133
+ // Retry, `pagePath` is the page's own.
119
134
  const rawPath = context.url.pathname;
120
- const path = normalizeTrailingSlash(stripPreviewPrefix(rawPath, opts.base));
121
- if (stripPreviewPrefix(rawPath, opts.base) !== rawPath) {
135
+ const d8 = opts.mode === 'd8' ? routePrefixed(context.url, opts.base, 'd8') : null;
136
+ if (d8 !== null && d8.kind !== 'slugged') return next();
137
+ const pagePath = d8?.inner ?? rawPath;
138
+ const path = normalizeTrailingSlash(stripPreviewPrefix(pagePath, opts.base));
139
+ // D2/D4 with a valid credential on the preview route itself: canonicalize to the clean site path instead of
140
+ // rendering under the route — links, assets and the page lookup all assume clean paths.
141
+ if (!isSluggedPreviewMode(opts.mode ?? 'd2') && stripPreviewPrefix(rawPath, opts.base) !== rawPath) {
122
142
  return new Response(null, {
123
143
  status: 302,
124
144
  headers: { location: path, ...PREVIEW_CACHE_HEADERS },
125
145
  });
126
146
  }
147
+ // Before anything reads `currentLocale`: the render sees the live page's `Astro.url`, canonical and locale.
148
+ if (d8 !== null) {
149
+ context.url.pathname = cleanPagePath(
150
+ d8.inner,
151
+ seams.baked?.trailingSlash ?? 'ignore',
152
+ seams.baked?.buildFormat ?? 'directory',
153
+ );
154
+ }
155
+ // D8 has no dispatcher: whatever the render answers stays under the route, HTML links and same-site `Location`.
156
+ const root = opts.base.replace(/\/+$/u, '');
157
+ const hosts = new Set(seams.baked?.domains ?? []);
158
+ const stay = (response: Response, html?: string): Response => {
159
+ const init = { status: response.status, headers: response.headers };
160
+ if (d8 === null) return applyPreviewHeaders(html === undefined ? response : new Response(html, init));
161
+ if (html === undefined) return finishEntry(response, d8.page, d8.route, root, hosts);
162
+ return applyPreviewHeaders(new Response(rewritePreviewLinks(html, d8.page, d8.route, root, hosts), init));
163
+ };
127
164
 
128
165
  context.locals.conlocaPreview = verdict.ctx;
129
166
  // An endpoint failure (5xx mid-deploy, auth envelope, network) must neither
@@ -149,7 +186,7 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
149
186
  return renderPreviewUnavailable({
150
187
  // Collapse leading slashes: `//evil.test/x` would otherwise be a cross-origin link.
151
188
  retryHref: `/${rawPath.replace(/^\/+/u, '')}${context.url.search}`,
152
- exitHref: `${exitPath}?to=${encodeURIComponent(rawPath)}`,
189
+ exitHref: `${exitPath}?to=${encodeURIComponent(pagePath)}`,
153
190
  });
154
191
  }
155
192
 
@@ -160,20 +197,49 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
160
197
  });
161
198
  }
162
199
 
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
- }
200
+ // The banner the draft and a site-authored page both carry.
201
+ const banner = (html: string): string => {
202
+ let shareUrl: string | undefined;
203
+ if (verdict.ctx.editorUrl !== undefined) {
204
+ const url = new URL(verdict.ctx.editorUrl);
205
+ url.searchParams.set('share', pathUnderBase(path, opts.base));
206
+ shareUrl = url.toString();
207
+ }
208
+ // The page's own path: under D3 and D8 the address bar holds the route, which Edit and Exit must not carry.
209
+ return injectPreviewBanner(html, verdict.ctx, opts.saasEndpoint, exitPath, shareUrl, pagePath);
210
+ };
169
211
 
170
212
  if (status.kind === 'redirect') {
171
213
  // Always 302 (fetchPageStatus already downgraded 301) so a stale preview
172
214
  // redirect can never be cached by intermediaries.
173
- return new Response(null, {
174
- status: 302,
175
- headers: { location: status.target, ...PREVIEW_CACHE_HEADERS },
176
- });
215
+ return stay(new Response(null, { status: 302, headers: { location: status.target } }));
216
+ }
217
+
218
+ // A page the site prerendered itself stays in the preview with its published bytes; unreadable, it goes out. With
219
+ // draft changes at the path, only a site route's own file stays (production serves it there by route priority); a
220
+ // page the list only matched to a route may be a CMS page listed by mistake, so its draft renders.
221
+ const sitePages = seams.sitePages ?? NO_SITE_PAGES;
222
+ const sitePage =
223
+ d8 !== null && (status.kind === 'changed' ? await sitePages.exact(path) : await sitePages.has(path));
224
+ if (d8 !== null && sitePage) {
225
+ const page = await sitePages.read(path);
226
+ const type = page?.headers.get('content-type') ?? '';
227
+ if (page === null || page.status !== 200 || !type.includes('text/html')) {
228
+ return applyPreviewHeaders(
229
+ new Response(null, { status: 302, headers: { location: `${d8.page.pathname}${d8.page.search}` } }),
230
+ );
231
+ }
232
+ // Only the type carries over: production's encoding, length, cookies and validators don't fit the rewritten bytes.
233
+ return stay(new Response(null, { headers: { 'content-type': type } }), banner(await page.text()));
234
+ }
235
+
236
+ if (status.kind === 'unchanged') {
237
+ // Production-equivalent bytes: render the ordinary route against the
238
+ // build's own collections. No banner — same delegated semantics as
239
+ // before — but preview responses always carry the robots/cache headers.
240
+ const live = await next();
241
+ const liveHtml = d8 !== null && (live.headers.get('content-type') ?? '').includes('text/html');
242
+ return stay(live, liveHtml ? await live.text() : undefined);
177
243
  }
178
244
 
179
245
  // 'changed' and 'deleted' both render through the site's own route with
@@ -187,6 +253,15 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
187
253
  baselineApi: await seams.baselineApi(),
188
254
  embeddedPayloads: status.kind === 'changed' ? status.embedded : new Map(),
189
255
  fetchFn: seams.fetchFn,
256
+ // Only the slugged modes serve `<route>/__media/`.
257
+ ...(isSluggedPreviewMode(opts.mode ?? 'd2')
258
+ ? {
259
+ media:
260
+ seams.baked?.media === undefined
261
+ ? { route }
262
+ : { route, refBase: seams.baked.media.refBase, deployed: deployedSet(seams.baked.media.deployed) },
263
+ }
264
+ : {}),
190
265
  });
191
266
  // Prime the branch page listing before the renderer enumerates content:
192
267
  // `listAllContent` is synchronous, and a page created on the branch is
@@ -199,27 +274,23 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
199
274
  if (!contentType.includes('text/html')) {
200
275
  // Redirects (e.g. the not-found fallback) and non-HTML responses pass
201
276
  // 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();
277
+ return stay(rendered);
209
278
  }
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 }));
279
+ return stay(rendered, banner(await rendered.text()));
220
280
  };
221
281
  }
222
282
 
283
+ /** The baked list is one array per process: its Set is built once, not per render. */
284
+ const deployedSets = new WeakMap<readonly string[], ReadonlySet<string>>();
285
+ function deployedSet(deployed: readonly string[]): ReadonlySet<string> {
286
+ let set = deployedSets.get(deployed);
287
+ if (set === undefined) {
288
+ set = new Set(deployed);
289
+ deployedSets.set(deployed, set);
290
+ }
291
+ return set;
292
+ }
293
+
223
294
  /**
224
295
  * Warn once per process that the middleware is inert.
225
296
  *
@@ -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
+ };
@@ -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
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The image endpoint a d8 draft page uses, at `<base>_conloca/preview/_image` on Vercel, Netlify and Node: it answers
3
+ * with a redirect to the original image, so drafts get untransformed images and the site's own `/_image` stays as it
4
+ * was. It never fetches: only a same-origin path or a host the site's `image` config allows is redirected to.
5
+ */
6
+
7
+ import { imageConfig } from 'astro:assets';
8
+ import type { APIContext, APIRoute } from 'astro';
9
+ import { isRemoteAllowed } from 'astro/assets/utils';
10
+ import { applyPreviewHeaders } from './preview/headers.js';
11
+
12
+ export const GET = (({ url }: Pick<APIContext, 'url'>) => {
13
+ const href = url.searchParams.get('href') ?? '';
14
+ const target = URL.canParse(href, url.href) ? new URL(href, url) : null;
15
+ // `//host` and `/\host` resolve off-origin, so the origin check catches them; decoded, `%5Fimage` is our own route.
16
+ const local =
17
+ href.startsWith('/') && target?.origin === url.origin && safeDecode(target.pathname) !== safeDecode(url.pathname);
18
+ const remote = /^https?:\/\//iu.test(href) && isRemoteAllowed(href, imageConfig);
19
+ try {
20
+ // The Location comes from the parsed URL, so no raw input reaches the header.
21
+ const location = local ? `${target.pathname}${target.search}` : remote && target ? target.href : null;
22
+ if (location !== null) return applyPreviewHeaders(new Response(null, { status: 302, headers: { location } }));
23
+ } catch {
24
+ // An invalid header value: refused below.
25
+ }
26
+ return applyPreviewHeaders(new Response(null, { status: 403 }));
27
+ }) satisfies APIRoute;
28
+
29
+ function safeDecode(path: string): string | null {
30
+ try {
31
+ return decodeURIComponent(path);
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The render seams a preview render takes from the site's own build graph: `astro:content` and the routing-config
3
+ * virtual module only resolve there, so the D2/D3 site middleware and the d8 render both build them here.
4
+ */
5
+
6
+ import { getCollection } from 'astro:content';
7
+ import routingConfig from 'virtual:conloca-routing-config';
8
+ import { createCollectionBackedContentAPI } from '@conloca/astro-cms';
9
+ import type { ContentAPI } from '@conloca/content-api';
10
+ import { resolveEndpointFetch } from './preview/_resolve-opts.js';
11
+ import type { PreviewRenderSeams } from './preview/site-middleware.js';
12
+
13
+ // One baseline per process: the built collections are immutable at runtime,
14
+ // and constructing the collection-backed reader walks every collection.
15
+ let baselinePromise: Promise<ContentAPI> | undefined;
16
+ function baselineApi(): Promise<ContentAPI> {
17
+ baselinePromise ??= createCollectionBackedContentAPI({
18
+ getCollection: (name) => getCollection(name),
19
+ routing: routingConfig,
20
+ });
21
+ return baselinePromise;
22
+ }
23
+
24
+ export async function previewRenderSeams(): Promise<PreviewRenderSeams> {
25
+ return {
26
+ baselineApi,
27
+ site: routingConfig.siteName,
28
+ locale: routingConfig.locale,
29
+ fetchFn: await resolveEndpointFetch(),
30
+ };
31
+ }