@conloca/cloud-astro 0.0.0-stage → 0.2.2

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 (196) hide show
  1. package/README.md +328 -2
  2. package/dist/src/build-commit.d.ts +19 -0
  3. package/dist/src/build-commit.d.ts.map +1 -0
  4. package/dist/src/build-commit.js +6 -0
  5. package/dist/src/build-commit.js.map +1 -0
  6. package/dist/src/bundle.d.ts +181 -0
  7. package/dist/src/bundle.d.ts.map +1 -0
  8. package/dist/src/bundle.js +413 -0
  9. package/dist/src/bundle.js.map +1 -0
  10. package/dist/src/component-manifest.d.ts +29 -0
  11. package/dist/src/component-manifest.d.ts.map +1 -0
  12. package/dist/src/component-manifest.js +53 -0
  13. package/dist/src/component-manifest.js.map +1 -0
  14. package/dist/src/constants.d.ts +26 -0
  15. package/dist/src/constants.d.ts.map +1 -0
  16. package/dist/src/constants.js +26 -0
  17. package/dist/src/constants.js.map +1 -0
  18. package/dist/src/descriptors.d.ts +25 -0
  19. package/dist/src/descriptors.d.ts.map +1 -0
  20. package/dist/src/descriptors.js +65 -0
  21. package/dist/src/descriptors.js.map +1 -0
  22. package/dist/src/discovery.d.ts +58 -0
  23. package/dist/src/discovery.d.ts.map +1 -0
  24. package/dist/src/discovery.js +133 -0
  25. package/dist/src/discovery.js.map +1 -0
  26. package/dist/src/doctor/checks-live.d.ts +15 -0
  27. package/dist/src/doctor/checks-live.d.ts.map +1 -0
  28. package/dist/src/doctor/checks-live.js +229 -0
  29. package/dist/src/doctor/checks-live.js.map +1 -0
  30. package/dist/src/doctor/checks-offline.d.ts +36 -0
  31. package/dist/src/doctor/checks-offline.d.ts.map +1 -0
  32. package/dist/src/doctor/checks-offline.js +301 -0
  33. package/dist/src/doctor/checks-offline.js.map +1 -0
  34. package/dist/src/doctor/config-scan.d.ts +55 -0
  35. package/dist/src/doctor/config-scan.d.ts.map +1 -0
  36. package/dist/src/doctor/config-scan.js +178 -0
  37. package/dist/src/doctor/config-scan.js.map +1 -0
  38. package/dist/src/doctor/run.d.ts +4 -0
  39. package/dist/src/doctor/run.d.ts.map +1 -0
  40. package/dist/src/doctor/run.js +29 -0
  41. package/dist/src/doctor/run.js.map +1 -0
  42. package/dist/src/doctor/types.d.ts +60 -0
  43. package/dist/src/doctor/types.d.ts.map +1 -0
  44. package/dist/src/doctor/types.js +18 -0
  45. package/dist/src/doctor/types.js.map +1 -0
  46. package/dist/src/doctor.d.ts +9 -0
  47. package/dist/src/doctor.d.ts.map +1 -0
  48. package/dist/src/doctor.js +12 -0
  49. package/dist/src/doctor.js.map +1 -0
  50. package/dist/src/git.d.ts +38 -0
  51. package/dist/src/git.d.ts.map +1 -0
  52. package/dist/src/git.js +43 -0
  53. package/dist/src/git.js.map +1 -0
  54. package/dist/src/index.d.ts +3 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/index.js +7 -0
  57. package/dist/src/index.js.map +1 -0
  58. package/dist/src/integration.d.ts +6 -0
  59. package/dist/src/integration.d.ts.map +1 -0
  60. package/dist/src/integration.js +544 -0
  61. package/dist/src/integration.js.map +1 -0
  62. package/dist/src/message-of.d.ts +3 -0
  63. package/dist/src/message-of.d.ts.map +1 -0
  64. package/dist/src/message-of.js +5 -0
  65. package/dist/src/message-of.js.map +1 -0
  66. package/dist/src/node.d.ts +3 -0
  67. package/dist/src/node.d.ts.map +1 -0
  68. package/dist/src/node.js +4 -0
  69. package/dist/src/node.js.map +1 -0
  70. package/dist/src/package-version.d.ts +7 -0
  71. package/dist/src/package-version.d.ts.map +1 -0
  72. package/dist/src/package-version.js +17 -0
  73. package/dist/src/package-version.js.map +1 -0
  74. package/dist/src/preview/_dispatch.d.ts +55 -0
  75. package/dist/src/preview/_dispatch.d.ts.map +1 -0
  76. package/dist/src/preview/_dispatch.js +72 -0
  77. package/dist/src/preview/_dispatch.js.map +1 -0
  78. package/dist/src/preview/_resolve-opts.d.ts +30 -0
  79. package/dist/src/preview/_resolve-opts.d.ts.map +1 -0
  80. package/dist/src/preview/_resolve-opts.js +73 -0
  81. package/dist/src/preview/_resolve-opts.js.map +1 -0
  82. package/dist/src/preview/banner.d.ts +29 -0
  83. package/dist/src/preview/banner.d.ts.map +1 -0
  84. package/dist/src/preview/banner.js +94 -0
  85. package/dist/src/preview/banner.js.map +1 -0
  86. package/dist/src/preview/content-api.d.ts +110 -0
  87. package/dist/src/preview/content-api.d.ts.map +1 -0
  88. package/dist/src/preview/content-api.js +216 -0
  89. package/dist/src/preview/content-api.js.map +1 -0
  90. package/dist/src/preview/cookie.d.ts +36 -0
  91. package/dist/src/preview/cookie.d.ts.map +1 -0
  92. package/dist/src/preview/cookie.js +59 -0
  93. package/dist/src/preview/cookie.js.map +1 -0
  94. package/dist/src/preview/headers.d.ts +25 -0
  95. package/dist/src/preview/headers.d.ts.map +1 -0
  96. package/dist/src/preview/headers.js +31 -0
  97. package/dist/src/preview/headers.js.map +1 -0
  98. package/dist/src/preview/landing.d.ts +22 -0
  99. package/dist/src/preview/landing.d.ts.map +1 -0
  100. package/dist/src/preview/landing.js +70 -0
  101. package/dist/src/preview/landing.js.map +1 -0
  102. package/dist/src/preview/middleware.d.ts +118 -0
  103. package/dist/src/preview/middleware.d.ts.map +1 -0
  104. package/dist/src/preview/middleware.js +197 -0
  105. package/dist/src/preview/middleware.js.map +1 -0
  106. package/dist/src/preview/preview-path.d.ts +21 -0
  107. package/dist/src/preview/preview-path.d.ts.map +1 -0
  108. package/dist/src/preview/preview-path.js +29 -0
  109. package/dist/src/preview/preview-path.js.map +1 -0
  110. package/dist/src/preview/satteri-workerd.d.ts +17 -0
  111. package/dist/src/preview/satteri-workerd.d.ts.map +1 -0
  112. package/dist/src/preview/satteri-workerd.js +18 -0
  113. package/dist/src/preview/satteri-workerd.js.map +1 -0
  114. package/dist/src/preview/site-middleware.d.ts +69 -0
  115. package/dist/src/preview/site-middleware.d.ts.map +1 -0
  116. package/dist/src/preview/site-middleware.js +160 -0
  117. package/dist/src/preview/site-middleware.js.map +1 -0
  118. package/dist/src/preview/workerd-shim.d.ts +19 -0
  119. package/dist/src/preview/workerd-shim.d.ts.map +1 -0
  120. package/dist/src/preview/workerd-shim.js +33 -0
  121. package/dist/src/preview/workerd-shim.js.map +1 -0
  122. package/dist/src/preview-build.d.ts +71 -0
  123. package/dist/src/preview-build.d.ts.map +1 -0
  124. package/dist/src/preview-build.js +115 -0
  125. package/dist/src/preview-build.js.map +1 -0
  126. package/dist/src/preview.d.ts +6 -0
  127. package/dist/src/preview.d.ts.map +1 -0
  128. package/dist/src/preview.js +12 -0
  129. package/dist/src/preview.js.map +1 -0
  130. package/dist/src/register.d.ts +98 -0
  131. package/dist/src/register.d.ts.map +1 -0
  132. package/dist/src/register.js +103 -0
  133. package/dist/src/register.js.map +1 -0
  134. package/dist/src/repository.d.ts +18 -0
  135. package/dist/src/repository.d.ts.map +1 -0
  136. package/dist/src/repository.js +46 -0
  137. package/dist/src/repository.js.map +1 -0
  138. package/dist/src/site-id.d.ts +18 -0
  139. package/dist/src/site-id.d.ts.map +1 -0
  140. package/dist/src/site-id.js +70 -0
  141. package/dist/src/site-id.js.map +1 -0
  142. package/dist/src/site-middleware.d.ts +18 -0
  143. package/dist/src/site-middleware.d.ts.map +1 -0
  144. package/dist/src/site-middleware.js +47 -0
  145. package/dist/src/site-middleware.js.map +1 -0
  146. package/dist/src/skill.d.ts +26 -0
  147. package/dist/src/skill.d.ts.map +1 -0
  148. package/dist/src/skill.js +67 -0
  149. package/dist/src/skill.js.map +1 -0
  150. package/dist/src/types.d.ts +135 -0
  151. package/dist/src/types.d.ts.map +1 -0
  152. package/dist/src/types.js +2 -0
  153. package/dist/src/types.js.map +1 -0
  154. package/package.json +182 -4
  155. package/src/build-commit.ts +22 -0
  156. package/src/bundle.ts +570 -0
  157. package/src/component-manifest.ts +75 -0
  158. package/src/constants.ts +28 -0
  159. package/src/descriptors.ts +92 -0
  160. package/src/discovery.ts +183 -0
  161. package/src/doctor/checks-live.ts +324 -0
  162. package/src/doctor/checks-offline.ts +325 -0
  163. package/src/doctor/config-scan.ts +205 -0
  164. package/src/doctor/run.ts +39 -0
  165. package/src/doctor/types.ts +71 -0
  166. package/src/doctor.ts +14 -0
  167. package/src/git.ts +66 -0
  168. package/src/index.ts +8 -0
  169. package/src/integration.ts +607 -0
  170. package/src/message-of.ts +4 -0
  171. package/src/node.ts +5 -0
  172. package/src/package-version.ts +16 -0
  173. package/src/preview/_dispatch.ts +105 -0
  174. package/src/preview/_resolve-opts.ts +89 -0
  175. package/src/preview/banner.ts +96 -0
  176. package/src/preview/content-api.ts +293 -0
  177. package/src/preview/cookie.ts +54 -0
  178. package/src/preview/headers.ts +30 -0
  179. package/src/preview/landing.ts +73 -0
  180. package/src/preview/middleware.ts +309 -0
  181. package/src/preview/preview-path.ts +28 -0
  182. package/src/preview/satteri-workerd.ts +24 -0
  183. package/src/preview/site-middleware.ts +210 -0
  184. package/src/preview/workerd-shim.ts +31 -0
  185. package/src/preview-build.ts +147 -0
  186. package/src/preview-handler.astro +55 -0
  187. package/src/preview-handler.d.ts +6 -0
  188. package/src/preview.ts +22 -0
  189. package/src/register.ts +180 -0
  190. package/src/repository.ts +54 -0
  191. package/src/site-id.ts +86 -0
  192. package/src/site-middleware.ts +55 -0
  193. package/src/skill/SKILL.md +69 -0
  194. package/src/skill.ts +66 -0
  195. package/src/types.ts +137 -0
  196. package/src/virtual-modules.d.ts +52 -0
