@conloca/cloud-astro 0.2.2 → 0.2.4

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 (241) hide show
  1. package/README.md +378 -207
  2. package/dist/.build-inputs.json +69 -0
  3. package/dist/src/component-manifest.d.ts +5 -3
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +7 -7
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +14 -13
  8. package/dist/src/constants.d.ts.map +1 -1
  9. package/dist/src/constants.js +14 -13
  10. package/dist/src/constants.js.map +1 -1
  11. package/dist/src/d3-build.d.ts +70 -0
  12. package/dist/src/d3-build.d.ts.map +1 -0
  13. package/dist/src/d3-build.js +272 -0
  14. package/dist/src/d3-build.js.map +1 -0
  15. package/dist/src/descriptors.d.ts +2 -2
  16. package/dist/src/descriptors.d.ts.map +1 -1
  17. package/dist/src/descriptors.js +4 -2
  18. package/dist/src/descriptors.js.map +1 -1
  19. package/dist/src/doctor/checks-address.d.ts +18 -0
  20. package/dist/src/doctor/checks-address.d.ts.map +1 -0
  21. package/dist/src/doctor/checks-address.js +163 -0
  22. package/dist/src/doctor/checks-address.js.map +1 -0
  23. package/dist/src/doctor/checks-live.d.ts +8 -5
  24. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  25. package/dist/src/doctor/checks-live.js +226 -188
  26. package/dist/src/doctor/checks-live.js.map +1 -1
  27. package/dist/src/doctor/checks-offline.d.ts +6 -25
  28. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  29. package/dist/src/doctor/checks-offline.js +30 -259
  30. package/dist/src/doctor/checks-offline.js.map +1 -1
  31. package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
  32. package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
  33. package/dist/src/doctor/checks-preview-limits.js +133 -0
  34. package/dist/src/doctor/checks-preview-limits.js.map +1 -0
  35. package/dist/src/doctor/checks-preview-live.d.ts +14 -0
  36. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
  37. package/dist/src/doctor/checks-preview-live.js +72 -0
  38. package/dist/src/doctor/checks-preview-live.js.map +1 -0
  39. package/dist/src/doctor/checks-preview.d.ts +7 -0
  40. package/dist/src/doctor/checks-preview.d.ts.map +1 -0
  41. package/dist/src/doctor/checks-preview.js +287 -0
  42. package/dist/src/doctor/checks-preview.js.map +1 -0
  43. package/dist/src/doctor/config-scan.d.ts +12 -3
  44. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  45. package/dist/src/doctor/config-scan.js +38 -11
  46. package/dist/src/doctor/config-scan.js.map +1 -1
  47. package/dist/src/doctor/run.d.ts.map +1 -1
  48. package/dist/src/doctor/run.js +16 -10
  49. package/dist/src/doctor/run.js.map +1 -1
  50. package/dist/src/doctor/types.d.ts +17 -7
  51. package/dist/src/doctor/types.d.ts.map +1 -1
  52. package/dist/src/doctor/types.js +17 -7
  53. package/dist/src/doctor/types.js.map +1 -1
  54. package/dist/src/editor-page/bundle.d.ts +90 -0
  55. package/dist/src/editor-page/bundle.d.ts.map +1 -0
  56. package/dist/src/editor-page/bundle.js +373 -0
  57. package/dist/src/editor-page/bundle.js.map +1 -0
  58. package/dist/src/editor-page/data-schemas.d.ts +16 -0
  59. package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
  60. package/dist/src/editor-page/data-schemas.js +39 -0
  61. package/dist/src/editor-page/data-schemas.js.map +1 -0
  62. package/dist/src/editor-page/emit.d.ts +69 -0
  63. package/dist/src/editor-page/emit.d.ts.map +1 -0
  64. package/dist/src/editor-page/emit.js +254 -0
  65. package/dist/src/editor-page/emit.js.map +1 -0
  66. package/dist/src/editor-page/framing.d.ts +23 -0
  67. package/dist/src/editor-page/framing.d.ts.map +1 -0
  68. package/dist/src/editor-page/framing.js +39 -0
  69. package/dist/src/editor-page/framing.js.map +1 -0
  70. package/dist/src/editor-page/page.d.ts +9 -0
  71. package/dist/src/editor-page/page.d.ts.map +1 -0
  72. package/dist/src/editor-page/page.js +31 -0
  73. package/dist/src/editor-page/page.js.map +1 -0
  74. package/dist/src/editor-page/site-base.d.ts +4 -0
  75. package/dist/src/editor-page/site-base.d.ts.map +1 -0
  76. package/dist/src/editor-page/site-base.js +13 -0
  77. package/dist/src/editor-page/site-base.js.map +1 -0
  78. package/dist/src/git.d.ts +11 -8
  79. package/dist/src/git.d.ts.map +1 -1
  80. package/dist/src/git.js +25 -8
  81. package/dist/src/git.js.map +1 -1
  82. package/dist/src/index.d.ts +4 -1
  83. package/dist/src/index.d.ts.map +1 -1
  84. package/dist/src/index.js +11 -6
  85. package/dist/src/index.js.map +1 -1
  86. package/dist/src/integration.d.ts +1 -1
  87. package/dist/src/integration.d.ts.map +1 -1
  88. package/dist/src/integration.js +377 -416
  89. package/dist/src/integration.js.map +1 -1
  90. package/dist/src/node.d.ts +3 -1
  91. package/dist/src/node.d.ts.map +1 -1
  92. package/dist/src/node.js +7 -2
  93. package/dist/src/node.js.map +1 -1
  94. package/dist/src/preview/_dispatch.d.ts +12 -0
  95. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  96. package/dist/src/preview/_dispatch.js +31 -0
  97. package/dist/src/preview/_dispatch.js.map +1 -1
  98. package/dist/src/preview/_resolve-opts.d.ts +19 -10
  99. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  100. package/dist/src/preview/_resolve-opts.js +24 -11
  101. package/dist/src/preview/_resolve-opts.js.map +1 -1
  102. package/dist/src/preview/banner.d.ts +12 -9
  103. package/dist/src/preview/banner.d.ts.map +1 -1
  104. package/dist/src/preview/banner.js +46 -43
  105. package/dist/src/preview/banner.js.map +1 -1
  106. package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
  107. package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
  108. package/dist/src/preview/cloudflare-adapter.js +92 -0
  109. package/dist/src/preview/cloudflare-adapter.js.map +1 -0
  110. package/dist/src/preview/cookie.d.ts +13 -14
  111. package/dist/src/preview/cookie.d.ts.map +1 -1
  112. package/dist/src/preview/cookie.js +19 -26
  113. package/dist/src/preview/cookie.js.map +1 -1
  114. package/dist/src/preview/dispatcher.d.ts +73 -0
  115. package/dist/src/preview/dispatcher.d.ts.map +1 -0
  116. package/dist/src/preview/dispatcher.js +329 -0
  117. package/dist/src/preview/dispatcher.js.map +1 -0
  118. package/dist/src/preview/entry-code.d.ts +33 -0
  119. package/dist/src/preview/entry-code.d.ts.map +1 -0
  120. package/dist/src/preview/entry-code.js +33 -0
  121. package/dist/src/preview/entry-code.js.map +1 -0
  122. package/dist/src/preview/headers.d.ts +24 -4
  123. package/dist/src/preview/headers.d.ts.map +1 -1
  124. package/dist/src/preview/headers.js +35 -7
  125. package/dist/src/preview/headers.js.map +1 -1
  126. package/dist/src/preview/label.d.ts +8 -0
  127. package/dist/src/preview/label.d.ts.map +1 -0
  128. package/dist/src/preview/label.js +14 -0
  129. package/dist/src/preview/label.js.map +1 -0
  130. package/dist/src/preview/landing.d.ts +23 -2
  131. package/dist/src/preview/landing.d.ts.map +1 -1
  132. package/dist/src/preview/landing.js +105 -37
  133. package/dist/src/preview/landing.js.map +1 -1
  134. package/dist/src/preview/middleware.d.ts +49 -22
  135. package/dist/src/preview/middleware.d.ts.map +1 -1
  136. package/dist/src/preview/middleware.js +259 -100
  137. package/dist/src/preview/middleware.js.map +1 -1
  138. package/dist/src/preview/preview-path.d.ts +47 -5
  139. package/dist/src/preview/preview-path.d.ts.map +1 -1
  140. package/dist/src/preview/preview-path.js +65 -8
  141. package/dist/src/preview/preview-path.js.map +1 -1
  142. package/dist/src/preview/redeem-url.d.ts +7 -0
  143. package/dist/src/preview/redeem-url.d.ts.map +1 -0
  144. package/dist/src/preview/redeem-url.js +14 -0
  145. package/dist/src/preview/redeem-url.js.map +1 -0
  146. package/dist/src/preview/site-middleware.d.ts +5 -5
  147. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  148. package/dist/src/preview/site-middleware.js +53 -26
  149. package/dist/src/preview/site-middleware.js.map +1 -1
  150. package/dist/src/preview-build.d.ts +29 -15
  151. package/dist/src/preview-build.d.ts.map +1 -1
  152. package/dist/src/preview-build.js +66 -25
  153. package/dist/src/preview-build.js.map +1 -1
  154. package/dist/src/preview.d.ts +1 -1
  155. package/dist/src/preview.d.ts.map +1 -1
  156. package/dist/src/preview.js +1 -1
  157. package/dist/src/preview.js.map +1 -1
  158. package/dist/src/repository.d.ts +1 -1
  159. package/dist/src/repository.js +1 -1
  160. package/dist/src/resolve-options.d.ts +17 -0
  161. package/dist/src/resolve-options.d.ts.map +1 -0
  162. package/dist/src/resolve-options.js +21 -0
  163. package/dist/src/resolve-options.js.map +1 -0
  164. package/dist/src/site-id.d.ts +0 -2
  165. package/dist/src/site-id.d.ts.map +1 -1
  166. package/dist/src/site-id.js +2 -3
  167. package/dist/src/site-id.js.map +1 -1
  168. package/dist/src/skill.d.ts +11 -0
  169. package/dist/src/skill.d.ts.map +1 -1
  170. package/dist/src/skill.js +32 -9
  171. package/dist/src/skill.js.map +1 -1
  172. package/dist/src/types.d.ts +33 -78
  173. package/dist/src/types.d.ts.map +1 -1
  174. package/package.json +63 -13
  175. package/src/component-manifest.ts +11 -8
  176. package/src/constants.ts +15 -13
  177. package/src/d3-build.ts +315 -0
  178. package/src/descriptors.ts +6 -4
  179. package/src/doctor/checks-address.ts +190 -0
  180. package/src/doctor/checks-live.ts +262 -268
  181. package/src/doctor/checks-offline.ts +32 -279
  182. package/src/doctor/checks-preview-limits.ts +137 -0
  183. package/src/doctor/checks-preview-live.ts +77 -0
  184. package/src/doctor/checks-preview.ts +302 -0
  185. package/src/doctor/config-scan.ts +35 -9
  186. package/src/doctor/run.ts +18 -16
  187. package/src/doctor/types.ts +17 -7
  188. package/src/editor-page/bundle.ts +487 -0
  189. package/src/editor-page/data-schemas.ts +47 -0
  190. package/src/editor-page/emit.ts +362 -0
  191. package/src/editor-page/framing.ts +62 -0
  192. package/src/editor-page/page.ts +37 -0
  193. package/src/editor-page/site-base.ts +11 -0
  194. package/src/git.ts +29 -10
  195. package/src/index.ts +22 -6
  196. package/src/integration.ts +399 -469
  197. package/src/node.ts +18 -2
  198. package/src/preview/_dispatch.ts +36 -1
  199. package/src/preview/_resolve-opts.ts +35 -12
  200. package/src/preview/banner.ts +61 -43
  201. package/src/preview/cloudflare-adapter.ts +103 -0
  202. package/src/preview/cookie.ts +18 -24
  203. package/src/preview/dispatcher.ts +407 -0
  204. package/src/preview/entry-code.ts +51 -0
  205. package/src/preview/headers.ts +35 -7
  206. package/src/preview/label.ts +12 -0
  207. package/src/preview/landing.ts +117 -39
  208. package/src/preview/middleware.ts +302 -115
  209. package/src/preview/preview-path.ts +83 -8
  210. package/src/preview/redeem-url.ts +14 -0
  211. package/src/preview/site-middleware.ts +60 -30
  212. package/src/preview-build.ts +85 -26
  213. package/src/preview-handler.astro +12 -9
  214. package/src/preview.ts +0 -1
  215. package/src/repository.ts +1 -1
  216. package/src/resolve-options.ts +37 -0
  217. package/src/site-id.ts +2 -4
  218. package/src/skill/SKILL.md +63 -55
  219. package/src/skill.ts +36 -8
  220. package/src/types.ts +33 -79
  221. package/src/virtual-modules.d.ts +4 -1
  222. package/dist/src/build-commit.d.ts +0 -19
  223. package/dist/src/build-commit.d.ts.map +0 -1
  224. package/dist/src/build-commit.js +0 -6
  225. package/dist/src/build-commit.js.map +0 -1
  226. package/dist/src/bundle.d.ts +0 -181
  227. package/dist/src/bundle.d.ts.map +0 -1
  228. package/dist/src/bundle.js +0 -413
  229. package/dist/src/bundle.js.map +0 -1
  230. package/dist/src/discovery.d.ts +0 -58
  231. package/dist/src/discovery.d.ts.map +0 -1
  232. package/dist/src/discovery.js +0 -133
  233. package/dist/src/discovery.js.map +0 -1
  234. package/dist/src/register.d.ts +0 -98
  235. package/dist/src/register.d.ts.map +0 -1
  236. package/dist/src/register.js +0 -103
  237. package/dist/src/register.js.map +0 -1
  238. package/src/build-commit.ts +0 -22
  239. package/src/bundle.ts +0 -570
  240. package/src/discovery.ts +0 -183
  241. package/src/register.ts +0 -180
