payload-live-preview 1.8.0 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +301 -93
- package/dist/adapters/astro/PreviewBoundary.astro +66 -0
- package/dist/adapters/astro/RichText.astro +6 -0
- package/dist/adapters/astro/index.d.ts +165 -134
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.d.ts +4 -9
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.d.ts +13 -80
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +46 -106
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.d.ts +10 -75
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/client.cjs +2 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +747 -0
- package/dist/client.d.ts +747 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/codegen-astro.d.ts +5 -27
- package/dist/codegen-astro.js +1 -1
- package/dist/codegen-astro.js.map +1 -1
- package/dist/codegen-cli.d.ts +3 -16
- package/dist/codegen-cli.js +1 -1
- package/dist/codegen-cli.js.map +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.cjs.map +1 -1
- package/dist/codegen.d.cts +37 -124
- package/dist/codegen.d.ts +37 -124
- package/dist/codegen.js +1 -1
- package/dist/codegen.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +647 -1100
- package/dist/core.d.ts +647 -1100
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +3 -28
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +16 -32
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/fragment.cjs +2 -0
- package/dist/fragment.cjs.map +1 -0
- package/dist/fragment.d.cts +333 -0
- package/dist/fragment.d.ts +333 -0
- package/dist/fragment.js +2 -0
- package/dist/fragment.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +885 -1531
- package/dist/index.d.ts +885 -1531
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lexical.cjs +2 -0
- package/dist/lexical.cjs.map +1 -0
- package/dist/lexical.d.cts +90 -0
- package/dist/lexical.d.ts +90 -0
- package/dist/lexical.js +2 -0
- package/dist/lexical.js.map +1 -0
- package/dist/middleware-CEPsY1P7.d.ts +40 -0
- package/dist/migrate.d.ts +73 -0
- package/dist/migrate.js +2 -0
- package/dist/migrate.js.map +1 -0
- package/dist/options-CEzzfHJu.d.ts +197 -0
- package/dist/payload.cjs +1 -1
- package/dist/payload.cjs.map +1 -1
- package/dist/payload.d.cts +11 -80
- package/dist/payload.d.ts +11 -80
- package/dist/payload.js +1 -1
- package/dist/payload.js.map +1 -1
- package/dist/plugins.cjs +2 -0
- package/dist/plugins.cjs.map +1 -0
- package/dist/plugins.d.cts +509 -0
- package/dist/plugins.d.ts +509 -0
- package/dist/plugins.js +2 -0
- package/dist/plugins.js.map +1 -0
- package/dist/{probe-tMHdim5y.d.ts → probe-CYtvj_Lm.d.ts} +43 -77
- package/dist/server.cjs +2 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +435 -0
- package/dist/server.d.ts +435 -0
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/structural.cjs +3 -0
- package/dist/structural.cjs.map +1 -0
- package/dist/structural.d.cts +243 -0
- package/dist/structural.d.ts +243 -0
- package/dist/structural.js +3 -0
- package/dist/structural.js.map +1 -0
- package/package.json +86 -7
- package/dist/middleware-DD4Hwomt.d.ts +0 -189
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","value","Object","isFrozen","createAuthorizedPreviewContext","fields","freeze","scope","payloadHeaders","PreviewConfigurationError","Error","name","refused","outcome","authorized","context","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","extractCookie","header","maxLength","length","prefix","values","part","split","trimmed","trim","startsWith","push","slice","test","cachedEncoder","DEFAULT_PURPOSE","TOKEN_VERSION","encoder","TextEncoder","secretBytes","secret","bytes","encode","byteLength","String","cryptoFor","configured","candidate","globalThis","crypto","subtle","async","hmacKey","importKey","hash","toBase64Url","binary","byte","fromCharCode","btoa","replace","fromBase64Url","text","padded","repeat","atob","Uint8Array","index","charCodeAt","DEFAULT_QUERY_PARAMS","bind","field","options","buildAttributes","bindByPath","picker","path","proxy","Proxy","get","_target","prop","recordPath","join","attrs","attribute","type","richtext","html","locale","alt","href","arrayTemplate","SUPPRESSED","PreviewFetchError","reason","status","url","constructor","cause","super","this","failureReason","external","aborted","isWhereTree","Array","isArray","queryName","map","segment","appendWhere","query","node","key","entries","nextPath","some","forEach","branch","set","request","strategy","cookieName","cookieNameFor","origin","serverURL","URL","protocol","serverOriginFor","headers","maxCookieLength","now","Date","timeoutMs","Math","max","fetchImpl","fetch","usersSlug","encodeURIComponent","forwarded","body","response","cookie","accept","signal","AbortSignal","timeout","ok","json","user","collection","id","Number","isFinite","readUser","expiresAt","exp","readExpiry","subject","authorizedAt","authorizeSession","token","transport","kind","searchParams","getAll","param","readToken","parts","payloadText","payloadBytes","signature","verified","verify","claims","parsed","JSON","parse","TextDecoder","decode","c","optionalString","parseClaims","iat","aud","audience","pur","purpose","pth","pathname","loc","replay","isUsed","jti","markUsed","sub","authorizeToken","authorizeVerifier","createPreviewBindings","authorization","owner","bindOptions","config","normalizeServerURL","route","apiRoute","isInteger","depth","resolved","runtimeOptions","mergeDepth","base","read","draft","startedAt","finish","result","durationMs","onDiagnostic","errorMode","any","cache","redirect","data","draftFor","params","URLSearchParams","fetchDocument","where","toString","first","docs","fetchGlobal","global","signals","Set","queryParams","has","adminOrigins","referer","refererOrigin","adminOrigin","ttl","min","ttlMs","getRandomValues","wire","v","payload","stringify","signed","sign"],"sources":["../src/types/authorized-preview.ts","../src/security/preview-verdict.ts","../src/security/preview-session.ts","../src/security/preview-token.ts","../src/adapters/shared/preview-request.ts","../src/dsl/bind.ts","../src/dsl/preview-bindings.ts","../src/server/index.ts","../src/security/preview-authorization.ts"],"sourcesContent":["/**\n * The authorized preview context's shape and brand, in the leaf `types` domain\n * so producer and consumers recognise the same context. See ADR 0006.\n */\n\n/**\n * The brand key, in the type and on the object.\n *\n * This was a `unique symbol` until 2026-08-30. A `unique symbol` is nominal per\n * *declaration*, and the published entries each carry their own declaration\n * file — so `AuthorizedPreviewContext` from the root barrel was a different\n * type from the one in `./server` or in an adapter, and the documented flow\n * (authorize once, hand the context to the adapter hook and to the draft read)\n * did not type-check in any combination a consumer can write.\n *\n * That is the same trap the runtime brand below already avoids by using\n * `Symbol.for` rather than `Symbol()`; the lesson simply had not reached the\n * type. A shared string literal is identical in every bundle for the same\n * reason a registry symbol is.\n *\n * It is not what makes a context trustworthy. `isAuthorizedPreviewContext`\n * decides that, on the registry symbol and on `Object.isFrozen`, and every\n * consumption point calls it — the adapter policy, the draft read and the\n * binding emitter. Writing this key by hand buys nothing.\n */\nexport const AUTHORIZED_PREVIEW_BRAND_KEY = 'payload-live-preview.authorized-preview-context';\n\nexport type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';\n\n/** What a context is bound to; every field is optional because every strategy binds differently. */\nexport interface AuthorizedPreviewScope {\n /** The site origin the credential was issued for. */\n readonly audience?: string;\n /** The request pathname the credential is valid for. */\n readonly path?: string;\n readonly locale?: string;\n}\n\n/** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */\nexport interface AuthorizedPreviewContext {\n readonly [AUTHORIZED_PREVIEW_BRAND_KEY]: true;\n readonly strategy: PreviewAuthorizationStrategyName;\n /** The user id, token subject, or whatever the verifier named. */\n readonly subject: string | undefined;\n /** Unix milliseconds. */\n readonly authorizedAt: number;\n /** Unix milliseconds, or `undefined` when the strategy does not know. */\n readonly expiresAt: number | undefined;\n readonly scope: AuthorizedPreviewScope;\n /** The minimal request material a draft read forwards to Payload — one verified cookie, never the whole `Cookie` header. */\n readonly payloadHeaders: Readonly<Record<string, string>>;\n}\n\n// A registry symbol: entries are separate bundles, and a per-bundle `Symbol()`\n// would refuse the other's contexts in the package while unit tests passed.\nconst BRAND = Symbol.for(AUTHORIZED_PREVIEW_BRAND_KEY);\n\n/** Whether `value` was produced by `authorizePreviewRequest()`; a copy or JSON round trip is not. */\nexport function isAuthorizedPreviewContext(value: unknown): value is AuthorizedPreviewContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[BRAND] === true &&\n Object.isFrozen(value)\n );\n}\n\n/** Internal: the one place a context is made. */\nexport function createAuthorizedPreviewContext(\n fields: Omit<AuthorizedPreviewContext, typeof AUTHORIZED_PREVIEW_BRAND_KEY>,\n): AuthorizedPreviewContext {\n const context = Object.freeze({\n ...fields,\n scope: Object.freeze({ ...fields.scope }),\n payloadHeaders: Object.freeze({ ...fields.payloadHeaders }),\n [BRAND]: true,\n [AUTHORIZED_PREVIEW_BRAND_KEY]: true,\n });\n // No cast: the frozen object carries the brand key the interface declares.\n return context;\n}\n","/**\n * The verdict shape every authorization strategy produces, and the one error\n * class that is allowed to escape it. Kept apart from the strategies so the\n * adapters can import the error without pulling in HMAC or session code.\n */\n\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\n\n/** Why a request was refused. `'authorized'` is the one non-refusal. */\nexport type PreviewAuthorizationOutcome =\n | 'authorized'\n | 'missing-credential'\n | 'invalid'\n | 'expired'\n | 'wrong-audience'\n | 'wrong-path'\n | 'wrong-locale'\n | 'wrong-purpose'\n | 'replayed'\n | 'unavailable';\n\n/** The result of `authorizePreviewRequest()`: a verdict, never an exception. */\nexport type PreviewAuthorization =\n | {\n readonly authorized: true;\n readonly outcome: 'authorized';\n readonly context: AuthorizedPreviewContext;\n }\n | {\n readonly authorized: false;\n readonly outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>;\n readonly context: null;\n };\n\n/** The request shape every strategy reads: a URL and a header getter. */\nexport interface PreviewAuthorizationRequest {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/**\n * A strategy was misconfigured — raised on first use and re-thrown by the\n * adapters rather than reported as `'unavailable'`, so it fails loudly.\n */\nexport class PreviewConfigurationError extends Error {\n override readonly name = 'PreviewConfigurationError';\n}\n\n/** Recognises the error across bundles, where `instanceof` sees a different class copy. */\nexport function isPreviewConfigurationError(error: unknown): error is PreviewConfigurationError {\n return (\n error instanceof PreviewConfigurationError ||\n (error instanceof Error && error.name === 'PreviewConfigurationError')\n );\n}\n\nexport function refused(\n outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>,\n): PreviewAuthorization {\n return { authorized: false, outcome, context: null };\n}\n","/**\n * The `payload-session` strategy: forward exactly one named cookie to\n * `GET <serverURL>/api/<usersSlug>/me` and authorize when a user comes back.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** A `fetch`-compatible function, injectable for tests. */\nexport type FetchLike = (\n input: string,\n init: { readonly headers: Record<string, string>; readonly signal: AbortSignal },\n) => Promise<{ readonly ok: boolean; readonly status: number; json(): Promise<unknown> }>;\n\nexport interface PayloadSessionStrategy {\n readonly type: 'payload-session';\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** Auth collection slug; `users` unless the project renamed it. */\n readonly usersSlug?: string;\n /** Cookie name; Payload's default is `payload-token`. */\n readonly cookieName?: string;\n /** Upper bound for the `/me` round trip. Below 250 ms is raised to 250 ms; default 3000. */\n readonly timeoutMs?: number;\n /** Longest cookie value accepted; longer ones are refused as `invalid`. Default 4096. */\n readonly maxCookieLength?: number;\n readonly fetch?: FetchLike;\n /** Clock, Unix milliseconds. Injectable for tests. */\n readonly now?: () => number;\n}\n\nconst DEFAULT_USERS_SLUG = 'users';\nconst DEFAULT_COOKIE_NAME = 'payload-token';\nconst DEFAULT_TIMEOUT_MS = 3_000;\nconst MIN_TIMEOUT_MS = 250;\nconst DEFAULT_MAX_COOKIE_LENGTH = 4_096;\nconst COOKIE_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst COOKIE_VALUE_PATTERN = /^[A-Za-z0-9._~-]+$/;\n/** Below this an `exp` is Unix seconds; a millisecond timestamp passed it in 1973. */\nconst SECONDS_CEILING = 1e11;\n\n/**\n * Exactly one value for `name`, or `null` when absent, empty, over `maxLength`\n * or repeated — a repeated cookie is ambiguous and is refused, not guessed.\n */\nexport function extractCookie(\n header: string | null,\n name: string,\n maxLength: number = DEFAULT_MAX_COOKIE_LENGTH,\n): string | null {\n if (header === null || header.length === 0) return null;\n const prefix = `${name}=`;\n const values: string[] = [];\n for (const part of header.split(';')) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) values.push(trimmed.slice(prefix.length));\n }\n if (values.length !== 1) return null;\n const value = values[0] ?? '';\n // A JWT is `[A-Za-z0-9._~-]`; anything else must not be forwarded in a header.\n if (value.length === 0 || value.length > maxLength || !COOKIE_VALUE_PATTERN.test(value)) {\n return null;\n }\n return value;\n}\n\nfunction cookieNameFor(configured: string | undefined): string {\n const name = configured ?? DEFAULT_COOKIE_NAME;\n if (!COOKIE_NAME_PATTERN.test(name)) {\n throw new PreviewConfigurationError(\n `payload-live-preview: cookie name \"${name}\" is not a valid cookie-name token`,\n );\n }\n return name;\n}\n\nfunction serverOriginFor(serverURL: string): string {\n let url: URL;\n try {\n url = new URL(serverURL);\n } catch {\n throw new PreviewConfigurationError(\n `payload-live-preview: serverURL \"${serverURL}\" is not an absolute URL`,\n );\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new PreviewConfigurationError(\n `payload-live-preview: serverURL must be http(s), got \"${url.protocol}\"`,\n );\n }\n return url.origin;\n}\n\nexport async function authorizeSession(\n request: PreviewAuthorizationRequest,\n strategy: PayloadSessionStrategy,\n): Promise<PreviewAuthorization> {\n const cookieName = cookieNameFor(strategy.cookieName);\n const origin = serverOriginFor(strategy.serverURL);\n const value = extractCookie(\n request.headers.get('cookie'),\n cookieName,\n strategy.maxCookieLength ?? DEFAULT_MAX_COOKIE_LENGTH,\n );\n if (value === null) return refused('missing-credential');\n const now = strategy.now ?? Date.now;\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, strategy.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const fetchImpl: FetchLike = strategy.fetch ?? globalThis.fetch;\n const usersSlug = encodeURIComponent(strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n const forwarded = `${cookieName}=${value}`;\n let body: unknown;\n try {\n // `depth=0`: the verdict needs the user's id, not its populated relations.\n const response = await fetchImpl(`${origin}/api/${usersSlug}/me?depth=0`, {\n headers: { cookie: forwarded, accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) return refused(response.status === 401 ? 'invalid' : 'unavailable');\n body = await response.json();\n } catch {\n return refused('unavailable');\n }\n const user = readUser(body, strategy.usersSlug ?? DEFAULT_USERS_SLUG);\n if (user === null) return refused('invalid');\n const expiresAt = readExpiry(body);\n if (expiresAt !== undefined && expiresAt <= now()) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'payload-session',\n subject: user,\n authorizedAt: now(),\n expiresAt,\n scope: {},\n payloadHeaders: { cookie: forwarded },\n }),\n };\n}\n\n/** The user id from a `/me` body, or `null` when absent or from another auth collection — Payload answers `/me` for every one of them. */\nfunction readUser(body: unknown, usersSlug: string): string | null {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const user = (body as { user?: unknown }).user;\n if (typeof user !== 'object' || user === null || Array.isArray(user)) return null;\n const collection =\n (body as { collection?: unknown }).collection ?? (user as { collection?: unknown }).collection;\n if (collection !== undefined && collection !== usersSlug) return null;\n const id = (user as { id?: unknown }).id;\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return null;\n}\n\n/** `/me` reports `exp` in Unix seconds; units are decided by magnitude so an expired millisecond value stays expired. */\nfunction readExpiry(body: unknown): number | undefined {\n const exp = (body as { exp?: unknown }).exp;\n if (typeof exp !== 'number' || !Number.isFinite(exp) || exp <= 0) return undefined;\n return exp < SECONDS_CEILING ? exp * 1000 : exp;\n}\n","/**\n * The `signed-token` strategy: a short-lived HMAC-SHA256 token minted by the\n * Payload side and verified by the site. Format and bindings: ADR 0006 §3.\n */\n\nimport { createAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport {\n PreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\n\n/** The subset of Web Crypto the token strategy needs, injectable for environments that expose it elsewhere. */\nexport interface SubtleCryptoLike {\n readonly subtle: {\n importKey(\n format: 'raw',\n keyData: Uint8Array,\n algorithm: { readonly name: 'HMAC'; readonly hash: 'SHA-256' },\n extractable: false,\n keyUsages: readonly ('sign' | 'verify')[],\n ): Promise<CryptoKey>;\n sign(algorithm: 'HMAC', key: CryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n verify(\n algorithm: 'HMAC',\n key: CryptoKey,\n signature: Uint8Array,\n data: Uint8Array,\n ): Promise<boolean>;\n };\n getRandomValues<T extends Uint8Array>(array: T): T;\n}\n\n/** Where a signed token is read from on the request. */\nexport type PreviewTokenTransport =\n | { readonly kind: 'query'; readonly param?: string }\n | { readonly kind: 'header'; readonly name?: string };\n\n/**\n * Optional replay store. Not shipped: a per-process memory is useless behind\n * a load balancer, so the store is a deployment decision.\n */\nexport interface PreviewTokenReplayStore {\n isUsed(id: string): Promise<boolean> | boolean;\n markUsed(id: string, expiresAt: number): Promise<void> | void;\n}\n\nexport interface SignedTokenStrategy {\n readonly type: 'signed-token';\n /** Shared secret, at least 32 bytes; shorter ones are refused on first use. */\n readonly secret: string | Uint8Array;\n /** The site origin tokens must name, e.g. `https://www.example.com`. */\n readonly audience: string;\n /** Purpose string tokens must carry. Default `live-preview`. */\n readonly purpose?: string;\n /** Default: query parameter `previewToken`. */\n readonly transport?: PreviewTokenTransport;\n /** Resolve the request's locale for the `loc` binding. Unset: tokens with `loc` are refused as `wrong-locale`. */\n readonly locale?: (request: PreviewAuthorizationRequest) => string | undefined;\n readonly replay?: PreviewTokenReplayStore;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\n/** What `issuePreviewToken()` binds a token to. */\nexport interface PreviewTokenClaims {\n /** The site origin the token is for. */\n readonly audience: string;\n /** Request pathname the token opens. Recommended; omit only for a single-page preview. */\n readonly path?: string;\n readonly locale?: string;\n readonly subject?: string;\n readonly purpose?: string;\n /** Lifetime in milliseconds. Default ten minutes; capped at one hour. */\n readonly ttlMs?: number;\n}\n\nexport interface IssuePreviewTokenOptions {\n readonly secret: string | Uint8Array;\n readonly crypto?: SubtleCryptoLike;\n readonly now?: () => number;\n}\n\ninterface WireClaims {\n readonly v: 1;\n readonly aud: string;\n readonly pth?: string;\n readonly loc?: string;\n readonly sub?: string;\n readonly pur: string;\n readonly iat: number;\n readonly exp: number;\n readonly jti: string;\n}\n\nconst DEFAULT_PURPOSE = 'live-preview';\nconst DEFAULT_QUERY_PARAM = 'previewToken';\nconst DEFAULT_HEADER_NAME = 'x-preview-token';\nconst DEFAULT_TTL_MS = 10 * 60_000;\nconst MAX_TTL_MS = 60 * 60_000;\nconst MIN_SECRET_BYTES = 32;\nconst TOKEN_VERSION = 'v1';\n/** A real token is a few hundred bytes. */\nconst MAX_TOKEN_LENGTH = 4_096;\n\n// Lazy: a module-scope `new TextEncoder()` is a side effect a bundler must keep.\nlet cachedEncoder: TextEncoder | undefined;\nfunction encoder(): TextEncoder {\n cachedEncoder ??= new TextEncoder();\n return cachedEncoder;\n}\n\nfunction secretBytes(secret: string | Uint8Array): Uint8Array {\n const bytes = typeof secret === 'string' ? encoder().encode(secret) : secret;\n if (bytes.byteLength < MIN_SECRET_BYTES) {\n throw new PreviewConfigurationError(\n `payload-live-preview: the preview token secret must be at least ${String(MIN_SECRET_BYTES)} bytes`,\n );\n }\n return bytes;\n}\n\nfunction cryptoFor(configured: SubtleCryptoLike | undefined): SubtleCryptoLike | undefined {\n if (configured !== undefined) return configured;\n const candidate = (globalThis as { crypto?: unknown }).crypto;\n if (typeof (candidate as { subtle?: unknown } | undefined)?.subtle === 'object') {\n return candidate as SubtleCryptoLike;\n }\n return undefined;\n}\n\nasync function hmacKey(crypto: SubtleCryptoLike, secret: Uint8Array): Promise<CryptoKey> {\n return crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n 'verify',\n ]);\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction fromBase64Url(text: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined;\n const padded =\n text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\n/** Mint a preview token on the Payload side; pair with `buildLivePreviewUrl`. */\nexport async function issuePreviewToken(\n claims: PreviewTokenClaims,\n options: IssuePreviewTokenOptions,\n): Promise<string> {\n const crypto = cryptoFor(options.crypto);\n if (crypto === undefined) {\n throw new Error('payload-live-preview: no Web Crypto implementation available to sign tokens');\n }\n const secret = secretBytes(options.secret);\n const now = (options.now ?? Date.now)();\n const ttl = Math.min(MAX_TTL_MS, Math.max(1, claims.ttlMs ?? DEFAULT_TTL_MS));\n const id = new Uint8Array(16);\n crypto.getRandomValues(id);\n const wire: WireClaims = {\n v: 1,\n aud: claims.audience,\n ...(claims.path !== undefined ? { pth: claims.path } : {}),\n ...(claims.locale !== undefined ? { loc: claims.locale } : {}),\n ...(claims.subject !== undefined ? { sub: claims.subject } : {}),\n pur: claims.purpose ?? DEFAULT_PURPOSE,\n iat: now,\n exp: now + ttl,\n jti: toBase64Url(id),\n };\n const payload = toBase64Url(encoder().encode(JSON.stringify(wire)));\n const signed = `${TOKEN_VERSION}.${payload}`;\n const key = await hmacKey(crypto, secret);\n const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder().encode(signed)));\n return `${signed}.${toBase64Url(signature)}`;\n}\n\nfunction readToken(\n request: PreviewAuthorizationRequest,\n transport: PreviewTokenTransport | undefined,\n): string | null {\n if (transport?.kind === 'header') {\n return request.headers.get(transport.name ?? DEFAULT_HEADER_NAME);\n }\n let url: URL;\n try {\n url = new URL(request.url);\n } catch {\n return null;\n }\n const values = url.searchParams.getAll(transport?.param ?? DEFAULT_QUERY_PARAM);\n return values.length === 1 ? (values[0] ?? null) : null;\n}\n\nfunction parseClaims(bytes: Uint8Array): WireClaims | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(bytes));\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const c = parsed as Record<string, unknown>;\n const optionalString = (key: string): boolean =>\n c[key] === undefined || typeof c[key] === 'string';\n if (\n c['v'] !== 1 ||\n typeof c['aud'] !== 'string' ||\n typeof c['pur'] !== 'string' ||\n typeof c['iat'] !== 'number' ||\n typeof c['exp'] !== 'number' ||\n typeof c['jti'] !== 'string' ||\n !optionalString('pth') ||\n !optionalString('loc') ||\n !optionalString('sub')\n ) {\n return undefined;\n }\n return c as unknown as WireClaims;\n}\n\nexport async function authorizeToken(\n request: PreviewAuthorizationRequest,\n strategy: SignedTokenStrategy,\n): Promise<PreviewAuthorization> {\n const secret = secretBytes(strategy.secret);\n const crypto = cryptoFor(strategy.crypto);\n if (crypto === undefined) return refused('unavailable');\n const token = readToken(request, strategy.transport);\n if (token === null || token.length === 0) return refused('missing-credential');\n if (token.length > MAX_TOKEN_LENGTH) return refused('invalid');\n const parts = token.split('.');\n if (parts.length !== 3 || parts[0] !== TOKEN_VERSION) return refused('invalid');\n const payloadText = parts[1] ?? '';\n const payloadBytes = fromBase64Url(payloadText);\n const signature = fromBase64Url(parts[2] ?? '');\n if (payloadBytes === undefined || signature?.byteLength !== 32) return refused('invalid');\n let verified: boolean;\n try {\n const key = await hmacKey(crypto, secret);\n verified = await crypto.subtle.verify(\n 'HMAC',\n key,\n signature,\n encoder().encode(`${TOKEN_VERSION}.${payloadText}`),\n );\n } catch {\n return refused('unavailable');\n }\n if (!verified) return refused('invalid');\n const claims = parseClaims(payloadBytes);\n if (claims === undefined) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.exp <= now || claims.iat > claims.exp) return refused('expired');\n if (claims.aud !== strategy.audience) return refused('wrong-audience');\n if (claims.pur !== (strategy.purpose ?? DEFAULT_PURPOSE)) return refused('wrong-purpose');\n if (claims.pth !== undefined) {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return refused('invalid');\n }\n if (claims.pth !== pathname) return refused('wrong-path');\n }\n if (claims.loc !== undefined) {\n const locale = strategy.locale?.(request);\n if (locale !== claims.loc) return refused('wrong-locale');\n }\n if (strategy.replay !== undefined) {\n try {\n if (await strategy.replay.isUsed(claims.jti)) return refused('replayed');\n await strategy.replay.markUsed(claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n }\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'signed-token',\n subject: claims.sub,\n authorizedAt: now,\n expiresAt: claims.exp,\n scope: {\n audience: claims.aud,\n ...(claims.pth !== undefined ? { path: claims.pth } : {}),\n ...(claims.loc !== undefined ? { locale: claims.loc } : {}),\n },\n payloadHeaders: {},\n }),\n };\n}\n","/**\n * Server-side preview-intent detection. Every signal here is client-controlled:\n * a positive result is a delivery hint, never proof of identity or permission.\n * Verify with `authorizePreviewRequest()` before anything privileged.\n */\n\n/** `query`: `?preview=true`; `fetch-dest`: `Sec-Fetch-Dest: iframe`; `referer`: an admin-origin Referer. */\nexport type PreviewSignal = 'query' | 'fetch-dest' | 'referer';\n\nexport interface PreviewRequestOptions {\n /** Which signals count. Default: all three. `['query']` is the adapters' 2.0 default. */\n readonly signals?: readonly PreviewSignal[];\n /** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */\n readonly queryParams?: readonly string[];\n /** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']`. */\n readonly adminOrigins?: readonly string[];\n}\n\nconst DEFAULT_QUERY_PARAMS = ['preview', 'draft', 'livePreview'] as const;\n\n/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */\nexport interface PreviewRequestLike {\n readonly url: string;\n readonly headers: { get(name: string): string | null };\n}\n\n/** Whether `request` carries live-preview intent. Intent, not authorization. */\nexport function hasPreviewIntent(\n request: PreviewRequestLike,\n options: PreviewRequestOptions = {},\n): boolean {\n const signals = new Set<PreviewSignal>(options.signals ?? ['query', 'fetch-dest', 'referer']);\n const queryParams = options.queryParams ?? DEFAULT_QUERY_PARAMS;\n\n if (signals.has('query')) {\n let url: URL | undefined;\n try {\n url = new URL(request.url);\n } catch {\n url = undefined;\n }\n if (url !== undefined) {\n for (const param of queryParams) {\n const value = url.searchParams.get(param);\n if (value === 'true' || value === '1') return true;\n }\n }\n }\n\n if (signals.has('fetch-dest') && request.headers.get('sec-fetch-dest') === 'iframe') {\n return true;\n }\n\n const adminOrigins = signals.has('referer') ? (options.adminOrigins ?? []) : [];\n if (adminOrigins.length > 0) {\n const referer = request.headers.get('referer');\n if (referer !== null) {\n try {\n const refererOrigin = new URL(referer).origin;\n for (const adminOrigin of adminOrigins) {\n try {\n if (new URL(adminOrigin).origin === refererOrigin) return true;\n } catch {\n // A malformed configured origin matches nothing.\n }\n }\n } catch {\n // A malformed referer is not a signal.\n }\n }\n }\n\n return false;\n}\n","/**\n * Typed helpers emitting the `data-payload-*` attributes the runtime reads.\n * `bindByPath` records the path through a Proxy, so a rename follows.\n */\n\nimport type { FieldName } from './paths';\n\n/** A spreadable attribute record: `<h1 {...bind<Homepage>('heroTitle')}>`. */\nexport interface FieldBindingAttributes {\n readonly 'data-payload-field': string;\n readonly 'data-payload-attribute'?: string;\n readonly 'data-payload-type'?: string;\n readonly 'data-payload-richtext'?: string;\n readonly 'data-payload-html'?: string;\n readonly 'data-payload-locale'?: string;\n readonly 'data-payload-alt'?: string;\n readonly 'data-payload-href'?: string;\n readonly 'data-payload-array-template'?: string;\n}\n\nexport interface BindOptions {\n /** Attribute to write instead of the text content, e.g. `'src'` for `<img>`. */\n readonly attribute?: string;\n /** Explicit field type, bypassing schema detection. */\n readonly type?: string;\n /** Mark the binding as Lexical rich text; needed only when the initial render is empty. */\n readonly richtext?: boolean;\n /** Render the value as sanitised HTML rather than text. */\n readonly html?: boolean;\n /** Lock this element to one locale, overriding the message locale. */\n readonly locale?: string;\n /** Field whose value becomes the image `alt`. */\n readonly alt?: string;\n /** Field whose value becomes the link `href`. */\n readonly href?: string;\n /** Markup per array item with `{{value}}` placeholders. */\n readonly arrayTemplate?: string;\n}\n\n/** `bind<Homepage>('heroTitle')`; without `T` any string is accepted. */\nexport function bind<T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n): FieldBindingAttributes {\n return buildAttributes(field, options);\n}\n\n/** `bindByPath<Homepage>(d => d.slides[0].title)` → `slides.title`; array indices are dropped because bindings resolve against the schema. */\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\nexport function bindByPath<T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n): FieldBindingAttributes {\n const path = recordPath(picker);\n if (path.length === 0) {\n throw new Error(\n 'bindByPath: the picker did not read any field — return data.<field> instead of a constant',\n );\n }\n return buildAttributes(path.join('.'), options);\n}\n\nfunction buildAttributes(field: string, options: BindOptions | undefined): FieldBindingAttributes {\n if (field.length === 0) {\n throw new Error('bind: field name must be a non-empty string');\n }\n const attrs: {\n 'data-payload-field': string;\n 'data-payload-attribute'?: string;\n 'data-payload-type'?: string;\n 'data-payload-richtext'?: string;\n 'data-payload-html'?: string;\n 'data-payload-locale'?: string;\n 'data-payload-alt'?: string;\n 'data-payload-href'?: string;\n 'data-payload-array-template'?: string;\n } = { 'data-payload-field': field };\n if (options?.attribute !== undefined) attrs['data-payload-attribute'] = options.attribute;\n if (options?.type !== undefined) attrs['data-payload-type'] = options.type;\n // Presence attributes: the runtime tests for the attribute, not its value.\n if (options?.richtext === true) attrs['data-payload-richtext'] = '';\n if (options?.html === true) attrs['data-payload-html'] = '';\n if (options?.locale !== undefined) attrs['data-payload-locale'] = options.locale;\n if (options?.alt !== undefined) attrs['data-payload-alt'] = options.alt;\n if (options?.href !== undefined) attrs['data-payload-href'] = options.href;\n if (options?.arrayTemplate !== undefined) {\n attrs['data-payload-array-template'] = options.arrayTemplate;\n }\n return attrs;\n}\n\nfunction recordPath(picker: (data: never) => unknown): string[] {\n const path: string[] = [];\n const proxy: unknown = new Proxy(\n {},\n {\n get(_target, prop: string | symbol): unknown {\n if (typeof prop === 'symbol') return undefined;\n if (/^\\d+$/.test(prop)) return proxy;\n path.push(prop);\n return proxy;\n },\n },\n );\n try {\n picker(proxy as never);\n } catch {\n // A picker doing math or JSX on the proxy throws after recording the path it meant.\n }\n return path;\n}\n","/**\n * Binding helpers gated on one authorization verdict per request: the\n * attributes publish the content model, so an unauthorized response carries\n * none and a binding is suppressed whole, never in part. See ADR 0006.\n */\n\nimport {\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n} from '@/types/authorized-preview';\nimport { bind, bindByPath, type BindOptions, type FieldBindingAttributes } from './bind';\nimport type { FieldName } from './paths';\n\nexport interface OwnerBindingAttributes {\n readonly 'data-payload-owner': string;\n}\n\n/** No attributes at all: an unauthorized response is byte-identical to one that never knew about live preview. */\nexport type SuppressedBinding = Readonly<Record<string, never>>;\n\nconst SUPPRESSED: SuppressedBinding = Object.freeze({});\n\nexport interface PreviewBindingsCommonOptions {\n /** Document this subtree belongs to, emitted as `data-payload-owner`; needed with `scopeBindingsByOwner`. */\n readonly owner?: string;\n}\n\n/** The verdict from `authorizePreviewRequest()`, or `null` for a public response. Only a branded context authorizes emission. */\nexport interface PreviewBindingsOptions extends PreviewBindingsCommonOptions {\n readonly authorization: AuthorizedPreviewContext | null;\n}\n\n/** Request-scoped binding helpers carrying one authorization decision. */\nexport interface PreviewBindings {\n readonly authorized: boolean;\n /** Typed field binding, or nothing while unauthorized. */\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /** Rename-safe field binding, or nothing while unauthorized. */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n options?: BindOptions,\n ) => FieldBindingAttributes | SuppressedBinding;\n /** Owner marker for this subtree, or nothing while unauthorized or without an owner. */\n owner: () => OwnerBindingAttributes | SuppressedBinding;\n}\n\n/** Request-scoped `bind`, `bindByPath` and `owner`, all suppressed unless `authorization` is a real context. */\nexport function createPreviewBindings(options: PreviewBindingsOptions): PreviewBindings {\n // A copied or hand-written context is a public response.\n const authorized = isAuthorizedPreviewContext(options.authorization);\n const owner = options.owner !== undefined && options.owner.length > 0 ? options.owner : undefined;\n\n return Object.freeze({\n authorized,\n bind: <T = Record<string, unknown>>(\n field: FieldName<T>,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bind<T>(field, bindOptions) : SUPPRESSED,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters\n bindByPath: <T = Record<string, unknown>>(\n picker: (data: T) => unknown,\n bindOptions?: BindOptions,\n ): FieldBindingAttributes | SuppressedBinding =>\n authorized ? bindByPath<T>(picker, bindOptions) : SUPPRESSED,\n owner: (): OwnerBindingAttributes | SuppressedBinding =>\n authorized && owner !== undefined ? { 'data-payload-owner': owner } : SUPPRESSED,\n });\n}\n","/**\n * `payload-live-preview/server` — the privileged surface: the initial draft\n * read, token issuance and verification, and the gated binding helpers. The\n * architecture policy keeps it out of every browser bundle.\n */\n\nimport {\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n} from '@/types/authorized-preview';\n\nexport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n authorizePreviewRequest,\n extractCookie,\n isAuthorizedPreviewContext,\n issuePreviewToken,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewScope,\n type FetchLike,\n type IssuePreviewTokenOptions,\n type PayloadSessionStrategy,\n type PreviewAuthorization,\n type PreviewAuthorizationOutcome,\n type PreviewAuthorizationRequest,\n type PreviewAuthorizationStrategy,\n type PreviewAuthorizationStrategyName,\n type PreviewTokenClaims,\n type PreviewTokenReplayStore,\n type PreviewTokenTransport,\n type PreviewVerifierClaims,\n type SignedTokenStrategy,\n type SubtleCryptoLike,\n type VerifierStrategy,\n} from '@security/preview-authorization';\nexport {\n hasPreviewIntent,\n type PreviewRequestLike,\n type PreviewRequestOptions,\n type PreviewSignal,\n} from '@adapters/shared/preview-request';\nexport { bind, bindByPath, createPreviewBindings } from '@dsl/index';\nexport type {\n BindOptions,\n FieldBindingAttributes,\n FieldName,\n FieldPath,\n OwnerBindingAttributes,\n PreviewBindings,\n PreviewBindingsCommonOptions,\n PreviewBindingsOptions,\n SuppressedBinding,\n ValueAt,\n} from '@dsl/index';\n\n/**\n * A `fetch`-compatible function. The read forwards a session cookie, so it is\n * `cache: 'no-store'` (never a framework data cache) and `redirect: 'error'`.\n */\nexport type PreviewFetchFunction = (\n input: string,\n init: {\n readonly headers: Record<string, string>;\n readonly signal: AbortSignal;\n readonly cache: 'no-store';\n readonly redirect: 'error';\n },\n) => Promise<{\n readonly ok: boolean;\n readonly status: number;\n json(): Promise<unknown>;\n}>;\n\n/** What a read or a failure looked like, for logs and metrics. Never carries a header value. */\nexport type PreviewFetchDiagnostic =\n | {\n readonly kind: 'response';\n readonly url: string;\n readonly status: number;\n readonly draft: boolean;\n readonly durationMs: number;\n }\n | {\n readonly kind: 'failure';\n readonly url: string;\n readonly reason: PreviewFetchFailureReason;\n readonly status: number | undefined;\n readonly draft: boolean;\n readonly durationMs: number;\n };\n\n/** The one configuration the initial read and the runtime merge share. */\nexport interface PreviewServerConfig {\n /** Payload origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST route prefix. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth for the read and for the runtime's `mergeDepth`. Required so the two cannot drift. */\n readonly depth: number;\n /** Upper bound for one read. Default 5000 ms. */\n readonly timeoutMs?: number;\n readonly fetch?: PreviewFetchFunction;\n /** Observe every read and failure — for logs and metrics, not for control flow. */\n readonly onDiagnostic?: (diagnostic: PreviewFetchDiagnostic) => void;\n}\n\n/** Why a read did not produce a document. */\nexport type PreviewFetchFailureReason =\n 'http' | 'network' | 'timeout' | 'aborted' | 'invalid-json' | 'no-fetch';\n\nexport type PreviewFetchResult<T> =\n | {\n readonly ok: true;\n /** The document, or `null` when the query matched nothing. */\n readonly data: T | null;\n /** Whether the draft was requested — `true` exactly when `authorization` was a real context. */\n readonly draft: boolean;\n readonly status: number;\n }\n | {\n readonly ok: false;\n readonly reason: PreviewFetchFailureReason;\n readonly status: number | undefined;\n readonly draft: boolean;\n /** The underlying error for `network`, `invalid-json` and `aborted`. */\n readonly cause: unknown;\n };\n\n/** Thrown in `errorMode: 'throw'` instead of returning the failed result. */\nexport class PreviewFetchError extends Error {\n readonly reason: PreviewFetchFailureReason;\n readonly status: number | undefined;\n readonly url: string;\n constructor(\n reason: PreviewFetchFailureReason,\n url: string,\n status: number | undefined,\n cause: unknown,\n ) {\n super(\n `payload-live-preview: preview read failed (${reason}${status === undefined ? '' : ` ${String(status)}`}) for ${url}`,\n { cause },\n );\n this.name = 'PreviewFetchError';\n this.reason = reason;\n this.status = status;\n this.url = url;\n }\n}\n\n/** A scalar operand of a `where` operator; `null` is sent as the literal `null`. */\nexport type PreviewWhereValue = string | number | boolean | null | readonly (string | number)[];\n\n/**\n * A `where` tree in Payload's REST query shape: `{ slug: { equals: 'about' } }`,\n * `{ or: [{ … }, { … }] }`. Arrays of trees are indexed (`where[or][0][…]`).\n */\nexport interface PreviewWhere {\n readonly [key: string]: PreviewWhere | readonly PreviewWhere[] | PreviewWhereValue;\n}\n\n/** Options every read shares; `fetchDocument` and `fetchGlobal` add their target. */\nexport interface PreviewReadOptions {\n /**\n * The verdict from `authorizePreviewRequest()`. Only a real context reads the\n * draft; `null`, a copy or a JSON round trip reads the published document.\n */\n readonly authorization: AuthorizedPreviewContext | null;\n readonly locale?: string;\n /** Extra headers for this read; the context's headers win on conflict. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Abort the read from the outside, e.g. with the request's own signal. */\n readonly signal?: AbortSignal;\n /** `'result'` (default) returns the failed result; `'throw'` throws `PreviewFetchError`. */\n readonly errorMode?: 'result' | 'throw';\n}\n\nexport interface ReadDocumentOptions extends PreviewReadOptions {\n readonly collection: string;\n readonly where?: PreviewWhere;\n}\n\nexport interface ReadGlobalOptions extends PreviewReadOptions {\n readonly global: string;\n}\n\n/** The runtime/adapter options this configuration implies — spread them into the adapter or client options. */\nexport interface PreviewRuntimeOptions {\n readonly serverURL: string;\n readonly apiRoute: string;\n readonly mergeDepth: number;\n}\n\nexport interface PreviewServer {\n readonly config: Readonly<\n Required<Pick<PreviewServerConfig, 'serverURL' | 'apiRoute' | 'depth' | 'timeoutMs'>>\n >;\n /** `{ serverURL, apiRoute, mergeDepth }` — the same depth the reads use. */\n readonly runtimeOptions: PreviewRuntimeOptions;\n fetchDocument<T = Record<string, unknown>>(\n options: ReadDocumentOptions,\n ): Promise<PreviewFetchResult<T>>;\n fetchGlobal<T = Record<string, unknown>>(\n options: ReadGlobalOptions,\n ): Promise<PreviewFetchResult<T>>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 5_000;\nconst MIN_TIMEOUT_MS = 250;\n\n/** Bind origin, route and depth once; read documents and globals with an explicit authorization verdict. */\nexport function definePreview(config: PreviewServerConfig): PreviewServer {\n const serverURL = normalizeServerURL(config.serverURL);\n const route = config.apiRoute ?? '/api';\n const apiRoute = route.startsWith('/') ? route : `/${route}`;\n if (!Number.isInteger(config.depth) || config.depth < 0) {\n throw new Error(\n `payload-live-preview: depth must be a non-negative integer, got ${String(config.depth)}`,\n );\n }\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, config.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const resolved = Object.freeze({ serverURL, apiRoute, depth: config.depth, timeoutMs });\n const runtimeOptions = Object.freeze({ serverURL, apiRoute, mergeDepth: config.depth });\n const base = `${serverURL}${apiRoute}`;\n\n async function read<T>(\n url: string,\n options: PreviewReadOptions,\n draft: boolean,\n ): Promise<PreviewFetchResult<T>> {\n const fetchImpl: PreviewFetchFunction | undefined =\n config.fetch ?? (typeof fetch === 'function' ? fetch : undefined);\n const startedAt = Date.now();\n const finish = (result: PreviewFetchResult<T>): PreviewFetchResult<T> => {\n const durationMs = Date.now() - startedAt;\n if (result.ok) {\n config.onDiagnostic?.({ kind: 'response', url, status: result.status, draft, durationMs });\n return result;\n }\n config.onDiagnostic?.({\n kind: 'failure',\n url,\n reason: result.reason,\n status: result.status,\n draft,\n durationMs,\n });\n if (options.errorMode === 'throw') {\n throw new PreviewFetchError(result.reason, url, result.status, result.cause);\n }\n return result;\n };\n if (fetchImpl === undefined) {\n return finish({ ok: false, reason: 'no-fetch', status: undefined, draft, cause: undefined });\n }\n const timeout = AbortSignal.timeout(timeoutMs);\n const signal =\n options.signal === undefined ? timeout : AbortSignal.any([timeout, options.signal]);\n const context = isAuthorizedPreviewContext(options.authorization)\n ? options.authorization\n : null;\n let response: Awaited<ReturnType<PreviewFetchFunction>>;\n try {\n response = await fetchImpl(url, {\n headers: {\n accept: 'application/json',\n ...(options.headers ?? {}),\n ...(context?.payloadHeaders ?? {}),\n },\n signal,\n cache: 'no-store',\n redirect: 'error',\n });\n } catch (cause) {\n return finish({\n ok: false,\n reason: failureReason(cause, options.signal),\n status: undefined,\n draft,\n cause,\n });\n }\n if (!response.ok) {\n return finish({\n ok: false,\n reason: 'http',\n status: response.status,\n draft,\n cause: undefined,\n });\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch (cause) {\n return finish({ ok: false, reason: 'invalid-json', status: response.status, draft, cause });\n }\n return finish({ ok: true, data: body as T, draft, status: response.status });\n }\n\n function draftFor(options: PreviewReadOptions): boolean {\n return isAuthorizedPreviewContext(options.authorization);\n }\n\n function params(options: PreviewReadOptions, draft: boolean): URLSearchParams {\n const query = new URLSearchParams();\n query.set('depth', String(config.depth));\n if (draft) query.set('draft', 'true');\n if (options.locale !== undefined) query.set('locale', options.locale);\n return query;\n }\n\n return Object.freeze({\n config: resolved,\n runtimeOptions,\n async fetchDocument<T = Record<string, unknown>>(\n options: ReadDocumentOptions,\n ): Promise<PreviewFetchResult<T>> {\n const draft = draftFor(options);\n const query = params(options, draft);\n query.set('limit', '1');\n if (options.where !== undefined) appendWhere(query, options.where, ['where']);\n const url = `${base}/${encodeURIComponent(options.collection)}?${query.toString()}`;\n const result = await read<{ docs?: T[] }>(url, options, draft);\n if (!result.ok) return result;\n const first = result.data?.docs?.[0];\n return { ok: true, data: first ?? null, draft, status: result.status };\n },\n async fetchGlobal<T = Record<string, unknown>>(\n options: ReadGlobalOptions,\n ): Promise<PreviewFetchResult<T>> {\n const draft = draftFor(options);\n const url = `${base}/globals/${encodeURIComponent(options.global)}?${params(options, draft).toString()}`;\n return read<T>(url, options, draft);\n },\n });\n}\n\nfunction normalizeServerURL(serverURL: string): string {\n let url: URL;\n try {\n url = new URL(serverURL);\n } catch {\n throw new Error(`payload-live-preview: serverURL \"${serverURL}\" is not an absolute URL`);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new Error(`payload-live-preview: serverURL must be http(s), got \"${url.protocol}\"`);\n }\n return `${url.origin}${url.pathname.replace(/\\/+$/, '')}`;\n}\n\nfunction failureReason(\n cause: unknown,\n external: AbortSignal | undefined,\n): PreviewFetchFailureReason {\n if (external?.aborted === true) return 'aborted';\n const name =\n typeof cause === 'object' && cause !== null ? (cause as { name?: unknown }).name : undefined;\n if (name === 'TimeoutError') return 'timeout';\n if (name === 'AbortError') return 'aborted';\n return 'network';\n}\n\nfunction isWhereTree(value: unknown): value is PreviewWhere {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction queryName(path: readonly string[]): string {\n return path.map((segment, index) => (index === 0 ? segment : `[${segment}]`)).join('');\n}\n\nfunction appendWhere(query: URLSearchParams, node: PreviewWhere, path: readonly string[]): void {\n for (const [key, value] of Object.entries(node)) {\n const nextPath = [...path, key];\n if (isWhereTree(value)) {\n appendWhere(query, value, nextPath);\n } else if (Array.isArray(value) && value.some(isWhereTree)) {\n // `or` / `and`: Payload's query parser turns bracketed indices back into an array.\n (value as readonly PreviewWhere[]).forEach((branch, index) => {\n appendWhere(query, branch, [...nextPath, String(index)]);\n });\n } else if (Array.isArray(value)) {\n query.set(queryName(nextPath), (value as readonly (string | number)[]).map(String).join(','));\n } else {\n // Only `null` is still an object here; Payload's query sanitizers read the literal back.\n query.set(queryName(nextPath), typeof value === 'object' ? 'null' : String(value));\n }\n }\n}\n","/**\n * Authorized preview context: the one verdict every privileged preview\n * decision is keyed on. Intent (`?preview=true`, an iframe destination, a\n * referer) is client-chosen; this turns a session, a signed token or the\n * application's own verifier into a branded context. Threat model: ADR 0006.\n */\n\nimport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n createAuthorizedPreviewContext,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n} from '@/types/authorized-preview';\nimport {\n refused,\n type PreviewAuthorization,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nimport { authorizeSession, type PayloadSessionStrategy } from './preview-session';\nimport { authorizeToken, type SignedTokenStrategy } from './preview-token';\n\nexport {\n AUTHORIZED_PREVIEW_BRAND_KEY,\n isAuthorizedPreviewContext,\n type AuthorizedPreviewContext,\n type AuthorizedPreviewScope,\n type PreviewAuthorizationStrategyName,\n};\nexport {\n PreviewConfigurationError,\n type PreviewAuthorization,\n type PreviewAuthorizationOutcome,\n type PreviewAuthorizationRequest,\n} from './preview-verdict';\nexport { extractCookie, type FetchLike, type PayloadSessionStrategy } from './preview-session';\nexport {\n issuePreviewToken,\n type IssuePreviewTokenOptions,\n type PreviewTokenClaims,\n type PreviewTokenReplayStore,\n type PreviewTokenTransport,\n type SignedTokenStrategy,\n type SubtleCryptoLike,\n} from './preview-token';\n\n/** Claims a consumer verifier returns for a request it accepts. */\nexport interface PreviewVerifierClaims {\n readonly subject?: string;\n readonly expiresAt?: number;\n readonly scope?: AuthorizedPreviewScope;\n readonly payloadHeaders?: Readonly<Record<string, string>>;\n}\n\n/** The application's own verification: claims authorize, `null` refuses, a throw is `unavailable`. */\nexport interface VerifierStrategy {\n readonly type: 'verifier';\n readonly verify: (\n request: PreviewAuthorizationRequest,\n ) => Promise<PreviewVerifierClaims | null> | PreviewVerifierClaims | null;\n readonly now?: () => number;\n}\n\nexport type PreviewAuthorizationStrategy =\n PayloadSessionStrategy | SignedTokenStrategy | VerifierStrategy;\n\n/** Decide whether `request` is an authorized preview; refusals resolve to `{ authorized: false }` and only a `PreviewConfigurationError` throws. */\nexport async function authorizePreviewRequest(\n request: PreviewAuthorizationRequest,\n strategy: PreviewAuthorizationStrategy,\n): Promise<PreviewAuthorization> {\n switch (strategy.type) {\n case 'payload-session':\n return authorizeSession(request, strategy);\n case 'signed-token':\n return authorizeToken(request, strategy);\n case 'verifier':\n return authorizeVerifier(request, strategy);\n }\n}\n\nasync function authorizeVerifier(\n request: PreviewAuthorizationRequest,\n strategy: VerifierStrategy,\n): Promise<PreviewAuthorization> {\n let claims: PreviewVerifierClaims | null;\n try {\n claims = await strategy.verify(request);\n } catch {\n return refused('unavailable');\n }\n if (claims === null) return refused('invalid');\n const now = (strategy.now ?? Date.now)();\n if (claims.expiresAt !== undefined && claims.expiresAt <= now) return refused('expired');\n return {\n authorized: true,\n outcome: 'authorized',\n context: createAuthorizedPreviewContext({\n strategy: 'verifier',\n subject: claims.subject,\n authorizedAt: now,\n expiresAt: claims.expiresAt,\n scope: claims.scope ?? {},\n payloadHeaders: claims.payloadHeaders ?? {},\n }),\n };\n}\n"],"mappings":"aAyBO,IAAMA,EAA+B,kDA8BtCC,EAAQC,OAAOC,IAAIH,GAGlB,SAASI,2BAA2BC,GACzC,MACmB,iBAAVA,GACG,OAAVA,IACmD,IAAlDA,EAAuCJ,IACxCK,OAAOC,SAASF,EAEpB,CAGO,SAASG,EACdC,GAUA,OARgBH,OAAOI,OAAO,IACzBD,EACHE,MAAOL,OAAOI,OAAO,IAAKD,EAAOE,QACjCC,eAAgBN,OAAOI,OAAO,IAAKD,EAAOG,iBAC1CX,CAACA,IAAQ,EACTD,CAACA,IAA+B,GAIpC,CCpCO,IAAMa,EAAN,cAAwCC,MAC3BC,KAAO,6BAWpB,SAASC,EACdC,GAEA,MAAO,CAAEC,YAAY,EAAOD,UAASE,QAAS,KAChD,CCxBA,IAAMC,EAAqB,QAKrBC,EAAsB,iCACtBC,EAAuB,qBAQtB,SAASC,EACdC,EACAT,EACAU,EAbgC,MAehC,GAAe,OAAXD,GAAqC,IAAlBA,EAAOE,OAAc,OAAO,KACnD,M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AElB,MAAM6B,EAASD,EAAYiC,EAAQhC,QAC7B4F,GAAO5D,EAAQ4D,KAAOC,KAAKD,OAC3BgH,EAAM7G,KAAK8G,IAtEA,KAsEgB9G,KAAKC,IAAI,EAAGwC,EAAOsE,OAvE/B,MAwEf7F,EAAK,IAAIvF,WAAW,IAC1BjB,EAAOsM,gBAAgB9F,GACvB,MAAM+F,EAAmB,CACvBC,EAAG,EACH/D,IAAKV,EAAOW,iBACQ,IAAhBX,EAAOpG,KAAqB,CAAEkH,IAAKd,EAAOpG,MAAS,WACjC,IAAlBoG,EAAOvF,OAAuB,CAAEuG,IAAKhB,EAAOvF,QAAW,WACpC,IAAnBuF,EAAOhB,QAAwB,CAAEqC,IAAKrB,EAAOhB,SAAY,GAC7D4B,IAAKZ,EAAOa,SAAW1J,EACvBsJ,IAAKrD,EACL0B,IAAK1B,EAAMgH,EACXjD,IAAK5I,EAAYkG,IAEbiG,EAAUnM,EAAYlB,IAAUK,OAAOwI,KAAKyE,UAAUH,KACtDI,EAAS,GAAGxN,KAAiBsN,IAC7BxI,QAAY9D,EAAQH,EAAQT,GAElC,MAAO,GAAGoN,KAAUrM,EADF,IAAIW,iBAAiBjB,EAAOC,OAAO2M,KAAK,OAAQ3I,EAAK7E,IAAUK,OAAOkN,OAE1F","ignoreList":[]}
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The authorized preview context's shape and brand, in the leaf `types` domain
|
|
3
|
+
* so producer and consumers recognise the same context. See ADR 0006.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The brand key, in the type and on the object.
|
|
7
|
+
*
|
|
8
|
+
* This was a `unique symbol` until 2026-08-30. A `unique symbol` is nominal per
|
|
9
|
+
* *declaration*, and the published entries each carry their own declaration
|
|
10
|
+
* file — so `AuthorizedPreviewContext` from the root barrel was a different
|
|
11
|
+
* type from the one in `./server` or in an adapter, and the documented flow
|
|
12
|
+
* (authorize once, hand the context to the adapter hook and to the draft read)
|
|
13
|
+
* did not type-check in any combination a consumer can write.
|
|
14
|
+
*
|
|
15
|
+
* That is the same trap the runtime brand below already avoids by using
|
|
16
|
+
* `Symbol.for` rather than `Symbol()`; the lesson simply had not reached the
|
|
17
|
+
* type. A shared string literal is identical in every bundle for the same
|
|
18
|
+
* reason a registry symbol is.
|
|
19
|
+
*
|
|
20
|
+
* It is not what makes a context trustworthy. `isAuthorizedPreviewContext`
|
|
21
|
+
* decides that, on the registry symbol and on `Object.isFrozen`, and every
|
|
22
|
+
* consumption point calls it — the adapter policy, the draft read and the
|
|
23
|
+
* binding emitter. Writing this key by hand buys nothing.
|
|
24
|
+
*/
|
|
25
|
+
declare const AUTHORIZED_PREVIEW_BRAND_KEY = "payload-live-preview.authorized-preview-context";
|
|
26
|
+
type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';
|
|
27
|
+
/** What a context is bound to; every field is optional because every strategy binds differently. */
|
|
28
|
+
interface AuthorizedPreviewScope {
|
|
29
|
+
/** The site origin the credential was issued for. */
|
|
30
|
+
readonly audience?: string;
|
|
31
|
+
/** The request pathname the credential is valid for. */
|
|
32
|
+
readonly path?: string;
|
|
33
|
+
readonly locale?: string;
|
|
34
|
+
}
|
|
35
|
+
/** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */
|
|
36
|
+
interface AuthorizedPreviewContext {
|
|
37
|
+
readonly [AUTHORIZED_PREVIEW_BRAND_KEY]: true;
|
|
38
|
+
readonly strategy: PreviewAuthorizationStrategyName;
|
|
39
|
+
/** The user id, token subject, or whatever the verifier named. */
|
|
40
|
+
readonly subject: string | undefined;
|
|
41
|
+
/** Unix milliseconds. */
|
|
42
|
+
readonly authorizedAt: number;
|
|
43
|
+
/** Unix milliseconds, or `undefined` when the strategy does not know. */
|
|
44
|
+
readonly expiresAt: number | undefined;
|
|
45
|
+
readonly scope: AuthorizedPreviewScope;
|
|
46
|
+
/** The minimal request material a draft read forwards to Payload — one verified cookie, never the whole `Cookie` header. */
|
|
47
|
+
readonly payloadHeaders: Readonly<Record<string, string>>;
|
|
48
|
+
}
|
|
49
|
+
/** Whether `value` was produced by `authorizePreviewRequest()`; a copy or JSON round trip is not. */
|
|
50
|
+
declare function isAuthorizedPreviewContext(value: unknown): value is AuthorizedPreviewContext;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The verdict shape every authorization strategy produces, and the one error
|
|
54
|
+
* class that is allowed to escape it. Kept apart from the strategies so the
|
|
55
|
+
* adapters can import the error without pulling in HMAC or session code.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/** Why a request was refused. `'authorized'` is the one non-refusal. */
|
|
59
|
+
type PreviewAuthorizationOutcome = 'authorized' | 'missing-credential' | 'invalid' | 'expired' | 'wrong-audience' | 'wrong-path' | 'wrong-locale' | 'wrong-purpose' | 'replayed' | 'unavailable';
|
|
60
|
+
/** The result of `authorizePreviewRequest()`: a verdict, never an exception. */
|
|
61
|
+
type PreviewAuthorization = {
|
|
62
|
+
readonly authorized: true;
|
|
63
|
+
readonly outcome: 'authorized';
|
|
64
|
+
readonly context: AuthorizedPreviewContext;
|
|
65
|
+
} | {
|
|
66
|
+
readonly authorized: false;
|
|
67
|
+
readonly outcome: Exclude<PreviewAuthorizationOutcome, 'authorized'>;
|
|
68
|
+
readonly context: null;
|
|
69
|
+
};
|
|
70
|
+
/** The request shape every strategy reads: a URL and a header getter. */
|
|
71
|
+
interface PreviewAuthorizationRequest {
|
|
72
|
+
readonly url: string;
|
|
73
|
+
readonly headers: {
|
|
74
|
+
get(name: string): string | null;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The `payload-session` strategy: forward exactly one named cookie to
|
|
80
|
+
* `GET <serverURL>/api/<usersSlug>/me` and authorize when a user comes back.
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
/** A `fetch`-compatible function, injectable for tests. */
|
|
84
|
+
type FetchLike = (input: string, init: {
|
|
85
|
+
readonly headers: Record<string, string>;
|
|
86
|
+
readonly signal: AbortSignal;
|
|
87
|
+
}) => Promise<{
|
|
88
|
+
readonly ok: boolean;
|
|
89
|
+
readonly status: number;
|
|
90
|
+
json(): Promise<unknown>;
|
|
91
|
+
}>;
|
|
92
|
+
interface PayloadSessionStrategy {
|
|
93
|
+
readonly type: 'payload-session';
|
|
94
|
+
/** Payload server origin, e.g. `https://cms.example.com`. */
|
|
95
|
+
readonly serverURL: string;
|
|
96
|
+
/** Auth collection slug; `users` unless the project renamed it. */
|
|
97
|
+
readonly usersSlug?: string;
|
|
98
|
+
/** Cookie name; Payload's default is `payload-token`. */
|
|
99
|
+
readonly cookieName?: string;
|
|
100
|
+
/** Upper bound for the `/me` round trip. Below 250 ms is raised to 250 ms; default 3000. */
|
|
101
|
+
readonly timeoutMs?: number;
|
|
102
|
+
/** Longest cookie value accepted; longer ones are refused as `invalid`. Default 4096. */
|
|
103
|
+
readonly maxCookieLength?: number;
|
|
104
|
+
readonly fetch?: FetchLike;
|
|
105
|
+
/** Clock, Unix milliseconds. Injectable for tests. */
|
|
106
|
+
readonly now?: () => number;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Exactly one value for `name`, or `null` when absent, empty, over `maxLength`
|
|
110
|
+
* or repeated — a repeated cookie is ambiguous and is refused, not guessed.
|
|
111
|
+
*/
|
|
112
|
+
declare function extractCookie(header: string | null, name: string, maxLength?: number): string | null;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The `signed-token` strategy: a short-lived HMAC-SHA256 token minted by the
|
|
116
|
+
* Payload side and verified by the site. Format and bindings: ADR 0006 §3.
|
|
117
|
+
*/
|
|
118
|
+
|
|
119
|
+
/** The subset of Web Crypto the token strategy needs, injectable for environments that expose it elsewhere. */
|
|
120
|
+
interface SubtleCryptoLike {
|
|
121
|
+
readonly subtle: {
|
|
122
|
+
importKey(format: 'raw', keyData: Uint8Array, algorithm: {
|
|
123
|
+
readonly name: 'HMAC';
|
|
124
|
+
readonly hash: 'SHA-256';
|
|
125
|
+
}, extractable: false, keyUsages: readonly ('sign' | 'verify')[]): Promise<CryptoKey>;
|
|
126
|
+
sign(algorithm: 'HMAC', key: CryptoKey, data: Uint8Array): Promise<ArrayBuffer>;
|
|
127
|
+
verify(algorithm: 'HMAC', key: CryptoKey, signature: Uint8Array, data: Uint8Array): Promise<boolean>;
|
|
128
|
+
};
|
|
129
|
+
getRandomValues<T extends Uint8Array>(array: T): T;
|
|
130
|
+
}
|
|
131
|
+
/** Where a signed token is read from on the request. */
|
|
132
|
+
type PreviewTokenTransport = {
|
|
133
|
+
readonly kind: 'query';
|
|
134
|
+
readonly param?: string;
|
|
135
|
+
} | {
|
|
136
|
+
readonly kind: 'header';
|
|
137
|
+
readonly name?: string;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Optional replay store. Not shipped: a per-process memory is useless behind
|
|
141
|
+
* a load balancer, so the store is a deployment decision.
|
|
142
|
+
*/
|
|
143
|
+
interface PreviewTokenReplayStore {
|
|
144
|
+
isUsed(id: string): Promise<boolean> | boolean;
|
|
145
|
+
markUsed(id: string, expiresAt: number): Promise<void> | void;
|
|
146
|
+
}
|
|
147
|
+
interface SignedTokenStrategy {
|
|
148
|
+
readonly type: 'signed-token';
|
|
149
|
+
/** Shared secret, at least 32 bytes; shorter ones are refused on first use. */
|
|
150
|
+
readonly secret: string | Uint8Array;
|
|
151
|
+
/** The site origin tokens must name, e.g. `https://www.example.com`. */
|
|
152
|
+
readonly audience: string;
|
|
153
|
+
/** Purpose string tokens must carry. Default `live-preview`. */
|
|
154
|
+
readonly purpose?: string;
|
|
155
|
+
/** Default: query parameter `previewToken`. */
|
|
156
|
+
readonly transport?: PreviewTokenTransport;
|
|
157
|
+
/** Resolve the request's locale for the `loc` binding. Unset: tokens with `loc` are refused as `wrong-locale`. */
|
|
158
|
+
readonly locale?: (request: PreviewAuthorizationRequest) => string | undefined;
|
|
159
|
+
readonly replay?: PreviewTokenReplayStore;
|
|
160
|
+
readonly crypto?: SubtleCryptoLike;
|
|
161
|
+
readonly now?: () => number;
|
|
162
|
+
}
|
|
163
|
+
/** What `issuePreviewToken()` binds a token to. */
|
|
164
|
+
interface PreviewTokenClaims {
|
|
165
|
+
/** The site origin the token is for. */
|
|
166
|
+
readonly audience: string;
|
|
167
|
+
/** Request pathname the token opens. Recommended; omit only for a single-page preview. */
|
|
168
|
+
readonly path?: string;
|
|
169
|
+
readonly locale?: string;
|
|
170
|
+
readonly subject?: string;
|
|
171
|
+
readonly purpose?: string;
|
|
172
|
+
/** Lifetime in milliseconds. Default ten minutes; capped at one hour. */
|
|
173
|
+
readonly ttlMs?: number;
|
|
174
|
+
}
|
|
175
|
+
interface IssuePreviewTokenOptions {
|
|
176
|
+
readonly secret: string | Uint8Array;
|
|
177
|
+
readonly crypto?: SubtleCryptoLike;
|
|
178
|
+
readonly now?: () => number;
|
|
179
|
+
}
|
|
180
|
+
/** Mint a preview token on the Payload side; pair with `buildLivePreviewUrl`. */
|
|
181
|
+
declare function issuePreviewToken(claims: PreviewTokenClaims, options: IssuePreviewTokenOptions): Promise<string>;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Authorized preview context: the one verdict every privileged preview
|
|
185
|
+
* decision is keyed on. Intent (`?preview=true`, an iframe destination, a
|
|
186
|
+
* referer) is client-chosen; this turns a session, a signed token or the
|
|
187
|
+
* application's own verifier into a branded context. Threat model: ADR 0006.
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
/** Claims a consumer verifier returns for a request it accepts. */
|
|
191
|
+
interface PreviewVerifierClaims {
|
|
192
|
+
readonly subject?: string;
|
|
193
|
+
readonly expiresAt?: number;
|
|
194
|
+
readonly scope?: AuthorizedPreviewScope;
|
|
195
|
+
readonly payloadHeaders?: Readonly<Record<string, string>>;
|
|
196
|
+
}
|
|
197
|
+
/** The application's own verification: claims authorize, `null` refuses, a throw is `unavailable`. */
|
|
198
|
+
interface VerifierStrategy {
|
|
199
|
+
readonly type: 'verifier';
|
|
200
|
+
readonly verify: (request: PreviewAuthorizationRequest) => Promise<PreviewVerifierClaims | null> | PreviewVerifierClaims | null;
|
|
201
|
+
readonly now?: () => number;
|
|
202
|
+
}
|
|
203
|
+
type PreviewAuthorizationStrategy = PayloadSessionStrategy | SignedTokenStrategy | VerifierStrategy;
|
|
204
|
+
/** Decide whether `request` is an authorized preview; refusals resolve to `{ authorized: false }` and only a `PreviewConfigurationError` throws. */
|
|
205
|
+
declare function authorizePreviewRequest(request: PreviewAuthorizationRequest, strategy: PreviewAuthorizationStrategy): Promise<PreviewAuthorization>;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Server-side preview-intent detection. Every signal here is client-controlled:
|
|
209
|
+
* a positive result is a delivery hint, never proof of identity or permission.
|
|
210
|
+
* Verify with `authorizePreviewRequest()` before anything privileged.
|
|
211
|
+
*/
|
|
212
|
+
/** `query`: `?preview=true`; `fetch-dest`: `Sec-Fetch-Dest: iframe`; `referer`: an admin-origin Referer. */
|
|
213
|
+
type PreviewSignal = 'query' | 'fetch-dest' | 'referer';
|
|
214
|
+
interface PreviewRequestOptions {
|
|
215
|
+
/** Which signals count. Default: all three. `['query']` is the adapters' 2.0 default. */
|
|
216
|
+
readonly signals?: readonly PreviewSignal[];
|
|
217
|
+
/** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */
|
|
218
|
+
readonly queryParams?: readonly string[];
|
|
219
|
+
/** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']`. */
|
|
220
|
+
readonly adminOrigins?: readonly string[];
|
|
221
|
+
}
|
|
222
|
+
/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */
|
|
223
|
+
interface PreviewRequestLike {
|
|
224
|
+
readonly url: string;
|
|
225
|
+
readonly headers: {
|
|
226
|
+
get(name: string): string | null;
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** Whether `request` carries live-preview intent. Intent, not authorization. */
|
|
230
|
+
declare function hasPreviewIntent(request: PreviewRequestLike, options?: PreviewRequestOptions): boolean;
|
|
231
|
+
|
|
232
|
+
/** Type-level field paths, so a binding name is checked at compile time against the codegen schema. */
|
|
233
|
+
/** String keys of `T`. */
|
|
234
|
+
type FieldName<T> = Extract<keyof T, string>;
|
|
235
|
+
/** Dotted paths into `T`, capped at three levels so IntelliSense stays usable. */
|
|
236
|
+
type FieldPath<T, Depth extends 0 | 1 | 2 | 3 = 3> = Depth extends 0 ? never : T extends readonly (infer U)[] ? FieldPath<U, Prev<Depth>> : T extends object ? {
|
|
237
|
+
[K in Extract<keyof T, string>]: K | (T[K] extends object ? `${K}.${FieldPath<T[K], Prev<Depth>>}` : never);
|
|
238
|
+
}[Extract<keyof T, string>] : never;
|
|
239
|
+
type Prev<N extends 0 | 1 | 2 | 3> = N extends 3 ? 2 : N extends 2 ? 1 : N extends 1 ? 0 : 0;
|
|
240
|
+
/** The value type at a dotted path, or `unknown` when the path does not exist. */
|
|
241
|
+
type ValueAt<T, P extends string> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? T[Head] extends readonly (infer U)[] ? ValueAt<U, Rest> : T[Head] extends object ? ValueAt<T[Head], Rest> : unknown : unknown : P extends keyof T ? T[P] : unknown;
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Typed helpers emitting the `data-payload-*` attributes the runtime reads.
|
|
245
|
+
* `bindByPath` records the path through a Proxy, so a rename follows.
|
|
246
|
+
*/
|
|
247
|
+
|
|
248
|
+
/** A spreadable attribute record: `<h1 {...bind<Homepage>('heroTitle')}>`. */
|
|
249
|
+
interface FieldBindingAttributes {
|
|
250
|
+
readonly 'data-payload-field': string;
|
|
251
|
+
readonly 'data-payload-attribute'?: string;
|
|
252
|
+
readonly 'data-payload-type'?: string;
|
|
253
|
+
readonly 'data-payload-richtext'?: string;
|
|
254
|
+
readonly 'data-payload-html'?: string;
|
|
255
|
+
readonly 'data-payload-locale'?: string;
|
|
256
|
+
readonly 'data-payload-alt'?: string;
|
|
257
|
+
readonly 'data-payload-href'?: string;
|
|
258
|
+
readonly 'data-payload-array-template'?: string;
|
|
259
|
+
}
|
|
260
|
+
interface BindOptions {
|
|
261
|
+
/** Attribute to write instead of the text content, e.g. `'src'` for `<img>`. */
|
|
262
|
+
readonly attribute?: string;
|
|
263
|
+
/** Explicit field type, bypassing schema detection. */
|
|
264
|
+
readonly type?: string;
|
|
265
|
+
/** Mark the binding as Lexical rich text; needed only when the initial render is empty. */
|
|
266
|
+
readonly richtext?: boolean;
|
|
267
|
+
/** Render the value as sanitised HTML rather than text. */
|
|
268
|
+
readonly html?: boolean;
|
|
269
|
+
/** Lock this element to one locale, overriding the message locale. */
|
|
270
|
+
readonly locale?: string;
|
|
271
|
+
/** Field whose value becomes the image `alt`. */
|
|
272
|
+
readonly alt?: string;
|
|
273
|
+
/** Field whose value becomes the link `href`. */
|
|
274
|
+
readonly href?: string;
|
|
275
|
+
/** Markup per array item with `{{value}}` placeholders. */
|
|
276
|
+
readonly arrayTemplate?: string;
|
|
277
|
+
}
|
|
278
|
+
/** `bind<Homepage>('heroTitle')`; without `T` any string is accepted. */
|
|
279
|
+
declare function bind<T = Record<string, unknown>>(field: FieldName<T>, options?: BindOptions): FieldBindingAttributes;
|
|
280
|
+
/** `bindByPath<Homepage>(d => d.slides[0].title)` → `slides.title`; array indices are dropped because bindings resolve against the schema. */
|
|
281
|
+
declare function bindByPath<T = Record<string, unknown>>(picker: (data: T) => unknown, options?: BindOptions): FieldBindingAttributes;
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Binding helpers gated on one authorization verdict per request: the
|
|
285
|
+
* attributes publish the content model, so an unauthorized response carries
|
|
286
|
+
* none and a binding is suppressed whole, never in part. See ADR 0006.
|
|
287
|
+
*/
|
|
288
|
+
|
|
289
|
+
interface OwnerBindingAttributes {
|
|
290
|
+
readonly 'data-payload-owner': string;
|
|
291
|
+
}
|
|
292
|
+
/** No attributes at all: an unauthorized response is byte-identical to one that never knew about live preview. */
|
|
293
|
+
type SuppressedBinding = Readonly<Record<string, never>>;
|
|
294
|
+
interface PreviewBindingsCommonOptions {
|
|
295
|
+
/** Document this subtree belongs to, emitted as `data-payload-owner`; needed with `scopeBindingsByOwner`. */
|
|
296
|
+
readonly owner?: string;
|
|
297
|
+
}
|
|
298
|
+
/** The verdict from `authorizePreviewRequest()`, or `null` for a public response. Only a branded context authorizes emission. */
|
|
299
|
+
interface PreviewBindingsOptions extends PreviewBindingsCommonOptions {
|
|
300
|
+
readonly authorization: AuthorizedPreviewContext | null;
|
|
301
|
+
}
|
|
302
|
+
/** Request-scoped binding helpers carrying one authorization decision. */
|
|
303
|
+
interface PreviewBindings {
|
|
304
|
+
readonly authorized: boolean;
|
|
305
|
+
/** Typed field binding, or nothing while unauthorized. */
|
|
306
|
+
bind: <T = Record<string, unknown>>(field: FieldName<T>, options?: BindOptions) => FieldBindingAttributes | SuppressedBinding;
|
|
307
|
+
/** Rename-safe field binding, or nothing while unauthorized. */
|
|
308
|
+
bindByPath: <T = Record<string, unknown>>(picker: (data: T) => unknown, options?: BindOptions) => FieldBindingAttributes | SuppressedBinding;
|
|
309
|
+
/** Owner marker for this subtree, or nothing while unauthorized or without an owner. */
|
|
310
|
+
owner: () => OwnerBindingAttributes | SuppressedBinding;
|
|
311
|
+
}
|
|
312
|
+
/** Request-scoped `bind`, `bindByPath` and `owner`, all suppressed unless `authorization` is a real context. */
|
|
313
|
+
declare function createPreviewBindings(options: PreviewBindingsOptions): PreviewBindings;
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* `payload-live-preview/server` — the privileged surface: the initial draft
|
|
317
|
+
* read, token issuance and verification, and the gated binding helpers. The
|
|
318
|
+
* architecture policy keeps it out of every browser bundle.
|
|
319
|
+
*/
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* A `fetch`-compatible function. The read forwards a session cookie, so it is
|
|
323
|
+
* `cache: 'no-store'` (never a framework data cache) and `redirect: 'error'`.
|
|
324
|
+
*/
|
|
325
|
+
type PreviewFetchFunction = (input: string, init: {
|
|
326
|
+
readonly headers: Record<string, string>;
|
|
327
|
+
readonly signal: AbortSignal;
|
|
328
|
+
readonly cache: 'no-store';
|
|
329
|
+
readonly redirect: 'error';
|
|
330
|
+
}) => Promise<{
|
|
331
|
+
readonly ok: boolean;
|
|
332
|
+
readonly status: number;
|
|
333
|
+
json(): Promise<unknown>;
|
|
334
|
+
}>;
|
|
335
|
+
/** What a read or a failure looked like, for logs and metrics. Never carries a header value. */
|
|
336
|
+
type PreviewFetchDiagnostic = {
|
|
337
|
+
readonly kind: 'response';
|
|
338
|
+
readonly url: string;
|
|
339
|
+
readonly status: number;
|
|
340
|
+
readonly draft: boolean;
|
|
341
|
+
readonly durationMs: number;
|
|
342
|
+
} | {
|
|
343
|
+
readonly kind: 'failure';
|
|
344
|
+
readonly url: string;
|
|
345
|
+
readonly reason: PreviewFetchFailureReason;
|
|
346
|
+
readonly status: number | undefined;
|
|
347
|
+
readonly draft: boolean;
|
|
348
|
+
readonly durationMs: number;
|
|
349
|
+
};
|
|
350
|
+
/** The one configuration the initial read and the runtime merge share. */
|
|
351
|
+
interface PreviewServerConfig {
|
|
352
|
+
/** Payload origin, e.g. `https://cms.example.com`. */
|
|
353
|
+
readonly serverURL: string;
|
|
354
|
+
/** REST route prefix. Default `/api`. */
|
|
355
|
+
readonly apiRoute?: string;
|
|
356
|
+
/** Population depth for the read and for the runtime's `mergeDepth`. Required so the two cannot drift. */
|
|
357
|
+
readonly depth: number;
|
|
358
|
+
/** Upper bound for one read. Default 5000 ms. */
|
|
359
|
+
readonly timeoutMs?: number;
|
|
360
|
+
readonly fetch?: PreviewFetchFunction;
|
|
361
|
+
/** Observe every read and failure — for logs and metrics, not for control flow. */
|
|
362
|
+
readonly onDiagnostic?: (diagnostic: PreviewFetchDiagnostic) => void;
|
|
363
|
+
}
|
|
364
|
+
/** Why a read did not produce a document. */
|
|
365
|
+
type PreviewFetchFailureReason = 'http' | 'network' | 'timeout' | 'aborted' | 'invalid-json' | 'no-fetch';
|
|
366
|
+
type PreviewFetchResult<T> = {
|
|
367
|
+
readonly ok: true;
|
|
368
|
+
/** The document, or `null` when the query matched nothing. */
|
|
369
|
+
readonly data: T | null;
|
|
370
|
+
/** Whether the draft was requested — `true` exactly when `authorization` was a real context. */
|
|
371
|
+
readonly draft: boolean;
|
|
372
|
+
readonly status: number;
|
|
373
|
+
} | {
|
|
374
|
+
readonly ok: false;
|
|
375
|
+
readonly reason: PreviewFetchFailureReason;
|
|
376
|
+
readonly status: number | undefined;
|
|
377
|
+
readonly draft: boolean;
|
|
378
|
+
/** The underlying error for `network`, `invalid-json` and `aborted`. */
|
|
379
|
+
readonly cause: unknown;
|
|
380
|
+
};
|
|
381
|
+
/** Thrown in `errorMode: 'throw'` instead of returning the failed result. */
|
|
382
|
+
declare class PreviewFetchError extends Error {
|
|
383
|
+
readonly reason: PreviewFetchFailureReason;
|
|
384
|
+
readonly status: number | undefined;
|
|
385
|
+
readonly url: string;
|
|
386
|
+
constructor(reason: PreviewFetchFailureReason, url: string, status: number | undefined, cause: unknown);
|
|
387
|
+
}
|
|
388
|
+
/** A scalar operand of a `where` operator; `null` is sent as the literal `null`. */
|
|
389
|
+
type PreviewWhereValue = string | number | boolean | null | readonly (string | number)[];
|
|
390
|
+
/**
|
|
391
|
+
* A `where` tree in Payload's REST query shape: `{ slug: { equals: 'about' } }`,
|
|
392
|
+
* `{ or: [{ … }, { … }] }`. Arrays of trees are indexed (`where[or][0][…]`).
|
|
393
|
+
*/
|
|
394
|
+
interface PreviewWhere {
|
|
395
|
+
readonly [key: string]: PreviewWhere | readonly PreviewWhere[] | PreviewWhereValue;
|
|
396
|
+
}
|
|
397
|
+
/** Options every read shares; `fetchDocument` and `fetchGlobal` add their target. */
|
|
398
|
+
interface PreviewReadOptions {
|
|
399
|
+
/**
|
|
400
|
+
* The verdict from `authorizePreviewRequest()`. Only a real context reads the
|
|
401
|
+
* draft; `null`, a copy or a JSON round trip reads the published document.
|
|
402
|
+
*/
|
|
403
|
+
readonly authorization: AuthorizedPreviewContext | null;
|
|
404
|
+
readonly locale?: string;
|
|
405
|
+
/** Extra headers for this read; the context's headers win on conflict. */
|
|
406
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
407
|
+
/** Abort the read from the outside, e.g. with the request's own signal. */
|
|
408
|
+
readonly signal?: AbortSignal;
|
|
409
|
+
/** `'result'` (default) returns the failed result; `'throw'` throws `PreviewFetchError`. */
|
|
410
|
+
readonly errorMode?: 'result' | 'throw';
|
|
411
|
+
}
|
|
412
|
+
interface ReadDocumentOptions extends PreviewReadOptions {
|
|
413
|
+
readonly collection: string;
|
|
414
|
+
readonly where?: PreviewWhere;
|
|
415
|
+
}
|
|
416
|
+
interface ReadGlobalOptions extends PreviewReadOptions {
|
|
417
|
+
readonly global: string;
|
|
418
|
+
}
|
|
419
|
+
/** The runtime/adapter options this configuration implies — spread them into the adapter or client options. */
|
|
420
|
+
interface PreviewRuntimeOptions {
|
|
421
|
+
readonly serverURL: string;
|
|
422
|
+
readonly apiRoute: string;
|
|
423
|
+
readonly mergeDepth: number;
|
|
424
|
+
}
|
|
425
|
+
interface PreviewServer {
|
|
426
|
+
readonly config: Readonly<Required<Pick<PreviewServerConfig, 'serverURL' | 'apiRoute' | 'depth' | 'timeoutMs'>>>;
|
|
427
|
+
/** `{ serverURL, apiRoute, mergeDepth }` — the same depth the reads use. */
|
|
428
|
+
readonly runtimeOptions: PreviewRuntimeOptions;
|
|
429
|
+
fetchDocument<T = Record<string, unknown>>(options: ReadDocumentOptions): Promise<PreviewFetchResult<T>>;
|
|
430
|
+
fetchGlobal<T = Record<string, unknown>>(options: ReadGlobalOptions): Promise<PreviewFetchResult<T>>;
|
|
431
|
+
}
|
|
432
|
+
/** Bind origin, route and depth once; read documents and globals with an explicit authorization verdict. */
|
|
433
|
+
declare function definePreview(config: PreviewServerConfig): PreviewServer;
|
|
434
|
+
|
|
435
|
+
export { AUTHORIZED_PREVIEW_BRAND_KEY, type AuthorizedPreviewContext, type AuthorizedPreviewScope, type BindOptions, type FetchLike, type FieldBindingAttributes, type FieldName, type FieldPath, type IssuePreviewTokenOptions, type OwnerBindingAttributes, type PayloadSessionStrategy, type PreviewAuthorization, type PreviewAuthorizationOutcome, type PreviewAuthorizationRequest, type PreviewAuthorizationStrategy, type PreviewAuthorizationStrategyName, type PreviewBindings, type PreviewBindingsCommonOptions, type PreviewBindingsOptions, type PreviewFetchDiagnostic, PreviewFetchError, type PreviewFetchFailureReason, type PreviewFetchFunction, type PreviewFetchResult, type PreviewReadOptions, type PreviewRequestLike, type PreviewRequestOptions, type PreviewRuntimeOptions, type PreviewServer, type PreviewServerConfig, type PreviewSignal, type PreviewTokenClaims, type PreviewTokenReplayStore, type PreviewTokenTransport, type PreviewVerifierClaims, type PreviewWhere, type PreviewWhereValue, type ReadDocumentOptions, type ReadGlobalOptions, type SignedTokenStrategy, type SubtleCryptoLike, type SuppressedBinding, type ValueAt, type VerifierStrategy, authorizePreviewRequest, bind, bindByPath, createPreviewBindings, definePreview, extractCookie, hasPreviewIntent, isAuthorizedPreviewContext, issuePreviewToken };
|