@@ -0,0 +1,92 @@
1
+ import type { MdxRegistryScanOptions } from '@conloca/astro-cms/node';
2
+ import {
3
+ discoverMdxComponents,
4
+ EDITOR_DESCRIPTORS_ENV_VAR,
5
+ readEditorDescriptors,
6
+ toPortableImports,
7
+ } from '@conloca/astro-cms/node';
8
+ import type { EditorBundleDescriptors } from './bundle.js';
9
+
10
+ /**
11
+ * The MDX discovery seam, so tests can drive the failure path without a
12
+ * fixture project (same convention as `_postRegistrationWith` in register.ts).
13
+ */
14
+ export type MdxDescriptorScan = (options: MdxRegistryScanOptions) => Promise<readonly unknown[]>;
15
+
16
+ /**
17
+ * Runs conlocaCMS's own registry scan and makes its local-component import
18
+ * specifiers portable — the descriptors are serialized into the site's
19
+ * MDX files on save, where a build agent's absolute path would be a
20
+ * committed dead link.
21
+ */
22
+ const scanMdxDescriptors: MdxDescriptorScan = async (options) => {
23
+ // Resolved ONCE and handed to both calls: the scan and the portability
24
+ // rewrite must agree on the root, or a drift in either default would
25
+ // produce non-portable paths with no failing test.
26
+ const projectRoot = options.projectRoot ?? process.cwd();
27
+ return toPortableImports(await discoverMdxComponents({ ...options, projectRoot }), projectRoot);
28
+ };
29
+
30
+ /**
31
+ * Resolves the editor descriptors for this build from the channel conlocaCMS
32
+ * published — the bundle's third leg, next to the puck config and the styles.
33
+ *
34
+ * The editor at the endpoint has no dev server to serve `/api/registry` from,
35
+ * so the scan runs HERE and its output is compiled into the bundle. Fail-soft throughout: a
36
+ * scan failure costs the auto-discovered half and warns; an absent channel (a
37
+ * CMS-less build) is simply a build with no descriptors; a PRESENT but
38
+ * unreadable channel warns — that is version drift between this package and
39
+ * `@conloca/astro-cms`, not a CMS-less build, and silence would strip every
40
+ * schema from the editor at the endpoint with no diagnostic. The bundle itself stays
41
+ * fail-hard, unchanged.
42
+ */
43
+ export async function resolveEditorDescriptors(
44
+ logger: { info(message: string): void; warn(message: string): void },
45
+ env: Record<string, string | undefined> = process.env,
46
+ scan: MdxDescriptorScan = scanMdxDescriptors,
47
+ ): Promise<EditorBundleDescriptors | undefined> {
48
+ const channel = readEditorDescriptors(env);
49
+ if (channel === undefined) {
50
+ if (env[EDITOR_DESCRIPTORS_ENV_VAR] !== undefined && env[EDITOR_DESCRIPTORS_ENV_VAR] !== '') {
51
+ logger.warn(
52
+ `${EDITOR_DESCRIPTORS_ENV_VAR} is set but unreadable — @conloca/astro-cms and @conloca/cloud-astro ` +
53
+ 'versions may have drifted; the editor at the endpoint gets no schemas or MDX descriptors from this build, ' +
54
+ 'and agents get no component manifest',
55
+ );
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ let discovered: readonly unknown[] = [];
61
+ try {
62
+ discovered = await scan(channel.registry);
63
+ } catch (error) {
64
+ logger.warn(
65
+ 'MDX component discovery failed — the editor at the endpoint gets the site-authored descriptors only ' +
66
+ `(${error instanceof Error ? error.message : String(error)})`,
67
+ );
68
+ }
69
+
70
+ const templateCount = Object.keys(channel.templates ?? {}).length;
71
+ const { dataBindings } = channel;
72
+ if (
73
+ channel.schemasPath === undefined &&
74
+ discovered.length === 0 &&
75
+ templateCount === 0 &&
76
+ dataBindings === undefined
77
+ ) {
78
+ return undefined;
79
+ }
80
+ logger.info(
81
+ `editor descriptors: ${discovered.length} auto-discovered MDX component(s)` +
82
+ (channel.schemasPath ? ` plus the host schemas module (${channel.schemasPath})` : '') +
83
+ (templateCount > 0 ? ` plus ${templateCount} page template(s)` : '') +
84
+ (dataBindings ? ` plus the data bindings of ${Object.keys(dataBindings.routes).length} page collection(s)` : ''),
85
+ );
86
+ return {
87
+ ...(channel.schemasPath === undefined ? {} : { schemasPath: channel.schemasPath }),
88
+ ...(discovered.length === 0 ? {} : { discoveredMdxComponents: discovered }),
89
+ ...(templateCount === 0 ? {} : { templates: channel.templates }),
90
+ ...(dataBindings === undefined ? {} : { dataBindings }),
91
+ };
92
+ }
@@ -0,0 +1,183 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import type { DiscoveredWrappers } from '@conloca/astro-cms/node';
4
+ import { findContentWrapper } from '@conloca/astro-cms/node';
5
+
6
+ /**
7
+ * Build-time style discovery. The editor at the endpoint cannot run the
8
+ * discovery flow conlocaCMS runs on the site's dev server — no Vite graph to
9
+ * ask for a route's CSS, and cross-origin computed styles are browser-blocked
10
+ * — but every mechanism only produces plain data, and the build is the moment
11
+ * this pipeline stands inside the site. So: read the discovery route's
12
+ * rendered page, collect its stylesheets, run the SAME wrapper heuristic the
13
+ * dev server runs (`findContentWrapper`, imported — not duplicated), and hand
14
+ * the results to registration.
15
+ *
16
+ * Where the rendered page comes from, in order:
17
+ * 1. a prerendered file in the client dir (static routes);
18
+ * 2. the built server entry, booted for one request (the node adapter's
19
+ * `dist/server/entry.mjs` honors HOST/PORT) — covers `output: 'server'`
20
+ * sites, which is what real CMS deployments are;
21
+ * 3. nothing → warn and skip; registration proceeds without the artifacts
22
+ * (fail-soft, like every other optional registration input).
23
+ *
24
+ * ponytail: only the node adapter's entry is bootable in v1 — a
25
+ * workerd-targeted build (Cloudflare adapter) skips discovery with the
26
+ * warning. A site whose prose is `.conloca-prose`-scoped is already covered
27
+ * by the derived tier; boot-via-wrangler is the upgrade path if a
28
+ * workerd-targeted site ever needs heuristic discovery.
29
+ */
30
+
31
+ export interface DiscoveredStyleContext {
32
+ hostWrappers: DiscoveredWrappers;
33
+ /** The route's stylesheets concatenated in document order (links + inline). */
34
+ routeCss: string;
35
+ }
36
+
37
+ export type CssRef = { kind: 'link'; href: string } | { kind: 'inline'; css: string };
38
+
39
+ /**
40
+ * Stylesheet references of a rendered page in document order. Regex-level on
41
+ * purpose: build-output HTML is machine-generated, and the only shapes that
42
+ * matter are `<link rel="stylesheet">` and `<style>` blocks.
43
+ */
44
+ export function extractRouteCssRefs(html: string): CssRef[] {
45
+ const refs: Array<{ index: number; ref: CssRef }> = [];
46
+
47
+ const linkRe = /<link\b[^>]*>/gi;
48
+ for (const match of html.matchAll(linkRe)) {
49
+ const tag = match[0];
50
+ if (!/rel\s*=\s*["']?stylesheet["']?/i.test(tag)) continue;
51
+ const href = tag.match(/href\s*=\s*["']([^"']+)["']/i)?.[1];
52
+ if (href) refs.push({ index: match.index ?? 0, ref: { kind: 'link', href } });
53
+ }
54
+
55
+ const styleRe = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
56
+ for (const match of html.matchAll(styleRe)) {
57
+ const css = match[1].trim();
58
+ if (css) refs.push({ index: match.index ?? 0, ref: { kind: 'inline', css } });
59
+ }
60
+
61
+ return refs.sort((a, b) => a.index - b.index).map((entry) => entry.ref);
62
+ }
63
+
64
+ interface DiscoverInput {
65
+ /** The build's client output dir (where `_conloca/` also lands). */
66
+ clientDir: string;
67
+ /** The built SSR entry, when the adapter produces a bootable one. */
68
+ serverEntry?: string;
69
+ /** The representative content route (the shared `fragmentPreviewRoute`). */
70
+ route: string;
71
+ logger: { info(message: string): void; warn(message: string): void };
72
+ }
73
+
74
+ export async function discoverStyleContext(input: DiscoverInput): Promise<DiscoveredStyleContext | undefined> {
75
+ const fromFile = await readPrerenderedPage(input);
76
+ if (fromFile) return fromFile;
77
+
78
+ if (input.serverEntry) {
79
+ try {
80
+ return await bootAndDiscover(input);
81
+ } catch (error) {
82
+ input.logger.warn(
83
+ `style discovery: booting the server entry failed — skipping (${
84
+ error instanceof Error ? error.message : String(error)
85
+ })`,
86
+ );
87
+ return undefined;
88
+ }
89
+ }
90
+
91
+ input.logger.warn(
92
+ `style discovery: no built page for ${input.route} and no bootable server entry — ` +
93
+ 'skipping; the editor falls back to the prose-safe tier.',
94
+ );
95
+ return undefined;
96
+ }
97
+
98
+ /** Try `<route>/index.html` then `<route>.html` under the client dir. */
99
+ async function readPrerenderedPage(input: DiscoverInput): Promise<DiscoveredStyleContext | undefined> {
100
+ const slug = input.route.replace(/^\/+|\/+$/g, '');
101
+ for (const candidate of [`${slug}/index.html`, `${slug}.html`]) {
102
+ let html: string;
103
+ try {
104
+ html = await readFile(join2(input.clientDir, candidate), 'utf8');
105
+ } catch {
106
+ continue;
107
+ }
108
+ const routeCss = await assembleCss(extractRouteCssRefs(html), async (href) => {
109
+ try {
110
+ return await readFile(join2(input.clientDir, href.replace(/^\/+/, '')), 'utf8');
111
+ } catch {
112
+ input.logger.warn(`style discovery: stylesheet ${href} not found in the client dir — skipped.`);
113
+ return '';
114
+ }
115
+ });
116
+ return { hostWrappers: findContentWrapper(html), routeCss };
117
+ }
118
+ return undefined;
119
+ }
120
+
121
+ /** Boot the built entry on a loopback port, fetch the route + its CSS, kill. */
122
+ async function bootAndDiscover(input: DiscoverInput): Promise<DiscoveredStyleContext | undefined> {
123
+ if (!input.serverEntry) return undefined;
124
+ const port = 41000 + Math.floor(Math.random() * 20000);
125
+ const origin = `http://127.0.0.1:${port}`;
126
+ const child = spawn(process.execPath, [input.serverEntry], {
127
+ env: { ...process.env, HOST: '127.0.0.1', PORT: String(port) },
128
+ stdio: 'ignore',
129
+ });
130
+ try {
131
+ await waitForServer(origin);
132
+ const page = await fetch(`${origin}${input.route}`);
133
+ if (!page.ok) {
134
+ input.logger.warn(`style discovery: ${input.route} answered ${page.status} on the booted entry — skipping.`);
135
+ return undefined;
136
+ }
137
+ const html = await page.text();
138
+ const routeCss = await assembleCss(extractRouteCssRefs(html), async (href) => {
139
+ const res = await fetch(new URL(href, origin));
140
+ if (!res.ok) {
141
+ input.logger.warn(`style discovery: stylesheet ${href} answered ${res.status} — skipped.`);
142
+ return '';
143
+ }
144
+ return res.text();
145
+ });
146
+ return { hostWrappers: findContentWrapper(html), routeCss };
147
+ } finally {
148
+ child.kill('SIGTERM');
149
+ }
150
+ }
151
+
152
+ async function assembleCss(refs: CssRef[], loadHref: (href: string) => Promise<string>): Promise<string> {
153
+ const parts: string[] = [];
154
+ for (const ref of refs) {
155
+ if (ref.kind === 'inline') {
156
+ parts.push(ref.css);
157
+ continue;
158
+ }
159
+ const css = await loadHref(ref.href);
160
+ if (css) parts.push(css);
161
+ }
162
+ return parts.join('\n');
163
+ }
164
+
165
+ async function waitForServer(origin: string): Promise<void> {
166
+ // A design-time boot of the SSR entry; on a saturated CI runner the first
167
+ // answer took >15s while a full parallel gate ran beside it.
168
+ const deadline = Date.now() + 60_000;
169
+ while (Date.now() < deadline) {
170
+ try {
171
+ await fetch(origin, { method: 'HEAD' });
172
+ return;
173
+ } catch {
174
+ await new Promise((r) => setTimeout(r, 150));
175
+ }
176
+ }
177
+ throw new Error('server entry did not answer within 60s');
178
+ }
179
+
180
+ /** node:path join without importing path twice under bundling edge cases. */
181
+ function join2(base: string, rel: string): string {
182
+ return `${base.replace(/\/+$/, '')}/${rel}`;
183
+ }
@@ -0,0 +1,324 @@
1
+ import { PACKAGE_NAME } from '../constants.js';
2
+ import { resolveBuildRef, resolveRepositoryUri } from '../git.js';
3
+ import { messageOf } from '../message-of.js';
4
+ import { resolveBuildSiteId } from '../site-id.js';
5
+ import { ENDPOINT_ENV_VAR, INTEGRATION_NOT_CALLED, suppliedBuildToken, suppliedEndpoint } from './checks-offline.js';
6
+ import { type ConfigScan, optionLiteral } from './config-scan.js';
7
+ import {
8
+ type CheckId,
9
+ type CheckOutcome,
10
+ type CloudDoctorContext,
11
+ type DoctorDeps,
12
+ outcomeOf,
13
+ skipped,
14
+ } from './types.js';
15
+
16
+ const LIVE_CHECK_IDS: readonly CheckId[] = ['CC5', 'CC6', 'CC7'];
17
+
18
+ /** Every doctor request is bounded: a hanging host must never hang `conloca doctor` (the CLI seam has no timer of its own). */
19
+ const REQUEST_TIMEOUT_MS = 10_000;
20
+
21
+ /** Version strings come from whatever build registered; only a value shaped like a version reaches the terminal. */
22
+ const VERSION_SHAPE = /^[0-9A-Za-z.+-]{1,64}$/;
23
+
24
+ function builtWithNote(value: string | null | undefined): string {
25
+ return typeof value === 'string' && VERSION_SHAPE.test(value) ? ` (built with ${PACKAGE_NAME} ${value})` : '';
26
+ }
27
+
28
+ /** One row of the endpoint's status route (`GET /api/v1/registrations/status`). */
29
+ interface StatusRegistration {
30
+ /**
31
+ * Absent on the wire for active rows; true for an older row with no site id yet, which becomes active the next
32
+ * time the editor opens.
33
+ */
34
+ parked?: boolean;
35
+ branch: string;
36
+ siteId: string | null;
37
+ gitSha: string;
38
+ registeredAt: number;
39
+ editorBundleUrl: string;
40
+ /** Absent when the endpoint predates the field; null when the build that registered sent none. */
41
+ clientVersion?: string | null;
42
+ }
43
+
44
+ interface StatusResponse {
45
+ defaultBranch: string | null;
46
+ registrations: StatusRegistration[];
47
+ }
48
+
49
+ interface LiveInput {
50
+ context: CloudDoctorContext;
51
+ deps: DoctorDeps;
52
+ scan: ConfigScan;
53
+ /** CC2's verdict: the token once it parses; undefined when missing or malformed. */
54
+ token: string | undefined;
55
+ /** CC3's verdict: the endpoint once it parses as a URL. */
56
+ endpoint: string | undefined;
57
+ }
58
+
59
+ const skipAll = (reason: string): CheckOutcome[] => LIVE_CHECK_IDS.map((id) => skipped(id, reason));
60
+
61
+ function isStatusRegistration(value: unknown): value is StatusRegistration {
62
+ if (typeof value !== 'object' || value === null) return false;
63
+ const row = value as Record<string, unknown>;
64
+ return (
65
+ typeof row.branch === 'string' &&
66
+ typeof row.gitSha === 'string' &&
67
+ typeof row.editorBundleUrl === 'string' &&
68
+ typeof row.registeredAt === 'number' &&
69
+ (row.siteId === null || typeof row.siteId === 'string') &&
70
+ (row.parked === undefined || typeof row.parked === 'boolean') &&
71
+ (row.clientVersion === undefined || row.clientVersion === null || typeof row.clientVersion === 'string')
72
+ );
73
+ }
74
+
75
+ /** Every field the checks read, so an endpoint drift fails CC5 loudly instead of surfacing as a broken CC6/CC7. */
76
+ function isStatusResponse(value: unknown): value is StatusResponse {
77
+ if (typeof value !== 'object' || value === null) return false;
78
+ const body = value as Record<string, unknown>;
79
+ return (
80
+ (body.defaultBranch === null || typeof body.defaultBranch === 'string') &&
81
+ Array.isArray(body.registrations) &&
82
+ body.registrations.every(isStatusRegistration)
83
+ );
84
+ }
85
+
86
+ type StatusProbe = { outcome: CheckOutcome } & ({ body: StatusResponse } | { skipReason: string });
87
+
88
+ interface StatusTarget {
89
+ token: string;
90
+ endpoint: string;
91
+ repoUri: string;
92
+ }
93
+
94
+ function statusFailed(outcome: CheckOutcome, message: string, skipReason: string): StatusProbe {
95
+ outcome.problems.push({ check: 'CC5', level: 'error', message });
96
+ return { outcome, skipReason };
97
+ }
98
+
99
+ /**
100
+ * CC5 — GET the status route with the token, joining the path exactly as the
101
+ * build does (register.ts) so --live reproduces the build's own request. 200
102
+ * and 401 both prove reachability; only 200 yields rows.
103
+ */
104
+ async function probeStatus(fetchFn: DoctorDeps['fetch'], target: StatusTarget): Promise<StatusProbe> {
105
+ const outcome = outcomeOf('CC5');
106
+ const url = `${target.endpoint}/api/v1/registrations/status?repoUri=${encodeURIComponent(target.repoUri)}`;
107
+ let response: Response;
108
+ try {
109
+ response = await fetchFn(url, {
110
+ headers: { authorization: `Bearer ${target.token}` },
111
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
112
+ });
113
+ } catch (error) {
114
+ return statusFailed(
115
+ outcome,
116
+ `endpoint ${target.endpoint} is unreachable (${messageOf(error)}) — check the endpoint option and network access from this machine`,
117
+ 'the endpoint is unreachable',
118
+ );
119
+ }
120
+ if (response.status === 401) {
121
+ return statusFailed(
122
+ outcome,
123
+ 'the build token is rejected by the endpoint — most likely rotated (a new token invalidates the old one); create a new token and update the CI secret — or the endpoint predates the registration status route, in which case update the endpoint first',
124
+ 'the endpoint rejected the build token',
125
+ );
126
+ }
127
+ if (response.status === 403) {
128
+ return statusFailed(
129
+ outcome,
130
+ `the token does not cover ${target.repoUri} — give the endpoint access to that repository or fix repoUri`,
131
+ 'the repository is not covered by the token',
132
+ );
133
+ }
134
+ if (!response.ok) {
135
+ return statusFailed(
136
+ outcome,
137
+ `endpoint answered HTTP ${response.status} for the registration status — the endpoint may predate this check; update it or retry`,
138
+ `the status route answered HTTP ${response.status}`,
139
+ );
140
+ }
141
+ let body: unknown;
142
+ try {
143
+ body = await response.json();
144
+ } catch {
145
+ return statusFailed(
146
+ outcome,
147
+ 'the endpoint answered 200 but not with JSON — does endpoint point at the site itself instead of the editor endpoint?',
148
+ 'the endpoint did not answer with JSON',
149
+ );
150
+ }
151
+ if (!isStatusResponse(body)) {
152
+ return statusFailed(
153
+ outcome,
154
+ 'the registration status response has an unexpected shape — update the endpoint or this package',
155
+ 'the status response was unreadable',
156
+ );
157
+ }
158
+ outcome.detail = `${target.endpoint} reachable — ${body.registrations.length} registration(s) for ${target.repoUri}`;
159
+ return { outcome, body };
160
+ }
161
+
162
+ /** CC6 — own row → probe; default-branch row → warn + probe; neither → error. Returns the row the editor would load. */
163
+ function diagnoseRegistrations(
164
+ body: StatusResponse,
165
+ branch: string | undefined,
166
+ siteId: string,
167
+ ): { outcome: CheckOutcome; row: StatusRegistration | undefined } {
168
+ const outcome = outcomeOf('CC6');
169
+ if (!branch) {
170
+ outcome.problems.push({
171
+ check: 'CC6',
172
+ level: 'warn',
173
+ message:
174
+ 'could not determine the current branch (detached HEAD?) — set CF_PAGES_BRANCH or GITHUB_REF_NAME, or check out a branch',
175
+ });
176
+ return { outcome, row: undefined };
177
+ }
178
+ // Newest first, whatever order the route returned: the editor loads the newest row.
179
+ const live = body.registrations.filter((row) => row.parked !== true).sort((a, b) => b.registeredAt - a.registeredAt);
180
+ // Activation is branch-scoped, so only rows parked for THIS branch say anything about it. They carry no siteId:
181
+ // the site stays undetermined until the editor's next open reads the branch's tree.
182
+ const parkedHere = body.registrations.filter((row) => row.parked === true && row.branch === branch);
183
+ // A branch without its own row is served by the default branch's row for that site — the editor's own lookup
184
+ // rule, which reads an empty default branch as none (the route relays the repository record as is).
185
+ const defaultBranch = body.defaultBranch === '' ? null : body.defaultBranch;
186
+ const inheritable = defaultBranch !== null && defaultBranch !== branch;
187
+ const own = live.find((row) => row.branch === branch && row.siteId === siteId);
188
+ const inherited =
189
+ own === undefined && inheritable
190
+ ? live.find((row) => row.branch === defaultBranch && row.siteId === siteId)
191
+ : undefined;
192
+ const details: string[] = [];
193
+ if (own) {
194
+ details.push(`site "${siteId}": own registration ${own.gitSha}${builtWithNote(own.clientVersion)}`);
195
+ } else if (inherited) {
196
+ outcome.problems.push({
197
+ check: 'CC6',
198
+ level: 'warn',
199
+ message: `site "${siteId}": no registration for branch ${branch} — the editor inherits the default branch's (${defaultBranch}) registration; it works, preview is degraded. Build ${branch} with the token to register it`,
200
+ });
201
+ } else if (parkedHere.length > 0) {
202
+ // The next editor open activates these rows, so the editor does load. It only fails when the branch has since
203
+ // grown a second site, which the doctor cannot foresee: resolveBuildSiteId answers with one id, never a count.
204
+ outcome.problems.push({
205
+ check: 'CC6',
206
+ level: 'warn',
207
+ message: `site "${siteId}": no active registration serves branch ${branch} — ${parkedHere.length} older registration(s) for it become active the next time the editor opens, unless this branch now declares more than one site (the editor answers 409 then). Build ${branch} with CONLOCA_BUILD_TOKEN set to replace them`,
208
+ });
209
+ } else {
210
+ const fallback = inheritable ? ` (nor the default branch ${defaultBranch})` : '';
211
+ outcome.problems.push({
212
+ check: 'CC6',
213
+ level: 'error',
214
+ message: `site "${siteId}": no registration serves branch ${branch}${fallback} — the editor will not load; build ${branch} with CONLOCA_BUILD_TOKEN set`,
215
+ });
216
+ }
217
+ // Only a footnote when something already serves the branch; the parked-only warning above carries the count itself.
218
+ if (parkedHere.length > 0 && (own ?? inherited)) {
219
+ details.push(
220
+ `${parkedHere.length} older registration(s) not active yet — they become active the next time the editor opens`,
221
+ );
222
+ }
223
+ if (details.length > 0) outcome.detail = details.join('; ');
224
+ return { outcome, row: own ?? inherited };
225
+ }
226
+
227
+ /** HEAD the URL; a host that refuses HEAD (405/501) gets a GET. */
228
+ async function reachable(
229
+ fetchFn: DoctorDeps['fetch'],
230
+ url: string,
231
+ ): Promise<{ ok: true } | { ok: false; answer: string }> {
232
+ try {
233
+ let response = await fetchFn(url, { method: 'HEAD', signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
234
+ if (response.status === 405 || response.status === 501) {
235
+ // A one-byte range keeps the probe from downloading the whole bundle; the 206 it earns is `ok`.
236
+ response = await fetchFn(url, {
237
+ method: 'GET',
238
+ headers: { range: 'bytes=0-0' },
239
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
240
+ });
241
+ }
242
+ return response.ok ? { ok: true } : { ok: false, answer: `HTTP ${response.status}` };
243
+ } catch (error) {
244
+ return { ok: false, answer: `unreachable (${messageOf(error)})` };
245
+ }
246
+ }
247
+
248
+ /** CC7 — the bundle a registration names must still be deployed: the row serving this branch needs its bytes. */
249
+ async function probeBundle(
250
+ siteId: string,
251
+ row: StatusRegistration | undefined,
252
+ localSha: string | undefined,
253
+ fetchFn: DoctorDeps['fetch'],
254
+ ): Promise<CheckOutcome> {
255
+ if (row === undefined) return skipped('CC7', 'no registration to probe');
256
+ const outcome = outcomeOf('CC7');
257
+ const result = await reachable(fetchFn, row.editorBundleUrl);
258
+ if (!result.ok) {
259
+ outcome.problems.push({
260
+ check: 'CC7',
261
+ level: 'error',
262
+ message: `site "${siteId}": the registration for ${row.branch} points at deleted editor assets — ${row.editorBundleUrl} answers ${result.answer} (a later deploy replaced them); rebuild and deploy from ${row.branch}`,
263
+ });
264
+ } else if (localSha && localSha !== row.gitSha) {
265
+ outcome.detail = `site "${siteId}": registered ${row.gitSha.slice(0, 7)}, local HEAD ${localSha.slice(0, 7)} — the editor at the endpoint lags this checkout`;
266
+ } else {
267
+ outcome.detail = `site "${siteId}": ${row.editorBundleUrl} reachable`;
268
+ }
269
+ return outcome;
270
+ }
271
+
272
+ /** CC5–CC7. Networks only under --live, and the token goes ONLY to the configured endpoint. */
273
+ export async function runLiveChecks(input: LiveInput): Promise<CheckOutcome[]> {
274
+ const { context, deps, scan, token, endpoint } = input;
275
+ if (!context.live) return skipAll('live checks run only with --live');
276
+ // The live trio diagnoses this integration: an unwired one is the reason, exactly as CC2/CC3 say.
277
+ if (scan.kind === 'read' && scan.config.conlocaCloud === 'absent') return skipAll(INTEGRATION_NOT_CALLED);
278
+ if (token === undefined) {
279
+ // CC2 already said why a supplied token is unusable; only a missing one gets the how-to here.
280
+ return skipAll(
281
+ suppliedBuildToken(scan, deps.env) === undefined
282
+ ? 'no build token — set CONLOCA_BUILD_TOKEN'
283
+ : 'no usable build token (see CC2)',
284
+ );
285
+ }
286
+ if (endpoint === undefined) {
287
+ // Likewise CC3 already said why a supplied endpoint is unusable.
288
+ return skipAll(
289
+ suppliedEndpoint(scan, deps.env) === undefined
290
+ ? `endpoint could not be determined — set ${ENDPOINT_ENV_VAR}`
291
+ : 'no usable endpoint (see CC3)',
292
+ );
293
+ }
294
+ // The doctor diagnoses the project it was handed, not whatever checkout the CLI happens to be standing in:
295
+ // `conloca doctor ./site` from a wrapper repo would otherwise read that repo's branch and call the site broken.
296
+ const git = (args: string[]) => deps.git(args, context.projectDir);
297
+ const repoUri = resolveRepositoryUri(optionLiteral(scan, 'repoUri'), deps.env, git);
298
+ if (repoUri === undefined) {
299
+ return skipAll(
300
+ 'repository identity could not be determined — build in a CI environment or Git checkout, or set repoUri',
301
+ );
302
+ }
303
+
304
+ const status = await probeStatus(deps.fetch, { token, endpoint, repoUri });
305
+ if (!('body' in status)) {
306
+ return [status.outcome, skipped('CC6', status.skipReason), skipped('CC7', status.skipReason)];
307
+ }
308
+
309
+ let siteId: string;
310
+ try {
311
+ siteId = resolveBuildSiteId({
312
+ contentRoot: context.contentRoot,
313
+ override: optionLiteral(scan, 'siteId'),
314
+ readFile: deps.readFile,
315
+ });
316
+ } catch (error) {
317
+ const outcome = outcomeOf('CC6');
318
+ outcome.problems.push({ check: 'CC6', level: 'error', message: messageOf(error) });
319
+ return [status.outcome, outcome, skipped('CC7', 'the site id could not be resolved')];
320
+ }
321
+ const ref = resolveBuildRef(deps.env, git);
322
+ const diagnosis = diagnoseRegistrations(status.body, ref.branch, siteId);
323
+ return [status.outcome, diagnosis.outcome, await probeBundle(siteId, diagnosis.row, ref.gitSha, deps.fetch)];
324
+ }