@conloca/cloud-astro 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +75 -24
  2. package/dist/.build-inputs.json +47 -29
  3. package/dist/src/component-manifest.d.ts +11 -0
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +20 -2
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +4 -4
  8. package/dist/src/constants.js +4 -4
  9. package/dist/src/d3-build.d.ts +6 -2
  10. package/dist/src/d3-build.d.ts.map +1 -1
  11. package/dist/src/d3-build.js +15 -11
  12. package/dist/src/d3-build.js.map +1 -1
  13. package/dist/src/d8-adapters.d.ts +10 -0
  14. package/dist/src/d8-adapters.d.ts.map +1 -0
  15. package/dist/src/d8-adapters.js +19 -0
  16. package/dist/src/d8-adapters.js.map +1 -0
  17. package/dist/src/d8-build.d.ts +99 -0
  18. package/dist/src/d8-build.d.ts.map +1 -0
  19. package/dist/src/d8-build.js +265 -0
  20. package/dist/src/d8-build.js.map +1 -0
  21. package/dist/src/d8-guards.d.ts +29 -0
  22. package/dist/src/d8-guards.d.ts.map +1 -0
  23. package/dist/src/d8-guards.js +145 -0
  24. package/dist/src/d8-guards.js.map +1 -0
  25. package/dist/src/d8-middleware.d.ts +7 -0
  26. package/dist/src/d8-middleware.d.ts.map +1 -0
  27. package/dist/src/d8-middleware.js +15 -0
  28. package/dist/src/d8-middleware.js.map +1 -0
  29. package/dist/src/d8-render.d.ts +9 -0
  30. package/dist/src/d8-render.d.ts.map +1 -0
  31. package/dist/src/d8-render.js +52 -0
  32. package/dist/src/d8-render.js.map +1 -0
  33. package/dist/src/descriptors.d.ts.map +1 -1
  34. package/dist/src/descriptors.js +6 -2
  35. package/dist/src/descriptors.js.map +1 -1
  36. package/dist/src/doctor/ancestor-chain.d.ts +14 -0
  37. package/dist/src/doctor/ancestor-chain.d.ts.map +1 -0
  38. package/dist/src/doctor/ancestor-chain.js +57 -0
  39. package/dist/src/doctor/ancestor-chain.js.map +1 -0
  40. package/dist/src/doctor/checks-d8.d.ts +7 -0
  41. package/dist/src/doctor/checks-d8.d.ts.map +1 -0
  42. package/dist/src/doctor/checks-d8.js +240 -0
  43. package/dist/src/doctor/checks-d8.js.map +1 -0
  44. package/dist/src/doctor/checks-frames.d.ts +5 -0
  45. package/dist/src/doctor/checks-frames.d.ts.map +1 -0
  46. package/dist/src/doctor/checks-frames.js +78 -0
  47. package/dist/src/doctor/checks-frames.js.map +1 -0
  48. package/dist/src/doctor/checks-live.d.ts +5 -14
  49. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  50. package/dist/src/doctor/checks-live.js +9 -21
  51. package/dist/src/doctor/checks-live.js.map +1 -1
  52. package/dist/src/doctor/checks-offline.d.ts +2 -0
  53. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  54. package/dist/src/doctor/checks-offline.js +17 -8
  55. package/dist/src/doctor/checks-offline.js.map +1 -1
  56. package/dist/src/doctor/checks-preview-live.d.ts +7 -2
  57. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -1
  58. package/dist/src/doctor/checks-preview-live.js +107 -7
  59. package/dist/src/doctor/checks-preview-live.js.map +1 -1
  60. package/dist/src/doctor/checks-preview.d.ts.map +1 -1
  61. package/dist/src/doctor/checks-preview.js +9 -4
  62. package/dist/src/doctor/checks-preview.js.map +1 -1
  63. package/dist/src/doctor/config-scan.d.ts +24 -6
  64. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  65. package/dist/src/doctor/config-scan.js +89 -18
  66. package/dist/src/doctor/config-scan.js.map +1 -1
  67. package/dist/src/doctor/request.d.ts +14 -0
  68. package/dist/src/doctor/request.d.ts.map +1 -0
  69. package/dist/src/doctor/request.js +17 -0
  70. package/dist/src/doctor/request.js.map +1 -0
  71. package/dist/src/doctor/run.d.ts.map +1 -1
  72. package/dist/src/doctor/run.js +2 -0
  73. package/dist/src/doctor/run.js.map +1 -1
  74. package/dist/src/doctor/types.d.ts +8 -0
  75. package/dist/src/doctor/types.d.ts.map +1 -1
  76. package/dist/src/doctor/types.js +8 -0
  77. package/dist/src/doctor/types.js.map +1 -1
  78. package/dist/src/editor-page/bundle.d.ts +4 -0
  79. package/dist/src/editor-page/bundle.d.ts.map +1 -1
  80. package/dist/src/editor-page/bundle.js +55 -7
  81. package/dist/src/editor-page/bundle.js.map +1 -1
  82. package/dist/src/editor-page/data-schemas.d.ts +19 -5
  83. package/dist/src/editor-page/data-schemas.d.ts.map +1 -1
  84. package/dist/src/editor-page/data-schemas.js +17 -13
  85. package/dist/src/editor-page/data-schemas.js.map +1 -1
  86. package/dist/src/editor-page/emit.d.ts +7 -3
  87. package/dist/src/editor-page/emit.d.ts.map +1 -1
  88. package/dist/src/editor-page/emit.js +36 -19
  89. package/dist/src/editor-page/emit.js.map +1 -1
  90. package/dist/src/editor-page/frame-chains.d.ts +51 -0
  91. package/dist/src/editor-page/frame-chains.d.ts.map +1 -0
  92. package/dist/src/editor-page/frame-chains.js +121 -0
  93. package/dist/src/editor-page/frame-chains.js.map +1 -0
  94. package/dist/src/editor-page/page.d.ts +1 -3
  95. package/dist/src/editor-page/page.d.ts.map +1 -1
  96. package/dist/src/editor-page/page.js +3 -5
  97. package/dist/src/editor-page/page.js.map +1 -1
  98. package/dist/src/integration.d.ts.map +1 -1
  99. package/dist/src/integration.js +231 -124
  100. package/dist/src/integration.js.map +1 -1
  101. package/dist/src/node.d.ts +2 -0
  102. package/dist/src/node.d.ts.map +1 -1
  103. package/dist/src/node.js +4 -0
  104. package/dist/src/node.js.map +1 -1
  105. package/dist/src/preview/_resolve-opts.d.ts +26 -1
  106. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  107. package/dist/src/preview/_resolve-opts.js.map +1 -1
  108. package/dist/src/preview/banner.d.ts +3 -2
  109. package/dist/src/preview/banner.d.ts.map +1 -1
  110. package/dist/src/preview/banner.js +15 -6
  111. package/dist/src/preview/banner.js.map +1 -1
  112. package/dist/src/preview/content-api.d.ts +23 -1
  113. package/dist/src/preview/content-api.d.ts.map +1 -1
  114. package/dist/src/preview/content-api.js +73 -7
  115. package/dist/src/preview/content-api.js.map +1 -1
  116. package/dist/src/preview/d8-middleware.d.ts +25 -0
  117. package/dist/src/preview/d8-middleware.d.ts.map +1 -0
  118. package/dist/src/preview/d8-middleware.js +94 -0
  119. package/dist/src/preview/d8-middleware.js.map +1 -0
  120. package/dist/src/preview/dispatcher.d.ts +3 -16
  121. package/dist/src/preview/dispatcher.d.ts.map +1 -1
  122. package/dist/src/preview/dispatcher.js +54 -136
  123. package/dist/src/preview/dispatcher.js.map +1 -1
  124. package/dist/src/preview/headers.d.ts +3 -0
  125. package/dist/src/preview/headers.d.ts.map +1 -1
  126. package/dist/src/preview/headers.js +10 -1
  127. package/dist/src/preview/headers.js.map +1 -1
  128. package/dist/src/preview/links.d.ts +23 -0
  129. package/dist/src/preview/links.d.ts.map +1 -0
  130. package/dist/src/preview/links.js +168 -0
  131. package/dist/src/preview/links.js.map +1 -0
  132. package/dist/src/preview/middleware.d.ts +9 -3
  133. package/dist/src/preview/middleware.d.ts.map +1 -1
  134. package/dist/src/preview/middleware.js +36 -16
  135. package/dist/src/preview/middleware.js.map +1 -1
  136. package/dist/src/preview/prefix-router.d.ts +67 -0
  137. package/dist/src/preview/prefix-router.d.ts.map +1 -0
  138. package/dist/src/preview/prefix-router.js +153 -0
  139. package/dist/src/preview/prefix-router.js.map +1 -0
  140. package/dist/src/preview/preview-path.d.ts +8 -3
  141. package/dist/src/preview/preview-path.d.ts.map +1 -1
  142. package/dist/src/preview/preview-path.js +16 -4
  143. package/dist/src/preview/preview-path.js.map +1 -1
  144. package/dist/src/preview/site-middleware.d.ts +8 -2
  145. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  146. package/dist/src/preview/site-middleware.js +95 -31
  147. package/dist/src/preview/site-middleware.js.map +1 -1
  148. package/dist/src/preview/site-page-sources.d.ts +21 -0
  149. package/dist/src/preview/site-page-sources.d.ts.map +1 -0
  150. package/dist/src/preview/site-page-sources.js +129 -0
  151. package/dist/src/preview/site-page-sources.js.map +1 -0
  152. package/dist/src/preview/site-pages.d.ts +18 -0
  153. package/dist/src/preview/site-pages.d.ts.map +1 -0
  154. package/dist/src/preview/site-pages.js +7 -0
  155. package/dist/src/preview/site-pages.js.map +1 -0
  156. package/dist/src/preview/unready-pages.d.ts +21 -0
  157. package/dist/src/preview/unready-pages.d.ts.map +1 -0
  158. package/dist/src/preview/unready-pages.js +54 -0
  159. package/dist/src/preview/unready-pages.js.map +1 -0
  160. package/dist/src/preview-build.d.ts +17 -16
  161. package/dist/src/preview-build.d.ts.map +1 -1
  162. package/dist/src/preview-build.js +37 -40
  163. package/dist/src/preview-build.js.map +1 -1
  164. package/dist/src/preview-image-endpoint.d.ts +8 -0
  165. package/dist/src/preview-image-endpoint.d.ts.map +1 -0
  166. package/dist/src/preview-image-endpoint.js +34 -0
  167. package/dist/src/preview-image-endpoint.js.map +1 -0
  168. package/dist/src/preview-render-seams.d.ts +7 -0
  169. package/dist/src/preview-render-seams.d.ts.map +1 -0
  170. package/dist/src/preview-render-seams.js +27 -0
  171. package/dist/src/preview-render-seams.js.map +1 -0
  172. package/dist/src/site-middleware.d.ts +2 -4
  173. package/dist/src/site-middleware.d.ts.map +1 -1
  174. package/dist/src/site-middleware.js +6 -22
  175. package/dist/src/site-middleware.js.map +1 -1
  176. package/dist/src/types.d.ts +15 -16
  177. package/dist/src/types.d.ts.map +1 -1
  178. package/package.json +138 -6
  179. package/src/component-manifest.ts +30 -4
  180. package/src/constants.ts +4 -4
  181. package/src/d3-build.ts +20 -14
  182. package/src/d8-adapters.ts +19 -0
  183. package/src/d8-build.ts +356 -0
  184. package/src/d8-guards.ts +177 -0
  185. package/src/d8-middleware.ts +17 -0
  186. package/src/d8-render.ts +61 -0
  187. package/src/descriptors.ts +6 -2
  188. package/src/doctor/ancestor-chain.ts +58 -0
  189. package/src/doctor/checks-d8.ts +256 -0
  190. package/src/doctor/checks-frames.ts +84 -0
  191. package/src/doctor/checks-live.ts +10 -39
  192. package/src/doctor/checks-offline.ts +21 -8
  193. package/src/doctor/checks-preview-live.ts +114 -8
  194. package/src/doctor/checks-preview.ts +9 -4
  195. package/src/doctor/config-scan.ts +86 -15
  196. package/src/doctor/request.ts +27 -0
  197. package/src/doctor/run.ts +2 -0
  198. package/src/doctor/types.ts +9 -0
  199. package/src/editor-page/bundle.ts +65 -7
  200. package/src/editor-page/data-schemas.ts +30 -16
  201. package/src/editor-page/emit.ts +52 -24
  202. package/src/editor-page/frame-chains.ts +143 -0
  203. package/src/editor-page/page.ts +3 -4
  204. package/src/integration.ts +277 -135
  205. package/src/node.ts +4 -0
  206. package/src/preview/_resolve-opts.ts +17 -1
  207. package/src/preview/banner.ts +17 -4
  208. package/src/preview/content-api.ts +78 -6
  209. package/src/preview/d8-middleware.ts +124 -0
  210. package/src/preview/dispatcher.ts +63 -153
  211. package/src/preview/headers.ts +10 -1
  212. package/src/preview/links.ts +175 -0
  213. package/src/preview/middleware.ts +41 -19
  214. package/src/preview/prefix-router.ts +197 -0
  215. package/src/preview/preview-path.ts +24 -6
  216. package/src/preview/site-middleware.ts +114 -38
  217. package/src/preview/site-page-sources.ts +146 -0
  218. package/src/preview/site-pages.ts +22 -0
  219. package/src/preview/unready-pages.ts +65 -0
  220. package/src/preview-build.ts +43 -42
  221. package/src/preview-image-endpoint.ts +35 -0
  222. package/src/preview-render-seams.ts +31 -0
  223. package/src/site-middleware.ts +6 -24
  224. package/src/skill/SKILL.md +25 -2
  225. package/src/types.ts +15 -16
  226. package/src/virtual-modules.d.ts +17 -2
