@conloca/cloud-astro 0.0.0-bootstrap.0 → 0.2.1
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 +327 -2
- package/dist/src/build-commit.d.ts +19 -0
- package/dist/src/build-commit.d.ts.map +1 -0
- package/dist/src/build-commit.js +6 -0
- package/dist/src/build-commit.js.map +1 -0
- package/dist/src/bundle.d.ts +173 -0
- package/dist/src/bundle.d.ts.map +1 -0
- package/dist/src/bundle.js +413 -0
- package/dist/src/bundle.js.map +1 -0
- package/dist/src/component-manifest.d.ts +29 -0
- package/dist/src/component-manifest.d.ts.map +1 -0
- package/dist/src/component-manifest.js +53 -0
- package/dist/src/component-manifest.js.map +1 -0
- package/dist/src/constants.d.ts +26 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +26 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/descriptors.d.ts +25 -0
- package/dist/src/descriptors.d.ts.map +1 -0
- package/dist/src/descriptors.js +65 -0
- package/dist/src/descriptors.js.map +1 -0
- package/dist/src/discovery.d.ts +58 -0
- package/dist/src/discovery.d.ts.map +1 -0
- package/dist/src/discovery.js +133 -0
- package/dist/src/discovery.js.map +1 -0
- package/dist/src/doctor/checks-live.d.ts +15 -0
- package/dist/src/doctor/checks-live.d.ts.map +1 -0
- package/dist/src/doctor/checks-live.js +229 -0
- package/dist/src/doctor/checks-live.js.map +1 -0
- package/dist/src/doctor/checks-offline.d.ts +36 -0
- package/dist/src/doctor/checks-offline.d.ts.map +1 -0
- package/dist/src/doctor/checks-offline.js +301 -0
- package/dist/src/doctor/checks-offline.js.map +1 -0
- package/dist/src/doctor/config-scan.d.ts +55 -0
- package/dist/src/doctor/config-scan.d.ts.map +1 -0
- package/dist/src/doctor/config-scan.js +178 -0
- package/dist/src/doctor/config-scan.js.map +1 -0
- package/dist/src/doctor/run.d.ts +4 -0
- package/dist/src/doctor/run.d.ts.map +1 -0
- package/dist/src/doctor/run.js +29 -0
- package/dist/src/doctor/run.js.map +1 -0
- package/dist/src/doctor/types.d.ts +60 -0
- package/dist/src/doctor/types.d.ts.map +1 -0
- package/dist/src/doctor/types.js +18 -0
- package/dist/src/doctor/types.js.map +1 -0
- package/dist/src/doctor.d.ts +9 -0
- package/dist/src/doctor.d.ts.map +1 -0
- package/dist/src/doctor.js +12 -0
- package/dist/src/doctor.js.map +1 -0
- package/dist/src/git.d.ts +38 -0
- package/dist/src/git.d.ts.map +1 -0
- package/dist/src/git.js +43 -0
- package/dist/src/git.js.map +1 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +7 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/integration.d.ts +6 -0
- package/dist/src/integration.d.ts.map +1 -0
- package/dist/src/integration.js +532 -0
- package/dist/src/integration.js.map +1 -0
- package/dist/src/message-of.d.ts +3 -0
- package/dist/src/message-of.d.ts.map +1 -0
- package/dist/src/message-of.js +5 -0
- package/dist/src/message-of.js.map +1 -0
- package/dist/src/node.d.ts +3 -0
- package/dist/src/node.d.ts.map +1 -0
- package/dist/src/node.js +4 -0
- package/dist/src/node.js.map +1 -0
- package/dist/src/package-version.d.ts +7 -0
- package/dist/src/package-version.d.ts.map +1 -0
- package/dist/src/package-version.js +17 -0
- package/dist/src/package-version.js.map +1 -0
- package/dist/src/preview/_dispatch.d.ts +52 -0
- package/dist/src/preview/_dispatch.d.ts.map +1 -0
- package/dist/src/preview/_dispatch.js +70 -0
- package/dist/src/preview/_dispatch.js.map +1 -0
- package/dist/src/preview/_resolve-opts.d.ts +28 -0
- package/dist/src/preview/_resolve-opts.d.ts.map +1 -0
- package/dist/src/preview/_resolve-opts.js +70 -0
- package/dist/src/preview/_resolve-opts.js.map +1 -0
- package/dist/src/preview/banner.d.ts +29 -0
- package/dist/src/preview/banner.d.ts.map +1 -0
- package/dist/src/preview/banner.js +94 -0
- package/dist/src/preview/banner.js.map +1 -0
- package/dist/src/preview/content-api.d.ts +110 -0
- package/dist/src/preview/content-api.d.ts.map +1 -0
- package/dist/src/preview/content-api.js +216 -0
- package/dist/src/preview/content-api.js.map +1 -0
- package/dist/src/preview/cookie.d.ts +36 -0
- package/dist/src/preview/cookie.d.ts.map +1 -0
- package/dist/src/preview/cookie.js +59 -0
- package/dist/src/preview/cookie.js.map +1 -0
- package/dist/src/preview/headers.d.ts +25 -0
- package/dist/src/preview/headers.d.ts.map +1 -0
- package/dist/src/preview/headers.js +31 -0
- package/dist/src/preview/headers.js.map +1 -0
- package/dist/src/preview/landing.d.ts +22 -0
- package/dist/src/preview/landing.d.ts.map +1 -0
- package/dist/src/preview/landing.js +70 -0
- package/dist/src/preview/landing.js.map +1 -0
- package/dist/src/preview/middleware.d.ts +112 -0
- package/dist/src/preview/middleware.d.ts.map +1 -0
- package/dist/src/preview/middleware.js +197 -0
- package/dist/src/preview/middleware.js.map +1 -0
- package/dist/src/preview/preview-path.d.ts +21 -0
- package/dist/src/preview/preview-path.d.ts.map +1 -0
- package/dist/src/preview/preview-path.js +29 -0
- package/dist/src/preview/preview-path.js.map +1 -0
- package/dist/src/preview/satteri-workerd.d.ts +17 -0
- package/dist/src/preview/satteri-workerd.d.ts.map +1 -0
- package/dist/src/preview/satteri-workerd.js +18 -0
- package/dist/src/preview/satteri-workerd.js.map +1 -0
- package/dist/src/preview/site-middleware.d.ts +69 -0
- package/dist/src/preview/site-middleware.d.ts.map +1 -0
- package/dist/src/preview/site-middleware.js +159 -0
- package/dist/src/preview/site-middleware.js.map +1 -0
- package/dist/src/preview/workerd-shim.d.ts +19 -0
- package/dist/src/preview/workerd-shim.d.ts.map +1 -0
- package/dist/src/preview/workerd-shim.js +33 -0
- package/dist/src/preview/workerd-shim.js.map +1 -0
- package/dist/src/preview-build.d.ts +71 -0
- package/dist/src/preview-build.d.ts.map +1 -0
- package/dist/src/preview-build.js +115 -0
- package/dist/src/preview-build.js.map +1 -0
- package/dist/src/preview.d.ts +6 -0
- package/dist/src/preview.d.ts.map +1 -0
- package/dist/src/preview.js +12 -0
- package/dist/src/preview.js.map +1 -0
- package/dist/src/register.d.ts +98 -0
- package/dist/src/register.d.ts.map +1 -0
- package/dist/src/register.js +103 -0
- package/dist/src/register.js.map +1 -0
- package/dist/src/repository.d.ts +18 -0
- package/dist/src/repository.d.ts.map +1 -0
- package/dist/src/repository.js +46 -0
- package/dist/src/repository.js.map +1 -0
- package/dist/src/site-id.d.ts +18 -0
- package/dist/src/site-id.d.ts.map +1 -0
- package/dist/src/site-id.js +70 -0
- package/dist/src/site-id.js.map +1 -0
- package/dist/src/site-middleware.d.ts +18 -0
- package/dist/src/site-middleware.d.ts.map +1 -0
- package/dist/src/site-middleware.js +47 -0
- package/dist/src/site-middleware.js.map +1 -0
- package/dist/src/skill.d.ts +26 -0
- package/dist/src/skill.d.ts.map +1 -0
- package/dist/src/skill.js +67 -0
- package/dist/src/skill.js.map +1 -0
- package/dist/src/types.d.ts +125 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/package.json +170 -5
- package/src/build-commit.ts +22 -0
- package/src/bundle.ts +563 -0
- package/src/component-manifest.ts +75 -0
- package/src/constants.ts +28 -0
- package/src/descriptors.ts +92 -0
- package/src/discovery.ts +183 -0
- package/src/doctor/checks-live.ts +324 -0
- package/src/doctor/checks-offline.ts +325 -0
- package/src/doctor/config-scan.ts +205 -0
- package/src/doctor/run.ts +39 -0
- package/src/doctor/types.ts +71 -0
- package/src/doctor.ts +14 -0
- package/src/git.ts +66 -0
- package/src/index.ts +8 -0
- package/src/integration.ts +595 -0
- package/src/message-of.ts +4 -0
- package/src/node.ts +5 -0
- package/src/package-version.ts +16 -0
- package/src/preview/_dispatch.ts +101 -0
- package/src/preview/_resolve-opts.ts +84 -0
- package/src/preview/banner.ts +96 -0
- package/src/preview/content-api.ts +293 -0
- package/src/preview/cookie.ts +54 -0
- package/src/preview/headers.ts +30 -0
- package/src/preview/landing.ts +73 -0
- package/src/preview/middleware.ts +303 -0
- package/src/preview/preview-path.ts +28 -0
- package/src/preview/satteri-workerd.ts +24 -0
- package/src/preview/site-middleware.ts +209 -0
- package/src/preview/workerd-shim.ts +31 -0
- package/src/preview-build.ts +147 -0
- package/src/preview-handler.astro +55 -0
- package/src/preview-handler.d.ts +6 -0
- package/src/preview.ts +22 -0
- package/src/register.ts +180 -0
- package/src/repository.ts +54 -0
- package/src/site-id.ts +86 -0
- package/src/site-middleware.ts +55 -0
- package/src/skill/SKILL.md +69 -0
- package/src/skill.ts +66 -0
- package/src/types.ts +127 -0
- package/src/virtual-modules.d.ts +51 -0
package/src/node.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Node-only build-hook entry for `@conloca/cloud-astro`. The site wires
|
|
2
|
+
// the integration into `astro.config.mjs` via this subpath.
|
|
3
|
+
|
|
4
|
+
export { conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
|
|
5
|
+
export type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { PACKAGE_NAME } from './constants.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The installed version of this package, read from its own package.json through the `./package.json` export
|
|
6
|
+
* (self-reference by name resolves in Node and Bun; the skill template is located the same way). Undefined when the
|
|
7
|
+
* lookup fails — a copy running outside its package boundary must not fail a site's build over a cosmetic field.
|
|
8
|
+
*/
|
|
9
|
+
export function packageVersion(): string | undefined {
|
|
10
|
+
try {
|
|
11
|
+
const pkg = createRequire(import.meta.url)(`${PACKAGE_NAME}/package.json`) as { version?: unknown };
|
|
12
|
+
return typeof pkg.version === 'string' ? pkg.version : undefined;
|
|
13
|
+
} catch {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { LocalizedEntry } from '@conloca/content-api';
|
|
2
|
+
import type { PreviewContext } from './middleware.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Four-verdict response of the endpoint's page-status route.
|
|
6
|
+
*
|
|
7
|
+
* - `unchanged` — page render graph is byte-equivalent to the production
|
|
8
|
+
* build; serve the ordinary page.
|
|
9
|
+
* - `changed` — page or one of its dependencies has been edited in the
|
|
10
|
+
* branch; carry the (possibly empty) embedded payload map into the
|
|
11
|
+
* preview reader so dependency reads short-circuit when the endpoint
|
|
12
|
+
* bundled them inline.
|
|
13
|
+
* - `deleted` — branch removed the page; the site's own not-found flow
|
|
14
|
+
* answers.
|
|
15
|
+
* - `redirect` — branch installed a redirect at the page's path; callers
|
|
16
|
+
* issue a 302 (we deliberately downgrade 301 to 302 — see fetchPageStatus).
|
|
17
|
+
*
|
|
18
|
+
* The verdict-to-response mapping lives in the site middleware
|
|
19
|
+
* (`./site-middleware.ts`), which renders through the site's own route.
|
|
20
|
+
*/
|
|
21
|
+
export type PageStatus =
|
|
22
|
+
| { kind: 'unchanged' }
|
|
23
|
+
| { kind: 'changed'; embedded: ReadonlyMap<string, LocalizedEntry> }
|
|
24
|
+
| { kind: 'deleted' }
|
|
25
|
+
| { kind: 'redirect'; target: string };
|
|
26
|
+
|
|
27
|
+
interface FetchPageStatusInput {
|
|
28
|
+
saasEndpoint: string;
|
|
29
|
+
ctx: PreviewContext;
|
|
30
|
+
path: string;
|
|
31
|
+
/** Site/locale the render resolves against. Unset ⇒ the endpoint's defaults
|
|
32
|
+
* (`default`/`en`) — fine for single-site, wrong for anything else, and the
|
|
33
|
+
* embedded map is locale-keyed so a mismatch silently never hits. */
|
|
34
|
+
site?: string;
|
|
35
|
+
locale?: string;
|
|
36
|
+
fetchFn?: typeof fetch;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Calls `GET {endpoint}/preview/page-status/{path}` with the preview JWT and
|
|
41
|
+
* decodes the four-verdict response into a {@link PageStatus} value.
|
|
42
|
+
*
|
|
43
|
+
* 301 responses are deliberately surfaced as `{ kind: 'redirect' }` with
|
|
44
|
+
* the same target as 302 — the downstream caller always emits 302 so
|
|
45
|
+
* a stale preview redirect cannot be cached by intermediaries.
|
|
46
|
+
*/
|
|
47
|
+
export async function fetchPageStatus(input: FetchPageStatusInput): Promise<PageStatus> {
|
|
48
|
+
const fetchImpl = input.fetchFn ?? fetch;
|
|
49
|
+
const normalisedPath = input.path.replace(/^\/+/u, '');
|
|
50
|
+
const query = new URLSearchParams();
|
|
51
|
+
if (input.locale !== undefined) query.set('locale', input.locale);
|
|
52
|
+
if (input.site !== undefined) query.set('site', input.site);
|
|
53
|
+
const suffix = query.size > 0 ? `?${query.toString()}` : '';
|
|
54
|
+
const url = `${input.saasEndpoint}/preview/page-status/${normalisedPath}${suffix}`;
|
|
55
|
+
const response = await fetchImpl(url, {
|
|
56
|
+
headers: { authorization: `Bearer ${input.ctx.jwt}` },
|
|
57
|
+
redirect: 'manual',
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
if (response.status === 304) return { kind: 'unchanged' };
|
|
61
|
+
if (response.status === 404) return { kind: 'deleted' };
|
|
62
|
+
if (response.status === 301 || response.status === 302) {
|
|
63
|
+
const target = response.headers.get('location') ?? '/';
|
|
64
|
+
return { kind: 'redirect', target };
|
|
65
|
+
}
|
|
66
|
+
if (response.status === 200) {
|
|
67
|
+
const data: unknown = await response.json();
|
|
68
|
+
return { kind: 'changed', embedded: decodeEmbedded(data) };
|
|
69
|
+
}
|
|
70
|
+
throw new Error(`preview page-status ${input.path}: ${response.status}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Decodes the optional `{ embedded: { "${id} ${locale}": LocalizedEntry } }`
|
|
75
|
+
* payload from a 200 page-status response into the strongly-typed map
|
|
76
|
+
* the {@link import('./content-api.js').PreviewContentAPI} consumes. Unknown
|
|
77
|
+
* fields are ignored; malformed entries are dropped silently rather than
|
|
78
|
+
* throwing — a bad embedded payload should degrade to a network fetch, not
|
|
79
|
+
* 500 the page.
|
|
80
|
+
*/
|
|
81
|
+
function decodeEmbedded(data: unknown): ReadonlyMap<string, LocalizedEntry> {
|
|
82
|
+
if (typeof data !== 'object' || data === null) return new Map();
|
|
83
|
+
const embedded = (data as { embedded?: unknown }).embedded;
|
|
84
|
+
if (typeof embedded !== 'object' || embedded === null) return new Map();
|
|
85
|
+
const map = new Map<string, LocalizedEntry>();
|
|
86
|
+
for (const [key, value] of Object.entries(embedded as Record<string, unknown>)) {
|
|
87
|
+
if (isLocalizedEntry(value)) {
|
|
88
|
+
map.set(key, value);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return map;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isLocalizedEntry(value: unknown): value is LocalizedEntry {
|
|
95
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
96
|
+
const v = value as { id?: unknown; localized?: unknown };
|
|
97
|
+
if (typeof v.id !== 'string') return false;
|
|
98
|
+
if (typeof v.localized !== 'object' || v.localized === null) return false;
|
|
99
|
+
const l = v.localized as { etag?: unknown; locale?: unknown; content?: unknown };
|
|
100
|
+
return typeof l.etag === 'string' && typeof l.locale === 'string' && typeof l.content === 'object';
|
|
101
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { PreviewMiddlewareOptions } from './middleware.js';
|
|
2
|
+
|
|
3
|
+
/** Values the preview build can bake into the artifact at build time. */
|
|
4
|
+
export interface BakedPreviewOpts {
|
|
5
|
+
secret?: string;
|
|
6
|
+
saasEndpoint?: string;
|
|
7
|
+
saasIssuer?: string;
|
|
8
|
+
saasAudience?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the middleware options, preferring values baked in at build time and
|
|
13
|
+
* falling back to the runtime environment.
|
|
14
|
+
*
|
|
15
|
+
* Baking is what removes the deployer's setup burden: every value is already
|
|
16
|
+
* known while the preview build runs — the secret arrived with registration,
|
|
17
|
+
* the endpoint and audience are integration options — so a correctly built
|
|
18
|
+
* preview artifact needs NO env vars on the deployment. It also removes a
|
|
19
|
+
* chicken-and-egg loop: the secret is generated during the build but the
|
|
20
|
+
* deployment that would carry it happens afterwards.
|
|
21
|
+
*
|
|
22
|
+
* The environment still wins when set, so one artifact can be promoted across
|
|
23
|
+
* environments without a rebuild.
|
|
24
|
+
*
|
|
25
|
+
* Throws naming the missing variable — a misconfigured preview runtime must
|
|
26
|
+
* not silently accept requests.
|
|
27
|
+
*/
|
|
28
|
+
export function resolveFromBaked(
|
|
29
|
+
baked: BakedPreviewOpts,
|
|
30
|
+
readEnvVar: (name: string) => string | undefined,
|
|
31
|
+
): PreviewMiddlewareOptions {
|
|
32
|
+
const pick = (envName: string, bakedValue: string | undefined): string => {
|
|
33
|
+
const fromEnv = readEnvVar(envName);
|
|
34
|
+
if (fromEnv) return fromEnv;
|
|
35
|
+
if (bakedValue) return bakedValue;
|
|
36
|
+
throw new Error(
|
|
37
|
+
`${'@conloca/cloud-astro'}: preview SSR handler is missing required configuration ${envName}. ` +
|
|
38
|
+
'The preview build normally bakes this in from the conlocaCloud() options; ' +
|
|
39
|
+
`set ${envName} on the deployment to override.`,
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
secret: pick('CONLOCA_PREVIEW_SECRET', baked.secret),
|
|
44
|
+
saasEndpoint: pick('CONLOCA_SAAS_ENDPOINT', baked.saasEndpoint),
|
|
45
|
+
saasIssuer: pick('CONLOCA_SAAS_ISSUER', baked.saasIssuer),
|
|
46
|
+
saasAudience: pick('CONLOCA_SAAS_AUDIENCE', baked.saasAudience),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Endpoint transport: prefer a `CONLOCA_SAAS` binding when the Cloudflare
|
|
52
|
+
* Workers runtime exposes one, else `undefined` so callers fall back to
|
|
53
|
+
* the global fetch. Bind it when a plain fetch from the preview deployment
|
|
54
|
+
* cannot reach the endpoint by its hostname; JWKS discovery and every preview
|
|
55
|
+
* read then go through the binding.
|
|
56
|
+
*
|
|
57
|
+
* Bindings come from Cloudflare's runtime module (Astro v6 removed
|
|
58
|
+
* `locals.runtime.env`); the import is dynamic and swallowed on Node, where
|
|
59
|
+
* the module does not exist and the global fetch is correct. Memoized so
|
|
60
|
+
* jose's JWKS cache keys off a stable function identity.
|
|
61
|
+
*/
|
|
62
|
+
let endpointFetchPromise: Promise<typeof fetch | undefined> | undefined;
|
|
63
|
+
export function resolveEndpointFetch(): Promise<typeof fetch | undefined> {
|
|
64
|
+
endpointFetchPromise ??= (async () => {
|
|
65
|
+
try {
|
|
66
|
+
const mod = (await import(/* @vite-ignore */ 'cloudflare:workers')) as { env?: Record<string, unknown> };
|
|
67
|
+
const binding = mod.env?.CONLOCA_SAAS;
|
|
68
|
+
if (
|
|
69
|
+
typeof binding === 'object' &&
|
|
70
|
+
binding !== null &&
|
|
71
|
+
typeof (binding as { fetch?: unknown }).fetch === 'function'
|
|
72
|
+
) {
|
|
73
|
+
const fetcher = binding as { fetch: typeof fetch };
|
|
74
|
+
// Cast: an arrow satisfies fetch's call signature but not the static
|
|
75
|
+
// properties Bun's typings hang off `typeof fetch` (preconnect).
|
|
76
|
+
return ((input, init) => fetcher.fetch(input, init)) as typeof fetch;
|
|
77
|
+
}
|
|
78
|
+
} catch {
|
|
79
|
+
// Not running on Cloudflare Workers — the global fetch is the transport.
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
})();
|
|
83
|
+
return endpointFetchPromise;
|
|
84
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { PreviewContext } from './middleware.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the body of the script tag that renders the floating preview
|
|
5
|
+
* banner inside the rendered page. Exported separately so the script
|
|
6
|
+
* source can be unit-tested without parsing surrounding HTML.
|
|
7
|
+
*
|
|
8
|
+
* The script is intentionally framework-free vanilla JS: it has to run
|
|
9
|
+
* inside whatever HTML the site's Astro renderer produced, with no
|
|
10
|
+
* assumption about React/preact/svelte runtime presence. The collapse-state
|
|
11
|
+
* persistence uses localStorage with a fixed key so opening multiple
|
|
12
|
+
* previews on the same origin gives a consistent UX.
|
|
13
|
+
*
|
|
14
|
+
* The preview context is embedded as a JSON literal — `JSON.stringify`
|
|
15
|
+
* encodes both `"` and `</script>` sequences safely, which is the
|
|
16
|
+
* canonical way to embed server data in a same-origin inline script.
|
|
17
|
+
*/
|
|
18
|
+
export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exitPath?: string): string {
|
|
19
|
+
// Serialize then patch the `<` character that JSON.stringify does NOT
|
|
20
|
+
// escape. Browsers terminate inline scripts on `</script>` regardless of
|
|
21
|
+
// string-literal context, so a branch name containing `</script>` would
|
|
22
|
+
// break out of the script tag. Replacing `</` with `<\/` is the standard
|
|
23
|
+
// mitigation (also done by ASP.NET's Json.Encode, Rails' j helper, etc.).
|
|
24
|
+
//
|
|
25
|
+
// The endpoint rides the envelope alongside the preview ctx so the
|
|
26
|
+
// "Share Preview" button can call `GET {endpoint}/preview/share` from the
|
|
27
|
+
// browser with the preview JWT (the same credential the cookie carries; the
|
|
28
|
+
// cookie is HttpOnly, so the button reads the JWT from here). Absent an
|
|
29
|
+
// endpoint the button is inert. `endpoint: undefined` drops out of the JSON.
|
|
30
|
+
//
|
|
31
|
+
// `exitPath` is the server-side exit route (secret-prefixed). Embedding it
|
|
32
|
+
// here does not widen the secret's exposure: this script is served only to
|
|
33
|
+
// credentialed preview visitors, who already hold the secret — it is in the
|
|
34
|
+
// entry/share URL they arrived through — and the response is no-store.
|
|
35
|
+
const ctxJson = JSON.stringify({ ...ctx, endpoint, exitPath }).replace(/</g, '\\u003c');
|
|
36
|
+
return [
|
|
37
|
+
`var __conlocaPreview = ${ctxJson};`,
|
|
38
|
+
"var __conlocaCollapseKey = 'conloca.preview.collapsed';",
|
|
39
|
+
"var __conlocaIsCollapsed = function () { try { return localStorage.getItem(__conlocaCollapseKey) === '1'; } catch (e) { return false; } };",
|
|
40
|
+
"var __conlocaSetCollapsed = function (v) { try { localStorage.setItem(__conlocaCollapseKey, v ? '1' : '0'); } catch (e) {} };",
|
|
41
|
+
'var __conlocaRender = function () {',
|
|
42
|
+
" var host = document.createElement('div');",
|
|
43
|
+
" host.id = 'conloca-preview-banner';",
|
|
44
|
+
" 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;';",
|
|
45
|
+
" var label = document.createElement('span'); label.textContent = 'Preview: ' + __conlocaPreview.branch; host.appendChild(label);",
|
|
46
|
+
// "Edit" reuses the landing page's `/login?return=` contract:
|
|
47
|
+
// the endpoint's login route already knows how to send an authenticated
|
|
48
|
+
// session into the editor for the requested page.
|
|
49
|
+
" var edit = document.createElement('a'); edit.textContent = 'Edit'; edit.style.color = '#9cf';",
|
|
50
|
+
" if (__conlocaPreview.endpoint) { edit.href = __conlocaPreview.endpoint + '/login?return=' + encodeURIComponent(location.pathname); host.appendChild(edit); }",
|
|
51
|
+
// "Exit Preview" must round-trip the server: the cookie is HttpOnly, so
|
|
52
|
+
// only a Set-Cookie response can expire it. `to` returns the visitor to
|
|
53
|
+
// this page, now published.
|
|
54
|
+
" var exitLink = document.createElement('a'); exitLink.textContent = 'Exit Preview'; exitLink.style.color = '#9cf';",
|
|
55
|
+
" if (__conlocaPreview.exitPath) { exitLink.href = __conlocaPreview.exitPath + '?to=' + encodeURIComponent(location.pathname); host.appendChild(exitLink); }",
|
|
56
|
+
" 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);",
|
|
57
|
+
// "Share Preview": mint a fresh shareable link via GET {endpoint}/preview/share
|
|
58
|
+
// and copy it to the clipboard. Bearer-authenticated with the preview JWT
|
|
59
|
+
// (the route reads Authorization/?token=, never the HttpOnly cookie). The
|
|
60
|
+
// button briefly reflects the outcome, then restores.
|
|
61
|
+
" share.addEventListener('click', function () {",
|
|
62
|
+
' if (!__conlocaPreview.endpoint) return;',
|
|
63
|
+
" var shareUrl = __conlocaPreview.endpoint + '/preview/share?branch=' + encodeURIComponent(__conlocaPreview.branch);",
|
|
64
|
+
' var previousLabel = share.textContent;',
|
|
65
|
+
' share.disabled = true;',
|
|
66
|
+
" fetch(shareUrl, { headers: { authorization: 'Bearer ' + __conlocaPreview.jwt } })",
|
|
67
|
+
" .then(function (res) { if (!res.ok) throw new Error('share ' + res.status); return res.json(); })",
|
|
68
|
+
" .then(function (data) { if (!data || typeof data.url !== 'string') throw new Error('missing url'); return navigator.clipboard.writeText(data.url); })",
|
|
69
|
+
" .then(function () { share.textContent = 'Link copied'; })",
|
|
70
|
+
" .catch(function () { share.textContent = 'Copy failed'; })",
|
|
71
|
+
' .then(function () { setTimeout(function () { share.textContent = previousLabel; share.disabled = false; }, 2000); });',
|
|
72
|
+
' });',
|
|
73
|
+
" 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);",
|
|
74
|
+
" collapse.addEventListener('click', function () { var c = !__conlocaIsCollapsed(); __conlocaSetCollapsed(c); host.style.display = c ? 'none' : ''; });",
|
|
75
|
+
" if (__conlocaIsCollapsed()) host.style.display = 'none';",
|
|
76
|
+
' document.body.appendChild(host);',
|
|
77
|
+
'};',
|
|
78
|
+
"if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', __conlocaRender); } else { __conlocaRender(); }",
|
|
79
|
+
].join(' ');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Returns `html` with the preview banner script and `<meta robots noindex>`
|
|
84
|
+
* tag injected before the closing `</body>` tag.
|
|
85
|
+
*
|
|
86
|
+
* The injection uses `String.prototype.replace` with a string argument
|
|
87
|
+
* (not a regex), so only the FIRST `</body>` match is rewritten. That
|
|
88
|
+
* matters because a misconfigured renderer can emit malformed HTML with
|
|
89
|
+
* multiple `</body>` tags; we never want to inject the banner more than
|
|
90
|
+
* once per response.
|
|
91
|
+
*/
|
|
92
|
+
export function injectPreviewBanner(html: string, ctx: PreviewContext, endpoint?: string, exitPath?: string): string {
|
|
93
|
+
const robotsMeta = '<meta name="robots" content="noindex, nofollow">';
|
|
94
|
+
const script = `<script>${getBannerScriptText(ctx, endpoint, exitPath)}</script>`;
|
|
95
|
+
return html.replace('</body>', `${robotsMeta + script}</body>`);
|
|
96
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
BatchResult,
|
|
3
|
+
ContentAPI,
|
|
4
|
+
ContentEntry,
|
|
5
|
+
ContentManifest,
|
|
6
|
+
CreateContentInput,
|
|
7
|
+
CreateResult,
|
|
8
|
+
DeleteLocaleInput,
|
|
9
|
+
DeleteResult,
|
|
10
|
+
FindOptions,
|
|
11
|
+
Fragments,
|
|
12
|
+
GlobalFilters,
|
|
13
|
+
LocaleVersion,
|
|
14
|
+
LocalizedEntry,
|
|
15
|
+
Site,
|
|
16
|
+
SitesConfig,
|
|
17
|
+
UpdateLocaleInput,
|
|
18
|
+
UpdateResult,
|
|
19
|
+
} from '@conloca/content-api';
|
|
20
|
+
import type { PreviewContext } from './middleware.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `Data` is not re-exported from `@conloca/content-api`'s package index; we
|
|
24
|
+
* pull it off the `ContentAPI` interface via an indexed type so the preview
|
|
25
|
+
* reader's `data` field has the same nominal shape without depending on
|
|
26
|
+
* deep imports.
|
|
27
|
+
*/
|
|
28
|
+
type ContentAPIData = ContentAPI['data'];
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Options consumed by {@link PreviewContentAPI}.
|
|
32
|
+
*
|
|
33
|
+
* The reader is constructed once per request inside the preview SSR
|
|
34
|
+
* dispatcher; passing the baseline reader through the options keeps the
|
|
35
|
+
* "no long-lived cache" rule honest (no per-package singleton can
|
|
36
|
+
* accidentally outlive a request).
|
|
37
|
+
*
|
|
38
|
+
* `embeddedPayloads` is the optimisation the endpoint's page-status route
|
|
39
|
+
* uses to avoid N+1 fetches when it has already loaded a changed dependency
|
|
40
|
+
* to compute the page render graph. Keys are `"${id} ${locale}"`; the value
|
|
41
|
+
* is the full {@link LocalizedEntry} envelope the renderer would have read
|
|
42
|
+
* from disk. When supplied, {@link PreviewContentAPI.getLocalized} short-
|
|
43
|
+
* circuits the network fetch for that pair.
|
|
44
|
+
*
|
|
45
|
+
* `fetchFn` is the optional fetch injection seam. Tests pass a recording
|
|
46
|
+
* stub so the network is never touched.
|
|
47
|
+
*/
|
|
48
|
+
export interface PreviewContentAPIOptions {
|
|
49
|
+
saasEndpoint: string;
|
|
50
|
+
ctx: PreviewContext;
|
|
51
|
+
/**
|
|
52
|
+
* The build's static collection-backed reader. Used for `304` fall-back
|
|
53
|
+
* inside `getLocalized` when the endpoint reports a dependency unchanged in the
|
|
54
|
+
* branch, and as the manifest source only when the branch listing could not
|
|
55
|
+
* be loaded. A loaded branch listing is authoritative for additions,
|
|
56
|
+
* deletions, and each manifest's locale set.
|
|
57
|
+
*/
|
|
58
|
+
baselineApi: ContentAPI;
|
|
59
|
+
embeddedPayloads?: ReadonlyMap<string, LocalizedEntry>;
|
|
60
|
+
fetchFn?: typeof fetch;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Per-request preview-aware `ContentAPI` reader.
|
|
65
|
+
*
|
|
66
|
+
* The page handler boundary reads through `Astro.locals.contentApi` when
|
|
67
|
+
* present; the preview dispatcher installs an instance of this class on that
|
|
68
|
+
* property. For unchanged dependencies the reader transparently
|
|
69
|
+
* falls back to the baseline so the production assets are reused; for changed
|
|
70
|
+
* dependencies the reader fetches `/preview/content` from the endpoint,
|
|
71
|
+
* carrying the preview JWT in the `Authorization` header.
|
|
72
|
+
*
|
|
73
|
+
* Write methods always return a failure result — preview SSR is strictly
|
|
74
|
+
* read-only: no write reaches the endpoint from the preview reader.
|
|
75
|
+
*/
|
|
76
|
+
export class PreviewContentAPI implements ContentAPI {
|
|
77
|
+
/**
|
|
78
|
+
* Fragments/Data facades delegate to the baseline reader. The preview
|
|
79
|
+
* renderer reads fragment / data dependencies through `getLocalized` once
|
|
80
|
+
* the page handler has resolved the dependency id, so the facades only
|
|
81
|
+
* need to surface the baseline's listing semantics for legacy callers.
|
|
82
|
+
*/
|
|
83
|
+
readonly fragments: Fragments;
|
|
84
|
+
readonly data: ContentAPIData;
|
|
85
|
+
|
|
86
|
+
private readonly opts: PreviewContentAPIOptions;
|
|
87
|
+
private readonly fetchImpl: typeof fetch;
|
|
88
|
+
/** The branch's page set, once {@link loadBranchManifests} has run. */
|
|
89
|
+
private branchManifests?: ContentManifest[];
|
|
90
|
+
private readonly localizedReads = new Map<string, Promise<LocalizedEntry | null>>();
|
|
91
|
+
|
|
92
|
+
constructor(opts: PreviewContentAPIOptions) {
|
|
93
|
+
this.opts = opts;
|
|
94
|
+
// Bind the global fetch: `this.fetchImpl(...)` is a method call, and on
|
|
95
|
+
// Cloudflare Workers an unbound fetch invoked with a foreign `this` throws
|
|
96
|
+
// "Illegal invocation" (Node does not care, so only workerd catches it).
|
|
97
|
+
this.fetchImpl = opts.fetchFn ?? fetch.bind(globalThis);
|
|
98
|
+
this.fragments = opts.baselineApi.fragments;
|
|
99
|
+
this.data = opts.baselineApi.data;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
get sitesConfig(): SitesConfig {
|
|
103
|
+
return this.opts.baselineApi.sitesConfig;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// -------------------------------------------------------------------------
|
|
107
|
+
// Reads — the actual preview behaviour.
|
|
108
|
+
// -------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
async getContent(id: string): Promise<ContentEntry | null> {
|
|
111
|
+
const manifest =
|
|
112
|
+
this.branchManifests === undefined
|
|
113
|
+
? await this.opts.baselineApi.getContent(id)
|
|
114
|
+
: (this.branchManifests.find((entry) => entry.id === id) ?? null);
|
|
115
|
+
if (!manifest) return null;
|
|
116
|
+
|
|
117
|
+
const locales: ContentEntry['locales'] = {};
|
|
118
|
+
for (const locale of Object.keys(manifest.locales)) {
|
|
119
|
+
const localized = await this.getLocalized(id, locale);
|
|
120
|
+
if (localized) {
|
|
121
|
+
locales[locale] = withContent(localized);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (Object.keys(locales).length === 0) return null;
|
|
125
|
+
return { ...manifest, locales };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
|
|
129
|
+
const embedded = this.opts.embeddedPayloads?.get(embeddedKey(id, locale));
|
|
130
|
+
if (embedded) return embedded;
|
|
131
|
+
|
|
132
|
+
// Request-scoped memoization (the instance lives for one render, so this
|
|
133
|
+
// is not a long-lived cache): the render enumerates the
|
|
134
|
+
// same entries repeatedly — page listing, fragment listing, dependency
|
|
135
|
+
// reads — and every duplicate would be another round trip to the endpoint
|
|
136
|
+
// against the Cloudflare Workers subrequest budget. Failures are evicted so a later read
|
|
137
|
+
// can retry.
|
|
138
|
+
const key = embeddedKey(id, locale);
|
|
139
|
+
const inFlight = this.localizedReads.get(key);
|
|
140
|
+
if (inFlight) return inFlight;
|
|
141
|
+
const read = this.fetchLocalized(id, locale);
|
|
142
|
+
this.localizedReads.set(key, read);
|
|
143
|
+
read.catch(() => this.localizedReads.delete(key));
|
|
144
|
+
return read;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private async fetchLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
|
|
148
|
+
const url = `${this.opts.saasEndpoint}/preview/content/${id}/${locale}`;
|
|
149
|
+
const response = await this.fetchImpl(url, {
|
|
150
|
+
headers: { authorization: `Bearer ${this.opts.ctx.jwt}` },
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
if (response.status === 304) {
|
|
154
|
+
return this.opts.baselineApi.getLocalized(id, locale);
|
|
155
|
+
}
|
|
156
|
+
if (response.status === 404) return null;
|
|
157
|
+
if (!response.ok) {
|
|
158
|
+
throw new Error(`preview fetch ${id}/${locale}: ${response.status}`);
|
|
159
|
+
}
|
|
160
|
+
const data: unknown = await response.json();
|
|
161
|
+
if (!isLocalizedEntry(data)) {
|
|
162
|
+
throw new Error(`preview fetch ${id}/${locale}: malformed payload`);
|
|
163
|
+
}
|
|
164
|
+
return data;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async getContentAsBuffer(
|
|
168
|
+
id: string,
|
|
169
|
+
locale: string,
|
|
170
|
+
): Promise<{ buffer: Uint8Array; etag: string; contentType: 'application/json' | 'text/mdx' } | null> {
|
|
171
|
+
return this.opts.baselineApi.getContentAsBuffer(id, locale);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// -------------------------------------------------------------------------
|
|
175
|
+
// Sites / listings.
|
|
176
|
+
// -------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
getSite(siteName: string): Site | null {
|
|
179
|
+
return this.opts.baselineApi.getSite(siteName);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Prefetch the branch's own manifest listing.
|
|
184
|
+
*
|
|
185
|
+
* The baseline is a snapshot of the last PRODUCTION build, so it cannot know
|
|
186
|
+
* about a page created on the branch and still contains pages the branch
|
|
187
|
+
* deleted — listing from it makes new pages unpreviewable and deleted ones
|
|
188
|
+
* linger. The branch is the authority for the page set; the baseline stays
|
|
189
|
+
* the fallback for unchanged dependency CONTENT.
|
|
190
|
+
*
|
|
191
|
+
* Prefetched rather than fetched lazily because `ContentAPI.listAllContent`
|
|
192
|
+
* is a synchronous generator. On any failure the listing is left unset and
|
|
193
|
+
* `listAllContent` degrades to the baseline — a stale page set renders
|
|
194
|
+
* something, an exception renders nothing.
|
|
195
|
+
*/
|
|
196
|
+
async loadBranchManifests(): Promise<void> {
|
|
197
|
+
try {
|
|
198
|
+
// /preview/manifests admits the preview scope; the editor listing at
|
|
199
|
+
// /api/v1/content/manifests filters a preview JWT to `*`-prefixed ids
|
|
200
|
+
// and would return an empty page set here.
|
|
201
|
+
const response = await this.fetchImpl(`${this.opts.saasEndpoint}/preview/manifests`, {
|
|
202
|
+
headers: { authorization: `Bearer ${this.opts.ctx.jwt}` },
|
|
203
|
+
});
|
|
204
|
+
if (!response.ok) return;
|
|
205
|
+
const data: unknown = await response.json();
|
|
206
|
+
if (Array.isArray(data)) this.branchManifests = data as ContentManifest[];
|
|
207
|
+
} catch {
|
|
208
|
+
// Network/parse failure — keep the baseline listing.
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
*listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {
|
|
213
|
+
if (this.branchManifests === undefined) {
|
|
214
|
+
yield* this.opts.baselineApi.listAllContent(filters);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
for (const manifest of this.branchManifests) {
|
|
218
|
+
if (filters?.collection !== undefined && manifest.collection !== filters.collection) continue;
|
|
219
|
+
if (filters?.kind !== undefined && manifest.kind !== filters.kind) continue;
|
|
220
|
+
if (filters?.site !== undefined && manifest.site !== filters.site) continue;
|
|
221
|
+
yield manifest;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
*findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {
|
|
226
|
+
yield* this.opts.baselineApi.findUntranslatedContent(targetLocale, options);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// -------------------------------------------------------------------------
|
|
230
|
+
// Writes — always rejected. Preview SSR never mutates branch state;
|
|
231
|
+
// edits go through the editor at the endpoint, never through the site.
|
|
232
|
+
// -------------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
async createContent(_input: CreateContentInput): Promise<CreateResult> {
|
|
235
|
+
return { success: false, reason: 'write_error', error: new Error(WRITE_REJECTED_MESSAGE) };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async updateLocalized(_input: UpdateLocaleInput): Promise<UpdateResult> {
|
|
239
|
+
return { success: false, reason: 'write_error', error: new Error(WRITE_REJECTED_MESSAGE) };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async deleteContent(_id: string, _etag: string): Promise<DeleteResult> {
|
|
243
|
+
return { success: false, reason: 'delete_error', error: new Error(WRITE_REJECTED_MESSAGE) };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async deleteLocalized(_input: DeleteLocaleInput): Promise<DeleteResult> {
|
|
247
|
+
return { success: false, reason: 'delete_error', error: new Error(WRITE_REJECTED_MESSAGE) };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {
|
|
251
|
+
return {
|
|
252
|
+
operations: operations.map((operation) => ({
|
|
253
|
+
id: operation.id,
|
|
254
|
+
locale: operation.locale,
|
|
255
|
+
updated: false,
|
|
256
|
+
error: new Error(WRITE_REJECTED_MESSAGE),
|
|
257
|
+
})),
|
|
258
|
+
success: false,
|
|
259
|
+
failed: operations.length,
|
|
260
|
+
updated: 0,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const WRITE_REJECTED_MESSAGE = 'preview SSR is read-only; edits must go through the editor at the endpoint';
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Composes the embedded-payload map key. Public so the dispatcher (and the
|
|
269
|
+
* page-status response decoder) can build keys that the reader will match
|
|
270
|
+
* without leaking the encoding choice across modules.
|
|
271
|
+
*/
|
|
272
|
+
export function embeddedKey(id: string, locale: string): string {
|
|
273
|
+
return `${id} ${locale}`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Lift a localized entry into the `LocaleVersion & { content }` shape that
|
|
278
|
+
* `ContentEntry.locales` expects. The entry is already the right shape — the
|
|
279
|
+
* helper exists so the dependency on `LocaleVersion` is documented at the
|
|
280
|
+
* call site rather than buried in a structural cast.
|
|
281
|
+
*/
|
|
282
|
+
function withContent(entry: LocalizedEntry): LocaleVersion & { content: LocalizedEntry['localized']['content'] } {
|
|
283
|
+
return entry.localized;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function isLocalizedEntry(value: unknown): value is LocalizedEntry {
|
|
287
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
288
|
+
const v = value as { id?: unknown; localized?: unknown };
|
|
289
|
+
if (typeof v.id !== 'string') return false;
|
|
290
|
+
if (typeof v.localized !== 'object' || v.localized === null) return false;
|
|
291
|
+
const l = v.localized as { etag?: unknown; locale?: unknown; content?: unknown };
|
|
292
|
+
return typeof l.etag === 'string' && typeof l.locale === 'string' && typeof l.content === 'object';
|
|
293
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal cookie-header parser. We only need to look up cookies by exact name
|
|
3
|
+
* (the secret-derived preview cookie); a full RFC 6265 parser would be
|
|
4
|
+
* overkill, and pulling in a dependency for this would be YAGNI.
|
|
5
|
+
*
|
|
6
|
+
* The parser intentionally rejects malformed segments silently rather than
|
|
7
|
+
* throwing — a bad cookie header from a misbehaving client must not crash
|
|
8
|
+
* the SSR handler. Callers always check whether the requested cookie was
|
|
9
|
+
* actually present.
|
|
10
|
+
*/
|
|
11
|
+
export function parseCookies(cookieHeader: string | null | undefined): Map<string, string> {
|
|
12
|
+
const out = new Map<string, string>();
|
|
13
|
+
if (!cookieHeader) return out;
|
|
14
|
+
for (const segment of cookieHeader.split(';')) {
|
|
15
|
+
const eq = segment.indexOf('=');
|
|
16
|
+
if (eq <= 0) continue;
|
|
17
|
+
const name = segment.slice(0, eq).trim();
|
|
18
|
+
const value = segment.slice(eq + 1).trim();
|
|
19
|
+
if (!name) continue;
|
|
20
|
+
// First occurrence wins; matches the spec-compliant behaviour of the
|
|
21
|
+
// browsers' document.cookie reader for duplicate names.
|
|
22
|
+
if (!out.has(name)) out.set(name, value);
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Serializes a `Set-Cookie` value with the security defaults the preview
|
|
29
|
+
* middleware requires: HttpOnly + Secure + SameSite=Lax + Path=/.
|
|
30
|
+
*
|
|
31
|
+
* Splitting this out from the middleware keeps the request handler
|
|
32
|
+
* declarative and lets the cookie defaults be reviewed in one place: the
|
|
33
|
+
* secret must never leak into a script-readable cookie.
|
|
34
|
+
*
|
|
35
|
+
* `SameSite=Lax`, not `Strict`: the share link always arrives from the editor
|
|
36
|
+
* origin, and Chrome withholds a `Strict` cookie on the request that FOLLOWS a
|
|
37
|
+
* cross-site redirect — so the init 302 would land without the cookie and loop
|
|
38
|
+
* straight back to the landing page. `Lax` still withholds the cookie from
|
|
39
|
+
* cross-site POSTs and subresource loads, which is the threat that matters for
|
|
40
|
+
* a read-only preview credential.
|
|
41
|
+
*
|
|
42
|
+
* `Path=/` is load-bearing: the browser sends the cookie on every same-origin
|
|
43
|
+
* request, which is what lets the preview follow internal links instead of
|
|
44
|
+
* surviving exactly one page view.
|
|
45
|
+
*
|
|
46
|
+
* `maxAgeSeconds` bounds the cookie to the credential it carries — pass the
|
|
47
|
+
* JWT's remaining lifetime so a stale cookie cannot outlive the token and
|
|
48
|
+
* strand the visitor on the landing page.
|
|
49
|
+
*/
|
|
50
|
+
export function serializePreviewCookie(name: string, value: string, maxAgeSeconds?: number): string {
|
|
51
|
+
const base = `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/`;
|
|
52
|
+
if (maxAgeSeconds === undefined) return base;
|
|
53
|
+
return `${base}; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;
|
|
54
|
+
}
|