@conloca/cloud-astro 0.2.2 → 0.2.3

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 (176) hide show
  1. package/README.md +261 -208
  2. package/dist/.build-inputs.json +60 -0
  3. package/dist/src/component-manifest.d.ts +5 -3
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +7 -7
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +5 -13
  8. package/dist/src/constants.d.ts.map +1 -1
  9. package/dist/src/constants.js +5 -13
  10. package/dist/src/constants.js.map +1 -1
  11. package/dist/src/descriptors.d.ts +2 -2
  12. package/dist/src/descriptors.d.ts.map +1 -1
  13. package/dist/src/doctor/checks-address.d.ts +18 -0
  14. package/dist/src/doctor/checks-address.d.ts.map +1 -0
  15. package/dist/src/doctor/checks-address.js +163 -0
  16. package/dist/src/doctor/checks-address.js.map +1 -0
  17. package/dist/src/doctor/checks-live.d.ts +8 -5
  18. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  19. package/dist/src/doctor/checks-live.js +220 -188
  20. package/dist/src/doctor/checks-live.js.map +1 -1
  21. package/dist/src/doctor/checks-offline.d.ts +8 -23
  22. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  23. package/dist/src/doctor/checks-offline.js +22 -239
  24. package/dist/src/doctor/checks-offline.js.map +1 -1
  25. package/dist/src/doctor/config-scan.d.ts +6 -3
  26. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  27. package/dist/src/doctor/config-scan.js +21 -11
  28. package/dist/src/doctor/config-scan.js.map +1 -1
  29. package/dist/src/doctor/run.d.ts.map +1 -1
  30. package/dist/src/doctor/run.js +12 -10
  31. package/dist/src/doctor/run.js.map +1 -1
  32. package/dist/src/doctor/types.d.ts +7 -7
  33. package/dist/src/doctor/types.d.ts.map +1 -1
  34. package/dist/src/doctor/types.js +7 -7
  35. package/dist/src/doctor/types.js.map +1 -1
  36. package/dist/src/editor-page/bundle.d.ts +88 -0
  37. package/dist/src/editor-page/bundle.d.ts.map +1 -0
  38. package/dist/src/editor-page/bundle.js +370 -0
  39. package/dist/src/editor-page/bundle.js.map +1 -0
  40. package/dist/src/editor-page/emit.d.ts +33 -0
  41. package/dist/src/editor-page/emit.d.ts.map +1 -0
  42. package/dist/src/editor-page/emit.js +183 -0
  43. package/dist/src/editor-page/emit.js.map +1 -0
  44. package/dist/src/editor-page/framing.d.ts +23 -0
  45. package/dist/src/editor-page/framing.d.ts.map +1 -0
  46. package/dist/src/editor-page/framing.js +39 -0
  47. package/dist/src/editor-page/framing.js.map +1 -0
  48. package/dist/src/editor-page/page.d.ts +9 -0
  49. package/dist/src/editor-page/page.d.ts.map +1 -0
  50. package/dist/src/editor-page/page.js +31 -0
  51. package/dist/src/editor-page/page.js.map +1 -0
  52. package/dist/src/editor-page/site-base.d.ts +4 -0
  53. package/dist/src/editor-page/site-base.d.ts.map +1 -0
  54. package/dist/src/editor-page/site-base.js +13 -0
  55. package/dist/src/editor-page/site-base.js.map +1 -0
  56. package/dist/src/git.d.ts +11 -8
  57. package/dist/src/git.d.ts.map +1 -1
  58. package/dist/src/git.js +25 -8
  59. package/dist/src/git.js.map +1 -1
  60. package/dist/src/index.d.ts +3 -1
  61. package/dist/src/index.d.ts.map +1 -1
  62. package/dist/src/index.js +9 -6
  63. package/dist/src/index.js.map +1 -1
  64. package/dist/src/integration.d.ts +1 -1
  65. package/dist/src/integration.d.ts.map +1 -1
  66. package/dist/src/integration.js +245 -408
  67. package/dist/src/integration.js.map +1 -1
  68. package/dist/src/node.d.ts +3 -1
  69. package/dist/src/node.d.ts.map +1 -1
  70. package/dist/src/node.js +7 -2
  71. package/dist/src/node.js.map +1 -1
  72. package/dist/src/preview/_resolve-opts.d.ts +16 -10
  73. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  74. package/dist/src/preview/_resolve-opts.js +21 -10
  75. package/dist/src/preview/_resolve-opts.js.map +1 -1
  76. package/dist/src/preview/banner.d.ts.map +1 -1
  77. package/dist/src/preview/banner.js +2 -4
  78. package/dist/src/preview/banner.js.map +1 -1
  79. package/dist/src/preview/cookie.d.ts +5 -2
  80. package/dist/src/preview/cookie.d.ts.map +1 -1
  81. package/dist/src/preview/cookie.js +5 -2
  82. package/dist/src/preview/cookie.js.map +1 -1
  83. package/dist/src/preview/label.d.ts +8 -0
  84. package/dist/src/preview/label.d.ts.map +1 -0
  85. package/dist/src/preview/label.js +14 -0
  86. package/dist/src/preview/label.js.map +1 -0
  87. package/dist/src/preview/landing.d.ts +2 -2
  88. package/dist/src/preview/landing.js +2 -2
  89. package/dist/src/preview/middleware.d.ts +25 -20
  90. package/dist/src/preview/middleware.d.ts.map +1 -1
  91. package/dist/src/preview/middleware.js +56 -51
  92. package/dist/src/preview/middleware.js.map +1 -1
  93. package/dist/src/preview/preview-path.d.ts +18 -5
  94. package/dist/src/preview/preview-path.d.ts.map +1 -1
  95. package/dist/src/preview/preview-path.js +24 -8
  96. package/dist/src/preview/preview-path.js.map +1 -1
  97. package/dist/src/preview/site-middleware.d.ts +5 -5
  98. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  99. package/dist/src/preview/site-middleware.js +16 -16
  100. package/dist/src/preview/site-middleware.js.map +1 -1
  101. package/dist/src/preview-build.d.ts +18 -15
  102. package/dist/src/preview-build.d.ts.map +1 -1
  103. package/dist/src/preview-build.js +36 -21
  104. package/dist/src/preview-build.js.map +1 -1
  105. package/dist/src/preview.d.ts +1 -1
  106. package/dist/src/preview.d.ts.map +1 -1
  107. package/dist/src/preview.js +1 -1
  108. package/dist/src/preview.js.map +1 -1
  109. package/dist/src/repository.d.ts +1 -1
  110. package/dist/src/repository.js +1 -1
  111. package/dist/src/resolve-options.d.ts +17 -0
  112. package/dist/src/resolve-options.d.ts.map +1 -0
  113. package/dist/src/resolve-options.js +21 -0
  114. package/dist/src/resolve-options.js.map +1 -0
  115. package/dist/src/site-id.d.ts +0 -2
  116. package/dist/src/site-id.d.ts.map +1 -1
  117. package/dist/src/site-id.js +2 -3
  118. package/dist/src/site-id.js.map +1 -1
  119. package/dist/src/types.d.ts +21 -69
  120. package/dist/src/types.d.ts.map +1 -1
  121. package/package.json +37 -13
  122. package/src/component-manifest.ts +11 -8
  123. package/src/constants.ts +5 -14
  124. package/src/descriptors.ts +2 -2
  125. package/src/doctor/checks-address.ts +190 -0
  126. package/src/doctor/checks-live.ts +256 -268
  127. package/src/doctor/checks-offline.ts +24 -262
  128. package/src/doctor/config-scan.ts +21 -9
  129. package/src/doctor/run.ts +14 -16
  130. package/src/doctor/types.ts +7 -7
  131. package/src/editor-page/bundle.ts +482 -0
  132. package/src/editor-page/emit.ts +246 -0
  133. package/src/editor-page/framing.ts +62 -0
  134. package/src/editor-page/page.ts +37 -0
  135. package/src/editor-page/site-base.ts +11 -0
  136. package/src/git.ts +29 -10
  137. package/src/index.ts +20 -6
  138. package/src/integration.ts +255 -461
  139. package/src/node.ts +18 -2
  140. package/src/preview/_resolve-opts.ts +29 -11
  141. package/src/preview/banner.ts +2 -4
  142. package/src/preview/cookie.ts +5 -2
  143. package/src/preview/label.ts +12 -0
  144. package/src/preview/landing.ts +2 -2
  145. package/src/preview/middleware.ts +77 -66
  146. package/src/preview/preview-path.ts +26 -8
  147. package/src/preview/site-middleware.ts +16 -21
  148. package/src/preview-build.ts +42 -26
  149. package/src/preview-handler.astro +10 -8
  150. package/src/preview.ts +0 -1
  151. package/src/repository.ts +1 -1
  152. package/src/resolve-options.ts +37 -0
  153. package/src/site-id.ts +2 -4
  154. package/src/skill/SKILL.md +51 -55
  155. package/src/types.ts +21 -70
  156. package/src/virtual-modules.d.ts +4 -1
  157. package/dist/src/build-commit.d.ts +0 -19
  158. package/dist/src/build-commit.d.ts.map +0 -1
  159. package/dist/src/build-commit.js +0 -6
  160. package/dist/src/build-commit.js.map +0 -1
  161. package/dist/src/bundle.d.ts +0 -181
  162. package/dist/src/bundle.d.ts.map +0 -1
  163. package/dist/src/bundle.js +0 -413
  164. package/dist/src/bundle.js.map +0 -1
  165. package/dist/src/discovery.d.ts +0 -58
  166. package/dist/src/discovery.d.ts.map +0 -1
  167. package/dist/src/discovery.js +0 -133
  168. package/dist/src/discovery.js.map +0 -1
  169. package/dist/src/register.d.ts +0 -98
  170. package/dist/src/register.d.ts.map +0 -1
  171. package/dist/src/register.js +0 -103
  172. package/dist/src/register.js.map +0 -1
  173. package/src/build-commit.ts +0 -22
  174. package/src/bundle.ts +0 -570
  175. package/src/discovery.ts +0 -183
  176. package/src/register.ts +0 -180