@@ -0,0 +1,315 @@
1
+ /**
2
+ * The site's build finishing a D3 preview: the preview server was built next to the static site (a child build),
3
+ * and this writes what Cloudflare Workers needs to serve both: the preview build's `_astro` files merged into the
4
+ * site's, the route list `wrangler.jsonc` must run the dispatcher on, and the dispatcher module and its config.
5
+ */
6
+
7
+ import { existsSync } from 'node:fs';
8
+ import { copyFile, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
9
+ import { dirname, join, relative, resolve, sep } from 'node:path';
10
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
11
+ import { readSitesConfig } from '@conloca/content-api/node';
12
+ import { PACKAGE_NAME } from './constants.js';
13
+ import { parseWranglerConfig, wranglerConfigPath } from './preview/cloudflare-adapter.js';
14
+ import type { DispatcherConfig, DispatcherExit } from './preview/dispatcher.js';
15
+ import { previewOwnEntries, previewRoutePrefix } from './preview/preview-path.js';
16
+
17
+ /** What the preview build tells the site's build: its pages, its on-demand routes and the exit values it baked. */
18
+ export interface PreviewRoutes {
19
+ /** Request paths without a trailing slash, under the base. */
20
+ prerendered: string[];
21
+ /** `run_worker_first` globs under the base. */
22
+ onDemand: string[];
23
+ /** What the dispatcher's exit route answers with. */
24
+ exit: DispatcherExit;
25
+ }
26
+
27
+ const ROUTES_FILE = 'routes.json';
28
+ /** The binding `conloca connect` writes and the dispatcher reads (`DispatcherEnv`). */
29
+ const LIMIT_BINDING = 'conlocaPreviewLimit';
30
+
31
+ /**
32
+ * The routes the live site must hand to its dispatcher: everything the preview build renders on demand, except the
33
+ * CMS pages (prerendered in production), the preview route itself, redirects (the static site writes them as pages)
34
+ * and Astro's internals other than islands, actions and the image endpoint draft pages use.
35
+ */
36
+ export function onDemandPatterns(
37
+ routes: readonly { pattern: string; isPrerendered: boolean; origin: string; entrypoint: string; type: string }[],
38
+ ): string[] {
39
+ return routes
40
+ .filter((route) => !route.isPrerendered && route.type !== 'redirect')
41
+ .filter((route) => !route.entrypoint.endsWith('/internal/page-handler.astro'))
42
+ .filter((route) => !/preview-handler(\.astro)?$/u.test(route.entrypoint))
43
+ .filter((route) => route.origin !== 'internal' || /^\/_(server-islands|actions|image)(\/|$)/u.test(route.pattern))
44
+ .map((route) => route.pattern);
45
+ }
46
+
47
+ /** An Astro route pattern as a `run_worker_first` glob under the base: from the first dynamic segment on, `*`. */
48
+ export function workerFirstPattern(pattern: string, base: string): string {
49
+ const segments = pattern.split('/');
50
+ const dynamic = segments.findIndex((segment) => segment.includes('['));
51
+ const path = dynamic === -1 ? pattern : `${segments.slice(0, dynamic).join('/')}/*`;
52
+ return `${base.replace(/\/+$/u, '')}${path}`;
53
+ }
54
+
55
+ export async function writePreviewRoutes(previewOut: string, routes: PreviewRoutes): Promise<void> {
56
+ await mkdir(previewOut, { recursive: true });
57
+ await writeFile(join(previewOut, ROUTES_FILE), `${JSON.stringify(routes, null, 2)}\n`);
58
+ }
59
+
60
+ function isStrings(value: unknown): value is string[] {
61
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
62
+ }
63
+
64
+ function isExit(value: unknown): value is DispatcherExit {
65
+ return (
66
+ isRecord(value) &&
67
+ typeof value.repo === 'string' &&
68
+ typeof value.siteId === 'string' &&
69
+ typeof value.branch === 'string' &&
70
+ typeof value.audience === 'string' &&
71
+ (value.issuer === undefined || typeof value.issuer === 'string')
72
+ );
73
+ }
74
+
75
+ /** The preview build's report, or undefined when it wrote none (it failed, or is from an older release). */
76
+ export async function readPreviewRoutes(previewOut: string): Promise<PreviewRoutes | undefined> {
77
+ let value: unknown;
78
+ try {
79
+ value = JSON.parse(await readFile(join(previewOut, ROUTES_FILE), 'utf8'));
80
+ } catch {
81
+ return undefined;
82
+ }
83
+ return isRecord(value) && isStrings(value.prerendered) && isStrings(value.onDemand) && isExit(value.exit)
84
+ ? { prerendered: value.prerendered, onDemand: value.onDemand, exit: value.exit }
85
+ : undefined;
86
+ }
87
+
88
+ /**
89
+ * Copies the preview build's built files into the site's, so the drafts' scripts and styles load from the one asset
90
+ * set the site serves. Content-hashed names mean the same name holds the same bytes; a name that holds other bytes
91
+ * copies nothing and answers false.
92
+ */
93
+ export async function mergeAssets(from: string, to: string): Promise<boolean> {
94
+ if (!existsSync(from)) return true;
95
+ const files = (await readdir(from, { recursive: true, withFileTypes: true }))
96
+ .filter((entry) => entry.isFile())
97
+ .map((entry) => relative(from, join(entry.parentPath, entry.name)));
98
+ const clashes = await Promise.all(
99
+ files.map(
100
+ async (file) =>
101
+ existsSync(join(to, file)) && !(await readFile(join(to, file))).equals(await readFile(join(from, file))),
102
+ ),
103
+ );
104
+ if (clashes.includes(true)) return false;
105
+ await Promise.all(
106
+ files.map(async (file) => {
107
+ if (existsSync(join(to, file))) return;
108
+ await mkdir(dirname(join(to, file)), { recursive: true });
109
+ await copyFile(join(from, file), join(to, file));
110
+ }),
111
+ );
112
+ return true;
113
+ }
114
+
115
+ /** The config's blocks a deploy can use, labelled: the top level, and each env block (the build selects one). */
116
+ function blocksOf(config: unknown): { label: string; block: unknown; inherited: unknown }[] {
117
+ if (!isRecord(config)) return [];
118
+ const env = isRecord(config.env) ? config.env : {};
119
+ return [
120
+ { label: '', block: config, inherited: undefined },
121
+ ...Object.entries(env).map(([name, block]) => ({ label: ` (env.${name})`, block, inherited: config })),
122
+ ];
123
+ }
124
+
125
+ /** `run_worker_first` of a block's own `assets`, else what it inherits; `true` covers every path. */
126
+ function workerFirstOf(block: unknown, inherited: unknown): readonly unknown[] | true | undefined {
127
+ const own = isRecord(block) && isRecord(block.assets) ? block.assets : undefined;
128
+ const assets = own ?? (isRecord(inherited) && isRecord(inherited.assets) ? inherited.assets : undefined);
129
+ if (assets === undefined) return undefined;
130
+ if (assets.run_worker_first === true) return true;
131
+ return Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
132
+ }
133
+
134
+ function hasLimit(block: unknown): boolean {
135
+ if (!isRecord(block) || !Array.isArray(block.ratelimits)) return false;
136
+ return block.ratelimits.some(
137
+ (entry) =>
138
+ isRecord(entry) &&
139
+ entry.name === LIMIT_BINDING &&
140
+ typeof entry.namespace_id === 'string' &&
141
+ /^[1-9]\d*$/u.test(entry.namespace_id),
142
+ );
143
+ }
144
+
145
+ /**
146
+ * What `wrangler.jsonc` lacks for D3, as fix messages: `run_worker_first` entries per block that has its own
147
+ * `assets` (an env block's replaces the top level's), and, when the plan needs it, the rate limit in every block
148
+ * (bindings are not inherited).
149
+ */
150
+ export function deployProblems(config: unknown, expected: readonly string[], needsLimit: boolean): string[] {
151
+ const problems: string[] = [];
152
+ for (const { label, block, inherited } of blocksOf(config)) {
153
+ const ownAssets = isRecord(block) && isRecord(block.assets);
154
+ if (label === '' || ownAssets) {
155
+ const listed = workerFirstOf(block, inherited);
156
+ const missing = listed === true ? [] : expected.filter((entry) => !(listed ?? []).includes(entry));
157
+ if (missing.length > 0) problems.push(`wrangler.jsonc run_worker_first lacks ${missing.join(', ')}${label}`);
158
+ }
159
+ if (needsLimit && !hasLimit(block)) problems.push(`wrangler.jsonc lacks the ${LIMIT_BINDING} rate limit${label}`);
160
+ }
161
+ return problems;
162
+ }
163
+
164
+ /** The site's recorded Cloudflare plan (`package.json` `conloca.cfPlan`, written by `conloca connect`), or undefined. */
165
+ export async function recordedCfPlan(root: string): Promise<'free' | 'paid' | undefined> {
166
+ let value: unknown;
167
+ try {
168
+ value = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
169
+ } catch {
170
+ return undefined;
171
+ }
172
+ const plan = isRecord(value) && isRecord(value.conloca) ? value.conloca.cfPlan : undefined;
173
+ return plan === 'free' || plan === 'paid' ? plan : undefined;
174
+ }
175
+
176
+ /**
177
+ * What the preview server serves for the live site beyond the preview route, per the config: `run_worker_first`
178
+ * entries past the prefix pair and the image endpoint (only drafts use it), and `not_found_handling: "none"` (it
179
+ * answers every miss). A failed preview build must not ship over any of these.
180
+ */
181
+ export function servedBeyondPrefix(config: unknown, base: string): string[] {
182
+ const own = new Set(previewOwnEntries(base));
183
+ const served = new Set<string>();
184
+ for (const { block, inherited } of blocksOf(config)) {
185
+ const listed = workerFirstOf(block, inherited);
186
+ if (listed === true) served.add('run_worker_first: true');
187
+ for (const entry of listed === true || listed === undefined ? [] : listed) {
188
+ if (typeof entry === 'string' && !entry.startsWith('!') && !own.has(entry)) served.add(entry);
189
+ }
190
+ const assets = isRecord(block) && isRecord(block.assets) ? block.assets : undefined;
191
+ if (assets?.not_found_handling === 'none') served.add('not_found_handling "none"');
192
+ }
193
+ return [...served];
194
+ }
195
+
196
+ /** The module `wrangler.jsonc` `main` names. Its preview server import is lazy, so a slow one never delays start-up. */
197
+ export function dispatcherModule(serverEntry: string | null): string {
198
+ const load = serverEntry === null ? 'null' : `() => import(${JSON.stringify(serverEntry)})`;
199
+ return [
200
+ '// Written by @conloca/cloud-astro on every build.',
201
+ "import { createDispatcher } from '@conloca/cloud-astro/dispatcher';",
202
+ "import config from './dispatcher.json';",
203
+ '',
204
+ `export default createDispatcher(config, ${load});`,
205
+ '',
206
+ ].join('\n');
207
+ }
208
+
209
+ /** Every host sites.json declares: links to them are links to this site. */
210
+ async function declaredDomains(): Promise<string[]> {
211
+ const contentRoot = process.env.CONLOCA_CONTENT_ROOT;
212
+ if (!contentRoot) return [];
213
+ const { sites } = await readSitesConfig(contentRoot);
214
+ return [...new Set(Object.values(sites).flatMap((site) => Object.values(site.domains ?? {})))];
215
+ }
216
+
217
+ /** A plain `wrangler deploy` follows `.wrangler/deploy/config.json`; one the preview build left would ship it as the site. */
218
+ async function dropDeployRedirect(root: string, previewOut: string, logger: { info(message: string): void }) {
219
+ const redirect = join(root, '.wrangler', 'deploy', 'config.json');
220
+ if (!existsSync(redirect)) return;
221
+ let target: string | undefined;
222
+ try {
223
+ const value: unknown = JSON.parse(await readFile(redirect, 'utf8'));
224
+ target =
225
+ isRecord(value) && typeof value.configPath === 'string'
226
+ ? resolve(dirname(redirect), value.configPath)
227
+ : undefined;
228
+ } catch {
229
+ target = undefined;
230
+ }
231
+ if (target === undefined || !target.startsWith(`${resolve(previewOut)}${sep}`)) return;
232
+ await rm(redirect);
233
+ logger.info('removed .wrangler/deploy/config.json: it pointed a plain `wrangler deploy` at the preview server');
234
+ }
235
+
236
+ export interface FinishD3Input {
237
+ root: string;
238
+ dist: string;
239
+ previewOut: string;
240
+ base: string;
241
+ endpoint: string;
242
+ /** Whether the preview build succeeded. */
243
+ built: boolean;
244
+ logger: { info(message: string): void; warn(message: string): void };
245
+ }
246
+
247
+ const FIX = 'run `conloca connect --update --yes`';
248
+
249
+ /** D3: everything after the preview build; it fails the site's build only where shipping would break it. */
250
+ export async function finishD3Build(input: FinishD3Input): Promise<void> {
251
+ const { root, dist, previewOut, base, logger } = input;
252
+ const prefix = previewRoutePrefix(base);
253
+ const routes = input.built ? await readPreviewRoutes(previewOut) : undefined;
254
+ let serving = routes !== undefined;
255
+ if (input.built && routes === undefined)
256
+ logger.warn('the preview build wrote no routes.json, so no preview is served');
257
+ if (serving && !(await mergeAssets(join(previewOut, 'client', '_astro'), join(dist, '_astro')))) {
258
+ serving = false;
259
+ logger.warn(`the preview build's _astro files clash with the site's, so ${prefix}/ answers "preview unavailable"`);
260
+ }
261
+ await dropDeployRedirect(root, previewOut, logger);
262
+
263
+ const outDir = join(root, '.conloca', 'dispatcher');
264
+ await mkdir(outDir, { recursive: true });
265
+ const expected = [prefix, `${prefix}/*`, ...(serving && routes !== undefined ? routes.onDemand : [])];
266
+ await writeFile(join(outDir, 'run_worker_first.json'), `${JSON.stringify(expected, null, 2)}\n`);
267
+
268
+ const configPath = wranglerConfigPath(root);
269
+ const config = configPath === undefined ? undefined : parseWranglerConfig(await readFile(configPath, 'utf8'));
270
+ // Production safety first: with no preview server, every route it serves for the live site would 404.
271
+ if (!serving) {
272
+ const served = servedBeyondPrefix(config, base);
273
+ if (served.length > 0) {
274
+ throw new Error(
275
+ `${PACKAGE_NAME}: the preview build failed and it serves this site's on-demand routes (${served.join(', ')}); fixing it is required to deploy`,
276
+ );
277
+ }
278
+ }
279
+ const problems =
280
+ configPath === undefined
281
+ ? [
282
+ existsSync(join(root, 'wrangler.toml'))
283
+ ? "wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then"
284
+ : 'no wrangler.jsonc:',
285
+ ]
286
+ : // A Free site carries no binding (a blocked request still counts against its quota); one with no recorded plan needs it.
287
+ deployProblems(config, expected, (await recordedCfPlan(root)) !== 'free').map((problem) => `${problem}:`);
288
+ for (const problem of problems) {
289
+ const message = `${PACKAGE_NAME}: ${problem} ${FIX}`;
290
+ // `conloca connect` builds to learn the routes it then writes; any other build must not ship a route that 404s.
291
+ if (process.env.CONLOCA_CONNECT === '1') logger.warn(message);
292
+ else throw new Error(message);
293
+ }
294
+ for (const glob of routes?.onDemand ?? []) {
295
+ if (glob === `${base.replace(/\/+$/u, '')}/*`) {
296
+ logger.warn(
297
+ `${PACKAGE_NAME}: the on-demand route ${glob} covers every path, so every visitor starts a Worker; give it a fixed first segment`,
298
+ );
299
+ }
300
+ }
301
+
302
+ const dispatcher: DispatcherConfig = {
303
+ base,
304
+ endpoint: input.endpoint,
305
+ prerendered: serving && routes !== undefined ? routes.prerendered : [],
306
+ domains: await declaredDomains(),
307
+ exit: serving && routes !== undefined ? routes.exit : null,
308
+ };
309
+ await writeFile(join(outDir, 'dispatcher.json'), `${JSON.stringify(dispatcher, null, 2)}\n`);
310
+ const entry = relative(outDir, join(previewOut, 'server', 'entry.mjs'))
311
+ .split(sep)
312
+ .join('/');
313
+ await writeFile(join(outDir, 'index.mjs'), dispatcherModule(serving ? entry : null));
314
+ logger.info(`preview dispatcher written to .conloca/dispatcher/${serving ? '' : ' (preview unavailable)'}`);
315
+ }
@@ -5,11 +5,11 @@ import {
5
5
  readEditorDescriptors,
6
6
  toPortableImports,
7
7
  } from '@conloca/astro-cms/node';
8
- import type { EditorBundleDescriptors } from './bundle.js';
8
+ import type { EditorBundleDescriptors } from './editor-page/bundle.js';
9
9
 
10
10
  /**
11
11
  * The MDX discovery seam, so tests can drive the failure path without a
12
- * fixture project (same convention as `_postRegistrationWith` in register.ts).
12
+ * fixture project.
13
13
  */
14
14
  export type MdxDescriptorScan = (options: MdxRegistryScanOptions) => Promise<readonly unknown[]>;
15
15
 
@@ -68,12 +68,13 @@ export async function resolveEditorDescriptors(
68
68
  }
69
69
 
70
70
  const templateCount = Object.keys(channel.templates ?? {}).length;
71
- const { dataBindings } = channel;
71
+ const { dataBindings, assetRefBase } = channel;
72
72
  if (
73
73
  channel.schemasPath === undefined &&
74
74
  discovered.length === 0 &&
75
75
  templateCount === 0 &&
76
- dataBindings === undefined
76
+ dataBindings === undefined &&
77
+ assetRefBase === undefined
77
78
  ) {
78
79
  return undefined;
79
80
  }
@@ -88,5 +89,6 @@ export async function resolveEditorDescriptors(
88
89
  ...(discovered.length === 0 ? {} : { discoveredMdxComponents: discovered }),
89
90
  ...(templateCount === 0 ? {} : { templates: channel.templates }),
90
91
  ...(dataBindings === undefined ? {} : { dataBindings }),
92
+ ...(assetRefBase === undefined ? {} : { assetRefBase }),
91
93
  };
92
94
  }
