@vcp-dev/site-edit-bridge 0.11.6 → 0.11.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/auto-bootstrap.js +7 -7
- package/dist/client.js +1 -1
- package/dist/cms-preview-identity-registry.d.ts +6 -1
- package/dist/cms-preview-probe.js +1 -1
- package/dist/index.js +10 -10
- package/package.json +3 -3
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function N(t){if(!V(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],i=new Map(t.dynamicDataSummaries??[]),s=new Map(t.pageCompositionActionScopes??[]),r=c=>{let o=e.get(c);if(o)return o;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,o)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[o],_=s.get(o),O=_?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:_.siblingEntryIndexes.map(M=>{let B=t.entries[M];if(!B)throw new Error(`Missing source sibling entry ${M}`);return r(B[0])})}:_;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...O?{pageCompositionActionScope:O}:{},operationSummary:z(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function z(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function V(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!H(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!l(e.pageComposition)||e.pageBlocks!==void 0&&!G(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(o=>typeof o=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((o,a)=>Array.isArray(o)&&o.length===2&&(o[0]===null||p(o[0])&&o[0]<a)&&p(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&p(o[0])&&o[0]<n.length&&p(o[1])&&o[1]<=15&&(o.length===2||p(o[2]))))return!1;let i=e.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==e.entries.length||!i.every(o=>o===null||p(o)&&o<n.length)))return!1;let s=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(o=>{if(!Array.isArray(o)||o.length!==2||!p(o[0])||o[0]>=e.entries.length||!l(o[1])||!["route-unit","source-siblings","unavailable"].includes(String(o[1].kind)))return!1;let a=o[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(o[0])}))&&(s===void 0||Array.isArray(s)&&s.every(o=>Array.isArray(o)&&o.length===2&&p(o[0])&&o[0]<e.entries.length&&l(o[1])))}function l(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return!l(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function G(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!l(n)||!b(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!J(n.rootRef)||!Q(n.source)||!Y(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>w(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!I(n.placementUnitKey)||!Z(n.capabilities)||n.unavailableReasons!==void 0&&!X(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let i=n.owner;for(let s of n.siblingBlockKeys){let r=e.get(s);if(!r)return!1;let c=r.owner;if(i.kind!==c.kind||i.key!==c.key)return!1}}return!0}function J(t){return!l(t)||!b(t,["key","instanceIndex","instanceCount"])||!I(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Q(t){return l(t)&&b(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ee(t.file)&&I(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function Y(t){return l(t)&&b(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&w(t.key,512)}function Z(t){return l(t)&&b(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function X(t){return l(t)&&Object.entries(t).every(([e,n])=>I(e)&&l(n)&&b(n,["code","reason"])&&I(n.code)&&I(n.reason))}function ee(t){let e=te(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let i=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function te(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),i=n.some(c=>K(c)),s=i?n[0]:n.pop(),r=i?n.slice(1):n;if(i&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(s)||!ne(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!K(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=s.replace(/-/gu,"+").replace(/_/gu,"/"),o=atob(c),a=Uint8Array.from(o,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===s}catch{return!1}}function K(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ne(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function w(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function I(t){return typeof t=="string"&&t.length>0}function b(t,e){let n=new Set(e);return Object.keys(t).every(i=>n.has(i))}var g=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(h(e)&&h(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?h(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&h(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!h(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=T(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&se(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&oe(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&v(t.request);case"undo":case"redo":return n&&(t.request===void 0||v(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function v(t){return h(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&T(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function se(t){if(t===void 0)return!0;if(!h(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function oe(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&T(t.composition)&&typeof t.kind=="string"&&h(t.target)&&(t.target.kind!=="route"||T(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function T(t){return h(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function h(t){return typeof t=="object"&&t!==null}function q(t){return h(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var re="vcp:designer:trace",ce="designer_trace",P="__VCP_DESIGNER_TRACE__";var ae=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function ue(t=globalThis){let e=t;try{if(e.localStorage?.getItem(re)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ce)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!ue(n))return;let i={type:t,timestamp:Date.now(),payload:de(e)},s=n,r=s[P]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[P]=r;let c=n.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",i)}function de(t){return R(t,0)}function R(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(i=>R(i,e+1));if(!t||typeof t!="object")return t;let n={};for(let[i,s]of Object.entries(t)){if(ae.test(i)){n[i]="[redacted]";continue}n[i]=R(s,e+1)}return n}var j=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===D&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let i;try{i=this.createSocket(this.options.url)}catch(a){let u=C(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:i,settled:!1,reject:n};this.connectAttempt=s,this.socket=i;let r=Math.max(0,this.options.connectTimeoutMs??pe);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,U(fe,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==i||this.connectAttempt!==s||(s.settled=!0,clearTimeout(s.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(i),e())},o=(a,u)=>{this.cleanupSocket(i,a,u)};i.onopen=()=>{if(!(this.socket!==i||this.connectAttempt!==s)){if(this.options.authKey){try{i.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(C(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=C(a,"WebSocket failed");o(u,"failed")},i.onmessage=a=>{if(this.socket===i){if(this.noteInboundMessage(i),this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(a.data,i,s,()=>{c()});return}this.handleMessage(a.data)}},i.onclose=a=>{if(this.socket!==i)return;let u=this.intentionalClose,d=new Error(be(a,{intentional:u}));o(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,i){let s=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:s,...i?{selectionRef:i}:{}})}getClassNameSource(e,n){let i=this.selector(n);return this.request("get-class-name-source",{key:e,composition:i})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let i=E(e),s={...e,composition:y(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(E(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,i){return this.request("undo",{composition:this.selector(e),...i?{request:i}:{}})}redo(e,n,i){return this.request("redo",{composition:this.selector(e),...i?{request:i}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let i=this.socket;if(!i||i.readyState!==D||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${i?.readyState??"none"})`));let s=`${e}-${this.sequence+=1}`,r=ke(s,e,n);return f("bridge.request",{id:s,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:$(n.request,"kind"),documentVersion:$(n.request,"documentVersion")}),new Promise((c,o)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(s);d&&(this.pending.delete(s),f("bridge.response",{id:s,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(s,{kind:e,timeout:u,resolve:d=>c(d),reject:o});try{i.send(g.stringifyMessage(r))}catch(d){let m=C(d,"WebSocket send failed");this.clearPendingRequest(s),o(m),this.cleanupSocket(i,m,"failed")}})}handleAuthHandshakeMessage(e,n,i,s){try{if(g.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=C(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let s of this.listeners)s(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let i=this.pending.get(n.payload.id);if(i){if(this.clearPendingRequest(n.payload.id),n.type==="error"){f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!1});let s=new Error(n.payload.message);n.payload.code&&(s.code=n.payload.code),i.reject(s);return}f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!0,resultVersion:Ce(n.payload.result)}),i.resolve(i.kind==="get-document"?{...n.payload.result,data:L(n.payload.result.data,n.payload.result.composition)}:i.kind==="initialize-session"?Se(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,i]of[...this.pending])this.clearPendingRequest(n),i.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Ie[e]??ye}cleanupSocket(e,n,i){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let s=this.connectAttempt;this.connectAttempt=null,clearTimeout(s.deadline),s.settled||(s.settled=!0,s.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(i,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===he||e.readyState===D)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?le:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let i=this.options.visibility===void 0?ge():this.options.visibility,s=()=>i?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!s())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,C(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,U(me,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},o=()=>{s()?c():r()};i?.addEventListener("visibilitychange",o),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>i?.removeEventListener("visibilitychange",o)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let i={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(i);for(let s of this.connectionStatusListeners)s(i)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},he=0,D=1,pe=1e4,le={intervalMs:2e4,timeoutMs:1e4},fe="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",me="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ge(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function U(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var ye=15e3,Ie={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function C(t,e){return t instanceof Error?t:new Error(e)}function be(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function $(t,e){if(!t||typeof t!="object")return null;let i=t[e];return typeof i=="string"||typeof i=="number"?i:null}function Ce(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Oe(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new A({composition:e,initialDocument:t.initialDocument,client:t.client})}var A=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let i=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=i.data.document,this.observedDocumentVersion=i.data.document.version,this.activeCompositionContext={...i.composition},this.rememberServerConfirmedComposition(i.composition),this.sessionInitialized=!0,this.clearObjectCaches(),i}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),i=k(n),s=this.styleContextCache.get(i);if(s?.generation===this.styleGeneration)return{ok:!0,data:s.value};let r=this.styleContextInFlight.get(i);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,o=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(i,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(i)?.request===o&&this.styleContextInFlight.delete(i)});return this.styleContextInFlight.set(i,{generation:c,request:o}),o}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,i){let s=this.requireBoundComposition(n),r=this.objectCacheKey(e,s,i),c=this.editContextCache.get(r);if(c)return{ok:!0,data:c};let o=this.editContextInFlight.get(r);if(o)return o;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,s,...i?[i]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let i=this.requireBoundComposition(n),s=this.objectCacheKey(e,i),r=this.classNameSourceCache.get(s);if(r)return r;let c=this.classNameSourceInFlight.get(s);if(c)return c;let o=this.objectGeneration,a=this.params.client.getClassNameSource(e,i).then(u=>(this.objectGeneration===o&&this.classNameSourceCache.set(s,u),u)).finally(()=>{this.classNameSourceInFlight.get(s)===a&&this.classNameSourceInFlight.delete(s)});return this.classNameSourceInFlight.set(s,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let i=E(e);i&&this.composition.templateId!==void 0&&this.requireBoundComposition(i);let s={...e,composition:i??this.composition};return this.params.client.execute(s)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.undo(s,void 0,i):this.params.client.undo(s)}async redo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.redo(s,void 0,i):this.params.client.redo(s)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let i=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),i&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let i=k(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await s.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let o=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&S(c.data.composition)===S(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),o||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:i,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,i){return`${k(n)}\0${e}\0${xe(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(k(e)===k(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&S(n)===S(W(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??W(this.composition);return S(e)===S(n)}};function F(t){return t.version===0&&t.entries.length===0}function Se(t){let e=t;return{...e,data:{...e.data,document:L(e.data.document,e.composition)}}}function L(t,e){let n=t,i=N(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...i,composition:e}:i}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function k(t){return JSON.stringify([t.routeId,t.templateId??null])}function xe(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function S(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function W(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function E(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function ke(t,e,n){let i=y(e==="execute"?E(n.request):n.composition),s={id:t,kind:e,composition:i};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...s,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...s,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...s,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...s,path:String(n.path)}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...s,request:{...n.request,composition:E(n.request)??i}}}}}export{fe as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,me as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,j as SiteEditWebSocketClient,Oe as createSiteEditBridge};
|
|
1
|
+
function N(t){if(!V(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],i=new Map(t.dynamicDataSummaries??[]),s=new Map(t.pageCompositionActionScopes??[]),r=c=>{let o=e.get(c);if(o)return o;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,o)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[o],_=s.get(o),O=_?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:_.siblingEntryIndexes.map(M=>{let B=t.entries[M];if(!B)throw new Error(`Missing source sibling entry ${M}`);return r(B[0])})}:_;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...O?{pageCompositionActionScope:O}:{},operationSummary:z(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function z(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function V(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!H(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!l(e.pageComposition)||e.pageBlocks!==void 0&&!G(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(o=>typeof o=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((o,a)=>Array.isArray(o)&&o.length===2&&(o[0]===null||p(o[0])&&o[0]<a)&&p(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&p(o[0])&&o[0]<n.length&&p(o[1])&&o[1]<=15&&(o.length===2||p(o[2]))))return!1;let i=e.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==e.entries.length||!i.every(o=>o===null||p(o)&&o<n.length)))return!1;let s=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(o=>{if(!Array.isArray(o)||o.length!==2||!p(o[0])||o[0]>=e.entries.length||!l(o[1])||!["route-unit","source-siblings","unavailable"].includes(String(o[1].kind)))return!1;let a=o[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(o[0])}))&&(s===void 0||Array.isArray(s)&&s.every(o=>Array.isArray(o)&&o.length===2&&p(o[0])&&o[0]<e.entries.length&&l(o[1])))}function l(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return!l(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function G(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!l(n)||!b(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!J(n.rootRef)||!Q(n.source)||!Y(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>w(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!I(n.placementUnitKey)||!Z(n.capabilities)||n.unavailableReasons!==void 0&&!X(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let i=n.owner;for(let s of n.siblingBlockKeys){let r=e.get(s);if(!r)return!1;let c=r.owner;if(i.kind!==c.kind||i.key!==c.key)return!1}}return!0}function J(t){return!l(t)||!b(t,["key","instanceIndex","instanceCount"])||!I(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Q(t){return l(t)&&b(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ee(t.file)&&I(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function Y(t){return l(t)&&b(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&w(t.key,512)}function Z(t){return l(t)&&b(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function X(t){return l(t)&&Object.entries(t).every(([e,n])=>I(e)&&l(n)&&b(n,["code","reason"])&&I(n.code)&&I(n.reason))}function ee(t){let e=te(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let i=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function te(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),i=n.some(c=>K(c)),s=i?n[0]:n.pop(),r=i?n.slice(1):n;if(i&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(s)||!ne(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!K(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=s.replace(/-/gu,"+").replace(/_/gu,"/"),o=atob(c),a=Uint8Array.from(o,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===s}catch{return!1}}function K(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ne(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function w(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function I(t){return typeof t=="string"&&t.length>0}function b(t,e){let n=new Set(e);return Object.keys(t).every(i=>n.has(i))}var g=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(h(e)&&h(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?h(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&h(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!h(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=T(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&se(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&oe(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&v(t.request);case"undo":case"redo":return n&&(t.request===void 0||v(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function v(t){return h(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&T(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function se(t){if(t===void 0)return!0;if(!h(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function oe(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&T(t.composition)&&typeof t.kind=="string"&&h(t.target)&&(t.target.kind!=="route"||T(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function T(t){return h(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function h(t){return typeof t=="object"&&t!==null}function q(t){return h(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var re="vcp:designer:trace",ce="designer_trace",P="__VCP_DESIGNER_TRACE__";var ae=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function ue(t=globalThis){let e=t;try{if(e.localStorage?.getItem(re)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ce)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!ue(n))return;let i={type:t,timestamp:Date.now(),payload:de(e)},s=n,r=s[P]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[P]=r;let c=n.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",i)}function de(t){return R(t,0)}function R(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(i=>R(i,e+1));if(!t||typeof t!="object")return t;let n={};for(let[i,s]of Object.entries(t)){if(ae.test(i)){n[i]="[redacted]";continue}n[i]=R(s,e+1)}return n}var j=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===D&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let i;try{i=this.createSocket(this.options.url)}catch(a){let u=C(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:i,settled:!1,reject:n};this.connectAttempt=s,this.socket=i;let r=Math.max(0,this.options.connectTimeoutMs??pe);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,U(fe,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==i||this.connectAttempt!==s||(s.settled=!0,clearTimeout(s.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(i),e())},o=(a,u)=>{this.cleanupSocket(i,a,u)};i.onopen=()=>{if(!(this.socket!==i||this.connectAttempt!==s)){if(this.options.authKey){try{i.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(C(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=C(a,"WebSocket failed");o(u,"failed")},i.onmessage=a=>{if(this.socket===i){if(this.noteInboundMessage(i),this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(a.data,i,s,()=>{c()});return}this.handleMessage(a.data)}},i.onclose=a=>{if(this.socket!==i)return;let u=this.intentionalClose,d=new Error(be(a,{intentional:u}));o(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,i){let s=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:s,...i?{selectionRef:i}:{}})}getClassNameSource(e,n){let i=this.selector(n);return this.request("get-class-name-source",{key:e,composition:i})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let i=E(e),s={...e,composition:y(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(E(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,i){return this.request("undo",{composition:this.selector(e),...i?{request:i}:{}})}redo(e,n,i){return this.request("redo",{composition:this.selector(e),...i?{request:i}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let i=this.socket;if(!i||i.readyState!==D||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${i?.readyState??"none"})`));let s=`${e}-${this.sequence+=1}`,r=ke(s,e,n);return f("bridge.request",{id:s,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:$(n.request,"kind"),documentVersion:$(n.request,"documentVersion")}),new Promise((c,o)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(s);d&&(this.pending.delete(s),f("bridge.response",{id:s,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(s,{kind:e,timeout:u,resolve:d=>c(d),reject:o});try{i.send(g.stringifyMessage(r))}catch(d){let m=C(d,"WebSocket send failed");this.clearPendingRequest(s),o(m),this.cleanupSocket(i,m,"failed")}})}handleAuthHandshakeMessage(e,n,i,s){try{if(g.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=C(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let s of this.listeners)s(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let i=this.pending.get(n.payload.id);if(i){if(this.clearPendingRequest(n.payload.id),n.type==="error"){f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!1});let s=new Error(n.payload.message);n.payload.code&&(s.code=n.payload.code),i.reject(s);return}f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!0,resultVersion:Ce(n.payload.result)}),i.resolve(i.kind==="get-document"?{...n.payload.result,data:L(n.payload.result.data,n.payload.result.composition)}:i.kind==="initialize-session"?Se(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,i]of[...this.pending])this.clearPendingRequest(n),i.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Ie[e]??ye}cleanupSocket(e,n,i){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let s=this.connectAttempt;this.connectAttempt=null,clearTimeout(s.deadline),s.settled||(s.settled=!0,s.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(i,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===he||e.readyState===D)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?le:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let i=this.options.visibility===void 0?ge():this.options.visibility,s=()=>i?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!s())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,C(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,U(me,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},o=()=>{s()?c():r()};i?.addEventListener("visibilitychange",o),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>i?.removeEventListener("visibilitychange",o)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let i={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(i);for(let s of this.connectionStatusListeners)s(i)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},he=0,D=1,pe=1e4,le={intervalMs:2e4,timeoutMs:1e4},fe="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",me="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ge(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function U(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var ye=15e3,Ie={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function C(t,e){return t instanceof Error?t:new Error(e)}function be(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function $(t,e){if(!t||typeof t!="object")return null;let i=t[e];return typeof i=="string"||typeof i=="number"?i:null}function Ce(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Oe(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new A({composition:e,initialDocument:t.initialDocument,client:t.client})}var A=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let i=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=i.data.document,this.observedDocumentVersion=i.data.document.version,this.activeCompositionContext={...i.composition},this.rememberServerConfirmedComposition(i.composition),this.sessionInitialized=!0,this.clearObjectCaches(),i}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),i=k(n),s=this.styleContextCache.get(i);if(s?.generation===this.styleGeneration)return{ok:!0,data:s.value};let r=this.styleContextInFlight.get(i);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,o=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(i,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(i)?.request===o&&this.styleContextInFlight.delete(i)});return this.styleContextInFlight.set(i,{generation:c,request:o}),o}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,i){let s=this.requireBoundComposition(n),r=this.objectCacheKey(e,s,i),c=this.editContextCache.get(r);if(c)return{ok:!0,composition:c.composition,data:c};let o=this.editContextInFlight.get(r);if(o)return o;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,s,...i?[i]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let i=this.requireBoundComposition(n),s=this.objectCacheKey(e,i),r=this.classNameSourceCache.get(s);if(r)return r;let c=this.classNameSourceInFlight.get(s);if(c)return c;let o=this.objectGeneration,a=this.params.client.getClassNameSource(e,i).then(u=>(this.objectGeneration===o&&this.classNameSourceCache.set(s,u),u)).finally(()=>{this.classNameSourceInFlight.get(s)===a&&this.classNameSourceInFlight.delete(s)});return this.classNameSourceInFlight.set(s,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let i=E(e);i&&this.composition.templateId!==void 0&&this.requireBoundComposition(i);let s={...e,composition:i??this.composition};return this.params.client.execute(s)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.undo(s,void 0,i):this.params.client.undo(s)}async redo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.redo(s,void 0,i):this.params.client.redo(s)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let i=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),i&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let i=k(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await s.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let o=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&S(c.data.composition)===S(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),o||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:i,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,i){return`${k(n)}\0${e}\0${xe(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(k(e)===k(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&S(n)===S(W(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??W(this.composition);return S(e)===S(n)}};function F(t){return t.version===0&&t.entries.length===0}function Se(t){let e=t;return{...e,data:{...e.data,document:L(e.data.document,e.composition)}}}function L(t,e){let n=t,i=N(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...i,composition:e}:i}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function k(t){return JSON.stringify([t.routeId,t.templateId??null])}function xe(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function S(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function W(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function E(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function ke(t,e,n){let i=y(e==="execute"?E(n.request):n.composition),s={id:t,kind:e,composition:i};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...s,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...s,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...s,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...s,path:String(n.path)}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...s,request:{...n.request,composition:E(n.request)??i}}}}}export{fe as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,me as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,j as SiteEditWebSocketClient,Oe as createSiteEditBridge};
|
|
@@ -12,10 +12,15 @@ export type CmsPreviewIdentityCandidate = Readonly<{
|
|
|
12
12
|
resourceId?: string;
|
|
13
13
|
currentUrl?: string;
|
|
14
14
|
}>;
|
|
15
|
-
export declare function createCmsPreviewIdentityRegistry(
|
|
15
|
+
export declare function createCmsPreviewIdentityRegistry(options?: {
|
|
16
|
+
/** Equality-only render epoch guard. Never parsed to derive CMS ownership. */
|
|
17
|
+
getRenderScope?: () => string;
|
|
18
|
+
}): {
|
|
16
19
|
register(element: Element, candidate: CmsPreviewIdentityCandidate): () => void;
|
|
17
20
|
resolve(element: Element): CmsPreviewIdentityCandidate | null;
|
|
18
21
|
invalidate(): void;
|
|
22
|
+
/** React may commit new refs before the Engine acknowledges the new route. */
|
|
23
|
+
advanceRoute(): void;
|
|
19
24
|
claimFrame(): () => void;
|
|
20
25
|
};
|
|
21
26
|
export type CmsPreviewIdentityRegistry = ReturnType<typeof createCmsPreviewIdentityRegistry>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{cloneElement as
|
|
1
|
+
"use client";import{cloneElement as m,isValidElement as I,useCallback as w}from"react";function g(e={}){let r=new WeakMap,i=null,n=e.getRenderScope?.(),f=n,u=()=>{let t=e.getRenderScope?.();return t!==n&&(r=new WeakMap,n=t),t};return{register(t,o){if(!y(o))return()=>{};u();let c=Symbol(),s=r,l=s.get(t)??new Map;return l.set(c,Object.freeze({appSlug:o.appSlug,operation:o.operation,...o.recordId===void 0?{}:{recordId:o.recordId},...o.recordUrl===void 0?{}:{recordUrl:o.recordUrl},...o.fieldKey===void 0?{}:{fieldKey:o.fieldKey},...o.mediaIndex===void 0?{}:{mediaIndex:o.mediaIndex},...o.resourceId===void 0?{}:{resourceId:o.resourceId},...o.currentUrl===void 0?{}:{currentUrl:o.currentUrl}})),s.set(t,l),()=>{l.delete(c),l.size===0&&s.delete(t)}},resolve(t){if(u(),!t.isConnected)return null;let o=r.get(t);return!o||o.size!==1?null:o.values().next().value??null},invalidate(){r=new WeakMap,f=u()},advanceRoute(){let t=u();(t===void 0||t===f)&&(r=new WeakMap),f=t},claimFrame(){i&&(r=new WeakMap),f=u();let t=Symbol();return i=t,()=>{i===t&&(i=null,r=new WeakMap)}}}}var d=Symbol.for("vcp.preview.cms.identity.registry.v1");function p(e){let r=e,i=r[d];if(i)return i;let n=g({getRenderScope:()=>e.location.href});return Object.defineProperty(r,d,{configurable:!0,value:n}),n}function y(e){let r=n=>typeof n=="string"&&n.trim().length>0,i=n=>typeof n=="string"&&/^[1-9]\d*$/.test(n)&&Number.isSafeInteger(Number(n));return r(e.appSlug)&&(e.operation==="list"||e.operation==="detail")&&(e.recordId===void 0||i(e.recordId))&&(e.recordUrl===void 0||r(e.recordUrl))&&(e.fieldKey===void 0||r(e.fieldKey))&&(e.resourceId===void 0||i(e.resourceId))&&(e.currentUrl===void 0||r(e.currentUrl))&&(e.mediaIndex===void 0||e.fieldKey!==void 0&&Number.isSafeInteger(e.mediaIndex)&&e.mediaIndex>=0)}function x(e){let r=I(e.children)?e.children.props.ref:void 0,i=w(n=>{if(!n)return;let f=typeof r=="function"?r(n):void 0;r&&typeof r!="function"&&(r.current=n);let u=n.ownerDocument?.defaultView,t=e.candidate&&u?p(u).register(n,e.candidate):()=>{};return()=>{t(),typeof f=="function"?f():typeof r=="function"?r(null):r&&(r.current=null)}},[r,e.candidate]);return m(e.children,{ref:i})}export{x as CmsPreviewProbe};
|