payload-live-preview 2.0.0 → 2.0.2
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 +41 -34
- package/dist/adapters/astro/RichText.astro +1 -1
- package/dist/adapters/astro/index.d.ts +8 -8
- 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 +3 -3
- 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 +2 -2
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +4 -4
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/nuxt/module.d.ts +13 -5
- package/dist/adapters/nuxt/module.js.map +1 -1
- package/dist/adapters/react/index.d.ts +8 -6
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.d.ts +5 -5
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.d.ts +3 -3
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/annotate.js +1 -1
- package/dist/annotate.js.map +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen-astro.d.ts +4 -1
- package/dist/codegen-astro.js.map +1 -1
- 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.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 +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +1 -1
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +4 -2
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/{fragment-endpoint-3Mlz7GDz.d.ts → fragment-endpoint-DATKU183.d.ts} +2 -2
- package/dist/fragment.cjs.map +1 -1
- package/dist/fragment.d.cts +6 -3
- package/dist/fragment.d.ts +6 -3
- package/dist/fragment.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.d.cts +3 -3
- package/dist/lean.d.ts +3 -3
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/lexical.cjs +1 -1
- package/dist/lexical.cjs.map +1 -1
- package/dist/lexical.d.cts +11 -1
- package/dist/lexical.d.ts +11 -1
- package/dist/lexical.js +1 -1
- package/dist/lexical.js.map +1 -1
- package/dist/{locals-DBXDMxOA.d.ts → locals-CNUGYbA_.d.ts} +1 -1
- package/dist/{middleware-Bx9I7PXW.d.ts → middleware-CWObDO37.d.ts} +2 -2
- package/dist/migrate.d.ts +6 -0
- package/dist/migrate.js +1 -1
- package/dist/migrate.js.map +1 -1
- package/dist/{options-BW1eqXvc.d.ts → options-uHKrDM2U.d.ts} +2 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/{probe-CELeUciC.d.ts → probe-DqaItcwX.d.ts} +15 -0
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js.map +1 -1
- package/dist/structural.cjs +2 -2
- package/dist/structural.cjs.map +1 -1
- package/dist/structural.js +2 -2
- package/dist/structural.js.map +1 -1
- package/package.json +6 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["assertMergeDepthExplicit","options","defaults","serverURL","mergeDepth","Error","V2_ADAPTER_DEFAULTS","Object","freeze","strict","previewSignals","V2_RUNTIME_DEFAULTS","disableReferrerDetection","eventSourcePolicy","skipUnchanged","sanitizerPolicy","V1_ADAPTER_DEFAULTS","V1_RUNTIME_DEFAULTS","RUNTIME_SOURCE","join","FRAGMENT_SOURCE","ROUTE_SOURCE","LOADER_SOURCE","LOADER_REACT_SOURCE","INLINE_CONFIG_KEYS","assertBuilt","source","artifact","length","generateInlineScript","config","runtime","profile","fragmentEndpoint","routeStrategy","runtimeFor","configStatement","strategyPrelude","profileSlots","map","key","value","JSON","stringify","replace","buildConfigLiteral","generateLoaderScript","target","bootstrap","hydration","loaderFor","runtimeSrc","encode","integrity","wrapWithScriptTag","body","nonce","test","RangeError","assertNonce","normalizePath","path","start","end","trimmed","slice","runtimeAsset","fileName","contentHash","urlPath","assetPath","ASSET_DIR","resolvePolicyOptions","adapter","runtimeRow","disableLocalhostMatching","inlineScriptConfig","facts","resolved","allowedOrigins","apiRoute","revealEditedField","debug","debounceMs","heartbeatMs","scopeBindingsByOwner","fragments","endpoint","onUnboundChange","onUnfaithfulPatch","autoBind","VIRTUAL_OPTIONS_ID","RESOLVED_VIRTUAL_OPTIONS_ID","livePreview","name","hooks","ctx","mode","autoInject","injectScript","updateConfig","asset","base","prefix","loaderAsset","vite","plugins","generateBundle","this","emitFile","type","configureServer","server","middlewares","use","req","res","next","url","split","statusCode","setHeader","setupLoaderMode","addMiddleware","authorizePreview","shouldInject","_mode","_shouldInject","serializable","optionsModule","resolveId","id","load","entrypoint","order","setupMiddlewareMode","CSP_ASCII_WHITESPACE","isCspWhitespace","index","code","charCodeAt","trimCspWhitespace","asciiLowercase","character","toLowerCase","buildFrameAncestors","self","origins","allowNone","seen","Set","out","push","add","origin","trim","has","mergeCspPolicy","existing","additions","directives","Map","part","whitespaceIndex","search","set","rawName","rawAddition","entries","addition","current","get","merged","token","withoutNone","filter","HEAD_INSERT","HTML_CONTENT_TYPE","META_CHARSET","renderScriptBody","delivery","DEFAULT_QUERY_PARAMS","hasPreviewIntent","request","signals","queryParams","URL","param","searchParams","headers","configured","adminOrigins","referer","refererOrigin","adminOrigin","isDevelopmentProcess","env","globalThis","process","warnOnce","message","holder","warned","console","warn","PreviewConfigurationError","refused","outcome","authorized","context","AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","isFrozen","createAuthorizedPreviewContext","fields","scope","payloadHeaders","async","runAuthorizeHook","hook","result","error","isPreviewConfigurationError","verdictFrom","STAGED","NONE","isPreview","authorization","inject","cspMode","exposeNonce","createPreviewPolicy","authorizes","protocol","includes","assertStrictConfiguration","manageCsp","decide","authorize","previewQueryParams","previewIntentFor","verdict","scriptTag","csp","frameAncestorsExtra","buildScriptSrcWithNonce","extra","strictDynamic","parts","e","scriptSrcExtra","policies","policy","mergeCspHeader","buildPreviewCsp","generateCspNonce","bytes","Number","isInteger","String","crypto","fromGlobal","getRandomValues","resolveCrypto","buffer","Uint8Array","binary","byte","fromCharCode","btoa","Buffer","from","toString","replaceAll","base64UrlEncode","NONCE_LOCALS_KEY","AUTHORIZATION_LOCALS_KEY","AUTHORIZATION_OUTCOME_LOCALS_KEY","createLivePreviewMiddleware","isPrerendered","locals","livePreviewNonce","decision","bindDecisionHooks","livePreviewAuthorization","livePreviewAuthorizationOutcome","exposeDecision","response","apply","Headers","Response","status","statusText","withHeaders","cacheControl","vary","listed","markUncacheable","applyCspHeaders","withCspHeader","injected","html","head","exec","headEnd","headClose","indexOf","meta","at","injectIntoHead","clone","text","delete","injectIntoResponse","applyDecision","renderLivePreviewScript","renderScriptTag","cachedEncoder","isPreviewRequest","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","encoder","TextEncoder","fromBase64Url","padded","repeat","atob","authorizePreviewRequest","strategy","cookieName","cookieNameFor","serverOriginFor","header","maxLength","values","startsWith","extractCookie","maxCookieLength","now","Date","timeoutMs","Math","max","fetchImpl","fetch","usersSlug","encodeURIComponent","forwarded","cookie","accept","signal","AbortSignal","timeout","ok","json","user","Array","isArray","collection","isFinite","readUser","expiresAt","exp","readExpiry","subject","authorizedAt","authorizeSession","secret","byteLength","secretBytes","candidate","subtle","cryptoFor","transport","kind","getAll","readToken","payloadText","payloadBytes","signature","verified","importKey","hash","hmacKey","verify","claims","parsed","parse","TextDecoder","decode","c","optionalString","parseClaims","iat","aud","audience","pur","purpose","pth","pathname","loc","locale","replay","first","store","consume","isUsed","markUsed","consumeTokenId","jti","sub","authorizeToken","authorizeVerifier","FRAGMENT_VERSION_HEADER","depthOf","depth","deepest","child","isRecord","parseFragmentRequest","fragment","route","revision","slugs","slug","collectionSlug","globalSlug","NO_STORE_HEADERS","refuse","TOO_LARGE","withTimeout","work","ms","Promise","resolve","reject","timer","setTimeout","then","clearTimeout","loadContainer","pending","started","specifier","astro","experimental_AstroContainer","create","cause","packages","names","one","missingPeerError","catch","lazyPeer","renderWithContainer","component","props","renderToString","createFragmentEndpoint","handler","binding","pageRequest","authorizerFor","render","rendererName","allowed","bodyLimit","limits","bodyBytes","registry","method","site","sameOrigin","raw","limit","readBody","Request","scopeAllows","entry","prototype","hasOwnProperty","call","input","record","boundary","metadata","renderedAt","toISOString","renderer","durationMs","createFragmentEndpointHandler"],"sources":["../../../src/types/merge-depth.ts","../../../src/types/defaults-profile.ts","../../../src/inline/runtime.generated.ts","../../../src/inline/fragment.generated.ts","../../../src/inline/route.generated.ts","../../../src/inline/loader.generated.ts","../../../src/inline/loader-react.generated.ts","../../../src/types/inline-config.ts","../../../src/inline/generator.ts","../../../src/adapters/shared/runtime-asset.ts","../../../src/adapters/astro/loader-asset.ts","../../../src/adapters/shared/policy-options.ts","../../../src/adapters/astro/integration.ts","../../../src/security/csp.ts","../../../src/adapters/shared/html-inject.ts","../../../src/adapters/shared/response.ts","../../../src/adapters/shared/preview-request.ts","../../../src/adapters/shared/dev-warning.ts","../../../src/security/preview-verdict.ts","../../../src/types/authorized-preview.ts","../../../src/adapters/shared/authorize-hook.ts","../../../src/adapters/shared/strict.ts","../../../src/adapters/shared/policy.ts","../../../src/adapters/shared/locals.ts","../../../src/adapters/astro/middleware.ts","../../../src/adapters/astro/component.ts","../../../src/adapters/shared/preview-request-legacy.ts","../../../src/security/preview-token.ts","../../../src/security/preview-session.ts","../../../src/security/preview-authorization.ts","../../../src/types/fragment-protocol.ts","../../../src/adapters/shared/fragment-endpoint.ts","../../../src/adapters/astro/fragments.ts","../../../src/adapters/shared/optional-peer.ts"],"sourcesContent":["/**\n * The one rule shared by the adapters, the client and the inline generator:\n * `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults (ADR 0007,\n * entry 10). It lives in the leaf `types` domain because the inline generator\n * is server-side code that may not reach the browser runtime in `core`, and\n * three copies of the check had already drifted in what they treated as\n * \"no server\" and \"no depth\".\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\n/**\n * The population depth is a deliberate choice; the 1.x default of 1 stays only\n * behind `defaults: 'v1'`. An empty `serverURL` fetches nothing and owes no\n * depth; `null` counts as omitted because the inline wire config carries it.\n */\nexport function assertMergeDepthExplicit(options: {\n readonly defaults?: DefaultsProfile | undefined;\n readonly serverURL?: string | undefined;\n readonly mergeDepth?: number | null | undefined;\n}): void {\n if (options.defaults === 'v1') return;\n if ((options.serverURL ?? '') === '' || options.mergeDepth != null) return;\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n}\n","/**\n * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts\n * back into the 1.x table for a staged migration. Each row belongs to exactly\n * one side — the adapter's request decision or the browser runtime — and a\n * test asserts the profile assigns every readiness row that has an option, so\n * a row added later cannot be forgotten. See ADR 0007.\n *\n * It lives in the leaf `types` domain, like `merge-depth.ts`, because the\n * inline generator resolves the profile too, and the generator is server-side\n * code that may not reach the browser runtime in `core`.\n */\n\n/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */\nexport type DefaultsProfile = 'v1' | 'v2';\n\n/** How the runtime decides which windows may post updates. */\nexport type EventSourcePolicy = 'any' | 'parent-or-opener';\n\n/** Readiness rows that are options, keyed by the option they set. */\nexport const READINESS_ROWS = Object.freeze({\n strict: 'production response changes require an authorized context',\n previewSignals: 'query-only intent signal',\n disableReferrerDetection: 'referrer trust off outside local dev',\n eventSourcePolicy: 'messages must come from parent/opener',\n skipUnchanged: 'skip unchanged bindings by default',\n sanitizerPolicy: 'hardened sanitizer id/data-* policy',\n} as const);\n\n/** Options an adapter's request decision reads from the profile. */\nexport interface AdapterProfileDefaults {\n readonly strict: boolean;\n readonly previewSignals: readonly ('query' | 'fetch-dest' | 'referer')[];\n}\n\n/** Options the browser runtime reads from the profile (through the inline configuration). */\nexport interface RuntimeProfileDefaults {\n readonly disableReferrerDetection: boolean;\n readonly eventSourcePolicy: EventSourcePolicy;\n readonly skipUnchanged: boolean;\n readonly sanitizerPolicy: 'compat' | 'strict';\n}\n\nexport const V2_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: true,\n previewSignals: Object.freeze(['query'] as const),\n});\n\nexport const V2_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: true,\n eventSourcePolicy: 'parent-or-opener',\n skipUnchanged: true,\n sanitizerPolicy: 'strict',\n});\n\n/** The 1.x table, spelled out so the profiles compare row by row. */\nexport const V1_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: false,\n previewSignals: Object.freeze(['query', 'fetch-dest', 'referer'] as const),\n});\n\nexport const V1_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: false,\n eventSourcePolicy: 'any',\n skipUnchanged: false,\n sanitizerPolicy: 'compat',\n});\n\n/** Only an explicit `'v1'` opts out; everything else gets the hardened rows. */\nexport function adapterDefaultsFor(profile: DefaultsProfile | undefined): AdapterProfileDefaults {\n return profile === 'v1' ? V1_ADAPTER_DEFAULTS : V2_ADAPTER_DEFAULTS;\n}\n\nexport function runtimeDefaultsFor(profile: DefaultsProfile | undefined): RuntimeProfileDefaults {\n return profile === 'v1' ? V1_RUNTIME_DEFAULTS : V2_RUNTIME_DEFAULTS;\n}\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = /* @__PURE__ */ [\"(()=>{function e(e){return(\\\"object\\\"==typeof e&&null!==e||\\\"function\\\"==typeof e)&&\\\"function\\\"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}function n(){}function i(e){return e.onUnfaithfulPatch??(\\\"ignore\\\"===e.onUnboundChange?\\\"ignore\\\":\\\"escalate\\\")}function r(e,t,n,i){if(t.reportedUnfaithful.has(n.element))return;t.reportedUnfaithful.add(n.element),t.unfaithfulCount+=1,t.unfaithfulFields.add(n.fieldName);let r=e.onUnfaithfulPatch;if(\\\"ignore\\\"!==r){if(\\\"warn\\\"===r){e.warn(`[live-preview] LP0411: \\\"${n.fieldName}\\\" ${i}`);return}e.log(\\\"LP0411\\\",n.fieldName,i),t.unfaithfulPatches.push(n)}}function l(e,t){return!e.unfaithfulFields.has(t)&&(e.unfaithfulFields.add(t),e.unfaithfulCount+=1,!0)}function o(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:e.textContent}function a(e){let t=e.trim();return JSON.stringify(t.length>Pn?`${t.slice(0,Pn)}\\\\u2026`:t)}function s(){return function(){if(typ\",\"eof document>\\\"u\\\")return;let e=document.documentElement.getAttribute(\\\"lang\\\");return null===e||0===e.length?void 0:e}()??function(){if(typeof navigator>\\\"u\\\")return;let e=navigator.language;return\\\"string\\\"==typeof e&&e.length>0?e:void 0}()??\\\"en\\\"}function u(e){null!==e.timer&&(clearTimeout(e.timer),e.timer=null),e.messageNode?.remove(),e.messageNode=null}function d(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=c(n);e&&t.push(e)}return t}function c(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e,n=t.name,i=t.type;if(\\\"string\\\"!=typeof n||0===n.length||\\\"string\\\"!=typeof i||0===i.length)return;let r=d(t.fields),l=function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(\\\"object\\\"!=typeof n||null===n)continue;let e=n,i=e.slug;if(\\\"string\\\"!=typeof i||0===i.length)continue;let r=d(e.fields);t.push({...e,slug:i,fields:r})}return t}(t.blocks),o={...t,name:n,type:i};return r.length>0?o.fields=r:delete o.fields,l.length>0?o.blocks=l:delete o.blocks,o}function h(e,t){return void 0===e||t(e)}function f(e,t){return null==e||t(e)}function p(e){if(\\\"object\\\"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function m(e,t=[]){let n=\\\"number\\\"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,i=Math.min(4,n??1),r=new Set(t),l=new Set;for(let e of Wn)(i>=_n[e].since||r.has(e))&&l.add(e);return{ours:4,...void 0!==n?{theirs:n}:{theirs:void 0},negotiated:i,capabilities:l,observed:r}}function g(e,t){return e.generation===t.generation&&e.revision===t.revision}function v(e){return function(e){if(!1===e.enableA11y)return null;let t=e.root,n=void 0===t?void 0:function(e){return 9===e.nodeType}(t)?t:t.ownerDocument;return new In(e.a11yLocale,n)}(e)}function y(e){if(typ\",\"eof window>\\\"u\\\")return;let t=[];window.parent!==window&&t.push(window.parent),window.opener instanceof Window&&t.push(window.opener),Bn.sendReady(t,e)}function b(e,t=\\\"\\\"){let n=new Map;return w(e,t,n),n}function w(e,t,n){for(let i of e){if(Dn.has(i.type)){i.fields&&w(i.fields,t,n);continue}let e=\\\"\\\"===t?i.name:`${t}.${i.name}`;if(n.set(e,i),\\\"group\\\"===i.type)i.fields&&w(i.fields,e,n);else if(\\\"array\\\"===i.type&&i.fields)w(i.fields,`${e}.*`,n);else if(\\\"blocks\\\"===i.type&&i.blocks)for(let t of i.blocks)w(t.fields,`${e}.*.${t.slug}`,n)}}function S(e,t){if(e.has(t))return e.get(t);let n=t.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return e.has(n)?e.get(n):void 0}function T(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?t:void 0}function k(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.blockType;return\\\"string\\\"==typeof t?t:void 0}function A(e,t){return t.every(e=>void 0!==T(e))?function(e,t){let n=[],i=new Map;for(let t=0;t<e.length;t+=1){let n=T(e[t]);void 0!==n&&i.set(n,t)}let r=new Set;for(let l=0;l<t.length;l+=1){let o=t[l],a=T(o);if(void 0===a){n.push({kind:\\\"insert\\\",index:l,value:o});continue}let s=i.get(a);if(void 0===s){n.push({kind:\\\"insert\\\",index:l,value:o});continue}r.add(s);let u=e[s];k(u)===k(o)?(s!==l&&n.push({kind:\\\"move\\\",from:s,to:l,value:o}),C(u,o)||n.push({kind:\\\"update\\\",index:l,value:o})):n.push({kind:\\\"replace\\\",index:l,oldValue:u,value:o})}for(let t=0;t<e.length;t+=1)r.has(t)||n.push({kind:\\\"remove\\\",index:t,value:e[t]});return n}(e,t):function(e,t){let n=[],i=Math.min(e.length,t.length);for(let r=0;r<i;r+=1)C(e[r],t[r])||n.push({kind:\\\"update\\\",index:r,value:t[r]});if(t.length>e.length)for(let i=e.length;i<t.length;i+=1)n.push({kind:\\\"insert\\\",index:i,value:t[i]});if(e.length>t.length)for(let i=t.length;i<e.length;i+=1)n.push({kind:\\\"remove\\\",index:i,value:e[i]});return n}(e,t)}function C(e,t){if(Object.is(e,t))return!0;if(\\\"object\\\"!=typeof e||\\\"object\\\"!=typeof t||null===e||null===t)return!1;let n=e,i=t,r=Object.keys(n),l=Object.keys(i);if(r.length!==l.length)return!1;for(let e of r)if(!Object.is(n[e],i[e]))return!1;return!0}function $(e){if(\\\"string\\\"!=typeof e)return!1;let t=e.trim().replace(Kn,\\\"\\\");if(0===t.length||Hn.test(t))return!1;if(t.startsWith(\\\"#\\\")||t.startsWith(\\\"?\\\")||qn.test(t)||t.startsWith(\\\"/\\\"))return!0;try{let e=new URL(t);return Vn.has(e.protocol)}catch{return Gn.test(t)}}function R(e){let t=e.trim().replace(Kn,\\\"\\\");return/^https?:\\\\/\\\\//i.test(t)||qn.test(t)}function F(e){return!e.startsWith(\\\"on\\\")&&!Jn.has(e)}function N(e){return Qn.add(e),e}function x(e){switch(typeof e){case\\\"string\\\":return e.length>65536?void 0:`s:${e}`;case\\\"number\\\":return`n:${Object.is(e,-0)?\\\"-0\\\":String(e)}`;case\\\"boolean\\\":return\\\"b:\\\"+(e?\\\"1\\\":\\\"0\\\");case\\\"bigint\\\":return`i:${String(e)}`;case\\\"undefined\\\":return\\\"u\\\";case\\\"object\\\":{if(null===e)return\\\"z\\\";let t;try{t=JSON.stringify(e)}catch{return}return t.length>65536?void 0:`o:${t}`}case\\\"symbol\\\":case\\\"function\\\":return}}function M(e){return e.closest(`[${Yn}]`)}function E(e){let t=e.getAttribute(ei);return null!==t&&t.length>0?\\\"patch\\\"===t||\\\"fragment\\\"===t||\\\"route\\\"===t?t:void 0:null!==M(e)?\\\"fragment\\\":null!==e.closest(\\\"head\\\")?\\\"route\\\":\\\"patch\\\"}function O(e){return`global:${e}`}function P(e,t){return void 0===t||\\\"\\\"===t?`collection:${e}`:`collection:${e}:${t}`}function L(e){return\\\"string\\\"==typeof e&&e.length>0}function U(e,t){return null!==t&&void 0!==e&&t.includes(e)}function I(e){let t=e.id;return\\\"string\\\"==typeof t&&t.length>0?t:\\\"number\\\"==typeof t&&Number.isFinite(t)?String(t):void 0}function j(e,t,n){let i=e.get(t);return void 0!==i&&(!1===n||i.some(e=>U(e.owner,n)))}function _(e,t,n){let i=`${t}.`;for(let[t,r]of e.entries())if(t.startsWith(i)&&(!1===n||r.some(e=>U(e.owner,n))))return!0;return!1}function W(e,t){if(void 0===t||0===t.length)return e;let n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}function B(e,t,n){let i;return r=>{if(j(e,r,n))return!0;let l=W(r,t);return!!(l!==r&&j(e,l,n)||_(e,r,n)||l!==r&&_(e,l,n))||(i??(i=function(e,t){let n=new Set;for(let[i,r]of e.entries())for(let e of r)!1!==t&&!U(e.owner,t)||void 0!==e.locale&&n.add(`${i}_${e.locale}`);return n}(e,n)),i.has(r))}}function D(e,t,n,i,r){return V(n)?!V(t)||function(e,t,n){let i=void 0===n?void 0:S(n,e);return void 0!==i&&!ni.has(i.type)||!0===t.get(e)?.some(z)||_(t,e,!1)}(e,i,r)?\\\"keep\\\":null==t?\\\"ask\\\":\\\"own\\\":\\\"ask\\\"}function z(e){return!ni.has(e.fieldType)}function V(e){return null===e||\\\"object\\\"!=typeof e&&\\\"function\\\"!=typeof e}function H(e){return!0===e?.includes(\\\".\\\")}function G(e){return null!==e&&e.forceRender&&!e.completed}function q(e){try{return!0===e.matchMedia?.(\\\"(prefers-reduced-motion: reduce)\\\").matches}catch{return!1}}function K(...e){let t=new Map;for(let n of e)for(let[e,i]of Object.entries(n)){let n=t.get(e);void 0===n&&(n=new Set,t.set(e,n));for(let e of i)n.add(e)}let n={};for(let[e,i]of t)n[e]=[...i];return n}function J(e,t){let n={};for(let i of t)i!==e&&(n[i]=[e]);return n}function X(e){return\\\"patch\\\"===e.getAttribute(hi)}function Q(e){return function(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()||e.hasAttribute(hi)}(e)&&!X(e)}function Z(e){let t=e.closest(Pi)?.getAttribute(Ri);return null==t||0===t.length?void 0:t}function Y(e){return Ui.has(e)||Li.test(e)}function ee(e){let t=e.getAttribute(mi);if(null!==t&&Y(t))return t;if(e.hasAttribute(ki))return\\\"richText\\\";if(e.hasAttribute(Ai))return\\\"html\\\";if(e.hasAttribute($i))return\\\"structural-array\\\";if(e.hasAttribute(Ci))return\\\"array\\\";if(\\\"IMG\\\"===e.tagName)return\\\"image\\\";if(\\\"A\\\"===e.tagName)return\\\"url\\\";if(\\\"TIME\\\"===e.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===e.tagName){let t=e.type;if(\\\"checkbox\\\"===t)return\\\"checkbox\\\";if(\\\"number\\\"===t)return\\\"number\\\";if(\\\"date\\\"===t||\\\"datetime-local\\\"===t)return\\\"date\\\"}return\\\"text\\\"}function te(){return!0}function ne(e,t){return e.length>0&&e.length<=t&&\\\".\\\"!==e&&\\\"..\\\"!==e&&!e.includes(\\\"/\\\")&&!e.includes(\\\"\\\\\\\\\\\")&&!function(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function ie(e){return ne(e,128)&&!e.includes(\\\"?\\\")&&!e.includes(\\\"#\\\")}function re(e){return e.has(\\\"schema-json\\\")?Wi:e.has(\\\"document-events\\\")||e.has(\\\"relationship-events\\\")?Bi:Di}function le(e){if(e.nodeType!==zi)return!1;let t=e;return t.hasAttribute(pi)||null!==t.querySelector(`[${pi}]`)}function oe(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[Hi]??(e[Hi]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function ae(){let e=oe();if(void 0===e||e.armed)return;e.armed=!0;let t=window,n=t.__REACT_DEVTOOLS_GLOBAL_HOOK__??(t.__REACT_DEVTOOLS_GLOBAL_HOOK__=function(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:t=>{let n=e.size+1;return e.set(n,t),n}}}()),i=n.onCommitFiberRoot;n.onCommitFiberRoot=function(t,n,...r){try{i?.call(this,t,n,...r)}catch{}let l=n?.containerInfo;void 0===e.onCommit?e.commits.push(l):e.onCommit(l)}}function se(e){e.committed=!0;let t=e.waiters;e.waiters=[];for(let e of t)e()}function ue(e,t){let n=e.waiters.indexOf(t);n>=0&&e.waiters.splice(n,1)}function de(e,t,n){if(e.committed)return null;let i=null,r=()=>{null!==i&&clearTimeout(i),i=null,t(\\\"committed\\\")};return e.waiters.push(r),i=setTimeout(()=>{i=null,ue(e,r),t(\\\"timed-out\\\")},n),()=>{null!==i&&clearTimeout(i),i=null,ue(e,r)}}function ce(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[Ki]??(e[Ki]={armed:!1,committed:!1,waiters:[]})}function he(e){return Object.prototype.hasOwnProperty.call(e,qi)?e[qi]:void 0}function fe(){let e=ce();if(void 0===e||e.armed)return;e.armed=!0;let t=Element.prototype;void 0===Object.getOwnPropertyDescriptor(t,qi)&&Object.defineProperty(t,qi,{configurable:!0,get:()=>{},set(e){Object.defineProperty(this,qi,{value:e,writable:!0,configurable:!0,enumerable:!0});let t=ce();void 0===t||t.committed||null===this.querySelector(Gi)||function(e,t){let n=t?.$nuxt;!0!==n?.isHydrating||\\\"function\\\"!=typeof n.hook?se(e):n.hook(Ji,()=>{e.committed||se(e)})}(t,e)}})}function pe(e){if(void 0===e.hydration){e.startNow();return}let t=t=>{e.later(()=>{me(e,t)})},n=\\\"react\\\"===e.hydration?function(e,t=5e3){ae();let n=oe();if(void 0===n)return null;if(void 0===n.onCommit){let e=e=>{!n.committed&&function(e){let t=e;return 9===t?.nodeType||null!=t?.querySelector?.(Gi)}(e)&&se(n)};n.onCommit=e;for(let t of n.commits.splice(0))e(t)}return de(n,e,t)}(t):function(e,t,n=5e3){fe();let i=ce();return void 0===i?null:(!i.committed&&function(e){for(let t=e.querySelector(Gi);null!==t;t=t.parentElement)if(void 0!==he(t))return!0;return!1}(e)&&se(i),de(i,t,n))}(e.root,t);null!==n?(e.defer(n),e.hydrated(\\\"waiting\\\")):me(e,\\\"committed\\\")}function me(e,t){e.hydrated(t),\\\"timed-out\\\"===t&&e.warn(`[live-preview] LP0607: no ${\\\"react\\\"===e.hydration?\\\"React commit\\\":\\\"Vue mount\\\"} in ${String(5e3)} ms; started without waiting for hydration.`),e.startNow()}function ge(e,t=er){if(\\\"string\\\"!=typeof e)return!1;let n=e.trim();return!(n.length<t||nr.test(n)||tr.has(n.toLowerCase())||ir.test(n)||rr.test(n))}function ve(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function ye(e,t,n=er){let i=new Map,r=(e,t,n)=>{i.set(e,i.has(e)?null:{field:t,media:n})};for(let[i,l]of Object.entries(e)){if(ti.has(i))continue;let e=W(i,t);if(ge(l,n))r(l.trim(),e,!1);else if(ve(l))if(\\\"string\\\"==typeof l.url)r(l.url,e,!0);else if(!(\\\"id\\\"in l)&&!(\\\"_id\\\"in l))for(let[t,i]of Object.entries(l))ti.has(t)||!ge(i,n)||r(i.trim(),`${e}.${t}`,!1)}return i}function be(e){if(e.namespaceURI!==or||lr.has(e.tagName)||e.hasAttribute(pi)||e.hasAttribute(Zi)||e.hasAttribute(Yi)||Q(e))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function we(e){let t;for(let n=e.firstChild;null!==n;n=n.nextSibling){if(1===n.nodeType)return;if(3!==n.nodeType)continue;let e=n.data.trim();if(0!==e.length){if(void 0!==t)return;t=e}}return t}function Se(e){return F(e)&&!e.startsWith(\\\"data-payload-\\\")&&\\\"value\\\"!==e}function Te(e,t,n){let i=e.byElement.get(t);void 0===i&&(i={attributes:new Map},e.byElement.set(t,i));let r=e.byField.get(n.field);return void 0===r&&(r=new Set,e.byField.set(n.field,r)),r.add(t),i}function ke(e,t){for(let n=e.firstElementChild;null!==n;n=n.nextElementSibling){if(be(n))continue;let e=we(n),i=void 0===e?void 0:t.values.get(e);null!=i&&!i.media&&(Te(t,n,i).text=i.field);for(let e of n.getAttributeNames()){if(!Se(e))continue;let i=t.values.get(n.getAttribute(e)??\\\"\\\");null!=i&&(i.media&&(\\\"IMG\\\"!==n.tagName||\\\"src\\\"!==e)||Te(t,n,i).attributes.set(e,i))}ke(n,t)}}function Ae(e,t,n){let i=e.tagName;if(void 0!==t){let r={[pi]:t};if(\\\"A\\\"===i){let e=n.get(\\\"href\\\");void 0===e?r[mi]=\\\"text\\\":e!==t&&(r[vi]=e)}return{element:e,fieldName:t,matched:we(e)??\\\"\\\",stamps:r}}if(\\\"IMG\\\"===i){let t=n.get(\\\"src\\\");if(void 0!==t){let i=n.get(\\\"alt\\\");return{element:e,fieldName:t,matched:e.getAttribute(\\\"src\\\")??\\\"\\\",attribute:\\\"src\\\",stamps:{[pi]:t,...void 0!==i&&i!==t?{[bi]:i}:{}}}}}let r=n.entries().next();if(r.done)return;let[l,o]=r.value;return{element:e,fieldName:o,matched:e.getAttribute(l)??\\\"\\\",attribute:l,stamps:{[pi]:o,[gi]:l}}}function Ce(e,t){let n={values:t,byElement:new Map,byField:new Map};t.size>0&&!be(e)&&ke(e,n);let i=e=>1===n.byField.get(e)?.size,r=[];for(let[e,t]of n.byElement){let n=void 0!==t.text&&i(t.text)?t.text:void 0,l=new Map;for(let[e,n]of t.attributes)i(n.field)&&l.set(e,n.field);let o=Ae(e,n,l);void 0!==o&&r.push(o)}return r}function $e(e){return 9===e.nodeType?e.body:e}function Re(e,t,n,i){let r=[];for(let l of t){let{element:t}=l;if(!t.hasAttribute(pi)&&(!1===n||U(Z(t),n))){for(let[e,n]of Object.entries(l.stamps))t.setAttribute(e,n);if(t.setAttribute(Mi,l.matched),void 0===e.cache.add(t)){for(let e of Object.keys(l.stamps))t.removeAttribute(e);t.removeAttribute(Mi);continue}e.observers.observeElement(t),e.log(\\\"autoBind\\\",l.fieldName,\\\"\\\\u2192\\\",`<${t.tagName.toLowerCase()}>`,l.attribute??\\\"text\\\",JSON.stringify(l.matched),i),r.push(l)}}return r}function Fe(e,t,n,i=!1){if(i&&void 0!==n){let i=Ne(e,`${t}_${n}`);if(void 0!==i)return i}let r=Ne(e,t);if(void 0!==r)return r;if(t.includes(\\\".\\\")){let n=e,i=!0;for(let e of t.split(\\\".\\\")){if(ar.has(e)||null===n||\\\"object\\\"!=typeof n){i=!1;break}if(n=Ne(n,e),void 0===n){i=!1;break}}if(i)return n}return void 0===n?void 0:Ne(e,`${t}_${n}`)}function Ne(e,t){if(!ar.has(t)&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}function xe(e,t,n,i){return Fe(e,n,t.locale??i,void 0!==t.locale)}function Me(e,t,n,i){let r=x(t);if(void 0===r)return;let l=[e.hrefField,e.srcField,e.altField],o=r;for(let t of l){if(void 0===t||0===t.length)continue;let r=x(xe(n,e,t,i));if(void 0===r)return;o+=`|${t}=${r}`}return o}function Ee(e,t,n,i){let{warned:r,warn:l}=e;r.has(n)||t(n)||(r.add(n),l(`[live-preview] LP0201: no <\\\\u2026 data-payload-field=\\\"${W(n,i)}\\\"> for field \\\"${n}\\\"; render the anchor unconditionally so edits to an empty field have somewhere to land.`))}function Oe(e){let t=typeof e;return\\\"string\\\"===t||\\\"number\\\"===t||\\\"boolean\\\"===t||\\\"bigint\\\"===t}function Pe(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function Le(e){let t=function(){if(void 0!==fn)return fn;let e=function(){let e=globalThis.trustedTypes;return\\\"object\\\"!=typeof e||null===e?void 0:\\\"function\\\"==typeof e.createPolicy?e:void 0}();try{fn=void 0===e?null:e.createPolicy(sr,{createHTML:e=>e})}catch{fn=null}return fn}();return null===t?e:t.createHTML(e)}function Ue(e,t){for(let n of t.keyAttributes){let t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function Ie(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(hi)||e.hasAttribute(ur))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function je(e,t,n){if(!function(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!Ie(e)&&!Ie(t)}(e,t))return t;let i=function(e){let t=e.ownerDocument.activeElement;return t instanceof HTMLElement&&e.contains(t)?{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}:null}(e);return function(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||dr.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){let i=function(e,t){let n,i=new Map;for(let r of Array.from(e.children)){let e=Ue(r,t);if(void 0!==e){if(i.has(e)){n??(n=e.slice(e.indexOf(\\\"=\\\")+1));continue}i.set(e,r)}}return void 0!==n&&t.onDuplicateKey?.(e,n),i}(e,n),r=new Set(i.values()),l=Array.from(e.childNodes).filter(e=>!r.has(e)),o=new Set,a=new Set,s=Array.from(t.childNodes),u=e.firstChild,d=0;for(let t=0;t<s.length;t+=1){let r=s[t],c=null,h=r instanceof Element?Ue(r,n):void 0;if(void 0!==h&&a.has(h)&&(h=void 0),void 0!==h){a.add(h);let e=i.get(h);if(void 0!==e&&!o.has(e)&&(c=_e(e,r,n)===e?e:null,null===c)){e.replaceWith(r),o.add(r),u=r.nextSibling;continue}}else{for(;d<l.length;){let i=l[d];if(d+=1,!o.has(i)){if(Be(i,r)){c=_e(i,r,n)===i?i:null,null===c&&(e.replaceChild(r,i),o.add(r),u=r.nextSibling);break}if(i instanceof Element){let n=s[t+1];if(!(r instanceof Element)||void 0!==n&&Be(i,n)){d-=1;break}e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}if(!(r instanceof Element)){e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}}}if(null===c&&o.has(r))continue}let f=c??r;for(o.add(f);null!==u&&u!==f&&!o.has(u)&&We(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let t of Array.from(e.childNodes))o.has(t)||t.remove()}(e,t,n),function(e){if(null===e)return;let{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});let[e,i]=n??[null,null];null!==e&&null!==i&&t.setSelectionRange(e,i)}catch{}}(i),e}function _e(e,t,n){return e instanceof Element&&t instanceof Element?Ie(e)&&Ie(t)?e:je(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function We(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??\\\"\\\").trim().length}function Be(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}function De(e){cr.has(e)||(cr.add(e),function(e){try{console.warn(e)}catch{}}(`[live-preview] LP0409: the strict sanitizer removed \\\\`${e}\\\\` from written markup; the 1.x default (\\\\`sanitizerPolicy: 'compat'\\\\`) kept it. ${function(e){return e.startsWith(hr)?\\\"A binding inside CMS content is refused by design \\\\u2014 an editor could otherwise aim a write at any element on the page (docs/security.md)\\\":\\\"id\\\"===e||\\\"name\\\"===e?\\\"CMS content that can name an element can shadow a global of that name \\\\u2014 DOM clobbering, refused by design (docs/security.md)\\\":\\\"List it in `allowedDataAttributes` if the page needs it, or set `sanitizerPolicy: 'compat'` to keep every `data-*` as 1.x did\\\"}(e)}.`))}function ze(e,t,n){let i=Ve();if(!i)throw new Error(\\\"sanitizeHtml needs a DOM\\\");if(\\\"\\\"===e)return\\\"\\\";let r=function(e,t){let n=e?.policy??t??Cr;if(!e){let e=new Map;for(let[t,n]of Object.entries(wr))e.set(t,n);return{allowedTags:fr,attrByTag:e,allowFormControls:!1,templateMode:!1,mode:n,allowedData:new Set}}let i=new Set(fr);if(e.additionalAllowedTags?.forEach(e=>i.add(e)),!0===e.allowFormControls)for(let e of pr)i.add(e);let r=new Map;for(let[e,t]of Object.entries(wr))r.set(e,t);for(let[t,n]of Object.entries(e.additionalAllowedAttributes??{})){let e=new Set(r.get(t));for(let t of n)e.add(t);r.set(t,e)}return{allowedTags:i,attrByTag:r,allowFormControls:!0===e.allowFormControls,templateMode:!0===e.templateMode,mode:n,allowedData:new Set(e.allowedDataAttributes?.map(e=>e.toLowerCase()))}}(n,t),l=i.createElement(\\\"template\\\");return l.innerHTML=Le(e),He(l.content,r),l.innerHTML}function Ve(){if(!(typ\",\"eof document>\\\"u\\\"))return document}function He(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Tr?Ge(n,t):n.nodeType===kr&&n.remove()}function Ge(e,t){let n=e.tagName.toLowerCase();!mr.has(n)||t.allowFormControls&&pr.has(n)?t.allowedTags.has(n)?(function(e,t,n){let i=n.attrByTag.get(t);for(let t of Array.from(e.attributes)){let r=t.name.toLowerCase();if(r.startsWith(\\\"on\\\")||\\\"style\\\"===r)e.removeAttribute(t.name);else{if(\\\"strict\\\"===n.mode){if(n.templateMode&&Ar.has(r))continue;if(\\\"id\\\"===r||\\\"name\\\"===r||r.startsWith(br)){e.removeAttribute(t.name),De(r);continue}if(r.startsWith(yr)){n.allowedData.has(r)||(e.removeAttribute(t.name),De(r));continue}if(gr.has(r)||r.startsWith(vr))continue}else if(gr.has(r)||r.startsWith(vr)||r.startsWith(yr))continue;i?.has(r)?(Sr.has(r)&&!$(t.value)||\\\"srcset\\\"===r&&!qe(t.value))&&e.removeAttribute(t.name):e.removeAttribute(t.name)}}}(e,n,t),\\\"a\\\"===n&&function(e){let t=e.getAttribute(\\\"href\\\");null===t||!R(t)||(e.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),e.hasAttribute(\\\"target\\\")||e.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(e),He(e,t)):(He(e,t),e.replaceWith(...e.childNodes)):e.remove()}function qe(e){for(let t of e.split(\\\",\\\")){let e=t.trim();if(0===e.length)continue;let[n=e]=e.split(/\\\\s/,1);if(!$(n))return!1}return!0}function Ke(e){return e.replace(Rr,e=>$r[e])}function Je(e){return e.replace(Nr,e=>Fr[e])}function Xe(e){let t=new Set;for(let n of e)if(\\\"object\\\"==typeof n&&null!==n)for(let e of Object.keys(n))t.add(e);return t}function Qe(e,t,n,i,r){let l=\\\"object\\\"==typeof t&&null!==t?t:null;return e.replace(xr,(e,o)=>null!==l&&function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(l,o)?Ke(i(Reflect.get(l,o))):null===l&&\\\"value\\\"===o?Ke(i(t)):\\\"index\\\"===o?String(n):null!==l&&!0===r?.has(o)?\\\"\\\":e)}function Ze(e){let t=e.children,n=t[0];if(void 0===n)return[];let i=[];for(let{name:e,value:r}of Array.from(n.attributes)){if(!F(e)||e.startsWith(Mr))continue;let n=!0;for(let i=1;i<t.length&&n;i+=1)n=t[i]?.getAttribute(e)===r;n&&i.push([e,r])}return i}function Ye(e,t){for(let[n,i]of t)e.hasAttribute(n)||e.setAttribute(n,i)}function et(e){if(null==e)return\\\"\\\";if(\\\"string\\\"==typeof e)return e;if(\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e||\\\"bigint\\\"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return\\\"\\\"}}function tt(e){return null==e||\\\"\\\"===e}function nt(e,t){let n=e.get(t);return void 0!==n&&(e.delete(t),e.set(t,n)),n}function it(e,t,n,i){return e.set(t,n),function(e,t){for(let n of e.keys()){if(e.size<=t)break;e.delete(n)}}(e,i),n}function rt(e){let t=nt(Ur,e);if(void 0!==t)return t;let n=new Set(Er);for(let t of e.matchAll(Pr)){let e=t[1]?.toLowerCase();void 0!==e&&n.add(e)}let i={};for(let e of n)i[e]=Or;let r={additionalAllowedTags:[...n],additionalAllowedAttributes:i,allowFormControls:!0,templateMode:!0};return it(Ur,e,r,Lr)}function lt(e){let t=at(e.container,e.patches,e);return null===t?null:st(t,e.store,{morph:e.morph??!0,onDuplicateKey:e.onDuplicateKey})}function ot(e,t){return t.hasAttribute(jr)&&t.hasAttribute(_r)}function at(e,t,n){let i=function(e,t,n){let{template:i,nextItems:r,forceRender:l=!1,store:o,sanitizerPolicy:a}=n,s=o.get(e),u=Ze(e),d=Xe(r),c=Array.from(e.children),h=mt(c,Ir),f=new Set,p=[];for(let o=0;o<r.length;o+=1){let m=r[o],g=pt(m),v=void 0===g?c[o]??null:gt(h,g)??null;null!==v&&f.has(v)&&(v=null),null!==v&&f.add(v);let y=t.replaces.has(o),b=l||t.renders.has(o)||null===v?vt(e.ownerDocument,i,m,o,a,u,d):void 0;if(null===b)return null;let w=void 0===b?[]:ut(y?null:v,b,m,void 0===g?void 0:s?.get(g),n);if(null===w)return null;p.push([o,v,b,w,y])}return p}(e,function(e){let t=new Set,n=new Set;for(let i of e)\\\"insert\\\"===i.kind||\\\"update\\\"===i.kind?t.add(i.index):\\\"replace\\\"===i.kind&&(t.add(i.index),n.add(i.index));return{renders:t,replaces:n}}(t),n);return null===i?null:[e,i,n.nextItems]}function st(e,t,n){let[i,r,l]=e,o=new Set,a=!1;for(let[e,l,s,u,d]of r){let r=l;if(void 0!==s){let e=!(!n.morph||d||null===l)&&je(l,s,{keyAttributes:[Ir,jr],retainChildrenOf:ot,...void 0!==n.onDuplicateKey?{onDuplicateKey:n.onDuplicateKey}:{}})===l;if(!e)for(let[e,t]of u)null!==e&&(ct(e,t),t.replaceWith(e));for(let[,,e]of u)void 0!==e&&st(e,t,n);e?a=!0:(null!==l&&(l.replaceWith(s),a=!0),r=s)}if(null===r)continue;let c=i.children[e]??null;r!==c&&(i.insertBefore(r,c),a=!0),o.add(r)}for(let e of Array.from(i.children))o.has(e)||(e.remove(),a=!0);let s=function(e,t){let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}(i,t);s.clear();for(let e of l)ft(s,e);return a}function ut(e,t,n,i,r){let l=mt(null===e?[]:dt(e),jr),o=[];for(let e of dt(t)){let t=e.getAttribute(jr);if(null===t)continue;let a,s=gt(l,t)??null,u=e.getAttribute(_r),d=u?s:null,c=d?.getAttribute(_r)??null;if(u){let l=ht(n,t);if(void 0!==l||null!==d){let n=l??[],o=A(null===d?[]:ht(i,t)??[],n),s=null!==d&&c!==u;if((o.length>0||s)&&(a=at(d??e,o,{template:u,nextItems:n,forceRender:s,store:r.store,sanitizerPolicy:r.sanitizerPolicy})??void 0,void 0===a))return null}}o.push([d,e,a])}return o}function dt(e){return Array.from(e.querySelectorAll(`[${jr}]`)).filter(t=>{let n=t.parentElement;for(;null!==n&&n!==e;){if(n.hasAttribute(jr))return!1;n=n.parentElement}return n===e})}function ct(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function ht(e,t){if(\\\"object\\\"!=typeof e||null===e)return;let n=e[t];return Array.isArray(n)?n:void 0}function ft(e,t){let n=pt(t);void 0!==n&&e.set(n,t)}function pt(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function mt(e,t){let n=new Map;for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(void 0===r)continue;let l=r.getAttribute(t);if(null===l)continue;let o=n.get(l);void 0===o?n.set(l,[r]):o.push(r)}return n}function gt(e,t){return e.get(t)?.pop()}function vt(e,t,n,i,r,l,o){let a=ze(Qe(t,n,i,et,o),r,rt(t)),s=e.createElement(\\\"template\\\");s.innerHTML=Le(a);let u=s.content.firstElementChild;if(!u)return null;Ye(u,l);let d=pt(n);return void 0!==d&&u.setAttribute(Ir,d),u}function yt(e,t){let n=new Set(t);return{boundaries:t,strategy:e,covers:e=>void 0!==e.fragmentBoundary&&n.has(e.fragmentBoundary)}}function bt(t,n,i,r,l){let o=t.transformValue;if(void 0===o)return i;try{let t=o(n.fieldName,i,{element:n.element,allFields:r},l),a=e(t);if(!l())return i;if(a)throw new TypeError(`Transform for \\\"${n.fieldName}\\\" returned a thenable; transforms must be synchronous`);return t}catch(e){if(!l())return i;let n=e instanceof Error?e:new Error(String(e));return t.emitter.emit(\\\"error\\\",{error:n,context:\\\"transform\\\",code:\\\"LP0602\\\"}),i}}function wt(e){return 9===e.nodeType}function St(e){return e.body}function Tt(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function kt(e){let t=e.trim();if(0!==t.length)try{let e=new URL(t);return\\\"http:\\\"!==e.protocol&&\\\"https:\\\"!==e.protocol||!qr.test(e.origin)?void 0:e.origin}catch{return}}function At(e){let t=e.format;return\\\"string\\\"==typeof t&&Zr.has(t)?t:\\\"number\\\"==typeof t?Qr[t]:void 0}function Ct(e){let t=e.indent;return\\\"number\\\"==typeof t&&t>0?t:0}function $t(e){return\\\"rtl\\\"===e.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===e.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function Rt(e){let t=At(e),n=Ct(e),i=[];return void 0!==t&&i.push(`lp-align-${t}`),n>0&&i.push(`lp-indent-${String(n)}`),0===i.length?\\\"\\\":` class=\\\"${i.join(\\\" \\\")}\\\"`}function Ft(e){return\\\"object\\\"==typeof e&&null!==e?e:void 0}function Nt(e){return Ft(e)}function xt(e){return e.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function Mt(e){return\\\"string\\\"==typeof e&&e.length>0?e:void 0}function Et(e){let t=Mt(e.title)??Mt(e.name)??Mt(e.slug);return void 0!==t?t:void 0===e.id?void 0:String(e.id)}function Ot(e){if(\\\"string\\\"==typeof e.text)return e.text;if(!e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Ot(n);return t}function Pt(e){return`${\\\"number\\\"==typeof e.width?` width=\\\"${String(e.width)}\\\"`:\\\"\\\"}${\\\"number\\\"==typeof e.height?` height=\\\"${String(e.height)}\\\"`:\\\"\\\"}`}function Lt(e){return\\\"string\\\"==typeof e.mimeType?` type=\\\"${Je(e.mimeType)}\\\"`:\\\"\\\"}function Ut(e){return nl.get(e)}function It(e,t,n,i){let r=Ft(e.fields)??{},l=\\\"string\\\"==typeof r.blockType?r.blockType:\\\"\\\",o=xt(l),a=\\\"\\\"===o?i:`${i} ${i}--${o}`;if(\\\"\\\"!==l){let e=Ut(l)??Ut(o);if(e)return e(r,{renderChildren:t.renderChildren});t.onUnrenderedBlock?.(l,a)}return`<${n} class=\\\"${a}\\\"></${n}>`}function jt(e,t){return\\\"number\\\"==typeof t&&t>1?` ${e}=\\\"${String(t)}\\\"`:\\\"\\\"}function _t(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&\\\"children\\\"in t&&Array.isArray(t.children)}function Wt(e,t){let n=function(e){return ll.get(e)??rl[e]}(e.type);return n?n(e,t):void 0!==e.children?t.renderChildren(e.children):\\\"\\\"}function Bt(e){if(\\\"string\\\"==typeof e.text)return e.text;if(\\\"linebreak\\\"===e.type)return\\\"\\\\n\\\";if(void 0===e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Bt(n);return t}function Dt(e=\\\"text\\\"){let t=new WeakSet;return{name:e,render:N((e,n)=>{let i=e.element,r=function(e){return null==e?\\\"\\\":_t(e)?function(e){return _t(e)?e.root.children.map(Bt).join(\\\"\\\\n\\\").trim():\\\"\\\"}(e):\\\"string\\\"==typeof e?e:\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e)}(n);if(\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName){if(function(e){return null!==e.querySelector(\\\":scope > :not(br)\\\")}(i)&&!i.hasAttribute(al))return function(e,t,n){e.has(t)||(e.add(t),kn(`[live-preview] LP0402: Skipping text update for \\\"${n}\\\": <${t.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,i,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?i.innerHTML=Le(function(e){return Ke(e).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}(r)):i.textContent=r}else i.value=r})}}function zt(e,t){let n=e.cloneNode(!1);n.innerHTML=Le(t);let i=function(e,t){let n=e.firstElementChild;if(null!==n?.nextElementSibling||t.children.length<2||!dl.has(n.tagName)||n.hasAttribute(pi))return null;for(let e of t.children)if(e.tagName===n.tagName&&e.className===n.className)return null;return n}(e,n)??e,r=new Map,l=n.querySelectorAll(il);if(l.length>0&&null!==i.firstElementChild){let e=[];Vt(i,n,e);for(let[t,n]of e)t.replaceWith(n),n.matches(il)||r.set(t.className,!1);for(let e of l)null!==e.parentNode&&r.set(e.className,!0)}return i.replaceChildren(...n.childNodes),r}function Vt(e,t,n){if(e.children.length!==t.children.length)return;let i=e.firstElementChild,r=t.firstElementChild;for(;null!==i&&null!==r;)r.matches(il)?n.push([r,i]):Vt(i,r,n),i=i.nextElementSibling,r=r.nextElementSibling}function Ht(e,t,n,i){i&&t.reportUnfaithful?.(e,`lost the markup the server drew for block \\\"${n}\\\"`);let r=i?ul:sl;r.has(n)||(r.add(n),kn(`[live-preview] ${i?`LP0413: no renderer for block \\\"${n}\\\", and the markup the server rendered for it is lost.`:`LP0410: no renderer for block \\\"${n}\\\"; keeping what the server rendered for it.`} Register one with registerBlockRenderer().`))}function Gt(e,t,n){return\\\"string\\\"!=typeof n||0===n.length?{kind:\\\"none\\\"}:$(n)?{kind:\\\"safe\\\",url:n}:(fl.has(e)||(fl.add(e),kn(`[live-preview] LP0401: refused an unsafe URL for \\\"${t}\\\" on <${e.tagName.toLowerCase()}>; the attribute was cleared.`)),{kind:\\\"unsafe\\\"})}function qt(e,t=e=>e){return{name:e,render(e,n,i){let r=e.element;if(tt(n)){!function(e){\\\"INPUT\\\"!==e.tagName&&\\\"TEXTAREA\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):e.value=\\\"\\\"}(r);return}let l=et(n);if(\\\"INPUT\\\"!==r.tagName&&\\\"TEXTAREA\\\"!==r.tagName){if(\\\"A\\\"===r.tagName){let n=e.hrefField,o=void 0===n||0===n.length?t(l):Fe(i.allFields,n,i.locale,void 0!==e.locale),a=Gt(r,e.fieldName,o);\\\"safe\\\"===a.kind?r.setAttribute(\\\"href\\\",a.url):\\\"unsafe\\\"===a.kind&&r.removeAttribute(\\\"href\\\")}r.textContent=l}else r.value=l}}}function Kt(e){for(let t of vl)e.removeAttribute(t)}function Jt(e,t,n){e.src=t;let i=function(e){if(void 0===e?.sizes)return;let t=[];for(let n of Object.values(e.sizes))\\\"string\\\"!=typeof n.url||\\\"number\\\"!=typeof n.width||!$(n.url)||t.push(`${Xt(n.url)} ${String(n.width)}w`);return 0!==t.length?(\\\"number\\\"==typeof e.width&&\\\"string\\\"==typeof e.url&&$(e.url)&&t.push(`${Xt(e.url)} ${String(e.width)}w`),t.join(\\\", \\\")):void 0}(n);void 0!==i?e.setAttribute(\\\"srcset\\\",i):(e.removeAttribute(\\\"srcset\\\"),e.removeAttribute(\\\"sizes\\\"))}function Xt(e){return e.replace(/[\\\\s,]/g,encodeURIComponent)}function Qt(e){\\\"IMG\\\"===e.tagName?Kt(e):e.style.backgroundImage=\\\"\\\"}function Zt(e){\\\"IMG\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):Kt(e)}function Yt(e){let t=Ft(e);return void 0===t?et(e):Et(t)??\\\"\\\"}function en(e,t){let n=e??\\\"\\\";if(null==t)return n;let i=tn(t);return\\\"{}\\\"===i?n:`${n}|${i}`}function tn(e){if(null===e||\\\"object\\\"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>tn(e)).join(\\\",\\\")}]`;let t=e,n=Object.keys(t).sort(),i=[];for(let e of n){let n=t[e];void 0!==n&&i.push(`${JSON.stringify(e)}:${tn(n)}`)}return`{${i.join(\\\",\\\")}}`}function nn(e){return{kind:\\\"date\\\",options:e}}function rn(e){return{kind:\\\"number\\\",options:e}}function ln(e,t,n,i){if(void 0===t||\\\"\\\"===t)return;let r=function(e){let t=e.indexOf(\\\":\\\"),n=-1===t?e:e.slice(0,t),i=-1===t?void 0:e.slice(t+1);switch(n){case\\\"date\\\":return void 0===i?nn({dateStyle:\\\"medium\\\"}):$l.has(i)?nn({dateStyle:i}):void 0;case\\\"time\\\":return void 0===i?nn({timeStyle:\\\"short\\\"}):Rl.has(i)?nn({timeStyle:i}):void 0;case\\\"datetime\\\":return void 0===i?nn({dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}):$l.has(i)?nn({dateStyle:i,timeStyle:\\\"short\\\"===i?\\\"short\\\":\\\"medium\\\"}):void 0;case\\\"number\\\":return void 0===i?rn({}):Nl.test(i)?rn({minimumFractionDigits:Number(i),maximumFractionDigits:Number(i)}):void 0;case\\\"currency\\\":return void 0!==i&&Fl.test(i)?rn({style:\\\"currency\\\",currency:i.toUpperCase()}):void 0;case\\\"percent\\\":return void 0===i?rn({style:\\\"percent\\\"}):void 0;default:return}}(t);if(void 0!==r)return r.kind===e?r.options:void 0;!function(e,t,n){xl.has(e)||(xl.add(e),kn(`[live-preview] LP0408: data-payload-format=\\\"${n}\\\" on \\\"${t}\\\" is not a known format; the default formatting was used. Known: date, date:short|medium|long|full, time, datetime, number, number:0-4, currency:XXX, percent.`))}(n,i,t)}function on(e){return String(e).padStart(2,\\\"0\\\")}function an(){let e=new WeakMap,t=new WeakSet,n=new WeakMap,i=new WeakMap;return{name:\\\"structural-array\\\",render:N((r,l,o)=>{let a=tt(l)?[]:l;if(!Array.isArray(a))return!1;let s=r.element,u=r.arrayTemplate;if(void 0===u||0===u.length)return function(e,t,n){e.has(t)||(e.add(t),kn(`[live-preview] LP0403: Skipping structural update for \\\"${n}\\\": <${t.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(t,s,r.fieldName),!1;let d=e.get(s),c=sn(s),h=d?.values??function(e){return e.map((e,t)=>null===e?{__payloadDomPosition:t}:{id:e})}(c),f=A(h,a),p=function(e,t,n){return void 0===e||e.template!==t||!function(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}(e.domSnapshot,n)}(d,u,c);if(0===f.length&&!p)return e.set(s,{values:a.slice(),template:u,domSnapshot:c}),!1;!function(e,t,n,i,r){let l=r.map(un),o=new Set,a=l.find(e=>!(void 0===e||!o.has(e)&&(o.add(e),1)));if(void 0!==a&&dn(e,t,n,a),l.some(e=>void 0===e)&&cn(e,t,\\\"LP0404\\\",`LP0404: an item of \\\"${n}\\\" has no id and pairs by position, so an insert re-renders every row after it. Give items a stable id.`),i?.length===r.length&&r.length>1){let r=new Set(i.map(un).filter(e=>void 0!==e)),o=l.some(e=>void 0!==e&&r.has(e));r.size>0&&!o&&cn(e,t,\\\"LP0406\\\",`LP0406: every key of \\\"${n}\\\" changed at once; the source generates ids per message, so no item can be retained across updates.`)}}(n,s,r.fieldName,d?.values,a);let m=lt({template:u,container:s,patches:f,nextItems:a,store:i,forceRender:p,sanitizerPolicy:o.sanitizerPolicy,onDuplicateKey:(e,t)=>{dn(n,e,r.fieldName,t)}});return null!==m&&(e.set(s,{values:a.slice(),template:u,domSnapshot:sn(s)}),!!m&&void 0)})}}function sn(e){return Array.from(e.children,e=>e.getAttribute(Ir))}function un(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function dn(e,t,n,i){cn(e,t,\\\"LP0405\\\",`LP0405: two items of \\\"${n}\\\" share the key \\\"${i}\\\"; later ones pair by position. Make \\\\`id\\\\` unique per item.`)}function cn(e,t,n,i){let r=e.get(t);void 0===r&&(r=new Set,e.set(t,r)),!r.has(n)&&(r.add(n),kn(`[live-preview] ${i}`))}function hn(){return typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__}var fn,pn=Object.defineProperty,mn=e=>{throw TypeError(e)},gn=(e,t,n)=>((e,t,n)=>t in e?pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,\\\"symbol\\\"!=typeof t?t+\\\"\\\":t,n),vn=(e,t,n)=>t.has(e)||mn(\\\"Cannot \\\"+n),yn=(e,t,n)=>(vn(e,t,\\\"read from private field\\\"),n?n.call(e):t.get(e)),bn=(e,t,n)=>t.has(e)?mn(\\\"Cannot add the same private member more than once\\\"):t instanceof WeakSet?t.add(e):t.set(e,n),wn=(e,t,n,i)=>(vn(e,t,\\\"write to private field\\\"),i?i.call(e,n):t.set(e,n),n),Sn=(e,t,n)=>(vn(e,t,\\\"access private method\\\"),n),Tn=t((...e)=>console.error(...e)),kn=t((...e)=>console.warn(...e)),An=t((...e)=>console.debug(...e)),Cn=class{constructor(){bn(this,Fn);bn(this,$n,new Map);bn(this,Rn,new Map)}on(e,t){return Sn(this,Fn,xn).call(this,yn(this,$n),e,t)}once(e,t){return Sn(this,Fn,xn).call(this,yn(this,Rn),e,t)}off(e,t){Sn(this,Fn,Mn).call(this,yn(this,$n),e,t),Sn(this,Fn,Mn).call(this,yn(this,Rn),e,t)}async emit(e,t){await Sn(this,Fn,Nn).call(this,e,t)}async emitWhile(e,t,n){return Sn(this,Fn,Nn).call(this,e,t,n)}listenerCount(e){return(yn(this,$n).get(e)?.size??0)+(yn(this,Rn).get(e)?.size??0)}removeAllListeners(e){void 0!==e?(yn(this,$n).delete(e),yn(this,Rn).delete(e)):(yn(this,$n).clear(),yn(this,Rn).clear())}eventNames(){let e=new Set;for(let t of yn(this,$n).keys())e.add(t);for(let t of yn(this,Rn).keys())e.add(t);return[...e]}},$n=new WeakMap,Rn=new WeakMap,Fn=new WeakSet,Nn=async function(e,t,n){let i=()=>n?.()??!0;if(!i())return!1;let r=yn(this,$n).get(e);if(r)for(let n of[...r])if(!i()||(await Sn(this,Fn,En).call(this,n,t,e),!i()))return!1;if(!i())return!1;let l=yn(this,Rn).get(e);if(l&&l.size>0){let n=[...l];yn(this,Rn).delete(e);for(let r of n)if(!i()||(await Sn(this,Fn,En).call(this,r,t,e),!i()))return!1}return i()},xn=function(e,t,n){let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(n),()=>{Sn(this,Fn,Mn).call(this,e,t,n)}},Mn=function(e,t,n){let i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))},En=async function(e,t,n){try{await e(t)}catch(e){let t=\\\"string\\\"==typeof n||\\\"number\\\"==typeof n?String(n):\\\"<event>\\\";Tn(`[live-preview] LP0601: handler for \\\"${t}\\\" threw:`,e)}},On=new Set([\\\"date\\\",\\\"number\\\",\\\"checkbox\\\"]),Pn=40,Ln=\\\"payload-live-preview-a11y\\\",Un=new WeakMap,In=class{constructor(e,t){gn(this,\\\"german\\\");gn(this,\\\"document\\\");gn(this,\\\"lease\\\",null);let n=t??(typ\",\"eof document>\\\"u\\\"?null:document),i=n?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.german=function(e){return/^de(?:[-_]|$)/i.test(e)}(e??(i.length>0?i:s())),this.document=n}mount(){let e=this.document;if(null==e?.body)return null;this.lease??(this.lease=function(e){let t=Un.get(e);return void 0===t&&(t={element:null,owned:!1,messageNode:null,refs:0,timer:null},Un.set(e,t)),t.refs+=1,t}(e));let t=this.lease,n=t.element;if(n?.isConnected&&n.ownerDocument===e)return n;if(null!==n){let e=t.owned;u(t),e&&n.remove()}let i=e.getElementById(Ln);return t.owned=null===i,null===i&&(i=e.createElement(\\\"div\\\"),i.id=Ln,i.setAttribute(\\\"role\\\",\\\"status\\\"),i.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),i.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),i.setAttribute(\\\"style\\\",\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\"),e.body.appendChild(i)),t.element=i,i}announceConnected(){this.say(this.german?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.german?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(e){e<=0||this.say(this.german?`${String(e)} ${1===e?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(e)} ${1===e?\\\"change\\\":\\\"changes\\\"} applied`)}detach(){let e=this.lease,t=this.document;if(null===e||null===t||(this.lease=null,e.refs-=1,e.refs>0))return;let n=e.element;null!==n&&u(e),e.owned&&n?.remove(),e.element=null,Un.delete(t)}say(e){let t=this.mount(),n=this.lease;if(null===t||null===n)return;let i=n.messageNode;i?.parentNode!==t?(i?.remove(),i=t.ownerDocument.createTextNode(t.hasChildNodes()?` ${e}`:e),n.messageNode=i,t.appendChild(i)):i.data=null===i.previousSibling?e:` ${e}`,null!==n.timer&&clearTimeout(n.timer);let r=setTimeout(()=>{n.timer===r&&n.element===t&&u(n)},1500);n.timer=r}},jn=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],_n={basic:{since:1},\\\"schema-json\\\":{since:2,observed:\\\"schema\\\"},locale:{since:2,observed:\\\"locale\\\"},\\\"preview-token\\\":{since:3,observed:\\\"preview-token\\\"},\\\"nested-arrays\\\":{since:4},\\\"recursive-diffs\\\":{since:4},\\\"document-events\\\":{since:4,observed:\\\"document-event\\\"},\\\"relationship-events\\\":{since:4,observed:\\\"relationship-event\\\"}},Wn=Object.keys(_n),Bn=class{constructor(e,t){gn(this,\\\"matcher\\\");gn(this,\\\"handlers\\\");gn(this,\\\"boundListener\\\");gn(this,\\\"attachedTarget\\\");gn(this,\\\"generation\\\",0);gn(this,\\\"revision\\\",0);gn(this,\\\"queueHead\\\");gn(this,\\\"queueTail\\\");this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1,n=i=>{if(!t||this.boundListener!==n)return;let r=this.generation;try{this.receive(i,r,e)}catch{let e;try{e=i.origin}catch{e=\\\"\\\"}this.reportInvalid(\\\"shape\\\",e,r)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=n;try{e.addEventListener(\\\"message\\\",n)}catch(t){this.boundListener===n&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener(\\\"message\\\",n)}catch{}throw t}if(this.boundListener===n)t=!0;else try{e.removeEventListener(\\\"message\\\",n)}catch{}}detach(){let e=this.attachedTarget,t=this.boundListener;void 0===e||void 0===t||(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener(\\\"message\\\",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}static sendReady(e,t){let n={type:\\\"payload-live-preview\\\",ready:!0,protocolVersion:4};for(let i of e)for(let e of t)try{i.postMessage(n,e)}catch{}}receive(e,t,n){let i=e.origin;if(!this.matchesOrigin(i,t)){this.reportInvalid(\\\"origin\\\",i,t);return}if(!this.matchesSource(e,n)){this.reportInvalid(\\\"source\\\",i,t);return}let r=e.data;if(function(e){return\\\"object\\\"==typeof e&&null!==e&&\\\"type\\\"in e&&\\\"string\\\"==typeof e.type}(r))switch(r.type){case\\\"payload-live-preview\\\":if(!function(e){let t=e;return!(void 0!==t.data&&null!==t.data&&!p(t.data))&&f(t.fieldSchemaJSON,e=>Array.isArray(e))&&f(t.globalSlug,e=>\\\"string\\\"==typeof e)&&f(t.collectionSlug,e=>\\\"string\\\"==typeof e)&&f(t.locale,e=>\\\"string\\\"==typeof e)&&f(t.ready,e=>\\\"boolean\\\"==typeof e)&&f(t.previewToken,e=>\\\"string\\\"==typeof e)&&f(t.protocolVersion,e=>\\\"number\\\"==typeof e)}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.dispatchUpdate(function(e){let t={...e};for(let e of jn)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);if(!Array.isArray(t.fieldSchemaJSON))return t;let n;try{n=d(t.fieldSchemaJSON)}catch{n=[]}return{...t,fieldSchemaJSON:n}}(r),i,t);return;case\\\"payload-document-event\\\":if(!function(e){let t=e;return h(t.action,e=>\\\"updated\\\"===e||\\\"created\\\"===e||\\\"deleted\\\"===e)&&h(t.slug,e=>\\\"string\\\"==typeof e)&&h(t.id,e=>\\\"string\\\"==typeof e||Number.isFinite(e))}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onDocumentEvent,r,i);return;case\\\"payload-live-preview-focus\\\":{let e=function(e){let t=e.field;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}(r);if(void 0===e){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onFocusField,e,i);return}default:this.reportInvalid(\\\"type\\\",i,t)}else this.reportInvalid(\\\"shape\\\",i,t)}dispatchUpdate(e,t,n){let i=p(e.data);if(!this.isCurrentGeneration(n))return;let r=i?{generation:n,revision:this.revision+=1}:void 0,l=this.handlers.validateToken;if(!this.isCurrentGeneration(n))return;if(void 0===l){this.commitUpdate(e,t,n,r);return}if(!0===e.ready&&void 0===e.data){this.commitUpdate(e,t,n,void 0);return}let o={generation:n,message:e,origin:t,messageRevision:r,verdict:void 0,next:void 0};this.enqueue(o);let a;try{a=l(e.previewToken,t)}catch{this.settleValidation(o,!1);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,a)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){let t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid(\\\"token\\\",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid(\\\"origin\\\",t.origin,t.generation)}}}commitUpdate(e,t,n,i){void 0===i?this.invokeHandler(n,this.handlers.onUpdate,e,t):this.invokeHandler(n,this.handlers.onUpdate,e,t,i)}reportInvalid(e,t,n){this.invokeHandler(n,this.handlers.onInvalid,e,t)}matchesSource(e,t){if(\\\"parent-or-opener\\\"!==this.handlers.sourcePolicy)return!0;try{let n=e.source;if(\\\"object\\\"!=typeof n||null===n)return!1;let i=t.parent;return i!==t&&n===i||n===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(t,n,...i){if(void 0!==n&&this.isCurrentGeneration(t))try{e(n(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}},Dn=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),zn={text:\\\"text\\\",textarea:\\\"textarea\\\",richText:\\\"richText\\\",email:\\\"email\\\",number:\\\"number\\\",checkbox:\\\"checkbox\\\",date:\\\"date\\\",select:\\\"select\\\",radio:\\\"radio\\\",array:\\\"array\\\",blocks:\\\"blocks\\\",group:\\\"text\\\",tabs:\\\"text\\\",row:\\\"text\\\",collapsible:\\\"text\\\",relationship:\\\"relationship\\\",upload:\\\"upload\\\",point:\\\"text\\\",json:\\\"text\\\",code:\\\"text\\\",ui:\\\"text\\\"},Vn=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),Hn=/^\\\\s*(?:javascript|data|vbscript|file|blob|about)\\\\s*:/i,Gn=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,qn=/^[\\\\\\\\/]{2}/,Kn=/[\\\\t\\\\n\\\\r]/g,Jn=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Xn=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Qn=new WeakSet,Zn=class{constructor(){gn(this,\\\"previous\\\",null)}diff(e,t){let n=this.previous,i=null===n,r=new Map,l=new Set;for(let[t,i]of Object.entries(e)){let e=x(i);r.set(t,e),(null===n||void 0===e||n.get(t)!==e)&&l.add(t)}if(null!==n)for(let e of n.keys())r.has(e)||l.add(e);this.previous=r;let o=new Set;for(let[e,n]of Object.entries(t))if(l.has(e))for(let e of n)o.add(e);return{changed:l,invalidated:o,baseline:i}}reset(){this.previous=null}},Yn=\\\"data-payload-fragment\\\",ei=\\\"data-payload-strategy\\\",ti=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),ni=new Set([\\\"text\\\",\\\"textarea\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"point\\\",\\\"code\\\",\\\"json\\\",\\\"ui\\\",\\\"html\\\"]),ii={},ri=class{constructor(){gn(this,\\\"rawChanges\\\",new Zn);gn(this,\\\"resolved\\\",null);gn(this,\\\"queued\\\",null);gn(this,\\\"pending\\\",null);gn(this,\\\"timer\\\",null);gn(this,\\\"openUntil\\\",0)}decide(e,t){let n=t.message.data??{},{changed:i}=this.rawChanges.diff(n,ii);if(!function(e){let{cache:t,emitter:n}=e;if(t.islands.length>0||n.listenerCount(\\\"beforeUpdate\\\")>0||n.listenerCount(\\\"afterUpdate\\\")>0)return!0;for(let e of t.values())if(z(e)||e.fieldName.includes(\\\".\\\")||H(e.hrefField)||H(e.srcField)||H(e.altField))return!0;return void 0!==e.strategies.fragment&&null!==e.root.querySelector(`[${Yn}]`)}(e))return{merge:!1,fields:n};let r=this.resolved;if(null===r)return this.resolved=n,{merge:!0,fields:n};let l={...r},o=t.forceRender;for(let a of i){let i=n[a];if(ti.has(a)){l[a]=i;continue}let s=D(a,r[a],i,e.cache,t.schemaIndex);\\\"own\\\"!==s&&(o=!0),\\\"keep\\\"!==s&&(l[a]=i)}return this.resolved=l,{merge:o,fields:l}}request(e,t,n){let i=Date.now();return i>=this.openUntil?(this.openUntil=i+t,{leading:!0,result:e.merge(n)}):(this.queued=n,this.openUntil=i+t,this.pending??(this.pending=function(){let e;return{promise:new Promise(t=>{e=t}),settle:e}}()),null!==this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.flush(e)},t),{leading:!1,result:this.pending.promise})}recordMerged(e){this.resolved=e}destroy(){null!==this.timer&&clearTimeout(this.timer),this.timer=null,this.queued=null,this.pending?.settle({status:\\\"superseded\\\"}),this.pending=null,this.openUntil=0}flush(e){let t=this.pending,n=this.queued;this.timer=null,this.pending=null,this.queued=null,null!==t&&null!==n&&e.merge(n).then(t.settle,()=>{t.settle({status:\\\"unavailable\\\"})})}},li=class{constructor(){gn(this,\\\"negotiation\\\",m(void 0));gn(this,\\\"observed\\\",new Set)}observe(e,t){let n=e.filter(e=>!this.observed.has(e));if(0!==n.length){for(let e of n)this.observed.add(e);this.negotiation=m(this.negotiation.theirs,this.observed),t(\\\"protocol\\\",`observed=${n.join(\\\",\\\")}`)}}applyVersion(e,t){let n=this.negotiation;if(n.theirs===e)return;let i=m(e,this.observed);this.negotiation=i,i.negotiated!==n.negotiated&&t(\\\"protocol\\\",\\\"ours=4\\\",`theirs=${e}`,`negotiated=${i.negotiated}`)}},oi=class{constructor(){gn(this,\\\"lastIdentity\\\")}edit(e){let t=e.externallyUpdatedRelationship;if(\\\"object\\\"!=typeof t||null===t)return null;let n=JSON.stringify([t.entitySlug,I(t),t.updatedAt]),i=n!==this.lastIdentity;return this.lastIdentity=n,i&&function(e,t){let n=t.globalSlug??t.collectionSlug;if(\\\"string\\\"!=typeof n||e.entitySlug!==n)return!0;let i=I(e),r=I(t.data??{});return void 0!==i&&void 0!==r&&i!==r}(t,e)?t:null}},ai=class{constructor(){bn(this,si)}reveal(e,t,n){return e===yn(this,si)?\\\"skipped-same\\\":(wn(this,si,e),function(e,t){return function(e,t){let n=e.getBoundingClientRect(),i=n.bottom>0&&n.top<t.innerHeight,r=n.right>0&&n.left<t.innerWidth;return i&&r}(e,t)?\\\"already-visible\\\":(e.scrollIntoView({behavior:q(t)?\\\"auto\\\":\\\"smooth\\\",block:\\\"center\\\"}),\\\"revealed\\\")}(t,n))}reset(){wn(this,si,void 0)}},si=new WeakMap,ui=class{constructor(){gn(this,\\\"seen\\\",new Map)}note(e,t,n){let i=x(n);if(void 0===i)return;let r=`${t.owner??\\\"\\\"}\\\\0${t.locale??\\\"\\\"}\\\\0${t.fieldName}`,l=this.seen.get(r);void 0!==l?l!==i&&(e.revealIdentities.push([r,i]),e.revealTarget??(e.revealTarget=t)):this.seen.set(r,i)}commit(e){for(let[t,n]of e.revealIdentities)this.seen.set(t,n);e.revealIdentities=[];let t=e.revealTarget;return e.revealTarget=void 0,t}},di=class{constructor(){gn(this,\\\"started\\\",!1);gn(this,\\\"suspended\\\",!1);gn(this,\\\"deferredStart\\\",null);gn(this,\\\"hydration\\\",\\\"idle\\\");gn(this,\\\"activeUpdate\\\",null);gn(this,\\\"locale\\\");gn(this,\\\"schema\\\");gn(this,\\\"schemaIndex\\\");gn(this,\\\"updateCount\\\",0);gn(this,\\\"supersededCount\\\",0);gn(this,\\\"completedCount\\\",0);gn(this,\\\"skippedUnchangedCount\\\",0);gn(this,\\\"lastFlush\\\",null);gn(this,\\\"absentFields\\\",new Set);gn(this,\\\"warnedOrphanFields\\\",new Set);gn(this,\\\"warnedStrategy\\\",new WeakSet);gn(this,\\\"warnedUnattributableMessage\\\",!1);gn(this,\\\"warnedVisibilityGate\\\",!1);gn(this,\\\"warnedFragmentFallback\\\",!1);gn(this,\\\"warnedProtocolShape\\\",!1);gn(this,\\\"reportedUnfaithful\\\",new WeakSet);gn(this,\\\"checkedServerFormat\\\",new WeakSet);gn(this,\\\"unfaithfulPatches\\\",[]);gn(this,\\\"unfaithfulCount\\\",0);gn(this,\\\"escalatedCount\\\",0);gn(this,\\\"unfaithfulFields\\\",new Set);gn(this,\\\"autoBindSearchMs\\\");gn(this,\\\"autoBindGuesses\\\",null);gn(this,\\\"warnedForeignSource\\\",!1);gn(this,\\\"lastAppliedIdentity\\\",new WeakMap);gn(this,\\\"revealLedger\\\",new ui);gn(this,\\\"fragmentStats\\\",{rendered:0,failed:0,superseded:0});gn(this,\\\"routeStats\\\",{refreshes:0,failed:0,refused:0,loopStopped:0});gn(this,\\\"fragmentController\\\",null);gn(this,\\\"routeController\\\",null);gn(this,\\\"routeRetry\\\",null);gn(this,\\\"readyTimers\\\",[]);gn(this,\\\"revealer\\\",new ai);gn(this,\\\"changes\\\",new Zn);gn(this,\\\"merges\\\",new ri);gn(this,\\\"protocol\\\",new li);gn(this,\\\"relationships\\\",new oi)}isRunning(){return this.started}isCurrent(e){return this.started&&this.activeUpdate===e}complete(e){e.completed||(e.completed=!0,this.completedCount+=1)}abortStrategies(){null!==this.routeRetry&&(clearTimeout(this.routeRetry),this.routeRetry=null);for(let e of[\\\"fragmentController\\\",\\\"routeController\\\"]){let t=this[e];null!==t&&(this[e]=null,t.abort())}}},ci=class{constructor(e,t){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"instanceContext\\\");this.instanceContext=function(e){let t={};for(let[n,i]of Object.entries(e))void 0!==i&&(t[n]=i);return t}({renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,reportUnfaithful:(n,i)=>{r(e,t,n,i)}})}apply(e){let{deps:t,state:n}=this,i=n.activeUpdate;if(null===i||void 0===e.revision||!g(i.revision,e.revision)||!n.isCurrent(i))return!1;let{target:l,value:s}=e,u=void 0!==i.schemaIndex?S(i.schemaIndex,l.fieldName):void 0,d=function(e,t){if(e.explicitFieldType)return e.fieldType;if(void 0!==t){let e=function(e){if(Object.prototype.hasOwnProperty.call(zn,e))return zn[e]}(t);if(void 0!==e)return e}return e.fieldType}(l,u?.type);\\\"text\\\"===d&&!0!==l.explicitFieldType&&function(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&Array.isArray(t.children)}(s)&&(d=\\\"richText\\\");let c;try{c=t.resolveRenderer(d,l)}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;let h=t.emitter.listenerCount(\\\"elementUpdate\\\")>0,f=h?function(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:\\\"IMG\\\"===e.tagName?e.src:e.textContent}(l.element):void 0;if(!n.isCurrent(i))return!1;let p={allFields:e.allFields,locale:l.locale??i.locale,schema:u,...this.instanceContext};!0===l.hidesWhenEmpty&&l.element.toggleAttribute(\\\"hidden\\\",function(e){return null==e||(\\\"string\\\"==typeof e?0===e.trim().length:Array.isArray(e)&&0===e.length)}(s));try{if(void 0!==l.targetAttribute){if(\\\"blocked\\\"===function(e,t,n){let i=t.toLowerCase().trim();if(0===i.length||!F(i))return\\\"blocked\\\";if(null==n)return e.removeAttribute(i),\\\"applied\\\";if(\\\"string\\\"!=typeof n&&\\\"number\\\"!=typeof n&&\\\"boolean\\\"!=typeof n)return\\\"blocked\\\";let r=String(n);return Xn.has(i)&&!$(r)?\\\"blocked\\\":(e.setAttribute(i,r),\\\"applied\\\")}(l.element,l.targetAttribute,s))return t.warn(`[live-preview] LP0401: refused to write \\\"${l.fieldName}\\\" into attribute \\\"${l.targetAttribute}\\\"`),!1}else{if(void 0===c)return t.log(\\\"no renderer for\\\",d),r(t,n,l,`has no renderer for \\\"${d}\\\"`),!1;{let e=function(e,t,n,i){if(\\\"ignore\\\"===e.onUnfaithfulPatch||void 0!==n.format||!On.has(i)||t.checkedServerFormat.has(n.element))return;t.checkedServerFormat.add(n.element);let r=o(n.element);return r.trim().length>0?r:void 0}(t,n,l,d);if(!1===function(e,t,n,i){return e.render(t,n,i)}(c,l,s,p)&&function(e){return Qn.has(e.render)}(c))return r(t,n,l,`is a value ${c.name} cannot render`),!1;void 0!==e&&function(e,t,n){let i=o(t.element);i!==n&&e.warn(`[live-preview] LP0412: \\\"${t.fieldName}\\\" showed ${a(n)}, the patch wrote ${a(i)} \\\\u2014 either an edit that arrived before the preview connected, or a template that formats this value differently. Set data-payload-format to match it.`)}(t,l,e)}}}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;h&&t.emitter.emitWhile(\\\"elementUpdate\\\",{element:l.element,fieldName:l.fieldName,previousValue:f,nextValue:s,revision:i.revision.revision,receivedAt:i.receivedAt,source:\\\"patch\\\"},()=>n.isCurrent(i));let m=n.isCurrent(i);return m&&(void 0!==e.valueIdentity?n.lastAppliedIdentity.set(l.element,e.valueIdentity):n.lastAppliedIdentity.delete(l.element)),m}fail(e,t){if(!this.state.isCurrent(e))return!1;let n=t instanceof Error?t:new Error(String(t));return this.deps.emitter.emitWhile(\\\"error\\\",{error:n,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.state.isCurrent(e)),!1}},hi=\\\"data-payload-island\\\",fi=`astro-island, [${hi}]`,pi=\\\"data-payload-field\\\",mi=\\\"data-payload-type\\\",gi=\\\"data-payload-attribute\\\",vi=\\\"data-payload-href\\\",yi=\\\"data-payload-src\\\",bi=\\\"data-payload-alt\\\",wi=\\\"data-payload-array-template\\\",Si=\\\"data-payload-array-separator\\\",Ti=\\\"data-payload-locale\\\",ki=\\\"data-payload-richtext\\\",Ai=\\\"data-payload-html\\\",Ci=\\\"data-payload-array\\\",$i=\\\"data-payload-structural\\\",Ri=\\\"data-payload-owner\\\",Fi=\\\"data-payload-depends\\\",Ni=\\\"data-payload-strategy\\\",xi=\\\"data-payload-boundary\\\",Mi=\\\"data-payload-guessed\\\",Ei=[pi,mi,gi,vi,yi,bi,wi,Si,Ti,ki,Ai,Ci,$i,Ri,Fi,Ni,xi,\\\"type\\\"],Oi=`[${pi}]`,Pi=`[${Ri}]`,Li=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,Ui=new Set([\\\"text\\\",\\\"textarea\\\",\\\"richText\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"array\\\",\\\"blocks\\\",\\\"group\\\",\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\",\\\"relationship\\\",\\\"upload\\\",\\\"point\\\",\\\"json\\\",\\\"code\\\",\\\"ui\\\",\\\"html\\\",\\\"url\\\",\\\"image\\\",\\\"structural-array\\\"]),Ii=class{constructor(e={}){gn(this,\\\"entriesByField\\\",new Map);gn(this,\\\"entryByElement\\\",new WeakMap);gn(this,\\\"filter\\\");gn(this,\\\"count\\\",0);gn(this,\\\"dependencies\\\",null);gn(this,\\\"islandRoots\\\",[]);this.filter=e.filter??te}dependencyMap(){if(null!==this.dependencies)return this.dependencies;let e=[];for(let t of this.values())void 0!==t.dependsOn&&e.push(J(t.fieldName,t.dependsOn));return this.dependencies=K(...e),this.dependencies}get islands(){return this.islandRoots}buildFromRoot(e){let t=performance.now();this.clear();let n=0;for(let t of e.querySelectorAll(Oi))void 0!==this.add(t)&&(n+=1);return this.islandRoots=function(e){let t=[];for(let n of e.querySelectorAll(fi))X(n)||t.push(n);return t}(e),{elementCount:n,fieldCount:this.entriesByField.size,durationMs:performance.now()-t}}add(e){let t=this.filter(e)?this.resolveBinding(e):void 0,n=this.entryByElement.get(e);if(this.dependencies=null,void 0!==t)return void 0!==n&&this.replaceEntry(n,t)?(this.entryByElement.set(e,t),t):(void 0!==n&&this.removeEntry(e,n),this.append(t),this.entryByElement.set(e,t),t);void 0!==n&&this.removeEntry(e,n)}remove(e){let t=this.entryByElement.get(e);return!!t&&(this.dependencies=null,this.removeEntry(e,t))}get(e){return this.entriesByField.get(e)}getByElement(e){return this.entryByElement.get(e)}get fieldCount(){return this.entriesByField.size}get elementCount(){return this.count}entries(){return this.entriesByField.entries()}*values(){for(let e of this.entriesByField.values())yield*e}has(e){return this.entryByElement.has(e)}clear(){this.entriesByField.clear(),this.entryByElement=new WeakMap,this.count=0,this.dependencies=null,this.islandRoots=[]}replaceEntry(e,t){if(e.fieldName!==t.fieldName)return!1;let n=this.entriesByField.get(e.fieldName),i=void 0===n?-1:n.indexOf(e);return!(void 0===n||i<0||(n[i]=t,0))}removeEntry(e,t){this.entryByElement.delete(e);let n=this.entriesByField.get(t.fieldName),i=void 0===n?-1:n.indexOf(t);return!(void 0===n||i<0||(n.splice(i,1),0===n.length&&this.entriesByField.delete(t.fieldName),this.count-=1,0))}append(e){let t=this.entriesByField.get(e.fieldName);t?t.push(e):this.entriesByField.set(e.fieldName,[e]),this.count+=1}resolveBinding(e){let t=e.getAttribute(pi);if(null===t||0===t.length)return;let n=e.getAttribute(mi),i=e.getAttribute(gi),r=e.getAttribute(vi),l=e.getAttribute(yi),o=e.getAttribute(bi),a=e.getAttribute(wi),s=e.getAttribute(Si),u=e.getAttribute(Ti),d=e.getAttribute(\\\"data-payload-format\\\"),c=Z(e),h=function(e){if(null==e)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let e=i.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}(e.getAttribute(Fi)),f=e.getAttribute(Ni),p=e.getAttribute(Mi),m=M(e);return{element:e,fieldName:t,fieldType:ee(e),explicitFieldType:null!==n&&Y(n),strategyKind:E(e)??\\\"unknown\\\",...null!==m?{fragmentBoundary:m}:{},...null!==i&&i.length>0?{targetAttribute:i}:{},...null!==r&&r.length>0?{hrefField:r}:{},...null!==l&&l.length>0?{srcField:l}:{},...null!==o&&o.length>0?{altField:o}:{},...null!==a?{arrayTemplate:a}:{},...null!==s?{arraySeparator:s}:{},...null!==u&&u.length>0?{locale:u}:{},...null!==d&&d.length>0?{format:d}:{},...void 0!==c?{owner:c}:{},...h.length>0?{dependsOn:h}:{},...null!==f&&f.length>0?{strategy:f}:{},...e.hasAttribute(xi)?{hidesWhenEmpty:!0}:{},...null!==p?{guessed:p}:{}}}},ji=class{constructor(e){gn(this,\\\"serverURL\\\");gn(this,\\\"apiRoute\\\");gn(this,\\\"depth\\\");gn(this,\\\"fetchFn\\\");gn(this,\\\"log\\\");gn(this,\\\"inflight\\\",null);gn(this,\\\"attempt\\\",0);gn(this,\\\"destroyDepth\\\",0);this.serverURL=function(e){let t=e.length;for(;e.endsWith(\\\"/\\\",t);)t-=1;return e.slice(0,t)}(e.serverURL);let i=e.apiRoute??\\\"/api\\\";this.apiRoute=i.startsWith(\\\"/\\\")?i:`/${i}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=t(e.log??n)}canMerge(e){return null!==this.endpointOf(e)}endpointOf(e){try{let t=e.globalSlug;if(t)return ie(t)?`globals/${encodeURIComponent(t)}`:null;let n=e.collectionSlug??\\\"\\\",i=e.data.id;return ie(n)&&function(e){return\\\"number\\\"==typeof e?Number.isFinite(e):\\\"string\\\"==typeof e&&ne(e,512)}(i)?`${encodeURIComponent(n)}/${encodeURIComponent(String(i))}`:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:\\\"superseded\\\"};let t=this.attempt+=1,n=this.inflight;this.inflight=null;let i=null,r=()=>this.attempt!==t;try{if(n?.abort(),r())return{status:\\\"superseded\\\"};let t=this.endpointOf(e);if(null===t)return r()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"};let l=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(void 0===l)return{status:\\\"unavailable\\\"};i=new AbortController,this.inflight=i;let o=`${this.serverURL}${this.apiRoute}/${t}`,a=await l(o,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale}),signal:i.signal});if(r())return{status:\\\"superseded\\\"};if(!a.ok)return this.log(\\\"merge HTTP\\\",a.status,o),{status:\\\"unavailable\\\"};let s=await a.json();return r()?{status:\\\"superseded\\\"}:null===s||\\\"object\\\"!=typeof s||Array.isArray(s)?(this.log(\\\"merge invalid\\\",o),{status:\\\"unavailable\\\"}):{status:\\\"merged\\\",doc:s}}catch(e){return r()?{status:\\\"superseded\\\"}:(this.log(\\\"merge exception\\\",e),{status:\\\"unavailable\\\"})}finally{this.inflight===i&&(this.inflight=null)}}destroy(){this.attempt+=1;let e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},_i=\\\"2.0.0\\\",Wi={name:\\\"payload-2\\\",fieldTyping:\\\"schema\\\",populatesRelationships:\\\"admin\\\",documentEvents:!1},Bi={name:\\\"payload-3\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!0},Di={name:\\\"unknown\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!1},zi=1,Vi=class{constructor(e,t={}){gn(this,\\\"callbacks\\\");gn(this,\\\"debounceMs\\\");gn(this,\\\"rootMargin\\\");gn(this,\\\"visible\\\",new Set);gn(this,\\\"mutation\\\",null);gn(this,\\\"intersection\\\",null);gn(this,\\\"debounceTimer\\\",null);gn(this,\\\"generation\\\",0);this.callbacks=e,this.debounceMs=t.mutationDebounceMs??100,this.rootMargin=t.intersectionRootMargin??\\\"200px\\\"}start(e){let t=this.generation;this.stop();let n=t+1;if(this.generation!==n)return;let i=null,r=null;try{i=new MutationObserver(e=>{this.handleMutations(e,n)}),r=new IntersectionObserver(e=>{this.handleIntersection(e,n)},{rootMargin:this.rootMargin,threshold:0}),i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...Ei]})}catch(e){throw i?.disconnect(),r?.disconnect(),e}this.generation===n?(this.mutation=i,this.intersection=r):(i.disconnect(),r.disconnect())}observeElement(e){this.intersection?.observe(e)}unobserveElement(e){this.intersection?.unobserve(e),this.visible.delete(e)}markVisible(e,t){t?this.visible.add(e):this.visible.delete(e)}isVisible(e){return this.visible.has(e)}stop(){this.generation+=1;let e=this.debounceTimer,t=this.mutation,n=this.intersection;this.debounceTimer=null,this.mutation=null,this.intersection=null,this.visible.clear(),null!==e&&clearTimeout(e);try{t?.disconnect()}finally{n?.disconnect()}}handleMutations(e,t){if(!this.isCurrentGeneration(t)||!function(e){for(let t of e){if(\\\"attributes\\\"===t.type&&null!==t.attributeName&&Ei.includes(t.attributeName)&&(t.attributeName===pi||t.attributeName===Ri||t.target.nodeType===zi&&t.target.hasAttribute(pi)))return!0;for(let e of t.addedNodes)if(le(e))return!0;for(let e of t.removedNodes)if(le(e))return!0}return!1}(e))return;null!==this.debounceTimer&&clearTimeout(this.debounceTimer);let n=setTimeout(()=>{!this.isCurrentGeneration(t)||this.debounceTimer!==n||(this.debounceTimer=null,this.callbacks.onStructuralChange())},this.debounceMs);this.debounceTimer=n}handleIntersection(e,t){for(let n of e){if(!this.isCurrentGeneration(t))return;let{target:e}=n;if(n.isIntersecting){if(this.visible.has(e))continue;this.visible.add(e),this.callbacks.onVisibilityChange(e,!0)}else this.visible.has(e)&&(this.visible.delete(e),this.callbacks.onVisibilityChange(e,!1))}}isCurrentGeneration(e){return this.generation===e&&null!==this.intersection}},Hi=\\\"__livePreviewHydration\\\",Gi=\\\"[data-payload-field]\\\",qi=\\\"__vue_app__\\\",Ki=\\\"__livePreviewVueHydration\\\",Ji=\\\"app:suspense:resolve\\\",Xi=class{constructor(e){gn(this,\\\"timeoutMs\\\");gn(this,\\\"onTimeout\\\");gn(this,\\\"handle\\\",null);gn(this,\\\"lastKick\\\",0);this.timeoutMs=e.timeoutMs??0,this.onTimeout=e.onTimeout}kick(){if(this.lastKick=Date.now(),this.timeoutMs<=0)return;null!==this.handle&&clearTimeout(this.handle);let e=setTimeout(()=>{this.handle===e&&(this.handle=null,this.onTimeout())},this.timeoutMs);this.handle=e}stop(){null!==this.handle&&(clearTimeout(this.handle),this.handle=null)}get lastKickAt(){return this.lastKick}get pending(){return null!==this.handle}},Qi=class{constructor(){gn(this,\\\"current\\\",\\\"disconnected\\\")}get status(){return this.current}markConnected(){return this.transition(\\\"connected\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(e){return this.current!==e&&(this.current=e,!0)}},Zi=\\\"data-payload-no-bind\\\",Yi=\\\"data-payload-owned\\\",er=13,tr=new Set([\\\"true\\\",\\\"false\\\",\\\"yes\\\",\\\"no\\\",\\\"on\\\",\\\"off\\\"]),nr=/^[\\\\d\\\\s.,:+/-]+$/u,ir=/^[a-z][a-z0-9_-]*$/u,rr=/^[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/u,lr=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"TITLE\\\",\\\"NOSCRIPT\\\",\\\"TEXTAREA\\\",\\\"SELECT\\\",\\\"OPTION\\\",\\\"INPUT\\\",\\\"IFRAME\\\"]),or=\\\"http://www.w3.org/1999/xhtml\\\",ar=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),sr=\\\"payload-live-preview\\\",ur=\\\"data-payload-owned\\\",dr=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]),cr=new Set,hr=\\\"data-payload-\\\",fr=new Set([\\\"p\\\",\\\"br\\\",\\\"strong\\\",\\\"b\\\",\\\"em\\\",\\\"i\\\",\\\"u\\\",\\\"s\\\",\\\"strike\\\",\\\"mark\\\",\\\"small\\\",\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\",\\\"ul\\\",\\\"ol\\\",\\\"li\\\",\\\"dl\\\",\\\"dt\\\",\\\"dd\\\",\\\"blockquote\\\",\\\"code\\\",\\\"pre\\\",\\\"kbd\\\",\\\"samp\\\",\\\"var\\\",\\\"a\\\",\\\"span\\\",\\\"div\\\",\\\"section\\\",\\\"article\\\",\\\"aside\\\",\\\"header\\\",\\\"footer\\\",\\\"nav\\\",\\\"figure\\\",\\\"figcaption\\\",\\\"img\\\",\\\"picture\\\",\\\"source\\\",\\\"audio\\\",\\\"video\\\",\\\"sub\\\",\\\"sup\\\",\\\"hr\\\",\\\"time\\\",\\\"abbr\\\",\\\"cite\\\",\\\"q\\\",\\\"table\\\",\\\"thead\\\",\\\"tbody\\\",\\\"tfoot\\\",\\\"tr\\\",\\\"th\\\",\\\"td\\\",\\\"caption\\\",\\\"colgroup\\\",\\\"col\\\"]),pr=new Set([\\\"input\\\",\\\"button\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"label\\\"]),mr=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),gr=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),vr=\\\"aria-\\\",yr=\\\"data-\\\",br=\\\"data-payload-\\\",wr={a:new Set([\\\"href\\\",\\\"target\\\",\\\"rel\\\",\\\"download\\\",\\\"hreflang\\\",\\\"type\\\"]),img:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"alt\\\",\\\"width\\\",\\\"height\\\",\\\"loading\\\",\\\"decoding\\\"]),picture:new Set([]),source:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"type\\\",\\\"media\\\"]),audio:new Set([\\\"src\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\"]),video:new Set([\\\"src\\\",\\\"poster\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\",\\\"width\\\",\\\"height\\\",\\\"playsinline\\\"]),time:new Set([\\\"datetime\\\"]),abbr:new Set([\\\"title\\\"]),q:new Set([\\\"cite\\\"]),blockquote:new Set([\\\"cite\\\"]),table:new Set([\\\"summary\\\"]),th:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"scope\\\",\\\"headers\\\",\\\"abbr\\\"]),td:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"headers\\\"]),col:new Set([\\\"span\\\"]),colgroup:new Set([\\\"span\\\"]),ol:new Set([\\\"start\\\",\\\"reversed\\\",\\\"type\\\"]),li:new Set([\\\"value\\\"]),code:new Set([\\\"class\\\"]),pre:new Set([\\\"class\\\"])},Sr=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),Tr=1,kr=8,Ar=(Error,new Set([\\\"id\\\",\\\"name\\\",\\\"data-payload-key\\\",\\\"data-payload-nested-key\\\",\\\"data-payload-nested-template\\\"])),Cr=\\\"strict\\\",$r=(Object.freeze({allowedTags:fr,removeCompletely:mr,globalAttributes:gr,attributesByTag:wr,urlAttributes:Sr}),Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"})),Rr=/[&<>\\\"'/`=]/g,Fr=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Nr=/[&<>\\\"']/g,xr=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g,Mr=\\\"data-payload-\\\",Er=[\\\"input\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"button\\\",\\\"label\\\",\\\"details\\\",\\\"summary\\\",\\\"dialog\\\",\\\"video\\\",\\\"audio\\\",\\\"progress\\\",\\\"meter\\\"],Or=[\\\"type\\\",\\\"name\\\",\\\"placeholder\\\",\\\"open\\\",\\\"disabled\\\",\\\"readonly\\\",\\\"required\\\",\\\"checked\\\",\\\"selected\\\",\\\"value\\\",\\\"min\\\",\\\"max\\\",\\\"step\\\",\\\"rows\\\",\\\"cols\\\",\\\"for\\\",\\\"controls\\\",\\\"muted\\\",\\\"loop\\\",\\\"poster\\\",\\\"src\\\"],Pr=/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\\\b/gi,Lr=64,Ur=new Map,Ir=\\\"data-payload-key\\\",jr=\\\"data-payload-nested-key\\\",_r=\\\"data-payload-nested-template\\\",Wr=class{constructor(e,t,n){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"host\\\",n)}planFragments(e){let t=this.deps.strategies.fragment;return void 0===t?null:yt(t,t.plan(this.deps.root,e))}escalateUnfaithful(e,t,n){if(e.routeRefreshed)return;let{fragment:i,route:r}=this.deps.strategies,l=void 0===i?void 0:function(e){let t=[];for(let n of e){let e=n.fragmentBoundary;if(void 0===e)return;t.includes(e)||t.push(e)}return t}(n);void 0===i||void 0===l?void 0!==r&&(this.state.escalatedCount+=n.length,this.refreshRoute(e,t,r)):(this.state.escalatedCount+=n.length,e.pendingFragments+=l.length,this.runFragments(e,t,yt(i,l)))}hasUnboundChange(e,t){let{deps:n,state:i}=this;if(e.baseline||e.routeRefreshed)return!1;let r=function(e,t,n,i){let r=B(e,n,i),l=[];for(let e of t)!ti.has(e)&&!r(e)&&l.push(e);return l}(n.cache,e.touched,e.locale,t),o=0;for(let e of r)l(i,e)&&(o+=1);let[a]=r;return void 0!==a&&\\\"escalate\\\"===n.onUnfaithfulPatch&&void 0!==n.strategies.route&&(n.log(\\\"route\\\",\\\"LP0807\\\",`field \\\"${a}\\\" has no binding; refreshing the route`),i.escalatedCount+=o,!0)}hasRouteBinding(e){for(let[t,n]of this.deps.cache.entries())if(e.has(t)&&n.some(e=>\\\"route\\\"===e.strategyKind))return!0;return!1}async runFragments(e,t,n){let{deps:i,state:r}=this,l=new AbortController;r.fragmentController=l;let o=()=>r.isCurrent(e)&&!l.signal.aborted,{emitter:a}=i,{message:s}=e,u=e.revision.revision,d=e.receivedAt,c={root:i.root,revision:u,receivedAt:d,fields:t.fields,locale:e.locale,collectionSlug:\\\"string\\\"==typeof s.collectionSlug?s.collectionSlug:void 0,globalSlug:\\\"string\\\"==typeof s.globalSlug?s.globalSlug:void 0,signal:l.signal,isCurrent:o,log:(e,t)=>{i.log(\\\"fragment\\\",e,t)},morph:(e,t)=>{!function(e,t){let n=e.ownerDocument.createElement(\\\"template\\\");n.innerHTML=Le(t);let i=e.cloneNode(!1);i.append(n.content),je(e,i,{keyAttributes:[Ir]})}(e,t)},patch:n=>{this.patchFallback(e,t,n)},rendered:(t,n,i)=>{e.pendingFragments-=1,a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:i,status:\\\"rendered\\\",revision:u,receivedAt:d},o)},failed:(t,n,r,l,s)=>{e.pendingFragments-=1;let c=`fragment \\\"${n}\\\" fell back to patch: ${s}`;i.log(\\\"fragment\\\",l,c),a.emitWhile(\\\"error\\\",{error:new Error(c),context:\\\"fragment\\\",code:l},o),a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:r,status:\\\"failed\\\",code:l,revision:u,receivedAt:d},o)}},h={rendered:0,failed:0,superseded:0};try{h=await n.strategy.render(c,n.boundaries)}catch(r){if(i.log(\\\"fragment\\\",\\\"LP0801\\\",r),o()){for(let i of n.boundaries)this.patchFallback(e,t,i);h={rendered:0,failed:n.boundaries.length,superseded:0}}}r.fragmentStats.rendered+=h.rendered,r.fragmentStats.failed+=h.failed,r.fragmentStats.superseded+=h.superseded,o()&&(r.fragmentController===l&&(r.fragmentController=null),e.pendingFragments=0,0===i.scheduler.pendingCount&&r.complete(e),this.host.revealPending(e),o()&&(0===h.rendered||0===a.listenerCount(\\\"afterUpdate\\\")||a.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:h.rendered,durationMs:Date.now()-d,revision:u,receivedAt:d,source:\\\"fragment\\\"},o)))}async refreshRoute(e,t,n){let{deps:i,state:r}=this;e.routeRefreshed?(r.routeStats.loopStopped+=1,i.log(\\\"route\\\",\\\"LP0805\\\",`revision ${String(e.revision.revision)} asked for a second refresh`)):(e.routeRefreshed=!0,await this.runRoute(e,t,n))}armRouteRetry(e,t,n,i){let{state:r}=this;null!==r.routeRetry&&clearTimeout(r.routeRetry),r.routeRetry=setTimeout(()=>{r.routeRetry=null,r.isCurrent(e)&&this.runRoute(e,t,n)},i)}async runRoute(e,t,n){let{deps:i,state:r}=this,l=r.routeStats,o=new AbortController;r.routeController=o;let a,s=()=>r.isCurrent(e)&&!o.signal.aborted;try{a=await n.refresh({revision:e.revision.revision,receivedAt:e.receivedAt,signal:o.signal,isCurrent:s,log:(e,t)=>{i.log(\\\"route\\\",e,t)},retryAfter:i=>{this.armRouteRetry(e,t,n,i)}})}catch(e){i.log(\\\"route\\\",\\\"LP0801\\\",e),a=\\\"failed\\\"}if(s()){if(r.routeController===o&&(r.routeController=null),\\\"refreshed\\\"===a){if(l.refreshes+=1,r.lastAppliedIdentity=new WeakMap,this.host.restoreGuesses(e,t),this.host.rebuildCache(),!s())return;this.host.reapply(e,t),i.emitter.listenerCount(\\\"afterUpdate\\\")>0&&i.emitter.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:i.cache.elementCount,durationMs:Date.now()-e.receivedAt,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"route\\\"},s);return}\\\"failed\\\"===a?l.failed+=1:\\\"refused\\\"===a&&(l.refused+=1),this.host.reapply(e,t)}}warnFragmentFallback(e){!function(e,t,n){t.warnedFragmentFallback||(t.warnedFragmentFallback=!0,e.warn(`[live-preview] LP0806: \\\"${n.fieldName}\\\" asks for the fragment strategy but no handler is configured; patching instead`))}(this.deps,this.state,e)}warnUnsupportedStrategy(e){!function(e,t,n){t.warnedStrategy.has(n.element)||(t.warnedStrategy.add(n.element),e.warn(`[live-preview] LP0407: \\\"${n.fieldName}\\\" asks for strategy \\\"${String(n.strategy)}\\\"; only patch, fragment and route exist`))}(this.deps,this.state,e)}patchFallback(e,t,n){for(let[i,r]of this.deps.cache.entries())for(let l of r){if(l.fragmentBoundary!==n)continue;let r=xe(t.fields,l,i,e.locale);void 0!==r&&this.deps.scheduler.schedule({target:l,value:this.host.transform(l,r,t.fields,()=>!0),allFields:t.fields,revision:e.revision,data:t})}}},Br=new Set,Dr=class{constructor(e,t,n){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"strategies\\\");this.strategies=new Wr(e,t,{reapply:(e,t)=>{this.scheduleAllFields(e,t)},transform:(t,n,i,r)=>bt(e,t,n,i,r),rebuildCache:n,restoreGuesses:(e,t)=>{this.restoreGuesses(e,t)},revealPending:e=>{this.revealPending(e)}})}handleUpdate(e,t,n){let{deps:i,state:r}=this;if(i.heartbeat.kick(),r.protocol.observe(function(e){let t=[];return Array.isArray(e.fieldSchemaJSON)&&t.push(\\\"schema-json\\\"),\\\"string\\\"==typeof e.locale&&t.push(\\\"locale\\\"),\\\"string\\\"==typeof e.previewToken&&t.push(\\\"preview-token\\\"),\\\"object\\\"==typeof e.externallyUpdatedRelationship&&null!==e.externallyUpdatedRelationship&&t.push(\\\"relationship-events\\\"),t}(e),i.log),void 0===e.data){void 0!==e.protocolVersion&&r.protocol.applyVersion(e.protocolVersion,i.log);return}if(void 0===n)return;let l=r.relationships.edit(e);null!==l&&i.emitter.emit(\\\"relationshipUpdate\\\",{detail:l,timestamp:Date.now()}),\\\"string\\\"==typeof e.locale&&(r.locale=e.locale),Array.isArray(e.fieldSchemaJSON)&&(r.schema=e.fieldSchemaJSON,r.schemaIndex=b(e.fieldSchemaJSON));let o={revision:n,message:e,locale:r.locale,schema:r.schema,schemaIndex:r.schemaIndex,receivedAt:Date.now(),forceRender:null!==l||G(r.activeUpdate),touched:new Set,baseline:!1,invalidated:new Set,revealTarget:void 0,revealIdentities:[],pendingFragments:0,routeRefreshed:!1,cancelled:!1,completed:!1},a=r.activeUpdate;r.abortStrategies(),null!==a&&!a.completed&&(r.supersededCount+=1),r.activeUpdate=o,i.scheduler.acceptRevision(n),r.updateCount+=1,(void 0===e.protocolVersion||(r.protocol.applyVersion(e.protocolVersion,i.log),r.isCurrent(o)))&&(i.connection.markConnected()&&(i.a11y?.announceConnected(),i.emitter.emit(\\\"connect\\\",{origin:t,timestamp:Date.now()}),!r.isCurrent(o)||(i.log(\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!r.isCurrent(o)))||this.processUpdate(o).catch(e=>{i.log(\\\"update failed:\\\",e)}))}async processUpdate(e){let{deps:t,state:n}=this,i=await this.resolveIncomingFields(e);if(null===i||!n.isCurrent(e))return;let r=this.dataFor(e,i);t.emitter.listenerCount(\\\"beforeUpdate\\\")>0&&(!await t.emitter.emitWhile(\\\"beforeUpdate\\\",{data:r,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"patch\\\",cancel:()=>{e.cancelled=!0,t.scheduler.cancelRevision(e.revision)}},()=>!e.cancelled&&n.isCurrent(e))||e.cancelled||!n.isCurrent(e))||this.applyFields(e,r,!1)}dataFor(e,t){let{message:n}=e;return{fields:t,...void 0!==e.schema?{schema:e.schema}:{},...\\\"string\\\"==typeof n.globalSlug?{globalSlug:n.globalSlug}:{},...\\\"string\\\"==typeof n.collectionSlug?{collectionSlug:n.collectionSlug}:{},...void 0!==e.locale?{locale:e.locale}:{}}}applyFields(e,t,n){let{deps:i,state:r}=this,l=K(i.dependencies,i.cache.dependencyMap()),o=r.changes.diff(t.fields,l);if(o.baseline&&!n&&\\\"off\\\"!==i.autoBind){let n=this.ownerKeysForUpdate(e,t.fields);!function(e,t,n,i,r){let l=performance.now(),o=$e(e.root),a=ye(n,i),s=null===o?[]:Re(e,Ce(o,a),r,\\\"on the first message\\\");t.autoBindGuesses=function(e,t){let n=new Set;for(let{fieldName:e,stamps:i}of t){n.add(e);for(let e of[vi,bi]){let t=i[e];void 0!==t&&n.add(t)}}let i=new Map;for(let[t,r]of e)null!==r&&n.has(r.field)&&i.set(t,r);return{fields:n,values:i}}(a,s),t.autoBindSearchMs=performance.now()-l,s.length}(i,r,t.fields,e.locale,n)}e.baseline=o.baseline,e.invalidated=n?Br:o.invalidated,e.touched=n?Br:new Set([...o.changed,...o.invalidated]),this.scheduleAllFields(e,t)}async resolveIncomingFields(e){let{deps:t,state:n}=this,i=e.message.data??{};if(null===t.merger||\\\"admin\\\"===re(n.protocol.observed).populatesRelationships)return i;let r=n.merges.decide(t,e);if(!r.merge)return r.fields;let{message:l}=e,o=n.merges.request(t.merger,t.mergeWindowMs,{collectionSlug:l.collectionSlug,globalSlug:l.globalSlug,data:i,locale:e.locale});if(!o.leading)return this.applyMerged(e,o.result).catch(e=>{t.log(\\\"update failed:\\\",e)}),r.fields;let a=await o.result;return n.isCurrent(e)?\\\"merged\\\"===a.status?(n.merges.recordMerged(a.doc),a.doc):\\\"superseded\\\"===a.status?null:r.fields:null}async applyMerged(e,t){let{state:n}=this,i=await t;\\\"merged\\\"!==i.status||!n.isCurrent(e)||(n.merges.recordMerged(i.doc),this.applyFields(e,this.dataFor(e,i.doc),!0))}scheduleAllFields(e,t){let{deps:n,state:i}=this;if(!i.isCurrent(e))return;let r=()=>i.isCurrent(e),l=this.ownerKeysForUpdate(e,t.fields),{touched:o}=e,a=n.strategies.route,s=this.strategies.hasUnboundChange(e,l);if(void 0!==a&&!e.routeRefreshed&&(s||a.plan(n.root,o)||this.strategies.hasRouteBinding(o))){this.strategies.refreshRoute(e,t,a);return}let u=this.strategies.planFragments(o),d=n.skipUnchanged,c=0;for(let[o,a]of n.cache.entries()){if(!r())return;for(let s of a){if(!1!==l&&!U(s.owner,l))continue;if(!0===u?.covers(s)){if(n.revealEditedField){let n=xe(t.fields,s,o,e.locale);i.revealLedger.note(e,s,n)}continue}let a=s.strategyKind??E(s.element)??\\\"unknown\\\";if(\\\"unknown\\\"===a){this.strategies.warnUnsupportedStrategy(s);continue}\\\"fragment\\\"===a&&null===u&&this.strategies.warnFragmentFallback(s);let h=xe(t.fields,s,o,e.locale);if(void 0===h){i.absentFields.add(o);continue}if(n.revealEditedField&&i.revealLedger.note(e,s,h),!r())return;let f=bt(n,s,h,t.fields,r);if(!r())return;let p=d?Me(s,f,t.fields,e.locale):void 0,m=i.lastAppliedIdentity.get(s.element);if(!e.forceRender&&n.skipUnchanged&&void 0!==p&&m===p&&!e.invalidated.has(o)){i.skippedUnchangedCount+=1;continue}let g={target:s,value:f,allFields:t.fields,revision:e.revision,data:t,valueIdentity:p};n.scheduler.schedule(g),c+=1}}(function(e,t,n,i){let{cache:r}=e;if(0===r.fieldCount||!1!==i&&!function(e,t){for(let n of e.values())if(U(n.owner,t))return!0;return!1}(r,i))return;let l=B(r,n,i);for(let[i,r]of Object.entries(t)){if(ti.has(i))continue;if(Oe(r)){Ee(e,l,i,n);continue}if(!Pe(r)||l(i))continue;let t=W(i,n);for(let[i,o]of Object.entries(r))!Oe(o)||ti.has(i)||Ee(e,l,`${t}.${i}`,n)}})({cache:n.cache,warned:i.warnedOrphanFields,warn:n.warn},t.fields,e.locale,l),null!==u&&u.boundaries.length>0&&(e.pendingFragments=u.boundaries.length,this.strategies.runFragments(e,t,u)),0===c&&0===e.pendingFragments&&(i.complete(e),this.revealPending(e))}restoreGuesses(e,t){let{deps:n,state:i}=this;if(\\\"off\\\"!==n.autoBind&&null!==i.autoBindGuesses){let r=this.ownerKeysForUpdate(e,t.fields);!function(e,t,n,i,r){let l=t.autoBindGuesses,o=$e(e.root);if(null===l||0===l.fields.size||null===o)return 0;let a=new Map(l.values);for(let[e,t]of ye(n,i)){if(null===t||!l.fields.has(t.field))continue;let n=a.get(e);void 0===n?a.set(e,t):n?.field!==t.field&&a.set(e,null)}Re(e,Ce(o,a),r,\\\"after a route refresh\\\").length}(n,i,t.fields,e.locale,r)}}ownerKeysForUpdate(e,t){let{deps:n,state:i}=this;if(!n.scopeBindingsByOwner)return!1;let{message:r}=e,l=function(e){if(L(e.globalSlug))return[O(e.globalSlug)];if(!L(e.collectionSlug))return null;let t=P(e.collectionSlug);return L(e.documentId)?[t,P(e.collectionSlug,e.documentId)]:[t]}({globalSlug:\\\"string\\\"==typeof r.globalSlug?r.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof r.collectionSlug?r.collectionSlug:void 0,documentId:I(t)});return null===l&&!i.warnedUnattributableMessage&&(i.warnedUnattributableMessage=!0,n.warn(\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),l}onFlush(e){let{deps:t,state:n}=this;n.lastFlush=e,e.deferred>0&&!n.warnedVisibilityGate&&(n.warnedVisibilityGate=!0,t.warn(`[live-preview] LP0301: visibility gate held ${String(e.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`));let{revision:i,data:r}=e;if(void 0===i)return;let l=n.activeUpdate;if(null===l||!n.isCurrent(l)||!g(l.revision,i))return;0===l.pendingFragments&&n.complete(l);let o=()=>n.isCurrent(l)&&g(l.revision,i);if(this.revealPending(l),!o())return;let a=n.unfaithfulPatches;a.length>0&&(n.unfaithfulPatches=[],void 0!==r&&this.strategies.escalateUnfaithful(l,r,a),!o())||0===e.applied||void 0===r||(t.a11y?.announceUpdate(e.applied),o()&&(function(e,t){for(let n of e)n.dispatchEvent(new CustomEvent(\\\"payload-live-preview:update\\\",{detail:t,bubbles:!1}));e.length}(t.cache.islands,{fields:r.fields,revision:i.revision,receivedAt:l.receivedAt,locale:l.locale}),o()&&0!==t.emitter.listenerCount(\\\"afterUpdate\\\")&&t.emitter.emitWhile(\\\"afterUpdate\\\",{data:r,updatedCount:e.applied,durationMs:e.durationMs,revision:i.revision,receivedAt:l.receivedAt,source:\\\"patch\\\"},o)))}revealPending(e){let t=this.state.revealLedger.commit(e);if(void 0!==t)try{this.revealBinding(t)}catch(e){this.deps.log(\\\"reveal\\\",e)}}revealField(e){let t=this.deps.cache.get(e)?.[0];return void 0===t?\\\"no-element\\\":this.revealBinding(t)}revealBinding(e){let{element:t}=e,n=t.ownerDocument.defaultView;if(null===n)return\\\"no-element\\\";let i=`${e.owner??\\\"\\\"} ${e.fieldName}`;return this.state.revealer.reveal(i,t,n)}},zr=class{constructor(e,t){gn(this,\\\"apply\\\");gn(this,\\\"debounceMs\\\");gn(this,\\\"maxWaitMs\\\");gn(this,\\\"isVisible\\\");gn(this,\\\"gateThresholdValue\\\");gn(this,\\\"gateDisabled\\\");gn(this,\\\"getCacheSize\\\");gn(this,\\\"onFlush\\\");gn(this,\\\"scheduleFrame\\\");gn(this,\\\"cancelFrame\\\");gn(this,\\\"pending\\\",new Map);gn(this,\\\"replay\\\",new Map);gn(this,\\\"activeFlushes\\\",new Set);gn(this,\\\"debounceTimer\\\",null);gn(this,\\\"debounceToken\\\",0);gn(this,\\\"deadlineTimer\\\",null);gn(this,\\\"frameHandle\\\",null);gn(this,\\\"frameToken\\\",0);gn(this,\\\"windowUntil\\\",0);gn(this,\\\"activeRevision\\\",null);gn(this,\\\"activeRevisionCancelled\\\",!1);this.apply=e,this.debounceMs=t.debounceMs??50,this.maxWaitMs=t.maxWaitMs??4*this.debounceMs,this.isVisible=t.isVisible,this.gateThresholdValue=t.visibilityGateThreshold??50,this.gateDisabled=t.disableVisibilityGate??!1,this.getCacheSize=t.getCacheSize,this.onFlush=t.onFlush,this.scheduleFrame=t.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>{e(performance.now())},0)),this.cancelFrame=t.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):e=>{clearTimeout(e)})}schedule(e){if(void 0!==e.revision&&(this.activeRevisionCancelled||null===this.activeRevision||!g(e.revision,this.activeRevision)))return;let t=this.pending.get(e.target.element);t?(t.value=e.value,t.allFields=e.allFields,t.revision=e.revision,t.data=e.data,t.valueIdentity=e.valueIdentity):this.pending.set(e.target.element,{target:e.target,value:e.value,allFields:e.allFields,revision:e.revision,data:e.data,valueIdentity:e.valueIdentity}),this.armDebounce()}acceptRevision(e){null!==this.activeRevision&&g(e,this.activeRevision)||null!==this.activeRevision&&function(e,t){return e.generation!==t.generation?e.generation-t.generation:e.revision-t.revision}(e,this.activeRevision)<0||(this.cancelScheduledWork(),this.clearWork(),this.activeRevision=e,this.activeRevisionCancelled=!1)}cancelRevision(e){null===this.activeRevision||!g(e,this.activeRevision)||(this.cancelScheduledWork(),this.clearWork(),this.activeRevisionCancelled=!0)}flushNow(){return this.cancelScheduledWork(),this.flush()}notifyVisible(e){let t=this.replay.get(e);if(!t||(this.replay.delete(e),!this.isCurrent(t)))return;let n=performance.now(),i=this.didApply(t)?1:0;this.onFlush?.(this.statsFor(t,i,0,performance.now()-n,1===i?[t.target.fieldName]:[]))}retarget(e){this.retargetBuffer(this.pending,e),this.retargetBuffer(this.replay,e);for(let t of this.activeFlushes)this.retargetBuffer(t,e)}forget(e){this.pending.delete(e),this.replay.delete(e);for(let t of this.activeFlushes)t.delete(e)}destroy(){this.cancelScheduledWork(),this.clearWork(),this.activeRevision=null,this.activeRevisionCancelled=!1,this.windowUntil=0}get pendingCount(){return this.pending.size}get replayCount(){return this.replay.size}get gateThreshold(){return this.gateThresholdValue}get gateActive(){return!this.gateDisabled&&this.getCacheSize()>this.gateThresholdValue}armDebounce(){let e=Date.now(),t=e>=this.windowUntil;if(this.windowUntil=e+this.debounceMs,t){this.requestFrame();return}let n=this.debounceToken+=1,i=this.debounceTimer;if(this.debounceTimer=null,null!==i&&clearTimeout(i),this.debounceToken!==n)return;let r=setTimeout(()=>{this.debounceToken===n&&(this.debounceTimer=null,this.pending.size>0&&this.requestFrame())},this.debounceMs);this.debounceToken===n&&(this.debounceTimer=r),null===this.deadlineTimer&&this.maxWaitMs>this.debounceMs&&(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.pending.size>0&&this.requestFrame()},this.maxWaitMs))}requestFrame(){let e=this.frameToken+=1,t=this.frameHandle;if(this.frameHandle=null,null!==t&&this.cancelFrame(t),this.frameToken!==e)return;let n=!1,i=this.scheduleFrame(()=>{this.frameToken===e&&(n=!0,this.frameHandle=null,this.flush())});!n&&this.frameToken===e&&(this.frameHandle=i)}flush(){let e=performance.now();this.clearDeadline();let t=this.gateActive,n=this.pending;this.pending=new Map;let i,r=0,l=[],o=0;this.activeFlushes.add(n);try{for(let e of n.values()){if(!this.isCurrent(e))continue;let n=!t||this.isVisible(e.target.element);if(this.isCurrent(e)){if(i??(i=e),!n){this.replay.set(e.target.element,e),o+=1;continue}this.replay.delete(e.target.element),this.didApply(e)&&(r+=1,l.push(e.target.fieldName))}}}finally{this.activeFlushes.delete(n)}let a=this.statsFor(i,r,o,performance.now()-e,l);return this.onFlush?.(a),a}isCurrent(e){return void 0===e.revision||!this.activeRevisionCancelled&&null!==this.activeRevision&&g(e.revision,this.activeRevision)}didApply(e){return!1!==this.apply(e)||!function(e){return Qn.has(e)}(this.apply)}retargetBuffer(e,t){let n=e.get(t.element);if(void 0!==n){if(n.target.fieldName!==t.fieldName||n.target.locale!==t.locale){e.delete(t.element);return}n.target=t}}clearWork(){this.pending.clear(),this.replay.clear();for(let e of this.activeFlushes)e.clear()}statsFor(e,t,n,i,r){return{applied:t,appliedFields:r,deferred:n,durationMs:i,...void 0!==e?.revision?{revision:e.revision}:{},...void 0!==e?.data?{data:e.data}:{}}}clearDeadline(){null!==this.deadlineTimer&&(clearTimeout(this.deadlineTimer),this.deadlineTimer=null)}cancelScheduledWork(){let e=this.debounceTimer,t=this.frameHandle;this.debounceToken+=1,this.frameToken+=1,this.debounceTimer=null,this.frameHandle=null,this.clearDeadline(),null!==e&&clearTimeout(e),null!==t&&this.cancelFrame(t)}},Vr=[0,500,1e3,2e3],Hr=class{constructor(e){gn(this,\\\"deps\\\");gn(this,\\\"state\\\",new di);gn(this,\\\"pipeline\\\");gn(this,\\\"writer\\\");gn(this,\\\"rootSentinel\\\",null);gn(this,\\\"observedRoot\\\",null);let{emitter:r,renderers:l}=e,o=void 0===e.log?n:t(e.log),a=void 0===e.warn?kn:t(e.warn),s=e.root??(typ\",\"eof document<\\\"u\\\"?document:void 0);if(void 0===s)throw new Error(\\\"LivePreviewRuntime: no document; pass options.root\\\");let u=new Ii({filter:e=>!function(e){let t=e;for(;null!==t;){if(Q(t))return!0;t=t.parentElement}return!1}(e)}),d=new Vi({onStructuralChange:()=>{this.rebuildCache()},onVisibilityChange:(e,t)=>{t&&c.notifyVisible(e)}},void 0!==e.intersectionRootMargin?{intersectionRootMargin:e.intersectionRootMargin}:{}),c=new zr(N(e=>this.writer.apply(e)),{...void 0!==e.debounceMs?{debounceMs:e.debounceMs}:{},...void 0!==e.disableVisibilityGate?{disableVisibilityGate:e.disableVisibilityGate}:{},...void 0!==e.visibilityGateThreshold?{visibilityGateThreshold:e.visibilityGateThreshold}:{},isVisible:e=>d.isVisible(e),getCacheSize:()=>u.elementCount,onFlush:e=>{this.pipeline.onFlush(e)}}),h=new Bn(e.originMatcher,{onUpdate:(e,t,n)=>{this.pipeline.handleUpdate(e,t,n)},onDocumentEvent:()=>{this.state.protocol.observe([\\\"document-events\\\"],o),r.emit(\\\"documentSave\\\",{timestamp:Date.now()})},onFocusField:e=>{this.deps.revealEditedField&&this.pipeline.revealField(e)},onInvalid:(e,t)=>{if(\\\"token\\\"===e){let e=new Error(`Preview token rejected (origin: ${t})`);r.emit(\\\"error\\\",{error:e,context:\\\"token\\\",code:\\\"LP0502\\\"})}(\\\"shape\\\"===e||\\\"type\\\"===e)&&!this.state.warnedProtocolShape&&(this.state.warnedProtocolShape=!0,a(`[live-preview] LP0503: ${t} posted a message this runtime does not recognise (${\\\"type\\\"===e?\\\"unknown message type\\\":\\\"unexpected shape\\\"}); it was ignored. A newer Payload or a custom sender: check that the versions match.`)),\\\"source\\\"===e&&!this.state.warnedForeignSource&&(this.state.warnedForeignSource=!0,a(`[live-preview] LP0501: a message from ${t} was ignored because it did not come from the window that framed or opened this page. \\\\`eventSourcePolicy\\\\` is 'parent-or-opener' by default since 2.0, where 1.x accepted any window on a trusted origin. Set \\\\`eventSourcePolicy: 'any'\\\\` if the admin posts from elsewhere.`)),o(\\\"LP0501 message rejected:\\\",e,t)},...void 0!==e.validateToken?{validateToken:e.validateToken}:{},...void 0!==e.eventSourcePolicy?{sourcePolicy:e.eventSourcePolicy}:{}}),f=e.dataMerge;this.deps={emitter:r,cache:u,observers:d,scheduler:c,bus:h,connection:new Qi,heartbeat:new Xi({...void 0!==e.heartbeatMs?{timeoutMs:e.heartbeatMs}:{},onTimeout:()=>{this.onHeartbeatTimeout()}}),renderers:l,resolveRenderer:e.resolveRenderer??(e=>l[e]),transformValue:e.transformValue,renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,root:s,readyTargets:\\\"function\\\"==typeof e.readyTargets?e.readyTargets:(e=>()=>e)(e.readyTargets),sendReady:e.sendReady??y,onHeartbeatTimeout:e.onHeartbeatTimeout,log:o,warn:a,a11y:v(e),merger:void 0===f?null:new ji({serverURL:f.serverURL,...void 0!==f.apiRoute?{apiRoute:f.apiRoute}:{},...void 0!==f.depth?{depth:f.depth}:{},...void 0!==f.fetchFn?{fetchFn:f.fetchFn}:{},log:o}),mergeWindowMs:e.debounceMs??50,scopeBindingsByOwner:!0===e.scopeBindingsByOwner,lockedOrigin:e.lockedOrigin??(()=>{}),skipUnchanged:!0===e.skipUnchanged,dependencies:e.dependencies??{},strategies:e.strategies??{},revealEditedField:!0===e.revealEditedField,onUnfaithfulPatch:i(e),autoBind:e.autoBind??\\\"off\\\",hydration:e.hydration},this.writer=new ci(this.deps,this.state),this.pipeline=new Dr(this.deps,this.state,()=>{this.rebuildCache()})}start(){let{state:e}=this;if(e.isRunning())return!1;e.started=!0,e.suspended=!1;try{return function(e){\\\"react\\\"===e.hydration?ae():\\\"vue\\\"===e.hydration&&fe();let{root:t}=e;if(!function(e){return 9===e.nodeType}(t)||\\\"loading\\\"!==t.readyState){pe(e);return}let n=()=>{e.isRunning()&&e.later(()=>{pe(e)})};t.addEventListener(\\\"DOMContentLoaded\\\",n,{once:!0}),e.defer(()=>{t.removeEventListener(\\\"DOMContentLoaded\\\",n)})}(this.startupHost()),!0}catch(e){throw this.rollbackFailedStart(),e}}startupHost(){let{state:e,deps:t}=this;return{root:t.root,hydration:t.hydration,isRunning:()=>e.isRunning(),defer:t=>{e.deferredStart=t},later:t=>{e.deferredStart=null;try{t()}catch(e){this.rollbackFailedStart(),this.reportError(e,\\\"startup\\\",\\\"LP0605\\\")}},hydrated:t=>{e.hydration=t},warn:t.warn,startNow:()=>{this.startNow()}}}startNow(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=wt(t.root)?St(t.root):t.root;if(null===n)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(t.observers.start(n),this.observedRoot=n,this.watchRootReplacement(),this.buildCacheAndObserve(),e.isRunning()&&(t.bus.attach(),t.emitter.emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>e.isRunning()),e.isRunning()))for(let n of Vr){if(!e.isRunning())return;0===n?t.sendReady(t.readyTargets()):e.readyTimers.push(setTimeout(()=>{e.isRunning()&&this.sendReadyAfterStart()},n))}}suspend(){if(!this.state.isRunning())return!1;let e=this.release();return this.state.suspended=!0,e&&this.deps.emitter.emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0}destroy(){let{state:e,deps:t}=this;if(!e.isRunning()&&!e.suspended)return;let n=!!e.isRunning()&&this.release();e.suspended=!1,n&&t.emitter.emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),t.a11y?.detach(),t.emitter.emit(\\\"destroy\\\",{timestamp:Date.now()})}release(){let{state:e,deps:t}=this;e.activeUpdate=null,e.started=!1;let n=e.deferredStart;e.deferredStart=null,null!==n&&this.runCleanup(n);for(let t of e.readyTimers)this.runCleanup(()=>{clearTimeout(t)});return e.readyTimers.length=0,this.runCleanup(()=>{t.heartbeat.stop()}),this.runCleanup(()=>{t.bus.detach()}),e.abortStrategies(),this.runCleanup(()=>{this.rootSentinel?.disconnect(),this.rootSentinel=null,this.observedRoot=null}),this.runCleanup(()=>{t.observers.stop()}),this.runCleanup(()=>{t.scheduler.destroy()}),this.runCleanup(()=>{t.merger?.destroy(),e.merges.destroy()}),t.cache.clear(),t.connection.markDisconnected()}rollbackFailedStart(){this.release(),this.runCleanup(()=>{this.deps.a11y?.detach()})}runCleanup(e){try{e()}catch(e){this.deps.log(\\\"cleanup failed:\\\",e)}}refreshCache(){this.state.isRunning()&&(this.state.revealer.reset(),this.followReplacedRoot()||this.rebuildCache())}watchRootReplacement(){let{root:e}=this.deps;!wt(e)||typeof MutationObserver>\\\"u\\\"||(this.rootSentinel?.disconnect(),this.rootSentinel=new MutationObserver(()=>{this.followReplacedRoot()}),this.rootSentinel.observe(e.documentElement,{childList:!0}))}followReplacedRoot(){let{root:e}=this.deps;if(!this.state.isRunning()||!wt(e))return!1;let t=St(e);return null!==t&&t!==this.observedRoot&&(this.observedRoot=t,this.deps.observers.start(t),this.rebuildCache(),!0)}get status(){return this.deps.connection.status}get cache(){return this.deps.cache}get updateCount(){return this.state.updateCount}get protocol(){return this.state.protocol.negotiation}inspect(){return function(e,t){let{cache:n,scheduler:i}=e,r=t.protocol.negotiation,l=t.activeUpdate,o=t.lastFlush,a=[],s=new Set,u=[];for(let[e,t]of n.entries()){a.push(e);for(let n of t)void 0!==n.owner&&s.add(n.owner),void 0!==n.guessed&&u.push({field:e,matched:n.guessed,attribute:n.targetAttribute??(\\\"IMG\\\"===n.element.tagName?\\\"src\\\":void 0)})}return{version:_i,started:t.started,status:e.connection.status,origins:{trusted:[...e.readyTargets()],locked:e.lockedOrigin()},protocol:{ours:r.ours,theirs:r.theirs,negotiated:r.negotiated,capabilities:[...r.capabilities].sort(),observed:[...r.observed].sort(),profile:re(r.observed).name},revisions:{accepted:t.updateCount,superseded:t.supersededCount,completed:t.completedCount,skippedUnchanged:t.skippedUnchangedCount,active:null===l?void 0:l.revision.revision},bindings:{elements:n.elementCount,fields:n.fieldCount,fieldNames:a.sort(),absentFields:[...t.absentFields].sort(),orphanFields:[...t.warnedOrphanFields].sort(),ownerScoped:e.scopeBindingsByOwner,owners:[...s].sort(),guessed:u.sort((e,t)=>e.field.localeCompare(t.field)),autoBind:{mode:e.autoBind,searchMs:t.autoBindSearchMs}},route:{handler:void 0!==e.strategies.route,...t.routeStats},fidelity:{mode:e.onUnfaithfulPatch,unfaithful:t.unfaithfulCount,escalated:t.escalatedCount,fields:[...t.unfaithfulFields].sort()},hydration:{mode:e.hydration??\\\"off\\\",state:t.hydration},fragments:{handler:void 0!==e.strategies.fragment,inFlight:l?.pendingFragments??0,...t.fragmentStats},scheduler:{pending:i.pendingCount,deferred:i.replayCount,visibilityGateThreshold:i.gateThreshold,visibilityGateActive:i.gateActive,lastFlush:null===o?void 0:{applied:o.applied,appliedFields:o.appliedFields,deferred:o.deferred,durationMs:o.durationMs}},plugins:[],renderers:Object.keys(e.renderers).sort()}}(this.deps,this.state)}buildCacheAndObserve(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=t.cache.buildFromRoot(t.root);if(t.log(\\\"cache\\\",n),e.isRunning()&&(t.emitter.emitWhile(\\\"cacheRefresh\\\",n,()=>e.isRunning()),e.isRunning()))for(let n of t.cache.values()){if(!e.isRunning())return;t.observers.observeElement(n.element)}}rebuildCache(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=new Map;for(let e of t.cache.values())n.set(e.element,e),t.observers.unobserveElement(e.element);if(this.buildCacheAndObserve(),e.isRunning()){for(let e of t.cache.values())n.get(e.element)?.fieldName===e.fieldName?t.scheduler.retarget(e):t.scheduler.forget(e.element),n.delete(e.element);for(let e of n.values())t.scheduler.forget(e.element)}}onHeartbeatTimeout(){let{state:e,deps:t}=this;if(!e.isRunning())return;t.bus.advanceGeneration();let n=e.activeUpdate;e.activeUpdate=null,null!==n&&t.scheduler.cancelRevision(n.revision),t.merger?.destroy(),e.merges.destroy();let i=t.connection.markDisconnected();try{t.onHeartbeatTimeout?.()}catch(e){t.log(\\\"heartbeat:\\\",e)}e.isRunning()&&(i&&this.isIdleDisconnected()&&(t.a11y?.announceDisconnected(),t.emitter.emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>this.isIdleDisconnected()),!e.isRunning()||(this.isIdleDisconnected()&&t.log(\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!e.isRunning()))||this.sendReadyAfterStart())}sendReadyAfterStart(){try{this.deps.sendReady(this.deps.readyTargets())}catch(e){this.reportError(e,\\\"ready\\\",\\\"LP0606\\\")}}reportError(e,t,n){let i=e instanceof Error?e:new Error(String(e));this.deps.emitter.emit(\\\"error\\\",{error:i,context:t,code:n})}isIdleDisconnected(){return this.state.isRunning()&&\\\"disconnected\\\"===this.deps.connection.status&&null===this.state.activeUpdate}},Gr=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,qr=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,Kr=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Jr=class{constructor(e={}){bn(this,Xr);let t=new Set;for(let n of e.additionalOrigins??[]){let e=kt(n);void 0!==e&&t.add(e)}let n;if(e.enableReferrerDetection??1){let t=e.referrer??(typ\",\"eof document<\\\"u\\\"?document.referrer:\\\"\\\");if(t.length>0)try{let e=new URL(t).origin;e&&\\\"null\\\"!==e&&(n=e)}catch{}}let i=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??function(){let e=function(){if(!(typ\",\"eof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==e)return\\\"production\\\"!==e;if(typ\",\"eof window<\\\"u\\\"){let e=window.location.hostname;return\\\"localhost\\\"===e||\\\"127.0.0.1\\\"===e}return!1}());wn(this,Xr,[t,n,i,void 0!==n,void 0])}matches(e){return 0!==e.length&&\\\"null\\\"!==e&&(void 0!==yn(this,Xr)[4]?e===yn(this,Xr)[4]:!!(yn(this,Xr)[0].has(e)||0===yn(this,Xr)[0].size&&void 0!==yn(this,Xr)[1]&&e===yn(this,Xr)[1]||yn(this,Xr)[2]&&Gr.test(e)))}lockOrigin(e){return!!this.matches(e)&&(yn(this,Xr)[4]=e,!0)}unlockOrigin(){let e=yn(this,Xr)[4];return yn(this,Xr)[4]=void 0,e}get lockedOrigin(){return yn(this,Xr)[4]}enumerate(){if(void 0!==yn(this,Xr)[4])return[yn(this,Xr)[4]];let e=new Set(yn(this,Xr)[0]);if(0===yn(this,Xr)[0].size&&void 0!==yn(this,Xr)[1]&&e.add(yn(this,Xr)[1]),yn(this,Xr)[2])for(let t of Kr)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return yn(this,Xr)[3]}get isProductionUnconfigured(){return!(!Tt()||yn(this,Xr)[0].size>0||yn(this,Xr)[2]||void 0!==yn(this,Xr)[1])}get isReferrerOnlyTrust(){return!(yn(this,Xr)[0].size>0||yn(this,Xr)[2])&&void 0!==yn(this,Xr)[1]}},Xr=new WeakMap,Qr={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Zr=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Yr=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),el=' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"',tl=(e,t)=>{let n=t.renderChildren(e.children??[]),i=Ft(e.fields),r=function(e,t){if(\\\"internal\\\"===t?.linkType)return function(e){let t=Ft(Ft(e)?.value),n=t?.url;if(\\\"string\\\"==typeof n&&n.length>0)return n;let i=t?.slug;return\\\"string\\\"==typeof i&&i.length>0?`/${i}`:void 0}(t.doc);let n=t?.url??e.url;return\\\"string\\\"==typeof n&&n.length>0?n:void 0}(e,i);if(void 0===r||!$(r))return n;let l=\\\"string\\\"==typeof e.title?` title=\\\"${Ke(e.title)}\\\"`:\\\"\\\";return`<a href=\\\"${Je(r)}\\\"${function(e,t,n){if(!0===t?.newTab||R(n))return el;let i=\\\"string\\\"==typeof e.target?e.target:\\\"\\\";return\\\"\\\"===i?\\\"\\\":\\\"_blank\\\"===i?el:` target=\\\"${Ke(i)}\\\"`}(e,i,r)}${l}>${n}</a>`},nl=new Map,il=\\\".lp-block:empty,.lp-inline-block:empty\\\",rl={text:e=>{let t=Ke(\\\"string\\\"==typeof e.text?e.text:\\\"\\\"),n=\\\"number\\\"==typeof e.format?e.format:0;return!!(16&n)&&(t=`<code>${t}</code>`),!!(1&n)&&(t=`<strong>${t}</strong>`),!!(2&n)&&(t=`<em>${t}</em>`),!!(8&n)&&(t=`<u>${t}</u>`),!!(4&n)&&(t=`<s>${t}</s>`),!!(32&n)&&(t=`<sub>${t}</sub>`),!!(64&n)&&(t=`<sup>${t}</sup>`),!!(128&n)&&(t=`<mark>${t}</mark>`),t},paragraph:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<p${$t(e)}${Rt(e)}>${n}</p>`},heading:(e,t)=>{let n=\\\"string\\\"==typeof e.tag?e.tag.toLowerCase():\\\"h2\\\",i=Yr.has(n)?n:\\\"h2\\\",r=t.renderChildren(e.children??[]);return`<${i}${$t(e)}${Rt(e)}>${r}</${i}>`},list:(e,t)=>{let n=\\\"string\\\"==typeof e.listType?e.listType:\\\"bullet\\\",i=\\\"number\\\"===n?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===n&&\\\"number\\\"==typeof e.start&&e.start>1?` start=\\\"${String(e.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===n?' role=\\\"list\\\"':\\\"\\\",o=t.renderChildren(e.children??[]);return`<${i}${$t(e)}${Rt(e)}${r}${l}>${o}</${i}>`},listitem:(e,t)=>{let n=t.renderChildren(e.children??[]);if(\\\"boolean\\\"==typeof e.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${e.checked?\\\"true\\\":\\\"false\\\"}\\\"${Rt(e)}>${n}</li>`;let i=\\\"number\\\"==typeof e.value?` value=\\\"${Ke(String(e.value))}\\\"`:\\\"\\\";return`<li${$t(e)}${Rt(e)}${i}>${n}</li>`},link:tl,autolink:tl,quote:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<blockquote${$t(e)}${Rt(e)}>${n}</blockquote>`},code:e=>{let t=xt(\\\"string\\\"==typeof e.language?e.language:\\\"\\\");return`<pre><code${\\\"\\\"===t?\\\"\\\":` class=\\\"language-${t}\\\"`}>${Ke(Ot(e))}</code></pre>`},\\\"code-highlight\\\":e=>{let t=\\\"string\\\"==typeof e.text?e.text:\\\"\\\";return`<span${\\\"string\\\"==typeof e.highlightType?` class=\\\"token-${xt(e.highlightType)}\\\"`:\\\"\\\"}>${Ke(t)}</span>`},linebreak:()=>\\\"<br>\\\",horizontalrule:()=>\\\"<hr>\\\",tab:()=>\\\"\\\\t\\\",upload:e=>{let t=Nt(e.value);if(void 0===t)return\\\"\\\";let n=t.url;if(\\\"string\\\"!=typeof n||!$(n))return\\\"\\\";let i=\\\"string\\\"==typeof t.mimeType?t.mimeType:\\\"\\\";return i.startsWith(\\\"video/\\\")?function(e,t){return`<video controls${Pt(e)}><source src=\\\"${Je(t)}\\\"${Lt(e)}></video>`}(t,n):i.startsWith(\\\"audio/\\\")?function(e,t){return`<audio controls><source src=\\\"${Je(t)}\\\"${Lt(e)}></audio>`}(t,n):\\\"\\\"===i||i.startsWith(\\\"image/\\\")?function(e,t){let n=\\\"string\\\"==typeof e.alt?Ke(e.alt):\\\"\\\";return`<img src=\\\"${Je(t)}\\\" alt=\\\"${n}\\\"${Pt(e)} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(t,n):function(e,t){let n=\\\"string\\\"==typeof e.filename?Ke(e.filename):Ke(t);return`<a href=\\\"${Je(t)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${n}</a>`}(t,n)},relationship:e=>{let t=\\\"string\\\"==typeof e.relationTo?e.relationTo:\\\"\\\",n=Ft(e.value),i=Ke((n&&Et(n))??`#${t}`),r=xt(t),l=\\\"\\\"===r?' class=\\\"lp-relation\\\"':` class=\\\"lp-relation lp-relation--${r}\\\"`,o=n?.url;return\\\"string\\\"==typeof o&&$(o)?`<a href=\\\"${Je(o)}\\\"${l}>${i}</a>`:`<span${l}>${i}</span>`},block:(e,t)=>It(e,t,\\\"div\\\",\\\"lp-block\\\"),inlineBlock:(e,t)=>It(e,t,\\\"span\\\",\\\"lp-inline-block\\\"),table:(e,t)=>`<table${$t(e)}><tbody>${t.renderChildren(e.children??[])}</tbody></table>`,tablerow:(e,t)=>`<tr>${t.renderChildren(e.children??[])}</tr>`,tablecell:(e,t)=>{let n=\\\"number\\\"==typeof e.headerState?e.headerState:0,i=3&n?\\\"th\\\":\\\"td\\\";return`<${i}${1===n?' scope=\\\"col\\\"':2===n?' scope=\\\"row\\\"':\\\"\\\"}${jt(\\\"colspan\\\",e.colSpan)}${jt(\\\"rowspan\\\",e.rowSpan)}>${t.renderChildren(e.children??[])}</${i}>`}},ll=new Map,ol=!1,al=\\\"data-payload-text\\\",sl=new Set,ul=new Set,dl=new Set([\\\"DIV\\\",\\\"SECTION\\\",\\\"ARTICLE\\\"]),cl={name:\\\"richText\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){i.textContent=\\\"\\\";return}let r=n.sanitizerPolicy;if(void 0!==n.renderRichText){let l=n.renderRichText(t,{fieldName:e.fieldName,element:i,locale:n.locale});i.innerHTML=Le(ze(l,r));return}if(_t(t)){let l=new Map,o=zt(i,ze(function(e,t={}){if(!_t(e))return\\\"\\\";let n=function(e){let t={renderChildren:e=>{let n=\\\"\\\";for(let i of e)n+=Wt(i,t);return n},resolveAlignment:At,resolveIndent:Ct,onUnrenderedBlock:e};return t}(t.onUnrenderedBlock).renderChildren(e.root.children);return!1===t.sanitize?n:void 0!==Ve()?function(e){return ze(e,void 0,void 0)}(n):(function(){if(!ol){ol=!0;try{console.warn(\\\"[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; call setSanitizerDocument() (linkedom/jsdom) for server rendering, see docs/security.md \\\\xa73.\\\")}catch{}}}(),n)}(t,{sanitize:!1,onUnrenderedBlock:(e,t)=>{l.set(t,e)}}),r));for(let[t,i]of o){let r=l.get(t);void 0!==r&&Ht(e,n,r,i)}return}if(\\\"string\\\"!=typeof t)return!1;i.innerHTML=Le(ze(t,r))})},hl={name:\\\"html\\\",render(e,t,n){if(tt(t)){e.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof t?t:et(t);e.element.innerHTML=Le(ze(i,n.sanitizerPolicy))}},fl=new WeakSet,pl=qt(\\\"url\\\"),ml=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,gl=qt(\\\"email\\\",function(e){let t=e.trim();return ml.test(t)||!t.includes(\\\"@\\\")?t:`mailto:${t}`}),vl=[\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\"],yl={name:\\\"image\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){Qt(i);return}let r=void 0!==e.locale,{media:l,candidate:o}=function(e,t,n,i){let r=void 0!==e.srcField&&e.srcField.length>0?Fe(n.allFields,e.srcField,n.locale,i):t,l=Nt(r);return{media:l,candidate:void 0===l?r:l.url}}(e,t,n,r),a=Gt(i,e.fieldName,o);if(\\\"none\\\"===a.kind)return!1;if(\\\"unsafe\\\"!==a.kind){if(\\\"IMG\\\"===i.tagName){let t=i;Jt(t,a.url,l);let o=function(e,t,n,i,r){if(void 0!==t&&t.length>0){let e=Fe(n,t,i,r);return\\\"string\\\"==typeof e?e:void 0}return e?.alt}(l,e.altField,n.allFields,n.locale,r);void 0!==o&&(t.alt=o);return}i.style.backgroundImage=`url('${function(e){return e.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(a.url)}')`}else Qt(i)})},bl={name:\\\"upload\\\",render:N((e,t)=>{let n=e.element;if(tt(t)){Zt(n);return}let i=Nt(t);if(void 0===i)return!1;let r=Gt(n,e.fieldName,i.url);if(\\\"none\\\"===r.kind)return!1;if(\\\"unsafe\\\"===r.kind){Zt(n);return}let l=r.url;if(\\\"IMG\\\"===n.tagName){let e=n;Jt(e,l,i),void 0!==i.alt&&(e.alt=i.alt);return}if(\\\"A\\\"===n.tagName){n.setAttribute(\\\"href\\\",l),n.textContent=i.filename??l;return}let o=Ke(i.filename??l);n.innerHTML=Le(`<a href=\\\"${Je(l)}\\\">${o}</a>`)})},wl={name:\\\"relationship\\\",render(e,t){let n=e.element;if(tt(t))n.removeAttribute(\\\"href\\\"),n.textContent=\\\"\\\";else{if(\\\"A\\\"===n.tagName&&!Array.isArray(t)){let i=Gt(n,e.fieldName,Ft(t)?.url);\\\"safe\\\"===i.kind?n.setAttribute(\\\"href\\\",i.url):\\\"unsafe\\\"===i.kind&&n.removeAttribute(\\\"href\\\")}n.textContent=Array.isArray(t)?t.map(Yt).join(\\\", \\\"):Yt(t)}}},Sl={name:\\\"select\\\",render(e,t,n){let i=e.element,r=tt(t)?[]:function(e){return Array.isArray(e)?e.map(et):[et(e)]}(t);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let e=i;e.checked=r.includes(e.value);return}i.textContent=r.map(e=>function(e,t){let n=t.schema?.options;if(!Array.isArray(n))return e;for(let t of n){let n=Ft(t);if(void 0!==n&&et(n.value)===e)return\\\"string\\\"==typeof n.label?n.label:e}return e}(e,n)).join(\\\", \\\")}else!function(e,t){if(e.multiple)for(let n of Array.from(e.options))n.selected=t.includes(n.value);else e.value=t[0]??\\\"\\\"}(i,r)}},Tl=new Set([\\\"\\\",\\\"false\\\",\\\"0\\\",\\\"off\\\",\\\"no\\\"]),kl={name:\\\"checkbox\\\",render(e,t){let n=e.element,i=function(e){return\\\"boolean\\\"==typeof e?e:\\\"string\\\"==typeof e?!Tl.has(e.trim().toLowerCase()):\\\"number\\\"==typeof e?0!==e:null!=e}(t);\\\"INPUT\\\"!==n.tagName||\\\"checkbox\\\"!==n.type?n.hasAttribute(\\\"aria-checked\\\")?n.setAttribute(\\\"aria-checked\\\",i?\\\"true\\\":\\\"false\\\"):n.textContent=i?\\\"true\\\":\\\"false\\\":n.checked=i}},Al=new Map,Cl=new Map,$l=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Rl=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Fl=/^[A-Za-z]{3}$/u,Nl=/^[0-4]$/u,xl=new WeakSet,Ml={name:\\\"date\\\",render(e,t,n){let i=e.element;if(tt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":(i.removeAttribute(\\\"datetime\\\"),i.textContent=\\\"\\\");return}let r=\\\"number\\\"==typeof t?t:et(t),l=new Date(r),o=!Number.isNaN(l.getTime()),a=String(r);\\\"INPUT\\\"!==i.tagName?(\\\"TIME\\\"===i.tagName&&i.setAttribute(\\\"datetime\\\",o?l.toISOString():a),i.textContent=o?function(e,t,n){let i=t.locale??n.locale??s(),r=ln(\\\"date\\\",t.format,t.element,t.fieldName)??El;try{return function(e,t){let n=en(e,t);return nt(Cl,n)??it(Cl,n,new Intl.DateTimeFormat(e,t),64)}(i,r).format(e)}catch{return e.toISOString()}}(l,e,n):a):i.value=o?function(e,t){let n=`${String(t.getFullYear()).padStart(4,\\\"0\\\")}-${on(t.getMonth()+1)}-${on(t.getDate())}`,i=`${on(t.getHours())}:${on(t.getMinutes())}`;return\\\"date\\\"===e?n:\\\"datetime-local\\\"===e?`${n}T${i}`:\\\"time\\\"===e?i:t.toISOString()}(i.type,l):a}},El={dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"},Ol={name:\\\"number\\\",render(e,t,n){let i=e.element;if(tt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":i.textContent=\\\"\\\";return}let r=\\\"number\\\"==typeof t?t:Number(et(t));Number.isNaN(r)?i.textContent=et(t):\\\"INPUT\\\"!==i.tagName?i.textContent=function(e,t,n){let i=t.locale??n.locale??s(),r=ln(\\\"number\\\",t.format,t.element,t.fieldName);try{return function(e,t){let n=en(e,t);return nt(Al,n)??it(Al,n,new Intl.NumberFormat(e,t),64)}(i,r).format(e)}catch{return String(e)}}(r,e,n):i.value=String(r)}},Pl={name:\\\"array\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){i.textContent=\\\"\\\";return}if(!Array.isArray(t))return!1;let r=e.arrayTemplate;if(void 0!==r&&r.length>0){let e=function(e,t){let n=Xe(t),i=\\\"\\\";for(let r=0;r<t.length;r+=1)i+=Qe(e,t[r],r,et,n);return i}(r,t),l=n.sanitizerPolicy,o=rt(r),a=Ze(i);i.innerHTML=Le(ze(e,l,o));for(let e of Array.from(i.children))Ye(e,a);return}i.textContent=t.map(et).join(e.arraySeparator??\\\", \\\")})},Ll=new Map;!function(){if(typ\",\"eof window>\\\"u\\\"||!Tt()&&(typ\",\"eof window>\\\"u\\\"||null==window.opener))return;let e=window.__livePreview,t=JSON.stringify(hn());if(void 0!==e&&(void 0===e.configSignature||e.configSignature===t))return e.refresh(),e;let[n=[],r=\\\"\\\",l=\\\"/api\\\",o=1,a=!1,s=50,u=!0,d=0,c=!1,h=50,f=\\\"200px\\\",p=!0,m=!1,g=!1,v=!0,y=\\\"parent-or-opener\\\",b=\\\"strict\\\",w,S=!1,T=!1,k,A,C=\\\"off\\\",$]=hn(),R=function(e){let t=typeof __LIVE_PREVIEW_FRAGMENT__<\\\"u\\\"?__LIVE_PREVIEW_FRAGMENT__:void 0,n=t??(typeof __LIVE_PREVIEW_ROUTE__<\\\"u\\\"?__LIVE_PREVIEW_ROUTE__:void 0);if(void 0===n)return;let i=n.createRouteStrategy();return void 0===t||void 0===e||\\\"\\\"===e?{route:i}:{fragment:t.createFragmentStrategy({endpoint:e}),route:i}}(w),F=new Jr({additionalOrigins:n,enableReferrerDetection:!p,enableLocalhostMatching:!m});F.isProductionUnconfigured?kn(\\\"[live-preview] LP0101: No trusted origin. Pass allowedOrigins to generateInlineScript() (or to the adapter) \\\\u2014 the runtime reads no environment variable in the browser.\\\"):F.isReferrerOnlyTrust&&kn(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let N=new Cn,x=function(){let e=[cl,hl,pl,gl,yl,bl,wl,Sl,{...Sl,name:\\\"radio\\\"},kl,Ml,Ol,Pl,{...Pl,name:\\\"blocks\\\"}];return function(e=[]){let t={};for(let n of e)t[n.name]=n;for(let[e,n]of Ll)t[e]=n;return Object.freeze(t)}([Dt(\\\"text\\\"),Dt(\\\"textarea\\\"),...e,an()])}(),M=new Hr({renderers:x,originMatcher:e=>F.matches(e),lockedOrigin:()=>F.lockedOrigin,readyTargets:()=>F.enumerate(),emitter:N,eventSourcePolicy:y,...\\\"\\\"!==r?{dataMerge:{serverURL:r,apiRoute:l,depth:o}}:{},debounceMs:s,heartbeatMs:d,intersectionRootMargin:f,disableVisibilityGate:c,visibilityGateThreshold:h,enableA11y:u,scopeBindingsByOwner:g,skipUnchanged:v,revealEditedField:S,onUnfaithfulPatch:i({onUnfaithfulPatch:A,onUnboundChange:k}),autoBind:C,...void 0!==$?{hydration:$}:{},sanitizerPolicy:b,...void 0!==R?{strategies:R}:{},onHeartbeatTimeout:()=>{F.unlockOrigin()},...a?{log:(...e)=>{An(\\\"[live-preview]\\\",...e)}}:{}});N.on(\\\"connect\\\",e=>{F.lockOrigin(e.origin)}),M.start(),e?.destroy();let E=function(e,t={}){let n=t.windowTarget??globalThis.window,i=t.documentTarget??globalThis.document,r=t.softNavigationEvents??[],l=()=>{e.suspend()},o=t=>{!0===t.persisted&&e.resume()},a=()=>{e.refreshCache()};n?.addEventListener(\\\"pagehide\\\",l),n?.addEventListener(\\\"pageshow\\\",o);for(let e of r)i?.addEventListener(e,a);let s=!1;return()=>{if(!s){s=!0,n?.removeEventListener(\\\"pagehide\\\",l),n?.removeEventListener(\\\"pageshow\\\",o);for(let e of r)i?.removeEventListener(e,a)}}}({suspend:()=>M.suspend(),resume:()=>M.start(),refreshCache:()=>{M.refreshCache()}}),O=Object.freeze({version:_i,configSignature:t,destroy:()=>{E(),M.destroy();let e=window;e.__livePreview===O&&delete e.__livePreview},refresh:()=>{M.refreshCache()},enumerateOrigins:()=>F.enumerate(),inspect:()=>M.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:O,writable:!1,configurable:!0})}catch(e){throw E(),M.destroy(),e}}()})();\"].join('');\nexport const RUNTIME_CONTENT_HASH = \"3266fb4453ad7b20\";\nexport const RUNTIME_INTEGRITY = \"sha384-EhQyNiwAY4o29ar5O3NijChxkjGh7q7hj/nFNR+0/rzb9glgeL2KkknpjmnL0nFh\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-09-14T11:53:55.000Z\", size: 113345 };\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const FRAGMENT_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_FRAGMENT__=(()=>{var P=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},ne=(e,t,n,o)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let r of Z(t))!ee.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(o=Q(t,r))||o.enumerable});return e};var re=e=>ne(P({},\\\"__esModule\\\",{value:!0}),e);var De={};te(De,{createFragmentStrategy:()=>J,createRouteStrategy:()=>X});function w(e,t){let n=new AbortController,o=!1,r=()=>{n.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let i=setTimeout(()=>{o=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>o,dispose:()=>{clearTimeout(i),e.removeEventListener(\\\"abort\\\",r)}}}function S(e){return e instanceof Error?e.message:String(e)}var A=\\\"data-payload-island\\\",Le=`astro-island, [${A}]`;function oe(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(A)}function ie(e){return e.getAttribute(A)===\\\"patch\\\"}function ae(e){return oe(e)&&!ie(e)}function _(e){let t=e;for(;t!==null;){if(ae(t))return!0;t=t.parentElement}return!1}function k(e){if(e==null)return[];let t=new Set,n=[];for(let o of e.split(/[\\\\s,]+/)){let r=o.trim();r.length===0||t.has(r)||(t.add(r),n.push(r))}return n}var b=\\\"data-payload-fragment\\\";var N=\\\"data-payload-fragment-key\\\",le=\\\"data-payload-depends\\\";function I(e){let t=e.getAttribute(b);if(t===null||t.length===0)return null;let n=e.getAttribute(N);return{element:e,id:t,key:n===null||n.length===0?void 0:n,dependsOn:k(e.getAttribute(le))}}function L(e,t){let n=[];for(let o of e.querySelectorAll(`[${b}]`)){let r=I(o);r===null||_(o)||r.dependsOn.length>0&&!r.dependsOn.some(i=>t.has(i))||n.push(r)}return n}var B=\\\"x-payload-fragment-version\\\";function D(e){return typeof e==\\\"object\\\"&&e!==null&&!Array.isArray(e)}function C(e){if(!D(e))return null;let{html:t,boundary:n,revision:o,metadata:r}=e;return typeof t!=\\\"string\\\"||!D(n)||typeof n.id!=\\\"string\\\"||n.key!==void 0&&typeof n.key!=\\\"string\\\"||typeof o!=\\\"number\\\"||!D(r)||typeof r.renderedAt!=\\\"string\\\"||typeof r.renderer!=\\\"string\\\"?null:e}function U(e){let t={};for(let[n,o]of Object.entries(e))o!==void 0&&(t[n]=o);return t}function H(e){let t=0,n=[],o=()=>{let r=n.shift();r===void 0?t-=1:r()};return async r=>{t<e?t+=1:await new Promise(i=>{n.push(i)});try{return await r()}finally{o()}}}var de=5e3,ue=4,ce=512*1024,T={status:\\\"superseded\\\"};function h(e,t){return{status:\\\"failed\\\",code:e,reason:t}}function fe(e){let t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with \\\"/\\\"')};if((typeof e!=\\\"string\\\"||!e.startsWith(\\\"/\\\")||e.startsWith(\\\"//\\\")||e.includes(\\\"\\\\\\\\\\\"))&&t(),typeof location<\\\"u\\\"){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}function me(e){return typeof e==\\\"object\\\"&&e!==null&&typeof e.getReader==\\\"function\\\"}async function ye(e,t,n){let o=e.body;if(!me(o)){let d=await e.text();return new TextEncoder().encode(d).byteLength>t?null:d}let r=o.getReader(),i=()=>{r.cancel().catch(()=>{})};n.addEventListener(\\\"abort\\\",i,{once:!0});let s=new TextDecoder,a=\\\"\\\",c=0;try{for(;;){let{done:d,value:p}=await r.read();if(d)break;if(c+=p.byteLength,c>t)return i(),null;a+=s.decode(p,{stream:!0})}}finally{n.removeEventListener(\\\"abort\\\",i)}return a+s.decode()}function K(e){let t=fe(e.endpoint),n=e.timeoutMs??de,o=e.maxResponseBytes??ce,r=H(Math.max(1,e.maxConcurrent??ue)),i=new Map;async function s(a,c){let d=()=>a.signal.aborted;if(d())return T;let p=e.location??location,f=U({fragment:c.id,key:c.key,route:p.pathname,search:p.search,revision:a.revision,locale:a.locale,collectionSlug:a.collectionSlug,globalSlug:a.globalSlug,fields:a.fields}),l=w(a.signal,n),y=u=>d()?T:l.timedOut()?h(\\\"LP0801\\\",`timeout after ${String(n)} ms`):h(\\\"LP0801\\\",S(u));try{let u;try{u=await(e.fetch??fetch)(t,{method:\\\"POST\\\",credentials:\\\"same-origin\\\",headers:{...e.headers,accept:\\\"application/json\\\",\\\"content-type\\\":\\\"application/json\\\",[B]:String(1)},body:JSON.stringify(f),signal:l.signal})}catch(M){return y(M)}if(d())return T;if(u.status===401||u.status===403)return h(\\\"LP0803\\\",`endpoint refused the preview (${String(u.status)})`);if(!u.ok)return h(\\\"LP0801\\\",`endpoint answered ${String(u.status)}`);let g=u.headers.get(\\\"content-type\\\")??\\\"\\\";if(!g.toLowerCase().startsWith(\\\"application/json\\\"))return h(\\\"LP0802\\\",`unexpected content type \\\"${g}\\\"`);if(Number(u.headers.get(\\\"content-length\\\")??\\\"0\\\")>o)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let E;try{E=await ye(u,o,l.signal)}catch(M){return y(M)}if(d())return T;if(l.timedOut())return h(\\\"LP0801\\\",`timeout after ${String(n)} ms`);if(E===null)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let x;try{x=JSON.parse(E)}catch{return h(\\\"LP0802\\\",\\\"response is not JSON\\\")}let R=C(x);return R===null?h(\\\"LP0802\\\",\\\"response has the wrong shape\\\"):R.boundary.id!==c.id?h(\\\"LP0802\\\",\\\"response is for another boundary\\\"):R.revision!==a.revision?T:{status:\\\"rendered\\\",html:R.html,metadata:R.metadata}}finally{l.dispose()}}return(a,c)=>{let d=`${c.id} ${c.key??\\\"\\\"} ${String(a.revision)}`,p=i.get(d);if(p!==void 0)return p;let f=r(()=>s(a,c));i.set(d,f);let l=()=>{i.get(d)===f&&i.delete(d)};return f.then(l,l),f}}var O=\\\"data-payload-owned\\\",pe=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function q(e,t){for(let n of t.keyAttributes){let o=e.getAttribute(n);if(o!==null&&o.length>0)return`${n}=${o}`}}function F(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(A)||e.hasAttribute(O))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return t!==null&&t!==\\\"false\\\"}function ge(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!F(e)&&!F(t)}function v(e,t,n){if(!ge(e,t))return t;let o=Re(e);return he(e,t),n.retainChildrenOf?.(e,t)!==!0&&Ee(e,t,n),Ae(o),e}function he(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||pe.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function Ee(e,t,n){let o=be(e,n),r=new Set(o.values()),i=Array.from(e.childNodes).filter(f=>!r.has(f)),s=new Set,a=new Set,c=Array.from(t.childNodes),d=e.firstChild,p=0;for(let f=0;f<c.length;f+=1){let l=c[f],y=null,u=l instanceof Element?q(l,n):void 0;if(u!==void 0&&a.has(u)&&(u=void 0),u!==void 0){a.add(u);let m=o.get(u);if(m!==void 0&&!s.has(m)&&(y=$(m,l,n)===m?m:null,y===null)){m.replaceWith(l),s.add(l),d=l.nextSibling;continue}}else{for(;p<i.length;){let m=i[p];if(p+=1,!s.has(m)){if(G(m,l)){y=$(m,l,n)===m?m:null,y===null&&(e.replaceChild(l,m),s.add(l),d=l.nextSibling);break}if(m instanceof Element){let E=c[f+1];if(!(l instanceof Element)||E!==void 0&&G(m,E)){p-=1;break}e.replaceChild(l,m),s.add(l),d=l.nextSibling;break}if(!(l instanceof Element)){e.replaceChild(l,m),s.add(l),d=l.nextSibling;break}}}if(y===null&&s.has(l))continue}let g=y??l;for(s.add(g);d!==null&&d!==g&&!s.has(d)&&Se(d);)d=d.nextSibling;g!==d&&e.insertBefore(g,d),d=g.nextSibling}for(let f of Array.from(e.childNodes))s.has(f)||f.remove()}function $(e,t,n){return e instanceof Element&&t instanceof Element?F(e)&&F(t)?e:v(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function Se(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function G(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function be(e,t){let n=new Map,o;for(let r of Array.from(e.children)){let i=q(r,t);if(i!==void 0){if(n.has(i)){o??(o=i.slice(i.indexOf(\\\"=\\\")+1));continue}n.set(i,r)}}return o!==void 0&&t.onDuplicateKey?.(e,o),n}function Re(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function Ae(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[o,r]=n??[null,null];o!==null&&r!==null&&t.setSelectionRange(o,r)}catch{}}var W=\\\"data-payload-key\\\";var Te=\\\"__livePreviewRouteRefresh\\\";function xe(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function z(){return xe()?.[Te]}var j=\\\"data-payload-strategy\\\",Y=\\\"data-payload-field\\\",we=\\\"data-payload-depends\\\",ke=\\\"x-payload-live-preview\\\",Fe=8e3,Oe=1e3;function Me(e){let t=e.getAttribute(j);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function Pe(e){let t=e.getAttribute(Y),n=k(e.getAttribute(we));return t===null||t.length===0?n:[t,...n]}function V(e){if(e.tagName===\\\"META\\\"){let t=e.getAttribute(\\\"name\\\")??e.getAttribute(\\\"property\\\");return t===null?null:`meta:${t}`}return e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"?\\\"link:canonical\\\":null}function Ne(e,t){t.title!==e.title&&(e.title=t.title);let n=new Map;for(let r of e.head.querySelectorAll(\\\"meta, link\\\")){let i=V(r);i!==null&&!n.has(i)&&n.set(i,r)}let o=new Set;for(let r of t.head.querySelectorAll(\\\"meta, link\\\")){let i=V(r);if(i===null)continue;o.add(i);let s=n.get(i);if(s===void 0){e.head.append(e.importNode(r,!0));continue}if(!s.hasAttribute(O))for(let a of Array.from(r.attributes))s.getAttribute(a.name)!==a.value&&s.setAttribute(a.name,a.value)}for(let[r,i]of n)!o.has(r)&&!i.hasAttribute(O)&&i.remove()}function X(e={}){let t=e.timeoutMs??Fe,n=e.minIntervalMs??Oe,o=-1/0;return{plan(r,i){for(let s of r.querySelectorAll(`[${Y}], [${j}=\\\"route\\\"]`)){if(!Me(s))continue;let a=Pe(s);if(a.length===0||a.some(c=>i.has(c)))return!0}return!1},async refresh(r){let i=Date.now(),s=n-(i-o);if(s>0)return r.retryAfter?.(s),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(i-o)} ms ago`),\\\"refused\\\";o=i;let a=e.document??document,c=e.location??location,d=e.window??window,p=w(r.signal,t),f=l=>{if(r.signal.aborted)return\\\"superseded\\\";let y=p.timedOut()?`route refresh timed out after ${String(t)} ms`:S(l);return r.log(\\\"LP0801\\\",y),\\\"failed\\\"};try{let l=z();if(l!==void 0){try{await l()}catch(u){return f(u)}return r.isCurrent()?\\\"refreshed\\\":\\\"superseded\\\"}let y;try{y=await(e.fetch??fetch)(c.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[ke]:\\\"route\\\"},signal:p.signal})}catch(u){return f(u)}if(r.signal.aborted)return\\\"superseded\\\";if(!y.ok||!(y.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(y.status)} ${y.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let u=await y.text();if(!r.isCurrent())return\\\"superseded\\\";let g=new DOMParser().parseFromString(u,\\\"text/html\\\"),m=d.scrollX,E=d.scrollY;return Ne(a,g),v(a.body,g.body,{keyAttributes:[W,N,b],retainChildrenOf:x=>x.hasAttribute(b)}),d.scrollTo(m,E),\\\"refreshed\\\"}catch(u){return f(u)}}finally{p.dispose()}}}}function Ie(e){return{plan:(t,n)=>L(t,n).map(o=>o.element),async render(t,n){let o={rendered:0,failed:0,superseded:0},r={revision:t.revision,receivedAt:t.receivedAt,fields:t.fields,locale:t.locale,collectionSlug:t.collectionSlug,globalSlug:t.globalSlug,signal:t.signal};return await Promise.all(n.map(async i=>{let s=I(i);if(s===null)return;let a;try{a=await e(r,s)}catch(c){a={status:\\\"failed\\\",code:\\\"LP0801\\\",reason:S(c)}}if(!t.isCurrent()||a.status===\\\"superseded\\\"){o.superseded+=1,t.log(\\\"LP0804\\\",`fragment \\\"${s.id}\\\" for revision ${String(r.revision)} discarded as superseded`);return}if(a.status===\\\"rendered\\\"){t.morph(i,a.html),t.rendered(i,s.id,s.key),o.rendered+=1;return}t.failed(i,s.id,s.key,a.code,a.reason),t.isCurrent()&&t.patch(i),o.failed+=1})),o}}}function J(e){return Ie(K(e))}return re(De);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const ROUTE_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_ROUTE__=(()=>{var S=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var $=(e,n)=>{for(var t in n)S(e,t,{get:n[t],enumerable:!0})},H=(e,n,t,o)=>{if(n&&typeof n==\\\"object\\\"||typeof n==\\\"function\\\")for(let r of L(n))!K.call(e,r)&&r!==t&&S(e,r,{get:()=>n[r],enumerable:!(o=U(n,r))||o.enumerable});return e};var z=e=>H(S({},\\\"__esModule\\\",{value:!0}),e);var ae={};$(ae,{createRouteStrategy:()=>B});var A=\\\"data-payload-island\\\",se=`astro-island, [${A}]`;var b=\\\"data-payload-owned\\\",W=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function k(e,n){for(let t of n.keyAttributes){let o=e.getAttribute(t);if(o!==null&&o.length>0)return`${t}=${o}`}}function E(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(A)||e.hasAttribute(b))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function q(e,n){return e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI&&!E(e)&&!E(n)}function R(e,n,t){if(!q(e,n))return n;let o=X(e);return Y(e,n),t.retainChildrenOf?.(e,n)!==!0&&G(e,n,t),J(o),e}function Y(e,n){for(let t of Array.from(e.attributes))n.hasAttribute(t.name)||W.has(t.name.toLowerCase())||e.removeAttribute(t.name);for(let t of Array.from(n.attributes))e.getAttribute(t.name)!==t.value&&e.setAttribute(t.name,t.value)}function G(e,n,t){let o=j(e,t),r=new Set(o.values()),l=Array.from(e.childNodes).filter(m=>!r.has(m)),a=new Set,f=new Set,g=Array.from(n.childNodes),s=e.firstChild,y=0;for(let m=0;m<g.length;m+=1){let i=g[m],u=null,c=i instanceof Element?k(i,t):void 0;if(c!==void 0&&f.has(c)&&(c=void 0),c!==void 0){f.add(c);let d=o.get(c);if(d!==void 0&&!a.has(d)&&(u=x(d,i,t)===d?d:null,u===null)){d.replaceWith(i),a.add(i),s=i.nextSibling;continue}}else{for(;y<l.length;){let d=l[y];if(y+=1,!a.has(d)){if(w(d,i)){u=x(d,i,t)===d?d:null,u===null&&(e.replaceChild(i,d),a.add(i),s=i.nextSibling);break}if(d instanceof Element){let h=g[m+1];if(!(i instanceof Element)||h!==void 0&&w(d,h)){y-=1;break}e.replaceChild(i,d),a.add(i),s=i.nextSibling;break}if(!(i instanceof Element)){e.replaceChild(i,d),a.add(i),s=i.nextSibling;break}}}if(u===null&&a.has(i))continue}let p=u??i;for(a.add(p);s!==null&&s!==p&&!a.has(s)&&V(s);)s=s.nextSibling;p!==s&&e.insertBefore(p,s),s=p.nextSibling}for(let m of Array.from(e.childNodes))a.has(m)||m.remove()}function x(e,n,t){return e instanceof Element&&n instanceof Element?E(e)&&E(n)?e:R(e,n,t):(e.nodeValue!==n.nodeValue&&(e.nodeValue=n.nodeValue),e)}function V(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function w(e,n){return e.nodeType!==n.nodeType?!1:e instanceof Element&&n instanceof Element?e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI:!0}function j(e,n){let t=new Map,o;for(let r of Array.from(e.children)){let l=k(r,n);if(l!==void 0){if(t.has(l)){o??(o=l.slice(l.indexOf(\\\"=\\\")+1));continue}t.set(l,r)}}return o!==void 0&&n.onDuplicateKey?.(e,o),t}function X(e){let n=e.ownerDocument.activeElement;if(!(n instanceof HTMLElement)||!e.contains(n))return null;let t=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd]:null;return{element:n,selection:t}}function J(e){if(e===null)return;let{element:n,selection:t}=e;if(!(n.ownerDocument.activeElement===n||!n.isConnected))try{n.focus({preventScroll:!0});let[o,r]=t??[null,null];o!==null&&r!==null&&n.setSelectionRange(o,r)}catch{}}var I=\\\"data-payload-key\\\";function N(e){if(e==null)return[];let n=new Set,t=[];for(let o of e.split(/[\\\\s,]+/)){let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}var Q=\\\"__livePreviewRouteRefresh\\\";function Z(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function M(){return Z()?.[Q]}var T=\\\"data-payload-fragment\\\";function v(e,n){let t=new AbortController,o=!1,r=()=>{t.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let l=setTimeout(()=>{o=!0,t.abort()},n);return{signal:t.signal,timedOut:()=>o,dispose:()=>{clearTimeout(l),e.removeEventListener(\\\"abort\\\",r)}}}function D(e){return e instanceof Error?e.message:String(e)}var P=\\\"data-payload-fragment-key\\\";var C=\\\"data-payload-strategy\\\",_=\\\"data-payload-field\\\",ee=\\\"data-payload-depends\\\",ne=\\\"x-payload-live-preview\\\",te=8e3,re=1e3;function oe(e){let n=e.getAttribute(C);return n!==null?n===\\\"route\\\":e.closest(\\\"head\\\")!==null}function le(e){let n=e.getAttribute(_),t=N(e.getAttribute(ee));return n===null||n.length===0?t:[n,...t]}function O(e){if(e.tagName===\\\"META\\\"){let n=e.getAttribute(\\\"name\\\")??e.getAttribute(\\\"property\\\");return n===null?null:`meta:${n}`}return e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"?\\\"link:canonical\\\":null}function ie(e,n){n.title!==e.title&&(e.title=n.title);let t=new Map;for(let r of e.head.querySelectorAll(\\\"meta, link\\\")){let l=O(r);l!==null&&!t.has(l)&&t.set(l,r)}let o=new Set;for(let r of n.head.querySelectorAll(\\\"meta, link\\\")){let l=O(r);if(l===null)continue;o.add(l);let a=t.get(l);if(a===void 0){e.head.append(e.importNode(r,!0));continue}if(!a.hasAttribute(b))for(let f of Array.from(r.attributes))a.getAttribute(f.name)!==f.value&&a.setAttribute(f.name,f.value)}for(let[r,l]of t)!o.has(r)&&!l.hasAttribute(b)&&l.remove()}function B(e={}){let n=e.timeoutMs??te,t=e.minIntervalMs??re,o=-1/0;return{plan(r,l){for(let a of r.querySelectorAll(`[${_}], [${C}=\\\"route\\\"]`)){if(!oe(a))continue;let f=le(a);if(f.length===0||f.some(g=>l.has(g)))return!0}return!1},async refresh(r){let l=Date.now(),a=t-(l-o);if(a>0)return r.retryAfter?.(a),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(l-o)} ms ago`),\\\"refused\\\";o=l;let f=e.document??document,g=e.location??location,s=e.window??window,y=v(r.signal,n),m=i=>{if(r.signal.aborted)return\\\"superseded\\\";let u=y.timedOut()?`route refresh timed out after ${String(n)} ms`:D(i);return r.log(\\\"LP0801\\\",u),\\\"failed\\\"};try{let i=M();if(i!==void 0){try{await i()}catch(c){return m(c)}return r.isCurrent()?\\\"refreshed\\\":\\\"superseded\\\"}let u;try{u=await(e.fetch??fetch)(g.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[ne]:\\\"route\\\"},signal:y.signal})}catch(c){return m(c)}if(r.signal.aborted)return\\\"superseded\\\";if(!u.ok||!(u.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(u.status)} ${u.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let c=await u.text();if(!r.isCurrent())return\\\"superseded\\\";let p=new DOMParser().parseFromString(c,\\\"text/html\\\"),d=s.scrollX,h=s.scrollY;return ie(f,p),R(f.body,p.body,{keyAttributes:[I,P,T],retainChildrenOf:F=>F.hasAttribute(T)}),s.scrollTo(d,h),\\\"refreshed\\\"}catch(c){return m(c)}}finally{y.dispose()}}}}return z(ae);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function o(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function t(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function e(){return o()||t()}function i(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}e()&&i();})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_REACT_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function f(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function m(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function d(){return f()||m()}var t=\\\"__livePreviewHydration\\\";function l(){if(typ\",\"eof window>\\\"u\\\")return;let n=window;return n[t]??(n[t]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function u(){let n=l();if(n===void 0||n.armed)return;n.armed=!0;let e=window,o=e.__REACT_DEVTOOLS_GLOBAL_HOOK__??(e.__REACT_DEVTOOLS_GLOBAL_HOOK__=_()),a=o.onCommitFiberRoot;o.onCommitFiberRoot=function(c,i,...s){try{a?.call(this,c,i,...s)}catch{}let r=i?.containerInfo;n.onCommit===void 0?n.commits.push(r):n.onCommit(r)}}function _(){let n=new Map;return{supportsFiber:!0,renderers:n,inject:e=>{let o=n.size+1;return n.set(o,e),o}}}function p(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}u();d()&&p();})();\"].join('');\n","/**\n * The inline script's configuration and its positional wire order: the\n * generator writes the tuple, `src/core/runtime.ts` destructures it, and\n * `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\nexport interface InlineScriptConfig {\n /** Trusted admin origins, merged with the detected ones. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API with credentials. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with `serverURL` unless `defaults: 'v1'`. */\n readonly mergeDepth?: number;\n /** Verbose console logging. Default `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Default `50`. */\n readonly debounceMs?: number;\n /** Mount the screen-reader live region. Default `true`. */\n readonly enableA11y?: boolean;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** Apply every update regardless of viewport position. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** `rootMargin` of the IntersectionObserver. Default `'200px'`. */\n readonly intersectionRootMargin?: string;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher (any port on `localhost`/`127.0.0.1`). Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Update only bindings under a matching `data-payload-owner`. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip bindings whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: 'any' | 'parent-or-opener';\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** Same-origin path of a fragment endpoint; the script then carries the fragment client ahead of the runtime (ADR 0011). */\n readonly fragmentEndpoint?: string;\n /**\n * Carry the route strategy, so a binding in `<head>` or one marked\n * `data-payload-strategy=\"route\"` refreshes the route. `fragmentEndpoint`\n * implies it — the fragment prelude already contains it. Default `false`.\n */\n readonly routeStrategy?: boolean;\n /**\n * The 2.0 name for `onUnfaithfulPatch`, kept until 3.0. `'route'` means\n * `'escalate'`, `'ignore'` means `'ignore'`.\n *\n * @deprecated Renamed to `onUnfaithfulPatch`.\n */\n readonly onUnboundChange?: 'ignore' | 'route';\n /**\n * What to do when the runtime knows a patch cannot reach what the server\n * would have drawn. `'escalate'` (the default) hands the region to the\n * fragment strategy when a boundary covers it and to the route otherwise, so\n * it needs `fragmentEndpoint` or `routeStrategy` to do anything. `'warn'`\n * reports LP0411 and keeps the patch; `'ignore'` keeps it silently.\n */\n readonly onUnfaithfulPatch?: 'ignore' | 'warn' | 'escalate';\n /**\n * Find bindings by value on the connection's first message (ADR 0014): a\n * scalar whose value is the whole content of exactly one element is bound\n * to it as if `data-payload-field` stood there. Default `'off'`.\n */\n readonly autoBind?: 'off' | 'unique';\n /**\n * The framework that hydrates this page (ADR 0015). Under `'react'` the\n * runtime holds its first write until React has committed the tree that\n * holds the bindings — otherwise React finds markup it did not render,\n * throws `Hydration failed` and regenerates the tree, and the write is gone.\n * Under `'vue'` it holds the write until Vue has mounted the app around them\n * — otherwise Vue's hydration repairs the write back to the server's value,\n * quietly. The Next.js and Nuxt adapters set it on every script they emit; a\n * page built by hand with `generateInlineScript()` may. Omitted: the runtime\n * starts on `DOMContentLoaded`, as on a static page.\n */\n readonly hydration?: 'react' | 'vue';\n /**\n * Which defaults the omitted options fall back to, resolved by the generator\n * rather than the runtime, whose own fallbacks are the 2.0 rows: `'v1'`\n * writes its four runtime rows into their slots (an explicit option still\n * wins) and relaxes the `mergeDepth` check. The resolved value always\n * travels, in the last slot, so a reader of the served page knows what an\n * empty slot means instead of guessing it — `pll doctor --v2` reads it. The\n * runtime does not: every row the profile decides is already in its slot.\n */\n readonly defaults?: DefaultsProfile;\n /**\n * A runtime artifact to embed instead of the full one — today only\n * `LEAN_RUNTIME` from `payload-live-preview/lean`, which leaves out the\n * strategies, the keyed morph, the structural arrays, the item templates and\n * the announcer (about 5.5 KB gzip less on the page) and reports LP0104 when\n * a page needs one of them.\n *\n * It is an imported value rather than a `profile: 'lean'` string on purpose:\n * a second artifact behind a string option would sit in every build that can\n * reach the generator, which measured +24 KB gzip in each adapter entry. This\n * way the bytes follow the import.\n *\n * Not serialized: it decides which bytes are emitted, not how they behave.\n */\n readonly runtime?: RuntimeArtifact;\n}\n\n/**\n * A runtime build this package produces. `source` is the IIFE the page runs;\n * the two digests describe the same bytes as a servable asset, so asset\n * delivery can hash-name and SRI-verify whichever artifact was chosen without\n * hashing anything at request time.\n */\nexport interface RuntimeArtifact {\n readonly profile: 'lean';\n readonly source: string;\n /** Short content hash, for the asset's file name. */\n readonly contentHash: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n}\n\n/** Keys that travel in the wire tuple, in slot order. */\nexport const INLINE_CONFIG_KEYS = [\n 'allowedOrigins',\n 'serverURL',\n 'apiRoute',\n 'mergeDepth',\n 'debug',\n 'debounceMs',\n 'enableA11y',\n 'heartbeatMs',\n 'disableVisibilityGate',\n 'visibilityGateThreshold',\n 'intersectionRootMargin',\n 'disableReferrerDetection',\n 'disableLocalhostMatching',\n 'scopeBindingsByOwner',\n 'skipUnchanged',\n 'eventSourcePolicy',\n 'sanitizerPolicy',\n 'fragmentEndpoint',\n 'revealEditedField',\n 'routeStrategy',\n 'onUnboundChange',\n 'onUnfaithfulPatch',\n 'autoBind',\n 'hydration',\n 'defaults',\n] as const satisfies readonly Exclude<keyof InlineScriptConfig, 'runtime'>[];\n","/**\n * Wraps the build-time runtime IIFE with the consumer's configuration, and\n * places at most one strategy prelude ahead of it.\n */\n\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { V1_RUNTIME_DEFAULTS } from '@/types/defaults-profile';\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { FRAGMENT_SOURCE } from './fragment.generated';\nimport { ROUTE_SOURCE } from './route.generated';\nimport { LOADER_SOURCE } from './loader.generated';\nimport { LOADER_REACT_SOURCE } from './loader-react.generated';\nimport { INLINE_CONFIG_KEYS, type InlineScriptConfig } from '@/types/inline-config';\n\nexport type { InlineScriptConfig, RuntimeArtifact } from '@/types/inline-config';\n\nfunction assertBuilt(source: string, artifact: string): void {\n if (source.length === 0) {\n throw new Error(\n `[live-preview] ${artifact} is empty. Run \\`npm run build:runtime\\` before bundling.`,\n );\n }\n}\n\n/** The inline script body without `<script>` tags; see `wrapWithScriptTag()`. */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n const runtime = runtimeFor(config);\n return [configStatement(config), ...strategyPrelude(config), runtime].join('\\n');\n}\n\n/**\n * The full runtime, or the artifact the consumer imported. The lean one leaves\n * out the strategies (docs/options.md), so the two preludes are refused with it\n * rather than emitted against a runtime that could never answer them.\n */\nfunction runtimeFor(config: InlineScriptConfig): string {\n const artifact = config.runtime;\n if (artifact === undefined) {\n assertBuilt(RUNTIME_SOURCE, 'runtime.generated.ts');\n return RUNTIME_SOURCE;\n }\n assertBuilt(artifact.source, `the ${artifact.profile} runtime`);\n if (config.fragmentEndpoint != null || config.routeStrategy === true) {\n throw new Error(\n `[live-preview] the ${artifact.profile} runtime and the fragment or route strategy exclude ` +\n 'each other: it carries no strategy runner, so the prelude would have nothing to talk to. ' +\n 'Drop the runtime option, or drop `fragmentEndpoint`/`routeStrategy`.',\n );\n }\n return artifact.source;\n}\n\n/**\n * At most one prelude, and the fragment one wins: it already contains the\n * route strategy, so emitting both would ship that code twice and leave two\n * globals where the runtime expects the fragment one to be authoritative.\n */\nfunction strategyPrelude(config: InlineScriptConfig): readonly string[] {\n if (config.fragmentEndpoint != null) {\n assertBuilt(FRAGMENT_SOURCE, 'fragment.generated.ts');\n return [FRAGMENT_SOURCE];\n }\n if (config.routeStrategy === true) {\n assertBuilt(ROUTE_SOURCE, 'route.generated.ts');\n return [ROUTE_SOURCE];\n }\n return [];\n}\n\n// `__LIVE_PREVIEW_CONFIG__` is a public presence signal: consumers' integration\n// tests grep for it, so the name outlives any refactor.\nfunction configStatement(config: InlineScriptConfig): string {\n return `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`;\n}\n\n/** The positional wire literal the runtime destructures; shared by the inline script and the loader. */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n assertMergeDepthExplicit(config);\n const profile = profileSlots(config);\n // `null` counts as omitted, and omitted slots stay empty (`[,,1]`): a JSON\n // `null` would bypass the runtime's destructuring defaults. The last slot is\n // always written, so there is no trailing hole to trim.\n const values: unknown[] = INLINE_CONFIG_KEYS.map((key) => config[key] ?? profile[key]);\n // `<` is escaped so a value containing `</script>` cannot end the tag.\n return `[${values\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n}\n\n/**\n * What the `defaults` profile puts on the wire. The runtime's own fallbacks are\n * the 2.0 rows, so `'v2'` fills nothing and `'v1'` has to write its four; the\n * profile itself goes into the last slot either way, so a reader of the served\n * page learns which generation an empty slot belongs to (ADR 0007).\n */\nfunction profileSlots(config: InlineScriptConfig): Partial<InlineScriptConfig> {\n const defaults = config.defaults ?? 'v2';\n return defaults === 'v1' ? { ...V1_RUNTIME_DEFAULTS, defaults } : { defaults };\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /** Subresource-integrity value, e.g. `sha384-…`; empty drops the check and the `crossorigin` it requires. */\n readonly integrity?: string;\n}\n\n/**\n * The static-delivery bootstrap: the configuration plus a few hundred bytes\n * appending the runtime inside a preview. The asset stays configuration-free.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n const bootstrap = loaderFor(config);\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n configStatement(config),\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n ...strategyPrelude(config),\n bootstrap,\n ].join('\\n');\n}\n\n/**\n * The bootstrap, or the one armed for React's first commit (ADR 0015 F2): the\n * inline runtime is the first script in `<head>` and arms the signal itself,\n * while a fetched asset may evaluate after `react-dom` has, when it is too\n * late — so on a page that declares React the bootstrap arms before it\n * fetches. One script either way, never a prelude ahead of the plain one. A\n * page that declares Vue takes the plain one: Vue's mount leaves state on the\n * container that a late runtime can still read (`core/hydration-vue`).\n */\nfunction loaderFor(config: InlineScriptConfig): string {\n if (config.hydration === 'react') {\n assertBuilt(LOADER_REACT_SOURCE, 'loader-react.generated.ts');\n return LOADER_REACT_SOURCE;\n }\n assertBuilt(LOADER_SOURCE, 'loader.generated.ts');\n return LOADER_SOURCE;\n}\n\n/** Wrap a script body in `<script>`, with the CSP nonce attribute when given. */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${assertNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\n/** @internal */\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\n/**\n * A nonce as CSP defines it: base64url characters only. Returned unchanged so\n * a caller can inline the result. Not re-exported from the package barrel — it\n * is shared with the adapters, not part of the public surface.\n */\nexport function assertNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('nonce contains characters CSP does not allow');\n }\n return nonce;\n}\n","/**\n * The runtime as a servable, cacheable asset — the request-time half of\n * `mode: 'loader'`.\n *\n * Name and integrity are constants of the package build (the artifact carries\n * both), so nothing here hashes anything per request and this module stays\n * reachable from a browser entry: no `node:crypto`, no Node builtins at all.\n *\n * The content hash is in the file name, which is what makes `immutable` honest:\n * different bytes are a different URL, so a year-long cache can never serve the\n * wrong runtime. A request for any other name under the mount path is a 404\n * rather than a redirect to the current one — a client asking for a hash we no\n * longer have is asking for bytes we cannot produce.\n */\n\nimport { RUNTIME_CONTENT_HASH, RUNTIME_INTEGRITY, RUNTIME_SOURCE } from '@inline/runtime.generated';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n/** Where the asset route is mounted when nothing says otherwise. */\nexport const DEFAULT_ASSET_PATH = '/payload-live-preview';\n\nexport interface RuntimeAssetOptions {\n /**\n * Path the asset route is mounted at. Must match on both sides — the\n * bootstrap requests it and the route serves it. Default\n * `/payload-live-preview`; give it the framework's own base path as a prefix\n * when the app is not served from the site root.\n */\n readonly assetPath?: string;\n /** The artifact to serve; the default runtime when omitted. */\n readonly runtime?: RuntimeArtifact;\n}\n\nexport interface RuntimeAsset {\n /** The file name alone, `runtime.<hash>.js`. */\n readonly fileName: string;\n /** The absolute path the bootstrap requests, mount path included. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to serve. */\n readonly source: string;\n}\n\n/**\n * One leading slash, no trailing one, so joining is a single concatenation.\n *\n * Trimmed by index rather than by `/^\\/+|\\/+$/`: that expression backtracks over\n * a long run of slashes and costs quadratic time on a path the consumer\n * configures (CodeQL js/polynomial-redos).\n */\nfunction normalizePath(path: string): string {\n let start = 0;\n let end = path.length;\n while (start < end && path[start] === '/') start += 1;\n while (end > start && path[end - 1] === '/') end -= 1;\n const trimmed = path.slice(start, end);\n return trimmed === '' ? '' : `/${trimmed}`;\n}\n\n/** Describe the asset for these options; deterministic per package version and artifact. */\nexport function runtimeAsset(options: RuntimeAssetOptions = {}): RuntimeAsset {\n const artifact = options.runtime;\n const hash = artifact?.contentHash ?? RUNTIME_CONTENT_HASH;\n const fileName = `runtime.${hash}.js`;\n return {\n fileName,\n urlPath: `${normalizePath(options.assetPath ?? DEFAULT_ASSET_PATH)}/${fileName}`,\n integrity: artifact?.integrity ?? RUNTIME_INTEGRITY,\n source: artifact?.source ?? RUNTIME_SOURCE,\n };\n}\n\n/**\n * A year, the longest `max-age` browsers honour, plus `immutable` so a reload\n * does not revalidate either. Safe only because the hash is in the name.\n */\nexport const ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';\n\n/** The headers the asset is served with, on every framework. */\nexport function runtimeAssetHeaders(): Record<string, string> {\n return {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': ASSET_CACHE_CONTROL,\n // The bootstrap sets `crossorigin=\"anonymous\"` for the integrity check;\n // same-origin needs no CORS header, and a CDN in front of it gets one that\n // says the bytes are public.\n 'access-control-allow-origin': '*',\n // Nothing here is HTML, and a browser that sniffs it as such would be wrong.\n 'x-content-type-options': 'nosniff',\n };\n}\n\n/**\n * The response for one requested URL: the asset when the file name is the one\n * this build produces, 404 otherwise.\n *\n * Only the file name is checked, never the mount path. Where the route sits is\n * the framework's business — the consumer put the file there — while the name\n * is ours, and it is the name that decides whether the bytes a client cached\n * for a year are still the bytes we would send.\n */\nexport function runtimeAssetResponse(url: string, options: RuntimeAssetOptions = {}): Response {\n const asset = runtimeAsset(options);\n // A query string is a cache-buster and must still resolve.\n const path = url.split('?')[0] ?? '';\n const requested = path.slice(path.lastIndexOf('/') + 1);\n if (requested !== asset.fileName) {\n return new Response('Not found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n });\n }\n return new Response(asset.source, { status: 200, headers: runtimeAssetHeaders() });\n}\n","/**\n * The runtime as a servable, cacheable asset, in the shape Astro's build wants:\n * a path inside the output directory to emit, and a site path to request.\n *\n * The naming and the digests come from `runtimeAsset()`, the same descriptor\n * the route-serving adapters use, so there is one answer to \"what is this file\n * called\" across all four. What stays Astro's own is the directory: an\n * underscore keeps it out of Astro's page routing, which is exactly what the\n * others cannot use — a leading underscore makes a folder private in the App\n * Router and in SvelteKit both.\n */\nimport { runtimeAsset } from '@adapters/shared/runtime-asset';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n// Not `_astro/`: Astro's bundler empties and rewrites that directory.\nconst ASSET_DIR = '_payload-live-preview';\n\nexport interface LoaderAsset {\n /** Path within the build output, e.g. `_payload-live-preview/runtime.<hash>.js`. */\n readonly fileName: string;\n /** Absolute site path the bootstrap requests, with a leading slash. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to write or serve. */\n readonly source: string;\n}\n\n/** Describe the asset for this build; deterministic per package version and artifact. */\nexport function loaderAsset(base = '/', runtime?: RuntimeArtifact): LoaderAsset {\n // `base` may carry slashes at either end; normalise to exactly one between segments.\n const prefix = base.replace(/^\\/+|\\/+$/gu, '');\n const asset = runtimeAsset({\n assetPath: prefix === '' ? `/${ASSET_DIR}` : `/${prefix}/${ASSET_DIR}`,\n ...(runtime !== undefined ? { runtime } : {}),\n });\n return {\n fileName: `${ASSET_DIR}/${asset.fileName}`,\n urlPath: asset.urlPath,\n integrity: asset.integrity,\n source: asset.source,\n };\n}\n","/**\n * The options the policy reads, and what they resolve to: the `defaults`\n * profile fills what an adapter left unset, and the inline-script config\n * carries only what was given so the runtime's own defaults stay the single\n * source of them.\n */\n\nimport type { generateInlineScript } from '@inline/generator';\nimport {\n adapterDefaultsFor,\n runtimeDefaultsFor,\n V2_RUNTIME_DEFAULTS,\n} from '@/types/defaults-profile';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport type { InlineScriptConfig } from '@/types/inline-config';\nimport type { PreviewSignal } from './preview-request';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The structural subset of any adapter's options the policy reads; hooks are bound per request. */\nexport type PreviewPolicyOptions = PreviewAdapterOptions<never>;\n\n/** The options after the `defaults` profile: explicit options win, the profile fills the rest. */\nexport interface ResolvedPolicyOptions {\n readonly strict: boolean;\n readonly previewSignals: readonly PreviewSignal[] | undefined;\n readonly skipUnchanged: boolean | undefined;\n readonly disableReferrerDetection: boolean | undefined;\n readonly disableLocalhostMatching: boolean | undefined;\n readonly eventSourcePolicy: 'any' | 'parent-or-opener' | undefined;\n readonly sanitizerPolicy: 'compat' | 'strict' | undefined;\n}\n\nexport function resolvePolicyOptions(options: PreviewPolicyOptions): ResolvedPolicyOptions {\n const adapter = adapterDefaultsFor(options.defaults);\n const runtime = runtimeDefaultsFor(options.defaults);\n // The inline runtime already defaults to the v2 rows, so only a differing\n // profile — an explicit `defaults: 'v1'` — needs a row on the wire.\n const runtimeRow = <K extends keyof typeof V2_RUNTIME_DEFAULTS>(\n key: K,\n ): (typeof V2_RUNTIME_DEFAULTS)[K] | undefined =>\n runtime[key] !== V2_RUNTIME_DEFAULTS[key] ? runtime[key] : undefined;\n return {\n strict: options.strict ?? adapter.strict,\n previewSignals: options.previewSignals ?? adapter.previewSignals,\n skipUnchanged: options.skipUnchanged ?? runtimeRow('skipUnchanged'),\n disableReferrerDetection:\n options.disableReferrerDetection ?? runtimeRow('disableReferrerDetection'),\n disableLocalhostMatching: options.disableLocalhostMatching,\n eventSourcePolicy: options.eventSourcePolicy ?? runtimeRow('eventSourcePolicy'),\n sanitizerPolicy: options.sanitizerPolicy ?? runtimeRow('sanitizerPolicy'),\n };\n}\n\n/**\n * What an adapter knows about the page beyond what a project configured — today\n * the framework that hydrates it (ADR 0015). Not an adapter option: a Next page\n * is a React tree whether or not anyone says so, so the adapter says it.\n */\nexport type PageFacts = Pick<InlineScriptConfig, 'hydration'>;\n\n/** The inline-script configuration; only given options travel, so the runtime's own defaults stay the single source of them. */\nexport function inlineScriptConfig(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): Parameters<typeof generateInlineScript>[0] {\n assertMergeDepthExplicit(options);\n const resolved = resolvePolicyOptions(options);\n return {\n // The generator names it in the last slot and, under `'v1'`, reads an\n // omitted `mergeDepth` as deliberate.\n ...(options.defaults !== undefined ? { defaults: options.defaults } : {}),\n ...(options.allowedOrigins !== undefined ? { allowedOrigins: options.allowedOrigins } : {}),\n ...(options.serverURL !== undefined ? { serverURL: options.serverURL } : {}),\n ...(options.apiRoute !== undefined ? { apiRoute: options.apiRoute } : {}),\n ...(options.mergeDepth !== undefined ? { mergeDepth: options.mergeDepth } : {}),\n ...(options.revealEditedField !== undefined\n ? { revealEditedField: options.revealEditedField }\n : {}),\n ...(options.debug !== undefined ? { debug: options.debug } : {}),\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.heartbeatMs !== undefined ? { heartbeatMs: options.heartbeatMs } : {}),\n ...(resolved.skipUnchanged !== undefined ? { skipUnchanged: resolved.skipUnchanged } : {}),\n ...(options.scopeBindingsByOwner !== undefined\n ? { scopeBindingsByOwner: options.scopeBindingsByOwner }\n : {}),\n ...(resolved.disableReferrerDetection !== undefined\n ? { disableReferrerDetection: resolved.disableReferrerDetection }\n : {}),\n ...(resolved.disableLocalhostMatching !== undefined\n ? { disableLocalhostMatching: resolved.disableLocalhostMatching }\n : {}),\n ...(resolved.eventSourcePolicy !== undefined\n ? { eventSourcePolicy: resolved.eventSourcePolicy }\n : {}),\n ...(resolved.sanitizerPolicy !== undefined\n ? { sanitizerPolicy: resolved.sanitizerPolicy }\n : {}),\n ...(options.runtime !== undefined ? { runtime: options.runtime } : {}),\n ...(options.fragments !== undefined ? { fragmentEndpoint: options.fragments.endpoint } : {}),\n // Only when no endpoint is configured: that prelude carries the route\n // strategy already, and asking for both would emit the larger one twice.\n ...(options.routeStrategy === true && options.fragments === undefined\n ? { routeStrategy: true }\n : {}),\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 name is carried through exactly here\n ...(options.onUnboundChange !== undefined ? { onUnboundChange: options.onUnboundChange } : {}),\n ...(options.onUnfaithfulPatch !== undefined\n ? { onUnfaithfulPatch: options.onUnfaithfulPatch }\n : {}),\n ...(options.autoBind !== undefined ? { autoBind: options.autoBind } : {}),\n ...(facts.hydration !== undefined ? { hydration: facts.hydration } : {}),\n };\n}\n","/**\n * The Astro integration for `astro.config.mjs`: `livePreview({ ... })`.\n * Inline and loader modes deliver at build time; middleware mode registers\n * the request-time middleware through a serialized options module.\n */\n\nimport { generateInlineScript, generateLoaderScript } from '@inline/generator';\nimport { loaderAsset } from './loader-asset';\nimport { inlineScriptConfig } from '@adapters/shared/policy-options';\nimport type { LivePreviewAstroOptions } from './types';\n\n// Local shims keep `astro` a runtime-optional peer.\ntype ScriptStage = 'head-inline' | 'page' | 'before-hydration' | 'page-ssr';\ninterface VitePluginLike {\n readonly name: string;\n readonly resolveId?: (id: string) => string | undefined;\n readonly load?: (id: string) => string | undefined;\n readonly configureServer?: (server: ViteDevServerLike) => void;\n readonly generateBundle?: (this: RollupEmitContext) => void;\n}\ninterface RollupEmitContext {\n emitFile: (file: { type: 'asset'; fileName: string; source: string }) => void;\n}\ninterface ViteDevServerLike {\n readonly middlewares: {\n use: (handler: (req: DevRequest, res: DevResponse, next: () => void) => void) => void;\n };\n}\ninterface DevRequest {\n readonly url?: string | undefined;\n}\ninterface DevResponse {\n statusCode: number;\n setHeader: (name: string, value: string) => void;\n end: (body?: string) => void;\n}\ninterface AstroConfigSetupContext {\n readonly injectScript: (stage: ScriptStage, content: string) => void;\n readonly addMiddleware?: (entry: { entrypoint: string; order: 'pre' | 'post' }) => void;\n readonly updateConfig?: (config: { vite?: { plugins?: VitePluginLike[] } }) => void;\n /** Astro's configured `base`; absent on versions that do not expose it. */\n readonly config?: { readonly base?: string };\n}\nexport interface AstroIntegrationLike {\n readonly name: string;\n readonly hooks: {\n readonly 'astro:config:setup': (ctx: AstroConfigSetupContext) => void;\n };\n}\n\nconst VIRTUAL_OPTIONS_ID = 'virtual:payload-live-preview/options';\nconst RESOLVED_VIRTUAL_OPTIONS_ID = `\\0${VIRTUAL_OPTIONS_ID}`;\nconst MIDDLEWARE_ENTRYPOINT = 'payload-live-preview/astro/middleware-entry';\n\n/** Build the integration. The injected runtime stays inert outside the admin's preview iframe. */\nexport function livePreview(options: LivePreviewAstroOptions = {}): AstroIntegrationLike {\n return {\n name: 'payload-live-preview',\n hooks: {\n 'astro:config:setup': (ctx): void => {\n if (options.mode === 'middleware') {\n setupMiddlewareMode(ctx, options);\n return;\n }\n if (options.autoInject === false) return;\n if (options.mode === 'loader') {\n setupLoaderMode(ctx, options);\n return;\n }\n ctx.injectScript('head-inline', generateInlineScript(inlineScriptConfig(options)));\n },\n },\n };\n}\n\n/**\n * Loader mode: a bootstrap in every page, the runtime published beside it.\n * One Vite plugin serves the identical bytes from the identical path during\n * `astro dev` (`configureServer`) and in the build (`generateBundle`).\n */\nfunction setupLoaderMode(ctx: AstroConfigSetupContext, options: LivePreviewAstroOptions): void {\n // Without a Vite plugin nothing emits or serves the asset while the bootstrap\n // is injected anyway; that 404 is invisible until an editor opens a preview.\n if (ctx.updateConfig === undefined) {\n throw new Error(\n \"payload-live-preview: mode 'loader' needs Astro's updateConfig hook \" +\n '(Astro >= 4) to publish the runtime asset. Upgrade Astro or use the ' +\n 'default inline mode.',\n );\n }\n\n const asset = loaderAsset(ctx.config?.base ?? '/', options.runtime);\n\n ctx.injectScript(\n 'head-inline',\n generateLoaderScript(inlineScriptConfig(options), {\n runtimeSrc: asset.urlPath,\n integrity: asset.integrity,\n }),\n );\n\n // Emitting through Vite rather than writing from an Astro hook keeps this\n // module free of Node builtins: it is reachable from a browser entry.\n ctx.updateConfig({\n vite: {\n plugins: [\n {\n name: 'payload-live-preview:loader-asset',\n generateBundle() {\n this.emitFile({ type: 'asset', fileName: asset.fileName, source: asset.source });\n },\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n // Path only: a cache-busting query string must still resolve.\n const path = (req.url ?? '').split('?')[0];\n if (path !== asset.urlPath) {\n next();\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/javascript; charset=utf-8');\n // The file changes with the installed package; a stale one is hard to notice.\n res.setHeader('Cache-Control', 'no-cache');\n res.end(asset.source);\n });\n },\n },\n ],\n },\n });\n}\n\nfunction setupMiddlewareMode(ctx: AstroConfigSetupContext, options: LivePreviewAstroOptions): void {\n if (ctx.addMiddleware === undefined || ctx.updateConfig === undefined) {\n throw new Error(\n \"payload-live-preview: mode 'middleware' needs Astro's addMiddleware/updateConfig \" +\n 'hooks (Astro >= 4). Upgrade Astro or use the default inline mode.',\n );\n }\n if (options.authorizePreview !== undefined) {\n throw new Error(\n \"payload-live-preview: `authorizePreview` cannot be used with mode 'middleware' — \" +\n 'options are serialized into the build. Compose `createLivePreviewMiddleware()` ' +\n 'in your own `src/middleware.ts` to pass the hook.',\n );\n }\n if (options.shouldInject !== undefined) {\n throw new Error(\n \"payload-live-preview: `shouldInject` cannot be used with mode 'middleware' — \" +\n 'options are serialized into the build. Use `previewQueryParams`/`previewSignals`, ' +\n 'or register createLivePreviewMiddleware() manually in src/middleware.ts.',\n );\n }\n // Strict needs `authorizePreview`, which cannot serialize: refuse here rather\n // than build cleanly and fail on every preview request.\n const willBeStrict = options.strict ?? options.defaults !== 'v1';\n if (willBeStrict) {\n throw new Error(\n \"payload-live-preview: mode 'middleware' cannot satisfy the 2.0 strict default — it \" +\n 'serializes its options into the build, so it cannot carry the `authorizePreview` ' +\n 'function strict mode requires. Either register ' +\n '`createLivePreviewMiddleware({ authorizePreview, ... })` yourself in src/middleware.ts ' +\n '(recommended: response changes stay gated on a verified context), or pass ' +\n \"`defaults: 'v1'` (or `strict: false`) to run intent-only middleware \" +\n '(ADR 0006 explains why intent is not authorization).',\n );\n }\n\n const { mode: _mode, shouldInject: _shouldInject, ...serializable } = options;\n const optionsModule = `export default ${JSON.stringify(serializable).replace(/</g, '\\\\u003C')};`;\n\n ctx.updateConfig({\n vite: {\n plugins: [\n {\n name: 'payload-live-preview-options',\n resolveId: (id) => (id === VIRTUAL_OPTIONS_ID ? RESOLVED_VIRTUAL_OPTIONS_ID : undefined),\n load: (id) => (id === RESOLVED_VIRTUAL_OPTIONS_ID ? optionsModule : undefined),\n },\n ],\n },\n });\n ctx.addMiddleware({ entrypoint: MIDDLEWARE_ENTRYPOINT, order: 'pre' });\n}\n","/**\n * Content-Security-Policy helpers: nonce generation, directive builders and\n * the header merge every adapter uses. Isomorphic; needs only Web Crypto.\n */\n\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\n\n/** Reads one code unit; an index past the end yields NaN, which matches nothing. */\nfunction isCspWhitespace(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code === 9 || code === 10 || code === 12 || code === 13 || code === 32;\n}\n\n/**\n * Trim CSP whitespace by scanning from both ends.\n *\n * The obvious `/^\\s+|\\s+$/` is superlinear by construction: for a long run the\n * trailing alternative is retried at every position. V8 happens to optimise the\n * shape away, but this header can come from a consumer's own response and this\n * module runs in every engine, so the guarantee has to come from the algorithm\n * rather than from one engine's optimiser.\n */\nfunction trimCspWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && isCspWhitespace(value, start)) start += 1;\n while (end > start && isCspWhitespace(value, end - 1)) end -= 1;\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/** CSP names are ASCII; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/** The one Web Crypto method this module calls; accepts Node's `webcrypto` without a cast. */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/** Supply a Web Crypto implementation for runtimes without `globalThis.crypto`; `null` clears it. @internal */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/** A base64url nonce of `bytes` random bytes (default 16); throws without Web Crypto, since a predictable nonce silently defeats the CSP. @internal */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** A `frame-ancestors` source: `'self'`, `'none'`, or an origin. */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/** The `frame-ancestors` value: `'self'` and the origins, deduplicated; `'none'` when empty. */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * A `script-src` value permitting one nonce plus optional extra sources.\n * `'strict-dynamic'` is opt-in: it makes CSP 3 browsers ignore `'self'` and\n * host sources, so every script on the page must then carry the nonce.\n * @internal\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/** `union` (default) adds sources to an existing directive; `replace` overwrites it. */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header value.\n * Commas separate policies (that is how `Headers.get()` joins repeated\n * headers); each is merged, because a browser enforces every policy and\n * widening only the last would leave the others blocking.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const policies = existing.split(',').filter((policy) => policy.trim().length > 0);\n if (policies.length === 0) return mergeCspPolicy('', additions);\n return policies.map((policy) => mergeCspPolicy(policy, additions)).join(', ');\n}\n\nfunction mergeCspPolicy(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = trimCspWhitespace(part);\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n // CSP3 §2.2.1: a user agent ignores later duplicates, so a looser\n // duplicate must not become the policy that is serialized.\n if (directives.has(name)) continue;\n const value = whitespaceIndex < 0 ? '' : trimCspWhitespace(trimmed.slice(whitespaceIndex));\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * Placing the runtime's script tag inside an HTML document, by text: the\n * adapters see a rendered string or a streamed chunk, never a DOM.\n */\n\n/** The opening `<head>` tag the runtime script is inserted into. */\nexport const HEAD_INSERT = /<head(\\s[^>]*)?>/i;\n\n/** `text/html` with or without parameters. */\nexport const HTML_CONTENT_TYPE = /text\\/html/i;\n\n// Browsers prescan only the first 1024 bytes for the encoding; a script\n// inserted ahead of `<meta charset>` would push it out of that window.\nconst META_CHARSET =\n /<meta\\s+(?:[^>]*\\s)?(?:charset\\s*=|http-equiv\\s*=\\s*[\"']?content-type)[^>]*>/i;\n\n/**\n * `html` with the script tag after `<meta charset>`, else right after\n * `<head>`; `undefined` when there is no `<head>` to insert into.\n */\nexport function injectIntoHead(html: string, scriptTag: string): string | undefined {\n const head = HEAD_INSERT.exec(html);\n if (head === null) return undefined;\n const headEnd = head.index + head[0].length;\n const headClose = html.indexOf('</head', headEnd);\n const meta = META_CHARSET.exec(html.slice(headEnd, headClose === -1 ? undefined : headClose));\n const at = meta === null ? headEnd : headEnd + meta.index + meta[0].length;\n return `${html.slice(0, at)}${scriptTag}${html.slice(at)}`;\n}\n","/**\n * Applying a decision to a fetch-style `Response`, and the request-side\n * glue every adapter repeats: hook binding and the manual script tag.\n */\n\nimport { generateInlineScript, generateLoaderScript, wrapWithScriptTag } from '@inline/generator';\nimport { runtimeAsset } from './runtime-asset';\nimport { HTML_CONTENT_TYPE, injectIntoHead } from './html-inject';\nimport { inlineScriptConfig, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport type { PreviewDecision, PreviewDecisionHooks, PreviewPolicy } from './policy';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The header surface shared by `Headers` and a Node response. */\nexport interface HeaderSink {\n get(name: string): string | null | undefined;\n set(name: string, value: string): void;\n}\n\n/** Bind an adapter's per-request hooks to `request`. */\nexport function bindDecisionHooks<Req>(\n policy: PreviewPolicy,\n options: Pick<PreviewAdapterOptions<Req>, 'authorizePreview' | 'shouldInject'>,\n request: Req,\n): PreviewDecisionHooks {\n return {\n shouldInject: () => options.shouldInject?.(request) ?? true,\n ...(policy.authorizes ? { authorize: () => options.authorizePreview?.(request) } : {}),\n };\n}\n\n/**\n * The script body alone, for a consumer that builds the element itself — a JSX\n * framework cannot render a tag that arrives as a string.\n *\n * The one place delivery is decided, so every adapter answers `delivery:\n * 'asset'` the same way: the bootstrap plus the URL and integrity of whichever\n * artifact was configured, and never the runtime itself.\n */\nexport function renderScriptBody(options: PreviewPolicyOptions, facts: PageFacts = {}): string {\n const config = inlineScriptConfig(options, facts);\n if (options.delivery !== 'asset') return generateInlineScript(config);\n const asset = runtimeAsset(options);\n return generateLoaderScript(config, { runtimeSrc: asset.urlPath, integrity: asset.integrity });\n}\n\n/** The `<script>` tag for manual embedding, with `nonce` when given. */\nexport function renderScriptTag(\n options: PreviewPolicyOptions & { readonly nonce?: string },\n facts: PageFacts = {},\n): string {\n const body = renderScriptBody(options, facts);\n return wrapWithScriptTag(body, options.nonce !== undefined ? { nonce: options.nonce } : {});\n}\n\n/** A changed response must never be stored as the public page, nor shared across sessions. */\nexport function markUncacheable(headers: HeaderSink): void {\n const cacheControl = headers.get('cache-control') ?? '';\n if (!/\\bno-store\\b/i.test(cacheControl)) headers.set('cache-control', 'private, no-store');\n const vary = (headers.get('vary') ?? '').trim();\n const listed = vary.split(',').map((token) => token.trim().toLowerCase());\n if (listed.includes('*') || listed.includes('cookie')) return;\n headers.set('vary', vary.length === 0 ? 'Cookie' : `${vary}, Cookie`);\n}\n\n/**\n * `response` with the script tag in its `<head>`, untouched when it has no\n * body (204/304/HEAD), is not HTML, or has no `<head>`. Headers describing\n * the old body — length, encoding, ETag — are dropped.\n */\nexport async function injectIntoResponse(response: Response, scriptTag: string): Promise<Response> {\n if (response.body === null) return response;\n if (!HTML_CONTENT_TYPE.test(response.headers.get('content-type') ?? '')) return response;\n const injected = injectIntoHead(await response.clone().text(), scriptTag);\n if (injected === undefined) return response;\n const headers = new Headers(response.headers);\n headers.delete('content-length');\n headers.delete('content-encoding');\n headers.delete('etag');\n return new Response(injected, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Run `apply` on the response headers, cloning first when they are immutable (responses passed through from `fetch()`). */\nexport function withHeaders(response: Response, apply: (headers: Headers) => void): Response {\n try {\n apply(response.headers);\n return response;\n } catch {\n const headers = new Headers(response.headers);\n apply(headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n}\n\n/**\n * The header side of a decision on any sink: the merged CSP for its mode,\n * then the cache headers — those also when the mode is off, because an\n * injected body alone already makes the response private.\n */\nexport function applyCspHeaders(\n headers: HeaderSink,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): void {\n const mode = decision.cspMode;\n if (mode !== false) {\n const existing = headers.get('content-security-policy') ?? '';\n headers.set('content-security-policy', policy.csp(existing, nonce, mode));\n }\n markUncacheable(headers);\n}\n\n/** Set the merged CSP header for `mode` and mark the response uncacheable. */\nexport function withCspHeader(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Response {\n return withHeaders(response, (headers) => {\n applyCspHeaders(headers, policy, decision, nonce);\n });\n}\n\n/** Apply a decision end to end: inject, then CSP and cache headers. The response is returned as-is when nothing changes. */\nexport async function applyDecision(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Promise<Response> {\n if (!decision.inject && decision.cspMode === false) return response;\n const injected = decision.inject\n ? await injectIntoResponse(response, policy.scriptTag(nonce))\n : response;\n return withCspHeader(injected, policy, decision, nonce);\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']` — the adapters' option of the same name. */\n readonly allowedOrigins?: readonly string[];\n /** @deprecated Use `allowedOrigins`; removed in 3.0. Ignored when `allowedOrigins` is given. */\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 // The 1.x spelling is honoured until 3.0; the canonical name wins when both are given.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the alias is read exactly here\n const configured = options.allowedOrigins ?? options.adminOrigins ?? [];\n const adminOrigins = signals.has('referer') ? configured : [];\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 * One development warning per process. The set of issued keys lives on\n * `globalThis` so two package copies in one process still warn once.\n */\n\nconst WARNED_KEY = '__payloadLivePreviewDeprecationsWarned';\n\n/** `true` outside a production build; `false` when `NODE_ENV` is production or unknown. */\nexport function isDevelopmentProcess(): boolean {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n if (env === undefined) return false;\n return env['NODE_ENV'] !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Warn once per process for `key`, outside production only. */\nexport function warnOnce(key: string, message: string): void {\n if (!isDevelopmentProcess()) return;\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n const warned = (holder[WARNED_KEY] ??= new Set<string>());\n if (warned.has(key)) return;\n warned.add(key);\n try {\n console.warn(`[payload-live-preview] ${message}`);\n } catch {\n // A console that throws must not break a request.\n }\n}\n\n/** Test hook: forget every warning issued so far. */\nexport function resetDevWarnings(): void {\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n holder[WARNED_KEY] = undefined;\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 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 * Running an `authorizePreview` hook. What the hook may resolve to is\n * normalised here once, so the page policy and the fragment endpoint read the\n * same verdict from the same callback. See ADR 0006.\n */\n\nimport {\n isPreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n} from '@security/preview-verdict';\n// From the leaf `types` domain on purpose: the security module would pull the\n// HMAC and session code into every adapter bundle for a ten-line brand check.\nimport { isAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewAuthorizationHookResult } from './options';\n\n/** A bound hook: the adapter option with the request already applied. */\nexport type BoundAuthorizeHook = () =>\n PreviewAuthorizationHookResult | Promise<PreviewAuthorizationHookResult>;\n\n/**\n * The hook's result as a verdict. Only a context `authorizePreviewRequest()`\n * produced authorizes, bare or inside its verdict; a `{ authorized: true }`\n * literal, a copy, a boolean or nothing refuses as `'invalid'`.\n */\nexport function verdictFrom(result: PreviewAuthorizationHookResult): PreviewAuthorization {\n if (isAuthorizedPreviewContext(result)) {\n return { authorized: true, outcome: 'authorized', context: result };\n }\n if (typeof result === 'object' && result !== null && 'authorized' in result) {\n if (result.authorized && isAuthorizedPreviewContext(result.context)) {\n return { authorized: true, outcome: 'authorized', context: result.context };\n }\n return refused(result.authorized ? 'invalid' : result.outcome);\n }\n // `null`, `undefined`, a boolean, a look-alike literal: refused.\n return refused('invalid');\n}\n\n/**\n * Run a bound hook: a `PreviewConfigurationError` is re-thrown so a\n * misconfigured strategy is loud, any other failure is the `'unavailable'`\n * refusal — an identity provider being down must never authorize.\n */\nexport async function runAuthorizeHook(hook: BoundAuthorizeHook): Promise<PreviewAuthorization> {\n let result: PreviewAuthorizationHookResult;\n try {\n result = await hook();\n } catch (error) {\n if (isPreviewConfigurationError(error)) throw error;\n return refused('unavailable');\n }\n return verdictFrom(result);\n}\n","/**\n * What `strict` refuses at startup, so a misconfiguration fails the process\n * rather than a public response (ADR 0006).\n */\n\nimport { isDevelopmentProcess } from './dev-warning';\nimport { resolvePolicyOptions, type PreviewPolicyOptions } from './policy-options';\n\n/**\n * The sentence every strict refusal ends with.\n *\n * Each of these rules is new in 2.0, and the process that stops is one that\n * worked yesterday. Saying only the rule leaves an upgrader to find out that\n * there is a staged path at all — so the way out is in the message that stops\n * them, not only in the guide they have not opened yet.\n */\nconst STAGED =\n \" New in 2.0; `defaults: 'v1'` keeps the 1.x table while you migrate (docs/migration.md).\";\n\n/** The configuration errors `strict` exists to raise, at startup rather than on a public response. */\nexport function assertStrictConfiguration(options: PreviewPolicyOptions): void {\n if (typeof options.authorizePreview !== 'function') {\n throw new Error(\n 'payload-live-preview: strict mode requires `authorizePreview` — response changes ' +\n 'must be gated on a verified context, not on intent (ADR 0006).' +\n STAGED,\n );\n }\n const origins = options.allowedOrigins ?? [];\n if (origins.length === 0) {\n throw new Error(\n 'payload-live-preview: strict mode requires explicit, non-empty `allowedOrigins`.' + STAGED,\n );\n }\n if (!isDevelopmentProcess()) {\n for (const origin of origins) {\n let protocol: string | undefined;\n try {\n protocol = new URL(origin).protocol;\n } catch {\n protocol = undefined;\n }\n if (protocol !== 'https:') {\n throw new Error(\n `payload-live-preview: strict mode requires https admin origins in production; got \"${origin}\".` +\n STAGED,\n );\n }\n }\n }\n // The resolved signals, not the option: `defaults: 'v1'` fills in `referer`.\n if (resolvePolicyOptions(options).previewSignals?.includes('referer') === true) {\n throw new Error(\n \"payload-live-preview: strict mode disables referrer trust; remove 'referer' from \" +\n \"`previewSignals` (the 'v1' profile includes it).\",\n );\n }\n}\n","/**\n * The preview policy every framework adapter applies: intent, authorization,\n * injection, CSP. Pure — it reads a `{ url, headers.get }` request shape and\n * never touches a response; the adapter translates both ends. See ADR 0006.\n */\n\nimport {\n buildFrameAncestors,\n buildScriptSrcWithNonce,\n generateCspNonce,\n mergeCspHeader,\n} from '@security/csp';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { wrapWithScriptTag } from '@inline/generator';\n// Delivery is decided in one place; the policy caches whatever that produced.\nimport { renderScriptBody } from './response';\nimport { hasPreviewIntent, type PreviewRequestLike } from './preview-request';\nimport { warnOnce } from './dev-warning';\nimport { runAuthorizeHook, type BoundAuthorizeHook } from './authorize-hook';\nimport { resolvePolicyOptions, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport { assertStrictConfiguration } from './strict';\n\nexport type { PreviewAuthorizationHookResult } from './options';\n\n/** How the adapter manages Content-Security-Policy, normalised. */\nexport type CspMode = false | 'frame-ancestors' | 'full';\n\n/** `manageCsp` normalised: unset and `true` both mean frame-ancestors only. */\nexport function normalizeCspMode(value: PreviewPolicyOptions['manageCsp']): CspMode {\n if (value === false) return false;\n if (value === 'full') return 'full';\n return 'frame-ancestors';\n}\n\n/** Whether the request shows preview intent under the options; `inject: 'always'` counts as intent. */\nexport function previewIntentFor(\n request: PreviewRequestLike,\n options: PreviewPolicyOptions,\n): boolean {\n const signals = resolvePolicyOptions(options).previewSignals;\n return (\n (options.inject ?? 'preview-only') === 'always' ||\n hasPreviewIntent(request, {\n ...(options.previewQueryParams !== undefined\n ? { queryParams: options.previewQueryParams }\n : {}),\n ...(signals !== undefined ? { signals } : {}),\n allowedOrigins: options.allowedOrigins ?? [],\n })\n );\n}\n\n/** The CSP header after merging: `frame-ancestors` always, a nonce'd `script-src` only in `'full'` mode. */\nexport function buildPreviewCsp(\n options: PreviewPolicyOptions,\n nonce: string,\n existing: string,\n mode: Exclude<CspMode, false>,\n): string {\n const additions: Record<string, string> = {\n 'frame-ancestors': buildFrameAncestors({\n self: true,\n origins: [...(options.allowedOrigins ?? []), ...(options.frameAncestorsExtra ?? [])],\n }),\n };\n if (mode === 'full') {\n additions['script-src'] = buildScriptSrcWithNonce(nonce, {\n self: true,\n strictDynamic: options.strictDynamic ?? false,\n ...(options.scriptSrcExtra !== undefined ? { extra: options.scriptSrcExtra } : {}),\n });\n }\n return mergeCspHeader(existing, additions);\n}\n\n/** What the policy decided for one request. */\nexport interface PreviewDecision {\n /** The request shows preview intent (or the adapter injects always). */\n readonly isPreview: boolean;\n /** The verified context, or `null` when there was no hook or it refused. */\n readonly authorization: AuthorizedPreviewContext | null;\n /** The hook's verdict, or `undefined` when no hook ran (no intent, or none configured). */\n readonly outcome: PreviewAuthorizationOutcome | undefined;\n /** Intent, authorization, `autoInject` and the adapter's content filter all agreed. */\n readonly inject: boolean;\n /** CSP directives to add, or `false`. Never set without intent, never after a refusal. */\n readonly cspMode: CspMode;\n /** Whether the request-scoped nonce may be handed to templates. */\n readonly exposeNonce: boolean;\n}\n\n/** The per-request hooks an adapter binds to its own request type. */\nexport interface PreviewDecisionHooks {\n /** The adapter's content filter, evaluated lazily once injection is otherwise decided. */\n readonly shouldInject?: () => boolean;\n /** The adapter's `authorizePreview` option, bound to the framework request. Called only on intent. */\n readonly authorize?: BoundAuthorizeHook;\n}\n\n/** A policy bound to one adapter's options. The script body depends on the options only and is built once. */\nexport interface PreviewPolicy {\n /**\n * Decide for a request: `hooks.authorize` runs only on intent, and a\n * `PreviewConfigurationError` from it is re-thrown while any other failure\n * becomes the `'unavailable'` refusal.\n */\n decide(request: PreviewRequestLike, hooks?: PreviewDecisionHooks): Promise<PreviewDecision>;\n /** The `<script>` tag for this policy's runtime, carrying `nonce`. */\n scriptTag(nonce: string): string;\n /** CSP header value for a decision that has a mode. */\n csp(existing: string, nonce: string, mode: Exclude<CspMode, false>): string;\n /** A fresh nonce. */\n nonce(): string;\n /** Whether `authorizePreview` is configured; `decide()` then requires the bound hook. */\n readonly authorizes: boolean;\n}\n\nconst NONE: PreviewDecision = Object.freeze({\n isPreview: false,\n authorization: null,\n outcome: undefined,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n});\n\nexport function createPreviewPolicy(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): PreviewPolicy {\n const resolved = resolvePolicyOptions(options);\n assertMergeDepthExplicit(options);\n const authorizes = typeof options.authorizePreview === 'function';\n if (resolved.strict) {\n assertStrictConfiguration(options);\n } else if (!authorizes) {\n warnOnce(\n 'intent-only-preview',\n 'preview responses are gated on client-controlled intent only. Configure `authorizePreview` ' +\n '(see authorizePreviewRequest) before production; `strict: true` enforces it. ' +\n 'ADR 0006 explains why intent is not authorization.',\n );\n }\n const cspMode = normalizeCspMode(options.manageCsp);\n const autoInject = options.autoInject ?? true;\n let body: string | undefined;\n const scriptBody = (): string => {\n body ??= renderScriptBody(options, facts);\n return body;\n };\n return {\n authorizes,\n async decide(request, hooks = {}) {\n if (authorizes && hooks.authorize === undefined) {\n throw new Error(\n 'payload-live-preview: `authorizePreview` is configured but decide() was called ' +\n 'without an `authorize` hook; bind the hook to the request (bindDecisionHooks).',\n );\n }\n const isPreview = previewIntentFor(request, options);\n if (!isPreview) return NONE;\n let authorization: AuthorizedPreviewContext | null = null;\n let outcome: PreviewAuthorizationOutcome | undefined;\n if (hooks.authorize !== undefined) {\n const verdict = await runAuthorizeHook(hooks.authorize);\n outcome = verdict.outcome;\n if (!verdict.authorized) {\n return {\n isPreview,\n authorization: null,\n outcome,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n };\n }\n authorization = verdict.context;\n }\n return {\n isPreview,\n authorization,\n outcome,\n inject: autoInject && (hooks.shouldInject?.() ?? true),\n cspMode,\n exposeNonce: true,\n };\n },\n scriptTag: (nonce) => wrapWithScriptTag(scriptBody(), { nonce }),\n csp: (existing, nonce, mode) => buildPreviewCsp(options, nonce, existing, mode),\n nonce: () => generateCspNonce(),\n };\n}\n","/** What a decision publishes for templates on `locals` (Astro, SvelteKit) or `event.context` (Nuxt). */\n\nimport { createPreviewBindings, type PreviewBindings } from '@dsl/preview-bindings';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewDecision } from './policy';\n\n/**\n * The keys the adapters publish on the request-scoped context — `Astro.locals`,\n * SvelteKit's `event.locals`, Nuxt's `event.context`. Extend the framework's\n * `App.Locals` with it and templates read them typed. Every key is optional:\n * a refused preview withholds them all, and Next.js has no locals at all.\n */\nexport interface LivePreviewLocals {\n /**\n * The request-scoped CSP nonce, for templates that nonce their own scripts.\n * Set by the Astro middleware (prerendered pages included), the SvelteKit\n * handle and the Nuxt server handler or plugin on every request — except a\n * preview the `authorizePreview` hook refused, which gets no preview artefact.\n */\n readonly livePreviewNonce?: string;\n /** The verified `AuthorizedPreviewContext`. Set only when `authorizePreview` authorized an intent-bearing request. */\n readonly livePreviewAuthorization?: AuthorizedPreviewContext;\n /** The hook's `PreviewAuthorizationOutcome`, refusals included. Set whenever the hook ran: on intent, with `authorizePreview` configured. */\n readonly livePreviewAuthorizationOutcome?: PreviewAuthorizationOutcome;\n}\n\n/** The request-scoped nonce, for templates that nonce their own scripts. @internal */\nexport const NONCE_LOCALS_KEY = 'livePreviewNonce' satisfies keyof LivePreviewLocals;\n\n/** The verified `AuthorizedPreviewContext`; absent unless `authorizePreview` authorized. @internal */\nexport const AUTHORIZATION_LOCALS_KEY =\n 'livePreviewAuthorization' satisfies keyof LivePreviewLocals;\n\n/** The hook's `PreviewAuthorizationOutcome`; absent when no hook ran. @internal */\nexport const AUTHORIZATION_OUTCOME_LOCALS_KEY =\n 'livePreviewAuthorizationOutcome' satisfies keyof LivePreviewLocals;\n\n/**\n * What an adapter needs of a framework's request context: the three keys it\n * writes, and nothing else.\n *\n * This is what the adapters' event types declare rather than\n * `Record<string, unknown>`. A framework's own `App.Locals` is an interface\n * without an index signature, so it is not assignable to a record — which made\n * composing our handle with SvelteKit's `Handle` type fail to compile, even\n * though the values matched. The adapters assign through the interface's own\n * keys, so the published type cannot drift from what the code writes either.\n */\nexport type LivePreviewLocalsSink = {\n -readonly [K in keyof LivePreviewLocals]: LivePreviewLocals[K];\n};\n\n/** Publish the nonce alone — a prerendered page has no request to decide for. */\nexport function exposeNonce(locals: LivePreviewLocalsSink, nonce: string): void {\n locals.livePreviewNonce = nonce;\n}\n\n/** Publish what templates may read; after a refusal the nonce is withheld like every other preview artefact. */\nexport function exposeDecision(\n locals: LivePreviewLocalsSink,\n decision: PreviewDecision,\n nonce: string,\n): void {\n if (decision.exposeNonce || !decision.isPreview) locals.livePreviewNonce = nonce;\n if (decision.authorization !== null) locals.livePreviewAuthorization = decision.authorization;\n if (decision.outcome !== undefined) locals.livePreviewAuthorizationOutcome = decision.outcome;\n}\n\n/**\n * The binding helpers for one request, read straight off whatever the framework\n * calls locals — `Astro.locals`, SvelteKit's `event.locals`, Nuxt's\n * `event.context`.\n *\n * `createPreviewBindings({ authorization: locals.livePreviewAuthorization })`\n * says the same thing, and a template that spells it out is welcome to. This\n * exists because generated code should not have to: the build-time annotator\n * writes one call per component, and a helper that takes `unknown` needs no\n * `App.Locals` declaration in the project it writes into. The verdict is\n * checked, not trusted — only a context `authorizePreviewRequest()` produced\n * emits anything (ADR 0006).\n * @internal\n */\nexport function previewBindingsFromLocals(\n locals: unknown,\n options: { readonly owner?: string } = {},\n): PreviewBindings {\n const value =\n typeof locals === 'object' && locals !== null\n ? (locals as Record<string, unknown>)[AUTHORIZATION_LOCALS_KEY]\n : undefined;\n return createPreviewBindings({\n authorization: (value ?? null) as AuthorizedPreviewContext | null,\n ...(options.owner !== undefined ? { owner: options.owner } : {}),\n });\n}\n","/**\n * Astro middleware: decides before rendering so templates can read\n * `Astro.locals`, then injects into the HTML response and merges CSP.\n * Prerendered pages are skipped — there is no request to decide for at build time.\n */\n\nimport { createPreviewPolicy } from '@adapters/shared/policy';\nimport { applyDecision, bindDecisionHooks } from '@adapters/shared/response';\nimport { exposeDecision, exposeNonce, type LivePreviewLocalsSink } from '@adapters/shared/locals';\nimport type { LivePreviewAstroOptions } from './types';\n\nexport {\n AUTHORIZATION_LOCALS_KEY,\n AUTHORIZATION_OUTCOME_LOCALS_KEY,\n NONCE_LOCALS_KEY,\n type LivePreviewLocals,\n} from '@adapters/shared/locals';\n\n// Local shims keep `astro` a runtime-optional peer; the runtime signature matches.\ntype MiddlewareNext = () => Promise<Response>;\ninterface MiddlewareContext {\n readonly request: Request;\n readonly locals: LivePreviewLocalsSink;\n /** Astro ≥ 5: `true` while prerendering at build time. */\n readonly isPrerendered?: boolean;\n}\nexport type LivePreviewMiddleware = (\n context: MiddlewareContext,\n next: MiddlewareNext,\n) => Promise<Response>;\n\n/** Build the middleware; it publishes the nonce, the context and the outcome on `Astro.locals`. */\nexport function createLivePreviewMiddleware(\n options: LivePreviewAstroOptions = {},\n): LivePreviewMiddleware {\n const policy = createPreviewPolicy(options);\n return async (context, next) => {\n const nonce = policy.nonce();\n if (context.isPrerendered === true) {\n exposeNonce(context.locals, nonce);\n return next();\n }\n const decision = await policy.decide(\n context.request,\n bindDecisionHooks(policy, options, context.request),\n );\n exposeDecision(context.locals, decision, nonce);\n const response = await next();\n if (!decision.isPreview) return response;\n return applyDecision(response, policy, decision, nonce);\n };\n}\n","/**\n * Manual embedding for `.astro` templates, for the cases the integration's\n * automatic injection does not fit (one layout, a conditional).\n */\n\nimport { renderScriptTag } from '@adapters/shared/response';\nimport type { LivePreviewAstroOptions } from './types';\n\nexport interface RenderScriptOptions extends LivePreviewAstroOptions {\n /** CSP nonce for the tag; read it from `Astro.locals.livePreviewNonce`. */\n readonly nonce?: string;\n}\n\n/** The complete `<script>` tag, for `<Fragment set:html={renderLivePreviewScript(...)} />`. */\nexport function renderLivePreviewScript(options: RenderScriptOptions = {}): string {\n return renderScriptTag(options);\n}\n","/**\n * The 1.x names that 2.0 renamed, kept so a 1.x project compiles unchanged.\n *\n * A file of its own, and a small one: everything deprecated for 3.0 that the\n * rename ledger produced lives here, so removing it is one deletion rather than\n * a search. It also keeps the alias out of the module that defines the real\n * function, where two exports of one value read as an accident.\n *\n * Measured against the published 1.8.1 declarations, entry by entry, not\n * guessed: `isPreviewRequest` was exported from the root **and** from\n * `./astro`, so it is re-exported from both. The other seven names 2.0 dropped\n * moved behind `definePreview()` or changed shape, where an alias would restore\n * the very defaults the move removed (ADR 0007, ledger rows 1 and 9).\n */\n\nimport { hasPreviewIntent } from './preview-request';\n\n/**\n * @deprecated Use `hasPreviewIntent`; removed in 3.0. `pll migrate` rewrites it.\n */\nexport const isPreviewRequest = hasPreviewIntent;\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 /**\n * Record `id` as used until `expiresAt` and say whether this call was the\n * first: `true` admits the token, anything else refuses it as `replayed`, a\n * throw refuses it as `unavailable`. Check and record in one step (Redis\n * `SET NX PX`, a unique insert): a read followed by a write lets two requests\n * that carry the same token and arrive together both pass.\n */\n consume(id: string, expiresAt: number): Promise<boolean> | boolean;\n}\n\n/**\n * @deprecated The 1.x store shape, removed in 3.0. Its two calls cannot be one\n * step, so two requests with the same token that arrive together both pass\n * `isUsed` before either reaches `markUsed`. Implement\n * {@link PreviewTokenReplayStore.consume} instead.\n */\nexport interface PreviewTokenReplayChecks {\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 // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape is accepted until 3.0\n readonly replay?: PreviewTokenReplayStore | PreviewTokenReplayChecks;\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 let first: boolean;\n try {\n first = await consumeTokenId(strategy.replay, claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n if (!first) return refused('replayed');\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/**\n * `true` when `id` was not seen before. A store that returns anything but\n * `true` from `consume` refuses the token: fail closed, since a forgotten\n * return would otherwise admit every replay. The 1.x shape keeps its two\n * steps and its race; that is why it is deprecated rather than emulated.\n */\nasync function consumeTokenId(\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape is accepted until 3.0\n store: PreviewTokenReplayStore | PreviewTokenReplayChecks,\n id: string,\n expiresAt: number,\n): Promise<boolean> {\n if ('consume' in store) {\n // The store is consumer code; its answer is a value, not a type.\n const answer: unknown = await store.consume(id, expiresAt);\n return answer === true;\n }\n if (await store.isUsed(id)) return false;\n await store.markUsed(id, expiresAt);\n return true;\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 * 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 // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape exists to be re-exported\n type PreviewTokenReplayChecks,\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","/**\n * The fragment wire protocol: what the browser posts to a fragment endpoint\n * and what it answers. Both sides validate the shape; nothing on the wire\n * names code, paths or templates. See ADR 0011.\n */\n\n/** Bumped when the request or response shape changes incompatibly. @internal */\nexport const FRAGMENT_PROTOCOL_VERSION = 1;\n/** @internal */\nexport const FRAGMENT_VERSION_HEADER = 'x-payload-fragment-version';\n\n/** @internal */\nexport interface FragmentRequestBody {\n /** Registry id of the boundary (`data-payload-fragment`). */\n readonly fragment: string;\n /** `data-payload-fragment-key`, when several boundaries share one id. */\n readonly key?: string;\n /** The page route the boundary belongs to; authorization is bound to it. */\n readonly route: string;\n /** The page's query string, so a `previewToken` in the URL reaches the endpoint. */\n readonly search: string;\n readonly revision: number;\n readonly locale?: string;\n readonly collectionSlug?: string;\n readonly globalSlug?: string;\n /** The unsaved form state as the admin posted it, after the runtime's merge. */\n readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/** @internal */\nexport interface FragmentResponseBody {\n /** The boundary's new inner HTML. */\n readonly html: string;\n readonly boundary: { readonly id: string; readonly key?: string };\n /** Echoes the request; the client discards a response for another revision. */\n readonly revision: number;\n readonly metadata: {\n readonly renderedAt: string;\n /** What rendered it, e.g. `astro-container`. */\n readonly renderer: string;\n readonly durationMs?: number;\n };\n}\n\nconst MAX_FIELD_DEPTH = 12;\n\nfunction depthOf(value: unknown, depth: number): number {\n if (depth > MAX_FIELD_DEPTH || typeof value !== 'object' || value === null) return depth;\n let deepest = depth;\n for (const child of Object.values(value)) {\n deepest = Math.max(deepest, depthOf(child, depth + 1));\n if (deepest > MAX_FIELD_DEPTH) break;\n }\n return deepest;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Shape check for a request body; `null` when it is not one. @internal */\nexport function parseFragmentRequest(value: unknown): FragmentRequestBody | null {\n if (!isRecord(value)) return null;\n const fragment = value['fragment'];\n if (typeof fragment !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/iu.test(fragment)) return null;\n const key = value['key'];\n if (key !== undefined && (typeof key !== 'string' || key.length > 128)) return null;\n const route = value['route'];\n if (typeof route !== 'string' || !route.startsWith('/') || route.length > 2048) return null;\n const search = value['search'];\n if (\n typeof search !== 'string' ||\n search.length > 4096 ||\n (search !== '' && !search.startsWith('?'))\n ) {\n return null;\n }\n const revision = value['revision'];\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 0) return null;\n const slugs: (string | undefined)[] = [];\n for (const name of ['locale', 'collectionSlug', 'globalSlug'] as const) {\n const slug = value[name];\n if (slug === undefined) {\n slugs.push(undefined);\n continue;\n }\n if (typeof slug !== 'string' || slug.length > 128) return null;\n slugs.push(slug);\n }\n const [locale, collectionSlug, globalSlug] = slugs;\n const fields = value['fields'];\n if (!isRecord(fields) || depthOf(fields, 0) > MAX_FIELD_DEPTH) return null;\n return {\n fragment,\n ...(typeof key === 'string' ? { key } : {}),\n route,\n search,\n revision,\n ...(locale !== undefined ? { locale } : {}),\n ...(collectionSlug !== undefined ? { collectionSlug } : {}),\n ...(globalSlug !== undefined ? { globalSlug } : {}),\n fields,\n };\n}\n\n/** Shape check for a response body; `null` when it is not one. @internal */\nexport function parseFragmentResponse(value: unknown): FragmentResponseBody | null {\n if (!isRecord(value)) return null;\n const { html, boundary, revision, metadata } = value;\n if (typeof html !== 'string') return null;\n if (!isRecord(boundary) || typeof boundary['id'] !== 'string') return null;\n if (boundary['key'] !== undefined && typeof boundary['key'] !== 'string') return null;\n if (typeof revision !== 'number') return null;\n if (\n !isRecord(metadata) ||\n typeof metadata['renderedAt'] !== 'string' ||\n typeof metadata['renderer'] !== 'string'\n ) {\n return null;\n }\n return value as unknown as FragmentResponseBody;\n}\n","/**\n * The fragment endpoint, without a component system (ADR 0011): it renders a\n * registered boundary from unsaved form state for an authorized preview, and\n * nothing else. The browser names a registry id; the server decides what that\n * id renders.\n *\n * Everything here is framework-neutral — method and origin checks, the body\n * limit, the protocol, authorization, the registry lookup, the timeouts and the\n * response shape. An adapter binds one renderer to it and exports the result;\n * `src/adapters/astro/fragments.ts` and `src/adapters/nextjs/fragments.ts` are\n * the two, and each is a few dozen lines because this file is the endpoint.\n */\nimport {\n authorizePreviewRequest,\n type PreviewAuthorizationStrategy,\n} from '@security/preview-authorization';\nimport type { PreviewAuthorization } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { runAuthorizeHook } from './authorize-hook';\nimport { warnOnce } from './dev-warning';\nimport type { PreviewAdapterOptions } from './options';\nimport {\n FRAGMENT_PROTOCOL_VERSION,\n FRAGMENT_VERSION_HEADER,\n parseFragmentRequest,\n type FragmentRequestBody,\n type FragmentResponseBody,\n} from '@/types/fragment-protocol';\n\n/** Everything a registry entry may use to compute its props. */\nexport interface FragmentRenderInput {\n readonly id: string;\n readonly key: string | undefined;\n readonly revision: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n readonly route: string;\n readonly authorization: AuthorizedPreviewContext;\n readonly request: Request;\n}\n\n/**\n * `Props extends object`, not `Record<string, unknown>`: an `interface` has no\n * implicit index signature, so the natural way to type a component's props\n * would not satisfy the narrower constraint and every consumer would have to\n * restate their props as a type alias. The renderer widens once, where the\n * props are handed to it.\n */\nexport interface FragmentRegistryEntry<Component, Props extends object = object> {\n readonly component: Component;\n /** Props for the component, computed from the input; never from request-controlled code. */\n readonly props: (input: FragmentRenderInput) => Props | Promise<Props>;\n}\n\nexport type FragmentRegistry<Component> = Readonly<\n Record<string, FragmentRegistryEntry<Component>>\n>;\n\n/** Renders a component with props to HTML. Each adapter supplies its own. */\nexport type FragmentRenderer<Component> = (\n component: Component,\n props: Record<string, unknown>,\n input: FragmentRenderInput,\n) => Promise<string>;\n\nexport interface FragmentEndpointOptions<Component> {\n /** The only things this endpoint can render. */\n readonly registry: FragmentRegistry<Component>;\n /**\n * The middleware's `authorizePreview` hook — same type, same rules: a\n * context `authorizePreviewRequest()` produced authorizes, anything else\n * refuses, a `PreviewConfigurationError` is loud. It is called with the\n * page request the fragment belongs to (route, search, and this request's\n * headers), so a token stays bound to its route and a session is the\n * visitor's own. One of `authorizePreview` and `authorize` is required.\n */\n readonly authorizePreview?: NonNullable<PreviewAdapterOptions['authorizePreview']>;\n /** A strategy for `authorizePreviewRequest()`, when there is no hook to share. Exclusive with `authorizePreview`. */\n readonly authorize?: PreviewAuthorizationStrategy;\n /** Override the adapter's renderer (tests, another component system). */\n readonly render?: FragmentRenderer<Component>;\n /** Origins besides the page's own that may call the endpoint. Default: none. */\n readonly allowedOrigins?: readonly string[];\n readonly limits?: {\n /** Largest request body. Default 64 KiB. */\n readonly bodyBytes?: number;\n /** Render timeout. Default 5000 ms. */\n readonly timeoutMs?: number;\n };\n}\n\n/** What an adapter adds to the consumer's options: its renderer and the name that goes in the response metadata. */\nexport interface FragmentEndpointBinding<Component> {\n readonly render: FragmentRenderer<Component>;\n readonly rendererName: string;\n}\n\nconst DEFAULT_BODY_BYTES = 64 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5_000;\n\nconst NO_STORE_HEADERS: Readonly<Record<string, string>> = {\n 'cache-control': 'private, no-store',\n 'x-content-type-options': 'nosniff',\n vary: 'Cookie',\n [FRAGMENT_VERSION_HEADER]: String(FRAGMENT_PROTOCOL_VERSION),\n};\n\n/** A refusal carries a status and a generic word, never why. */\nfunction refuse(status: number, error: string): Response {\n return new Response(JSON.stringify({ error }), {\n status,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n}\n\nfunction sameOrigin(request: Request, allowed: ReadonlySet<string>): boolean {\n const site = request.headers.get('sec-fetch-site');\n if (site !== null && site !== 'same-origin' && site !== 'none') return false;\n const origin = request.headers.get('origin');\n if (origin === null) return true;\n return origin === new URL(request.url).origin || allowed.has(origin);\n}\n\nfunction scopeAllows(context: AuthorizedPreviewContext, body: FragmentRequestBody): boolean {\n const scope = context.scope;\n if (scope.locale !== undefined && body.locale !== undefined && scope.locale !== body.locale) {\n return false;\n }\n return true;\n}\n\n/**\n * A body that exceeded the limit, as a value no JSON document can be. The two\n * refusals it separates are both in the abuse model (ADR 0011 §4) and both say\n * one generic word: \"413 body\" for a request that was too large to read, and\n * the shape refusal below for one that was read and is not a request. Folding\n * them together answered eight bytes of `not json` with \"Payload Too Large\".\n */\nconst TOO_LARGE = Symbol('body over the limit');\n\n/** The parsed body, `TOO_LARGE` over the limit, or `null` when it is not JSON. */\nasync function readBody(request: Request, limit: number): Promise<unknown> {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > limit) return TOO_LARGE;\n const text = await request.text();\n if (text.length > limit) return TOO_LARGE;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n // Not JSON is not a request: `parseFragmentRequest` refuses `null` as the\n // wrong shape, which is what it is, and no second branch is needed.\n return null;\n }\n}\n\nfunction withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error('fragment render timed out'));\n }, ms);\n work.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timer);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n\ntype FragmentAuthorizer = (pageRequest: Request) => Promise<PreviewAuthorization>;\n\n/** One authorizer from the two options: the hook decides as it does in the middleware, a strategy as `authorizePreviewRequest()` does. */\nfunction authorizerFor<Component>(options: FragmentEndpointOptions<Component>): FragmentAuthorizer {\n const { authorize, authorizePreview } = options;\n if (authorizePreview !== undefined && authorize !== undefined) {\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() takes `authorizePreview` or `authorize`, ' +\n 'not both — pass the middleware hook as `authorizePreview`, or a strategy as `authorize`.',\n );\n }\n if (authorizePreview !== undefined) {\n return (pageRequest) => runAuthorizeHook(() => authorizePreview(pageRequest));\n }\n if (authorize !== undefined) {\n return (pageRequest) => authorizePreviewRequest(pageRequest, authorize);\n }\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() needs `authorizePreview` (the middleware hook) ' +\n 'or `authorize` (a strategy); without one it would render drafts for anyone.',\n );\n}\n\n/**\n * The endpoint as a plain `Request` → `Response` function. Adapters wrap it in\n * whatever their framework hands a route handler.\n */\nexport function createFragmentEndpointHandler<Component>(\n options: FragmentEndpointOptions<Component>,\n binding: FragmentEndpointBinding<Component>,\n): (request: Request) => Promise<Response> {\n const authorize = authorizerFor(options);\n const render = options.render ?? binding.render;\n const rendererName = options.render === undefined ? binding.rendererName : 'custom';\n const allowed = new Set(options.allowedOrigins ?? []);\n const bodyLimit = options.limits?.bodyBytes ?? DEFAULT_BODY_BYTES;\n const timeoutMs = options.limits?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const registry = options.registry;\n\n return async (request) => {\n if (request.method !== 'POST') return refuse(405, 'method');\n if (!sameOrigin(request, allowed)) return refuse(403, 'origin');\n const type = request.headers.get('content-type') ?? '';\n if (!type.toLowerCase().startsWith('application/json')) return refuse(415, 'content-type');\n const raw = await readBody(request, bodyLimit);\n if (raw === TOO_LARGE) return refuse(413, 'body');\n const body = parseFragmentRequest(raw);\n if (body === null) return refuse(400, 'shape');\n\n // Authorize as the page would, so a token stays bound to the route it was\n // issued for and a session is the visitor's own.\n const origin = new URL(request.url).origin;\n const pageRequest = new Request(`${origin}${body.route}${body.search}`, {\n headers: request.headers,\n });\n const authorization = await authorize(pageRequest);\n if (!authorization.authorized || !scopeAllows(authorization.context, body)) {\n return refuse(403, 'unauthorized');\n }\n const entry = Object.prototype.hasOwnProperty.call(registry, body.fragment)\n ? registry[body.fragment]\n : undefined;\n if (entry === undefined) return refuse(404, 'fragment');\n\n const input: FragmentRenderInput = {\n id: body.fragment,\n key: body.key,\n revision: body.revision,\n fields: body.fields,\n locale: body.locale,\n collectionSlug: body.collectionSlug,\n globalSlug: body.globalSlug,\n route: body.route,\n authorization: authorization.context,\n request,\n };\n const started = Date.now();\n let html: string;\n try {\n const props = await withTimeout(Promise.resolve(entry.props(input)), timeoutMs);\n // The one widening: the site types its props as it likes (see\n // FragmentRegistryEntry), the renderer takes a record of them.\n const record = props as Record<string, unknown>;\n html = await withTimeout(render(entry.component, record, input), timeoutMs);\n } catch (error) {\n // The response stays generic; the server log is where the cause belongs,\n // and without it a 500 here is a boundary that silently never renders.\n warnOnce(\n `fragment-render:${body.fragment}`,\n `fragment \"${body.fragment}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n return refuse(500, 'render');\n }\n const response: FragmentResponseBody = {\n html,\n boundary: { id: body.fragment, ...(body.key !== undefined ? { key: body.key } : {}) },\n revision: body.revision,\n metadata: {\n renderedAt: new Date().toISOString(),\n renderer: rendererName,\n durationMs: Date.now() - started,\n },\n };\n return new Response(JSON.stringify(response), {\n status: 200,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n","/**\n * The Astro binding of the fragment endpoint: Astro's container API as the\n * renderer, and the endpoint shaped as an Astro API route. Everything the\n * endpoint decides — authorization, limits, the protocol, the registry lookup —\n * is in `@adapters/shared/fragment-endpoint`.\n */\nimport { lazyPeer, missingPeerError } from '@adapters/shared/optional-peer';\nimport {\n createFragmentEndpointHandler,\n type FragmentEndpointOptions as SharedOptions,\n type FragmentRegistry as SharedRegistry,\n type FragmentRegistryEntry as SharedRegistryEntry,\n type FragmentRenderer as SharedRenderer,\n} from '@adapters/shared/fragment-endpoint';\n\nexport type { FragmentRenderInput } from '@adapters/shared/fragment-endpoint';\n\n/** An Astro component as `import Hero from './Hero.astro'` yields it. */\nexport type AstroComponentLike = object;\n\nexport type FragmentRegistryEntry<Props extends object = object> = SharedRegistryEntry<\n AstroComponentLike,\n Props\n>;\n/** @internal */\nexport type FragmentRegistry = SharedRegistry<AstroComponentLike>;\n/** @internal */\nexport type FragmentRenderer = SharedRenderer<AstroComponentLike>;\nexport type FragmentEndpointOptions = SharedOptions<AstroComponentLike>;\n\nconst RENDERER_NAME = 'astro-container';\n\ninterface ContainerLike {\n renderToString: (\n component: AstroComponentLike,\n options: { props: Record<string, unknown> },\n ) => Promise<string>;\n}\n\n/** One container per process; see `lazyPeer` for what a failed start does. */\nconst loadContainer = lazyPeer(async (): Promise<ContainerLike> => {\n // Through a variable so the bundler leaves it as a runtime import: `astro` is\n // an optional peer, and a project without it must still be able to install\n // this package.\n const specifier = 'astro/container';\n try {\n const astro = (await import(/* @vite-ignore */ specifier)) as {\n experimental_AstroContainer: { create: () => Promise<unknown> };\n };\n return (await astro.experimental_AstroContainer.create()) as ContainerLike;\n } catch (cause) {\n throw missingPeerError(['astro'], cause);\n }\n});\n\nconst renderWithContainer: FragmentRenderer = async (component, props) => {\n const container = await loadContainer();\n return container.renderToString(component, { props });\n};\n\n/** Build the endpoint; export it as the `POST` of a non-prerendered Astro API route. */\nexport function createFragmentEndpoint(\n options: FragmentEndpointOptions,\n): (context: { readonly request: Request }) => Promise<Response> {\n const handler = createFragmentEndpointHandler(options, {\n render: renderWithContainer,\n rendererName: RENDERER_NAME,\n });\n return ({ request }) => handler(request);\n}\n","/**\n * An optional peer dependency, imported the first time it is actually needed.\n *\n * Every fragment binding renders with a component system this package does not\n * install: `astro`, `react`/`react-dom`, `svelte`, `vue`. A project that never\n * registers a fragment — most of them — must still be able to install and run\n * this package, so the import happens at the first render rather than at module\n * load, and always through a variable specifier so a bundler leaves it alone.\n */\n\n/**\n * `load` runs once per process. Callers arriving while it is in flight share\n * that promise; a rejected one is forgotten rather than kept, so a project that\n * installs the package after the first request is not answered from the first\n * bad start for the rest of the process's life.\n */\nexport function lazyPeer<T>(load: () => Promise<T>): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n if (pending === undefined) {\n const started = load();\n pending = started;\n started.catch(() => {\n if (pending === started) pending = undefined;\n });\n }\n return pending;\n };\n}\n\n/**\n * The error a binding throws when its renderer's packages are not installed.\n * The endpoint answers 500 either way; this is what the server log says, and\n * without it the cause reads as \"render failed\".\n */\nexport function missingPeerError(packages: readonly string[], cause: unknown): Error {\n const names = packages.map((name) => `\\`${name}\\``).join(' and ');\n const one = packages.length === 1;\n return new Error(\n `payload-live-preview: this fragment endpoint renders with ${names}, ` +\n `${one ? 'an optional peer' : 'optional peers'} this package does not install. ` +\n `${one ? 'Install it' : 'Install them'}, or pass your own \\`render\\`.`,\n { cause },\n );\n}\n"],"mappings":"AAgBO,SAASA,EAAyBC,GAKvC,GAAyB,OAArBA,EAAQC,UACsB,MAA7BD,EAAQE,WAAa,KAAoC,MAAtBF,EAAQG,WAChD,MAAM,IAAIC,MACR,+OAIJ,CCcO,IAAMC,EAA8CC,OAAOC,OAAO,CACvEC,QAAQ,EACRC,eAAgBH,OAAOC,OAAO,CAAC,YAGpBG,EAA8CJ,OAAOC,OAAO,CACvEI,0BAA0B,EAC1BC,kBAAmB,mBACnBC,eAAe,EACfC,gBAAiB,WAINC,EAA8CT,OAAOC,OAAO,CACvEC,QAAQ,EACRC,eAAgBH,OAAOC,OAAO,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,GAAO,IAAK,SACrB,CACA,MAAM9I,EAAiC,CACrCc,OACAwL,SAAU,CAAErW,GAAI5E,EAAKiX,iBAA2B,IAAbjX,EAAKf,IAAoB,CAAEA,IAAKe,EAAKf,KAAQ,IAChFkY,SAAUnX,EAAKmX,SACf+D,SAAU,CACRC,2BAAA,IAAgBnJ,MAAOoJ,cACvBC,SAAUxB,EACVyB,WAAYtJ,KAAKD,MAAQwG,IAG7B,OAAO,IAAIzJ,SAAS3P,KAAKC,UAAUuP,GAAW,CAC5CI,OAAQ,IACRzG,QAAS,IAAKkP,GAAkB,eAAgB,qCAGtD,CC3NkB+D,CAA8B7e,EAAS,CACrDkd,OAAQT,GACRU,aApCkB,oBAsCpB,MAAO,EAAG7R,aAAcwR,EAAQxR,EAClC,Q","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["assertMergeDepthExplicit","options","defaults","serverURL","mergeDepth","Error","V2_ADAPTER_DEFAULTS","Object","freeze","strict","previewSignals","V2_RUNTIME_DEFAULTS","disableReferrerDetection","eventSourcePolicy","skipUnchanged","sanitizerPolicy","V1_ADAPTER_DEFAULTS","V1_RUNTIME_DEFAULTS","RUNTIME_SOURCE","join","FRAGMENT_SOURCE","ROUTE_SOURCE","LOADER_SOURCE","LOADER_REACT_SOURCE","INLINE_CONFIG_KEYS","assertBuilt","source","artifact","length","generateInlineScript","config","runtime","profile","fragmentEndpoint","routeStrategy","runtimeFor","configStatement","strategyPrelude","profileSlots","map","key","value","JSON","stringify","replace","buildConfigLiteral","generateLoaderScript","target","bootstrap","hydration","loaderFor","runtimeSrc","encode","integrity","wrapWithScriptTag","body","nonce","test","RangeError","assertNonce","normalizePath","path","start","end","trimmed","slice","runtimeAsset","fileName","contentHash","urlPath","assetPath","ASSET_DIR","resolvePolicyOptions","adapter","runtimeRow","disableLocalhostMatching","inlineScriptConfig","facts","resolved","allowedOrigins","apiRoute","revealEditedField","debug","debounceMs","heartbeatMs","scopeBindingsByOwner","fragments","endpoint","onUnboundChange","onUnfaithfulPatch","autoBind","VIRTUAL_OPTIONS_ID","RESOLVED_VIRTUAL_OPTIONS_ID","livePreview","name","hooks","ctx","mode","autoInject","injectScript","updateConfig","asset","base","prefix","loaderAsset","vite","plugins","generateBundle","this","emitFile","type","configureServer","server","middlewares","use","req","res","next","url","split","statusCode","setHeader","setupLoaderMode","addMiddleware","authorizePreview","shouldInject","_mode","_shouldInject","serializable","optionsModule","resolveId","id","load","entrypoint","order","setupMiddlewareMode","CSP_ASCII_WHITESPACE","isCspWhitespace","index","code","charCodeAt","trimCspWhitespace","asciiLowercase","character","toLowerCase","buildFrameAncestors","self","origins","allowNone","seen","Set","out","push","add","origin","trim","has","mergeCspPolicy","existing","additions","directives","Map","part","whitespaceIndex","search","set","rawName","rawAddition","entries","addition","current","get","merged","token","withoutNone","filter","HEAD_INSERT","HTML_CONTENT_TYPE","META_CHARSET","renderScriptBody","delivery","DEFAULT_QUERY_PARAMS","hasPreviewIntent","request","signals","queryParams","URL","param","searchParams","headers","configured","adminOrigins","referer","refererOrigin","adminOrigin","isDevelopmentProcess","env","globalThis","process","warnOnce","message","holder","warned","console","warn","PreviewConfigurationError","refused","outcome","authorized","context","AUTHORIZED_PREVIEW_BRAND_KEY","BRAND","Symbol","for","isAuthorizedPreviewContext","isFrozen","createAuthorizedPreviewContext","fields","scope","payloadHeaders","async","runAuthorizeHook","hook","result","error","isPreviewConfigurationError","verdictFrom","STAGED","NONE","isPreview","authorization","inject","cspMode","exposeNonce","createPreviewPolicy","authorizes","protocol","includes","assertStrictConfiguration","manageCsp","decide","authorize","previewQueryParams","previewIntentFor","verdict","scriptTag","csp","frameAncestorsExtra","buildScriptSrcWithNonce","extra","strictDynamic","parts","e","scriptSrcExtra","policies","policy","mergeCspHeader","buildPreviewCsp","generateCspNonce","bytes","Number","isInteger","String","crypto","fromGlobal","getRandomValues","resolveCrypto","buffer","Uint8Array","binary","byte","fromCharCode","btoa","Buffer","from","toString","replaceAll","base64UrlEncode","NONCE_LOCALS_KEY","AUTHORIZATION_LOCALS_KEY","AUTHORIZATION_OUTCOME_LOCALS_KEY","createLivePreviewMiddleware","isPrerendered","locals","livePreviewNonce","decision","bindDecisionHooks","livePreviewAuthorization","livePreviewAuthorizationOutcome","exposeDecision","response","apply","Headers","Response","status","statusText","withHeaders","cacheControl","vary","listed","markUncacheable","applyCspHeaders","withCspHeader","injected","html","head","exec","headEnd","headClose","indexOf","meta","at","injectIntoHead","clone","text","delete","injectIntoResponse","applyDecision","renderLivePreviewScript","renderScriptTag","cachedEncoder","isPreviewRequest","DEFAULT_USERS_SLUG","COOKIE_NAME_PATTERN","COOKIE_VALUE_PATTERN","encoder","TextEncoder","fromBase64Url","padded","repeat","atob","authorizePreviewRequest","strategy","cookieName","cookieNameFor","serverOriginFor","header","maxLength","values","startsWith","extractCookie","maxCookieLength","now","Date","timeoutMs","Math","max","fetchImpl","fetch","usersSlug","encodeURIComponent","forwarded","cookie","accept","signal","AbortSignal","timeout","ok","json","user","Array","isArray","collection","isFinite","readUser","expiresAt","exp","readExpiry","subject","authorizedAt","authorizeSession","secret","byteLength","secretBytes","candidate","subtle","cryptoFor","transport","kind","getAll","readToken","payloadText","payloadBytes","signature","verified","importKey","hash","hmacKey","verify","claims","parsed","parse","TextDecoder","decode","c","optionalString","parseClaims","iat","aud","audience","pur","purpose","pth","pathname","loc","locale","replay","first","store","consume","isUsed","markUsed","consumeTokenId","jti","sub","authorizeToken","authorizeVerifier","FRAGMENT_VERSION_HEADER","depthOf","depth","deepest","child","isRecord","parseFragmentRequest","fragment","route","revision","slugs","slug","collectionSlug","globalSlug","NO_STORE_HEADERS","refuse","TOO_LARGE","withTimeout","work","ms","Promise","resolve","reject","timer","setTimeout","then","clearTimeout","loadContainer","pending","started","specifier","astro","experimental_AstroContainer","create","cause","packages","names","one","missingPeerError","catch","lazyPeer","renderWithContainer","component","props","renderToString","createFragmentEndpoint","handler","binding","pageRequest","authorizerFor","render","rendererName","allowed","bodyLimit","limits","bodyBytes","registry","method","site","sameOrigin","raw","limit","readBody","Request","scopeAllows","entry","prototype","hasOwnProperty","call","input","record","boundary","metadata","renderedAt","toISOString","renderer","durationMs","createFragmentEndpointHandler"],"sources":["../../../src/types/merge-depth.ts","../../../src/types/defaults-profile.ts","../../../src/inline/runtime.generated.ts","../../../src/inline/fragment.generated.ts","../../../src/inline/route.generated.ts","../../../src/inline/loader.generated.ts","../../../src/inline/loader-react.generated.ts","../../../src/types/inline-config.ts","../../../src/inline/generator.ts","../../../src/adapters/shared/runtime-asset.ts","../../../src/adapters/astro/loader-asset.ts","../../../src/adapters/shared/policy-options.ts","../../../src/adapters/astro/integration.ts","../../../src/security/csp.ts","../../../src/adapters/shared/html-inject.ts","../../../src/adapters/shared/response.ts","../../../src/adapters/shared/preview-request.ts","../../../src/adapters/shared/dev-warning.ts","../../../src/security/preview-verdict.ts","../../../src/types/authorized-preview.ts","../../../src/adapters/shared/authorize-hook.ts","../../../src/adapters/shared/strict.ts","../../../src/adapters/shared/policy.ts","../../../src/adapters/shared/locals.ts","../../../src/adapters/astro/middleware.ts","../../../src/adapters/astro/component.ts","../../../src/adapters/shared/preview-request-legacy.ts","../../../src/security/preview-token.ts","../../../src/security/preview-session.ts","../../../src/security/preview-authorization.ts","../../../src/types/fragment-protocol.ts","../../../src/adapters/shared/fragment-endpoint.ts","../../../src/adapters/astro/fragments.ts","../../../src/adapters/shared/optional-peer.ts"],"sourcesContent":["/**\n * The one rule shared by the adapters, the client and the inline generator:\n * `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults (ADR 0007,\n * entry 10). It lives in the leaf `types` domain because the inline generator\n * is server-side code that may not reach the browser runtime in `core`, and\n * three copies of the check had already drifted in what they treated as\n * \"no server\" and \"no depth\".\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\n/**\n * The population depth is a deliberate choice; the 1.x default of 1 stays only\n * behind `defaults: 'v1'`. An empty `serverURL` fetches nothing and owes no\n * depth; `null` counts as omitted because the inline wire config carries it.\n */\nexport function assertMergeDepthExplicit(options: {\n readonly defaults?: DefaultsProfile | undefined;\n readonly serverURL?: string | undefined;\n readonly mergeDepth?: number | null | undefined;\n}): void {\n if (options.defaults === 'v1') return;\n if ((options.serverURL ?? '') === '' || options.mergeDepth != null) return;\n throw new Error(\n 'payload-live-preview: `serverURL` needs an explicit `mergeDepth` under the 2.0 defaults — ' +\n \"choose the population depth deliberately (0 for none), or pass `defaults: 'v1'` to keep \" +\n 'the 1.x default of 1 while migrating (ADR 0007, entry 10).',\n );\n}\n","/**\n * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts\n * back into the 1.x table for a staged migration. Each row belongs to exactly\n * one side — the adapter's request decision or the browser runtime — and a\n * test asserts the profile assigns every readiness row that has an option, so\n * a row added later cannot be forgotten. See ADR 0007.\n *\n * It lives in the leaf `types` domain, like `merge-depth.ts`, because the\n * inline generator resolves the profile too, and the generator is server-side\n * code that may not reach the browser runtime in `core`.\n */\n\n/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */\nexport type DefaultsProfile = 'v1' | 'v2';\n\n/** How the runtime decides which windows may post updates. */\nexport type EventSourcePolicy = 'any' | 'parent-or-opener';\n\n/** Readiness rows that are options, keyed by the option they set. */\nexport const READINESS_ROWS = Object.freeze({\n strict: 'production response changes require an authorized context',\n previewSignals: 'query-only intent signal',\n disableReferrerDetection: 'referrer trust off',\n eventSourcePolicy: 'messages must come from parent/opener',\n skipUnchanged: 'skip unchanged bindings by default',\n sanitizerPolicy: 'hardened sanitizer id/data-* policy',\n} as const);\n\n/** Options an adapter's request decision reads from the profile. */\nexport interface AdapterProfileDefaults {\n readonly strict: boolean;\n readonly previewSignals: readonly ('query' | 'fetch-dest' | 'referer')[];\n}\n\n/** Options the browser runtime reads from the profile (through the inline configuration). */\nexport interface RuntimeProfileDefaults {\n readonly disableReferrerDetection: boolean;\n readonly eventSourcePolicy: EventSourcePolicy;\n readonly skipUnchanged: boolean;\n readonly sanitizerPolicy: 'compat' | 'strict';\n}\n\nexport const V2_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: true,\n previewSignals: Object.freeze(['query'] as const),\n});\n\nexport const V2_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: true,\n eventSourcePolicy: 'parent-or-opener',\n skipUnchanged: true,\n sanitizerPolicy: 'strict',\n});\n\n/** The 1.x table, spelled out so the profiles compare row by row. */\nexport const V1_ADAPTER_DEFAULTS: AdapterProfileDefaults = Object.freeze({\n strict: false,\n previewSignals: Object.freeze(['query', 'fetch-dest', 'referer'] as const),\n});\n\nexport const V1_RUNTIME_DEFAULTS: RuntimeProfileDefaults = Object.freeze({\n disableReferrerDetection: false,\n eventSourcePolicy: 'any',\n skipUnchanged: false,\n sanitizerPolicy: 'compat',\n});\n\n/** Only an explicit `'v1'` opts out; everything else gets the hardened rows. */\nexport function adapterDefaultsFor(profile: DefaultsProfile | undefined): AdapterProfileDefaults {\n return profile === 'v1' ? V1_ADAPTER_DEFAULTS : V2_ADAPTER_DEFAULTS;\n}\n\nexport function runtimeDefaultsFor(profile: DefaultsProfile | undefined): RuntimeProfileDefaults {\n return profile === 'v1' ? V1_RUNTIME_DEFAULTS : V2_RUNTIME_DEFAULTS;\n}\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport interface RuntimeBuildInfo { readonly generatedAt: string; readonly size: number }\nexport const RUNTIME_SOURCE: string = /* @__PURE__ */ [\"(()=>{function e(e){return(\\\"object\\\"==typeof e&&null!==e||\\\"function\\\"==typeof e)&&\\\"function\\\"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}function n(){}function i(e){return e.onUnfaithfulPatch??(\\\"ignore\\\"===e.onUnboundChange?\\\"ignore\\\":\\\"escalate\\\")}function r(e,t,n,i){if(t.reportedUnfaithful.has(n.element))return;t.reportedUnfaithful.add(n.element),t.unfaithfulCount+=1,t.unfaithfulFields.add(n.fieldName);let r=e.onUnfaithfulPatch;if(\\\"ignore\\\"!==r){if(\\\"warn\\\"===r){e.warn(`[live-preview] LP0411: \\\"${n.fieldName}\\\" ${i}`);return}e.log(\\\"LP0411\\\",n.fieldName,i),t.unfaithfulPatches.push(n)}}function l(e,t){return!e.unfaithfulFields.has(t)&&(e.unfaithfulFields.add(t),e.unfaithfulCount+=1,!0)}function o(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:e.textContent}function a(e){let t=e.trim();return JSON.stringify(t.length>Pn?`${t.slice(0,Pn)}\\\\u2026`:t)}function s(){return function(){if(typ\",\"eof document>\\\"u\\\")return;let e=document.documentElement.getAttribute(\\\"lang\\\");return null===e||0===e.length?void 0:e}()??function(){if(typeof navigator>\\\"u\\\")return;let e=navigator.language;return\\\"string\\\"==typeof e&&e.length>0?e:void 0}()??\\\"en\\\"}function u(e){null!==e.timer&&(clearTimeout(e.timer),e.timer=null),e.messageNode?.remove(),e.messageNode=null}function d(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=c(n);e&&t.push(e)}return t}function c(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e,n=t.name,i=t.type;if(\\\"string\\\"!=typeof n||0===n.length||\\\"string\\\"!=typeof i||0===i.length)return;let r=d(t.fields),l=function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(\\\"object\\\"!=typeof n||null===n)continue;let e=n,i=e.slug;if(\\\"string\\\"!=typeof i||0===i.length)continue;let r=d(e.fields);t.push({...e,slug:i,fields:r})}return t}(t.blocks),o={...t,name:n,type:i};return r.length>0?o.fields=r:delete o.fields,l.length>0?o.blocks=l:delete o.blocks,o}function h(e,t){return void 0===e||t(e)}function f(e,t){return null==e||t(e)}function p(e){if(\\\"object\\\"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}function m(e,t=[]){let n=\\\"number\\\"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,i=Math.min(4,n??1),r=new Set(t),l=new Set;for(let e of Wn)(i>=_n[e].since||r.has(e))&&l.add(e);return{ours:4,...void 0!==n?{theirs:n}:{theirs:void 0},negotiated:i,capabilities:l,observed:r}}function g(e,t){return e.generation===t.generation&&e.revision===t.revision}function v(e){return function(e){if(!1===e.enableA11y)return null;let t=e.root,n=void 0===t?void 0:function(e){return 9===e.nodeType}(t)?t:t.ownerDocument;return new In(e.a11yLocale,n)}(e)}function y(e){if(typ\",\"eof window>\\\"u\\\")return;let t=[];window.parent!==window&&t.push(window.parent),window.opener instanceof Window&&t.push(window.opener),Bn.sendReady(t,e)}function b(e,t=\\\"\\\"){let n=new Map;return w(e,t,n),n}function w(e,t,n){for(let i of e){if(zn.has(i.type)){i.fields&&w(i.fields,t,n);continue}let e=\\\"\\\"===t?i.name:`${t}.${i.name}`;if(n.set(e,i),\\\"group\\\"===i.type)i.fields&&w(i.fields,e,n);else if(\\\"array\\\"===i.type&&i.fields)w(i.fields,`${e}.*`,n);else if(\\\"blocks\\\"===i.type&&i.blocks)for(let t of i.blocks)w(t.fields,`${e}.*.${t.slug}`,n)}}function S(e,t){if(e.has(t))return e.get(t);let n=t.replace(/\\\\.\\\\d+(?=\\\\.|$)/g,\\\".*\\\");return e.has(n)?e.get(n):void 0}function T(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?t:void 0}function k(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.blockType;return\\\"string\\\"==typeof t?t:void 0}function A(e,t){return t.every(e=>void 0!==T(e))?function(e,t){let n=[],i=new Map;for(let t=0;t<e.length;t+=1){let n=T(e[t]);void 0!==n&&i.set(n,t)}let r=new Set;for(let l=0;l<t.length;l+=1){let o=t[l],a=T(o);if(void 0===a){n.push({kind:\\\"insert\\\",index:l,value:o});continue}let s=i.get(a);if(void 0===s){n.push({kind:\\\"insert\\\",index:l,value:o});continue}r.add(s);let u=e[s];k(u)===k(o)?(s!==l&&n.push({kind:\\\"move\\\",from:s,to:l,value:o}),C(u,o)||n.push({kind:\\\"update\\\",index:l,value:o})):n.push({kind:\\\"replace\\\",index:l,oldValue:u,value:o})}for(let t=0;t<e.length;t+=1)r.has(t)||n.push({kind:\\\"remove\\\",index:t,value:e[t]});return n}(e,t):function(e,t){let n=[],i=Math.min(e.length,t.length);for(let r=0;r<i;r+=1)C(e[r],t[r])||n.push({kind:\\\"update\\\",index:r,value:t[r]});if(t.length>e.length)for(let i=e.length;i<t.length;i+=1)n.push({kind:\\\"insert\\\",index:i,value:t[i]});if(e.length>t.length)for(let i=t.length;i<e.length;i+=1)n.push({kind:\\\"remove\\\",index:i,value:e[i]});return n}(e,t)}function C(e,t){if(Object.is(e,t))return!0;if(\\\"object\\\"!=typeof e||\\\"object\\\"!=typeof t||null===e||null===t)return!1;let n=e,i=t,r=Object.keys(n),l=Object.keys(i);if(r.length!==l.length)return!1;for(let e of r)if(!Object.is(n[e],i[e]))return!1;return!0}function $(e){if(\\\"string\\\"!=typeof e)return!1;let t=e.trim().replace(Kn,\\\"\\\");if(0===t.length||Hn.test(t))return!1;if(t.startsWith(\\\"#\\\")||t.startsWith(\\\"?\\\")||qn.test(t)||t.startsWith(\\\"/\\\"))return!0;try{let e=new URL(t);return Vn.has(e.protocol)}catch{return Gn.test(t)}}function R(e){let t=e.trim().replace(Kn,\\\"\\\");return/^https?:\\\\/\\\\//i.test(t)||qn.test(t)}function F(e){return!e.startsWith(\\\"on\\\")&&!Jn.has(e)}function N(e){return Qn.add(e),e}function M(e){switch(typeof e){case\\\"string\\\":return e.length>65536?void 0:`s:${e}`;case\\\"number\\\":return`n:${Object.is(e,-0)?\\\"-0\\\":String(e)}`;case\\\"boolean\\\":return\\\"b:\\\"+(e?\\\"1\\\":\\\"0\\\");case\\\"bigint\\\":return`i:${String(e)}`;case\\\"undefined\\\":return\\\"u\\\";case\\\"object\\\":{if(null===e)return\\\"z\\\";let t;try{t=JSON.stringify(e)}catch{return}return t.length>65536?void 0:`o:${t}`}case\\\"symbol\\\":case\\\"function\\\":return}}function x(e){return e.closest(`[${Yn}]`)}function E(e){let t=e.getAttribute(ei);return null!==t&&t.length>0?\\\"patch\\\"===t||\\\"fragment\\\"===t||\\\"route\\\"===t?t:void 0:null!==x(e)?\\\"fragment\\\":null!==e.closest(\\\"head\\\")?\\\"route\\\":\\\"patch\\\"}function O(e){return`global:${e}`}function P(e,t){return void 0===t||\\\"\\\"===t?`collection:${e}`:`collection:${e}:${t}`}function L(e){return\\\"string\\\"==typeof e&&e.length>0}function U(e,t){return null!==t&&void 0!==e&&t.includes(e)}function I(e){let t=e.id;return\\\"string\\\"==typeof t&&t.length>0?t:\\\"number\\\"==typeof t&&Number.isFinite(t)?String(t):void 0}function j(e,t,n){let i=e.get(t);return void 0!==i&&(!1===n||i.some(e=>U(e.owner,n)))}function _(e,t,n){let i=`${t}.`;for(let[t,r]of e.entries())if(t.startsWith(i)&&(!1===n||r.some(e=>U(e.owner,n))))return!0;return!1}function W(e,t){if(void 0===t||0===t.length)return e;let n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}function B(e,t,n){let i;return r=>{if(j(e,r,n))return!0;let l=W(r,t);return!!(l!==r&&j(e,l,n)||_(e,r,n)||l!==r&&_(e,l,n))||(i??(i=function(e,t){let n=new Set;for(let[i,r]of e.entries())for(let e of r)!1!==t&&!U(e.owner,t)||void 0!==e.locale&&n.add(`${i}_${e.locale}`);return n}(e,n)),i.has(r))}}function z(e,t,n,i,r){return V(n)?!V(t)||function(e,t,n){let i=void 0===n?void 0:S(n,e);return void 0!==i&&!ni.has(i.type)||!0===t.get(e)?.some(D)||_(t,e,!1)}(e,i,r)?\\\"keep\\\":null==t?\\\"ask\\\":\\\"own\\\":\\\"ask\\\"}function D(e){return!ni.has(e.fieldType)}function V(e){return null===e||\\\"object\\\"!=typeof e&&\\\"function\\\"!=typeof e}function H(e){return!0===e?.includes(\\\".\\\")}function G(e){return null!==e&&e.forceRender&&!e.completed}function q(e){try{return!0===e.matchMedia?.(\\\"(prefers-reduced-motion: reduce)\\\").matches}catch{return!1}}function K(...e){let t=new Map;for(let n of e)for(let[e,i]of Object.entries(n)){let n=t.get(e);void 0===n&&(n=new Set,t.set(e,n));for(let e of i)n.add(e)}let n={};for(let[e,i]of t)n[e]=[...i];return n}function J(e,t){let n={};for(let i of t)i!==e&&(n[i]=[e]);return n}function X(e){return\\\"patch\\\"===e.getAttribute(hi)}function Q(e){return function(e){return\\\"astro-island\\\"===e.tagName.toLowerCase()||e.hasAttribute(hi)}(e)&&!X(e)}function Z(e){let t=e.closest(Pi)?.getAttribute(Ri);return null==t||0===t.length?void 0:t}function Y(e){return Ui.has(e)||Li.test(e)}function ee(e){let t=e.getAttribute(mi);if(null!==t&&Y(t))return t;if(e.hasAttribute(ki))return\\\"richText\\\";if(e.hasAttribute(Ai))return\\\"html\\\";if(e.hasAttribute($i))return\\\"structural-array\\\";if(e.hasAttribute(Ci))return\\\"array\\\";if(\\\"IMG\\\"===e.tagName)return\\\"image\\\";if(\\\"A\\\"===e.tagName)return\\\"url\\\";if(\\\"TIME\\\"===e.tagName)return\\\"date\\\";if(\\\"INPUT\\\"===e.tagName){let t=e.type;if(\\\"checkbox\\\"===t)return\\\"checkbox\\\";if(\\\"number\\\"===t)return\\\"number\\\";if(\\\"date\\\"===t||\\\"datetime-local\\\"===t)return\\\"date\\\"}return\\\"text\\\"}function te(){return!0}function ne(e,t){return e.length>0&&e.length<=t&&\\\".\\\"!==e&&\\\"..\\\"!==e&&!e.includes(\\\"/\\\")&&!e.includes(\\\"\\\\\\\\\\\")&&!function(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function ie(e){return ne(e,128)&&!e.includes(\\\"?\\\")&&!e.includes(\\\"#\\\")}function re(e){return e.has(\\\"schema-json\\\")?Wi:e.has(\\\"document-events\\\")||e.has(\\\"relationship-events\\\")?Bi:zi}function le(e){if(e.nodeType!==Di)return!1;let t=e;return t.hasAttribute(pi)||null!==t.querySelector(`[${pi}]`)}function oe(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[Hi]??(e[Hi]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function ae(){let e=oe();if(void 0===e||e.armed)return;e.armed=!0;let t=window,n=t.__REACT_DEVTOOLS_GLOBAL_HOOK__??(t.__REACT_DEVTOOLS_GLOBAL_HOOK__=function(){let e=new Map;return{supportsFiber:!0,renderers:e,inject:t=>{let n=e.size+1;return e.set(n,t),n}}}()),i=n.onCommitFiberRoot;n.onCommitFiberRoot=function(t,n,...r){try{i?.call(this,t,n,...r)}catch{}let l=n?.containerInfo;void 0===e.onCommit?e.commits.push(l):e.onCommit(l)}}function se(e){e.committed=!0;let t=e.waiters;e.waiters=[];for(let e of t)e()}function ue(e,t){let n=e.waiters.indexOf(t);n>=0&&e.waiters.splice(n,1)}function de(e,t,n){if(e.committed)return null;let i=null,r=()=>{null!==i&&clearTimeout(i),i=null,t(\\\"committed\\\")};return e.waiters.push(r),i=setTimeout(()=>{i=null,ue(e,r),t(\\\"timed-out\\\")},n),()=>{null!==i&&clearTimeout(i),i=null,ue(e,r)}}function ce(){if(typ\",\"eof window>\\\"u\\\")return;let e=window;return e[Ki]??(e[Ki]={armed:!1,committed:!1,waiters:[]})}function he(e){return Object.prototype.hasOwnProperty.call(e,qi)?e[qi]:void 0}function fe(){let e=ce();if(void 0===e||e.armed)return;e.armed=!0;let t=Element.prototype;void 0===Object.getOwnPropertyDescriptor(t,qi)&&Object.defineProperty(t,qi,{configurable:!0,get:()=>{},set(e){Object.defineProperty(this,qi,{value:e,writable:!0,configurable:!0,enumerable:!0});let t=ce();void 0===t||t.committed||null===this.querySelector(Gi)||function(e,t){let n=t?.$nuxt;!0!==n?.isHydrating||\\\"function\\\"!=typeof n.hook?se(e):n.hook(Ji,()=>{e.committed||se(e)})}(t,e)}})}function pe(e){if(void 0===e.hydration){e.startNow();return}let t=t=>{e.later(()=>{me(e,t)})},n=\\\"react\\\"===e.hydration?function(e,t=5e3){ae();let n=oe();if(void 0===n)return null;if(void 0===n.onCommit){let e=e=>{!n.committed&&function(e){let t=e;return 9===t?.nodeType||null!=t?.querySelector?.(Gi)}(e)&&se(n)};n.onCommit=e;for(let t of n.commits.splice(0))e(t)}return de(n,e,t)}(t):function(e,t,n=5e3){fe();let i=ce();return void 0===i?null:(!i.committed&&function(e){for(let t=e.querySelector(Gi);null!==t;t=t.parentElement)if(void 0!==he(t))return!0;return!1}(e)&&se(i),de(i,t,n))}(e.root,t);null!==n?(e.defer(n),e.hydrated(\\\"waiting\\\")):me(e,\\\"committed\\\")}function me(e,t){e.hydrated(t),\\\"timed-out\\\"===t&&e.warn(`[live-preview] LP0607: no ${\\\"react\\\"===e.hydration?\\\"React commit\\\":\\\"Vue mount\\\"} in ${String(5e3)} ms; started without waiting for hydration.`),e.startNow()}function ge(e,t=er){if(\\\"string\\\"!=typeof e)return!1;let n=e.trim();return!(n.length<t||nr.test(n)||tr.has(n.toLowerCase())||ir.test(n)||rr.test(n))}function ve(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function ye(e,t,n=er){let i=new Map,r=(e,t,n)=>{i.set(e,i.has(e)?null:{field:t,media:n})};for(let[i,l]of Object.entries(e)){if(ti.has(i))continue;let e=W(i,t);if(ge(l,n))r(l.trim(),e,!1);else if(ve(l))if(\\\"string\\\"==typeof l.url)r(l.url,e,!0);else if(!(\\\"id\\\"in l)&&!(\\\"_id\\\"in l))for(let[t,i]of Object.entries(l))ti.has(t)||!ge(i,n)||r(i.trim(),`${e}.${t}`,!1)}return i}function be(e){if(e.namespaceURI!==or||lr.has(e.tagName)||e.hasAttribute(pi)||e.hasAttribute(Zi)||e.hasAttribute(Yi)||Q(e))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function we(e){let t;for(let n=e.firstChild;null!==n;n=n.nextSibling){if(1===n.nodeType)return;if(3!==n.nodeType)continue;let e=n.data.trim();if(0!==e.length){if(void 0!==t)return;t=e}}return t}function Se(e){return F(e)&&!e.startsWith(\\\"data-payload-\\\")&&\\\"value\\\"!==e}function Te(e,t,n){let i=e.byElement.get(t);void 0===i&&(i={attributes:new Map},e.byElement.set(t,i));let r=e.byField.get(n.field);return void 0===r&&(r=new Set,e.byField.set(n.field,r)),r.add(t),i}function ke(e,t){for(let n=e.firstElementChild;null!==n;n=n.nextElementSibling){if(be(n))continue;let e=we(n),i=void 0===e?void 0:t.values.get(e);null!=i&&!i.media&&(Te(t,n,i).text=i.field);for(let e of n.getAttributeNames()){if(!Se(e))continue;let i=t.values.get(n.getAttribute(e)??\\\"\\\");null!=i&&(i.media&&(\\\"IMG\\\"!==n.tagName||\\\"src\\\"!==e)||Te(t,n,i).attributes.set(e,i))}ke(n,t)}}function Ae(e,t,n){let i=e.tagName;if(void 0!==t){let r={[pi]:t};if(\\\"A\\\"===i){let e=n.get(\\\"href\\\");void 0===e?r[mi]=\\\"text\\\":e!==t&&(r[vi]=e)}return{element:e,fieldName:t,matched:we(e)??\\\"\\\",stamps:r}}if(\\\"IMG\\\"===i){let t=n.get(\\\"src\\\");if(void 0!==t){let i=n.get(\\\"alt\\\");return{element:e,fieldName:t,matched:e.getAttribute(\\\"src\\\")??\\\"\\\",attribute:\\\"src\\\",stamps:{[pi]:t,...void 0!==i&&i!==t?{[bi]:i}:{}}}}}let r=n.entries().next();if(r.done)return;let[l,o]=r.value;return{element:e,fieldName:o,matched:e.getAttribute(l)??\\\"\\\",attribute:l,stamps:{[pi]:o,[gi]:l}}}function Ce(e,t){let n={values:t,byElement:new Map,byField:new Map};t.size>0&&!be(e)&&ke(e,n);let i=e=>1===n.byField.get(e)?.size,r=[];for(let[e,t]of n.byElement){let n=void 0!==t.text&&i(t.text)?t.text:void 0,l=new Map;for(let[e,n]of t.attributes)i(n.field)&&l.set(e,n.field);let o=Ae(e,n,l);void 0!==o&&r.push(o)}return r}function $e(e){return 9===e.nodeType?e.body:e}function Re(e,t,n,i){let r=[];for(let l of t){let{element:t}=l;if(!t.hasAttribute(pi)&&(!1===n||U(Z(t),n))){for(let[e,n]of Object.entries(l.stamps))t.setAttribute(e,n);if(t.setAttribute(xi,l.matched),void 0===e.cache.add(t)){for(let e of Object.keys(l.stamps))t.removeAttribute(e);t.removeAttribute(xi);continue}e.observers.observeElement(t),e.log(\\\"autoBind\\\",l.fieldName,\\\"\\\\u2192\\\",`<${t.tagName.toLowerCase()}>`,l.attribute??\\\"text\\\",JSON.stringify(l.matched),i),r.push(l)}}return r}function Fe(e,t,n,i=!1){if(i&&void 0!==n){let i=Ne(e,`${t}_${n}`);if(void 0!==i)return i}let r=Ne(e,t);if(void 0!==r)return r;if(t.includes(\\\".\\\")){let n=e,i=!0;for(let e of t.split(\\\".\\\")){if(ar.has(e)||null===n||\\\"object\\\"!=typeof n){i=!1;break}if(n=Ne(n,e),void 0===n){i=!1;break}}if(i)return n}return void 0===n?void 0:Ne(e,`${t}_${n}`)}function Ne(e,t){if(!ar.has(t)&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Me(e,t,n,i){return Fe(e,n,t.locale??i,void 0!==t.locale)}function xe(e,t,n,i){let r=M(t);if(void 0===r)return;let l=[e.hrefField,e.srcField,e.altField],o=r;for(let t of l){if(void 0===t||0===t.length)continue;let r=M(Me(n,e,t,i));if(void 0===r)return;o+=`|${t}=${r}`}return o}function Ee(e,t,n,i){let{warned:r,warn:l}=e;r.has(n)||t(n)||(r.add(n),l(`[live-preview] LP0201: no <\\\\u2026 data-payload-field=\\\"${W(n,i)}\\\"> for field \\\"${n}\\\"; render the anchor unconditionally so edits to an empty field have somewhere to land.`))}function Oe(e){let t=typeof e;return\\\"string\\\"===t||\\\"number\\\"===t||\\\"boolean\\\"===t||\\\"bigint\\\"===t}function Pe(e){return\\\"object\\\"==typeof e&&null!==e&&!Array.isArray(e)}function Le(e){let t=function(){if(void 0!==fn)return fn;let e=function(){let e=globalThis.trustedTypes;return\\\"object\\\"!=typeof e||null===e?void 0:\\\"function\\\"==typeof e.createPolicy?e:void 0}();try{fn=void 0===e?null:e.createPolicy(sr,{createHTML:e=>e})}catch{fn=null}return fn}();return null===t?e:t.createHTML(e)}function Ue(e,t){for(let n of t.keyAttributes){let t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function Ie(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(hi)||e.hasAttribute(ur))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return null!==t&&\\\"false\\\"!==t}function je(e,t,n){if(!function(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!Ie(e)&&!Ie(t)}(e,t))return t;let i=function(e){let t=e.ownerDocument.activeElement;return t instanceof HTMLElement&&e.contains(t)?{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}:null}(e);return function(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||dr.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){let i=function(e,t){let n,i=new Map;for(let r of Array.from(e.children)){let e=Ue(r,t);if(void 0!==e){if(i.has(e)){n??(n=e.slice(e.indexOf(\\\"=\\\")+1));continue}i.set(e,r)}}return void 0!==n&&t.onDuplicateKey?.(e,n),i}(e,n),r=new Set(i.values()),l=Array.from(e.childNodes).filter(e=>!r.has(e)),o=new Set,a=new Set,s=Array.from(t.childNodes),u=e.firstChild,d=0;for(let t=0;t<s.length;t+=1){let r=s[t],c=null,h=r instanceof Element?Ue(r,n):void 0;if(void 0!==h&&a.has(h)&&(h=void 0),void 0!==h){a.add(h);let e=i.get(h);if(void 0!==e&&!o.has(e)&&(c=_e(e,r,n)===e?e:null,null===c)){e.replaceWith(r),o.add(r),u=r.nextSibling;continue}}else{for(;d<l.length;){let i=l[d];if(d+=1,!o.has(i)){if(Be(i,r)){c=_e(i,r,n)===i?i:null,null===c&&(e.replaceChild(r,i),o.add(r),u=r.nextSibling);break}if(i instanceof Element){let n=s[t+1];if(!(r instanceof Element)||void 0!==n&&Be(i,n)){d-=1;break}e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}if(!(r instanceof Element)){e.replaceChild(r,i),o.add(r),u=r.nextSibling;break}}}if(null===c&&o.has(r))continue}let f=c??r;for(o.add(f);null!==u&&u!==f&&!o.has(u)&&We(u);)u=u.nextSibling;f!==u&&e.insertBefore(f,u),u=f.nextSibling}for(let t of Array.from(e.childNodes))o.has(t)||t.remove()}(e,t,n),function(e){if(null===e)return;let{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});let[e,i]=n??[null,null];null!==e&&null!==i&&t.setSelectionRange(e,i)}catch{}}(i),e}function _e(e,t,n){return e instanceof Element&&t instanceof Element?Ie(e)&&Ie(t)?e:je(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function We(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??\\\"\\\").trim().length}function Be(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}function ze(e){cr.has(e)||(cr.add(e),function(e){try{console.warn(e)}catch{}}(`[live-preview] LP0409: the strict sanitizer removed \\\\`${e}\\\\` from written markup; the 1.x default (\\\\`sanitizerPolicy: 'compat'\\\\`) kept it. ${function(e){return e.startsWith(hr)?\\\"A binding inside CMS content is refused by design \\\\u2014 an editor could otherwise aim a write at any element on the page (docs/security.md)\\\":\\\"id\\\"===e||\\\"name\\\"===e?\\\"CMS content that can name an element can shadow a global of that name \\\\u2014 DOM clobbering, refused by design (docs/security.md)\\\":\\\"List it in `allowedDataAttributes` if the page needs it, or set `sanitizerPolicy: 'compat'` to keep every `data-*` as 1.x did\\\"}(e)}.`))}function De(e,t,n){let i=Ve();if(!i)throw new Error(\\\"sanitizeHtml needs a DOM\\\");if(\\\"\\\"===e)return\\\"\\\";let r=function(e,t){let n=e?.policy??t??Cr;if(!e){let e=new Map;for(let[t,n]of Object.entries(wr))e.set(t,n);return{allowedTags:fr,attrByTag:e,allowFormControls:!1,templateMode:!1,mode:n,allowedData:new Set}}let i=new Set(fr);if(e.additionalAllowedTags?.forEach(e=>i.add(e)),!0===e.allowFormControls)for(let e of pr)i.add(e);let r=new Map;for(let[e,t]of Object.entries(wr))r.set(e,t);for(let[t,n]of Object.entries(e.additionalAllowedAttributes??{})){let e=new Set(r.get(t));for(let t of n)e.add(t);r.set(t,e)}return{allowedTags:i,attrByTag:r,allowFormControls:!0===e.allowFormControls,templateMode:!0===e.templateMode,mode:n,allowedData:new Set(e.allowedDataAttributes?.map(e=>e.toLowerCase()))}}(n,t),l=i.createElement(\\\"template\\\");return l.innerHTML=Le(e),He(l.content,r),l.innerHTML}function Ve(){if(!(typ\",\"eof document>\\\"u\\\"))return document}function He(e,t){for(let n of Array.from(e.childNodes))n.nodeType===Tr?Ge(n,t):n.nodeType===kr&&n.remove()}function Ge(e,t){let n=e.tagName.toLowerCase();!mr.has(n)||t.allowFormControls&&pr.has(n)?t.allowedTags.has(n)?(function(e,t,n){let i=n.attrByTag.get(t);for(let t of Array.from(e.attributes)){let r=t.name.toLowerCase();if(r.startsWith(\\\"on\\\")||\\\"style\\\"===r)e.removeAttribute(t.name);else{if(\\\"strict\\\"===n.mode){if(n.templateMode&&Ar.has(r))continue;if(\\\"id\\\"===r||\\\"name\\\"===r||r.startsWith(br)){e.removeAttribute(t.name),(\\\"name\\\"!==r||!0===i?.has(r))&&ze(r);continue}if(r.startsWith(yr)){n.allowedData.has(r)||(e.removeAttribute(t.name),ze(r));continue}if(gr.has(r)||r.startsWith(vr))continue}else if(gr.has(r)||r.startsWith(vr)||r.startsWith(yr))continue;i?.has(r)?(Sr.has(r)&&!$(t.value)||\\\"srcset\\\"===r&&!qe(t.value))&&e.removeAttribute(t.name):e.removeAttribute(t.name)}}}(e,n,t),\\\"a\\\"===n&&function(e){let t=e.getAttribute(\\\"href\\\");null===t||!R(t)||(e.setAttribute(\\\"rel\\\",\\\"noopener noreferrer\\\"),e.hasAttribute(\\\"target\\\")||e.setAttribute(\\\"target\\\",\\\"_blank\\\"))}(e),He(e,t)):(He(e,t),e.replaceWith(...e.childNodes)):e.remove()}function qe(e){for(let t of e.split(\\\",\\\")){let e=t.trim();if(0===e.length)continue;let[n=e]=e.split(/\\\\s/,1);if(!$(n))return!1}return!0}function Ke(e){return e.replace(Rr,e=>$r[e])}function Je(e){return e.replace(Nr,e=>Fr[e])}function Xe(e){let t=new Set;for(let n of e)if(\\\"object\\\"==typeof n&&null!==n)for(let e of Object.keys(n))t.add(e);return t}function Qe(e,t,n,i,r){let l=\\\"object\\\"==typeof t&&null!==t?t:null;return e.replace(Mr,(e,o)=>null!==l&&function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(l,o)?Ke(i(Reflect.get(l,o))):null===l&&\\\"value\\\"===o?Ke(i(t)):\\\"index\\\"===o?String(n):null!==l&&!0===r?.has(o)?\\\"\\\":e)}function Ze(e){let t=e.children,n=t[0];if(void 0===n)return[];let i=[];for(let{name:e,value:r}of Array.from(n.attributes)){if(!F(e)||e.startsWith(xr))continue;let n=!0;for(let i=1;i<t.length&&n;i+=1)n=t[i]?.getAttribute(e)===r;n&&i.push([e,r])}return i}function Ye(e,t){for(let[n,i]of t)e.hasAttribute(n)||e.setAttribute(n,i)}function et(e){if(null==e)return\\\"\\\";if(\\\"string\\\"==typeof e)return e;if(\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e||\\\"bigint\\\"==typeof e)return String(e);try{return JSON.stringify(e)}catch{return\\\"\\\"}}function tt(e){return null==e||\\\"\\\"===e}function nt(e,t){let n=e.get(t);return void 0!==n&&(e.delete(t),e.set(t,n)),n}function it(e,t,n,i){return e.set(t,n),function(e,t){for(let n of e.keys()){if(e.size<=t)break;e.delete(n)}}(e,i),n}function rt(e){let t=nt(Ur,e);if(void 0!==t)return t;let n=new Set(Er);for(let t of e.matchAll(Pr)){let e=t[1]?.toLowerCase();void 0!==e&&n.add(e)}let i={};for(let e of n)i[e]=Or;let r={additionalAllowedTags:[...n],additionalAllowedAttributes:i,allowFormControls:!0,templateMode:!0};return it(Ur,e,r,Lr)}function lt(e){let t=at(e.container,e.patches,e);return null===t?null:st(t,e.store,{morph:e.morph??!0,onDuplicateKey:e.onDuplicateKey})}function ot(e,t){return t.hasAttribute(jr)&&t.hasAttribute(_r)}function at(e,t,n){let i=function(e,t,n){let{template:i,nextItems:r,forceRender:l=!1,store:o,sanitizerPolicy:a}=n,s=o.get(e),u=Ze(e),d=Xe(r),c=Array.from(e.children),h=mt(c,Ir),f=new Set,p=[];for(let o=0;o<r.length;o+=1){let m=r[o],g=pt(m),v=void 0===g?c[o]??null:gt(h,g)??null;null!==v&&f.has(v)&&(v=null),null!==v&&f.add(v);let y=t.replaces.has(o),b=l||t.renders.has(o)||null===v?vt(e.ownerDocument,i,m,o,a,u,d):void 0;if(null===b)return null;let w=void 0===b?[]:ut(y?null:v,b,m,void 0===g?void 0:s?.get(g),n);if(null===w)return null;p.push([o,v,b,w,y])}return p}(e,function(e){let t=new Set,n=new Set;for(let i of e)\\\"insert\\\"===i.kind||\\\"update\\\"===i.kind?t.add(i.index):\\\"replace\\\"===i.kind&&(t.add(i.index),n.add(i.index));return{renders:t,replaces:n}}(t),n);return null===i?null:[e,i,n.nextItems]}function st(e,t,n){let[i,r,l]=e,o=new Set,a=!1;for(let[e,l,s,u,d]of r){let r=l;if(void 0!==s){let e=!(!n.morph||d||null===l)&&je(l,s,{keyAttributes:[Ir,jr],retainChildrenOf:ot,...void 0!==n.onDuplicateKey?{onDuplicateKey:n.onDuplicateKey}:{}})===l;if(!e)for(let[e,t]of u)null!==e&&(ct(e,t),t.replaceWith(e));for(let[,,e]of u)void 0!==e&&st(e,t,n);e?a=!0:(null!==l&&(l.replaceWith(s),a=!0),r=s)}if(null===r)continue;let c=i.children[e]??null;r!==c&&(i.insertBefore(r,c),a=!0),o.add(r)}for(let e of Array.from(i.children))o.has(e)||(e.remove(),a=!0);let s=function(e,t){let n=t.get(e);return n||(n=new Map,t.set(e,n)),n}(i,t);s.clear();for(let e of l)ft(s,e);return a}function ut(e,t,n,i,r){let l=mt(null===e?[]:dt(e),jr),o=[];for(let e of dt(t)){let t=e.getAttribute(jr);if(null===t)continue;let a,s=gt(l,t)??null,u=e.getAttribute(_r),d=u?s:null,c=d?.getAttribute(_r)??null;if(u){let l=ht(n,t);if(void 0!==l||null!==d){let n=l??[],o=A(null===d?[]:ht(i,t)??[],n),s=null!==d&&c!==u;if((o.length>0||s)&&(a=at(d??e,o,{template:u,nextItems:n,forceRender:s,store:r.store,sanitizerPolicy:r.sanitizerPolicy})??void 0,void 0===a))return null}}o.push([d,e,a])}return o}function dt(e){return Array.from(e.querySelectorAll(`[${jr}]`)).filter(t=>{let n=t.parentElement;for(;null!==n&&n!==e;){if(n.hasAttribute(jr))return!1;n=n.parentElement}return n===e})}function ct(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function ht(e,t){if(\\\"object\\\"!=typeof e||null===e)return;let n=e[t];return Array.isArray(n)?n:void 0}function ft(e,t){let n=pt(t);void 0!==n&&e.set(n,t)}function pt(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function mt(e,t){let n=new Map;for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(void 0===r)continue;let l=r.getAttribute(t);if(null===l)continue;let o=n.get(l);void 0===o?n.set(l,[r]):o.push(r)}return n}function gt(e,t){return e.get(t)?.pop()}function vt(e,t,n,i,r,l,o){let a=De(Qe(t,n,i,et,o),r,rt(t)),s=e.createElement(\\\"template\\\");s.innerHTML=Le(a);let u=s.content.firstElementChild;if(!u)return null;Ye(u,l);let d=pt(n);return void 0!==d&&u.setAttribute(Ir,d),u}function yt(e,t){let n=new Set(t);return{boundaries:t,strategy:e,covers:e=>void 0!==e.fragmentBoundary&&n.has(e.fragmentBoundary)}}function bt(t,n,i,r,l){let o=t.transformValue;if(void 0===o)return i;try{let t=o(n.fieldName,i,{element:n.element,allFields:r},l),a=e(t);if(!l())return i;if(a)throw new TypeError(`Transform for \\\"${n.fieldName}\\\" returned a thenable; transforms must be synchronous`);return t}catch(e){if(!l())return i;let n=e instanceof Error?e:new Error(String(e));return t.emitter.emit(\\\"error\\\",{error:n,context:\\\"transform\\\",code:\\\"LP0602\\\"}),i}}function wt(e){return 9===e.nodeType}function St(e){return e.body}function Tt(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function kt(e){let t=e.trim();if(0!==t.length)try{let e=new URL(t);return\\\"http:\\\"!==e.protocol&&\\\"https:\\\"!==e.protocol||!qr.test(e.origin)?void 0:e.origin}catch{return}}function At(e){let t=e.format;return\\\"string\\\"==typeof t&&Zr.has(t)?t:\\\"number\\\"==typeof t?Qr[t]:void 0}function Ct(e){let t=e.indent;return\\\"number\\\"==typeof t&&t>0?t:0}function $t(e){return\\\"rtl\\\"===e.direction?' dir=\\\"rtl\\\"':\\\"ltr\\\"===e.direction?' dir=\\\"ltr\\\"':\\\"\\\"}function Rt(e){let t=At(e),n=Ct(e),i=[];return void 0!==t&&i.push(`lp-align-${t}`),n>0&&i.push(`lp-indent-${String(n)}`),0===i.length?\\\"\\\":` class=\\\"${i.join(\\\" \\\")}\\\"`}function Ft(e){return\\\"object\\\"==typeof e&&null!==e?e:void 0}function Nt(e){return Ft(e)}function Mt(e){return e.replace(/[^a-zA-Z0-9_-]/g,\\\"-\\\").toLowerCase()}function xt(e){return\\\"string\\\"==typeof e&&e.length>0?e:void 0}function Et(e){let t=xt(e.title)??xt(e.name)??xt(e.slug);return void 0!==t?t:void 0===e.id?void 0:String(e.id)}function Ot(e){if(\\\"string\\\"==typeof e.text)return e.text;if(!e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Ot(n);return t}function Pt(e){return`${\\\"number\\\"==typeof e.width?` width=\\\"${String(e.width)}\\\"`:\\\"\\\"}${\\\"number\\\"==typeof e.height?` height=\\\"${String(e.height)}\\\"`:\\\"\\\"}`}function Lt(e){return\\\"string\\\"==typeof e.mimeType?` type=\\\"${Je(e.mimeType)}\\\"`:\\\"\\\"}function Ut(e){return nl.get(e)}function It(e,t,n,i){let r=Ft(e.fields)??{},l=\\\"string\\\"==typeof r.blockType?r.blockType:\\\"\\\",o=Mt(l),a=\\\"\\\"===o?i:`${i} ${i}--${o}`;if(\\\"\\\"!==l){let e=Ut(l)??Ut(o);if(e)return e(r,{renderChildren:t.renderChildren});t.onUnrenderedBlock?.(l,a)}return`<${n} class=\\\"${a}\\\"></${n}>`}function jt(e,t){return\\\"number\\\"==typeof t&&t>1?` ${e}=\\\"${String(t)}\\\"`:\\\"\\\"}function _t(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&\\\"children\\\"in t&&Array.isArray(t.children)}function Wt(e,t){let n=function(e){return ll.get(e)??rl[e]}(e.type);return n?n(e,t):void 0!==e.children?t.renderChildren(e.children):\\\"\\\"}function Bt(e){if(\\\"string\\\"==typeof e.text)return e.text;if(\\\"linebreak\\\"===e.type)return\\\"\\\\n\\\";if(void 0===e.children)return\\\"\\\";let t=\\\"\\\";for(let n of e.children)t+=Bt(n);return t}function zt(e=\\\"text\\\"){let t=new WeakSet;return{name:e,render:N((e,n)=>{let i=e.element,r=function(e){return null==e?\\\"\\\":_t(e)?function(e){return _t(e)?e.root.children.map(Bt).join(\\\"\\\\n\\\").trim():\\\"\\\"}(e):\\\"string\\\"==typeof e?e:\\\"number\\\"==typeof e||\\\"boolean\\\"==typeof e?String(e):JSON.stringify(e)}(n);if(\\\"INPUT\\\"!==i.tagName&&\\\"TEXTAREA\\\"!==i.tagName){if(function(e){return null!==e.querySelector(\\\":scope > :not(br)\\\")}(i)&&!i.hasAttribute(al))return function(e,t,n){e.has(t)||(e.add(t),kn(`[live-preview] LP0402: Skipping text update for \\\"${n}\\\": <${t.tagName.toLowerCase()}> has structured children. Move data-payload-field to the value element, or add data-payload-text to replace them.`))}(t,i,e.fieldName),!1;r.includes(\\\"\\\\n\\\")||r.includes(\\\"\\\\r\\\")?i.innerHTML=Le(function(e){return Ke(e).replace(/\\\\r\\\\n|\\\\r|\\\\n/g,\\\"<br>\\\")}(r)):i.textContent=r}else i.value=r})}}function Dt(e,t){let n=e.cloneNode(!1);n.innerHTML=Le(t);let i=function(e,t){let n=e.firstElementChild;if(null!==n?.nextElementSibling||t.children.length<2||!dl.has(n.tagName)||n.hasAttribute(pi))return null;for(let e of t.children)if(e.tagName===n.tagName&&e.className===n.className)return null;return n}(e,n)??e,r=new Map,l=n.querySelectorAll(il);if(l.length>0&&null!==i.firstElementChild){let e=[];Vt(i,n,e);for(let[t,n]of e)t.replaceWith(n),n.matches(il)||r.set(t.className,!1);for(let e of l)null!==e.parentNode&&r.set(e.className,!0)}return i.replaceChildren(...n.childNodes),r}function Vt(e,t,n){if(e.children.length!==t.children.length)return;let i=e.firstElementChild,r=t.firstElementChild;for(;null!==i&&null!==r;)r.matches(il)?n.push([r,i]):Vt(i,r,n),i=i.nextElementSibling,r=r.nextElementSibling}function Ht(e,t,n,i){i&&t.reportUnfaithful?.(e,`lost the markup the server drew for block \\\"${n}\\\"`);let r=i?ul:sl;r.has(n)||(r.add(n),kn(`[live-preview] ${i?`LP0413: no renderer for block \\\"${n}\\\", and the markup the server rendered for it is lost.`:`LP0410: no renderer for block \\\"${n}\\\"; keeping what the server rendered for it.`} Register one with registerBlockRenderer().`))}function Gt(e,t,n){return\\\"string\\\"!=typeof n||0===n.length?{kind:\\\"none\\\"}:$(n)?{kind:\\\"safe\\\",url:n}:(fl.has(e)||(fl.add(e),kn(`[live-preview] LP0401: refused an unsafe URL for \\\"${t}\\\" on <${e.tagName.toLowerCase()}>; the attribute was cleared.`)),{kind:\\\"unsafe\\\"})}function qt(e,t=e=>e){return{name:e,render(e,n,i){let r=e.element;if(tt(n)){!function(e){\\\"INPUT\\\"!==e.tagName&&\\\"TEXTAREA\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):e.value=\\\"\\\"}(r);return}let l=et(n);if(\\\"INPUT\\\"!==r.tagName&&\\\"TEXTAREA\\\"!==r.tagName){if(\\\"A\\\"===r.tagName){let n=e.hrefField,o=void 0===n||0===n.length?t(l):Fe(i.allFields,n,i.locale,void 0!==e.locale),a=Gt(r,e.fieldName,o);\\\"safe\\\"===a.kind?r.setAttribute(\\\"href\\\",a.url):\\\"unsafe\\\"===a.kind&&r.removeAttribute(\\\"href\\\")}r.textContent=l}else r.value=l}}}function Kt(e){for(let t of vl)e.removeAttribute(t)}function Jt(e,t,n){e.src=t;let i=function(e){if(void 0===e?.sizes)return;let t=[];for(let n of Object.values(e.sizes))\\\"string\\\"!=typeof n.url||\\\"number\\\"!=typeof n.width||!$(n.url)||t.push(`${Xt(n.url)} ${String(n.width)}w`);return 0!==t.length?(\\\"number\\\"==typeof e.width&&\\\"string\\\"==typeof e.url&&$(e.url)&&t.push(`${Xt(e.url)} ${String(e.width)}w`),t.join(\\\", \\\")):void 0}(n);void 0!==i?e.setAttribute(\\\"srcset\\\",i):(e.removeAttribute(\\\"srcset\\\"),e.removeAttribute(\\\"sizes\\\"))}function Xt(e){return e.replace(/[\\\\s,]/g,encodeURIComponent)}function Qt(e){\\\"IMG\\\"===e.tagName?Kt(e):e.style.backgroundImage=\\\"\\\"}function Zt(e){\\\"IMG\\\"!==e.tagName?(e.removeAttribute(\\\"href\\\"),e.textContent=\\\"\\\"):Kt(e)}function Yt(e){let t=Ft(e);return void 0===t?et(e):Et(t)??\\\"\\\"}function en(e,t){let n=e??\\\"\\\";if(null==t)return n;let i=tn(t);return\\\"{}\\\"===i?n:`${n}|${i}`}function tn(e){if(null===e||\\\"object\\\"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>tn(e)).join(\\\",\\\")}]`;let t=e,n=Object.keys(t).sort(),i=[];for(let e of n){let n=t[e];void 0!==n&&i.push(`${JSON.stringify(e)}:${tn(n)}`)}return`{${i.join(\\\",\\\")}}`}function nn(e){return{kind:\\\"date\\\",options:e}}function rn(e){return{kind:\\\"number\\\",options:e}}function ln(e,t,n,i){if(void 0===t||\\\"\\\"===t)return;let r=function(e){let t=e.indexOf(\\\":\\\"),n=-1===t?e:e.slice(0,t),i=-1===t?void 0:e.slice(t+1);switch(n){case\\\"date\\\":return void 0===i?nn({dateStyle:\\\"medium\\\"}):$l.has(i)?nn({dateStyle:i}):void 0;case\\\"time\\\":return void 0===i?nn({timeStyle:\\\"short\\\"}):Rl.has(i)?nn({timeStyle:i}):void 0;case\\\"datetime\\\":return void 0===i?nn({dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"}):$l.has(i)?nn({dateStyle:i,timeStyle:\\\"short\\\"===i?\\\"short\\\":\\\"medium\\\"}):void 0;case\\\"number\\\":return void 0===i?rn({}):Nl.test(i)?rn({minimumFractionDigits:Number(i),maximumFractionDigits:Number(i)}):void 0;case\\\"currency\\\":return void 0!==i&&Fl.test(i)?rn({style:\\\"currency\\\",currency:i.toUpperCase()}):void 0;case\\\"percent\\\":return void 0===i?rn({style:\\\"percent\\\"}):void 0;default:return}}(t);if(void 0!==r)return r.kind===e?r.options:void 0;!function(e,t,n){Ml.has(e)||(Ml.add(e),kn(`[live-preview] LP0408: data-payload-format=\\\"${n}\\\" on \\\"${t}\\\" is not a known format; the default formatting was used. Known: date, date:short|medium|long|full, time, datetime, number, number:0-4, currency:XXX, percent.`))}(n,i,t)}function on(e){return String(e).padStart(2,\\\"0\\\")}function an(){let e=new WeakMap,t=new WeakSet,n=new WeakMap,i=new WeakMap;return{name:\\\"structural-array\\\",render:N((r,l,o)=>{let a=tt(l)?[]:l;if(!Array.isArray(a))return!1;let s=r.element,u=r.arrayTemplate;if(void 0===u||0===u.length)return function(e,t,n){e.has(t)||(e.add(t),kn(`[live-preview] LP0403: Skipping structural update for \\\"${n}\\\": <${t.tagName.toLowerCase()} data-payload-structural> needs data-payload-array-template (for example \\\"<li>{{label}}</li>\\\").`))}(t,s,r.fieldName),!1;let d=e.get(s),c=sn(s),h=d?.values??function(e){return e.map((e,t)=>null===e?{__payloadDomPosition:t}:{id:e})}(c),f=A(h,a),p=function(e,t,n){return void 0===e||e.template!==t||!function(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}(e.domSnapshot,n)}(d,u,c);if(0===f.length&&!p)return e.set(s,{values:a.slice(),template:u,domSnapshot:c}),!1;!function(e,t,n,i,r){let l=r.map(un),o=new Set,a=l.find(e=>!(void 0===e||!o.has(e)&&(o.add(e),1)));if(void 0!==a&&dn(e,t,n,a),l.some(e=>void 0===e)&&cn(e,t,\\\"LP0404\\\",`LP0404: an item of \\\"${n}\\\" has no id and pairs by position, so an insert re-renders every row after it. Give items a stable id.`),i?.length===r.length&&r.length>1){let r=new Set(i.map(un).filter(e=>void 0!==e)),o=l.some(e=>void 0!==e&&r.has(e));r.size>0&&!o&&cn(e,t,\\\"LP0406\\\",`LP0406: every key of \\\"${n}\\\" changed at once; the source generates ids per message, so no item can be retained across updates.`)}}(n,s,r.fieldName,d?.values,a);let m=lt({template:u,container:s,patches:f,nextItems:a,store:i,forceRender:p,sanitizerPolicy:o.sanitizerPolicy,onDuplicateKey:(e,t)=>{dn(n,e,r.fieldName,t)}});return null!==m&&(e.set(s,{values:a.slice(),template:u,domSnapshot:sn(s)}),!!m&&void 0)})}}function sn(e){return Array.from(e.children,e=>e.getAttribute(Ir))}function un(e){if(\\\"object\\\"!=typeof e||null===e)return;let t=e.id;return\\\"string\\\"==typeof t||\\\"number\\\"==typeof t?String(t):void 0}function dn(e,t,n,i){cn(e,t,\\\"LP0405\\\",`LP0405: two items of \\\"${n}\\\" share the key \\\"${i}\\\"; later ones pair by position. Make \\\\`id\\\\` unique per item.`)}function cn(e,t,n,i){let r=e.get(t);void 0===r&&(r=new Set,e.set(t,r)),!r.has(n)&&(r.add(n),kn(`[live-preview] ${i}`))}function hn(){return typeof __LIVE_PREVIEW_CONFIG__>\\\"u\\\"?[]:__LIVE_PREVIEW_CONFIG__}var fn,pn=Object.defineProperty,mn=e=>{throw TypeError(e)},gn=(e,t,n)=>((e,t,n)=>t in e?pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,\\\"symbol\\\"!=typeof t?t+\\\"\\\":t,n),vn=(e,t,n)=>t.has(e)||mn(\\\"Cannot \\\"+n),yn=(e,t,n)=>(vn(e,t,\\\"read from private field\\\"),n?n.call(e):t.get(e)),bn=(e,t,n)=>t.has(e)?mn(\\\"Cannot add the same private member more than once\\\"):t instanceof WeakSet?t.add(e):t.set(e,n),wn=(e,t,n,i)=>(vn(e,t,\\\"write to private field\\\"),i?i.call(e,n):t.set(e,n),n),Sn=(e,t,n)=>(vn(e,t,\\\"access private method\\\"),n),Tn=t((...e)=>console.error(...e)),kn=t((...e)=>console.warn(...e)),An=t((...e)=>console.debug(...e)),Cn=class{constructor(){bn(this,Fn);bn(this,$n,new Map);bn(this,Rn,new Map)}on(e,t){return Sn(this,Fn,Mn).call(this,yn(this,$n),e,t)}once(e,t){return Sn(this,Fn,Mn).call(this,yn(this,Rn),e,t)}off(e,t){Sn(this,Fn,xn).call(this,yn(this,$n),e,t),Sn(this,Fn,xn).call(this,yn(this,Rn),e,t)}async emit(e,t){await Sn(this,Fn,Nn).call(this,e,t)}async emitWhile(e,t,n){return Sn(this,Fn,Nn).call(this,e,t,n)}listenerCount(e){return(yn(this,$n).get(e)?.size??0)+(yn(this,Rn).get(e)?.size??0)}removeAllListeners(e){void 0!==e?(yn(this,$n).delete(e),yn(this,Rn).delete(e)):(yn(this,$n).clear(),yn(this,Rn).clear())}eventNames(){let e=new Set;for(let t of yn(this,$n).keys())e.add(t);for(let t of yn(this,Rn).keys())e.add(t);return[...e]}},$n=new WeakMap,Rn=new WeakMap,Fn=new WeakSet,Nn=async function(e,t,n){let i=()=>n?.()??!0;if(!i())return!1;let r=yn(this,$n).get(e);if(r)for(let n of[...r])if(!i()||(await Sn(this,Fn,En).call(this,n,t,e),!i()))return!1;if(!i())return!1;let l=yn(this,Rn).get(e);if(l&&l.size>0){let n=[...l];yn(this,Rn).delete(e);for(let r of n)if(!i()||(await Sn(this,Fn,En).call(this,r,t,e),!i()))return!1}return i()},Mn=function(e,t,n){let i=e.get(t);return i||(i=new Set,e.set(t,i)),i.add(n),()=>{Sn(this,Fn,xn).call(this,e,t,n)}},xn=function(e,t,n){let i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))},En=async function(e,t,n){try{await e(t)}catch(e){let t=\\\"string\\\"==typeof n||\\\"number\\\"==typeof n?String(n):\\\"<event>\\\";Tn(`[live-preview] LP0601: handler for \\\"${t}\\\" threw:`,e)}},On=new Set([\\\"date\\\",\\\"number\\\",\\\"checkbox\\\"]),Pn=40,Ln=\\\"payload-live-preview-a11y\\\",Un=new WeakMap,In=class{constructor(e,t){gn(this,\\\"german\\\");gn(this,\\\"document\\\");gn(this,\\\"lease\\\",null);let n=t??(typ\",\"eof document>\\\"u\\\"?null:document),i=n?.documentElement.getAttribute(\\\"lang\\\")??\\\"\\\";this.german=function(e){return/^de(?:[-_]|$)/i.test(e)}(e??(i.length>0?i:s())),this.document=n}mount(){let e=this.document;if(null==e?.body)return null;this.lease??(this.lease=function(e){let t=Un.get(e);return void 0===t&&(t={element:null,owned:!1,messageNode:null,refs:0,timer:null},Un.set(e,t)),t.refs+=1,t}(e));let t=this.lease,n=t.element;if(n?.isConnected&&n.ownerDocument===e)return n;if(null!==n){let e=t.owned;u(t),e&&n.remove()}let i=e.getElementById(Ln);return t.owned=null===i,null===i&&(i=e.createElement(\\\"div\\\"),i.id=Ln,i.setAttribute(\\\"role\\\",\\\"status\\\"),i.setAttribute(\\\"aria-live\\\",\\\"polite\\\"),i.setAttribute(\\\"aria-atomic\\\",\\\"true\\\"),i.setAttribute(\\\"style\\\",\\\"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0\\\"),e.body.appendChild(i)),t.element=i,i}announceConnected(){this.say(this.german?\\\"Vorschau verbunden\\\":\\\"Live preview connected\\\")}announceDisconnected(){this.say(this.german?\\\"Vorschau getrennt\\\":\\\"Live preview disconnected\\\")}announceUpdate(e){e<=0||this.say(this.german?`${String(e)} ${1===e?\\\"\\\\xc4nderung\\\":\\\"\\\\xc4nderungen\\\"} angewendet`:`${String(e)} ${1===e?\\\"change\\\":\\\"changes\\\"} applied`)}detach(){let e=this.lease,t=this.document;if(null===e||null===t||(this.lease=null,e.refs-=1,e.refs>0))return;let n=e.element;null!==n&&u(e),e.owned&&n?.remove(),e.element=null,Un.delete(t)}say(e){let t=this.mount(),n=this.lease;if(null===t||null===n)return;let i=n.messageNode;i?.parentNode!==t?(i?.remove(),i=t.ownerDocument.createTextNode(t.hasChildNodes()?` ${e}`:e),n.messageNode=i,t.appendChild(i)):i.data=null===i.previousSibling?e:` ${e}`,null!==n.timer&&clearTimeout(n.timer);let r=setTimeout(()=>{n.timer===r&&n.element===t&&u(n)},1500);n.timer=r}},jn=[\\\"data\\\",\\\"fieldSchemaJSON\\\",\\\"globalSlug\\\",\\\"collectionSlug\\\",\\\"locale\\\",\\\"ready\\\",\\\"previewToken\\\",\\\"protocolVersion\\\"],_n={basic:{since:1},\\\"schema-json\\\":{since:2,observed:\\\"schema\\\"},locale:{since:2,observed:\\\"locale\\\"},\\\"preview-token\\\":{since:3,observed:\\\"preview-token\\\"},\\\"nested-arrays\\\":{since:4},\\\"recursive-diffs\\\":{since:4},\\\"document-events\\\":{since:4,observed:\\\"document-event\\\"},\\\"relationship-events\\\":{since:4,observed:\\\"relationship-event\\\"}},Wn=Object.keys(_n),Bn=class{constructor(e,t){gn(this,\\\"matcher\\\");gn(this,\\\"handlers\\\");gn(this,\\\"boundListener\\\");gn(this,\\\"attachedTarget\\\");gn(this,\\\"generation\\\",0);gn(this,\\\"revision\\\",0);gn(this,\\\"queueHead\\\");gn(this,\\\"queueTail\\\");this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1,n=i=>{if(!t||this.boundListener!==n)return;let r=this.generation;try{this.receive(i,r,e)}catch{let e;try{e=i.origin}catch{e=\\\"\\\"}this.reportInvalid(\\\"shape\\\",e,r)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=n;try{e.addEventListener(\\\"message\\\",n)}catch(t){this.boundListener===n&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener(\\\"message\\\",n)}catch{}throw t}if(this.boundListener===n)t=!0;else try{e.removeEventListener(\\\"message\\\",n)}catch{}}detach(){let e=this.attachedTarget,t=this.boundListener;void 0===e||void 0===t||(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener(\\\"message\\\",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}static sendReady(e,t){let n={type:\\\"payload-live-preview\\\",ready:!0,protocolVersion:4};for(let i of e)for(let e of t)try{i.postMessage(n,e)}catch{}}receive(e,t,n){let i=e.origin;if(!this.matchesOrigin(i,t)){this.reportInvalid(\\\"origin\\\",i,t);return}if(!this.matchesSource(e,n)){this.reportInvalid(\\\"source\\\",i,t);return}let r=e.data;if(function(e){return\\\"object\\\"==typeof e&&null!==e&&\\\"type\\\"in e&&\\\"string\\\"==typeof e.type}(r))switch(r.type){case\\\"payload-live-preview\\\":if(!function(e){let t=e;return!(void 0!==t.data&&null!==t.data&&!p(t.data))&&f(t.fieldSchemaJSON,e=>Array.isArray(e))&&f(t.globalSlug,e=>\\\"string\\\"==typeof e)&&f(t.collectionSlug,e=>\\\"string\\\"==typeof e)&&f(t.locale,e=>\\\"string\\\"==typeof e)&&f(t.ready,e=>\\\"boolean\\\"==typeof e)&&f(t.previewToken,e=>\\\"string\\\"==typeof e)&&f(t.protocolVersion,e=>\\\"number\\\"==typeof e)}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.dispatchUpdate(function(e){let t={...e};for(let e of jn)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);if(!Array.isArray(t.fieldSchemaJSON))return t;let n;try{n=d(t.fieldSchemaJSON)}catch{n=[]}return{...t,fieldSchemaJSON:n}}(r),i,t);return;case\\\"payload-document-event\\\":if(!function(e){let t=e;return h(t.action,e=>\\\"updated\\\"===e||\\\"created\\\"===e||\\\"deleted\\\"===e)&&h(t.slug,e=>\\\"string\\\"==typeof e)&&h(t.id,e=>\\\"string\\\"==typeof e||Number.isFinite(e))}(r)){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onDocumentEvent,r,i);return;case\\\"payload-live-preview-focus\\\":{let e=function(e){let t=e.field;return\\\"string\\\"==typeof t&&t.length>0?t:void 0}(r);if(void 0===e){this.reportInvalid(\\\"shape\\\",i,t);return}this.invokeHandler(t,this.handlers.onFocusField,e,i);return}default:this.reportInvalid(\\\"type\\\",i,t)}else this.reportInvalid(\\\"shape\\\",i,t)}dispatchUpdate(e,t,n){let i=p(e.data);if(!this.isCurrentGeneration(n))return;let r=i?{generation:n,revision:this.revision+=1}:void 0,l=this.handlers.validateToken;if(!this.isCurrentGeneration(n))return;if(void 0===l){this.commitUpdate(e,t,n,r);return}if(!0===e.ready&&void 0===e.data){this.commitUpdate(e,t,n,void 0);return}let o={generation:n,message:e,origin:t,messageRevision:r,verdict:void 0,next:void 0};this.enqueue(o);let a;try{a=l(e.previewToken,t)}catch{this.settleValidation(o,!1);return}\\\"boolean\\\"!=typeof a?Promise.resolve(a).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,a)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){let t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid(\\\"token\\\",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid(\\\"origin\\\",t.origin,t.generation)}}}commitUpdate(e,t,n,i){void 0===i?this.invokeHandler(n,this.handlers.onUpdate,e,t):this.invokeHandler(n,this.handlers.onUpdate,e,t,i)}reportInvalid(e,t,n){this.invokeHandler(n,this.handlers.onInvalid,e,t)}matchesSource(e,t){if(\\\"parent-or-opener\\\"!==this.handlers.sourcePolicy)return!0;try{let n=e.source;if(\\\"object\\\"!=typeof n||null===n)return!1;let i=t.parent;return i!==t&&n===i||n===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(t,n,...i){if(void 0!==n&&this.isCurrentGeneration(t))try{e(n(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}},zn=new Set([\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\"]),Dn={text:\\\"text\\\",textarea:\\\"textarea\\\",richText:\\\"richText\\\",email:\\\"email\\\",number:\\\"number\\\",checkbox:\\\"checkbox\\\",date:\\\"date\\\",select:\\\"select\\\",radio:\\\"radio\\\",array:\\\"array\\\",blocks:\\\"blocks\\\",group:\\\"text\\\",tabs:\\\"text\\\",row:\\\"text\\\",collapsible:\\\"text\\\",relationship:\\\"relationship\\\",upload:\\\"upload\\\",point:\\\"text\\\",json:\\\"text\\\",code:\\\"text\\\",ui:\\\"text\\\"},Vn=new Set([\\\"http:\\\",\\\"https:\\\",\\\"mailto:\\\",\\\"tel:\\\"]),Hn=/^\\\\s*(?:javascript|data|vbscript|file|blob|about)\\\\s*:/i,Gn=/^(?:\\\\.{1,2}\\\\/|[a-zA-Z0-9_-]+\\\\/?)/,qn=/^[\\\\\\\\/]{2}/,Kn=/[\\\\t\\\\n\\\\r]/g,Jn=new Set([\\\"style\\\",\\\"srcdoc\\\",\\\"formaction\\\",\\\"form\\\",\\\"id\\\",\\\"name\\\",\\\"is\\\",\\\"srcset\\\",\\\"imagesrcset\\\"]),Xn=new Set([\\\"href\\\",\\\"src\\\",\\\"poster\\\",\\\"cite\\\",\\\"action\\\",\\\"xlink:href\\\",\\\"data\\\"]),Qn=new WeakSet,Zn=class{constructor(){gn(this,\\\"previous\\\",null)}diff(e,t){let n=this.previous,i=null===n,r=new Map,l=new Set;for(let[t,i]of Object.entries(e)){let e=M(i);r.set(t,e),(null===n||void 0===e||n.get(t)!==e)&&l.add(t)}if(null!==n)for(let e of n.keys())r.has(e)||l.add(e);this.previous=r;let o=new Set;for(let[e,n]of Object.entries(t))if(l.has(e))for(let e of n)o.add(e);return{changed:l,invalidated:o,baseline:i}}reset(){this.previous=null}},Yn=\\\"data-payload-fragment\\\",ei=\\\"data-payload-strategy\\\",ti=new Set([\\\"id\\\",\\\"_id\\\",\\\"createdAt\\\",\\\"updatedAt\\\",\\\"createdBy\\\",\\\"updatedBy\\\",\\\"_status\\\",\\\"globalType\\\",\\\"collection\\\",\\\"locale\\\",\\\"localized\\\"]),ni=new Set([\\\"text\\\",\\\"textarea\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"point\\\",\\\"code\\\",\\\"json\\\",\\\"ui\\\",\\\"html\\\"]),ii={},ri=class{constructor(){gn(this,\\\"rawChanges\\\",new Zn);gn(this,\\\"resolved\\\",null);gn(this,\\\"queued\\\",null);gn(this,\\\"pending\\\",null);gn(this,\\\"timer\\\",null);gn(this,\\\"openUntil\\\",0)}decide(e,t){let n=t.message.data??{},{changed:i}=this.rawChanges.diff(n,ii);if(!function(e){let{cache:t,emitter:n}=e;if(t.islands.length>0||n.listenerCount(\\\"beforeUpdate\\\")>0||n.listenerCount(\\\"afterUpdate\\\")>0)return!0;for(let e of t.values())if(D(e)||e.fieldName.includes(\\\".\\\")||H(e.hrefField)||H(e.srcField)||H(e.altField))return!0;return void 0!==e.strategies.fragment&&null!==e.root.querySelector(`[${Yn}]`)}(e))return{merge:!1,fields:n};let r=this.resolved;if(null===r)return this.resolved=n,{merge:!0,fields:n};let l={...r},o=t.forceRender;for(let a of i){let i=n[a];if(ti.has(a)){l[a]=i;continue}let s=z(a,r[a],i,e.cache,t.schemaIndex);\\\"own\\\"!==s&&(o=!0),\\\"keep\\\"!==s&&(l[a]=i)}return this.resolved=l,{merge:o,fields:l}}request(e,t,n){let i=Date.now();return i>=this.openUntil?(this.dropQueued(),this.openUntil=i+t,{leading:!0,result:e.merge(n)}):(this.queued=n,this.openUntil=i+t,this.pending??(this.pending=function(){let e;return{promise:new Promise(t=>{e=t}),settle:e}}()),null!==this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.flush(e)},t),{leading:!1,result:this.pending.promise})}recordMerged(e){this.resolved=e}destroy(){this.dropQueued(),this.openUntil=0}dropQueued(){null!==this.timer&&clearTimeout(this.timer),this.timer=null,this.queued=null,this.pending?.settle({status:\\\"superseded\\\"}),this.pending=null}flush(e){let t=this.pending,n=this.queued;this.timer=null,this.pending=null,this.queued=null,null!==t&&null!==n&&e.merge(n).then(t.settle,()=>{t.settle({status:\\\"unavailable\\\"})})}},li=class{constructor(){gn(this,\\\"negotiation\\\",m(void 0));gn(this,\\\"observed\\\",new Set)}observe(e,t){let n=e.filter(e=>!this.observed.has(e));if(0!==n.length){for(let e of n)this.observed.add(e);this.negotiation=m(this.negotiation.theirs,this.observed),t(\\\"protocol\\\",`observed=${n.join(\\\",\\\")}`)}}applyVersion(e,t){let n=this.negotiation;if(n.theirs===e)return;let i=m(e,this.observed);this.negotiation=i,i.negotiated!==n.negotiated&&t(\\\"protocol\\\",\\\"ours=4\\\",`theirs=${e}`,`negotiated=${i.negotiated}`)}},oi=class{constructor(){gn(this,\\\"lastIdentity\\\")}edit(e){let t=e.externallyUpdatedRelationship;if(\\\"object\\\"!=typeof t||null===t)return null;let n=JSON.stringify([t.entitySlug,I(t),t.updatedAt]),i=n!==this.lastIdentity;return this.lastIdentity=n,i&&function(e,t){let n=t.globalSlug??t.collectionSlug;if(\\\"string\\\"!=typeof n||e.entitySlug!==n)return!0;let i=I(e),r=I(t.data??{});return void 0!==i&&void 0!==r&&i!==r}(t,e)?t:null}},ai=class{constructor(){bn(this,si)}reveal(e,t,n){return e===yn(this,si)?\\\"skipped-same\\\":(wn(this,si,e),function(e,t){return function(e,t){let n=e.getBoundingClientRect(),i=n.bottom>0&&n.top<t.innerHeight,r=n.right>0&&n.left<t.innerWidth;return i&&r}(e,t)?\\\"already-visible\\\":(e.scrollIntoView({behavior:q(t)?\\\"auto\\\":\\\"smooth\\\",block:\\\"center\\\"}),\\\"revealed\\\")}(t,n))}reset(){wn(this,si,void 0)}},si=new WeakMap,ui=class{constructor(){gn(this,\\\"seen\\\",new Map)}note(e,t,n){let i=M(n);if(void 0===i)return;let r=`${t.owner??\\\"\\\"}\\\\0${t.locale??\\\"\\\"}\\\\0${t.fieldName}`,l=this.seen.get(r);void 0!==l?l!==i&&(e.revealIdentities.push([r,i]),e.revealTarget??(e.revealTarget=t)):this.seen.set(r,i)}commit(e){for(let[t,n]of e.revealIdentities)this.seen.set(t,n);e.revealIdentities=[];let t=e.revealTarget;return e.revealTarget=void 0,t}},di=class{constructor(){gn(this,\\\"started\\\",!1);gn(this,\\\"suspended\\\",!1);gn(this,\\\"deferredStart\\\",null);gn(this,\\\"hydration\\\",\\\"idle\\\");gn(this,\\\"activeUpdate\\\",null);gn(this,\\\"locale\\\");gn(this,\\\"schema\\\");gn(this,\\\"schemaIndex\\\");gn(this,\\\"updateCount\\\",0);gn(this,\\\"supersededCount\\\",0);gn(this,\\\"completedCount\\\",0);gn(this,\\\"skippedUnchangedCount\\\",0);gn(this,\\\"lastFlush\\\",null);gn(this,\\\"absentFields\\\",new Set);gn(this,\\\"warnedOrphanFields\\\",new Set);gn(this,\\\"warnedStrategy\\\",new WeakSet);gn(this,\\\"warnedUnattributableMessage\\\",!1);gn(this,\\\"warnedVisibilityGate\\\",!1);gn(this,\\\"warnedFragmentFallback\\\",!1);gn(this,\\\"warnedProtocolShape\\\",!1);gn(this,\\\"reportedUnfaithful\\\",new WeakSet);gn(this,\\\"checkedServerFormat\\\",new WeakSet);gn(this,\\\"unfaithfulPatches\\\",[]);gn(this,\\\"unfaithfulCount\\\",0);gn(this,\\\"escalatedCount\\\",0);gn(this,\\\"unfaithfulFields\\\",new Set);gn(this,\\\"autoBindSearchMs\\\");gn(this,\\\"autoBindGuesses\\\",null);gn(this,\\\"warnedForeignSource\\\",!1);gn(this,\\\"lastAppliedIdentity\\\",new WeakMap);gn(this,\\\"revealLedger\\\",new ui);gn(this,\\\"fragmentStats\\\",{rendered:0,failed:0,superseded:0});gn(this,\\\"routeStats\\\",{refreshes:0,failed:0,refused:0,loopStopped:0});gn(this,\\\"fragmentController\\\",null);gn(this,\\\"routeController\\\",null);gn(this,\\\"routeRetry\\\",null);gn(this,\\\"readyTimers\\\",[]);gn(this,\\\"revealer\\\",new ai);gn(this,\\\"changes\\\",new Zn);gn(this,\\\"merges\\\",new ri);gn(this,\\\"protocol\\\",new li);gn(this,\\\"relationships\\\",new oi)}isRunning(){return this.started}isCurrent(e){return this.started&&this.activeUpdate===e}complete(e){e.completed||(e.completed=!0,this.completedCount+=1)}abortStrategies(){null!==this.routeRetry&&(clearTimeout(this.routeRetry),this.routeRetry=null);for(let e of[\\\"fragmentController\\\",\\\"routeController\\\"]){let t=this[e];null!==t&&(this[e]=null,t.abort())}}},ci=class{constructor(e,t){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"instanceContext\\\");this.instanceContext=function(e){let t={};for(let[n,i]of Object.entries(e))void 0!==i&&(t[n]=i);return t}({renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,reportUnfaithful:(n,i)=>{r(e,t,n,i)}})}apply(e){let{deps:t,state:n}=this,i=n.activeUpdate;if(null===i||void 0===e.revision||!g(i.revision,e.revision)||!n.isCurrent(i))return!1;let{target:l,value:s}=e,u=void 0!==i.schemaIndex?S(i.schemaIndex,l.fieldName):void 0,d=function(e,t){if(e.explicitFieldType)return e.fieldType;if(void 0!==t){let e=function(e){if(Object.prototype.hasOwnProperty.call(Dn,e))return Dn[e]}(t);if(void 0!==e)return e}return e.fieldType}(l,u?.type);\\\"text\\\"===d&&!0!==l.explicitFieldType&&function(e){if(\\\"object\\\"!=typeof e||null===e||!(\\\"root\\\"in e))return!1;let t=e.root;return\\\"object\\\"==typeof t&&null!==t&&Array.isArray(t.children)}(s)&&(d=\\\"richText\\\");let c;try{c=t.resolveRenderer(d,l)}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;let h=t.emitter.listenerCount(\\\"elementUpdate\\\")>0,f=h?function(e){return\\\"INPUT\\\"===e.tagName||\\\"TEXTAREA\\\"===e.tagName?e.value:\\\"IMG\\\"===e.tagName?e.src:e.textContent}(l.element):void 0;if(!n.isCurrent(i))return!1;let p={allFields:e.allFields,locale:l.locale??i.locale,schema:u,...this.instanceContext};!0===l.hidesWhenEmpty&&l.element.toggleAttribute(\\\"hidden\\\",function(e){return null==e||(\\\"string\\\"==typeof e?0===e.trim().length:Array.isArray(e)&&0===e.length)}(s));try{if(void 0!==l.targetAttribute){if(\\\"blocked\\\"===function(e,t,n){let i=t.toLowerCase().trim();if(0===i.length||!F(i))return\\\"blocked\\\";if(null==n)return e.removeAttribute(i),\\\"applied\\\";if(\\\"string\\\"!=typeof n&&\\\"number\\\"!=typeof n&&\\\"boolean\\\"!=typeof n)return\\\"blocked\\\";let r=String(n);return Xn.has(i)&&!$(r)?\\\"blocked\\\":(e.setAttribute(i,r),\\\"applied\\\")}(l.element,l.targetAttribute,s))return t.warn(`[live-preview] LP0401: refused to write \\\"${l.fieldName}\\\" into attribute \\\"${l.targetAttribute}\\\"`),!1}else{if(void 0===c)return t.log(\\\"no renderer for\\\",d),r(t,n,l,`has no renderer for \\\"${d}\\\"`),!1;{let e=function(e,t,n,i){if(\\\"ignore\\\"===e.onUnfaithfulPatch||void 0!==n.format||!On.has(i)||t.checkedServerFormat.has(n.element))return;t.checkedServerFormat.add(n.element);let r=o(n.element);return r.trim().length>0?r:void 0}(t,n,l,d);if(!1===function(e,t,n,i){return e.render(t,n,i)}(c,l,s,p)&&function(e){return Qn.has(e.render)}(c))return r(t,n,l,`is a value ${c.name} cannot render`),!1;void 0!==e&&function(e,t,n){let i=o(t.element);i!==n&&e.warn(`[live-preview] LP0412: \\\"${t.fieldName}\\\" showed ${a(n)}, the patch wrote ${a(i)} \\\\u2014 either an edit that arrived before the preview connected, or a template that formats this value differently. Set data-payload-format to match it.`)}(t,l,e)}}}catch(e){return this.fail(i,e)}if(!n.isCurrent(i))return!1;h&&t.emitter.emitWhile(\\\"elementUpdate\\\",{element:l.element,fieldName:l.fieldName,previousValue:f,nextValue:s,revision:i.revision.revision,receivedAt:i.receivedAt,source:\\\"patch\\\"},()=>n.isCurrent(i));let m=n.isCurrent(i);return m&&(void 0!==e.valueIdentity?n.lastAppliedIdentity.set(l.element,e.valueIdentity):n.lastAppliedIdentity.delete(l.element)),m}fail(e,t){if(!this.state.isCurrent(e))return!1;let n=t instanceof Error?t:new Error(String(t));return this.deps.emitter.emitWhile(\\\"error\\\",{error:n,context:\\\"renderer\\\",code:\\\"LP0603\\\"},()=>this.state.isCurrent(e)),!1}},hi=\\\"data-payload-island\\\",fi=`astro-island, [${hi}]`,pi=\\\"data-payload-field\\\",mi=\\\"data-payload-type\\\",gi=\\\"data-payload-attribute\\\",vi=\\\"data-payload-href\\\",yi=\\\"data-payload-src\\\",bi=\\\"data-payload-alt\\\",wi=\\\"data-payload-array-template\\\",Si=\\\"data-payload-array-separator\\\",Ti=\\\"data-payload-locale\\\",ki=\\\"data-payload-richtext\\\",Ai=\\\"data-payload-html\\\",Ci=\\\"data-payload-array\\\",$i=\\\"data-payload-structural\\\",Ri=\\\"data-payload-owner\\\",Fi=\\\"data-payload-depends\\\",Ni=\\\"data-payload-strategy\\\",Mi=\\\"data-payload-boundary\\\",xi=\\\"data-payload-guessed\\\",Ei=[pi,mi,gi,vi,yi,bi,wi,Si,Ti,ki,Ai,Ci,$i,Ri,Fi,Ni,Mi,\\\"type\\\"],Oi=`[${pi}]`,Pi=`[${Ri}]`,Li=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i,Ui=new Set([\\\"text\\\",\\\"textarea\\\",\\\"richText\\\",\\\"email\\\",\\\"number\\\",\\\"checkbox\\\",\\\"date\\\",\\\"select\\\",\\\"radio\\\",\\\"array\\\",\\\"blocks\\\",\\\"group\\\",\\\"tabs\\\",\\\"row\\\",\\\"collapsible\\\",\\\"relationship\\\",\\\"upload\\\",\\\"point\\\",\\\"json\\\",\\\"code\\\",\\\"ui\\\",\\\"html\\\",\\\"url\\\",\\\"image\\\",\\\"structural-array\\\"]),Ii=class{constructor(e={}){gn(this,\\\"entriesByField\\\",new Map);gn(this,\\\"entryByElement\\\",new WeakMap);gn(this,\\\"filter\\\");gn(this,\\\"count\\\",0);gn(this,\\\"dependencies\\\",null);gn(this,\\\"islandRoots\\\",[]);this.filter=e.filter??te}dependencyMap(){if(null!==this.dependencies)return this.dependencies;let e=[];for(let t of this.values())void 0!==t.dependsOn&&e.push(J(t.fieldName,t.dependsOn));return this.dependencies=K(...e),this.dependencies}get islands(){return this.islandRoots}buildFromRoot(e){let t=performance.now();this.clear();let n=0;for(let t of e.querySelectorAll(Oi))void 0!==this.add(t)&&(n+=1);return this.islandRoots=function(e){let t=[];for(let n of e.querySelectorAll(fi))X(n)||t.push(n);return t}(e),{elementCount:n,fieldCount:this.entriesByField.size,durationMs:performance.now()-t}}add(e){let t=this.filter(e)?this.resolveBinding(e):void 0,n=this.entryByElement.get(e);if(this.dependencies=null,void 0!==t)return void 0!==n&&this.replaceEntry(n,t)?(this.entryByElement.set(e,t),t):(void 0!==n&&this.removeEntry(e,n),this.append(t),this.entryByElement.set(e,t),t);void 0!==n&&this.removeEntry(e,n)}remove(e){let t=this.entryByElement.get(e);return!!t&&(this.dependencies=null,this.removeEntry(e,t))}get(e){return this.entriesByField.get(e)}getByElement(e){return this.entryByElement.get(e)}get fieldCount(){return this.entriesByField.size}get elementCount(){return this.count}entries(){return this.entriesByField.entries()}*values(){for(let e of this.entriesByField.values())yield*e}has(e){return this.entryByElement.has(e)}clear(){this.entriesByField.clear(),this.entryByElement=new WeakMap,this.count=0,this.dependencies=null,this.islandRoots=[]}replaceEntry(e,t){if(e.fieldName!==t.fieldName)return!1;let n=this.entriesByField.get(e.fieldName),i=void 0===n?-1:n.indexOf(e);return!(void 0===n||i<0||(n[i]=t,0))}removeEntry(e,t){this.entryByElement.delete(e);let n=this.entriesByField.get(t.fieldName),i=void 0===n?-1:n.indexOf(t);return!(void 0===n||i<0||(n.splice(i,1),0===n.length&&this.entriesByField.delete(t.fieldName),this.count-=1,0))}append(e){let t=this.entriesByField.get(e.fieldName);t?t.push(e):this.entriesByField.set(e.fieldName,[e]),this.count+=1}resolveBinding(e){let t=e.getAttribute(pi);if(null===t||0===t.length)return;let n=e.getAttribute(mi),i=e.getAttribute(gi),r=e.getAttribute(vi),l=e.getAttribute(yi),o=e.getAttribute(bi),a=e.getAttribute(wi),s=e.getAttribute(Si),u=e.getAttribute(Ti),d=e.getAttribute(\\\"data-payload-format\\\"),c=Z(e),h=function(e){if(null==e)return[];let t=new Set,n=[];for(let i of e.split(/[\\\\s,]+/)){let e=i.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}(e.getAttribute(Fi)),f=e.getAttribute(Ni),p=e.getAttribute(xi),m=x(e);return{element:e,fieldName:t,fieldType:ee(e),explicitFieldType:null!==n&&Y(n),strategyKind:E(e)??\\\"unknown\\\",...null!==m?{fragmentBoundary:m}:{},...null!==i&&i.length>0?{targetAttribute:i}:{},...null!==r&&r.length>0?{hrefField:r}:{},...null!==l&&l.length>0?{srcField:l}:{},...null!==o&&o.length>0?{altField:o}:{},...null!==a?{arrayTemplate:a}:{},...null!==s?{arraySeparator:s}:{},...null!==u&&u.length>0?{locale:u}:{},...null!==d&&d.length>0?{format:d}:{},...void 0!==c?{owner:c}:{},...h.length>0?{dependsOn:h}:{},...null!==f&&f.length>0?{strategy:f}:{},...e.hasAttribute(Mi)?{hidesWhenEmpty:!0}:{},...null!==p?{guessed:p}:{}}}},ji=class{constructor(e){gn(this,\\\"serverURL\\\");gn(this,\\\"apiRoute\\\");gn(this,\\\"depth\\\");gn(this,\\\"fetchFn\\\");gn(this,\\\"log\\\");gn(this,\\\"inflight\\\",null);gn(this,\\\"attempt\\\",0);gn(this,\\\"destroyDepth\\\",0);this.serverURL=function(e){let t=e.length;for(;e.endsWith(\\\"/\\\",t);)t-=1;return e.slice(0,t)}(e.serverURL);let i=e.apiRoute??\\\"/api\\\";this.apiRoute=i.startsWith(\\\"/\\\")?i:`/${i}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=t(e.log??n)}canMerge(e){return null!==this.endpointOf(e)}endpointOf(e){try{let t=e.globalSlug;if(t)return ie(t)?`globals/${encodeURIComponent(t)}`:null;let n=e.collectionSlug??\\\"\\\",i=e.data.id;return ie(n)&&function(e){return\\\"number\\\"==typeof e?Number.isFinite(e):\\\"string\\\"==typeof e&&ne(e,512)}(i)?`${encodeURIComponent(n)}/${encodeURIComponent(String(i))}`:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:\\\"superseded\\\"};let t=this.attempt+=1,n=this.inflight;this.inflight=null;let i=null,r=()=>this.attempt!==t;try{if(n?.abort(),r())return{status:\\\"superseded\\\"};let t=this.endpointOf(e);if(null===t)return r()?{status:\\\"superseded\\\"}:{status:\\\"unavailable\\\"};let l=this.fetchFn??(\\\"function\\\"==typeof fetch?fetch:void 0);if(void 0===l)return{status:\\\"unavailable\\\"};i=new AbortController,this.inflight=i;let o=`${this.serverURL}${this.apiRoute}/${t}`,a=await l(o,{method:\\\"POST\\\",credentials:\\\"include\\\",headers:{\\\"Content-Type\\\":\\\"application/json\\\",\\\"X-Payload-HTTP-Method-Override\\\":\\\"GET\\\"},body:JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale}),signal:i.signal});if(r())return{status:\\\"superseded\\\"};if(!a.ok)return this.log(\\\"merge HTTP\\\",a.status,o),{status:\\\"unavailable\\\"};let s=await a.json();return r()?{status:\\\"superseded\\\"}:null===s||\\\"object\\\"!=typeof s||Array.isArray(s)?(this.log(\\\"merge invalid\\\",o),{status:\\\"unavailable\\\"}):{status:\\\"merged\\\",doc:s}}catch(e){return r()?{status:\\\"superseded\\\"}:(this.log(\\\"merge exception\\\",e),{status:\\\"unavailable\\\"})}finally{this.inflight===i&&(this.inflight=null)}}destroy(){this.attempt+=1;let e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},_i=\\\"2.0.2\\\",Wi={name:\\\"payload-2\\\",fieldTyping:\\\"schema\\\",populatesRelationships:\\\"admin\\\",documentEvents:!1},Bi={name:\\\"payload-3\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!0},zi={name:\\\"unknown\\\",fieldTyping:\\\"heuristic\\\",populatesRelationships:\\\"server\\\",documentEvents:!1},Di=1,Vi=class{constructor(e,t={}){gn(this,\\\"callbacks\\\");gn(this,\\\"debounceMs\\\");gn(this,\\\"rootMargin\\\");gn(this,\\\"visible\\\",new Set);gn(this,\\\"mutation\\\",null);gn(this,\\\"intersection\\\",null);gn(this,\\\"debounceTimer\\\",null);gn(this,\\\"generation\\\",0);this.callbacks=e,this.debounceMs=t.mutationDebounceMs??100,this.rootMargin=t.intersectionRootMargin??\\\"200px\\\"}start(e){let t=this.generation;this.stop();let n=t+1;if(this.generation!==n)return;let i=null,r=null;try{i=new MutationObserver(e=>{this.handleMutations(e,n)}),r=new IntersectionObserver(e=>{this.handleIntersection(e,n)},{rootMargin:this.rootMargin,threshold:0}),i.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[...Ei]})}catch(e){throw i?.disconnect(),r?.disconnect(),e}this.generation===n?(this.mutation=i,this.intersection=r):(i.disconnect(),r.disconnect())}observeElement(e){this.intersection?.observe(e)}unobserveElement(e){this.intersection?.unobserve(e),this.visible.delete(e)}markVisible(e,t){t?this.visible.add(e):this.visible.delete(e)}isVisible(e){return this.visible.has(e)}stop(){this.generation+=1;let e=this.debounceTimer,t=this.mutation,n=this.intersection;this.debounceTimer=null,this.mutation=null,this.intersection=null,this.visible.clear(),null!==e&&clearTimeout(e);try{t?.disconnect()}finally{n?.disconnect()}}handleMutations(e,t){if(!this.isCurrentGeneration(t)||!function(e){for(let t of e){if(\\\"attributes\\\"===t.type&&null!==t.attributeName&&Ei.includes(t.attributeName)&&(t.attributeName===pi||t.attributeName===Ri||t.target.nodeType===Di&&t.target.hasAttribute(pi)))return!0;for(let e of t.addedNodes)if(le(e))return!0;for(let e of t.removedNodes)if(le(e))return!0}return!1}(e))return;null!==this.debounceTimer&&clearTimeout(this.debounceTimer);let n=setTimeout(()=>{!this.isCurrentGeneration(t)||this.debounceTimer!==n||(this.debounceTimer=null,this.callbacks.onStructuralChange())},this.debounceMs);this.debounceTimer=n}handleIntersection(e,t){for(let n of e){if(!this.isCurrentGeneration(t))return;let{target:e}=n;if(n.isIntersecting){if(this.visible.has(e))continue;this.visible.add(e),this.callbacks.onVisibilityChange(e,!0)}else this.visible.has(e)&&(this.visible.delete(e),this.callbacks.onVisibilityChange(e,!1))}}isCurrentGeneration(e){return this.generation===e&&null!==this.intersection}},Hi=\\\"__livePreviewHydration\\\",Gi=\\\"[data-payload-field]\\\",qi=\\\"__vue_app__\\\",Ki=\\\"__livePreviewVueHydration\\\",Ji=\\\"app:suspense:resolve\\\",Xi=class{constructor(e){gn(this,\\\"timeoutMs\\\");gn(this,\\\"onTimeout\\\");gn(this,\\\"handle\\\",null);gn(this,\\\"lastKick\\\",0);this.timeoutMs=e.timeoutMs??0,this.onTimeout=e.onTimeout}kick(){if(this.lastKick=Date.now(),this.timeoutMs<=0)return;null!==this.handle&&clearTimeout(this.handle);let e=setTimeout(()=>{this.handle===e&&(this.handle=null,this.onTimeout())},this.timeoutMs);this.handle=e}stop(){null!==this.handle&&(clearTimeout(this.handle),this.handle=null)}get lastKickAt(){return this.lastKick}get pending(){return null!==this.handle}},Qi=class{constructor(){gn(this,\\\"current\\\",\\\"disconnected\\\")}get status(){return this.current}markConnected(){return this.transition(\\\"connected\\\")}markDisconnected(){return this.transition(\\\"disconnected\\\")}transition(e){return this.current!==e&&(this.current=e,!0)}},Zi=\\\"data-payload-no-bind\\\",Yi=\\\"data-payload-owned\\\",er=13,tr=new Set([\\\"true\\\",\\\"false\\\",\\\"yes\\\",\\\"no\\\",\\\"on\\\",\\\"off\\\"]),nr=/^[\\\\d\\\\s.,:+/-]+$/u,ir=/^[a-z][a-z0-9_-]*$/u,rr=/^[a-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/u,lr=new Set([\\\"SCRIPT\\\",\\\"STYLE\\\",\\\"TEMPLATE\\\",\\\"TITLE\\\",\\\"NOSCRIPT\\\",\\\"TEXTAREA\\\",\\\"SELECT\\\",\\\"OPTION\\\",\\\"INPUT\\\",\\\"IFRAME\\\"]),or=\\\"http://www.w3.org/1999/xhtml\\\",ar=new Set([\\\"__proto__\\\",\\\"prototype\\\",\\\"constructor\\\"]),sr=\\\"payload-live-preview\\\",ur=\\\"data-payload-owned\\\",dr=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]),cr=new Set,hr=\\\"data-payload-\\\",fr=new Set([\\\"p\\\",\\\"br\\\",\\\"strong\\\",\\\"b\\\",\\\"em\\\",\\\"i\\\",\\\"u\\\",\\\"s\\\",\\\"strike\\\",\\\"mark\\\",\\\"small\\\",\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\",\\\"ul\\\",\\\"ol\\\",\\\"li\\\",\\\"dl\\\",\\\"dt\\\",\\\"dd\\\",\\\"blockquote\\\",\\\"code\\\",\\\"pre\\\",\\\"kbd\\\",\\\"samp\\\",\\\"var\\\",\\\"a\\\",\\\"span\\\",\\\"div\\\",\\\"section\\\",\\\"article\\\",\\\"aside\\\",\\\"header\\\",\\\"footer\\\",\\\"nav\\\",\\\"figure\\\",\\\"figcaption\\\",\\\"img\\\",\\\"picture\\\",\\\"source\\\",\\\"audio\\\",\\\"video\\\",\\\"sub\\\",\\\"sup\\\",\\\"hr\\\",\\\"time\\\",\\\"abbr\\\",\\\"cite\\\",\\\"q\\\",\\\"table\\\",\\\"thead\\\",\\\"tbody\\\",\\\"tfoot\\\",\\\"tr\\\",\\\"th\\\",\\\"td\\\",\\\"caption\\\",\\\"colgroup\\\",\\\"col\\\"]),pr=new Set([\\\"input\\\",\\\"button\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"label\\\"]),mr=new Set([\\\"script\\\",\\\"style\\\",\\\"iframe\\\",\\\"object\\\",\\\"embed\\\",\\\"link\\\",\\\"meta\\\",\\\"base\\\",\\\"form\\\",\\\"input\\\",\\\"button\\\",\\\"select\\\",\\\"textarea\\\",\\\"svg\\\",\\\"math\\\",\\\"template\\\",\\\"frame\\\",\\\"frameset\\\",\\\"noframes\\\",\\\"noscript\\\"]),gr=new Set([\\\"id\\\",\\\"class\\\",\\\"lang\\\",\\\"dir\\\",\\\"title\\\",\\\"role\\\",\\\"tabindex\\\"]),vr=\\\"aria-\\\",yr=\\\"data-\\\",br=\\\"data-payload-\\\",wr={a:new Set([\\\"href\\\",\\\"target\\\",\\\"rel\\\",\\\"download\\\",\\\"hreflang\\\",\\\"type\\\"]),img:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"alt\\\",\\\"width\\\",\\\"height\\\",\\\"loading\\\",\\\"decoding\\\"]),picture:new Set([]),source:new Set([\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\",\\\"type\\\",\\\"media\\\"]),audio:new Set([\\\"src\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\"]),video:new Set([\\\"src\\\",\\\"poster\\\",\\\"controls\\\",\\\"autoplay\\\",\\\"loop\\\",\\\"muted\\\",\\\"preload\\\",\\\"width\\\",\\\"height\\\",\\\"playsinline\\\"]),time:new Set([\\\"datetime\\\"]),abbr:new Set([\\\"title\\\"]),q:new Set([\\\"cite\\\"]),blockquote:new Set([\\\"cite\\\"]),table:new Set([\\\"summary\\\"]),th:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"scope\\\",\\\"headers\\\",\\\"abbr\\\"]),td:new Set([\\\"colspan\\\",\\\"rowspan\\\",\\\"headers\\\"]),col:new Set([\\\"span\\\"]),colgroup:new Set([\\\"span\\\"]),ol:new Set([\\\"start\\\",\\\"reversed\\\",\\\"type\\\"]),li:new Set([\\\"value\\\"]),code:new Set([\\\"class\\\"]),pre:new Set([\\\"class\\\"])},Sr=new Set([\\\"href\\\",\\\"src\\\",\\\"cite\\\",\\\"poster\\\"]),Tr=1,kr=8,Ar=(Error,new Set([\\\"id\\\",\\\"name\\\",\\\"data-payload-key\\\",\\\"data-payload-nested-key\\\",\\\"data-payload-nested-template\\\"])),Cr=\\\"strict\\\",$r=(Object.freeze({allowedTags:fr,removeCompletely:mr,globalAttributes:gr,attributesByTag:wr,urlAttributes:Sr}),Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\",\\\"/\\\":\\\"/\\\",\\\"`\\\":\\\"`\\\",\\\"=\\\":\\\"=\\\"})),Rr=/[&<>\\\"'/`=]/g,Fr=Object.freeze({\\\"&\\\":\\\"&\\\",\\\"<\\\":\\\"<\\\",\\\">\\\":\\\">\\\",'\\\"':\\\""\\\",\\\"'\\\":\\\"'\\\"}),Nr=/[&<>\\\"']/g,Mr=/\\\\{\\\\{([\\\\s\\\\S]*?)\\\\}\\\\}/g,xr=\\\"data-payload-\\\",Er=[\\\"input\\\",\\\"textarea\\\",\\\"select\\\",\\\"option\\\",\\\"button\\\",\\\"label\\\",\\\"details\\\",\\\"summary\\\",\\\"dialog\\\",\\\"video\\\",\\\"audio\\\",\\\"progress\\\",\\\"meter\\\"],Or=[\\\"type\\\",\\\"name\\\",\\\"placeholder\\\",\\\"open\\\",\\\"disabled\\\",\\\"readonly\\\",\\\"required\\\",\\\"checked\\\",\\\"selected\\\",\\\"value\\\",\\\"min\\\",\\\"max\\\",\\\"step\\\",\\\"rows\\\",\\\"cols\\\",\\\"for\\\",\\\"controls\\\",\\\"muted\\\",\\\"loop\\\",\\\"poster\\\",\\\"src\\\"],Pr=/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\\\b/gi,Lr=64,Ur=new Map,Ir=\\\"data-payload-key\\\",jr=\\\"data-payload-nested-key\\\",_r=\\\"data-payload-nested-template\\\",Wr=class{constructor(e,t,n){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"host\\\",n)}planFragments(e){let t=this.deps.strategies.fragment;return void 0===t?null:yt(t,t.plan(this.deps.root,e))}escalateUnfaithful(e,t,n){if(e.routeRefreshed)return;let{fragment:i,route:r}=this.deps.strategies,l=void 0===i?void 0:function(e){let t=[];for(let n of e){let e=n.fragmentBoundary;if(void 0===e)return;t.includes(e)||t.push(e)}return t}(n);void 0===i||void 0===l?void 0!==r&&(this.state.escalatedCount+=n.length,this.refreshRoute(e,t,r)):(this.state.escalatedCount+=n.length,e.pendingFragments+=l.length,this.runFragments(e,t,yt(i,l)))}hasUnboundChange(e,t){let{deps:n,state:i}=this;if(e.baseline||e.routeRefreshed)return!1;let r=function(e,t,n,i){let r=B(e,n,i),l=[];for(let e of t)!ti.has(e)&&!r(e)&&l.push(e);return l}(n.cache,e.touched,e.locale,t),o=0;for(let e of r)l(i,e)&&(o+=1);let[a]=r;return void 0!==a&&\\\"escalate\\\"===n.onUnfaithfulPatch&&void 0!==n.strategies.route&&(n.log(\\\"route\\\",\\\"LP0807\\\",`field \\\"${a}\\\" has no binding; refreshing the route`),i.escalatedCount+=o,!0)}hasRouteBinding(e){for(let[t,n]of this.deps.cache.entries())if(e.has(t)&&n.some(e=>\\\"route\\\"===e.strategyKind))return!0;return!1}async runFragments(e,t,n){let{deps:i,state:r}=this,l=new AbortController;r.fragmentController=l;let o=()=>r.isCurrent(e)&&!l.signal.aborted,{emitter:a}=i,{message:s}=e,u=e.revision.revision,d=e.receivedAt,c={root:i.root,revision:u,receivedAt:d,fields:t.fields,locale:e.locale,collectionSlug:\\\"string\\\"==typeof s.collectionSlug?s.collectionSlug:void 0,globalSlug:\\\"string\\\"==typeof s.globalSlug?s.globalSlug:void 0,signal:l.signal,isCurrent:o,log:(e,t)=>{i.log(\\\"fragment\\\",e,t)},morph:(e,t)=>{!function(e,t){let n=e.ownerDocument.createElement(\\\"template\\\");n.innerHTML=Le(t);let i=e.cloneNode(!1);i.append(n.content),je(e,i,{keyAttributes:[Ir]})}(e,t)},patch:n=>{this.patchFallback(e,t,n)},rendered:(t,n,i)=>{e.pendingFragments-=1,a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:i,status:\\\"rendered\\\",revision:u,receivedAt:d},o)},failed:(t,n,r,l,s)=>{e.pendingFragments-=1;let c=`fragment \\\"${n}\\\" fell back to patch: ${s}`;i.log(\\\"fragment\\\",l,c),a.emitWhile(\\\"error\\\",{error:new Error(c),context:\\\"fragment\\\",code:l},o),a.emitWhile(\\\"fragmentRender\\\",{element:t,id:n,key:r,status:\\\"failed\\\",code:l,revision:u,receivedAt:d},o)}},h={rendered:0,failed:0,superseded:0};try{h=await n.strategy.render(c,n.boundaries)}catch(r){if(i.log(\\\"fragment\\\",\\\"LP0801\\\",r),o()){for(let i of n.boundaries)this.patchFallback(e,t,i);h={rendered:0,failed:n.boundaries.length,superseded:0}}}r.fragmentStats.rendered+=h.rendered,r.fragmentStats.failed+=h.failed,r.fragmentStats.superseded+=h.superseded,o()&&(r.fragmentController===l&&(r.fragmentController=null),e.pendingFragments=0,h.rendered>0&&this.host.restoreGuesses(e,t),0===i.scheduler.pendingCount&&r.complete(e),this.host.revealPending(e),o()&&(0===h.rendered||0===a.listenerCount(\\\"afterUpdate\\\")||a.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:h.rendered,durationMs:Date.now()-d,revision:u,receivedAt:d,source:\\\"fragment\\\"},o)))}async refreshRoute(e,t,n){let{deps:i,state:r}=this;e.routeRefreshed?(r.routeStats.loopStopped+=1,i.log(\\\"route\\\",\\\"LP0805\\\",`revision ${String(e.revision.revision)} asked for a second refresh`)):(e.routeRefreshed=!0,await this.runRoute(e,t,n))}armRouteRetry(e,t,n,i){let{state:r}=this;null!==r.routeRetry&&clearTimeout(r.routeRetry),r.routeRetry=setTimeout(()=>{r.routeRetry=null,r.isCurrent(e)&&this.runRoute(e,t,n)},i)}async runRoute(e,t,n){let{deps:i,state:r}=this,l=r.routeStats,o=new AbortController;r.routeController=o;let a,s=()=>r.isCurrent(e)&&!o.signal.aborted;try{a=await n.refresh({revision:e.revision.revision,receivedAt:e.receivedAt,signal:o.signal,isCurrent:s,log:(e,t)=>{i.log(\\\"route\\\",e,t)},retryAfter:i=>{this.armRouteRetry(e,t,n,i)}})}catch(e){i.log(\\\"route\\\",\\\"LP0801\\\",e),a=\\\"failed\\\"}if(s()){if(r.routeController===o&&(r.routeController=null),\\\"refreshed\\\"===a){if(l.refreshes+=1,r.lastAppliedIdentity=new WeakMap,this.host.restoreGuesses(e,t),this.host.rebuildCache(),!s())return;this.host.reapply(e,t),i.emitter.listenerCount(\\\"afterUpdate\\\")>0&&i.emitter.emitWhile(\\\"afterUpdate\\\",{data:t,updatedCount:i.cache.elementCount,durationMs:Date.now()-e.receivedAt,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"route\\\"},s);return}\\\"failed\\\"===a?l.failed+=1:\\\"refused\\\"===a&&(l.refused+=1),this.host.reapply(e,t)}}warnFragmentFallback(e){!function(e,t,n){t.warnedFragmentFallback||(t.warnedFragmentFallback=!0,e.warn(`[live-preview] LP0806: \\\"${n.fieldName}\\\" asks for the fragment strategy but no handler is configured; patching instead`))}(this.deps,this.state,e)}warnUnsupportedStrategy(e){!function(e,t,n){t.warnedStrategy.has(n.element)||(t.warnedStrategy.add(n.element),e.warn(`[live-preview] LP0407: \\\"${n.fieldName}\\\" asks for strategy \\\"${String(n.strategy)}\\\"; only patch, fragment and route exist`))}(this.deps,this.state,e)}patchFallback(e,t,n){for(let[i,r]of this.deps.cache.entries())for(let l of r){if(l.fragmentBoundary!==n)continue;let r=Me(t.fields,l,i,e.locale);void 0!==r&&this.deps.scheduler.schedule({target:l,value:this.host.transform(l,r,t.fields,()=>!0),allFields:t.fields,revision:e.revision,data:t})}}},Br=new Set,zr=class{constructor(e,t,n){gn(this,\\\"deps\\\",e);gn(this,\\\"state\\\",t);gn(this,\\\"strategies\\\");this.strategies=new Wr(e,t,{reapply:(e,t)=>{this.scheduleAllFields(e,t)},transform:(t,n,i,r)=>bt(e,t,n,i,r),rebuildCache:n,restoreGuesses:(e,t)=>{this.restoreGuesses(e,t)},revealPending:e=>{this.revealPending(e)}})}handleUpdate(e,t,n){let{deps:i,state:r}=this;if(i.heartbeat.kick(),r.protocol.observe(function(e){let t=[];return Array.isArray(e.fieldSchemaJSON)&&t.push(\\\"schema-json\\\"),\\\"string\\\"==typeof e.locale&&t.push(\\\"locale\\\"),\\\"string\\\"==typeof e.previewToken&&t.push(\\\"preview-token\\\"),\\\"object\\\"==typeof e.externallyUpdatedRelationship&&null!==e.externallyUpdatedRelationship&&t.push(\\\"relationship-events\\\"),t}(e),i.log),void 0===e.data){void 0!==e.protocolVersion&&r.protocol.applyVersion(e.protocolVersion,i.log);return}if(void 0===n)return;let l=r.relationships.edit(e);null!==l&&i.emitter.emit(\\\"relationshipUpdate\\\",{detail:l,timestamp:Date.now()}),\\\"string\\\"==typeof e.locale&&(r.locale=e.locale),Array.isArray(e.fieldSchemaJSON)&&(r.schema=e.fieldSchemaJSON,r.schemaIndex=b(e.fieldSchemaJSON));let o={revision:n,message:e,locale:r.locale,schema:r.schema,schemaIndex:r.schemaIndex,receivedAt:Date.now(),forceRender:null!==l||G(r.activeUpdate),touched:new Set,baseline:!1,invalidated:new Set,revealTarget:void 0,revealIdentities:[],pendingFragments:0,routeRefreshed:!1,cancelled:!1,completed:!1},a=r.activeUpdate;r.abortStrategies(),null!==a&&!a.completed&&(r.supersededCount+=1),r.activeUpdate=o,i.scheduler.acceptRevision(n),r.updateCount+=1,(void 0===e.protocolVersion||(r.protocol.applyVersion(e.protocolVersion,i.log),r.isCurrent(o)))&&(i.connection.markConnected()&&(i.a11y?.announceConnected(),i.emitter.emit(\\\"connect\\\",{origin:t,timestamp:Date.now()}),!r.isCurrent(o)||(i.log(\\\"connection\\\",\\\"disconnected\\\",\\\"\\\\u2192\\\",\\\"connected\\\"),!r.isCurrent(o)))||this.processUpdate(o).catch(e=>{i.log(\\\"update failed:\\\",e)}))}async processUpdate(e){let{deps:t,state:n}=this,i=await this.resolveIncomingFields(e);if(null===i||!n.isCurrent(e))return;let r=this.dataFor(e,i);t.emitter.listenerCount(\\\"beforeUpdate\\\")>0&&(!await t.emitter.emitWhile(\\\"beforeUpdate\\\",{data:r,revision:e.revision.revision,receivedAt:e.receivedAt,source:\\\"patch\\\",cancel:()=>{e.cancelled=!0,t.scheduler.cancelRevision(e.revision)}},()=>!e.cancelled&&n.isCurrent(e))||e.cancelled||!n.isCurrent(e))||this.applyFields(e,r,!1)}dataFor(e,t){let{message:n}=e;return{fields:t,...void 0!==e.schema?{schema:e.schema}:{},...\\\"string\\\"==typeof n.globalSlug?{globalSlug:n.globalSlug}:{},...\\\"string\\\"==typeof n.collectionSlug?{collectionSlug:n.collectionSlug}:{},...void 0!==e.locale?{locale:e.locale}:{}}}applyFields(e,t,n){let{deps:i,state:r}=this,l=K(i.dependencies,i.cache.dependencyMap()),o=r.changes.diff(t.fields,l);if(o.baseline&&!n&&\\\"off\\\"!==i.autoBind){let n=this.ownerKeysForUpdate(e,t.fields);!function(e,t,n,i,r){let l=performance.now(),o=$e(e.root),a=ye(n,i),s=null===o?[]:Re(e,Ce(o,a),r,\\\"on the first message\\\");t.autoBindGuesses=function(e,t){let n=new Set;for(let{fieldName:e,stamps:i}of t){n.add(e);for(let e of[vi,bi]){let t=i[e];void 0!==t&&n.add(t)}}let i=new Map;for(let[t,r]of e)null!==r&&n.has(r.field)&&i.set(t,r);return{fields:n,values:i}}(a,s),t.autoBindSearchMs=performance.now()-l,s.length}(i,r,t.fields,e.locale,n)}e.baseline=o.baseline,e.invalidated=n?Br:o.invalidated,e.touched=n?Br:new Set([...o.changed,...o.invalidated]),this.scheduleAllFields(e,t)}async resolveIncomingFields(e){let{deps:t,state:n}=this,i=e.message.data??{};if(null===t.merger||\\\"admin\\\"===re(n.protocol.observed).populatesRelationships)return i;let r=n.merges.decide(t,e);if(!r.merge)return r.fields;let{message:l}=e,o=n.merges.request(t.merger,t.mergeWindowMs,{collectionSlug:l.collectionSlug,globalSlug:l.globalSlug,data:i,locale:e.locale});if(!o.leading)return this.applyMerged(e,o.result).catch(e=>{t.log(\\\"update failed:\\\",e)}),r.fields;let a=await o.result;return n.isCurrent(e)?\\\"merged\\\"===a.status?(n.merges.recordMerged(a.doc),a.doc):\\\"superseded\\\"===a.status?null:r.fields:null}async applyMerged(e,t){let{state:n}=this,i=await t;\\\"merged\\\"!==i.status||!n.isCurrent(e)||(n.merges.recordMerged(i.doc),this.applyFields(e,this.dataFor(e,i.doc),!0))}scheduleAllFields(e,t){let{deps:n,state:i}=this;if(!i.isCurrent(e))return;let r=()=>i.isCurrent(e),l=this.ownerKeysForUpdate(e,t.fields),{touched:o}=e,a=n.strategies.route,s=this.strategies.hasUnboundChange(e,l);if(void 0!==a&&!e.routeRefreshed&&(s||a.plan(n.root,o)||this.strategies.hasRouteBinding(o))){this.strategies.refreshRoute(e,t,a);return}let u=this.strategies.planFragments(o),d=n.skipUnchanged,c=0;for(let[o,a]of n.cache.entries()){if(!r())return;for(let s of a){if(!1!==l&&!U(s.owner,l))continue;if(!0===u?.covers(s)){if(n.revealEditedField){let n=Me(t.fields,s,o,e.locale);i.revealLedger.note(e,s,n)}continue}let a=s.strategyKind??E(s.element)??\\\"unknown\\\";if(\\\"unknown\\\"===a){this.strategies.warnUnsupportedStrategy(s);continue}\\\"fragment\\\"===a&&null===u&&this.strategies.warnFragmentFallback(s);let h=Me(t.fields,s,o,e.locale);if(void 0===h){i.absentFields.add(o);continue}if(n.revealEditedField&&i.revealLedger.note(e,s,h),!r())return;let f=bt(n,s,h,t.fields,r);if(!r())return;let p=d?xe(s,f,t.fields,e.locale):void 0,m=i.lastAppliedIdentity.get(s.element);if(!e.forceRender&&n.skipUnchanged&&void 0!==p&&m===p&&!e.invalidated.has(o)){i.skippedUnchangedCount+=1;continue}let g={target:s,value:f,allFields:t.fields,revision:e.revision,data:t,valueIdentity:p};n.scheduler.schedule(g),c+=1}}(function(e,t,n,i){let{cache:r}=e;if(0===r.fieldCount||!1!==i&&!function(e,t){for(let n of e.values())if(U(n.owner,t))return!0;return!1}(r,i))return;let l=B(r,n,i);for(let[i,r]of Object.entries(t)){if(ti.has(i))continue;if(Oe(r)){Ee(e,l,i,n);continue}if(!Pe(r)||l(i))continue;let t=W(i,n);for(let[i,o]of Object.entries(r))!Oe(o)||ti.has(i)||Ee(e,l,`${t}.${i}`,n)}})({cache:n.cache,warned:i.warnedOrphanFields,warn:n.warn},t.fields,e.locale,l),null!==u&&u.boundaries.length>0&&(e.pendingFragments=u.boundaries.length,this.strategies.runFragments(e,t,u)),0===c&&0===e.pendingFragments&&(i.complete(e),this.revealPending(e))}restoreGuesses(e,t){let{deps:n,state:i}=this;if(\\\"off\\\"!==n.autoBind&&null!==i.autoBindGuesses){let r=this.ownerKeysForUpdate(e,t.fields);!function(e,t,n,i,r){let l=t.autoBindGuesses,o=$e(e.root);if(null===l||0===l.fields.size||null===o)return 0;let a=new Map(l.values);for(let[e,t]of ye(n,i)){if(null===t||!l.fields.has(t.field))continue;let n=a.get(e);void 0===n?a.set(e,t):n?.field!==t.field&&a.set(e,null)}Re(e,Ce(o,a),r,\\\"after a server render\\\").length}(n,i,t.fields,e.locale,r)}}ownerKeysForUpdate(e,t){let{deps:n,state:i}=this;if(!n.scopeBindingsByOwner)return!1;let{message:r}=e,l=function(e){if(L(e.globalSlug))return[O(e.globalSlug)];if(!L(e.collectionSlug))return null;let t=P(e.collectionSlug);return L(e.documentId)?[t,P(e.collectionSlug,e.documentId)]:[t]}({globalSlug:\\\"string\\\"==typeof r.globalSlug?r.globalSlug:void 0,collectionSlug:\\\"string\\\"==typeof r.collectionSlug?r.collectionSlug:void 0,documentId:I(t)});return null===l&&!i.warnedUnattributableMessage&&(i.warnedUnattributableMessage=!0,n.warn(\\\"[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied\\\")),l}onFlush(e){let{deps:t,state:n}=this;n.lastFlush=e,e.deferred>0&&!n.warnedVisibilityGate&&(n.warnedVisibilityGate=!0,t.warn(`[live-preview] LP0301: visibility gate held ${String(e.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`));let{revision:i,data:r}=e;if(void 0===i)return;let l=n.activeUpdate;if(null===l||!n.isCurrent(l)||!g(l.revision,i))return;0===l.pendingFragments&&n.complete(l);let o=()=>n.isCurrent(l)&&g(l.revision,i);if(this.revealPending(l),!o())return;let a=n.unfaithfulPatches;a.length>0&&(n.unfaithfulPatches=[],void 0!==r&&this.strategies.escalateUnfaithful(l,r,a),!o())||0===e.applied||void 0===r||(t.a11y?.announceUpdate(e.applied),o()&&(function(e,t){for(let n of e)n.dispatchEvent(new CustomEvent(\\\"payload-live-preview:update\\\",{detail:t,bubbles:!1}));e.length}(t.cache.islands,{fields:r.fields,revision:i.revision,receivedAt:l.receivedAt,locale:l.locale}),o()&&0!==t.emitter.listenerCount(\\\"afterUpdate\\\")&&t.emitter.emitWhile(\\\"afterUpdate\\\",{data:r,updatedCount:e.applied,durationMs:e.durationMs,revision:i.revision,receivedAt:l.receivedAt,source:\\\"patch\\\"},o)))}revealPending(e){let t=this.state.revealLedger.commit(e);if(void 0!==t)try{this.revealBinding(t)}catch(e){this.deps.log(\\\"reveal\\\",e)}}revealField(e){let t=this.deps.cache.get(e)?.[0];return void 0===t?\\\"no-element\\\":this.revealBinding(t)}revealBinding(e){let{element:t}=e,n=t.ownerDocument.defaultView;if(null===n)return\\\"no-element\\\";let i=`${e.owner??\\\"\\\"} ${e.fieldName}`;return this.state.revealer.reveal(i,t,n)}},Dr=class{constructor(e,t){gn(this,\\\"apply\\\");gn(this,\\\"debounceMs\\\");gn(this,\\\"maxWaitMs\\\");gn(this,\\\"isVisible\\\");gn(this,\\\"gateThresholdValue\\\");gn(this,\\\"gateDisabled\\\");gn(this,\\\"getCacheSize\\\");gn(this,\\\"onFlush\\\");gn(this,\\\"scheduleFrame\\\");gn(this,\\\"cancelFrame\\\");gn(this,\\\"pending\\\",new Map);gn(this,\\\"replay\\\",new Map);gn(this,\\\"activeFlushes\\\",new Set);gn(this,\\\"debounceTimer\\\",null);gn(this,\\\"debounceToken\\\",0);gn(this,\\\"deadlineTimer\\\",null);gn(this,\\\"frameHandle\\\",null);gn(this,\\\"frameToken\\\",0);gn(this,\\\"windowUntil\\\",0);gn(this,\\\"activeRevision\\\",null);gn(this,\\\"activeRevisionCancelled\\\",!1);this.apply=e,this.debounceMs=t.debounceMs??50,this.maxWaitMs=t.maxWaitMs??4*this.debounceMs,this.isVisible=t.isVisible,this.gateThresholdValue=t.visibilityGateThreshold??50,this.gateDisabled=t.disableVisibilityGate??!1,this.getCacheSize=t.getCacheSize,this.onFlush=t.onFlush,this.scheduleFrame=t.scheduleFrame??(\\\"function\\\"==typeof requestAnimationFrame?requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>{e(performance.now())},0)),this.cancelFrame=t.cancelFrame??(\\\"function\\\"==typeof cancelAnimationFrame?cancelAnimationFrame.bind(globalThis):e=>{clearTimeout(e)})}schedule(e){if(void 0!==e.revision&&(this.activeRevisionCancelled||null===this.activeRevision||!g(e.revision,this.activeRevision)))return;let t=this.pending.get(e.target.element);t?(t.value=e.value,t.allFields=e.allFields,t.revision=e.revision,t.data=e.data,t.valueIdentity=e.valueIdentity):this.pending.set(e.target.element,{target:e.target,value:e.value,allFields:e.allFields,revision:e.revision,data:e.data,valueIdentity:e.valueIdentity}),this.armDebounce()}acceptRevision(e){null!==this.activeRevision&&g(e,this.activeRevision)||null!==this.activeRevision&&function(e,t){return e.generation!==t.generation?e.generation-t.generation:e.revision-t.revision}(e,this.activeRevision)<0||(this.cancelScheduledWork(),this.clearWork(),this.activeRevision=e,this.activeRevisionCancelled=!1)}cancelRevision(e){null===this.activeRevision||!g(e,this.activeRevision)||(this.cancelScheduledWork(),this.clearWork(),this.activeRevisionCancelled=!0)}flushNow(){return this.cancelScheduledWork(),this.flush()}notifyVisible(e){let t=this.replay.get(e);if(!t||(this.replay.delete(e),!this.isCurrent(t)))return;let n=performance.now(),i=this.didApply(t)?1:0;this.onFlush?.(this.statsFor(t,i,0,performance.now()-n,1===i?[t.target.fieldName]:[]))}retarget(e){this.retargetBuffer(this.pending,e),this.retargetBuffer(this.replay,e);for(let t of this.activeFlushes)this.retargetBuffer(t,e)}forget(e){this.pending.delete(e),this.replay.delete(e);for(let t of this.activeFlushes)t.delete(e)}destroy(){this.cancelScheduledWork(),this.clearWork(),this.activeRevision=null,this.activeRevisionCancelled=!1,this.windowUntil=0}get pendingCount(){return this.pending.size}get replayCount(){return this.replay.size}get gateThreshold(){return this.gateThresholdValue}get gateActive(){return!this.gateDisabled&&this.getCacheSize()>this.gateThresholdValue}armDebounce(){let e=Date.now(),t=e>=this.windowUntil;if(this.windowUntil=e+this.debounceMs,t){this.requestFrame();return}let n=this.debounceToken+=1,i=this.debounceTimer;if(this.debounceTimer=null,null!==i&&clearTimeout(i),this.debounceToken!==n)return;let r=setTimeout(()=>{this.debounceToken===n&&(this.debounceTimer=null,this.pending.size>0&&this.requestFrame())},this.debounceMs);this.debounceToken===n&&(this.debounceTimer=r),null===this.deadlineTimer&&this.maxWaitMs>this.debounceMs&&(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.pending.size>0&&this.requestFrame()},this.maxWaitMs))}requestFrame(){let e=this.frameToken+=1,t=this.frameHandle;if(this.frameHandle=null,null!==t&&this.cancelFrame(t),this.frameToken!==e)return;let n=!1,i=this.scheduleFrame(()=>{this.frameToken===e&&(n=!0,this.frameHandle=null,this.flush())});!n&&this.frameToken===e&&(this.frameHandle=i)}flush(){let e=performance.now();this.clearDeadline();let t=this.gateActive,n=this.pending;this.pending=new Map;let i,r=0,l=[],o=0;this.activeFlushes.add(n);try{for(let e of n.values()){if(!this.isCurrent(e))continue;let n=!t||this.isVisible(e.target.element);if(this.isCurrent(e)){if(i??(i=e),!n){this.replay.set(e.target.element,e),o+=1;continue}this.replay.delete(e.target.element),this.didApply(e)&&(r+=1,l.push(e.target.fieldName))}}}finally{this.activeFlushes.delete(n)}let a=this.statsFor(i,r,o,performance.now()-e,l);return this.onFlush?.(a),a}isCurrent(e){return void 0===e.revision||!this.activeRevisionCancelled&&null!==this.activeRevision&&g(e.revision,this.activeRevision)}didApply(e){return!1!==this.apply(e)||!function(e){return Qn.has(e)}(this.apply)}retargetBuffer(e,t){let n=e.get(t.element);if(void 0!==n){if(n.target.fieldName!==t.fieldName||n.target.locale!==t.locale){e.delete(t.element);return}n.target=t}}clearWork(){this.pending.clear(),this.replay.clear();for(let e of this.activeFlushes)e.clear()}statsFor(e,t,n,i,r){return{applied:t,appliedFields:r,deferred:n,durationMs:i,...void 0!==e?.revision?{revision:e.revision}:{},...void 0!==e?.data?{data:e.data}:{}}}clearDeadline(){null!==this.deadlineTimer&&(clearTimeout(this.deadlineTimer),this.deadlineTimer=null)}cancelScheduledWork(){let e=this.debounceTimer,t=this.frameHandle;this.debounceToken+=1,this.frameToken+=1,this.debounceTimer=null,this.frameHandle=null,this.clearDeadline(),null!==e&&clearTimeout(e),null!==t&&this.cancelFrame(t)}},Vr=[0,500,1e3,2e3],Hr=class{constructor(e){gn(this,\\\"deps\\\");gn(this,\\\"state\\\",new di);gn(this,\\\"pipeline\\\");gn(this,\\\"writer\\\");gn(this,\\\"rootSentinel\\\",null);gn(this,\\\"observedRoot\\\",null);let{emitter:r,renderers:l}=e,o=void 0===e.log?n:t(e.log),a=void 0===e.warn?kn:t(e.warn),s=e.root??(typ\",\"eof document<\\\"u\\\"?document:void 0);if(void 0===s)throw new Error(\\\"LivePreviewRuntime: no document; pass options.root\\\");let u=new Ii({filter:e=>!function(e){let t=e;for(;null!==t;){if(Q(t))return!0;t=t.parentElement}return!1}(e)}),d=new Vi({onStructuralChange:()=>{this.rebuildCache()},onVisibilityChange:(e,t)=>{t&&c.notifyVisible(e)}},void 0!==e.intersectionRootMargin?{intersectionRootMargin:e.intersectionRootMargin}:{}),c=new Dr(N(e=>this.writer.apply(e)),{...void 0!==e.debounceMs?{debounceMs:e.debounceMs}:{},...void 0!==e.disableVisibilityGate?{disableVisibilityGate:e.disableVisibilityGate}:{},...void 0!==e.visibilityGateThreshold?{visibilityGateThreshold:e.visibilityGateThreshold}:{},isVisible:e=>d.isVisible(e),getCacheSize:()=>u.elementCount,onFlush:e=>{this.pipeline.onFlush(e)}}),h=new Bn(e.originMatcher,{onUpdate:(e,t,n)=>{this.pipeline.handleUpdate(e,t,n)},onDocumentEvent:()=>{this.state.protocol.observe([\\\"document-events\\\"],o),r.emit(\\\"documentSave\\\",{timestamp:Date.now()})},onFocusField:e=>{this.deps.revealEditedField&&this.pipeline.revealField(e)},onInvalid:(e,t)=>{if(\\\"token\\\"===e){let e=new Error(`Preview token rejected (origin: ${t})`);r.emit(\\\"error\\\",{error:e,context:\\\"token\\\",code:\\\"LP0502\\\"})}(\\\"shape\\\"===e||\\\"type\\\"===e)&&!this.state.warnedProtocolShape&&(this.state.warnedProtocolShape=!0,a(`[live-preview] LP0503: ${t} posted a message this runtime does not recognise (${\\\"type\\\"===e?\\\"unknown message type\\\":\\\"unexpected shape\\\"}); it was ignored. A newer Payload or a custom sender: check that the versions match.`)),\\\"source\\\"===e&&!this.state.warnedForeignSource&&(this.state.warnedForeignSource=!0,a(`[live-preview] LP0501: a message from ${t} was ignored because it did not come from the window that framed or opened this page. \\\\`eventSourcePolicy\\\\` is 'parent-or-opener' by default since 2.0, where 1.x accepted any window on a trusted origin. Set \\\\`eventSourcePolicy: 'any'\\\\` if the admin posts from elsewhere.`)),o(\\\"LP0501 message rejected:\\\",e,t)},...void 0!==e.validateToken?{validateToken:e.validateToken}:{},...void 0!==e.eventSourcePolicy?{sourcePolicy:e.eventSourcePolicy}:{}}),f=e.dataMerge;this.deps={emitter:r,cache:u,observers:d,scheduler:c,bus:h,connection:new Qi,heartbeat:new Xi({...void 0!==e.heartbeatMs?{timeoutMs:e.heartbeatMs}:{},onTimeout:()=>{this.onHeartbeatTimeout()}}),renderers:l,resolveRenderer:e.resolveRenderer??(e=>l[e]),transformValue:e.transformValue,renderRichText:e.renderRichText,sanitizerPolicy:e.sanitizerPolicy,root:s,readyTargets:\\\"function\\\"==typeof e.readyTargets?e.readyTargets:(e=>()=>e)(e.readyTargets),sendReady:e.sendReady??y,onHeartbeatTimeout:e.onHeartbeatTimeout,log:o,warn:a,a11y:v(e),merger:void 0===f?null:new ji({serverURL:f.serverURL,...void 0!==f.apiRoute?{apiRoute:f.apiRoute}:{},...void 0!==f.depth?{depth:f.depth}:{},...void 0!==f.fetchFn?{fetchFn:f.fetchFn}:{},log:o}),mergeWindowMs:e.debounceMs??50,scopeBindingsByOwner:!0===e.scopeBindingsByOwner,lockedOrigin:e.lockedOrigin??(()=>{}),skipUnchanged:!0===e.skipUnchanged,dependencies:e.dependencies??{},strategies:e.strategies??{},revealEditedField:!0===e.revealEditedField,onUnfaithfulPatch:i(e),autoBind:e.autoBind??\\\"off\\\",hydration:e.hydration},this.writer=new ci(this.deps,this.state),this.pipeline=new zr(this.deps,this.state,()=>{this.rebuildCache()})}start(){let{state:e}=this;if(e.isRunning())return!1;e.started=!0,e.suspended=!1;try{return function(e){\\\"react\\\"===e.hydration?ae():\\\"vue\\\"===e.hydration&&fe();let{root:t}=e;if(!function(e){return 9===e.nodeType}(t)||\\\"loading\\\"!==t.readyState){pe(e);return}let n=()=>{e.isRunning()&&e.later(()=>{pe(e)})};t.addEventListener(\\\"DOMContentLoaded\\\",n,{once:!0}),e.defer(()=>{t.removeEventListener(\\\"DOMContentLoaded\\\",n)})}(this.startupHost()),!0}catch(e){throw this.rollbackFailedStart(),e}}startupHost(){let{state:e,deps:t}=this;return{root:t.root,hydration:t.hydration,isRunning:()=>e.isRunning(),defer:t=>{e.deferredStart=t},later:t=>{e.deferredStart=null;try{t()}catch(e){this.rollbackFailedStart(),this.reportError(e,\\\"startup\\\",\\\"LP0605\\\")}},hydrated:t=>{e.hydration=t},warn:t.warn,startNow:()=>{this.startNow()}}}startNow(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=wt(t.root)?St(t.root):t.root;if(null===n)throw new Error(\\\"LivePreviewRuntime: document.body unavailable\\\");if(t.observers.start(n),this.observedRoot=n,this.watchRootReplacement(),this.buildCacheAndObserve(),e.isRunning()&&(t.bus.attach(),t.emitter.emitWhile(\\\"init\\\",{timestamp:Date.now()},()=>e.isRunning()),e.isRunning()))for(let n of Vr){if(!e.isRunning())return;0===n?t.sendReady(t.readyTargets()):e.readyTimers.push(setTimeout(()=>{e.isRunning()&&this.sendReadyAfterStart()},n))}}suspend(){if(!this.state.isRunning())return!1;let e=this.release();return this.state.suspended=!0,e&&this.deps.emitter.emit(\\\"disconnect\\\",{reason:\\\"unload\\\",timestamp:Date.now()}),!0}destroy(){let{state:e,deps:t}=this;if(!e.isRunning()&&!e.suspended)return;let n=!!e.isRunning()&&this.release();e.suspended=!1,n&&t.emitter.emit(\\\"disconnect\\\",{reason:\\\"destroy\\\",timestamp:Date.now()}),t.a11y?.detach(),t.emitter.emit(\\\"destroy\\\",{timestamp:Date.now()})}release(){let{state:e,deps:t}=this;e.activeUpdate=null,e.started=!1;let n=e.deferredStart;e.deferredStart=null,null!==n&&this.runCleanup(n);for(let t of e.readyTimers)this.runCleanup(()=>{clearTimeout(t)});return e.readyTimers.length=0,this.runCleanup(()=>{t.heartbeat.stop()}),this.runCleanup(()=>{t.bus.detach()}),e.abortStrategies(),this.runCleanup(()=>{this.rootSentinel?.disconnect(),this.rootSentinel=null,this.observedRoot=null}),this.runCleanup(()=>{t.observers.stop()}),this.runCleanup(()=>{t.scheduler.destroy()}),this.runCleanup(()=>{t.merger?.destroy(),e.merges.destroy()}),t.cache.clear(),t.connection.markDisconnected()}rollbackFailedStart(){this.release(),this.runCleanup(()=>{this.deps.a11y?.detach()})}runCleanup(e){try{e()}catch(e){this.deps.log(\\\"cleanup failed:\\\",e)}}refreshCache(){this.state.isRunning()&&(this.state.revealer.reset(),this.followReplacedRoot()||this.rebuildCache())}watchRootReplacement(){let{root:e}=this.deps;!wt(e)||typeof MutationObserver>\\\"u\\\"||(this.rootSentinel?.disconnect(),this.rootSentinel=new MutationObserver(()=>{this.followReplacedRoot()}),this.rootSentinel.observe(e.documentElement,{childList:!0}))}followReplacedRoot(){let{root:e}=this.deps;if(!this.state.isRunning()||!wt(e))return!1;let t=St(e);return null!==t&&t!==this.observedRoot&&(this.observedRoot=t,this.deps.observers.start(t),this.rebuildCache(),!0)}get status(){return this.deps.connection.status}get cache(){return this.deps.cache}get updateCount(){return this.state.updateCount}get protocol(){return this.state.protocol.negotiation}inspect(){return function(e,t){let{cache:n,scheduler:i}=e,r=t.protocol.negotiation,l=t.activeUpdate,o=t.lastFlush,a=[],s=new Set,u=[];for(let[e,t]of n.entries()){a.push(e);for(let n of t)void 0!==n.owner&&s.add(n.owner),void 0!==n.guessed&&u.push({field:e,matched:n.guessed,attribute:n.targetAttribute??(\\\"IMG\\\"===n.element.tagName?\\\"src\\\":void 0)})}return{version:_i,started:t.started,status:e.connection.status,origins:{trusted:[...e.readyTargets()],locked:e.lockedOrigin()},protocol:{ours:r.ours,theirs:r.theirs,negotiated:r.negotiated,capabilities:[...r.capabilities].sort(),observed:[...r.observed].sort(),profile:re(r.observed).name},revisions:{accepted:t.updateCount,superseded:t.supersededCount,completed:t.completedCount,skippedUnchanged:t.skippedUnchangedCount,active:null===l?void 0:l.revision.revision},bindings:{elements:n.elementCount,fields:n.fieldCount,fieldNames:a.sort(),absentFields:[...t.absentFields].sort(),orphanFields:[...t.warnedOrphanFields].sort(),ownerScoped:e.scopeBindingsByOwner,owners:[...s].sort(),guessed:u.sort((e,t)=>e.field.localeCompare(t.field)),autoBind:{mode:e.autoBind,searchMs:t.autoBindSearchMs}},route:{handler:void 0!==e.strategies.route,...t.routeStats},fidelity:{mode:e.onUnfaithfulPatch,unfaithful:t.unfaithfulCount,escalated:t.escalatedCount,fields:[...t.unfaithfulFields].sort()},hydration:{mode:e.hydration??\\\"off\\\",state:t.hydration},fragments:{handler:void 0!==e.strategies.fragment,inFlight:l?.pendingFragments??0,...t.fragmentStats},scheduler:{pending:i.pendingCount,deferred:i.replayCount,visibilityGateThreshold:i.gateThreshold,visibilityGateActive:i.gateActive,lastFlush:null===o?void 0:{applied:o.applied,appliedFields:o.appliedFields,deferred:o.deferred,durationMs:o.durationMs}},plugins:[],renderers:Object.keys(e.renderers).sort()}}(this.deps,this.state)}buildCacheAndObserve(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=t.cache.buildFromRoot(t.root);if(t.log(\\\"cache\\\",n),e.isRunning()&&(t.emitter.emitWhile(\\\"cacheRefresh\\\",n,()=>e.isRunning()),e.isRunning()))for(let n of t.cache.values()){if(!e.isRunning())return;t.observers.observeElement(n.element)}}rebuildCache(){let{state:e,deps:t}=this;if(!e.isRunning())return;let n=new Map;for(let e of t.cache.values())n.set(e.element,e),t.observers.unobserveElement(e.element);if(this.buildCacheAndObserve(),e.isRunning()){for(let e of t.cache.values())n.get(e.element)?.fieldName===e.fieldName?t.scheduler.retarget(e):t.scheduler.forget(e.element),n.delete(e.element);for(let e of n.values())t.scheduler.forget(e.element)}}onHeartbeatTimeout(){let{state:e,deps:t}=this;if(!e.isRunning())return;t.bus.advanceGeneration();let n=e.activeUpdate;e.activeUpdate=null,null!==n&&t.scheduler.cancelRevision(n.revision),t.merger?.destroy(),e.merges.destroy();let i=t.connection.markDisconnected();try{t.onHeartbeatTimeout?.()}catch(e){t.log(\\\"heartbeat:\\\",e)}e.isRunning()&&(i&&this.isIdleDisconnected()&&(t.a11y?.announceDisconnected(),t.emitter.emitWhile(\\\"disconnect\\\",{reason:\\\"timeout\\\",timestamp:Date.now()},()=>this.isIdleDisconnected()),!e.isRunning()||(this.isIdleDisconnected()&&t.log(\\\"connection\\\",\\\"connected\\\",\\\"\\\\u2192\\\",\\\"disconnected\\\"),!e.isRunning()))||this.sendReadyAfterStart())}sendReadyAfterStart(){try{this.deps.sendReady(this.deps.readyTargets())}catch(e){this.reportError(e,\\\"ready\\\",\\\"LP0606\\\")}}reportError(e,t,n){let i=e instanceof Error?e:new Error(String(e));this.deps.emitter.emit(\\\"error\\\",{error:i,context:t,code:n})}isIdleDisconnected(){return this.state.isRunning()&&\\\"disconnected\\\"===this.deps.connection.status&&null===this.state.activeUpdate}},Gr=/^https?:\\\\/\\\\/(localhost|127\\\\.0\\\\.0\\\\.1)(?::\\\\d+)?$/i,qr=/^https?:\\\\/\\\\/[^/?#\\\\s]+$/i,Kr=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3],Jr=class{constructor(e={}){bn(this,Xr);let t=new Set;for(let n of e.additionalOrigins??[]){let e=kt(n);void 0!==e&&t.add(e)}let n;if(e.enableReferrerDetection??1){let t=e.referrer??(typ\",\"eof document<\\\"u\\\"?document.referrer:\\\"\\\");if(t.length>0)try{let e=new URL(t).origin;e&&\\\"null\\\"!==e&&(n=e)}catch{}}let i=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??function(){let e=function(){if(!(typ\",\"eof process>\\\"u\\\"))return\\\"production\\\"}();if(void 0!==e)return\\\"production\\\"!==e;if(typ\",\"eof window<\\\"u\\\"){let e=window.location.hostname;return\\\"localhost\\\"===e||\\\"127.0.0.1\\\"===e}return!1}());wn(this,Xr,[t,n,i,void 0!==n,void 0])}matches(e){return 0!==e.length&&\\\"null\\\"!==e&&(void 0!==yn(this,Xr)[4]?e===yn(this,Xr)[4]:!!(yn(this,Xr)[0].has(e)||0===yn(this,Xr)[0].size&&void 0!==yn(this,Xr)[1]&&e===yn(this,Xr)[1]||yn(this,Xr)[2]&&Gr.test(e)))}lockOrigin(e){return!!this.matches(e)&&(yn(this,Xr)[4]=e,!0)}unlockOrigin(){let e=yn(this,Xr)[4];return yn(this,Xr)[4]=void 0,e}get lockedOrigin(){return yn(this,Xr)[4]}enumerate(){if(void 0!==yn(this,Xr)[4])return[yn(this,Xr)[4]];let e=new Set(yn(this,Xr)[0]);if(0===yn(this,Xr)[0].size&&void 0!==yn(this,Xr)[1]&&e.add(yn(this,Xr)[1]),yn(this,Xr)[2])for(let t of Kr)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return yn(this,Xr)[3]}get isProductionUnconfigured(){return!(!Tt()||yn(this,Xr)[0].size>0||yn(this,Xr)[2]||void 0!==yn(this,Xr)[1])}get isReferrerOnlyTrust(){return!(yn(this,Xr)[0].size>0||yn(this,Xr)[2])&&void 0!==yn(this,Xr)[1]}},Xr=new WeakMap,Qr={1:\\\"left\\\",2:\\\"center\\\",3:\\\"right\\\",4:\\\"justify\\\"},Zr=new Set([\\\"left\\\",\\\"center\\\",\\\"right\\\",\\\"justify\\\",\\\"start\\\",\\\"end\\\"]),Yr=new Set([\\\"h1\\\",\\\"h2\\\",\\\"h3\\\",\\\"h4\\\",\\\"h5\\\",\\\"h6\\\"]),el=' target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\"',tl=(e,t)=>{let n=t.renderChildren(e.children??[]),i=Ft(e.fields),r=function(e,t){if(\\\"internal\\\"===t?.linkType)return function(e){let t=Ft(Ft(e)?.value),n=t?.url;if(\\\"string\\\"==typeof n&&n.length>0)return n;let i=t?.slug;return\\\"string\\\"==typeof i&&i.length>0?`/${i}`:void 0}(t.doc);let n=t?.url??e.url;return\\\"string\\\"==typeof n&&n.length>0?n:void 0}(e,i);if(void 0===r||!$(r))return n;let l=\\\"string\\\"==typeof e.title?` title=\\\"${Ke(e.title)}\\\"`:\\\"\\\";return`<a href=\\\"${Je(r)}\\\"${function(e,t,n){if(!0===t?.newTab||R(n))return el;let i=\\\"string\\\"==typeof e.target?e.target:\\\"\\\";return\\\"\\\"===i?\\\"\\\":\\\"_blank\\\"===i?el:` target=\\\"${Ke(i)}\\\"`}(e,i,r)}${l}>${n}</a>`},nl=new Map,il=\\\".lp-block:empty,.lp-inline-block:empty\\\",rl={text:e=>{let t=Ke(\\\"string\\\"==typeof e.text?e.text:\\\"\\\"),n=\\\"number\\\"==typeof e.format?e.format:0;return!!(16&n)&&(t=`<code>${t}</code>`),!!(1&n)&&(t=`<strong>${t}</strong>`),!!(2&n)&&(t=`<em>${t}</em>`),!!(8&n)&&(t=`<u>${t}</u>`),!!(4&n)&&(t=`<s>${t}</s>`),!!(32&n)&&(t=`<sub>${t}</sub>`),!!(64&n)&&(t=`<sup>${t}</sup>`),!!(128&n)&&(t=`<mark>${t}</mark>`),t},paragraph:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<p${$t(e)}${Rt(e)}>${n}</p>`},heading:(e,t)=>{let n=\\\"string\\\"==typeof e.tag?e.tag.toLowerCase():\\\"h2\\\",i=Yr.has(n)?n:\\\"h2\\\",r=t.renderChildren(e.children??[]);return`<${i}${$t(e)}${Rt(e)}>${r}</${i}>`},list:(e,t)=>{let n=\\\"string\\\"==typeof e.listType?e.listType:\\\"bullet\\\",i=\\\"number\\\"===n?\\\"ol\\\":\\\"ul\\\",r=\\\"number\\\"===n&&\\\"number\\\"==typeof e.start&&e.start>1?` start=\\\"${String(e.start)}\\\"`:\\\"\\\",l=\\\"check\\\"===n?' role=\\\"list\\\"':\\\"\\\",o=t.renderChildren(e.children??[]);return`<${i}${$t(e)}${Rt(e)}${r}${l}>${o}</${i}>`},listitem:(e,t)=>{let n=t.renderChildren(e.children??[]);if(\\\"boolean\\\"==typeof e.checked)return`<li role=\\\"checkbox\\\" aria-checked=\\\"${e.checked?\\\"true\\\":\\\"false\\\"}\\\"${Rt(e)}>${n}</li>`;let i=\\\"number\\\"==typeof e.value?` value=\\\"${Ke(String(e.value))}\\\"`:\\\"\\\";return`<li${$t(e)}${Rt(e)}${i}>${n}</li>`},link:tl,autolink:tl,quote:(e,t)=>{let n=t.renderChildren(e.children??[]);return`<blockquote${$t(e)}${Rt(e)}>${n}</blockquote>`},code:e=>{let t=Mt(\\\"string\\\"==typeof e.language?e.language:\\\"\\\");return`<pre><code${\\\"\\\"===t?\\\"\\\":` class=\\\"language-${t}\\\"`}>${Ke(Ot(e))}</code></pre>`},\\\"code-highlight\\\":e=>{let t=\\\"string\\\"==typeof e.text?e.text:\\\"\\\";return`<span${\\\"string\\\"==typeof e.highlightType?` class=\\\"token-${Mt(e.highlightType)}\\\"`:\\\"\\\"}>${Ke(t)}</span>`},linebreak:()=>\\\"<br>\\\",horizontalrule:()=>\\\"<hr>\\\",tab:()=>\\\"\\\\t\\\",upload:e=>{let t=Nt(e.value);if(void 0===t)return\\\"\\\";let n=t.url;if(\\\"string\\\"!=typeof n||!$(n))return\\\"\\\";let i=\\\"string\\\"==typeof t.mimeType?t.mimeType:\\\"\\\";return i.startsWith(\\\"video/\\\")?function(e,t){return`<video controls${Pt(e)}><source src=\\\"${Je(t)}\\\"${Lt(e)}></video>`}(t,n):i.startsWith(\\\"audio/\\\")?function(e,t){return`<audio controls><source src=\\\"${Je(t)}\\\"${Lt(e)}></audio>`}(t,n):\\\"\\\"===i||i.startsWith(\\\"image/\\\")?function(e,t){let n=\\\"string\\\"==typeof e.alt?Ke(e.alt):\\\"\\\";return`<img src=\\\"${Je(t)}\\\" alt=\\\"${n}\\\"${Pt(e)} loading=\\\"lazy\\\" decoding=\\\"async\\\">`}(t,n):function(e,t){let n=\\\"string\\\"==typeof e.filename?Ke(e.filename):Ke(t);return`<a href=\\\"${Je(t)}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">${n}</a>`}(t,n)},relationship:e=>{let t=\\\"string\\\"==typeof e.relationTo?e.relationTo:\\\"\\\",n=Ft(e.value),i=Ke((n&&Et(n))??`#${t}`),r=Mt(t),l=\\\"\\\"===r?' class=\\\"lp-relation\\\"':` class=\\\"lp-relation lp-relation--${r}\\\"`,o=n?.url;return\\\"string\\\"==typeof o&&$(o)?`<a href=\\\"${Je(o)}\\\"${l}>${i}</a>`:`<span${l}>${i}</span>`},block:(e,t)=>It(e,t,\\\"div\\\",\\\"lp-block\\\"),inlineBlock:(e,t)=>It(e,t,\\\"span\\\",\\\"lp-inline-block\\\"),table:(e,t)=>`<table${$t(e)}><tbody>${t.renderChildren(e.children??[])}</tbody></table>`,tablerow:(e,t)=>`<tr>${t.renderChildren(e.children??[])}</tr>`,tablecell:(e,t)=>{let n=\\\"number\\\"==typeof e.headerState?e.headerState:0,i=3&n?\\\"th\\\":\\\"td\\\";return`<${i}${1===n?' scope=\\\"col\\\"':2===n?' scope=\\\"row\\\"':\\\"\\\"}${jt(\\\"colspan\\\",e.colSpan)}${jt(\\\"rowspan\\\",e.rowSpan)}>${t.renderChildren(e.children??[])}</${i}>`}},ll=new Map,ol=!1,al=\\\"data-payload-text\\\",sl=new Set,ul=new Set,dl=new Set([\\\"DIV\\\",\\\"SECTION\\\",\\\"ARTICLE\\\"]),cl={name:\\\"richText\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){i.textContent=\\\"\\\";return}let r=n.sanitizerPolicy;if(void 0!==n.renderRichText){let l=n.renderRichText(t,{fieldName:e.fieldName,element:i,locale:n.locale});i.innerHTML=Le(De(l,r));return}if(_t(t)){let l=new Map,o=Dt(i,De(function(e,t={}){if(!_t(e))return\\\"\\\";let n=function(e){let t={renderChildren:e=>{let n=\\\"\\\";for(let i of e)n+=Wt(i,t);return n},resolveAlignment:At,resolveIndent:Ct,onUnrenderedBlock:e};return t}(t.onUnrenderedBlock).renderChildren(e.root.children);return!1===t.sanitize?n:void 0!==Ve()?function(e){return De(e,void 0,void 0)}(n):(function(){if(!ol){ol=!0;try{console.warn('[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; call setSanitizerDocument() (linkedom/jsdom) for server rendering, see \\\"HTML sanitization\\\" in docs/security.md.')}catch{}}}(),n)}(t,{sanitize:!1,onUnrenderedBlock:(e,t)=>{l.set(t,e)}}),r));for(let[t,i]of o){let r=l.get(t);void 0!==r&&Ht(e,n,r,i)}return}if(\\\"string\\\"!=typeof t)return!1;i.innerHTML=Le(De(t,r))})},hl={name:\\\"html\\\",render(e,t,n){if(tt(t)){e.element.textContent=\\\"\\\";return}let i=\\\"string\\\"==typeof t?t:et(t);e.element.innerHTML=Le(De(i,n.sanitizerPolicy))}},fl=new WeakSet,pl=qt(\\\"url\\\"),ml=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,gl=qt(\\\"email\\\",function(e){let t=e.trim();return ml.test(t)||!t.includes(\\\"@\\\")?t:`mailto:${t}`}),vl=[\\\"src\\\",\\\"srcset\\\",\\\"sizes\\\"],yl={name:\\\"image\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){Qt(i);return}let r=void 0!==e.locale,{media:l,candidate:o}=function(e,t,n,i){let r=void 0!==e.srcField&&e.srcField.length>0?Fe(n.allFields,e.srcField,n.locale,i):t,l=Nt(r);return{media:l,candidate:void 0===l?r:l.url}}(e,t,n,r),a=Gt(i,e.fieldName,o);if(\\\"none\\\"===a.kind)return!1;if(\\\"unsafe\\\"!==a.kind){if(\\\"IMG\\\"===i.tagName){let t=i;Jt(t,a.url,l);let o=function(e,t,n,i,r){if(void 0!==t&&t.length>0){let e=Fe(n,t,i,r);return\\\"string\\\"==typeof e?e:void 0}return e?.alt}(l,e.altField,n.allFields,n.locale,r);void 0!==o&&(t.alt=o);return}i.style.backgroundImage=`url('${function(e){return e.replace(/['\\\"()\\\\\\\\]/g,\\\"\\\\\\\\$&\\\")}(a.url)}')`}else Qt(i)})},bl={name:\\\"upload\\\",render:N((e,t)=>{let n=e.element;if(tt(t)){Zt(n);return}let i=Nt(t);if(void 0===i)return!1;let r=Gt(n,e.fieldName,i.url);if(\\\"none\\\"===r.kind)return!1;if(\\\"unsafe\\\"===r.kind){Zt(n);return}let l=r.url;if(\\\"IMG\\\"===n.tagName){let e=n;Jt(e,l,i),void 0!==i.alt&&(e.alt=i.alt);return}if(\\\"A\\\"===n.tagName){n.setAttribute(\\\"href\\\",l),n.textContent=i.filename??l;return}let o=Ke(i.filename??l);n.innerHTML=Le(`<a href=\\\"${Je(l)}\\\">${o}</a>`)})},wl={name:\\\"relationship\\\",render(e,t){let n=e.element;if(tt(t))n.removeAttribute(\\\"href\\\"),n.textContent=\\\"\\\";else{if(\\\"A\\\"===n.tagName&&!Array.isArray(t)){let i=Gt(n,e.fieldName,Ft(t)?.url);\\\"safe\\\"===i.kind?n.setAttribute(\\\"href\\\",i.url):\\\"unsafe\\\"===i.kind&&n.removeAttribute(\\\"href\\\")}n.textContent=Array.isArray(t)?t.map(Yt).join(\\\", \\\"):Yt(t)}}},Sl={name:\\\"select\\\",render(e,t,n){let i=e.element,r=tt(t)?[]:function(e){return Array.isArray(e)?e.map(et):[et(e)]}(t);if(\\\"SELECT\\\"!==i.tagName){if(\\\"INPUT\\\"===i.tagName&&\\\"radio\\\"===i.type){let e=i;e.checked=r.includes(e.value);return}i.textContent=r.map(e=>function(e,t){let n=t.schema?.options;if(!Array.isArray(n))return e;for(let t of n){let n=Ft(t);if(void 0!==n&&et(n.value)===e)return\\\"string\\\"==typeof n.label?n.label:e}return e}(e,n)).join(\\\", \\\")}else!function(e,t){if(e.multiple)for(let n of Array.from(e.options))n.selected=t.includes(n.value);else e.value=t[0]??\\\"\\\"}(i,r)}},Tl=new Set([\\\"\\\",\\\"false\\\",\\\"0\\\",\\\"off\\\",\\\"no\\\"]),kl={name:\\\"checkbox\\\",render(e,t){let n=e.element,i=function(e){return\\\"boolean\\\"==typeof e?e:\\\"string\\\"==typeof e?!Tl.has(e.trim().toLowerCase()):\\\"number\\\"==typeof e?0!==e:null!=e}(t);\\\"INPUT\\\"!==n.tagName||\\\"checkbox\\\"!==n.type?n.hasAttribute(\\\"aria-checked\\\")?n.setAttribute(\\\"aria-checked\\\",i?\\\"true\\\":\\\"false\\\"):n.textContent=i?\\\"true\\\":\\\"false\\\":n.checked=i}},Al=new Map,Cl=new Map,$l=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Rl=new Set([\\\"short\\\",\\\"medium\\\",\\\"long\\\",\\\"full\\\"]),Fl=/^[A-Za-z]{3}$/u,Nl=/^[0-4]$/u,Ml=new WeakSet,xl={name:\\\"date\\\",render(e,t,n){let i=e.element;if(tt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":(i.removeAttribute(\\\"datetime\\\"),i.textContent=\\\"\\\");return}let r=\\\"number\\\"==typeof t?t:et(t),l=new Date(r),o=!Number.isNaN(l.getTime()),a=String(r);\\\"INPUT\\\"!==i.tagName?(\\\"TIME\\\"===i.tagName&&i.setAttribute(\\\"datetime\\\",o?l.toISOString():a),i.textContent=o?function(e,t,n){let i=t.locale??n.locale??s(),r=ln(\\\"date\\\",t.format,t.element,t.fieldName)??El;try{return function(e,t){let n=en(e,t);return nt(Cl,n)??it(Cl,n,new Intl.DateTimeFormat(e,t),64)}(i,r).format(e)}catch{return e.toISOString()}}(l,e,n):a):i.value=o?function(e,t){let n=`${String(t.getFullYear()).padStart(4,\\\"0\\\")}-${on(t.getMonth()+1)}-${on(t.getDate())}`,i=`${on(t.getHours())}:${on(t.getMinutes())}`;return\\\"date\\\"===e?n:\\\"datetime-local\\\"===e?`${n}T${i}`:\\\"time\\\"===e?i:t.toISOString()}(i.type,l):a}},El={dateStyle:\\\"medium\\\",timeStyle:\\\"short\\\"},Ol={name:\\\"number\\\",render(e,t,n){let i=e.element;if(tt(t)){\\\"INPUT\\\"===i.tagName?i.value=\\\"\\\":i.textContent=\\\"\\\";return}let r=\\\"number\\\"==typeof t?t:Number(et(t));Number.isNaN(r)?i.textContent=et(t):\\\"INPUT\\\"!==i.tagName?i.textContent=function(e,t,n){let i=t.locale??n.locale??s(),r=ln(\\\"number\\\",t.format,t.element,t.fieldName);try{return function(e,t){let n=en(e,t);return nt(Al,n)??it(Al,n,new Intl.NumberFormat(e,t),64)}(i,r).format(e)}catch{return String(e)}}(r,e,n):i.value=String(r)}},Pl={name:\\\"array\\\",render:N((e,t,n)=>{let i=e.element;if(tt(t)){i.textContent=\\\"\\\";return}if(!Array.isArray(t))return!1;let r=e.arrayTemplate;if(void 0!==r&&r.length>0){let e=function(e,t){let n=Xe(t),i=\\\"\\\";for(let r=0;r<t.length;r+=1)i+=Qe(e,t[r],r,et,n);return i}(r,t),l=n.sanitizerPolicy,o=rt(r),a=Ze(i);i.innerHTML=Le(De(e,l,o));for(let e of Array.from(i.children))Ye(e,a);return}i.textContent=t.map(et).join(e.arraySeparator??\\\", \\\")})},Ll=new Map;!function(){if(typ\",\"eof window>\\\"u\\\"||!Tt()&&(typ\",\"eof window>\\\"u\\\"||null==window.opener))return;let e=window.__livePreview,t=JSON.stringify(hn());if(void 0!==e&&(void 0===e.configSignature||e.configSignature===t))return e.refresh(),e;let[n=[],r=\\\"\\\",l=\\\"/api\\\",o=1,a=!1,s=50,u=!0,d=0,c=!1,h=50,f=\\\"200px\\\",p=!0,m=!1,g=!1,v=!0,y=\\\"parent-or-opener\\\",b=\\\"strict\\\",w,S=!1,T=!1,k,A,C=\\\"off\\\",$]=hn(),R=function(e){let t=typeof __LIVE_PREVIEW_FRAGMENT__<\\\"u\\\"?__LIVE_PREVIEW_FRAGMENT__:void 0,n=t??(typeof __LIVE_PREVIEW_ROUTE__<\\\"u\\\"?__LIVE_PREVIEW_ROUTE__:void 0);if(void 0===n)return;let i=n.createRouteStrategy();return void 0===t||void 0===e||\\\"\\\"===e?{route:i}:{fragment:t.createFragmentStrategy({endpoint:e}),route:i}}(w),F=new Jr({additionalOrigins:n,enableReferrerDetection:!p,enableLocalhostMatching:!m});F.isProductionUnconfigured?kn(\\\"[live-preview] LP0101: No trusted origin. Pass allowedOrigins to generateInlineScript() (or to the adapter) \\\\u2014 the runtime reads no environment variable in the browser.\\\"):F.isReferrerOnlyTrust&&kn(\\\"[live-preview] LP0102: document.referrer fallback trusts any framing site. Set allowedOrigins and a frame-ancestors CSP in production.\\\");let N=new Cn,M=function(){let e=[cl,hl,pl,gl,yl,bl,wl,Sl,{...Sl,name:\\\"radio\\\"},kl,xl,Ol,Pl,{...Pl,name:\\\"blocks\\\"}];return function(e=[]){let t={};for(let n of e)t[n.name]=n;for(let[e,n]of Ll)t[e]=n;return Object.freeze(t)}([zt(\\\"text\\\"),zt(\\\"textarea\\\"),...e,an()])}(),x=new Hr({renderers:M,originMatcher:e=>F.matches(e),lockedOrigin:()=>F.lockedOrigin,readyTargets:()=>F.enumerate(),emitter:N,eventSourcePolicy:y,...\\\"\\\"!==r?{dataMerge:{serverURL:r,apiRoute:l,depth:o}}:{},debounceMs:s,heartbeatMs:d,intersectionRootMargin:f,disableVisibilityGate:c,visibilityGateThreshold:h,enableA11y:u,scopeBindingsByOwner:g,skipUnchanged:v,revealEditedField:S,onUnfaithfulPatch:i({onUnfaithfulPatch:A,onUnboundChange:k}),autoBind:C,...void 0!==$?{hydration:$}:{},sanitizerPolicy:b,...void 0!==R?{strategies:R}:{},onHeartbeatTimeout:()=>{F.unlockOrigin()},...a?{log:(...e)=>{An(\\\"[live-preview]\\\",...e)}}:{}});N.on(\\\"connect\\\",e=>{F.lockOrigin(e.origin)}),x.start(),e?.destroy();let E=function(e,t={}){let n=t.windowTarget??globalThis.window,i=t.documentTarget??globalThis.document,r=t.softNavigationEvents??[],l=()=>{e.suspend()},o=t=>{!0===t.persisted&&e.resume()},a=()=>{e.refreshCache()};n?.addEventListener(\\\"pagehide\\\",l),n?.addEventListener(\\\"pageshow\\\",o);for(let e of r)i?.addEventListener(e,a);let s=!1;return()=>{if(!s){s=!0,n?.removeEventListener(\\\"pagehide\\\",l),n?.removeEventListener(\\\"pageshow\\\",o);for(let e of r)i?.removeEventListener(e,a)}}}({suspend:()=>x.suspend(),resume:()=>x.start(),refreshCache:()=>{x.refreshCache()}}),O=Object.freeze({version:_i,configSignature:t,destroy:()=>{E(),x.destroy();let e=window;e.__livePreview===O&&delete e.__livePreview},refresh:()=>{x.refreshCache()},enumerateOrigins:()=>F.enumerate(),inspect:()=>x.inspect()});try{Object.defineProperty(window,\\\"__livePreview\\\",{value:O,writable:!1,configurable:!0})}catch(e){throw E(),x.destroy(),e}}()})();\"].join('');\nexport const RUNTIME_CONTENT_HASH = \"1d50b9cae44903e6\";\nexport const RUNTIME_INTEGRITY = \"sha384-ZCoe+Oq1pIxejgVIGoKL067f5rIUSiGFOM3DAUflYasc4S6acIJRSRGwwKLkyYOe\";\nexport const RUNTIME_BUILD_INFO: RuntimeBuildInfo = { generatedAt: \"2026-09-17T08:30:32.000Z\", size: 113485 };\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const FRAGMENT_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_FRAGMENT__=(()=>{var P=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},ne=(e,t,n,o)=>{if(t&&typeof t==\\\"object\\\"||typeof t==\\\"function\\\")for(let r of Z(t))!ee.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(o=Q(t,r))||o.enumerable});return e};var re=e=>ne(P({},\\\"__esModule\\\",{value:!0}),e);var De={};te(De,{createFragmentStrategy:()=>J,createRouteStrategy:()=>X});function w(e,t){let n=new AbortController,o=!1,r=()=>{n.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let i=setTimeout(()=>{o=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>o,dispose:()=>{clearTimeout(i),e.removeEventListener(\\\"abort\\\",r)}}}function S(e){return e instanceof Error?e.message:String(e)}var A=\\\"data-payload-island\\\",Le=`astro-island, [${A}]`;function oe(e){return e.tagName.toLowerCase()===\\\"astro-island\\\"||e.hasAttribute(A)}function ie(e){return e.getAttribute(A)===\\\"patch\\\"}function ae(e){return oe(e)&&!ie(e)}function _(e){let t=e;for(;t!==null;){if(ae(t))return!0;t=t.parentElement}return!1}function k(e){if(e==null)return[];let t=new Set,n=[];for(let o of e.split(/[\\\\s,]+/)){let r=o.trim();r.length===0||t.has(r)||(t.add(r),n.push(r))}return n}var b=\\\"data-payload-fragment\\\";var N=\\\"data-payload-fragment-key\\\",le=\\\"data-payload-depends\\\";function I(e){let t=e.getAttribute(b);if(t===null||t.length===0)return null;let n=e.getAttribute(N);return{element:e,id:t,key:n===null||n.length===0?void 0:n,dependsOn:k(e.getAttribute(le))}}function L(e,t){let n=[];for(let o of e.querySelectorAll(`[${b}]`)){let r=I(o);r===null||_(o)||r.dependsOn.length>0&&!r.dependsOn.some(i=>t.has(i))||n.push(r)}return n}var B=\\\"x-payload-fragment-version\\\";function D(e){return typeof e==\\\"object\\\"&&e!==null&&!Array.isArray(e)}function C(e){if(!D(e))return null;let{html:t,boundary:n,revision:o,metadata:r}=e;return typeof t!=\\\"string\\\"||!D(n)||typeof n.id!=\\\"string\\\"||n.key!==void 0&&typeof n.key!=\\\"string\\\"||typeof o!=\\\"number\\\"||!D(r)||typeof r.renderedAt!=\\\"string\\\"||typeof r.renderer!=\\\"string\\\"?null:e}function U(e){let t={};for(let[n,o]of Object.entries(e))o!==void 0&&(t[n]=o);return t}function H(e){let t=0,n=[],o=()=>{let r=n.shift();r===void 0?t-=1:r()};return async r=>{t<e?t+=1:await new Promise(i=>{n.push(i)});try{return await r()}finally{o()}}}var de=5e3,ue=4,ce=512*1024,T={status:\\\"superseded\\\"};function h(e,t){return{status:\\\"failed\\\",code:e,reason:t}}function fe(e){let t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with \\\"/\\\"')};if((typeof e!=\\\"string\\\"||!e.startsWith(\\\"/\\\")||e.startsWith(\\\"//\\\")||e.includes(\\\"\\\\\\\\\\\"))&&t(),typeof location<\\\"u\\\"){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}function me(e){return typeof e==\\\"object\\\"&&e!==null&&typeof e.getReader==\\\"function\\\"}async function ye(e,t,n){let o=e.body;if(!me(o)){let d=await e.text();return new TextEncoder().encode(d).byteLength>t?null:d}let r=o.getReader(),i=()=>{r.cancel().catch(()=>{})};n.addEventListener(\\\"abort\\\",i,{once:!0});let s=new TextDecoder,a=\\\"\\\",c=0;try{for(;;){let{done:d,value:p}=await r.read();if(d)break;if(c+=p.byteLength,c>t)return i(),null;a+=s.decode(p,{stream:!0})}}finally{n.removeEventListener(\\\"abort\\\",i)}return a+s.decode()}function K(e){let t=fe(e.endpoint),n=e.timeoutMs??de,o=e.maxResponseBytes??ce,r=H(Math.max(1,e.maxConcurrent??ue)),i=new Map;async function s(a,c){let d=()=>a.signal.aborted;if(d())return T;let p=e.location??location,f=U({fragment:c.id,key:c.key,route:p.pathname,search:p.search,revision:a.revision,locale:a.locale,collectionSlug:a.collectionSlug,globalSlug:a.globalSlug,fields:a.fields}),l=w(a.signal,n),y=u=>d()?T:l.timedOut()?h(\\\"LP0801\\\",`timeout after ${String(n)} ms`):h(\\\"LP0801\\\",S(u));try{let u;try{u=await(e.fetch??fetch)(t,{method:\\\"POST\\\",credentials:\\\"same-origin\\\",headers:{...e.headers,accept:\\\"application/json\\\",\\\"content-type\\\":\\\"application/json\\\",[B]:String(1)},body:JSON.stringify(f),signal:l.signal})}catch(M){return y(M)}if(d())return T;if(u.status===401||u.status===403)return h(\\\"LP0803\\\",`endpoint refused the preview (${String(u.status)})`);if(!u.ok)return h(\\\"LP0801\\\",`endpoint answered ${String(u.status)}`);let g=u.headers.get(\\\"content-type\\\")??\\\"\\\";if(!g.toLowerCase().startsWith(\\\"application/json\\\"))return h(\\\"LP0802\\\",`unexpected content type \\\"${g}\\\"`);if(Number(u.headers.get(\\\"content-length\\\")??\\\"0\\\")>o)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let E;try{E=await ye(u,o,l.signal)}catch(M){return y(M)}if(d())return T;if(l.timedOut())return h(\\\"LP0801\\\",`timeout after ${String(n)} ms`);if(E===null)return h(\\\"LP0802\\\",\\\"response exceeds the size limit\\\");let x;try{x=JSON.parse(E)}catch{return h(\\\"LP0802\\\",\\\"response is not JSON\\\")}let R=C(x);return R===null?h(\\\"LP0802\\\",\\\"response has the wrong shape\\\"):R.boundary.id!==c.id?h(\\\"LP0802\\\",\\\"response is for another boundary\\\"):R.revision!==a.revision?T:{status:\\\"rendered\\\",html:R.html,metadata:R.metadata}}finally{l.dispose()}}return(a,c)=>{let d=`${c.id} ${c.key??\\\"\\\"} ${String(a.revision)}`,p=i.get(d);if(p!==void 0)return p;let f=r(()=>s(a,c));i.set(d,f);let l=()=>{i.get(d)===f&&i.delete(d)};return f.then(l,l),f}}var O=\\\"data-payload-owned\\\",pe=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function q(e,t){for(let n of t.keyAttributes){let o=e.getAttribute(n);if(o!==null&&o.length>0)return`${n}=${o}`}}function F(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(A)||e.hasAttribute(O))return!0;let t=e.getAttribute(\\\"contenteditable\\\");return t!==null&&t!==\\\"false\\\"}function ge(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!F(e)&&!F(t)}function v(e,t,n){if(!ge(e,t))return t;let o=Re(e);return he(e,t),n.retainChildrenOf?.(e,t)!==!0&&Ee(e,t,n),Ae(o),e}function he(e,t){for(let n of Array.from(e.attributes))t.hasAttribute(n.name)||pe.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(let n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}function Ee(e,t,n){let o=be(e,n),r=new Set(o.values()),i=Array.from(e.childNodes).filter(f=>!r.has(f)),s=new Set,a=new Set,c=Array.from(t.childNodes),d=e.firstChild,p=0;for(let f=0;f<c.length;f+=1){let l=c[f],y=null,u=l instanceof Element?q(l,n):void 0;if(u!==void 0&&a.has(u)&&(u=void 0),u!==void 0){a.add(u);let m=o.get(u);if(m!==void 0&&!s.has(m)&&(y=$(m,l,n)===m?m:null,y===null)){m.replaceWith(l),s.add(l),d=l.nextSibling;continue}}else{for(;p<i.length;){let m=i[p];if(p+=1,!s.has(m)){if(G(m,l)){y=$(m,l,n)===m?m:null,y===null&&(e.replaceChild(l,m),s.add(l),d=l.nextSibling);break}if(m instanceof Element){let E=c[f+1];if(!(l instanceof Element)||E!==void 0&&G(m,E)){p-=1;break}e.replaceChild(l,m),s.add(l),d=l.nextSibling;break}if(!(l instanceof Element)){e.replaceChild(l,m),s.add(l),d=l.nextSibling;break}}}if(y===null&&s.has(l))continue}let g=y??l;for(s.add(g);d!==null&&d!==g&&!s.has(d)&&Se(d);)d=d.nextSibling;g!==d&&e.insertBefore(g,d),d=g.nextSibling}for(let f of Array.from(e.childNodes))s.has(f)||f.remove()}function $(e,t,n){return e instanceof Element&&t instanceof Element?F(e)&&F(t)?e:v(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function Se(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function G(e,t){return e.nodeType!==t.nodeType?!1:e instanceof Element&&t instanceof Element?e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI:!0}function be(e,t){let n=new Map,o;for(let r of Array.from(e.children)){let i=q(r,t);if(i!==void 0){if(n.has(i)){o??(o=i.slice(i.indexOf(\\\"=\\\")+1));continue}n.set(i,r)}}return o!==void 0&&t.onDuplicateKey?.(e,o),n}function Re(e){let t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement)||!e.contains(t))return null;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null;return{element:t,selection:n}}function Ae(e){if(e===null)return;let{element:t,selection:n}=e;if(!(t.ownerDocument.activeElement===t||!t.isConnected))try{t.focus({preventScroll:!0});let[o,r]=n??[null,null];o!==null&&r!==null&&t.setSelectionRange(o,r)}catch{}}var W=\\\"data-payload-key\\\";var Te=\\\"__livePreviewRouteRefresh\\\";function xe(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function z(){return xe()?.[Te]}var j=\\\"data-payload-strategy\\\",Y=\\\"data-payload-field\\\",we=\\\"data-payload-depends\\\",ke=\\\"x-payload-live-preview\\\",Fe=8e3,Oe=1e3;function Me(e){let t=e.getAttribute(j);return t!==null?t===\\\"route\\\":e.closest(\\\"head\\\")!==null}function Pe(e){let t=e.getAttribute(Y),n=k(e.getAttribute(we));return t===null||t.length===0?n:[t,...n]}function V(e){if(e.tagName===\\\"META\\\"){let t=e.getAttribute(\\\"name\\\")??e.getAttribute(\\\"property\\\");return t===null?null:`meta:${t}`}return e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"?\\\"link:canonical\\\":null}function Ne(e,t){t.title!==e.title&&(e.title=t.title);let n=new Map;for(let r of e.head.querySelectorAll(\\\"meta, link\\\")){let i=V(r);i!==null&&!n.has(i)&&n.set(i,r)}let o=new Set;for(let r of t.head.querySelectorAll(\\\"meta, link\\\")){let i=V(r);if(i===null)continue;o.add(i);let s=n.get(i);if(s===void 0){e.head.append(e.importNode(r,!0));continue}if(!s.hasAttribute(O))for(let a of Array.from(r.attributes))s.getAttribute(a.name)!==a.value&&s.setAttribute(a.name,a.value)}for(let[r,i]of n)!o.has(r)&&!i.hasAttribute(O)&&i.remove()}function X(e={}){let t=e.timeoutMs??Fe,n=e.minIntervalMs??Oe,o=-1/0;return{plan(r,i){for(let s of r.querySelectorAll(`[${Y}], [${j}=\\\"route\\\"]`)){if(!Me(s))continue;let a=Pe(s);if(a.length===0||a.some(c=>i.has(c)))return!0}return!1},async refresh(r){let i=Date.now(),s=n-(i-o);if(s>0)return r.retryAfter?.(s),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(i-o)} ms ago`),\\\"refused\\\";o=i;let a=e.document??document,c=e.location??location,d=e.window??window,p=w(r.signal,t),f=l=>{if(r.signal.aborted)return\\\"superseded\\\";let y=p.timedOut()?`route refresh timed out after ${String(t)} ms`:S(l);return r.log(\\\"LP0801\\\",y),\\\"failed\\\"};try{let l=z();if(l!==void 0){try{await l()}catch(u){return f(u)}return r.isCurrent()?\\\"refreshed\\\":\\\"superseded\\\"}let y;try{y=await(e.fetch??fetch)(c.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[ke]:\\\"route\\\"},signal:p.signal})}catch(u){return f(u)}if(r.signal.aborted)return\\\"superseded\\\";if(!y.ok||!(y.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(y.status)} ${y.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let u=await y.text();if(!r.isCurrent())return\\\"superseded\\\";let g=new DOMParser().parseFromString(u,\\\"text/html\\\"),m=d.scrollX,E=d.scrollY;return Ne(a,g),v(a.body,g.body,{keyAttributes:[W,N,b],retainChildrenOf:x=>x.hasAttribute(b)}),d.scrollTo(m,E),\\\"refreshed\\\"}catch(u){return f(u)}}finally{p.dispose()}}}}function Ie(e){return{plan:(t,n)=>L(t,n).map(o=>o.element),async render(t,n){let o={rendered:0,failed:0,superseded:0},r={revision:t.revision,receivedAt:t.receivedAt,fields:t.fields,locale:t.locale,collectionSlug:t.collectionSlug,globalSlug:t.globalSlug,signal:t.signal};return await Promise.all(n.map(async i=>{let s=I(i);if(s===null)return;let a;try{a=await e(r,s)}catch(c){a={status:\\\"failed\\\",code:\\\"LP0801\\\",reason:S(c)}}if(!t.isCurrent()||a.status===\\\"superseded\\\"){o.superseded+=1,t.log(\\\"LP0804\\\",`fragment \\\"${s.id}\\\" for revision ${String(r.revision)} discarded as superseded`);return}if(a.status===\\\"rendered\\\"){t.morph(i,a.html),t.rendered(i,s.id,s.key),o.rendered+=1;return}t.failed(i,s.id,s.key,a.code,a.reason),t.isCurrent()&&t.patch(i),o.failed+=1})),o}}}function J(e){return Ie(K(e))}return re(De);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const ROUTE_SOURCE = /* @__PURE__ */ [\"\\\"use strict\\\";var __LIVE_PREVIEW_ROUTE__=(()=>{var S=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var $=(e,n)=>{for(var t in n)S(e,t,{get:n[t],enumerable:!0})},H=(e,n,t,o)=>{if(n&&typeof n==\\\"object\\\"||typeof n==\\\"function\\\")for(let r of L(n))!K.call(e,r)&&r!==t&&S(e,r,{get:()=>n[r],enumerable:!(o=U(n,r))||o.enumerable});return e};var z=e=>H(S({},\\\"__esModule\\\",{value:!0}),e);var ae={};$(ae,{createRouteStrategy:()=>B});var A=\\\"data-payload-island\\\",se=`astro-island, [${A}]`;var b=\\\"data-payload-owned\\\",W=new Set([\\\"open\\\",\\\"value\\\",\\\"checked\\\",\\\"selected\\\"]);function k(e,n){for(let t of n.keyAttributes){let o=e.getAttribute(t);if(o!==null&&o.length>0)return`${t}=${o}`}}function E(e){if(e.tagName.toLowerCase().includes(\\\"-\\\")||e.hasAttribute(A)||e.hasAttribute(b))return!0;let n=e.getAttribute(\\\"contenteditable\\\");return n!==null&&n!==\\\"false\\\"}function q(e,n){return e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI&&!E(e)&&!E(n)}function R(e,n,t){if(!q(e,n))return n;let o=X(e);return Y(e,n),t.retainChildrenOf?.(e,n)!==!0&&G(e,n,t),J(o),e}function Y(e,n){for(let t of Array.from(e.attributes))n.hasAttribute(t.name)||W.has(t.name.toLowerCase())||e.removeAttribute(t.name);for(let t of Array.from(n.attributes))e.getAttribute(t.name)!==t.value&&e.setAttribute(t.name,t.value)}function G(e,n,t){let o=j(e,t),r=new Set(o.values()),l=Array.from(e.childNodes).filter(m=>!r.has(m)),a=new Set,f=new Set,g=Array.from(n.childNodes),s=e.firstChild,y=0;for(let m=0;m<g.length;m+=1){let i=g[m],u=null,c=i instanceof Element?k(i,t):void 0;if(c!==void 0&&f.has(c)&&(c=void 0),c!==void 0){f.add(c);let d=o.get(c);if(d!==void 0&&!a.has(d)&&(u=x(d,i,t)===d?d:null,u===null)){d.replaceWith(i),a.add(i),s=i.nextSibling;continue}}else{for(;y<l.length;){let d=l[y];if(y+=1,!a.has(d)){if(w(d,i)){u=x(d,i,t)===d?d:null,u===null&&(e.replaceChild(i,d),a.add(i),s=i.nextSibling);break}if(d instanceof Element){let h=g[m+1];if(!(i instanceof Element)||h!==void 0&&w(d,h)){y-=1;break}e.replaceChild(i,d),a.add(i),s=i.nextSibling;break}if(!(i instanceof Element)){e.replaceChild(i,d),a.add(i),s=i.nextSibling;break}}}if(u===null&&a.has(i))continue}let p=u??i;for(a.add(p);s!==null&&s!==p&&!a.has(s)&&V(s);)s=s.nextSibling;p!==s&&e.insertBefore(p,s),s=p.nextSibling}for(let m of Array.from(e.childNodes))a.has(m)||m.remove()}function x(e,n,t){return e instanceof Element&&n instanceof Element?E(e)&&E(n)?e:R(e,n,t):(e.nodeValue!==n.nodeValue&&(e.nodeValue=n.nodeValue),e)}function V(e){return e.nodeType===Node.TEXT_NODE&&(e.nodeValue??\\\"\\\").trim().length===0}function w(e,n){return e.nodeType!==n.nodeType?!1:e instanceof Element&&n instanceof Element?e.tagName===n.tagName&&e.namespaceURI===n.namespaceURI:!0}function j(e,n){let t=new Map,o;for(let r of Array.from(e.children)){let l=k(r,n);if(l!==void 0){if(t.has(l)){o??(o=l.slice(l.indexOf(\\\"=\\\")+1));continue}t.set(l,r)}}return o!==void 0&&n.onDuplicateKey?.(e,o),t}function X(e){let n=e.ownerDocument.activeElement;if(!(n instanceof HTMLElement)||!e.contains(n))return null;let t=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd]:null;return{element:n,selection:t}}function J(e){if(e===null)return;let{element:n,selection:t}=e;if(!(n.ownerDocument.activeElement===n||!n.isConnected))try{n.focus({preventScroll:!0});let[o,r]=t??[null,null];o!==null&&r!==null&&n.setSelectionRange(o,r)}catch{}}var I=\\\"data-payload-key\\\";function N(e){if(e==null)return[];let n=new Set,t=[];for(let o of e.split(/[\\\\s,]+/)){let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}var Q=\\\"__livePreviewRouteRefresh\\\";function Z(){return typ\",\"eof window>\\\"u\\\"?void 0:window}function M(){return Z()?.[Q]}var T=\\\"data-payload-fragment\\\";function v(e,n){let t=new AbortController,o=!1,r=()=>{t.abort()};e.addEventListener(\\\"abort\\\",r,{once:!0});let l=setTimeout(()=>{o=!0,t.abort()},n);return{signal:t.signal,timedOut:()=>o,dispose:()=>{clearTimeout(l),e.removeEventListener(\\\"abort\\\",r)}}}function D(e){return e instanceof Error?e.message:String(e)}var P=\\\"data-payload-fragment-key\\\";var C=\\\"data-payload-strategy\\\",_=\\\"data-payload-field\\\",ee=\\\"data-payload-depends\\\",ne=\\\"x-payload-live-preview\\\",te=8e3,re=1e3;function oe(e){let n=e.getAttribute(C);return n!==null?n===\\\"route\\\":e.closest(\\\"head\\\")!==null}function le(e){let n=e.getAttribute(_),t=N(e.getAttribute(ee));return n===null||n.length===0?t:[n,...t]}function O(e){if(e.tagName===\\\"META\\\"){let n=e.getAttribute(\\\"name\\\")??e.getAttribute(\\\"property\\\");return n===null?null:`meta:${n}`}return e.tagName===\\\"LINK\\\"&&e.getAttribute(\\\"rel\\\")===\\\"canonical\\\"?\\\"link:canonical\\\":null}function ie(e,n){n.title!==e.title&&(e.title=n.title);let t=new Map;for(let r of e.head.querySelectorAll(\\\"meta, link\\\")){let l=O(r);l!==null&&!t.has(l)&&t.set(l,r)}let o=new Set;for(let r of n.head.querySelectorAll(\\\"meta, link\\\")){let l=O(r);if(l===null)continue;o.add(l);let a=t.get(l);if(a===void 0){e.head.append(e.importNode(r,!0));continue}if(!a.hasAttribute(b))for(let f of Array.from(r.attributes))a.getAttribute(f.name)!==f.value&&a.setAttribute(f.name,f.value)}for(let[r,l]of t)!o.has(r)&&!l.hasAttribute(b)&&l.remove()}function B(e={}){let n=e.timeoutMs??te,t=e.minIntervalMs??re,o=-1/0;return{plan(r,l){for(let a of r.querySelectorAll(`[${_}], [${C}=\\\"route\\\"]`)){if(!oe(a))continue;let f=le(a);if(f.length===0||f.some(g=>l.has(g)))return!0}return!1},async refresh(r){let l=Date.now(),a=t-(l-o);if(a>0)return r.retryAfter?.(a),r.log(\\\"LP0805\\\",`route refresh for revision ${String(r.revision)} refused: the previous one was ${String(l-o)} ms ago`),\\\"refused\\\";o=l;let f=e.document??document,g=e.location??location,s=e.window??window,y=v(r.signal,n),m=i=>{if(r.signal.aborted)return\\\"superseded\\\";let u=y.timedOut()?`route refresh timed out after ${String(n)} ms`:D(i);return r.log(\\\"LP0801\\\",u),\\\"failed\\\"};try{let i=M();if(i!==void 0){try{await i()}catch(c){return m(c)}return r.isCurrent()?\\\"refreshed\\\":\\\"superseded\\\"}let u;try{u=await(e.fetch??fetch)(g.href,{method:\\\"GET\\\",credentials:\\\"same-origin\\\",cache:\\\"no-store\\\",headers:{accept:\\\"text/html\\\",[ne]:\\\"route\\\"},signal:y.signal})}catch(c){return m(c)}if(r.signal.aborted)return\\\"superseded\\\";if(!u.ok||!(u.headers.get(\\\"content-type\\\")??\\\"\\\").includes(\\\"text/html\\\"))return r.log(\\\"LP0802\\\",`route answered ${String(u.status)} ${u.headers.get(\\\"content-type\\\")??\\\"\\\"}`),\\\"failed\\\";try{let c=await u.text();if(!r.isCurrent())return\\\"superseded\\\";let p=new DOMParser().parseFromString(c,\\\"text/html\\\"),d=s.scrollX,h=s.scrollY;return ie(f,p),R(f.body,p.body,{keyAttributes:[I,P,T],retainChildrenOf:F=>F.hasAttribute(T)}),s.scrollTo(d,h),\\\"refreshed\\\"}catch(c){return m(c)}}finally{y.dispose()}}}}return z(ae);})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function o(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function t(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function e(){return o()||t()}function i(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}e()&&i();})();\"].join('');\n","// Auto-generated by scripts/build-runtime.ts — do not edit.\nexport const LOADER_REACT_SOURCE: string = /* @__PURE__ */ [\"\\\"use strict\\\";(()=>{function f(){if(typ\",\"eof window>\\\"u\\\")return!1;try{return window.self!==window.top}catch{return!0}}function m(){return typ\",\"eof window>\\\"u\\\"?!1:window.opener!=null}function d(){return f()||m()}var t=\\\"__livePreviewHydration\\\";function l(){if(typ\",\"eof window>\\\"u\\\")return;let n=window;return n[t]??(n[t]={armed:!1,committed:!1,commits:[],onCommit:void 0,waiters:[]})}function u(){let n=l();if(n===void 0||n.armed)return;n.armed=!0;let e=window,o=e.__REACT_DEVTOOLS_GLOBAL_HOOK__??(e.__REACT_DEVTOOLS_GLOBAL_HOOK__=_()),a=o.onCommitFiberRoot;o.onCommitFiberRoot=function(c,i,...s){try{a?.call(this,c,i,...s)}catch{}let r=i?.containerInfo;n.onCommit===void 0?n.commits.push(r):n.onCommit(r)}}function _(){let n=new Map;return{supportsFiber:!0,renderers:n,inject:e=>{let o=n.size+1;return n.set(o,e),o}}}function p(){let n=document.createElement(\\\"script\\\");n.src=__LP_RUNTIME_SRC__,__LP_RUNTIME_INTEGRITY__!==\\\"\\\"&&(n.integrity=__LP_RUNTIME_INTEGRITY__,n.crossOrigin=\\\"anonymous\\\"),n.async=!0,document.head.appendChild(n)}u();d()&&p();})();\"].join('');\n","/**\n * The inline script's configuration and its positional wire order: the\n * generator writes the tuple, `src/core/runtime.ts` destructures it, and\n * `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.\n */\n\nimport type { DefaultsProfile } from '@/types/defaults-profile';\n\nexport interface InlineScriptConfig {\n /** Trusted admin origins, merged with the detected ones. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API with credentials. Requires `mergeDepth`. */\n readonly serverURL?: string;\n /** REST route prefix used with `serverURL`. Default `/api`. */\n readonly apiRoute?: string;\n /** Population depth used with `serverURL`. Required with `serverURL` unless `defaults: 'v1'`. */\n readonly mergeDepth?: number;\n /** Verbose console logging. Default `false`. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates in ms. Default `50`. */\n readonly debounceMs?: number;\n /** Mount the screen-reader live region. Default `true`. */\n readonly enableA11y?: boolean;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** Apply every update regardless of viewport position. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** `rootMargin` of the IntersectionObserver. Default `'200px'`. */\n readonly intersectionRootMargin?: string;\n /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly disableReferrerDetection?: boolean;\n /** Disable the dev-mode localhost matcher (any port on `localhost`/`127.0.0.1`). Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Update only bindings under a matching `data-payload-owner`. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip bindings whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: 'any' | 'parent-or-opener';\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** Same-origin path of a fragment endpoint; the script then carries the fragment client ahead of the runtime (ADR 0011). */\n readonly fragmentEndpoint?: string;\n /**\n * Carry the route strategy, so a binding in `<head>` or one marked\n * `data-payload-strategy=\"route\"` refreshes the route. `fragmentEndpoint`\n * implies it — the fragment prelude already contains it. Default `false`.\n */\n readonly routeStrategy?: boolean;\n /**\n * The 2.0 name for `onUnfaithfulPatch`, kept until 3.0. `'route'` means\n * `'escalate'`, `'ignore'` means `'ignore'`.\n *\n * @deprecated Renamed to `onUnfaithfulPatch`.\n */\n readonly onUnboundChange?: 'ignore' | 'route';\n /**\n * What to do when the runtime knows a patch cannot reach what the server\n * would have drawn. `'escalate'` (the default) hands the region to the\n * fragment strategy when a boundary covers it and to the route otherwise, so\n * it needs `fragmentEndpoint` or `routeStrategy` to do anything. `'warn'`\n * reports LP0411 and keeps the patch; `'ignore'` keeps it silently.\n */\n readonly onUnfaithfulPatch?: 'ignore' | 'warn' | 'escalate';\n /**\n * Find bindings by value on the connection's first message (ADR 0014): a\n * scalar whose value is the whole content of exactly one element is bound\n * to it as if `data-payload-field` stood there. Default `'off'`.\n */\n readonly autoBind?: 'off' | 'unique';\n /**\n * The framework that hydrates this page (ADR 0015). Under `'react'` the\n * runtime holds its first write until React has committed the tree that\n * holds the bindings — otherwise React finds markup it did not render,\n * throws `Hydration failed` and regenerates the tree, and the write is gone.\n * Under `'vue'` it holds the write until Vue has mounted the app around them\n * — otherwise Vue's hydration repairs the write back to the server's value,\n * quietly. The Next.js and Nuxt adapters set it on every script they emit; a\n * page built by hand with `generateInlineScript()` may. Omitted: the runtime\n * starts on `DOMContentLoaded`, as on a static page.\n */\n readonly hydration?: 'react' | 'vue';\n /**\n * Which defaults the omitted options fall back to, resolved by the generator\n * rather than the runtime, whose own fallbacks are the 2.0 rows: `'v1'`\n * writes its four runtime rows into their slots (an explicit option still\n * wins) and relaxes the `mergeDepth` check. The resolved value always\n * travels, in the last slot, so a reader of the served page knows what an\n * empty slot means instead of guessing it — `pll doctor --v2` reads it. The\n * runtime does not: every row the profile decides is already in its slot.\n */\n readonly defaults?: DefaultsProfile;\n /**\n * A runtime artifact to embed instead of the full one — today only\n * `LEAN_RUNTIME` from `payload-live-preview/lean`, which leaves out the\n * strategies, the keyed morph, the structural arrays, the item templates, the\n * announcer and auto-binding (about 7 KB gzip less on the page) and reports\n * LP0104 when a page needs one of them.\n *\n * It is an imported value rather than a `profile: 'lean'` string on purpose:\n * a second artifact behind a string option would sit in every build that can\n * reach the generator; measured, it grew each adapter entry by the artifact's\n * whole size. This way the bytes follow the import.\n *\n * Not serialized: it decides which bytes are emitted, not how they behave.\n */\n readonly runtime?: RuntimeArtifact;\n}\n\n/**\n * A runtime build this package produces. `source` is the IIFE the page runs;\n * the two digests describe the same bytes as a servable asset, so asset\n * delivery can hash-name and SRI-verify whichever artifact was chosen without\n * hashing anything at request time.\n */\nexport interface RuntimeArtifact {\n readonly profile: 'lean';\n readonly source: string;\n /** Short content hash, for the asset's file name. */\n readonly contentHash: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n}\n\n/** Keys that travel in the wire tuple, in slot order. */\nexport const INLINE_CONFIG_KEYS = [\n 'allowedOrigins',\n 'serverURL',\n 'apiRoute',\n 'mergeDepth',\n 'debug',\n 'debounceMs',\n 'enableA11y',\n 'heartbeatMs',\n 'disableVisibilityGate',\n 'visibilityGateThreshold',\n 'intersectionRootMargin',\n 'disableReferrerDetection',\n 'disableLocalhostMatching',\n 'scopeBindingsByOwner',\n 'skipUnchanged',\n 'eventSourcePolicy',\n 'sanitizerPolicy',\n 'fragmentEndpoint',\n 'revealEditedField',\n 'routeStrategy',\n 'onUnboundChange',\n 'onUnfaithfulPatch',\n 'autoBind',\n 'hydration',\n 'defaults',\n] as const satisfies readonly Exclude<keyof InlineScriptConfig, 'runtime'>[];\n","/**\n * Wraps the build-time runtime IIFE with the consumer's configuration, and\n * places at most one strategy prelude ahead of it.\n */\n\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { V1_RUNTIME_DEFAULTS } from '@/types/defaults-profile';\nimport { RUNTIME_SOURCE, RUNTIME_BUILD_INFO, type RuntimeBuildInfo } from './runtime.generated';\nimport { FRAGMENT_SOURCE } from './fragment.generated';\nimport { ROUTE_SOURCE } from './route.generated';\nimport { LOADER_SOURCE } from './loader.generated';\nimport { LOADER_REACT_SOURCE } from './loader-react.generated';\nimport { INLINE_CONFIG_KEYS, type InlineScriptConfig } from '@/types/inline-config';\n\nexport type { InlineScriptConfig, RuntimeArtifact } from '@/types/inline-config';\n\nfunction assertBuilt(source: string, artifact: string): void {\n if (source.length === 0) {\n throw new Error(\n `[live-preview] ${artifact} is empty. Run \\`npm run build:runtime\\` before bundling.`,\n );\n }\n}\n\n/** The inline script body without `<script>` tags; see `wrapWithScriptTag()`. */\nexport function generateInlineScript(config: InlineScriptConfig = {}): string {\n const runtime = runtimeFor(config);\n return [configStatement(config), ...strategyPrelude(config), runtime].join('\\n');\n}\n\n/**\n * The full runtime, or the artifact the consumer imported. The lean one leaves\n * out the strategies (docs/options.md), so the two preludes are refused with it\n * rather than emitted against a runtime that could never answer them.\n */\nfunction runtimeFor(config: InlineScriptConfig): string {\n const artifact = config.runtime;\n if (artifact === undefined) {\n assertBuilt(RUNTIME_SOURCE, 'runtime.generated.ts');\n return RUNTIME_SOURCE;\n }\n assertBuilt(artifact.source, `the ${artifact.profile} runtime`);\n if (config.fragmentEndpoint != null || config.routeStrategy === true) {\n throw new Error(\n `[live-preview] the ${artifact.profile} runtime and the fragment or route strategy exclude ` +\n 'each other: it carries no strategy runner, so the prelude would have nothing to talk to. ' +\n 'Drop the runtime option, or drop `fragmentEndpoint`/`routeStrategy`.',\n );\n }\n return artifact.source;\n}\n\n/**\n * At most one prelude, and the fragment one wins: it already contains the\n * route strategy, so emitting both would ship that code twice and leave two\n * globals where the runtime expects the fragment one to be authoritative.\n */\nfunction strategyPrelude(config: InlineScriptConfig): readonly string[] {\n if (config.fragmentEndpoint != null) {\n assertBuilt(FRAGMENT_SOURCE, 'fragment.generated.ts');\n return [FRAGMENT_SOURCE];\n }\n if (config.routeStrategy === true) {\n assertBuilt(ROUTE_SOURCE, 'route.generated.ts');\n return [ROUTE_SOURCE];\n }\n return [];\n}\n\n// `__LIVE_PREVIEW_CONFIG__` is a public presence signal: consumers' integration\n// tests grep for it, so the name outlives any refactor.\nfunction configStatement(config: InlineScriptConfig): string {\n return `var __LIVE_PREVIEW_CONFIG__=${buildConfigLiteral(config)};`;\n}\n\n/** The positional wire literal the runtime destructures; shared by the inline script and the loader. */\nfunction buildConfigLiteral(config: InlineScriptConfig): string {\n assertMergeDepthExplicit(config);\n const profile = profileSlots(config);\n // `null` counts as omitted, and omitted slots stay empty (`[,,1]`): a JSON\n // `null` would bypass the runtime's destructuring defaults. The last slot is\n // always written, so there is no trailing hole to trim.\n const values: unknown[] = INLINE_CONFIG_KEYS.map((key) => config[key] ?? profile[key]);\n // `<` is escaped so a value containing `</script>` cannot end the tag.\n return `[${values\n .map((value) => (value === undefined ? '' : JSON.stringify(value)))\n .join(',')}]`.replace(/</g, '\\\\u003C');\n}\n\n/**\n * What the `defaults` profile puts on the wire. The runtime's own fallbacks are\n * the 2.0 rows, so `'v2'` fills nothing and `'v1'` has to write its four; the\n * profile itself goes into the last slot either way, so a reader of the served\n * page learns which generation an empty slot belongs to (ADR 0007).\n */\nfunction profileSlots(config: InlineScriptConfig): Partial<InlineScriptConfig> {\n const defaults = config.defaults ?? 'v2';\n return defaults === 'v1' ? { ...V1_RUNTIME_DEFAULTS, defaults } : { defaults };\n}\n\n/** Where the runtime asset lives, and how the browser should verify it. */\nexport interface LoaderScriptTarget {\n /** URL the bootstrap appends. Same-origin or absolute; hashed by the caller. */\n readonly runtimeSrc: string;\n /** Subresource-integrity value, e.g. `sha384-…`; empty drops the check and the `crossorigin` it requires. */\n readonly integrity?: string;\n}\n\n/**\n * The static-delivery bootstrap: the configuration plus a few hundred bytes\n * appending the runtime inside a preview. The asset stays configuration-free.\n */\nexport function generateLoaderScript(\n config: InlineScriptConfig = {},\n target: LoaderScriptTarget,\n): string {\n const bootstrap = loaderFor(config);\n if (target.runtimeSrc === '') {\n throw new Error('[live-preview] generateLoaderScript needs a runtimeSrc.');\n }\n const encode = (value: string): string => JSON.stringify(value).replace(/</gu, '\\\\u003C');\n return [\n configStatement(config),\n `var __LP_RUNTIME_SRC__=${encode(target.runtimeSrc)};`,\n `var __LP_RUNTIME_INTEGRITY__=${encode(target.integrity ?? '')};`,\n ...strategyPrelude(config),\n bootstrap,\n ].join('\\n');\n}\n\n/**\n * The bootstrap, or the one armed for React's first commit (ADR 0015 F2): the\n * inline runtime is the first script in `<head>` and arms the signal itself,\n * while a fetched asset may evaluate after `react-dom` has, when it is too\n * late — so on a page that declares React the bootstrap arms before it\n * fetches. One script either way, never a prelude ahead of the plain one. A\n * page that declares Vue takes the plain one: Vue's mount leaves state on the\n * container that a late runtime can still read (`core/hydration-vue`).\n */\nfunction loaderFor(config: InlineScriptConfig): string {\n if (config.hydration === 'react') {\n assertBuilt(LOADER_REACT_SOURCE, 'loader-react.generated.ts');\n return LOADER_REACT_SOURCE;\n }\n assertBuilt(LOADER_SOURCE, 'loader.generated.ts');\n return LOADER_SOURCE;\n}\n\n/** Wrap a script body in `<script>`, with the CSP nonce attribute when given. */\nexport function wrapWithScriptTag(body: string, options: { nonce?: string } = {}): string {\n const nonceAttr = options.nonce !== undefined ? ` nonce=\"${assertNonce(options.nonce)}\"` : '';\n return `<script${nonceAttr}>${body}</script>`;\n}\n\n/** @internal */\nexport function runtimeBuildInfo(): RuntimeBuildInfo {\n return RUNTIME_BUILD_INFO;\n}\n\n/**\n * A nonce as CSP defines it: base64url characters only. Returned unchanged so\n * a caller can inline the result. Not re-exported from the package barrel — it\n * is shared with the adapters, not part of the public surface.\n */\nexport function assertNonce(nonce: string): string {\n if (!/^[A-Za-z0-9+/=_-]+$/.test(nonce)) {\n throw new RangeError('nonce contains characters CSP does not allow');\n }\n return nonce;\n}\n","/**\n * The runtime as a servable, cacheable asset — the request-time half of\n * `mode: 'loader'`.\n *\n * Name and integrity are constants of the package build (the artifact carries\n * both), so nothing here hashes anything per request and this module stays\n * reachable from a browser entry: no `node:crypto`, no Node builtins at all.\n *\n * The content hash is in the file name, which is what makes `immutable` honest:\n * different bytes are a different URL, so a year-long cache can never serve the\n * wrong runtime. A request for any other name under the mount path is a 404\n * rather than a redirect to the current one — a client asking for a hash we no\n * longer have is asking for bytes we cannot produce.\n */\n\nimport { RUNTIME_CONTENT_HASH, RUNTIME_INTEGRITY, RUNTIME_SOURCE } from '@inline/runtime.generated';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n/** Where the asset route is mounted when nothing says otherwise. */\nexport const DEFAULT_ASSET_PATH = '/payload-live-preview';\n\nexport interface RuntimeAssetOptions {\n /**\n * Path the asset route is mounted at. Must match on both sides — the\n * bootstrap requests it and the route serves it. Default\n * `/payload-live-preview`; give it the framework's own base path as a prefix\n * when the app is not served from the site root.\n */\n readonly assetPath?: string;\n /** The artifact to serve; the default runtime when omitted. */\n readonly runtime?: RuntimeArtifact;\n}\n\nexport interface RuntimeAsset {\n /** The file name alone, `runtime.<hash>.js`. */\n readonly fileName: string;\n /** The absolute path the bootstrap requests, mount path included. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to serve. */\n readonly source: string;\n}\n\n/**\n * One leading slash, no trailing one, so joining is a single concatenation.\n *\n * Trimmed by index rather than by `/^\\/+|\\/+$/`: that expression backtracks over\n * a long run of slashes and costs quadratic time on a path the consumer\n * configures (CodeQL js/polynomial-redos).\n */\nfunction normalizePath(path: string): string {\n let start = 0;\n let end = path.length;\n while (start < end && path[start] === '/') start += 1;\n while (end > start && path[end - 1] === '/') end -= 1;\n const trimmed = path.slice(start, end);\n return trimmed === '' ? '' : `/${trimmed}`;\n}\n\n/** Describe the asset for these options; deterministic per package version and artifact. */\nexport function runtimeAsset(options: RuntimeAssetOptions = {}): RuntimeAsset {\n const artifact = options.runtime;\n const hash = artifact?.contentHash ?? RUNTIME_CONTENT_HASH;\n const fileName = `runtime.${hash}.js`;\n return {\n fileName,\n urlPath: `${normalizePath(options.assetPath ?? DEFAULT_ASSET_PATH)}/${fileName}`,\n integrity: artifact?.integrity ?? RUNTIME_INTEGRITY,\n source: artifact?.source ?? RUNTIME_SOURCE,\n };\n}\n\n/**\n * A year, the longest `max-age` browsers honour, plus `immutable` so a reload\n * does not revalidate either. Safe only because the hash is in the name.\n */\nexport const ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';\n\n/** The headers the asset is served with, on every framework. */\nexport function runtimeAssetHeaders(): Record<string, string> {\n return {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': ASSET_CACHE_CONTROL,\n // The bootstrap sets `crossorigin=\"anonymous\"` for the integrity check;\n // same-origin needs no CORS header, and a CDN in front of it gets one that\n // says the bytes are public.\n 'access-control-allow-origin': '*',\n // Nothing here is HTML, and a browser that sniffs it as such would be wrong.\n 'x-content-type-options': 'nosniff',\n };\n}\n\n/**\n * The response for one requested URL: the asset when the file name is the one\n * this build produces, 404 otherwise.\n *\n * Only the file name is checked, never the mount path. Where the route sits is\n * the framework's business — the consumer put the file there — while the name\n * is ours, and it is the name that decides whether the bytes a client cached\n * for a year are still the bytes we would send.\n */\nexport function runtimeAssetResponse(url: string, options: RuntimeAssetOptions = {}): Response {\n const asset = runtimeAsset(options);\n // A query string is a cache-buster and must still resolve.\n const path = url.split('?')[0] ?? '';\n const requested = path.slice(path.lastIndexOf('/') + 1);\n if (requested !== asset.fileName) {\n return new Response('Not found', {\n status: 404,\n headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },\n });\n }\n return new Response(asset.source, { status: 200, headers: runtimeAssetHeaders() });\n}\n","/**\n * The runtime as a servable, cacheable asset, in the shape Astro's build wants:\n * a path inside the output directory to emit, and a site path to request.\n *\n * The naming and the digests come from `runtimeAsset()`, the same descriptor\n * the route-serving adapters use, so there is one answer to \"what is this file\n * called\" across all four. What stays Astro's own is the directory: an\n * underscore keeps it out of Astro's page routing, which is exactly what the\n * others cannot use — a leading underscore makes a folder private in the App\n * Router and in SvelteKit both.\n */\nimport { runtimeAsset } from '@adapters/shared/runtime-asset';\nimport type { RuntimeArtifact } from '@/types/inline-config';\n\n// Not `_astro/`: Astro's bundler empties and rewrites that directory.\nconst ASSET_DIR = '_payload-live-preview';\n\nexport interface LoaderAsset {\n /** Path within the build output, e.g. `_payload-live-preview/runtime.<hash>.js`. */\n readonly fileName: string;\n /** Absolute site path the bootstrap requests, with a leading slash. */\n readonly urlPath: string;\n /** `sha384-…`, for the bootstrap's `integrity` attribute. */\n readonly integrity: string;\n /** The bytes to write or serve. */\n readonly source: string;\n}\n\n/** Describe the asset for this build; deterministic per package version and artifact. */\nexport function loaderAsset(base = '/', runtime?: RuntimeArtifact): LoaderAsset {\n // `base` may carry slashes at either end; normalise to exactly one between segments.\n const prefix = base.replace(/^\\/+|\\/+$/gu, '');\n const asset = runtimeAsset({\n assetPath: prefix === '' ? `/${ASSET_DIR}` : `/${prefix}/${ASSET_DIR}`,\n ...(runtime !== undefined ? { runtime } : {}),\n });\n return {\n fileName: `${ASSET_DIR}/${asset.fileName}`,\n urlPath: asset.urlPath,\n integrity: asset.integrity,\n source: asset.source,\n };\n}\n","/**\n * The options the policy reads, and what they resolve to: the `defaults`\n * profile fills what an adapter left unset, and the inline-script config\n * carries only what was given so the runtime's own defaults stay the single\n * source of them.\n */\n\nimport type { generateInlineScript } from '@inline/generator';\nimport {\n adapterDefaultsFor,\n runtimeDefaultsFor,\n V2_RUNTIME_DEFAULTS,\n} from '@/types/defaults-profile';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport type { InlineScriptConfig } from '@/types/inline-config';\nimport type { PreviewSignal } from './preview-request';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The structural subset of any adapter's options the policy reads; hooks are bound per request. */\nexport type PreviewPolicyOptions = PreviewAdapterOptions<never>;\n\n/** The options after the `defaults` profile: explicit options win, the profile fills the rest. */\nexport interface ResolvedPolicyOptions {\n readonly strict: boolean;\n readonly previewSignals: readonly PreviewSignal[] | undefined;\n readonly skipUnchanged: boolean | undefined;\n readonly disableReferrerDetection: boolean | undefined;\n readonly disableLocalhostMatching: boolean | undefined;\n readonly eventSourcePolicy: 'any' | 'parent-or-opener' | undefined;\n readonly sanitizerPolicy: 'compat' | 'strict' | undefined;\n}\n\nexport function resolvePolicyOptions(options: PreviewPolicyOptions): ResolvedPolicyOptions {\n const adapter = adapterDefaultsFor(options.defaults);\n const runtime = runtimeDefaultsFor(options.defaults);\n // The inline runtime already defaults to the v2 rows, so only a differing\n // profile — an explicit `defaults: 'v1'` — needs a row on the wire.\n const runtimeRow = <K extends keyof typeof V2_RUNTIME_DEFAULTS>(\n key: K,\n ): (typeof V2_RUNTIME_DEFAULTS)[K] | undefined =>\n runtime[key] !== V2_RUNTIME_DEFAULTS[key] ? runtime[key] : undefined;\n return {\n strict: options.strict ?? adapter.strict,\n previewSignals: options.previewSignals ?? adapter.previewSignals,\n skipUnchanged: options.skipUnchanged ?? runtimeRow('skipUnchanged'),\n disableReferrerDetection:\n options.disableReferrerDetection ?? runtimeRow('disableReferrerDetection'),\n disableLocalhostMatching: options.disableLocalhostMatching,\n eventSourcePolicy: options.eventSourcePolicy ?? runtimeRow('eventSourcePolicy'),\n sanitizerPolicy: options.sanitizerPolicy ?? runtimeRow('sanitizerPolicy'),\n };\n}\n\n/**\n * What an adapter knows about the page beyond what a project configured — today\n * the framework that hydrates it (ADR 0015). Not an adapter option: a Next page\n * is a React tree whether or not anyone says so, so the adapter says it.\n */\nexport type PageFacts = Pick<InlineScriptConfig, 'hydration'>;\n\n/** The inline-script configuration; only given options travel, so the runtime's own defaults stay the single source of them. */\nexport function inlineScriptConfig(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): Parameters<typeof generateInlineScript>[0] {\n assertMergeDepthExplicit(options);\n const resolved = resolvePolicyOptions(options);\n return {\n // The generator names it in the last slot and, under `'v1'`, reads an\n // omitted `mergeDepth` as deliberate.\n ...(options.defaults !== undefined ? { defaults: options.defaults } : {}),\n ...(options.allowedOrigins !== undefined ? { allowedOrigins: options.allowedOrigins } : {}),\n ...(options.serverURL !== undefined ? { serverURL: options.serverURL } : {}),\n ...(options.apiRoute !== undefined ? { apiRoute: options.apiRoute } : {}),\n ...(options.mergeDepth !== undefined ? { mergeDepth: options.mergeDepth } : {}),\n ...(options.revealEditedField !== undefined\n ? { revealEditedField: options.revealEditedField }\n : {}),\n ...(options.debug !== undefined ? { debug: options.debug } : {}),\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.heartbeatMs !== undefined ? { heartbeatMs: options.heartbeatMs } : {}),\n ...(resolved.skipUnchanged !== undefined ? { skipUnchanged: resolved.skipUnchanged } : {}),\n ...(options.scopeBindingsByOwner !== undefined\n ? { scopeBindingsByOwner: options.scopeBindingsByOwner }\n : {}),\n ...(resolved.disableReferrerDetection !== undefined\n ? { disableReferrerDetection: resolved.disableReferrerDetection }\n : {}),\n ...(resolved.disableLocalhostMatching !== undefined\n ? { disableLocalhostMatching: resolved.disableLocalhostMatching }\n : {}),\n ...(resolved.eventSourcePolicy !== undefined\n ? { eventSourcePolicy: resolved.eventSourcePolicy }\n : {}),\n ...(resolved.sanitizerPolicy !== undefined\n ? { sanitizerPolicy: resolved.sanitizerPolicy }\n : {}),\n ...(options.runtime !== undefined ? { runtime: options.runtime } : {}),\n ...(options.fragments !== undefined ? { fragmentEndpoint: options.fragments.endpoint } : {}),\n // Only when no endpoint is configured: that prelude carries the route\n // strategy already, and asking for both would emit the larger one twice.\n ...(options.routeStrategy === true && options.fragments === undefined\n ? { routeStrategy: true }\n : {}),\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 2.0 name is carried through exactly here\n ...(options.onUnboundChange !== undefined ? { onUnboundChange: options.onUnboundChange } : {}),\n ...(options.onUnfaithfulPatch !== undefined\n ? { onUnfaithfulPatch: options.onUnfaithfulPatch }\n : {}),\n ...(options.autoBind !== undefined ? { autoBind: options.autoBind } : {}),\n ...(facts.hydration !== undefined ? { hydration: facts.hydration } : {}),\n };\n}\n","/**\n * The Astro integration for `astro.config.mjs`: `livePreview({ ... })`.\n * Inline and loader modes deliver at build time; middleware mode registers\n * the request-time middleware through a serialized options module.\n */\n\nimport { generateInlineScript, generateLoaderScript } from '@inline/generator';\nimport { loaderAsset } from './loader-asset';\nimport { inlineScriptConfig } from '@adapters/shared/policy-options';\nimport type { LivePreviewAstroOptions } from './types';\n\n// Local shims keep `astro` a runtime-optional peer.\ntype ScriptStage = 'head-inline' | 'page' | 'before-hydration' | 'page-ssr';\ninterface VitePluginLike {\n readonly name: string;\n readonly resolveId?: (id: string) => string | undefined;\n readonly load?: (id: string) => string | undefined;\n readonly configureServer?: (server: ViteDevServerLike) => void;\n readonly generateBundle?: (this: RollupEmitContext) => void;\n}\ninterface RollupEmitContext {\n emitFile: (file: { type: 'asset'; fileName: string; source: string }) => void;\n}\ninterface ViteDevServerLike {\n readonly middlewares: {\n use: (handler: (req: DevRequest, res: DevResponse, next: () => void) => void) => void;\n };\n}\ninterface DevRequest {\n readonly url?: string | undefined;\n}\ninterface DevResponse {\n statusCode: number;\n setHeader: (name: string, value: string) => void;\n end: (body?: string) => void;\n}\ninterface AstroConfigSetupContext {\n readonly injectScript: (stage: ScriptStage, content: string) => void;\n readonly addMiddleware?: (entry: { entrypoint: string; order: 'pre' | 'post' }) => void;\n readonly updateConfig?: (config: { vite?: { plugins?: VitePluginLike[] } }) => void;\n /** Astro's configured `base`; absent on versions that do not expose it. */\n readonly config?: { readonly base?: string };\n}\nexport interface AstroIntegrationLike {\n readonly name: string;\n readonly hooks: {\n readonly 'astro:config:setup': (ctx: AstroConfigSetupContext) => void;\n };\n}\n\nconst VIRTUAL_OPTIONS_ID = 'virtual:payload-live-preview/options';\nconst RESOLVED_VIRTUAL_OPTIONS_ID = `\\0${VIRTUAL_OPTIONS_ID}`;\nconst MIDDLEWARE_ENTRYPOINT = 'payload-live-preview/astro/middleware-entry';\n\n/** Build the integration. The injected runtime stays inert outside the admin's preview iframe. */\nexport function livePreview(options: LivePreviewAstroOptions = {}): AstroIntegrationLike {\n return {\n name: 'payload-live-preview',\n hooks: {\n 'astro:config:setup': (ctx): void => {\n if (options.mode === 'middleware') {\n setupMiddlewareMode(ctx, options);\n return;\n }\n if (options.autoInject === false) return;\n if (options.mode === 'loader') {\n setupLoaderMode(ctx, options);\n return;\n }\n ctx.injectScript('head-inline', generateInlineScript(inlineScriptConfig(options)));\n },\n },\n };\n}\n\n/**\n * Loader mode: a bootstrap in every page, the runtime published beside it.\n * One Vite plugin serves the identical bytes from the identical path during\n * `astro dev` (`configureServer`) and in the build (`generateBundle`).\n */\nfunction setupLoaderMode(ctx: AstroConfigSetupContext, options: LivePreviewAstroOptions): void {\n // Without a Vite plugin nothing emits or serves the asset while the bootstrap\n // is injected anyway; that 404 is invisible until an editor opens a preview.\n if (ctx.updateConfig === undefined) {\n throw new Error(\n \"payload-live-preview: mode 'loader' needs Astro's updateConfig hook \" +\n '(Astro >= 4) to publish the runtime asset. Upgrade Astro or use the ' +\n 'default inline mode.',\n );\n }\n\n const asset = loaderAsset(ctx.config?.base ?? '/', options.runtime);\n\n ctx.injectScript(\n 'head-inline',\n generateLoaderScript(inlineScriptConfig(options), {\n runtimeSrc: asset.urlPath,\n integrity: asset.integrity,\n }),\n );\n\n // Emitting through Vite rather than writing from an Astro hook keeps this\n // module free of Node builtins: it is reachable from a browser entry.\n ctx.updateConfig({\n vite: {\n plugins: [\n {\n name: 'payload-live-preview:loader-asset',\n generateBundle() {\n this.emitFile({ type: 'asset', fileName: asset.fileName, source: asset.source });\n },\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n // Path only: a cache-busting query string must still resolve.\n const path = (req.url ?? '').split('?')[0];\n if (path !== asset.urlPath) {\n next();\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/javascript; charset=utf-8');\n // The file changes with the installed package; a stale one is hard to notice.\n res.setHeader('Cache-Control', 'no-cache');\n res.end(asset.source);\n });\n },\n },\n ],\n },\n });\n}\n\nfunction setupMiddlewareMode(ctx: AstroConfigSetupContext, options: LivePreviewAstroOptions): void {\n if (ctx.addMiddleware === undefined || ctx.updateConfig === undefined) {\n throw new Error(\n \"payload-live-preview: mode 'middleware' needs Astro's addMiddleware/updateConfig \" +\n 'hooks (Astro >= 4). Upgrade Astro or use the default inline mode.',\n );\n }\n if (options.authorizePreview !== undefined) {\n throw new Error(\n \"payload-live-preview: `authorizePreview` cannot be used with mode 'middleware' — \" +\n 'options are serialized into the build. Compose `createLivePreviewMiddleware()` ' +\n 'in your own `src/middleware.ts` to pass the hook.',\n );\n }\n if (options.shouldInject !== undefined) {\n throw new Error(\n \"payload-live-preview: `shouldInject` cannot be used with mode 'middleware' — \" +\n 'options are serialized into the build. Use `previewQueryParams`/`previewSignals`, ' +\n 'or register createLivePreviewMiddleware() manually in src/middleware.ts.',\n );\n }\n // Strict needs `authorizePreview`, which cannot serialize: refuse here rather\n // than build cleanly and fail on every preview request.\n const willBeStrict = options.strict ?? options.defaults !== 'v1';\n if (willBeStrict) {\n throw new Error(\n \"payload-live-preview: mode 'middleware' cannot satisfy the 2.0 strict default — it \" +\n 'serializes its options into the build, so it cannot carry the `authorizePreview` ' +\n 'function strict mode requires. Either register ' +\n '`createLivePreviewMiddleware({ authorizePreview, ... })` yourself in src/middleware.ts ' +\n '(recommended: response changes stay gated on a verified context), or pass ' +\n \"`defaults: 'v1'` (or `strict: false`) to run intent-only middleware \" +\n '(ADR 0006 explains why intent is not authorization).',\n );\n }\n\n const { mode: _mode, shouldInject: _shouldInject, ...serializable } = options;\n const optionsModule = `export default ${JSON.stringify(serializable).replace(/</g, '\\\\u003C')};`;\n\n ctx.updateConfig({\n vite: {\n plugins: [\n {\n name: 'payload-live-preview-options',\n resolveId: (id) => (id === VIRTUAL_OPTIONS_ID ? RESOLVED_VIRTUAL_OPTIONS_ID : undefined),\n load: (id) => (id === RESOLVED_VIRTUAL_OPTIONS_ID ? optionsModule : undefined),\n },\n ],\n },\n });\n ctx.addMiddleware({ entrypoint: MIDDLEWARE_ENTRYPOINT, order: 'pre' });\n}\n","/**\n * Content-Security-Policy helpers: nonce generation, directive builders and\n * the header merge every adapter uses. Isomorphic; needs only Web Crypto.\n */\n\nconst DEFAULT_NONCE_BYTES = 16;\n\n/** CSP3's exact whitespace set: HTAB, LF, FF, CR, and SPACE. */\nconst CSP_ASCII_WHITESPACE = /[\\t\\n\\f\\r ]+/;\n\n/** Reads one code unit; an index past the end yields NaN, which matches nothing. */\nfunction isCspWhitespace(value: string, index: number): boolean {\n const code = value.charCodeAt(index);\n return code === 9 || code === 10 || code === 12 || code === 13 || code === 32;\n}\n\n/**\n * Trim CSP whitespace by scanning from both ends.\n *\n * The obvious `/^\\s+|\\s+$/` is superlinear by construction: for a long run the\n * trailing alternative is retried at every position. V8 happens to optimise the\n * shape away, but this header can come from a consumer's own response and this\n * module runs in every engine, so the guarantee has to come from the algorithm\n * rather than from one engine's optimiser.\n */\nfunction trimCspWhitespace(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && isCspWhitespace(value, start)) start += 1;\n while (end > start && isCspWhitespace(value, end - 1)) end -= 1;\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/** CSP names are ASCII; Unicode case folding must not create directives. */\nfunction asciiLowercase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\n/** The one Web Crypto method this module calls; accepts Node's `webcrypto` without a cast. */\ninterface WebCryptoLike {\n getRandomValues: <T extends ArrayBufferView | null>(array: T) => T;\n}\n\nlet cryptoOverride: WebCryptoLike | undefined;\n\n/** Supply a Web Crypto implementation for runtimes without `globalThis.crypto`; `null` clears it. @internal */\nexport function setCspCrypto(crypto: WebCryptoLike | null): void {\n cryptoOverride = crypto ?? undefined;\n}\n\n/** A base64url nonce of `bytes` random bytes (default 16); throws without Web Crypto, since a predictable nonce silently defeats the CSP. @internal */\nexport function generateCspNonce(bytes: number = DEFAULT_NONCE_BYTES): string {\n if (!Number.isInteger(bytes) || bytes < 8) {\n throw new RangeError(`generateCspNonce: bytes must be an integer >= 8, got ${String(bytes)}`);\n }\n const crypto = resolveCrypto();\n if (!crypto) {\n throw new Error(\n 'generateCspNonce: Web Crypto is unavailable. On Node 18 call setCspCrypto(webcrypto) ' +\n \"once at startup, or run with --experimental-global-webcrypto. We won't fabricate \" +\n 'a predictable nonce — that would silently defeat the entire CSP.',\n );\n }\n const buffer = new Uint8Array(bytes);\n crypto.getRandomValues(buffer);\n return base64UrlEncode(buffer);\n}\n\nfunction resolveCrypto(): WebCryptoLike | undefined {\n if (cryptoOverride?.getRandomValues) return cryptoOverride;\n const fromGlobal = (globalThis as { crypto?: WebCryptoLike }).crypto;\n if (fromGlobal?.getRandomValues) return fromGlobal;\n return undefined;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const base64 = typeof btoa === 'function' ? btoa(binary) : Buffer.from(bytes).toString('base64');\n return base64.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/** A `frame-ancestors` source: `'self'`, `'none'`, or an origin. */\nexport type FrameAncestorSource = string;\n\nexport interface FrameAncestorsOptions {\n readonly self?: boolean;\n readonly origins?: readonly string[];\n readonly allowNone?: boolean;\n}\n\n/** The `frame-ancestors` value: `'self'` and the origins, deduplicated; `'none'` when empty. */\nexport function buildFrameAncestors(options: FrameAncestorsOptions = {}): string {\n const { self = true, origins = [], allowNone = false } = options;\n const seen = new Set<string>();\n const out: FrameAncestorSource[] = [];\n if (allowNone && !self && origins.length === 0) return \"'none'\";\n if (self) {\n out.push(\"'self'\");\n seen.add(\"'self'\");\n }\n for (const origin of origins) {\n const trimmed = origin.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) continue;\n seen.add(trimmed);\n out.push(trimmed);\n }\n return out.length > 0 ? out.join(' ') : \"'none'\";\n}\n\n/**\n * A `script-src` value permitting one nonce plus optional extra sources.\n * `'strict-dynamic'` is opt-in: it makes CSP 3 browsers ignore `'self'` and\n * host sources, so every script on the page must then carry the nonce.\n * @internal\n */\nexport function buildScriptSrcWithNonce(\n nonce: string,\n options: {\n readonly self?: boolean;\n readonly extra?: readonly string[];\n readonly strictDynamic?: boolean;\n } = {},\n): string {\n if (nonce.length === 0) throw new RangeError('buildScriptSrcWithNonce: nonce is empty');\n const { self = true, extra = [], strictDynamic = false } = options;\n const parts: string[] = [];\n if (self) parts.push(\"'self'\");\n parts.push(`'nonce-${nonce}'`);\n if (strictDynamic) parts.push(\"'strict-dynamic'\");\n for (const e of extra) {\n const trimmed = e.trim();\n if (trimmed.length > 0) parts.push(trimmed);\n }\n return parts.join(' ');\n}\n\n/** `union` (default) adds sources to an existing directive; `replace` overwrites it. */\nexport interface CspDirectiveMerge {\n readonly value: string;\n readonly mode?: 'union' | 'replace';\n}\n\n/**\n * Merge directives into an existing `Content-Security-Policy` header value.\n * Commas separate policies (that is how `Headers.get()` joins repeated\n * headers); each is merged, because a browser enforces every policy and\n * widening only the last would leave the others blocking.\n */\nexport function mergeCspHeader(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const policies = existing.split(',').filter((policy) => policy.trim().length > 0);\n if (policies.length === 0) return mergeCspPolicy('', additions);\n return policies.map((policy) => mergeCspPolicy(policy, additions)).join(', ');\n}\n\nfunction mergeCspPolicy(\n existing: string,\n additions: Readonly<Record<string, string | CspDirectiveMerge>>,\n): string {\n const directives = new Map<string, string>();\n for (const part of existing.split(';')) {\n const trimmed = trimCspWhitespace(part);\n if (trimmed.length === 0) continue;\n const whitespaceIndex = trimmed.search(CSP_ASCII_WHITESPACE);\n const name = asciiLowercase(whitespaceIndex < 0 ? trimmed : trimmed.slice(0, whitespaceIndex));\n // CSP3 §2.2.1: a user agent ignores later duplicates, so a looser\n // duplicate must not become the policy that is serialized.\n if (directives.has(name)) continue;\n const value = whitespaceIndex < 0 ? '' : trimCspWhitespace(trimmed.slice(whitespaceIndex));\n directives.set(name, value);\n }\n\n for (const [rawName, rawAddition] of Object.entries(additions)) {\n const name = asciiLowercase(rawName);\n const addition: CspDirectiveMerge =\n typeof rawAddition === 'string' ? { value: rawAddition } : rawAddition;\n const mode = addition.mode ?? 'union';\n const current = directives.get(name);\n if (mode === 'replace' || current === undefined || current.length === 0) {\n directives.set(name, addition.value);\n continue;\n }\n const seen = new Set<string>();\n const merged: string[] = [];\n for (const token of [\n ...current.split(CSP_ASCII_WHITESPACE),\n ...addition.value.split(CSP_ASCII_WHITESPACE),\n ]) {\n if (token.length === 0 || seen.has(token)) continue;\n seen.add(token);\n merged.push(token);\n }\n // `'none'` cannot coexist with other sources.\n const withoutNone = merged.filter((token) => token !== \"'none'\");\n directives.set(name, (withoutNone.length > 0 ? withoutNone : merged).join(' '));\n }\n\n const out: string[] = [];\n for (const [name, value] of directives) {\n out.push(value.length === 0 ? name : `${name} ${value}`);\n }\n return out.join('; ');\n}\n","/**\n * Placing the runtime's script tag inside an HTML document, by text: the\n * adapters see a rendered string or a streamed chunk, never a DOM.\n */\n\n/** The opening `<head>` tag the runtime script is inserted into. */\nexport const HEAD_INSERT = /<head(\\s[^>]*)?>/i;\n\n/** `text/html` with or without parameters. */\nexport const HTML_CONTENT_TYPE = /text\\/html/i;\n\n// Browsers prescan only the first 1024 bytes for the encoding; a script\n// inserted ahead of `<meta charset>` would push it out of that window.\nconst META_CHARSET =\n /<meta\\s+(?:[^>]*\\s)?(?:charset\\s*=|http-equiv\\s*=\\s*[\"']?content-type)[^>]*>/i;\n\n/**\n * `html` with the script tag after `<meta charset>`, else right after\n * `<head>`; `undefined` when there is no `<head>` to insert into.\n */\nexport function injectIntoHead(html: string, scriptTag: string): string | undefined {\n const head = HEAD_INSERT.exec(html);\n if (head === null) return undefined;\n const headEnd = head.index + head[0].length;\n const headClose = html.indexOf('</head', headEnd);\n const meta = META_CHARSET.exec(html.slice(headEnd, headClose === -1 ? undefined : headClose));\n const at = meta === null ? headEnd : headEnd + meta.index + meta[0].length;\n return `${html.slice(0, at)}${scriptTag}${html.slice(at)}`;\n}\n","/**\n * Applying a decision to a fetch-style `Response`, and the request-side\n * glue every adapter repeats: hook binding and the manual script tag.\n */\n\nimport { generateInlineScript, generateLoaderScript, wrapWithScriptTag } from '@inline/generator';\nimport { runtimeAsset } from './runtime-asset';\nimport { HTML_CONTENT_TYPE, injectIntoHead } from './html-inject';\nimport { inlineScriptConfig, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport type { PreviewDecision, PreviewDecisionHooks, PreviewPolicy } from './policy';\nimport type { PreviewAdapterOptions } from './options';\n\n/** The header surface shared by `Headers` and a Node response. */\nexport interface HeaderSink {\n get(name: string): string | null | undefined;\n set(name: string, value: string): void;\n}\n\n/** Bind an adapter's per-request hooks to `request`. */\nexport function bindDecisionHooks<Req>(\n policy: PreviewPolicy,\n options: Pick<PreviewAdapterOptions<Req>, 'authorizePreview' | 'shouldInject'>,\n request: Req,\n): PreviewDecisionHooks {\n return {\n shouldInject: () => options.shouldInject?.(request) ?? true,\n ...(policy.authorizes ? { authorize: () => options.authorizePreview?.(request) } : {}),\n };\n}\n\n/**\n * The script body alone, for a consumer that builds the element itself — a JSX\n * framework cannot render a tag that arrives as a string.\n *\n * The one place delivery is decided, so every adapter answers `delivery:\n * 'asset'` the same way: the bootstrap plus the URL and integrity of whichever\n * artifact was configured, and never the runtime itself.\n */\nexport function renderScriptBody(options: PreviewPolicyOptions, facts: PageFacts = {}): string {\n const config = inlineScriptConfig(options, facts);\n if (options.delivery !== 'asset') return generateInlineScript(config);\n const asset = runtimeAsset(options);\n return generateLoaderScript(config, { runtimeSrc: asset.urlPath, integrity: asset.integrity });\n}\n\n/** The `<script>` tag for manual embedding, with `nonce` when given. */\nexport function renderScriptTag(\n options: PreviewPolicyOptions & { readonly nonce?: string },\n facts: PageFacts = {},\n): string {\n const body = renderScriptBody(options, facts);\n return wrapWithScriptTag(body, options.nonce !== undefined ? { nonce: options.nonce } : {});\n}\n\n/** A changed response must never be stored as the public page, nor shared across sessions. */\nexport function markUncacheable(headers: HeaderSink): void {\n const cacheControl = headers.get('cache-control') ?? '';\n if (!/\\bno-store\\b/i.test(cacheControl)) headers.set('cache-control', 'private, no-store');\n const vary = (headers.get('vary') ?? '').trim();\n const listed = vary.split(',').map((token) => token.trim().toLowerCase());\n if (listed.includes('*') || listed.includes('cookie')) return;\n headers.set('vary', vary.length === 0 ? 'Cookie' : `${vary}, Cookie`);\n}\n\n/**\n * `response` with the script tag in its `<head>`, untouched when it has no\n * body (204/304/HEAD), is not HTML, or has no `<head>`. Headers describing\n * the old body — length, encoding, ETag — are dropped.\n */\nexport async function injectIntoResponse(response: Response, scriptTag: string): Promise<Response> {\n if (response.body === null) return response;\n if (!HTML_CONTENT_TYPE.test(response.headers.get('content-type') ?? '')) return response;\n const injected = injectIntoHead(await response.clone().text(), scriptTag);\n if (injected === undefined) return response;\n const headers = new Headers(response.headers);\n headers.delete('content-length');\n headers.delete('content-encoding');\n headers.delete('etag');\n return new Response(injected, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** Run `apply` on the response headers, cloning first when they are immutable (responses passed through from `fetch()`). */\nexport function withHeaders(response: Response, apply: (headers: Headers) => void): Response {\n try {\n apply(response.headers);\n return response;\n } catch {\n const headers = new Headers(response.headers);\n apply(headers);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n}\n\n/**\n * The header side of a decision on any sink: the merged CSP for its mode,\n * then the cache headers — those also when the mode is off, because an\n * injected body alone already makes the response private.\n */\nexport function applyCspHeaders(\n headers: HeaderSink,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): void {\n const mode = decision.cspMode;\n if (mode !== false) {\n const existing = headers.get('content-security-policy') ?? '';\n headers.set('content-security-policy', policy.csp(existing, nonce, mode));\n }\n markUncacheable(headers);\n}\n\n/** Set the merged CSP header for `mode` and mark the response uncacheable. */\nexport function withCspHeader(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Response {\n return withHeaders(response, (headers) => {\n applyCspHeaders(headers, policy, decision, nonce);\n });\n}\n\n/** Apply a decision end to end: inject, then CSP and cache headers. The response is returned as-is when nothing changes. */\nexport async function applyDecision(\n response: Response,\n policy: PreviewPolicy,\n decision: PreviewDecision,\n nonce: string,\n): Promise<Response> {\n if (!decision.inject && decision.cspMode === false) return response;\n const injected = decision.inject\n ? await injectIntoResponse(response, policy.scriptTag(nonce))\n : response;\n return withCspHeader(injected, policy, decision, nonce);\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']` — the adapters' option of the same name. */\n readonly allowedOrigins?: readonly string[];\n /** @deprecated Use `allowedOrigins`; removed in 3.0. Ignored when `allowedOrigins` is given. */\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 // The 1.x spelling is honoured until 3.0; the canonical name wins when both are given.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the alias is read exactly here\n const configured = options.allowedOrigins ?? options.adminOrigins ?? [];\n const adminOrigins = signals.has('referer') ? configured : [];\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 * One development warning per process. The set of issued keys lives on\n * `globalThis` so two package copies in one process still warn once.\n */\n\nconst WARNED_KEY = '__payloadLivePreviewDeprecationsWarned';\n\n/** `true` outside a production build; `false` when `NODE_ENV` is production or unknown. */\nexport function isDevelopmentProcess(): boolean {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n if (env === undefined) return false;\n return env['NODE_ENV'] !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Warn once per process for `key`, outside production only. */\nexport function warnOnce(key: string, message: string): void {\n if (!isDevelopmentProcess()) return;\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n const warned = (holder[WARNED_KEY] ??= new Set<string>());\n if (warned.has(key)) return;\n warned.add(key);\n try {\n console.warn(`[payload-live-preview] ${message}`);\n } catch {\n // A console that throws must not break a request.\n }\n}\n\n/** Test hook: forget every warning issued so far. */\nexport function resetDevWarnings(): void {\n const holder = globalThis as unknown as Record<string, Set<string> | undefined>;\n holder[WARNED_KEY] = undefined;\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 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 * Running an `authorizePreview` hook. What the hook may resolve to is\n * normalised here once, so the page policy and the fragment endpoint read the\n * same verdict from the same callback. See ADR 0006.\n */\n\nimport {\n isPreviewConfigurationError,\n refused,\n type PreviewAuthorization,\n} from '@security/preview-verdict';\n// From the leaf `types` domain on purpose: the security module would pull the\n// HMAC and session code into every adapter bundle for a ten-line brand check.\nimport { isAuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewAuthorizationHookResult } from './options';\n\n/** A bound hook: the adapter option with the request already applied. */\nexport type BoundAuthorizeHook = () =>\n PreviewAuthorizationHookResult | Promise<PreviewAuthorizationHookResult>;\n\n/**\n * The hook's result as a verdict. Only a context `authorizePreviewRequest()`\n * produced authorizes, bare or inside its verdict; a `{ authorized: true }`\n * literal, a copy, a boolean or nothing refuses as `'invalid'`.\n */\nexport function verdictFrom(result: PreviewAuthorizationHookResult): PreviewAuthorization {\n if (isAuthorizedPreviewContext(result)) {\n return { authorized: true, outcome: 'authorized', context: result };\n }\n if (typeof result === 'object' && result !== null && 'authorized' in result) {\n if (result.authorized && isAuthorizedPreviewContext(result.context)) {\n return { authorized: true, outcome: 'authorized', context: result.context };\n }\n return refused(result.authorized ? 'invalid' : result.outcome);\n }\n // `null`, `undefined`, a boolean, a look-alike literal: refused.\n return refused('invalid');\n}\n\n/**\n * Run a bound hook: a `PreviewConfigurationError` is re-thrown so a\n * misconfigured strategy is loud, any other failure is the `'unavailable'`\n * refusal — an identity provider being down must never authorize.\n */\nexport async function runAuthorizeHook(hook: BoundAuthorizeHook): Promise<PreviewAuthorization> {\n let result: PreviewAuthorizationHookResult;\n try {\n result = await hook();\n } catch (error) {\n if (isPreviewConfigurationError(error)) throw error;\n return refused('unavailable');\n }\n return verdictFrom(result);\n}\n","/**\n * What `strict` refuses at startup, so a misconfiguration fails the process\n * rather than a public response (ADR 0006).\n */\n\nimport { isDevelopmentProcess } from './dev-warning';\nimport { resolvePolicyOptions, type PreviewPolicyOptions } from './policy-options';\n\n/**\n * The sentence every strict refusal ends with.\n *\n * Each of these rules is new in 2.0, and the process that stops is one that\n * worked yesterday. Saying only the rule leaves an upgrader to find out that\n * there is a staged path at all — so the way out is in the message that stops\n * them, not only in the guide they have not opened yet.\n */\nconst STAGED =\n \" New in 2.0; `defaults: 'v1'` keeps the 1.x table while you migrate (docs/migration.md).\";\n\n/** The configuration errors `strict` exists to raise, at startup rather than on a public response. */\nexport function assertStrictConfiguration(options: PreviewPolicyOptions): void {\n if (typeof options.authorizePreview !== 'function') {\n throw new Error(\n 'payload-live-preview: strict mode requires `authorizePreview` — response changes ' +\n 'must be gated on a verified context, not on intent (ADR 0006).' +\n STAGED,\n );\n }\n const origins = options.allowedOrigins ?? [];\n if (origins.length === 0) {\n throw new Error(\n 'payload-live-preview: strict mode requires explicit, non-empty `allowedOrigins`.' + STAGED,\n );\n }\n if (!isDevelopmentProcess()) {\n for (const origin of origins) {\n let protocol: string | undefined;\n try {\n protocol = new URL(origin).protocol;\n } catch {\n protocol = undefined;\n }\n if (protocol !== 'https:') {\n throw new Error(\n `payload-live-preview: strict mode requires https admin origins in production; got \"${origin}\".` +\n STAGED,\n );\n }\n }\n }\n // The resolved signals, not the option: `defaults: 'v1'` fills in `referer`.\n if (resolvePolicyOptions(options).previewSignals?.includes('referer') === true) {\n throw new Error(\n \"payload-live-preview: strict mode disables referrer trust; remove 'referer' from \" +\n \"`previewSignals` (the 'v1' profile includes it).\",\n );\n }\n}\n","/**\n * The preview policy every framework adapter applies: intent, authorization,\n * injection, CSP. Pure — it reads a `{ url, headers.get }` request shape and\n * never touches a response; the adapter translates both ends. See ADR 0006.\n */\n\nimport {\n buildFrameAncestors,\n buildScriptSrcWithNonce,\n generateCspNonce,\n mergeCspHeader,\n} from '@security/csp';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { assertMergeDepthExplicit } from '@/types/merge-depth';\nimport { wrapWithScriptTag } from '@inline/generator';\n// Delivery is decided in one place; the policy caches whatever that produced.\nimport { renderScriptBody } from './response';\nimport { hasPreviewIntent, type PreviewRequestLike } from './preview-request';\nimport { warnOnce } from './dev-warning';\nimport { runAuthorizeHook, type BoundAuthorizeHook } from './authorize-hook';\nimport { resolvePolicyOptions, type PageFacts, type PreviewPolicyOptions } from './policy-options';\nimport { assertStrictConfiguration } from './strict';\n\nexport type { PreviewAuthorizationHookResult } from './options';\n\n/** How the adapter manages Content-Security-Policy, normalised. */\nexport type CspMode = false | 'frame-ancestors' | 'full';\n\n/** `manageCsp` normalised: unset and `true` both mean frame-ancestors only. */\nexport function normalizeCspMode(value: PreviewPolicyOptions['manageCsp']): CspMode {\n if (value === false) return false;\n if (value === 'full') return 'full';\n return 'frame-ancestors';\n}\n\n/** Whether the request shows preview intent under the options; `inject: 'always'` counts as intent. */\nexport function previewIntentFor(\n request: PreviewRequestLike,\n options: PreviewPolicyOptions,\n): boolean {\n const signals = resolvePolicyOptions(options).previewSignals;\n return (\n (options.inject ?? 'preview-only') === 'always' ||\n hasPreviewIntent(request, {\n ...(options.previewQueryParams !== undefined\n ? { queryParams: options.previewQueryParams }\n : {}),\n ...(signals !== undefined ? { signals } : {}),\n allowedOrigins: options.allowedOrigins ?? [],\n })\n );\n}\n\n/** The CSP header after merging: `frame-ancestors` always, a nonce'd `script-src` only in `'full'` mode. */\nexport function buildPreviewCsp(\n options: PreviewPolicyOptions,\n nonce: string,\n existing: string,\n mode: Exclude<CspMode, false>,\n): string {\n const additions: Record<string, string> = {\n 'frame-ancestors': buildFrameAncestors({\n self: true,\n origins: [...(options.allowedOrigins ?? []), ...(options.frameAncestorsExtra ?? [])],\n }),\n };\n if (mode === 'full') {\n additions['script-src'] = buildScriptSrcWithNonce(nonce, {\n self: true,\n strictDynamic: options.strictDynamic ?? false,\n ...(options.scriptSrcExtra !== undefined ? { extra: options.scriptSrcExtra } : {}),\n });\n }\n return mergeCspHeader(existing, additions);\n}\n\n/** What the policy decided for one request. */\nexport interface PreviewDecision {\n /** The request shows preview intent (or the adapter injects always). */\n readonly isPreview: boolean;\n /** The verified context, or `null` when there was no hook or it refused. */\n readonly authorization: AuthorizedPreviewContext | null;\n /** The hook's verdict, or `undefined` when no hook ran (no intent, or none configured). */\n readonly outcome: PreviewAuthorizationOutcome | undefined;\n /** Intent, authorization, `autoInject` and the adapter's content filter all agreed. */\n readonly inject: boolean;\n /** CSP directives to add, or `false`. Never set without intent, never after a refusal. */\n readonly cspMode: CspMode;\n /** Whether the request-scoped nonce may be handed to templates. */\n readonly exposeNonce: boolean;\n}\n\n/** The per-request hooks an adapter binds to its own request type. */\nexport interface PreviewDecisionHooks {\n /** The adapter's content filter, evaluated lazily once injection is otherwise decided. */\n readonly shouldInject?: () => boolean;\n /** The adapter's `authorizePreview` option, bound to the framework request. Called only on intent. */\n readonly authorize?: BoundAuthorizeHook;\n}\n\n/** A policy bound to one adapter's options. The script body depends on the options only and is built once. */\nexport interface PreviewPolicy {\n /**\n * Decide for a request: `hooks.authorize` runs only on intent, and a\n * `PreviewConfigurationError` from it is re-thrown while any other failure\n * becomes the `'unavailable'` refusal.\n */\n decide(request: PreviewRequestLike, hooks?: PreviewDecisionHooks): Promise<PreviewDecision>;\n /** The `<script>` tag for this policy's runtime, carrying `nonce`. */\n scriptTag(nonce: string): string;\n /** CSP header value for a decision that has a mode. */\n csp(existing: string, nonce: string, mode: Exclude<CspMode, false>): string;\n /** A fresh nonce. */\n nonce(): string;\n /** Whether `authorizePreview` is configured; `decide()` then requires the bound hook. */\n readonly authorizes: boolean;\n}\n\nconst NONE: PreviewDecision = Object.freeze({\n isPreview: false,\n authorization: null,\n outcome: undefined,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n});\n\nexport function createPreviewPolicy(\n options: PreviewPolicyOptions,\n facts: PageFacts = {},\n): PreviewPolicy {\n const resolved = resolvePolicyOptions(options);\n assertMergeDepthExplicit(options);\n const authorizes = typeof options.authorizePreview === 'function';\n if (resolved.strict) {\n assertStrictConfiguration(options);\n } else if (!authorizes) {\n warnOnce(\n 'intent-only-preview',\n 'preview responses are gated on client-controlled intent only. Configure `authorizePreview` ' +\n '(see authorizePreviewRequest) before production; `strict: true` enforces it. ' +\n 'ADR 0006 explains why intent is not authorization.',\n );\n }\n const cspMode = normalizeCspMode(options.manageCsp);\n const autoInject = options.autoInject ?? true;\n let body: string | undefined;\n const scriptBody = (): string => {\n body ??= renderScriptBody(options, facts);\n return body;\n };\n return {\n authorizes,\n async decide(request, hooks = {}) {\n if (authorizes && hooks.authorize === undefined) {\n throw new Error(\n 'payload-live-preview: `authorizePreview` is configured but decide() was called ' +\n 'without an `authorize` hook; bind the hook to the request (bindDecisionHooks).',\n );\n }\n const isPreview = previewIntentFor(request, options);\n if (!isPreview) return NONE;\n let authorization: AuthorizedPreviewContext | null = null;\n let outcome: PreviewAuthorizationOutcome | undefined;\n if (hooks.authorize !== undefined) {\n const verdict = await runAuthorizeHook(hooks.authorize);\n outcome = verdict.outcome;\n if (!verdict.authorized) {\n return {\n isPreview,\n authorization: null,\n outcome,\n inject: false,\n cspMode: false,\n exposeNonce: false,\n };\n }\n authorization = verdict.context;\n }\n return {\n isPreview,\n authorization,\n outcome,\n inject: autoInject && (hooks.shouldInject?.() ?? true),\n cspMode,\n exposeNonce: true,\n };\n },\n scriptTag: (nonce) => wrapWithScriptTag(scriptBody(), { nonce }),\n csp: (existing, nonce, mode) => buildPreviewCsp(options, nonce, existing, mode),\n nonce: () => generateCspNonce(),\n };\n}\n","/** What a decision publishes for templates on `locals` (Astro, SvelteKit) or `event.context` (Nuxt). */\n\nimport { createPreviewBindings, type PreviewBindings } from '@dsl/preview-bindings';\nimport type { PreviewAuthorizationOutcome } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport type { PreviewDecision } from './policy';\n\n/**\n * The keys the adapters publish on the request-scoped context — `Astro.locals`,\n * SvelteKit's `event.locals`, Nuxt's `event.context`. Extend the framework's\n * `App.Locals` with it and templates read them typed. Every key is optional:\n * a refused preview withholds them all, and Next.js has no locals at all.\n */\nexport interface LivePreviewLocals {\n /**\n * The request-scoped CSP nonce, for templates that nonce their own scripts.\n * Set by the Astro middleware (prerendered pages included), the SvelteKit\n * handle and the Nuxt server handler or plugin on every request — except a\n * preview the `authorizePreview` hook refused, which gets no preview artefact.\n */\n readonly livePreviewNonce?: string;\n /** The verified `AuthorizedPreviewContext`. Set only when `authorizePreview` authorized an intent-bearing request. */\n readonly livePreviewAuthorization?: AuthorizedPreviewContext;\n /** The hook's `PreviewAuthorizationOutcome`, refusals included. Set whenever the hook ran: on intent, with `authorizePreview` configured. */\n readonly livePreviewAuthorizationOutcome?: PreviewAuthorizationOutcome;\n}\n\n/** The request-scoped nonce, for templates that nonce their own scripts. @internal */\nexport const NONCE_LOCALS_KEY = 'livePreviewNonce' satisfies keyof LivePreviewLocals;\n\n/** The verified `AuthorizedPreviewContext`; absent unless `authorizePreview` authorized. @internal */\nexport const AUTHORIZATION_LOCALS_KEY =\n 'livePreviewAuthorization' satisfies keyof LivePreviewLocals;\n\n/** The hook's `PreviewAuthorizationOutcome`; absent when no hook ran. @internal */\nexport const AUTHORIZATION_OUTCOME_LOCALS_KEY =\n 'livePreviewAuthorizationOutcome' satisfies keyof LivePreviewLocals;\n\n/**\n * What an adapter needs of a framework's request context: the three keys it\n * writes, and nothing else.\n *\n * This is what the adapters' event types declare rather than\n * `Record<string, unknown>`. A framework's own `App.Locals` is an interface\n * without an index signature, so it is not assignable to a record — which made\n * composing our handle with SvelteKit's `Handle` type fail to compile, even\n * though the values matched. The adapters assign through the interface's own\n * keys, so the published type cannot drift from what the code writes either.\n */\nexport type LivePreviewLocalsSink = {\n -readonly [K in keyof LivePreviewLocals]: LivePreviewLocals[K];\n};\n\n/** Publish the nonce alone — a prerendered page has no request to decide for. */\nexport function exposeNonce(locals: LivePreviewLocalsSink, nonce: string): void {\n locals.livePreviewNonce = nonce;\n}\n\n/** Publish what templates may read; after a refusal the nonce is withheld like every other preview artefact. */\nexport function exposeDecision(\n locals: LivePreviewLocalsSink,\n decision: PreviewDecision,\n nonce: string,\n): void {\n if (decision.exposeNonce || !decision.isPreview) locals.livePreviewNonce = nonce;\n if (decision.authorization !== null) locals.livePreviewAuthorization = decision.authorization;\n if (decision.outcome !== undefined) locals.livePreviewAuthorizationOutcome = decision.outcome;\n}\n\n/**\n * The binding helpers for one request, read straight off whatever the framework\n * calls locals — `Astro.locals`, SvelteKit's `event.locals`, Nuxt's\n * `event.context`.\n *\n * `createPreviewBindings({ authorization: locals.livePreviewAuthorization })`\n * says the same thing, and a template that spells it out is welcome to. This\n * exists because generated code should not have to: the build-time annotator\n * writes one call per component, and a helper that takes `unknown` needs no\n * `App.Locals` declaration in the project it writes into. The verdict is\n * checked, not trusted — only a context `authorizePreviewRequest()` produced\n * emits anything (ADR 0006).\n * @internal\n */\nexport function previewBindingsFromLocals(\n locals: unknown,\n options: { readonly owner?: string } = {},\n): PreviewBindings {\n const value =\n typeof locals === 'object' && locals !== null\n ? (locals as Record<string, unknown>)[AUTHORIZATION_LOCALS_KEY]\n : undefined;\n return createPreviewBindings({\n authorization: (value ?? null) as AuthorizedPreviewContext | null,\n ...(options.owner !== undefined ? { owner: options.owner } : {}),\n });\n}\n","/**\n * Astro middleware: decides before rendering so templates can read\n * `Astro.locals`, then injects into the HTML response and merges CSP.\n * Prerendered pages are skipped — there is no request to decide for at build time.\n */\n\nimport { createPreviewPolicy } from '@adapters/shared/policy';\nimport { applyDecision, bindDecisionHooks } from '@adapters/shared/response';\nimport { exposeDecision, exposeNonce, type LivePreviewLocalsSink } from '@adapters/shared/locals';\nimport type { LivePreviewAstroOptions } from './types';\n\nexport {\n AUTHORIZATION_LOCALS_KEY,\n AUTHORIZATION_OUTCOME_LOCALS_KEY,\n NONCE_LOCALS_KEY,\n type LivePreviewLocals,\n} from '@adapters/shared/locals';\n\n// Local shims keep `astro` a runtime-optional peer; the runtime signature matches.\ntype MiddlewareNext = () => Promise<Response>;\ninterface MiddlewareContext {\n readonly request: Request;\n readonly locals: LivePreviewLocalsSink;\n /** Astro ≥ 5: `true` while prerendering at build time. */\n readonly isPrerendered?: boolean;\n}\nexport type LivePreviewMiddleware = (\n context: MiddlewareContext,\n next: MiddlewareNext,\n) => Promise<Response>;\n\n/** Build the middleware; it publishes the nonce, the context and the outcome on `Astro.locals`. */\nexport function createLivePreviewMiddleware(\n options: LivePreviewAstroOptions = {},\n): LivePreviewMiddleware {\n const policy = createPreviewPolicy(options);\n return async (context, next) => {\n const nonce = policy.nonce();\n if (context.isPrerendered === true) {\n exposeNonce(context.locals, nonce);\n return next();\n }\n const decision = await policy.decide(\n context.request,\n bindDecisionHooks(policy, options, context.request),\n );\n exposeDecision(context.locals, decision, nonce);\n const response = await next();\n if (!decision.isPreview) return response;\n return applyDecision(response, policy, decision, nonce);\n };\n}\n","/**\n * Manual embedding for `.astro` templates, for the cases the integration's\n * automatic injection does not fit (one layout, a conditional).\n */\n\nimport { renderScriptTag } from '@adapters/shared/response';\nimport type { LivePreviewAstroOptions } from './types';\n\nexport interface RenderScriptOptions extends LivePreviewAstroOptions {\n /** CSP nonce for the tag; read it from `Astro.locals.livePreviewNonce`. */\n readonly nonce?: string;\n}\n\n/** The complete `<script>` tag, for `<Fragment set:html={renderLivePreviewScript(...)} />`. */\nexport function renderLivePreviewScript(options: RenderScriptOptions = {}): string {\n return renderScriptTag(options);\n}\n","/**\n * The 1.x names that 2.0 renamed, kept so a 1.x project compiles unchanged.\n *\n * A file of its own, and a small one: everything deprecated for 3.0 that the\n * rename ledger produced lives here, so removing it is one deletion rather than\n * a search. It also keeps the alias out of the module that defines the real\n * function, where two exports of one value read as an accident.\n *\n * Measured against the published 1.8.1 declarations, entry by entry, not\n * guessed: `isPreviewRequest` was exported from the root **and** from\n * `./astro`, so it is re-exported from both. The six names 2.0 dropped\n * moved behind `definePreview()` or changed shape, where an alias would restore\n * the very defaults the move removed (ADR 0007, ledger rows 1 and 9).\n */\n\nimport { hasPreviewIntent } from './preview-request';\n\n/**\n * @deprecated Use `hasPreviewIntent`; removed in 3.0. `pll migrate` rewrites it.\n */\nexport const isPreviewRequest = hasPreviewIntent;\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 /**\n * Record `id` as used until `expiresAt` and say whether this call was the\n * first: `true` admits the token, anything else refuses it as `replayed`, a\n * throw refuses it as `unavailable`. Check and record in one step (Redis\n * `SET NX PX`, a unique insert): a read followed by a write lets two requests\n * that carry the same token and arrive together both pass.\n */\n consume(id: string, expiresAt: number): Promise<boolean> | boolean;\n}\n\n/**\n * @deprecated The 1.x store shape, removed in 3.0. Its two calls cannot be one\n * step, so two requests with the same token that arrive together both pass\n * `isUsed` before either reaches `markUsed`. Implement\n * {@link PreviewTokenReplayStore.consume} instead.\n */\nexport interface PreviewTokenReplayChecks {\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 // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape is accepted until 3.0\n readonly replay?: PreviewTokenReplayStore | PreviewTokenReplayChecks;\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 let first: boolean;\n try {\n first = await consumeTokenId(strategy.replay, claims.jti, claims.exp);\n } catch {\n return refused('unavailable');\n }\n if (!first) return refused('replayed');\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/**\n * `true` when `id` was not seen before. A store that returns anything but\n * `true` from `consume` refuses the token: fail closed, since a forgotten\n * return would otherwise admit every replay. The 1.x shape keeps its two\n * steps and its race; that is why it is deprecated rather than emulated.\n */\nasync function consumeTokenId(\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape is accepted until 3.0\n store: PreviewTokenReplayStore | PreviewTokenReplayChecks,\n id: string,\n expiresAt: number,\n): Promise<boolean> {\n if ('consume' in store) {\n // The store is consumer code; its answer is a value, not a type.\n const answer: unknown = await store.consume(id, expiresAt);\n return answer === true;\n }\n if (await store.isUsed(id)) return false;\n await store.markUsed(id, expiresAt);\n return true;\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 `missing-credential`. 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 * 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 // eslint-disable-next-line @typescript-eslint/no-deprecated -- the 1.x shape exists to be re-exported\n type PreviewTokenReplayChecks,\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","/**\n * The fragment wire protocol: what the browser posts to a fragment endpoint\n * and what it answers. Both sides validate the shape. The request names the\n * page by its own route and query and the boundary by its registry id; nothing\n * on the wire carries code, templates, import paths or file paths. See ADR 0011.\n */\n\n/** Bumped when the request or response shape changes incompatibly. @internal */\nexport const FRAGMENT_PROTOCOL_VERSION = 1;\n/** @internal */\nexport const FRAGMENT_VERSION_HEADER = 'x-payload-fragment-version';\n\n/** @internal */\nexport interface FragmentRequestBody {\n /** Registry id of the boundary (`data-payload-fragment`). */\n readonly fragment: string;\n /** `data-payload-fragment-key`, when several boundaries share one id. */\n readonly key?: string;\n /** The page route the boundary belongs to; authorization is bound to it. */\n readonly route: string;\n /** The page's query string, so a `previewToken` in the URL reaches the endpoint. */\n readonly search: string;\n readonly revision: number;\n readonly locale?: string;\n readonly collectionSlug?: string;\n readonly globalSlug?: string;\n /** The unsaved form state as the admin posted it, after the runtime's merge. */\n readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/** @internal */\nexport interface FragmentResponseBody {\n /** The boundary's new inner HTML. */\n readonly html: string;\n readonly boundary: { readonly id: string; readonly key?: string };\n /** Echoes the request; the client discards a response for another revision. */\n readonly revision: number;\n readonly metadata: {\n readonly renderedAt: string;\n /** What rendered it, e.g. `astro-container`. */\n readonly renderer: string;\n readonly durationMs?: number;\n };\n}\n\nconst MAX_FIELD_DEPTH = 12;\n\nfunction depthOf(value: unknown, depth: number): number {\n if (depth > MAX_FIELD_DEPTH || typeof value !== 'object' || value === null) return depth;\n let deepest = depth;\n for (const child of Object.values(value)) {\n deepest = Math.max(deepest, depthOf(child, depth + 1));\n if (deepest > MAX_FIELD_DEPTH) break;\n }\n return deepest;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Shape check for a request body; `null` when it is not one. @internal */\nexport function parseFragmentRequest(value: unknown): FragmentRequestBody | null {\n if (!isRecord(value)) return null;\n const fragment = value['fragment'];\n if (typeof fragment !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/iu.test(fragment)) return null;\n const key = value['key'];\n if (key !== undefined && (typeof key !== 'string' || key.length > 128)) return null;\n const route = value['route'];\n if (typeof route !== 'string' || !route.startsWith('/') || route.length > 2048) return null;\n const search = value['search'];\n if (\n typeof search !== 'string' ||\n search.length > 4096 ||\n (search !== '' && !search.startsWith('?'))\n ) {\n return null;\n }\n const revision = value['revision'];\n if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 0) return null;\n const slugs: (string | undefined)[] = [];\n for (const name of ['locale', 'collectionSlug', 'globalSlug'] as const) {\n const slug = value[name];\n if (slug === undefined) {\n slugs.push(undefined);\n continue;\n }\n if (typeof slug !== 'string' || slug.length > 128) return null;\n slugs.push(slug);\n }\n const [locale, collectionSlug, globalSlug] = slugs;\n const fields = value['fields'];\n if (!isRecord(fields) || depthOf(fields, 0) > MAX_FIELD_DEPTH) return null;\n return {\n fragment,\n ...(typeof key === 'string' ? { key } : {}),\n route,\n search,\n revision,\n ...(locale !== undefined ? { locale } : {}),\n ...(collectionSlug !== undefined ? { collectionSlug } : {}),\n ...(globalSlug !== undefined ? { globalSlug } : {}),\n fields,\n };\n}\n\n/** Shape check for a response body; `null` when it is not one. @internal */\nexport function parseFragmentResponse(value: unknown): FragmentResponseBody | null {\n if (!isRecord(value)) return null;\n const { html, boundary, revision, metadata } = value;\n if (typeof html !== 'string') return null;\n if (!isRecord(boundary) || typeof boundary['id'] !== 'string') return null;\n if (boundary['key'] !== undefined && typeof boundary['key'] !== 'string') return null;\n if (typeof revision !== 'number') return null;\n if (\n !isRecord(metadata) ||\n typeof metadata['renderedAt'] !== 'string' ||\n typeof metadata['renderer'] !== 'string'\n ) {\n return null;\n }\n return value as unknown as FragmentResponseBody;\n}\n","/**\n * The fragment endpoint, without a component system (ADR 0011): it renders a\n * registered boundary from unsaved form state for an authorized preview, and\n * nothing else. The browser names a registry id; the server decides what that\n * id renders.\n *\n * Everything here is framework-neutral — method and origin checks, the body\n * limit, the protocol, authorization, the registry lookup, the timeouts and the\n * response shape. An adapter binds one renderer to it and exports the result;\n * `src/adapters/astro/fragments.ts` and `src/adapters/nextjs/fragments.ts` are\n * the two, and each is a few dozen lines because this file is the endpoint.\n */\nimport {\n authorizePreviewRequest,\n type PreviewAuthorizationStrategy,\n} from '@security/preview-authorization';\nimport type { PreviewAuthorization } from '@security/preview-verdict';\nimport type { AuthorizedPreviewContext } from '@/types/authorized-preview';\nimport { runAuthorizeHook } from './authorize-hook';\nimport { warnOnce } from './dev-warning';\nimport type { PreviewAdapterOptions } from './options';\nimport {\n FRAGMENT_PROTOCOL_VERSION,\n FRAGMENT_VERSION_HEADER,\n parseFragmentRequest,\n type FragmentRequestBody,\n type FragmentResponseBody,\n} from '@/types/fragment-protocol';\n\n/** Everything a registry entry may use to compute its props. */\nexport interface FragmentRenderInput {\n readonly id: string;\n readonly key: string | undefined;\n readonly revision: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n readonly route: string;\n readonly authorization: AuthorizedPreviewContext;\n readonly request: Request;\n}\n\n/**\n * `Props extends object`, not `Record<string, unknown>`: an `interface` has no\n * implicit index signature, so the natural way to type a component's props\n * would not satisfy the narrower constraint and every consumer would have to\n * restate their props as a type alias. The renderer widens once, where the\n * props are handed to it.\n */\nexport interface FragmentRegistryEntry<Component, Props extends object = object> {\n readonly component: Component;\n /** Props for the component, computed from the input; never from request-controlled code. */\n readonly props: (input: FragmentRenderInput) => Props | Promise<Props>;\n}\n\nexport type FragmentRegistry<Component> = Readonly<\n Record<string, FragmentRegistryEntry<Component>>\n>;\n\n/** Renders a component with props to HTML. Each adapter supplies its own. */\nexport type FragmentRenderer<Component> = (\n component: Component,\n props: Record<string, unknown>,\n input: FragmentRenderInput,\n) => Promise<string>;\n\nexport interface FragmentEndpointOptions<Component> {\n /** The only things this endpoint can render. */\n readonly registry: FragmentRegistry<Component>;\n /**\n * The middleware's `authorizePreview` hook — same type, same rules: a\n * context `authorizePreviewRequest()` produced authorizes, anything else\n * refuses, a `PreviewConfigurationError` is loud. It is called with the\n * page request the fragment belongs to (route, search, and this request's\n * headers), so a token stays bound to its route and a session is the\n * visitor's own. One of `authorizePreview` and `authorize` is required.\n */\n readonly authorizePreview?: NonNullable<PreviewAdapterOptions['authorizePreview']>;\n /** A strategy for `authorizePreviewRequest()`, when there is no hook to share. Exclusive with `authorizePreview`. */\n readonly authorize?: PreviewAuthorizationStrategy;\n /** Override the adapter's renderer (tests, another component system). */\n readonly render?: FragmentRenderer<Component>;\n /** Origins besides the page's own that may call the endpoint. Default: none. */\n readonly allowedOrigins?: readonly string[];\n readonly limits?: {\n /** Largest request body. Default 64 KiB. */\n readonly bodyBytes?: number;\n /** Render timeout. Default 5000 ms. */\n readonly timeoutMs?: number;\n };\n}\n\n/** What an adapter adds to the consumer's options: its renderer and the name that goes in the response metadata. */\nexport interface FragmentEndpointBinding<Component> {\n readonly render: FragmentRenderer<Component>;\n readonly rendererName: string;\n}\n\nconst DEFAULT_BODY_BYTES = 64 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5_000;\n\nconst NO_STORE_HEADERS: Readonly<Record<string, string>> = {\n 'cache-control': 'private, no-store',\n 'x-content-type-options': 'nosniff',\n vary: 'Cookie',\n [FRAGMENT_VERSION_HEADER]: String(FRAGMENT_PROTOCOL_VERSION),\n};\n\n/** A refusal carries a status and a generic word, never why. */\nfunction refuse(status: number, error: string): Response {\n return new Response(JSON.stringify({ error }), {\n status,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n}\n\nfunction sameOrigin(request: Request, allowed: ReadonlySet<string>): boolean {\n const site = request.headers.get('sec-fetch-site');\n if (site !== null && site !== 'same-origin' && site !== 'none') return false;\n const origin = request.headers.get('origin');\n if (origin === null) return true;\n return origin === new URL(request.url).origin || allowed.has(origin);\n}\n\nfunction scopeAllows(context: AuthorizedPreviewContext, body: FragmentRequestBody): boolean {\n const scope = context.scope;\n if (scope.locale !== undefined && body.locale !== undefined && scope.locale !== body.locale) {\n return false;\n }\n return true;\n}\n\n/**\n * A body that exceeded the limit, as a value no JSON document can be. The two\n * refusals it separates are both in the abuse model (ADR 0011 §4) and both say\n * one generic word: \"413 body\" for a request that was too large to read, and\n * the shape refusal below for one that was read and is not a request. Folding\n * them together answered eight bytes of `not json` with \"Payload Too Large\".\n */\nconst TOO_LARGE = Symbol('body over the limit');\n\n/** The parsed body, `TOO_LARGE` over the limit, or `null` when it is not JSON. */\nasync function readBody(request: Request, limit: number): Promise<unknown> {\n const declared = Number(request.headers.get('content-length') ?? '0');\n if (declared > limit) return TOO_LARGE;\n const text = await request.text();\n if (text.length > limit) return TOO_LARGE;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n // Not JSON is not a request: `parseFragmentRequest` refuses `null` as the\n // wrong shape, which is what it is, and no second branch is needed.\n return null;\n }\n}\n\nfunction withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error('fragment render timed out'));\n }, ms);\n work.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timer);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n\ntype FragmentAuthorizer = (pageRequest: Request) => Promise<PreviewAuthorization>;\n\n/** One authorizer from the two options: the hook decides as it does in the middleware, a strategy as `authorizePreviewRequest()` does. */\nfunction authorizerFor<Component>(options: FragmentEndpointOptions<Component>): FragmentAuthorizer {\n const { authorize, authorizePreview } = options;\n if (authorizePreview !== undefined && authorize !== undefined) {\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() takes `authorizePreview` or `authorize`, ' +\n 'not both — pass the middleware hook as `authorizePreview`, or a strategy as `authorize`.',\n );\n }\n if (authorizePreview !== undefined) {\n return (pageRequest) => runAuthorizeHook(() => authorizePreview(pageRequest));\n }\n if (authorize !== undefined) {\n return (pageRequest) => authorizePreviewRequest(pageRequest, authorize);\n }\n throw new Error(\n 'payload-live-preview: createFragmentEndpoint() needs `authorizePreview` (the middleware hook) ' +\n 'or `authorize` (a strategy); without one it would render drafts for anyone.',\n );\n}\n\n/**\n * The endpoint as a plain `Request` → `Response` function. Adapters wrap it in\n * whatever their framework hands a route handler.\n */\nexport function createFragmentEndpointHandler<Component>(\n options: FragmentEndpointOptions<Component>,\n binding: FragmentEndpointBinding<Component>,\n): (request: Request) => Promise<Response> {\n const authorize = authorizerFor(options);\n const render = options.render ?? binding.render;\n const rendererName = options.render === undefined ? binding.rendererName : 'custom';\n const allowed = new Set(options.allowedOrigins ?? []);\n const bodyLimit = options.limits?.bodyBytes ?? DEFAULT_BODY_BYTES;\n const timeoutMs = options.limits?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const registry = options.registry;\n\n return async (request) => {\n if (request.method !== 'POST') return refuse(405, 'method');\n if (!sameOrigin(request, allowed)) return refuse(403, 'origin');\n const type = request.headers.get('content-type') ?? '';\n if (!type.toLowerCase().startsWith('application/json')) return refuse(415, 'content-type');\n const raw = await readBody(request, bodyLimit);\n if (raw === TOO_LARGE) return refuse(413, 'body');\n const body = parseFragmentRequest(raw);\n if (body === null) return refuse(400, 'shape');\n\n // Authorize as the page would, so a token stays bound to the route it was\n // issued for and a session is the visitor's own.\n const origin = new URL(request.url).origin;\n const pageRequest = new Request(`${origin}${body.route}${body.search}`, {\n headers: request.headers,\n });\n const authorization = await authorize(pageRequest);\n if (!authorization.authorized || !scopeAllows(authorization.context, body)) {\n return refuse(403, 'unauthorized');\n }\n const entry = Object.prototype.hasOwnProperty.call(registry, body.fragment)\n ? registry[body.fragment]\n : undefined;\n if (entry === undefined) return refuse(404, 'fragment');\n\n const input: FragmentRenderInput = {\n id: body.fragment,\n key: body.key,\n revision: body.revision,\n fields: body.fields,\n locale: body.locale,\n collectionSlug: body.collectionSlug,\n globalSlug: body.globalSlug,\n route: body.route,\n authorization: authorization.context,\n request,\n };\n const started = Date.now();\n let html: string;\n try {\n const props = await withTimeout(Promise.resolve(entry.props(input)), timeoutMs);\n // The one widening: the site types its props as it likes (see\n // FragmentRegistryEntry), the renderer takes a record of them.\n const record = props as Record<string, unknown>;\n html = await withTimeout(render(entry.component, record, input), timeoutMs);\n } catch (error) {\n // The response stays generic; the server log is where the cause belongs,\n // and without it a 500 here is a boundary that silently never renders.\n warnOnce(\n `fragment-render:${body.fragment}`,\n `fragment \"${body.fragment}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n return refuse(500, 'render');\n }\n const response: FragmentResponseBody = {\n html,\n boundary: { id: body.fragment, ...(body.key !== undefined ? { key: body.key } : {}) },\n revision: body.revision,\n metadata: {\n renderedAt: new Date().toISOString(),\n renderer: rendererName,\n durationMs: Date.now() - started,\n },\n };\n return new Response(JSON.stringify(response), {\n status: 200,\n headers: { ...NO_STORE_HEADERS, 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n","/**\n * The Astro binding of the fragment endpoint: Astro's container API as the\n * renderer, and the endpoint shaped as an Astro API route. Everything the\n * endpoint decides — authorization, limits, the protocol, the registry lookup —\n * is in `@adapters/shared/fragment-endpoint`.\n */\nimport { lazyPeer, missingPeerError } from '@adapters/shared/optional-peer';\nimport {\n createFragmentEndpointHandler,\n type FragmentEndpointOptions as SharedOptions,\n type FragmentRegistry as SharedRegistry,\n type FragmentRegistryEntry as SharedRegistryEntry,\n type FragmentRenderer as SharedRenderer,\n} from '@adapters/shared/fragment-endpoint';\n\nexport type { FragmentRenderInput } from '@adapters/shared/fragment-endpoint';\n\n/** An Astro component as `import Hero from './Hero.astro'` yields it. */\nexport type AstroComponentLike = object;\n\nexport type FragmentRegistryEntry<Props extends object = object> = SharedRegistryEntry<\n AstroComponentLike,\n Props\n>;\n/** @internal */\nexport type FragmentRegistry = SharedRegistry<AstroComponentLike>;\n/** @internal */\nexport type FragmentRenderer = SharedRenderer<AstroComponentLike>;\nexport type FragmentEndpointOptions = SharedOptions<AstroComponentLike>;\n\nconst RENDERER_NAME = 'astro-container';\n\ninterface ContainerLike {\n renderToString: (\n component: AstroComponentLike,\n options: { props: Record<string, unknown> },\n ) => Promise<string>;\n}\n\n/** One container per process; see `lazyPeer` for what a failed start does. */\nconst loadContainer = lazyPeer(async (): Promise<ContainerLike> => {\n // Through a variable so the bundler leaves it as a runtime import: `astro` is\n // an optional peer, and a project without it must still be able to install\n // this package.\n const specifier = 'astro/container';\n try {\n const astro = (await import(/* @vite-ignore */ specifier)) as {\n experimental_AstroContainer: { create: () => Promise<unknown> };\n };\n return (await astro.experimental_AstroContainer.create()) as ContainerLike;\n } catch (cause) {\n throw missingPeerError(['astro'], cause);\n }\n});\n\nconst renderWithContainer: FragmentRenderer = async (component, props) => {\n const container = await loadContainer();\n return container.renderToString(component, { props });\n};\n\n/** Build the endpoint; export it as the `POST` of a non-prerendered Astro API route. */\nexport function createFragmentEndpoint(\n options: FragmentEndpointOptions,\n): (context: { readonly request: Request }) => Promise<Response> {\n const handler = createFragmentEndpointHandler(options, {\n render: renderWithContainer,\n rendererName: RENDERER_NAME,\n });\n return ({ request }) => handler(request);\n}\n","/**\n * An optional peer dependency, imported the first time it is actually needed.\n *\n * Every fragment binding renders with a component system this package does not\n * install: `astro`, `react`/`react-dom`, `svelte`, `vue`. A project that never\n * registers a fragment — most of them — must still be able to install and run\n * this package, so the import happens at the first render rather than at module\n * load, and always through a variable specifier so a bundler leaves it alone.\n */\n\n/**\n * `load` runs once per process. Callers arriving while it is in flight share\n * that promise; a rejected one is forgotten rather than kept, so a project that\n * installs the package after the first request is not answered from the first\n * bad start for the rest of the process's life.\n */\nexport function lazyPeer<T>(load: () => Promise<T>): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n if (pending === undefined) {\n const started = load();\n pending = started;\n started.catch(() => {\n if (pending === started) pending = undefined;\n });\n }\n return pending;\n };\n}\n\n/**\n * The error a binding throws when its renderer's packages are not installed.\n * The endpoint answers 500 either way; this is what the server log says, and\n * without it the cause reads as \"render failed\".\n */\nexport function missingPeerError(packages: readonly string[], cause: unknown): Error {\n const names = packages.map((name) => `\\`${name}\\``).join(' and ');\n const one = packages.length === 1;\n return new Error(\n `payload-live-preview: this fragment endpoint renders with ${names}, ` +\n `${one ? 'an optional peer' : 'optional peers'} this package does not install. ` +\n `${one ? 'Install it' : 'Install them'}, or pass your own \\`render\\`.`,\n { cause },\n );\n}\n"],"mappings":"AAgBO,SAASA,EAAyBC,GAKvC,GAAyB,OAArBA,EAAQC,UACsB,MAA7BD,EAAQE,WAAa,KAAoC,MAAtBF,EAAQG,WAChD,MAAM,IAAIC,MACR,+OAIJ,CCcO,IAAMC,EAA8CC,OAAOC,OAAO,CACvEC,QAAQ,EACRC,eAAgBH,OAAOC,OAAO,CAAC,YAGpBG,EAA8CJ,OAAOC,OAAO,CACvEI,0BAA0B,EAC1BC,kBAAmB,mBACnBC,eAAe,EACfC,gBAAiB,WAINC,EAA8CT,OAAOC,OAAO,CACvEC,QAAQ,EACRC,eAAgBH,OAAOC,OAAO,CAAC,QAAS,aAAc,cAG3CS,EAA8CV,OAAOC,OAAO,CACvEI,0BAA0B,EAC1BC,kBAAmB,MACnBC,eAAe,EACfC,gBAAiB,WC9DNG,iBAAyC,CAAC,m8BAA29B,6tDAAqvD,+kMAAywM,k8BAAw8B,unUAA6uU,8mNAA8rN,8sXAA8/X,ihhDAAy/jD,kzUAAg5U,6MAAmN,qFAA2F,01VAA8vW,8BAAgC,o6FAAo9FC,KAAK,ICDlyjHC,iBAAkC,CAAC,+gQAAiqQ,q1GAAi7GD,KAAK,ICA1nXE,iBAA+B,CAAC,mmHAAqoH,k7FAA0gGF,KAAK,ICAprNG,iBAAwC,CAAC,yCAA2C,sGAAwG,0SAAkTH,KAAK,ICAnfI,iBAAA,CAA+C,yCAA2C,sGAAwG,wHAA4H,kxBAA0xBJ,KAAK,ICgI7lCK,EAAqB,CAChC,iBACA,YACA,WACA,aACA,QACA,aACA,aACA,cACA,wBACA,0BACA,yBACA,2BACA,2BACA,uBACA,gBACA,oBACA,kBACA,mBACA,oBACA,gBACA,kBACA,oBACA,WACA,YACA,YC1IF,SAASC,EAAYC,E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