payload-live-preview 1.8.0 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +301 -93
  2. package/dist/adapters/astro/PreviewBoundary.astro +66 -0
  3. package/dist/adapters/astro/RichText.astro +6 -0
  4. package/dist/adapters/astro/index.d.ts +165 -134
  5. package/dist/adapters/astro/index.js +1 -1
  6. package/dist/adapters/astro/index.js.map +1 -1
  7. package/dist/adapters/astro/middleware-entry.d.ts +4 -9
  8. package/dist/adapters/astro/middleware-entry.js +1 -1
  9. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  10. package/dist/adapters/nextjs/index.d.ts +13 -80
  11. package/dist/adapters/nextjs/index.js +1 -1
  12. package/dist/adapters/nextjs/index.js.map +1 -1
  13. package/dist/adapters/nuxt/index.d.ts +46 -106
  14. package/dist/adapters/nuxt/index.js +1 -1
  15. package/dist/adapters/nuxt/index.js.map +1 -1
  16. package/dist/adapters/sveltekit/index.d.ts +10 -75
  17. package/dist/adapters/sveltekit/index.js +1 -1
  18. package/dist/adapters/sveltekit/index.js.map +1 -1
  19. package/dist/client.cjs +2 -0
  20. package/dist/client.cjs.map +1 -0
  21. package/dist/client.d.cts +747 -0
  22. package/dist/client.d.ts +747 -0
  23. package/dist/client.js +2 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/codegen-astro.d.ts +5 -27
  26. package/dist/codegen-astro.js +1 -1
  27. package/dist/codegen-astro.js.map +1 -1
  28. package/dist/codegen-cli.d.ts +3 -16
  29. package/dist/codegen-cli.js +1 -1
  30. package/dist/codegen-cli.js.map +1 -1
  31. package/dist/codegen.cjs +1 -1
  32. package/dist/codegen.cjs.map +1 -1
  33. package/dist/codegen.d.cts +37 -124
  34. package/dist/codegen.d.ts +37 -124
  35. package/dist/codegen.js +1 -1
  36. package/dist/codegen.js.map +1 -1
  37. package/dist/core.cjs +1 -1
  38. package/dist/core.cjs.map +1 -1
  39. package/dist/core.d.cts +647 -1100
  40. package/dist/core.d.ts +647 -1100
  41. package/dist/core.js +1 -1
  42. package/dist/core.js.map +1 -1
  43. package/dist/doctor-cli.d.ts +3 -28
  44. package/dist/doctor-cli.js +1 -1
  45. package/dist/doctor-cli.js.map +1 -1
  46. package/dist/doctor.d.ts +16 -32
  47. package/dist/doctor.js +1 -1
  48. package/dist/doctor.js.map +1 -1
  49. package/dist/fragment.cjs +2 -0
  50. package/dist/fragment.cjs.map +1 -0
  51. package/dist/fragment.d.cts +333 -0
  52. package/dist/fragment.d.ts +333 -0
  53. package/dist/fragment.js +2 -0
  54. package/dist/fragment.js.map +1 -0
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +885 -1531
  58. package/dist/index.d.ts +885 -1531
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/lexical.cjs +2 -0
  62. package/dist/lexical.cjs.map +1 -0
  63. package/dist/lexical.d.cts +90 -0
  64. package/dist/lexical.d.ts +90 -0
  65. package/dist/lexical.js +2 -0
  66. package/dist/lexical.js.map +1 -0
  67. package/dist/middleware-CEPsY1P7.d.ts +40 -0
  68. package/dist/migrate.d.ts +73 -0
  69. package/dist/migrate.js +2 -0
  70. package/dist/migrate.js.map +1 -0
  71. package/dist/options-CEzzfHJu.d.ts +197 -0
  72. package/dist/payload.cjs +1 -1
  73. package/dist/payload.cjs.map +1 -1
  74. package/dist/payload.d.cts +11 -80
  75. package/dist/payload.d.ts +11 -80
  76. package/dist/payload.js +1 -1
  77. package/dist/payload.js.map +1 -1
  78. package/dist/plugins.cjs +2 -0
  79. package/dist/plugins.cjs.map +1 -0
  80. package/dist/plugins.d.cts +509 -0
  81. package/dist/plugins.d.ts +509 -0
  82. package/dist/plugins.js +2 -0
  83. package/dist/plugins.js.map +1 -0
  84. package/dist/{probe-tMHdim5y.d.ts → probe-CYtvj_Lm.d.ts} +43 -77
  85. package/dist/server.cjs +2 -0
  86. package/dist/server.cjs.map +1 -0
  87. package/dist/server.d.cts +435 -0
  88. package/dist/server.d.ts +435 -0
  89. package/dist/server.js +2 -0
  90. package/dist/server.js.map +1 -0
  91. package/dist/structural.cjs +3 -0
  92. package/dist/structural.cjs.map +1 -0
  93. package/dist/structural.d.cts +243 -0
  94. package/dist/structural.d.ts +243 -0
  95. package/dist/structural.js +3 -0
  96. package/dist/structural.js.map +1 -0
  97. package/package.json +86 -7
  98. package/dist/middleware-DD4Hwomt.d.ts +0 -189
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["detectInitialLocale","document","lang","documentElement","getAttribute","length","readHtmlLang","navigator","language","readNavigatorLanguage","ELEMENT_ID","documentLeases","WeakMap","clearLeaseMessage","lease","timer","clearTimeout","messageNode","remove","A11yAnnouncer","german","constructor","locale","targetDocument","activeDocument","documentLocale","this","test","isGerman","mount","body","get","element","owned","refs","set","acquireDocumentLease","leased","isConnected","ownerDocument","getElementById","createElement","id","setAttribute","appendChild","announceConnected","say","announceDisconnected","announceUpdate","count","String","detach","delete","message","parentNode","createTextNode","hasChildNodes","data","previousSibling","setTimeout","parseFieldSchema","raw","Array","isArray","out","entry","parsed","parseFieldEntry","push","value","record","name","type","fields","blocks","slug","parseBlockSchema","result","STRUCTURAL_TYPES","Set","buildSchemaIndex","schemas","basePath","Map","walk","schema","has","path","block","getId","item","getBlockType","blockType","diffArray","prev","next","every","patches","prevIndexById","i","consumedFromPrev","to","kind","index","from","add","prevItem","shallowEqual","oldValue","diffById","min","Math","diffByPosition","a","b","Object","is","aRec","bRec","aKeys","keys","bKeys","key","MAP","text","textarea","richText","email","number","checkbox","date","select","radio","array","group","tabs","row","collapsible","relationship","upload","point","json","code","ui","SAFE_PROTOCOLS","DANGEROUS_PROTOCOL_PATTERN","RELATIVE_PATH","PROTOCOL_RELATIVE","PARSER_IGNORED","isSafeUrl","url","trimmed","trim","replace","startsWith","URL","protocol","isExternalHttpUrl","BLOCKED_ATTRIBUTES","URL_ATTRIBUTES","noWriteCallbacks","WeakSet","markNoWriteCallback","callback","valueIdentity","JSON","stringify","FieldChangeTracker","previous","diff","dependencies","changed","entries","identity","invalidated","source","dependents","dependent","reset","CAPABILITY_DECLARATIONS","basic","since","observed","PROTOCOL_CAPABILITIES","negotiateProtocol","theirs","sanitisedTheirs","Number","isFinite","floor","effectiveTheirs","negotiated","seen","capabilities","capability","ours","ProtocolTracker","negotiation","observe","log","fresh","filter","join","applyVersion","remoteVersion","current","prefersReducedMotion","win","matchMedia","matches","FieldRevealer","lastField","reveal","fieldName","rect","getBoundingClientRect","vertically","bottom","top","innerHeight","horizontally","right","left","innerWidth","isInViewport","scrollIntoView","behavior","revealElement","sameRevision","generation","revision","RuntimeState","started","suspended","deferredStart","activeUpdate","schemaIndex","updateCount","supersededCount","completedCount","skippedUnchangedCount","lastFlush","absentFields","warnedOrphanFields","warnedStrategy","warnedUnattributableMessage","warnedVisibilityGate","warnedFragmentFallback","lastAppliedIdentity","seenFieldIdentity","fragmentStats","rendered","failed","superseded","routeStats","refreshes","loopStopped","fragmentController","routeController","readyTimers","revealer","changes","isRunning","isCurrent","transaction","complete","completed","abortStrategies","controller","abort","BindingWriter","deps","state","apply","update","target","schemaEntry","fieldPath","wildcardPath","lookupSchema","renderer","schemaType","explicitFieldType","fieldType","mapped","prototype","hasOwnProperty","call","payloadTypeToRenderer","resolveFieldType","root","children","looksLikeLexicalRoot","resolveRenderer","error","fail","emitElementUpdate","emitter","listenerCount","tagName","src","textContent","context","allFields","renderRichText","boundary","toggleAttribute","isEmptyFieldValue","targetAttribute","attribute","toLowerCase","removeAttribute","stringValue","applyAttributeBinding","warn","outcome","render","invokeRenderer","rendererUsesNoWriteOutcome","emitWhile","previousValue","nextValue","receivedAt","applied","cause","Error","mergeDependencyMaps","maps","merged","map","bucket","dependencyMapFromBinding","dependsOn","ISLAND_ATTRIBUTE","ISLAND_SELECTOR","isIslandRoot","hasAttribute","islandAllowsPatching","island","enclosingFragment","closest","resolveStrategy","explicit","FIELD_ATTRIBUTE","TYPE_ATTRIBUTE","TARGET_ATTRIBUTE_ATTRIBUTE","HREF_ATTRIBUTE","SRC_ATTRIBUTE","ALT_ATTRIBUTE","ARRAY_TEMPLATE_ATTRIBUTE","ARRAY_SEPARATOR_ATTRIBUTE","LOCALE_ATTRIBUTE","RICH_TEXT_ATTRIBUTE","HTML_ATTRIBUTE","ARRAY_ATTRIBUTE","STRUCTURAL_ATTRIBUTE","OWNER_ATTRIBUTE","DEPENDS_ATTRIBUTE","STRATEGY_ATTRIBUTE","BOUNDARY_ATTRIBUTE","BINDING_ATTRIBUTES","FIELD_SELECTOR","OWNER_SELECTOR","CUSTOM_RENDERER_KEY","VALID_FIELD_TYPES","isRendererKey","ElementCache","entriesByField","entryByElement","islandRoots","options","alwaysTrue","dependencyMap","binding","values","islands","buildFromRoot","t0","performance","now","clear","elementCount","querySelectorAll","collectIslands","fieldCount","size","durationMs","resolveBinding","replaceEntry","removeEntry","append","getByElement","indexOf","splice","hrefField","srcField","altField","arrayTemplate","arraySeparator","owner","resolveBindingOwner","names","split","parseDependencyList","strategy","fragmentBoundary","strategyKind","inputType","observeThenableResult","then","Promise","resolve","catch","isolateDiagnostic","diagnostic","args","noopDiagnostic","safeConsoleError","console","safeConsoleWarn","safeConsoleDebug","debug","hasControlCharacter","character","codePoint","codePointAt","isSafeSlug","includes","encodeURIComponent","DataMerger","serverURL","apiRoute","depth","fetchFn","inflight","attempt","destroyDepth","route","canMerge","request","globalSlug","collectionSlug","isSafeId","merge","status","fetch","AbortController","endpoint","response","method","credentials","headers","flattenLocales","signal","isAborted","ok","doc","destroy","aborted","VERSION","PAYLOAD_2","fieldTyping","populatesRelationships","documentEvents","PAYLOAD_3","UNKNOWN","detectProtocolProfile","optionalFieldOk","check","optionalTypeOk","isPlainObject","getPrototypeOf","NULL_AS_ABSENT_FIELDS","MessageBus","matcher","handlers","boundListener","attachedTarget","queue","queueHead","attach","window","committed","listener","event","receive","origin","reportInvalid","resetQueue","addEventListener","removeEventListener","advanceGeneration","sendReady","targets","origins","payload","ready","protocolVersion","postMessage","isCurrentGeneration","matchesOrigin","matchesSource","v","x","isLivePreviewMessage","dispatchUpdate","normalized","field","Reflect","deleteProperty","fieldSchemaJSON","normalizeLivePreviewMessage","isDocumentEventMessage","invokeHandler","onDocumentEvent","focusFieldOf","onFocusField","hasUpdateData","messageRevision","validator","validateToken","commitUpdate","pending","settled","approved","verdict","previewToken","settleValidation","drainQueue","dequeue","onUpdate","reason","onInvalid","sourcePolicy","parent","opener","handler","expected","slice","ObserverManager","callbacks","debounceMs","rootMargin","visible","mutation","intersection","debounceTimer","mutationDebounceMs","intersectionRootMargin","start","previousGeneration","stop","MutationObserver","mutations","handleMutations","IntersectionObserver","handleIntersection","threshold","childList","subtree","attributes","attributeFilter","disconnect","observeElement","unobserveElement","unobserve","markVisible","isVisible","m","attributeName","nodeType","node","addedNodes","containsTrackedElement","removedNodes","hasStructuralImpact","onStructuralChange","isIntersecting","onVisibilityChange","querySelector","HeartbeatTimer","timeoutMs","onTimeout","handle","lastKick","kick","Date","lastKickAt","ConnectionState","markConnected","transition","markDisconnected","collectionOwnerKey","documentId","nonEmpty","isBindingInScope","readDocumentId","BLOCKED_KEYS","resolveFieldValue","preferLocale","localized","readOwn","direct","resolved","segment","object","autoPolicy","SYSTEM_FIELD_NAMES","hasAddressableBinding","cache","ownerKeys","bindings","some","localisedBindingNames","isBindableScalar","stripLocaleSuffix","suffix","endsWith","trustedHtml","html","policy","api","candidate","globalThis","trustedTypes","createPolicy","factory","createHTML","input","resolvePolicy","STATE_ATTRIBUTES","keyOf","keyAttributes","isMorphBoundary","editable","morphElement","live","namespaceURI","isMorphCompatible","focus","active","activeElement","HTMLElement","contains","selection","HTMLInputElement","HTMLTextAreaElement","selectionStart","selectionEnd","captureFocus","syncAttributes","retainChildrenOf","liveKeyed","keyed","duplicate","child","onDuplicateKey","indexKeyed","keyedElements","liveUnkeyed","childNodes","claimed","usedKeys","renderedNodes","cursor","firstChild","unkeyedIndex","kept","Element","reconcile","replaceWith","nextSibling","sameKind","replaceChild","following","isBlankText","insertBefore","morphChildren","snapshot","preventScroll","end","setSelectionRange","restoreFocus","nodeValue","Node","TEXT_NODE","ALLOWED_TAGS","FORM_CONTROLS","REMOVE_COMPLETELY","ATTR_GLOBAL","ATTR_ARIA_PREFIX","ATTR_DATA_PREFIX","ATTR_BY_TAG","img","picture","audio","video","time","abbr","q","blockquote","table","th","td","col","colgroup","ol","li","pre","SanitizerEnvironmentError","TEMPLATE_ATTRIBUTES","defaultMode","sanitizeHtml","resolveDocument","__INLINE_BUILD__","attrMap","tag","attrs","allowedTags","attrByTag","allowFormControls","templateMode","mode","allowedData","allowed","additionalAllowedTags","additionalAllowedAttributes","existing","attr","allowedDataAttributes","template","innerHTML","sanitizeFragment","content","sanitizeElement","tagAttrs","isSafeSrcset","sanitizeAttributes","anchor","href","hardenAnchor","descriptorStart","search","HTML_ESCAPES","freeze","HTML_ESCAPE_PATTERN","escapeHtml","char","ATTR_ESCAPES","ATTR_ESCAPE_PATTERN","escapeHtmlAttribute","PLACEHOLDER_PATTERN","interpolateArrayTemplate","placeholder","hasOwn","safeStringify","isEmptyValue","TEMPLATE_EXTRA_TAGS","TEMPLATE_EXTRA_ATTRIBUTES","CUSTOM_TAG_PATTERN","optionsByTemplate","templateSanitizeOptions","cached","tags","match","matchAll","KEY_ATTRIBUTE","NESTED_KEY_ATTRIBUTE","NESTED_TEMPLATE_ATTRIBUTE","applyStructuralPatches","container","nextItems","store","forceRender","plan","prepareStructuralPlan","commitStructuralPlan","morph","isManagedNestedSlot","_live","memory","initialChildren","keyedChildren","indexByAttribute","reserved","readKey","takeIndexedElement","replaces","renders","renderItem","nestedSlots","prepareNestedSlots","prepareReconciliation","patch","createPatchPlan","mutated","retained","liveSlot","renderedSlot","synchronizeAttributes","before","getMemory","rememberItem","oldItem","newItem","oldSlotsByKey","findDirectNestedSlots","itemKey","prevValue","plans","newSlot","oldSlot","nextTemplate","previousTemplate","nextNested","readNestedArray","resolvedNext","templateChanged","slot","ancestor","parentElement","nested","elements","indexed","pop","safe","host","first","firstElementChild","StrategyRunner","planFragments","touched","strategies","fragment","boundaries","covered","covers","hasRouteBinding","runFragments","detail","cloneNode","morphFragment","patchFallback","pendingFragments","report","scheduler","pendingCount","revealPending","updatedCount","refreshRoute","stats","routeRefreshed","refresh","rebuildCache","reapply","warnFragmentFallback","warnUnsupportedStrategy","schedule","transform","UpdatePipeline","scheduleAllFields","transformForBinding","handleUpdate","heartbeat","externallyUpdatedRelationship","observeCapabilities","relationshipEdited","emit","timestamp","revealTarget","revealIdentities","cancelled","acceptRevision","connection","a11y","processUpdate","resolveIncomingFields","cancel","cancelRevision","merger","ownerKeysForUpdate","trackIdentity","skipUnchanged","scheduled","revealEditedField","noteRevealCandidate","rawValue","transformed","bindingIdentity","last","warned","ownsAnyBinding","localisedNames","rawName","baseName","diagnoseOrphanFields","scopeBindingsByOwner","collectionKey","messageOwnerKeys","originalValue","transformValue","returnedThenable","TypeError","err","onFlush","deferred","dispatchEvent","CustomEvent","bubbles","dispatchIslandUpdate","revealBinding","revealField","defaultView","own","siblings","combined","sibling","UpdateScheduler","maxWaitMs","gateThresholdValue","gateDisabled","getCacheSize","scheduleFrame","cancelFrame","replay","activeFlushes","debounceToken","deadlineTimer","frameHandle","frameToken","activeIdentity","activeRevisionCancelled","visibilityGateThreshold","disableVisibilityGate","requestAnimationFrame","bind","cancelAnimationFrame","sameIdentity","armDebounce","cancelScheduledWork","clearWork","flushNow","flush","notifyVisible","didApply","statsFor","retarget","retargetBuffer","forget","replayCount","gateThreshold","gateActive","token","requestFrame","clearDeadline","appliedFields","batchEntry","buffer","READY_RETRY_DELAYS_MS","LivePreviewRuntime","pipeline","writer","rootSentinel","observedRoot","renderers","isInsideIsland","observers","bus","originMatcher","eventSourcePolicy","dataMerge","heartbeatMs","onHeartbeatTimeout","readyTargets","defaultSendReady","createA11y","lockedOrigin","isDocumentRoot","readyState","onReady","startNow","rollbackFailedStart","reportError","once","observerRoot","readDocumentBody","watchRootReplacement","buildCacheAndObserve","delay","sendReadyAfterStart","suspend","wasConnected","release","runCleanup","cleanup","refreshCache","followReplacedRoot","inspect","fieldNames","owners","version","trusted","locked","sort","profile","revisions","accepted","skippedUnchanged","orphanFields","ownerScoped","fragments","inFlight","visibilityGateActive","plugins","buildInspection","removed","isIdleDisconnected","enableA11y","a11yLocale","Window","EventEmitter","regular","on","register","off","emitSequential","shouldContinue","eligible","invoke","removeAllListeners","eventNames","label","isInIframe","self","isDevMode","nodeEnv","process","env","readNodeEnv","location","hostname","LOCALHOST_PATTERN","VALID_ORIGIN_PATTERN","LOCALHOST_HANDSHAKE_PORTS","OriginDetector","additionalOrigins","normalised","normaliseOrigin","referrerOrigin","enableReferrerDetection","referrer","allowLocalhost","enableLocalhostMatching","forceDevMode","lockOrigin","unlockOrigin","enumerate","port","referrerWasAvailable","isProductionUnconfigured","isReferrerOnlyTrust","noopDisposer","ResourceScope","pluginName","resources","assertOpen","track","acquire","finalize","disposed","stage","resource","dispose","activate","counts","subscription","commit","close","reverse","ScopedPluginEvents","events","scope","subscriptions","subscribe","untypedHandler","callerEligible","find","subscriptionActive","wrapped","async","PluginManager","config","registerRenderer","onTransformError","initializing","teardowns","destroying","transforms","mutationQueue","queuedHooks","registerFieldRenderer","plugin","registerNow","enqueue","unregister","unregisterNow","destroyAll","destroyAllNow","applyTransforms","registrations","registration","list","describe","cleanups","queued","incompatibility","compat","runtimeVersion","runtime","range","exec","parseVersion","alternative","comparators","part","comparator","operator","order","delta","compare","satisfiesComparator","satisfiesRange","isInteger","incompatibilityOf","refuse","createContext","runHook","init","registerTransform","registerCleanup","getConfig","existingTeardown","holdQueue","teardown","destroyPlugin","hook","operation","RendererRegistry","base","layers","layer","stack","wasTop","previousLayer","at","previousRenderer","ALIGNMENT_NUMERIC","ALIGNMENT_STRING","resolveAlignment","fmt","format","resolveIndent","indent","dirAttribute","direction","layoutClassAttribute","align","classes","VALID_TAGS","asRecord","readMedia","sanitizeIdent","pickRelationLabel","title","BLANK_TARGET","linkRenderer","ctx","renderChildren","internalUrl","resolveUrl","titleAttr","extractText","dimensionAttributes","width","height","typeAttribute","mimeType","registry","lookupBlockRenderer","renderBlockNode","baseClass","custom","spanAttribute","BUILTIN_NODE_RENDERERS","paragraph","heading","tagRaw","listType","startAttr","checkAttr","listitem","valueAttr","link","autolink","quote","linebreak","horizontalrule","tab","mime","renderVideo","renderAudio","alt","renderImage","filename","renderFallbackLink","relationTo","classAttr","inlineBlock","tablerow","tablecell","header","RENDER_CONTEXT","warnedNoSanitizer","isLexicalContent","renderNode","extractPlainText","createTextRenderer","warnedElements","toPlainString","hasForeignChildren","warnOnce","escapeAndLinebreak","richTextRenderer","sanitize","warnNoSanitizerOnce","lexicalToHtml","htmlRenderer","acceptUrl","createLinkRenderer","toHref","urlRenderer","HAS_SCHEME","emailRenderer","IMAGE_SOURCE_ATTRIBUTES","clearImage","writeImage","media","srcset","sizes","candidates","srcsetUrl","buildSrcset","imageRenderer","pickSource","pickAlt","style","backgroundImage","escapeCssUrl","uploadRenderer","relationshipRenderer","selectRenderer","toValues","checked","option","labelFor","multiple","selected","writeSelect","FALSE_STRINGS","checkboxRenderer","toBoolean","NUMBER_CACHE","DATE_CACHE","buildKey","localePart","serialised","stableStringify","parts","inner","trimToLimit","oldest","dateRenderer","valid","isNaN","getTime","fallback","toISOString","formatter","Intl","DateTimeFormat","getDateTimeFormat","dateStyle","timeStyle","formatDate","day","getFullYear","padStart","pad","getMonth","getDate","clock","getHours","getMinutes","formatForInput","numberRenderer","num","NumberFormat","getNumberFormat","arrayRenderer","items","renderTemplate","createStructuralArrayRenderer","states","warnedContainers","warnedKeys","warnMissingTemplate","previousState","domSnapshot","readDomKeySnapshot","position","__payloadDomPosition","sameDomKeySnapshot","needsForcedRender","nextKeys","warnDuplicateKey","previousKeys","stable","warnAboutKeys","codes","builtinRenderers","definedOnly","V2_RUNTIME_DEFAULTS","disableReferrerDetection","sanitizerPolicy","V1_RUNTIME_DEFAULTS","invert","LivePreviewClient","detector","rendererRegistry","destroyed","tornDown","destroyPromise","rawConfig","defaults","rows","withProfileDefaults","mergeDepth","allowedOrigins","disableLocalhostMatching","stateless","buildBuiltinRenderers","mergeFetch","e","autoStart","isInPreviewContext","isInPopup","resume","resolveDestroy","rejectDestroy","reject","finish","finally","use","unuse","initLivePreview","client","reportPreviewFocus","targetOrigin","createPreviewFocusReporter","resolveTarget","DIAGNOSTIC_CODES","NoTrustedOrigin","ReferrerOnlyTrust","PluginIncompatible","OrphanField","UnattributableUpdate","VisibilityGateDeferred","UnsafeAttributeWrite","TextTargetHasChildren","MissingArrayTemplate","StructuralItemUnkeyed","StructuralDuplicateKey","StructuralUnstableKeys","UnsupportedStrategy","MessageRejected","TokenRejected","HandlerThrew","TransformThrew","RendererThrew","StartupFailed","ReadyFailed","AuditRuntimeMissing","AuditNoFrameAncestors","AuditFrameOptionsBlocks","AuditBindingsExposed","AuditGateThresholdExceeded","AuditUnownedBindings","AuditNoBindings","AuditNotAPage","FragmentRequestFailed","FragmentResponseInvalid","FragmentUnauthorized","FragmentSuperseded","RouteRefreshLoop","FragmentStrategyUnavailable","V2ReadinessGap","RuntimeOnPublicPage"],"sources":["../src/detection/locale.ts","../src/core/a11y.ts","../src/schema/parser.ts","../src/schema/walker.ts","../src/schema/diff.ts","../src/schema/field-type-map.ts","../src/security/url-validator.ts","../src/core/attribute-binding.ts","../src/core/internal-outcome.ts","../src/core/value-identity.ts","../src/core/field-changes.ts","../src/core/protocol-version.ts","../src/core/protocol-tracker.ts","../src/core/reveal.ts","../src/core/runtime-state.ts","../src/core/binding-writer.ts","../src/core/dependencies.ts","../src/core/islands.ts","../src/core/strategies.ts","../src/core/cache.ts","../src/core/thenable.ts","../src/core/diagnostics.ts","../src/core/data-merger.ts","../package.json","../src/version.ts","../src/core/protocol-profile.ts","../src/core/message-guards.ts","../src/core/message-bus.ts","../src/core/observers.ts","../src/core/state.ts","../src/core/binding-owner.ts","../src/core/field-value.ts","../src/core/orphan-diagnostics.ts","../src/security/trusted-types.ts","../src/core/morph.ts","../src/security/sanitizer.ts","../src/security/escape.ts","../src/core/array-template.ts","../src/field-types/utils.ts","../src/core/template-sanitize.ts","../src/core/structural-applier.ts","../src/core/strategy-runner.ts","../src/core/update-pipeline.ts","../src/core/update-scheduler.ts","../src/core/lifecycle.ts","../src/core/inspection/snapshot.ts","../src/events/emitter.ts","../src/detection/environment.ts","../src/detection/origin.ts","../src/plugins/resource-scope.ts","../src/plugins/scoped-events.ts","../src/plugins/manager.ts","../src/plugins/compat.ts","../src/plugins/renderer-registry.ts","../src/lexical/utils.ts","../src/lexical/nodes/paragraph.ts","../src/lexical/nodes/heading.ts","../src/lexical/value-shapes.ts","../src/lexical/nodes/link.ts","../src/lexical/nodes/code.ts","../src/lexical/nodes/upload.ts","../src/lexical/nodes/relationship.ts","../src/lexical/blocks/registry.ts","../src/lexical/nodes/block.ts","../src/lexical/nodes/table.ts","../src/lexical/nodes/builtin.ts","../src/lexical/nodes/text.ts","../src/lexical/types.ts","../src/lexical/nodes/list.ts","../src/lexical/nodes/quote.ts","../src/lexical/nodes/linebreak.ts","../src/lexical/registry.ts","../src/lexical/render.ts","../src/field-types/text.ts","../src/field-types/rich-text.ts","../src/field-types/html.ts","../src/field-types/unsafe-url.ts","../src/field-types/url.ts","../src/field-types/email.ts","../src/field-types/media.ts","../src/field-types/image.ts","../src/field-types/upload.ts","../src/field-types/relationship.ts","../src/field-types/select.ts","../src/field-types/checkbox.ts","../src/core/intl-cache.ts","../src/field-types/date.ts","../src/field-types/number.ts","../src/field-types/array.ts","../src/field-types/structural-array.ts","../src/field-types/registry.ts","../src/types/defined-only.ts","../src/core/defaults-profile.ts","../src/client/index.ts","../src/client/config.ts","../src/field-types/index.ts","../src/client/preview-focus.ts","../src/core/diagnostic-codes.ts"],"sourcesContent":["/** The locale for `Intl` renders before Payload names one: `<html lang>`, then `navigator.language`, then `'en'`. */\n\nconst FALLBACK_LOCALE = 'en';\n\nexport function detectInitialLocale(): string {\n return readHtmlLang() ?? readNavigatorLanguage() ?? FALLBACK_LOCALE;\n}\n\nfunction readHtmlLang(): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const lang = document.documentElement.getAttribute('lang');\n return lang === null || lang.length === 0 ? undefined : lang;\n}\n\nfunction readNavigatorLanguage(): string | undefined {\n if (typeof navigator === 'undefined') return undefined;\n const lang = navigator.language;\n return typeof lang === 'string' && lang.length > 0 ? lang : undefined;\n}\n","/**\n * One polite `aria-live` region per document, leased by every announcer on\n * the page, for connect / update / disconnect announcements. The message\n * clears itself after a moment so a repeated string is heard again.\n */\n\nimport { detectInitialLocale } from '@detection/locale';\n\nconst ELEMENT_ID = 'payload-live-preview-a11y';\nconst CLEAR_DELAY_MS = 1500;\nconst STYLE =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;' +\n 'clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0';\n\nfunction isGerman(locale: string): boolean {\n return /^de(?:[-_]|$)/i.test(locale);\n}\n\n/** Shared per document; reference-counted so one client cannot remove another's region. */\ninterface DocumentLease {\n element: HTMLElement | null;\n /** Created by this package (removable) rather than adopted from the page. */\n owned: boolean;\n messageNode: Text | null;\n refs: number;\n timer: ReturnType<typeof setTimeout> | null;\n}\n\nconst documentLeases = new WeakMap<Document, DocumentLease>();\n\nfunction acquireDocumentLease(activeDocument: Document): DocumentLease {\n let lease = documentLeases.get(activeDocument);\n if (lease === undefined) {\n lease = { element: null, owned: false, messageNode: null, refs: 0, timer: null };\n documentLeases.set(activeDocument, lease);\n }\n lease.refs += 1;\n return lease;\n}\n\n/** Remove only the package-owned message node, never consumer children. */\nfunction clearLeaseMessage(lease: DocumentLease): void {\n if (lease.timer !== null) {\n clearTimeout(lease.timer);\n lease.timer = null;\n }\n lease.messageNode?.remove();\n lease.messageNode = null;\n}\n\nexport class A11yAnnouncer {\n private readonly german: boolean;\n private readonly document: Document | null;\n private lease: DocumentLease | null = null;\n\n constructor(locale?: string, targetDocument?: Document | null) {\n const activeDocument = targetDocument ?? (typeof document === 'undefined' ? null : document);\n const documentLocale = activeDocument?.documentElement.getAttribute('lang') ?? '';\n this.german = isGerman(\n locale ?? (documentLocale.length > 0 ? documentLocale : detectInitialLocale()),\n );\n this.document = activeDocument;\n // The region mounts on the first announcement: a <head> inline script runs before `body` exists.\n }\n\n /** The shared region, or `null` without a body yet (announcements are then dropped). */\n private mount(): HTMLElement | null {\n const activeDocument = this.document;\n if (activeDocument?.body == null) return null;\n this.lease ??= acquireDocumentLease(activeDocument);\n const lease = this.lease;\n const leased = lease.element;\n if (leased?.isConnected && leased.ownerDocument === activeDocument) return leased;\n // The host removed or replaced the region between announcements.\n if (leased !== null) {\n const owned = lease.owned;\n clearLeaseMessage(lease);\n if (owned) leased.remove();\n }\n let element = activeDocument.getElementById(ELEMENT_ID);\n lease.owned = element === null;\n if (element === null) {\n element = activeDocument.createElement('div');\n element.id = ELEMENT_ID;\n element.setAttribute('role', 'status');\n element.setAttribute('aria-live', 'polite');\n element.setAttribute('aria-atomic', 'true');\n element.setAttribute('style', STYLE);\n activeDocument.body.appendChild(element);\n }\n lease.element = element;\n return element;\n }\n\n announceConnected(): void {\n this.say(this.german ? 'Vorschau verbunden' : 'Live preview connected');\n }\n\n announceDisconnected(): void {\n this.say(this.german ? 'Vorschau getrennt' : 'Live preview disconnected');\n }\n\n announceUpdate(count: number): void {\n if (count <= 0) return;\n this.say(\n this.german\n ? `${String(count)} ${count === 1 ? 'Änderung' : 'Änderungen'} angewendet`\n : `${String(count)} ${count === 1 ? 'change' : 'changes'} applied`,\n );\n }\n\n /** Release the lease; the last release removes an owned region but leaves an adopted one. Idempotent. */\n detach(): void {\n const lease = this.lease;\n const activeDocument = this.document;\n if (lease === null || activeDocument === null) return;\n this.lease = null;\n lease.refs -= 1;\n if (lease.refs > 0) return;\n const element = lease.element;\n if (element !== null) clearLeaseMessage(lease);\n if (lease.owned) element?.remove();\n lease.element = null;\n documentLeases.delete(activeDocument);\n }\n\n private say(message: string): void {\n const element = this.mount();\n const lease = this.lease;\n if (element === null || lease === null) return;\n let messageNode = lease.messageNode;\n if (messageNode?.parentNode !== element) {\n // A dedicated text node leaves consumer-owned children untouched.\n messageNode?.remove();\n messageNode = element.ownerDocument.createTextNode(\n element.hasChildNodes() ? ` ${message}` : message,\n );\n lease.messageNode = messageNode;\n element.appendChild(messageNode);\n } else {\n messageNode.data = messageNode.previousSibling === null ? message : ` ${message}`;\n }\n if (lease.timer !== null) clearTimeout(lease.timer);\n const timer = setTimeout(() => {\n if (lease.timer === timer && lease.element === element) clearLeaseMessage(lease);\n }, CLEAR_DELAY_MS);\n lease.timer = timer;\n }\n}\n","/**\n * Validates the `fieldSchemaJSON` the admin sends. Entries that fail\n * validation are dropped, never thrown: a Payload/runtime version mismatch\n * must not take the preview down.\n */\n\nimport type { PayloadBlockSchema, PayloadFieldSchema } from '@/types/payload-protocol';\n\nexport function parseFieldSchema(raw: unknown): readonly PayloadFieldSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadFieldSchema[] = [];\n for (const entry of raw) {\n const parsed = parseFieldEntry(entry);\n if (parsed) out.push(parsed);\n }\n return out;\n}\n\nfunction parseFieldEntry(value: unknown): PayloadFieldSchema | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n const name = record['name'];\n const type = record['type'];\n if (typeof name !== 'string' || name.length === 0) return undefined;\n if (typeof type !== 'string' || type.length === 0) return undefined;\n\n const fields = parseFieldSchema(record['fields']);\n const blocks = parseBlockSchema(record['blocks']);\n\n const result: Record<string, unknown> = { ...record, name, type };\n if (fields.length > 0) result['fields'] = fields;\n else delete result['fields'];\n if (blocks.length > 0) result['blocks'] = blocks;\n else delete result['blocks'];\n\n return result as unknown as PayloadFieldSchema;\n}\n\nfunction parseBlockSchema(raw: unknown): readonly PayloadBlockSchema[] {\n if (!Array.isArray(raw)) return [];\n const out: PayloadBlockSchema[] = [];\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const slug = record['slug'];\n if (typeof slug !== 'string' || slug.length === 0) continue;\n const fields = parseFieldSchema(record['fields']);\n out.push({ ...record, slug, fields });\n }\n return out;\n}\n","/**\n * Flattens a parsed field schema into dotted paths (`hero.title`,\n * `sections.*.heading`). Tabs, rows and collapsibles have no name and\n * dissolve into their inner fields.\n */\n\nimport type {\n PayloadBlockSchema,\n PayloadFieldSchema,\n PayloadFieldType,\n} from '@/types/payload-protocol';\n\nexport type SchemaIndex = ReadonlyMap<string, PayloadFieldSchema>;\n\nconst STRUCTURAL_TYPES: ReadonlySet<PayloadFieldType> = new Set<PayloadFieldType>([\n 'tabs',\n 'row',\n 'collapsible',\n]);\n\nexport function buildSchemaIndex(\n schemas: readonly PayloadFieldSchema[],\n basePath = '',\n): SchemaIndex {\n const out = new Map<string, PayloadFieldSchema>();\n walk(schemas, basePath, out);\n return out;\n}\n\nfunction walk(\n schemas: readonly PayloadFieldSchema[],\n basePath: string,\n out: Map<string, PayloadFieldSchema>,\n): void {\n for (const schema of schemas) {\n if (STRUCTURAL_TYPES.has(schema.type)) {\n if (schema.fields) walk(schema.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? schema.name : `${basePath}.${schema.name}`;\n out.set(path, schema);\n if (schema.type === 'group') {\n if (schema.fields) walk(schema.fields, path, out);\n } else if (schema.type === 'array' && schema.fields) {\n walk(schema.fields, `${path}.*`, out);\n } else if (schema.type === 'blocks' && schema.blocks) {\n for (const block of schema.blocks) {\n walk(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\n/** Schema for `fieldPath`; numeric segments are retried as `*` wildcards. */\nexport function lookupSchema(\n index: SchemaIndex,\n fieldPath: string,\n): PayloadFieldSchema | undefined {\n if (index.has(fieldPath)) return index.get(fieldPath);\n const wildcardPath = fieldPath.replace(/\\.\\d+(?=\\.|$)/g, '.*');\n if (index.has(wildcardPath)) return index.get(wildcardPath);\n return undefined;\n}\n\nexport function lookupBlockSchema(\n index: SchemaIndex,\n blocksFieldPath: string,\n blockType: string,\n): PayloadBlockSchema | undefined {\n const schema = lookupSchema(index, blocksFieldPath);\n if (!schema?.blocks) return undefined;\n return schema.blocks.find((b) => b.slug === blockType);\n}\n","/**\n * Structural diff for array and blocks fields. Items with an `id` are keyed\n * (moves are detected); without ids the diff is positional.\n */\n\nexport type ArrayPatch =\n | { readonly kind: 'insert'; readonly index: number; readonly value: unknown }\n | { readonly kind: 'remove'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'move';\n readonly from: number;\n readonly to: number;\n readonly value: unknown;\n }\n | { readonly kind: 'update'; readonly index: number; readonly value: unknown }\n | {\n readonly kind: 'replace';\n readonly index: number;\n readonly oldValue: unknown;\n readonly value: unknown;\n };\n\nfunction getId(item: unknown): string | number | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const id = (item as Record<string, unknown>)['id'];\n if (typeof id === 'string' || typeof id === 'number') return id;\n return undefined;\n}\n\nfunction getBlockType(item: unknown): string | undefined {\n if (typeof item !== 'object' || item === null) return undefined;\n const blockType = (item as Record<string, unknown>)['blockType'];\n return typeof blockType === 'string' ? blockType : undefined;\n}\n\n/** Patches that turn `prev` into `next`; a changed `blockType` is a `replace`, never an `update`. */\nexport function diffArray(\n prev: readonly unknown[],\n next: readonly unknown[],\n): readonly ArrayPatch[] {\n const haveIds = next.every((item) => getId(item) !== undefined);\n if (haveIds) return diffById(prev, next);\n return diffByPosition(prev, next);\n}\n\nfunction diffById(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const prevIndexById = new Map<string | number, number>();\n for (let i = 0; i < prev.length; i += 1) {\n const id = getId(prev[i]);\n if (id !== undefined) prevIndexById.set(id, i);\n }\n\n const consumedFromPrev = new Set<number>();\n for (let to = 0; to < next.length; to += 1) {\n const item = next[to];\n const id = getId(item);\n if (id === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n const from = prevIndexById.get(id);\n if (from === undefined) {\n patches.push({ kind: 'insert', index: to, value: item });\n continue;\n }\n consumedFromPrev.add(from);\n const prevItem = prev[from];\n if (getBlockType(prevItem) !== getBlockType(item)) {\n patches.push({ kind: 'replace', index: to, oldValue: prevItem, value: item });\n continue;\n }\n if (from !== to) {\n patches.push({ kind: 'move', from, to, value: item });\n }\n if (!shallowEqual(prevItem, item)) {\n patches.push({ kind: 'update', index: to, value: item });\n }\n }\n\n for (let i = 0; i < prev.length; i += 1) {\n if (consumedFromPrev.has(i)) continue;\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n return patches;\n}\n\nfunction diffByPosition(prev: readonly unknown[], next: readonly unknown[]): readonly ArrayPatch[] {\n const patches: ArrayPatch[] = [];\n const min = Math.min(prev.length, next.length);\n for (let i = 0; i < min; i += 1) {\n if (!shallowEqual(prev[i], next[i])) {\n patches.push({ kind: 'update', index: i, value: next[i] });\n }\n }\n if (next.length > prev.length) {\n for (let i = prev.length; i < next.length; i += 1) {\n patches.push({ kind: 'insert', index: i, value: next[i] });\n }\n }\n if (prev.length > next.length) {\n for (let i = next.length; i < prev.length; i += 1) {\n patches.push({ kind: 'remove', index: i, value: prev[i] });\n }\n }\n return patches;\n}\n\n// Shallow on purpose: any nested reference change is an update, and the\n// renderer reconciles deeper differences itself.\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const aRec = a as Record<string, unknown>;\n const bRec = b as Record<string, unknown>;\n const aKeys = Object.keys(aRec);\n const bKeys = Object.keys(bRec);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.is(aRec[key], bRec[key])) return false;\n }\n return true;\n}\n","/**\n * Payload field type → renderer name. Structural containers the walker has\n * already flattened, and types without a display, map to `text` so a new\n * Payload field type never leaves a binding without a renderer.\n */\n\nimport type { FieldType } from '@core/types';\nimport type { PayloadFieldType } from '@/types/payload-protocol';\n\nconst MAP: Readonly<Record<PayloadFieldType, FieldType>> = {\n text: 'text',\n textarea: 'textarea',\n richText: 'richText',\n email: 'email',\n number: 'number',\n checkbox: 'checkbox',\n date: 'date',\n select: 'select',\n radio: 'radio',\n array: 'array',\n blocks: 'blocks',\n group: 'text',\n tabs: 'text',\n row: 'text',\n collapsible: 'text',\n relationship: 'relationship',\n upload: 'upload',\n point: 'text',\n json: 'text',\n code: 'text',\n ui: 'text',\n};\n\n/** `undefined` for a type not in the table, so the caller can fall back to the DOM attribute. */\nexport function payloadTypeToRenderer(type: string): FieldType | undefined {\n if (Object.prototype.hasOwnProperty.call(MAP, type)) {\n return MAP[type as PayloadFieldType];\n }\n return undefined;\n}\n","/**\n * URL safety: the one scheme allow-list the runtime, the client and the\n * sanitizer share. Empty strings are not safe (`<a href=\"\">` is never emitted).\n */\n\nconst SAFE_PROTOCOLS: ReadonlySet<string> = new Set(['http:', 'https:', 'mailto:', 'tel:']);\n\n// Browsers strip leading whitespace before scheme detection.\nconst DANGEROUS_PROTOCOL_PATTERN = /^\\s*(?:javascript|data|vbscript|file|blob|about)\\s*:/i;\n\nconst RELATIVE_PATH = /^(?:\\.{1,2}\\/|[a-zA-Z0-9_-]+\\/?)/;\n\n// The URL parser treats `\\` as `/` for special schemes, so `/\\evil.com`\n// resolves to another origin rather than to a same-origin path.\nconst PROTOCOL_RELATIVE = /^[\\\\/]{2}/;\n\n/** The URL parser drops these anywhere in the input before it looks at anything. */\nconst PARSER_IGNORED = /[\\t\\n\\r]/g;\n\n/** `true` only for absolute `http`/`https`/`mailto`/`tel` URLs, protocol-relative URLs, paths, `#`/`?` fragments and relative paths. */\nexport function isSafeUrl(url: unknown): boolean {\n if (typeof url !== 'string' || url.length === 0) return false;\n const trimmed = url.trim().replace(PARSER_IGNORED, '');\n if (trimmed.length === 0) return false;\n if (DANGEROUS_PROTOCOL_PATTERN.test(trimmed)) return false;\n if (trimmed.startsWith('#') || trimmed.startsWith('?')) return true;\n if (PROTOCOL_RELATIVE.test(trimmed)) return true;\n if (trimmed.startsWith('/')) return true;\n try {\n const parsed = new URL(trimmed);\n return SAFE_PROTOCOLS.has(parsed.protocol);\n } catch {\n return RELATIVE_PATH.test(trimmed);\n }\n}\n\n/** Whether a safe URL points at another HTTP(S) origin, protocol-relative forms included, and so needs `noopener` hardening. */\nexport function isExternalHttpUrl(url: string): boolean {\n if (!isSafeUrl(url)) return false;\n const trimmed = url.trim().replace(PARSER_IGNORED, '');\n return /^https?:\\/\\//i.test(trimmed) || PROTOCOL_RELATIVE.test(trimmed);\n}\n\n/** The safe scheme set, for tests and introspection. */\nexport const SAFE_URL_PROTOCOLS: ReadonlySet<string> = SAFE_PROTOCOLS;\n","/**\n * Policed writes for `data-payload-attribute` bindings. The value is\n * remote-controlled, so event handlers, `style`, `srcdoc`, `formaction`/`form`,\n * `id`/`name` (DOM clobbering) and `srcset` (multi-URL syntax) are refused,\n * URL-bearing attributes must pass `isSafeUrl`, and non-scalars never write.\n */\n\nimport { isSafeUrl } from '@security/url-validator';\n\nconst BLOCKED_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'style',\n 'srcdoc',\n 'formaction',\n 'form',\n 'id',\n 'name',\n 'is',\n 'srcset',\n 'imagesrcset',\n]);\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'href',\n 'src',\n 'poster',\n 'cite',\n 'action',\n 'xlink:href',\n 'data',\n]);\n\nexport type AttributeApplyResult = 'applied' | 'blocked';\n\n/** Returns `'blocked'` without touching the DOM when the write is refused. */\nexport function applyAttributeBinding(\n element: Element,\n attribute: string,\n value: unknown,\n): AttributeApplyResult {\n const name = attribute.toLowerCase().trim();\n if (name.length === 0) return 'blocked';\n if (name.startsWith('on')) return 'blocked';\n if (BLOCKED_ATTRIBUTES.has(name)) return 'blocked';\n\n if (value === null || value === undefined) {\n element.removeAttribute(name);\n return 'applied';\n }\n if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {\n return 'blocked';\n }\n const stringValue = String(value);\n\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(stringValue)) return 'blocked';\n\n element.setAttribute(name, stringValue);\n return 'applied';\n}\n","/**\n * Public renderer callbacks return `void`, but a JavaScript implementation may\n * return anything. Only callbacks marked here may reserve exact `false` as\n * \"no write\", so a custom renderer's incidental boolean cannot change the\n * lifecycle's applied counts.\n */\n\ntype Callback = (...args: never[]) => unknown;\n\nconst noWriteCallbacks = new WeakSet<Callback>();\n\n/** Mark a package-owned callback whose exact `false` return means no write. */\nexport function markNoWriteCallback<T extends Callback>(callback: T): T {\n noWriteCallbacks.add(callback);\n return callback;\n}\n\n/** Whether `callback` owns the internal exact-false sentinel contract. */\nexport function usesNoWriteOutcome(callback: Callback): boolean {\n return noWriteCallbacks.has(callback);\n}\n\n/** Check a renderer object without detaching its public method at the call site. */\nexport function rendererUsesNoWriteOutcome(renderer: { readonly render: Callback }): boolean {\n return noWriteCallbacks.has(renderer.render);\n}\n","/**\n * Stable identity for a field value, so two messages can be compared without\n * rendering either — every keystroke ships the whole document, of which one\n * field changed. Equality is structural (plain, unsorted JSON): Payload\n * allocates a fresh object graph per message, so reference identity would skip\n * nothing. A value JSON cannot represent has no identity and counts as\n * changed, which is the safe direction — a false \"equal\" leaves a stale\n * binding, a false \"different\" only renders once more.\n */\n\n/** Past this size the comparison is no longer obviously cheaper than the render it avoids. */\nexport const IDENTITY_SIZE_LIMIT = 64 * 1024;\n\n/**\n * Canonical string for `value`, or `undefined` when it cannot have one.\n * Primitives carry a type tag, so `1` and `'1'` differ even though a text\n * renderer prints them alike — that is the renderer's decision, not this one.\n */\nexport function valueIdentity(value: unknown): string | undefined {\n switch (typeof value) {\n case 'string':\n return value.length > IDENTITY_SIZE_LIMIT ? undefined : `s:${value}`;\n case 'number':\n // Object.is semantics at the top level: NaN equals NaN, -0 is not 0.\n return `n:${Object.is(value, -0) ? '-0' : String(value)}`;\n case 'boolean':\n return `b:${value ? '1' : '0'}`;\n case 'bigint':\n return `i:${String(value)}`;\n case 'undefined':\n return 'u';\n case 'object': {\n if (value === null) return 'z';\n let json: string;\n try {\n // Throws on a cycle and on a nested BigInt; both mean \"no identity\".\n json = JSON.stringify(value);\n } catch {\n return undefined;\n }\n return json.length > IDENTITY_SIZE_LIMIT ? undefined : `o:${json}`;\n }\n case 'symbol':\n case 'function':\n return undefined;\n }\n}\n","/**\n * The one per-message diff of top-level field values. Strategies, dependency\n * invalidation and reveal all consume it, so \"changed\" means the same thing\n * everywhere.\n */\n\nimport type { DependencyMap } from './dependencies';\nimport { valueIdentity } from './value-identity';\n\nexport interface FieldChanges {\n /** Fields whose value differs from the previous message; every field on the first one. */\n readonly changed: ReadonlySet<string>;\n /** Dependents of changed fields, per the dependency map. */\n readonly invalidated: ReadonlySet<string>;\n}\n\nexport class FieldChangeTracker {\n private previous: Map<string, string | undefined> | null = null;\n\n /** Diff `fields` against the previous message and remember them for the next call. */\n diff(fields: Readonly<Record<string, unknown>>, dependencies: DependencyMap): FieldChanges {\n const previous = this.previous;\n const next = new Map<string, string | undefined>();\n const changed = new Set<string>();\n for (const [name, value] of Object.entries(fields)) {\n const identity = valueIdentity(value);\n next.set(name, identity);\n // A value without an identity always counts as changed: rendering once\n // more is cheap, a stale binding is not.\n if (previous === null || identity === undefined || previous.get(name) !== identity) {\n changed.add(name);\n }\n }\n if (previous !== null) {\n for (const name of previous.keys()) if (!next.has(name)) changed.add(name);\n }\n this.previous = next;\n const invalidated = new Set<string>();\n for (const [source, dependents] of Object.entries(dependencies)) {\n if (!changed.has(source)) continue;\n for (const dependent of dependents) invalidated.add(dependent);\n }\n return { changed, invalidated };\n }\n\n reset(): void {\n this.previous = null;\n }\n}\n","/**\n * Protocol negotiation. A capability is granted either by the version a peer\n * announces or by observation, since the stock Payload admin announces none:\n * what it can do is read off the messages it sends. See ADR 0010.\n */\n\n/** Bumped only when this library's understanding of the wire format changes. */\nexport const LIBRARY_PROTOCOL_VERSION = 4;\n\n/** How a capability becomes active. */\nexport type CapabilitySource = 'version' | 'observed';\n\nexport interface CapabilityDeclaration {\n /** Enabled once the negotiated version reaches this (for announced peers). */\n readonly since: number;\n /** The wire signal that grants this capability to a peer announcing no version. */\n readonly observed?:\n 'schema' | 'locale' | 'preview-token' | 'document-event' | 'relationship-event';\n}\n\n/** What activates each capability; the prose lives in `CAPABILITY_DOCUMENTATION`. */\nexport const CAPABILITY_DECLARATIONS = {\n basic: { since: 1 },\n 'schema-json': { since: 2, observed: 'schema' },\n locale: { since: 2, observed: 'locale' },\n 'preview-token': { since: 3, observed: 'preview-token' },\n 'nested-arrays': { since: 4 },\n 'recursive-diffs': { since: 4 },\n 'document-events': { since: 4, observed: 'document-event' },\n 'relationship-events': { since: 4, observed: 'relationship-event' },\n} as const satisfies Record<string, CapabilityDeclaration>;\n\nexport type ProtocolCapability = keyof typeof CAPABILITY_DECLARATIONS;\n\n/** Every declared capability, in declaration order. */\nexport const PROTOCOL_CAPABILITIES = Object.keys(\n CAPABILITY_DECLARATIONS,\n) as readonly ProtocolCapability[];\n\nexport interface ProtocolNegotiation {\n /** This library's protocol version. */\n readonly ours: number;\n /** The remote party's version, when it announced one. */\n readonly theirs: number | undefined;\n /** `min(ours, theirs ?? 1)` — the version both sides actually share. */\n readonly negotiated: number;\n /** Capabilities active at the negotiated version or seen on the wire. */\n readonly capabilities: ReadonlySet<ProtocolCapability>;\n /** The subset that was observed on the wire rather than granted by version. */\n readonly observed: ReadonlySet<ProtocolCapability>;\n}\n\n/** Deterministic; the runtime re-runs it whenever either input changes. */\nexport function negotiateProtocol(\n theirs: number | undefined,\n observed: Iterable<ProtocolCapability> = [],\n): ProtocolNegotiation {\n const sanitisedTheirs =\n typeof theirs === 'number' && Number.isFinite(theirs) && theirs >= 1\n ? Math.floor(theirs)\n : undefined;\n const effectiveTheirs = sanitisedTheirs ?? 1;\n const negotiated = Math.min(LIBRARY_PROTOCOL_VERSION, effectiveTheirs);\n const seen = new Set<ProtocolCapability>(observed);\n const capabilities = new Set<ProtocolCapability>();\n for (const capability of PROTOCOL_CAPABILITIES) {\n if (negotiated >= CAPABILITY_DECLARATIONS[capability].since || seen.has(capability)) {\n capabilities.add(capability);\n }\n }\n return {\n ours: LIBRARY_PROTOCOL_VERSION,\n ...(sanitisedTheirs !== undefined ? { theirs: sanitisedTheirs } : { theirs: undefined }),\n negotiated,\n capabilities,\n observed: seen,\n };\n}\n\nexport function hasCapability(\n negotiation: ProtocolNegotiation,\n capability: ProtocolCapability,\n): boolean {\n return negotiation.capabilities.has(capability);\n}\n\n/** The capabilities a single message demonstrates, by its shape alone. */\nexport function observeCapabilities(message: {\n readonly fieldSchemaJSON?: unknown;\n readonly locale?: unknown;\n readonly previewToken?: unknown;\n readonly externallyUpdatedRelationship?: unknown;\n}): readonly ProtocolCapability[] {\n const seen: ProtocolCapability[] = [];\n if (Array.isArray(message.fieldSchemaJSON)) seen.push('schema-json');\n if (typeof message.locale === 'string') seen.push('locale');\n if (typeof message.previewToken === 'string') seen.push('preview-token');\n if (\n typeof message.externallyUpdatedRelationship === 'object' &&\n message.externallyUpdatedRelationship !== null\n ) {\n seen.push('relationship-events');\n }\n return seen;\n}\n","/** Tracks the announced protocol version and the capabilities seen on the wire. */\n\nimport {\n LIBRARY_PROTOCOL_VERSION,\n negotiateProtocol,\n type ProtocolCapability,\n type ProtocolNegotiation,\n} from './protocol-version';\n\nexport class ProtocolTracker {\n negotiation: ProtocolNegotiation = negotiateProtocol(undefined);\n readonly observed = new Set<ProtocolCapability>();\n\n /** Record capabilities a message demonstrated; the stock admin announces no version. */\n observe(capabilities: readonly ProtocolCapability[], log: (...args: unknown[]) => void): void {\n const fresh = capabilities.filter((capability) => !this.observed.has(capability));\n if (fresh.length === 0) return;\n for (const capability of fresh) this.observed.add(capability);\n this.negotiation = negotiateProtocol(this.negotiation.theirs, this.observed);\n log('protocol', `observed=${fresh.join(',')}`);\n }\n\n applyVersion(remoteVersion: number, log: (...args: unknown[]) => void): void {\n const current = this.negotiation;\n if (current.theirs === remoteVersion) return;\n const next = negotiateProtocol(remoteVersion, this.observed);\n this.negotiation = next;\n if (next.negotiated === current.negotiated) return;\n log(\n 'protocol',\n `ours=${LIBRARY_PROTOCOL_VERSION}`,\n `theirs=${remoteVersion}`,\n `negotiated=${next.negotiated}`,\n );\n }\n}\n","/**\n * Scroll the edited field's bound element into view. Deliberately quiet: only\n * when the target is off-screen and only when the edited field changed since\n * the last reveal, so continuous typing never re-scrolls and a deliberate\n * scroll-away is not fought. Honours `prefers-reduced-motion`.\n */\n\n/** The slice of `Window` this reads, so it tests without a browser. */\nexport interface RevealWindow {\n readonly innerHeight: number;\n readonly innerWidth: number;\n matchMedia?: (query: string) => { readonly matches: boolean };\n}\n\n/** The slice of `Element` this module needs. */\nexport interface RevealElement {\n getBoundingClientRect: () => {\n readonly top: number;\n readonly bottom: number;\n readonly left: number;\n readonly right: number;\n };\n scrollIntoView: (options?: {\n behavior?: 'auto' | 'smooth';\n block?: 'center' | 'nearest' | 'start';\n }) => void;\n}\n\n/** Whether the viewer asked for reduced motion; smooth scrolling is suppressed when so. */\nexport function prefersReducedMotion(win: RevealWindow): boolean {\n try {\n return win.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;\n } catch {\n return false;\n }\n}\n\n/** A visible sliver counts: an element the editor can already see is never scrolled to. */\nexport function isInViewport(element: RevealElement, win: RevealWindow): boolean {\n const rect = element.getBoundingClientRect();\n const vertically = rect.bottom > 0 && rect.top < win.innerHeight;\n const horizontally = rect.right > 0 && rect.left < win.innerWidth;\n return vertically && horizontally;\n}\n\n/** Outcome of a reveal attempt, for the caller's diagnostics. */\nexport type RevealOutcome = 'revealed' | 'already-visible';\n\n/** Scroll `element` into view only when it is off-screen. */\nexport function revealElement(element: RevealElement, win: RevealWindow): RevealOutcome {\n if (isInViewport(element, win)) return 'already-visible';\n element.scrollIntoView({\n behavior: prefersReducedMotion(win) ? 'auto' : 'smooth',\n block: 'center',\n });\n return 'revealed';\n}\n\n/** Remembers the last field revealed, so only a change of field scrolls again. */\nexport class FieldRevealer {\n #lastField: string | undefined;\n\n /** `skipped-same` when this is still the field last revealed. */\n reveal(\n fieldName: string,\n element: RevealElement,\n win: RevealWindow,\n ): RevealOutcome | 'skipped-same' {\n if (fieldName === this.#lastField) return 'skipped-same';\n this.#lastField = fieldName;\n return revealElement(element, win);\n }\n\n /** Forget the last field, after a navigation that rebuilt the page. */\n reset(): void {\n this.#lastField = undefined;\n }\n}\n","/**\n * What the runtime owns for its lifetime (`RuntimeDeps`) and what changes as it\n * runs (`RuntimeState`). Both are shared by the pipeline collaborators.\n */\n\nimport type { PayloadFieldSchema, PayloadLivePreviewMessage } from '@/types/payload-protocol';\nimport type { EventEmitter } from '@events/emitter';\nimport type { SchemaIndex } from '@schema/index';\nimport type { A11yAnnouncer } from './a11y';\nimport type { ElementCache } from './cache';\nimport type { DataMerger } from './data-merger';\nimport { FieldChangeTracker } from './field-changes';\nimport type { MessageBus, MessageRevision } from './message-bus';\nimport type { ObserverManager } from './observers';\nimport { ProtocolTracker } from './protocol-tracker';\nimport { FieldRevealer } from './reveal';\nimport type { RuntimeOptions } from './runtime-options';\nimport type { ConnectionState, HeartbeatTimer } from './state';\nimport type { StrategyHandlers } from './strategies';\nimport type { CachedElement, FieldRenderer, RichTextRenderer } from './types';\nimport type { FlushStats, UpdateScheduler } from './update-scheduler';\n\n/** One accepted message on its way to the DOM. See ADR 0004. */\nexport interface UpdateTransaction {\n readonly identity: MessageRevision;\n readonly message: PayloadLivePreviewMessage;\n readonly locale: string | undefined;\n readonly schema: readonly PayloadFieldSchema[] | undefined;\n readonly schemaIndex: SchemaIndex | undefined;\n readonly receivedAt: number;\n /** A relationship edit may change populated values only, so render everything. */\n readonly forceRender: boolean;\n /** Top-level fields whose value changed since the previous message, plus their dependents. */\n touched: ReadonlySet<string>;\n /** Dependents of changed fields; re-applied even when their own value is unchanged. */\n invalidated: ReadonlySet<string>;\n /**\n * First binding whose value changed; revealed once its write landed. The\n * binding itself, not its field name: several documents on one page share\n * field names, and only this one belongs to the edited document.\n */\n revealTarget: CachedElement | undefined;\n /**\n * Identities the reveal ledger will record once this revision reaches its\n * reveal point — not before. A revision superseded on the way there never\n * revealed, so the ledger must still show the previous value: the message\n * that supersedes it is then the one that owes the reveal.\n */\n revealIdentities: [key: string, identity: string][];\n pendingFragments: number;\n routeRefreshed: boolean;\n cancelled: boolean;\n /** Terminal: the scheduled writes reached the DOM (or there were none). */\n completed: boolean;\n}\n\nexport interface RuntimeDeps {\n readonly emitter: EventEmitter;\n readonly cache: ElementCache;\n readonly observers: ObserverManager;\n readonly scheduler: UpdateScheduler;\n readonly bus: MessageBus;\n readonly connection: ConnectionState;\n readonly heartbeat: HeartbeatTimer;\n readonly renderers: Readonly<Record<string, FieldRenderer>>;\n readonly resolveRenderer: NonNullable<RuntimeOptions['resolveRenderer']>;\n readonly transformValue: RuntimeOptions['transformValue'];\n readonly renderRichText: RichTextRenderer | undefined;\n readonly root: Document | Element;\n readonly readyTargets: () => readonly string[];\n readonly sendReady: (origins: readonly string[]) => void;\n readonly onHeartbeatTimeout: RuntimeOptions['onHeartbeatTimeout'];\n readonly log: (...args: unknown[]) => void;\n readonly warn: (...args: unknown[]) => void;\n readonly a11y: A11yAnnouncer | null;\n readonly merger: DataMerger | null;\n readonly scopeBindingsByOwner: boolean;\n readonly lockedOrigin: () => string | undefined;\n readonly skipUnchanged: boolean;\n readonly dependencies: Readonly<Record<string, readonly string[]>>;\n readonly strategies: StrategyHandlers;\n readonly revealEditedField: boolean;\n}\n\nexport function sameRevision(a: MessageRevision, b: MessageRevision): boolean {\n return a.generation === b.generation && a.revision === b.revision;\n}\n\nexport class RuntimeState {\n started = false;\n /** Set by `suspend()`; lets `destroy()` finish a suspended instance. */\n suspended = false;\n deferredStart: (() => void) | null = null;\n activeUpdate: UpdateTransaction | null = null;\n locale: string | undefined = undefined;\n schema: readonly PayloadFieldSchema[] | undefined = undefined;\n schemaIndex: SchemaIndex | undefined = undefined;\n updateCount = 0;\n supersededCount = 0;\n completedCount = 0;\n skippedUnchangedCount = 0;\n lastFlush: FlushStats | null = null;\n readonly absentFields = new Set<string>();\n readonly warnedOrphanFields = new Set<string>();\n readonly warnedStrategy = new WeakSet<Element>();\n warnedUnattributableMessage = false;\n warnedVisibilityGate = false;\n warnedFragmentFallback = false;\n /** Identity of the value each element last applied; reset when the markup is re-rendered. */\n lastAppliedIdentity = new WeakMap<Element, string>();\n /**\n * Identity of the value last seen per owned field, for the reveal decision\n * only. Keyed by document and field rather than by element, so a field the\n * server re-renders behind a fragment boundary — where no element survives\n * to carry the identity — is still known to have changed.\n */\n readonly seenFieldIdentity = new Map<string, string>();\n readonly fragmentStats = { rendered: 0, failed: 0, superseded: 0 };\n readonly routeStats = { refreshes: 0, failed: 0, loopStopped: 0 };\n fragmentController: AbortController | null = null;\n routeController: AbortController | null = null;\n readonly readyTimers: ReturnType<typeof setTimeout>[] = [];\n readonly revealer = new FieldRevealer();\n readonly changes = new FieldChangeTracker();\n readonly protocol = new ProtocolTracker();\n\n /** Read through a method: TypeScript keeps a narrowed `started` across the calls that can flip it. */\n isRunning(): boolean {\n return this.started;\n }\n\n /** Whether `transaction` may still touch the DOM; re-checked after every reentrant callback. */\n isCurrent(transaction: UpdateTransaction): boolean {\n return this.started && this.activeUpdate === transaction;\n }\n\n complete(transaction: UpdateTransaction): void {\n if (transaction.completed) return;\n transaction.completed = true;\n this.completedCount += 1;\n }\n\n /** Abort in-flight strategy work; a newer revision or a stop supersedes it. */\n abortStrategies(): void {\n for (const key of ['fragmentController', 'routeController'] as const) {\n const controller = this[key];\n if (controller === null) continue;\n this[key] = null;\n controller.abort();\n }\n }\n}\n","/**\n * Writes one scheduled value into its bound element: renderer resolution,\n * the attribute or renderer write, and the `elementUpdate` event. Every\n * consumer callback may accept a newer revision synchronously, so the\n * transaction is re-checked after each one (ADR 0004).\n */\n\nimport { lookupSchema, payloadTypeToRenderer } from '@schema/index';\nimport { applyAttributeBinding } from './attribute-binding';\nimport { rendererUsesNoWriteOutcome } from './internal-outcome';\nimport {\n sameRevision,\n type RuntimeDeps,\n type RuntimeState,\n type UpdateTransaction,\n} from './runtime-state';\nimport type { CachedElement, FieldRenderer, RenderContext, RendererKey } from './types';\nimport type { ScheduledUpdate } from './update-scheduler';\n\nexport class BindingWriter {\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n ) {}\n\n /** Scheduler callback. `false` means nothing reached the DOM. */\n apply(update: ScheduledUpdate): boolean {\n const { deps, state } = this;\n const transaction = state.activeUpdate;\n if (\n transaction === null ||\n update.identity === undefined ||\n !sameRevision(transaction.identity, update.identity) ||\n !state.isCurrent(transaction)\n ) {\n return false;\n }\n const { target, value } = update;\n const schemaEntry =\n transaction.schemaIndex !== undefined\n ? lookupSchema(transaction.schemaIndex, target.fieldName)\n : undefined;\n let type = resolveFieldType(target, schemaEntry?.type);\n // Payload 3.x sends no schema; a Lexical root is unmistakable.\n if (type === 'text' && target.explicitFieldType !== true && looksLikeLexicalRoot(value)) {\n type = 'richText';\n }\n let renderer: FieldRenderer | undefined;\n try {\n renderer = deps.resolveRenderer(type, target);\n } catch (error) {\n return this.fail(transaction, error);\n }\n if (!state.isCurrent(transaction)) return false;\n const emitElementUpdate = deps.emitter.listenerCount('elementUpdate') > 0;\n // Custom-element accessors run application code, so this is a boundary too.\n const previous = emitElementUpdate ? readElementSnapshot(target.element) : undefined;\n if (!state.isCurrent(transaction)) return false;\n const context: RenderContext = {\n allFields: update.allFields,\n locale: target.locale ?? transaction.locale,\n schema: schemaEntry,\n ...(deps.renderRichText !== undefined ? { renderRichText: deps.renderRichText } : {}),\n };\n // A boundary anchor stays out of layout and the accessibility tree while empty.\n if (target.boundary === true) {\n target.element.toggleAttribute('hidden', isEmptyFieldValue(value));\n }\n try {\n if (target.targetAttribute !== undefined) {\n if (applyAttributeBinding(target.element, target.targetAttribute, value) === 'blocked') {\n deps.warn(\n `[live-preview] LP0401: refused to write \"${target.fieldName}\" into attribute \"${target.targetAttribute}\"`,\n );\n return false;\n }\n } else if (renderer !== undefined) {\n const outcome = invokeRenderer(renderer, target, value, context);\n if (outcome === false && rendererUsesNoWriteOutcome(renderer)) return false;\n } else {\n deps.log('no renderer for', type);\n return false;\n }\n } catch (error) {\n return this.fail(transaction, error);\n }\n if (!state.isCurrent(transaction)) return false;\n if (emitElementUpdate) {\n void deps.emitter.emitWhile(\n 'elementUpdate',\n {\n element: target.element,\n fieldName: target.fieldName,\n previousValue: previous,\n nextValue: value,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n },\n () => state.isCurrent(transaction),\n );\n }\n // The first handler runs before emitWhile yields; a reentrant newer\n // revision must not count this write as applied.\n const applied = state.isCurrent(transaction);\n if (applied) {\n if (update.valueIdentity !== undefined) {\n state.lastAppliedIdentity.set(target.element, update.valueIdentity);\n } else {\n state.lastAppliedIdentity.delete(target.element);\n }\n }\n return applied;\n }\n\n private fail(transaction: UpdateTransaction, cause: unknown): false {\n if (!this.state.isCurrent(transaction)) return false;\n const error = cause instanceof Error ? cause : new Error(String(cause));\n void this.deps.emitter.emitWhile('error', { error, context: 'renderer', code: 'LP0603' }, () =>\n this.state.isCurrent(transaction),\n );\n return false;\n }\n}\n\n/** Explicit `data-payload-type` wins over the schema, which wins over tag heuristics. */\nfunction resolveFieldType(target: CachedElement, schemaType: string | undefined): RendererKey {\n if (target.explicitFieldType) return target.fieldType;\n if (schemaType !== undefined) {\n const mapped = payloadTypeToRenderer(schemaType);\n if (mapped !== undefined) return mapped;\n }\n return target.fieldType;\n}\n\n/** Built-in renderers may return exact `false` for a deliberate no-write; the public type stays `void`. */\nfunction invokeRenderer(\n renderer: FieldRenderer,\n target: CachedElement,\n value: unknown,\n context: RenderContext,\n): unknown {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n return renderer.render(target, value, context);\n}\n\n/** Same shape test as `isLexicalContent`, duplicated so core does not pull the Lexical renderer. */\nfunction looksLikeLexicalRoot(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || !('root' in value)) return false;\n const root = value.root;\n return (\n typeof root === 'object' &&\n root !== null &&\n Array.isArray((root as { children?: unknown }).children)\n );\n}\n\nfunction readElementSnapshot(element: Element): unknown {\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n return (element as HTMLInputElement).value;\n }\n if (element.tagName === 'IMG') return (element as HTMLImageElement).src;\n return element.textContent;\n}\n\nfunction isEmptyFieldValue(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n if (typeof value === 'string') return value.trim().length === 0;\n return Array.isArray(value) && value.length === 0;\n}\n","/**\n * One source → dependents map for `skipUnchanged`. Markup declares it the\n * other way round (`data-payload-depends=\"price\"` on the element bound to\n * `priceLabel`) because an author names what a binding needs; the runtime\n * option is keyed by source because the scheduler asks what changed.\n */\n\nexport type DependencyMap = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Field names from an attribute value. Separators are commas and\n * whitespace; empty entries are dropped; order is kept, duplicates removed.\n */\nexport function parseDependencyList(value: string | null | undefined): readonly string[] {\n if (value === null || value === undefined) return [];\n const seen = new Set<string>();\n const names: string[] = [];\n for (const raw of value.split(/[\\s,]+/)) {\n const name = raw.trim();\n if (name.length === 0 || seen.has(name)) continue;\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/**\n * Merge dependency maps (source → dependents). Later maps add to earlier\n * ones; a dependent is listed once per source.\n */\nexport function mergeDependencyMaps(...maps: readonly DependencyMap[]): DependencyMap {\n const merged = new Map<string, Set<string>>();\n for (const map of maps) {\n for (const [source, dependents] of Object.entries(map)) {\n let bucket = merged.get(source);\n if (bucket === undefined) {\n bucket = new Set();\n merged.set(source, bucket);\n }\n for (const dependent of dependents) bucket.add(dependent);\n }\n }\n const result: Record<string, readonly string[]> = {};\n for (const [source, dependents] of merged) result[source] = [...dependents];\n return result;\n}\n\n/**\n * The map an element's `data-payload-depends` contributes: every declared\n * source points at this binding's field.\n */\nexport function dependencyMapFromBinding(\n fieldName: string,\n dependsOn: readonly string[],\n): DependencyMap {\n const map: Record<string, readonly string[]> = {};\n for (const source of dependsOn) {\n if (source === fieldName) continue;\n map[source] = [fieldName];\n }\n return map;\n}\n","/**\n * Hydrated islands own their subtree, so the runtime never patches inside one.\n * Instead every flush dispatches `payload-live-preview:update` on each island\n * root with the update in `detail`. `data-payload-island=\"patch\"` opts back in.\n */\n\nexport const ISLAND_EVENT = 'payload-live-preview:update';\nexport const ISLAND_ATTRIBUTE = 'data-payload-island';\nexport const ISLAND_SELECTOR = `astro-island, [${ISLAND_ATTRIBUTE}]`;\n\nexport interface IslandUpdateDetail {\n readonly fields: Readonly<Record<string, unknown>>;\n readonly revision: number;\n readonly receivedAt: number;\n readonly locale: string | undefined;\n}\n\nfunction isIslandRoot(element: Element): boolean {\n return element.tagName.toLowerCase() === 'astro-island' || element.hasAttribute(ISLAND_ATTRIBUTE);\n}\n\nfunction islandAllowsPatching(island: Element): boolean {\n return island.getAttribute(ISLAND_ATTRIBUTE) === 'patch';\n}\n\n/** Whether `element` (or an ancestor) is an island that did not opt into patching. */\nexport function isInsideIsland(element: Element): boolean {\n let current: Element | null = element;\n while (current !== null) {\n if (isIslandRoot(current) && !islandAllowsPatching(current)) return true;\n current = current.parentElement;\n }\n return false;\n}\n\n/** Island roots under `root` that receive update events. */\nexport function collectIslands(root: ParentNode): Element[] {\n const islands: Element[] = [];\n for (const island of root.querySelectorAll(ISLAND_SELECTOR)) {\n if (!islandAllowsPatching(island)) islands.push(island);\n }\n return islands;\n}\n\nexport function dispatchIslandUpdate(\n islands: readonly Element[],\n detail: IslandUpdateDetail,\n): number {\n for (const island of islands) {\n island.dispatchEvent(\n new CustomEvent<IslandUpdateDetail>(ISLAND_EVENT, { detail, bubbles: false }),\n );\n }\n return islands.length;\n}\n","/**\n * How a bound region is brought up to date: the runtime patches it, a server\n * renders a `data-payload-fragment` boundary from the unsaved form state, or\n * the whole route refreshes. Core carries only the seam — which boundaries a\n * strategy owns and what it may do — so a patch-only page pays for nothing\n * more; the orchestration lives in `payload-live-preview/fragment`.\n */\nimport type { DiagnosticCode } from './diagnostic-codes';\n\n/** What produced an update: the runtime's DOM patching, a server-rendered fragment, or a route refresh. */\nexport type UpdateSource = 'patch' | 'fragment' | 'route';\n\n/** Marks a server-rendered boundary; the value is the registry id the server may render. */\nexport const FRAGMENT_ATTRIBUTE = 'data-payload-fragment';\n\n/** The nearest fragment boundary enclosing `element` (the element itself included). */\nexport function enclosingFragment(element: Element): Element | null {\n return element.closest(`[${FRAGMENT_ATTRIBUTE}]`);\n}\n\n/** One revision, as a strategy sees it, with the runtime capabilities it may use. */\nexport interface FragmentContext {\n readonly root: ParentNode;\n readonly revision: number;\n readonly receivedAt: number;\n readonly fields: Readonly<Record<string, unknown>>;\n readonly locale: string | undefined;\n readonly collectionSlug: string | undefined;\n readonly globalSlug: string | undefined;\n /** Aborted when a newer revision arrives or the runtime stops. */\n readonly signal: AbortSignal;\n /** Whether this revision is still the current one. */\n readonly isCurrent: () => boolean;\n /** Morph server-rendered HTML into a boundary (Trusted Types and the keyed morph apply). */\n readonly morph: (boundary: Element, html: string) => void;\n /** Patch the boundary's own bindings from this revision — the deterministic fallback. */\n readonly patch: (boundary: Element) => void;\n /** Debug log through the runtime's logger, with the diagnostic code. */\n readonly log: (code: DiagnosticCode, detail: string) => void;\n /** Report a boundary rendered. */\n readonly rendered: (boundary: Element, id: string, key: string | undefined) => void;\n /** Report a boundary failed and patched instead; emits the `error` and `fragmentRender` events. */\n readonly failed: (\n boundary: Element,\n id: string,\n key: string | undefined,\n code: DiagnosticCode,\n reason: string,\n ) => void;\n}\n\nexport interface FragmentReport {\n readonly rendered: number;\n readonly failed: number;\n readonly superseded: number;\n}\n\n/** A fragment strategy: which boundaries it owns for a revision, and how it renders them. */\nexport interface FragmentStrategy {\n /** The boundaries this update re-renders; their inner bindings are left to the strategy. */\n readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => readonly Element[];\n /** Render the planned boundaries; resolves once every one settled. */\n readonly render: (\n context: FragmentContext,\n boundaries: readonly Element[],\n ) => Promise<FragmentReport>;\n}\n\n/** One revision, as the route strategy sees it. */\nexport interface RouteContext {\n readonly revision: number;\n readonly receivedAt: number;\n /** Aborted when a newer revision arrives or the runtime stops. */\n readonly signal: AbortSignal;\n readonly isCurrent: () => boolean;\n readonly log: (code: DiagnosticCode, detail: string) => void;\n}\n\n/**\n * Whether a revision needs the whole route re-rendered, and how. After a\n * refresh the runtime rescans and re-applies the revision, so the unsaved\n * state lands on the fresh markup.\n */\nexport interface RouteStrategy {\n readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => boolean;\n readonly refresh: (context: RouteContext) => Promise<'refreshed' | 'failed' | 'superseded'>;\n}\n\nexport interface StrategyHandlers {\n readonly fragment?: FragmentStrategy;\n readonly route?: RouteStrategy;\n}\n\nconst STRATEGY_ATTRIBUTE = 'data-payload-strategy';\n\n/**\n * Explicit `data-payload-strategy` wins; otherwise a binding inside a fragment\n * boundary belongs to the fragment, one in `<head>` to the route, the rest is\n * patched. An unknown explicit value resolves to `undefined` (LP0407).\n */\nexport function resolveStrategy(element: Element): UpdateSource | undefined {\n const explicit = element.getAttribute(STRATEGY_ATTRIBUTE);\n if (explicit !== null && explicit.length > 0) {\n return explicit === 'patch' || explicit === 'fragment' || explicit === 'route'\n ? explicit\n : undefined;\n }\n if (enclosingFragment(element) !== null) return 'fragment';\n if (element.closest('head') !== null) return 'route';\n return 'patch';\n}\n","/**\n * Maps field names to their bound elements so an update walks the cache, not\n * the DOM. Everything an update needs about a binding is resolved here, once,\n * at build time.\n */\n\nimport {\n dependencyMapFromBinding,\n mergeDependencyMaps,\n parseDependencyList,\n type DependencyMap,\n} from './dependencies';\nimport { collectIslands } from './islands';\nimport { enclosingFragment, resolveStrategy } from './strategies';\nimport type { CachedElement, ElementPredicate, FieldType, RendererKey } from './types';\n\nexport const FIELD_ATTRIBUTE = 'data-payload-field';\nexport const TYPE_ATTRIBUTE = 'data-payload-type';\nexport const TARGET_ATTRIBUTE_ATTRIBUTE = 'data-payload-attribute';\nexport const HREF_ATTRIBUTE = 'data-payload-href';\nexport const SRC_ATTRIBUTE = 'data-payload-src';\nexport const ALT_ATTRIBUTE = 'data-payload-alt';\nexport const ARRAY_TEMPLATE_ATTRIBUTE = 'data-payload-array-template';\nexport const ARRAY_SEPARATOR_ATTRIBUTE = 'data-payload-array-separator';\nexport const LOCALE_ATTRIBUTE = 'data-payload-locale';\nexport const RICH_TEXT_ATTRIBUTE = 'data-payload-richtext';\nexport const HTML_ATTRIBUTE = 'data-payload-html';\nexport const ARRAY_ATTRIBUTE = 'data-payload-array';\nexport const STRUCTURAL_ATTRIBUTE = 'data-payload-structural';\nexport const OWNER_ATTRIBUTE = 'data-payload-owner';\nexport const DEPENDS_ATTRIBUTE = 'data-payload-depends';\nexport const STRATEGY_ATTRIBUTE = 'data-payload-strategy';\nexport const BOUNDARY_ATTRIBUTE = 'data-payload-boundary';\nexport const INPUT_TYPE_ATTRIBUTE = 'type';\n\n/**\n * Attributes captured in a `CachedElement`. The mutation observer watches\n * exactly this list, so a snapshot can never go stale on a mounted element.\n */\nexport const BINDING_ATTRIBUTES: readonly string[] = [\n FIELD_ATTRIBUTE,\n TYPE_ATTRIBUTE,\n TARGET_ATTRIBUTE_ATTRIBUTE,\n HREF_ATTRIBUTE,\n SRC_ATTRIBUTE,\n ALT_ATTRIBUTE,\n ARRAY_TEMPLATE_ATTRIBUTE,\n ARRAY_SEPARATOR_ATTRIBUTE,\n LOCALE_ATTRIBUTE,\n RICH_TEXT_ATTRIBUTE,\n HTML_ATTRIBUTE,\n ARRAY_ATTRIBUTE,\n STRUCTURAL_ATTRIBUTE,\n OWNER_ATTRIBUTE,\n DEPENDS_ATTRIBUTE,\n STRATEGY_ATTRIBUTE,\n BOUNDARY_ATTRIBUTE,\n INPUT_TYPE_ATTRIBUTE,\n];\n\nconst FIELD_SELECTOR = `[${FIELD_ATTRIBUTE}]`;\nconst OWNER_SELECTOR = `[${OWNER_ATTRIBUTE}]`;\n\n/** The document a binding belongs to: its nearest `data-payload-owner`, itself included. */\nexport function resolveBindingOwner(element: Element): string | undefined {\n const owner = element.closest(OWNER_SELECTOR)?.getAttribute(OWNER_ATTRIBUTE);\n return owner === null || owner === undefined || owner.length === 0 ? undefined : owner;\n}\n\n/** `namespace:name` — a project renderer key can never be a typo of a built-in type. */\nconst CUSTOM_RENDERER_KEY = /^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*$/i;\n\nconst VALID_FIELD_TYPES: ReadonlySet<FieldType> = new Set<FieldType>([\n 'text',\n 'textarea',\n 'richText',\n 'email',\n 'number',\n 'checkbox',\n 'date',\n 'select',\n 'radio',\n 'array',\n 'blocks',\n 'group',\n 'tabs',\n 'row',\n 'collapsible',\n 'relationship',\n 'upload',\n 'point',\n 'json',\n 'code',\n 'ui',\n 'html',\n 'url',\n 'image',\n 'structural-array',\n]);\n\nfunction isRendererKey(value: string): value is RendererKey {\n return VALID_FIELD_TYPES.has(value as FieldType) || CUSTOM_RENDERER_KEY.test(value);\n}\n\nexport interface CacheBuildStats {\n readonly elementCount: number;\n readonly fieldCount: number;\n readonly durationMs: number;\n}\n\nexport interface ElementCacheOptions {\n /** Restricts which elements are accepted. Defaults to all. */\n readonly filter?: ElementPredicate;\n}\n\n/**\n * Elements share a field name when the same field is rendered in several\n * places; within a field the order is DOM order.\n */\nexport class ElementCache {\n private readonly entriesByField = new Map<string, CachedElement[]>();\n private entryByElement = new WeakMap<Element, CachedElement>();\n private readonly filter: ElementPredicate;\n private count = 0;\n private dependencies: DependencyMap | null = null;\n private islandRoots: readonly Element[] = [];\n\n constructor(options: ElementCacheOptions = {}) {\n this.filter = options.filter ?? alwaysTrue;\n }\n\n /** Source → dependents declared with `data-payload-depends`; memoised until the cache changes. */\n dependencyMap(): DependencyMap {\n if (this.dependencies !== null) return this.dependencies;\n const maps: DependencyMap[] = [];\n for (const binding of this.values()) {\n if (binding.dependsOn !== undefined) {\n maps.push(dependencyMapFromBinding(binding.fieldName, binding.dependsOn));\n }\n }\n this.dependencies = mergeDependencyMaps(...maps);\n return this.dependencies;\n }\n\n /** Island roots under the last built root, for update events. */\n get islands(): readonly Element[] {\n return this.islandRoots;\n }\n\n buildFromRoot(root: ParentNode): CacheBuildStats {\n const t0 = performance.now();\n this.clear();\n let elementCount = 0;\n for (const element of root.querySelectorAll(FIELD_SELECTOR)) {\n if (this.add(element) !== undefined) elementCount += 1;\n }\n this.islandRoots = collectIslands(root);\n return {\n elementCount,\n fieldCount: this.entriesByField.size,\n durationMs: performance.now() - t0,\n };\n }\n\n /**\n * Insert or replace a single element's binding. Re-adding refreshes the\n * snapshot in place; an element that is now filtered or unbound is removed.\n */\n add(element: Element): CachedElement | undefined {\n // Resolve before mutating so a throwing filter leaves the old entry intact.\n const entry = this.filter(element) ? this.resolveBinding(element) : undefined;\n const previous = this.entryByElement.get(element);\n this.dependencies = null;\n if (entry === undefined) {\n if (previous !== undefined) this.removeEntry(element, previous);\n return undefined;\n }\n if (previous !== undefined && this.replaceEntry(previous, entry)) {\n this.entryByElement.set(element, entry);\n return entry;\n }\n if (previous !== undefined) this.removeEntry(element, previous);\n this.append(entry);\n this.entryByElement.set(element, entry);\n return entry;\n }\n\n /** Returns whether a binding was removed. */\n remove(element: Element): boolean {\n const entry = this.entryByElement.get(element);\n if (!entry) return false;\n this.dependencies = null;\n return this.removeEntry(element, entry);\n }\n\n get(fieldName: string): readonly CachedElement[] | undefined {\n return this.entriesByField.get(fieldName);\n }\n\n getByElement(element: Element): CachedElement | undefined {\n return this.entryByElement.get(element);\n }\n\n get fieldCount(): number {\n return this.entriesByField.size;\n }\n\n get elementCount(): number {\n return this.count;\n }\n\n entries(): IterableIterator<[string, readonly CachedElement[]]> {\n return this.entriesByField.entries() as IterableIterator<[string, readonly CachedElement[]]>;\n }\n\n *values(): IterableIterator<CachedElement> {\n for (const bucket of this.entriesByField.values()) yield* bucket;\n }\n\n has(element: Element): boolean {\n return this.entryByElement.has(element);\n }\n\n clear(): void {\n this.entriesByField.clear();\n // WeakMap cannot be cleared; a detached element must not observe stale membership.\n this.entryByElement = new WeakMap();\n this.count = 0;\n this.dependencies = null;\n this.islandRoots = [];\n }\n\n /** Replace in place when the field bucket is unchanged, preserving order. */\n private replaceEntry(previous: CachedElement, next: CachedElement): boolean {\n if (previous.fieldName !== next.fieldName) return false;\n const bucket = this.entriesByField.get(previous.fieldName);\n const index = bucket === undefined ? -1 : bucket.indexOf(previous);\n if (bucket === undefined || index < 0) return false;\n bucket[index] = next;\n return true;\n }\n\n private removeEntry(element: Element, entry: CachedElement): boolean {\n this.entryByElement.delete(element);\n const bucket = this.entriesByField.get(entry.fieldName);\n const index = bucket === undefined ? -1 : bucket.indexOf(entry);\n if (bucket === undefined || index < 0) return false;\n bucket.splice(index, 1);\n if (bucket.length === 0) this.entriesByField.delete(entry.fieldName);\n this.count -= 1;\n return true;\n }\n\n private append(entry: CachedElement): void {\n const bucket = this.entriesByField.get(entry.fieldName);\n if (bucket) bucket.push(entry);\n else this.entriesByField.set(entry.fieldName, [entry]);\n this.count += 1;\n }\n\n private resolveBinding(element: Element): CachedElement | undefined {\n const fieldName = element.getAttribute(FIELD_ATTRIBUTE);\n if (fieldName === null || fieldName.length === 0) return undefined;\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n const targetAttribute = element.getAttribute(TARGET_ATTRIBUTE_ATTRIBUTE);\n const hrefField = element.getAttribute(HREF_ATTRIBUTE);\n const srcField = element.getAttribute(SRC_ATTRIBUTE);\n const altField = element.getAttribute(ALT_ATTRIBUTE);\n const arrayTemplate = element.getAttribute(ARRAY_TEMPLATE_ATTRIBUTE);\n const arraySeparator = element.getAttribute(ARRAY_SEPARATOR_ATTRIBUTE);\n const locale = element.getAttribute(LOCALE_ATTRIBUTE);\n const owner = resolveBindingOwner(element);\n const dependsOn = parseDependencyList(element.getAttribute(DEPENDS_ATTRIBUTE));\n const strategy = element.getAttribute(STRATEGY_ATTRIBUTE);\n const fragmentBoundary = enclosingFragment(element);\n return {\n element,\n fieldName,\n fieldType: resolveFieldType(element),\n explicitFieldType: explicit !== null && isRendererKey(explicit),\n strategyKind: resolveStrategy(element) ?? 'unknown',\n ...(fragmentBoundary !== null ? { fragmentBoundary } : {}),\n ...(targetAttribute !== null && targetAttribute.length > 0 ? { targetAttribute } : {}),\n ...(hrefField !== null && hrefField.length > 0 ? { hrefField } : {}),\n ...(srcField !== null && srcField.length > 0 ? { srcField } : {}),\n ...(altField !== null && altField.length > 0 ? { altField } : {}),\n ...(arrayTemplate !== null ? { arrayTemplate } : {}),\n ...(arraySeparator !== null ? { arraySeparator } : {}),\n ...(locale !== null && locale.length > 0 ? { locale } : {}),\n ...(owner !== undefined ? { owner } : {}),\n ...(dependsOn.length > 0 ? { dependsOn } : {}),\n ...(strategy !== null && strategy.length > 0 ? { strategy } : {}),\n ...(element.hasAttribute(BOUNDARY_ATTRIBUTE) ? { boundary: true } : {}),\n };\n }\n}\n\n/** Explicit `data-payload-type`, then element heuristics, then `text`. */\nexport function resolveFieldType(element: Element): RendererKey {\n const explicit = element.getAttribute(TYPE_ATTRIBUTE);\n if (explicit !== null && isRendererKey(explicit)) return explicit;\n if (element.hasAttribute(RICH_TEXT_ATTRIBUTE)) return 'richText';\n if (element.hasAttribute(HTML_ATTRIBUTE)) return 'html';\n if (element.hasAttribute(STRUCTURAL_ATTRIBUTE)) return 'structural-array';\n if (element.hasAttribute(ARRAY_ATTRIBUTE)) return 'array';\n if (element.tagName === 'IMG') return 'image';\n if (element.tagName === 'A') return 'url';\n if (element.tagName === 'TIME') return 'date';\n if (element.tagName === 'INPUT') {\n const inputType = (element as HTMLInputElement).type;\n if (inputType === 'checkbox') return 'checkbox';\n if (inputType === 'number') return 'number';\n if (inputType === 'date' || inputType === 'datetime-local') return 'date';\n }\n return 'text';\n}\n\nfunction alwaysTrue(): boolean {\n return true;\n}\n","/**\n * Detect an invalid async result in a synchronous extension point.\n *\n * Rejected native Promises otherwise become unhandled after the caller falls\n * back synchronously. Assimilating the result through a handled Promise keeps\n * that contract violation observable only through the runtime's explicit\n * error channel.\n */\nexport function observeThenableResult(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false;\n if (typeof (value as { readonly then?: unknown }).then !== 'function') return false;\n void Promise.resolve(value).catch(() => undefined);\n return true;\n}\n","import { observeThenableResult } from './thenable';\n\n/**\n * Diagnostics are observability, never control flow: a consumer logger may\n * throw or return a rejected thenable, and reporting a failure must not become\n * a second failure. Invocation stays synchronous for ordinary loggers.\n */\nexport function isolateDiagnostic(\n diagnostic: (...args: unknown[]) => unknown,\n): (...args: unknown[]) => void {\n return (...args): void => {\n try {\n observeThenableResult(diagnostic(...args));\n } catch {\n // Diagnostics must not become a second failure boundary.\n }\n };\n}\n\n/** Shared allocation-free default for disabled diagnostic channels. */\nexport function noopDiagnostic(): void {\n // Intentionally empty.\n}\n\n// Access, invocation and thenable inspection all happen inside the wrapper, so\n// a missing or hostile console cannot escape.\nexport const safeConsoleError = isolateDiagnostic((...args) =>\n (console.error as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleWarn = isolateDiagnostic((...args) =>\n (console.warn as (...values: unknown[]) => unknown)(...args),\n);\n\nexport const safeConsoleDebug = isolateDiagnostic((...args) =>\n // eslint-disable-next-line no-console -- best-effort development diagnostics\n (console.debug as (...values: unknown[]) => unknown)(...args),\n);\n","/**\n * Server-side merge for Payload 3.x, whose admin posts raw form values with\n * relationships as bare ids. Like the official client, the update is re-fetched\n * through the REST API with `X-Payload-HTTP-Method-Override: GET`, which\n * merges the form values into the stored document and returns it populated.\n * Only the newest request matters: a newer merge aborts the one in flight.\n */\n\nimport { isolateDiagnostic, noopDiagnostic } from './diagnostics';\n\nexport interface DataMergerOptions {\n /** Payload server origin, e.g. `https://cms.example.com`. */\n readonly serverURL: string;\n /** REST route prefix. Defaults to `/api`. */\n readonly apiRoute?: string;\n /** Population depth requested from the server. Defaults to `1`. */\n readonly depth?: number;\n readonly fetchFn?: typeof fetch;\n readonly log?: (...args: unknown[]) => void;\n}\n\nexport interface MergeRequest {\n readonly collectionSlug?: string | undefined;\n readonly globalSlug?: string | undefined;\n readonly data: Record<string, unknown>;\n readonly locale?: string | undefined;\n}\n\n/** `superseded`: a newer merge replaced this one. `unavailable`: fall back to the raw values. */\nexport type MergeResult =\n | { readonly status: 'merged'; readonly doc: Record<string, unknown> }\n | { readonly status: 'superseded' }\n | { readonly status: 'unavailable' };\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;\n }\n return false;\n}\n\nfunction isSafeSlug(value: string | undefined): value is string {\n if (\n value === undefined ||\n value.length === 0 ||\n value.length > 128 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n value.includes('?') ||\n value.includes('#') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isSafeId(value: unknown): value is string | number {\n if (typeof value === 'number') return Number.isFinite(value);\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > 512 ||\n value === '.' ||\n value === '..' ||\n value.includes('/') ||\n value.includes('\\\\') ||\n hasControlCharacter(value)\n ) {\n return false;\n }\n try {\n encodeURIComponent(value);\n return true;\n } catch {\n // A lone surrogate cannot become a URL segment.\n return false;\n }\n}\n\nexport class DataMerger {\n private readonly serverURL: string;\n private readonly apiRoute: string;\n private readonly depth: number;\n private readonly fetchFn: typeof fetch | undefined;\n private readonly log: (...args: unknown[]) => void;\n private inflight: AbortController | null = null;\n private attempt = 0;\n private destroyDepth = 0;\n\n constructor(options: DataMergerOptions) {\n this.serverURL = options.serverURL.replace(/\\/+$/, '');\n const route = options.apiRoute ?? '/api';\n this.apiRoute = route.startsWith('/') ? route : `/${route}`;\n this.depth = options.depth ?? 1;\n this.fetchFn = options.fetchFn;\n this.log = options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log);\n }\n\n /** Collections need an `id` in the form values; globals only their slug. */\n canMerge(request: MergeRequest): boolean {\n try {\n // An empty global slug means \"collection document\" on the wire.\n if (request.globalSlug) return isSafeSlug(request.globalSlug);\n if (!isSafeSlug(request.collectionSlug)) return false;\n return isSafeId(request.data['id']);\n } catch {\n return false;\n }\n }\n\n async merge(request: MergeRequest): Promise<MergeResult> {\n if (this.destroyDepth > 0) return { status: 'superseded' };\n // Claim the attempt before aborting: abort listeners and fetch shims are\n // reentrant, and a newer merge they start must win.\n const attempt = (this.attempt += 1);\n const previous = this.inflight;\n this.inflight = null;\n let controller: AbortController | null = null;\n const superseded = (): boolean => this.attempt !== attempt;\n try {\n previous?.abort();\n if (superseded()) return { status: 'superseded' };\n // `canMerge` reads the request's own values, which may be consumer getters\n // that start a newer merge before throwing.\n if (!this.canMerge(request)) {\n return superseded() ? { status: 'superseded' } : { status: 'unavailable' };\n }\n const fetchFn = this.fetchFn ?? (typeof fetch === 'function' ? fetch : undefined);\n if (fetchFn === undefined) return { status: 'unavailable' };\n controller = new AbortController();\n this.inflight = controller;\n const endpoint = request.globalSlug\n ? `globals/${encodeURIComponent(request.globalSlug)}`\n : `${encodeURIComponent(request.collectionSlug ?? '')}/${encodeURIComponent(\n String(request.data['id']),\n )}`;\n const url = `${this.serverURL}${this.apiRoute}/${endpoint}`;\n const response = await fetchFn(url, {\n method: 'POST',\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Payload-HTTP-Method-Override': 'GET',\n },\n body: JSON.stringify({\n data: request.data,\n depth: this.depth,\n // The admin already flattens locales before posting.\n flattenLocales: false,\n ...(request.locale !== undefined ? { locale: request.locale } : {}),\n }),\n signal: controller.signal,\n });\n // A fetch shim may ignore the signal; the attempt is authoritative.\n if (superseded() || isAborted(controller.signal)) return { status: 'superseded' };\n if (!response.ok) {\n this.log('merge HTTP', response.status, url);\n return { status: 'unavailable' };\n }\n const merged: unknown = await response.json();\n if (superseded() || isAborted(controller.signal)) return { status: 'superseded' };\n if (merged === null || typeof merged !== 'object' || Array.isArray(merged)) {\n this.log('merge invalid', url);\n return { status: 'unavailable' };\n }\n return { status: 'merged', doc: merged as Record<string, unknown> };\n } catch (error) {\n if (superseded() || (controller !== null && isAborted(controller.signal))) {\n return { status: 'superseded' };\n }\n this.log('merge exception', error);\n return { status: 'unavailable' };\n } finally {\n if (controller !== null && !superseded() && this.inflight === controller) {\n this.inflight = null;\n }\n }\n }\n\n /** Abort any in-flight merge. The merger stays usable across a stop/start cycle. */\n destroy(): void {\n this.attempt += 1;\n const inflight = this.inflight;\n this.inflight = null;\n this.destroyDepth += 1;\n try {\n inflight?.abort();\n } finally {\n this.destroyDepth -= 1;\n }\n }\n}\n\n/** Opaque to control-flow narrowing: an injected fetch or parser may await while another task aborts. */\nfunction isAborted(signal: AbortSignal): boolean {\n return signal.aborted;\n}\n","{\n \"name\": \"payload-live-preview\",\n \"version\": \"2.0.0-beta.0\",\n \"description\": \"Live preview for Payload CMS in Astro and any SSR/static frontend (SvelteKit, Nuxt, Next.js, plain HTML). Patches the DOM live, no rebuild.\",\n \"author\": \"relative23\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"packageManager\": \"npm@12.0.2\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./core\": {\n \"import\": {\n \"types\": \"./dist/core.d.ts\",\n \"default\": \"./dist/core.js\"\n },\n \"require\": {\n \"types\": \"./dist/core.d.cts\",\n \"default\": \"./dist/core.cjs\"\n }\n },\n \"./astro\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/index.d.ts\",\n \"default\": \"./dist/adapters/astro/index.js\"\n }\n },\n \"./nextjs\": {\n \"import\": {\n \"types\": \"./dist/adapters/nextjs/index.d.ts\",\n \"default\": \"./dist/adapters/nextjs/index.js\"\n }\n },\n \"./sveltekit\": {\n \"import\": {\n \"types\": \"./dist/adapters/sveltekit/index.d.ts\",\n \"default\": \"./dist/adapters/sveltekit/index.js\"\n }\n },\n \"./nuxt\": {\n \"import\": {\n \"types\": \"./dist/adapters/nuxt/index.d.ts\",\n \"default\": \"./dist/adapters/nuxt/index.js\"\n }\n },\n \"./codegen\": {\n \"import\": {\n \"types\": \"./dist/codegen.d.ts\",\n \"default\": \"./dist/codegen.js\"\n },\n \"require\": {\n \"types\": \"./dist/codegen.d.cts\",\n \"default\": \"./dist/codegen.cjs\"\n }\n },\n \"./codegen/astro\": {\n \"import\": {\n \"types\": \"./dist/codegen-astro.d.ts\",\n \"default\": \"./dist/codegen-astro.js\"\n }\n },\n \"./doctor\": {\n \"import\": {\n \"types\": \"./dist/doctor.d.ts\",\n \"default\": \"./dist/doctor.js\"\n }\n },\n \"./migrate\": {\n \"import\": {\n \"types\": \"./dist/migrate.d.ts\",\n \"default\": \"./dist/migrate.js\"\n }\n },\n \"./payload\": {\n \"import\": {\n \"types\": \"./dist/payload.d.ts\",\n \"default\": \"./dist/payload.js\"\n },\n \"require\": {\n \"types\": \"./dist/payload.d.cts\",\n \"default\": \"./dist/payload.cjs\"\n }\n },\n \"./server\": {\n \"import\": {\n \"types\": \"./dist/server.d.ts\",\n \"default\": \"./dist/server.js\"\n },\n \"require\": {\n \"types\": \"./dist/server.d.cts\",\n \"default\": \"./dist/server.cjs\"\n }\n },\n \"./client\": {\n \"import\": {\n \"types\": \"./dist/client.d.ts\",\n \"default\": \"./dist/client.js\"\n },\n \"require\": {\n \"types\": \"./dist/client.d.cts\",\n \"default\": \"./dist/client.cjs\"\n }\n },\n \"./structural\": {\n \"import\": {\n \"types\": \"./dist/structural.d.ts\",\n \"default\": \"./dist/structural.js\"\n },\n \"require\": {\n \"types\": \"./dist/structural.d.cts\",\n \"default\": \"./dist/structural.cjs\"\n }\n },\n \"./lexical\": {\n \"import\": {\n \"types\": \"./dist/lexical.d.ts\",\n \"default\": \"./dist/lexical.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexical.d.cts\",\n \"default\": \"./dist/lexical.cjs\"\n }\n },\n \"./plugins\": {\n \"import\": {\n \"types\": \"./dist/plugins.d.ts\",\n \"default\": \"./dist/plugins.js\"\n },\n \"require\": {\n \"types\": \"./dist/plugins.d.cts\",\n \"default\": \"./dist/plugins.cjs\"\n }\n },\n \"./fragment\": {\n \"import\": {\n \"types\": \"./dist/fragment.d.ts\",\n \"default\": \"./dist/fragment.js\"\n },\n \"require\": {\n \"types\": \"./dist/fragment.d.cts\",\n \"default\": \"./dist/fragment.cjs\"\n }\n },\n \"./astro/RichText.astro\": \"./dist/adapters/astro/RichText.astro\",\n \"./astro/PreviewBoundary.astro\": \"./dist/adapters/astro/PreviewBoundary.astro\",\n \"./astro/middleware-entry\": {\n \"import\": {\n \"types\": \"./dist/adapters/astro/middleware-entry.d.ts\",\n \"default\": \"./dist/adapters/astro/middleware-entry.js\"\n }\n }\n },\n \"bin\": {\n \"pll-codegen\": \"./dist/codegen-cli.js\",\n \"pll\": \"./dist/doctor-cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"sideEffects\": false,\n \"scripts\": {\n \"build:runtime\": \"tsx scripts/build-runtime.ts\",\n \"build\": \"npm run build:runtime && tsx scripts/build-dist.ts && npm run build:assets && npm run test:bundle && npm run test:treeshake && npm run test:edge\",\n \"build:assets\": \"node -e \\\"const fs=require('node:fs');for(const f of ['RichText','PreviewBoundary'])fs.copyFileSync('src/adapters/astro/'+f+'.astro','dist/adapters/astro/'+f+'.astro')\\\"\",\n \"dev\": \"tsup --watch\",\n \"pretest\": \"npm run build:runtime\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:unit\": \"vitest run tests/unit\",\n \"test:integration\": \"vitest run tests/integration\",\n \"test:e2e\": \"playwright test\",\n \"check:fixtures\": \"tsx scripts/check-fixture-freshness.ts\",\n \"test:e2e:real-payload\": \"playwright test --config playwright.real-payload.config.ts\",\n \"test:a11y\": \"playwright test tests/e2e/specs/accessibility.spec.ts\",\n \"test:soak\": \"playwright test --config playwright.soak.config.ts\",\n \"test:browser-bench\": \"playwright test --config playwright.bench.config.ts\",\n \"test:bench\": \"vitest bench tests/benchmarks\",\n \"test:bench:codspeed\": \"vitest bench --run --config vitest.bench.config.ts\",\n \"test:bundle\": \"tsx scripts/check-bundle-size.ts\",\n \"test:treeshake\": \"tsx scripts/check-tree-shaking.ts\",\n \"test:edge\": \"NODE_OPTIONS='--experimental-vm-modules --no-warnings' tsx scripts/check-edge-runtime.ts\",\n \"compat:check\": \"tsx scripts/compat-table.ts --check\",\n \"compat:write\": \"tsx scripts/compat-table.ts --write\",\n \"test:package\": \"tsx scripts/check-package.ts\",\n \"audit:gate\": \"tsx scripts/audit-gate.ts\",\n \"test:smoke\": \"tsx scripts/post-publish-smoke.ts\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:coverage:diff\": \"tsx scripts/coverage-policy.ts\",\n \"test:policy\": \"tsx scripts/test-policy.ts\",\n \"test:architecture\": \"tsx scripts/architecture-policy.ts && tsx scripts/workflow-contracts.ts && tsx scripts/docs-contracts.ts && knip --no-progress --treat-config-hints-as-errors\",\n \"test:property\": \"vitest run tests/unit/property\",\n \"test:mutation\": \"stryker run stryker.config.js\",\n \"test:mutation:policy:pr\": \"tsx scripts/mutation-policy.ts --policy quality/mutation-policy-pr.json --report test-results/stryker-pr.json\",\n \"test:mutation:policy\": \"tsx scripts/mutation-policy.ts\",\n \"test:leak\": \"node --expose-gc --import tsx scripts/leak-soak.ts\",\n \"test:leak:quick\": \"node --expose-gc --import tsx scripts/leak-soak.ts --quick\",\n \"api:update\": \"npm run build && tsx scripts/check-package.ts --update-api-reports\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"lint:fix\": \"eslint . --fix\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --write \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"format:check\": \"prettier --check \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\" \\\"scripts/**/*.ts\\\" \\\"*.{js,cjs,mjs,ts,json,jsonc,yml,yaml,md}\\\" \\\"quality/**/*.json\\\" \\\"docs/**/*.md\\\" \\\"type-tests/**/*.md\\\" \\\".prettierrc.json\\\" \\\".changeset/*.{json,md}\\\" \\\".github/**/*.{yml,yaml,json}\\\" \\\"examples/**/*.{ts,tsx,js,cjs,mjs,json}\\\" && prettier --check \\\"type-tests/packed/*.fixture\\\" --parser typescript\",\n \"check\": \"npm run typecheck && npm run lint && npm run test:policy && npm run test:architecture && npm run test\",\n \"prepublishOnly\": \"npm run build && npm run check && npm run format:check && npm run test:package\",\n \"changeset\": \"changeset\",\n \"version\": \"changeset version && tsx scripts/sync-lockfile-metadata.ts\",\n \"release\": \"tsx scripts/publish-artifact.ts\",\n \"test:docs\": \"tsx scripts/docs-contracts.ts\"\n },\n \"devDependencies\": {\n \"@arethetypeswrong/cli\": \"^0.18.5\",\n \"@axe-core/playwright\": \"^4.13.0\",\n \"@changesets/cli\": \"^2.31.1\",\n \"@codspeed/vitest-plugin\": \"^5.7.1\",\n \"@eslint/js\": \"^10.0.1\",\n \"@fast-check/vitest\": \"^0.4.1\",\n \"@microsoft/api-extractor\": \"^7.58.12\",\n \"@playwright/test\": \"^1.62.1\",\n \"@stryker-mutator/core\": \"^9.6.1\",\n \"@stryker-mutator/vitest-runner\": \"^9.6.1\",\n \"@types/jsdom\": \"^30.0.0\",\n \"@types/node\": \"^22.20.1\",\n \"@vitest/coverage-v8\": \"^4.1.10\",\n \"esbuild\": \"^0.28.2\",\n \"eslint\": \"^10.8.1\",\n \"fast-check\": \"^4.9.0\",\n \"globals\": \"^17.11.0\",\n \"jsdom\": \"^29.1.1\",\n \"knip\": \"^6.32.2\",\n \"prettier\": \"^3.9.6\",\n \"publint\": \"^0.3.23\",\n \"terser\": \"^5.46.1\",\n \"ts-morph\": \"^28.0.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.12\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.67.0\",\n \"vite\": \"^7.3.6\",\n \"vitest\": \"^4.1.10\",\n \"yaml\": \"^2.9.0\"\n },\n \"overrides\": {\n \"qs\": \"6.15.3\",\n \"tsup\": {\n \"esbuild\": \"0.28.2\"\n }\n },\n \"allowScripts\": {\n \"esbuild@0.28.2\": true,\n \"fsevents@2.3.2\": false,\n \"fsevents@2.3.3\": false\n },\n \"keywords\": [\n \"astro\",\n \"astro-payload\",\n \"astro-cms\",\n \"astro-integration\",\n \"astro-live-preview\",\n \"payload\",\n \"payload-cms\",\n \"payload-live-preview\",\n \"payload-plugin\",\n \"live-preview\",\n \"preview\",\n \"cms\",\n \"headless\",\n \"headless-cms\",\n \"lexical\",\n \"sveltekit\",\n \"nuxt\",\n \"nextjs\",\n \"ssr\",\n \"framework-agnostic\"\n ],\n \"peerDependencies\": {\n \"astro\": \">=4.0.0 <8.0.0\",\n \"ts-morph\": \"^28.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"astro\": {\n \"optional\": true\n },\n \"ts-morph\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"provenance\": true\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/relative23/payload-live-preview.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/relative23/payload-live-preview/issues\"\n },\n \"homepage\": \"https://github.com/relative23/payload-live-preview#readme\"\n}\n","/** The package version, read from package.json so the entries and the inline runtime cannot drift. */\n\nimport pkg from '../package.json' with { type: 'json' };\n\nexport const VERSION: string = pkg.version;\n","/**\n * What the peer does, derived from the capabilities its messages showed —\n * the runtime never asks which Payload version it is talking to. Unknown\n * until the admin reveals its shape. See ADR 0010.\n */\nimport type { ProtocolCapability } from './protocol-version';\n\nexport type ProtocolProfileName = 'unknown' | 'payload-2' | 'payload-3';\n\nexport interface ProtocolProfile {\n readonly name: ProtocolProfileName;\n /** Where field types come from. */\n readonly fieldTyping: 'schema' | 'heuristic';\n /**\n * Who populates relationships. Payload 2.x's admin posts populated data\n * (it merges client-side with `fieldSchemaJSON`); Payload 3.x posts raw\n * form values and the runtime asks the REST API when `serverURL` is set.\n */\n readonly populatesRelationships: 'admin' | 'server';\n /** Whether the peer reports document saves and relationship edits. */\n readonly documentEvents: boolean;\n}\n\nconst PAYLOAD_2: ProtocolProfile = {\n name: 'payload-2',\n fieldTyping: 'schema',\n populatesRelationships: 'admin',\n documentEvents: false,\n};\nconst PAYLOAD_3: ProtocolProfile = {\n name: 'payload-3',\n fieldTyping: 'heuristic',\n populatesRelationships: 'server',\n documentEvents: true,\n};\nconst UNKNOWN: ProtocolProfile = {\n name: 'unknown',\n fieldTyping: 'heuristic',\n populatesRelationships: 'server',\n documentEvents: false,\n};\n\n/**\n * `schema-json` on the wire is the Payload 2.x signature: 3.x removed\n * `fieldSchemaJSON`. Document or relationship events are 3.x-only. Until\n * either shows, the peer is unknown and treated like 3.x for merging — the\n * conservative choice, because a needless REST merge costs a request while\n * a missing one loses populated relationships.\n */\nexport function detectProtocolProfile(observed: ReadonlySet<ProtocolCapability>): ProtocolProfile {\n if (observed.has('schema-json')) return PAYLOAD_2;\n if (observed.has('document-events') || observed.has('relationship-events')) return PAYLOAD_3;\n return UNKNOWN;\n}\n","/** Shape guards for the messages the bus accepts. `null` counts as absent, as JSON bridges send it. */\n\nimport type {\n PayloadDocumentEventMessage,\n PayloadFieldSchema,\n PayloadLivePreviewMessage,\n} from '@/types/payload-protocol';\nimport { parseFieldSchema } from '@schema/parser';\n\nexport function isObjectMessage(value: unknown): value is { type: string } {\n return (\n typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'\n );\n}\n\n/** A `payload-live-preview` message: `data` a plain object when present, scalars of the right type or absent. */\nexport function isLivePreviewMessage(value: { type: string }): value is PayloadLivePreviewMessage {\n const v = value as Record<string, unknown>;\n if (v['data'] !== undefined && v['data'] !== null && !isPlainObject(v['data'])) return false;\n return (\n optionalTypeOk(v['fieldSchemaJSON'], (x) => Array.isArray(x)) &&\n optionalTypeOk(v['globalSlug'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['collectionSlug'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['locale'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['ready'], (x) => typeof x === 'boolean') &&\n optionalTypeOk(v['previewToken'], (x) => typeof x === 'string') &&\n optionalTypeOk(v['protocolVersion'], (x) => typeof x === 'number')\n );\n}\n\n/** The non-empty field name of a `payload-live-preview-focus` message, else `undefined`. */\nexport function focusFieldOf(value: { type: string }): string | undefined {\n const field = (value as Record<string, unknown>)['field'];\n return typeof field === 'string' && field.length > 0 ? field : undefined;\n}\n\n/** Stock Payload sends only the `type`; custom senders may add the typed fields (omitted, never `null`). */\nexport function isDocumentEventMessage(value: {\n type: string;\n}): value is PayloadDocumentEventMessage {\n const v = value as Record<string, unknown>;\n return (\n optionalFieldOk(v['action'], (x) => x === 'updated' || x === 'created' || x === 'deleted') &&\n optionalFieldOk(v['slug'], (x) => typeof x === 'string') &&\n optionalFieldOk(\n v['id'],\n (x) => typeof x === 'string' || (typeof x === 'number' && Number.isFinite(x)),\n )\n );\n}\n\nfunction optionalFieldOk(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || check(value);\n}\n\nfunction optionalTypeOk(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || value === null || check(value);\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as object | null;\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\n\nconst NULL_AS_ABSENT_FIELDS = [\n 'data',\n 'fieldSchemaJSON',\n 'globalSlug',\n 'collectionSlug',\n 'locale',\n 'ready',\n 'previewToken',\n 'protocolVersion',\n] as const satisfies readonly (keyof PayloadLivePreviewMessage)[];\n\n/**\n * Drop `null` optionals so downstream sees the strict public type, and parse\n * the field schema entry by entry (malformed entries are dropped). Unknown\n * fields stay, for protocol evolution.\n */\nexport function normalizeLivePreviewMessage(\n message: PayloadLivePreviewMessage,\n): PayloadLivePreviewMessage {\n const normalized = { ...message };\n for (const field of NULL_AS_ABSENT_FIELDS) {\n const wireValue: unknown = Reflect.get(normalized, field);\n if (wireValue === null) Reflect.deleteProperty(normalized, field);\n }\n if (!Array.isArray(normalized.fieldSchemaJSON)) return normalized;\n let fieldSchemaJSON: readonly PayloadFieldSchema[];\n try {\n fieldSchemaJSON = parseFieldSchema(normalized.fieldSchemaJSON);\n } catch {\n fieldSchemaJSON = [];\n }\n return { ...normalized, fieldSchemaJSON };\n}\n","/**\n * postMessage ingress: origin and source checks, per-type shape guards, the\n * ordered preview-token validation queue, and the `ready` handshake. The bus\n * never throws; a rejected message is dropped or reported via `onInvalid`.\n * Consumer callbacks may detach or re-attach the bus synchronously, so\n * anything that runs after one re-checks the generation it started in.\n * See ADR 0004.\n */\n\nimport type {\n PayloadDocumentEventMessage,\n PayloadLivePreviewMessage,\n} from '@/types/payload-protocol';\nimport {\n focusFieldOf,\n isDocumentEventMessage,\n isLivePreviewMessage,\n isObjectMessage,\n isPlainObject,\n normalizeLivePreviewMessage,\n} from './message-guards';\nimport { LIBRARY_PROTOCOL_VERSION } from './protocol-version';\nimport { observeThenableResult } from './thenable';\n\nexport type OriginMatcher = (origin: string) => boolean;\n\n/** Identity of a data-bearing update: `revision` is monotonic, `generation` names the listener attachment. */\nexport interface MessageRevision {\n readonly revision: number;\n readonly generation: number;\n}\n\nexport type InvalidReason = 'origin' | 'shape' | 'type' | 'token' | 'source';\n\nexport interface MessageHandlers {\n /** A validated update; data-bearing ones carry their revision, ready handshakes do not. */\n readonly onUpdate: (\n msg: PayloadLivePreviewMessage,\n origin: string,\n messageRevision?: MessageRevision,\n ) => void;\n readonly onDocumentEvent: (msg: PayloadDocumentEventMessage, origin: string) => void;\n /** The admin reports the cursor moved into a field (reveal tier 2). */\n readonly onFocusField?: (field: string, origin: string) => void;\n readonly onInvalid?: (reason: InvalidReason, origin: string) => void;\n /** `'parent-or-opener'` refuses every window but the framing/opening one, even from an allowed origin. */\n readonly sourcePolicy?: 'any' | 'parent-or-opener';\n /**\n * Gate for data-bearing updates. Verdicts commit in arrival order, so an\n * earlier update is dispatched before a later one even when its validation\n * resolves later; an error counts as rejection.\n */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n}\n\ninterface PendingValidation {\n readonly generation: number;\n readonly message: PayloadLivePreviewMessage;\n readonly origin: string;\n readonly messageRevision: MessageRevision | undefined;\n settled: boolean;\n approved: boolean;\n}\n\n/** Compact the consumed queue prefix only once it is both large and at least half the array. */\nconst QUEUE_COMPACTION_THRESHOLD = 1_024;\n\nexport class MessageBus {\n private readonly matcher: OriginMatcher;\n private readonly handlers: MessageHandlers;\n private boundListener: ((event: MessageEvent) => void) | undefined = undefined;\n private attachedTarget: Window | undefined = undefined;\n private generation = 0;\n private revision = 0;\n private queue: PendingValidation[] = [];\n private queueHead = 0;\n\n constructor(matcher: OriginMatcher, handlers: MessageHandlers) {\n this.matcher = matcher;\n this.handlers = handlers;\n }\n\n /** Start listening on `target`. Idempotent. */\n attach(target: Window = window): void {\n if (this.attachedTarget !== undefined) return;\n let committed = false;\n const listener = (event: MessageEvent): void => {\n // Each attachment owns its listener; a stale one must not borrow the new generation.\n if (!committed || this.boundListener !== listener) return;\n const generation = this.generation;\n try {\n this.receive(event, generation);\n } catch {\n // A synthetic event can carry throwing accessors; that is a shape failure.\n let origin: string;\n try {\n origin = event.origin;\n } catch {\n origin = '';\n }\n this.reportInvalid('shape', origin, generation);\n }\n };\n this.generation += 1;\n this.resetQueue();\n this.attachedTarget = target;\n this.boundListener = listener;\n try {\n target.addEventListener('message', listener);\n } catch (error) {\n // Invalidate before rollback: a hook may already have attached a newer generation.\n if (this.boundListener === listener) {\n this.attachedTarget = undefined;\n this.boundListener = undefined;\n this.resetQueue();\n }\n try {\n target.removeEventListener('message', listener);\n } catch {\n // Keep the original failure.\n }\n throw error;\n }\n if (this.boundListener === listener) {\n committed = true;\n } else {\n try {\n target.removeEventListener('message', listener);\n } catch {\n // The listener is identity-gated above even if removal fails.\n }\n }\n }\n\n /** Stop listening. Idempotent. */\n detach(): void {\n const target = this.attachedTarget;\n const listener = this.boundListener;\n if (target === undefined || listener === undefined) return;\n // Invalidate first so a listener already on the stack sees an obsolete generation.\n this.attachedTarget = undefined;\n this.boundListener = undefined;\n this.resetQueue();\n target.removeEventListener('message', listener);\n }\n\n /** Invalidate pending validations while staying attached (heartbeat expiry). */\n advanceGeneration(): boolean {\n if (this.attachedTarget === undefined) return false;\n this.generation += 1;\n this.resetQueue();\n return true;\n }\n\n /** Post the `ready` handshake to every target for every origin. */\n static sendReady(targets: readonly Window[], origins: readonly string[]): void {\n if (targets.length === 0 || origins.length === 0) return;\n const payload: PayloadLivePreviewMessage = {\n type: 'payload-live-preview',\n ready: true,\n protocolVersion: LIBRARY_PROTOCOL_VERSION,\n };\n for (const target of targets) {\n for (const origin of origins) {\n try {\n target.postMessage(payload, origin);\n } catch {\n // A malformed origin is the consumer's configuration problem.\n }\n }\n }\n }\n\n private receive(event: MessageEvent, generation: number): void {\n if (!this.isCurrentGeneration(generation)) return;\n const origin = event.origin;\n if (!this.matchesOrigin(origin, generation)) {\n this.reportInvalid('origin', origin, generation);\n return;\n }\n if (!this.matchesSource(event)) {\n this.reportInvalid('source', origin, generation);\n return;\n }\n const data: unknown = event.data;\n if (!isObjectMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n switch (data.type) {\n case 'payload-live-preview':\n if (!isLivePreviewMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n this.dispatchUpdate(normalizeLivePreviewMessage(data), origin, generation);\n return;\n case 'payload-document-event':\n if (!isDocumentEventMessage(data)) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n this.invokeHandler(generation, this.handlers.onDocumentEvent, data, origin);\n return;\n case 'payload-live-preview-focus': {\n const field = focusFieldOf(data);\n if (field === undefined) {\n this.reportInvalid('shape', origin, generation);\n return;\n }\n const onFocusField = this.handlers.onFocusField;\n if (onFocusField !== undefined) this.invokeHandler(generation, onFocusField, field, origin);\n return;\n }\n default:\n this.reportInvalid('type', origin, generation);\n }\n }\n\n private dispatchUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n generation: number,\n ): void {\n const hasUpdateData = isPlainObject(message.data);\n if (!this.isCurrentGeneration(generation)) return;\n // A shape-valid data update consumes its revision before validation; a rejected token leaves a gap.\n const messageRevision = hasUpdateData\n ? { generation, revision: (this.revision += 1) }\n : undefined;\n const validator = this.handlers.validateToken;\n if (!this.isCurrentGeneration(generation)) return;\n if (validator === undefined) {\n this.commitUpdate(message, origin, generation, messageRevision);\n return;\n }\n // The data-less ready handshake carries no token and passes, so the admin learns we listen.\n if (message.ready === true && message.data === undefined) {\n this.commitUpdate(message, origin, generation, undefined);\n return;\n }\n const pending: PendingValidation = {\n generation,\n message,\n origin,\n messageRevision,\n settled: false,\n approved: false,\n };\n this.queue.push(pending);\n let verdict: unknown;\n try {\n // Invoked eagerly; only the commit waits for earlier queue entries.\n verdict = validator(message.previewToken, origin);\n } catch {\n this.settleValidation(pending, false);\n return;\n }\n if (typeof verdict === 'boolean') {\n this.settleValidation(pending, verdict);\n return;\n }\n // Assimilate any thenable; only literal `true` approves.\n void Promise.resolve(verdict).then(\n (approved) => {\n this.settleValidation(pending, approved === true);\n },\n () => {\n this.settleValidation(pending, false);\n },\n );\n }\n\n private settleValidation(pending: PendingValidation, approved: boolean): void {\n if (!this.isCurrentGeneration(pending.generation)) return;\n pending.approved = approved;\n pending.settled = true;\n this.drainQueue(pending.generation);\n }\n\n private drainQueue(generation: number): void {\n while (this.isCurrentGeneration(generation)) {\n const pending = this.queue[this.queueHead];\n if (pending === undefined) return;\n // The matcher may have narrowed since ingress (origin lock); an obsolete\n // origin must not hold the queue head and block the locked origin's work.\n if (!this.matchesOrigin(pending.origin, generation)) {\n if (!this.dequeue(pending)) continue;\n this.reportInvalid('origin', pending.origin, pending.generation);\n continue;\n }\n if (!pending.settled) return;\n if (!this.dequeue(pending)) continue;\n if (pending.approved) {\n this.commitUpdate(\n pending.message,\n pending.origin,\n pending.generation,\n pending.messageRevision,\n );\n } else {\n this.reportInvalid('token', pending.origin, pending.generation);\n }\n }\n }\n\n private commitUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n generation: number,\n messageRevision: MessageRevision | undefined,\n ): void {\n if (!this.isCurrentGeneration(generation)) return;\n if (messageRevision === undefined) {\n this.invokeHandler(generation, this.handlers.onUpdate, message, origin);\n } else {\n this.invokeHandler(generation, this.handlers.onUpdate, message, origin, messageRevision);\n }\n }\n\n private reportInvalid(reason: InvalidReason, origin: string, generation: number): void {\n if (!this.isCurrentGeneration(generation)) return;\n const onInvalid = this.handlers.onInvalid;\n if (onInvalid !== undefined) this.invokeHandler(generation, onInvalid, reason, origin);\n }\n\n /** Under `'parent-or-opener'`, whether the event came from the attached window's parent or opener. */\n private matchesSource(event: MessageEvent): boolean {\n if (this.handlers.sourcePolicy !== 'parent-or-opener') return true;\n const target = this.attachedTarget;\n if (target === undefined) return false;\n try {\n const source = event.source;\n if (source === null) return false;\n const parent = target.parent;\n if (parent !== target && source === parent) return true;\n const opener: unknown = target.opener;\n return opener !== null && opener !== undefined && source === opener;\n } catch {\n return false;\n }\n }\n\n /** Fail-closed: only literal `true` from the matcher, and only within the generation it ran in. */\n private matchesOrigin(origin: string, generation: number): boolean {\n if (!this.isCurrentGeneration(generation)) return false;\n try {\n const approved: unknown = this.matcher(origin);\n return approved === true && this.isCurrentGeneration(generation);\n } catch {\n return false;\n }\n }\n\n /** Callbacks run only in a current generation and must not unwind the listener or the drain. */\n private invokeHandler<TArgs extends unknown[]>(\n generation: number,\n handler: (...args: TArgs) => unknown,\n ...args: TArgs\n ): void {\n if (!this.isCurrentGeneration(generation)) return;\n try {\n observeThenableResult(handler(...args));\n } catch {\n // Isolated by contract.\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return this.attachedTarget !== undefined && this.generation === generation;\n }\n\n /** Advance the head past `expected`, unless a matcher reset the queue meanwhile. */\n private dequeue(expected: PendingValidation): boolean {\n if (this.queue[this.queueHead] !== expected) return false;\n this.queueHead += 1;\n if (this.queueHead === this.queue.length) {\n this.resetQueue();\n return true;\n }\n if (this.queueHead >= QUEUE_COMPACTION_THRESHOLD && this.queueHead * 2 >= this.queue.length) {\n this.queue = this.queue.slice(this.queueHead);\n this.queueHead = 0;\n }\n return true;\n }\n\n private resetQueue(): void {\n this.queue = [];\n this.queueHead = 0;\n }\n}\n","/**\n * Mutation and intersection observers: ask the host to rebuild the cache when\n * bindings appear, vanish or change metadata, and track which bound elements\n * are in the viewport so off-screen writes can wait. Kept apart from cache and\n * scheduler so tests can run without the browser observer APIs.\n */\n\nimport { BINDING_ATTRIBUTES, FIELD_ATTRIBUTE, OWNER_ATTRIBUTE } from './cache';\n\nexport interface ObserverCallbacks {\n readonly onStructuralChange: () => void;\n readonly onVisibilityChange: (element: Element, isVisible: boolean) => void;\n}\n\nexport interface ObserverOptions {\n /** Debounce for mutation batches in ms. Default 100. */\n readonly mutationDebounceMs?: number;\n /** `rootMargin` for the IntersectionObserver. Default `200px`. */\n readonly intersectionRootMargin?: string;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 100;\nconst DEFAULT_ROOT_MARGIN = '200px';\n/** `nodeType` is stable across realms; the global `Node` constructor is not. */\nconst ELEMENT_NODE = 1;\n\nexport class ObserverManager {\n private readonly callbacks: ObserverCallbacks;\n private readonly debounceMs: number;\n private readonly rootMargin: string;\n private readonly visible = new Set<Element>();\n private mutation: MutationObserver | null = null;\n private intersection: IntersectionObserver | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Bumped by every start/stop so deliveries from an older lifetime are inert. */\n private generation = 0;\n\n constructor(callbacks: ObserverCallbacks, options: ObserverOptions = {}) {\n this.callbacks = callbacks;\n this.debounceMs = options.mutationDebounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.rootMargin = options.intersectionRootMargin ?? DEFAULT_ROOT_MARGIN;\n }\n\n /** Observe `root`; a repeated start hands over cleanly. */\n start(root: Node): void {\n const previousGeneration = this.generation;\n this.stop();\n const generation = previousGeneration + 1;\n // A disconnect hook may have started a newer generation; it owns the lifecycle.\n if (this.generation !== generation) return;\n let mutation: MutationObserver | null = null;\n let intersection: IntersectionObserver | null = null;\n try {\n mutation = new MutationObserver((mutations) => {\n this.handleMutations(mutations, generation);\n });\n // Both resources exist before either is live, so a missing IntersectionObserver leaves nothing behind.\n intersection = new IntersectionObserver(\n (entries) => {\n this.handleIntersection(entries, generation);\n },\n { rootMargin: this.rootMargin, threshold: 0 },\n );\n mutation.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [...BINDING_ATTRIBUTES],\n });\n } catch (error) {\n mutation?.disconnect();\n intersection?.disconnect();\n throw error;\n }\n if (this.generation !== generation) {\n mutation.disconnect();\n intersection.disconnect();\n return;\n }\n this.mutation = mutation;\n this.intersection = intersection;\n }\n\n observeElement(element: Element): void {\n this.intersection?.observe(element);\n }\n\n unobserveElement(element: Element): void {\n this.intersection?.unobserve(element);\n this.visible.delete(element);\n }\n\n /** Seed visibility (tests). */\n markVisible(element: Element, visible: boolean): void {\n if (visible) this.visible.add(element);\n else this.visible.delete(element);\n }\n\n isVisible(element: Element): boolean {\n return this.visible.has(element);\n }\n\n /** Disconnect everything; safe to repeat. */\n stop(): void {\n // Invalidate first so queued deliveries and the timer are inert before disconnecting.\n this.generation += 1;\n const timer = this.debounceTimer;\n const mutation = this.mutation;\n const intersection = this.intersection;\n this.debounceTimer = null;\n this.mutation = null;\n this.intersection = null;\n this.visible.clear();\n if (timer !== null) clearTimeout(timer);\n try {\n mutation?.disconnect();\n } finally {\n intersection?.disconnect();\n }\n }\n\n private handleMutations(mutations: readonly MutationRecord[], generation: number): void {\n if (!this.isCurrentGeneration(generation) || !hasStructuralImpact(mutations)) return;\n if (this.debounceTimer !== null) clearTimeout(this.debounceTimer);\n const timer = setTimeout(() => {\n if (!this.isCurrentGeneration(generation) || this.debounceTimer !== timer) return;\n this.debounceTimer = null;\n this.callbacks.onStructuralChange();\n }, this.debounceMs);\n this.debounceTimer = timer;\n }\n\n private handleIntersection(\n entries: readonly IntersectionObserverEntry[],\n generation: number,\n ): void {\n for (const entry of entries) {\n if (!this.isCurrentGeneration(generation)) return;\n const { target } = entry;\n if (entry.isIntersecting) {\n if (this.visible.has(target)) continue;\n this.visible.add(target);\n this.callbacks.onVisibilityChange(target, true);\n } else if (this.visible.has(target)) {\n this.visible.delete(target);\n this.callbacks.onVisibilityChange(target, false);\n }\n }\n }\n\n private isCurrentGeneration(generation: number): boolean {\n return this.generation === generation && this.intersection !== null;\n }\n}\n\n/** Whether a mutation batch can change what is bound; unrelated DOM activity never rebuilds. */\nfunction hasStructuralImpact(mutations: readonly MutationRecord[]): boolean {\n for (const m of mutations) {\n if (\n m.type === 'attributes' &&\n m.attributeName !== null &&\n BINDING_ATTRIBUTES.includes(m.attributeName)\n ) {\n // The field and owner attributes matter anywhere; other metadata (notably\n // the native `type`) only on an element that is a binding.\n if (\n m.attributeName === FIELD_ATTRIBUTE ||\n m.attributeName === OWNER_ATTRIBUTE ||\n (m.target.nodeType === ELEMENT_NODE && (m.target as Element).hasAttribute(FIELD_ATTRIBUTE))\n ) {\n return true;\n }\n }\n for (const node of m.addedNodes) if (containsTrackedElement(node)) return true;\n for (const node of m.removedNodes) if (containsTrackedElement(node)) return true;\n }\n return false;\n}\n\nfunction containsTrackedElement(node: Node): boolean {\n if (node.nodeType !== ELEMENT_NODE) return false;\n const element = node as Element;\n return (\n element.hasAttribute(FIELD_ATTRIBUTE) || element.querySelector(`[${FIELD_ATTRIBUTE}]`) !== null\n );\n}\n","/** Connection status and the heartbeat that decides a disconnect. */\n\nexport type ConnectionStatus = 'disconnected' | 'connecting' | 'connected';\n\nexport interface HeartbeatOptions {\n /**\n * Silence before declaring a timeout. `0` disables the timer, which is right\n * for the stock Payload protocol: it sends messages only on edits, so any\n * idle timeout would report false disconnects.\n */\n readonly timeoutMs?: number;\n readonly onTimeout: () => void;\n}\n\nexport class HeartbeatTimer {\n private readonly timeoutMs: number;\n private readonly onTimeout: () => void;\n private handle: ReturnType<typeof setTimeout> | null = null;\n private lastKick = 0;\n\n constructor(options: HeartbeatOptions) {\n this.timeoutMs = options.timeoutMs ?? 0;\n this.onTimeout = options.onTimeout;\n }\n\n /** Called on every valid message; re-arms the timeout. */\n kick(): void {\n this.lastKick = Date.now();\n if (this.timeoutMs <= 0) return;\n if (this.handle !== null) clearTimeout(this.handle);\n const handle = setTimeout(() => {\n if (this.handle !== handle) return;\n this.handle = null;\n this.onTimeout();\n }, this.timeoutMs);\n this.handle = handle;\n }\n\n stop(): void {\n if (this.handle === null) return;\n clearTimeout(this.handle);\n this.handle = null;\n }\n\n get lastKickAt(): number {\n return this.lastKick;\n }\n\n get pending(): boolean {\n return this.handle !== null;\n }\n}\n\nexport class ConnectionState {\n private current: ConnectionStatus = 'disconnected';\n\n get status(): ConnectionStatus {\n return this.current;\n }\n\n /** Returns whether the status changed. */\n markConnected(): boolean {\n return this.transition('connected');\n }\n\n markDisconnected(): boolean {\n return this.transition('disconnected');\n }\n\n private transition(next: ConnectionStatus): boolean {\n if (this.current === next) return false;\n this.current = next;\n return true;\n }\n}\n","/**\n * Document ownership for bindings. A field name alone cannot identify a\n * binding on a page that previews several documents — `title` may belong to a\n * global, to shared SEO metadata and to every card at once. An owner marker\n * names the document a subtree belongs to, as a plain comparable string:\n * `global:<slug>`, `collection:<slug>`, `collection:<slug>:<id>`.\n */\n\n/** Identity of the document an incoming message describes. */\nexport interface MessageDocumentIdentity {\n readonly globalSlug?: string | undefined;\n readonly collectionSlug?: string | undefined;\n /** Primary key of the edited document, when the payload carries one. */\n readonly documentId?: string | undefined;\n}\n\n/** Owner key naming one Payload global. */\nexport function globalOwnerKey(slug: string): string {\n return `global:${slug}`;\n}\n\n/** Owner key for a collection; without an id it claims every document of it. */\nexport function collectionOwnerKey(slug: string, documentId?: string): string {\n return documentId === undefined || documentId === ''\n ? `collection:${slug}`\n : `collection:${slug}:${documentId}`;\n}\n\nfunction nonEmpty(value: string | undefined): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * Owner keys this message may address, or `null` when it carries no usable\n * identity — the runtime treats that as fail-closed rather than guessing. A\n * marker naming an id stays unreachable while the id is unknown: an unproven\n * identity must not satisfy an exact claim.\n */\nexport function messageOwnerKeys(identity: MessageDocumentIdentity): readonly string[] | null {\n if (nonEmpty(identity.globalSlug)) return [globalOwnerKey(identity.globalSlug)];\n if (!nonEmpty(identity.collectionSlug)) return null;\n const collectionKey = collectionOwnerKey(identity.collectionSlug);\n return nonEmpty(identity.documentId)\n ? [collectionKey, collectionOwnerKey(identity.collectionSlug, identity.documentId)]\n : [collectionKey];\n}\n\n/** Whether a binding may receive an update addressed to `keys`; an unowned binding never may. */\nexport function isBindingInScope(\n owner: string | undefined,\n keys: readonly string[] | null,\n): boolean {\n if (keys === null || owner === undefined) return false;\n return keys.includes(owner);\n}\n\n/** The document id Payload sends alongside the edited values; only scalars prove an identity. */\nexport function readDocumentId(fields: Record<string, unknown>): string | undefined {\n const id: unknown = fields['id'];\n if (typeof id === 'string' && id.length > 0) return id;\n if (typeof id === 'number' && Number.isFinite(id)) return String(id);\n return undefined;\n}\n","/** Field-path resolution for bindings and sibling-field metadata, prototype-safe. */\n\nconst BLOCKED_KEYS: ReadonlySet<string> = new Set(['__proto__', 'prototype', 'constructor']);\n\n/**\n * Resolve a dotted field path, preferring a `_<locale>` suffix when one is\n * active. Prototype-chain properties and pollution-prone segments never resolve.\n */\nexport function resolveFieldValue(\n fields: Record<string, unknown>,\n path: string,\n locale: string | undefined,\n preferLocale = false,\n): unknown {\n if (preferLocale && locale !== undefined) {\n const localized = readOwn(fields, `${path}_${locale}`);\n if (localized !== undefined) return localized;\n }\n const direct = readOwn(fields, path);\n if (direct !== undefined) return direct;\n\n if (path.includes('.')) {\n let current: unknown = fields;\n let resolved = true;\n for (const segment of path.split('.')) {\n if (BLOCKED_KEYS.has(segment) || current === null || typeof current !== 'object') {\n resolved = false;\n break;\n }\n current = readOwn(current as Record<string, unknown>, segment);\n if (current === undefined) {\n resolved = false;\n break;\n }\n }\n if (resolved) return current;\n }\n\n return locale === undefined ? undefined : readOwn(fields, `${path}_${locale}`);\n}\n\nfunction readOwn(object: Record<string, unknown>, key: string): unknown {\n if (BLOCKED_KEYS.has(key) || !Object.prototype.hasOwnProperty.call(object, key)) {\n return undefined;\n }\n return object[key];\n}\n","/**\n * LP0201: a scalar field arrived for which the page has no binding. The usual\n * cause is a template that renders the anchor only when the field is non-empty.\n */\n\nimport { isBindingInScope } from './binding-owner';\nimport type { ElementCache } from './cache';\n\n/** Document fields Payload ships in every update that nobody binds to. */\nconst SYSTEM_FIELD_NAMES: ReadonlySet<string> = new Set([\n 'id',\n '_id',\n 'createdAt',\n 'updatedAt',\n 'createdBy',\n 'updatedBy',\n '_status',\n 'globalType',\n 'collection',\n 'locale',\n 'localized',\n]);\n\nexport interface OrphanDiagnosticContext {\n readonly cache: ElementCache;\n readonly warned: Set<string>;\n readonly warn: (...args: unknown[]) => void;\n}\n\nexport function diagnoseOrphanFields(\n context: OrphanDiagnosticContext,\n fields: Readonly<Record<string, unknown>>,\n locale: string | undefined,\n ownerKeys: readonly string[] | null | false,\n): void {\n const { cache, warned, warn } = context;\n if (cache.fieldCount === 0) return;\n // With scoping on, a page that renders none of this document is normal.\n if (ownerKeys !== false && !ownsAnyBinding(cache, ownerKeys)) return;\n let localisedNames: Set<string> | undefined;\n for (const [rawName, value] of Object.entries(fields)) {\n if (warned.has(rawName) || SYSTEM_FIELD_NAMES.has(rawName)) continue;\n if (!isBindableScalar(value)) continue;\n const baseName = stripLocaleSuffix(rawName, locale);\n if (hasAddressableBinding(cache, rawName, ownerKeys)) continue;\n if (baseName !== rawName && hasAddressableBinding(cache, baseName, ownerKeys)) continue;\n localisedNames ??= localisedBindingNames(cache, ownerKeys);\n if (localisedNames.has(rawName)) continue;\n warned.add(rawName);\n warn(\n `[live-preview] LP0201: no <… data-payload-field=\"${baseName}\"> for field \"${rawName}\"; ` +\n 'render the anchor unconditionally so edits to an empty field have somewhere to land.',\n );\n }\n}\n\nfunction ownsAnyBinding(cache: ElementCache, ownerKeys: readonly string[] | null): boolean {\n for (const binding of cache.values()) {\n if (isBindingInScope(binding.owner, ownerKeys)) return true;\n }\n return false;\n}\n\nfunction hasAddressableBinding(\n cache: ElementCache,\n fieldName: string,\n ownerKeys: readonly string[] | null | false,\n): boolean {\n const bindings = cache.get(fieldName);\n if (bindings === undefined) return false;\n if (ownerKeys === false) return true;\n return bindings.some((binding) => isBindingInScope(binding.owner, ownerKeys));\n}\n\n/** `field_locale` names an element-local locale may consume while the message locale differs. */\nfunction localisedBindingNames(\n cache: ElementCache,\n ownerKeys: readonly string[] | null | false,\n): Set<string> {\n const names = new Set<string>();\n for (const [fieldName, bindings] of cache.entries()) {\n for (const binding of bindings) {\n if (ownerKeys !== false && !isBindingInScope(binding.owner, ownerKeys)) continue;\n if (binding.locale !== undefined) names.add(`${fieldName}_${binding.locale}`);\n }\n }\n return names;\n}\n\nfunction isBindableScalar(value: unknown): boolean {\n const type = typeof value;\n return type === 'string' || type === 'number' || type === 'boolean' || type === 'bigint';\n}\n\nfunction stripLocaleSuffix(name: string, locale: string | undefined): string {\n if (locale === undefined || locale.length === 0) return name;\n const suffix = `_${locale}`;\n return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;\n}\n","/**\n * Trusted Types: every HTML sink routes through one policy, `payload-live-preview`,\n * whose `createHTML` is the identity — what reaches a sink is already sanitized\n * or escaped. Without the API, strings pass through untouched.\n */\n\n/** The subset of the Trusted Types API this module needs. */\nexport interface TrustedHtmlPolicyLike {\n createHTML(input: string): unknown;\n}\n\ninterface TrustedTypesFactoryLike {\n createPolicy(\n name: string,\n rules: { createHTML: (input: string) => string },\n ): TrustedHtmlPolicyLike;\n}\n\nexport const TRUSTED_TYPES_POLICY_NAME = 'payload-live-preview';\n\nlet policyOverride: TrustedHtmlPolicyLike | null | undefined;\nlet autoPolicy: TrustedHtmlPolicyLike | null | undefined;\n\n/**\n * Use `policy` for every sink, `null` to assign plain strings, `undefined` to\n * return to the auto-created package policy.\n */\nexport function setTrustedTypesPolicy(policy: TrustedHtmlPolicyLike | null | undefined): void {\n policyOverride = policy;\n}\n\nfunction factory(): TrustedTypesFactoryLike | undefined {\n const candidate = (globalThis as { trustedTypes?: unknown }).trustedTypes;\n if (typeof candidate !== 'object' || candidate === null) return undefined;\n const create = (candidate as { createPolicy?: unknown }).createPolicy;\n return typeof create === 'function' ? (candidate as TrustedTypesFactoryLike) : undefined;\n}\n\nfunction resolvePolicy(): TrustedHtmlPolicyLike | null {\n if (policyOverride !== undefined) return policyOverride;\n if (autoPolicy !== undefined) return autoPolicy;\n const api = factory();\n if (api === undefined) {\n autoPolicy = null;\n return null;\n }\n try {\n autoPolicy = api.createPolicy(TRUSTED_TYPES_POLICY_NAME, { createHTML: (input) => input });\n } catch {\n // The site's `trusted-types` directive does not list this name; the\n // sink assignment will surface the enforcement error.\n autoPolicy = null;\n }\n return autoPolicy;\n}\n\n/** `html` as a `TrustedHTML` when a policy exists, else the string. Typed `string` for `innerHTML`. */\nexport function trustedHtml(html: string): string {\n const policy = resolvePolicy();\n if (policy === null) return html;\n return policy.createHTML(html) as string;\n}\n\n/** Test hook: forget the auto-created policy. */\nexport function __resetTrustedTypesForTests(): void {\n policyOverride = undefined;\n autoPolicy = undefined;\n}\n","/**\n * Keyed DOM morph: edits a live element toward a freshly rendered one while\n * keeping the live nodes, and with them focus, selection, scroll, playback and\n * listeners. Custom elements, islands, `contenteditable` and\n * `data-payload-owned` subtrees are boundaries the morph never enters.\n * See ADR 0008.\n */\n\nimport { ISLAND_ATTRIBUTE } from './islands';\n\nexport { ISLAND_ATTRIBUTE };\nexport const OWNED_ATTRIBUTE = 'data-payload-owned';\n\n/** Attributes the CMS controls only when the template names them (ADR 0008 §3). */\nconst STATE_ATTRIBUTES: ReadonlySet<string> = new Set(['open', 'value', 'checked', 'selected']);\n\nexport interface MorphOptions {\n /** Attributes that key child elements for pairing, tried in order; unkeyed children pair by position. */\n readonly keyAttributes: readonly string[];\n /** Called once per parent when two children share a key; the later ones pair by position. */\n readonly onDuplicateKey?: (parent: Element, key: string) => void;\n /** Elements whose attributes are synchronised but whose children are left alone (nested structural slots). */\n readonly retainChildrenOf?: (live: Element, rendered: Element) => boolean;\n}\n\n/** Empty attribute values (boolean markers such as `data-payload-island`) are not keys. */\nfunction keyOf(element: Element, options: MorphOptions): string | undefined {\n for (const attribute of options.keyAttributes) {\n const value = element.getAttribute(attribute);\n if (value !== null && value.length > 0) return `${attribute}=${value}`;\n }\n return undefined;\n}\n\nexport function isMorphBoundary(element: Element): boolean {\n if (element.tagName.toLowerCase().includes('-')) return true;\n if (element.hasAttribute(ISLAND_ATTRIBUTE) || element.hasAttribute(OWNED_ATTRIBUTE)) return true;\n const editable = element.getAttribute('contenteditable');\n return editable !== null && editable !== 'false';\n}\n\n/** Whether `live` can be edited toward `rendered` instead of being replaced by it. */\nexport function isMorphCompatible(live: Element, rendered: Element): boolean {\n return (\n live.tagName === rendered.tagName &&\n live.namespaceURI === rendered.namespaceURI &&\n !isMorphBoundary(live) &&\n !isMorphBoundary(rendered)\n );\n}\n\n/**\n * Morph `live` toward `rendered`. Returns `live` when it was retained, or\n * `rendered` when the two are incompatible and the caller must replace.\n * `rendered` is consumed: its children may move into `live`.\n */\nexport function morphElement(live: Element, rendered: Element, options: MorphOptions): Element {\n if (!isMorphCompatible(live, rendered)) return rendered;\n const focus = captureFocus(live);\n syncAttributes(live, rendered);\n if (options.retainChildrenOf?.(live, rendered) !== true) morphChildren(live, rendered, options);\n restoreFocus(focus);\n return live;\n}\n\n/** Match attributes, except that state-bearing ones change only when `rendered` carries them. */\nexport function syncAttributes(live: Element, rendered: Element): void {\n for (const attribute of Array.from(live.attributes)) {\n if (rendered.hasAttribute(attribute.name)) continue;\n if (STATE_ATTRIBUTES.has(attribute.name.toLowerCase())) continue;\n live.removeAttribute(attribute.name);\n }\n for (const attribute of Array.from(rendered.attributes)) {\n if (live.getAttribute(attribute.name) !== attribute.value) {\n live.setAttribute(attribute.name, attribute.value);\n }\n }\n}\n\nfunction morphChildren(live: Element, rendered: Element, options: MorphOptions): void {\n const liveKeyed = indexKeyed(live, options);\n const keyedElements = new Set<Node>(liveKeyed.values());\n const liveUnkeyed = Array.from(live.childNodes).filter((node) => !keyedElements.has(node));\n const claimed = new Set<Node>();\n const usedKeys = new Set<string>();\n const renderedNodes = Array.from(rendered.childNodes);\n let cursor: Node | null = live.firstChild;\n let unkeyedIndex = 0;\n\n for (let i = 0; i < renderedNodes.length; i += 1) {\n const next = renderedNodes[i] as Node;\n let kept: Node | null = null;\n let key = next instanceof Element ? keyOf(next, options) : undefined;\n // A repeated key on the rendered side pairs positionally like a live duplicate.\n if (key !== undefined && usedKeys.has(key)) key = undefined;\n if (key !== undefined) {\n usedKeys.add(key);\n const candidate = liveKeyed.get(key);\n if (candidate !== undefined && !claimed.has(candidate)) {\n kept = reconcile(candidate, next, options) === candidate ? candidate : null;\n if (kept === null) {\n candidate.replaceWith(next);\n claimed.add(next);\n cursor = next.nextSibling;\n continue;\n }\n }\n } else {\n while (unkeyedIndex < liveUnkeyed.length) {\n const candidate = liveUnkeyed[unkeyedIndex] as Node;\n unkeyedIndex += 1;\n if (claimed.has(candidate)) continue;\n if (sameKind(candidate, next)) {\n kept = reconcile(candidate, next, options) === candidate ? candidate : null;\n if (kept === null) {\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n }\n break;\n }\n if (candidate instanceof Element) {\n // `next` is a text/comment, or an element whose kind the following\n // rendered node matches: an insertion, so the live element stays for it.\n const following = renderedNodes[i + 1];\n if (\n !(next instanceof Element) ||\n (following !== undefined && sameKind(candidate, following))\n ) {\n unkeyedIndex -= 1;\n break;\n }\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n break;\n }\n if (!(next instanceof Element)) {\n // Text vs comment: replace rather than rewrite one node type's value into the other.\n live.replaceChild(next, candidate);\n claimed.add(next);\n cursor = next.nextSibling;\n break;\n }\n // A surplus live text/comment before the element `next` needs; removed below.\n }\n if (kept === null && claimed.has(next)) continue;\n }\n\n const node: Node = kept ?? next;\n claimed.add(node);\n // Whitespace-only text the template did not render is surplus. Stepping the\n // cursor over it keeps a retained element where it is: `insertBefore` on a\n // node already in the tree is a remove-and-insert, which blurs a focused input.\n while (cursor !== null && cursor !== node && !claimed.has(cursor) && isBlankText(cursor)) {\n cursor = cursor.nextSibling;\n }\n if (node !== cursor) live.insertBefore(node, cursor);\n cursor = node.nextSibling;\n }\n\n for (const child of Array.from(live.childNodes)) {\n if (!claimed.has(child)) child.remove();\n }\n}\n\n/** Retain `candidate` when it can be edited toward `next`; otherwise report `next`. */\nfunction reconcile(candidate: Node, next: Node, options: MorphOptions): Node {\n if (candidate instanceof Element && next instanceof Element) {\n // A compatible boundary stays exactly as it is (ADR 0008 §4).\n if (isMorphBoundary(candidate) && isMorphBoundary(next)) return candidate;\n return morphElement(candidate, next, options);\n }\n if (candidate.nodeValue !== next.nodeValue) candidate.nodeValue = next.nodeValue;\n return candidate;\n}\n\nfunction isBlankText(node: Node): boolean {\n return node.nodeType === Node.TEXT_NODE && (node.nodeValue ?? '').trim().length === 0;\n}\n\nfunction sameKind(a: Node, b: Node): boolean {\n if (a.nodeType !== b.nodeType) return false;\n if (a instanceof Element && b instanceof Element) {\n return a.tagName === b.tagName && a.namespaceURI === b.namespaceURI;\n }\n return true;\n}\n\n/** First element per key; later duplicates are left as they are and pair positionally. */\nfunction indexKeyed(parent: Element, options: MorphOptions): Map<string, Element> {\n const keyed = new Map<string, Element>();\n let duplicate: string | undefined;\n for (const child of Array.from(parent.children)) {\n const key = keyOf(child, options);\n if (key === undefined) continue;\n if (keyed.has(key)) {\n duplicate ??= key.slice(key.indexOf('=') + 1);\n continue;\n }\n keyed.set(key, child);\n }\n if (duplicate !== undefined) options.onDuplicateKey?.(parent, duplicate);\n return keyed;\n}\n\ninterface FocusSnapshot {\n readonly element: HTMLElement;\n readonly selection: readonly [number | null, number | null] | null;\n}\n\n/** A keyed move is a remove-and-insert, which blurs; remember what had focus. */\nfunction captureFocus(live: Element): FocusSnapshot | null {\n const active = live.ownerDocument.activeElement;\n if (!(active instanceof HTMLElement) || !live.contains(active)) return null;\n const selection =\n active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement\n ? ([active.selectionStart, active.selectionEnd] as const)\n : null;\n return { element: active, selection };\n}\n\nfunction restoreFocus(snapshot: FocusSnapshot | null): void {\n if (snapshot === null) return;\n const { element, selection } = snapshot;\n if (element.ownerDocument.activeElement === element || !element.isConnected) return;\n try {\n element.focus({ preventScroll: true });\n const [start, end] = selection ?? [null, null];\n if (start !== null && end !== null) {\n (element as HTMLInputElement).setSelectionRange(start, end);\n }\n } catch {\n // Not focusable any more; nothing to restore.\n }\n}\n","/**\n * HTML sanitizer built on the host parser (`<template>`): allow-listed tags\n * and attributes, validated URLs, hardened external links, no `style`.\n * Needs a DOM; string-only sanitizers are historically brittle.\n */\n\nimport { trustedHtml } from './trusted-types';\nimport { isSafeUrl, isExternalHttpUrl } from './url-validator';\n\ndeclare const __INLINE_BUILD__: boolean | undefined;\n\n/** Tags kept with their content. Others are unwrapped unless in `REMOVE_COMPLETELY`. */\nconst ALLOWED_TAGS: ReadonlySet<string> = new Set([\n 'p',\n 'br',\n 'strong',\n 'b',\n 'em',\n 'i',\n 'u',\n 's',\n 'strike',\n 'mark',\n 'small',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'ul',\n 'ol',\n 'li',\n 'dl',\n 'dt',\n 'dd',\n 'blockquote',\n 'code',\n 'pre',\n 'kbd',\n 'samp',\n 'var',\n 'a',\n 'span',\n 'div',\n 'section',\n 'article',\n 'aside',\n 'header',\n 'footer',\n 'nav',\n 'figure',\n 'figcaption',\n 'img',\n 'picture',\n 'source',\n 'audio',\n 'video',\n 'sub',\n 'sup',\n 'hr',\n 'time',\n 'abbr',\n 'cite',\n 'q',\n 'table',\n 'thead',\n 'tbody',\n 'tfoot',\n 'tr',\n 'th',\n 'td',\n 'caption',\n 'colgroup',\n 'col',\n]);\n\n/** Tags `allowFormControls` re-admits for author templates; `form` is deliberately not one. */\nconst FORM_CONTROLS: ReadonlySet<string> = new Set([\n 'input',\n 'button',\n 'textarea',\n 'select',\n 'option',\n 'label',\n]);\n\n/** Removed with their children: the content itself is the hazard. */\nconst REMOVE_COMPLETELY: ReadonlySet<string> = new Set([\n 'script',\n 'style',\n 'iframe',\n 'object',\n 'embed',\n 'link',\n 'meta',\n 'base',\n 'form',\n 'input',\n 'button',\n 'select',\n 'textarea',\n 'svg',\n 'math',\n 'template',\n 'frame',\n 'frameset',\n 'noframes',\n 'noscript',\n]);\n\nconst ATTR_GLOBAL: ReadonlySet<string> = new Set([\n 'id',\n 'class',\n 'lang',\n 'dir',\n 'title',\n 'role',\n 'tabindex',\n]);\n\nconst ATTR_ARIA_PREFIX = 'aria-';\nconst ATTR_DATA_PREFIX = 'data-';\nconst BINDING_DATA_PREFIX = 'data-payload-';\n\nconst ATTR_BY_TAG: Readonly<Record<string, ReadonlySet<string>>> = {\n a: new Set(['href', 'target', 'rel', 'download', 'hreflang', 'type']),\n img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding']),\n picture: new Set([]),\n source: new Set(['src', 'srcset', 'sizes', 'type', 'media']),\n audio: new Set(['src', 'controls', 'autoplay', 'loop', 'muted', 'preload']),\n video: new Set([\n 'src',\n 'poster',\n 'controls',\n 'autoplay',\n 'loop',\n 'muted',\n 'preload',\n 'width',\n 'height',\n 'playsinline',\n ]),\n time: new Set(['datetime']),\n abbr: new Set(['title']),\n q: new Set(['cite']),\n blockquote: new Set(['cite']),\n table: new Set(['summary']),\n th: new Set(['colspan', 'rowspan', 'scope', 'headers', 'abbr']),\n td: new Set(['colspan', 'rowspan', 'headers']),\n col: new Set(['span']),\n colgroup: new Set(['span']),\n ol: new Set(['start', 'reversed', 'type']),\n li: new Set(['value']),\n code: new Set(['class']),\n pre: new Set(['class']),\n};\n\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set(['href', 'src', 'cite', 'poster']);\n\n// Numeric nodeType constants keep an injected SSR document independent of a\n// browser-global `Node` constructor.\nconst ELEMENT_NODE = 1;\nconst COMMENT_NODE = 8;\n\n/** Thrown by `sanitizeHtml()` when no `document` is available (SSR without `setSanitizerDocument()`). */\nexport class SanitizerEnvironmentError extends Error {\n override readonly name = 'SanitizerEnvironmentError';\n}\n\n/**\n * `'strict'` (default) strips `id`, `name` and `data-payload-*` and passes\n * other `data-*` only via `allowedDataAttributes`; `'compat'` keeps them.\n */\nexport type SanitizerPolicyMode = 'compat' | 'strict';\n\nexport interface SanitizeOptions {\n /** Overrides the module default set by `setSanitizerPolicy()`. */\n readonly policy?: SanitizerPolicyMode;\n /** `data-*` attributes (full names) that pass under `'strict'`; `data-payload-*` never does. */\n readonly allowedDataAttributes?: readonly string[];\n /**\n * Keep `input`, `button`, `textarea`, `select`, `option` and `label` — only\n * for markup the page author wrote, never for CMS content. `form`,\n * handlers, `style` and unsafe URLs stay dropped.\n */\n readonly allowFormControls?: boolean;\n /** Extra tags to allow. Lower-case, untrimmed. */\n readonly additionalAllowedTags?: readonly string[];\n /**\n * Extra per-tag attributes, lower-case. Cannot re-admit handlers, `style`,\n * or — under `'strict'` — `id`, `name` and `data-payload-*`.\n */\n readonly additionalAllowedAttributes?: Readonly<Record<string, readonly string[]>>;\n /**\n * The input is a page-author item template, so `'strict'` keeps the\n * applier's reconciliation attributes (`TEMPLATE_ATTRIBUTES`) and nothing\n * else — every other `data-payload-*` is still stripped, so a template can\n * never add a binding.\n */\n readonly templateMode?: boolean;\n}\n\n/** What `templateMode` keeps under `'strict'`. */\nconst TEMPLATE_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'id',\n 'name',\n 'data-payload-key',\n 'data-payload-nested-key',\n 'data-payload-nested-template',\n]);\n\ninterface ResolvedPolicy {\n readonly allowedTags: ReadonlySet<string>;\n readonly allowFormControls: boolean;\n readonly templateMode: boolean;\n readonly mode: SanitizerPolicyMode;\n readonly allowedData: ReadonlySet<string>;\n readonly attrByTag: ReadonlyMap<string, ReadonlySet<string>>;\n}\n\nlet defaultMode: SanitizerPolicyMode = 'strict';\n\n/** Set the policy for calls without an explicit `policy`. The runtime sets it from `sanitizerPolicy`. */\nexport function setSanitizerPolicy(mode: SanitizerPolicyMode): void {\n defaultMode = mode;\n}\n\nfunction resolvePolicy(options: SanitizeOptions | undefined): ResolvedPolicy {\n if (!options) {\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n return {\n allowedTags: ALLOWED_TAGS,\n attrByTag: attrMap,\n allowFormControls: false,\n templateMode: false,\n mode: defaultMode,\n allowedData: new Set(),\n };\n }\n const allowed = new Set(ALLOWED_TAGS);\n for (const tag of options.additionalAllowedTags ?? []) allowed.add(tag);\n if (options.allowFormControls === true) for (const tag of FORM_CONTROLS) allowed.add(tag);\n const attrMap = new Map<string, ReadonlySet<string>>();\n for (const [tag, attrs] of Object.entries(ATTR_BY_TAG)) attrMap.set(tag, attrs);\n for (const [tag, attrs] of Object.entries(options.additionalAllowedAttributes ?? {})) {\n const existing = attrMap.get(tag);\n const merged = new Set(existing ?? []);\n for (const attr of attrs) merged.add(attr);\n attrMap.set(tag, merged);\n }\n return {\n allowedTags: allowed,\n attrByTag: attrMap,\n allowFormControls: options.allowFormControls === true,\n templateMode: options.templateMode === true,\n mode: options.policy ?? defaultMode,\n allowedData: new Set((options.allowedDataAttributes ?? []).map((name) => name.toLowerCase())),\n };\n}\n\n/** The `Document` surface the sanitizer needs; jsdom, linkedom and happy-dom all provide it. */\nexport interface SanitizerDocument {\n createElement: (tagName: string) => {\n innerHTML: string;\n readonly content: ParentNode;\n };\n}\n\nlet documentOverride: SanitizerDocument | undefined;\n\n/** Supply a `Document` for SSR, e.g. linkedom's `parseHTML(...).document`; `null` clears it. */\nexport function setSanitizerDocument(doc: SanitizerDocument | null): void {\n documentOverride = doc ?? undefined;\n}\n\n/**\n * Sanitize `html`; malformed input is recovered by the parser first.\n *\n * @throws {SanitizerEnvironmentError} when no DOM is available.\n */\nexport function sanitizeHtml(html: string, options?: SanitizeOptions): string {\n const doc = resolveDocument();\n if (!doc) throw environmentError();\n if (html === '') return '';\n\n const policy = resolvePolicy(options);\n const template = doc.createElement('template');\n // The sanitizer's own parse is a sink too: under Trusted Types it needs the policy.\n template.innerHTML = trustedHtml(html);\n sanitizeFragment(template.content, policy);\n return template.innerHTML;\n}\n\n// Read the define at each branch rather than through a helper: a bundler\n// folds the substituted literal in place, but will not inline a call, and the\n// SSR-only class and override must not reach the browser runtime.\nfunction environmentError(): Error {\n if (typeof __INLINE_BUILD__ !== 'undefined' && __INLINE_BUILD__) {\n return new Error('sanitizeHtml needs a DOM');\n }\n return new SanitizerEnvironmentError(\n 'sanitizeHtml needs a DOM; provide one with setSanitizerDocument() during SSR.',\n );\n}\n\nfunction resolveDocument(): SanitizerDocument | undefined {\n if (typeof __INLINE_BUILD__ === 'undefined' || !__INLINE_BUILD__) {\n if (documentOverride) return documentOverride;\n }\n if (typeof document === 'undefined') return undefined;\n return document;\n}\n\n/** Whether a DOM is available — the global or an injected one — for callers that treat sanitizing as optional. */\nexport function hasSanitizerDocument(): boolean {\n return resolveDocument() !== undefined;\n}\n\nfunction sanitizeFragment(node: ParentNode, policy: ResolvedPolicy): void {\n // Snapshot: children are mutated during the walk.\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) {\n sanitizeElement(child as Element, policy);\n } else if (child.nodeType === COMMENT_NODE) {\n child.remove();\n }\n }\n}\n\nfunction sanitizeElement(element: Element, policy: ResolvedPolicy): void {\n const tag = element.tagName.toLowerCase();\n\n if (REMOVE_COMPLETELY.has(tag) && !(policy.allowFormControls && FORM_CONTROLS.has(tag))) {\n element.remove();\n return;\n }\n\n if (!policy.allowedTags.has(tag)) {\n sanitizeFragment(element, policy);\n const parent = element.parentNode;\n if (parent) {\n while (element.firstChild) parent.insertBefore(element.firstChild, element);\n element.remove();\n }\n return;\n }\n\n sanitizeAttributes(element, tag, policy);\n if (tag === 'a') hardenAnchor(element);\n sanitizeFragment(element, policy);\n}\n\nfunction sanitizeAttributes(element: Element, tag: string, policy: ResolvedPolicy): void {\n const tagAttrs = policy.attrByTag.get(tag);\n\n for (const attr of Array.from(element.attributes)) {\n const name = attr.name.toLowerCase();\n if (name.startsWith('on') || name === 'style') {\n element.removeAttribute(attr.name);\n continue;\n }\n if (policy.mode === 'strict') {\n if (policy.templateMode && TEMPLATE_ATTRIBUTES.has(name)) continue;\n // DOM clobbering and binding injection (docs/security.md §5c). Checked\n // before the allow-list so an extension cannot re-admit them.\n if (name === 'id' || name === 'name' || name.startsWith(BINDING_DATA_PREFIX)) {\n element.removeAttribute(attr.name);\n continue;\n }\n if (name.startsWith(ATTR_DATA_PREFIX)) {\n if (!policy.allowedData.has(name)) element.removeAttribute(attr.name);\n continue;\n }\n if (ATTR_GLOBAL.has(name) || name.startsWith(ATTR_ARIA_PREFIX)) continue;\n } else if (\n ATTR_GLOBAL.has(name) ||\n name.startsWith(ATTR_ARIA_PREFIX) ||\n name.startsWith(ATTR_DATA_PREFIX)\n ) {\n continue;\n }\n if (tagAttrs?.has(name)) {\n if (URL_ATTRIBUTES.has(name) && !isSafeUrl(attr.value)) {\n element.removeAttribute(attr.name);\n } else if (name === 'srcset' && !isSafeSrcset(attr.value)) {\n element.removeAttribute(attr.name);\n }\n continue;\n }\n element.removeAttribute(attr.name);\n }\n}\n\n/** Every `srcset` candidate must pass; partial rewriting would silently change what renders. */\nfunction isSafeSrcset(value: string): boolean {\n for (const candidate of value.split(',')) {\n const trimmed = candidate.trim();\n if (trimmed.length === 0) continue;\n const descriptorStart = trimmed.search(/\\s/);\n const url = descriptorStart === -1 ? trimmed : trimmed.slice(0, descriptorStart);\n if (!isSafeUrl(url)) return false;\n }\n return true;\n}\n\nfunction hardenAnchor(anchor: Element): void {\n const href = anchor.getAttribute('href');\n if (href === null || !isExternalHttpUrl(href)) return;\n anchor.setAttribute('rel', 'noopener noreferrer');\n if (!anchor.hasAttribute('target')) anchor.setAttribute('target', '_blank');\n}\n\n/** The built-in allow-lists, for documentation and tests. */\nexport const SANITIZER_POLICY = Object.freeze({\n allowedTags: ALLOWED_TAGS,\n removeCompletely: REMOVE_COMPLETELY,\n globalAttributes: ATTR_GLOBAL,\n attributesByTag: ATTR_BY_TAG,\n urlAttributes: URL_ATTRIBUTES,\n});\n","/** HTML and CSS escaping primitives (OWASP XSS Prevention Cheat Sheet). DOM-free. */\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;',\n});\n\nconst HTML_ESCAPE_PATTERN = /[&<>\"'/`=]/g;\n\n/** Escape `text` for an element body or a *quoted* attribute value; strings only, and unquoted attributes are not covered. */\nexport function escapeHtml(text: string): string {\n if (text === '') return '';\n // The character class and the map are coupled: every match is a key.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return text.replace(HTML_ESCAPE_PATTERN, (char) => HTML_ESCAPES[char] as string);\n}\n\n/** Escape a value for a CSS `url(...)` literal; this stops the break-out, not the scheme, so pair it with `isSafeUrl()`. */\nexport function escapeCssUrl(value: string): string {\n return value.replace(/['\"()\\\\]/g, '\\\\$&');\n}\n\nconst ATTR_ESCAPES: Readonly<Record<string, string>> = Object.freeze({\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n});\n\nconst ATTR_ESCAPE_PATTERN = /[&<>\"']/g;\n\n/** Escape a value for a *quoted* HTML attribute, leaving URL characters intact; it validates no scheme, so run `isSafeUrl()` on `href`/`src` first. */\nexport function escapeHtmlAttribute(value: string): string {\n if (value === '') return '';\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return value.replace(ATTR_ESCAPE_PATTERN, (char) => ATTR_ESCAPES[char] as string);\n}\n\n/** `escapeHtml()` then newlines to `<br>`; the order is what makes it safe. */\nexport function escapeAndLinebreak(text: string): string {\n return escapeHtml(text).replace(/\\r\\n|\\r|\\n/g, '<br>');\n}\n","/**\n * Interpolate one array-item template in a single pass. A replacement value is\n * data, not template syntax: one `replace()` per key would re-interpret\n * `{{index}}` text that an earlier value introduced, and would apply\n * `String.replace`'s `$` semantics to CMS content.\n */\n\nimport { escapeHtml } from '@security/escape';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{([\\s\\S]*?)\\}\\}/g;\n\nfunction hasOwn(record: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nexport function interpolateArrayTemplate(\n template: string,\n item: unknown,\n index: number,\n stringify: (value: unknown) => string,\n): string {\n const record = typeof item === 'object' && item !== null ? item : null;\n\n return template.replace(PLACEHOLDER_PATTERN, (placeholder, key: string) => {\n // Preserve the established object-field precedence when an object itself\n // has an `index` or `value` property. Otherwise these are reserved tokens.\n if (record !== null && hasOwn(record, key)) {\n return escapeHtml(stringify(Reflect.get(record, key)));\n }\n if (record === null && key === 'value') return escapeHtml(stringify(item));\n if (key === 'index') return String(index);\n return placeholder;\n });\n}\n","/** Value coercion shared by the field renderers. */\n\n/** Display string for any value: primitives as-is, objects as JSON, `null`/`undefined` as `''`. */\nexport function safeStringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return '';\n }\n}\n\n/** The three values every renderer treats as \"clear\" (docs/renderers.md, value semantics). */\nexport function isEmptyValue(value: unknown): value is null | undefined | '' {\n return value === null || value === undefined || value === '';\n}\n","/**\n * Sanitizer options for item templates (`data-payload-array-template`,\n * nested templates). A template is the page author's markup and every\n * interpolated value is escaped to text before the sanitizer runs, so it may\n * carry form controls and custom elements the rich-text policy refuses.\n * Event handlers, `style` and unsafe URLs are still stripped.\n *\n * Some entries below are already admitted by the sanitizer through another\n * route — `video` and `audio` by the tag allow-list, `select` by\n * `allowFormControls`, `name` by `templateMode`, and `controls`, `muted`,\n * `loop`, `poster` and `src` by the per-tag attribute map. They are kept\n * because this list states what a template may contain, and an allow-list\n * that depends on a second list staying unchanged is the more fragile of the\n * two arrangements. Mutating those entries changes nothing observable, so\n * they survive mutation testing by construction; the behaviour they describe\n * is pinned in `tests/unit/core/template-sanitize.test.ts` instead.\n */\n\nimport type { SanitizeOptions } from '@security/sanitizer';\n\nconst TEMPLATE_EXTRA_TAGS: readonly string[] = [\n 'input',\n 'textarea',\n 'select',\n 'option',\n 'button',\n 'label',\n 'details',\n 'summary',\n 'dialog',\n 'video',\n 'audio',\n 'progress',\n 'meter',\n];\n\nconst TEMPLATE_EXTRA_ATTRIBUTES: readonly string[] = [\n 'type',\n 'name',\n 'placeholder',\n 'open',\n 'disabled',\n 'readonly',\n 'required',\n 'checked',\n 'selected',\n 'value',\n 'min',\n 'max',\n 'step',\n 'rows',\n 'cols',\n 'for',\n 'controls',\n 'muted',\n 'loop',\n 'poster',\n 'src',\n];\n\nconst CUSTOM_TAG_PATTERN = /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\b/gi;\nconst optionsByTemplate = new Map<string, SanitizeOptions>();\n\n/** Options for one template; memoised per template string. */\nexport function templateSanitizeOptions(template: string): SanitizeOptions {\n const cached = optionsByTemplate.get(template);\n if (cached !== undefined) return cached;\n const tags = new Set(TEMPLATE_EXTRA_TAGS);\n for (const match of template.matchAll(CUSTOM_TAG_PATTERN)) {\n const tag = match[1]?.toLowerCase();\n if (tag !== undefined) tags.add(tag);\n }\n const attributes: Record<string, readonly string[]> = {};\n for (const tag of tags) attributes[tag] = TEMPLATE_EXTRA_ATTRIBUTES;\n const options: SanitizeOptions = {\n additionalAllowedTags: [...tags],\n additionalAllowedAttributes: attributes,\n allowFormControls: true,\n templateMode: true,\n };\n optionsByTemplate.set(template, options);\n return options;\n}\n","/**\n * Applies an `ArrayPatch[]` diff to a container as keyed DOM operations\n * instead of rebuilding the list, so consumer state on surviving children is\n * kept. Items are paired by `data-payload-key` (the item `id`); items without\n * one pair by position. Nested arrays reconcile recursively through\n * `data-payload-nested-key` slots. See ADR 0008.\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport { interpolateArrayTemplate } from './array-template';\nimport { safeStringify } from '@field-types/utils';\nimport { diffArray, type ArrayPatch } from '@schema/diff';\nimport { morphElement } from './morph';\nimport { templateSanitizeOptions } from './template-sanitize';\n\nexport const KEY_ATTRIBUTE = 'data-payload-key';\nconst NESTED_KEY_ATTRIBUTE = 'data-payload-nested-key';\nconst NESTED_TEMPLATE_ATTRIBUTE = 'data-payload-nested-template';\n\n/** Last value seen per item key, per container; owned by the caller so instances never share it. */\nexport type StructuralStore = WeakMap<Element, Map<string, unknown>>;\n\nexport function createStructuralStore(): StructuralStore {\n return new WeakMap<Element, Map<string, unknown>>();\n}\n\nexport interface StructuralApplyOptions {\n readonly template: string;\n readonly container: Element;\n readonly patches: readonly ArrayPatch[];\n /** The full new array; inserts and replaces render by index from it. */\n readonly nextItems: readonly unknown[];\n /** Pass the same store across renders so nested arrays diff incrementally. */\n readonly store: StructuralStore;\n /** Re-render existing items even when unchanged. */\n readonly forceRender?: boolean;\n /** Edit a changed item in place instead of replacing it. Default `true`. */\n readonly morph?: boolean;\n /** Reported once per container when two items share a key (`LP0405`). */\n readonly onDuplicateKey?: (container: Element, key: string) => void;\n}\n\n/**\n * Returns `true` for a DOM mutation, `false` for an already-current tree, and\n * `null` when an item's markup has no sanitized element root — preflighted\n * before any mutation, so the previous DOM and memory stay intact.\n */\nexport function applyStructuralPatches(options: StructuralApplyOptions): boolean | null {\n const { template, container, patches, nextItems, store, forceRender = false } = options;\n const plan = prepareStructuralPlan(container, template, patches, nextItems, forceRender, store);\n if (plan === null) return null;\n return commitStructuralPlan(plan, store, {\n morph: options.morph ?? true,\n onDuplicateKey: options.onDuplicateKey,\n });\n}\n\n// Plan records are tuples: many are created per recursive render, and named\n// keys would repeat in the inline bundle.\ntype StructuralPlan = readonly [\n container: Element,\n entries: readonly ReconciliationEntry[],\n nextItems: readonly unknown[],\n];\ntype ReconciliationEntry = readonly [\n index: number,\n live: Element | null,\n rendered: Element | undefined,\n nestedSlots: readonly NestedSlotPlan[],\n /** A `replace` patch: a different item, never morphed toward. */\n replace: boolean,\n];\ntype NestedSlotPlan = readonly [\n live: Element | null,\n rendered: Element,\n children: StructuralPlan | undefined,\n];\n\ninterface CommitOptions {\n readonly morph: boolean;\n readonly onDuplicateKey: ((container: Element, key: string) => void) | undefined;\n}\n\n/** A rendered slot that still carries a nested template keeps its children for its own plan. */\nfunction isManagedNestedSlot(_live: Element, rendered: Element): boolean {\n return (\n rendered.hasAttribute(NESTED_KEY_ATTRIBUTE) && rendered.hasAttribute(NESTED_TEMPLATE_ATTRIBUTE)\n );\n}\n\n/** Materialise the whole recursive replacement tree before touching live DOM. */\nfunction prepareStructuralPlan(\n container: Element,\n template: string,\n patches: readonly ArrayPatch[],\n nextItems: readonly unknown[],\n forceRender: boolean,\n store: StructuralStore,\n): StructuralPlan | null {\n const entries = prepareReconciliation(\n container,\n template,\n nextItems,\n createPatchPlan(patches),\n forceRender,\n store.get(container),\n store,\n );\n return entries === null ? null : [container, entries, nextItems];\n}\n\nfunction commitStructuralPlan(\n plan: StructuralPlan,\n store: StructuralStore,\n options: CommitOptions,\n): boolean {\n const [container, entries, nextItems] = plan;\n const claimed = new Set<Element>();\n let mutated = false;\n for (const [index, live, rendered, nestedSlots, replace] of entries) {\n let node = live;\n if (rendered !== undefined) {\n // Morph a compatible live item in place; otherwise transplant its live\n // nested slots into the rendered item and swap.\n const retained =\n options.morph && !replace && live !== null\n ? morphElement(live, rendered, {\n keyAttributes: [KEY_ATTRIBUTE, NESTED_KEY_ATTRIBUTE],\n retainChildrenOf: isManagedNestedSlot,\n ...(options.onDuplicateKey !== undefined\n ? { onDuplicateKey: options.onDuplicateKey }\n : {}),\n }) === live\n : false;\n if (!retained) {\n for (const [liveSlot, renderedSlot] of nestedSlots) {\n if (liveSlot === null) continue;\n synchronizeAttributes(liveSlot, renderedSlot);\n renderedSlot.replaceWith(liveSlot);\n }\n }\n for (const [, , children] of nestedSlots) {\n if (children !== undefined) commitStructuralPlan(children, store, options);\n }\n if (retained) {\n mutated = true;\n } else {\n if (live !== null) {\n live.replaceWith(rendered);\n mutated = true;\n }\n node = rendered;\n }\n }\n if (node === null) continue;\n const before = container.children[index] ?? null;\n if (node !== before) {\n container.insertBefore(node, before);\n mutated = true;\n }\n claimed.add(node);\n }\n // `nextItems` is the source of truth; this also drops SSR children the first value did not carry.\n for (const child of Array.from(container.children)) {\n if (claimed.has(child)) continue;\n child.remove();\n mutated = true;\n }\n const memory = getMemory(container, store);\n memory.clear();\n for (const value of nextItems) rememberItem(memory, value);\n return mutated;\n}\n\n/**\n * Pair every final item with a live child (by key, else by position) and\n * render what needs rendering. Patch indices describe `next`, live indices\n * move during reconciliation, so keyed nodes are resolved from the DOM first.\n */\nfunction prepareReconciliation(\n container: Element,\n template: string,\n nextItems: readonly unknown[],\n plan: PatchPlan,\n forceRender: boolean,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly ReconciliationEntry[] | null {\n const initialChildren = Array.from(container.children);\n const keyedChildren = indexByAttribute(initialChildren, KEY_ATTRIBUTE);\n const reserved = new Set<Element>();\n const entries: ReconciliationEntry[] = [];\n for (let index = 0; index < nextItems.length; index += 1) {\n const value = nextItems[index];\n const key = readKey(value);\n let live =\n key === undefined\n ? (initialChildren[index] ?? null)\n : (takeIndexedElement(keyedChildren, key) ?? null);\n if (live !== null && reserved.has(live)) live = null;\n if (live !== null) reserved.add(live);\n const replace = plan.replaces.has(index);\n const needsRender = forceRender || plan.renders.has(index) || live === null;\n const rendered = needsRender\n ? renderItem(container.ownerDocument, template, value, index)\n : undefined;\n if (rendered === null) return null;\n const nestedSlots =\n rendered === undefined\n ? []\n : prepareNestedSlots(replace ? null : live, rendered, value, memory, store);\n if (nestedSlots === null) return null;\n entries.push([index, live, rendered ?? undefined, nestedSlots, replace]);\n }\n return entries;\n}\n\ninterface PatchPlan {\n readonly renders: ReadonlySet<number>;\n readonly replaces: ReadonlySet<number>;\n}\n\nfunction createPatchPlan(patches: readonly ArrayPatch[]): PatchPlan {\n const renders = new Set<number>();\n const replaces = new Set<number>();\n for (const patch of patches) {\n if (patch.kind === 'insert' || patch.kind === 'update') renders.add(patch.index);\n else if (patch.kind === 'replace') {\n renders.add(patch.index);\n replaces.add(patch.index);\n }\n }\n return { renders, replaces };\n}\n\n/** Plan each direct nested slot; a failure at any depth aborts before commit. */\nfunction prepareNestedSlots(\n oldItem: Element | null,\n newItem: Element,\n nextValue: unknown,\n memory: ReadonlyMap<string, unknown> | undefined,\n store: StructuralStore,\n): readonly NestedSlotPlan[] | null {\n const oldSlots = oldItem === null ? [] : findDirectNestedSlots(oldItem);\n const oldSlotsByKey = indexByAttribute(oldSlots, NESTED_KEY_ATTRIBUTE);\n const itemKey = readKey(nextValue);\n const prevValue = itemKey !== undefined ? memory?.get(itemKey) : undefined;\n const plans: NestedSlotPlan[] = [];\n for (const newSlot of findDirectNestedSlots(newItem)) {\n const key = newSlot.getAttribute(NESTED_KEY_ATTRIBUTE);\n if (key === null) continue;\n const oldSlot = takeIndexedElement(oldSlotsByKey, key) ?? null;\n const nextTemplate = newSlot.getAttribute(NESTED_TEMPLATE_ATTRIBUTE);\n // Without a nested template the slot's rendered static content is authoritative.\n const liveSlot = nextTemplate ? oldSlot : null;\n const previousTemplate = liveSlot?.getAttribute(NESTED_TEMPLATE_ATTRIBUTE) ?? null;\n let children: StructuralPlan | undefined;\n if (nextTemplate) {\n const nextNested = readNestedArray(nextValue, key);\n if (nextNested !== undefined || liveSlot !== null) {\n const resolvedNext = nextNested ?? [];\n const prevNested = liveSlot === null ? [] : (readNestedArray(prevValue, key) ?? []);\n const patches = diffArray(prevNested, resolvedNext);\n const templateChanged = liveSlot !== null && previousTemplate !== nextTemplate;\n if (patches.length > 0 || templateChanged) {\n children =\n prepareStructuralPlan(\n liveSlot ?? newSlot,\n nextTemplate,\n patches,\n resolvedNext,\n templateChanged,\n store,\n ) ?? undefined;\n if (children === undefined) return null;\n }\n }\n }\n plans.push([liveSlot, newSlot, children]);\n }\n return plans;\n}\n\n/** Only the outermost nested slots: a transplanted slot owns the recursion below it. */\nfunction findDirectNestedSlots(item: Element): readonly Element[] {\n return Array.from(item.querySelectorAll(`[${NESTED_KEY_ATTRIBUTE}]`)).filter((slot) => {\n let ancestor = slot.parentElement;\n while (ancestor !== null && ancestor !== item) {\n if (ancestor.hasAttribute(NESTED_KEY_ATTRIBUTE)) return false;\n ancestor = ancestor.parentElement;\n }\n return ancestor === item;\n });\n}\n\nfunction synchronizeAttributes(target: Element, source: Element): void {\n for (const attribute of Array.from(target.attributes)) {\n if (!source.hasAttribute(attribute.name)) target.removeAttribute(attribute.name);\n }\n for (const attribute of Array.from(source.attributes)) {\n if (target.getAttribute(attribute.name) !== attribute.value) {\n target.setAttribute(attribute.name, attribute.value);\n }\n }\n}\n\nfunction readNestedArray(value: unknown, key: string): readonly unknown[] | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const nested = (value as Record<string, unknown>)[key];\n return Array.isArray(nested) ? (nested as readonly unknown[]) : undefined;\n}\n\nfunction getMemory(container: Element, store: StructuralStore): Map<string, unknown> {\n let map = store.get(container);\n if (!map) {\n map = new Map();\n store.set(container, map);\n }\n return map;\n}\n\nfunction rememberItem(memory: Map<string, unknown>, value: unknown): void {\n const key = readKey(value);\n if (key !== undefined) memory.set(key, value);\n}\n\nfunction readKey(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const id = (value as Record<string, unknown>)['id'];\n return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;\n}\n\nfunction indexByAttribute(elements: readonly Element[], attribute: string): Map<string, Element[]> {\n const indexed = new Map<string, Element[]>();\n // Reverse order so pop() yields duplicates in DOM order.\n for (let index = elements.length - 1; index >= 0; index -= 1) {\n const element = elements[index];\n if (element === undefined) continue;\n const key = element.getAttribute(attribute);\n if (key === null) continue;\n const bucket = indexed.get(key);\n if (bucket === undefined) indexed.set(key, [element]);\n else bucket.push(element);\n }\n return indexed;\n}\n\nfunction takeIndexedElement(indexed: Map<string, Element[]>, key: string): Element | undefined {\n return indexed.get(key)?.pop();\n}\n\n/** Render one item; its `id` is stamped as `data-payload-key` so later diffs find it. */\nfunction renderItem(\n ownerDocument: Document,\n template: string,\n value: unknown,\n index: number,\n): Element | null {\n const filled = interpolateArrayTemplate(template, value, index, safeStringify);\n const safe = sanitizeHtml(filled, templateSanitizeOptions(template));\n const host = ownerDocument.createElement('template');\n host.innerHTML = trustedHtml(safe);\n const first = host.content.firstElementChild;\n if (!first) return null;\n const key = readKey(value);\n if (key !== undefined) first.setAttribute(KEY_ATTRIBUTE, key);\n return first;\n}\n","/**\n * Runs the fragment and route strategies for a revision. A strategy that\n * throws or rejects is treated as failed, never left to reject the runtime.\n */\n\nimport type { PayloadLivePreviewData } from '@/types/payload-protocol';\nimport { trustedHtml } from '@security/trusted-types';\nimport { resolveFieldValue } from './field-value';\nimport { morphElement } from './morph';\nimport type { RuntimeDeps, RuntimeState, UpdateTransaction } from './runtime-state';\nimport type { FragmentContext, FragmentStrategy, RouteStrategy } from './strategies';\nimport { KEY_ATTRIBUTE } from './structural-applier';\nimport type { CachedElement } from './types';\n\n/** What the pipeline lends the runner. */\nexport interface StrategyHost {\n readonly reapply: (transaction: UpdateTransaction, data: PayloadLivePreviewData) => void;\n readonly transform: (\n target: CachedElement,\n value: unknown,\n allFields: Record<string, unknown>,\n isCurrent: () => boolean,\n ) => unknown;\n readonly rebuildCache: () => void;\n /** Scroll to the binding this revision marked, if it has not been revealed yet. */\n readonly revealPending: (transaction: UpdateTransaction) => void;\n}\n\nexport interface FragmentPlan {\n readonly boundaries: readonly Element[];\n readonly strategy: FragmentStrategy;\n /** Whether a binding sits inside a boundary the strategy renders this revision. */\n readonly covers: (target: CachedElement) => boolean;\n}\n\nexport class StrategyRunner {\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n private readonly host: StrategyHost,\n ) {}\n\n planFragments(touched: ReadonlySet<string>): FragmentPlan | null {\n const strategy = this.deps.strategies.fragment;\n if (strategy === undefined) return null;\n const boundaries = strategy.plan(this.deps.root, touched);\n const covered = new Set(boundaries);\n return {\n boundaries,\n strategy,\n covers: (target) =>\n target.fragmentBoundary !== undefined && covered.has(target.fragmentBoundary),\n };\n }\n\n /** Whether a touched field is bound to an element the route owns. */\n hasRouteBinding(touched: ReadonlySet<string>): boolean {\n for (const [fieldName, bindings] of this.deps.cache.entries()) {\n if (!touched.has(fieldName)) continue;\n if (bindings.some((target) => target.strategyKind === 'route')) return true;\n }\n return false;\n }\n\n async runFragments(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n plan: FragmentPlan,\n ): Promise<void> {\n const { deps, state } = this;\n const controller = new AbortController();\n state.fragmentController = controller;\n const isCurrent = (): boolean => state.isCurrent(transaction) && !controller.signal.aborted;\n const { emitter } = deps;\n const { message } = transaction;\n const revision = transaction.identity.revision;\n const receivedAt = transaction.receivedAt;\n const context: FragmentContext = {\n root: deps.root,\n revision,\n receivedAt,\n fields: data.fields,\n locale: transaction.locale,\n collectionSlug:\n typeof message.collectionSlug === 'string' ? message.collectionSlug : undefined,\n globalSlug: typeof message.globalSlug === 'string' ? message.globalSlug : undefined,\n signal: controller.signal,\n isCurrent,\n log: (code, detail) => {\n deps.log('fragment', code, detail);\n },\n morph: (boundary, html) => {\n morphFragment(boundary, html);\n },\n patch: (boundary) => {\n this.patchFallback(transaction, data, boundary);\n },\n rendered: (element, id, key) => {\n transaction.pendingFragments -= 1;\n void emitter.emitWhile(\n 'fragmentRender',\n { element, id, key, status: 'rendered', revision, receivedAt },\n isCurrent,\n );\n },\n failed: (element, id, key, code, reason) => {\n transaction.pendingFragments -= 1;\n void emitter.emitWhile(\n 'error',\n {\n error: new Error(`fragment \"${id}\" fell back to patch: ${reason}`),\n context: 'fragment',\n code,\n },\n isCurrent,\n );\n void emitter.emitWhile(\n 'fragmentRender',\n { element, id, key, status: 'failed', code, revision, receivedAt },\n isCurrent,\n );\n },\n };\n let report = { rendered: 0, failed: 0, superseded: 0 };\n try {\n report = await plan.strategy.render(context, plan.boundaries);\n } catch (error) {\n deps.log('fragment', 'LP0801', error);\n if (isCurrent()) {\n for (const boundary of plan.boundaries) this.patchFallback(transaction, data, boundary);\n report = { rendered: 0, failed: plan.boundaries.length, superseded: 0 };\n }\n }\n state.fragmentStats.rendered += report.rendered;\n state.fragmentStats.failed += report.failed;\n state.fragmentStats.superseded += report.superseded;\n if (!isCurrent()) return;\n if (state.fragmentController === controller) state.fragmentController = null;\n transaction.pendingFragments = 0;\n if (deps.scheduler.pendingCount === 0) state.complete(transaction);\n // The edited field may be one the server just rendered: its element is only\n // in place now, so this is the earliest point it can be scrolled to.\n this.host.revealPending(transaction);\n if (!isCurrent()) return;\n if (report.rendered === 0 || emitter.listenerCount('afterUpdate') === 0) return;\n void emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n updatedCount: report.rendered,\n durationMs: Date.now() - receivedAt,\n revision,\n receivedAt,\n source: 'fragment',\n },\n isCurrent,\n );\n }\n\n /** Refresh the route once per revision, then re-apply the revision onto the fresh markup. */\n async refreshRoute(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n strategy: RouteStrategy,\n ): Promise<void> {\n const { deps, state } = this;\n const stats = state.routeStats;\n if (transaction.routeRefreshed) {\n stats.loopStopped += 1;\n deps.log(\n 'route',\n 'LP0805',\n `revision ${String(transaction.identity.revision)} asked for a second refresh`,\n );\n return;\n }\n transaction.routeRefreshed = true;\n const controller = new AbortController();\n state.routeController = controller;\n const isCurrent = (): boolean => state.isCurrent(transaction) && !controller.signal.aborted;\n let outcome: 'refreshed' | 'failed' | 'superseded';\n try {\n outcome = await strategy.refresh({\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n signal: controller.signal,\n isCurrent,\n log: (code, detail) => {\n deps.log('route', code, detail);\n },\n });\n } catch (error) {\n deps.log('route', 'LP0801', error);\n outcome = 'failed';\n }\n if (!isCurrent()) return;\n if (state.routeController === controller) state.routeController = null;\n if (outcome === 'refreshed') {\n stats.refreshes += 1;\n // The route rendered the saved document; nothing on the page is \"last applied\" any more.\n state.lastAppliedIdentity = new WeakMap();\n this.host.rebuildCache();\n if (!isCurrent()) return;\n this.host.reapply(transaction, data);\n if (deps.emitter.listenerCount('afterUpdate') > 0) {\n void deps.emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n // The server re-rendered the whole route, so every binding now on\n // the page carries fresh markup; the unsaved fields scheduled just\n // above report themselves in their own `patch` batch.\n updatedCount: deps.cache.elementCount,\n durationMs: Date.now() - transaction.receivedAt,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'route',\n },\n isCurrent,\n );\n }\n return;\n }\n if (outcome === 'failed') stats.failed += 1;\n this.host.reapply(transaction, data);\n }\n\n /** LP0806, once: a fragment boundary with no handler is patched instead. */\n warnFragmentFallback(target: CachedElement): void {\n if (this.state.warnedFragmentFallback) return;\n this.state.warnedFragmentFallback = true;\n this.deps.warn(\n `[live-preview] LP0806: \"${target.fieldName}\" asks for the fragment strategy but no handler is configured; patching instead`,\n );\n }\n\n /** LP0407, once per element: an unknown strategy is left alone, not guessed at. */\n warnUnsupportedStrategy(target: CachedElement): void {\n if (this.state.warnedStrategy.has(target.element)) return;\n this.state.warnedStrategy.add(target.element);\n this.deps.warn(\n `[live-preview] LP0407: \"${target.fieldName}\" asks for strategy \"${String(target.strategy)}\"; only patch, fragment and route exist`,\n );\n }\n\n /** The deterministic fallback: patch the boundary's own bindings from the same revision. */\n private patchFallback(\n transaction: UpdateTransaction,\n data: PayloadLivePreviewData,\n boundary: Element,\n ): void {\n for (const [fieldName, bindings] of this.deps.cache.entries()) {\n for (const target of bindings) {\n if (target.fragmentBoundary !== boundary) continue;\n const value = resolveFieldValue(\n data.fields,\n fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n if (value === undefined) continue;\n this.deps.scheduler.schedule({\n target,\n value: this.host.transform(target, value, data.fields, () => true),\n allFields: data.fields,\n identity: transaction.identity,\n data,\n });\n }\n }\n }\n}\n\n/** Morph server-rendered HTML into the boundary, keeping focus and visitor state. */\nfunction morphFragment(boundary: Element, html: string): void {\n const template = boundary.ownerDocument.createElement('template');\n template.innerHTML = trustedHtml(html);\n const rendered = boundary.cloneNode(false) as Element;\n rendered.append(template.content);\n morphElement(boundary, rendered, { keyAttributes: [KEY_ATTRIBUTE] });\n}\n","/**\n * From an accepted message to scheduled writes: merge, diff, plan the\n * strategies, schedule each binding, and finish the revision on flush.\n */\n\nimport type { PayloadLivePreviewData, PayloadLivePreviewMessage } from '@/types/payload-protocol';\nimport { buildSchemaIndex } from '@schema/index';\nimport { isBindingInScope, messageOwnerKeys, readDocumentId } from './binding-owner';\nimport { mergeDependencyMaps } from './dependencies';\nimport { resolveFieldValue } from './field-value';\nimport { dispatchIslandUpdate } from './islands';\nimport type { MessageRevision } from './message-bus';\nimport { diagnoseOrphanFields } from './orphan-diagnostics';\nimport { detectProtocolProfile } from './protocol-profile';\nimport { observeCapabilities } from './protocol-version';\nimport type { RevealWindow } from './reveal';\nimport {\n sameRevision,\n type RuntimeDeps,\n type RuntimeState,\n type UpdateTransaction,\n} from './runtime-state';\nimport { resolveStrategy } from './strategies';\nimport { StrategyRunner } from './strategy-runner';\nimport { observeThenableResult } from './thenable';\nimport type { CachedElement } from './types';\nimport type { FlushStats, ScheduledUpdate } from './update-scheduler';\nimport { valueIdentity } from './value-identity';\n\nexport class UpdatePipeline {\n private readonly strategies: StrategyRunner;\n\n constructor(\n private readonly deps: RuntimeDeps,\n private readonly state: RuntimeState,\n rebuildCache: () => void,\n ) {\n this.strategies = new StrategyRunner(deps, state, {\n reapply: (transaction, data) => {\n this.scheduleAllFields(transaction, data);\n },\n transform: (target, value, allFields, isCurrent) =>\n this.transformForBinding(target, value, allFields, isCurrent),\n rebuildCache,\n revealPending: (transaction) => {\n this.revealPending(transaction);\n },\n });\n }\n\n /** Message-bus callback for every shape-valid update. */\n handleUpdate(\n message: PayloadLivePreviewMessage,\n origin: string,\n identity: MessageRevision | undefined,\n ): void {\n const { deps, state } = this;\n deps.heartbeat.kick();\n state.protocol.observe(observeCapabilities(message), deps.log);\n if (message.data === undefined) {\n if (message.protocolVersion !== undefined) {\n state.protocol.applyVersion(message.protocolVersion, deps.log);\n }\n return;\n }\n if (identity === undefined) return;\n const relationship = message.externallyUpdatedRelationship;\n const relationshipEdited = typeof relationship === 'object' && relationship !== null;\n if (relationshipEdited) {\n void deps.emitter.emit('relationshipUpdate', { detail: relationship, timestamp: Date.now() });\n }\n if (typeof message.locale === 'string') state.locale = message.locale;\n if (Array.isArray(message.fieldSchemaJSON)) {\n state.schema = message.fieldSchemaJSON;\n state.schemaIndex = buildSchemaIndex(message.fieldSchemaJSON);\n }\n const transaction: UpdateTransaction = {\n identity,\n message,\n locale: state.locale,\n schema: state.schema,\n schemaIndex: state.schemaIndex,\n receivedAt: Date.now(),\n forceRender: relationshipEdited,\n touched: new Set(),\n invalidated: new Set(),\n revealTarget: undefined,\n revealIdentities: [],\n pendingFragments: 0,\n routeRefreshed: false,\n cancelled: false,\n completed: false,\n };\n // Acceptance is the single supersession point. Only a revision that never\n // reached its terminal state counts as superseded.\n const previous = state.activeUpdate;\n state.abortStrategies();\n if (previous !== null && !previous.completed) state.supersededCount += 1;\n state.activeUpdate = transaction;\n deps.scheduler.acceptRevision(identity);\n state.updateCount += 1;\n if (message.protocolVersion !== undefined) {\n state.protocol.applyVersion(message.protocolVersion, deps.log);\n if (!state.isCurrent(transaction)) return;\n }\n if (deps.connection.markConnected()) {\n deps.a11y?.announceConnected();\n void deps.emitter.emit('connect', { origin, timestamp: Date.now() });\n if (!state.isCurrent(transaction)) return;\n deps.log('connection', 'disconnected', '→', 'connected');\n if (!state.isCurrent(transaction)) return;\n }\n // Nothing awaits this, so an unexpected throw would leave the page as an\n // unhandled rejection — a console error the host cannot attribute, and a\n // process exit under `--unhandled-rejections=strict`.\n void this.processUpdate(transaction).catch((error: unknown) => {\n deps.log('update failed:', error);\n });\n }\n\n private async processUpdate(transaction: UpdateTransaction): Promise<void> {\n const { deps, state } = this;\n const fields = await this.resolveIncomingFields(transaction);\n if (fields === null || !state.isCurrent(transaction)) return;\n const { message } = transaction;\n const data: PayloadLivePreviewData = {\n fields,\n ...(transaction.schema !== undefined ? { schema: transaction.schema } : {}),\n ...(typeof message.globalSlug === 'string' ? { globalSlug: message.globalSlug } : {}),\n ...(typeof message.collectionSlug === 'string'\n ? { collectionSlug: message.collectionSlug }\n : {}),\n ...(transaction.locale !== undefined ? { locale: transaction.locale } : {}),\n };\n if (deps.emitter.listenerCount('beforeUpdate') > 0) {\n const completed = await deps.emitter.emitWhile(\n 'beforeUpdate',\n {\n data,\n revision: transaction.identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n cancel: (): void => {\n transaction.cancelled = true;\n deps.scheduler.cancelRevision(transaction.identity);\n },\n },\n () => !transaction.cancelled && state.isCurrent(transaction),\n );\n if (!completed || transaction.cancelled || !state.isCurrent(transaction)) return;\n }\n const dependencies = mergeDependencyMaps(deps.dependencies, deps.cache.dependencyMap());\n const changes = state.changes.diff(fields, dependencies);\n transaction.invalidated = changes.invalidated;\n transaction.touched = new Set([...changes.changed, ...changes.invalidated]);\n this.scheduleAllFields(transaction, data);\n }\n\n /** The merged document when a `DataMerger` is configured, else the raw form values; `null` when superseded. */\n private async resolveIncomingFields(\n transaction: UpdateTransaction,\n ): Promise<Record<string, unknown> | null> {\n const { deps, state } = this;\n const raw = transaction.message.data ?? {};\n if (deps.merger === null) return raw;\n // A Payload 2.x admin posts populated relationships itself.\n if (detectProtocolProfile(state.protocol.observed).populatesRelationships === 'admin') {\n return raw;\n }\n const { message } = transaction;\n const result = await deps.merger.merge({\n collectionSlug: message.collectionSlug,\n globalSlug: message.globalSlug,\n data: raw,\n locale: transaction.locale,\n });\n if (!state.isCurrent(transaction)) return null;\n if (result.status === 'merged') return result.doc;\n if (result.status === 'superseded') return null;\n return raw;\n }\n\n scheduleAllFields(transaction: UpdateTransaction, data: PayloadLivePreviewData): void {\n const { deps, state } = this;\n if (!state.isCurrent(transaction)) return;\n const isCurrent = (): boolean => state.isCurrent(transaction);\n const ownerKeys = this.ownerKeysForUpdate(transaction, data.fields);\n const { touched } = transaction;\n // A revision that touches the route refreshes it first; the re-apply lands on the fresh markup.\n const route = deps.strategies.route;\n if (\n route !== undefined &&\n !transaction.routeRefreshed &&\n (route.plan(deps.root, touched) || this.strategies.hasRouteBinding(touched))\n ) {\n void this.strategies.refreshRoute(transaction, data, route);\n return;\n }\n const plan = this.strategies.planFragments(touched);\n // Only `skipUnchanged` needs it now; the reveal keeps its own ledger.\n const trackIdentity = deps.skipUnchanged;\n let scheduled = 0;\n for (const [fieldName, bindings] of deps.cache.entries()) {\n if (!isCurrent()) return;\n for (const target of bindings) {\n if (ownerKeys !== false && !isBindingInScope(target.owner, ownerKeys)) continue;\n // A binding inside a boundary the server renders is patched only as the\n // fallback — but it can still be the field being edited, so the reveal\n // has to notice it here, before the boundary is re-rendered.\n if (plan?.covers(target) === true) {\n // Resolving the value is only worth it when something reveals.\n if (deps.revealEditedField) {\n this.noteRevealCandidate(transaction, target, this.rawValue(transaction, target, data));\n }\n continue;\n }\n const kind = target.strategyKind ?? resolveStrategy(target.element) ?? 'unknown';\n if (kind === 'unknown') {\n this.strategies.warnUnsupportedStrategy(target);\n continue;\n }\n if (kind === 'fragment' && plan === null) this.strategies.warnFragmentFallback(target);\n const value = resolveFieldValue(\n data.fields,\n fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n if (value === undefined) {\n state.absentFields.add(fieldName);\n continue;\n }\n // Noted before `skipUnchanged` can skip the write: the reveal ledger is\n // its own record, and a binding whose write is unchanged since the last\n // one that landed may still be the field whose reveal was superseded.\n this.noteRevealCandidate(transaction, target, value);\n if (!isCurrent()) return;\n const transformed = this.transformForBinding(target, value, data.fields, isCurrent);\n if (!isCurrent()) return;\n // A binding renders its own value *and* the sibling fields bound to\n // href/src/alt, so its identity must cover them: otherwise an edit to\n // the sibling alone looks unchanged and the link or image stays stale.\n const identity = trackIdentity\n ? bindingIdentity(target, transformed, data.fields, transaction.locale)\n : undefined;\n const last = state.lastAppliedIdentity.get(target.element);\n if (\n !transaction.forceRender &&\n deps.skipUnchanged &&\n identity !== undefined &&\n last === identity &&\n !transaction.invalidated.has(fieldName)\n ) {\n state.skippedUnchangedCount += 1;\n continue;\n }\n const update: ScheduledUpdate = {\n target,\n value: transformed,\n allFields: data.fields,\n identity: transaction.identity,\n data,\n valueIdentity: identity,\n };\n deps.scheduler.schedule(update);\n scheduled += 1;\n }\n }\n diagnoseOrphanFields(\n { cache: deps.cache, warned: state.warnedOrphanFields, warn: deps.warn },\n data.fields,\n transaction.locale,\n ownerKeys,\n );\n if (plan !== null && plan.boundaries.length > 0) {\n transaction.pendingFragments = plan.boundaries.length;\n void this.strategies.runFragments(transaction, data, plan);\n }\n // Nothing to flush is still this revision reaching its end — and its reveal\n // point: every write may be unchanged while the reveal is still owed.\n if (scheduled === 0 && transaction.pendingFragments === 0) {\n state.complete(transaction);\n this.revealPending(transaction);\n }\n }\n\n private rawValue(\n transaction: UpdateTransaction,\n target: CachedElement,\n data: PayloadLivePreviewData,\n ): unknown {\n return resolveFieldValue(\n data.fields,\n target.fieldName,\n target.locale ?? transaction.locale,\n target.locale !== undefined,\n );\n }\n\n /**\n * Record what this binding's value looks like now and, for the first binding\n * whose value moved, mark it as the one to reveal.\n *\n * The first message is a baseline and a binding new to the page is not an\n * edit, so an unseen key only records. A value too large or cyclic to compare\n * cannot claim to have changed either, or it would take the reveal from a\n * field that did. The ledger is keyed by document, locale and field rather\n * than by element: the element a fragment renders does not survive its own\n * re-render, but the field it shows is the same field.\n */\n private noteRevealCandidate(\n transaction: UpdateTransaction,\n target: CachedElement,\n value: unknown,\n ): void {\n const { deps, state } = this;\n if (!deps.revealEditedField) return;\n const identity = valueIdentity(value);\n if (identity === undefined) return;\n const key = `${target.owner ?? ''}\\u0000${target.locale ?? ''}\\u0000${target.fieldName}`;\n const seen = state.seenFieldIdentity.get(key);\n if (seen === undefined) {\n // A baseline is recorded at once: nothing is owed for it.\n state.seenFieldIdentity.set(key, identity);\n return;\n }\n if (seen === identity) return;\n transaction.revealIdentities.push([key, identity]);\n transaction.revealTarget ??= target;\n }\n\n /** Owner keys this update may address; `false` when scoping is off, `null` when the message names no document. */\n private ownerKeysForUpdate(\n transaction: UpdateTransaction,\n fields: Record<string, unknown>,\n ): readonly string[] | null | false {\n const { deps, state } = this;\n if (!deps.scopeBindingsByOwner) return false;\n const { message } = transaction;\n const keys = messageOwnerKeys({\n globalSlug: typeof message.globalSlug === 'string' ? message.globalSlug : undefined,\n collectionSlug:\n typeof message.collectionSlug === 'string' ? message.collectionSlug : undefined,\n documentId: readDocumentId(fields),\n });\n if (keys === null && !state.warnedUnattributableMessage) {\n state.warnedUnattributableMessage = true;\n deps.warn(\n '[live-preview] LP0202: scopeBindingsByOwner: update names no document; nothing applied',\n );\n }\n return keys;\n }\n\n /** Transforms are plugin code: frozen into the scheduler entry, errors reported, never awaited. */\n private transformForBinding(\n target: CachedElement,\n originalValue: unknown,\n allFields: Record<string, unknown>,\n isCurrent: () => boolean,\n ): unknown {\n const transform = this.deps.transformValue;\n if (transform === undefined) return originalValue;\n try {\n const transformed = transform(\n target.fieldName,\n originalValue,\n { element: target.element, allFields },\n isCurrent,\n );\n const returnedThenable = observeThenableResult(transformed);\n if (!isCurrent()) return originalValue;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${target.fieldName}\" returned a thenable; transforms must be synchronous`,\n );\n }\n return transformed;\n } catch (err) {\n if (!isCurrent()) return originalValue;\n const error = err instanceof Error ? err : new Error(String(err));\n void this.deps.emitter.emit('error', { error, context: 'transform', code: 'LP0602' });\n return originalValue;\n }\n }\n\n /** Scheduler callback after every flush, including one that applied nothing. */\n onFlush(stats: FlushStats): void {\n const { deps, state } = this;\n state.lastFlush = stats;\n if (stats.deferred > 0 && !state.warnedVisibilityGate) {\n state.warnedVisibilityGate = true;\n deps.warn(\n `[live-preview] LP0301: visibility gate held ${String(stats.deferred)} off-screen update(s) until scrolled into view; see visibilityGateThreshold`,\n );\n }\n const { identity, data } = stats;\n if (identity === undefined) return;\n const transaction = state.activeUpdate;\n if (\n transaction === null ||\n !state.isCurrent(transaction) ||\n !sameRevision(transaction.identity, identity)\n ) {\n return;\n }\n if (transaction.pendingFragments === 0) state.complete(transaction);\n const isCurrent = (): boolean =>\n state.isCurrent(transaction) && sameRevision(transaction.identity, identity);\n // Reveal before the applied check: the edited element may be exactly the\n // off-screen one the visibility gate deferred, and scrolling to it is what replays it.\n this.revealPending(transaction);\n if (!isCurrent()) return;\n if (stats.applied === 0 || data === undefined) return;\n deps.a11y?.announceUpdate(stats.applied);\n if (!isCurrent()) return;\n dispatchIslandUpdate(deps.cache.islands, {\n fields: data.fields,\n revision: identity.revision,\n receivedAt: transaction.receivedAt,\n locale: transaction.locale,\n });\n if (!isCurrent() || deps.emitter.listenerCount('afterUpdate') === 0) return;\n void deps.emitter.emitWhile(\n 'afterUpdate',\n {\n data,\n updatedCount: stats.applied,\n durationMs: stats.durationMs,\n revision: identity.revision,\n receivedAt: transaction.receivedAt,\n source: 'patch',\n },\n isCurrent,\n );\n }\n\n /**\n * Reveal the binding this revision marked, once. Called from the patch flush\n * and again once fragments land, because only one of the two runs for any\n * given field, and a fragment-rendered element is in place only afterwards.\n */\n revealPending(transaction: UpdateTransaction): void {\n // This revision reached its reveal point, so what it saw is now what the\n // ledger shows — whether or not the scroll below has anything to do.\n for (const [key, identity] of transaction.revealIdentities) {\n this.state.seenFieldIdentity.set(key, identity);\n }\n transaction.revealIdentities = [];\n const target = transaction.revealTarget;\n if (target === undefined) return;\n transaction.revealTarget = undefined;\n try {\n this.revealBinding(target);\n } catch (error) {\n this.deps.log('reveal', error);\n }\n }\n\n /**\n * Scroll one field's bound element into view; the admin-focus path (tier 2)\n * names a field, so it takes the first binding — a focus message carries no\n * document identity to choose between several.\n */\n revealField(fieldName: string): 'revealed' | 'already-visible' | 'skipped-same' | 'no-element' {\n const target = this.deps.cache.get(fieldName)?.[0];\n if (target === undefined) return 'no-element';\n return this.revealBinding(target);\n }\n\n private revealBinding(\n target: CachedElement,\n ): 'revealed' | 'already-visible' | 'skipped-same' | 'no-element' {\n const { element } = target;\n const win = element.ownerDocument.defaultView as RevealWindow | null;\n if (win === null) return 'no-element';\n // Keyed by document as well as field: two documents on one page have their\n // own `title`, and revealing one must not count as revealing the other.\n const key = `${target.owner ?? ''} ${target.fieldName}`;\n return this.state.revealer.reveal(key, element, win);\n }\n}\n\n/** Identity of everything a binding renders: its value plus any sibling href/src/alt fields. */\nfunction bindingIdentity(\n target: CachedElement,\n value: unknown,\n fields: Record<string, unknown>,\n locale: string | undefined,\n): string | undefined {\n const own = valueIdentity(value);\n if (own === undefined) return undefined;\n const siblings = [target.hrefField, target.srcField, target.altField];\n let combined = own;\n for (const sibling of siblings) {\n if (sibling === undefined || sibling.length === 0) continue;\n const resolved = resolveFieldValue(\n fields,\n sibling,\n target.locale ?? locale,\n target.locale !== undefined,\n );\n const identity = valueIdentity(resolved);\n if (identity === undefined) return undefined;\n combined += `|${sibling}=${identity}`;\n }\n return combined;\n}\n","/**\n * Debounce, frame batching and off-screen replay for scheduled writes. The\n * scheduler never touches the DOM; the injected `apply` callback does.\n */\n\nimport type { PayloadLivePreviewData } from '@/types/payload-protocol';\nimport { usesNoWriteOutcome } from './internal-outcome';\nimport type { MessageRevision } from './message-bus';\nimport type { CachedElement } from './types';\n\nexport interface ScheduledUpdate {\n readonly target: CachedElement;\n readonly value: unknown;\n readonly allFields: Record<string, unknown>;\n /** Revision identity; runtime-produced entries always carry one. */\n readonly identity?: MessageRevision | undefined;\n readonly data?: PayloadLivePreviewData | undefined;\n /** `valueIdentity(value)`, computed once by the pipeline for skip and reveal. */\n readonly valueIdentity?: string | undefined;\n}\n\nexport type ApplyUpdate = (update: ScheduledUpdate) => void;\n\nexport interface UpdateSchedulerOptions {\n /** Debounce window in ms. Default 50. */\n readonly debounceMs?: number;\n /** Longest a flush may be postponed by continuous scheduling. Default `4 * debounceMs`. */\n readonly maxWaitMs?: number;\n /** Deferred writes replay when the host reports the element visible via `notifyVisible()`. */\n readonly isVisible: (element: Element) => boolean;\n /** Apply every write immediately regardless of visibility. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cached-element count above which the gate activates. Default 50. */\n readonly visibilityGateThreshold?: number;\n readonly getCacheSize: () => number;\n readonly onFlush?: (stats: FlushStats) => void;\n /** Frame scheduler; defaults to `requestAnimationFrame`. Tests inject a synchronous one. */\n readonly scheduleFrame?: (callback: FrameRequestCallback) => number;\n readonly cancelFrame?: (handle: number) => void;\n}\n\nexport interface FlushStats {\n readonly applied: number;\n /** Field names applied, in order; `applied` alone cannot say which binding stayed stale. */\n readonly appliedFields: readonly string[];\n readonly deferred: number;\n readonly durationMs: number;\n readonly identity?: MessageRevision;\n readonly data?: PayloadLivePreviewData;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 50;\n/** Exported so `pll doctor` can prove its own copy of the number has not drifted. */\nexport const DEFAULT_VISIBILITY_THRESHOLD = 50;\n\ninterface BufferEntry {\n target: CachedElement;\n value: unknown;\n allFields: Record<string, unknown>;\n identity: MessageRevision | undefined;\n data: PayloadLivePreviewData | undefined;\n valueIdentity: string | undefined;\n}\n\nexport class UpdateScheduler {\n private readonly apply: ApplyUpdate;\n private readonly debounceMs: number;\n private readonly maxWaitMs: number;\n private readonly isVisible: (element: Element) => boolean;\n private readonly gateThresholdValue: number;\n private readonly gateDisabled: boolean;\n private readonly getCacheSize: () => number;\n private readonly onFlush: ((stats: FlushStats) => void) | undefined;\n private readonly scheduleFrame: (callback: FrameRequestCallback) => number;\n private readonly cancelFrame: (handle: number) => void;\n private pending = new Map<Element, BufferEntry>();\n private readonly replay = new Map<Element, BufferEntry>();\n private readonly activeFlushes = new Set<Map<Element, BufferEntry>>();\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private debounceToken = 0;\n private deadlineTimer: ReturnType<typeof setTimeout> | null = null;\n private frameHandle: number | null = null;\n private frameToken = 0;\n private activeIdentity: MessageRevision | null = null;\n private activeRevisionCancelled = false;\n\n constructor(apply: ApplyUpdate, options: UpdateSchedulerOptions) {\n this.apply = apply;\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.maxWaitMs = options.maxWaitMs ?? this.debounceMs * 4;\n this.isVisible = options.isVisible;\n this.gateThresholdValue = options.visibilityGateThreshold ?? DEFAULT_VISIBILITY_THRESHOLD;\n this.gateDisabled = options.disableVisibilityGate ?? false;\n this.getCacheSize = options.getCacheSize;\n this.onFlush = options.onFlush;\n this.scheduleFrame =\n options.scheduleFrame ??\n (typeof requestAnimationFrame === 'function'\n ? requestAnimationFrame.bind(globalThis)\n : (callback) =>\n setTimeout(() => {\n callback(performance.now());\n }, 0) as unknown as number);\n this.cancelFrame =\n options.cancelFrame ??\n (typeof cancelAnimationFrame === 'function'\n ? cancelAnimationFrame.bind(globalThis)\n : (handle) => {\n clearTimeout(handle as unknown as ReturnType<typeof setTimeout>);\n });\n }\n\n /** Queue a write; a later write for the same element replaces it until the flush. */\n schedule(update: ScheduledUpdate): void {\n if (update.identity !== undefined) {\n if (this.activeRevisionCancelled) return;\n if (!sameIdentity(update.identity, this.activeIdentity)) return;\n }\n const existing = this.pending.get(update.target.element);\n if (existing) {\n existing.value = update.value;\n existing.allFields = update.allFields;\n existing.identity = update.identity;\n existing.data = update.data;\n existing.valueIdentity = update.valueIdentity;\n } else {\n this.pending.set(update.target.element, {\n target: update.target,\n value: update.value,\n allFields: update.allFields,\n identity: update.identity,\n data: update.data,\n valueIdentity: update.valueIdentity,\n });\n }\n this.armDebounce();\n }\n\n /**\n * Make `identity` the sole revision allowed to schedule, flush or replay.\n * Older buffered work is dropped even if the new revision is later cancelled.\n */\n acceptRevision(identity: MessageRevision): void {\n if (sameIdentity(identity, this.activeIdentity)) return;\n if (this.activeIdentity !== null && compareIdentity(identity, this.activeIdentity) < 0) return;\n this.cancelScheduledWork();\n this.clearWork();\n this.activeIdentity = identity;\n this.activeRevisionCancelled = false;\n }\n\n /** Cancel buffered work for exactly one revision without reviving its predecessor. */\n cancelRevision(identity: MessageRevision): void {\n if (!sameIdentity(identity, this.activeIdentity)) return;\n this.cancelScheduledWork();\n this.clearWork();\n this.activeRevisionCancelled = true;\n }\n\n /** Flush immediately, bypassing the debounce. */\n flushNow(): FlushStats {\n this.cancelScheduledWork();\n return this.flush();\n }\n\n /** Apply the buffered value for an element that scrolled into view. */\n notifyVisible(element: Element): void {\n const entry = this.replay.get(element);\n if (!entry) return;\n this.replay.delete(element);\n if (!this.isCurrent(entry)) return;\n const t0 = performance.now();\n const applied = this.didApply(entry) ? 1 : 0;\n this.onFlush?.(\n this.statsFor(\n entry,\n applied,\n 0,\n performance.now() - t0,\n applied === 1 ? [entry.target.fieldName] : [],\n ),\n );\n }\n\n /**\n * Point buffered work at a rebuilt cache entry for the same element and\n * field. A different field or locale is a different binding: drop the work.\n */\n retarget(target: CachedElement): void {\n this.retargetBuffer(this.pending, target);\n this.retargetBuffer(this.replay, target);\n for (const flush of this.activeFlushes) this.retargetBuffer(flush, target);\n }\n\n forget(element: Element): void {\n this.pending.delete(element);\n this.replay.delete(element);\n for (const flush of this.activeFlushes) flush.delete(element);\n }\n\n /** Cancel timers and drop buffered state without draining it. */\n destroy(): void {\n this.cancelScheduledWork();\n this.clearWork();\n this.activeIdentity = null;\n this.activeRevisionCancelled = false;\n }\n\n get pendingCount(): number {\n return this.pending.size;\n }\n\n get replayCount(): number {\n return this.replay.size;\n }\n\n get gateThreshold(): number {\n return this.gateThresholdValue;\n }\n\n get gateActive(): boolean {\n return !this.gateDisabled && this.getCacheSize() > this.gateThresholdValue;\n }\n\n private armDebounce(): void {\n const token = (this.debounceToken += 1);\n const timer = this.debounceTimer;\n this.debounceTimer = null;\n if (timer !== null) clearTimeout(timer);\n // clearTimeout is a host boundary; a reentrant schedule owns a newer token.\n if (this.debounceToken !== token) return;\n const next = setTimeout(() => {\n if (this.debounceToken !== token) return;\n this.debounceTimer = null;\n this.requestFrame();\n }, this.debounceMs);\n if (this.debounceToken === token) this.debounceTimer = next;\n // Continuous scheduling (key repeat) must not postpone the flush forever.\n if (this.deadlineTimer === null && this.maxWaitMs > this.debounceMs) {\n this.deadlineTimer = setTimeout(() => {\n this.deadlineTimer = null;\n if (this.pending.size > 0) this.requestFrame();\n }, this.maxWaitMs);\n }\n }\n\n private requestFrame(): void {\n const token = (this.frameToken += 1);\n const handle = this.frameHandle;\n this.frameHandle = null;\n if (handle !== null) this.cancelFrame(handle);\n if (this.frameToken !== token) return;\n let completed = false;\n const next = this.scheduleFrame(() => {\n if (this.frameToken !== token) return;\n completed = true;\n this.frameHandle = null;\n this.flush();\n });\n // An injected scheduler may run the callback synchronously; never publish a spent handle.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!completed && this.frameToken === token) this.frameHandle = next;\n }\n\n private flush(): FlushStats {\n const t0 = performance.now();\n this.clearDeadline();\n const gateActive = this.gateActive;\n const pending = this.pending;\n this.pending = new Map();\n let applied = 0;\n const appliedFields: string[] = [];\n let deferred = 0;\n let batchEntry: BufferEntry | undefined;\n this.activeFlushes.add(pending);\n try {\n for (const entry of pending.values()) {\n if (!this.isCurrent(entry)) continue;\n const visible = !gateActive || this.isVisible(entry.target.element);\n // The visibility callback is consumer code and may change the revision.\n if (!this.isCurrent(entry)) continue;\n batchEntry ??= entry;\n if (!visible) {\n this.replay.set(entry.target.element, entry);\n deferred += 1;\n continue;\n }\n this.replay.delete(entry.target.element);\n if (this.didApply(entry)) {\n applied += 1;\n appliedFields.push(entry.target.fieldName);\n }\n }\n } finally {\n this.activeFlushes.delete(pending);\n }\n const stats = this.statsFor(\n batchEntry,\n applied,\n deferred,\n performance.now() - t0,\n appliedFields,\n );\n this.onFlush?.(stats);\n return stats;\n }\n\n private isCurrent(entry: BufferEntry): boolean {\n return (\n entry.identity === undefined ||\n (!this.activeRevisionCancelled && sameIdentity(entry.identity, this.activeIdentity))\n );\n }\n\n private didApply(entry: BufferEntry): boolean {\n // Only a runtime-marked callback may report exact `false` as \"no write\".\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const outcome: unknown = this.apply(entry);\n return outcome !== false || !usesNoWriteOutcome(this.apply);\n }\n\n private retargetBuffer(buffer: Map<Element, BufferEntry>, target: CachedElement): void {\n const entry = buffer.get(target.element);\n if (entry === undefined) return;\n if (entry.target.fieldName !== target.fieldName || entry.target.locale !== target.locale) {\n buffer.delete(target.element);\n return;\n }\n entry.target = target;\n }\n\n private clearWork(): void {\n this.pending.clear();\n this.replay.clear();\n for (const flush of this.activeFlushes) flush.clear();\n }\n\n private statsFor(\n entry: BufferEntry | undefined,\n applied: number,\n deferred: number,\n durationMs: number,\n appliedFields: readonly string[],\n ): FlushStats {\n return {\n applied,\n appliedFields,\n deferred,\n durationMs,\n ...(entry?.identity !== undefined ? { identity: entry.identity } : {}),\n ...(entry?.data !== undefined ? { data: entry.data } : {}),\n };\n }\n\n private clearDeadline(): void {\n if (this.deadlineTimer === null) return;\n clearTimeout(this.deadlineTimer);\n this.deadlineTimer = null;\n }\n\n private cancelScheduledWork(): void {\n const debounceTimer = this.debounceTimer;\n const frameHandle = this.frameHandle;\n // Revoke tokens before calling host cancellation, so a hook that\n // schedules newer work is not clobbered by this older cleanup.\n this.debounceToken += 1;\n this.frameToken += 1;\n this.debounceTimer = null;\n this.frameHandle = null;\n this.clearDeadline();\n if (debounceTimer !== null) clearTimeout(debounceTimer);\n if (frameHandle !== null) this.cancelFrame(frameHandle);\n }\n}\n\nfunction sameIdentity(a: MessageRevision, b: MessageRevision | null): boolean {\n return b !== null && a.generation === b.generation && a.revision === b.revision;\n}\n\nfunction compareIdentity(a: MessageRevision, b: MessageRevision): number {\n if (a.generation !== b.generation) return a.generation - b.generation;\n return a.revision - b.revision;\n}\n","/**\n * `LivePreviewRuntime` builds the primitives, owns their lifecycle and hands\n * accepted messages to the update pipeline. It never speaks postMessage\n * itself and never walks the DOM during an update. See ADR 0004.\n */\n\nimport { A11yAnnouncer } from './a11y';\nimport { BindingWriter } from './binding-writer';\nimport { ElementCache } from './cache';\nimport { DataMerger } from './data-merger';\nimport type { DiagnosticCode } from './diagnostic-codes';\nimport { isolateDiagnostic, noopDiagnostic, safeConsoleWarn } from './diagnostics';\nimport { buildInspection } from './inspection/snapshot';\nimport type { LivePreviewInspection } from './inspection/types';\nimport { markNoWriteCallback } from './internal-outcome';\nimport { isInsideIsland } from './islands';\nimport { MessageBus } from './message-bus';\nimport { ObserverManager } from './observers';\nimport type { ProtocolNegotiation } from './protocol-version';\nimport type { RuntimeOptions } from './runtime-options';\nimport { RuntimeState, type RuntimeDeps } from './runtime-state';\nimport { ConnectionState, HeartbeatTimer } from './state';\nimport type { CachedElement } from './types';\nimport { UpdatePipeline } from './update-pipeline';\nimport { UpdateScheduler } from './update-scheduler';\n\nexport type { RuntimeOptions } from './runtime-options';\nexport { resolveFieldValue } from './field-value';\n\n/** Re-broadcast `ready` a few times to absorb admin-side init latency. */\nconst READY_RETRY_DELAYS_MS = [0, 500, 1000, 2000] as const;\n\nexport class LivePreviewRuntime {\n private readonly deps: RuntimeDeps;\n private readonly state = new RuntimeState();\n private readonly pipeline: UpdatePipeline;\n private readonly writer: BindingWriter;\n /** Watches `<html>` for a swapped `<body>` so the observers follow it. */\n private rootSentinel: MutationObserver | null = null;\n private observedRoot: Node | null = null;\n\n constructor(options: RuntimeOptions) {\n const { emitter, renderers } = options;\n const log = options.log === undefined ? noopDiagnostic : isolateDiagnostic(options.log);\n const warn = options.warn === undefined ? safeConsoleWarn : isolateDiagnostic(options.warn);\n const root =\n options.root ?? (typeof document !== 'undefined' ? document : (null as unknown as Document));\n // Bindings inside a hydrated island are the island's business (ADR 0008 §4).\n const cache = new ElementCache({ filter: (element) => !isInsideIsland(element) });\n const observers = new ObserverManager(\n {\n onStructuralChange: () => {\n this.rebuildCache();\n },\n onVisibilityChange: (element, visible) => {\n if (visible) scheduler.notifyVisible(element);\n },\n },\n options.intersectionRootMargin !== undefined\n ? { intersectionRootMargin: options.intersectionRootMargin }\n : {},\n );\n const scheduler = new UpdateScheduler(\n markNoWriteCallback((update) => this.writer.apply(update)),\n {\n ...(options.debounceMs !== undefined ? { debounceMs: options.debounceMs } : {}),\n ...(options.disableVisibilityGate !== undefined\n ? { disableVisibilityGate: options.disableVisibilityGate }\n : {}),\n ...(options.visibilityGateThreshold !== undefined\n ? { visibilityGateThreshold: options.visibilityGateThreshold }\n : {}),\n isVisible: (element) => observers.isVisible(element),\n getCacheSize: () => cache.elementCount,\n onFlush: (stats) => {\n this.pipeline.onFlush(stats);\n },\n },\n );\n const bus = new MessageBus(options.originMatcher, {\n onUpdate: (message, origin, identity) => {\n this.pipeline.handleUpdate(message, origin, identity);\n },\n onDocumentEvent: () => {\n this.state.protocol.observe(['document-events'], log);\n void emitter.emit('documentSave', { timestamp: Date.now() });\n },\n onFocusField: (field) => {\n if (this.deps.revealEditedField) this.pipeline.revealField(field);\n },\n onInvalid: (reason, origin) => {\n if (reason === 'token') {\n const error = new Error(`Preview token rejected (origin: ${origin})`);\n void emitter.emit('error', { error, context: 'token', code: 'LP0502' });\n }\n log('LP0501 message rejected:', reason, origin);\n },\n ...(options.validateToken !== undefined ? { validateToken: options.validateToken } : {}),\n ...(options.eventSourcePolicy !== undefined\n ? { sourcePolicy: options.eventSourcePolicy }\n : {}),\n });\n const merge = options.dataMerge;\n this.deps = {\n emitter,\n cache,\n observers,\n scheduler,\n bus,\n connection: new ConnectionState(),\n heartbeat: new HeartbeatTimer({\n ...(options.heartbeatMs !== undefined ? { timeoutMs: options.heartbeatMs } : {}),\n onTimeout: () => {\n this.onHeartbeatTimeout();\n },\n }),\n renderers,\n resolveRenderer: options.resolveRenderer ?? ((fieldType) => renderers[fieldType]),\n transformValue: options.transformValue,\n renderRichText: options.renderRichText,\n root,\n readyTargets:\n typeof options.readyTargets === 'function'\n ? options.readyTargets\n : (\n (targets) => (): readonly string[] =>\n targets\n )(options.readyTargets),\n sendReady: options.sendReady ?? defaultSendReady,\n onHeartbeatTimeout: options.onHeartbeatTimeout,\n log,\n warn,\n a11y: createA11y(options),\n merger:\n merge === undefined\n ? null\n : new DataMerger({\n serverURL: merge.serverURL,\n ...(merge.apiRoute !== undefined ? { apiRoute: merge.apiRoute } : {}),\n ...(merge.depth !== undefined ? { depth: merge.depth } : {}),\n ...(merge.fetchFn !== undefined ? { fetchFn: merge.fetchFn } : {}),\n log,\n }),\n scopeBindingsByOwner: options.scopeBindingsByOwner === true,\n lockedOrigin: options.lockedOrigin ?? ((): undefined => undefined),\n skipUnchanged: options.skipUnchanged === true,\n dependencies: options.dependencies ?? {},\n strategies: options.strategies ?? {},\n revealEditedField: options.revealEditedField === true,\n };\n this.writer = new BindingWriter(this.deps, this.state);\n this.pipeline = new UpdatePipeline(this.deps, this.state, () => {\n this.rebuildCache();\n });\n }\n\n /**\n * Build the cache, attach observers and listeners, broadcast `ready`.\n * Returns `false` when already started. While the document is still\n * parsing the real start waits for `DOMContentLoaded`.\n */\n start(): boolean {\n const { state, deps } = this;\n if (state.isRunning()) return false;\n state.started = true;\n state.suspended = false;\n if (isDocumentRoot(deps.root) && deps.root.readyState === 'loading') {\n const onReady = (): void => {\n if (!state.isRunning()) return;\n state.deferredStart = null;\n try {\n this.startNow();\n } catch (error) {\n // start() already returned; roll back and report through the error event.\n this.rollbackFailedStart();\n this.reportError(error, 'startup', 'LP0605');\n }\n };\n state.deferredStart = onReady;\n try {\n deps.root.addEventListener('DOMContentLoaded', onReady, { once: true });\n } catch (error) {\n this.rollbackFailedStart();\n throw error;\n }\n return true;\n }\n try {\n this.startNow();\n return true;\n } catch (error) {\n this.rollbackFailedStart();\n throw error;\n }\n }\n\n private startNow(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const observerRoot: Node | null = isDocumentRoot(deps.root)\n ? readDocumentBody(deps.root)\n : deps.root;\n if (observerRoot === null) throw new Error('LivePreviewRuntime: document.body unavailable');\n deps.observers.start(observerRoot);\n this.observedRoot = observerRoot;\n this.watchRootReplacement();\n // Observers first: the cache scan registers its elements with them.\n this.buildCacheAndObserve();\n if (!state.isRunning()) return;\n deps.bus.attach();\n void deps.emitter.emitWhile('init', { timestamp: Date.now() }, () => state.isRunning());\n if (!state.isRunning()) return;\n for (const delay of READY_RETRY_DELAYS_MS) {\n if (!state.isRunning()) return;\n if (delay === 0) {\n deps.sendReady(deps.readyTargets());\n } else {\n state.readyTimers.push(\n setTimeout(() => {\n if (state.isRunning()) this.sendReadyAfterStart();\n }, delay),\n );\n }\n }\n }\n\n /**\n * Release the message ingress and observers but keep the configuration, so\n * `start()` brings the same instance back — what a back/forward-cache\n * restore needs, since it re-runs no scripts.\n */\n suspend(): boolean {\n if (!this.state.isRunning()) return false;\n const wasConnected = this.release();\n this.state.suspended = true;\n if (wasConnected) {\n void this.deps.emitter.emit('disconnect', { reason: 'unload', timestamp: Date.now() });\n }\n return true;\n }\n\n destroy(): void {\n const { state, deps } = this;\n if (!state.isRunning() && !state.suspended) return;\n const wasConnected = state.isRunning() ? this.release() : false;\n state.suspended = false;\n if (wasConnected) {\n void deps.emitter.emit('disconnect', { reason: 'destroy', timestamp: Date.now() });\n }\n deps.a11y?.detach();\n void deps.emitter.emit('destroy', { timestamp: Date.now() });\n }\n\n /** Invalidate first, then release everything startup may have acquired. */\n private release(): boolean {\n const { state, deps } = this;\n state.activeUpdate = null;\n state.started = false;\n const deferredStart = state.deferredStart;\n state.deferredStart = null;\n if (deferredStart !== null && isDocumentRoot(deps.root)) {\n this.runCleanup(() => {\n deps.root.removeEventListener('DOMContentLoaded', deferredStart);\n });\n }\n for (const handle of state.readyTimers) {\n this.runCleanup(() => {\n clearTimeout(handle);\n });\n }\n state.readyTimers.length = 0;\n this.runCleanup(() => {\n deps.heartbeat.stop();\n });\n this.runCleanup(() => {\n deps.bus.detach();\n });\n state.abortStrategies();\n this.runCleanup(() => {\n this.rootSentinel?.disconnect();\n this.rootSentinel = null;\n this.observedRoot = null;\n });\n this.runCleanup(() => {\n deps.observers.stop();\n });\n this.runCleanup(() => {\n deps.scheduler.destroy();\n });\n this.runCleanup(() => {\n deps.merger?.destroy();\n });\n deps.cache.clear();\n return deps.connection.markDisconnected();\n }\n\n private rollbackFailedStart(): void {\n this.release();\n this.runCleanup(() => {\n this.deps.a11y?.detach();\n });\n }\n\n private runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n this.deps.log('cleanup failed:', error);\n }\n }\n\n /** Re-scan the DOM and re-register every binding. */\n refreshCache(): void {\n if (!this.state.isRunning()) return;\n this.state.revealer.reset();\n if (!this.followReplacedRoot()) this.rebuildCache();\n }\n\n /** Some routers swap `document.body` on navigation, leaving observers on a detached node. */\n private watchRootReplacement(): void {\n const { root } = this.deps;\n if (!isDocumentRoot(root) || typeof MutationObserver === 'undefined') return;\n this.rootSentinel?.disconnect();\n this.rootSentinel = new MutationObserver(() => {\n this.followReplacedRoot();\n });\n this.rootSentinel.observe(root.documentElement, { childList: true });\n }\n\n /** Rebind observers and cache to a replaced body; returns whether it did. */\n private followReplacedRoot(): boolean {\n const { root } = this.deps;\n if (!this.state.isRunning() || !isDocumentRoot(root)) return false;\n const body = readDocumentBody(root);\n if (body === null || body === this.observedRoot) return false;\n this.observedRoot = body;\n this.deps.observers.start(body);\n this.rebuildCache();\n return true;\n }\n\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.deps.connection.status;\n }\n\n get cache(): ElementCache {\n return this.deps.cache;\n }\n\n get updateCount(): number {\n return this.state.updateCount;\n }\n\n /** Negotiated protocol view, `min(library, remote)`. */\n get protocol(): ProtocolNegotiation {\n return this.state.protocol.negotiation;\n }\n\n /** Point-in-time read of runtime state for diagnosing a preview that is not updating. */\n inspect(): LivePreviewInspection {\n return buildInspection(this.deps, this.state);\n }\n\n private buildCacheAndObserve(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const stats = deps.cache.buildFromRoot(deps.root);\n deps.log('cache', stats);\n if (!state.isRunning()) return;\n void deps.emitter.emitWhile('cacheRefresh', stats, () => state.isRunning());\n if (!state.isRunning()) return;\n for (const entry of deps.cache.values()) {\n if (!state.isRunning()) return;\n deps.observers.observeElement(entry.element);\n }\n }\n\n private rebuildCache(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n const previous = new Map<Element, CachedElement>();\n for (const entry of deps.cache.values()) {\n previous.set(entry.element, entry);\n deps.observers.unobserveElement(entry.element);\n }\n this.buildCacheAndObserve();\n if (!state.isRunning()) return;\n // Buffered work survives only while the same element is bound to the same field.\n for (const entry of deps.cache.values()) {\n const before = previous.get(entry.element);\n if (before?.fieldName === entry.fieldName) deps.scheduler.retarget(entry);\n else deps.scheduler.forget(entry.element);\n previous.delete(entry.element);\n }\n for (const removed of previous.values()) deps.scheduler.forget(removed.element);\n }\n\n private onHeartbeatTimeout(): void {\n const { state, deps } = this;\n if (!state.isRunning()) return;\n deps.bus.advanceGeneration();\n const active = state.activeUpdate;\n state.activeUpdate = null;\n if (active !== null) deps.scheduler.cancelRevision(active.identity);\n deps.merger?.destroy();\n const wasConnected = deps.connection.markDisconnected();\n // Release the origin lock before the disconnect event: a listener may\n // reconnect from another allow-listed origin synchronously.\n try {\n deps.onHeartbeatTimeout?.();\n } catch (error) {\n deps.log('heartbeat:', error);\n }\n if (!state.isRunning()) return;\n if (wasConnected && this.isIdleDisconnected()) {\n deps.a11y?.announceDisconnected();\n void deps.emitter.emitWhile('disconnect', { reason: 'timeout', timestamp: Date.now() }, () =>\n this.isIdleDisconnected(),\n );\n if (!state.isRunning()) return;\n if (this.isIdleDisconnected()) deps.log('connection', 'connected', '→', 'disconnected');\n if (!state.isRunning()) return;\n }\n this.sendReadyAfterStart();\n }\n\n /** Later handshake retries are best-effort and must not escape timer callbacks. */\n private sendReadyAfterStart(): void {\n try {\n this.deps.sendReady(this.deps.readyTargets());\n } catch (error) {\n this.reportError(error, 'ready', 'LP0606');\n }\n }\n\n private reportError(cause: unknown, context: string, code: DiagnosticCode): void {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n void this.deps.emitter.emit('error', { error, context, code });\n }\n\n private isIdleDisconnected(): boolean {\n return (\n this.state.isRunning() &&\n this.deps.connection.status === 'disconnected' &&\n this.state.activeUpdate === null\n );\n }\n}\n\nfunction createA11y(options: RuntimeOptions): A11yAnnouncer | null {\n if (options.enableA11y === false) return null;\n const root = options.root;\n const targetDocument =\n root === undefined ? undefined : isDocumentRoot(root) ? root : root.ownerDocument;\n return new A11yAnnouncer(options.a11yLocale, targetDocument);\n}\n\n/** Node types are stable across realms; global constructors are not. */\nfunction isDocumentRoot(root: Document | Element): root is Document {\n return root.nodeType === 9;\n}\n\n/** lib.dom types body as present; a head-time document has none yet. */\nfunction readDocumentBody(root: Document): HTMLElement | null {\n return root.body;\n}\n\nfunction defaultSendReady(origins: readonly string[]): void {\n if (typeof window === 'undefined') return;\n const targets: Window[] = [];\n if (window.parent !== window) targets.push(window.parent);\n if (window.opener instanceof Window) targets.push(window.opener);\n MessageBus.sendReady(targets, origins);\n}\n","/** Assembles the `inspect()` snapshot. Reads state only; sends nothing anywhere. */\n\nimport { VERSION } from '../../version';\nimport { detectProtocolProfile } from '../protocol-profile';\nimport type { RuntimeDeps, RuntimeState } from '../runtime-state';\nimport type { LivePreviewInspection } from './types';\n\nexport function buildInspection(deps: RuntimeDeps, state: RuntimeState): LivePreviewInspection {\n const { cache, scheduler } = deps;\n const negotiation = state.protocol.negotiation;\n const active = state.activeUpdate;\n const flush = state.lastFlush;\n const fieldNames: string[] = [];\n const owners = new Set<string>();\n for (const [fieldName, bindings] of cache.entries()) {\n fieldNames.push(fieldName);\n for (const binding of bindings) {\n if (binding.owner !== undefined) owners.add(binding.owner);\n }\n }\n return {\n version: VERSION,\n started: state.started,\n status: deps.connection.status,\n origins: { trusted: [...deps.readyTargets()], locked: deps.lockedOrigin() },\n protocol: {\n ours: negotiation.ours,\n theirs: negotiation.theirs,\n negotiated: negotiation.negotiated,\n capabilities: [...negotiation.capabilities].sort(),\n observed: [...negotiation.observed].sort(),\n profile: detectProtocolProfile(negotiation.observed).name,\n },\n revisions: {\n accepted: state.updateCount,\n superseded: state.supersededCount,\n completed: state.completedCount,\n skippedUnchanged: state.skippedUnchangedCount,\n active: active === null ? undefined : active.identity.revision,\n },\n bindings: {\n elements: cache.elementCount,\n fields: cache.fieldCount,\n fieldNames: fieldNames.sort(),\n absentFields: [...state.absentFields].sort(),\n orphanFields: [...state.warnedOrphanFields].sort(),\n ownerScoped: deps.scopeBindingsByOwner,\n owners: [...owners].sort(),\n },\n route: { handler: deps.strategies.route !== undefined, ...state.routeStats },\n fragments: {\n handler: deps.strategies.fragment !== undefined,\n inFlight: active?.pendingFragments ?? 0,\n ...state.fragmentStats,\n },\n scheduler: {\n pending: scheduler.pendingCount,\n deferred: scheduler.replayCount,\n visibilityGateThreshold: scheduler.gateThreshold,\n visibilityGateActive: scheduler.gateActive,\n lastFlush:\n flush === null\n ? undefined\n : {\n applied: flush.applied,\n appliedFields: flush.appliedFields,\n deferred: flush.deferred,\n durationMs: flush.durationMs,\n },\n },\n plugins: [],\n renderers: Object.keys(deps.renderers).sort(),\n };\n}\n","/**\n * Per-instance typed emitter: handlers run sequentially in registration order,\n * may be async, and a throwing one is logged and isolated. See ADR 0002.\n */\n\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from './types';\nimport { safeConsoleError } from '@core/diagnostics';\n\ntype AnyHandler = EventHandler<unknown>;\n\n// `object`, not `Record<string, unknown>`: interfaces with readonly and\n// exact-optional properties must be usable as maps.\nexport class EventEmitter<TMap extends object = LivePreviewEventMap> {\n readonly #regular = new Map<keyof TMap, Set<AnyHandler>>();\n readonly #once = new Map<keyof TMap, Set<AnyHandler>>();\n\n on<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#regular, event, handler as AnyHandler);\n }\n\n once<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe {\n return this.#register(this.#once, event, handler as AnyHandler);\n }\n\n off<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): void {\n this.#remove(this.#regular, event, handler as AnyHandler);\n this.#remove(this.#once, event, handler as AnyHandler);\n }\n\n /** Dispatch to every handler: regular ones first, then `once` handlers. */\n async emit<E extends keyof TMap>(event: E, payload: TMap[E]): Promise<void> {\n await this.#emitSequential(event, payload);\n }\n\n /**\n * Dispatch while `shouldContinue()` holds — checked around every handler, so\n * an obsolete transaction cannot resume across an await.\n * @internal\n */\n async emitWhile<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n return this.#emitSequential(event, payload, shouldContinue);\n }\n\n async #emitSequential<E extends keyof TMap>(\n event: E,\n payload: TMap[E],\n shouldContinue?: () => boolean,\n ): Promise<boolean> {\n const eligible = (): boolean => shouldContinue?.() ?? true;\n if (!eligible()) return false;\n const regular = this.#regular.get(event);\n if (regular) {\n for (const handler of [...regular]) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n if (!eligible()) return false;\n const once = this.#once.get(event);\n if (once && once.size > 0) {\n const snapshot = [...once];\n this.#once.delete(event);\n for (const handler of snapshot) {\n if (!eligible()) return false;\n await this.#invoke(handler, payload, event);\n if (!eligible()) return false;\n }\n }\n return eligible();\n }\n\n /** Registered handlers for `event`, `on` and `once` together. */\n listenerCount(event: keyof TMap): number {\n return (this.#regular.get(event)?.size ?? 0) + (this.#once.get(event)?.size ?? 0);\n }\n\n /** Remove every handler, or only those of `event`. */\n removeAllListeners(event?: keyof TMap): void {\n if (event === undefined) {\n this.#regular.clear();\n this.#once.clear();\n return;\n }\n this.#regular.delete(event);\n this.#once.delete(event);\n }\n\n /** Event names with at least one handler. */\n eventNames(): (keyof TMap)[] {\n const names = new Set<keyof TMap>();\n for (const key of this.#regular.keys()) names.add(key);\n for (const key of this.#once.keys()) names.add(key);\n return [...names];\n }\n\n #register(\n bucket: Map<keyof TMap, Set<AnyHandler>>,\n event: keyof TMap,\n handler: AnyHandler,\n ): Unsubscribe {\n let set = bucket.get(event);\n if (!set) {\n set = new Set();\n bucket.set(event, set);\n }\n set.add(handler);\n return () => {\n this.#remove(bucket, event, handler);\n };\n }\n\n #remove(bucket: Map<keyof TMap, Set<AnyHandler>>, event: keyof TMap, handler: AnyHandler): void {\n const set = bucket.get(event);\n if (set === undefined) return;\n set.delete(handler);\n if (set.size === 0) bucket.delete(event);\n }\n\n async #invoke(handler: AnyHandler, payload: unknown, event: keyof TMap): Promise<void> {\n try {\n await handler(payload);\n } catch (err) {\n const label =\n typeof event === 'string' || typeof event === 'number' ? String(event) : '<event>';\n safeConsoleError(`[live-preview] LP0601: handler for \"${label}\" threw:`, err);\n }\n }\n}\n","/**\n * Where the runtime is running: framed, opened, or on a developer's machine.\n * Nothing reads bundler-injected variables; a Vite consumer passes\n * `import.meta.env.X` explicitly (docs/astro.md).\n */\n\nexport function isInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.self !== window.top;\n } catch {\n // A cross-origin parent throws on the comparison; that is an iframe.\n return true;\n }\n}\n\nexport function isInPopup(): boolean {\n if (typeof window === 'undefined') return false;\n return window.opener != null;\n}\n\n/** An iframe or a popup; top-level navigation never starts the preview. */\nexport function isInPreviewContext(): boolean {\n return isInIframe() || isInPopup();\n}\n\n/** Under Node, `NODE_ENV !== 'production'`; in a browser the hostname, which is the only signal a bundle has. */\nexport function isDevMode(): boolean {\n const nodeEnv = readNodeEnv();\n if (nodeEnv !== undefined) return nodeEnv !== 'production';\n if (typeof window !== 'undefined') {\n const host = window.location.hostname;\n return host === 'localhost' || host === '127.0.0.1';\n }\n return false;\n}\n\nfunction readNodeEnv(): string | undefined {\n if (typeof process === 'undefined') return undefined;\n const value = process.env['NODE_ENV'];\n return typeof value === 'string' ? value : undefined;\n}\n","/**\n * Which admin origins the runtime trusts: explicit ones always, the\n * `document.referrer` origin only when none is configured, any localhost port\n * in development. See docs/security.md §1.\n */\n\nimport { isDevMode, isInIframe } from './environment';\n\nconst LOCALHOST_PATTERN = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)(?::\\d+)?$/i;\nconst VALID_ORIGIN_PATTERN = /^https?:\\/\\/[^/?#\\s]+$/i;\n\n/** Ports the handshake broadcasts to when the localhost pattern is on; matching itself is unrestricted. */\nconst LOCALHOST_HANDSHAKE_PORTS: readonly number[] = [\n 3000, 3001, 3333, 4000, 4321, 5000, 5173, 5174, 8000, 8080, 8888, 9000,\n];\n\nexport interface OriginDetectorOptions {\n /** Explicit origins to trust. Always allowed. */\n readonly additionalOrigins?: readonly string[];\n /** Set to `false` to ignore `document.referrer`. */\n readonly enableReferrerDetection?: boolean;\n /** Set to `false` to ignore the localhost pattern even in development. */\n readonly enableLocalhostMatching?: boolean;\n /** Override dev-mode detection. */\n readonly forceDevMode?: boolean;\n /** Override `document.referrer` for tests. */\n readonly referrer?: string;\n}\n\nconst enum OriginSlot {\n ExplicitOrigins,\n ReferrerOrigin,\n AllowLocalhost,\n ReferrerWasAvailable,\n LockedOrigin,\n}\n\ntype OriginState = [\n explicitOrigins: ReadonlySet<string>,\n referrerOrigin: string | undefined,\n allowLocalhost: boolean,\n referrerWasAvailable: boolean,\n lockedOrigin: string | undefined,\n];\n\n/** The trusted-origin policy: the union of the candidate sources, narrowed to one by `lockOrigin()`. */\nexport class OriginDetector {\n readonly #state: OriginState;\n\n constructor(options: OriginDetectorOptions = {}) {\n const explicit = new Set<string>();\n for (const origin of options.additionalOrigins ?? []) {\n const normalised = normaliseOrigin(origin);\n if (normalised !== undefined) explicit.add(normalised);\n }\n let referrerOrigin: string | undefined;\n if (options.enableReferrerDetection ?? true) {\n const referrer =\n options.referrer ?? (typeof document !== 'undefined' ? document.referrer : '');\n if (referrer.length > 0) {\n try {\n const origin = new URL(referrer).origin;\n if (origin && origin !== 'null') referrerOrigin = origin;\n } catch {\n // opaque referrer\n }\n }\n }\n const allowLocalhost =\n (options.enableLocalhostMatching ?? true) && (options.forceDevMode ?? isDevMode());\n this.#state = [\n explicit,\n referrerOrigin,\n allowLocalhost,\n referrerOrigin !== undefined,\n undefined,\n ];\n }\n\n /** Whether `origin` is trusted: the locked origin alone once locked, otherwise the policy above. */\n matches(origin: string): boolean {\n if (origin.length === 0 || origin === 'null') return false;\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return origin === this.#state[OriginSlot.LockedOrigin];\n }\n if (this.#state[OriginSlot.ExplicitOrigins].has(origin)) return true;\n // The referrer is a fallback, not a union member: any embedder lands there.\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined &&\n origin === this.#state[OriginSlot.ReferrerOrigin]\n ) {\n return true;\n }\n if (this.#state[OriginSlot.AllowLocalhost] && LOCALHOST_PATTERN.test(origin)) return true;\n return false;\n }\n\n /** Narrow trust to `origin`; refused (`false`) when it is not currently trusted. */\n lockOrigin(origin: string): boolean {\n if (!this.matches(origin)) return false;\n this.#state[OriginSlot.LockedOrigin] = origin;\n return true;\n }\n\n /** Release the lock (heartbeat timeout) so another allow-listed origin may reconnect. Returns the previous lock. */\n unlockOrigin(): string | undefined {\n const previous = this.#state[OriginSlot.LockedOrigin];\n this.#state[OriginSlot.LockedOrigin] = undefined;\n return previous;\n }\n\n get lockedOrigin(): string | undefined {\n return this.#state[OriginSlot.LockedOrigin];\n }\n\n /** Every origin the `ready` handshake is broadcast to; the localhost pattern expands to the common dev ports. */\n enumerate(): string[] {\n if (this.#state[OriginSlot.LockedOrigin] !== undefined) {\n return [this.#state[OriginSlot.LockedOrigin]];\n }\n const result = new Set<string>(this.#state[OriginSlot.ExplicitOrigins]);\n if (\n this.#state[OriginSlot.ExplicitOrigins].size === 0 &&\n this.#state[OriginSlot.ReferrerOrigin] !== undefined\n ) {\n result.add(this.#state[OriginSlot.ReferrerOrigin]);\n }\n if (this.#state[OriginSlot.AllowLocalhost]) {\n for (const port of LOCALHOST_HANDSHAKE_PORTS) {\n result.add(`http://localhost:${String(port)}`);\n result.add(`http://127.0.0.1:${String(port)}`);\n }\n }\n return [...result];\n }\n\n /** Whether `document.referrer` contributed an origin (absent under `Referrer-Policy: no-referrer`). */\n get referrerWasAvailable(): boolean {\n return this.#state[OriginSlot.ReferrerWasAvailable];\n }\n\n /** Framed, outside development, with no trusted origin at all: the host should warn (LP0101). */\n get isProductionUnconfigured(): boolean {\n if (!isInIframe()) return false;\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n if (this.#state[OriginSlot.ReferrerOrigin] !== undefined) return false;\n return true;\n }\n\n /** The referrer is the only trust source, so any framing site may drive the preview (LP0102). */\n get isReferrerOnlyTrust(): boolean {\n if (this.#state[OriginSlot.ExplicitOrigins].size > 0) return false;\n if (this.#state[OriginSlot.AllowLocalhost]) return false;\n return this.#state[OriginSlot.ReferrerOrigin] !== undefined;\n }\n}\n\n/** The canonical `http(s)://host[:port]` form of `value`, or `undefined` when it is not one. */\nexport function normaliseOrigin(value: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n try {\n const url = new URL(trimmed);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined;\n if (!VALID_ORIGIN_PATTERN.test(url.origin)) return undefined;\n return url.origin;\n } catch {\n return undefined;\n }\n}\n","/**\n * Registration-local resource scope: every listener, transform, renderer\n * layer and cleanup a plugin registers is staged here until `init` commits\n * and released together, in reverse order, when the plugin goes. See ADR 0005.\n */\n\nimport { observeThenableResult } from '@core/thenable';\nimport type { PluginDisposer } from './types';\n\nexport type ResourceKind = 'transform' | 'renderer' | 'subscription' | 'cleanup';\n\ninterface ScopedResource {\n readonly kind: ResourceKind;\n readonly acquire: (() => PluginDisposer | undefined) | undefined;\n readonly finalize: (() => void) | undefined;\n cleanup: PluginDisposer | undefined;\n disposed: boolean;\n}\n\nexport const noopDisposer: PluginDisposer = () => undefined;\n\nexport class ResourceScope {\n readonly #pluginName: string;\n readonly #log: (...args: unknown[]) => void;\n // Insertion order gives commit/reverse-teardown order; short-lived entries\n // (once listeners) leave immediately instead of accumulating until removal.\n readonly #resources = new Set<ScopedResource>();\n #state: 'staging' | 'committing' | 'active' | 'closed' = 'staging';\n\n constructor(pluginName: string, log: (...args: unknown[]) => void) {\n this.#pluginName = pluginName;\n this.#log = log;\n }\n\n assertOpen(): void {\n if (this.#state === 'closed') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" is no longer active`);\n }\n }\n\n get active(): boolean {\n return this.#state === 'active';\n }\n\n /** Whether a retained context still belongs to this registration. */\n eligible(): boolean {\n return this.#state !== 'closed';\n }\n\n /** Own a resource the plugin itself already acquired. */\n own(cleanup: PluginDisposer): PluginDisposer {\n this.assertOpen();\n return this.#track({\n kind: 'cleanup',\n acquire: undefined,\n finalize: undefined,\n cleanup,\n disposed: false,\n });\n }\n\n /** Stage a manager-owned resource; an active scope acquires it at once. */\n stage(\n kind: ResourceKind,\n acquire: () => PluginDisposer | undefined,\n finalize?: () => void,\n ): PluginDisposer {\n this.assertOpen();\n const resource: ScopedResource = {\n kind,\n acquire,\n finalize,\n cleanup: undefined,\n disposed: false,\n };\n const dispose = this.#track(resource);\n if (this.#state === 'active') {\n try {\n this.#activate(resource);\n } catch (error) {\n this.#dispose(resource);\n throw error;\n }\n }\n return dispose;\n }\n\n /** Live resources by kind, what `inspect().plugins` reports. */\n counts(): Record<ResourceKind, number> {\n const counts: Record<ResourceKind, number> = {\n transform: 0,\n renderer: 0,\n subscription: 0,\n cleanup: 0,\n };\n for (const resource of this.#resources) counts[resource.kind] += 1;\n return counts;\n }\n\n /** Publish every staged resource at once after `init` succeeded. */\n commit(): void {\n if (this.#state !== 'staging') {\n throw new Error(`Plugin context for \"${this.#pluginName}\" cannot be committed`);\n }\n this.#state = 'committing';\n try {\n for (const resource of this.#resources) this.#activate(resource);\n this.#state = 'active';\n } catch (error) {\n this.close();\n throw error;\n }\n }\n\n close(): void {\n if (this.#state === 'closed') return;\n this.#state = 'closed';\n for (const resource of [...this.#resources].reverse()) this.#dispose(resource);\n this.#resources.clear();\n }\n\n #track(resource: ScopedResource): PluginDisposer {\n this.#resources.add(resource);\n return (): void => {\n this.#dispose(resource);\n };\n }\n\n #activate(resource: ScopedResource): void {\n if (resource.disposed || resource.cleanup !== undefined || resource.acquire === undefined) {\n return;\n }\n const cleanup = resource.acquire();\n resource.cleanup = cleanup ?? noopDisposer;\n }\n\n #dispose(resource: ScopedResource): void {\n if (resource.disposed) return;\n resource.disposed = true;\n this.#resources.delete(resource);\n const cleanup = resource.cleanup;\n resource.cleanup = undefined;\n if (cleanup !== undefined) {\n try {\n // A `void` cleanup may still return a thenable; observe it without awaiting.\n const cleanupWithResult: () => unknown = cleanup;\n if (observeThenableResult(cleanupWithResult())) {\n this.#log(\n `plugin \"${this.#pluginName}\" cleanup returned a Promise/thenable; cleanups must be synchronous`,\n );\n }\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n try {\n resource.finalize?.();\n } catch (error) {\n this.#log(`plugin \"${this.#pluginName}\" cleanup failed:`, error);\n }\n }\n}\n","/**\n * Event facade handed to a plugin: subscriptions are owned by the plugin's\n * scope, emits go to the client's emitter. It implements the emitter surface\n * without extending it, so no unused base emitter is allocated per plugin.\n */\n\nimport type { EventEmitter } from '@events/emitter';\nimport type { EventHandler, LivePreviewEventMap, Unsubscribe } from '@events/types';\nimport { noopDisposer, type ResourceScope } from './resource-scope';\nimport type { PluginEvents } from './types';\n\ninterface OwnedSubscription {\n readonly kind: 'on' | 'once';\n readonly event: keyof LivePreviewEventMap;\n readonly handler: EventHandler<unknown>;\n dispose: Unsubscribe;\n}\n\nexport class ScopedPluginEvents implements PluginEvents {\n readonly #events: EventEmitter;\n readonly #scope: ResourceScope;\n readonly #subscriptions = new Set<OwnedSubscription>();\n\n constructor(events: EventEmitter, scope: ResourceScope) {\n this.#events = events;\n this.#scope = scope;\n }\n\n on<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('on', event, handler);\n }\n\n once<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n return this.#subscribe('once', event, handler);\n }\n\n off<E extends keyof LivePreviewEventMap>(\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): void {\n const untypedHandler = handler as EventHandler<unknown>;\n for (const subscription of [...this.#subscriptions]) {\n if (subscription.event === event && subscription.handler === untypedHandler) {\n subscription.dispose();\n }\n }\n }\n\n emit<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n ): Promise<void> {\n this.#scope.assertOpen();\n return this.#events.emit(event, payload);\n }\n\n emitWhile<E extends keyof LivePreviewEventMap>(\n event: E,\n payload: LivePreviewEventMap[E],\n shouldContinue: () => boolean,\n ): Promise<boolean> {\n this.#scope.assertOpen();\n return this.#events.emitWhile(event, payload, () => {\n if (!this.#scope.eligible()) return false;\n const callerEligible = shouldContinue();\n // The predicate is plugin code and may close this scope re-entrantly.\n if (!this.#scope.eligible()) return false;\n return callerEligible;\n });\n }\n\n listenerCount(event: keyof LivePreviewEventMap): number {\n let count = 0;\n for (const subscription of this.#subscriptions) {\n if (subscription.event === event) count += 1;\n }\n return count;\n }\n\n removeAllListeners(event?: keyof LivePreviewEventMap): void {\n for (const subscription of [...this.#subscriptions]) {\n if (event === undefined || subscription.event === event) subscription.dispose();\n }\n }\n\n eventNames(): (keyof LivePreviewEventMap)[] {\n const names = new Set<keyof LivePreviewEventMap>();\n for (const subscription of this.#subscriptions) names.add(subscription.event);\n return [...names];\n }\n\n #subscribe<E extends keyof LivePreviewEventMap>(\n kind: 'on' | 'once',\n event: E,\n handler: EventHandler<LivePreviewEventMap[E]>,\n ): Unsubscribe {\n this.#scope.assertOpen();\n\n const untypedHandler = handler as EventHandler<unknown>;\n const existing = [...this.#subscriptions].find(\n (subscription) =>\n subscription.kind === kind &&\n subscription.event === event &&\n subscription.handler === untypedHandler,\n );\n if (existing !== undefined) return existing.dispose;\n\n // A distinct wrapper per scope: two plugins passing the same handler\n // reference must be revocable independently in the Set-based emitter.\n let dispose = noopDisposer;\n let subscriptionActive = true;\n const wrapped: EventHandler<LivePreviewEventMap[E]> = async (payload) => {\n if (!this.#scope.active || !subscriptionActive) return;\n // Mirror the base emitter, which drops a once bucket before dispatch.\n if (kind === 'once') dispose();\n await handler(payload);\n };\n const subscription: OwnedSubscription = {\n kind,\n event,\n handler: untypedHandler,\n dispose: noopDisposer,\n };\n dispose = this.#scope.stage(\n 'subscription',\n () => this.#events[kind](event, wrapped),\n () => {\n subscriptionActive = false;\n this.#subscriptions.delete(subscription);\n },\n );\n subscription.dispose = dispose;\n this.#subscriptions.add(subscription);\n return dispose;\n }\n}\n","/**\n * Per-instance plugin manager. Mutations run through one call-order queue;\n * while a queue-held hook is pending, a requested mutation takes the direct\n * path because that hook may be awaiting it. See ADR 0005.\n */\n\nimport type { FieldRenderer } from '@core/types';\nimport type { PluginInspection } from '@core/inspection/types';\nimport { LIBRARY_PROTOCOL_VERSION } from '@core/protocol-version';\nimport { VERSION } from '@/version';\nimport { incompatibilityOf } from './compat';\nimport { isolateDiagnostic } from '@core/diagnostics';\nimport { observeThenableResult } from '@core/thenable';\nimport type { EventEmitter } from '@events/emitter';\nimport { ResourceScope } from './resource-scope';\nimport { ScopedPluginEvents } from './scoped-events';\nimport type { FieldTransform, LivePreviewPlugin, PluginContext } from './types';\n\nexport interface PluginManagerOptions {\n readonly events: EventEmitter;\n readonly config: Readonly<Record<string, unknown>>;\n /** Add one renderer layer to the host; may return the layer's disposer. */\n readonly registerFieldRenderer: (renderer: FieldRenderer) => void;\n /** Receives transform contract failures for the runtime's `error` event. */\n readonly onTransformError?: (error: Error) => unknown;\n readonly log: (...args: unknown[]) => void;\n}\n\ninterface PluginRegistration {\n readonly plugin: LivePreviewPlugin;\n readonly scope: ResourceScope;\n}\n\ninterface InitializingPluginRegistration {\n readonly scope: ResourceScope;\n cancelled: boolean;\n}\n\ninterface TransformRegistration {\n readonly transform: FieldTransform;\n active: boolean;\n}\n\nfunction isPluginDisposer(value: unknown): value is (() => void) | undefined {\n return typeof value === 'function';\n}\n\nexport class PluginManager {\n readonly #events: EventEmitter;\n readonly #config: Readonly<Record<string, unknown>>;\n // The public callback type is void; the client host returns its layer disposer through it.\n readonly #registerRenderer: (renderer: FieldRenderer) => unknown;\n readonly #onTransformError: ((error: Error) => void) | undefined;\n readonly #log: (...args: unknown[]) => void;\n readonly #plugins = new Map<string, PluginRegistration>();\n readonly #initializing = new Map<string, InitializingPluginRegistration>();\n readonly #teardowns = new Map<string, Promise<void>>();\n readonly #destroying = new Set<string>();\n readonly #transforms = new Map<string, TransformRegistration[]>();\n #mutationQueue: Promise<void> = Promise.resolve();\n // Hooks awaited by the queue entry in flight. Hooks started on the direct\n // path never hold the queue, so they must not open it for others.\n #queuedHooks = 0;\n\n constructor(options: PluginManagerOptions) {\n this.#events = options.events;\n this.#config = options.config;\n this.#registerRenderer = options.registerFieldRenderer;\n this.#log = isolateDiagnostic(options.log);\n const onTransformError = options.onTransformError;\n this.#onTransformError =\n onTransformError === undefined\n ? undefined\n : isolateDiagnostic((...args: unknown[]): unknown => {\n // Private and single-callered: `applyTransforms` normalizes to an\n // Error before it reports one.\n const error = args[0] as Error;\n try {\n return onTransformError(error);\n } catch (reportError) {\n this.#log('transform error reporter failed:', reportError);\n return undefined;\n }\n });\n }\n\n /** Register a plugin transactionally; concurrent mutations run in call order. */\n register(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#queuedHooks > 0) return this.#registerNow(plugin, false);\n return this.#enqueue(() => this.#registerNow(plugin, true));\n }\n\n /** Remove one plugin and every resource its registration created. */\n unregister(name: string): Promise<void> {\n if (this.#queuedHooks > 0) return this.#unregisterNow(name, false);\n return this.#enqueue(async () => {\n await this.#unregisterNow(name, true);\n });\n }\n\n /** Destroy every registration; one failure never strands another. */\n destroyAll(): Promise<void> {\n if (this.#queuedHooks > 0) return this.#destroyAllNow(false);\n return this.#enqueue(async () => {\n await this.#destroyAllNow(true);\n });\n }\n\n /** Apply active transforms in registration order; a failure returns the original value. */\n applyTransforms(\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ): unknown {\n const registrations = this.#transforms.get(fieldName);\n if (registrations === undefined || registrations.length === 0) return value;\n\n let result: unknown = value;\n for (const registration of [...registrations]) {\n if (!registration.active) continue;\n const { transform } = registration;\n if (isCurrent?.() === false) return value;\n try {\n result = transform(result, {\n fieldName,\n element: context.element,\n allFields: context.allFields,\n });\n const returnedThenable = observeThenableResult(result);\n // A transform may synchronously let a newer message in; then its\n // result belongs to a superseded revision and is not reported.\n if (isCurrent?.() === false) return value;\n if (returnedThenable) {\n throw new TypeError(\n `Transform for \"${fieldName}\" returned a Promise/thenable; transforms must be synchronous`,\n );\n }\n } catch (error) {\n if (isCurrent?.() === false) return value;\n const normalized = error instanceof Error ? error : new Error(String(error));\n this.#log(`transform for \"${fieldName}\" failed:`, normalized);\n this.#onTransformError?.(normalized);\n return value;\n }\n }\n return result;\n }\n\n list(): readonly string[] {\n return [...this.#plugins.keys()];\n }\n\n /** Every plugin with its state and live registrations (`inspect().plugins`). */\n snapshot(): readonly PluginInspection[] {\n const entries: PluginInspection[] = [];\n const describe = (\n name: string,\n version: string | undefined,\n state: PluginInspection['state'],\n scope: ResourceScope,\n ): PluginInspection => {\n const counts = scope.counts();\n return {\n name,\n version,\n state,\n registrations: {\n transforms: counts.transform,\n renderers: counts.renderer,\n subscriptions: counts.subscription,\n cleanups: counts.cleanup,\n },\n };\n };\n for (const [name, initializing] of this.#initializing) {\n entries.push(describe(name, undefined, 'initializing', initializing.scope));\n }\n for (const [name, registration] of this.#plugins) {\n entries.push(describe(name, registration.plugin.version, 'active', registration.scope));\n }\n // A name with a pending teardown left `#plugins` before the teardown began.\n for (const name of this.#teardowns.keys()) {\n entries.push({\n name,\n version: undefined,\n state: 'tearing-down',\n registrations: { transforms: 0, renderers: 0, subscriptions: 0, cleanups: 0 },\n });\n }\n return entries;\n }\n\n get size(): number {\n return this.#plugins.size;\n }\n\n async #registerNow(plugin: LivePreviewPlugin, queued: boolean): Promise<void> {\n if (\n this.#plugins.has(plugin.name) ||\n this.#initializing.has(plugin.name) ||\n this.#teardowns.has(plugin.name)\n ) {\n this.#log(`plugin \"${plugin.name}\" already registered`);\n return;\n }\n\n const incompatibility = incompatibilityOf(plugin.compat, VERSION, LIBRARY_PROTOCOL_VERSION);\n if (incompatibility !== undefined) {\n this.#refuse(plugin.name, incompatibility);\n return;\n }\n const scope = new ResourceScope(plugin.name, this.#log);\n const context = this.#createContext(plugin.name, scope);\n const initializing: InitializingPluginRegistration = { scope, cancelled: false };\n this.#initializing.set(plugin.name, initializing);\n try {\n await this.#runHook(() => plugin.init(context), queued);\n if (initializing.cancelled) return;\n scope.commit();\n } catch (error) {\n scope.close();\n if (!initializing.cancelled) this.#log(`plugin \"${plugin.name}\" init failed:`, error);\n return;\n } finally {\n if (this.#initializing.get(plugin.name) === initializing) {\n this.#initializing.delete(plugin.name);\n }\n }\n\n this.#plugins.set(plugin.name, { plugin, scope });\n this.#log(`plugin \"${plugin.name}\" registered`);\n }\n\n /** A refused plugin is an integration mistake; it reaches the `error` event, not only the log. */\n #refuse(name: string, reason: string): void {\n const message = `plugin \"${name}\" refused: ${reason}`;\n this.#log(message);\n void this.#events.emit('error', {\n error: new Error(message),\n context: 'plugin',\n code: 'LP0103',\n });\n }\n\n #createContext(pluginName: string, scope: ResourceScope): PluginContext {\n return {\n events: new ScopedPluginEvents(this.#events, scope),\n registerFieldRenderer: (renderer) => {\n scope.stage('renderer', () => {\n const result = this.#registerRenderer(renderer);\n return isPluginDisposer(result) ? result : undefined;\n });\n },\n registerTransform: (fieldName, transform) => {\n const registration: TransformRegistration = { transform, active: false };\n scope.stage('transform', () => {\n registration.active = true;\n const existing = this.#transforms.get(fieldName);\n if (existing === undefined) this.#transforms.set(fieldName, [registration]);\n else existing.push(registration);\n\n return () => {\n registration.active = false;\n const current = this.#transforms.get(fieldName);\n if (current === undefined) return;\n const index = current.indexOf(registration);\n if (index >= 0) current.splice(index, 1);\n if (current.length === 0) this.#transforms.delete(fieldName);\n };\n });\n },\n registerCleanup: (cleanup) => {\n scope.own(cleanup);\n },\n getConfig: () => this.#config,\n log: (...args) => {\n this.#log(`[${pluginName}]`, ...args);\n },\n };\n }\n\n #unregisterNow(name: string, queued: boolean): Promise<void> {\n const initializing = this.#initializing.get(name);\n if (initializing !== undefined) {\n initializing.cancelled = true;\n initializing.scope.close();\n return Promise.resolve();\n }\n\n const existingTeardown = this.#teardowns.get(name);\n if (existingTeardown !== undefined) {\n // A destroy hook removing its own name cannot await the teardown that\n // awaits it; its resources are already revoked, so this is complete.\n if (this.#destroying.has(name)) return Promise.resolve();\n return queued ? this.#holdQueue(existingTeardown) : existingTeardown;\n }\n const registration = this.#plugins.get(name);\n if (registration === undefined) return Promise.resolve();\n\n // Revoke before consumer code runs: a throwing destroy keeps no access,\n // and a same-name registration from inside destroy stays a duplicate.\n this.#plugins.delete(name);\n registration.scope.close();\n const teardown = Promise.resolve().then(() =>\n this.#destroyPlugin(name, registration.plugin, queued),\n );\n this.#teardowns.set(name, teardown);\n void teardown.then(() => {\n if (this.#teardowns.get(name) === teardown) this.#teardowns.delete(name);\n });\n return teardown;\n }\n\n async #destroyPlugin(name: string, plugin: LivePreviewPlugin, queued: boolean): Promise<void> {\n if (plugin.destroy === undefined) return;\n this.#destroying.add(name);\n try {\n await this.#runHook(() => plugin.destroy?.(), queued);\n } catch (error) {\n this.#log(`plugin \"${name}\" destroy failed:`, error);\n } finally {\n this.#destroying.delete(name);\n }\n }\n\n async #destroyAllNow(queued: boolean): Promise<void> {\n for (const initializing of this.#initializing.values()) {\n initializing.cancelled = true;\n initializing.scope.close();\n }\n const names = [...this.#plugins.keys()];\n for (const name of names) await this.#unregisterNow(name, queued);\n }\n\n async #runHook(hook: () => void | Promise<void>, queued: boolean): Promise<void> {\n if (!queued) {\n await hook();\n return;\n }\n await this.#holdQueue(Promise.resolve().then(hook));\n }\n\n async #holdQueue(pending: Promise<void>): Promise<void> {\n this.#queuedHooks += 1;\n try {\n await pending;\n } finally {\n this.#queuedHooks -= 1;\n }\n }\n\n #enqueue(operation: () => void | Promise<void>): Promise<void> {\n const result = this.#mutationQueue.then(operation);\n // Keep the tail usable after an escaped error; the caller still sees it on `result`.\n this.#mutationQueue = result.catch((error: unknown) => {\n this.#log('plugin manager mutation failed:', error);\n });\n return result;\n }\n}\n","/**\n * Plugin compatibility claims. The range grammar is the subset a plugin\n * author writes (`*`, `1.2.3`, `^`, `~`, `>=`, `>`, `<`, `<=`, space-joined\n * conjunctions, `||` alternatives); prerelease tags are ignored.\n */\n\nexport interface PluginCompatibility {\n /** A semver range the runtime's `VERSION` must satisfy, e.g. `>=2.0.0`. */\n readonly runtime?: string;\n /** The highest postMessage protocol version the plugin understands. */\n readonly protocol?: number;\n}\n\ntype Version = readonly [number, number, number];\n\nfunction parseVersion(text: string): Version | undefined {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(text.trim());\n if (match === null) return undefined;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction compare(a: Version, b: Version): number {\n for (let index = 0; index < 3; index += 1) {\n const delta = (a[index] ?? 0) - (b[index] ?? 0);\n if (delta !== 0) return delta;\n }\n return 0;\n}\n\nfunction satisfiesComparator(version: Version, comparator: string): boolean {\n const trimmed = comparator.trim();\n if (trimmed === '' || trimmed === '*') return true;\n const match = /^(\\^|~|>=|<=|>|<|=)?\\s*v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(trimmed);\n if (match === null) return false;\n const operator = match[1] ?? '=';\n const target: Version = [Number(match[2]), Number(match[3]), Number(match[4])];\n const order = compare(version, target);\n switch (operator) {\n case '=':\n return order === 0;\n case '>':\n return order > 0;\n case '>=':\n return order >= 0;\n case '<':\n return order < 0;\n case '<=':\n return order <= 0;\n case '~':\n return order >= 0 && version[0] === target[0] && version[1] === target[1];\n case '^':\n if (order < 0) return false;\n if (target[0] > 0) return version[0] === target[0];\n if (target[1] > 0) return version[0] === 0 && version[1] === target[1];\n return version[0] === 0 && version[1] === 0 && version[2] === target[2];\n default:\n return false;\n }\n}\n\n/** Whether `version` satisfies `range`; anything unparsable never satisfies. */\nexport function satisfiesRange(version: string, range: string): boolean {\n const parsed = parseVersion(version);\n if (parsed === undefined) return false;\n const alternatives = range.split('||');\n return alternatives.some((alternative) => {\n const comparators = alternative\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n if (comparators.length === 0) return alternative.trim() === '' && range.trim() === '';\n return comparators.every((comparator) => satisfiesComparator(parsed, comparator));\n });\n}\n\n/** Why a plugin was refused, or `undefined` when it fits. */\nexport function incompatibilityOf(\n compat: PluginCompatibility | undefined,\n runtimeVersion: string,\n protocolVersion: number,\n): string | undefined {\n if (compat === undefined) return undefined;\n if (compat.runtime !== undefined && !satisfiesRange(runtimeVersion, compat.runtime)) {\n return `declares runtime ${compat.runtime}, this runtime is ${runtimeVersion}`;\n }\n if (compat.protocol !== undefined) {\n if (!Number.isInteger(compat.protocol) || compat.protocol < 1) {\n return `declares an invalid protocol version ${String(compat.protocol)}`;\n }\n if (compat.protocol < protocolVersion) {\n return `declares protocol ${String(compat.protocol)}, this runtime speaks ${String(protocolVersion)}`;\n }\n }\n return undefined;\n}\n","/**\n * Per-client renderer layers: built-ins are the base, plugin registrations\n * stack above per field type, and removing a layer by identity reveals the\n * one beneath. See ADR 0005.\n */\n\nimport type { FieldRenderer, RendererKey } from '@core/types';\nimport type { PluginDisposer } from './types';\n\ninterface RendererLayer {\n readonly renderer: FieldRenderer;\n}\n\nexport class RendererRegistry {\n readonly #base: Readonly<Record<string, FieldRenderer>>;\n readonly #active: Record<string, FieldRenderer>;\n readonly #layers = new Map<RendererKey, RendererLayer[]>();\n\n constructor(base: Readonly<Record<string, FieldRenderer>>) {\n this.#base = base;\n this.#active = { ...base };\n }\n\n /** Stable live map, retained for the runtime's `renderers` option. */\n get renderers(): Readonly<Record<string, FieldRenderer>> {\n return this.#active;\n }\n\n resolve(fieldType: RendererKey): FieldRenderer | undefined {\n return this.#active[fieldType];\n }\n\n register(renderer: FieldRenderer): PluginDisposer {\n const fieldType = renderer.name;\n const layer: RendererLayer = { renderer };\n const stack = this.#layers.get(fieldType);\n if (stack === undefined) this.#layers.set(fieldType, [layer]);\n else stack.push(layer);\n this.#active[fieldType] = renderer;\n\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n\n const current = this.#layers.get(fieldType);\n if (current === undefined) return;\n const index = current.indexOf(layer);\n if (index < 0) return;\n const wasTop = index === current.length - 1;\n current.splice(index, 1);\n if (current.length === 0) this.#layers.delete(fieldType);\n if (!wasTop) return;\n\n const previousLayer = current.at(-1);\n const previousRenderer = previousLayer?.renderer ?? this.#base[fieldType];\n if (previousRenderer === undefined) Reflect.deleteProperty(this.#active, fieldType);\n else this.#active[fieldType] = previousRenderer;\n };\n }\n}\n","/** Attribute helpers shared by the block-level node renderers. */\n\nimport type { LexicalNode } from './types';\n\nconst ALIGNMENT_NUMERIC: Readonly<Record<number, string>> = {\n 1: 'left',\n 2: 'center',\n 3: 'right',\n 4: 'justify',\n};\n\nconst ALIGNMENT_STRING = new Set(['left', 'center', 'right', 'justify', 'start', 'end']);\n\n/** Alignment of a block node; Payload emits it as a string or as Lexical's numeric format. */\nexport function resolveAlignment(node: LexicalNode): string | undefined {\n const fmt = node.format;\n if (typeof fmt === 'string' && ALIGNMENT_STRING.has(fmt)) return fmt;\n if (typeof fmt === 'number') return ALIGNMENT_NUMERIC[fmt];\n return undefined;\n}\n\nexport function resolveIndent(node: LexicalNode): number {\n const indent = node.indent;\n return typeof indent === 'number' && indent > 0 ? indent : 0;\n}\n\nexport function dirAttribute(node: LexicalNode): string {\n if (node.direction === 'rtl') return ' dir=\"rtl\"';\n if (node.direction === 'ltr') return ' dir=\"ltr\"';\n return '';\n}\n\n/**\n * Alignment and indent as `lp-align-*` / `lp-indent-N` classes. The sanitizer\n * strips `style` under every policy, so inline CSS would never reach the page.\n */\nexport function layoutClassAttribute(node: LexicalNode): string {\n const align = resolveAlignment(node);\n const indent = resolveIndent(node);\n const classes: string[] = [];\n if (align !== undefined) classes.push(`lp-align-${align}`);\n if (indent > 0) classes.push(`lp-indent-${String(indent)}`);\n return classes.length === 0 ? '' : ` class=\"${classes.join(' ')}\"`;\n}\n","import type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst paragraphRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<p${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</p>`;\n};\n\nexport { paragraphRenderer };\n","/** `heading` renderer; an unknown `tag` (transient editor states emit them) falls back to `h2`. */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst VALID_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\nconst headingRenderer: NodeRenderer = (node, ctx): string => {\n const tagRaw = typeof node['tag'] === 'string' ? node['tag'].toLowerCase() : 'h2';\n const tag = VALID_TAGS.has(tagRaw) ? tagRaw : 'h2';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</${tag}>`;\n};\n\nexport { headingRenderer };\n","/**\n * Value-shape helpers shared by the Lexical node renderers and the field\n * renderers. They live here because `field-types` may import `lexical`, never\n * the reverse (scripts/architecture-policy.ts).\n */\n\nexport interface MediaShape {\n readonly id?: string | number;\n readonly url?: string;\n readonly alt?: string;\n readonly filename?: string;\n readonly mimeType?: string;\n readonly width?: number;\n readonly height?: number;\n readonly sizes?: Readonly<\n Record<string, { readonly url?: string; readonly width?: number; readonly height?: number }>\n >;\n}\n\nexport interface RelationShape {\n readonly id?: string | number;\n readonly title?: string;\n readonly name?: string;\n readonly slug?: string;\n readonly url?: string;\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nexport function readMedia(value: unknown): MediaShape | undefined {\n return asRecord(value);\n}\n\n/** Reduce `value` to `[a-z0-9_-]` so it can be a class-name fragment without escaping. */\nexport function sanitizeIdent(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase();\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/** Label precedence for a populated relation: `title`, `name`, `slug`, then `id`. */\nexport function pickRelationLabel(value: RelationShape): string | undefined {\n const label = nonEmpty(value.title) ?? nonEmpty(value.name) ?? nonEmpty(value.slug);\n if (label !== undefined) return label;\n return value.id === undefined ? undefined : String(value.id);\n}\n","/**\n * `link` / `autolink` renderer. Payload 3.x serialises links as\n * `{ fields: { linkType, url, newTab, doc } }`; vanilla Lexical puts `url`\n * and `target` on the node itself. Both shapes are read, Payload's first.\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isExternalHttpUrl, isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { asRecord } from '../value-shapes';\n\nconst BLANK_TARGET = ' target=\"_blank\" rel=\"noopener noreferrer\"';\n\nconst linkRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n const fields = asRecord(node['fields']);\n const url = resolveUrl(node, fields);\n if (url === undefined || !isSafeUrl(url)) return children;\n const titleAttr =\n typeof node['title'] === 'string' ? ` title=\"${escapeHtml(node['title'])}\"` : '';\n return `<a href=\"${escapeHtmlAttribute(url)}\"${targetAttribute(node, fields, url)}${titleAttr}>${children}</a>`;\n};\n\nfunction resolveUrl(\n node: LexicalNode,\n fields: Record<string, unknown> | undefined,\n): string | undefined {\n if (fields?.['linkType'] === 'internal') return internalUrl(fields['doc']);\n const url = fields?.['url'] ?? node['url'];\n return typeof url === 'string' && url.length > 0 ? url : undefined;\n}\n\n/** An internal link needs the populated document; a bare id has no route to offer. */\nfunction internalUrl(doc: unknown): string | undefined {\n const value = asRecord(asRecord(doc)?.['value']);\n const url = value?.['url'];\n if (typeof url === 'string' && url.length > 0) return url;\n const slug = value?.['slug'];\n return typeof slug === 'string' && slug.length > 0 ? `/${slug}` : undefined;\n}\n\n/** `_blank` always carries `noopener noreferrer`, whichever side asked for it. */\nfunction targetAttribute(\n node: LexicalNode,\n fields: Record<string, unknown> | undefined,\n url: string,\n): string {\n if (fields?.['newTab'] === true || isExternalHttpUrl(url)) return BLANK_TARGET;\n const target = typeof node['target'] === 'string' ? node['target'] : '';\n if (target === '') return '';\n if (target === '_blank') return BLANK_TARGET;\n return ` target=\"${escapeHtml(target)}\"`;\n}\n\nexport { linkRenderer };\n","/** `code` (fenced block) and `code-highlight` (token span) renderers. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { sanitizeIdent } from '../value-shapes';\n\nconst codeRenderer: NodeRenderer = (node): string => {\n const language = sanitizeIdent(typeof node['language'] === 'string' ? node['language'] : '');\n const langClass = language === '' ? '' : ` class=\"language-${language}\"`;\n return `<pre><code${langClass}>${escapeHtml(extractText(node))}</code></pre>`;\n};\n\nconst codeHighlightRenderer: NodeRenderer = (node): string => {\n const text = typeof node.text === 'string' ? node.text : '';\n const highlight =\n typeof node['highlightType'] === 'string'\n ? ` class=\"token-${sanitizeIdent(node['highlightType'])}\"`\n : '';\n return `<span${highlight}>${escapeHtml(text)}</span>`;\n};\n\nexport { codeRenderer, codeHighlightRenderer };\n\nfunction extractText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (!node.children) return '';\n let out = '';\n for (const child of node.children) out += extractText(child);\n return out;\n}\n","/**\n * `upload` renderer: `<img>` for image (or unknown) MIME types, `<video>` /\n * `<audio>` for media, a download link otherwise. An unsafe URL renders nothing.\n */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport { readMedia, type MediaShape } from '../value-shapes';\n\nconst uploadRenderer: NodeRenderer = (node): string => {\n const value = readMedia(node['value']);\n if (value === undefined) return '';\n const url = value.url;\n if (typeof url !== 'string' || !isSafeUrl(url)) return '';\n\n const mime = typeof value.mimeType === 'string' ? value.mimeType : '';\n if (mime.startsWith('video/')) return renderVideo(value, url);\n if (mime.startsWith('audio/')) return renderAudio(value, url);\n if (mime === '' || mime.startsWith('image/')) return renderImage(value, url);\n return renderFallbackLink(value, url);\n};\n\nexport { uploadRenderer };\n\nfunction dimensionAttributes(value: MediaShape): string {\n const width = typeof value.width === 'number' ? ` width=\"${String(value.width)}\"` : '';\n const height = typeof value.height === 'number' ? ` height=\"${String(value.height)}\"` : '';\n return `${width}${height}`;\n}\n\nfunction typeAttribute(value: MediaShape): string {\n return typeof value.mimeType === 'string' ? ` type=\"${escapeHtmlAttribute(value.mimeType)}\"` : '';\n}\n\nfunction renderImage(value: MediaShape, url: string): string {\n const alt = typeof value.alt === 'string' ? escapeHtml(value.alt) : '';\n return `<img src=\"${escapeHtmlAttribute(url)}\" alt=\"${alt}\"${dimensionAttributes(value)} loading=\"lazy\" decoding=\"async\">`;\n}\n\nfunction renderVideo(value: MediaShape, url: string): string {\n return `<video controls${dimensionAttributes(value)}><source src=\"${escapeHtmlAttribute(url)}\"${typeAttribute(value)}></video>`;\n}\n\nfunction renderAudio(value: MediaShape, url: string): string {\n return `<audio controls><source src=\"${escapeHtmlAttribute(url)}\"${typeAttribute(value)}></audio>`;\n}\n\nfunction renderFallbackLink(value: MediaShape, url: string): string {\n const label = typeof value.filename === 'string' ? escapeHtml(value.filename) : escapeHtml(url);\n return `<a href=\"${escapeHtmlAttribute(url)}\" target=\"_blank\" rel=\"noopener noreferrer\">${label}</a>`;\n}\n","/** `relationship` renderer: a link when the populated document carries a URL, a span otherwise. */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { isSafeUrl } from '@security/url-validator';\nimport type { NodeRenderer } from '../registry';\nimport { asRecord, pickRelationLabel, sanitizeIdent, type RelationShape } from '../value-shapes';\n\nconst relationshipRenderer: NodeRenderer = (node): string => {\n const relationTo = typeof node['relationTo'] === 'string' ? node['relationTo'] : '';\n const value = asRecord(node['value']) as RelationShape | undefined;\n const label = escapeHtml((value && pickRelationLabel(value)) ?? `#${relationTo}`);\n const slug = sanitizeIdent(relationTo);\n const classAttr =\n slug === '' ? ' class=\"lp-relation\"' : ` class=\"lp-relation lp-relation--${slug}\"`;\n const url = value?.url;\n if (typeof url === 'string' && isSafeUrl(url)) {\n return `<a href=\"${escapeHtmlAttribute(url)}\"${classAttr}>${label}</a>`;\n }\n return `<span${classAttr}>${label}</span>`;\n};\n\nexport { relationshipRenderer };\n","/** Block-renderer registry keyed by Payload block slug; consulted by the `block` and `inlineBlock` nodes. */\n\nimport type { LexicalNode } from '../types';\n\nexport interface BlockRenderContext {\n /** Render nested Lexical content through the node registry. */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n}\n\n/** Receives the block's `fields` (with `blockType`) and returns HTML. */\nexport type BlockRenderer = (\n fields: Record<string, unknown>,\n context: BlockRenderContext,\n) => string;\n\nconst registry = new Map<string, BlockRenderer>();\n\n/** Register or replace the renderer for `blockType`. */\nexport function registerBlockRenderer(blockType: string, renderer: BlockRenderer): void {\n registry.set(blockType, renderer);\n}\n\nexport function lookupBlockRenderer(blockType: string): BlockRenderer | undefined {\n return registry.get(blockType);\n}\n\nexport function registeredBlockTypes(): readonly string[] {\n return [...registry.keys()];\n}\n\n/** Test-only: clear the registry. */\nexport function __resetBlockRegistryForTests(): void {\n registry.clear();\n}\n","/**\n * `block` and `inlineBlock` renderers for Payload's BlocksFeature. The block\n * registry is consulted first; without a renderer for the slug the node\n * becomes an empty, class-tagged element a consumer can style or replace.\n */\n\nimport { lookupBlockRenderer } from '../blocks/registry';\nimport type { NodeRenderer, RenderNodeContext } from '../registry';\nimport type { LexicalNode } from '../types';\nimport { asRecord, sanitizeIdent } from '../value-shapes';\n\nfunction renderBlockNode(\n node: LexicalNode,\n ctx: RenderNodeContext,\n tag: 'div' | 'span',\n baseClass: string,\n): string {\n const fields = asRecord(node['fields']) ?? {};\n const blockType = typeof fields['blockType'] === 'string' ? fields['blockType'] : '';\n const slug = sanitizeIdent(blockType);\n if (blockType !== '') {\n const custom = lookupBlockRenderer(blockType) ?? lookupBlockRenderer(slug);\n if (custom) return custom(fields, { renderChildren: ctx.renderChildren });\n }\n const classes = slug === '' ? baseClass : `${baseClass} ${baseClass}--${slug}`;\n return `<${tag} class=\"${classes}\"></${tag}>`;\n}\n\nconst blockRenderer: NodeRenderer = (node, ctx) => renderBlockNode(node, ctx, 'div', 'lp-block');\n\nconst inlineBlockRenderer: NodeRenderer = (node, ctx) =>\n renderBlockNode(node, ctx, 'span', 'lp-inline-block');\n\nexport { blockRenderer, inlineBlockRenderer };\n","/** `table` / `tablerow` / `tablecell` renderers for the `@lexical/table` shapes Payload's table feature emits. */\n\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute } from '../utils';\n\n// `@lexical/table` TableCellHeaderStates: ROW marks a cell in a header row, COLUMN one in a header column.\nconst HEADER_ROW = 1;\nconst HEADER_COLUMN = 2;\n\nconst tableRenderer: NodeRenderer = (node, ctx) =>\n `<table${dirAttribute(node)}><tbody>${ctx.renderChildren(node.children ?? [])}</tbody></table>`;\n\nconst tableRowRenderer: NodeRenderer = (node, ctx) =>\n `<tr>${ctx.renderChildren(node.children ?? [])}</tr>`;\n\nconst tableCellRenderer: NodeRenderer = (node, ctx): string => {\n const header = typeof node['headerState'] === 'number' ? node['headerState'] : 0;\n const tag = (header & (HEADER_ROW | HEADER_COLUMN)) === 0 ? 'td' : 'th';\n const scope =\n header === HEADER_ROW ? ' scope=\"col\"' : header === HEADER_COLUMN ? ' scope=\"row\"' : '';\n return `<${tag}${scope}${spanAttribute('colspan', node['colSpan'])}${spanAttribute('rowspan', node['rowSpan'])}>${ctx.renderChildren(node.children ?? [])}</${tag}>`;\n};\n\nfunction spanAttribute(name: string, value: unknown): string {\n return typeof value === 'number' && value > 1 ? ` ${name}=\"${String(value)}\"` : '';\n}\n\nexport { tableRenderer, tableRowRenderer, tableCellRenderer };\n","import type { NodeRenderer } from '../registry';\nimport { textRenderer } from './text';\nimport { paragraphRenderer } from './paragraph';\nimport { headingRenderer } from './heading';\nimport { listRenderer, listItemRenderer } from './list';\nimport { linkRenderer } from './link';\nimport { quoteRenderer } from './quote';\nimport { codeRenderer, codeHighlightRenderer } from './code';\nimport { linebreakRenderer, horizontalRuleRenderer, tabRenderer } from './linebreak';\nimport { uploadRenderer } from './upload';\nimport { relationshipRenderer } from './relationship';\nimport { blockRenderer, inlineBlockRenderer } from './block';\nimport { tableCellRenderer, tableRenderer, tableRowRenderer } from './table';\n\n// A value table instead of `register()` calls at import time: a consumer that\n// never renders Lexical content must not carry these under `sideEffects: false`.\nexport const BUILTIN_NODE_RENDERERS: Readonly<Record<string, NodeRenderer>> = {\n text: textRenderer,\n paragraph: paragraphRenderer,\n heading: headingRenderer,\n list: listRenderer,\n listitem: listItemRenderer,\n link: linkRenderer,\n autolink: linkRenderer,\n quote: quoteRenderer,\n code: codeRenderer,\n 'code-highlight': codeHighlightRenderer,\n linebreak: linebreakRenderer,\n horizontalrule: horizontalRuleRenderer,\n tab: tabRenderer,\n upload: uploadRenderer,\n relationship: relationshipRenderer,\n block: blockRenderer,\n inlineBlock: inlineBlockRenderer,\n table: tableRenderer,\n tablerow: tableRowRenderer,\n tablecell: tableCellRenderer,\n};\n","/** `text` renderer. Format flags wrap in a fixed order so equal input gives byte-equal output. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { LexicalNode } from '../types';\nimport { TextFormat } from '../types';\nimport type { NodeRenderer } from '../registry';\n\nconst textRenderer: NodeRenderer = (node: LexicalNode): string => {\n const raw = typeof node.text === 'string' ? node.text : '';\n let out = escapeHtml(raw);\n const format = typeof node.format === 'number' ? node.format : 0;\n if ((format & TextFormat.CODE) !== 0) out = `<code>${out}</code>`;\n if ((format & TextFormat.BOLD) !== 0) out = `<strong>${out}</strong>`;\n if ((format & TextFormat.ITALIC) !== 0) out = `<em>${out}</em>`;\n if ((format & TextFormat.UNDERLINE) !== 0) out = `<u>${out}</u>`;\n if ((format & TextFormat.STRIKETHROUGH) !== 0) out = `<s>${out}</s>`;\n if ((format & TextFormat.SUBSCRIPT) !== 0) out = `<sub>${out}</sub>`;\n if ((format & TextFormat.SUPERSCRIPT) !== 0) out = `<sup>${out}</sup>`;\n if ((format & TextFormat.HIGHLIGHT) !== 0) out = `<mark>${out}</mark>`;\n return out;\n};\n\nexport { textRenderer };\n","/**\n * Lexical document types. Only `type` and `children` are required; every\n * other property is forwarded opaquely to the renderer for that node type.\n */\n\n/** Lexical text-format bitmask; flags combine (`BOLD | ITALIC === 3`). */\nexport const TextFormat = {\n BOLD: 1,\n ITALIC: 2,\n STRIKETHROUGH: 4,\n UNDERLINE: 8,\n CODE: 16,\n SUBSCRIPT: 32,\n SUPERSCRIPT: 64,\n HIGHLIGHT: 128,\n} as const;\n\nexport interface LexicalNode {\n readonly type: string;\n readonly version?: number;\n readonly format?: number | string;\n readonly indent?: number;\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly children?: readonly LexicalNode[];\n readonly text?: string;\n readonly [extra: string]: unknown;\n}\n\nexport interface LexicalRoot {\n readonly root: {\n readonly type?: string;\n readonly children: readonly LexicalNode[];\n readonly direction?: 'ltr' | 'rtl' | null;\n readonly format?: number | string;\n readonly indent?: number;\n readonly [extra: string]: unknown;\n };\n}\n","/** `list` / `listitem` renderers: `bullet` → `<ul>`, `number` → `<ol>`, `check` → `<ul role=\"list\">` with `aria-checked` items. */\n\nimport { escapeHtml } from '@security/escape';\nimport type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst listRenderer: NodeRenderer = (node, ctx): string => {\n const listType = typeof node['listType'] === 'string' ? node['listType'] : 'bullet';\n const tag = listType === 'number' ? 'ol' : 'ul';\n const startAttr =\n listType === 'number' && typeof node['start'] === 'number' && node['start'] > 1\n ? ` start=\"${String(node['start'])}\"`\n : '';\n const checkAttr = listType === 'check' ? ' role=\"list\"' : '';\n const children = ctx.renderChildren(node.children ?? []);\n return `<${tag}${dirAttribute(node)}${layoutClassAttribute(node)}${startAttr}${checkAttr}>${children}</${tag}>`;\n};\n\nconst listItemRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n if (typeof node['checked'] === 'boolean') {\n const state = node['checked'] ? 'true' : 'false';\n return `<li role=\"checkbox\" aria-checked=\"${state}\"${layoutClassAttribute(node)}>${children}</li>`;\n }\n const valueAttr =\n typeof node['value'] === 'number' ? ` value=\"${escapeHtml(String(node['value']))}\"` : '';\n return `<li${dirAttribute(node)}${layoutClassAttribute(node)}${valueAttr}>${children}</li>`;\n};\n\nexport { listRenderer, listItemRenderer };\n","import type { NodeRenderer } from '../registry';\nimport { dirAttribute, layoutClassAttribute } from '../utils';\n\nconst quoteRenderer: NodeRenderer = (node, ctx): string => {\n const children = ctx.renderChildren(node.children ?? []);\n return `<blockquote${dirAttribute(node)}${layoutClassAttribute(node)}>${children}</blockquote>`;\n};\n\nexport { quoteRenderer };\n","import type { NodeRenderer } from '../registry';\n\nconst linebreakRenderer: NodeRenderer = () => '<br>';\nconst horizontalRuleRenderer: NodeRenderer = () => '<hr>';\nconst tabRenderer: NodeRenderer = () => '\\t';\n\nexport { linebreakRenderer, horizontalRuleRenderer, tabRenderer };\n","/** Node-renderer registry: consumer registrations layered over the built-in table. */\n\nimport type { LexicalNode } from './types';\nimport { BUILTIN_NODE_RENDERERS } from './nodes/builtin';\n\nexport interface RenderNodeContext {\n /** Render child nodes through the registry. */\n readonly renderChildren: (children: readonly LexicalNode[]) => string;\n /** Text alignment of a block node, or `undefined`. */\n readonly resolveAlignment: (node: LexicalNode) => string | undefined;\n /** Indent level of a node, `0` when none. */\n readonly resolveIndent: (node: LexicalNode) => number;\n}\n\nexport type NodeRenderer = (node: LexicalNode, context: RenderNodeContext) => string;\n\nconst registry = new Map<string, NodeRenderer>();\n\n/** Register or replace the renderer for `type`. */\nexport function register(type: string, renderer: NodeRenderer): void {\n registry.set(type, renderer);\n}\n\nexport function lookup(type: string): NodeRenderer | undefined {\n return registry.get(type) ?? BUILTIN_NODE_RENDERERS[type];\n}\n\nexport function registeredTypes(): readonly string[] {\n return [...new Set([...Object.keys(BUILTIN_NODE_RENDERERS), ...registry.keys()])];\n}\n\n/** Test-only: drop consumer registrations. */\nexport function __resetForTests(): void {\n registry.clear();\n}\n","/**\n * Lexical → HTML. Each node dispatches to the renderer registered for its\n * `type`; an unknown node renders its children so content is never lost.\n */\n\nimport { sanitizeHtml, hasSanitizerDocument } from '@security/sanitizer';\nimport { lookup, type RenderNodeContext } from './registry';\nimport type { LexicalNode, LexicalRoot } from './types';\nimport { resolveAlignment, resolveIndent } from './utils';\n\nconst RENDER_CONTEXT: RenderNodeContext = {\n renderChildren,\n resolveAlignment,\n resolveIndent,\n};\n\nexport interface LexicalRenderOptions {\n /** Pass the result through `sanitizeHtml()` (default `true`). */\n readonly sanitize?: boolean;\n}\n\nlet warnedNoSanitizer = false;\n\nexport function isLexicalContent(value: unknown): value is LexicalRoot {\n if (typeof value !== 'object' || value === null) return false;\n if (!('root' in value)) return false;\n const root = value.root;\n if (typeof root !== 'object' || root === null) return false;\n if (!('children' in root)) return false;\n return Array.isArray(root.children);\n}\n\n/** Render a Lexical document to HTML; without `setSanitizerDocument()` the result is unsanitised and warns once. */\nexport function lexicalToHtml(content: LexicalRoot, options: LexicalRenderOptions = {}): string {\n if (!isLexicalContent(content)) return '';\n const html = renderChildren(content.root.children);\n if (options.sanitize === false) return html;\n if (hasSanitizerDocument()) return sanitizeHtml(html);\n warnNoSanitizerOnce();\n return html;\n}\n\n/** Plain text of a document, paragraphs separated by `\\n`. */\nexport function lexicalToPlainText(content: LexicalRoot): string {\n if (!isLexicalContent(content)) return '';\n return content.root.children.map(extractPlainText).join('\\n').trim();\n}\n\n/** Test-only: allow the SSR warning to fire again. */\nexport function __resetSanitizerWarningForTests(): void {\n warnedNoSanitizer = false;\n}\n\nfunction renderChildren(children: readonly LexicalNode[]): string {\n let out = '';\n for (const child of children) out += renderNode(child);\n return out;\n}\n\nfunction renderNode(node: LexicalNode): string {\n const renderer = lookup(node.type);\n if (renderer) return renderer(node, RENDER_CONTEXT);\n return node.children !== undefined ? renderChildren(node.children) : '';\n}\n\nfunction extractPlainText(node: LexicalNode): string {\n if (typeof node.text === 'string') return node.text;\n if (node.type === 'linebreak') return '\\n';\n if (node.children === undefined) return '';\n let out = '';\n for (const child of node.children) out += extractPlainText(child);\n return out;\n}\n\n// This layer may not import `@core/diagnostics` (architecture policy), so the\n// warn-once lives here; a hostile or absent console must not break rendering.\nfunction warnNoSanitizerOnce(): void {\n if (warnedNoSanitizer) return;\n warnedNoSanitizer = true;\n try {\n console.warn(\n '[live-preview] lexicalToHtml() has no sanitizer document and returned unsanitised HTML; ' +\n 'call setSanitizerDocument() (linkedom/jsdom) for server rendering, see docs/security.md §3.',\n );\n } catch {\n // Diagnostics never become a second failure.\n }\n}\n","/**\n * `text` / `textarea` renderer. An element with structured children is left\n * alone (warned once) unless it opts in with `data-payload-text`, so a styled\n * wrapper is not destroyed by a value meant for its text node.\n */\n\nimport { isLexicalContent, lexicalToPlainText } from '@lexical/render';\nimport { trustedHtml } from '@security/trusted-types';\nimport { escapeAndLinebreak } from '@security/escape';\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer, RendererKey } from '@core/types';\n\nconst TEXT_OPT_IN_ATTRIBUTE = 'data-payload-text';\n\n/** Build the renderer with its own warn-once state; one per client (ADR 0002). */\nexport function createTextRenderer(name: RendererKey = 'text'): FieldRenderer {\n const warnedElements = new WeakSet<Element>();\n\n return {\n name,\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n const text = toPlainString(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n if (hasForeignChildren(element) && !element.hasAttribute(TEXT_OPT_IN_ATTRIBUTE)) {\n warnOnce(warnedElements, element, target.fieldName);\n return false;\n }\n if (text.includes('\\n') || text.includes('\\r')) {\n element.innerHTML = trustedHtml(escapeAndLinebreak(text));\n return;\n }\n element.textContent = text;\n return;\n }),\n };\n}\n\n// `<br>` is this renderer's own multiline output, not a consumer wrapper;\n// counting it froze every multiline binding after its first write.\nfunction hasForeignChildren(element: Element): boolean {\n return element.querySelector(':scope > :not(br)') !== null;\n}\n\nfunction warnOnce(warnedElements: WeakSet<Element>, element: Element, fieldName: string): void {\n if (warnedElements.has(element)) return;\n warnedElements.add(element);\n safeConsoleWarn(\n `[live-preview] LP0402: Skipping text update for \"${fieldName}\": ` +\n `<${element.tagName.toLowerCase()}> has structured children. Move ` +\n `data-payload-field to the value element, or add data-payload-text to replace them.`,\n );\n}\n\nfunction toPlainString(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (isLexicalContent(value)) return lexicalToPlainText(value);\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n return JSON.stringify(value);\n}\n","/**\n * `richText` renderer: a Lexical root or an HTML string. A project\n * `renderRichText` takes precedence; its output is sanitised like every\n * other HTML write.\n */\n\nimport { isLexicalContent, lexicalToHtml } from '@lexical/render';\nimport { trustedHtml } from '@security/trusted-types';\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue } from './utils';\n\nconst richTextRenderer: FieldRenderer = {\n name: 'richText',\n render: /* @__PURE__ */ markNoWriteCallback((target, value, context) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.textContent = '';\n return;\n }\n if (context.renderRichText !== undefined) {\n const html = context.renderRichText(value, {\n fieldName: target.fieldName,\n element,\n locale: context.locale,\n });\n element.innerHTML = trustedHtml(sanitizeHtml(html));\n return;\n }\n if (isLexicalContent(value)) {\n element.innerHTML = trustedHtml(lexicalToHtml(value));\n return;\n }\n if (typeof value === 'string') {\n element.innerHTML = trustedHtml(sanitizeHtml(value));\n return;\n }\n return false;\n }),\n};\n\nexport { richTextRenderer };\n","/** `html` renderer (`data-payload-type=\"html\"`): the value is sanitised, then injected. */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst htmlRenderer: FieldRenderer = {\n name: 'html',\n render(target, value) {\n if (isEmptyValue(value)) {\n target.element.textContent = '';\n return;\n }\n const html = typeof value === 'string' ? value : safeStringify(value);\n target.element.innerHTML = trustedHtml(sanitizeHtml(html));\n },\n};\n\nexport { htmlRenderer };\n","/** URL acceptance shared by the renderers that write `href` / `src`: one LP0401 warning per element. */\n\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { isSafeUrl } from '@security/url-validator';\n\n// Keyed by element so a second client on the same page does not repeat the warning.\nconst warned = new WeakSet<Element>();\n\nexport type UrlOutcome =\n | { readonly kind: 'none' }\n | { readonly kind: 'unsafe' }\n | { readonly kind: 'safe'; readonly url: string };\n\n/** `none` when there is no URL to write, `unsafe` (warned once) when it fails `isSafeUrl`. */\nexport function acceptUrl(element: Element, fieldName: string, candidate: unknown): UrlOutcome {\n if (typeof candidate !== 'string' || candidate.length === 0) return { kind: 'none' };\n if (isSafeUrl(candidate)) return { kind: 'safe', url: candidate };\n if (!warned.has(element)) {\n warned.add(element);\n safeConsoleWarn(\n `[live-preview] LP0401: refused an unsafe URL for \"${fieldName}\" on ` +\n `<${element.tagName.toLowerCase()}>; the attribute was cleared.`,\n );\n }\n return { kind: 'unsafe' };\n}\n","/**\n * `url` renderer and the factory the `email` renderer shares. On an `<a>` the\n * value (or the `data-payload-href` sibling) becomes `href`; the value is\n * always the visible text.\n */\n\nimport { resolveFieldValue } from '@core/field-value';\nimport type { FieldRenderer, RendererKey } from '@core/types';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue, safeStringify } from './utils';\n\n/** Build the link renderer named `name`; `toHref` derives the URL from the field value. */\nexport function createLinkRenderer(\n name: RendererKey,\n toHref: (value: string) => string = (value) => value,\n): FieldRenderer {\n return {\n name,\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const text = safeStringify(value);\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = text;\n return;\n }\n if (element.tagName === 'A') {\n const hrefField = target.hrefField;\n const candidate =\n hrefField === undefined || hrefField.length === 0\n ? toHref(text)\n : resolveFieldValue(\n context.allFields,\n hrefField,\n context.locale,\n target.locale !== undefined,\n );\n const outcome = acceptUrl(element, target.fieldName, candidate);\n if (outcome.kind === 'safe') element.setAttribute('href', outcome.url);\n else if (outcome.kind === 'unsafe') element.removeAttribute('href');\n }\n element.textContent = text;\n },\n };\n}\n\nfunction clear(element: Element): void {\n if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {\n (element as HTMLInputElement | HTMLTextAreaElement).value = '';\n return;\n }\n element.removeAttribute('href');\n element.textContent = '';\n}\n\nexport const urlRenderer: FieldRenderer = createLinkRenderer('url');\n","/** `email` renderer: a bare address becomes a `mailto:` link, a value with a scheme is used as written. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { createLinkRenderer } from './url';\n\nconst HAS_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;\n\nfunction mailtoHref(value: string): string {\n const trimmed = value.trim();\n if (HAS_SCHEME.test(trimmed) || !trimmed.includes('@')) return trimmed;\n return `mailto:${trimmed}`;\n}\n\nexport const emailRenderer: FieldRenderer = createLinkRenderer('email', mailtoHref);\n","/** `<img>` writes shared by the image and upload renderers. */\n\nimport { isSafeUrl } from '@security/url-validator';\nimport type { MediaShape } from '@lexical/value-shapes';\n\nconst IMAGE_SOURCE_ATTRIBUTES = ['src', 'srcset', 'sizes'] as const;\n\nexport function clearImage(img: HTMLImageElement): void {\n for (const name of IMAGE_SOURCE_ATTRIBUTES) img.removeAttribute(name);\n}\n\n/**\n * A server-rendered `srcset` would keep winning over a new `src`, so it is\n * rebuilt from the media's `sizes` or removed together with `sizes`.\n */\nexport function writeImage(\n img: HTMLImageElement,\n url: string,\n media: MediaShape | undefined,\n): void {\n img.src = url;\n const srcset = buildSrcset(media);\n if (srcset === undefined) {\n img.removeAttribute('srcset');\n img.removeAttribute('sizes');\n return;\n }\n img.setAttribute('srcset', srcset);\n}\n\nfunction buildSrcset(media: MediaShape | undefined): string | undefined {\n if (media?.sizes === undefined) return undefined;\n const candidates: string[] = [];\n for (const size of Object.values(media.sizes)) {\n if (typeof size.url !== 'string' || typeof size.width !== 'number' || !isSafeUrl(size.url)) {\n continue;\n }\n candidates.push(`${srcsetUrl(size.url)} ${String(size.width)}w`);\n }\n if (candidates.length === 0) return undefined;\n if (typeof media.width === 'number' && typeof media.url === 'string' && isSafeUrl(media.url)) {\n candidates.push(`${srcsetUrl(media.url)} ${String(media.width)}w`);\n }\n return candidates.join(', ');\n}\n\n// Commas and whitespace delimit srcset candidates and cannot appear raw in a URL there.\nfunction srcsetUrl(url: string): string {\n return url.replace(/[\\s,]/g, encodeURIComponent);\n}\n","/**\n * `image` renderer: `src`/`alt`/`srcset` on an `<img>`, a CSS background on\n * anything else. The value is a media object, a URL string, or resolved from\n * the `data-payload-src` / `data-payload-alt` sibling fields.\n */\n\nimport { escapeCssUrl } from '@security/escape';\nimport { resolveFieldValue } from '@core/field-value';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { CachedElement, FieldRenderer, RenderContext } from '@core/types';\nimport { readMedia, type MediaShape } from '@lexical/value-shapes';\nimport { clearImage, writeImage } from './media';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue } from './utils';\n\nconst imageRenderer: FieldRenderer = {\n name: 'image',\n render: /* @__PURE__ */ markNoWriteCallback((target, value, context) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const preferLocale = target.locale !== undefined;\n const { media, candidate } = pickSource(target, value, context, preferLocale);\n const outcome = acceptUrl(element, target.fieldName, candidate);\n if (outcome.kind === 'none') return false;\n if (outcome.kind === 'unsafe') {\n clear(element);\n return;\n }\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n writeImage(img, outcome.url, media);\n const alt = pickAlt(media, target.altField, context.allFields, context.locale, preferLocale);\n if (alt !== undefined) img.alt = alt;\n return;\n }\n (element as HTMLElement).style.backgroundImage = `url('${escapeCssUrl(outcome.url)}')`;\n return;\n }),\n};\n\nfunction clear(element: Element): void {\n if (element.tagName === 'IMG') clearImage(element as HTMLImageElement);\n else (element as HTMLElement).style.backgroundImage = '';\n}\n\nfunction pickSource(\n target: CachedElement,\n value: unknown,\n context: RenderContext,\n preferLocale: boolean,\n): { readonly media: MediaShape | undefined; readonly candidate: unknown } {\n const source =\n target.srcField !== undefined && target.srcField.length > 0\n ? resolveFieldValue(context.allFields, target.srcField, context.locale, preferLocale)\n : value;\n const media = readMedia(source);\n return { media, candidate: media === undefined ? source : media.url };\n}\n\nfunction pickAlt(\n media: MediaShape | undefined,\n altField: string | undefined,\n allFields: Record<string, unknown>,\n locale: string | undefined,\n preferLocale: boolean,\n): string | undefined {\n if (altField !== undefined && altField.length > 0) {\n const sibling = resolveFieldValue(allFields, altField, locale, preferLocale);\n return typeof sibling === 'string' ? sibling : undefined;\n }\n return media?.alt;\n}\n\nexport { imageRenderer };\n","/** `upload` renderer: an image on `<img>`, a download link on `<a>`, an injected link elsewhere. */\n\nimport { escapeHtml, escapeHtmlAttribute } from '@security/escape';\nimport { trustedHtml } from '@security/trusted-types';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport type { FieldRenderer } from '@core/types';\nimport { readMedia } from '@lexical/value-shapes';\nimport { clearImage, writeImage } from './media';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue } from './utils';\n\nconst uploadRenderer: FieldRenderer = {\n name: 'upload',\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n clear(element);\n return;\n }\n const media = readMedia(value);\n if (media === undefined) return false;\n const outcome = acceptUrl(element, target.fieldName, media.url);\n if (outcome.kind === 'none') return false;\n if (outcome.kind === 'unsafe') {\n clear(element);\n return;\n }\n const url = outcome.url;\n if (element.tagName === 'IMG') {\n const img = element as HTMLImageElement;\n writeImage(img, url, media);\n if (media.alt !== undefined) img.alt = media.alt;\n return;\n }\n if (element.tagName === 'A') {\n element.setAttribute('href', url);\n element.textContent = media.filename ?? url;\n return;\n }\n const label = escapeHtml(media.filename ?? url);\n element.innerHTML = trustedHtml(`<a href=\"${escapeHtmlAttribute(url)}\">${label}</a>`);\n return;\n }),\n};\n\nfunction clear(element: Element): void {\n if (element.tagName === 'IMG') {\n clearImage(element as HTMLImageElement);\n return;\n }\n element.removeAttribute('href');\n element.textContent = '';\n}\n\nexport { uploadRenderer };\n","/** `relationship` renderer: the relation's label as text; on an `<a>` a populated `url` becomes `href`. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { asRecord, pickRelationLabel, type RelationShape } from '@lexical/value-shapes';\nimport { acceptUrl } from './unsafe-url';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst relationshipRenderer: FieldRenderer = {\n name: 'relationship',\n render(target, value) {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.removeAttribute('href');\n element.textContent = '';\n return;\n }\n if (element.tagName === 'A' && !Array.isArray(value)) {\n const outcome = acceptUrl(element, target.fieldName, asRecord(value)?.['url']);\n if (outcome.kind === 'safe') element.setAttribute('href', outcome.url);\n else if (outcome.kind === 'unsafe') element.removeAttribute('href');\n }\n element.textContent = Array.isArray(value) ? value.map(label).join(', ') : label(value);\n },\n};\n\nfunction label(value: unknown): string {\n const record = asRecord(value) as RelationShape | undefined;\n if (record === undefined) return safeStringify(value);\n return pickRelationLabel(record) ?? '';\n}\n\nexport { relationshipRenderer };\n","/**\n * `select` / `radio` renderer. Form controls receive option values; other\n * elements show the option labels from the field schema when the admin sent\n * one, else the values.\n */\n\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { asRecord } from '@lexical/value-shapes';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst selectRenderer: FieldRenderer = {\n name: 'select',\n render(target, value, context) {\n const element = target.element;\n const values = isEmptyValue(value) ? [] : toValues(value);\n if (element.tagName === 'SELECT') {\n writeSelect(element as HTMLSelectElement, values);\n return;\n }\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'radio') {\n const radio = element as HTMLInputElement;\n radio.checked = values.includes(radio.value);\n return;\n }\n element.textContent = values.map((item) => labelFor(item, context)).join(', ');\n },\n};\n\nfunction toValues(value: unknown): readonly string[] {\n if (Array.isArray(value)) return value.map(safeStringify);\n return [safeStringify(value)];\n}\n\n// `.value = 'a, b'` on a multiple select selects nothing; options are set one by one.\nfunction writeSelect(select: HTMLSelectElement, values: readonly string[]): void {\n if (select.multiple) {\n for (const option of Array.from(select.options)) {\n option.selected = values.includes(option.value);\n }\n return;\n }\n select.value = values[0] ?? '';\n}\n\nfunction labelFor(value: string, context: RenderContext): string {\n const options = context.schema?.['options'];\n if (!Array.isArray(options)) return value;\n for (const option of options) {\n const record = asRecord(option);\n if (record === undefined || safeStringify(record['value']) !== value) continue;\n return typeof record['label'] === 'string' ? record['label'] : value;\n }\n return value;\n}\n\nexport { selectRenderer };\n","/** `checkbox` renderer: `checked` on an input, `aria-checked` where present, `true`/`false` text otherwise. */\n\nimport type { FieldRenderer } from '@core/types';\n\nconst FALSE_STRINGS = new Set(['', 'false', '0', 'off', 'no']);\n\nconst checkboxRenderer: FieldRenderer = {\n name: 'checkbox',\n render(target, value) {\n const element = target.element;\n const checked = toBoolean(value);\n if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'checkbox') {\n (element as HTMLInputElement).checked = checked;\n return;\n }\n if (element.hasAttribute('aria-checked')) {\n element.setAttribute('aria-checked', checked ? 'true' : 'false');\n return;\n }\n element.textContent = checked ? 'true' : 'false';\n },\n};\n\n// Form state and query parameters arrive as strings; `Boolean('false')` is not an answer.\nfunction toBoolean(value: unknown): boolean {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return !FALSE_STRINGS.has(value.trim().toLowerCase());\n if (typeof value === 'number') return value !== 0;\n return value !== null && value !== undefined;\n}\n\nexport { checkboxRenderer };\n","/**\n * Memoised `Intl` formatters, keyed by locale and options. Constructing them\n * per call dominates render time for arrays of many numeric or date fields,\n * and a formatter is a pure function of its key, so one instance is safe to\n * share across the page. Bounded so a language switcher cannot grow it without\n * limit.\n */\n\nconst NUMBER_CACHE = new Map<string, Intl.NumberFormat>();\nconst DATE_CACHE = new Map<string, Intl.DateTimeFormat>();\n\nconst DEFAULT_MAX_ENTRIES = 64;\n\nlet maxEntries = DEFAULT_MAX_ENTRIES;\n\n/** Internal test helper — purges every cached formatter. */\nexport function __resetIntlCache(): void {\n NUMBER_CACHE.clear();\n DATE_CACHE.clear();\n maxEntries = DEFAULT_MAX_ENTRIES;\n}\n\n/** Adjust the LRU bound. Returns the previous value. */\nexport function setIntlCacheLimit(limit: number): number {\n if (!Number.isFinite(limit) || limit < 1) return maxEntries;\n const previous = maxEntries;\n maxEntries = Math.floor(limit);\n trimToLimit(NUMBER_CACHE);\n trimToLimit(DATE_CACHE);\n return previous;\n}\n\n/** Cache occupancy, for tests and dev observability. */\nexport function intlCacheSize(): { readonly numbers: number; readonly dates: number } {\n return { numbers: NUMBER_CACHE.size, dates: DATE_CACHE.size };\n}\n\nexport function getNumberFormat(\n locale: string | undefined,\n options?: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n const key = buildKey(locale, options);\n const cached = NUMBER_CACHE.get(key);\n if (cached !== undefined) {\n NUMBER_CACHE.delete(key);\n NUMBER_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.NumberFormat(locale, options);\n NUMBER_CACHE.set(key, formatter);\n trimToLimit(NUMBER_CACHE);\n return formatter;\n}\n\nexport function getDateTimeFormat(\n locale: string | undefined,\n options?: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key = buildKey(locale, options);\n const cached = DATE_CACHE.get(key);\n if (cached !== undefined) {\n DATE_CACHE.delete(key);\n DATE_CACHE.set(key, cached);\n return cached;\n }\n const formatter = new Intl.DateTimeFormat(locale, options);\n DATE_CACHE.set(key, formatter);\n trimToLimit(DATE_CACHE);\n return formatter;\n}\n\nfunction buildKey(locale: string | undefined, options: unknown): string {\n // Stable key order so equivalent option objects share a slot, and an empty\n // one collapses to the bare-locale key.\n const localePart = locale ?? '';\n if (options === undefined || options === null) return localePart;\n const serialised = stableStringify(options);\n if (serialised === '{}') return localePart;\n return `${localePart}|${serialised}`;\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((v) => stableStringify(v)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const inner = record[key];\n if (inner === undefined) continue;\n parts.push(`${JSON.stringify(key)}:${stableStringify(inner)}`);\n }\n return `{${parts.join(',')}}`;\n}\n\nfunction trimToLimit(map: Map<string, unknown>): void {\n while (map.size > maxEntries) {\n const oldest = map.keys().next().value;\n if (oldest === undefined) break;\n map.delete(oldest);\n }\n}\n","/**\n * `date` renderer. `<time>` gets an ISO `datetime` plus a localised label;\n * date inputs get the value in the visitor's local time zone, because that is\n * what the control displays.\n */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getDateTimeFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst dateRenderer: FieldRenderer = {\n name: 'date',\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n if (element.tagName === 'INPUT') (element as HTMLInputElement).value = '';\n else {\n element.removeAttribute('datetime');\n element.textContent = '';\n }\n return;\n }\n const raw = typeof value === 'number' ? value : safeStringify(value);\n const date = new Date(raw);\n const valid = !Number.isNaN(date.getTime());\n const fallback = String(raw);\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = valid\n ? formatForInput((element as HTMLInputElement).type, date)\n : fallback;\n return;\n }\n if (element.tagName === 'TIME') {\n element.setAttribute('datetime', valid ? date.toISOString() : fallback);\n }\n element.textContent = valid ? formatDate(date, context) : fallback;\n },\n};\n\nfunction formatDate(date: Date, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getDateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date);\n } catch {\n return date.toISOString();\n }\n}\n\n/** Value for `<input type=\"date|datetime-local|time\">` in local time; other inputs get the ISO instant. */\nexport function formatForInput(type: string, date: Date): string {\n const day = `${String(date.getFullYear()).padStart(4, '0')}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;\n if (type === 'date') return day;\n if (type === 'datetime-local') return `${day}T${clock}`;\n if (type === 'time') return clock;\n return date.toISOString();\n}\n\nfunction pad(value: number): string {\n return String(value).padStart(2, '0');\n}\n\nexport { dateRenderer };\n","/** `number` renderer: raw value on inputs, `Intl.NumberFormat` elsewhere. */\n\nimport { detectInitialLocale } from '@detection/locale';\nimport { getNumberFormat } from '@core/intl-cache';\nimport type { FieldRenderer, RenderContext } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst numberRenderer: FieldRenderer = {\n name: 'number',\n render(target, value, context) {\n const element = target.element;\n if (isEmptyValue(value)) {\n if (element.tagName === 'INPUT') (element as HTMLInputElement).value = '';\n else element.textContent = '';\n return;\n }\n const num = typeof value === 'number' ? value : Number(safeStringify(value));\n if (Number.isNaN(num)) {\n element.textContent = safeStringify(value);\n return;\n }\n if (element.tagName === 'INPUT') {\n (element as HTMLInputElement).value = String(num);\n return;\n }\n element.textContent = format(num, context);\n },\n};\n\nfunction format(num: number, context: RenderContext): string {\n const locale = context.locale ?? detectInitialLocale();\n try {\n return getNumberFormat(locale).format(num);\n } catch {\n return String(num);\n }\n}\n\nexport { numberRenderer };\n","/**\n * `array` / `blocks` renderer. With `data-payload-array-template` each item\n * is interpolated into the template (`{{key}}`, `{{value}}`, `{{index}}`);\n * without one, items are joined by `data-payload-array-separator`.\n */\n\nimport { sanitizeHtml } from '@security/sanitizer';\nimport { trustedHtml } from '@security/trusted-types';\nimport { interpolateArrayTemplate } from '@core/array-template';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport { templateSanitizeOptions } from '@core/template-sanitize';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue, safeStringify } from './utils';\n\nconst arrayRenderer: FieldRenderer = {\n name: 'array',\n render: /* @__PURE__ */ markNoWriteCallback((target, value) => {\n const element = target.element;\n if (isEmptyValue(value)) {\n element.textContent = '';\n return;\n }\n if (!Array.isArray(value)) return false;\n const template = target.arrayTemplate;\n if (template !== undefined && template.length > 0) {\n const html = renderTemplate(template, value);\n element.innerHTML = trustedHtml(sanitizeHtml(html, templateSanitizeOptions(template)));\n return;\n }\n element.textContent = value.map(safeStringify).join(target.arraySeparator ?? ', ');\n return;\n }),\n};\n\nfunction renderTemplate(template: string, items: readonly unknown[]): string {\n let out = '';\n for (let i = 0; i < items.length; i += 1) {\n out += interpolateArrayTemplate(template, items[i], i, safeStringify);\n }\n return out;\n}\n\nexport { arrayRenderer };\n","/**\n * `structural-array` renderer (`data-payload-structural`): diffs the previous\n * and next item lists and patches the container through the keyed morph\n * (ADR 0008). All diff memory lives in the closure, one per client.\n */\n\nimport { safeConsoleWarn } from '@core/diagnostics';\nimport { markNoWriteCallback } from '@core/internal-outcome';\nimport {\n applyStructuralPatches,\n createStructuralStore,\n KEY_ATTRIBUTE,\n type StructuralStore,\n} from '@core/structural-applier';\nimport { diffArray } from '@schema/diff';\nimport type { FieldRenderer } from '@core/types';\nimport { isEmptyValue } from './utils';\n\ninterface StructuralRenderState {\n readonly values: readonly unknown[];\n readonly template: string;\n readonly domSnapshot: readonly (string | null)[];\n}\n\ntype WarnedCodes = WeakMap<Element, Set<string>>;\n\nexport function createStructuralArrayRenderer(): FieldRenderer {\n const states = new WeakMap<Element, StructuralRenderState>();\n const warnedContainers = new WeakSet<Element>();\n const warnedKeys: WarnedCodes = new WeakMap();\n const store: StructuralStore = createStructuralStore();\n\n return {\n name: 'structural-array',\n render: /* @__PURE__ */ markNoWriteCallback((target, rawValue) => {\n const value = isEmptyValue(rawValue) ? [] : rawValue;\n if (!Array.isArray(value)) return false;\n const container = target.element;\n const template = target.arrayTemplate;\n if (template === undefined || template.length === 0) {\n warnMissingTemplate(warnedContainers, container, target.fieldName);\n return false;\n }\n const previousState = states.get(container);\n const domSnapshot = readDomKeySnapshot(container);\n const previous = previousState?.values ?? valuesFromDomSnapshot(domSnapshot);\n const patches = diffArray(previous, value);\n const forceRender = needsForcedRender(previousState, template, domSnapshot);\n if (patches.length === 0 && !forceRender) {\n states.set(container, { values: value.slice(), template, domSnapshot });\n return false;\n }\n warnAboutKeys(warnedKeys, container, target.fieldName, previousState?.values, value);\n const applied = applyStructuralPatches({\n template,\n container,\n patches,\n nextItems: value,\n store,\n forceRender,\n onDuplicateKey: (owner, key) => {\n warnDuplicateKey(warnedKeys, owner, target.fieldName, key);\n },\n });\n if (applied === null) return false;\n states.set(container, {\n values: value.slice(),\n template,\n domSnapshot: readDomKeySnapshot(container),\n });\n return applied ? undefined : false;\n }),\n };\n}\n\nfunction needsForcedRender(\n previous: StructuralRenderState | undefined,\n template: string,\n domSnapshot: readonly (string | null)[],\n): boolean {\n if (previous === undefined) return true;\n return previous.template !== template || !sameDomKeySnapshot(previous.domSnapshot, domSnapshot);\n}\n\n// SSR markup exists before any in-memory snapshot; its direct-child keys let\n// the first update reconcile instead of appending a second copy.\nfunction readDomKeySnapshot(container: Element): readonly (string | null)[] {\n return Array.from(container.children, (child) => child.getAttribute(KEY_ATTRIBUTE));\n}\n\nfunction valuesFromDomSnapshot(snapshot: readonly (string | null)[]): readonly unknown[] {\n return snapshot.map((key, position) =>\n key === null ? { __payloadDomPosition: position } : { id: key },\n );\n}\n\nfunction sameDomKeySnapshot(\n previous: readonly (string | null)[],\n current: readonly (string | null)[],\n): boolean {\n if (previous.length !== current.length) return false;\n return previous.every((key, index) => key === current[index]);\n}\n\nfunction warnMissingTemplate(\n warnedContainers: WeakSet<Element>,\n container: Element,\n fieldName: string,\n): void {\n if (warnedContainers.has(container)) return;\n warnedContainers.add(container);\n safeConsoleWarn(\n `[live-preview] LP0403: Skipping structural update for \"${fieldName}\": ` +\n `<${container.tagName.toLowerCase()} data-payload-structural> needs ` +\n `data-payload-array-template (for example \"<li>{{label}}</li>\").`,\n );\n}\n\nfunction itemKey(value: unknown): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const id = (value as Record<string, unknown>)['id'];\n return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;\n}\n\n/** Key problems degrade the morph, they do not break it; each is announced once per container (ADR 0008 §5). */\nfunction warnAboutKeys(\n warned: WarnedCodes,\n container: Element,\n fieldName: string,\n previous: readonly unknown[] | undefined,\n next: readonly unknown[],\n): void {\n const nextKeys = next.map(itemKey);\n const seen = new Set<string>();\n const duplicate = nextKeys.find((key) => {\n if (key === undefined) return false;\n if (seen.has(key)) return true;\n seen.add(key);\n return false;\n });\n if (duplicate !== undefined) warnDuplicateKey(warned, container, fieldName, duplicate);\n if (nextKeys.some((key) => key === undefined)) {\n warnOnce(\n warned,\n container,\n 'LP0404',\n `LP0404: an item of \"${fieldName}\" has no id and pairs by ` +\n 'position, so an insert re-renders every row after it. Give items a stable id.',\n );\n }\n if (previous?.length === next.length && next.length > 1) {\n const previousKeys = new Set(previous.map(itemKey).filter((key) => key !== undefined));\n const stable = nextKeys.some((key) => key !== undefined && previousKeys.has(key));\n if (previousKeys.size > 0 && !stable) {\n warnOnce(\n warned,\n container,\n 'LP0406',\n `LP0406: every key of \"${fieldName}\" changed at once; the ` +\n 'source generates ids per message, so no item can be retained across updates.',\n );\n }\n }\n}\n\n// Reached from the pre-diff check and from the morph's nested-slot check; one site, one message.\nfunction warnDuplicateKey(\n warned: WarnedCodes,\n owner: Element,\n fieldName: string,\n key: string,\n): void {\n warnOnce(\n warned,\n owner,\n 'LP0405',\n `LP0405: two items of \"${fieldName}\" share the key \"${key}\"; later ones pair by ` +\n 'position. Make `id` unique per item.',\n );\n}\n\nfunction warnOnce(warned: WarnedCodes, container: Element, code: string, message: string): void {\n let codes = warned.get(container);\n if (codes === undefined) {\n codes = new Set();\n warned.set(container, codes);\n }\n if (codes.has(code)) return;\n codes.add(code);\n safeConsoleWarn(`[live-preview] ${message}`);\n}\n","/**\n * Explicit renderer overrides, layered above the defaults each time a map is\n * built. The registry never retains the defaults, so stateful ones can be\n * recreated per client.\n */\n\nimport type { FieldRenderer, RendererKey } from '@core/types';\n\nconst builtinRenderers = new Map<RendererKey, FieldRenderer>();\n\nexport function buildBuiltinRenderers(\n defaults: readonly FieldRenderer[] = [],\n): Readonly<Record<string, FieldRenderer>> {\n const out: Record<string, FieldRenderer> = {};\n for (const renderer of defaults) out[renderer.name] = renderer;\n for (const [type, renderer] of builtinRenderers) out[type] = renderer;\n return Object.freeze(out);\n}\n\n/** Register or replace an override for maps built afterwards. */\nexport function registerBuiltinRenderer(renderer: FieldRenderer): void {\n builtinRenderers.set(renderer.name, renderer);\n}\n\n/** Test-only: clear the overrides. */\nexport function __resetBuiltinRenderersForTests(): void {\n builtinRenderers.clear();\n}\n","/** Drops `undefined`-valued keys, so a literal built from optional inputs satisfies `exactOptionalPropertyTypes`. */\n\nexport type DefinedOnly<T> = { readonly [K in keyof T]-?: Exclude<T[K], undefined> };\n\nexport function definedOnly<T extends object>(source: T): DefinedOnly<T> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(source)) {\n if (value !== undefined) result[key] = value;\n }\n return result as DefinedOnly<T>;\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\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","/**\n * `LivePreviewClient`: a `LivePreviewRuntime` with its own emitter, plugin\n * manager and renderer registry. A page that only needs a working preview uses\n * `generateInlineScript()` instead.\n */\n\nimport { LivePreviewRuntime, type RuntimeOptions } from '@core/lifecycle';\nimport type { LivePreviewInspection } from '@core/inspection/types';\nimport type { CachedElement, RendererKey } from '@core/types';\nimport { EventEmitter } from '@events/emitter';\nimport { OriginDetector } from '@detection/origin';\nimport { setSanitizerPolicy } from '@security/sanitizer';\nimport { PluginManager } from '@plugins/manager';\nimport { RendererRegistry } from '@plugins/renderer-registry';\nimport type { LivePreviewPlugin } from '@plugins/types';\nimport { isDevMode, isInPreviewContext } from '@detection/environment';\nimport { buildBuiltinRenderers } from '@field-types/index';\nimport { definedOnly } from '@/types/defined-only';\nimport { withProfileDefaults, type LivePreviewClientConfig } from './config';\nimport { noopDiagnostic, safeConsoleDebug } from '@core/diagnostics';\n\n/** `T` with every property optional and `undefined`-able, for literals built from optional inputs. */\ntype Loose<T> = { readonly [K in keyof T]?: T[K] | undefined };\n\nfunction invert(value: boolean | undefined): boolean | undefined {\n return value === undefined ? undefined : !value;\n}\n\nexport class LivePreviewClient {\n readonly #emitter = new EventEmitter();\n readonly #detector: OriginDetector;\n readonly #rendererRegistry: RendererRegistry;\n readonly #runtime: LivePreviewRuntime;\n readonly #plugins: PluginManager;\n readonly #log: (...args: unknown[]) => void;\n #started = false;\n #destroyed = false;\n #tornDown = false;\n #destroyPromise: Promise<void> | null = null;\n\n constructor(rawConfig: LivePreviewClientConfig = {}) {\n const config = withProfileDefaults(rawConfig);\n const serverURL = config.serverURL ?? '';\n if (rawConfig.defaults !== 'v1' && serverURL !== '' && config.mergeDepth === undefined) {\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 if (config.sanitizerPolicy !== undefined) setSanitizerPolicy(config.sanitizerPolicy);\n const debug = config.debug ?? isDevMode();\n this.#log = debug\n ? (...args): void => {\n safeConsoleDebug('[live-preview]', ...args);\n }\n : noopDiagnostic;\n\n this.#detector = new OriginDetector(\n definedOnly({\n additionalOrigins: config.allowedOrigins,\n enableReferrerDetection: invert(config.disableReferrerDetection),\n enableLocalhostMatching: invert(config.disableLocalhostMatching),\n }),\n );\n\n if (this.#detector.isProductionUnconfigured) {\n this.#log('no trusted origin could be detected — set allowedOrigins');\n }\n\n this.#rendererRegistry = new RendererRegistry(buildBuiltinRenderers());\n\n this.#plugins = new PluginManager({\n events: this.#emitter,\n config: Object.freeze({ ...config }),\n registerFieldRenderer: (renderer) => this.#rendererRegistry.register(renderer),\n onTransformError: (error) => {\n void this.#emitter.emit('error', { error, context: 'transform', code: 'LP0602' });\n },\n log: this.#log,\n });\n\n this.#runtime = new LivePreviewRuntime(\n definedOnly({\n root: config.root,\n renderers: this.#rendererRegistry.renderers,\n resolveRenderer: (fieldType: RendererKey, target: CachedElement) =>\n config.resolveRenderer?.(fieldType, target) ?? this.#rendererRegistry.resolve(fieldType),\n renderRichText: config.renderRichText,\n transformValue: (\n fieldName: string,\n value: unknown,\n context: { readonly element: Element; readonly allFields: Record<string, unknown> },\n isCurrent?: () => boolean,\n ) => this.#plugins.applyTransforms(fieldName, value, context, isCurrent),\n originMatcher: (origin: string) => this.#detector.matches(origin),\n // Read per handshake, not once: after a lock, a bfcache restore must\n // re-broadcast to the locked origin alone, not every pre-lock candidate.\n readyTargets: () => this.#detector.enumerate(),\n emitter: this.#emitter,\n dataMerge:\n serverURL === ''\n ? undefined\n : definedOnly({\n serverURL,\n apiRoute: config.apiRoute,\n depth: config.mergeDepth,\n fetchFn: config.mergeFetch,\n }),\n debounceMs: config.debounceMs,\n heartbeatMs: config.heartbeatMs,\n intersectionRootMargin: config.intersectionRootMargin,\n scopeBindingsByOwner: config.scopeBindingsByOwner,\n skipUnchanged: config.skipUnchanged,\n revealEditedField: config.revealEditedField,\n eventSourcePolicy: config.eventSourcePolicy,\n dependencies: config.dependencies,\n strategies: config.strategies,\n disableVisibilityGate: config.disableVisibilityGate,\n visibilityGateThreshold: config.visibilityGateThreshold,\n enableA11y: config.enableA11y,\n a11yLocale: config.a11yLocale,\n onHeartbeatTimeout: () => {\n this.#detector.unlockOrigin();\n },\n lockedOrigin: () => this.#detector.lockedOrigin,\n validateToken: config.validateToken,\n log: this.#log,\n } satisfies Loose<RuntimeOptions>),\n );\n\n this.#emitter.on('connect', (e) => {\n this.#detector.lockOrigin(e.origin);\n });\n\n if (config.autoStart !== false) {\n this.start();\n }\n }\n\n /**\n * Start the runtime: `true` while eligible and started or scheduled for DOM\n * readiness, `false` once destroyed or outside a preview context.\n */\n start(): boolean {\n if (this.#destroyed) return false;\n if (this.#started) {\n // A deferred DOM-ready startup can fail after this returned and roll\n // itself back; this call retries it.\n this.#runtime.start();\n return true;\n }\n if (!isInPreviewContext()) return false;\n const started = this.#runtime.start();\n if (started) this.#started = true;\n return started;\n }\n\n /**\n * Release the message ingress, keeping plugins and renderers, for `pagehide`:\n * a bfcache restore re-runs no script, so an attached client would return\n * bound to a frozen page. `false` when nothing was running.\n */\n suspend(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.suspend();\n }\n\n /** Reacquire after `suspend()`: the same path as `start()`, because a restored document needs the same rebuild. */\n resume(): boolean {\n if (this.#destroyed || !this.#started) return false;\n return this.#runtime.start();\n }\n\n /** Stop the runtime and tear down every plugin. Idempotent; concurrent callers share one promise. */\n destroy(): Promise<void> {\n if (this.#destroyPromise !== null) return this.#destroyPromise;\n this.#destroyed = true;\n let resolveDestroy!: () => void;\n let rejectDestroy!: (reason: unknown) => void;\n const inFlight = new Promise<void>((resolve, reject) => {\n resolveDestroy = resolve;\n rejectDestroy = reject;\n });\n // Published before the teardown: a `destroy` handler calling destroy()\n // re-entrantly must get this same promise.\n this.#destroyPromise = inFlight;\n const finish = (): void => {\n this.#emitter.removeAllListeners();\n this.#tornDown = true;\n };\n try {\n this.#runtime.destroy();\n void this.#plugins.destroyAll().finally(finish).then(resolveDestroy, rejectDestroy);\n } catch (error) {\n finish();\n rejectDestroy(error);\n }\n return inFlight;\n }\n\n async use(plugin: LivePreviewPlugin): Promise<void> {\n if (this.#destroyed) throw new Error('LivePreviewClient: already destroyed');\n await this.#plugins.register(plugin);\n }\n\n /** Unregister a plugin and release everything its registration owned. Still allowed from a destroy hook during teardown. */\n async unuse(name: string): Promise<void> {\n if (this.#tornDown) throw new Error('LivePreviewClient: already destroyed');\n await this.#plugins.unregister(name);\n }\n\n refreshCache(): void {\n this.#runtime.refreshCache();\n }\n\n get events(): EventEmitter {\n return this.#emitter;\n }\n\n /** Names of the registered plugins. */\n get plugins(): readonly string[] {\n return this.#plugins.list();\n }\n\n get status(): 'disconnected' | 'connecting' | 'connected' {\n return this.#runtime.status;\n }\n\n /**\n * Point-in-time read of runtime state, no I/O: `bindings.orphanFields` when a\n * field refuses to update, `scheduler.deferred` when updates stop below the fold.\n */\n inspect(): LivePreviewInspection {\n return { ...this.#runtime.inspect(), plugins: this.#plugins.snapshot() };\n }\n\n /** Number of accepted updates so far. */\n get updateCount(): number {\n return this.#runtime.updateCount;\n }\n\n /** `true` once `destroy()` has been called. */\n get destroyed(): boolean {\n return this.#destroyed;\n }\n}\n\n/** A started client, or `null` when the page is not a preview context. */\nexport function initLivePreview(config: LivePreviewClientConfig = {}): LivePreviewClient | null {\n const client = new LivePreviewClient({ ...config, autoStart: false });\n return client.start() ? client : null;\n}\n\nexport type { LivePreviewClientConfig } from './config';\n","/**\n * `LivePreviewClient` configuration. Defaults are the 2.0 rows; `defaults: 'v1'`\n * restores the 1.x values named per option (ADR 0007).\n */\n\nimport type { CachedElement, FieldRenderer, RendererKey, RichTextRenderer } from '@core/types';\nimport type { StrategyHandlers } from '@core/strategies';\nimport {\n runtimeDefaultsFor,\n type DefaultsProfile,\n type EventSourcePolicy,\n} from '@core/defaults-profile';\n\nexport interface LivePreviewClientConfig {\n /** Explicit trusted admin origins. */\n readonly allowedOrigins?: readonly string[];\n /** Payload origin; every update is then re-fetched through the REST API so relations arrive populated. 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 it; `defaults: 'v1'` falls back to `1`. */\n readonly mergeDepth?: number;\n /** Custom fetch for the `serverURL` merge request: attach auth headers or route through a proxy. */\n readonly mergeFetch?: typeof fetch;\n /** Verbose console output. Defaults to dev-mode detection. */\n readonly debug?: boolean;\n /** Debounce window for incoming updates. Default 50 ms. */\n readonly debounceMs?: number;\n /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */\n readonly heartbeatMs?: number;\n /** IntersectionObserver `rootMargin`. Default `200px`. */\n readonly intersectionRootMargin?: string;\n /** Update only bindings under a matching `data-payload-owner`; an unowned binding is then never updated. Default `false`. */\n readonly scopeBindingsByOwner?: boolean;\n /** Skip a binding whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */\n readonly skipUnchanged?: boolean;\n /** Scroll the preview to the field being edited when its value changes. Default `false`. */\n readonly revealEditedField?: boolean;\n /** Fields whose change re-applies other bindings regardless of their own value: `{ price: ['priceLabel'] }`. Used with `skipUnchanged`. */\n readonly dependencies?: Readonly<Record<string, readonly string[]>>;\n /** Strategy handlers beyond patching; `createFragmentStrategy()` from `payload-live-preview/fragment` builds one. */\n readonly strategies?: StrategyHandlers;\n /** Apply every update regardless of visibility. Default `false`. */\n readonly disableVisibilityGate?: boolean;\n /** Cache size above which off-screen updates wait for intersection. Default `50`. */\n readonly visibilityGateThreshold?: number;\n /** Mount an `aria-live` region for connections, applied updates and heartbeat disconnects. Default `true`. */\n readonly enableA11y?: boolean;\n /** Locale of the announcement strings. Defaults to the detected locale. */\n readonly a11yLocale?: string;\n /** Document root. Default `document`. */\n readonly root?: Document | Element;\n /** Renderer resolution ahead of the registry; return `undefined` to fall through. */\n readonly resolveRenderer?: (\n fieldType: RendererKey,\n target: CachedElement,\n ) => FieldRenderer | undefined;\n /** The project's rich-text renderer, shared with SSR. Its output is sanitized. */\n readonly renderRichText?: RichTextRenderer;\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. Default `false`. */\n readonly disableLocalhostMatching?: boolean;\n /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */\n readonly eventSourcePolicy?: EventSourcePolicy;\n /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */\n readonly sanitizerPolicy?: 'compat' | 'strict';\n /** `'v2'` (default) is the 2.0 table; `'v1'` restores every 1.x row at once. Explicit options win. */\n readonly defaults?: DefaultsProfile;\n /** Start the runtime in the constructor. Default `true`. */\n readonly autoStart?: boolean;\n /** Preview-token validator; every update must then carry a `previewToken` it approves. Stock Payload sends none. */\n readonly validateToken?: (\n token: string | undefined,\n origin: string,\n ) => boolean | Promise<boolean>;\n}\n\n/** The configuration with the `defaults` profile applied: explicit options win, `'v1'` changes nothing. */\nexport function withProfileDefaults(config: LivePreviewClientConfig): LivePreviewClientConfig {\n if (config.defaults === 'v1') return config;\n const rows = runtimeDefaultsFor(config.defaults);\n return {\n ...config,\n skipUnchanged: config.skipUnchanged ?? rows.skipUnchanged,\n disableReferrerDetection: config.disableReferrerDetection ?? rows.disableReferrerDetection,\n eventSourcePolicy: config.eventSourcePolicy ?? rows.eventSourcePolicy,\n sanitizerPolicy: config.sanitizerPolicy ?? rows.sanitizerPolicy,\n };\n}\n","/** Built-in field renderers, assembled as values so `sideEffects: false` bundlers keep them all. */\n\nimport type { FieldRenderer } from '@core/types';\nimport { createTextRenderer } from './text';\nimport { richTextRenderer } from './rich-text';\nimport { htmlRenderer } from './html';\nimport { urlRenderer } from './url';\nimport { emailRenderer } from './email';\nimport { imageRenderer } from './image';\nimport { uploadRenderer } from './upload';\nimport { relationshipRenderer } from './relationship';\nimport { selectRenderer } from './select';\nimport { checkboxRenderer } from './checkbox';\nimport { dateRenderer } from './date';\nimport { numberRenderer } from './number';\nimport { arrayRenderer } from './array';\nimport { createStructuralArrayRenderer } from './structural-array';\nimport {\n buildBuiltinRenderers as buildRegistry,\n registerBuiltinRenderer,\n __resetBuiltinRenderersForTests,\n} from './registry';\n\n/** One renderer map per client; the stateful text and structural renderers are created fresh each call. */\nexport function buildBuiltinRenderers(): Readonly<Record<string, FieldRenderer>> {\n // Built per call: a module-level table would pin every renderer into any\n // consumer importing an unrelated symbol from the root barrel.\n const stateless: readonly FieldRenderer[] = [\n richTextRenderer,\n htmlRenderer,\n urlRenderer,\n emailRenderer,\n imageRenderer,\n uploadRenderer,\n relationshipRenderer,\n selectRenderer,\n { ...selectRenderer, name: 'radio' },\n checkboxRenderer,\n dateRenderer,\n numberRenderer,\n arrayRenderer,\n { ...arrayRenderer, name: 'blocks' },\n ];\n\n return buildRegistry([\n createTextRenderer('text'),\n createTextRenderer('textarea'),\n ...stateless,\n createStructuralArrayRenderer(),\n ]);\n}\n\nexport { registerBuiltinRenderer, __resetBuiltinRenderersForTests };\nexport type { PayloadMedia, PayloadRelationship } from './types';\n","/**\n * Admin-side reporter for \"reveal the edited section\": it names the field the\n * editor's cursor is in so the preview scrolls there without a keystroke.\n */\n\n/** The preview window (usually `iframe.contentWindow`) messages are posted to. */\nexport interface FocusReportTarget {\n postMessage: (message: unknown, targetOrigin: string) => void;\n}\n\nexport interface PreviewFocusMessage {\n readonly type: 'payload-live-preview-focus';\n readonly field: string;\n}\n\n/** Post one focus report. `targetOrigin` must be the preview's exact origin, never `'*'`. */\nexport function reportPreviewFocus(\n target: FocusReportTarget,\n field: string,\n targetOrigin: string,\n): void {\n if (field.length === 0) return;\n const message: PreviewFocusMessage = { type: 'payload-live-preview-focus', field };\n target.postMessage(message, targetOrigin);\n}\n\n/** A reporter bound to a preview window and origin; `resolveTarget` runs per report, so a re-created iframe is addressed freshly. */\nexport function createPreviewFocusReporter(\n resolveTarget: () => FocusReportTarget | null | undefined,\n targetOrigin: string,\n): (field: string) => void {\n return (field: string): void => {\n const target = resolveTarget();\n if (target === null || target === undefined) return;\n reportPreviewFocus(target, field, targetOrigin);\n };\n}\n","/**\n * Every diagnostic code the runtime and tools emit, so a consumer can branch\n * on `e.code` instead of matching message text. A code is never reused for a\n * different meaning; a retired one stays reserved.\n *\n * Browser-side reporting sites write the literal (`code: 'LP0603'`) rather than\n * reading it from this record: the frozen table would then ship in the inline\n * runtime for the sake of six characters. Server-side tools may import it.\n */\n\n/**\n * Every diagnostic code the runtime can report, by name.\n *\n * ```ts\n * client.events.on('error', (e) => {\n * if (e.code === DIAGNOSTIC_CODES.TransformThrew) reportToSentry(e.error);\n * });\n * ```\n */\nexport const DIAGNOSTIC_CODES = Object.freeze({\n /** No trusted origin configured in production; nothing will be accepted. */\n NoTrustedOrigin: 'LP0101',\n /** Origin trust rests on `document.referrer`, so any framing site is trusted. */\n ReferrerOnlyTrust: 'LP0102',\n /** A plugin declares a runtime range this runtime does not satisfy; it was refused. */\n PluginIncompatible: 'LP0103',\n\n /** An update named a field with no binding anchor on the page. */\n OrphanField: 'LP0201',\n /** Owner scoping is on and the update names no document it could belong to. */\n UnattributableUpdate: 'LP0202',\n\n /** The visibility gate held offscreen writes back until they scroll into view. */\n VisibilityGateDeferred: 'LP0301',\n\n /** A value was refused because the attribute or the value itself is unsafe. */\n UnsafeAttributeWrite: 'LP0401',\n /** A text element has structured children, so replacing its text was skipped. */\n TextTargetHasChildren: 'LP0402',\n /** A structural container has no array template, so the update was skipped. */\n MissingArrayTemplate: 'LP0403',\n /** A structural item has no `id`; it pairs positionally, so an insert re-renders every row after it. */\n StructuralItemUnkeyed: 'LP0404',\n /** Two structural items share a key; later ones pair positionally. */\n StructuralDuplicateKey: 'LP0405',\n /** Every structural key changed while the length did not; the source generates keys per message. */\n StructuralUnstableKeys: 'LP0406',\n /** A binding asks for a delivery strategy this release does not have; it is left unchanged. */\n UnsupportedStrategy: 'LP0407',\n\n /** A message was rejected before it reached the update pipeline. */\n MessageRejected: 'LP0501',\n /** A preview token was rejected. */\n TokenRejected: 'LP0502',\n\n /** A consumer event handler threw. */\n HandlerThrew: 'LP0601',\n /** A consumer transform threw; the original value was kept. */\n TransformThrew: 'LP0602',\n /** A renderer threw while writing a value. */\n RendererThrew: 'LP0603',\n // LP0604 is reserved and unassigned; codes are never reused or renumbered.\n /** Runtime startup failed. */\n StartupFailed: 'LP0605',\n /** Sending the ready handshake failed. */\n ReadyFailed: 'LP0606',\n\n /** The audit found no runtime in a response that carried preview intent. */\n AuditRuntimeMissing: 'LP0701',\n /** The preview response declares no `frame-ancestors`. */\n AuditNoFrameAncestors: 'LP0702',\n /** `X-Frame-Options` forbids framing, which no CSP can undo. */\n AuditFrameOptionsBlocks: 'LP0703',\n /** Binding attributes are served to anonymous visitors. */\n AuditBindingsExposed: 'LP0704',\n /** More bindings than the default visibility gate will write eagerly. */\n AuditGateThresholdExceeded: 'LP0705',\n /** Owner markers exist, but some bindings are outside all of them. */\n AuditUnownedBindings: 'LP0706',\n /** The preview response carries no bindings at all. */\n AuditNoBindings: 'LP0707',\n /** The URL did not return an HTML page, so nothing else can be judged. */\n AuditNotAPage: 'LP0708',\n /** A fragment request failed (network, timeout, server error); the boundary was patched instead. */\n FragmentRequestFailed: 'LP0801',\n /** The fragment response had the wrong content type or shape; the boundary was patched instead. */\n FragmentResponseInvalid: 'LP0802',\n /** The fragment endpoint refused the preview (not authorized); the boundary was patched instead. */\n FragmentUnauthorized: 'LP0803',\n /** A fragment response arrived for a revision that was already superseded and was discarded. */\n FragmentSuperseded: 'LP0804',\n /** A route refresh was requested again for the same revision; the loop guard stopped it. */\n RouteRefreshLoop: 'LP0805',\n /** A boundary asks for the fragment strategy but no fragment handler is configured; it is patched. */\n FragmentStrategyUnavailable: 'LP0806',\n /** A readiness row is not yet at its 2.0 value; `pll doctor --v2` reports it. */\n V2ReadinessGap: 'LP0709',\n /** The preview runtime is served to anonymous visitors, not only inside the admin frame. */\n RuntimeOnPublicPage: 'LP0710',\n} as const);\n\n/** A diagnostic code, as it appears in log output and on the `error` event. */\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];\n"],"mappings":"AAIO,SAASA,sBACd,OAGF,WACE,GAAwB,oBAAbC,SAA0B,OACrC,MAAMC,EAAOD,SAASE,gBAAgBC,aAAa,QACnD,OAAgB,OAATF,GAAiC,IAAhBA,EAAKG,YAAe,EAAYH,CAC1D,CAPSI,IAST,WACE,GAAyB,oBAAdC,UAA2B,OACtC,MAAML,EAAOK,UAAUC,SACvB,MAAuB,iBAATN,GAAqBA,EAAKG,OAAS,EAAIH,OAAO,CAC9D,CAb2BO,IAHH,IAIxB,CCEA,IAAMC,EAAa,4BAoBbC,iBAAA,IAAqBC,QAa3B,SAASC,EAAkBC,GACL,OAAhBA,EAAMC,QACRC,aAAaF,EAAMC,OACnBD,EAAMC,MAAQ,MAEhBD,EAAMG,aAAaC,SACnBJ,EAAMG,YAAc,IACtB,CAEO,IAAME,EAAN,MACYC,OACAnB,SACTa,MAA8B,KAEtC,WAAAO,CAAYC,EAAiBC,GAC3B,MAAMC,EAAiBD,IAAuC,oBAAbtB,SAA2B,KAAOA,UAC7EwB,EAAiBD,GAAgBrB,gBAAgBC,aAAa,SAAW,GAC/EsB,KAAKN,OA5CT,SAAkBE,GAChB,MAAO,iBAAiBK,KAAKL,EAC/B,CA0CkBM,CACZ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A,OACA,QACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,aACA,OACA,MACA,MACA,OACA,MACA,IACA,OACA,MACA,UACA,UACA,QACA,SACA,SACA,MACA,SACA,aACA,MACA,UACA,SACA,QACA,QACA,MACA,MACA,KACA,OACA,OACA,OACA,IACA,QACA,QACA,QACA,QACA,KACA,KACA,KACA,UACA,WACA,QAIIgmB,kBAAA,IAAyChmB,IAAI,CACjD,QACA,SACA,WACA,SACA,SACA,UAIIimB,kBAAA,IAA6CjmB,IAAI,CACrD,SACA,QACA,SACA,SACA,QACA,OACA,OACA,OACA,OACA,QACA,SACA,SACA,WACA,MACA,OACA,WACA,QACA,WACA,WACA,aAGIkmB,kBAAA,IAAuClmB,IAAI,CAC/C,KACA,QACA,OACA,MACA,QACA,OACA,aAGImmB,GAAmB,QACnBC,GAAmB,QAGnBC,GAA6D,CACjEnkB,iBAAG,IAAIlC,IAAI,CAAC,OAAQ,SAAU,MAAO,WAAY,WAAY,SAC7DsmB,mBAAK,IAAItmB,IAAI,CAAC,MAAO,SAAU,QAAS,MAAO,QAAS,SAAU,UAAW,aAC7EumB,uBAAS,IAAIvmB,IAAI,IACjBgG,sBAAA,IAAYhG,IAAI,CAAC,MAAO,SAAU,QAAS,OAAQ,UACnDwmB,qBAAO,IAAIxmB,IAAI,CAAC,MAAO,WAAY,WAAY,OAAQ,QAAS,YAChEymB,qBAAA,IAAWzmB,IAAI,CACb,MACA,SACA,WACA,WACA,OACA,QACA,UACA,QACA,SACA,gBAEF0mB,oBAAM,IAAI1mB,IAAI,CAAC,aACf2mB,oBAAM,IAAI3mB,IAAI,CAAC,UACf4mB,iBAAG,IAAI5mB,IAAI,CAAC,SACZ6mB,0BAAY,IAAI7mB,IAAI,CAAC,SACrB8mB,qBAAO,IAAI9mB,IAAI,CAAC,YAChB+mB,kBAAA,IAAQ/mB,IAAI,CAAC,UAAW,UAAW,QAAS,UAAW,SACvDgnB,kBAAI,IAAIhnB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