@@ -1,21 +1,16 @@
1
- import { existsSync } from 'node:fs';
2
1
  import { createRequire } from 'node:module';
3
2
  import { fileURLToPath } from 'node:url';
4
3
  import { readEditorDescriptors } from '@conloca/astro-cms/node';
5
- import type { AstroIntegration, AstroIntegrationLogger } from 'astro';
4
+ import { DEFAULT_EDITOR_ENDPOINT, editorUiOrigin } from '@conloca/content-api/editor-host';
5
+ import type { AstroIntegration } from 'astro';
6
6
  import type { UserConfig as ViteUserConfig } from 'vite';
7
- import { registrationCommits } from './build-commit.js';
8
- import type { BundledStylesheet, BundleEditorAssetsResult } from './bundle.js';
9
- import { bundleEditorAssets, emitRouteCssArtifact, mirrorEditorAssets } from './bundle.js';
10
- import { type ComponentManifestArtifact, emitComponentManifest } from './component-manifest.js';
11
- import { BUILD_TOKEN_ENV_VAR, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG, PREVIEW_SECRET_ENV_FLAG } from './constants.js';
12
- import { resolveEditorDescriptors } from './descriptors.js';
13
- import type { DiscoveredStyleContext } from './discovery.js';
14
- import { discoverStyleContext } from './discovery.js';
7
+ import { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './constants.js';
8
+ import { emitEditorPage, mirrorEditorPage } from './editor-page/emit.js';
15
9
  import { gitOutput, resolveBuildRef, resolveRepositoryUri } from './git.js';
16
- import { packageVersion } from './package-version.js';
17
- import { spawnPreviewBuild } from './preview-build.js';
18
- import { postRegistration } from './register.js';
10
+ import type { BakedPreviewOpts } from './preview/_resolve-opts.js';
11
+ import { PREVIEW_ROUTE_SEGMENT } from './preview/preview-path.js';
12
+ import { previewBuildMode, spawnPreviewBuild } from './preview-build.js';
13
+ import { type InheritedOptions, resolveInheritedOptions } from './resolve-options.js';
19
14
  import { resolveBuildSiteId } from './site-id.js';
20
15
  import { scaffoldSkill } from './skill.js';
21
16
  import type { ConlocaCloudOptions } from './types.js';
@@ -27,226 +22,233 @@ export { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG };
27
22
 
28
23
  /**
29
24
  * Returns the site's Astro integration that hooks into `astro:build:done`
30
- * to bundle editor assets, register the build at `endpoint`, and
31
- * (optionally) trigger a recursive preview build.
25
+ * to write the editor page and, when the site opts in, trigger a recursive
26
+ * preview build.
32
27
  *
33
28
  * The build:done pipeline:
34
29
  *
35
- * 1. esbuild the site's puck config into one browser ESM bundle under
36
- * `dist/_conloca/` with react/react-dom/jsx-runtime/puck externalized
37
- * (the editor supplies them at runtime), plus a `_headers` CORS
38
- * rule so the editor's origin can load it cross-origin. For a conlocaCMS
39
- * build it also writes the component manifest there (what each
40
- * component accepts, read from source) and registers its URL + hash
41
- * with the bundle.
42
- * 2. POST the registration (repo, git sha, branch, bundle URL + hash) to the
43
- * endpoint, authenticated by the build token. An ATTEMPTED
44
- * registration that is rejected FAILS THE BUILD — the error carries the
45
- * endpoint's exact status and body. Only a never-attempted registration (no
46
- * build token, repo identity, git sha/branch, or public base URL) skips,
47
- * ending the build with one summary block — or failing it when
48
- * `requireRegistration` is set.
49
- * 3. Spawn the recursive preview build with the preview secret
50
- * returned by registration (or the env override).
30
+ * 0. Write the editor page to `dist/_conloca/editor/`: `index.html`, the
31
+ * site's compiled puck config and styles, the MDX sandbox frame and
32
+ * `conloca.json`. Every build does this; the page carries no credential.
33
+ * 1. Only when `previewBuild` is given as an object and an SSR adapter
34
+ * exists (refused under @astrojs/vercel and @astrojs/netlify, checked
35
+ * already at `astro:config:done`), spawn the recursive preview build
36
+ * and copy the editor page into its
37
+ * client folder. It mounts `/_conloca/preview/` and
38
+ * bakes in the repository, site and branch it serves (every pass must
39
+ * match them), Astro's base and the commit it was built from.
51
40
  */
52
41
  const VIRTUAL_PREVIEW_OPTS = 'virtual:conloca-preview-opts';
53
42
  const RESOLVED_PREVIEW_OPTS = `\0${VIRTUAL_PREVIEW_OPTS}`;
54
43
 
55
- export function conlocaCloud(options: ConlocaCloudOptions): AstroIntegration {
44
+ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegration {
56
45
  validateOptions(options);
57
46
  const repoUri = resolveRepositoryUri(options.repoUri, process.env);
58
47
  // Populated during the preview build's config:setup and read by the virtual
59
48
  // module below. Server-only — never reaches a browser bundle.
60
- let previewOptsModule: Record<string, string> | undefined;
49
+ let previewOptsModule: BakedPreviewOpts | undefined;
50
+ // The Astro command, recorded in config:setup: only `astro build` starts
51
+ // the preview build, so only it checks the preview adapter at config:done.
52
+ let astroCommand: string | undefined;
61
53
  // The project root, captured in config:setup: astro:build:done only hands
62
54
  // over the build's own outDir, but the siteStyles resolve against the root,
63
- // and locating the CHILD build's client dir (for the editor-asset mirror)
55
+ // and locating the CHILD build's client dir (for the editor page mirror)
64
56
  // needs the root the child resolves against.
65
57
  let projectRoot: URL | undefined;
66
- // Adapter name, finalized only at config:done. Discovery boots the built
67
- // server entry for `output: 'server'` sites, and only the node adapter's
68
- // entry is a plain bootable process (see discovery.ts).
58
+ // Adapter name, finalized only at config:done: the preview build reads it
59
+ // when previewBuild names no adapter of its own.
69
60
  let adapterName: string | undefined;
70
- // The site's Vite config, finalized at config:done: the siteStyles compile
71
- // through it, as they do in conlocaCMS's dev editor.
61
+ // The site's Vite config, finalized at config:done: the editor page and the
62
+ // siteStyles compile through it, as they do in conlocaCMS's dev editor. It
63
+ // holds the site's and integrations' plugins only; Astro adds its own core
64
+ // plugins to a separate config when it builds, so none reach the editor page.
72
65
  let viteConfig: ViteUserConfig | undefined;
66
+ // Astro's base, as written: the editor page's URLs sit below it.
67
+ let astroBase = '/';
68
+ // The editor options, settled at config:done: conlocaCMS publishes its
69
+ // channel from its own config:setup, which may run after ours.
70
+ let inherited: InheritedOptions | undefined;
71
+ // Whether the parent build starts the preview build, read with the adapter
72
+ // the child will use: previewBuild.adapter, else the project's own.
73
+ const previewMode = () =>
74
+ previewBuildMode(options.previewBuild, (options.previewBuild || undefined)?.adapter?.name ?? adapterName);
73
75
 
74
76
  return {
75
77
  name: PACKAGE_NAME,
76
78
  hooks: {
77
- 'astro:config:setup': ({ logger, injectRoute, updateConfig, config, addMiddleware }) => {
79
+ 'astro:config:setup': ({ logger, injectRoute, updateConfig, config, addMiddleware, command }) => {
78
80
  // Optional-chained: unit tests drive this hook with a bare { logger }.
79
81
  projectRoot = config?.root;
82
+ astroCommand = command;
80
83
  // The agent skill: write-if-not-exists, fail-soft, and
81
84
  // never from the recursive preview child (it would race the parent).
82
85
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1' && config?.root) {
83
86
  scaffoldSkill(fileURLToPath(config.root), logger);
84
87
  }
85
- logger.info(
86
- `integration registered (endpoint=${options.endpoint}, previewMode=${
87
- options.previewDomain ? 'preview-domain' : 'same-domain-runtime'
88
- })`,
89
- );
88
+ logger.info(`integration registered (endpoint=${options.endpoint ?? DEFAULT_EDITOR_ENDPOINT})`);
90
89
 
91
90
  // Only the recursive preview build (which sets PREVIEW_BUILD_ENV_FLAG)
92
- // mounts the secret-scoped SSR catch-all that renders previews. A
93
- // site's normal build must never expose it; the per-branch secret in
94
- // the path is the load guard (JWT validation in the handler is the real
95
- // auth boundary). Without a secret there is nothing to scope, so skip.
91
+ // mounts the SSR catch-all that renders previews; a site's normal
92
+ // build never exposes it. The route is fixed and public: the signed
93
+ // pass, checked against what this build bakes in, is the lock.
96
94
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
97
- const secret = process.env[PREVIEW_SECRET_ENV_FLAG];
98
- if (secret) {
99
- if (!repoUri) {
100
- throw new Error(
101
- `${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
102
- '(build in a Git checkout or set repoUri as an advanced override)',
103
- );
104
- }
105
- injectRoute({
106
- pattern: `/conloca_preview_${secret}/[...path]`,
107
- entrypoint: '@conloca/cloud-astro/preview-handler',
108
- prerender: false,
109
- });
110
- // The prefixed route above is the ENTRY DOOR — the only URL the
111
- // endpoint can link to before a cookie exists. This interceptor is the
112
- // serving surface: once the init hop sets the `Path=/` cookie, the
113
- // browser sends the credential on every same-origin request, so
114
- // internal links keep rendering drafts instead of silently falling
115
- // back to published content after one page view. Fail-open — an
116
- // uncredentialed visitor gets the ordinary page.
117
- addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware', order: 'pre' });
118
- // Bake the middleware's configuration into the artifact. Every
119
- // value is already known here — the secret arrived with
120
- // registration, endpoint/audience are integration options — so a
121
- // correctly built preview deployment needs NO env vars set on it.
122
- // That also closes a chicken-and-egg loop: the secret is generated
123
- // DURING this build, but the deployment that would carry it as an
124
- // env var only happens afterwards. `saasIssuer` stays unbaked
125
- // unless configured: it is a property of the endpoint, not of the site.
126
- // The commit this preview build's checkout holds: a PR build may
127
- // check out a merge commit rather than the PR commit it registers.
128
- // Page-status compares the branch's latest commit with it, so the
129
- // endpoint diffs against the content actually serving, not a newer
130
- // registration whose deploy never landed. A checkout commit the
131
- // endpoint does not have makes it render from the branch instead.
132
- const buildCommit = registrationCommits({
133
- eventCommitSha: process.env.CF_PAGES_COMMIT_SHA,
134
- checkoutCommitSha: gitOutput(['rev-parse', 'HEAD']),
135
- }).buildId;
136
- previewOptsModule = {
137
- secret,
138
- saasEndpoint: options.endpoint,
139
- // The token's `aud` is the repo URI as registered — the same
140
- // string this integration posts at registration time.
141
- saasAudience: repoUri,
142
- ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
143
- ...(buildCommit ? { buildCommit } : {}),
144
- };
145
- // Preview-build path: the child build must emit an SSR
146
- // artifact even when the primary build is fully static. Switch to
147
- // server output, apply the preview adapter (the project's own
148
- // adapter stays in force when it already has one), and write to a
149
- // SEPARATE outDir so the child never clobbers the primary dist/.
150
- const previewBuild = options.previewBuild === false ? {} : (options.previewBuild ?? {});
151
- const adapter = previewBuild.adapter ?? config.adapter;
152
- if (!adapter) {
153
- throw new Error(
154
- `${PACKAGE_NAME}: the preview build needs an SSR adapter — the project is static and ` +
155
- 'previewBuild.adapter is not set. Pass one (e.g. previewBuild: { adapter: cloudflare() }) ' +
156
- 'or set previewBuild: false to opt out of draft preview.',
157
- );
158
- }
159
- // Astro allows exactly one deployment integration. Adding
160
- // previewBuild.adapter next to the project's own would make the
161
- // child build die on Astro's adapter-conflict error, which names
162
- // neither this integration nor the option — fail here with the
163
- // actual cause. The child inherits the project adapter, so the
164
- // option is unnecessary on SSR projects.
165
- if (previewBuild.adapter && config.adapter) {
166
- const projectAdapterName = (config.adapter as { name?: string }).name ?? 'the project adapter';
167
- throw new Error(
168
- `${PACKAGE_NAME}: previewBuild.adapter conflicts with the project's own adapter ` +
169
- `(${projectAdapterName}) — Astro allows only one deployment integration per build. ` +
170
- 'Remove previewBuild.adapter; the preview build inherits the project adapter.',
171
- );
172
- }
173
- // Trailing slash so URL-joining treats it as a directory. Astro
174
- // derives build.client/build.server from outDir BEFORE hooks run,
175
- // so overriding outDir alone still writes into the primary dist/ —
176
- // all three must move together.
177
- // OUTSIDE dist/ on purpose, against the original design: the
178
- // artifact bakes the preview secret, so a wholesale static upload
179
- // of dist/ must never be able to publish it — and Astro clears
180
- // dist/ at the start of a build, which would wipe a sibling
181
- // artifact parked inside it.
182
- const previewOut = new URL(`${previewBuild.outDir ?? '.conloca/preview-server'}/`, config.root);
183
- // The site's extra config goes through its OWN updateConfig
184
- // call: Astro deep-merges successive calls (concatenating
185
- // vite.plugins and integrations), whereas spreading it into the
186
- // object below would shallow-replace whole keys — a user `vite`
187
- // entry silently dropped the required virtual-module plugin.
188
- // Ours comes second so the required scalars (output, outDir,
189
- // build dirs) always win; previewBuild.outDir is the supported
190
- // override for the artifact location.
191
- if (previewBuild.config) {
192
- updateConfig(previewBuild.config);
193
- }
194
- updateConfig({
195
- output: 'server',
196
- outDir: previewOut,
197
- build: { client: new URL('client/', previewOut), server: new URL('server/', previewOut) },
198
- vite: {
199
- // The middleware dynamically imports Cloudflare's runtime
200
- // module (binding transport). The Cloudflare adapter resolves
201
- // the scheme itself; every other adapter's Rollup pass fails
202
- // the child build on it unless externalized. Off Cloudflare
203
- // Workers the runtime import rejects and the middleware falls
204
- // back to the global fetch.
205
- build: { rollupOptions: { external: [/^cloudflare:/] } },
206
- // Starlight renders Steps, Tabs and FileTree with satteri's
207
- // htmlToHast. On Cloudflare Workers satteri resolves to a
208
- // binding that can be neither installed nor run on workerd, so the child
209
- // build fails to resolve it — swap in a stand-in there. The
210
- // target is an absolute path: a bare name would be looked up
211
- // from the Starlight file, which cannot see this package in an
212
- // isolated (non-hoisted) node_modules layout.
213
- ...(adapter.name === '@astrojs/cloudflare'
214
- ? {
215
- resolve: {
216
- alias: [
217
- {
218
- find: /^satteri$/,
219
- replacement: resolveSatteriStandIn(),
220
- },
221
- ],
222
- },
223
- }
224
- : {}),
225
- plugins: [
226
- {
227
- name: 'conloca-preview-opts',
228
- resolveId(id: string) {
229
- return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
230
- },
231
- load(id: string) {
232
- if (id !== RESOLVED_PREVIEW_OPTS) return undefined;
233
- // Read lazily so the values assigned above are captured.
234
- return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
95
+ if (!repoUri) {
96
+ throw new Error(
97
+ `${PACKAGE_NAME}: could not determine repository identity for the preview build ` +
98
+ '(build in a Git checkout or set repoUri as an advanced override)',
99
+ );
100
+ }
101
+ // The project's own checkout answers git, not the directory the
102
+ // build was started from.
103
+ const projectGit = (args: string[]) => gitOutput(args, fileURLToPath(config.root));
104
+ const buildRef = resolveBuildRef(process.env, projectGit);
105
+ if (!buildRef.branch) {
106
+ throw new Error(
107
+ `${PACKAGE_NAME}: could not determine the branch the preview build serves (set CF_PAGES_BRANCH, ` +
108
+ 'WORKERS_CI_BRANCH, VERCEL_GIT_COMMIT_REF or GITHUB_REF_NAME, or build in a git checkout on a branch)',
109
+ );
110
+ }
111
+ const siteId = resolveBuildSiteId({
112
+ contentRoot: process.env.CONLOCA_CONTENT_ROOT,
113
+ override: options.siteId,
114
+ });
115
+ injectRoute({
116
+ pattern: `${PREVIEW_ROUTE_SEGMENT}/[...path]`,
117
+ entrypoint: '@conloca/cloud-astro/preview-handler',
118
+ prerender: false,
119
+ });
120
+ // The route above is the ENTRY DOOR — the only URL the endpoint can
121
+ // link to before a cookie exists. This interceptor is the serving
122
+ // surface: once the init hop sets the `Path=/` cookie, the browser
123
+ // sends the credential on every same-origin request, so internal
124
+ // links keep rendering drafts instead of silently falling back to
125
+ // published content after one page view. Fail-open — an
126
+ // uncredentialed visitor gets the ordinary page.
127
+ addMiddleware({ entrypoint: '@conloca/cloud-astro/site-middleware', order: 'pre' });
128
+ // The commit this preview build's checkout holds: a PR build may
129
+ // check out a merge commit rather than the commit CI hands over.
130
+ // Page-status compares the branch's latest commit with it, so the
131
+ // endpoint diffs against the content actually serving, not a newer
132
+ // commit whose deploy never landed. A checkout commit the
133
+ // endpoint does not have makes it render from the branch instead.
134
+ const buildCommit = projectGit(['rev-parse', 'HEAD']) ?? buildRef.gitSha;
135
+ // Bake the middleware's configuration into the artifact. Every value
136
+ // is already known here — endpoint and audience are integration
137
+ // options; repository, site, branch, base and commit are what this
138
+ // build was made from, and every pass must match the first three —
139
+ // so a correctly built preview deployment needs NO env vars set on
140
+ // it. `saasIssuer` stays unbaked unless configured: it is a property
141
+ // of the endpoint, not of the site.
142
+ previewOptsModule = {
143
+ saasEndpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
144
+ // The token's `aud` is the repo URI this build resolved.
145
+ saasAudience: repoUri,
146
+ ...(options.saasIssuer ? { saasIssuer: options.saasIssuer } : {}),
147
+ ...(buildCommit ? { buildCommit } : {}),
148
+ repo: repoUri,
149
+ siteId,
150
+ branch: buildRef.branch,
151
+ base: config.base ?? '/',
152
+ };
153
+ // Preview-build path: the child build must emit an SSR
154
+ // artifact even when the primary build is fully static. Switch to
155
+ // server output, apply the preview adapter (the project's own
156
+ // adapter stays in force when it already has one), and write to a
157
+ // SEPARATE outDir so the child never clobbers the primary dist/.
158
+ const previewBuild = options.previewBuild || {};
159
+ const adapter = previewBuild.adapter ?? config.adapter;
160
+ // Throws for a missing adapter, or one the preview build is refused
161
+ // under — the parent already checked, this keeps the child honest.
162
+ previewBuildMode(previewBuild, adapter?.name);
163
+ // Astro allows exactly one deployment integration. Adding
164
+ // previewBuild.adapter next to the project's own would make the
165
+ // child build die on Astro's adapter-conflict error, which names
166
+ // neither this integration nor the option — fail here with the
167
+ // actual cause. The child inherits the project adapter, so the
168
+ // option is unnecessary on SSR projects.
169
+ if (previewBuild.adapter && config.adapter) {
170
+ const projectAdapterName = config.adapter.name;
171
+ throw new Error(
172
+ `${PACKAGE_NAME}: previewBuild.adapter conflicts with the project's own adapter ` +
173
+ `(${projectAdapterName}) — Astro allows only one deployment integration per build. ` +
174
+ 'Remove previewBuild.adapter; the preview build inherits the project adapter.',
175
+ );
176
+ }
177
+ // Trailing slash so URL-joining treats it as a directory. Astro
178
+ // derives build.client/build.server from outDir BEFORE hooks run,
179
+ // so overriding outDir alone still writes into the primary dist/ —
180
+ // all three must move together.
181
+ // OUTSIDE dist/ on purpose, against the original design: a
182
+ // wholesale static upload of dist/ must never publish the preview
183
+ // server — and Astro clears dist/ at the start of a build, which
184
+ // would wipe a sibling artifact parked inside it.
185
+ const previewOut = new URL(`${previewBuild.outDir ?? '.conloca/preview-server'}/`, config.root);
186
+ // The site's extra config goes through its OWN updateConfig
187
+ // call: Astro deep-merges successive calls (concatenating
188
+ // vite.plugins and integrations), whereas spreading it into the
189
+ // object below would shallow-replace whole keys — a user `vite`
190
+ // entry silently dropped the required virtual-module plugin.
191
+ // Ours comes second so the required scalars (output, outDir,
192
+ // build dirs) always win; previewBuild.outDir is the supported
193
+ // override for the artifact location.
194
+ if (previewBuild.config) {
195
+ updateConfig(previewBuild.config);
196
+ }
197
+ updateConfig({
198
+ output: 'server',
199
+ outDir: previewOut,
200
+ build: { client: new URL('client/', previewOut), server: new URL('server/', previewOut) },
201
+ vite: {
202
+ // The middleware dynamically imports Cloudflare's runtime
203
+ // module (binding transport). The Cloudflare adapter resolves
204
+ // the scheme itself; every other adapter's Rollup pass fails
205
+ // the child build on it unless externalized. Off Cloudflare
206
+ // Workers the runtime import rejects and the middleware falls
207
+ // back to the global fetch.
208
+ build: { rollupOptions: { external: [/^cloudflare:/] } },
209
+ // Starlight renders Steps, Tabs and FileTree with satteri's
210
+ // htmlToHast. On Cloudflare Workers satteri resolves to a
211
+ // binding that can be neither installed nor run on workerd, so the child
212
+ // build fails to resolve it — swap in a stand-in there. The
213
+ // target is an absolute path: a bare name would be looked up
214
+ // from the Starlight file, which cannot see this package in an
215
+ // isolated (non-hoisted) node_modules layout.
216
+ ...(adapter?.name === '@astrojs/cloudflare'
217
+ ? {
218
+ resolve: {
219
+ alias: [
220
+ {
221
+ find: /^satteri$/,
222
+ replacement: resolveSatteriStandIn(),
223
+ },
224
+ ],
235
225
  },
226
+ }
227
+ : {}),
228
+ plugins: [
229
+ {
230
+ name: 'conloca-preview-opts',
231
+ resolveId(id: string) {
232
+ return id === VIRTUAL_PREVIEW_OPTS ? RESOLVED_PREVIEW_OPTS : undefined;
236
233
  },
237
- ],
238
- },
239
- // The adapter must ride in BOTH ways: as `adapter` because the
240
- // build gate checks `config.adapter` before creating the SSR
241
- // bundle, and as an integration because only the adapter's own
242
- // astro:config:done hook calls setAdapter — which is what the
243
- // build pipeline actually renders through. (Astro unshifts
244
- // config.adapter into the integration list BEFORE any hook runs,
245
- // so setting `adapter` alone here is too late for the hooks.)
246
- // A project that is already SSR keeps its own adapter untouched.
247
- ...(previewBuild.adapter ? { adapter: previewBuild.adapter, integrations: [previewBuild.adapter] } : {}),
248
- });
249
- }
234
+ load(id: string) {
235
+ if (id !== RESOLVED_PREVIEW_OPTS) return undefined;
236
+ // Read lazily so the values assigned above are captured.
237
+ return `export default ${JSON.stringify(previewOptsModule ?? {})};`;
238
+ },
239
+ },
240
+ ],
241
+ },
242
+ // The adapter must ride in BOTH ways: as `adapter` because the
243
+ // build gate checks `config.adapter` before creating the SSR
244
+ // bundle, and as an integration because only the adapter's own
245
+ // astro:config:done hook calls setAdapter — which is what the
246
+ // build pipeline actually renders through. (Astro unshifts
247
+ // config.adapter into the integration list BEFORE any hook runs,
248
+ // so setting `adapter` alone here is too late for the hooks.)
249
+ // A project that is already SSR keeps its own adapter untouched.
250
+ ...(previewBuild.adapter ? { adapter: previewBuild.adapter, integrations: [previewBuild.adapter] } : {}),
251
+ });
250
252
  }
251
253
  },
252
254
  /**
@@ -268,13 +270,11 @@ export function conlocaCloud(options: ConlocaCloudOptions): AstroIntegration {
268
270
  * record, runs AFTER the `export const prerender` source parse, and
269
271
  * Astro reads `prerender` back after every integration has run.
270
272
  *
271
- * Gated on the secret as well as the flag, mirroring the config hook: no
272
- * secret means no interceptor was mounted, so stripping the site's
273
- * static output would buy nothing.
273
+ * Gated on the flag, as the config hook is: only the preview build
274
+ * mounts the interceptor these routes must reach.
274
275
  */
275
276
  'astro:route:setup': ({ route, logger }) => {
276
277
  if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') return;
277
- if (!process.env[PREVIEW_SECRET_ENV_FLAG]) return;
278
278
  // `type` exists at runtime but is absent from the public RouteOptions
279
279
  // type. Endpoints keep their prerendered data files: they emit no HTML
280
280
  // to intercept, and one built from getStaticPaths would break on demand.
@@ -296,120 +296,59 @@ export function conlocaCloud(options: ConlocaCloudOptions): AstroIntegration {
296
296
  'astro:config:done': ({ config }) => {
297
297
  adapterName = config.adapter?.name;
298
298
  viteConfig = config.vite;
299
+ astroBase = config.base ?? '/';
300
+ inherited = resolveInheritedOptions(options, readEditorDescriptors());
301
+ // A refused or missing preview adapter fails `astro build` here,
302
+ // before the site builds, rather than after it. `astro dev`, `sync`
303
+ // and `preview` never start the preview build, so they are left
304
+ // alone. The child build checks its own.
305
+ if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') previewMode();
299
306
  },
300
307
  'astro:build:done': async ({ dir, logger }) => {
301
308
  if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
302
309
  // The recursive preview build sets this flag on the child
303
- // Astro process. Re-entering registration there would create an
304
- // infinite build loop, so we short-circuit.
305
- logger.info('skipping registration: recursive preview build detected');
310
+ // Astro process. Writing the editor page there again would race
311
+ // the parent, which mirrors its own copy in, so we short-circuit.
312
+ logger.info('skipping the editor page: recursive preview build detected');
306
313
  return;
307
314
  }
308
315
 
309
316
  // Astro always runs the config hooks first. No fallback: compiling
310
317
  // against the working directory would build the canvas stylesheet for
311
318
  // the wrong project without a word.
312
- if (projectRoot === undefined || viteConfig === undefined) {
319
+ if (projectRoot === undefined || viteConfig === undefined || inherited === undefined) {
313
320
  throw new Error(
314
321
  `${PACKAGE_NAME}: astro:build:done ran before the config hooks recorded the project root and Vite config`,
315
322
  );
316
323
  }
317
324
 
318
- // Editor descriptors (the bundle's third leg): the host's schemas
319
- // module and the auto-discovered MDX registry, both resolved by
320
- // conlocaCMS and read off its channel. The scan runs here because the
321
- // editor at the endpoint has no dev server to serve `/api/registry` from.
322
- const descriptors = await resolveEditorDescriptors(logger);
323
-
324
- const bundle = await bundleEditorAssets({
325
+ // The editor page: every build writes it.
326
+ await emitEditorPage({
325
327
  dir: fileURLToPath(dir),
326
328
  root: fileURLToPath(projectRoot),
329
+ base: astroBase,
327
330
  vite: viteConfig,
328
- puckConfigPath: options.puckConfigPath,
329
- siteStyles: options.siteStyles,
330
- ...(options.editorBundlePlugins ? { plugins: options.editorBundlePlugins } : {}),
331
- publicBaseUrl: resolveDeploymentUrl(options),
332
- ...(descriptors === undefined ? {} : { descriptors }),
331
+ endpoint: options.endpoint,
332
+ inherited,
333
+ repoUri,
334
+ siteIdOverride: options.siteId,
333
335
  logger,
334
336
  });
335
337
 
336
- // The component vocabulary for agents, read from the config the bundle
337
- // just compiled. Only a build conlocaCMS is part of carries one (its
338
- // descriptor channel is how this add-on knows): without the CMS there
339
- // are no pages for an agent to compose. Gated on the channel itself,
340
- // not on `descriptors` — that is also undefined for a CMS build with
341
- // no schemas module, MDX components or templates, which still has a
342
- // Puck vocabulary. An unreadable channel already warned above.
343
- const componentManifest =
344
- readEditorDescriptors(process.env) === undefined
345
- ? undefined
346
- : await emitComponentManifest({
347
- dir: fileURLToPath(dir),
348
- puckConfigPath: options.puckConfigPath,
349
- projectRoot: process.cwd(),
350
- logger,
351
- });
352
-
353
- // Build-time style discovery: read the discovery
354
- // route's rendered page, collect its CSS, run the shared wrapper
355
- // heuristic; results ride registration below. Opt-in via the option —
356
- // and fail-soft throughout: a build must never die over preview
357
- // styling.
358
- let discovery: Awaited<ReturnType<typeof discoverStyleContext>>;
359
- let routeCssArtifact: Awaited<ReturnType<typeof emitRouteCssArtifact>>;
360
- if (options.fragmentPreviewRoute) {
361
- const clientDir = fileURLToPath(dir);
362
- const nodeEntry = fileURLToPath(new URL('../server/entry.mjs', dir));
363
- discovery = await discoverStyleContext({
364
- clientDir,
365
- serverEntry: adapterName === '@astrojs/node' && existsSync(nodeEntry) ? nodeEntry : undefined,
366
- route: options.fragmentPreviewRoute,
367
- logger,
368
- });
369
- if (discovery?.routeCss) {
370
- routeCssArtifact = await emitRouteCssArtifact(
371
- clientDir,
372
- discovery.routeCss,
373
- resolveDeploymentUrl(options),
374
- logger,
375
- );
376
- }
377
- }
378
-
379
- const registration = await registerBuild(options, repoUri, bundle, logger, {
380
- hostWrappers: discovery?.hostWrappers,
381
- routeCssArtifact: routeCssArtifact?.stylesheet,
382
- componentManifest,
383
- });
384
- let registeredSecret: string | undefined;
385
- if ('missing' in registration) reportSkippedRegistration(registration.missing, options, logger);
386
- else registeredSecret = registration.previewSecret;
387
-
388
- if (options.previewBuild === false) {
389
- // The site explicitly opted out of the recursive preview build.
390
- return;
391
- }
392
- // Prefer the secret returned by registration; the env override lets
393
- // CI smoke-test the recursive build path without a reachable endpoint.
394
- const previewSecret = registeredSecret ?? process.env[PREVIEW_SECRET_ENV_FLAG];
395
- if (!previewSecret) {
396
- return;
397
- }
398
- await spawnPreviewBuild(previewSecret, options.previewBuild ?? {});
399
- // The child build cannot compile the editor bundle itself (it
338
+ // Strict opt-in: only a previewBuild given as an object starts the
339
+ // second build.
340
+ const previewBuild = options.previewBuild || undefined;
341
+ if (previewBuild === undefined || previewMode() === 'off') return;
342
+ await spawnPreviewBuild(previewBuild);
343
+ // The child build cannot write the editor files itself (it
400
344
  // short-circuits this hook — see the recursion guard above), but in
401
345
  // a deployment that serves the site and the preview from one
402
346
  // Cloudflare Worker its client dir is THE asset set serving the site,
403
- // so the editor at the endpoint loads `/_conloca/*` from it. Mirror
404
- // the bundle + its CORS rule from this build's dist into it.
405
- // previewBuild === false already returned above, so only the options
406
- // object (or undefined) reaches this point.
407
- const previewOut = new URL(`${options.previewBuild?.outDir ?? '.conloca/preview-server'}/`, projectRoot);
408
- await mirrorEditorAssets(fileURLToPath(dir), fileURLToPath(new URL('client/', previewOut)), [
409
- ...bundle.assetCorsPaths,
410
- ...(routeCssArtifact?.assetCorsPaths ?? []),
411
- ]);
412
- logger.info('editor assets mirrored into the preview client dir');
347
+ // so the editor files must be there too. Mirror them from this build's dist.
348
+ const previewOut = new URL(`${previewBuild.outDir ?? '.conloca/preview-server'}/`, projectRoot);
349
+ const previewClient = fileURLToPath(new URL('client/', previewOut));
350
+ await mirrorEditorPage(fileURLToPath(dir), previewClient);
351
+ logger.info('editor page mirrored into the preview client dir');
413
352
  },
414
353
  },
415
354
  };
@@ -428,180 +367,35 @@ function resolveSatteriStandIn(): string {
428
367
  }
429
368
  }
430
369
 
431
- /**
432
- * The origin the deployed site answers on. Used for two things that must agree:
433
- * absolutizing the bundle/stylesheet URLs a registration carries, and re-pointing the
434
- * stylesheet's own asset URLs at the site (they would otherwise resolve
435
- * against the editor's origin — see `rewriteStylesheetAssetUrls`).
436
- */
437
- function resolveDeploymentUrl(options: ConlocaCloudOptions): string | undefined {
438
- if (!options.previewDomain) {
439
- return options.publicBaseUrl ?? process.env.CF_PAGES_URL;
440
- }
441
- const previewUrl = new URL(
442
- options.previewDomain.includes('://') ? options.previewDomain : `https://${options.previewDomain}`,
443
- );
444
- return previewUrl.origin;
445
- }
446
-
447
- /**
448
- * ONE end-of-build block for a skipped registration — every prerequisite that
449
- * was missing and what it costs — the last thing the integration prints.
450
- * With `requireRegistration` it fails the build instead.
451
- */
452
- function reportSkippedRegistration(
453
- missing: string[],
454
- options: ConlocaCloudOptions,
455
- logger: AstroIntegrationLogger,
456
- ): void {
457
- const summary = [
458
- `editor at ${options.endpoint} NOT updated by this build`,
459
- ...missing.map((prerequisite) => ` missing: ${prerequisite}`),
460
- " consequence: registration was skipped, so the editor keeps serving the previous build of this branch (or the default branch's, or nothing, if neither was ever registered)",
461
- ' check: conloca doctor --live',
462
- ].join('\n');
463
- if (options.requireRegistration) {
464
- throw new Error(`${PACKAGE_NAME}: ${summary}\n requireRegistration is on, so this build fails.`);
465
- }
466
- logger.warn(summary);
467
- }
468
-
469
- /** What `registerBuild` ended with: the preview secret, or every prerequisite whose absence made it skip. */
470
- type RegistrationOutcome = { previewSecret: string } | { missing: string[] };
471
-
472
- /**
473
- * Registers the freshly built editor bundle at the endpoint. Soft-skip ONLY
474
- * when registration was never attempted: the pre-request guards (no build
475
- * token, no repo identity, no sha/branch, no base URL) each warn, and every
476
- * missing prerequisite is returned at once, so one build names all that setup
477
- * still lacks and an unregistered deploy still completes — the hook turns
478
- * that into one end-of-build summary (or a failure under
479
- * `requireRegistration`). Once a registration IS attempted, its failure
480
- * FAILS THE BUILD: postRegistration throws on any
481
- * deterministic 4xx and after exhausting the ≥500 retry backoff, and that
482
- * error — carrying the HTTP status and response body — propagates. A green
483
- * deploy whose registration silently went missing is the "deployed but
484
- * editor unregistered" class this project exists to kill.
485
- */
486
- async function registerBuild(
487
- options: ConlocaCloudOptions,
488
- repoUri: string | undefined,
489
- bundle: BundleEditorAssetsResult,
490
- logger: AstroIntegrationLogger,
491
- discovery: {
492
- hostWrappers?: DiscoveredStyleContext['hostWrappers'];
493
- routeCssArtifact?: BundledStylesheet;
494
- componentManifest?: ComponentManifestArtifact;
495
- } = {},
496
- ): Promise<RegistrationOutcome> {
497
- const missing: string[] = [];
498
- const buildToken = options.buildToken ?? process.env[BUILD_TOKEN_ENV_VAR];
499
- if (!buildToken) {
500
- logger.warn(`skipping registration: no build token (set buildToken or ${BUILD_TOKEN_ENV_VAR})`);
501
- missing.push(`build token (set buildToken or ${BUILD_TOKEN_ENV_VAR})`);
502
- }
503
-
504
- if (!repoUri) {
505
- logger.warn(
506
- 'skipping registration: could not determine repository identity ' +
507
- '(build in a supported CI environment or Git checkout, or set repoUri)',
508
- );
509
- missing.push('repository identity (build in a supported CI environment or Git checkout, or set repoUri)');
510
- }
511
-
512
- const { branch } = resolveBuildRef();
513
- // CI may hand over the branch's latest commit to register; the checkout is what was built.
514
- const commits = registrationCommits({
515
- eventCommitSha: process.env.CF_PAGES_COMMIT_SHA,
516
- checkoutCommitSha: gitOutput(['rev-parse', 'HEAD']),
517
- });
518
- const gitSha = commits.gitSha;
519
- if (!gitSha || !branch) {
520
- logger.warn(
521
- 'skipping registration: could not resolve the git sha/branch ' +
522
- '(set CF_PAGES_COMMIT_SHA and CF_PAGES_BRANCH, or build inside a git checkout)',
523
- );
524
- missing.push('git sha/branch (set CF_PAGES_COMMIT_SHA and CF_PAGES_BRANCH, or build inside a git checkout)');
525
- }
526
-
527
- const deploymentUrl = resolveDeploymentUrl(options);
528
- const baseUrl = deploymentUrl;
529
- if (!baseUrl) {
530
- logger.warn(
531
- 'skipping registration: no public base URL for the editor bundle (set previewDomain, publicBaseUrl, or CF_PAGES_URL)',
532
- );
533
- missing.push('public base URL for the editor bundle (set previewDomain, publicBaseUrl, or CF_PAGES_URL)');
534
- }
535
- // Restates the guards above, so the values below are typed as set.
536
- if (!buildToken || !repoUri || !gitSha || !branch || !baseUrl) return { missing };
537
-
538
- // Resolve the deployable-site id (STRICT): a throw here FAILS THE BUILD —
539
- // after the soft skip guards above, so only a build that is actually
540
- // registering can die on it. A silently mis-attached registration points
541
- // the editor at the wrong site, which is the same miss as never having
542
- // registered at all. The channel is CONLOCA_CONTENT_ROOT (published by
543
- // conlocaCMS); options.siteId is the CMS-less-build override.
544
- const siteId = resolveBuildSiteId({
545
- contentRoot: process.env.CONLOCA_CONTENT_ROOT,
546
- override: options.siteId,
547
- });
548
-
549
- // NO catch: from here on the registration is ATTEMPTED, and an attempted
550
- // registration's failure fails the build. postRegistration already retried
551
- // transient (≥500 / network) failures with backoff; what escapes is either
552
- // a deterministic 4xx (unknown siteId, bad token — fix and rebuild) or an
553
- // exhausted retry budget, and the error message carries the HTTP status +
554
- // response body verbatim.
555
- logger.info(
556
- 'registering at the endpoint (transient failures retry, with up to ~2.5 minutes of waiting between attempts)',
557
- );
558
- const { previewSecret } = await postRegistration({
559
- endpoint: options.endpoint,
560
- buildToken,
561
- repoUri,
562
- gitSha,
563
- siteId,
564
- branch,
565
- editorBundleUrl: new URL(bundle.url, baseUrl).toString(),
566
- bundleHash: bundle.hash,
567
- ...(bundle.stylesheet === undefined
568
- ? {}
569
- : {
570
- stylesheetUrl: new URL(bundle.stylesheet.url, baseUrl).toString(),
571
- stylesheetHash: bundle.stylesheet.hash,
572
- }),
573
- ...(discovery.hostWrappers === undefined ? {} : { hostWrappers: discovery.hostWrappers }),
574
- ...(discovery.routeCssArtifact === undefined
575
- ? {}
576
- : {
577
- routeCssUrl: new URL(discovery.routeCssArtifact.url, baseUrl).toString(),
578
- routeCssHash: discovery.routeCssArtifact.hash,
579
- }),
580
- ...(discovery.componentManifest === undefined
581
- ? {}
582
- : {
583
- componentManifestUrl: new URL(discovery.componentManifest.url, baseUrl).toString(),
584
- componentManifestHash: discovery.componentManifest.hash,
585
- }),
586
- deploymentUrl,
587
- buildId: commits.buildId,
588
- clientVersion: packageVersion(),
589
- });
590
- logger.info(`registration complete (gitSha=${gitSha}, branch=${branch}, buildId=${commits.buildId})`);
591
- return { previewSecret };
592
- }
370
+ /** The options the editor page made obsolete; naming one fails the build so the config gets updated. */
371
+ const REMOVED_OPTIONS = [
372
+ 'buildToken',
373
+ 'requireRegistration',
374
+ 'publicBaseUrl',
375
+ 'previewDomain',
376
+ 'editorBundlePlugins',
377
+ 'fragmentPreviewRoute',
378
+ ] as const;
593
379
 
380
+ /** Refuses a removed option, a malformed endpoint, or one that is not an `app.` address, at config load. */
594
381
  function validateOptions(options: ConlocaCloudOptions): void {
595
- if (!options.endpoint) {
596
- throw new Error(`${PACKAGE_NAME}: endpoint is required`);
597
- }
598
- if (!options.puckConfigPath) {
599
- throw new Error(`${PACKAGE_NAME}: puckConfigPath is required`);
382
+ for (const name of REMOVED_OPTIONS) {
383
+ if (name in options) {
384
+ throw new Error(
385
+ `${PACKAGE_NAME}: option "${name}" was removed — run \`npx @conloca/cli connect\` to update this config`,
386
+ );
387
+ }
600
388
  }
389
+ if (options.endpoint === undefined) return;
601
390
  try {
602
391
  // Throws on malformed URLs; we don't keep the parsed value.
603
392
  new URL(options.endpoint);
604
393
  } catch {
605
394
  throw new Error(`${PACKAGE_NAME}: endpoint must be a valid URL, got ${options.endpoint}`);
606
395
  }
396
+ if (editorUiOrigin(options.endpoint) === null) {
397
+ throw new Error(
398
+ `${PACKAGE_NAME}: endpoint must be the workspace editor's app. address (for example https://app.conloca.com), got ${options.endpoint}`,
399
+ );
400
+ }
607
401
  }