@conloca/cloud-astro 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +155 -37
- package/dist/.build-inputs.json +32 -23
- package/dist/src/constants.d.ts +12 -3
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +12 -3
- package/dist/src/constants.js.map +1 -1
- package/dist/src/d3-build.d.ts +70 -0
- package/dist/src/d3-build.d.ts.map +1 -0
- package/dist/src/d3-build.js +272 -0
- package/dist/src/d3-build.js.map +1 -0
- package/dist/src/descriptors.d.ts.map +1 -1
- package/dist/src/descriptors.js +4 -2
- package/dist/src/descriptors.js.map +1 -1
- package/dist/src/doctor/checks-live.d.ts +2 -2
- package/dist/src/doctor/checks-live.d.ts.map +1 -1
- package/dist/src/doctor/checks-live.js +10 -4
- package/dist/src/doctor/checks-live.js.map +1 -1
- package/dist/src/doctor/checks-offline.d.ts +1 -5
- package/dist/src/doctor/checks-offline.d.ts.map +1 -1
- package/dist/src/doctor/checks-offline.js +15 -27
- package/dist/src/doctor/checks-offline.js.map +1 -1
- package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
- package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview-limits.js +133 -0
- package/dist/src/doctor/checks-preview-limits.js.map +1 -0
- package/dist/src/doctor/checks-preview-live.d.ts +14 -0
- package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview-live.js +72 -0
- package/dist/src/doctor/checks-preview-live.js.map +1 -0
- package/dist/src/doctor/checks-preview.d.ts +7 -0
- package/dist/src/doctor/checks-preview.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview.js +287 -0
- package/dist/src/doctor/checks-preview.js.map +1 -0
- package/dist/src/doctor/config-scan.d.ts +6 -0
- package/dist/src/doctor/config-scan.d.ts.map +1 -1
- package/dist/src/doctor/config-scan.js +17 -0
- package/dist/src/doctor/config-scan.js.map +1 -1
- package/dist/src/doctor/run.d.ts.map +1 -1
- package/dist/src/doctor/run.js +4 -0
- package/dist/src/doctor/run.js.map +1 -1
- package/dist/src/doctor/types.d.ts +11 -1
- package/dist/src/doctor/types.d.ts.map +1 -1
- package/dist/src/doctor/types.js +11 -1
- package/dist/src/doctor/types.js.map +1 -1
- package/dist/src/editor-page/bundle.d.ts +2 -0
- package/dist/src/editor-page/bundle.d.ts.map +1 -1
- package/dist/src/editor-page/bundle.js +3 -0
- package/dist/src/editor-page/bundle.js.map +1 -1
- package/dist/src/editor-page/data-schemas.d.ts +16 -0
- package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
- package/dist/src/editor-page/data-schemas.js +39 -0
- package/dist/src/editor-page/data-schemas.js.map +1 -0
- package/dist/src/editor-page/emit.d.ts +37 -1
- package/dist/src/editor-page/emit.d.ts.map +1 -1
- package/dist/src/editor-page/emit.js +75 -4
- package/dist/src/editor-page/emit.js.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +2 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/integration.d.ts.map +1 -1
- package/dist/src/integration.js +165 -41
- package/dist/src/integration.js.map +1 -1
- package/dist/src/preview/_dispatch.d.ts +12 -0
- package/dist/src/preview/_dispatch.d.ts.map +1 -1
- package/dist/src/preview/_dispatch.js +31 -0
- package/dist/src/preview/_dispatch.js.map +1 -1
- package/dist/src/preview/_resolve-opts.d.ts +3 -0
- package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
- package/dist/src/preview/_resolve-opts.js +3 -1
- package/dist/src/preview/_resolve-opts.js.map +1 -1
- package/dist/src/preview/banner.d.ts +12 -9
- package/dist/src/preview/banner.d.ts.map +1 -1
- package/dist/src/preview/banner.js +46 -41
- package/dist/src/preview/banner.js.map +1 -1
- package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
- package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
- package/dist/src/preview/cloudflare-adapter.js +92 -0
- package/dist/src/preview/cloudflare-adapter.js.map +1 -0
- package/dist/src/preview/cookie.d.ts +9 -13
- package/dist/src/preview/cookie.d.ts.map +1 -1
- package/dist/src/preview/cookie.js +15 -25
- package/dist/src/preview/cookie.js.map +1 -1
- package/dist/src/preview/dispatcher.d.ts +73 -0
- package/dist/src/preview/dispatcher.d.ts.map +1 -0
- package/dist/src/preview/dispatcher.js +329 -0
- package/dist/src/preview/dispatcher.js.map +1 -0
- package/dist/src/preview/entry-code.d.ts +33 -0
- package/dist/src/preview/entry-code.d.ts.map +1 -0
- package/dist/src/preview/entry-code.js +33 -0
- package/dist/src/preview/entry-code.js.map +1 -0
- package/dist/src/preview/headers.d.ts +24 -4
- package/dist/src/preview/headers.d.ts.map +1 -1
- package/dist/src/preview/headers.js +35 -7
- package/dist/src/preview/headers.js.map +1 -1
- package/dist/src/preview/landing.d.ts +21 -0
- package/dist/src/preview/landing.d.ts.map +1 -1
- package/dist/src/preview/landing.js +103 -35
- package/dist/src/preview/landing.js.map +1 -1
- package/dist/src/preview/middleware.d.ts +29 -7
- package/dist/src/preview/middleware.d.ts.map +1 -1
- package/dist/src/preview/middleware.js +238 -84
- package/dist/src/preview/middleware.js.map +1 -1
- package/dist/src/preview/preview-path.d.ts +29 -0
- package/dist/src/preview/preview-path.d.ts.map +1 -1
- package/dist/src/preview/preview-path.js +41 -0
- package/dist/src/preview/preview-path.js.map +1 -1
- package/dist/src/preview/redeem-url.d.ts +7 -0
- package/dist/src/preview/redeem-url.d.ts.map +1 -0
- package/dist/src/preview/redeem-url.js +14 -0
- package/dist/src/preview/redeem-url.js.map +1 -0
- package/dist/src/preview/site-middleware.d.ts.map +1 -1
- package/dist/src/preview/site-middleware.js +39 -12
- package/dist/src/preview/site-middleware.js.map +1 -1
- package/dist/src/preview-build.d.ts +19 -8
- package/dist/src/preview-build.d.ts.map +1 -1
- package/dist/src/preview-build.js +47 -21
- package/dist/src/preview-build.js.map +1 -1
- package/dist/src/skill.d.ts +11 -0
- package/dist/src/skill.d.ts.map +1 -1
- package/dist/src/skill.js +32 -9
- package/dist/src/skill.js.map +1 -1
- package/dist/src/types.d.ts +15 -12
- package/dist/src/types.d.ts.map +1 -1
- package/package.json +33 -7
- package/src/constants.ts +14 -3
- package/src/d3-build.ts +315 -0
- package/src/descriptors.ts +4 -2
- package/src/doctor/checks-live.ts +10 -4
- package/src/doctor/checks-offline.ts +16 -25
- package/src/doctor/checks-preview-limits.ts +137 -0
- package/src/doctor/checks-preview-live.ts +77 -0
- package/src/doctor/checks-preview.ts +302 -0
- package/src/doctor/config-scan.ts +14 -0
- package/src/doctor/run.ts +4 -0
- package/src/doctor/types.ts +11 -1
- package/src/editor-page/bundle.ts +5 -0
- package/src/editor-page/data-schemas.ts +47 -0
- package/src/editor-page/emit.ts +124 -8
- package/src/index.ts +2 -0
- package/src/integration.ts +176 -40
- package/src/preview/_dispatch.ts +36 -1
- package/src/preview/_resolve-opts.ts +6 -1
- package/src/preview/banner.ts +61 -41
- package/src/preview/cloudflare-adapter.ts +103 -0
- package/src/preview/cookie.ts +14 -23
- package/src/preview/dispatcher.ts +407 -0
- package/src/preview/entry-code.ts +51 -0
- package/src/preview/headers.ts +35 -7
- package/src/preview/landing.ts +115 -37
- package/src/preview/middleware.ts +264 -88
- package/src/preview/preview-path.ts +57 -0
- package/src/preview/redeem-url.ts +14 -0
- package/src/preview/site-middleware.ts +47 -12
- package/src/preview-build.ts +67 -24
- package/src/preview-handler.astro +2 -1
- package/src/skill/SKILL.md +14 -2
- package/src/skill.ts +36 -8
- package/src/types.ts +15 -12
package/src/integration.ts
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import type { AstroI18nLocales } from '@conloca/astro-cms/checks';
|
|
3
4
|
import { readEditorDescriptors } from '@conloca/astro-cms/node';
|
|
4
5
|
import { DEFAULT_EDITOR_ENDPOINT, editorUiOrigin } from '@conloca/content-api/editor-host';
|
|
5
6
|
import type { AstroIntegration } from 'astro';
|
|
6
7
|
import type { UserConfig as ViteUserConfig } from 'vite';
|
|
7
8
|
import { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './constants.js';
|
|
8
|
-
import {
|
|
9
|
+
import { finishD3Build, onDemandPatterns, workerFirstPattern, writePreviewRoutes } from './d3-build.js';
|
|
10
|
+
import { emitEditorPage, emitPreviewServerInfo, mirrorEditorPage } from './editor-page/emit.js';
|
|
9
11
|
import { gitOutput, resolveBuildRef, resolveRepositoryUri } from './git.js';
|
|
12
|
+
import { messageOf } from './message-of.js';
|
|
10
13
|
import type { BakedPreviewOpts } from './preview/_resolve-opts.js';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
14
|
+
import { cloudflareAdapter, resolveCloudflareAdapter } from './preview/cloudflare-adapter.js';
|
|
15
|
+
import type { DispatcherExit } from './preview/dispatcher.js';
|
|
16
|
+
import { normalizeTrailingSlash, PREVIEW_ROUTE_SEGMENT, type PreviewServeMode } from './preview/preview-path.js';
|
|
17
|
+
import {
|
|
18
|
+
prerenderedKey,
|
|
19
|
+
previewBuildMode,
|
|
20
|
+
previewChildMode,
|
|
21
|
+
previewChildPrerendered,
|
|
22
|
+
spawnPreviewBuild,
|
|
23
|
+
} from './preview-build.js';
|
|
13
24
|
import { type InheritedOptions, resolveInheritedOptions } from './resolve-options.js';
|
|
14
25
|
import { resolveBuildSiteId } from './site-id.js';
|
|
15
26
|
import { scaffoldSkill } from './skill.js';
|
|
16
|
-
import type { ConlocaCloudOptions } from './types.js';
|
|
27
|
+
import type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';
|
|
17
28
|
|
|
18
29
|
// Re-export the constants that moved out of this module when the preview
|
|
19
30
|
// wiring broke the circular import. Public callers (and tests) import them
|
|
@@ -30,23 +41,28 @@ export { PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG };
|
|
|
30
41
|
* 0. Write the editor page to `dist/_conloca/editor/`: `index.html`, the
|
|
31
42
|
* site's compiled puck config and styles, the MDX sandbox frame and
|
|
32
43
|
* `conloca.json`. Every build does this; the page carries no credential.
|
|
33
|
-
* 1. Only when `previewBuild` is given as an object and
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
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.
|
|
44
|
+
* 1. Only when `previewBuild` is given as an object: D2 spawns the recursive preview build and mirrors the editor
|
|
45
|
+
* page into its client folder; D3 spawns it next to the static site and writes the dispatcher (`d3-build.ts`),
|
|
46
|
+
* failing the build when a failed preview build would leave the site's own on-demand routes unserved; D4 builds
|
|
47
|
+
* it in a separate deploy, not here. The preview build mounts `/_conloca/preview/` and bakes in the repository,
|
|
48
|
+
* site and branch it serves (every pass must match them), Astro's base and the commit it was built from.
|
|
40
49
|
*/
|
|
41
50
|
const VIRTUAL_PREVIEW_OPTS = 'virtual:conloca-preview-opts';
|
|
42
51
|
const RESOLVED_PREVIEW_OPTS = `\0${VIRTUAL_PREVIEW_OPTS}`;
|
|
43
52
|
|
|
53
|
+
/** Where the preview build writes its server and client, outside dist/ (see config:setup). */
|
|
54
|
+
function previewOutDir(previewBuild: PreviewBuildOptions | false | undefined, root: URL): URL {
|
|
55
|
+
return new URL(`${(previewBuild || undefined)?.outDir ?? '.conloca/preview-server'}/`, root);
|
|
56
|
+
}
|
|
57
|
+
|
|
44
58
|
export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegration {
|
|
45
59
|
validateOptions(options);
|
|
46
60
|
const repoUri = resolveRepositoryUri(options.repoUri, process.env);
|
|
47
61
|
// Populated during the preview build's config:setup and read by the virtual
|
|
48
62
|
// module below. Server-only — never reaches a browser bundle.
|
|
49
63
|
let previewOptsModule: BakedPreviewOpts | undefined;
|
|
64
|
+
// The exit values the preview build baked (its config:setup), reported to the site's build for the dispatcher.
|
|
65
|
+
let childExit: DispatcherExit | undefined;
|
|
50
66
|
// The Astro command, recorded in config:setup: only `astro build` starts
|
|
51
67
|
// the preview build, so only it checks the preview adapter at config:done.
|
|
52
68
|
let astroCommand: string | undefined;
|
|
@@ -65,6 +81,10 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
65
81
|
let viteConfig: ViteUserConfig | undefined;
|
|
66
82
|
// Astro's base, as written: the editor page's URLs sit below it.
|
|
67
83
|
let astroBase = '/';
|
|
84
|
+
// Where the site's pages live and how Astro builds them: conloca.json lists the prerendered ones.
|
|
85
|
+
let srcDir: URL | undefined;
|
|
86
|
+
let serverOutput = false;
|
|
87
|
+
let i18n: AstroI18nLocales | undefined;
|
|
68
88
|
// The editor options, settled at config:done: conlocaCMS publishes its
|
|
69
89
|
// channel from its own config:setup, which may run after ours.
|
|
70
90
|
let inherited: InheritedOptions | undefined;
|
|
@@ -72,14 +92,26 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
72
92
|
// the child will use: previewBuild.adapter, else the project's own.
|
|
73
93
|
const previewMode = () =>
|
|
74
94
|
previewBuildMode(options.previewBuild, (options.previewBuild || undefined)?.adapter?.name ?? adapterName);
|
|
95
|
+
// Whether the project has no adapter of its own, read in config:setup before the preview build switches to
|
|
96
|
+
// server output: such a site can use no server islands, so its dispatcher never runs on their route.
|
|
97
|
+
let projectStatic = false;
|
|
98
|
+
// The routes the preview build renders on demand (astro:routes:resolved), as Astro patterns.
|
|
99
|
+
let onDemand: string[] = [];
|
|
100
|
+
// The site's build: the routes it prerendered (astro:routes:resolved), handed to a D3 child.
|
|
101
|
+
let sitePrerendered: string[] = [];
|
|
102
|
+
// A D3 child: the routes its site's build prerendered, which it keeps prerendered (config:setup).
|
|
103
|
+
let keepPrerendered = new Set<string>();
|
|
104
|
+
// The preview build's mode (config:setup): a D4 child of a static site has no site build to ask.
|
|
105
|
+
let childServeMode: PreviewServeMode = 'd4';
|
|
75
106
|
|
|
76
107
|
return {
|
|
77
108
|
name: PACKAGE_NAME,
|
|
78
109
|
hooks: {
|
|
79
|
-
'astro:config:setup': ({ logger, injectRoute, updateConfig, config, addMiddleware, command }) => {
|
|
110
|
+
'astro:config:setup': async ({ logger, injectRoute, updateConfig, config, addMiddleware, command }) => {
|
|
80
111
|
// Optional-chained: unit tests drive this hook with a bare { logger }.
|
|
81
112
|
projectRoot = config?.root;
|
|
82
113
|
astroCommand = command;
|
|
114
|
+
projectStatic = config?.adapter === undefined;
|
|
83
115
|
// The agent skill: write-if-not-exists, fail-soft, and
|
|
84
116
|
// never from the recursive preview child (it would race the parent).
|
|
85
117
|
if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1' && config?.root) {
|
|
@@ -108,6 +140,9 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
108
140
|
'WORKERS_CI_BRANCH, VERCEL_GIT_COMMIT_REF or GITHUB_REF_NAME, or build in a git checkout on a branch)',
|
|
109
141
|
);
|
|
110
142
|
}
|
|
143
|
+
const childMode = previewChildMode(process.env);
|
|
144
|
+
childServeMode = childMode;
|
|
145
|
+
keepPrerendered = previewChildPrerendered(process.env);
|
|
111
146
|
const siteId = resolveBuildSiteId({
|
|
112
147
|
contentRoot: process.env.CONLOCA_CONTENT_ROOT,
|
|
113
148
|
override: options.siteId,
|
|
@@ -149,6 +184,16 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
149
184
|
siteId,
|
|
150
185
|
branch: buildRef.branch,
|
|
151
186
|
base: config.base ?? '/',
|
|
187
|
+
mode: childMode,
|
|
188
|
+
};
|
|
189
|
+
// The dispatcher's exit route answers with these: the values every pass is checked against, already
|
|
190
|
+
// narrowed by the two throws above.
|
|
191
|
+
childExit = {
|
|
192
|
+
repo: repoUri,
|
|
193
|
+
siteId,
|
|
194
|
+
branch: buildRef.branch,
|
|
195
|
+
audience: repoUri,
|
|
196
|
+
...(options.saasIssuer ? { issuer: options.saasIssuer } : {}),
|
|
152
197
|
};
|
|
153
198
|
// Preview-build path: the child build must emit an SSR
|
|
154
199
|
// artifact even when the primary build is fully static. Switch to
|
|
@@ -156,9 +201,12 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
156
201
|
// adapter stays in force when it already has one), and write to a
|
|
157
202
|
// SEPARATE outDir so the child never clobbers the primary dist/.
|
|
158
203
|
const previewBuild = options.previewBuild || {};
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
204
|
+
// A site that names no adapter builds its preview server for Cloudflare Workers: next to it (D3) or apart (D4).
|
|
205
|
+
const adapter =
|
|
206
|
+
previewBuild.adapter ??
|
|
207
|
+
config.adapter ??
|
|
208
|
+
(childMode === 'd2' ? undefined : await cloudflareAdapter(config.root, childMode));
|
|
209
|
+
// Throws for a refused adapter — the parent already checked, this keeps the child honest.
|
|
162
210
|
previewBuildMode(previewBuild, adapter?.name);
|
|
163
211
|
// Astro allows exactly one deployment integration. Adding
|
|
164
212
|
// previewBuild.adapter next to the project's own would make the
|
|
@@ -182,7 +230,7 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
182
230
|
// wholesale static upload of dist/ must never publish the preview
|
|
183
231
|
// server — and Astro clears dist/ at the start of a build, which
|
|
184
232
|
// would wipe a sibling artifact parked inside it.
|
|
185
|
-
const previewOut =
|
|
233
|
+
const previewOut = previewOutDir(previewBuild, config.root);
|
|
186
234
|
// The site's extra config goes through its OWN updateConfig
|
|
187
235
|
// call: Astro deep-merges successive calls (concatenating
|
|
188
236
|
// vite.plugins and integrations), whereas spreading it into the
|
|
@@ -247,7 +295,8 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
247
295
|
// config.adapter into the integration list BEFORE any hook runs,
|
|
248
296
|
// so setting `adapter` alone here is too late for the hooks.)
|
|
249
297
|
// A project that is already SSR keeps its own adapter untouched.
|
|
250
|
-
|
|
298
|
+
// A static site's Cloudflare adapter rides in the same way.
|
|
299
|
+
...(adapter !== undefined && adapter !== config.adapter ? { adapter, integrations: [adapter] } : {}),
|
|
251
300
|
});
|
|
252
301
|
}
|
|
253
302
|
},
|
|
@@ -275,12 +324,33 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
275
324
|
*/
|
|
276
325
|
'astro:route:setup': ({ route, logger }) => {
|
|
277
326
|
if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') return;
|
|
278
|
-
|
|
279
|
-
|
|
327
|
+
const cms = route.component.endsWith('/internal/page-handler.astro');
|
|
328
|
+
const entry = /preview-handler(\.astro)?$/u.test(route.component);
|
|
329
|
+
// `route` (the pattern) and `type` exist at runtime but are absent from the public RouteOptions type.
|
|
330
|
+
const pattern = 'route' in route && typeof route.route === 'string' ? route.route : '';
|
|
331
|
+
// A D3 child keeps prerendered what its static site's build prerendered, endpoints included: on demand, a
|
|
332
|
+
// getStaticPaths route would lose its props, and the dispatcher would have to run on it in production. Its
|
|
333
|
+
// own on-demand routes (and every route of a D2 child) keep their own setting.
|
|
334
|
+
if (!cms && keepPrerendered.has(prerenderedKey(pattern, route.component))) {
|
|
335
|
+
route.prerender = true;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
// Endpoints keep their prerendered data files: they emit no HTML
|
|
280
339
|
// to intercept, and one built from getStaticPaths would break on demand.
|
|
281
340
|
const routeType = (route as { type?: string }).type;
|
|
341
|
+
// A static site's separate preview deploy (D4) has no site build to ask, but every page of the site was
|
|
342
|
+
// prerendered: they stay so, or a getStaticPaths page would render on demand without its props.
|
|
343
|
+
if (
|
|
344
|
+
projectStatic &&
|
|
345
|
+
childServeMode === 'd4' &&
|
|
346
|
+
!cms &&
|
|
347
|
+
!entry &&
|
|
348
|
+
(routeType === undefined || routeType === 'page')
|
|
349
|
+
) {
|
|
350
|
+
route.prerender = true;
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
282
353
|
if (routeType !== undefined && routeType !== 'page') return;
|
|
283
|
-
if (route.prerender === false) return;
|
|
284
354
|
// ONLY the CMS page routes go on demand. Forcing every route stripped
|
|
285
355
|
// the getStaticPaths path-space partitioning: two root catch-alls (the
|
|
286
356
|
// CMS pages route and e.g. Starlight's docs route) both match any path
|
|
@@ -289,27 +359,70 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
289
359
|
// keep their static output (served by the adapter before the app), and
|
|
290
360
|
// App.match falls through a prerendered dynamic match to the first
|
|
291
361
|
// on-demand route — exactly the CMS handler for CMS pathnames.
|
|
292
|
-
if (!route.
|
|
362
|
+
if (!cms || route.prerender === false) return;
|
|
293
363
|
route.prerender = false;
|
|
294
364
|
logger.debug(`preview build: forcing on-demand rendering for ${route.component}`);
|
|
295
365
|
},
|
|
296
|
-
'astro:
|
|
366
|
+
'astro:routes:resolved': ({ routes }) => {
|
|
367
|
+
if (process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
|
|
368
|
+
sitePrerendered = routes
|
|
369
|
+
.filter((route) => route.isPrerendered)
|
|
370
|
+
.map((route) => prerenderedKey(route.pattern, route.entrypoint));
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
// Astro injects the server-islands route whenever an adapter is set, but refuses islands without one: a static
|
|
374
|
+
// site uses none, so its dispatcher must not run on that route.
|
|
375
|
+
const used = projectStatic ? routes.filter((route) => route.pattern !== '/_server-islands/[name]') : routes;
|
|
376
|
+
onDemand = onDemandPatterns(used);
|
|
377
|
+
},
|
|
378
|
+
'astro:config:done': ({ config, logger }) => {
|
|
297
379
|
adapterName = config.adapter?.name;
|
|
298
380
|
viteConfig = config.vite;
|
|
299
381
|
astroBase = config.base ?? '/';
|
|
382
|
+
srcDir = config.srcDir;
|
|
383
|
+
serverOutput = config.output === 'server';
|
|
384
|
+
i18n = config.i18n;
|
|
300
385
|
inherited = resolveInheritedOptions(options, readEditorDescriptors());
|
|
301
386
|
// A refused or missing preview adapter fails `astro build` here,
|
|
302
387
|
// before the site builds, rather than after it. `astro dev`, `sync`
|
|
303
388
|
// and `preview` never start the preview build, so they are left
|
|
304
389
|
// alone. The child build checks its own.
|
|
305
|
-
if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1')
|
|
390
|
+
if (astroCommand === 'build' && process.env[PREVIEW_BUILD_ENV_FLAG] !== '1') {
|
|
391
|
+
const mode = previewMode();
|
|
392
|
+
// D3 builds its preview server with @astrojs/cloudflare: missing, the build fails here, before the site builds.
|
|
393
|
+
if (mode === 'd3' && projectRoot !== undefined) resolveCloudflareAdapter(fileURLToPath(projectRoot));
|
|
394
|
+
if (mode === 'd2' && adapterName === undefined) {
|
|
395
|
+
logger.warn(
|
|
396
|
+
'previewBuild.adapter on a static site serves drafts from the deployed preview server; remove ' +
|
|
397
|
+
'previewBuild.adapter to serve them next to the static site on Cloudflare Workers instead',
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
306
401
|
},
|
|
307
|
-
'astro:build:done': async ({ dir, logger }) => {
|
|
402
|
+
'astro:build:done': async ({ dir, logger, pages }) => {
|
|
308
403
|
if (process.env[PREVIEW_BUILD_ENV_FLAG] === '1') {
|
|
309
|
-
// The recursive preview build sets this flag on the child
|
|
310
|
-
//
|
|
311
|
-
// the parent, which mirrors its own copy in, so we short-circuit.
|
|
404
|
+
// The recursive preview build sets this flag on the child Astro process. Writing the editor page there
|
|
405
|
+
// again would race the parent, which writes its own; the child reports only what the parent reads.
|
|
312
406
|
logger.info('skipping the editor page: recursive preview build detected');
|
|
407
|
+
if (previewChildMode(process.env) === 'd4') {
|
|
408
|
+
await emitPreviewServerInfo(fileURLToPath(dir), {
|
|
409
|
+
root: fileURLToPath(projectRoot ?? dir),
|
|
410
|
+
repoUri,
|
|
411
|
+
siteIdOverride: options.siteId,
|
|
412
|
+
logger,
|
|
413
|
+
});
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (projectRoot === undefined) return;
|
|
417
|
+
// config:setup records the exit values in the child (below), or throws before the build starts.
|
|
418
|
+
const exit = childExit;
|
|
419
|
+
if (exit === undefined) throw new Error(`${PACKAGE_NAME}: the preview build recorded no exit values`);
|
|
420
|
+
const root = astroBase.replace(/\/+$/u, '');
|
|
421
|
+
await writePreviewRoutes(fileURLToPath(previewOutDir(options.previewBuild, projectRoot)), {
|
|
422
|
+
prerendered: (pages ?? []).map(({ pathname }) => normalizeTrailingSlash(`${root}/${pathname}`)),
|
|
423
|
+
onDemand: onDemand.map((pattern) => workerFirstPattern(pattern, astroBase)),
|
|
424
|
+
exit,
|
|
425
|
+
});
|
|
313
426
|
return;
|
|
314
427
|
}
|
|
315
428
|
|
|
@@ -322,6 +435,7 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
322
435
|
);
|
|
323
436
|
}
|
|
324
437
|
|
|
438
|
+
const mode = previewMode();
|
|
325
439
|
// The editor page: every build writes it.
|
|
326
440
|
await emitEditorPage({
|
|
327
441
|
dir: fileURLToPath(dir),
|
|
@@ -332,23 +446,45 @@ export function conlocaCloud(options: ConlocaCloudOptions = {}): AstroIntegratio
|
|
|
332
446
|
inherited,
|
|
333
447
|
repoUri,
|
|
334
448
|
siteIdOverride: options.siteId,
|
|
449
|
+
previewMode: mode,
|
|
450
|
+
pagesDir: fileURLToPath(new URL('pages/', srcDir ?? new URL('src/', projectRoot))),
|
|
451
|
+
serverOutput,
|
|
452
|
+
i18n,
|
|
335
453
|
logger,
|
|
336
454
|
});
|
|
337
455
|
|
|
338
|
-
// Strict opt-in: only a previewBuild given as an object starts the
|
|
339
|
-
// second build.
|
|
456
|
+
// Strict opt-in: only a previewBuild given as an object starts the second build. D4 builds it elsewhere.
|
|
340
457
|
const previewBuild = options.previewBuild || undefined;
|
|
341
|
-
if (previewBuild === undefined ||
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
458
|
+
if (previewBuild === undefined || mode === 'off' || mode === 'd4') return;
|
|
459
|
+
const previewOut = previewOutDir(previewBuild, projectRoot);
|
|
460
|
+
if (mode === 'd2') {
|
|
461
|
+
await spawnPreviewBuild(previewBuild, 'd2');
|
|
462
|
+
// The child build cannot write the editor files itself (it
|
|
463
|
+
// short-circuits this hook — see the recursion guard above), but in
|
|
464
|
+
// a deployment that serves the site and the preview from one
|
|
465
|
+
// Cloudflare Worker its client dir is THE asset set serving the site,
|
|
466
|
+
// so the editor files must be there too. Mirror them from this build's dist.
|
|
467
|
+
await mirrorEditorPage(fileURLToPath(dir), fileURLToPath(new URL('client/', previewOut)));
|
|
468
|
+
logger.info('editor page mirrored into the preview client dir');
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
// D3: a failed preview build is isolated unless its server also serves the live site (finishD3Build decides).
|
|
472
|
+
let built = true;
|
|
473
|
+
try {
|
|
474
|
+
await spawnPreviewBuild({ ...previewBuild, required: true }, 'd3', sitePrerendered);
|
|
475
|
+
} catch (error) {
|
|
476
|
+
built = false;
|
|
477
|
+
logger.warn(`the preview build failed: ${messageOf(error)}`);
|
|
478
|
+
}
|
|
479
|
+
await finishD3Build({
|
|
480
|
+
root: fileURLToPath(projectRoot),
|
|
481
|
+
dist: fileURLToPath(dir),
|
|
482
|
+
previewOut: fileURLToPath(previewOut),
|
|
483
|
+
base: astroBase,
|
|
484
|
+
endpoint: options.endpoint ?? DEFAULT_EDITOR_ENDPOINT,
|
|
485
|
+
built,
|
|
486
|
+
logger,
|
|
487
|
+
});
|
|
352
488
|
},
|
|
353
489
|
},
|
|
354
490
|
};
|
package/src/preview/_dispatch.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { PreviewContext } from './middleware.js';
|
|
|
15
15
|
* answers.
|
|
16
16
|
* - `redirect` — branch installed a redirect at the page's path; callers
|
|
17
17
|
* issue a 302 (we deliberately downgrade 301 to 302 — see fetchPageStatus).
|
|
18
|
+
* - an ended share link (`grant-revoked`, `grant-expired`, `draft-published`, `draft-discarded`) — Conloca answers 410 and names who shared the link; the site shows that page, never the published one.
|
|
18
19
|
*
|
|
19
20
|
* The verdict-to-response mapping lives in the site middleware
|
|
20
21
|
* (`./site-middleware.ts`), which renders through the site's own route.
|
|
@@ -23,7 +24,22 @@ export type PageStatus =
|
|
|
23
24
|
| { kind: 'unchanged' }
|
|
24
25
|
| { kind: 'changed'; embedded: ReadonlyMap<string, LocalizedEntry> }
|
|
25
26
|
| { kind: 'deleted' }
|
|
26
|
-
| { kind: 'redirect'; target: string }
|
|
27
|
+
| { kind: 'redirect'; target: string }
|
|
28
|
+
| { kind: ShareEndedKind; sharedBy: string };
|
|
29
|
+
|
|
30
|
+
/** Why a share link no longer opens: turned off, expired, or its draft was published or discarded. */
|
|
31
|
+
export type ShareEndedKind = 'grant-revoked' | 'grant-expired' | 'draft-published' | 'draft-discarded';
|
|
32
|
+
|
|
33
|
+
const SHARE_ENDED: ReadonlySet<string> = new Set([
|
|
34
|
+
'grant-revoked',
|
|
35
|
+
'grant-expired',
|
|
36
|
+
'draft-published',
|
|
37
|
+
'draft-discarded',
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
export function isShareEndedKind(value: string): value is ShareEndedKind {
|
|
41
|
+
return SHARE_ENDED.has(value);
|
|
42
|
+
}
|
|
27
43
|
|
|
28
44
|
interface FetchPageStatusInput {
|
|
29
45
|
saasEndpoint: string;
|
|
@@ -71,6 +87,10 @@ export async function fetchPageStatus(input: FetchPageStatusInput): Promise<Page
|
|
|
71
87
|
const data: unknown = await response.json();
|
|
72
88
|
return { kind: 'changed', embedded: decodeEmbedded(data) };
|
|
73
89
|
}
|
|
90
|
+
if (response.status === 410) {
|
|
91
|
+
const ended = await shareEndedOf(response);
|
|
92
|
+
if (ended !== null) return ended;
|
|
93
|
+
}
|
|
74
94
|
throw new Error(`preview page-status ${input.path}: ${response.status}`);
|
|
75
95
|
}
|
|
76
96
|
|
|
@@ -103,3 +123,18 @@ function isLocalizedEntry(value: unknown): value is LocalizedEntry {
|
|
|
103
123
|
const l = v.localized as { etag?: unknown; locale?: unknown; content?: unknown };
|
|
104
124
|
return typeof l.etag === 'string' && typeof l.locale === 'string' && typeof l.content === 'object';
|
|
105
125
|
}
|
|
126
|
+
|
|
127
|
+
/** The ended-link verdict a 410 names, or null when the body is not one. */
|
|
128
|
+
export async function shareEndedOf(response: Response): Promise<{ kind: ShareEndedKind; sharedBy: string } | null> {
|
|
129
|
+
let body: unknown;
|
|
130
|
+
try {
|
|
131
|
+
body = await response.json();
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
if (typeof body !== 'object' || body === null) return null;
|
|
136
|
+
const error = 'error' in body ? body.error : undefined;
|
|
137
|
+
const sharedBy = 'sharedBy' in body ? body.sharedBy : undefined;
|
|
138
|
+
if (typeof error !== 'string' || !isShareEndedKind(error)) return null;
|
|
139
|
+
return { kind: error, sharedBy: typeof sharedBy === 'string' ? sharedBy : '' };
|
|
140
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { PreviewMiddlewareOptions } from './middleware.js';
|
|
2
|
+
import type { PreviewServeMode } from './preview-path.js';
|
|
2
3
|
|
|
3
4
|
/** Values the preview build can bake into the artifact at build time. */
|
|
4
5
|
export interface BakedPreviewOpts {
|
|
@@ -13,6 +14,8 @@ export interface BakedPreviewOpts {
|
|
|
13
14
|
branch?: string;
|
|
14
15
|
/** Astro's `base` at build time. */
|
|
15
16
|
base?: string;
|
|
17
|
+
/** How this build serves previews (`d2` when not baked). */
|
|
18
|
+
mode?: PreviewServeMode;
|
|
16
19
|
}
|
|
17
20
|
|
|
18
21
|
/** A value only the build can bake; the deployment cannot supply it. */
|
|
@@ -56,14 +59,16 @@ export function resolveFromBaked(
|
|
|
56
59
|
`set ${envName} on the deployment to override.`,
|
|
57
60
|
);
|
|
58
61
|
};
|
|
62
|
+
const saasIssuer = readEnvVar('CONLOCA_SAAS_ISSUER') || baked.saasIssuer;
|
|
59
63
|
return {
|
|
60
64
|
saasEndpoint: pick('CONLOCA_SAAS_ENDPOINT', baked.saasEndpoint),
|
|
61
|
-
saasIssuer
|
|
65
|
+
...(saasIssuer ? { saasIssuer } : {}),
|
|
62
66
|
saasAudience: pick('CONLOCA_SAAS_AUDIENCE', baked.saasAudience),
|
|
63
67
|
repo: bakedOnly('repo', baked.repo),
|
|
64
68
|
siteId: bakedOnly('siteId', baked.siteId),
|
|
65
69
|
branch: bakedOnly('branch', baked.branch),
|
|
66
70
|
base: baked.base || '/',
|
|
71
|
+
mode: baked.mode ?? 'd2',
|
|
67
72
|
// Optional: an artifact built before this was baked has none, and the
|
|
68
73
|
// endpoint then falls back to the branch's registered build.
|
|
69
74
|
...(baked.buildCommit ? { buildCommit: baked.buildCommit } : {}),
|
package/src/preview/banner.ts
CHANGED
|
@@ -15,22 +15,33 @@ import type { PreviewContext } from './middleware.js';
|
|
|
15
15
|
* encodes both `"` and `</script>` sequences safely, which is the
|
|
16
16
|
* canonical way to embed server data in a same-origin inline script.
|
|
17
17
|
*/
|
|
18
|
-
export function getBannerScriptText(
|
|
18
|
+
export function getBannerScriptText(
|
|
19
|
+
ctx: Pick<PreviewContext, 'branch' | 'grant'>,
|
|
20
|
+
endpoint?: string,
|
|
21
|
+
exitPath?: string,
|
|
22
|
+
shareUrl?: string,
|
|
23
|
+
pagePath?: string,
|
|
24
|
+
): string {
|
|
19
25
|
// Serialize then patch the `<` character that JSON.stringify does NOT
|
|
20
26
|
// escape. Browsers terminate inline scripts on `</script>` regardless of
|
|
21
27
|
// string-literal context, so a branch name containing `</script>` would
|
|
22
28
|
// break out of the script tag. Replacing `</` with `<\/` is the standard
|
|
23
29
|
// mitigation (also done by ASP.NET's Json.Encode, Rails' j helper, etc.).
|
|
24
30
|
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
// Only the branch name and public addresses reach the page, never the pass:
|
|
32
|
+
// every script on the page, third-party tags included, could read it. A
|
|
33
|
+
// share viewer gets who shared the draft and when the link expires instead
|
|
34
|
+
// of the editor links. `undefined` values drop out of the JSON.
|
|
35
|
+
const embedded =
|
|
36
|
+
ctx.grant === undefined
|
|
37
|
+
? { branch: ctx.branch, endpoint, exitPath, shareUrl, path: pagePath }
|
|
38
|
+
: {
|
|
39
|
+
branch: ctx.branch,
|
|
40
|
+
exitPath,
|
|
41
|
+
path: pagePath,
|
|
42
|
+
viewer: { sharedBy: ctx.grant.sharedBy, expiresAt: ctx.grant.expiresAt },
|
|
43
|
+
};
|
|
44
|
+
const ctxJson = JSON.stringify(embedded).replace(/</g, '\\u003c');
|
|
34
45
|
return [
|
|
35
46
|
`var __conlocaPreview = ${ctxJson};`,
|
|
36
47
|
"var __conlocaCollapseKey = 'conloca.preview.collapsed';",
|
|
@@ -40,34 +51,24 @@ export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exit
|
|
|
40
51
|
" var host = document.createElement('div');",
|
|
41
52
|
" host.id = 'conloca-preview-banner';",
|
|
42
53
|
" host.style.cssText = 'position:fixed;bottom:16px;right:16px;z-index:2147483647;font-family:system-ui,sans-serif;background:#111;color:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.35);padding:8px 12px;font-size:13px;display:flex;gap:12px;align-items:center;';",
|
|
43
|
-
" var label = document.createElement('span');
|
|
54
|
+
" var label = document.createElement('span');",
|
|
55
|
+
' if (__conlocaPreview.viewer) {',
|
|
56
|
+
' var days = Math.max(1, Math.ceil((__conlocaPreview.viewer.expiresAt * 1000 - Date.now()) / 86400000));',
|
|
57
|
+
" label.textContent = 'Draft: ' + __conlocaPreview.branch + (__conlocaPreview.viewer.sharedBy ? ' · Shared by ' + __conlocaPreview.viewer.sharedBy : '') + ' · Expires in ' + days + (days === 1 ? ' day' : ' days');",
|
|
58
|
+
" } else { label.textContent = 'Preview: ' + __conlocaPreview.branch; }",
|
|
59
|
+
' host.appendChild(label);',
|
|
44
60
|
// "Edit" reuses the landing page's `/login?return=` contract:
|
|
45
61
|
// the endpoint's login route already knows how to send an authenticated
|
|
46
62
|
// session into the editor for the requested page.
|
|
47
63
|
" var edit = document.createElement('a'); edit.textContent = 'Edit'; edit.style.color = '#9cf';",
|
|
48
|
-
" if (__conlocaPreview.endpoint) { edit.href = __conlocaPreview.endpoint + '/login?return=' + encodeURIComponent(location.pathname); host.appendChild(edit); }",
|
|
64
|
+
" if (__conlocaPreview.endpoint) { edit.href = __conlocaPreview.endpoint + '/login?return=' + encodeURIComponent(__conlocaPreview.path || location.pathname); host.appendChild(edit); }",
|
|
65
|
+
// Share opens the editor's share dialog for this page in a new tab.
|
|
66
|
+
" if (__conlocaPreview.shareUrl) { var share = document.createElement('a'); share.textContent = 'Share'; share.style.color = '#9cf'; share.href = __conlocaPreview.shareUrl; share.target = '_blank'; share.rel = 'noopener'; host.appendChild(share); }",
|
|
49
67
|
// "Exit Preview" must round-trip the server: the cookie is HttpOnly, so
|
|
50
68
|
// only a Set-Cookie response can expire it. `to` returns the visitor to
|
|
51
69
|
// this page, now published.
|
|
52
70
|
" var exitLink = document.createElement('a'); exitLink.textContent = 'Exit Preview'; exitLink.style.color = '#9cf';",
|
|
53
|
-
" if (__conlocaPreview.exitPath) { exitLink.href = __conlocaPreview.exitPath + '?to=' + encodeURIComponent(location.pathname); host.appendChild(exitLink); }",
|
|
54
|
-
" var share = document.createElement('button'); share.type = 'button'; share.textContent = 'Share Preview'; share.style.cssText = 'background:#333;color:#fff;border:1px solid #555;border-radius:4px;padding:2px 8px;cursor:pointer;'; host.appendChild(share);",
|
|
55
|
-
// "Share Preview": mint a fresh shareable link via GET {endpoint}/preview/share
|
|
56
|
-
// and copy it to the clipboard. Bearer-authenticated with the preview JWT
|
|
57
|
-
// (the route reads Authorization/?token=, never the HttpOnly cookie). The
|
|
58
|
-
// button briefly reflects the outcome, then restores.
|
|
59
|
-
" share.addEventListener('click', function () {",
|
|
60
|
-
' if (!__conlocaPreview.endpoint) return;',
|
|
61
|
-
" var shareUrl = __conlocaPreview.endpoint + '/preview/share?branch=' + encodeURIComponent(__conlocaPreview.branch);",
|
|
62
|
-
' var previousLabel = share.textContent;',
|
|
63
|
-
' share.disabled = true;',
|
|
64
|
-
" fetch(shareUrl, { headers: { authorization: 'Bearer ' + __conlocaPreview.jwt } })",
|
|
65
|
-
" .then(function (res) { if (!res.ok) throw new Error('share ' + res.status); return res.json(); })",
|
|
66
|
-
" .then(function (data) { if (!data || typeof data.url !== 'string') throw new Error('missing url'); return navigator.clipboard.writeText(data.url); })",
|
|
67
|
-
" .then(function () { share.textContent = 'Link copied'; })",
|
|
68
|
-
" .catch(function () { share.textContent = 'Copy failed'; })",
|
|
69
|
-
' .then(function () { setTimeout(function () { share.textContent = previousLabel; share.disabled = false; }, 2000); });',
|
|
70
|
-
' });',
|
|
71
|
+
" if (__conlocaPreview.exitPath) { exitLink.href = __conlocaPreview.exitPath + '?to=' + encodeURIComponent(__conlocaPreview.path || location.pathname); host.appendChild(exitLink); }",
|
|
71
72
|
" var collapse = document.createElement('button'); collapse.type = 'button'; collapse.textContent = __conlocaIsCollapsed() ? '+' : '-'; collapse.style.cssText = 'background:transparent;color:#fff;border:none;cursor:pointer;font-size:16px;line-height:1;'; host.appendChild(collapse);",
|
|
72
73
|
" collapse.addEventListener('click', function () { var c = !__conlocaIsCollapsed(); __conlocaSetCollapsed(c); host.style.display = c ? 'none' : ''; });",
|
|
73
74
|
" if (__conlocaIsCollapsed()) host.style.display = 'none';",
|
|
@@ -77,18 +78,37 @@ export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exit
|
|
|
77
78
|
].join(' ');
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
const ROBOTS_META = '<meta name="robots" content="noindex, nofollow">';
|
|
82
|
+
// Any `<meta name=robots …>`, whatever the case, quoting or attribute order; `robots-extra` and `googlebot` are other names.
|
|
83
|
+
const SITE_ROBOTS_META_RE = /<meta\b[^>]*?\sname\s*=\s*["']?robots(?=["'\s/>])[^>]*>/giu;
|
|
84
|
+
|
|
80
85
|
/**
|
|
81
|
-
* Returns `html` with the preview banner script
|
|
82
|
-
*
|
|
86
|
+
* Returns `html` with the preview banner script (or, on a share pass, the
|
|
87
|
+
* viewer banner) injected before the closing `</body>` tag, and the page's robots metas replaced by one
|
|
88
|
+
* `<meta robots noindex>`. The site's own robots meta (often
|
|
89
|
+
* `index, follow`) must not sit next to the preview's. Ours takes the first
|
|
90
|
+
* one's place, or goes before `</body>` when the page has none.
|
|
83
91
|
*
|
|
84
|
-
* The injection uses `String.prototype.replace` with a string
|
|
85
|
-
* (not a regex), so only the FIRST `</body>` match is rewritten.
|
|
86
|
-
* matters because a misconfigured renderer can emit malformed HTML with
|
|
87
|
-
* multiple `</body>` tags; we never want to inject the banner more than
|
|
88
|
-
*
|
|
92
|
+
* The `</body>` injection uses `String.prototype.replace` with a string
|
|
93
|
+
* argument (not a regex), so only the FIRST `</body>` match is rewritten.
|
|
94
|
+
* That matters because a misconfigured renderer can emit malformed HTML with
|
|
95
|
+
* multiple `</body>` tags; we never want to inject the banner more than once
|
|
96
|
+
* per response.
|
|
89
97
|
*/
|
|
90
|
-
export function injectPreviewBanner(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
98
|
+
export function injectPreviewBanner(
|
|
99
|
+
html: string,
|
|
100
|
+
ctx: Pick<PreviewContext, 'branch' | 'grant'>,
|
|
101
|
+
endpoint?: string,
|
|
102
|
+
exitPath?: string,
|
|
103
|
+
shareUrl?: string,
|
|
104
|
+
pagePath?: string,
|
|
105
|
+
): string {
|
|
106
|
+
const script = `<script>${getBannerScriptText(ctx, endpoint, exitPath, shareUrl, pagePath)}</script>`;
|
|
107
|
+
let replaced = false;
|
|
108
|
+
const page = html.replace(SITE_ROBOTS_META_RE, () => {
|
|
109
|
+
const first = !replaced;
|
|
110
|
+
replaced = true;
|
|
111
|
+
return first ? ROBOTS_META : '';
|
|
112
|
+
});
|
|
113
|
+
return page.replace('</body>', `${replaced ? '' : ROBOTS_META}${script}</body>`);
|
|
94
114
|
}
|