@conloca/cloud-astro 0.2.3 → 0.2.5

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 (159) hide show
  1. package/README.md +155 -37
  2. package/dist/.build-inputs.json +32 -23
  3. package/dist/src/constants.d.ts +12 -3
  4. package/dist/src/constants.d.ts.map +1 -1
  5. package/dist/src/constants.js +12 -3
  6. package/dist/src/constants.js.map +1 -1
  7. package/dist/src/d3-build.d.ts +70 -0
  8. package/dist/src/d3-build.d.ts.map +1 -0
  9. package/dist/src/d3-build.js +272 -0
  10. package/dist/src/d3-build.js.map +1 -0
  11. package/dist/src/descriptors.d.ts.map +1 -1
  12. package/dist/src/descriptors.js +4 -2
  13. package/dist/src/descriptors.js.map +1 -1
  14. package/dist/src/doctor/checks-live.d.ts +2 -2
  15. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  16. package/dist/src/doctor/checks-live.js +10 -4
  17. package/dist/src/doctor/checks-live.js.map +1 -1
  18. package/dist/src/doctor/checks-offline.d.ts +1 -5
  19. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  20. package/dist/src/doctor/checks-offline.js +15 -27
  21. package/dist/src/doctor/checks-offline.js.map +1 -1
  22. package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
  23. package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
  24. package/dist/src/doctor/checks-preview-limits.js +133 -0
  25. package/dist/src/doctor/checks-preview-limits.js.map +1 -0
  26. package/dist/src/doctor/checks-preview-live.d.ts +14 -0
  27. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
  28. package/dist/src/doctor/checks-preview-live.js +72 -0
  29. package/dist/src/doctor/checks-preview-live.js.map +1 -0
  30. package/dist/src/doctor/checks-preview.d.ts +7 -0
  31. package/dist/src/doctor/checks-preview.d.ts.map +1 -0
  32. package/dist/src/doctor/checks-preview.js +287 -0
  33. package/dist/src/doctor/checks-preview.js.map +1 -0
  34. package/dist/src/doctor/config-scan.d.ts +6 -0
  35. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  36. package/dist/src/doctor/config-scan.js +17 -0
  37. package/dist/src/doctor/config-scan.js.map +1 -1
  38. package/dist/src/doctor/run.d.ts.map +1 -1
  39. package/dist/src/doctor/run.js +4 -0
  40. package/dist/src/doctor/run.js.map +1 -1
  41. package/dist/src/doctor/types.d.ts +11 -1
  42. package/dist/src/doctor/types.d.ts.map +1 -1
  43. package/dist/src/doctor/types.js +11 -1
  44. package/dist/src/doctor/types.js.map +1 -1
  45. package/dist/src/editor-page/bundle.d.ts +2 -0
  46. package/dist/src/editor-page/bundle.d.ts.map +1 -1
  47. package/dist/src/editor-page/bundle.js +3 -0
  48. package/dist/src/editor-page/bundle.js.map +1 -1
  49. package/dist/src/editor-page/data-schemas.d.ts +16 -0
  50. package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
  51. package/dist/src/editor-page/data-schemas.js +39 -0
  52. package/dist/src/editor-page/data-schemas.js.map +1 -0
  53. package/dist/src/editor-page/emit.d.ts +37 -1
  54. package/dist/src/editor-page/emit.d.ts.map +1 -1
  55. package/dist/src/editor-page/emit.js +75 -4
  56. package/dist/src/editor-page/emit.js.map +1 -1
  57. package/dist/src/index.d.ts +1 -0
  58. package/dist/src/index.d.ts.map +1 -1
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/index.js.map +1 -1
  61. package/dist/src/integration.d.ts.map +1 -1
  62. package/dist/src/integration.js +165 -41
  63. package/dist/src/integration.js.map +1 -1
  64. package/dist/src/preview/_dispatch.d.ts +12 -0
  65. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  66. package/dist/src/preview/_dispatch.js +31 -0
  67. package/dist/src/preview/_dispatch.js.map +1 -1
  68. package/dist/src/preview/_resolve-opts.d.ts +3 -0
  69. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  70. package/dist/src/preview/_resolve-opts.js +3 -1
  71. package/dist/src/preview/_resolve-opts.js.map +1 -1
  72. package/dist/src/preview/banner.d.ts +12 -9
  73. package/dist/src/preview/banner.d.ts.map +1 -1
  74. package/dist/src/preview/banner.js +46 -41
  75. package/dist/src/preview/banner.js.map +1 -1
  76. package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
  77. package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
  78. package/dist/src/preview/cloudflare-adapter.js +92 -0
  79. package/dist/src/preview/cloudflare-adapter.js.map +1 -0
  80. package/dist/src/preview/cookie.d.ts +9 -13
  81. package/dist/src/preview/cookie.d.ts.map +1 -1
  82. package/dist/src/preview/cookie.js +15 -25
  83. package/dist/src/preview/cookie.js.map +1 -1
  84. package/dist/src/preview/dispatcher.d.ts +73 -0
  85. package/dist/src/preview/dispatcher.d.ts.map +1 -0
  86. package/dist/src/preview/dispatcher.js +329 -0
  87. package/dist/src/preview/dispatcher.js.map +1 -0
  88. package/dist/src/preview/entry-code.d.ts +33 -0
  89. package/dist/src/preview/entry-code.d.ts.map +1 -0
  90. package/dist/src/preview/entry-code.js +33 -0
  91. package/dist/src/preview/entry-code.js.map +1 -0
  92. package/dist/src/preview/headers.d.ts +24 -4
  93. package/dist/src/preview/headers.d.ts.map +1 -1
  94. package/dist/src/preview/headers.js +35 -7
  95. package/dist/src/preview/headers.js.map +1 -1
  96. package/dist/src/preview/landing.d.ts +21 -0
  97. package/dist/src/preview/landing.d.ts.map +1 -1
  98. package/dist/src/preview/landing.js +103 -35
  99. package/dist/src/preview/landing.js.map +1 -1
  100. package/dist/src/preview/middleware.d.ts +29 -7
  101. package/dist/src/preview/middleware.d.ts.map +1 -1
  102. package/dist/src/preview/middleware.js +238 -84
  103. package/dist/src/preview/middleware.js.map +1 -1
  104. package/dist/src/preview/preview-path.d.ts +29 -0
  105. package/dist/src/preview/preview-path.d.ts.map +1 -1
  106. package/dist/src/preview/preview-path.js +41 -0
  107. package/dist/src/preview/preview-path.js.map +1 -1
  108. package/dist/src/preview/redeem-url.d.ts +7 -0
  109. package/dist/src/preview/redeem-url.d.ts.map +1 -0
  110. package/dist/src/preview/redeem-url.js +14 -0
  111. package/dist/src/preview/redeem-url.js.map +1 -0
  112. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  113. package/dist/src/preview/site-middleware.js +39 -12
  114. package/dist/src/preview/site-middleware.js.map +1 -1
  115. package/dist/src/preview-build.d.ts +19 -8
  116. package/dist/src/preview-build.d.ts.map +1 -1
  117. package/dist/src/preview-build.js +47 -21
  118. package/dist/src/preview-build.js.map +1 -1
  119. package/dist/src/skill.d.ts +11 -0
  120. package/dist/src/skill.d.ts.map +1 -1
  121. package/dist/src/skill.js +32 -9
  122. package/dist/src/skill.js.map +1 -1
  123. package/dist/src/types.d.ts +15 -12
  124. package/dist/src/types.d.ts.map +1 -1
  125. package/package.json +33 -7
  126. package/src/constants.ts +14 -3
  127. package/src/d3-build.ts +315 -0
  128. package/src/descriptors.ts +4 -2
  129. package/src/doctor/checks-live.ts +10 -4
  130. package/src/doctor/checks-offline.ts +16 -25
  131. package/src/doctor/checks-preview-limits.ts +137 -0
  132. package/src/doctor/checks-preview-live.ts +77 -0
  133. package/src/doctor/checks-preview.ts +302 -0
  134. package/src/doctor/config-scan.ts +14 -0
  135. package/src/doctor/run.ts +4 -0
  136. package/src/doctor/types.ts +11 -1
  137. package/src/editor-page/bundle.ts +5 -0
  138. package/src/editor-page/data-schemas.ts +47 -0
  139. package/src/editor-page/emit.ts +124 -8
  140. package/src/index.ts +2 -0
  141. package/src/integration.ts +176 -40
  142. package/src/preview/_dispatch.ts +36 -1
  143. package/src/preview/_resolve-opts.ts +6 -1
  144. package/src/preview/banner.ts +61 -41
  145. package/src/preview/cloudflare-adapter.ts +103 -0
  146. package/src/preview/cookie.ts +14 -23
  147. package/src/preview/dispatcher.ts +407 -0
  148. package/src/preview/entry-code.ts +51 -0
  149. package/src/preview/headers.ts +35 -7
  150. package/src/preview/landing.ts +115 -37
  151. package/src/preview/middleware.ts +264 -88
  152. package/src/preview/preview-path.ts +57 -0
  153. package/src/preview/redeem-url.ts +14 -0
  154. package/src/preview/site-middleware.ts +47 -12
  155. package/src/preview-build.ts +67 -24
  156. package/src/preview-handler.astro +2 -1
  157. package/src/skill/SKILL.md +14 -2
  158. package/src/skill.ts +36 -8
  159. package/src/types.ts +15 -12