@@ -3,6 +3,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { endpointReaderOptions, type PuckManifest, readPuckConfig } from '@conloca/astro-cms/puck-manifest';
5
5
  import { COMPONENT_MANIFEST_LIMITS, measureJson } from '@conloca/content-api/component-vocabulary';
6
+ import type { UserConfig } from 'vite';
6
7
 
7
8
  /** The emitted manifest: its site-relative URL, its file name and the full sha-256 hex of its bytes. */
8
9
  export interface ComponentManifestArtifact {
@@ -33,13 +34,31 @@ export async function emitComponentManifest(input: {
33
34
  folder?: string;
34
35
  puckConfigPath: string;
35
36
  projectRoot: string;
37
+ vite: UserConfig;
38
+ /** The fragment components render module (conlocaCMS `fragmentComponentsPath`). */
39
+ fragmentComponentsPath?: string;
40
+ /** The loaded schemas module; absent when the site sets no `schemasPath`. */
41
+ schemas?: { mdxComponents: unknown } | { error: string };
42
+ discoveredMdxComponents?: readonly unknown[];
36
43
  logger: Logger;
37
44
  }): Promise<ComponentManifestArtifact | undefined> {
38
45
  const folder = input.folder ?? '_conloca';
39
46
  try {
40
- const manifest = readPuckConfig(
41
- endpointReaderOptions({ puckConfigPath: input.puckConfigPath, projectRoot: input.projectRoot }),
42
- );
47
+ // Imported here so loading the config does not pay for the page renderer.
48
+ const { readFragmentManifest } = await import('@conloca/astro-cms/fragment-manifest');
49
+ const fragments = await readFragmentManifest({
50
+ root: input.projectRoot,
51
+ vite: input.vite,
52
+ ...(input.fragmentComponentsPath ? { fragmentComponentsPath: input.fragmentComponentsPath } : {}),
53
+ schemas: input.schemas,
54
+ discovered: input.discoveredMdxComponents ?? [],
55
+ });
56
+ const manifest: PuckManifest = {
57
+ ...readPuckConfig(
58
+ endpointReaderOptions({ puckConfigPath: input.puckConfigPath, projectRoot: input.projectRoot }),
59
+ ),
60
+ fragments: fragments.manifest,
61
+ };
43
62
  const bytes = new TextEncoder().encode(JSON.stringify(manifest));
44
63
  if (bytes.byteLength > MAX_MANIFEST_BYTES) {
45
64
  input.logger.warn(
@@ -53,6 +72,7 @@ export async function emitComponentManifest(input: {
53
72
  await mkdir(join(input.dir, folder), { recursive: true });
54
73
  await writeFile(join(input.dir, folder, filename), bytes);
55
74
  reportManifest(manifest, `/${folder}/${filename}`, input.logger);
75
+ for (const warning of fragments.warnings) input.logger.warn(warning);
56
76
  return { url: `/${folder}/${filename}`, filename, hash };
57
77
  } catch (error) {
58
78
  input.logger.warn(
@@ -65,7 +85,13 @@ export async function emitComponentManifest(input: {
65
85
 
66
86
  /** One info line for the artifact, and a warning for everything the reader could not read. */
67
87
  function reportManifest(manifest: PuckManifest, url: string, logger: Logger): void {
68
- logger.info(`component manifest written: ${url} (${Object.keys(manifest.components).length} components)`);
88
+ const fragments = manifest.fragments;
89
+ logger.info(
90
+ `component manifest written: ${url} (${Object.keys(manifest.components).length} components, ${Object.keys(fragments?.components ?? {}).length} fragment components)`,
91
+ );
92
+ if (fragments?.unreadable) {
93
+ logger.warn(`fragment components are missing from the component manifest: ${fragments.unreadableReason}`);
94
+ }
69
95
  if (manifest.unreadable) {
70
96
  logger.warn(
71
97
  `component manifest is incomplete: ${manifest.unreadableReason ?? 'the config could not be fully read'}`,
package/src/constants.ts CHANGED
@@ -11,7 +11,7 @@ export const PACKAGE_NAME = '@conloca/cloud-astro';
11
11
  export const PREVIEW_BUILD_ENV_FLAG = 'CONLOCA_PREVIEW_BUILD';
12
12
 
13
13
  /**
14
- * Environment variable the site's build names the child's mode in (`d2` or `d3`). A build started with
14
+ * Environment variable the site's build names the child's mode in (`d3`). A build started with
15
15
  * {@link PREVIEW_BUILD_ENV_FLAG} alone, as a separate preview deploy runs it, has none: it is D4.
16
16
  */
17
17
  export const PREVIEW_MODE_ENV = 'CONLOCA_PREVIEW_MODE';
@@ -23,8 +23,8 @@ export const PREVIEW_MODE_ENV = 'CONLOCA_PREVIEW_MODE';
23
23
  export const PREVIEW_PRERENDERED_ENV = 'CONLOCA_PREVIEW_PRERENDERED';
24
24
 
25
25
  /**
26
- * Adapters the preview build is refused under: they write their deployable
27
- * output at the project root whatever `outDir` says, so the preview build
28
- * could replace the live site.
26
+ * Adapters the separate preview build (D4) is refused under: they write their
27
+ * deployable output at the project root whatever `outDir` says, so the
28
+ * preview build could replace the live site.
29
29
  */
30
30
  export const REFUSED_PREVIEW_ADAPTERS: readonly string[] = ['@astrojs/vercel', '@astrojs/netlify'];
package/src/d3-build.ts CHANGED
@@ -11,7 +11,8 @@ import { isRecord } from '@conloca/content-api/component-vocabulary';
11
11
  import { readSitesConfig } from '@conloca/content-api/node';
12
12
  import { PACKAGE_NAME } from './constants.js';
13
13
  import { parseWranglerConfig, wranglerConfigPath } from './preview/cloudflare-adapter.js';
14
- import type { DispatcherConfig, DispatcherExit } from './preview/dispatcher.js';
14
+ import type { DispatcherConfig } from './preview/dispatcher.js';
15
+ import type { PreviewExit } from './preview/prefix-router.js';
15
16
  import { previewOwnEntries, previewRoutePrefix } from './preview/preview-path.js';
16
17
 
17
18
  /** What the preview build tells the site's build: its pages, its on-demand routes and the exit values it baked. */
@@ -21,7 +22,7 @@ export interface PreviewRoutes {
21
22
  /** `run_worker_first` globs under the base. */
22
23
  onDemand: string[];
23
24
  /** What the dispatcher's exit route answers with. */
24
- exit: DispatcherExit;
25
+ exit: PreviewExit;
25
26
  }
26
27
 
27
28
  const ROUTES_FILE = 'routes.json';
@@ -57,11 +58,25 @@ export async function writePreviewRoutes(previewOut: string, routes: PreviewRout
57
58
  await writeFile(join(previewOut, ROUTES_FILE), `${JSON.stringify(routes, null, 2)}\n`);
58
59
  }
59
60
 
61
+ /** `.conloca/dispatcher/run_worker_first.json`: the entries `conloca connect` writes into wrangler.jsonc. */
62
+ export async function writeWorkerFirst(root: string, entries: readonly string[]): Promise<void> {
63
+ const outDir = join(root, '.conloca', 'dispatcher');
64
+ await mkdir(outDir, { recursive: true });
65
+ await writeFile(join(outDir, 'run_worker_first.json'), `${JSON.stringify(entries, null, 2)}\n`);
66
+ }
67
+
68
+ /** Every host sites.json declares: links to them are links to this site. */
69
+ export async function declaredDomains(contentRoot: string | undefined): Promise<string[]> {
70
+ if (!contentRoot) return [];
71
+ const { sites } = await readSitesConfig(contentRoot);
72
+ return [...new Set(Object.values(sites).flatMap((site) => Object.values(site.domains ?? {})))];
73
+ }
74
+
60
75
  function isStrings(value: unknown): value is string[] {
61
76
  return Array.isArray(value) && value.every((item) => typeof item === 'string');
62
77
  }
63
78
 
64
- function isExit(value: unknown): value is DispatcherExit {
79
+ function isExit(value: unknown): value is PreviewExit {
65
80
  return (
66
81
  isRecord(value) &&
67
82
  typeof value.repo === 'string' &&
@@ -206,14 +221,6 @@ export function dispatcherModule(serverEntry: string | null): string {
206
221
  ].join('\n');
207
222
  }
208
223
 
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
224
  /** A plain `wrangler deploy` follows `.wrangler/deploy/config.json`; one the preview build left would ship it as the site. */
218
225
  async function dropDeployRedirect(root: string, previewOut: string, logger: { info(message: string): void }) {
219
226
  const redirect = join(root, '.wrangler', 'deploy', 'config.json');
@@ -261,9 +268,8 @@ export async function finishD3Build(input: FinishD3Input): Promise<void> {
261
268
  await dropDeployRedirect(root, previewOut, logger);
262
269
 
263
270
  const outDir = join(root, '.conloca', 'dispatcher');
264
- await mkdir(outDir, { recursive: true });
265
271
  const expected = [prefix, `${prefix}/*`, ...(serving && routes !== undefined ? routes.onDemand : [])];
266
- await writeFile(join(outDir, 'run_worker_first.json'), `${JSON.stringify(expected, null, 2)}\n`);
272
+ await writeWorkerFirst(root, expected);
267
273
 
268
274
  const configPath = wranglerConfigPath(root);
269
275
  const config = configPath === undefined ? undefined : parseWranglerConfig(await readFile(configPath, 'utf8'));
@@ -303,7 +309,7 @@ export async function finishD3Build(input: FinishD3Input): Promise<void> {
303
309
  base,
304
310
  endpoint: input.endpoint,
305
311
  prerendered: serving && routes !== undefined ? routes.prerendered : [],
306
- domains: await declaredDomains(),
312
+ domains: await declaredDomains(process.env.CONLOCA_CONTENT_ROOT),
307
313
  exit: serving && routes !== undefined ? routes.exit : null,
308
314
  };
309
315
  await writeFile(join(outDir, 'dispatcher.json'), `${JSON.stringify(dispatcher, null, 2)}\n`);
@@ -0,0 +1,19 @@
1
+ /** The adapter releases draft preview is tested with; `conloca connect` installs exactly these (a test keeps them equal). */
2
+ export const D8_TESTED_ADAPTERS = {
3
+ '@astrojs/vercel': '11.0.18',
4
+ '@astrojs/netlify': '8.2.11',
5
+ '@astrojs/cloudflare': '14.3.2',
6
+ '@astrojs/node': '11.1.9',
7
+ } as const;
8
+
9
+ /** The host rate-limit rule for the preview route under `prefix`, as connect prints it and doctor names it. */
10
+ export function d8RateLimitLines(adapter: string, prefix: string): string[] {
11
+ if (adapter === '@astrojs/vercel') {
12
+ return [
13
+ `Firewall → Add rule → If Request Path starts with ${prefix}/ → Rate Limit, 60 requests per 10 seconds per IP → Deny`,
14
+ ];
15
+ }
16
+ if (adapter === '@astrojs/netlify')
17
+ return [`Rate limiting rule: path ${prefix}/*, 60 requests per 60 seconds per IP`];
18
+ return [];
19
+ }
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The site's build serving d8: the draft preview renders inside the site's own build, at the preview route, with
3
+ * the values every pass is checked against baked in. Also what every preview build bakes.
4
+ */
5
+
6
+ import { existsSync, readdirSync } from 'node:fs';
7
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
8
+ import { createRequire } from 'node:module';
9
+ import { basename, dirname, join, relative, sep } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { isDeepStrictEqual } from 'node:util';
12
+ import { mediaRefPath } from '@conloca/content-api';
13
+ import { isRecord } from '@conloca/content-api/component-vocabulary';
14
+ import { DEFAULT_EDITOR_ENDPOINT } from '@conloca/content-api/editor-host';
15
+ import type { AstroConfig, IntegrationResolvedRoute } from 'astro';
16
+ import { PACKAGE_NAME } from './constants.js';
17
+ import { declaredDomains, deployProblems, onDemandPatterns } from './d3-build.js';
18
+ import { mediaFromBuild } from './editor-page/emit.js';
19
+ import { gitOutput, resolveBuildRef } from './git.js';
20
+ import type { BakedPreviewOpts, BakedSitePages } from './preview/_resolve-opts.js';
21
+ import { normalizeTrailingSlash } from './preview/preview-path.js';
22
+ import { resolveBuildSiteId } from './site-id.js';
23
+ import type { ConlocaCloudOptions } from './types.js';
24
+
25
+ /**
26
+ * astro-cms's second copy of its page handler, as the site resolves it: a route injected at it is a route of its own,
27
+ * where one at the published handler's file would be taken for that route.
28
+ */
29
+ export function previewPageHandlerPath(root: URL): string {
30
+ const manifest = createRequire(new URL('package.json', root)).resolve('@conloca/astro-cms/package.json');
31
+ const path = join(dirname(manifest), 'dist', 'internal', 'preview-page-handler.astro');
32
+ if (!existsSync(path)) {
33
+ throw new Error(`@conloca/astro-cms is too old for draft preview on this site (no ${path}); upgrade it`);
34
+ }
35
+ return path;
36
+ }
37
+
38
+ export interface BakeInput {
39
+ options: ConlocaCloudOptions;
40
+ config: Pick<AstroConfig, 'root' | 'base'>;
41
+ repoUri: string | undefined;
42
+ env: NodeJS.ProcessEnv;
43
+ }
44
+
45
+ /**
46
+ * What every preview build bakes into its artifact, so a correctly built preview needs NO env vars on the
47
+ * deployment: the endpoint and audience are integration options; repository, site, branch, base and commit are what
48
+ * this build was made from, and every pass must match the first three. `saasIssuer` stays unbaked unless configured:
49
+ * it is a property of the endpoint, not of the site. Throws without a repository or a branch.
50
+ */
51
+ export function bakedIdentity({
52
+ options,
53
+ config,
54
+ repoUri,
55
+ env,
56
+ }: BakeInput): BakedPreviewOpts & { repo: string; siteId: string; branch: string } {
57
+ if (!repoUri) {
58
+ throw new Error(
59
+ `${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
60
+ '(build in a Git checkout or set repoUri as an advanced override)',
61
+ );
62
+ }
63
+ // The project's own checkout answers git, not the directory the build was started from.
64
+ const projectGit = (args: string[]) => gitOutput(args, fileURLToPath(config.root));
65
+ const buildRef = resolveBuildRef(env, projectGit);
66
+ if (!buildRef.branch) {
67
+ throw new Error(
68
+ `${PACKAGE_NAME}: could not determine the branch the preview build serves (set CF_PAGES_BRANCH, ` +
69
+ 'WORKERS_CI_BRANCH, VERCEL_GIT_COMMIT_REF or GITHUB_REF_NAME, or build in a git checkout on a branch)',
70
+ );
71
+ }
72
+ const siteId = resolveBuildSiteId({ contentRoot: env.CONLOCA_CONTENT_ROOT, override: options.siteId });
73
+ // The commit this build's checkout holds: a PR build may check out a merge commit rather than the commit CI hands
74
+ // over. Page-status compares the branch's latest commit with it, so the endpoint diffs against the content actually
75
+ // serving; a checkout commit the endpoint does not have makes it render from the branch instead.
76
+ const buildCommit = projectGit(['rev-parse', 'HEAD']) ?? buildRef.gitSha;
77
+ return {
78
+ saasEndpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
79
+ // The token's `aud` is the repo URI this build resolved.
80
+ saasAudience: repoUri,
81
+ ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
82
+ ...(buildCommit ? { buildCommit } : {}),
83
+ repo: repoUri,
84
+ siteId,
85
+ branch: buildRef.branch,
86
+ base: config.base ?? '/',
87
+ };
88
+ }
89
+
90
+ /** What a d8 site build bakes: the identity, plus the routing values the draft render moves links with. */
91
+ export async function d8Baked(
92
+ input: BakeInput & {
93
+ config: Pick<AstroConfig, 'root' | 'base' | 'trailingSlash' | 'site'> &
94
+ SitePagesConfig & {
95
+ build: Pick<AstroConfig['build'], 'format'>;
96
+ };
97
+ },
98
+ ): Promise<BakedPreviewOpts> {
99
+ return {
100
+ ...bakedIdentity(input),
101
+ mode: 'd8',
102
+ domains: await declaredDomains(input.env.CONLOCA_CONTENT_ROOT),
103
+ trailingSlash: input.config.trailingSlash,
104
+ buildFormat: input.config.build.format,
105
+ sitePages: bakedSitePages(input.config, input.env),
106
+ };
107
+ }
108
+
109
+ /**
110
+ * The media folder's link base, from the source conloca.json's `media` uses, and the images in it this build deploys
111
+ * (relative to it): a draft link to any other image is a file committed on the branch, served by the media route.
112
+ * A branch file with a deployed file's name shows the deployed bytes. Symlinked subfolders are not followed. Unbaked
113
+ * (no git repository, an unreadable folder), draft addresses still move; branch-committed images do not.
114
+ * Throws when the folder can't be read.
115
+ */
116
+ export function bakedMedia(
117
+ channel: { assetsPath?: string; assetRefBase?: string } | undefined,
118
+ root: URL,
119
+ ): BakedPreviewOpts['media'] {
120
+ const media = mediaFromBuild(channel, gitOutput(['rev-parse', '--show-toplevel'], fileURLToPath(root)));
121
+ if (media === undefined || channel?.assetsPath === undefined) return undefined;
122
+ // An empty base is the whole `public/`: the rewrite moves only draft addresses there, so nothing is listed.
123
+ if (media.refBase === '') return { refBase: '', deployed: [] };
124
+ const { assetsPath } = channel;
125
+ const entries = existsSync(assetsPath) ? readdirSync(assetsPath, { recursive: true, withFileTypes: true }) : [];
126
+ const deployed = entries
127
+ .filter((entry) => entry.isFile())
128
+ .map((entry) => relative(assetsPath, join(entry.parentPath, entry.name)).split(sep).join('/'))
129
+ .filter((file) => mediaRefPath(`${media.refBase}/${file}`, media.refBase) !== undefined);
130
+ // oxlint-disable-next-line unicorn/no-array-sort -- the target lib predates toSorted; this sorts its own array.
131
+ return { refBase: media.refBase, deployed: deployed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) };
132
+ }
133
+
134
+ /** Only builds that render drafts from this build's own files bake its media list. */
135
+ export function bakesMedia(mode: string | undefined): boolean {
136
+ return mode === 'd8' || mode === 'd3';
137
+ }
138
+
139
+ type SitePagesConfig = Pick<AstroConfig, 'site'> & {
140
+ adapter?: { name: string };
141
+ build: Pick<AstroConfig['build'], 'serverEntry'>;
142
+ };
143
+
144
+ function bakedSitePages(config: SitePagesConfig, env: NodeJS.ProcessEnv): BakedSitePages {
145
+ const { serverEntry } = config.build;
146
+ switch (config.adapter?.name) {
147
+ case '@astrojs/node':
148
+ return { kind: 'disk', serverEntry };
149
+ case '@astrojs/cloudflare':
150
+ return { kind: 'assets' };
151
+ case '@astrojs/vercel':
152
+ case '@astrojs/netlify': {
153
+ // Only a production deploy's `site` serves this build's pages; a branch deploy's pages live elsewhere.
154
+ const production = env.VERCEL_ENV === 'production' || env.CONTEXT === 'production';
155
+ const origin = production && config.site ? config.site.replace(/\/+$/u, '') : null;
156
+ return { kind: 'function', serverEntry, origin };
157
+ }
158
+ default:
159
+ return { kind: 'none' };
160
+ }
161
+ }
162
+
163
+ // astro-cms's published page handler: the CMS route, whose pages render drafts rather than published bytes.
164
+ const CMS_PAGE_HANDLER = '/internal/page-handler.astro';
165
+
166
+ /** The site's own prerendered pages; `exact` holds those a site route's own output file names. */
167
+ export interface SitePagesList {
168
+ pages: string[];
169
+ exact: string[];
170
+ }
171
+
172
+ /**
173
+ * The pages the site prerendered itself, base included, in normalizeTrailingSlash form: every page `astro:build:done`
174
+ * reports but those the CMS route wrote. A page goes to the route whose output files hold it (`pages` names no route);
175
+ * that page is `exact`, since production serves the site route there by route priority. One no route's files hold
176
+ * goes to the first prerendered route that matches it (`routes` is in Astro's priority order), and is not exact.
177
+ */
178
+ export function sitePagesOf(
179
+ pages: readonly { pathname: string }[],
180
+ assets: ReadonlyMap<string, readonly URL[]>,
181
+ routes: readonly Pick<
182
+ IntegrationResolvedRoute,
183
+ 'pattern' | 'patternRegex' | 'entrypoint' | 'isPrerendered' | 'type'
184
+ >[],
185
+ dir: URL,
186
+ base: string,
187
+ ): SitePagesList {
188
+ const root = base.replace(/\/+$/u, '');
189
+ // Whether each page Astro lists files for is the CMS route's.
190
+ const ownedByCms = new Map(
191
+ routes.flatMap((route) =>
192
+ (assets.get(route.pattern) ?? []).map(
193
+ (file) =>
194
+ [
195
+ normalizeTrailingSlash(
196
+ `${root}/${decodeURI(file.pathname.slice(dir.pathname.length)).replace(/(?:^|\/)index\.html$|\.html$/u, '')}`,
197
+ ),
198
+ route.entrypoint.endsWith(CMS_PAGE_HANDLER),
199
+ ] as const,
200
+ ),
201
+ ),
202
+ );
203
+ // shortcut: the Cloudflare prerenderer leaves each route only its last file in `assets`, so most pages there fall to
204
+ // the first matching route, which lists a CMS page behind a site getStaticPaths route that does not generate it; such
205
+ // a page is not exact, and the preview middleware renders its draft when page-status is `changed`.
206
+ const list: SitePagesList = { pages: [], exact: [] };
207
+ for (const { pathname } of pages) {
208
+ const page = normalizeTrailingSlash(`${root}/${pathname}`);
209
+ const owned = ownedByCms.get(page);
210
+ const matched =
211
+ owned === undefined
212
+ ? routes.find(
213
+ (route) => route.type === 'page' && route.isPrerendered && route.patternRegex.test(`/${pathname}`),
214
+ )
215
+ : undefined;
216
+ if (owned ?? matched?.entrypoint.endsWith(CMS_PAGE_HANDLER)) continue;
217
+ list.pages.push(page);
218
+ // A route without parameters has one page, so matching it proves the file is that route's own.
219
+ if (owned === false || (matched !== undefined && !matched.pattern.includes('['))) list.exact.push(page);
220
+ }
221
+ return list;
222
+ }
223
+
224
+ /**
225
+ * Writes `site-pages.json` where the adapter's runtime reads it (`preview/site-page-sources.ts`), none of it needing
226
+ * `site`: beside the Node server entry; beside every copy of the server entry in the Vercel or Netlify function bundle
227
+ * (the adapter's build:done, which runs first, wrote it); in the Cloudflare client build's editor folder. Returns the
228
+ * files written; throws when the function bundle holds no server entry.
229
+ */
230
+ export async function writeSitePagesList(
231
+ adapterName: string,
232
+ config: Pick<AstroConfig, 'root'> & { build: Pick<AstroConfig['build'], 'server' | 'client' | 'serverEntry'> },
233
+ list: SitePagesList,
234
+ ): Promise<string[]> {
235
+ // Where Vercel and Netlify put the function they deploy, under the project root.
236
+ const functionRoot =
237
+ adapterName === '@astrojs/vercel'
238
+ ? '.vercel/output/functions/_render.func/'
239
+ : adapterName === '@astrojs/netlify'
240
+ ? '.netlify/v1/functions/ssr/'
241
+ : undefined;
242
+ let dirs: string[] = [];
243
+ if (adapterName === '@astrojs/node') dirs = [fileURLToPath(config.build.server)];
244
+ if (adapterName === '@astrojs/cloudflare') dirs = [join(fileURLToPath(config.build.client), '_conloca', 'editor')];
245
+ if (functionRoot !== undefined) {
246
+ const bundle = fileURLToPath(new URL(functionRoot, config.root));
247
+ const files = await readdir(bundle, { recursive: true }).catch((): string[] => []);
248
+ dirs = files
249
+ .filter((file) => basename(file) === config.build.serverEntry && !file.split(sep).includes('node_modules'))
250
+ .map((file) => join(bundle, dirname(file)));
251
+ if (dirs.length === 0)
252
+ throw new Error(`no ${config.build.serverEntry} in ${bundle} to write site-pages.json beside`);
253
+ }
254
+ const body = `${JSON.stringify(list)}\n`;
255
+ return Promise.all(
256
+ dirs.map(async (dir) => {
257
+ await mkdir(dir, { recursive: true });
258
+ await writeFile(join(dir, 'site-pages.json'), body);
259
+ return join(dir, 'site-pages.json');
260
+ }),
261
+ );
262
+ }
263
+
264
+ /** The endpoint d8 moves the image route to: Cloudflare's own passthrough there, Conloca's redirect elsewhere. */
265
+ export function d8ImageEndpoint(adapterName: string): string {
266
+ return adapterName === '@astrojs/cloudflare'
267
+ ? '@astrojs/cloudflare/image-passthrough-endpoint'
268
+ : '@conloca/cloud-astro/preview-image-endpoint';
269
+ }
270
+
271
+ const PAGE_FILE = /\.(?:astro|md|mdx|markdown|html|js|ts|mjs)$/u;
272
+ // Astro's own rule (astro core/routing/prerender.js).
273
+ const PRERENDER_FALSE = /^\s*export\s+const\s+prerender\s*=\s*false/mu;
274
+
275
+ /**
276
+ * Astro's own image services, Cloudflare's and Netlify's (whose URLs go to `/.netlify/images`): they serve `<Image>`
277
+ * URLs that do not depend on the endpoint route.
278
+ */
279
+ export function knownImageService(entrypoint: string | undefined): boolean {
280
+ // Unset is Astro's default (sharp).
281
+ return (
282
+ entrypoint === undefined ||
283
+ entrypoint.startsWith('astro/assets/services/') ||
284
+ entrypoint.startsWith('@astrojs/cloudflare/image-service') ||
285
+ entrypoint.startsWith('@astrojs/netlify/image-service')
286
+ );
287
+ }
288
+
289
+ /** Whether the site renders anything on demand, as far as astro.config and `src/pages` tell before routes exist. */
290
+ export async function hasOnDemandRoutes(config: Pick<AstroConfig, 'output' | 'srcDir'>): Promise<boolean> {
291
+ if (config.output === 'server') return true;
292
+ const pages = fileURLToPath(new URL('pages/', config.srcDir));
293
+ const files = await readdir(pages, { recursive: true }).catch((): string[] => []);
294
+ const sources = await Promise.all(
295
+ files
296
+ // Astro skips `_`-prefixed files and folders.
297
+ .filter((file) => PAGE_FILE.test(file) && !file.split(sep).some((part) => part.startsWith('_')))
298
+ .map((file) => readFile(join(pages, file), 'utf8').catch(() => '')),
299
+ );
300
+ return sources.some((source) => PRERENDER_FALSE.test(source));
301
+ }
302
+
303
+ /** Site on-demand routes other than ours and Astro's runtime routes (`/_image`, `/_server-islands/[name]`, default `/404`). */
304
+ export function siteOnDemand(routes: Parameters<typeof onDemandPatterns>[0], prefixPattern: string): string[] {
305
+ // onDemandPatterns already drops Astro's other internal routes, the default 404 among them.
306
+ return onDemandPatterns(routes).filter(
307
+ (pattern) =>
308
+ pattern !== prefixPattern &&
309
+ !pattern.startsWith(`${prefixPattern}/`) &&
310
+ pattern !== '/_image' &&
311
+ pattern !== '/_server-islands/[name]',
312
+ );
313
+ }
314
+
315
+ const VERCEL_STATIC_404 = { src: '^/.*$', dest: '/404.html', status: 404 };
316
+ // The function's `/404` under any base and trailing-slash setting: `^/404/?$`, `^/404$`, `^/docs/404/?$`.
317
+ const RENDERED_404 = /^\^(?:\/[^/^$]+)*\/404(?:\/\?)?\$$/u;
318
+
319
+ /** The rewritten Vercel config, or null to leave it (with the reason to warn). */
320
+ export function narrowVercelCatchAll(
321
+ config: unknown,
322
+ siteStaticWithoutPreview: boolean,
323
+ ): { config: unknown } | { leave: string } | null {
324
+ // An SSR site's misses reached its function before preview, too.
325
+ if (!siteStaticWithoutPreview) return null;
326
+ if (!isRecord(config) || !Array.isArray(config.routes)) return { leave: 'it has no routes list' };
327
+ const last: unknown = config.routes.at(-1);
328
+ // A prerendered 404.astro: the adapter already sends misses to it.
329
+ if (isDeepStrictEqual(last, VERCEL_STATIC_404)) return null;
330
+ if (!isDeepStrictEqual(last, { src: '^/.*$', dest: '_render' })) {
331
+ return { leave: `its final route is not the adapter's catch-all: ${JSON.stringify(last)}` };
332
+ }
333
+ const kept = config.routes
334
+ .slice(0, -1)
335
+ .filter(
336
+ (route: unknown) =>
337
+ !(isRecord(route) && route.dest === '_render' && typeof route.src === 'string' && RENDERED_404.test(route.src)),
338
+ );
339
+ return { config: { ...config, routes: [...kept, VERCEL_STATIC_404] } };
340
+ }
341
+
342
+ /** Problems in the Cloudflare adapter's dist/server/wrangler.json for a d8 site, each with what it breaks and the edit (empty when fine). */
343
+ export function cloudflareD8Problems(wrangler: unknown, expected: readonly string[]): string[] {
344
+ const assets = isRecord(wrangler) && isRecord(wrangler.assets) ? wrangler.assets : {};
345
+ return [
346
+ ...deployProblems(wrangler, expected, false).map(
347
+ (problem) =>
348
+ `${problem}: drafts get a 404 (preview broken); add them to assets.run_worker_first in wrangler.jsonc`,
349
+ ),
350
+ ...(assets.not_found_handling === '404-page'
351
+ ? []
352
+ : [
353
+ 'wrangler.jsonc assets.not_found_handling is not "404-page": misses start the Cloudflare Worker; set assets.not_found_handling to "404-page" in wrangler.jsonc',
354
+ ]),
355
+ ];
356
+ }