@@ -0,0 +1,190 @@
1
+ import { join, relative } from 'node:path';
2
+ import { addressSiteName, isValidSiteBase, type SitesConfig } from '@conloca/content-api';
3
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
4
+ import { EDITOR_PAGE_PATH, editorUiOrigin, parentRoot } from '@conloca/content-api/editor-host';
5
+ import { findFramingBlockers, framingSnippets } from '../editor-page/framing.js';
6
+ import { baseMismatch } from '../editor-page/site-base.js';
7
+ import { INTEGRATION_NOT_CALLED } from './checks-offline.js';
8
+ import type { ConfigScan } from './config-scan.js';
9
+ import { type CheckOutcome, type DoctorDeps, outcomeOf, skipped } from './types.js';
10
+
11
+ /** The server's bare-host rule: lowercase dot-separated labels of letters, digits and inner hyphens; no scheme, port or path. */
12
+ const PLAIN_HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
13
+
14
+ /**
15
+ * Why the editor's address rule refuses a bare host, else undefined.
16
+ * shortcut: the editor also refuses its own login host and private names; those surface only in the editor's setup
17
+ * list, since doctor cannot tell them without the editor's settings.
18
+ */
19
+ function refusedHost(host: string): string | undefined {
20
+ // WHATWG rewrites IPv4 shorthands (`127.1`) and refuses a host ending in a number that is no IPv4.
21
+ const parsed = URL.canParse(`https://${host}/`) ? new URL(`https://${host}/`).hostname : null;
22
+ if (parsed !== host || /^\d+(\.\d+){3}$/.test(host)) return 'an IP address';
23
+ if (host === 'localhost' || host.endsWith('.localhost')) return 'localhost';
24
+ // Bare `conloca.com` is Conloca's own website, which the rule allows for that one repository.
25
+ if (host.endsWith('.conloca.com')) return 'a conloca.com host';
26
+ return undefined;
27
+ }
28
+
29
+ /** What the build key setup left behind: its environment variable and the options that went with it. */
30
+ const LEFTOVER_KEY_NAMES = [
31
+ 'CONLOCA_BUILD_TOKEN',
32
+ 'buildToken',
33
+ 'publicBaseUrl',
34
+ 'previewDomain',
35
+ 'requireRegistration',
36
+ ] as const;
37
+ const LEFTOVER_RE = new RegExp(`\\b(?:${LEFTOVER_KEY_NAMES.join('|')})\\b`, 'g');
38
+
39
+ /** The fields of sites.json the address reads; the rest is the editor's business. */
40
+ function isSitesConfig(value: unknown): value is SitesConfig {
41
+ return (
42
+ isRecord(value) &&
43
+ isRecord(value.sites) &&
44
+ Object.values(value.sites).every(
45
+ (site) =>
46
+ isRecord(site) &&
47
+ typeof site.defaultLocale === 'string' &&
48
+ (site.domains === undefined || isRecord(site.domains)) &&
49
+ (site.base === undefined || typeof site.base === 'string'),
50
+ )
51
+ );
52
+ }
53
+
54
+ /** CC9's outcome and, when it passed, the address the live checks contact. */
55
+ interface SiteAddressCheck {
56
+ outcome: CheckOutcome;
57
+ address?: string;
58
+ }
59
+
60
+ /**
61
+ * CC9 — the address the editor frames, `https://<domains[defaultLocale]><base>` of the site `addressSiteName` picks,
62
+ * by the same rule the server applies. Astro's own `site` and `base`, when the config text shows them, must agree.
63
+ */
64
+ export function checkSiteAddress(
65
+ scan: ConfigScan,
66
+ contentRoot: string,
67
+ deps: Pick<DoctorDeps, 'readFile'>,
68
+ ): SiteAddressCheck {
69
+ if (scan.kind === 'read' && scan.config.conlocaCloud === 'absent') {
70
+ return { outcome: skipped('CC9', INTEGRATION_NOT_CALLED) };
71
+ }
72
+ const outcome = outcomeOf('CC9');
73
+ const sitesPath = join(contentRoot, 'sites.json');
74
+ const fail = (message: string) => {
75
+ outcome.problems.push({ check: 'CC9', level: 'error', message, path: sitesPath });
76
+ return { outcome };
77
+ };
78
+ let sites: unknown;
79
+ try {
80
+ sites = JSON.parse(deps.readFile(sitesPath));
81
+ } catch {
82
+ return fail(`${sitesPath} is missing or not JSON — run conloca connect`);
83
+ }
84
+ if (!isSitesConfig(sites)) return fail(`${sitesPath} has no readable sites map`);
85
+ const name = addressSiteName(sites);
86
+ const site = name === null ? undefined : sites.sites[name];
87
+ if (name === null || site === undefined) {
88
+ return fail(
89
+ 'sites.json lists several sites and none is named default, so the editor cannot tell which one gives the address',
90
+ );
91
+ }
92
+ const locale = site.defaultLocale;
93
+ const host = site.domains?.[locale];
94
+ if (host === undefined) {
95
+ return fail(
96
+ `site "${name}" in sites.json has no domains.${locale} — run conloca connect, or add your site's host there`,
97
+ );
98
+ }
99
+ if (typeof host !== 'string' || !PLAIN_HOST.test(host)) {
100
+ return fail(`site "${name}" has domains.${locale} "${host}", which is not a bare host such as www.example.com`);
101
+ }
102
+ const refused = refusedHost(host);
103
+ if (refused !== undefined) {
104
+ return fail(
105
+ `site "${name}" has domains.${locale} "${host}", which is ${refused}: the editor never frames a page there — use your site's public host`,
106
+ );
107
+ }
108
+ const base = site.base ?? '/';
109
+ if (!isValidSiteBase(base)) return fail(`site "${name}" has base "${base}", which is not a path such as /docs/`);
110
+ const address = `https://${host}${base}`;
111
+ outcome.detail = address;
112
+
113
+ if (scan.kind === 'read') {
114
+ const { url, base: astroBase } = scan.config.site;
115
+ const warn = (message: string) =>
116
+ outcome.problems.push({ check: 'CC9', level: 'warn', message, path: scan.config.path });
117
+ const astroHost = typeof url === 'string' && URL.canParse(url) ? new URL(url).hostname : undefined;
118
+ if (astroHost !== undefined && astroHost !== host) {
119
+ warn(
120
+ `Astro's site is ${url} but sites.json gives the site "${name}" the host ${host}: the workspace editor opens ${address}${EDITOR_PAGE_PATH.slice(1)}. Make them match.`,
121
+ );
122
+ }
123
+ // An absent Astro base is `/`; a computed one is not judged.
124
+ const mismatch = astroBase === null ? undefined : baseMismatch(sites, astroBase ?? '/');
125
+ if (mismatch !== undefined) warn(mismatch);
126
+ }
127
+ return { outcome, address };
128
+ }
129
+
130
+ /** CC10 — a committed header rule that keeps the workspace editor from framing /_conloca/editor/, with the fix. */
131
+ export async function checkFramingHeaders(
132
+ scan: ConfigScan,
133
+ projectDir: string,
134
+ endpoint: string | undefined,
135
+ deps: Pick<DoctorDeps, 'exists'>,
136
+ ): Promise<CheckOutcome> {
137
+ if (scan.kind === 'read' && scan.config.conlocaCloud === 'absent') return skipped('CC10', INTEGRATION_NOT_CALLED);
138
+ const origin = editorUiOrigin(endpoint);
139
+ const editorRoot = origin === null ? null : parentRoot(origin);
140
+ if (editorRoot === null) return skipped('CC10', 'no editor UI origin');
141
+ const outcome = outcomeOf('CC10');
142
+ const snippets = framingSnippets(editorRoot);
143
+ // Netlify reads public/_headers too, but has no syntax for removing a header.
144
+ const headersRule = deps.exists(join(projectDir, 'netlify.toml'))
145
+ ? snippets.netlifyHeaders
146
+ : snippets.cloudflareHeaders;
147
+ for (const { file, header } of await findFramingBlockers(projectDir)) {
148
+ const snippet = file === 'vercel.json' ? JSON.stringify(snippets.vercelHeaders, null, 2) : headersRule;
149
+ // A second header cannot loosen a site-wide frame-ancestors, so connect never writes around that one.
150
+ const fix =
151
+ header === 'frame-ancestors' ? 'exclude /_conloca/editor/ from it, then add' : 'run conloca connect, or add';
152
+ outcome.problems.push({
153
+ check: 'CC10',
154
+ level: 'error',
155
+ message: `${file} sets ${header} for the whole site, so the workspace editor cannot frame /_conloca/editor/ — ${fix}:\n${snippet}`,
156
+ path: join(projectDir, file),
157
+ });
158
+ }
159
+ return outcome;
160
+ }
161
+
162
+ /** CC14 — each line of a tracked workflow or the astro config that still names the build key or one of its options. */
163
+ export function checkKeyLeftovers(scan: ConfigScan, projectDir: string, deps: DoctorDeps): CheckOutcome {
164
+ const outcome = outcomeOf('CC14');
165
+ // `:(top)` finds the repository's workflows from a project in a subfolder; git answers paths relative to projectDir.
166
+ const tracked = deps.git(['ls-files', '--', ':(top).github/workflows'], projectDir)?.split('\n') ?? [];
167
+ const paths = [
168
+ ...tracked.filter((path) => /\.ya?ml$/.test(path)).map((path) => join(projectDir, path)),
169
+ ...(scan.kind === 'read' ? [scan.config.path] : []),
170
+ ];
171
+ for (const path of paths) {
172
+ let text: string;
173
+ try {
174
+ text = deps.readFile(path);
175
+ } catch {
176
+ continue;
177
+ }
178
+ for (const [index, line] of text.split('\n').entries()) {
179
+ const names = [...new Set(line.match(LEFTOVER_RE))];
180
+ if (names.length === 0) continue;
181
+ outcome.problems.push({
182
+ check: 'CC14',
183
+ level: 'warn',
184
+ message: `${relative(projectDir, path)}:${index + 1} still names ${names.join(', ')}, left from the build key the editor page no longer needs — remove it`,
185
+ path,
186
+ });
187
+ }
188
+ }
189
+ return outcome;
190
+ }