@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
@@ -0,0 +1,177 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from 'astro';
3
+ import { balancedSlice, containsOutsideStrings, stripComments } from './doctor/config-scan.js';
4
+ import { PREVIEW_ROUTE_SEGMENT } from './preview/preview-path.js';
5
+
6
+ /** The adapters whose middleware can run at the edge, and the call that names each in astro.config. */
7
+ const EDGE_ADAPTER_CALLS = new Map([
8
+ ['@astrojs/vercel', 'vercel'],
9
+ ['@astrojs/netlify', 'netlify'],
10
+ ]);
11
+ const EDGE_OPTION = /middlewareMode\s*:\s*['"]edge['"]|edgeMiddleware\s*:\s*true/;
12
+
13
+ export const D8_EDGE_REFUSAL =
14
+ "draft preview does not run in edge middleware (middlewareMode: 'edge' / edgeMiddleware): its middleware does not " +
15
+ 'bundle into the edge function, and the adapter serializes locals to JSON. Remove the option to turn preview on.';
16
+
17
+ /** Astro's preview prefix under `base`, as served. */
18
+ function previewPrefix(base: string): string {
19
+ return `${base.replace(/\/+$/u, '')}${PREVIEW_ROUTE_SEGMENT}`;
20
+ }
21
+
22
+ /** The isr refusal, naming the exclude entry that covers `<base>_conloca/preview(/.*)?`. */
23
+ export function d8IsrRefusal(base: string): string {
24
+ const prefix = previewPrefix(base);
25
+ return (
26
+ `@astrojs/vercel isr caches ${prefix}/ by path, ignoring the preview cookie, so drafts could be served to anyone. ` +
27
+ `Add the prefix to isr.exclude in astro.config: isr: { exclude: [/^${prefix.replaceAll('/', '\\/')}(\\/.*)?$/] }`
28
+ );
29
+ }
30
+
31
+ /** The text of the astro.config Astro loads from `root` (its own search order), or '' when there is none. */
32
+ export function readAstroConfigText(root: URL): string {
33
+ // shortcut: a config passed with `astro build --config <file>` is not seen; the probe and the build:done backstop still run.
34
+ const file = ['mjs', 'js', 'ts', 'mts']
35
+ .map((ext) => new URL(`astro.config.${ext}`, root))
36
+ .find((url) => existsSync(url));
37
+ return file === undefined ? '' : readFileSync(file, 'utf8');
38
+ }
39
+
40
+ /** The parenthesized arguments of the adapter's call in comment-stripped config text, or null without one. */
41
+ function adapterArgs(text: string, adapterName: string): string | null {
42
+ const name = EDGE_ADAPTER_CALLS.get(adapterName);
43
+ if (name === undefined) return null;
44
+ const code = stripComments(text);
45
+ const call = new RegExp(`\\b${name}\\s*\\(`).exec(code);
46
+ return call === null ? null : balancedSlice(code, call.index + call[0].length - 1);
47
+ }
48
+
49
+ /** The config-text refusal for d8 on this adapter, or null. `text` is the astro.config file Astro loaded. Doctor (Plan 50) reuses it. */
50
+ export function d8ConfigRefusal(text: string, adapterName: string, base = '/'): string | null {
51
+ const args = adapterArgs(text, adapterName);
52
+ if (args === null) return null;
53
+ if (adapterName === '@astrojs/vercel' && /\bisr\s*:(?!\s*false\b)/.test(args)) {
54
+ const exclude = /\bexclude\s*:\s*\[/.exec(args);
55
+ const list = exclude === null ? null : balancedSlice(args, exclude.index + exclude[0].length - 1);
56
+ if (!(list?.includes('_conloca') && list.includes('preview'))) return d8IsrRefusal(base);
57
+ }
58
+ return EDGE_OPTION.test(args) ? D8_EDGE_REFUSAL : null;
59
+ }
60
+
61
+ /** A logger that drops everything: the probe's adapter hook must not log twice. */
62
+ const silentLogger: AstroIntegrationLogger = {
63
+ options: { destination: { write: () => undefined }, level: 'silent' },
64
+ label: 'probe',
65
+ fork: () => silentLogger,
66
+ info: () => undefined,
67
+ warn: () => undefined,
68
+ error: () => undefined,
69
+ debug: () => undefined,
70
+ flush: () => undefined,
71
+ close: () => undefined,
72
+ };
73
+
74
+ /** The adapter's resolved middleware mode, read by calling its own `astro:config:done` with a capturing `setAdapter`; undefined when that yields no `adapterFeatures.middlewareMode`. */
75
+ export async function adapterMiddlewareMode(
76
+ adapter: AstroIntegration,
77
+ config: AstroConfig,
78
+ ): Promise<'classic' | 'edge' | undefined> {
79
+ let mode: 'classic' | 'edge' | undefined;
80
+ try {
81
+ await adapter.hooks['astro:config:done']?.({
82
+ config,
83
+ buildOutput: 'static',
84
+ setAdapter: (resolved) => {
85
+ mode = resolved.adapterFeatures?.middlewareMode;
86
+ },
87
+ injectTypes: () => new URL('noop', config.root),
88
+ logger: silentLogger,
89
+ });
90
+ } catch {
91
+ return undefined;
92
+ }
93
+ return mode;
94
+ }
95
+
96
+ /** The edge refusal for this build, or null: `probed === 'edge'` → edge text; `probed === undefined` on vercel/netlify → `d8ConfigRefusal`'s edge text when the text names edge, else the unreadable text unless the text proves classic. */
97
+ export function d8EdgeRefusal(
98
+ probed: 'classic' | 'edge' | undefined,
99
+ text: string,
100
+ adapterName: string,
101
+ ): string | null {
102
+ if (probed === 'edge') return D8_EDGE_REFUSAL;
103
+ if (probed === 'classic' || !EDGE_ADAPTER_CALLS.has(adapterName)) return null;
104
+ const args = adapterArgs(text, adapterName);
105
+ if (args !== null && EDGE_OPTION.test(args)) return D8_EDGE_REFUSAL;
106
+ const inner = args?.slice(1, -1).trim();
107
+ // Classic is proven by no argument, or one spread-free object literal whose mode keys are absent or literally classic.
108
+ const classic =
109
+ inner === '' ||
110
+ (inner?.startsWith('{') === true &&
111
+ balancedSlice(inner, 0) === inner &&
112
+ !containsOutsideStrings(inner, '...') &&
113
+ !/\b(?:middlewareMode|edgeMiddleware)\b/.test(
114
+ inner.replace(/\bmiddlewareMode\s*:\s*(['"])classic\1|\bedgeMiddleware\s*:\s*false\b/g, ''),
115
+ ));
116
+ return classic
117
+ ? null
118
+ : `couldn't read middlewareMode from astro.config; write the ${adapterName} options literally to turn preview on.`;
119
+ }
120
+
121
+ interface VercelRoute {
122
+ src?: unknown;
123
+ dest?: unknown;
124
+ handle?: unknown;
125
+ status?: unknown;
126
+ continue?: unknown;
127
+ }
128
+
129
+ /** A `.vercel/output/config.json` after the prefix is darkened: its other keys as the adapter wrote them. */
130
+ interface VercelOutputConfig {
131
+ routes: VercelRoute[];
132
+ }
133
+
134
+ /** The routes of a `.vercel/output/config.json`, or [] when it holds none. */
135
+ function vercelRoutes(configJson: unknown): VercelRoute[] {
136
+ if (typeof configJson !== 'object' || configJson === null || !('routes' in configJson)) return [];
137
+ return Array.isArray(configJson.routes)
138
+ ? configJson.routes.filter((route): route is VercelRoute => typeof route === 'object' && route !== null)
139
+ : [];
140
+ }
141
+
142
+ /** Whether a Vercel route src matches the path. Srcs are PCRE: compiled without 'u', and one JS can't read matches nothing. */
143
+ function srcMatches(src: unknown, path: string): boolean {
144
+ if (typeof src !== 'string') return false;
145
+ try {
146
+ return new RegExp(src).test(path);
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+
152
+ /** True when `.vercel/output/config.json` sends the preview route to an `_isr` function. */
153
+ export function vercelIsrCatchesPrefix(configJson: unknown, base: string): boolean {
154
+ const routes = vercelRoutes(configJson);
155
+ const prefix = previewPrefix(base);
156
+ const after = routes.slice(routes.findIndex((route) => route.handle === 'filesystem') + 1);
157
+ const end = after.findIndex((route) => route.handle !== undefined);
158
+ // Only the filesystem phase's routes that serve: a dest without `continue` ends the lookup.
159
+ const serving = (end < 0 ? after : after.slice(0, end)).filter(
160
+ (route) => typeof route.dest === 'string' && route.continue !== true,
161
+ );
162
+ return [prefix, `${prefix}/`, `${prefix}/slug/page`].some((sample) => {
163
+ const served = serving.find((route) => srcMatches(route.src, sample));
164
+ return typeof served?.dest === 'string' && served.dest.startsWith('/_isr');
165
+ });
166
+ }
167
+
168
+ /** The config with a static 404 for `<prefix>(/.*)?` placed first after `handle: filesystem`, so no route below it (the prefix's own `_isr` route or an `_isr` catch-all) ever serves or caches the prefix. Every other route is unchanged. */
169
+ export function darkenIsrPrefix(configJson: unknown, base: string): VercelOutputConfig {
170
+ const src = `^${previewPrefix(base).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:/.*)?$`;
171
+ const routes = vercelRoutes(configJson);
172
+ const at = routes.findIndex((route) => route.handle === 'filesystem') + 1;
173
+ const darkened = [...routes.slice(0, at), { src, dest: '/404.html', status: 404 }, ...routes.slice(at)];
174
+ return typeof configJson === 'object' && configJson !== null
175
+ ? { ...configJson, routes: darkened }
176
+ : { routes: darkened };
177
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Astro middleware entrypoint for a d8 site: `addMiddleware({ entrypoint: '@conloca/cloud-astro/d8-middleware' })`
3
+ * resolves here, so it exports `onRequest`. No static import of `astro:content`: the draft render (`./d8-render.ts`)
4
+ * loads only when a request needs it, so every other request runs nothing but the prefix check.
5
+ */
6
+
7
+ import baked from 'virtual:conloca-preview-opts';
8
+ import { createD8Middleware } from './preview/d8-middleware.js';
9
+ import { untagWorkerdProcess } from './preview/workerd-shim.js';
10
+
11
+ // Before any render on Cloudflare Workers: see the shim's doc.
12
+ untagWorkerdProcess();
13
+
14
+ export const onRequest = createD8Middleware(baked, {
15
+ loadRender: () => import('./d8-render.js'),
16
+ env: (name) => process.env[name],
17
+ });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The d8 draft render, loaded by the front (`./d8-middleware.ts`) only for a navigation that holds a pass: it pulls in
3
+ * `astro:content` and the routing config, which a request off the preview route must never pay for.
4
+ */
5
+
6
+ import baked from 'virtual:conloca-preview-opts';
7
+ import { resolveFromBaked } from './preview/_resolve-opts.js';
8
+ import type { D8Context } from './preview/d8-middleware.js';
9
+ import type { PreviewMiddlewareOptions } from './preview/middleware.js';
10
+ import { createPreviewSiteMiddleware } from './preview/site-middleware.js';
11
+ import { assetsSitePages, diskSitePages, functionSitePages, serverDirOf } from './preview/site-page-sources.js';
12
+ import { NO_SITE_PAGES, type SitePageSource } from './preview/site-pages.js';
13
+ import { previewRenderSeams } from './preview-render-seams.js';
14
+
15
+ // Always d8: a missing bake must not fall back to the D2 rules.
16
+ export function d8Opts(): PreviewMiddlewareOptions {
17
+ return { ...resolveFromBaked(baked, (name) => process.env[name]), mode: 'd8' };
18
+ }
19
+
20
+ // One source per process: each reads its list once.
21
+ let sitePagesPromise: Promise<SitePageSource> | undefined;
22
+ async function sitePageSource(): Promise<SitePageSource> {
23
+ const where = baked.sitePages;
24
+ const base = baked.base || '/';
25
+ switch (where?.kind) {
26
+ case 'disk':
27
+ return diskSitePages(await serverDirOf(import.meta.url, where.serverEntry), base);
28
+ case 'function':
29
+ return functionSitePages(await serverDirOf(import.meta.url, where.serverEntry), where.origin, fetch);
30
+ case 'assets': {
31
+ // Dynamic: only workerd has this module.
32
+ const { env } = await import(/* @vite-ignore */ 'cloudflare:workers');
33
+ const assets = env.ASSETS;
34
+ return typeof assets === 'object' && assets !== null && 'fetch' in assets && typeof assets.fetch === 'function'
35
+ ? // SAFETY: the Cloudflare adapter binds ASSETS to the static assets Fetcher, checked callable just above.
36
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- same reason as the SAFETY note.
37
+ assetsSitePages(assets as { fetch(request: Request): Promise<Response> }, base)
38
+ : NO_SITE_PAGES;
39
+ }
40
+ default:
41
+ return NO_SITE_PAGES;
42
+ }
43
+ }
44
+
45
+ export async function render(
46
+ context: D8Context,
47
+ next: () => Promise<Response>,
48
+ slug: string | undefined,
49
+ ): Promise<Response> {
50
+ sitePagesPromise ??= sitePageSource().catch((error: unknown) => {
51
+ // Without the list, site pages fall to the CMS route; the draft render itself still works.
52
+ console.warn(`[@conloca/cloud-astro] preview can't read the site's own pages: ${String(error)}`);
53
+ return NO_SITE_PAGES;
54
+ });
55
+ const handler = createPreviewSiteMiddleware(d8Opts, {
56
+ ...(await previewRenderSeams()),
57
+ baked,
58
+ sitePages: await sitePagesPromise,
59
+ });
60
+ return handler(context, next, slug);
61
+ }
@@ -68,13 +68,15 @@ export async function resolveEditorDescriptors(
68
68
  }
69
69
 
70
70
  const templateCount = Object.keys(channel.templates ?? {}).length;
71
- const { dataBindings, assetRefBase } = channel;
71
+ const { dataBindings, assetRefBase, fragmentComponentsPath, editorFrames } = channel;
72
72
  if (
73
73
  channel.schemasPath === undefined &&
74
74
  discovered.length === 0 &&
75
75
  templateCount === 0 &&
76
76
  dataBindings === undefined &&
77
- assetRefBase === undefined
77
+ assetRefBase === undefined &&
78
+ fragmentComponentsPath === undefined &&
79
+ editorFrames === undefined
78
80
  ) {
79
81
  return undefined;
80
82
  }
@@ -90,5 +92,7 @@ export async function resolveEditorDescriptors(
90
92
  ...(templateCount === 0 ? {} : { templates: channel.templates }),
91
93
  ...(dataBindings === undefined ? {} : { dataBindings }),
92
94
  ...(assetRefBase === undefined ? {} : { assetRefBase }),
95
+ ...(fragmentComponentsPath === undefined ? {} : { fragmentComponentsPath }),
96
+ ...(editorFrames === undefined ? {} : { editorFrames }),
93
97
  };
94
98
  }
@@ -0,0 +1,58 @@
1
+ import { Parser } from 'htmlparser2';
2
+
3
+ /** One element between `<body>` and the page-root marker. */
4
+ export interface AncestorElement {
5
+ tag: string;
6
+ classes: readonly string[];
7
+ }
8
+
9
+ /** The attribute a framed page carries on the element that wraps its content. */
10
+ const PAGE_ROOT = 'data-conloca-page-root';
11
+
12
+ /**
13
+ * The elements from `<body>` (excluded) down to the first element carrying `data-conloca-page-root` (excluded), with
14
+ * sorted classes; undefined when there is no marker. Script and style text is raw to the parser; template content is
15
+ * skipped.
16
+ */
17
+ export function ancestorChain(html: string): AncestorElement[] | undefined {
18
+ const stack: AncestorElement[] = [];
19
+ let inBody = false;
20
+ let templates = 0;
21
+ let chain: AncestorElement[] | undefined;
22
+ const parser = new Parser({
23
+ onopentag(name, attribs) {
24
+ if (chain !== undefined) return;
25
+ if (name === 'template' || templates > 0) {
26
+ if (name === 'template') templates++;
27
+ return;
28
+ }
29
+ if (name === 'body') {
30
+ inBody = true;
31
+ return;
32
+ }
33
+ if (!inBody) return;
34
+ if (PAGE_ROOT in attribs) {
35
+ chain = [...stack];
36
+ return;
37
+ }
38
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh array `filter` made; ES2022 has no toSorted.
39
+ stack.push({ tag: name, classes: (attribs.class ?? '').split(/\s+/).filter(Boolean).sort() });
40
+ },
41
+ onclosetag(name) {
42
+ if (chain !== undefined) return;
43
+ if (templates > 0) {
44
+ if (name === 'template') templates--;
45
+ return;
46
+ }
47
+ if (name === 'body') inBody = false;
48
+ else if (inBody) stack.pop();
49
+ },
50
+ });
51
+ parser.end(html);
52
+ return chain;
53
+ }
54
+
55
+ /** A chain as `tag.class.class > …`. */
56
+ export function formatChain(chain: readonly AncestorElement[]): string {
57
+ return chain.length === 0 ? '(nothing)' : chain.map((e) => [e.tag, ...e.classes].join('.')).join(' > ');
58
+ }
@@ -0,0 +1,256 @@
1
+ import { basename, dirname, join } from 'node:path';
2
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
3
+ import { REFUSED_PREVIEW_ADAPTERS } from '../constants.js';
4
+ import { D8_TESTED_ADAPTERS, d8RateLimitLines } from '../d8-adapters.js';
5
+ import { D8_EDGE_REFUSAL, d8ConfigRefusal, d8EdgeRefusal } from '../d8-guards.js';
6
+ import { parseWranglerConfig } from '../preview/cloudflare-adapter.js';
7
+ import { previewRoutePrefix } from '../preview/preview-path.js';
8
+ import { separateRefusal } from '../preview-build.js';
9
+ import { INTEGRATION_NOT_CALLED, PREVIEW_BUILD_ADAPTER } from './checks-offline.js';
10
+ import {
11
+ type ConfigScan,
12
+ previewBuildSetting,
13
+ previewBuildText,
14
+ previewServeSetting,
15
+ type ReadScan,
16
+ separateRefused,
17
+ siteAdapter,
18
+ } from './config-scan.js';
19
+ import { type CheckId, type CheckOutcome, type DoctorDeps, outcomeOf, skipped } from './types.js';
20
+
21
+ type D8Deps = Pick<DoctorDeps, 'exists' | 'readFile'>;
22
+ const IDS: readonly CheckId[] = ['CC25', 'CC26', 'CC27', 'CC28'];
23
+
24
+ type Official = keyof typeof D8_TESTED_ADAPTERS;
25
+ const isOfficial = (name: string): name is Official => Object.hasOwn(D8_TESTED_ADAPTERS, name);
26
+ /** The page files Astro builds a `src/pages/404` route from. */
27
+ const NOT_FOUND_PAGES = ['astro', 'md', 'mdx', 'html', 'js', 'ts'].map((extension) => `404.${extension}`);
28
+
29
+ /** previewBuild options the site's own build ignores. */
30
+ const NO_EFFECT = ['config', 'outDir', 'required'] as const;
31
+ const UPDATE = '— run `conloca connect --update --yes`';
32
+ const UNREADABLE_MODE =
33
+ "doctor can't read middlewareMode from astro.config; the build reads it from the adapter and turns preview off if it is edge";
34
+ const NO_SITE =
35
+ 'your own (non-CMS) pages open the published page instead of staying in the preview: set site in astro.config (on Vercel and Netlify, conloca connect proposes it from sites.json or --site-url and writes it only on your yes in a terminal, never under --yes, since site also changes canonical, sitemap, RSS and Open Graph URLs on your live pages)';
36
+
37
+ function read(deps: D8Deps, path: string): string | undefined {
38
+ try {
39
+ return deps.readFile(path);
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ }
44
+
45
+ /** A JSON file's object, or undefined; the return type is `isRecord`'s narrowing. */
46
+ function jsonRecord(deps: D8Deps, path: string) {
47
+ const text = read(deps, path);
48
+ if (text === undefined) return undefined;
49
+ try {
50
+ const value: unknown = JSON.parse(text);
51
+ return isRecord(value) ? value : undefined;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ /** A package's manifest as the project installs it: the nearest node_modules from the project up, as Node resolves it. */
58
+ function installedManifest(deps: D8Deps, projectDir: string, name: string) {
59
+ for (let dir = projectDir; ; dir = dirname(dir)) {
60
+ const found = jsonRecord(deps, join(dir, 'node_modules', name, 'package.json'));
61
+ if (found !== undefined || dir === dirname(dir)) return found;
62
+ }
63
+ }
64
+
65
+ /** `[major, minor, patch]` of a version or range floor; undefined when it names none. */
66
+ function versionParts(text: string): [number, number, number] | undefined {
67
+ const match = /(\d+)\.(\d+)\.(\d+)/u.exec(text);
68
+ return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
69
+ }
70
+
71
+ function below(a: [number, number, number], b: [number, number, number]): boolean {
72
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return (a[i] ?? 0) < (b[i] ?? 0);
73
+ return false;
74
+ }
75
+
76
+ /** CC25: an official adapter, in the release range draft preview is tested with, on an astro it accepts. */
77
+ function adapterCheck(name: string | null, deps: D8Deps, projectDir: string): CheckOutcome {
78
+ const outcome = outcomeOf('CC25');
79
+ const warn = (message: string) => outcome.problems.push({ check: 'CC25', level: 'warn', message });
80
+ if (name === null) {
81
+ warn("doctor can't tell which adapter astro.config uses: import it by default and call it in adapter");
82
+ return outcome;
83
+ }
84
+ if (!isOfficial(name)) {
85
+ warn(`unsupported adapter ${name}: draft preview may work, Conloca doesn't test it`);
86
+ return outcome;
87
+ }
88
+ const manifest = installedManifest(deps, projectDir, name);
89
+ const version = typeof manifest?.version === 'string' ? manifest.version : undefined;
90
+ if (version === undefined) {
91
+ warn(`${name} is not installed: install the site's packages, then run doctor again`);
92
+ return outcome;
93
+ }
94
+ const tested = D8_TESTED_ADAPTERS[name];
95
+ const have = versionParts(version);
96
+ const want = versionParts(tested);
97
+ if (have === undefined || want === undefined || have[0] !== want[0] || below(have, want)) {
98
+ warn(`${name} ${version} is outside the range Conloca tests draft preview with (^${tested})`);
99
+ }
100
+ const peers = isRecord(manifest?.peerDependencies) ? manifest.peerDependencies : {};
101
+ const floor = typeof peers.astro === 'string' ? versionParts(peers.astro) : undefined;
102
+ const astroManifest = installedManifest(deps, projectDir, 'astro');
103
+ const astro = typeof astroManifest?.version === 'string' ? astroManifest.version : undefined;
104
+ const astroParts = astro === undefined ? undefined : versionParts(astro);
105
+ if (floor !== undefined && astro !== undefined && astroParts !== undefined && below(astroParts, floor)) {
106
+ outcome.problems.push({
107
+ check: 'CC25',
108
+ level: 'error',
109
+ message: `${name} ${version} needs astro ${floor.join('.')} or later; this site has ${astro}`,
110
+ });
111
+ }
112
+ outcome.detail = `${name} ${version}`;
113
+ return outcome;
114
+ }
115
+
116
+ /** CC26: what the build turns preview off for. */
117
+ function guardCheck(scan: ReadScan, name: string | null | undefined, base: string): CheckOutcome {
118
+ const outcome = outcomeOf('CC26');
119
+ const add = (level: 'error' | 'warn', message: string) => outcome.problems.push({ check: 'CC26', level, message });
120
+ if (previewBuildSetting(scan) === 'adapter') {
121
+ add('error', PREVIEW_BUILD_ADAPTER);
122
+ return outcome;
123
+ }
124
+ const options = previewBuildText(scan) ?? '';
125
+ if (name && REFUSED_PREVIEW_ADAPTERS.includes(name) && /\bseparate\s*:\s*true\b/u.test(options)) {
126
+ add('error', separateRefusal(name));
127
+ return outcome;
128
+ }
129
+ if (name) {
130
+ const { text } = scan.config;
131
+ const refusal = d8ConfigRefusal(text, name, base);
132
+ if (refusal !== null) add('error', refusal);
133
+ else {
134
+ const edge = d8EdgeRefusal(undefined, text, name);
135
+ if (edge === D8_EDGE_REFUSAL) add('error', edge);
136
+ else if (edge !== null) add('warn', UNREADABLE_MODE);
137
+ }
138
+ }
139
+ for (const key of NO_EFFECT) {
140
+ if (new RegExp(`\\b${key}\\s*:`, 'u').test(options)) {
141
+ add('warn', `previewBuild.${key} has no effect: drafts render in the site's own build`);
142
+ }
143
+ }
144
+ return outcome;
145
+ }
146
+
147
+ /** CC27: how the host routes the preview route and the site's misses. Notes go in `detail`, the doctor's info. */
148
+ function routingCheck(scan: ReadScan, name: Official, deps: D8Deps, projectDir: string, base: string): CheckOutcome {
149
+ const outcome = outcomeOf('CC27');
150
+ const warn = (message: string) => outcome.problems.push({ check: 'CC27', level: 'warn', message });
151
+ const notes: string[] = [];
152
+ const prefix = previewRoutePrefix(base);
153
+ const { site, text } = scan.config;
154
+ const isStatic = site.output === 'static';
155
+ if (name === '@astrojs/vercel') {
156
+ if (/\bformat\s*:\s*['"]file['"]/u.test(text)) {
157
+ warn("@astrojs/vercel builds build.format 'file' as 'directory', so page addresses lose their .html");
158
+ }
159
+ const pages = join(projectDir, 'src', 'pages');
160
+ if (isStatic && !NOT_FOUND_PAGES.some((file) => deps.exists(join(pages, file)))) {
161
+ notes.push(
162
+ 'misses run the preview function unless the build can restore the static 404 route; add src/pages/404.astro',
163
+ );
164
+ }
165
+ notes.push(...d8RateLimitLines(name, prefix));
166
+ }
167
+ if (name === '@astrojs/netlify') {
168
+ notes.push("every missing URL, images included, runs your site's function");
169
+ notes.push(...d8RateLimitLines(name, prefix));
170
+ }
171
+ // A computed site (null) may well be set at build time; only an absent one is certain.
172
+ if ((name === '@astrojs/vercel' || name === '@astrojs/netlify') && site.url === undefined) warn(NO_SITE);
173
+ if (name === '@astrojs/cloudflare' && isStatic) {
174
+ // The build's list is the truth: it leaves out `<base>_image` once the image endpoint moved under the prefix.
175
+ const reported = jsonStrings(deps, join(projectDir, '.conloca', 'dispatcher', 'run_worker_first.json'));
176
+ const wanted = reported ?? [prefix, `${prefix}/*`];
177
+ const path = ['wrangler.jsonc', 'wrangler.json'].map((file) => join(projectDir, file)).find((p) => deps.exists(p));
178
+ if (path === undefined && deps.exists(join(projectDir, 'wrangler.toml'))) {
179
+ warn('convert wrangler.toml to wrangler.jsonc, then run conloca connect --update --yes');
180
+ if (notes.length > 0) outcome.detail = notes.join('; ');
181
+ return outcome;
182
+ }
183
+ const config = path === undefined ? undefined : parseWranglerConfig(read(deps, path) ?? '');
184
+ const assets = isRecord(config?.assets) ? config.assets : {};
185
+ const listed: unknown[] = Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
186
+ const missing = assets.run_worker_first === true ? [] : wanted.filter((entry) => !listed.includes(entry));
187
+ if (missing.length > 0 || (assets.not_found_handling !== '404-page' && assets.not_found_handling !== 'none')) {
188
+ warn(
189
+ `${path === undefined ? 'wrangler.jsonc' : basename(path)} does not route the preview to the Cloudflare Worker: add ${(missing.length > 0 ? missing : wanted).join(', ')} to assets.run_worker_first and set assets.not_found_handling to "404-page" ${UPDATE}`,
190
+ );
191
+ }
192
+ }
193
+ if (notes.length > 0) outcome.detail = notes.join('; ');
194
+ return outcome;
195
+ }
196
+
197
+ /** A JSON file's array of strings, or undefined. */
198
+ function jsonStrings(deps: D8Deps, path: string): string[] | undefined {
199
+ const text = read(deps, path);
200
+ if (text === undefined) return undefined;
201
+ try {
202
+ const value: unknown = JSON.parse(text);
203
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined;
204
+ } catch {
205
+ return undefined;
206
+ }
207
+ }
208
+
209
+ /** CC28: Node checks the forwarded host against `security.allowedDomains`, so a TLS proxy needs the site's domains there. */
210
+ function nodeCheck(scan: ReadScan): CheckOutcome {
211
+ const outcome = outcomeOf('CC28');
212
+ const { text } = scan.config;
213
+ if (!/\ballowedDomains\s*:/u.test(text)) {
214
+ outcome.problems.push({
215
+ check: 'CC28',
216
+ level: 'error',
217
+ message:
218
+ 'add security.allowedDomains with your domains (connect writes it): without it every preview entry fails behind a TLS proxy',
219
+ });
220
+ } else if (/\ballowedDomains\s*:\s*\[\s*\]/u.test(text)) {
221
+ outcome.problems.push({
222
+ check: 'CC28',
223
+ level: 'warn',
224
+ message: 'security.allowedDomains is empty: add your domains, or every preview entry fails behind a TLS proxy',
225
+ });
226
+ }
227
+ return outcome;
228
+ }
229
+
230
+ /** CC25–CC28: what drafts rendered in the site's own build (d8) need from its adapter and host. Never networks. */
231
+ export function runD8Checks(scan: ConfigScan, projectDir: string, deps: D8Deps): CheckOutcome[] {
232
+ const mode = previewServeSetting(scan);
233
+ const misplaced = previewBuildSetting(scan) === 'adapter';
234
+ const refusedSeparate = separateRefused(scan) !== undefined;
235
+ if (scan.kind !== 'read' || (mode !== 'd8' && !misplaced && !refusedSeparate)) {
236
+ const reason =
237
+ scan.kind === 'read' && scan.config.conlocaCloud === 'absent'
238
+ ? INTEGRATION_NOT_CALLED
239
+ : "only drafts rendered in the site's own build, through its adapter (d8), need these";
240
+ return IDS.map((id) => skipped(id, reason));
241
+ }
242
+ const name = siteAdapter(scan);
243
+ const base = scan.config.site.base ?? '/';
244
+ const guards = guardCheck(scan, name, base);
245
+ if (mode !== 'd8') {
246
+ return [skipped('CC25', 'no d8 build'), guards, skipped('CC27', 'no d8 build'), skipped('CC28', 'no d8 build')];
247
+ }
248
+ return [
249
+ adapterCheck(name ?? null, deps, projectDir),
250
+ guards,
251
+ name && isOfficial(name)
252
+ ? routingCheck(scan, name, deps, projectDir, base)
253
+ : skipped('CC27', 'not an adapter Conloca knows the routing of'),
254
+ name === '@astrojs/node' ? nodeCheck(scan) : skipped('CC28', 'not @astrojs/node'),
255
+ ];
256
+ }