@@ -0,0 +1,302 @@
1
+ import { dirname, join, resolve, sep } from 'node:path';
2
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
3
+ import { parseWranglerConfig } from '../preview/cloudflare-adapter.js';
4
+ import { previewOwnEntries, previewRoutePrefix } from '../preview/preview-path.js';
5
+ import { INTEGRATION_NOT_CALLED } from './checks-offline.js';
6
+ import { type ConfigScan, previewServeSetting } from './config-scan.js';
7
+ import { type CheckId, type CheckOutcome, type DoctorDeps, outcomeOf, skipped } from './types.js';
8
+
9
+ type PreviewDeps = Pick<DoctorDeps, 'exists' | 'readFile' | 'git'>;
10
+ const IDS: readonly CheckId[] = ['CC15', 'CC16', 'CC17', 'CC18', 'CC19', 'CC20', 'CC21'];
11
+ const DISPATCHER_MAIN = '.conloca/dispatcher/index.mjs';
12
+ const UPDATE = '— run `conloca connect --update --yes`';
13
+ /** Cloudflare's cap on `run_worker_first` entries. */
14
+ const MAX_WORKER_FIRST = 100;
15
+ /** Script hosts and snippets of tag managers and analytics loaders. */
16
+ const TAG_MANAGERS =
17
+ /googletagmanager\.com|gtag\(|cdn\.segment\.com|connect\.facebook\.net|static\.hotjar\.com|js\.hs-scripts\.com|plausible\.io\/js|@builder\.io\/partytown/u;
18
+ const SOURCE = /\.(astro|html|[cm]?[jt]sx?|mdx?)$/u;
19
+ const MIDDLEWARE_FILES = ['src/middleware.ts', 'src/middleware.js', 'src/middleware.mjs'];
20
+
21
+ function read(deps: PreviewDeps, path: string): string | undefined {
22
+ try {
23
+ return deps.readFile(path);
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ /** A JSON file's object, or undefined; the return type is `isRecord`'s narrowing, never written out. */
30
+ function jsonRecord(deps: PreviewDeps, path: string) {
31
+ const text = read(deps, path);
32
+ if (text === undefined) return undefined;
33
+ try {
34
+ const value: unknown = JSON.parse(text);
35
+ return isRecord(value) ? value : undefined;
36
+ } catch {
37
+ return undefined;
38
+ }
39
+ }
40
+
41
+ /** A JSON file's array of strings, or undefined. */
42
+ function jsonStrings(deps: PreviewDeps, path: string): string[] | undefined {
43
+ const text = read(deps, path);
44
+ if (text === undefined) return undefined;
45
+ try {
46
+ const value: unknown = JSON.parse(text);
47
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined;
48
+ } catch {
49
+ return undefined;
50
+ }
51
+ }
52
+
53
+ /** A heuristic: the site's middleware reads `Accept`, or answers a 404 body of its own. Doctor only warns on it. */
54
+ function middlewareNegotiates(deps: PreviewDeps, projectDir: string): boolean {
55
+ const text = MIDDLEWARE_FILES.map((name) => read(deps, join(projectDir, name))).find((found) => found !== undefined);
56
+ return (
57
+ text !== undefined && (/\.get\(\s*['"`]accept['"`]\s*\)/iu.test(text) || /\bstatus\s*={2,3}\s*404\b/u.test(text))
58
+ );
59
+ }
60
+
61
+ const onlyD3 = (id: CheckId) => skipped(id, 'a separate preview deploy (D4) runs no dispatcher');
62
+
63
+ /** CC15–CC21: the settings a D3 or D4 preview deploy needs, read from the project's files. Never networks. */
64
+ export function runPreviewChecks(scan: ConfigScan, projectDir: string, deps: PreviewDeps): CheckOutcome[] {
65
+ const mode = previewServeSetting(scan);
66
+ if (mode !== 'd3' && mode !== 'd4') {
67
+ const reason =
68
+ scan.kind === 'read' && scan.config.conlocaCloud === 'absent'
69
+ ? INTEGRATION_NOT_CALLED
70
+ : mode === 'unknown'
71
+ ? 'doctor cannot read previewBuild from the config text'
72
+ : 'only a static site previewing next to itself (D3) or on a separate deploy (D4) needs these';
73
+ return IDS.map((id) => skipped(id, reason));
74
+ }
75
+ const base = scan.kind === 'read' ? (scan.config.site.base ?? '/') : '/';
76
+ const prefix = previewRoutePrefix(base);
77
+ const path = ['wrangler.jsonc', 'wrangler.json'].map((name) => join(projectDir, name)).find((p) => deps.exists(p));
78
+ const text = path === undefined ? undefined : read(deps, path);
79
+ const config = text === undefined ? undefined : parseWranglerConfig(text);
80
+ const assets = isRecord(config?.assets) ? config.assets : {};
81
+ const everything = assets.run_worker_first === true;
82
+ const listed: unknown[] = Array.isArray(assets.run_worker_first) ? assets.run_worker_first : [];
83
+
84
+ // CC15
85
+ const deployTarget = outcomeOf('CC15');
86
+ if (config === undefined && deps.exists(join(projectDir, 'wrangler.toml'))) {
87
+ deployTarget.problems.push({
88
+ check: 'CC15',
89
+ level: 'error',
90
+ message:
91
+ "wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then run `conloca connect --update --yes`",
92
+ });
93
+ } else if (config === undefined) {
94
+ deployTarget.problems.push({
95
+ check: 'CC15',
96
+ level: 'error',
97
+ message:
98
+ 'no wrangler.jsonc: draft previews of a static site deploy to Cloudflare Workers — run `conloca connect --yes`',
99
+ });
100
+ } else if (config.pages_build_output_dir !== undefined) {
101
+ deployTarget.problems.push({
102
+ check: 'CC15',
103
+ level: 'error',
104
+ message:
105
+ 'wrangler.jsonc configures Cloudflare Pages (pages_build_output_dir); draft previews need Cloudflare Workers with static assets',
106
+ path,
107
+ });
108
+ } else {
109
+ deployTarget.detail = 'Cloudflare Workers';
110
+ }
111
+
112
+ // CC16: array run_worker_first needs 4.20, the ratelimits binding 4.36; D4 uses neither.
113
+ let version: CheckOutcome;
114
+ if (mode === 'd4') version = onlyD3('CC16');
115
+ else {
116
+ version = outcomeOf('CC16');
117
+ const manifest = [projectDir, join(projectDir, '..'), join(projectDir, '..', '..')]
118
+ .map((dir) => jsonRecord(deps, join(dir, 'node_modules', 'wrangler', 'package.json')))
119
+ .find((found) => found !== undefined);
120
+ const installed = typeof manifest?.version === 'string' ? manifest.version : undefined;
121
+ const [major = 0, minor = 0] = (installed ?? '').split('.').map(Number);
122
+ if (installed === undefined) {
123
+ version.problems.push({
124
+ check: 'CC16',
125
+ level: 'warn',
126
+ message:
127
+ 'wrangler is not installed in this project: the deploy uses whichever wrangler it finds, and the preview settings need 4.36 or newer',
128
+ });
129
+ } else if (major < 4 || (major === 4 && minor < 36)) {
130
+ version.problems.push({
131
+ check: 'CC16',
132
+ level: 'error',
133
+ message: `wrangler ${installed} cannot deploy the preview settings: run_worker_first patterns and the ratelimits binding need wrangler 4.36 or newer`,
134
+ });
135
+ } else {
136
+ version.detail = `wrangler ${installed}`;
137
+ }
138
+ }
139
+
140
+ // CC17
141
+ const dispatcher = {
142
+ ...(config === undefined ? skipped('CC17', 'no wrangler.jsonc (see CC15)') : outcomeOf('CC17')),
143
+ ...(mode === 'd4' ? { label: 'wrangler.jsonc keeps no D3 dispatcher settings' } : {}),
144
+ };
145
+ const add = (message: string) => dispatcher.problems.push({ check: 'CC17', level: 'error', message, path });
146
+ if (mode === 'd4' && config?.main === DISPATCHER_MAIN) {
147
+ add(
148
+ `main is the D3 dispatcher, which a separate preview deploy (D4) inherits and its main deploy no longer builds ${UPDATE}`,
149
+ );
150
+ }
151
+ // An assets-only deploy: Wrangler refuses both settings without a script to run.
152
+ if (mode === 'd4' && config !== undefined && config.main === undefined) {
153
+ // `conloca connect --update` removes only what the D3 dispatcher left: an ASSETS binding and the preview's own entries.
154
+ const own = previewOwnEntries(base);
155
+ if (assets.binding !== undefined) {
156
+ const fix = assets.binding === 'ASSETS' ? UPDATE : '— remove assets.binding';
157
+ add(`assets.binding without main: Wrangler refuses an assets binding on a deploy with no script ${fix}`);
158
+ }
159
+ if (assets.run_worker_first !== undefined) {
160
+ const ours = listed.length > 0 && listed.every((entry) => typeof entry === 'string' && own.includes(entry));
161
+ const fix = ours ? UPDATE : '— remove it, or set main to a script of your own';
162
+ add(`run_worker_first without main: Wrangler refuses it on a deploy with no script ${fix}`);
163
+ }
164
+ }
165
+ if (mode === 'd3' && config !== undefined) {
166
+ if (config.main !== DISPATCHER_MAIN) add(`main is not ${DISPATCHER_MAIN} ${UPDATE}`);
167
+ if (!(Array.isArray(config.compatibility_flags) && config.compatibility_flags.includes('nodejs_compat'))) {
168
+ add(`compatibility_flags lacks nodejs_compat ${UPDATE}`);
169
+ }
170
+ if (assets.binding !== 'ASSETS') add(`assets.binding is not ASSETS ${UPDATE}`);
171
+ const missing = everything ? [] : [prefix, `${prefix}/*`].filter((entry) => !listed.includes(entry));
172
+ if (missing.length > 0) add(`run_worker_first lacks ${missing.join(', ')} ${UPDATE}`);
173
+ if (assets.not_found_handling === 'single-page-application') {
174
+ add(`not_found_handling is single-page-application; previews need "404-page" or "none" ${UPDATE}`);
175
+ }
176
+ for (const [envName, block] of Object.entries(isRecord(config.env) ? config.env : {})) {
177
+ if (isRecord(block) && (block.main !== undefined || block.assets !== undefined)) {
178
+ add(`env.${envName} sets main or assets, which replaces the dispatcher's — remove them from the env block`);
179
+ }
180
+ }
181
+ const excluded = listed.find(
182
+ (entry) => typeof entry === 'string' && entry.startsWith('!') && entry.slice(1).startsWith(prefix),
183
+ );
184
+ if (typeof excluded === 'string') {
185
+ add(`run_worker_first excludes the preview route (${excluded}) — remove that entry`);
186
+ }
187
+ if (listed.length > MAX_WORKER_FIRST) {
188
+ add(
189
+ `run_worker_first has ${listed.length} entries, past Cloudflare's cap of ${MAX_WORKER_FIRST} — merge some into wider patterns`,
190
+ );
191
+ }
192
+ }
193
+
194
+ // CC18
195
+ const reported = jsonStrings(deps, join(projectDir, '.conloca', 'dispatcher', 'run_worker_first.json'));
196
+ let routes: CheckOutcome;
197
+ if (mode === 'd4') routes = onlyD3('CC18');
198
+ else if (reported === undefined) routes = skipped('CC18', 'no build yet: build the site, then run doctor');
199
+ else {
200
+ routes = outcomeOf('CC18');
201
+ const missing = everything ? [] : reported.filter((entry) => !listed.includes(entry) && !entry.startsWith(prefix));
202
+ if (missing.length > 0) {
203
+ routes.problems.push({
204
+ check: 'CC18',
205
+ level: 'error',
206
+ message: `run_worker_first lacks ${missing.join(', ')}, which the last build renders on demand ${UPDATE}`,
207
+ path,
208
+ });
209
+ }
210
+ }
211
+
212
+ // CC19
213
+ const redirectPath = join(projectDir, '.wrangler', 'deploy', 'config.json');
214
+ const redirect = jsonRecord(deps, redirectPath);
215
+ const ships = mode === 'd4' ? onlyD3('CC19') : outcomeOf('CC19');
216
+ const target =
217
+ typeof redirect?.configPath === 'string' ? resolve(dirname(redirectPath), redirect.configPath) : undefined;
218
+ if (
219
+ mode === 'd3' &&
220
+ target !== undefined &&
221
+ target.startsWith(`${resolve(projectDir, '.conloca', 'preview-server')}${sep}`)
222
+ ) {
223
+ ships.problems.push({
224
+ check: 'CC19',
225
+ level: 'error',
226
+ message:
227
+ 'a plain `wrangler deploy` would ship the preview server as the site: delete .wrangler/deploy/config.json and build again with this release',
228
+ path: redirectPath,
229
+ });
230
+ }
231
+
232
+ // CC20: a heuristic, so a warning. The detection of middleware negotiation lives here too.
233
+ let misses: CheckOutcome;
234
+ const negotiates = middlewareNegotiates(deps, projectDir);
235
+ if (mode === 'd4') misses = onlyD3('CC20');
236
+ else if (assets.not_found_handling === 'none') {
237
+ misses = {
238
+ ...outcomeOf('CC20'),
239
+ detail: negotiates
240
+ ? 'not_found_handling is "none": every miss reaches the dispatcher, so the middleware negotiates them; its negotiated pages need run_worker_first entries too'
241
+ : 'not_found_handling is "none": every miss reaches the dispatcher, which answers it',
242
+ };
243
+ } else {
244
+ misses = outcomeOf('CC20');
245
+ // A build holds the 404 page however it is made (a CMS page, src/pages/404.ts, [lang]/404.astro); before one, the
246
+ // source files.
247
+ const built = deps.exists(join(projectDir, 'dist', 'index.html'));
248
+ const sources = [
249
+ 'src/pages/404.astro',
250
+ 'src/pages/404.md',
251
+ 'src/pages/404.mdx',
252
+ 'src/pages/404.html',
253
+ 'src/pages/404.ts',
254
+ 'public/404.html',
255
+ ];
256
+ // shortcut: a Starlight site counts as having its own 404 page before a build; the build's dist/404.html settles it.
257
+ const starlight = scan.kind === 'read' && /\bstarlight\s*\(/u.test(read(deps, scan.config.path) ?? '');
258
+ const hasPage = built
259
+ ? deps.exists(join(projectDir, 'dist', '404.html'))
260
+ : starlight || sources.some((page) => deps.exists(join(projectDir, page)));
261
+ if (!hasPage) {
262
+ misses.problems.push({
263
+ check: 'CC20',
264
+ level: 'warn',
265
+ message:
266
+ 'no 404 page: with not_found_handling "404-page" Cloudflare answers a miss with an empty 404 and never starts the dispatcher — add src/pages/404.astro',
267
+ });
268
+ }
269
+ if (negotiates) {
270
+ misses.problems.push({
271
+ check: 'CC20',
272
+ level: 'warn',
273
+ // A heuristic, so only a warning naming the flag: connect never switches "none" on its own.
274
+ message:
275
+ 'the middleware negotiates responses: either (a) run `conloca connect --update --yes --negotiate-404` (not_found_handling "none") and list the negotiated paths in run_worker_first, or (b) keep "404-page" and accept static responses',
276
+ });
277
+ }
278
+ }
279
+
280
+ // CC21
281
+ let tags: CheckOutcome;
282
+ if (mode === 'd4') tags = skipped('CC21', 'a separate preview deploy (D4) serves no visitors');
283
+ else {
284
+ tags = outcomeOf('CC21');
285
+ const files = (deps.git(['ls-files', '--', 'src', 'public'], projectDir) ?? '')
286
+ .split('\n')
287
+ .filter((file) => SOURCE.test(file));
288
+ for (const file of files) {
289
+ const match = TAG_MANAGERS.exec(read(deps, join(projectDir, file)) ?? '');
290
+ if (match === null) continue;
291
+ tags.problems.push({
292
+ check: 'CC21',
293
+ level: 'warn',
294
+ message: `${file} loads a tag manager (${match[0]}): it runs on draft pages and can read them — previewBuild: { separate: true } keeps drafts on a deploy no tag reads`,
295
+ path: join(projectDir, file),
296
+ });
297
+ break;
298
+ }
299
+ }
300
+
301
+ return [deployTarget, version, dispatcher, routes, ships, misses, tags];
302
+ }
@@ -215,3 +215,17 @@ export function previewBuildSetting(scan: ConfigScan): 'off' | 'adapter' | 'on'
215
215
  if (containsOutsideStrings(text, 'adapter')) return 'adapter';
216
216
  return value[1] === '{' ? 'on' : 'unknown';
217
217
  }
218
+
219
+ /**
220
+ * How the preview build serves, as the config text shows it (the rule of `previewBuildMode`): `separate: true` is D4,
221
+ * an adapter named anywhere (the site's or previewBuild's) is D2, a static site is D3; 'unknown' when the text cannot
222
+ * tell.
223
+ */
224
+ export function previewServeSetting(scan: ConfigScan): 'off' | 'd2' | 'd3' | 'd4' | 'unknown' {
225
+ const setting = previewBuildSetting(scan);
226
+ if (setting === 'off' || setting === 'unknown') return setting;
227
+ if (scan.kind !== 'read' || typeof scan.config.conlocaCloud === 'string') return 'unknown';
228
+ if (/\bseparate\s*:\s*true\b/u.test(scan.config.conlocaCloud.text)) return 'd4';
229
+ if (setting === 'adapter' || scan.config.site.adapter) return 'd2';
230
+ return scan.config.site.output === 'unknown' ? 'unknown' : 'd3';
231
+ }
package/src/doctor/run.ts CHANGED
@@ -3,6 +3,8 @@ import { gitOutput, resolveRepositoryUri } from '../git.js';
3
3
  import { checkFramingHeaders, checkKeyLeftovers, checkSiteAddress } from './checks-address.js';
4
4
  import { runLiveChecks } from './checks-live.js';
5
5
  import { checkPreviewBuildAdapter, checkWiring, suppliedEndpoint } from './checks-offline.js';
6
+ import { runPreviewChecks } from './checks-preview.js';
7
+ import { runPreviewLimitChecks } from './checks-preview-limits.js';
6
8
  import { optionLiteral, scanAstroConfig } from './config-scan.js';
7
9
  import type { CloudDoctorContext, CloudDoctorResult, DoctorDeps } from './types.js';
8
10
 
@@ -31,6 +33,8 @@ export async function runDoctor(
31
33
  await checkFramingHeaders(scan, context.projectDir, suppliedEndpoint(scan, deps.env), deps),
32
34
  checkKeyLeftovers(scan, context.projectDir, deps),
33
35
  checkPreviewBuildAdapter(scan),
36
+ ...runPreviewChecks(scan, context.projectDir, deps),
37
+ ...runPreviewLimitChecks(scan, context.projectDir, deps),
34
38
  ...(await runLiveChecks({ context, deps, scan, address: site.address, repoUri })),
35
39
  ];
36
40
  return { contractVersion: 1, checks };
@@ -53,10 +53,20 @@ const CHECK_LABELS = {
53
53
  CC9: 'the site domain is declared in sites.json',
54
54
  CC10: 'committed headers allow framing the editor page',
55
55
  CC14: 'no build key leftovers',
56
- CC8: 'the preview build, when previewBuild is set, has an SSR adapter',
56
+ CC8: 'how the preview build serves drafts',
57
+ CC15: 'the preview deploys to Cloudflare Workers',
58
+ CC16: 'Wrangler is 4.36 or newer',
59
+ CC17: 'wrangler.jsonc runs the preview dispatcher',
60
+ CC18: 'run_worker_first lists every on-demand route',
61
+ CC19: 'a plain wrangler deploy ships the site',
62
+ CC20: 'misses and negotiated pages reach the right place',
63
+ CC21: 'no tag manager runs on draft pages',
64
+ CC22: "the preview route's rate limit fits the plan",
65
+ CC23: 'the recorded Cloudflare plan fits draft previews',
57
66
  CC11: 'the deployed editor page answers',
58
67
  CC12: 'the deployed editor page may be framed',
59
68
  CC13: "the editor speaks this page's protocol",
69
+ CC24: 'the separate preview deploy runs this release',
60
70
  } as const;
61
71
 
62
72
  /** A typo in a check id fails tsc here; the CLI would otherwise drop a label-less outcome silently. */
@@ -58,6 +58,8 @@ export interface EditorBundleDescriptors {
58
58
  * same routes the published page resolves with.
59
59
  */
60
60
  dataBindings?: EditorDataBindings;
61
+ /** The URL the site serves its media folder at (conlocaCMS `assetRefBase`), which every picked image link starts with. */
62
+ assetRefBase?: string;
61
63
  }
62
64
 
63
65
  export interface EditorPageBundleInput {
@@ -176,6 +178,9 @@ export async function bundleEditorPage(input: EditorPageBundleInput): Promise<Ed
176
178
  ...(discovered.length > 0 ? [`export const discoveredMdxComponents = ${JSON.stringify(discovered)};`] : []),
177
179
  ...(descriptors?.templates ? [`export const templates = ${JSON.stringify(descriptors.templates)};`] : []),
178
180
  ...(descriptors?.dataBindings ? [`export const dataBindings = ${JSON.stringify(descriptors.dataBindings)};`] : []),
181
+ ...(descriptors?.assetRefBase === undefined
182
+ ? []
183
+ : [`export const assetRefBase = ${JSON.stringify(descriptors.assetRefBase)};`]),
179
184
  ].join('\n');
180
185
 
181
186
  const jsAssets: EditorAsset[] = [];
@@ -0,0 +1,47 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
4
+ import { DATA_SCHEMAS_FILE } from '@conloca/content-api/editor-host';
5
+ import { runnerImport, type UserConfig } from 'vite';
6
+ import { PACKAGE_NAME } from '../constants.js';
7
+ import { messageOf } from '../message-of.js';
8
+
9
+ /**
10
+ * Writes `<folder>/data-schemas.json`: the JSON schema `metadata` of each `dataSchemas` collection in the schemas
11
+ * module, in the module's order. The module runs through the site's own Vite plugins, as the content config does, so
12
+ * schema generators such as typia's transform apply. A module that fails to load costs the file, not the build.
13
+ */
14
+ export async function emitDataSchemas(input: {
15
+ folder: string;
16
+ root: string;
17
+ vite: UserConfig;
18
+ schemasPath: string;
19
+ logger: { warn(message: string): void };
20
+ }): Promise<void> {
21
+ let dataSchemas: unknown;
22
+ try {
23
+ // shortcut: runnerImport resolves plugins in serve mode, so an apply: 'build' schema transform is skipped (warning, no file); upgrade if a site needs one.
24
+ const { module } = await runnerImport<{ dataSchemas?: unknown }>(resolve(input.root, input.schemasPath), {
25
+ ...input.vite,
26
+ configFile: false,
27
+ root: input.root,
28
+ logLevel: 'warn',
29
+ });
30
+ dataSchemas = module.dataSchemas;
31
+ } catch (error) {
32
+ input.logger.warn(
33
+ `${PACKAGE_NAME}: the schemas module at ${input.schemasPath} failed to load, so ${DATA_SCHEMAS_FILE} is not written: ${messageOf(error)}`,
34
+ );
35
+ return;
36
+ }
37
+ if (!isRecord(dataSchemas)) return;
38
+ const collections = Object.fromEntries(
39
+ Object.entries(dataSchemas).flatMap(([name, entry]) => {
40
+ const metadata = isRecord(entry) ? entry.metadata : undefined;
41
+ return isRecord(metadata) && isRecord(metadata.schema) && isRecord(metadata.components)
42
+ ? [[name, metadata] as const]
43
+ : [];
44
+ }),
45
+ );
46
+ await writeFile(join(input.folder, DATA_SCHEMAS_FILE), `${JSON.stringify({ collections }, null, 2)}\n`);
47
+ }
@@ -2,18 +2,32 @@ import { createHash } from 'node:crypto';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { cp, mkdir, writeFile } from 'node:fs/promises';
4
4
  import { isAbsolute, join, relative, sep } from 'node:path';
5
+ import {
6
+ type AstroI18nLocales,
7
+ collectStaticPageRoutes,
8
+ nonDefaultLocalesOf,
9
+ type StaticPageRoute,
10
+ } from '@conloca/astro-cms/checks';
5
11
  import { readEditorDescriptors } from '@conloca/astro-cms/node';
6
12
  import { isValidSiteBase } from '@conloca/content-api';
7
13
  import {
8
14
  type BranchDeploys,
9
15
  branchDeploysOf,
16
+ CONLOCA_JSON_MAX_BYTES,
10
17
  contentPathsOf,
11
18
  EDITOR_HOST_PROTOCOL,
12
19
  EDITOR_PAGE_INFO_FORMATS,
20
+ type EditorMedia,
13
21
  type EditorPageInfo,
14
22
  editorUiOrigin,
15
23
  isEditorPageInfo,
24
+ isEditorRoute,
16
25
  isValidBranchName,
26
+ mediaOf,
27
+ PREVIEW_PROTOCOL,
28
+ type PreviewMode,
29
+ type PreviewSignal,
30
+ ROUTES_MAX,
17
31
  } from '@conloca/content-api/editor-host';
18
32
  import { readSitesConfig } from '@conloca/content-api/node';
19
33
  import { buildSandboxSrcdoc } from '@conloca/mdx/sandbox-frame';
@@ -26,6 +40,7 @@ import { packageVersion } from '../package-version.js';
26
40
  import type { InheritedOptions } from '../resolve-options.js';
27
41
  import { resolveBuildSiteId } from '../site-id.js';
28
42
  import { bundleEditorPage } from './bundle.js';
43
+ import { emitDataSchemas } from './data-schemas.js';
29
44
  import { findFramingBlockers } from './framing.js';
30
45
  import { renderEditorPage } from './page.js';
31
46
  import { baseMismatch } from './site-base.js';
@@ -46,6 +61,14 @@ export interface EmitEditorPageInput {
46
61
  inherited: InheritedOptions;
47
62
  repoUri: string | undefined;
48
63
  siteIdOverride: string | undefined;
64
+ /** How this build serves draft previews; conloca.json `preview.mode`. */
65
+ previewMode: PreviewMode;
66
+ /** The site's `src/pages` folder, as a filesystem path. */
67
+ pagesDir: string;
68
+ /** Astro `output === 'server'`: only pages with `prerender = true` are built. */
69
+ serverOutput: boolean;
70
+ /** Astro's `i18n`, whose non-default locale folders hold no pages to offer. */
71
+ i18n: AstroI18nLocales | undefined;
49
72
  logger: { info(message: string): void; warn(message: string): void };
50
73
  }
51
74
 
@@ -61,7 +84,8 @@ export async function emitEditorPage(input: EmitEditorPageInput): Promise<void>
61
84
  );
62
85
  }
63
86
  const contentRoot = process.env.CONLOCA_CONTENT_ROOT;
64
- const mismatch = contentRoot ? baseMismatch(await readSitesConfig(contentRoot), base) : undefined;
87
+ const sitesConfig = contentRoot ? await readSitesConfig(contentRoot) : undefined;
88
+ const mismatch = sitesConfig ? baseMismatch(sitesConfig, base) : undefined;
65
89
  if (mismatch !== undefined) logger.warn(mismatch);
66
90
  for (const { file, header } of await findFramingBlockers(input.root)) {
67
91
  logger.warn(
@@ -91,6 +115,15 @@ export async function emitEditorPage(input: EmitEditorPageInput): Promise<void>
91
115
  ...(descriptors === undefined ? {} : { descriptors }),
92
116
  logger,
93
117
  });
118
+ if (descriptors?.schemasPath) {
119
+ await emitDataSchemas({
120
+ folder,
121
+ root: input.root,
122
+ vite: input.vite,
123
+ schemasPath: descriptors.schemasPath,
124
+ logger,
125
+ });
126
+ }
94
127
 
95
128
  let editorCssFile: string | null = null;
96
129
  if (inherited.editorCss) {
@@ -117,17 +150,35 @@ export async function emitEditorPage(input: EmitEditorPageInput): Promise<void>
117
150
  if (!isEditorPageInfo(info)) {
118
151
  throw new Error(`${PACKAGE_NAME}: internal error: conloca.json failed its own format check`);
119
152
  }
120
- const contentPaths = contentPathsFromBuild(
121
- channel?.contentPaths ?? [],
122
- gitOutput(['rev-parse', '--show-toplevel'], input.root),
123
- );
153
+ const repoRoot = gitOutput(['rev-parse', '--show-toplevel'], input.root);
154
+ const contentPaths = contentPathsFromBuild(channel?.contentPaths ?? [], repoRoot);
155
+ const media = mediaFromBuild(channel, repoRoot);
156
+ if (media === undefined && repoRoot !== undefined && channel?.assetsPath !== undefined) {
157
+ logger.warn(
158
+ `the media folder ${channel.assetsPath} is not a folder of this site's repository, so the workspace editor cannot add images to it`,
159
+ );
160
+ }
124
161
  const branchDeploys = branchDeploysFromEnv(process.env);
125
- const written = {
162
+ const preview: PreviewSignal = { mode: input.previewMode, protocol: PREVIEW_PROTOCOL };
163
+ const written: WrittenConlocaJson = {
126
164
  ...info,
165
+ preview,
127
166
  ...(branchDeploys === undefined ? {} : { branchDeploys }),
128
167
  ...(contentPaths === undefined ? {} : { contentPaths }),
168
+ ...(media === undefined ? {} : { media }),
129
169
  };
130
- await writeFile(join(folder, 'conloca.json'), `${JSON.stringify(written, null, 2)}\n`);
170
+ const collected = await collectStaticPageRoutes({
171
+ pagesDir: input.pagesDir,
172
+ serverOutput: input.serverOutput,
173
+ nonDefaultLocales: nonDefaultLocalesOf(sitesConfig ?? { sites: {} }, info.siteId, input.i18n),
174
+ });
175
+ const { routes, left } = routesFromBuild(collected, written);
176
+ if (left > 0) {
177
+ logger.warn(
178
+ `conloca.json lists ${routes.length} of ${routes.length + left} static page routes; the others have names outside the editor's route format or do not fit. \`npx @conloca/cli routes\` lists them all.`,
179
+ );
180
+ }
181
+ await writeFile(join(folder, 'conloca.json'), `${JSON.stringify({ ...written, routes }, null, 2)}\n`);
131
182
 
132
183
  const url = (file: string) => `${base}${EDITOR_DIR}/${file}`;
133
184
  const html = renderEditorPage(
@@ -153,6 +204,23 @@ export async function mirrorEditorPage(fromDir: string, toDir: string): Promise<
153
204
  await cp(join(fromDir, EDITOR_DIR), join(toDir, EDITOR_DIR), { recursive: true });
154
205
  }
155
206
 
207
+ /**
208
+ * A separate preview deploy (D4) serves no editor page, but it answers its own conloca.json: its release, protocol
209
+ * and mode, read next to the site's to tell when the two deploys run different releases.
210
+ */
211
+ export async function emitPreviewServerInfo(
212
+ dir: string,
213
+ input: Pick<EmitEditorPageInput, 'root' | 'repoUri' | 'siteIdOverride' | 'logger'>,
214
+ ): Promise<void> {
215
+ const preview: PreviewSignal = { mode: 'd4', protocol: PREVIEW_PROTOCOL };
216
+ const folder = join(dir, EDITOR_DIR);
217
+ await mkdir(folder, { recursive: true });
218
+ await writeFile(
219
+ join(folder, 'conloca.json'),
220
+ `${JSON.stringify({ ...editorPageInfo(input, undefined), preview }, null, 2)}\n`,
221
+ );
222
+ }
223
+
156
224
  /**
157
225
  * The Cloudflare Pages project that serves this site's branch builds: `CONLOCA_PAGES_PROJECT` (direct upload with
158
226
  * wrangler) wins, else the project in a Pages build's `CF_PAGES_URL` (`https://<hash>.<project>.pages.dev`).
@@ -186,12 +254,60 @@ export function contentPathsFromBuild(paths: readonly string[], repoRoot: string
186
254
  return contentPathsOf({ contentPaths });
187
255
  }
188
256
 
257
+ /** conloca.json as the build writes it before its `routes`. */
258
+ export interface WrittenConlocaJson extends EditorPageInfo {
259
+ preview: PreviewSignal;
260
+ branchDeploys?: BranchDeploys;
261
+ contentPaths?: string[];
262
+ media?: EditorMedia;
263
+ }
264
+
265
+ /** The routes conloca.json lists and how many prerendered routes it leaves out. */
266
+ export interface BuildRoutes {
267
+ routes: string[];
268
+ left: number;
269
+ }
270
+
271
+ /**
272
+ * The prerendered routes in the editor's route format, in order, up to `ROUTES_MAX` and while the whole conloca.json
273
+ * stays within `CONLOCA_JSON_MAX_BYTES`; `left` counts the prerendered routes not written.
274
+ */
275
+ export function routesFromBuild(collected: readonly StaticPageRoute[], written: WrittenConlocaJson): BuildRoutes {
276
+ const prerendered = collected.filter((page) => page.prerendered);
277
+ const routes: string[] = [];
278
+ for (const { route } of prerendered) {
279
+ if (routes.length === ROUTES_MAX) break;
280
+ if (!isEditorRoute(route)) continue;
281
+ routes.push(route);
282
+ const bytes = new TextEncoder().encode(`${JSON.stringify({ ...written, routes }, null, 2)}\n`).length;
283
+ if (bytes > CONLOCA_JSON_MAX_BYTES) {
284
+ routes.pop();
285
+ break;
286
+ }
287
+ }
288
+ return { routes, left: prerendered.length - routes.length };
289
+ }
290
+
291
+ /** The media folder written from the repository root, with its link base; undefined outside the repository. */
292
+ export function mediaFromBuild(
293
+ channel: { assetsPath?: string; assetRefBase?: string } | undefined,
294
+ repoRoot: string | undefined,
295
+ ): EditorMedia | undefined {
296
+ if (repoRoot === undefined || channel?.assetsPath === undefined || channel.assetRefBase === undefined) {
297
+ return undefined;
298
+ }
299
+ const path = relative(repoRoot, channel.assetsPath);
300
+ const segments = path.split(sep);
301
+ if (isAbsolute(path) || segments[0] === '..') return undefined;
302
+ return mediaOf({ media: { path: segments.join('/'), refBase: channel.assetRefBase } });
303
+ }
304
+
189
305
  /**
190
306
  * conloca.json's facts. A repository, commit or branch that is unknown or fails its format is written as null with a
191
307
  * warning; a `builtWith` that cannot be formed fails the build, since the workspace editor would refuse the page.
192
308
  */
193
309
  function editorPageInfo(
194
- input: EmitEditorPageInput,
310
+ input: Pick<EmitEditorPageInput, 'root' | 'repoUri' | 'siteIdOverride' | 'logger'>,
195
311
  componentManifest: { filename: string; hash: string } | undefined,
196
312
  ): EditorPageInfo {
197
313
  const { logger } = input;
package/src/index.ts CHANGED
@@ -19,4 +19,6 @@ export {
19
19
  } from './editor-page/framing.js';
20
20
  // The default export is what `astro add @conloca/cloud-astro` wires in.
21
21
  export { conlocaCloud as default, conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
22
+ // The page `conloca upgrade` compares against the site's copy and refreshes.
23
+ export { agentSkill } from './skill.js';
22
24
  export type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';