@vcp-dev/site-edit-bridge 0.6.9 → 0.6.11

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- function mt(e){let t=new Map,n=[],r=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(i.map((d,h)=>[d,h])),c=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},a=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),u=d=>{let h=t.get(d);if(typeof h=="number")return h;let m=n.length;return n.push(d),t.set(d,m),m},l=d=>{let h=null;for(let m of _r(d)){let P=`${h??"root"}\0${m}`,x=r.get(P);if(typeof x=="number"){h=x;continue}let T=o.length;o.push([h,u(m)]),r.set(P,T),h=T}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:c,tokens:n,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?s.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[l(d.key),Rr(d.operationSummary),...h>=0?[h]:[]]}),...a.length>0?{dynamicDataSummaries:a}:{}}}function gt(e){if(!Cr(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),o=i=>{let s=t.get(i);if(s)return s;let c=e.nodes[i];if(!c)throw new Error(`Missing compact document node ${i}`);let[a,u]=c,l=e.tokens[u];if(typeof l!="string")throw new Error(`Missing compact document token ${u}`);let d=`${a===null?"":o(a)}${l}`;return t.set(i,d),d};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((i,s)=>{let[c,a,u]=i,l=u===void 0?void 0:n[u];if(u!==void 0&&!l)throw new Error(`Missing page composition unit ${u}`);return{key:o(c),...l?{pageCompositionUnitKey:l}:{},operationSummary:xr(a),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function Rr(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function xr(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function Cr(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!en(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(o=>typeof o=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((o,i)=>Array.isArray(o)&&o.length===2&&(o[0]===null||Re(o[0])&&o[0]<i)&&Re(o[1])&&o[1]<t.tokens.length)||!t.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&Re(o[0])&&o[0]<n.length&&Re(o[1])&&o[1]<=15&&(o.length===2||Re(o[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(o=>Array.isArray(o)&&o.length===2&&Re(o[0])&&o[0]<t.entries.length&&en(o[1]))}function en(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function _r(e){if(!e)return[];let t=[],n=0,r=tn(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=tn(e,n+(e.startsWith("::",n)?2:1)),r<0){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r}return t}function tn(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var oe=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!ue(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?ue(t.payload)&&typeof t.payload.id=="string":t.type==="event"?ue(t.payload)&&ue(t.payload.event):t.type==="auth"?ue(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?ue(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!ue(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||yt(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"get-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Tr(t.request)&&(t.request.mutationContext===void 0||yt(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||yt(t.mutationContext)}}},Ke=class{constructor(t){this.options=t,this.messageQueue=new St,this.eventDispatcher=new bt(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"initialize-session":{let i=await this.options.engine.initializeSession({routeId:r.routeId,...r.mutationContext?{mutationContext:r.mutationContext}:{}});this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:{document:mt(i.data.document),historyStatus:i.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:mt((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getStyleContext(r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":{await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.execute(r.request));return}case"undo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=oe.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:rn(n),code:nn(n)}})}}async handleRawMessage(t){try{await this.handleMessage(oe.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Ar(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(oe.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:rn(o),code:nn(o)}}),this.eventDispatcher.flush()}}},bt=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},St=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function ue(e){return typeof e=="object"&&e!==null}function Tr(e){return ue(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&ue(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&ue(e.params)}function yt(e){return Pr(e)}function nn(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function rn(e){if(e instanceof Error)return e.message;if(!e||typeof e!="object")return"Unknown websocket operation failure";let t=e.message;return typeof t=="string"&&t.length>0?t:"Unknown websocket operation failure"}function Pr(e){return ue(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}function Ar(e){try{return oe.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var kr="vcp:designer:trace",Nr="designer_trace",on="__VCP_DESIGNER_TRACE__";var Br=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Dr(e=globalThis){let t=e;try{if(t.localStorage?.getItem(kr)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Nr)==="1"}catch{return!1}}function me(e,t={},n=globalThis){if(!Dr(n))return;let r={type:e,timestamp:Date.now(),payload:Fr(t)},o=n,i=o[on]??[];i.push(r),i.length>1e3&&i.splice(0,i.length-1e3),o[on]=i;let s=n.console?.debug;r.payload.diagnosticOnly!==!0&&typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Fr(e){return Et(e,0)}function Et(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Et(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Br.test(r)){n[r]="[redacted]";continue}n[r]=Et(o,t+1)}return n}var Ue=class{constructor(t){this.options=t,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.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===vt&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((t,n)=>{let r;try{r=this.createSocket(this.options.url)}catch(c){let a=Ae(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",a.message),n(a);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let i=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(c,a)=>{this.cleanupSocket(r,c,a)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(oe.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){s(Ae(c,"WebSocket auth failed"),"failed")}return}i()}},r.onerror=c=>{if(this.socket!==r)return;let a=Ae(c,"WebSocket failed");s(a,"failed")},r.onmessage=c=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(c.data,r,o,()=>{i()});return}this.handleMessage(c.data)}},r.onclose=c=>{if(this.socket!==r)return;let a=this.intentionalClose,u=new Error(Vr(c,{intentional:a}));s(u,a?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let t=this.socket;if(!t){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(t,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(t){return this.connectionStatusListeners.add(t),t({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(t)}}getDocument(t){return this.request("get-document",{routeId:t})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}getSourceTree(){return this.request("get-source-tree",{})}getSourceFile(t){return this.request("get-source-file",t)}resolveSourceLocation(t){return this.request("resolve-source-location",t)}execute(t,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r||r.readyState!==vt||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let o=`${t}-${this.sequence+=1}`,i=Hr(o,t,n);return me("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:sn(n.request,"kind"),documentVersion:sn(n.request,"documentVersion")}),new Promise((s,c)=>{let a=this.resolveRequestTimeoutMs(t),u=a>0?setTimeout(()=>{let l=this.pending.get(o);l&&(this.pending.delete(o),me("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),l.reject(new Error(`Bridge request timed out after ${a}ms: ${t}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:l=>s(l),reject:c});try{r.send(oe.stringifyMessage(i))}catch(l){let d=Ae(l,"WebSocket send failed");this.clearPendingRequest(o),c(d),this.cleanupSocket(r,d,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(oe.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(i){let s=Ae(i,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=oe.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.clearPendingRequest(n.payload.id),n.type==="error"){me("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}me("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:zr(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:gt(n.payload.result.data)}:r.kind==="initialize-session"?Wr(n.payload.result):n.payload.result)}}rejectAll(t){for(let[n,r]of[...this.pending])this.clearPendingRequest(n),r.reject(t)}clearPendingRequest(t){let n=this.pending.get(t);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(t))}resolveRequestTimeoutMs(t){let n=this.options.requestTimeoutMsByKind?.[t];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Mr[t]??Or}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let o=this.connectAttempt;this.connectAttempt=null,o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(r,n.message),t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{(t.readyState===wr||t.readyState===vt)&&t.close()}catch{}}setConnectionState(t,n){if(this.connectionState===t&&!n)return;this.connectionState=t;let r={state:t,...n?{message:n}:{}};this.options.onConnectionStatus?.(r);for(let o of this.connectionStatusListeners)o(r)}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}},wr=0,vt=1,Or=15e3,Mr={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function Ae(e,t){return e instanceof Error?e:new Error(t)}function Vr(e,t){return t.intentional?"WebSocket disconnected":e?.code===1008?e.reason?`Bridge session authentication failed: ${e.reason}`:"Bridge session authentication failed":e?.reason?`WebSocket closed: ${e.reason}`:typeof e?.code=="number"&&e.code!==1005?`WebSocket closed with code ${e.code}`:"WebSocket closed"}function sn(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function zr(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function cn(e){return new It(e)}var It=class{constructor(t){this.params=t,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=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!an(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=an(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let o=this.styleGeneration,i=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===o&&(this.styleContextCache={generation:o,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===i&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:o,request:i},i}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),o=this.editContextCache.get(r);if(o)return{ok:!0,data:o};let i=this.editContextInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.editContextCache.set(r,a.data),a)).finally(()=>{this.editContextInFlight.get(r)===c&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,c),c}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),o=this.classNameSourceCache.get(r);if(o)return o;let i=this.classNameSourceInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getClassNameSource(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,a),a)).finally(()=>{this.classNameSourceInFlight.get(r)===c&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,c),c}async getSourceTree(){return this.params.client.getSourceTree()}async getSourceFile(t){return this.params.client.getSourceFile(t)}async resolveSourceLocation(t){return this.params.client.resolveSourceLocation({...t,routeId:t.routeId??this.params.routeId})}async execute(t,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId&&this.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,o.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function an(e){return e.version===0&&e.entries.length===0}function Wr(e){let t=e;return{...t,data:{...t.data,document:gt(t.data.document)}}}function Hr(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-source-tree":return{type:"request",payload:{id:e,kind:t}};case"get-source-file":return{type:"request",payload:{id:e,kind:t,path:String(n.path)}};case"resolve-source-location":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t,mutationContext:n.mutationContext}}}}var un="vcp-window-message",Ia=1;function $r(e){return{source:un,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function qr(e){try{return R(e)?G(e,"source",un)&&G(e,"version",1)&&w(e,"namespace")&&w(e,"channel")&&se(e,"body")&&(!Ee(e,"sessionKey")||w(e,"sessionKey")):!1}catch{return!1}}var ln="site-edit",dn="frame-runtime",xt=1,ke=1,Ne=1,pn=24;function De(e,t={}){return $r({namespace:ln,channel:dn,sessionKey:t.sessionKey,body:e})}function hn(e){try{return!qr(e)||e.namespace!==ln||e.channel!==dn?!1:fo(e.body)}catch{return!1}}var Ee=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function se(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function p(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function G(e,t,n){return se(e,t)&&p(e,t)===n}function w(e,t){return se(e,t)&&typeof p(e,t)=="string"}function Ge(e,t){return se(e,t)&&typeof p(e,t)=="boolean"}function M(e,t){let n=p(e,t);return se(e,t)&&typeof n=="number"&&Number.isFinite(n)}function Kr(e,t){let n=p(e,t);return se(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>0}function Se(e,t){return!Ee(e,t)||p(e,t)===void 0||w(e,t)}function be(e,t){return!Ee(e,t)||p(e,t)===void 0||M(e,t)}function je(e,t){let n=p(e,t);return!Ee(e,t)||n===void 0||se(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function q(e,t){return!Ee(e,t)||p(e,t)===void 0}function R(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ur(e){return R(e)&&Reflect.ownKeys(e).length===0}function fn(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function le(e){return R(e)&&w(e,"key")&&je(e,"instanceIndex")&&je(e,"instanceCount")&&je(e,"textSegmentIndex")}function jr(e){return R(e)&&w(e,"blockId")&&le(p(e,"ref"))&&Be(p(e,"rect"))&&Ge(e,"targetIsSectionRoot")}function Gr(e){if(!R(e))return!1;let t=p(e,"placement"),n=p(e,"boundary");return w(e,"anchorBlockId")&&le(p(e,"anchorRef"))&&(t==="before"||t==="after")&&R(n)&&M(n,"top")&&M(n,"left")&&M(n,"width")}function Be(e){return R(e)&&["top","left","width","height"].every(t=>M(e,t))}function mn(e){if(!R(e))return!1;let t=p(e,"rect"),n=p(e,"layout"),r=R(n)?p(n,"containingBlock"):null,o=p(e,"scrollContext"),i=R(r)&&(G(r,"kind","viewport")&&Reflect.ownKeys(r).length===1||G(r,"kind","document")&&Reflect.ownKeys(r).length===1||G(r,"kind","element")&&w(r,"runtimeNodeId"));return G(e,"version",xt)&&w(e,"runtimeNodeId")&&R(t)&&Be(p(t,"viewport"))&&Be(p(t,"document"))&&R(n)&&w(n,"position")&&w(n,"transform")&&i&&R(o)&&["scrollX","scrollY","viewportWidth","viewportHeight"].every(s=>M(o,s))&&se(o,"scrollContainers")&&Yr(p(o,"scrollContainers"))}function Yr(e){return Array.isArray(e)&&e.every(t=>R(t)&&w(t,"runtimeNodeId")&&M(t,"scrollLeft")&&M(t,"scrollTop"))}function Rt(e){return R(e)&&(q(e,"layoutSnapshot")||mn(p(e,"layoutSnapshot")))}function Xr(e){return R(e)&&le(p(e,"ref"))&&se(e,"layoutSnapshot")&&mn(p(e,"layoutSnapshot"))&&(q(e,"childBoxes")||Qr(p(e,"childBoxes")))&&(q(e,"childRects")||Lr(p(e,"childRects")))&&(q(e,"layout")||Jr(p(e,"layout")))&&(q(e,"spacing")||Zr(p(e,"spacing")))}function Jr(e){if(!R(e))return!1;let t=p(e,"indicatorOrientation");return w(e,"display")&&(t==="horizontal"||t==="vertical")&&Se(e,"flexDirection")&&Se(e,"gridAutoFlow")}function Lr(e){return Array.isArray(e)&&e.every(t=>Be(t))}function Qr(e){return Array.isArray(e)&&e.every(t=>R(t)&&Be(p(t,"rect"))&&gn(p(t,"margin")))}function gn(e){return R(e)&&["marginTop","marginRight","marginBottom","marginLeft"].every(t=>M(e,t))}function Zr(e){return gn(e)&&["paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","columnGap","rowGap"].every(t=>M(e,t))}function eo(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||!Xr(n.value))return!1}return!0}function to(e){return R(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&se(e,t)&&(typeof p(e,t)=="string"||p(e,t)===null))}function yn(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function no(e){return R(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&se(e,t)&&yn(p(e,t)))}function ro(e){if(!R(e))return!1;let t=p(e,"priority");return w(e,"property")&&se(e,"value")&&yn(p(e,"value"))&&(!Ee(e,"priority")||t===void 0||t==="important")}function oo(e){return R(e)?(q(e,"attributes")||to(p(e,"attributes")))&&Se(e,"className")&&(q(e,"style")||no(p(e,"style")))&&(q(e,"styleDeclarations")||Array.isArray(p(e,"styleDeclarations"))&&p(e,"styleDeclarations").every(ro)):!1}function io(e){return R(e)&&M(e,"x")&&M(e,"y")&&(q(e,"detailLevel")||G(e,"detailLevel","summary")||G(e,"detailLevel","full"))}function so(e){return R(e)&&le(p(e,"ref"))}function ao(e){if(!R(e)||!R(p(e,"variables")))return!1;let t=p(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&w(t,n))?q(e,"stylesheets")||fn(p(e,"stylesheets")):!1}function co(e){if(!G(e,"type","request")||!w(e,"id")||!w(e,"kind")||!se(e,"payload"))return!1;let t=p(e,"kind"),n=p(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return io(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return Ur(n);case"bridge-get-source-file":return R(n)&&w(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return R(n)&&w(n,"key")&&Se(n,"routeId");case"scroll-to":return R(n)&&M(n,"x")&&M(n,"y");case"scroll-by":return R(n)&&M(n,"deltaX")&&M(n,"deltaY");case"set-interaction-mode":return R(n)&&Ge(n,"enabled");case"set-selection-visual":return R(n)&&G(n,"version",ke)&&le(p(n,"ref"))&&G(n,"visible",!0);case"clear-selection-visual":return R(n)&&G(n,"version",ke);case"set-resize-visual":return R(n)&&G(n,"version",Ne)&&le(p(n,"ref"))&&G(n,"visible",!0);case"clear-resize-visual":return R(n)&&G(n,"version",Ne);case"set-theme-override":return ao(n);case"get-theme-variables":return R(n)&&fn(p(n,"names"));case"compute-drop-target-at-point":return R(n)&&M(n,"x")&&M(n,"y")&&(G(n,"dragKind","insert")||G(n,"dragKind","move"))&&(q(n,"movingRef")||le(p(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return R(n)&&(q(n,"ref")||le(p(n,"ref")));case"apply-node-patch":return R(n)&&le(p(n,"ref"))&&oo(p(n,"patch"))&&(q(n,"preview")||R(p(n,"preview"))&&w(p(n,"preview"),"sessionId")&&je(p(n,"preview"),"revision")&&Ee(p(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return so(n);case"bridge-initialize-session":case"bridge-get-style-context":return R(n)&&w(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return R(n)&&w(n,"routeId")&&be(n,"minVersion")&&be(n,"version");case"bridge-execute":return R(n)&&R(p(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return R(n)&&w(n,"subscriptionId");default:return!1}}function uo(e){return G(e,"type","response")&&w(e,"id")&&Ge(e,"ok")&&(q(e,"error")||w(e,"error"))}var lo=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]),bn=new Set(["e","s","se"]);function po(e,t){if(q(e,"resizeSession"))return!0;let n=p(e,"resizeSession");if(!R(n))return!1;let r=p(e,"pointerId"),o=p(n,"pointerId"),i=p(n,"phase"),s=p(n,"edge"),c=t==="pointer-down"?"start":t==="pointer-up"?"commit":t==="pointer-cancel"?"cancel":null;return p(n,"version")===1&&i===c&&w(n,"sessionId")&&String(p(n,"sessionId")).length>0&&typeof r=="number"&&Number.isInteger(r)&&typeof o=="number"&&Number.isInteger(o)&&r===o&&typeof s=="string"&&bn.has(s)&&p(e,"resizeEdge")===s&&le(p(n,"ref"))&&["startWidth","startHeight","width","height"].every(a=>M(n,a))}function ho(e){if(!G(e,"type","event")||!w(e,"kind")||!R(p(e,"payload")))return!1;let t=p(e,"kind"),n=p(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return le(p(n,"ref"))&&Se(n,"value")&&(q(n,"hit")||Rt(p(n,"hit")));case"node-bounds-change":return Rt(p(n,"hit"));case"geometry-batch":{let r=p(n,"reason");return Kr(n,"sequence")&&M(n,"sourceEventAt")&&M(n,"captureStartedAt")&&M(n,"capturedAt")&&(r==="scroll"||r==="resize"||r==="mutation")&&eo(p(n,"snapshots"))}case"bridge-event":return w(n,"subscriptionId")&&R(p(n,"event"));case"route-ready":return w(n,"routeId")&&be(n,"version");case"bridge-status":{let r=p(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&Se(n,"routeId")&&be(n,"attempt")&&be(n,"retryInMs")&&Se(n,"messageKey")}case"scroll":{let r=p(n,"metrics");return R(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(o=>M(r,o))}default:return lo.has(t)&&M(n,"clientX")&&M(n,"clientY")&&be(n,"buttons")&&be(n,"pointerId")&&(q(n,"hoverVisualOwned")||Ge(n,"hoverVisualOwned"))&&(q(n,"resizeEdge")||w(n,"resizeEdge")&&bn.has(p(n,"resizeEdge")))&&po(n,t)&&(p(n,"hit")===null||Rt(p(n,"hit")))&&(q(n,"section")||p(n,"section")===null||jr(p(n,"section")))&&(q(n,"sectionGap")||p(n,"sectionGap")===null||Gr(p(n,"sectionGap")))}}function fo(e){if(!R(e))return!1;switch(p(e,"type")){case"request":return co(e);case"response":return uo(e);case"event":return ho(e);default:return!1}}var Tt="vcp-site-edit:route-ready",Pt="vcp-site-edit:bridge-status",mo=80,go=120,yo=1e3,bo="data-vcp-ui-component",Fn="data-vcp-theme-preview",Sn="::repeat-item#",Ye="components/ui",So=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Eo=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function vo(e,t=""){let n=Vn(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function Io(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function Ro(e,t={}){if(t.explicit_ws_url)return t.explicit_ws_url.startsWith("/")?`${e.location.protocol==="https:"?"wss:":"ws:"}//${e.location.host}${t.explicit_ws_url}`:t.explicit_ws_url;let n=e.location.protocol==="https:"?"wss:":"ws:",r=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return`${n}//${r}${t.path??"/__vcp/site-edit/bridge"}`}async function _a(e=window,t={}){let n=Ro(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=xo({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(Co(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let i={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,a=t.create_client??(f=>new Ue({url:f,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Xo,l=()=>{i.retryTimer&&(e.clearTimeout(i.retryTimer),i.retryTimer=void 0)},d=()=>vo(e.location.pathname,t.basePath||""),h=!!e.parent&&e.parent!==e,m=f=>{Jo(e,f)},P=f=>{i.currentDocument=f,i.currentEntriesByKey=new Map((f?.entries??[]).map(v=>[v.key,v]))},x=()=>{i.unsubscribeConnectionStatus?.(),i.unsubscribeConnectionStatus=void 0,i.unsubscribeDocument?.(),i.unsubscribeDocument=void 0},T=(f,v)=>!i.disposed&&v===i.routeSequence&&f===d(),B=async(f,v)=>{let F=i.activeBridge;if(!F)return null;let k=await F.getDocument(f);return T(f,v)&&P(k.data),k.data},O=()=>{x(),P(null);let f=i.activeBridge;i.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__;let v=i.activeClient;i.activeClient=null,v?.disconnect()},J=f=>f===s.routeId&&!!i.activeBridge&&(h||!!(i.currentDocument&&Qo(i.currentDocument,f)))&&Lo(i.activeClient),b=f=>Math.min(yo*2**Math.max(0,f),8e3),L=(f,v,F)=>{if(i.disposed)return;l();let k=b(F);m({state:"reconnecting",routeId:f,attempt:F,retryInMs:k,messageKey:"studio.status.previewBridgeConnecting"}),i.retryTimer=e.setTimeout(()=>{i.retryTimer=void 0,!(i.disposed||v!==i.routeSequence)&&z(F+1).catch(Q=>{let Z=d();if(f===Z){if(xe(Q)){m({state:"reload-required",routeId:f,attempt:F,messageKey:"studio.errors.previewBridgeReloadRequired"});return}L(f,i.routeSequence,F+1)}})},k)},H=(f,v,F)=>{if(!T(f,v)||i.activeClient===null)return;if(xe(F.message)){O(),l(),m({state:"reload-required",routeId:f,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let k=i.activeClient;x(),P(null);let Q=i.activeBridge;i.activeBridge=null,Q&&e.__VCP_SITE_EDIT__===Q&&delete e.__VCP_SITE_EDIT__,i.activeClient=null,k?.disconnect(),L(f,v,0)},$=f=>{let v=d(),F=i.routeSequence;if(!(!T(v,F)||i.activeClient===null)){if(xe(f)){O(),l(),m({state:"reload-required",routeId:v,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Mn(f)&&H(v,F,{state:"failed",message:Nt(f,"Site edit bridge request failed")})}};i.cleanupFrameRuntime=ko(e,{getCurrentDocument:()=>i.currentDocument,getDocumentEntry:f=>i.currentEntriesByKey.get(f)??null,setCurrentDocument:P,onBridgeRequestError:f=>{$(f)}});let U=async()=>z(0),z=async f=>{if(i.disposed)return;let v=d();if(J(v))return;let F=i.syncInFlight;if(F?.routeId===v)return F.promise;let k=i.routeSequence+1,Q=Y(v,k,f);i.syncInFlight={routeId:v,sequence:k,promise:Q};try{await Q}finally{i.syncInFlight?.promise===Q&&(i.syncInFlight=null)}},Y=async(f,v,F)=>{i.routeSequence=v,l(),O(),m({state:F>0?"reconnecting":"connecting",routeId:f,attempt:F,messageKey:F>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let k=a(n),Q=!1;i.activeClient=k,i.unsubscribeConnectionStatus=k.subscribeConnectionStatus?.(Z=>{Q&&(Z.state==="closed"||Z.state==="failed")&&H(f,v,Z)});try{if(await k.connect(),!T(f,v)){k.disconnect();return}let Z=cn({routeId:f,client:k,initialDocument:Ao(f)});i.activeBridge=Z,c()&&(e.__VCP_SITE_EDIT__=Z),i.activeClient=k,i.unsubscribeDocument=Z.subscribe(S=>{S.type==="site-edit.document.changed"&&S.routeId===f&&i.currentDocument&&S.version>i.currentDocument.version&&B(f,v).catch(()=>{})}),c()&&(s.routeId=f);let E=(h?null:await Z.initializeSession({routeId:f}))?.data.document??null;if(E&&P(E),!T(f,v)){k.disconnect();return}Q=!0,m({state:"ready",routeId:f,attempt:F,messageKey:"studio.status.previewReady"}),Io(e,{documentVersion:E?.version??0,routeId:f,versions:t.runtime_versions}),E&&On(e,{routeId:f,version:E.version})}catch(Z){if(x(),i.activeClient===k&&(i.activeClient=null),i.activeBridge&&e.__VCP_SITE_EDIT__===i.activeBridge&&delete e.__VCP_SITE_EDIT__,i.activeBridge=null,k.disconnect(),P(null),!T(f,v))return;throw m({state:xe(Z)?"reload-required":"failed",routeId:f,attempt:F,messageKey:xe(Z)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),Z}},_=f=>{if(i.disposed)return;let v=d();if(xe(f)){l(),m({state:"reload-required",routeId:v,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}L(v,i.routeSequence,0)},A=()=>{i.syncScheduled||i.disposed||(i.syncScheduled=!0,u(()=>{i.syncScheduled=!1,!i.disposed&&U().catch(f=>_(f))}))},C=()=>{i.disposed||(i.disposed=!0,i.syncScheduled=!1,i.syncInFlight=null,l(),i.routeSequence+=1,i.unbindRouteChange?.(),i.unbindRouteChange=void 0,i.unbindBootstrapLifecycle?.(),i.unbindBootstrapLifecycle=void 0,i.cleanupFrameRuntime(),O(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:U,cleanup:C},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,i.unbindBootstrapLifecycle=To(e,C),i.unbindRouteChange=Yo(e,A,d),t.defer_initial_sync){A();return}await U()}function xo(e){return{basePath:Vn(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:_o(e.options.bridge_session_key)}}function Co(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function _o(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function To(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Po(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Po(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Ao(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function ko(e=window,t={}){let n=null,r=null,o=null,i=null,s=null,c=null,a=0,u=null,l=null,d=null,h=null,m=null,P=new Map,x=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,T=()=>{n?.(),n=null,r=null},B=()=>{o?.(),o=null,i?.(),i=null,s?.(),s=null,c?.cleanup(),c=null},O=(E,S,g)=>{let j=u?.sessionKey!==E||u?.sourceWindow!==S||u?.targetOrigin!==g;u={sessionKey:E,sourceWindow:S,targetOrigin:g},j&&(a=0,h=null,m=null)},J=(E,S)=>{let g=e.parent&&e.parent!==e?e.parent:null;return!g||S!==g?!1:!x||E===x},b=()=>{for(let E of P.values())E();P.clear()},L=E=>JSON.stringify([E.routeId,E.version]),H=()=>!d||d.state==="ready",$=E=>JSON.stringify([E.state,E.routeId??null,E.attempt??null,E.retryInMs??null,E.messageKey??null]),U=E=>{if(!H())return;let S=L(E);h!==S&&(i?.(),i=null,s?.(),s=null,c?.cleanup(),c=null,f({kind:"route-ready",payload:{routeId:E.routeId,version:E.version}}),u&&(h=S))},z=E=>{let S=$(E);m!==S&&(E.state!=="ready"&&(h=null,l=null),f({kind:"bridge-status",payload:E}),u&&(m=S))},Y=E=>{l=E,U(E)},_=E=>{d=E,z(E)},A=()=>{l&&U(l)},C=()=>{d&&z(d)},f=E=>{u&&u.sourceWindow.postMessage(De({type:"event",...E},{sessionKey:u.sessionKey}),u.targetOrigin)},v=(E,S,g,j)=>{let W=t.getCurrentDocument?.()??null,ne=ai(e.document,S.clientX,S.clientY),I=S.resizeSession?null:Me(e.document,S.clientX,S.clientY,W),X=I?de(I,g==="full"?pe(e.document,I,W):rt(e.document,I,W),t.getDocumentEntry,g):null,re=ci(e.document,ne,W),ae=li(e.document,S,W);j&&X&&(E==="pointer-click"||E==="pointer-double-click")&&(j.preventDefault(),j.stopPropagation(),typeof j.stopImmediatePropagation=="function"&&j.stopImmediatePropagation()),f({kind:E,payload:{clientX:S.clientX,clientY:S.clientY,buttons:Number(S.buttons??0),pointerId:S.pointerId,hoverVisualOwned:S.hoverVisualOwned,resizeEdge:S.resizeEdge,resizeSession:S.resizeSession,hit:X,section:re,sectionGap:ae}})},F=E=>{f({kind:"pointer-leave",payload:{clientX:E?.clientX??0,clientY:E?.clientY??0,buttons:Number(E?.buttons??0),hit:null,section:null,sectionGap:null}})},k=(E,S,g)=>{B(),u={sessionKey:E,sourceWindow:S,targetOrigin:g};let j=Xi(e.document),W=No(e,t.getCurrentDocument),ne=null,I=null,X=null,re=null,ae=null,ce=()=>{ae!==null&&(e.clearTimeout(ae),ae=null)},ge=()=>{X!==null&&(tt(e,X),X=null),ne=null},$e=()=>{X=null;let y=ne;ne=null,y&&v("pointer-move",y,"summary")},Pe=y=>{ce(),I=y,ne=y,X===null&&(X=et(e,$e))},ee=()=>{I&&Pe({...I,hoverVisualOwned:W?.updateAtPoint(I.clientX,I.clientY)??!1})},ye=e.document.documentElement,N=typeof ye.addEventListener=="function"?ye:e.document,D=y=>{if(c?.update(y)){y.preventDefault();return}Pe({clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons),hoverVisualOwned:W?.update(y.target)??!1})},te=y=>{let V=$o(y.target),Zt=V?c?.begin(y,V):null;Zt&&(y.target?.setPointerCapture?.(y.pointerId),y.preventDefault(),y.stopPropagation()),v("pointer-down",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons),pointerId:Number(y.pointerId),resizeEdge:V,resizeSession:Zt??void 0},"full",y)},fe=y=>{let V=c?.finish(y,"commit")??null;if(V){v("pointer-up",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons),pointerId:Number(y.pointerId),resizeEdge:V.edge,resizeSession:V},"summary",y);return}v("pointer-up",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons)},"summary",y)},Ie=y=>{let V=c?.finish(y,"cancel")??null;v("pointer-cancel",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons),pointerId:V?.pointerId,resizeEdge:V?.edge,resizeSession:V??void 0},"summary",y)},Kt=y=>{let V=c?.finish(y,"cancel")??null;V&&v("pointer-cancel",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons),pointerId:V.pointerId,resizeEdge:V.edge,resizeSession:V},"summary",y)},Ut=y=>{v("pointer-click",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons)},"full",y)},jt=y=>{v("pointer-double-click",{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons)},"full",y)},ft=y=>{if(y&&y.target!==N&&y.target!==ye)return;let V=y?{clientX:Number(y.clientX),clientY:Number(y.clientY),buttons:Number(y.buttons)}:I;if(y&&V&&V.clientX>0&&V.clientX<e.innerWidth&&V.clientY>0&&V.clientY<e.innerHeight){ee();return}if(ge(),y){ce(),ae=e.setTimeout(()=>{ae=null,I=null,F(V??void 0)},go);return}ce(),I=null,W?.clear(),F(V??void 0)},Gt=()=>ft(),Ir=()=>{re=null,f({kind:"scroll",payload:{metrics:Qe(e)}}),ee()},Yt=()=>{re===null&&(re=et(e,Ir))};e.document.addEventListener("pointerdown",te,!0),e.document.addEventListener("pointermove",D,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",fe,!0),e.document.addEventListener("pointercancel",Ie,!0),e.document.addEventListener("lostpointercapture",Kt,!0),e.document.addEventListener("click",Ut,!0),e.document.addEventListener("dblclick",jt,!0),e.addEventListener("scroll",Yt,{passive:!0}),e.addEventListener("resize",ee,{passive:!0}),e.addEventListener("blur",Gt),e.document.addEventListener("load",ee,!0),N.addEventListener("pointerleave",ft,!0);let qe=e.visualViewport;qe?.addEventListener?.("resize",ee,{passive:!0}),qe?.addEventListener?.("scroll",ee,{passive:!0});let Xt=e.ResizeObserver,Jt=typeof Xt=="function"?new Xt(ee):null;Jt?.observe(ye);let Lt=e.MutationObserver,Qt=typeof Lt=="function"?new Lt(ee):null;Qt?.observe(ye,{attributes:!0,childList:!0,subtree:!0}),o=()=>{ge(),ce(),I=null,W?.cleanup(),Jt?.disconnect(),Qt?.disconnect(),re!==null&&(tt(e,re),re=null),j(),e.document.removeEventListener("pointerdown",te,!0),e.document.removeEventListener("pointermove",D,!0),e.document.removeEventListener("pointerup",fe,!0),e.document.removeEventListener("pointercancel",Ie,!0),e.document.removeEventListener("lostpointercapture",Kt,!0),e.document.removeEventListener("click",Ut,!0),e.document.removeEventListener("dblclick",jt,!0),e.removeEventListener("scroll",Yt),e.removeEventListener("resize",ee),e.removeEventListener("blur",Gt),e.document.removeEventListener("load",ee,!0),N.removeEventListener("pointerleave",ft,!0),qe?.removeEventListener?.("resize",ee),qe?.removeEventListener?.("scroll",ee)}},Q=E=>{let S=E.detail;S?.routeId&&Y(S)},Z=E=>{let S=E.detail;S?.state&&_(S)},ht=E=>{let S=E.data;if(!hn(S)||S.body.type!=="request"||S.body.kind!=="apply-node-patch"&&S.body.kind!=="get-hit-by-ref"&&S.body.kind!=="get-path-by-ref"&&S.body.kind!=="get-scroll-metrics"&&S.body.kind!=="scroll-to"&&S.body.kind!=="scroll-by"&&S.body.kind!=="set-interaction-mode"&&S.body.kind!=="set-selection-visual"&&S.body.kind!=="clear-selection-visual"&&S.body.kind!=="set-resize-visual"&&S.body.kind!=="clear-resize-visual"&&S.body.kind!=="set-theme-override"&&S.body.kind!=="clear-theme-override"&&S.body.kind!=="get-theme-variables"&&S.body.kind!=="compute-drop-target-at-point"&&S.body.kind!=="observe-node-bounds"&&S.body.kind!=="clear-node-bounds-observer"&&S.body.kind!=="restore-text-edit"&&S.body.kind!=="clear-text-edit-rollback"&&S.body.kind!=="start-text-edit-at-point"&&S.body.kind!=="hit-test-at-point"&&!xn(S.body))return;let g=S.body,j=typeof S.sessionKey=="string"?S.sessionKey:null,W=E.source,ne=E.origin;if(!j||!ne||!W||typeof W.postMessage!="function"||!J(j,W))return;if(u){if(u.sourceWindow!==W||u.targetOrigin!==ne)return;u.sessionKey!==j&&(T(),B(),b(),u=null)}O(j,W,ne),C(),A();let I=X=>{let re=typeof g.id=="string"?g.id:"unknown";W.postMessage(De({id:re,...X},{sessionKey:j}),ne)};try{if(xn(g)){Uo({message:g,sendEvent:N=>{W.postMessage(De({type:"event",...N},{sessionKey:j}),ne)},sendResponse:I,subscriptions:P,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(g.kind==="apply-node-patch"){let N=he(e.document,g.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for patch target"});return}let D=g.payload.preview,te=D?wi(D.sessionId,g.payload.ref):null;if(te&&D){let fe=Fe.get(te)??-1;if(D.revision<fe){I({type:"response",ok:!0,result:{applied:!1,appliedRevision:D.revision,stale:!0,latestRevision:fe}});return}if(D.revision===fe){I({type:"response",ok:!0,result:{applied:!1,appliedRevision:D.revision,duplicate:!0,latestRevision:fe}});return}}if(Di(N,g.payload.patch),te&&D&&Oi(te,D.revision),D?.responseDetail==="none"){I({type:"response",ok:!0,result:{applied:!0,appliedRevision:D.revision}});return}I({type:"response",ok:!0,result:de(N,pe(e.document,N,t.getCurrentDocument?.()??null),t.getDocumentEntry,D?.responseDetail??"full")});return}if(g.kind==="get-hit-by-ref"){let N=he(e.document,g.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for hit target"});return}I({type:"response",ok:!0,result:de(N,pe(e.document,N,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(g.kind==="get-path-by-ref"){let N=he(e.document,g.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for path target"});return}let D=[],te=N;for(;te;)te.getAttribute("data-vcp-edit-key")&&D.push(de(te,pe(e.document,te,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),te=te.parentElement;I({type:"response",ok:!0,result:D.reverse()});return}if(g.kind==="restore-text-edit"||g.kind==="clear-text-edit-rollback"){let N=g.payload.ref;if(g.kind==="clear-text-edit-rollback"){r&&Cn(r.ref,N)&&(r=null),I({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!Cn(r.ref,N)){I({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let D=ti(e.document,r,t.getCurrentDocument?.()??null);r=null,I(D?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(g.kind==="get-scroll-metrics"){I({type:"response",ok:!0,result:Qe(e)});return}if(g.kind==="scroll-to"){let N=Number(g.payload.x),D=Number(g.payload.y);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:N,top:D}),I({type:"response",ok:!0,result:Qe(e)});return}if(g.kind==="scroll-by"){let N=Number(g.payload.deltaX),D=Number(g.payload.deltaY);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:N,top:D}),I({type:"response",ok:!0,result:{...Qe(e),scrolled:!0}});return}if(g.kind==="set-interaction-mode"){g.payload.enabled?k(j,W,ne):u?.sourceWindow===W&&u.targetOrigin===ne&&u.sessionKey===j&&B(),I({type:"response",ok:!0,result:{interactionEnabled:g.payload.enabled}});return}if(g.kind==="set-selection-visual"){s?.(),s=null,o&&(s=Do(e,g.payload.ref,t.getCurrentDocument)),I({type:"response",ok:!0,result:{version:ke,active:!!s}});return}if(g.kind==="clear-selection-visual"){s?.(),s=null,I({type:"response",ok:!0,result:{version:ke,active:!1}});return}if(g.kind==="set-resize-visual"){c?.cleanup(),c=null,o&&(c=qo(e,g.payload.ref,t.getCurrentDocument)),I({type:"response",ok:!0,result:{version:Ne,active:!!c}});return}if(g.kind==="clear-resize-visual"){c?.cleanup(),c=null,I({type:"response",ok:!0,result:{version:Ne,active:!1}});return}if(g.kind==="set-theme-override"){Mi(e.document,g.payload),I({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(g.kind==="clear-theme-override"){Vi(e.document),I({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(g.kind==="get-theme-variables"){I({type:"response",ok:!0,result:zi(e.document,g.payload.names)});return}if(g.kind==="compute-drop-target-at-point"){let N=Number(g.payload?.x),D=Number(g.payload?.y);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid drop target point"});return}I({type:"response",ok:!0,result:Ti(e,N,D,g.payload.dragKind,g.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(g.kind==="observe-node-bounds"){let N=g.payload.ref;if(!N){I({type:"response",ok:!1,error:"Missing bounds observer target"});return}let D=he(e.document,N,t.getCurrentDocument?.()??null);if(!D){I({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}i?.(),i=vi(e,D,N,t.getCurrentDocument,(te,fe,Ie)=>{a+=1,f({kind:"geometry-batch",payload:{sequence:a,sourceEventAt:Ie.sourceEventAt,captureStartedAt:Ie.captureStartedAt,capturedAt:Ie.capturedAt,reason:te,snapshots:[fe]}})}),I({type:"response",ok:!0,result:{observing:!0}}),f({kind:"node-bounds-change",payload:{hit:de(D,N,t.getDocumentEntry,"summary",e)}});return}if(g.kind==="clear-node-bounds-observer"){i?.(),i=null,I({type:"response",ok:!0,result:{cleared:!0}});return}if(g.kind!=="hit-test-at-point"&&g.kind!=="start-text-edit-at-point")return;let X=Number(g.payload?.x),re=Number(g.payload?.y);if(!Number.isFinite(X)||!Number.isFinite(re)){I({type:"response",ok:!1,error:"Invalid text edit point"});return}let ae=g.kind==="hit-test-at-point"?Me(e.document,X,re,t.getCurrentDocument?.()??null):ri(e.document,X,re,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!ae){I({type:"response",ok:!1,error:g.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let ce=g.kind==="start-text-edit-at-point"?ae:null,ge=g.kind==="hit-test-at-point"?ae:ce.element,$e=g.payload.detailLevel??"full",Pe=$e==="full"?pe(e.document,ge,t.getCurrentDocument?.()??null):rt(e.document,ge,t.getCurrentDocument?.()??null),ee=ce&&typeof ce.textSegmentIndex=="number"?{...Pe,textSegmentIndex:ce.textSegmentIndex}:Pe,ye=de(ge,ee,t.getDocumentEntry,$e);if(g.kind==="hit-test-at-point"){I({type:"response",ok:!0,result:ye});return}T(),n=qi(e,ge,ee,N=>{W.postMessage(De({type:"event",...N},{sessionKey:j}),ne)},{...ce?.textNode?{textNode:ce.textNode}:{},onCommitSnapshot:N=>{r=N}}),I({type:"response",ok:!0,result:{ref:ee}})}catch(X){I({type:"response",ok:!1,error:X instanceof Error?X.message:"Failed to start text edit"})}};return e.addEventListener("message",ht),e.addEventListener(Tt,Q),e.addEventListener(Pt,Z),()=>{T(),B(),u=null,b(),e.removeEventListener("message",ht),e.removeEventListener(Tt,Q),e.removeEventListener(Pt,Z)}}function No(e,t){let n=e.document,r=n.head??n.documentElement;if(typeof r?.appendChild!="function")return null;let o="data-vcp-designer-hover-visual",i="data-vcp-designer-selection-visual",s=n.createElement("style");s.setAttribute("data-vcp-designer-hover-visual-style","true"),s.textContent=`
1
+ function mt(e){let t=new Map,n=[],r=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(i.map((d,h)=>[d,h])),c=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},a=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),u=d=>{let h=t.get(d);if(typeof h=="number")return h;let m=n.length;return n.push(d),t.set(d,m),m},l=d=>{let h=null;for(let m of _r(d)){let P=`${h??"root"}\0${m}`,x=r.get(P);if(typeof x=="number"){h=x;continue}let T=o.length;o.push([h,u(m)]),r.set(P,T),h=T}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:c,tokens:n,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?s.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[l(d.key),Rr(d.operationSummary),...h>=0?[h]:[]]}),...a.length>0?{dynamicDataSummaries:a}:{}}}function gt(e){if(!Cr(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),o=i=>{let s=t.get(i);if(s)return s;let c=e.nodes[i];if(!c)throw new Error(`Missing compact document node ${i}`);let[a,u]=c,l=e.tokens[u];if(typeof l!="string")throw new Error(`Missing compact document token ${u}`);let d=`${a===null?"":o(a)}${l}`;return t.set(i,d),d};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((i,s)=>{let[c,a,u]=i,l=u===void 0?void 0:n[u];if(u!==void 0&&!l)throw new Error(`Missing page composition unit ${u}`);return{key:o(c),...l?{pageCompositionUnitKey:l}:{},operationSummary:xr(a),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function Rr(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function xr(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function Cr(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!en(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(o=>typeof o=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((o,i)=>Array.isArray(o)&&o.length===2&&(o[0]===null||Re(o[0])&&o[0]<i)&&Re(o[1])&&o[1]<t.tokens.length)||!t.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&Re(o[0])&&o[0]<n.length&&Re(o[1])&&o[1]<=15&&(o.length===2||Re(o[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(o=>Array.isArray(o)&&o.length===2&&Re(o[0])&&o[0]<t.entries.length&&en(o[1]))}function en(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function _r(e){if(!e)return[];let t=[],n=0,r=tn(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=tn(e,n+(e.startsWith("::",n)?2:1)),r<0){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r}return t}function tn(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var oe=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!ue(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?ue(t.payload)&&typeof t.payload.id=="string":t.type==="event"?ue(t.payload)&&ue(t.payload.event):t.type==="auth"?ue(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?ue(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!ue(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||yt(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"get-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Tr(t.request)&&(t.request.mutationContext===void 0||yt(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||yt(t.mutationContext)}}},Ke=class{constructor(t){this.options=t,this.messageQueue=new St,this.eventDispatcher=new bt(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"initialize-session":{let i=await this.options.engine.initializeSession({routeId:r.routeId,...r.mutationContext?{mutationContext:r.mutationContext}:{}});this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:{document:mt(i.data.document),historyStatus:i.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:mt((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getStyleContext(r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":{await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.execute(r.request));return}case"undo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=oe.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:rn(n),code:nn(n)}})}}async handleRawMessage(t){try{await this.handleMessage(oe.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Ar(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(oe.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:rn(o),code:nn(o)}}),this.eventDispatcher.flush()}}},bt=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},St=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function ue(e){return typeof e=="object"&&e!==null}function Tr(e){return ue(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&ue(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&ue(e.params)}function yt(e){return Pr(e)}function nn(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function rn(e){if(e instanceof Error)return e.message;if(!e||typeof e!="object")return"Unknown websocket operation failure";let t=e.message;return typeof t=="string"&&t.length>0?t:"Unknown websocket operation failure"}function Pr(e){return ue(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}function Ar(e){try{return oe.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var kr="vcp:designer:trace",Nr="designer_trace",on="__VCP_DESIGNER_TRACE__";var Br=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Dr(e=globalThis){let t=e;try{if(t.localStorage?.getItem(kr)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Nr)==="1"}catch{return!1}}function me(e,t={},n=globalThis){if(!Dr(n))return;let r={type:e,timestamp:Date.now(),payload:Fr(t)},o=n,i=o[on]??[];i.push(r),i.length>1e3&&i.splice(0,i.length-1e3),o[on]=i;let s=n.console?.debug;r.payload.diagnosticOnly!==!0&&typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Fr(e){return Et(e,0)}function Et(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Et(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Br.test(r)){n[r]="[redacted]";continue}n[r]=Et(o,t+1)}return n}var Ue=class{constructor(t){this.options=t,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.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===vt&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((t,n)=>{let r;try{r=this.createSocket(this.options.url)}catch(c){let a=Ae(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",a.message),n(a);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let i=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(c,a)=>{this.cleanupSocket(r,c,a)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(oe.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){s(Ae(c,"WebSocket auth failed"),"failed")}return}i()}},r.onerror=c=>{if(this.socket!==r)return;let a=Ae(c,"WebSocket failed");s(a,"failed")},r.onmessage=c=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(c.data,r,o,()=>{i()});return}this.handleMessage(c.data)}},r.onclose=c=>{if(this.socket!==r)return;let a=this.intentionalClose,u=new Error(Vr(c,{intentional:a}));s(u,a?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let t=this.socket;if(!t){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(t,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(t){return this.connectionStatusListeners.add(t),t({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(t)}}getDocument(t){return this.request("get-document",{routeId:t})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}getSourceTree(){return this.request("get-source-tree",{})}getSourceFile(t){return this.request("get-source-file",t)}resolveSourceLocation(t){return this.request("resolve-source-location",t)}execute(t,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r||r.readyState!==vt||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let o=`${t}-${this.sequence+=1}`,i=Hr(o,t,n);return me("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:sn(n.request,"kind"),documentVersion:sn(n.request,"documentVersion")}),new Promise((s,c)=>{let a=this.resolveRequestTimeoutMs(t),u=a>0?setTimeout(()=>{let l=this.pending.get(o);l&&(this.pending.delete(o),me("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),l.reject(new Error(`Bridge request timed out after ${a}ms: ${t}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:l=>s(l),reject:c});try{r.send(oe.stringifyMessage(i))}catch(l){let d=Ae(l,"WebSocket send failed");this.clearPendingRequest(o),c(d),this.cleanupSocket(r,d,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(oe.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(i){let s=Ae(i,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=oe.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.clearPendingRequest(n.payload.id),n.type==="error"){me("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}me("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:zr(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:gt(n.payload.result.data)}:r.kind==="initialize-session"?Wr(n.payload.result):n.payload.result)}}rejectAll(t){for(let[n,r]of[...this.pending])this.clearPendingRequest(n),r.reject(t)}clearPendingRequest(t){let n=this.pending.get(t);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(t))}resolveRequestTimeoutMs(t){let n=this.options.requestTimeoutMsByKind?.[t];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Mr[t]??Or}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let o=this.connectAttempt;this.connectAttempt=null,o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(r,n.message),t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{(t.readyState===wr||t.readyState===vt)&&t.close()}catch{}}setConnectionState(t,n){if(this.connectionState===t&&!n)return;this.connectionState=t;let r={state:t,...n?{message:n}:{}};this.options.onConnectionStatus?.(r);for(let o of this.connectionStatusListeners)o(r)}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}},wr=0,vt=1,Or=15e3,Mr={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function Ae(e,t){return e instanceof Error?e:new Error(t)}function Vr(e,t){return t.intentional?"WebSocket disconnected":e?.code===1008?e.reason?`Bridge session authentication failed: ${e.reason}`:"Bridge session authentication failed":e?.reason?`WebSocket closed: ${e.reason}`:typeof e?.code=="number"&&e.code!==1005?`WebSocket closed with code ${e.code}`:"WebSocket closed"}function sn(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function zr(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function cn(e){return new It(e)}var It=class{constructor(t){this.params=t,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=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!an(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=an(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let o=this.styleGeneration,i=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===o&&(this.styleContextCache={generation:o,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===i&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:o,request:i},i}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),o=this.editContextCache.get(r);if(o)return{ok:!0,data:o};let i=this.editContextInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.editContextCache.set(r,a.data),a)).finally(()=>{this.editContextInFlight.get(r)===c&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,c),c}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),o=this.classNameSourceCache.get(r);if(o)return o;let i=this.classNameSourceInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getClassNameSource(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,a),a)).finally(()=>{this.classNameSourceInFlight.get(r)===c&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,c),c}async getSourceTree(){return this.params.client.getSourceTree()}async getSourceFile(t){return this.params.client.getSourceFile(t)}async resolveSourceLocation(t){return this.params.client.resolveSourceLocation({...t,routeId:t.routeId??this.params.routeId})}async execute(t,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId&&this.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}me("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,o.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function an(e){return e.version===0&&e.entries.length===0}function Wr(e){let t=e;return{...t,data:{...t.data,document:gt(t.data.document)}}}function Hr(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-source-tree":return{type:"request",payload:{id:e,kind:t}};case"get-source-file":return{type:"request",payload:{id:e,kind:t,path:String(n.path)}};case"resolve-source-location":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t,mutationContext:n.mutationContext}}}}var un="vcp-window-message",Ia=1;function $r(e){return{source:un,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function qr(e){try{return R(e)?G(e,"source",un)&&G(e,"version",1)&&w(e,"namespace")&&w(e,"channel")&&se(e,"body")&&(!Ee(e,"sessionKey")||w(e,"sessionKey")):!1}catch{return!1}}var ln="site-edit",dn="frame-runtime",xt=1,ke=1,Ne=1,pn=24;function De(e,t={}){return $r({namespace:ln,channel:dn,sessionKey:t.sessionKey,body:e})}function hn(e){try{return!qr(e)||e.namespace!==ln||e.channel!==dn?!1:fo(e.body)}catch{return!1}}var Ee=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function se(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function p(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function G(e,t,n){return se(e,t)&&p(e,t)===n}function w(e,t){return se(e,t)&&typeof p(e,t)=="string"}function Ge(e,t){return se(e,t)&&typeof p(e,t)=="boolean"}function M(e,t){let n=p(e,t);return se(e,t)&&typeof n=="number"&&Number.isFinite(n)}function Kr(e,t){let n=p(e,t);return se(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>0}function Se(e,t){return!Ee(e,t)||p(e,t)===void 0||w(e,t)}function be(e,t){return!Ee(e,t)||p(e,t)===void 0||M(e,t)}function je(e,t){let n=p(e,t);return!Ee(e,t)||n===void 0||se(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function q(e,t){return!Ee(e,t)||p(e,t)===void 0}function R(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ur(e){return R(e)&&Reflect.ownKeys(e).length===0}function fn(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function le(e){return R(e)&&w(e,"key")&&je(e,"instanceIndex")&&je(e,"instanceCount")&&je(e,"textSegmentIndex")}function jr(e){return R(e)&&w(e,"blockId")&&le(p(e,"ref"))&&Be(p(e,"rect"))&&Ge(e,"targetIsSectionRoot")}function Gr(e){if(!R(e))return!1;let t=p(e,"placement"),n=p(e,"boundary");return w(e,"anchorBlockId")&&le(p(e,"anchorRef"))&&(t==="before"||t==="after")&&R(n)&&M(n,"top")&&M(n,"left")&&M(n,"width")}function Be(e){return R(e)&&["top","left","width","height"].every(t=>M(e,t))}function mn(e){if(!R(e))return!1;let t=p(e,"rect"),n=p(e,"layout"),r=R(n)?p(n,"containingBlock"):null,o=p(e,"scrollContext"),i=R(r)&&(G(r,"kind","viewport")&&Reflect.ownKeys(r).length===1||G(r,"kind","document")&&Reflect.ownKeys(r).length===1||G(r,"kind","element")&&w(r,"runtimeNodeId"));return G(e,"version",xt)&&w(e,"runtimeNodeId")&&R(t)&&Be(p(t,"viewport"))&&Be(p(t,"document"))&&R(n)&&w(n,"position")&&w(n,"transform")&&i&&R(o)&&["scrollX","scrollY","viewportWidth","viewportHeight"].every(s=>M(o,s))&&se(o,"scrollContainers")&&Yr(p(o,"scrollContainers"))}function Yr(e){return Array.isArray(e)&&e.every(t=>R(t)&&w(t,"runtimeNodeId")&&M(t,"scrollLeft")&&M(t,"scrollTop"))}function Rt(e){return R(e)&&(q(e,"layoutSnapshot")||mn(p(e,"layoutSnapshot")))}function Xr(e){return R(e)&&le(p(e,"ref"))&&se(e,"layoutSnapshot")&&mn(p(e,"layoutSnapshot"))&&(q(e,"childBoxes")||Qr(p(e,"childBoxes")))&&(q(e,"childRects")||Lr(p(e,"childRects")))&&(q(e,"layout")||Jr(p(e,"layout")))&&(q(e,"spacing")||Zr(p(e,"spacing")))}function Jr(e){if(!R(e))return!1;let t=p(e,"indicatorOrientation");return w(e,"display")&&(t==="horizontal"||t==="vertical")&&Se(e,"flexDirection")&&Se(e,"gridAutoFlow")}function Lr(e){return Array.isArray(e)&&e.every(t=>Be(t))}function Qr(e){return Array.isArray(e)&&e.every(t=>R(t)&&Be(p(t,"rect"))&&gn(p(t,"margin")))}function gn(e){return R(e)&&["marginTop","marginRight","marginBottom","marginLeft"].every(t=>M(e,t))}function Zr(e){return gn(e)&&["paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","columnGap","rowGap"].every(t=>M(e,t))}function eo(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||!Xr(n.value))return!1}return!0}function to(e){return R(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&se(e,t)&&(typeof p(e,t)=="string"||p(e,t)===null))}function yn(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function no(e){return R(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&se(e,t)&&yn(p(e,t)))}function ro(e){if(!R(e))return!1;let t=p(e,"priority");return w(e,"property")&&se(e,"value")&&yn(p(e,"value"))&&(!Ee(e,"priority")||t===void 0||t==="important")}function oo(e){return R(e)?(q(e,"attributes")||to(p(e,"attributes")))&&Se(e,"className")&&(q(e,"style")||no(p(e,"style")))&&(q(e,"styleDeclarations")||Array.isArray(p(e,"styleDeclarations"))&&p(e,"styleDeclarations").every(ro)):!1}function io(e){return R(e)&&M(e,"x")&&M(e,"y")&&(q(e,"detailLevel")||G(e,"detailLevel","summary")||G(e,"detailLevel","full"))}function so(e){return R(e)&&le(p(e,"ref"))}function ao(e){if(!R(e)||!R(p(e,"variables")))return!1;let t=p(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&w(t,n))?q(e,"stylesheets")||fn(p(e,"stylesheets")):!1}function co(e){if(!G(e,"type","request")||!w(e,"id")||!w(e,"kind")||!se(e,"payload"))return!1;let t=p(e,"kind"),n=p(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return io(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return Ur(n);case"bridge-get-source-file":return R(n)&&w(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return R(n)&&w(n,"key")&&Se(n,"routeId");case"scroll-to":return R(n)&&M(n,"x")&&M(n,"y");case"scroll-by":return R(n)&&M(n,"deltaX")&&M(n,"deltaY");case"set-interaction-mode":return R(n)&&Ge(n,"enabled");case"set-selection-visual":return R(n)&&G(n,"version",ke)&&le(p(n,"ref"))&&G(n,"visible",!0);case"clear-selection-visual":return R(n)&&G(n,"version",ke);case"set-resize-visual":return R(n)&&G(n,"version",Ne)&&le(p(n,"ref"))&&G(n,"visible",!0);case"clear-resize-visual":return R(n)&&G(n,"version",Ne);case"set-theme-override":return ao(n);case"get-theme-variables":return R(n)&&fn(p(n,"names"));case"compute-drop-target-at-point":return R(n)&&M(n,"x")&&M(n,"y")&&(G(n,"dragKind","insert")||G(n,"dragKind","move"))&&(q(n,"movingRef")||le(p(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return R(n)&&(q(n,"ref")||le(p(n,"ref")));case"apply-node-patch":return R(n)&&le(p(n,"ref"))&&oo(p(n,"patch"))&&(q(n,"preview")||R(p(n,"preview"))&&w(p(n,"preview"),"sessionId")&&je(p(n,"preview"),"revision")&&Ee(p(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return so(n);case"bridge-initialize-session":case"bridge-get-style-context":return R(n)&&w(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return R(n)&&w(n,"routeId")&&be(n,"minVersion")&&be(n,"version");case"bridge-execute":return R(n)&&R(p(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return R(n)&&w(n,"subscriptionId");default:return!1}}function uo(e){return G(e,"type","response")&&w(e,"id")&&Ge(e,"ok")&&(q(e,"error")||w(e,"error"))}var lo=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]),bn=new Set(["e","s","se"]);function po(e,t){if(q(e,"resizeSession"))return!0;let n=p(e,"resizeSession");if(!R(n))return!1;let r=p(e,"pointerId"),o=p(n,"pointerId"),i=p(n,"phase"),s=p(n,"edge"),c=t==="pointer-down"?"start":t==="pointer-up"?"commit":t==="pointer-cancel"?"cancel":null;return p(n,"version")===1&&i===c&&w(n,"sessionId")&&String(p(n,"sessionId")).length>0&&typeof r=="number"&&Number.isInteger(r)&&typeof o=="number"&&Number.isInteger(o)&&r===o&&typeof s=="string"&&bn.has(s)&&p(e,"resizeEdge")===s&&le(p(n,"ref"))&&["startWidth","startHeight","width","height"].every(a=>M(n,a))}function ho(e){if(!G(e,"type","event")||!w(e,"kind")||!R(p(e,"payload")))return!1;let t=p(e,"kind"),n=p(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return le(p(n,"ref"))&&Se(n,"value")&&(q(n,"hit")||Rt(p(n,"hit")));case"node-bounds-change":return Rt(p(n,"hit"));case"geometry-batch":{let r=p(n,"reason");return Kr(n,"sequence")&&M(n,"sourceEventAt")&&M(n,"captureStartedAt")&&M(n,"capturedAt")&&(r==="scroll"||r==="resize"||r==="mutation")&&eo(p(n,"snapshots"))}case"bridge-event":return w(n,"subscriptionId")&&R(p(n,"event"));case"route-ready":return w(n,"routeId")&&be(n,"version");case"bridge-status":{let r=p(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&Se(n,"routeId")&&be(n,"attempt")&&be(n,"retryInMs")&&Se(n,"messageKey")}case"scroll":{let r=p(n,"metrics");return R(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(o=>M(r,o))}default:return lo.has(t)&&M(n,"clientX")&&M(n,"clientY")&&be(n,"buttons")&&be(n,"pointerId")&&(q(n,"hoverVisualOwned")||Ge(n,"hoverVisualOwned"))&&(q(n,"resizeEdge")||w(n,"resizeEdge")&&bn.has(p(n,"resizeEdge")))&&po(n,t)&&(p(n,"hit")===null||Rt(p(n,"hit")))&&(q(n,"section")||p(n,"section")===null||jr(p(n,"section")))&&(q(n,"sectionGap")||p(n,"sectionGap")===null||Gr(p(n,"sectionGap")))}}function fo(e){if(!R(e))return!1;switch(p(e,"type")){case"request":return co(e);case"response":return uo(e);case"event":return ho(e);default:return!1}}var Tt="vcp-site-edit:route-ready",Pt="vcp-site-edit:bridge-status",mo=80,go=120,yo=1e3,bo="data-vcp-ui-component",Fn="data-vcp-theme-preview",Sn="::repeat-item#",Ye="components/ui",So=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Eo=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function vo(e,t=""){let n=Vn(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function Io(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function Ro(e,t={}){if(t.explicit_ws_url)return t.explicit_ws_url.startsWith("/")?`${e.location.protocol==="https:"?"wss:":"ws:"}//${e.location.host}${t.explicit_ws_url}`:t.explicit_ws_url;let n=e.location.protocol==="https:"?"wss:":"ws:",r=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return`${n}//${r}${t.path??"/__vcp/site-edit/bridge"}`}async function _a(e=window,t={}){let n=Ro(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=xo({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(Co(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let i={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,a=t.create_client??(f=>new Ue({url:f,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Xo,l=()=>{i.retryTimer&&(e.clearTimeout(i.retryTimer),i.retryTimer=void 0)},d=()=>vo(e.location.pathname,t.basePath||""),h=!!e.parent&&e.parent!==e,m=f=>{Jo(e,f)},P=f=>{i.currentDocument=f,i.currentEntriesByKey=new Map((f?.entries??[]).map(v=>[v.key,v]))},x=()=>{i.unsubscribeConnectionStatus?.(),i.unsubscribeConnectionStatus=void 0,i.unsubscribeDocument?.(),i.unsubscribeDocument=void 0},T=(f,v)=>!i.disposed&&v===i.routeSequence&&f===d(),B=async(f,v)=>{let F=i.activeBridge;if(!F)return null;let k=await F.getDocument(f);return T(f,v)&&P(k.data),k.data},O=()=>{x(),P(null);let f=i.activeBridge;i.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__;let v=i.activeClient;i.activeClient=null,v?.disconnect()},J=f=>f===s.routeId&&!!i.activeBridge&&(h||!!(i.currentDocument&&Qo(i.currentDocument,f)))&&Lo(i.activeClient),g=f=>Math.min(yo*2**Math.max(0,f),8e3),L=(f,v,F)=>{if(i.disposed)return;l();let k=g(F);m({state:"reconnecting",routeId:f,attempt:F,retryInMs:k,messageKey:"studio.status.previewBridgeConnecting"}),i.retryTimer=e.setTimeout(()=>{i.retryTimer=void 0,!(i.disposed||v!==i.routeSequence)&&z(F+1).catch(Q=>{let Z=d();if(f===Z){if(xe(Q)){m({state:"reload-required",routeId:f,attempt:F,messageKey:"studio.errors.previewBridgeReloadRequired"});return}L(f,i.routeSequence,F+1)}})},k)},H=(f,v,F)=>{if(!T(f,v)||i.activeClient===null)return;if(xe(F.message)){O(),l(),m({state:"reload-required",routeId:f,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let k=i.activeClient;x(),P(null);let Q=i.activeBridge;i.activeBridge=null,Q&&e.__VCP_SITE_EDIT__===Q&&delete e.__VCP_SITE_EDIT__,i.activeClient=null,k?.disconnect(),L(f,v,0)},$=f=>{let v=d(),F=i.routeSequence;if(!(!T(v,F)||i.activeClient===null)){if(xe(f)){O(),l(),m({state:"reload-required",routeId:v,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Mn(f)&&H(v,F,{state:"failed",message:Nt(f,"Site edit bridge request failed")})}};i.cleanupFrameRuntime=ko(e,{getCurrentDocument:()=>i.currentDocument,getDocumentEntry:f=>i.currentEntriesByKey.get(f)??null,setCurrentDocument:P,onBridgeRequestError:f=>{$(f)}});let U=async()=>z(0),z=async f=>{if(i.disposed)return;let v=d();if(J(v))return;let F=i.syncInFlight;if(F?.routeId===v)return F.promise;let k=i.routeSequence+1,Q=Y(v,k,f);i.syncInFlight={routeId:v,sequence:k,promise:Q};try{await Q}finally{i.syncInFlight?.promise===Q&&(i.syncInFlight=null)}},Y=async(f,v,F)=>{i.routeSequence=v,l(),O(),m({state:F>0?"reconnecting":"connecting",routeId:f,attempt:F,messageKey:F>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let k=a(n),Q=!1;i.activeClient=k,i.unsubscribeConnectionStatus=k.subscribeConnectionStatus?.(Z=>{Q&&(Z.state==="closed"||Z.state==="failed")&&H(f,v,Z)});try{if(await k.connect(),!T(f,v)){k.disconnect();return}let Z=cn({routeId:f,client:k,initialDocument:Ao(f)});i.activeBridge=Z,c()&&(e.__VCP_SITE_EDIT__=Z),i.activeClient=k,i.unsubscribeDocument=Z.subscribe(S=>{S.type==="site-edit.document.changed"&&S.routeId===f&&i.currentDocument&&S.version>i.currentDocument.version&&B(f,v).catch(()=>{})}),c()&&(s.routeId=f);let E=(h?null:await Z.initializeSession({routeId:f}))?.data.document??null;if(E&&P(E),!T(f,v)){k.disconnect();return}Q=!0,m({state:"ready",routeId:f,attempt:F,messageKey:"studio.status.previewReady"}),Io(e,{documentVersion:E?.version??0,routeId:f,versions:t.runtime_versions}),E&&On(e,{routeId:f,version:E.version})}catch(Z){if(x(),i.activeClient===k&&(i.activeClient=null),i.activeBridge&&e.__VCP_SITE_EDIT__===i.activeBridge&&delete e.__VCP_SITE_EDIT__,i.activeBridge=null,k.disconnect(),P(null),!T(f,v))return;throw m({state:xe(Z)?"reload-required":"failed",routeId:f,attempt:F,messageKey:xe(Z)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),Z}},_=f=>{if(i.disposed)return;let v=d();if(xe(f)){l(),m({state:"reload-required",routeId:v,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}L(v,i.routeSequence,0)},A=()=>{i.syncScheduled||i.disposed||(i.syncScheduled=!0,u(()=>{i.syncScheduled=!1,!i.disposed&&U().catch(f=>_(f))}))},C=()=>{i.disposed||(i.disposed=!0,i.syncScheduled=!1,i.syncInFlight=null,l(),i.routeSequence+=1,i.unbindRouteChange?.(),i.unbindRouteChange=void 0,i.unbindBootstrapLifecycle?.(),i.unbindBootstrapLifecycle=void 0,i.cleanupFrameRuntime(),O(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:U,cleanup:C},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,i.unbindBootstrapLifecycle=To(e,C),i.unbindRouteChange=Yo(e,A,d),t.defer_initial_sync){A();return}await U()}function xo(e){return{basePath:Vn(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:_o(e.options.bridge_session_key)}}function Co(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function _o(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function To(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Po(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Po(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Ao(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function ko(e=window,t={}){let n=null,r=null,o=null,i=null,s=null,c=null,a=0,u=null,l=null,d=null,h=null,m=null,P=new Map,x=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,T=()=>{n?.(),n=null,r=null},B=()=>{o?.(),o=null,i?.(),i=null,s?.(),s=null,c?.cleanup(),c=null},O=(E,S,y)=>{let j=u?.sessionKey!==E||u?.sourceWindow!==S||u?.targetOrigin!==y;u={sessionKey:E,sourceWindow:S,targetOrigin:y},j&&(a=0,h=null,m=null)},J=(E,S)=>{let y=e.parent&&e.parent!==e?e.parent:null;return!y||S!==y?!1:!x||E===x},g=()=>{for(let E of P.values())E();P.clear()},L=E=>JSON.stringify([E.routeId,E.version]),H=()=>!d||d.state==="ready",$=E=>JSON.stringify([E.state,E.routeId??null,E.attempt??null,E.retryInMs??null,E.messageKey??null]),U=E=>{if(!H())return;let S=L(E);h!==S&&(i?.(),i=null,s?.(),s=null,c?.cleanup(),c=null,f({kind:"route-ready",payload:{routeId:E.routeId,version:E.version}}),u&&(h=S))},z=E=>{let S=$(E);m!==S&&(E.state!=="ready"&&(h=null,l=null),f({kind:"bridge-status",payload:E}),u&&(m=S))},Y=E=>{l=E,U(E)},_=E=>{d=E,z(E)},A=()=>{l&&U(l)},C=()=>{d&&z(d)},f=E=>{u&&u.sourceWindow.postMessage(De({type:"event",...E},{sessionKey:u.sessionKey}),u.targetOrigin)},v=(E,S,y,j)=>{let W=t.getCurrentDocument?.()??null,ne=ai(e.document,S.clientX,S.clientY),I=S.resizeSession?null:Me(e.document,S.clientX,S.clientY,W),X=I?de(I,y==="full"?pe(e.document,I,W):rt(e.document,I,W),t.getDocumentEntry,y):null,re=ci(e.document,ne,W),ae=li(e.document,S,W);j&&X&&(E==="pointer-click"||E==="pointer-double-click")&&(j.preventDefault(),j.stopPropagation(),typeof j.stopImmediatePropagation=="function"&&j.stopImmediatePropagation()),f({kind:E,payload:{clientX:S.clientX,clientY:S.clientY,buttons:Number(S.buttons??0),pointerId:S.pointerId,hoverVisualOwned:S.hoverVisualOwned,resizeEdge:S.resizeEdge,resizeSession:S.resizeSession,hit:X,section:re,sectionGap:ae}})},F=E=>{f({kind:"pointer-leave",payload:{clientX:E?.clientX??0,clientY:E?.clientY??0,buttons:Number(E?.buttons??0),hit:null,section:null,sectionGap:null}})},k=(E,S,y)=>{B(),u={sessionKey:E,sourceWindow:S,targetOrigin:y};let j=Xi(e.document),W=No(e,t.getCurrentDocument),ne=null,I=null,X=null,re=null,ae=null,ce=()=>{ae!==null&&(e.clearTimeout(ae),ae=null)},ge=()=>{X!==null&&(tt(e,X),X=null),ne=null},$e=()=>{X=null;let b=ne;ne=null,b&&v("pointer-move",b,"summary")},Pe=b=>{ce(),I=b,ne=b,X===null&&(X=et(e,$e))},ee=()=>{I&&Pe({...I,hoverVisualOwned:W?.updateAtPoint(I.clientX,I.clientY)??!1})},ye=e.document.documentElement,N=typeof ye.addEventListener=="function"?ye:e.document,D=b=>{if(c?.update(b)){b.preventDefault();return}Pe({clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons),hoverVisualOwned:W?.update(b.target)??!1})},te=b=>{let V=$o(b.target),Zt=V?c?.begin(b,V):null;Zt&&(b.target?.setPointerCapture?.(b.pointerId),b.preventDefault(),b.stopPropagation()),v("pointer-down",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons),pointerId:Number(b.pointerId),resizeEdge:V,resizeSession:Zt??void 0},"full",b)},fe=b=>{let V=c?.finish(b,"commit")??null;if(V){v("pointer-up",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons),pointerId:Number(b.pointerId),resizeEdge:V.edge,resizeSession:V},"summary",b);return}v("pointer-up",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},Ie=b=>{let V=c?.finish(b,"cancel")??null;v("pointer-cancel",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons),pointerId:V?.pointerId,resizeEdge:V?.edge,resizeSession:V??void 0},"summary",b)},Kt=b=>{let V=c?.finish(b,"cancel")??null;V&&v("pointer-cancel",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons),pointerId:V.pointerId,resizeEdge:V.edge,resizeSession:V},"summary",b)},Ut=b=>{v("pointer-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},jt=b=>{v("pointer-double-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},ft=b=>{if(b&&b.target!==N&&b.target!==ye)return;let V=b?{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)}:I;if(b&&V&&V.clientX>0&&V.clientX<e.innerWidth&&V.clientY>0&&V.clientY<e.innerHeight){ee();return}if(ge(),b){ce(),ae=e.setTimeout(()=>{ae=null,I=null,F(V??void 0)},go);return}ce(),I=null,W?.clear(),F(V??void 0)},Gt=()=>ft(),Ir=()=>{re=null,f({kind:"scroll",payload:{metrics:Qe(e)}}),ee()},Yt=()=>{re===null&&(re=et(e,Ir))};e.document.addEventListener("pointerdown",te,!0),e.document.addEventListener("pointermove",D,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",fe,!0),e.document.addEventListener("pointercancel",Ie,!0),e.document.addEventListener("lostpointercapture",Kt,!0),e.document.addEventListener("click",Ut,!0),e.document.addEventListener("dblclick",jt,!0),e.addEventListener("scroll",Yt,{passive:!0}),e.addEventListener("resize",ee,{passive:!0}),e.addEventListener("blur",Gt),e.document.addEventListener("load",ee,!0),N.addEventListener("pointerleave",ft,!0);let qe=e.visualViewport;qe?.addEventListener?.("resize",ee,{passive:!0}),qe?.addEventListener?.("scroll",ee,{passive:!0});let Xt=e.ResizeObserver,Jt=typeof Xt=="function"?new Xt(ee):null;Jt?.observe(ye);let Lt=e.MutationObserver,Qt=typeof Lt=="function"?new Lt(ee):null;Qt?.observe(ye,{attributes:!0,childList:!0,subtree:!0}),o=()=>{ge(),ce(),I=null,W?.cleanup(),Jt?.disconnect(),Qt?.disconnect(),re!==null&&(tt(e,re),re=null),j(),e.document.removeEventListener("pointerdown",te,!0),e.document.removeEventListener("pointermove",D,!0),e.document.removeEventListener("pointerup",fe,!0),e.document.removeEventListener("pointercancel",Ie,!0),e.document.removeEventListener("lostpointercapture",Kt,!0),e.document.removeEventListener("click",Ut,!0),e.document.removeEventListener("dblclick",jt,!0),e.removeEventListener("scroll",Yt),e.removeEventListener("resize",ee),e.removeEventListener("blur",Gt),e.document.removeEventListener("load",ee,!0),N.removeEventListener("pointerleave",ft,!0),qe?.removeEventListener?.("resize",ee),qe?.removeEventListener?.("scroll",ee)}},Q=E=>{let S=E.detail;S?.routeId&&Y(S)},Z=E=>{let S=E.detail;S?.state&&_(S)},ht=E=>{let S=E.data;if(!hn(S)||S.body.type!=="request"||S.body.kind!=="apply-node-patch"&&S.body.kind!=="get-hit-by-ref"&&S.body.kind!=="get-path-by-ref"&&S.body.kind!=="get-scroll-metrics"&&S.body.kind!=="scroll-to"&&S.body.kind!=="scroll-by"&&S.body.kind!=="set-interaction-mode"&&S.body.kind!=="set-selection-visual"&&S.body.kind!=="clear-selection-visual"&&S.body.kind!=="set-resize-visual"&&S.body.kind!=="clear-resize-visual"&&S.body.kind!=="set-theme-override"&&S.body.kind!=="clear-theme-override"&&S.body.kind!=="get-theme-variables"&&S.body.kind!=="compute-drop-target-at-point"&&S.body.kind!=="observe-node-bounds"&&S.body.kind!=="clear-node-bounds-observer"&&S.body.kind!=="restore-text-edit"&&S.body.kind!=="clear-text-edit-rollback"&&S.body.kind!=="start-text-edit-at-point"&&S.body.kind!=="hit-test-at-point"&&!xn(S.body))return;let y=S.body,j=typeof S.sessionKey=="string"?S.sessionKey:null,W=E.source,ne=E.origin;if(!j||!ne||!W||typeof W.postMessage!="function"||!J(j,W))return;if(u){if(u.sourceWindow!==W||u.targetOrigin!==ne)return;u.sessionKey!==j&&(T(),B(),g(),u=null)}O(j,W,ne),C(),A();let I=X=>{let re=typeof y.id=="string"?y.id:"unknown";W.postMessage(De({id:re,...X},{sessionKey:j}),ne)};try{if(xn(y)){Uo({message:y,sendEvent:N=>{W.postMessage(De({type:"event",...N},{sessionKey:j}),ne)},sendResponse:I,subscriptions:P,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(y.kind==="apply-node-patch"){let N=he(e.document,y.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for patch target"});return}let D=y.payload.preview,te=D?wi(D.sessionId,y.payload.ref):null;if(te&&D){let fe=Fe.get(te)??-1;if(D.revision<fe){I({type:"response",ok:!0,result:{applied:!1,appliedRevision:D.revision,stale:!0,latestRevision:fe}});return}if(D.revision===fe){I({type:"response",ok:!0,result:{applied:!1,appliedRevision:D.revision,duplicate:!0,latestRevision:fe}});return}}if(Di(N,y.payload.patch),te&&D&&Oi(te,D.revision),D?.responseDetail==="none"){I({type:"response",ok:!0,result:{applied:!0,appliedRevision:D.revision}});return}I({type:"response",ok:!0,result:de(N,pe(e.document,N,t.getCurrentDocument?.()??null),t.getDocumentEntry,D?.responseDetail??"full")});return}if(y.kind==="get-hit-by-ref"){let N=he(e.document,y.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for hit target"});return}I({type:"response",ok:!0,result:de(N,pe(e.document,N,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(y.kind==="get-path-by-ref"){let N=he(e.document,y.payload.ref,t.getCurrentDocument?.()??null);if(!N){I({type:"response",ok:!1,error:"No editable element found for path target"});return}let D=[],te=N;for(;te;)te.getAttribute("data-vcp-edit-key")&&D.push(de(te,pe(e.document,te,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),te=te.parentElement;I({type:"response",ok:!0,result:D.reverse()});return}if(y.kind==="restore-text-edit"||y.kind==="clear-text-edit-rollback"){let N=y.payload.ref;if(y.kind==="clear-text-edit-rollback"){r&&Cn(r.ref,N)&&(r=null),I({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!Cn(r.ref,N)){I({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let D=ti(e.document,r,t.getCurrentDocument?.()??null);r=null,I(D?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(y.kind==="get-scroll-metrics"){I({type:"response",ok:!0,result:Qe(e)});return}if(y.kind==="scroll-to"){let N=Number(y.payload.x),D=Number(y.payload.y);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:N,top:D}),I({type:"response",ok:!0,result:Qe(e)});return}if(y.kind==="scroll-by"){let N=Number(y.payload.deltaX),D=Number(y.payload.deltaY);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:N,top:D}),I({type:"response",ok:!0,result:{...Qe(e),scrolled:!0}});return}if(y.kind==="set-interaction-mode"){y.payload.enabled?k(j,W,ne):u?.sourceWindow===W&&u.targetOrigin===ne&&u.sessionKey===j&&B(),I({type:"response",ok:!0,result:{interactionEnabled:y.payload.enabled}});return}if(y.kind==="set-selection-visual"){s?.(),s=null,o&&(s=Do(e,y.payload.ref,t.getCurrentDocument)),I({type:"response",ok:!0,result:{version:ke,active:!!s}});return}if(y.kind==="clear-selection-visual"){s?.(),s=null,I({type:"response",ok:!0,result:{version:ke,active:!1}});return}if(y.kind==="set-resize-visual"){c?.cleanup(),c=null,o&&(c=qo(e,y.payload.ref,t.getCurrentDocument)),I({type:"response",ok:!0,result:{version:Ne,active:!!c}});return}if(y.kind==="clear-resize-visual"){c?.cleanup(),c=null,I({type:"response",ok:!0,result:{version:Ne,active:!1}});return}if(y.kind==="set-theme-override"){Mi(e.document,y.payload),I({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(y.kind==="clear-theme-override"){Vi(e.document),I({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(y.kind==="get-theme-variables"){I({type:"response",ok:!0,result:zi(e.document,y.payload.names)});return}if(y.kind==="compute-drop-target-at-point"){let N=Number(y.payload?.x),D=Number(y.payload?.y);if(!Number.isFinite(N)||!Number.isFinite(D)){I({type:"response",ok:!1,error:"Invalid drop target point"});return}I({type:"response",ok:!0,result:Ti(e,N,D,y.payload.dragKind,y.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(y.kind==="observe-node-bounds"){let N=y.payload.ref;if(!N){I({type:"response",ok:!1,error:"Missing bounds observer target"});return}let D=he(e.document,N,t.getCurrentDocument?.()??null);if(!D){I({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}i?.(),i=vi(e,D,N,t.getCurrentDocument,(te,fe,Ie)=>{a+=1,f({kind:"geometry-batch",payload:{sequence:a,sourceEventAt:Ie.sourceEventAt,captureStartedAt:Ie.captureStartedAt,capturedAt:Ie.capturedAt,reason:te,snapshots:[fe]}})}),I({type:"response",ok:!0,result:{observing:!0}}),f({kind:"node-bounds-change",payload:{hit:de(D,N,t.getDocumentEntry,"summary",e)}});return}if(y.kind==="clear-node-bounds-observer"){i?.(),i=null,I({type:"response",ok:!0,result:{cleared:!0}});return}if(y.kind!=="hit-test-at-point"&&y.kind!=="start-text-edit-at-point")return;let X=Number(y.payload?.x),re=Number(y.payload?.y);if(!Number.isFinite(X)||!Number.isFinite(re)){I({type:"response",ok:!1,error:"Invalid text edit point"});return}let ae=y.kind==="hit-test-at-point"?Me(e.document,X,re,t.getCurrentDocument?.()??null):ri(e.document,X,re,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!ae){I({type:"response",ok:!1,error:y.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let ce=y.kind==="start-text-edit-at-point"?ae:null,ge=y.kind==="hit-test-at-point"?ae:ce.element,$e=y.payload.detailLevel??"full",Pe=$e==="full"?pe(e.document,ge,t.getCurrentDocument?.()??null):rt(e.document,ge,t.getCurrentDocument?.()??null),ee=ce&&typeof ce.textSegmentIndex=="number"?{...Pe,textSegmentIndex:ce.textSegmentIndex}:Pe,ye=de(ge,ee,t.getDocumentEntry,$e);if(y.kind==="hit-test-at-point"){I({type:"response",ok:!0,result:ye});return}T(),n=qi(e,ge,ee,N=>{W.postMessage(De({type:"event",...N},{sessionKey:j}),ne)},{...ce?.textNode?{textNode:ce.textNode}:{},onCommitSnapshot:N=>{r=N}}),I({type:"response",ok:!0,result:{ref:ee}})}catch(X){I({type:"response",ok:!1,error:X instanceof Error?X.message:"Failed to start text edit"})}};return e.addEventListener("message",ht),e.addEventListener(Tt,Q),e.addEventListener(Pt,Z),()=>{T(),B(),u=null,g(),e.removeEventListener("message",ht),e.removeEventListener(Tt,Q),e.removeEventListener(Pt,Z)}}function No(e,t){let n=e.document,r=n.head??n.documentElement;if(typeof r?.appendChild!="function")return null;let o="data-vcp-designer-hover-visual",i="data-vcp-designer-selection-visual",s=n.createElement("style");s.setAttribute("data-vcp-designer-hover-visual-style","true"),s.textContent=`
2
2
  [${o}="true"]:not([${i}="true"]) {
3
3
  outline: 1px dashed #4f6bff !important;
4
4
  outline-offset: -1px !important;
@@ -6,7 +6,7 @@ function mt(e){let t=new Map,n=[],r=new Map,o=[],i=e.pageComposition.status==="s
6
6
  [${d}="true"] {
7
7
  outline: 2px solid #4f6bff !important;
8
8
  outline-offset: -2px !important;
9
- }`,o.appendChild(h);let m=r.createElement("div");m.setAttribute("data-vcp-designer-spacing-visual-layer","true"),m.setAttribute("aria-hidden","true"),m.style.setProperty("position","fixed","important"),m.style.setProperty("inset","0","important"),m.style.setProperty("overflow","hidden","important"),m.style.setProperty("pointer-events","none","important"),m.style.setProperty("z-index","2147483645","important"),r.documentElement.appendChild(m),l.setAttribute(d,"true");let P=a?Ze(l,s):null,x=!1,T=null,B=[],O=[],J=()=>{T=null,O.forEach(C=>C()),O=Fo(m,B,l,a?s:null,c)},b=()=>{x||T!==null||(T=et(e,J))};J();let L=()=>{if(x)return;let C=u();C===l&&C?.isConnected||(l?.removeAttribute(d),P?.(),P=null,l=C,l?.isConnected&&(l.setAttribute(d,"true"),P=a?Ze(l,s):null),z(),b())},H=e.ResizeObserver,$=typeof H=="function"?new H(b):null,U=[];function z(){U.forEach(C=>$?.unobserve(C)),U=l?.isConnected?[l,...Array.from(l.children)].filter(C=>typeof C.getBoundingClientRect=="function"):[],U.forEach(C=>$?.observe(C))}z();let Y=e.MutationObserver,_=typeof Y=="function"?new Y(C=>{let f=l;L();let v=f!==l,F=C.some(k=>k.type!=="attributes"||k.attributeName!=="class"&&k.attributeName!=="style"?!1:k.target===l?!0:l?.contains?.(k.target)===!0&&k.target!==m);!v&&!F||(z(),b())}):null;return _?.observe(r.documentElement,{attributeFilter:["data-vcp-edit-key","class","style"],attributes:!0,childList:!0,subtree:!0}),a||(e.addEventListener("scroll",b,!0),r.addEventListener("scroll",b,!0)),e.addEventListener("resize",b),()=>{x||(x=!0,T!==null&&(tt(e,T),T=null),e.removeEventListener("scroll",b,!0),r.removeEventListener("scroll",b,!0),e.removeEventListener("resize",b),_?.disconnect(),$?.disconnect(),l?.removeAttribute(d),O.forEach(C=>C()),O=[],P?.(),P=null,l=null,m.remove(),h.remove())}}function Fo(e,t,n,r,o){if(n?.isConnected===!0&&r)return wo(e,t,n,r,o);let i=n?.isConnected===!0?Oo(n):[];return i.forEach((s,c)=>{let a=t[c]??e.ownerDocument.createElement("div");t[c]||(a.style.setProperty("position","fixed","important"),a.style.setProperty("pointer-events","none","important"),e.appendChild(a),t[c]=a),a.setAttribute("data-vcp-designer-spacing-kind",s.kind),a.style.setProperty("background",s.kind==="margin"?"rgba(245, 158, 11, 0.24)":s.kind==="padding"?"rgba(56, 189, 248, 0.22)":"rgba(34, 197, 94, 0.22)","important"),a.style.setProperty("display","block","important"),a.style.setProperty("left",`${s.left}px`,"important"),a.style.setProperty("top",`${s.top}px`,"important"),a.style.setProperty("width",`${s.width}px`,"important"),a.style.setProperty("height",`${s.height}px`,"important")}),t.slice(i.length).forEach(s=>{s.style.setProperty("display","none","important")}),[]}function wo(e,t,n,r,o){let i=st(n),s=[{kind:"margin",left:"anchor(left)",top:`calc(anchor(top) - ${i.marginTop}px)`,width:"anchor-size(width)",height:`${i.marginTop}px`},{kind:"margin",left:"anchor(right)",top:"anchor(top)",width:`${i.marginRight}px`,height:"anchor-size(height)"},{kind:"margin",left:"anchor(left)",top:"anchor(bottom)",width:"anchor-size(width)",height:`${i.marginBottom}px`},{kind:"margin",left:`calc(anchor(left) - ${i.marginLeft}px)`,top:"anchor(top)",width:`${i.marginLeft}px`,height:"anchor-size(height)"},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(top) + ${i.borderTopWidth}px)`,width:`calc(anchor-size(width) - ${i.borderLeftWidth+i.borderRightWidth}px)`,height:`${i.paddingTop}px`},{kind:"padding",left:`calc(anchor(right) - ${i.borderRightWidth+i.paddingRight}px)`,top:`calc(anchor(top) + ${i.borderTopWidth+i.paddingTop}px)`,width:`${i.paddingRight}px`,height:`calc(anchor-size(height) - ${i.borderTopWidth+i.borderBottomWidth+i.paddingTop+i.paddingBottom}px)`},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(bottom) - ${i.borderBottomWidth+i.paddingBottom}px)`,width:`calc(anchor-size(width) - ${i.borderLeftWidth+i.borderRightWidth}px)`,height:`${i.paddingBottom}px`},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(top) + ${i.borderTopWidth+i.paddingTop}px)`,width:`${i.paddingLeft}px`,height:`calc(anchor-size(height) - ${i.borderTopWidth+i.borderBottomWidth+i.paddingTop+i.paddingBottom}px)`}];s.forEach((u,l)=>{let d=En(e,t,l);d.setAttribute("data-vcp-designer-spacing-kind",u.kind),d.style.setProperty("position-anchor",r,"important"),d.style.setProperty("left",u.left,"important"),d.style.setProperty("top",u.top,"important"),d.style.setProperty("width",u.width,"important"),d.style.setProperty("height",u.height,"important"),d.style.setProperty("background",u.kind==="margin"?"rgba(245, 158, 11, 0.24)":"rgba(56, 189, 248, 0.22)","important");let h=u.kind==="margin"?[i.marginTop,i.marginRight,i.marginBottom,i.marginLeft][l]:[i.paddingTop,i.paddingRight,i.paddingBottom,i.paddingLeft][l-4];d.style.setProperty("display",(h??0)>.5?"block":"none","important")});let c=Vo(n,i),a=c.map((u,l)=>{let d=En(e,t,s.length+l),h=`${o}-${l}`,m=Ze(u.anchorElement,h);return d.setAttribute("data-vcp-designer-spacing-kind","gap"),d.style.setProperty("position-anchor",h,"important"),d.style.setProperty("background","rgba(34, 197, 94, 0.22)","important"),d.style.setProperty("display","block","important"),d.style.setProperty("left",`calc(anchor(left) + ${u.leftOffset}px)`,"important"),d.style.setProperty("top",`calc(anchor(top) + ${u.topOffset}px)`,"important"),d.style.setProperty("width",`${u.width}px`,"important"),d.style.setProperty("height",`${u.height}px`,"important"),m});return t.slice(s.length+c.length).forEach(u=>{u.style.setProperty("display","none","important")}),a}function En(e,t,n){let r=t[n];if(r)return r;let o=e.ownerDocument.createElement("div");return o.style.setProperty("position","fixed","important"),o.style.setProperty("pointer-events","none","important"),e.appendChild(o),t[n]=o,o}function Oo(e){let t=ve(e.getBoundingClientRect()),n=st(e),r=t.left+n.borderLeftWidth,o=t.top+n.borderTopWidth,i=t.width-n.borderLeftWidth-n.borderRightWidth,s=t.height-n.borderTopWidth-n.borderBottomWidth,c=o+n.paddingTop,a=s-n.paddingTop-n.paddingBottom,u=[{kind:"margin",left:t.left,top:t.top-n.marginTop,width:t.width,height:n.marginTop},{kind:"margin",left:t.left+t.width,top:t.top,width:n.marginRight,height:t.height},{kind:"margin",left:t.left,top:t.top+t.height,width:t.width,height:n.marginBottom},{kind:"margin",left:t.left-n.marginLeft,top:t.top,width:n.marginLeft,height:t.height}];return i>0&&s>0&&u.push({kind:"padding",left:r,top:o,width:i,height:n.paddingTop},{kind:"padding",left:r+i-n.paddingRight,top:c,width:n.paddingRight,height:a},{kind:"padding",left:r,top:o+s-n.paddingBottom,width:i,height:n.paddingBottom},{kind:"padding",left:r,top:c,width:n.paddingLeft,height:a}),u.push(...Mo(e,n)),u.filter(l=>l.width>.5&&l.height>.5)}function Mo(e,t){let n=e.ownerDocument?.defaultView?.getComputedStyle(e).display??"";if(!["flex","inline-flex","grid","inline-grid"].includes(n)||t.columnGap<=0&&t.rowGap<=0)return[];let r=Ot(e);return[...In(r,"horizontal",t.columnGap),...In(r,"vertical",t.rowGap)]}function Vo(e,t){let n=e.ownerDocument?.defaultView?.getComputedStyle(e).display??"";if(!["flex","inline-flex","grid","inline-grid"].includes(n)||t.columnGap<=0&&t.rowGap<=0)return[];let r=e.ownerDocument?.defaultView,o=Array.from(e.children).filter(i=>typeof i.getBoundingClientRect=="function").map(i=>({element:i,rect:ve(i.getBoundingClientRect()),margin:wt(r?.getComputedStyle(i))})).filter(({rect:i})=>i.width>0&&i.height>0);return[...vn(o,"horizontal",t.columnGap),...vn(o,"vertical",t.rowGap)].filter(i=>i.width>.5&&i.height>.5)}function vn(e,t,n){if(n<=0||e.length<2)return[];let r=wn(e,t==="horizontal"?"y":"x"),o=[];return r.forEach(i=>{let s=[...i].sort((c,a)=>t==="horizontal"?c.rect.left-a.rect.left:c.rect.top-a.rect.top);for(let c=0;c<s.length-1;c+=1){let a=s[c],u=s[c+1];if(t==="horizontal"){let l=a.rect.left+a.rect.width+a.margin.marginRight,d=u.rect.left-u.margin.marginLeft-l,h=Math.min(n,d);o.push({anchorElement:a.element,leftOffset:l+Math.max(0,(d-h)/2)-a.rect.left,topOffset:Math.max(a.rect.top,u.rect.top)-a.rect.top,width:h,height:Math.min(a.rect.top+a.rect.height,u.rect.top+u.rect.height)-Math.max(a.rect.top,u.rect.top)})}else{let l=a.rect.top+a.rect.height+a.margin.marginBottom,d=u.rect.top-u.margin.marginTop-l,h=Math.min(n,d);o.push({anchorElement:a.element,leftOffset:Math.max(a.rect.left,u.rect.left)-a.rect.left,topOffset:l+Math.max(0,(d-h)/2)-a.rect.top,width:Math.min(a.rect.left+a.rect.width,u.rect.left+u.rect.width)-Math.max(a.rect.left,u.rect.left),height:h})}}}),o}function In(e,t,n){if(n<=0||e.length<2)return[];let r=wn(e,t==="horizontal"?"y":"x"),o=[];return r.forEach(i=>{let s=[...i].sort((c,a)=>t==="horizontal"?c.rect.left-a.rect.left:c.rect.top-a.rect.top);for(let c=0;c<s.length-1;c+=1){let a=s[c],u=s[c+1];if(t==="horizontal"){let l=a.rect.left+a.rect.width+a.margin.marginRight,d=u.rect.left-u.margin.marginLeft-l,h=Math.min(n,d);o.push({kind:"gap",left:l+Math.max(0,(d-h)/2),top:Math.max(a.rect.top,u.rect.top),width:h,height:Math.min(a.rect.top+a.rect.height,u.rect.top+u.rect.height)-Math.max(a.rect.top,u.rect.top)})}else{let l=a.rect.top+a.rect.height+a.margin.marginBottom,d=u.rect.top-u.margin.marginTop-l,h=Math.min(n,d);o.push({kind:"gap",left:Math.max(a.rect.left,u.rect.left),top:l+Math.max(0,(d-h)/2),width:Math.min(a.rect.left+a.rect.width,u.rect.left+u.rect.width)-Math.max(a.rect.left,u.rect.left),height:h})}}}),o}function wn(e,t){let n=[...e].sort((o,i)=>t==="x"?o.rect.left-i.rect.left||o.rect.top-i.rect.top:o.rect.top-i.rect.top||o.rect.left-i.rect.left),r=[];return n.forEach(o=>{let i=r.find(s=>s.some(c=>zo(c.rect,o.rect,t)>.5));i?i.push(o):r.push([o])}),r}function zo(e,t,n){return n==="x"?Math.min(e.left+e.width,t.left+t.width)-Math.max(e.left,t.left):Math.min(e.top+e.height,t.top+t.height)-Math.max(e.top,t.top)}var Xe=new WeakMap;function Ze(e,t){let n=Xe.get(e);if(!n){let o=e.style.getPropertyValue("anchor-name"),i=e.ownerDocument?.defaultView?.getComputedStyle(e).getPropertyValue?.("anchor-name").trim()??"";n={names:new Set,originalValue:o,originalPriority:e.style.getPropertyPriority("anchor-name"),computedValue:i==="none"?"":i},Xe.set(e,n)}n.names.add(t),Rn(e,n);let r=!1;return()=>{if(r)return;r=!0;let o=Xe.get(e);if(o){if(o.names.delete(t),o.names.size>0){Rn(e,o);return}o.originalValue?e.style.setProperty("anchor-name",o.originalValue,o.originalPriority):e.style.removeProperty("anchor-name"),Xe.delete(e)}}}function Rn(e,t){let n=t.originalValue.trim()||t.computedValue;e.style.setProperty("anchor-name",[...n?[n]:[],...t.names].join(", "),"important")}var Wo=["e","se","s"],Ho=0;function $o(e){let t=e,o=(t?.getAttribute?.("data-vcp-designer-resize-handle")?t:t?.closest?.("[data-vcp-designer-resize-handle]"))?.getAttribute?.("data-vcp-designer-resize-handle");return o==="e"||o==="s"||o==="se"?o:void 0}function qo(e,t,n){let r=++Ho,o=`--vcp-designer-resize-target-${r}`,i=e.CSS;if(typeof i?.supports!="function"||!i.supports(`anchor-name: ${o}`)||!i.supports(`position-anchor: ${o}`)||!i.supports("left: anchor(left)")||!i.supports("top: anchor(top)"))return null;let s=e.document,c=s.head??s.documentElement,a=s.body??s.documentElement,u=()=>he(s,t,n?.()??null),l=u();if(!l||!l.isConnected||typeof c?.appendChild!="function"||typeof a?.appendChild!="function")return null;let d="data-vcp-designer-resize-visual",h="data-vcp-designer-resize-handle",m=s.createElement("style");m.setAttribute("data-vcp-designer-resize-visual-style","true"),m.textContent=`
9
+ }`,o.appendChild(h);let m=r.createElement("div");m.setAttribute("data-vcp-designer-spacing-visual-layer","true"),m.setAttribute("aria-hidden","true"),m.style.setProperty("position","fixed","important"),m.style.setProperty("inset","0","important"),m.style.setProperty("overflow","hidden","important"),m.style.setProperty("pointer-events","none","important"),m.style.setProperty("z-index","2147483645","important"),r.documentElement.appendChild(m),l.setAttribute(d,"true");let P=a?Ze(l,s):null,x=!1,T=null,B=[],O=[],J=()=>{T=null,O.forEach(C=>C()),O=Fo(m,B,l,a?s:null,c)},g=()=>{x||T!==null||(T=et(e,J))};J();let L=()=>{if(x)return;let C=u();C===l&&C?.isConnected||(l?.removeAttribute(d),P?.(),P=null,l=C,l?.isConnected&&(l.setAttribute(d,"true"),P=a?Ze(l,s):null),z(),g())},H=e.ResizeObserver,$=typeof H=="function"?new H(g):null,U=[];function z(){U.forEach(C=>$?.unobserve(C)),U=l?.isConnected?[l,...Array.from(l.children)].filter(C=>typeof C.getBoundingClientRect=="function"):[],U.forEach(C=>$?.observe(C))}z();let Y=e.MutationObserver,_=typeof Y=="function"?new Y(C=>{let f=l;L();let v=f!==l,F=C.some(k=>k.type!=="attributes"||k.attributeName!=="class"&&k.attributeName!=="style"?!1:k.target===l?!0:l?.contains?.(k.target)===!0&&k.target!==m);!v&&!F||(z(),g())}):null;return _?.observe(r.documentElement,{attributeFilter:["data-vcp-edit-key","class","style"],attributes:!0,childList:!0,subtree:!0}),a||(e.addEventListener("scroll",g,!0),r.addEventListener("scroll",g,!0)),e.addEventListener("resize",g),()=>{x||(x=!0,T!==null&&(tt(e,T),T=null),e.removeEventListener("scroll",g,!0),r.removeEventListener("scroll",g,!0),e.removeEventListener("resize",g),_?.disconnect(),$?.disconnect(),l?.removeAttribute(d),O.forEach(C=>C()),O=[],P?.(),P=null,l=null,m.remove(),h.remove())}}function Fo(e,t,n,r,o){if(n?.isConnected===!0&&r)return wo(e,t,n,r,o);let i=n?.isConnected===!0?Oo(n):[];return i.forEach((s,c)=>{let a=t[c]??e.ownerDocument.createElement("div");t[c]||(a.style.setProperty("position","fixed","important"),a.style.setProperty("pointer-events","none","important"),e.appendChild(a),t[c]=a),a.setAttribute("data-vcp-designer-spacing-kind",s.kind),a.style.setProperty("background",s.kind==="margin"?"rgba(245, 158, 11, 0.24)":s.kind==="padding"?"rgba(56, 189, 248, 0.22)":"rgba(34, 197, 94, 0.22)","important"),a.style.setProperty("display","block","important"),a.style.setProperty("left",`${s.left}px`,"important"),a.style.setProperty("top",`${s.top}px`,"important"),a.style.setProperty("width",`${s.width}px`,"important"),a.style.setProperty("height",`${s.height}px`,"important")}),t.slice(i.length).forEach(s=>{s.style.setProperty("display","none","important")}),[]}function wo(e,t,n,r,o){let i=st(n),s=[{kind:"margin",left:"anchor(left)",top:`calc(anchor(top) - ${i.marginTop}px)`,width:"anchor-size(width)",height:`${i.marginTop}px`},{kind:"margin",left:"anchor(right)",top:"anchor(top)",width:`${i.marginRight}px`,height:"anchor-size(height)"},{kind:"margin",left:"anchor(left)",top:"anchor(bottom)",width:"anchor-size(width)",height:`${i.marginBottom}px`},{kind:"margin",left:`calc(anchor(left) - ${i.marginLeft}px)`,top:"anchor(top)",width:`${i.marginLeft}px`,height:"anchor-size(height)"},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(top) + ${i.borderTopWidth}px)`,width:`calc(anchor-size(width) - ${i.borderLeftWidth+i.borderRightWidth}px)`,height:`${i.paddingTop}px`},{kind:"padding",left:`calc(anchor(right) - ${i.borderRightWidth+i.paddingRight}px)`,top:`calc(anchor(top) + ${i.borderTopWidth+i.paddingTop}px)`,width:`${i.paddingRight}px`,height:`calc(anchor-size(height) - ${i.borderTopWidth+i.borderBottomWidth+i.paddingTop+i.paddingBottom}px)`},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(bottom) - ${i.borderBottomWidth+i.paddingBottom}px)`,width:`calc(anchor-size(width) - ${i.borderLeftWidth+i.borderRightWidth}px)`,height:`${i.paddingBottom}px`},{kind:"padding",left:`calc(anchor(left) + ${i.borderLeftWidth}px)`,top:`calc(anchor(top) + ${i.borderTopWidth+i.paddingTop}px)`,width:`${i.paddingLeft}px`,height:`calc(anchor-size(height) - ${i.borderTopWidth+i.borderBottomWidth+i.paddingTop+i.paddingBottom}px)`}];s.forEach((u,l)=>{let d=En(e,t,l);d.setAttribute("data-vcp-designer-spacing-kind",u.kind),d.style.setProperty("position-anchor",r,"important"),d.style.setProperty("left",u.left,"important"),d.style.setProperty("top",u.top,"important"),d.style.setProperty("width",u.width,"important"),d.style.setProperty("height",u.height,"important"),d.style.setProperty("background",u.kind==="margin"?"rgba(245, 158, 11, 0.24)":"rgba(56, 189, 248, 0.22)","important");let h=u.kind==="margin"?[i.marginTop,i.marginRight,i.marginBottom,i.marginLeft][l]:[i.paddingTop,i.paddingRight,i.paddingBottom,i.paddingLeft][l-4];d.style.setProperty("display",(h??0)>.5?"block":"none","important")});let c=Vo(n,i),a=c.map((u,l)=>{let d=En(e,t,s.length+l),h=`${o}-${l}`,m=Ze(u.anchorElement,h);return d.setAttribute("data-vcp-designer-spacing-kind","gap"),d.style.setProperty("position-anchor",h,"important"),d.style.setProperty("background","rgba(34, 197, 94, 0.22)","important"),d.style.setProperty("display","block","important"),d.style.setProperty("left",`calc(anchor(left) + ${u.leftOffset}px)`,"important"),d.style.setProperty("top",`calc(anchor(top) + ${u.topOffset}px)`,"important"),d.style.setProperty("width",`${u.width}px`,"important"),d.style.setProperty("height",`${u.height}px`,"important"),m});return t.slice(s.length+c.length).forEach(u=>{u.style.setProperty("display","none","important")}),a}function En(e,t,n){let r=t[n];if(r)return r;let o=e.ownerDocument.createElement("div");return o.style.setProperty("position","fixed","important"),o.style.setProperty("pointer-events","none","important"),e.appendChild(o),t[n]=o,o}function Oo(e){let t=ve(e.getBoundingClientRect()),n=st(e),r=t.left+n.borderLeftWidth,o=t.top+n.borderTopWidth,i=t.width-n.borderLeftWidth-n.borderRightWidth,s=t.height-n.borderTopWidth-n.borderBottomWidth,c=o+n.paddingTop,a=s-n.paddingTop-n.paddingBottom,u=[{kind:"margin",left:t.left,top:t.top-n.marginTop,width:t.width,height:n.marginTop},{kind:"margin",left:t.left+t.width,top:t.top,width:n.marginRight,height:t.height},{kind:"margin",left:t.left,top:t.top+t.height,width:t.width,height:n.marginBottom},{kind:"margin",left:t.left-n.marginLeft,top:t.top,width:n.marginLeft,height:t.height}];return i>0&&s>0&&u.push({kind:"padding",left:r,top:o,width:i,height:n.paddingTop},{kind:"padding",left:r+i-n.paddingRight,top:c,width:n.paddingRight,height:a},{kind:"padding",left:r,top:o+s-n.paddingBottom,width:i,height:n.paddingBottom},{kind:"padding",left:r,top:c,width:n.paddingLeft,height:a}),u.push(...Mo(e,n)),u.filter(l=>l.width>.5&&l.height>.5)}function Mo(e,t){let n=e.ownerDocument?.defaultView?.getComputedStyle(e).display??"";if(!["flex","inline-flex","grid","inline-grid"].includes(n)||t.columnGap<=0&&t.rowGap<=0)return[];let r=Ot(e);return[...In(r,"horizontal",t.columnGap),...In(r,"vertical",t.rowGap)]}function Vo(e,t){let n=e.ownerDocument?.defaultView?.getComputedStyle(e).display??"";if(!["flex","inline-flex","grid","inline-grid"].includes(n)||t.columnGap<=0&&t.rowGap<=0)return[];let r=e.ownerDocument?.defaultView,o=Array.from(e.children).filter(i=>typeof i.getBoundingClientRect=="function").map(i=>({element:i,rect:ve(i.getBoundingClientRect()),margin:wt(r?.getComputedStyle(i))})).filter(({rect:i})=>i.width>0&&i.height>0);return[...vn(o,"horizontal",t.columnGap),...vn(o,"vertical",t.rowGap)].filter(i=>i.width>.5&&i.height>.5)}function vn(e,t,n){if(n<=0||e.length<2)return[];let r=wn(e,t==="horizontal"?"y":"x"),o=[];return r.forEach(i=>{let s=[...i].sort((c,a)=>t==="horizontal"?c.rect.left-a.rect.left:c.rect.top-a.rect.top);for(let c=0;c<s.length-1;c+=1){let a=s[c],u=s[c+1];if(t==="horizontal"){let l=a.rect.left+a.rect.width+a.margin.marginRight,d=u.rect.left-u.margin.marginLeft-l,h=Math.min(n,d);o.push({anchorElement:a.element,leftOffset:l+Math.max(0,(d-h)/2)-a.rect.left,topOffset:Math.max(a.rect.top,u.rect.top)-a.rect.top,width:h,height:Math.min(a.rect.top+a.rect.height,u.rect.top+u.rect.height)-Math.max(a.rect.top,u.rect.top)})}else{let l=a.rect.top+a.rect.height+a.margin.marginBottom,d=u.rect.top-u.margin.marginTop-l,h=Math.min(n,d);o.push({anchorElement:a.element,leftOffset:Math.max(a.rect.left,u.rect.left)-a.rect.left,topOffset:l+Math.max(0,(d-h)/2)-a.rect.top,width:Math.min(a.rect.left+a.rect.width,u.rect.left+u.rect.width)-Math.max(a.rect.left,u.rect.left),height:h})}}}),o}function In(e,t,n){if(n<=0||e.length<2)return[];let r=wn(e,t==="horizontal"?"y":"x"),o=[];return r.forEach(i=>{let s=[...i].sort((c,a)=>t==="horizontal"?c.rect.left-a.rect.left:c.rect.top-a.rect.top);for(let c=0;c<s.length-1;c+=1){let a=s[c],u=s[c+1];if(t==="horizontal"){let l=a.rect.left+a.rect.width+a.margin.marginRight,d=u.rect.left-u.margin.marginLeft-l,h=Math.min(n,d);o.push({kind:"gap",left:l+Math.max(0,(d-h)/2),top:Math.max(a.rect.top,u.rect.top),width:h,height:Math.min(a.rect.top+a.rect.height,u.rect.top+u.rect.height)-Math.max(a.rect.top,u.rect.top)})}else{let l=a.rect.top+a.rect.height+a.margin.marginBottom,d=u.rect.top-u.margin.marginTop-l,h=Math.min(n,d);o.push({kind:"gap",left:Math.max(a.rect.left,u.rect.left),top:l+Math.max(0,(d-h)/2),width:Math.min(a.rect.left+a.rect.width,u.rect.left+u.rect.width)-Math.max(a.rect.left,u.rect.left),height:h})}}}),o}function wn(e,t){let n=[...e].sort((o,i)=>t==="x"?o.rect.left-i.rect.left||o.rect.top-i.rect.top:o.rect.top-i.rect.top||o.rect.left-i.rect.left),r=[];return n.forEach(o=>{let i=r.find(s=>s.some(c=>zo(c.rect,o.rect,t)>.5));i?i.push(o):r.push([o])}),r}function zo(e,t,n){return n==="x"?Math.min(e.left+e.width,t.left+t.width)-Math.max(e.left,t.left):Math.min(e.top+e.height,t.top+t.height)-Math.max(e.top,t.top)}var Xe=new WeakMap;function Ze(e,t){let n=Xe.get(e);if(!n){let o=e.style.getPropertyValue("anchor-name"),i=e.ownerDocument?.defaultView?.getComputedStyle(e).getPropertyValue?.("anchor-name").trim()??"";n={names:new Set,originalValue:o,originalPriority:e.style.getPropertyPriority("anchor-name"),computedValue:i==="none"?"":i},Xe.set(e,n)}n.names.add(t),Rn(e,n);let r=!1;return()=>{if(r)return;r=!0;let o=Xe.get(e);if(o){if(o.names.delete(t),o.names.size>0){Rn(e,o);return}o.originalValue?e.style.setProperty("anchor-name",o.originalValue,o.originalPriority):e.style.removeProperty("anchor-name"),Xe.delete(e)}}}function Rn(e,t){let n=t.originalValue.trim()||t.computedValue;e.style.setProperty("anchor-name",[...n?[n]:[],...t.names].join(", "),"important")}var Wo=["e","se","s"],Ho=0;function $o(e){let t=e,o=(t?.getAttribute?.("data-vcp-designer-resize-handle")?t:t?.closest?.("[data-vcp-designer-resize-handle]"))?.getAttribute?.("data-vcp-designer-resize-handle");return o==="e"||o==="s"||o==="se"?o:void 0}function qo(e,t,n){let r=++Ho,o=`--vcp-designer-resize-target-${r}`,i=e.CSS;if(typeof i?.supports!="function"||!i.supports(`anchor-name: ${o}`)||!i.supports(`position-anchor: ${o}`)||!i.supports("left: anchor(left)")||!i.supports("top: anchor(top)"))return null;let s=e.document,c=s.head??s.documentElement,a=s.body??s.documentElement,u=()=>he(s,t,n?.()??null),l=u();if(!l||!l.isConnected||typeof c?.appendChild!="function"||typeof a?.appendChild!="function")return null;let d="data-vcp-designer-resize-visual",h="data-vcp-designer-resize-handle",m=s.createElement("style");m.setAttribute("data-vcp-designer-resize-visual-style","true"),m.textContent=`
10
10
  [${h}] {
11
11
  position: fixed !important;
12
12
  position-anchor: ${o};
@@ -28,9 +28,9 @@ function mt(e){let t=new Map,n=[],r=new Map,o=[],i=e.pageComposition.status==="s
28
28
  [${h}="e"] { left: anchor(right); top: anchor(center); }
29
29
  [${h}="se"] { left: anchor(right); top: anchor(bottom); }
30
30
  [${h}="s"] { left: anchor(center); top: anchor(bottom); }
31
- `,c.appendChild(m);let P=Wo.map(_=>{let A=s.createElement("div");return A.setAttribute(h,_),A.setAttribute("aria-hidden","true"),a.appendChild(A),A}),x=null,T=null,B=()=>{x?.removeAttribute(d),T?.(),T=null,x=null},O=_=>{B(),x=_,T=Ze(_,o),_.setAttribute(d,"true"),P.forEach(A=>A.style.removeProperty("display"))};O(l);let J=!1,b=null,L=()=>{if(!b||!l)return;let _=(A,C,f)=>{C?l.style.setProperty(A,C,f):l.style.removeProperty(A)};_("width",b.widthValue,b.widthPriority),_("height",b.heightValue,b.heightPriority)},H=(_,A,C)=>b?{version:1,phase:_,sessionId:b.sessionId,pointerId:b.pointerId,edge:b.edge,ref:t,startWidth:b.startWidth,startHeight:b.startHeight,width:A,height:C}:null,$=_=>{if(!b||!l?.isConnected||_.pointerId!==b.pointerId)return!1;let A=Number(_.clientX)-b.startX,C=Number(_.clientY)-b.startY,f=Math.max(1,Math.round(b.startWidth+A)),v=Math.max(1,Math.round(b.startHeight+C));return(b.edge==="e"||b.edge==="se")&&l.style.setProperty("width",`${f}px`,"important"),(b.edge==="s"||b.edge==="se")&&l.style.setProperty("height",`${v}px`,"important"),!0},U=()=>{if(J)return;let _=u();if(_===l&&_?.isConnected)return;L();let A=b?.captureTarget,C=b?.pointerId;b=null,C!==void 0&&A?.releasePointerCapture?.(C),B(),l=_,l?.isConnected?O(l):P.forEach(f=>f.style.setProperty("display","none","important"))},z=e.MutationObserver,Y=typeof z=="function"?new z(U):null;return Y?.observe(s.documentElement,{attributeFilter:["data-vcp-edit-key"],attributes:!0,childList:!0,subtree:!0}),{begin(_,A){if(J||b||!l?.isConnected)return null;let C=l.getBoundingClientRect();return b={sessionId:`resize-${r}-${_.pointerId}`,pointerId:_.pointerId,edge:A,startX:Number(_.clientX),startY:Number(_.clientY),startWidth:C.width,startHeight:C.height,widthValue:l.style.getPropertyValue("width"),widthPriority:l.style.getPropertyPriority("width"),heightValue:l.style.getPropertyValue("height"),heightPriority:l.style.getPropertyPriority("height"),captureTarget:_.target},H("start",C.width,C.height)},update:$,finish(_,A){if(!b||_.pointerId!==b.pointerId)return null;A==="commit"&&$(_);let C=Math.max(1,Math.round(b.startWidth+Number(_.clientX)-b.startX)),f=Math.max(1,Math.round(b.startHeight+Number(_.clientY)-b.startY)),v=H(A,A==="commit"?C:b.startWidth,A==="commit"?f:b.startHeight),F=b.captureTarget,k=b.pointerId;return L(),b=null,F?.releasePointerCapture?.(k),v},cleanup(){if(J)return;J=!0,Y?.disconnect(),L();let _=b?.captureTarget,A=b?.pointerId;b=null,A!==void 0&&_?.releasePointerCapture?.(A),B(),l=null,P.forEach(C=>C.remove()),m.remove()}}}function xn(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function Ko(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Uo({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,setCurrentDocument:i,onBridgeRequestError:s,windowLike:c}){let a=c.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let u=await a.initializeSession({routeId:e.payload.routeId});i?.(u.data.document),On(c,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await a.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await a.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.acknowledgeDocumentVersion?await a.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:jo(u,e.payload.key,c.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let u=await a.execute(e.payload.request),l=o?.()?.routeId;if(u.ok&&l&&a.acknowledgeDocumentVersion&&Ko(e.payload.request)){let d=await a.acknowledgeDocumentVersion(l,u.data.resultVersion);i?.(d.data)}n({type:"response",ok:!0,result:u});return}case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let l=a.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:u}})});r.set(u,l),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let u=e.payload.subscriptionId;r.get(u)?.(),r.delete(u),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(u){s?.(u,e),n({type:"response",ok:!1,error:Zo(u)})}}function jo(e,t,n,r){if(!e.ok)return e;let o=he(n,{key:t},r),i=o?Go(o):null;return i?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...i}}}:e}function Go(e){let t=e.ownerDocument.defaultView;if(!t)return null;let n=t.getComputedStyle(e);return{color:n.color,backgroundColor:n.backgroundColor,borderColor:n.borderColor}}function Yo(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,i=n(),s=()=>{let u=n();u!==i&&(i=u,t())},c=()=>s(),a=()=>s();return e.history.pushState=function(...l){let d=r.apply(this,l);return s(),d},e.history.replaceState=function(...l){let d=o.apply(this,l);return s(),d},e.addEventListener("popstate",c),e.addEventListener("hashchange",a),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",a)}}function Xo(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function et(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function tt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function On(e,t){e.dispatchEvent(new CustomEvent(Tt,{detail:t}))}function Jo(e,t){e.dispatchEvent(new CustomEvent(Pt,{detail:t}))}function Lo(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Qo(e,t){return e.routeId===t}function Nt(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Mn(e){let t=Nt(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Zo(e){let t=Nt(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Mn(t)?"Site edit bridge disconnected":t}function xe(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return/authentication|auth failed|auth rejected|bridge key|session|unauthorized|forbidden|expired/i.test(t)}function Vn(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Bt(e){return So.has(Wn(e))}function ei(e){return Eo.has(Wn(e))}function zn(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:ei(e.tagName),canInsertChild:Bt(e.tagName),canMove:!1,canRemove:!1}}function Wn(e){return e?.trim().toLowerCase()??""}function Cn(e,t){return e.key!==t.key||e.instanceIndex!==t.instanceIndex||e.instanceCount!==t.instanceCount?!1:typeof e.textSegmentIndex=="number"&&typeof t.textSegmentIndex=="number"?e.textSegmentIndex===t.textSegmentIndex:!0}function ti(e,t,n){let r=he(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=ni(r,t.ref.textSegmentIndex);return o?(o.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function ni(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function ri(e,t,n,r,o){let i=Me(e,t,n,r),s=Dt(i);if(!s)return null;let c=s.getAttribute("data-vcp-edit-key")??"",a=pe(e,s,r),u=o?.(a.key)??o?.(c);if(!zn({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let d=oi(e,t,n,s);if(d){let h=si(s,d);if(h!==null)return{element:s,textNode:d,textSegmentIndex:h}}return at(s)?null:{element:s}}function oi(e,t,n,r){let o=ii(e,t,n);return!o||o.parentElement!==r?null:o}function ii(e,t,n){let r=e,i=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(nt(i))return i;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return nt(c)?c:null}function si(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function nt(e){return e?.nodeType===3}function ai(e,t,n){return(typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean))[0]??null}function ci(e,t,n){let r=t;for(;r&&!r.getAttribute("data-site-block-id");)r=r.parentElement;if(!r)return null;let o=r.getAttribute("data-site-block-id")??"",i=r.getAttribute("data-vcp-edit-key")??"";return!o||!i?null:{blockId:o,ref:rt(e,r,n),rect:ve(r.getBoundingClientRect()),targetIsSectionRoot:t===r}}function ui(e,t){return Array.from(e.querySelectorAll("[data-site-block-id]")).filter(n=>{let r=n.parentElement;for(;r;){if(r.getAttribute("data-site-block-id"))return!1;r=r.parentElement}return!!(n.getAttribute("data-site-block-id")&&n.getAttribute("data-vcp-edit-key"))}).map(n=>({element:n,blockId:n.getAttribute("data-site-block-id")??"",ref:rt(e,n,t),rect:ve(n.getBoundingClientRect())})).filter(({rect:n})=>n.width>0&&n.height>0).sort((n,r)=>n.rect.top-r.rect.top||n.rect.left-r.rect.left)}function li(e,t,n){let r=ui(e,n),o=r[0],i=r.at(-1);return!o||!i?null:[{anchorBlockId:o.blockId,anchorRef:o.ref,placement:"before",boundary:{top:o.rect.top,left:o.rect.left,width:o.rect.width}},...r.slice(1).map(c=>({anchorBlockId:c.blockId,anchorRef:c.ref,placement:"before",boundary:{top:c.rect.top,left:c.rect.left,width:c.rect.width}})),{anchorBlockId:i.blockId,anchorRef:i.ref,placement:"after",boundary:{top:i.rect.top+i.rect.height,left:i.rect.left,width:i.rect.width}}].find(({boundary:c})=>t.clientX>=c.left&&t.clientX<=c.left+c.width&&Math.abs(t.clientY-c.top)<=pn)??null}function Me(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let i of o){let s=Dt(i),c=s?.getAttribute("data-vcp-edit-key")??"";if(s&&qn(s,r,c))return s}return null}function Dt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ft(t))return n??t;!di(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ft(e){return e.getAttribute(bo)!==null}function di(e){return pi(e.split("::")[0]??"")}function pi(e){if(!e)return!1;let t=hi(e);return t===Ye||t.startsWith(`${Ye}/`)||t.includes(`/${Ye}/`)||t.endsWith(`/${Ye}`)}function hi(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function pe(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,r);if(o.length<=1)return{key:_n(n,r,0)};let i=o.indexOf(t);return i>=0?{key:_n(n,r,i),instanceIndex:i,instanceCount:o.length}:{key:r}}function rt(e,t,n){return pe(e,t,n)}function he(e,t,n){let r=ot(t.key)??t.key,o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,t.key);if(o.length===0)return null;let i=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,s=(ot(t.key)??t.key)!==t.key;if(i!==null&&!s)return o[i]??null;let c=fi(n,t.key);return c!==null&&c>=0&&c<o.length?o[c]??null:i!==null?o[i]??null:o[0]??null}function _n(e,t,n){return Hn(e,t)[n]?.key??t}function fi(e,t){let n=ot(t);if(!n)return null;let o=Hn(e,n).findIndex(i=>i.key===t);return o>=0?o:null}function Hn(e,t){return(e?.entries??[]).filter(n=>(ot(n.key)??n.key)===t)}function $n(e,t,n){let r=Kn(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function qn(e,t,n){let r=Kn(t,n);return!r||e.tagName.toLowerCase()===r}function Kn(e,t){return null}var mi=2,gi=4;function Un(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&gi)!==0?-1:(r&mi)!==0?1:0})}function ot(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Sn);if(n<0)break;let r=Number(t.slice(n+Sn.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function st(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...wt(n),paddingTop:ie(n?.paddingTop),paddingRight:ie(n?.paddingRight),paddingBottom:ie(n?.paddingBottom),paddingLeft:ie(n?.paddingLeft),borderTopWidth:ie(n?.borderTopWidth),borderRightWidth:ie(n?.borderRightWidth),borderBottomWidth:ie(n?.borderBottomWidth),borderLeftWidth:ie(n?.borderLeftWidth),columnGap:ie(n?.columnGap),rowGap:ie(n?.rowGap)}}function wt(e){return{marginTop:ie(e?.marginTop,!0),marginRight:ie(e?.marginRight,!0),marginBottom:ie(e?.marginBottom,!0),marginLeft:ie(e?.marginLeft,!0)}}function ie(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function Ot(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:ve(n.getBoundingClientRect()),margin:wt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function yi(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>ve(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}var Tn=new WeakMap,Pn=0;function we(e){let t=Tn.get(e);if(t)return t;Pn+=1;let n=`runtime-node-${Pn}`;return Tn.set(e,n),n}function jn(e,t,n){let r=n??e.ownerDocument?.defaultView,o=e.ownerDocument?.defaultView?.getComputedStyle(e),i=ve(t),s=K(r?.scrollX),c=K(r?.scrollY),a=o?.position||"static";return{version:xt,runtimeNodeId:we(e),rect:{viewport:i,document:{top:i.top+c,left:i.left+s,width:i.width,height:i.height}},layout:{position:a,transform:o?.transform||"none",containingBlock:Si(e,a)},scrollContext:{scrollX:s,scrollY:c,viewportWidth:K(r?.innerWidth),viewportHeight:K(r?.innerHeight),scrollContainers:bi(e)}}}function bi(e){let t=e.ownerDocument,n=t?.defaultView,r=[],o=e.parentElement;for(;o;){if(o!==t?.body&&o!==t?.documentElement){let i=n?.getComputedStyle(o),s=i?.overflowX||i?.overflow||"visible",c=i?.overflowY||i?.overflow||"visible",a=K(o.scrollLeft),u=K(o.scrollTop),l=a!==0||An(s)&&K(o.scrollWidth)>K(o.clientWidth),d=u!==0||An(c)&&K(o.scrollHeight)>K(o.clientHeight);(l||d)&&r.push({runtimeNodeId:we(o),scrollLeft:a,scrollTop:u})}o=o.parentElement}return r}function An(e){return["auto","scroll","overlay","hidden"].includes(e)}function Si(e,t){if(t==="fixed"){let r=kn(e.parentElement,!0);return r?{kind:"element",runtimeNodeId:we(r)}:{kind:"viewport"}}if(t==="absolute"){let r=e.offsetParent,o=Ei(r)??kn(e.parentElement,!1);return o?{kind:"element",runtimeNodeId:we(o)}:{kind:"document"}}let n=e.parentElement;return n?{kind:"element",runtimeNodeId:we(n)}:{kind:"document"}}function kn(e,t){let n=e;for(;n;){let r=n.ownerDocument?.defaultView?.getComputedStyle(n);if(!!(r?.transform&&r.transform!=="none")||!!(r?.perspective&&r.perspective!=="none")||!!(r?.filter&&r.filter!=="none")||(r?.willChange??"").split(",").some(i=>["transform","perspective","filter"].includes(i.trim()))||!t&&(r?.position||"static")!=="static")return n;n=n.parentElement}return null}function Ei(e){return e&&typeof e.getBoundingClientRect=="function"?e:null}function de(e,t,n,r="full",o){let i=e.getBoundingClientRect(),s=n?.(t.key)??null,c=e.tagName.toLowerCase(),a=Ve(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([T,B])=>[T,B??""])),attributes:Object.fromEntries(e.getAttributeNames().map(T=>[T,e.getAttribute(T)??""]))}:{},l=zn({operationSummary:s?.operationSummary,tagName:c,fallbackMode:"preview"}),d=Ft(e),h=!0,m=Gn(e)?.getAttribute("data-vcp-edit-key")??null,P=Ot(e),x=jn(e,i,o);return{ref:t,key:t.key,detailLevel:r,tagName:c,...s?{sourceKind:"jsx"}:{},...m?{parentKey:m}:{},...s?.pageCompositionUnitKey?{pageCompositionUnitKey:s.pageCompositionUnitKey}:{},...u,runtimeFlags:{selectable:!0,movable:l.canMove,removable:l.canRemove,textEditable:l.canUpdateText,container:d?!1:!!at(e)||l.canInsertChild||h&&Bt(c)},layoutSnapshot:x,layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:P,childRects:P.map(({rect:T})=>T),spacing:st(e)}}function Nn(e,t,n,r){let o=e.getBoundingClientRect(),i=jn(e,o,n);if(r==="light")return{ref:t,layoutSnapshot:i};if(r==="child-rects")return{ref:t,layoutSnapshot:i,childRects:yi(e)};let s=Ot(e);return{ref:t,layoutSnapshot:i,childBoxes:s,childRects:s.map(({rect:c})=>c),layout:Ve(e),spacing:st(e)}}function Bn(e){let t=e.layout?.display??"",n=e.spacing;return["flex","inline-flex","grid","inline-grid"].includes(t)&&!!(n&&(n.columnGap>0||n.rowGap>0)&&(e.childRects?.length??0)>=2)}function vi(e,t,n,r,o){let i=t,s=Nn(i,n,e,"detailed"),c=Bn(s),a=null,u=null,l="mutation",d=Ce(e),h=d,m=!1,P=!1,x=({reason:Y,sourceEventAt:_,forceEmit:A=!1,includeDetailedGeometry:C=!1})=>{(a===null||(Y==="scroll"?0:1)>=(l==="scroll"?0:1))&&(l=Y,d=_),m=m||A,P=P||C,a===null&&(a=et(e,T))},T=()=>{let Y=Ce(e);a=null;let _=l,A=d,C=m,f=P;m=!1,P=!1;let v=he(e.document,n,r?.()??null);if(!v)return;v!==i&&(H?.unobserve(i),i=v,H?.observe(i),f=!0);let F=f?"detailed":c?"child-rects":"light",k=Nn(i,n,e,F),Q=k.layoutSnapshot.rect.viewport;Q.width<=0||Q.height<=0||!C&&!Ii(s,k)||(s=k,F==="detailed"&&(c=Bn(k)),o(_,k,{sourceEventAt:A,captureStartedAt:Y,capturedAt:Ce(e)}))},B=()=>{u!==null&&(e.clearTimeout(u),u=null)},O=()=>{B(),x({reason:"resize",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},J=()=>{B(),x({reason:"mutation",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},b=()=>{h=Ce(e),x({reason:"scroll",sourceEventAt:h}),B(),u=e.setTimeout(()=>{u=null,x({reason:"scroll",sourceEventAt:h,forceEmit:!0,includeDetailedGeometry:!0})},mo)},L=e.ResizeObserver,H=typeof L=="function"?new L(O):null;H?.observe(i);let $=e.MutationObserver,U=typeof $=="function"?new $(J):null;U?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",O,{passive:!0}),e.addEventListener("scroll",b,{passive:!0});let z=e.visualViewport;return z?.addEventListener?.("resize",O,{passive:!0}),z?.addEventListener?.("scroll",b,{passive:!0}),e.document.addEventListener("scroll",b,{capture:!0,passive:!0}),e.document.addEventListener("load",J,!0),()=>{a!==null&&(tt(e,a),a=null),B(),H?.disconnect(),U?.disconnect(),e.removeEventListener("resize",O),e.removeEventListener("scroll",b),z?.removeEventListener?.("resize",O),z?.removeEventListener?.("scroll",b),e.document.removeEventListener("scroll",b,!0),e.document.removeEventListener("load",J,!0)}}function Ce(e){let t=e.performance;return t&&Number.isFinite(t.timeOrigin)&&typeof t.now=="function"?t.timeOrigin+t.now():Date.now()}function Ii(e,t){return Ri(e.layoutSnapshot,t.layoutSnapshot)||t.childBoxes!==void 0&&Ci(e.childBoxes,t.childBoxes)||t.childRects!==void 0&&_i(e.childRects,t.childRects)||t.layout!==void 0&&At(e.layout,t.layout)||t.spacing!==void 0&&At(e.spacing,t.spacing)}function Ri(e,t){return!e||!t?e!==t:e.version!==t.version||e.runtimeNodeId!==t.runtimeNodeId||it(e.rect.viewport,t.rect.viewport)||it(e.rect.document,t.rect.document)||e.layout.position!==t.layout.position||e.layout.transform!==t.layout.transform||e.layout.containingBlock.kind!==t.layout.containingBlock.kind||e.layout.containingBlock.kind==="element"&&t.layout.containingBlock.kind==="element"&&e.layout.containingBlock.runtimeNodeId!==t.layout.containingBlock.runtimeNodeId||e.scrollContext.scrollX!==t.scrollContext.scrollX||e.scrollContext.scrollY!==t.scrollContext.scrollY||e.scrollContext.viewportWidth!==t.scrollContext.viewportWidth||e.scrollContext.viewportHeight!==t.scrollContext.viewportHeight||xi(e.scrollContext.scrollContainers,t.scrollContext.scrollContainers)}function xi(e,t){return e.length!==t.length||e.some((n,r)=>{let o=t[r];return!o||n.runtimeNodeId!==o.runtimeNodeId||n.scrollLeft!==o.scrollLeft||n.scrollTop!==o.scrollTop})}function Ci(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>{let s=r[i];return!s||it(o.rect,s.rect)||At(o.margin,s.margin)})}function _i(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>it(o,r[i]??o))}function At(e,t){let n=e??{},r=t??{},o=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(o).some(i=>n[i]!==r[i])}function ve(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function it(e,t){return Math.abs(e.top-t.top)>.5||Math.abs(e.left-t.left)>.5||Math.abs(e.width-t.width)>.5||Math.abs(e.height-t.height)>.5}function Ti(e,t,n,r,o,i,s){let c=e.document,a=Me(c,t,n,i);if(!a)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?he(c,o,i):null;if(u&&kt(a,u))return Je(c,a,"self-or-descendant",i,s);if(r==="move"&&u){let x=Ni(c,a,u,i,s);if(x){let T=Ct(x.child,x.targetParent,t,n,"nearest");if(T)return Le(c,x.child,x.targetParent,T,i,s)}}let l=null,d=!1,h=a,m=a.parentElement;for(;m;){if(m.getAttribute("data-vcp-edit-key")){if(u&&kt(m,u))return Je(c,a,"self-or-descendant",i,s);let x=Dn(m,r,s);if(x==="accept"){l={child:h,targetParent:m};break}x==="blocked"&&(d=!0),h=m}m=m.parentElement}let P=Dn(a,r,s);if(P==="accept"){if(l){let x=Ct(l.child,l.targetParent,t,n,"edge");if(x)return Le(c,l.child,l.targetParent,x,i,s)}return Le(c,a,a,Pi(a,t,n),i,s)}if(l){let x=Ct(l.child,l.targetParent,t,n,"nearest");return Le(c,l.child,l.targetParent,x??"after",i,s)}return P==="blocked"||d?Je(c,a,"operation-boundary-blocked",i,s):Je(c,a,"no-accepting-parent",i,s)}function Je(e,t,n,r,o){return{anchorHit:de(t,pe(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Le(e,t,n,r,o,i){let s=de(t,pe(e,t,o),i,"summary"),c=de(n,pe(e,n,o),i,"summary"),a=Ve(n).indicatorOrientation,u=r==="append"||r==="prepend"?Ai(n.getBoundingClientRect(),a,r):ki(t.getBoundingClientRect(),a,r);return{anchorHit:s,targetParentHit:c,relation:r,indicatorOrientation:a,indicatorBounds:u}}function Dn(e,t,n){if(Ft(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":at(e)?"blocked":"not-container";let i=e.tagName.toLowerCase();return Bt(i)?"accept":"not-container"}function Ct(e,t,n,r,o){let i=Ve(t).indicatorOrientation,s=e.getBoundingClientRect(),c=i==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return o==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function Pi(e,t,n){let r=Ve(e).indicatorOrientation,o=e.getBoundingClientRect();return(r==="vertical"?o.width>0?(t-o.left)/o.width:.5:o.height>0?(n-o.top)/o.height:.5)<.5?"prepend":"append"}function Ve(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,i=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(i??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...i?{gridAutoFlow:i}:{},indicatorOrientation:s}}function Ai(e,t,n){if(t==="vertical")return{left:n==="prepend"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="prepend"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function ki(e,t,n){if(t==="vertical")return{left:n==="before"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="before"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function kt(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Ni(e,t,n,r,o){let i=Bi(e,t,n,r,o);if(i)return i;let s=Gn(n);if(!s||t===s)return null;let c=t,a=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==s;)c.getAttribute("data-vcp-edit-key")&&(a=c),c=c.parentElement;return c!==s||!a||a===s||a===n||kt(a,n)?null:{child:a,targetParent:s}}function Bi(e,t,n,r,o){return null}function Gn(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function at(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=at(n);if(r)return r}return null}function Qe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:K(e.scrollX),scrollY:K(e.scrollY),scrollWidth:Math.max(K(t?.scrollWidth),K(n?.scrollWidth),K(e.innerWidth)),scrollHeight:Math.max(K(t?.scrollHeight),K(n?.scrollHeight),K(e.innerHeight)),viewportWidth:K(e.innerWidth),viewportHeight:K(e.innerHeight)}}function Di(e,t){Object.entries(t.attributes??{}).forEach(([r,o])=>{if(o===null){e.removeAttribute(r);return}e.setAttribute(r,o)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,o])=>{if(n.has(r))return;let i=e.style,s=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(o==null||o===""){i.removeProperty(s);return}i.setProperty(s,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,i=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),s=r.value;if(s==null||s===""){o.removeProperty(i);return}o.setProperty(i,String(s),r.priority)})}var Fi=500,Fe=new Map;function wi(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Oi(e,t){if(Fe.size>=Fi){let n=Fe.keys().next().value;n&&Fe.delete(n)}Fe.set(e,t)}var Oe=new Set;function Mi(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,i]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,i));for(let o of Oe)r.has(o)||n?.removeProperty(o);Oe.clear();for(let o of r)Oe.add(o);$i(e,t.stylesheets??[])}function Vi(e){let t=e.documentElement?.style;for(let n of Oe)t?.removeProperty(n);Oe.clear();for(let n of Jn(e))n.remove()}function zi(e,t){let n=Array.from(new Set(t.filter(s=>typeof s=="string"&&s.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,i={};for(let s of n){let c=Yn(o,s);c&&(i[s]=c)}return i}function Yn(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Xn(e,r,n)}function Xn(e,t,n){if(!t)return null;let r=Wi(t);if(!r)return t;let o=Yn(e,r.name,n);return o||(r.fallback?Xn(e,r.fallback,n)??r.fallback:null)}function Wi(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Hi(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let i=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:i||null}}function Hi(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function $i(e,t){let n=new Set(t.filter(i=>typeof i=="string"&&i.length>0)),r=new Map;for(let i of Jn(e)){let s=i.getAttribute("href")??"";if(!n.has(s)||r.has(s)){i.remove();continue}r.set(s,i)}let o=e.head;if(o)for(let i of n){if(r.has(i))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(Fn,"true"),s.setAttribute("href",i),o.appendChild(s)}}function Jn(e){return Array.from(e.querySelectorAll(`link[${Fn}]`))}function qi(e,t,n,r,o={}){let i=o.textNode?Ki(e.document,o.textNode):null;if(o.textNode&&!i)throw new Error("Failed to prepare text segment editor");let s=i?.element??t,c=s.textContent??"",a=i?void 0:t.innerHTML,u=Ui(s),l=!1,d=()=>{e.document.removeEventListener("pointerdown",m,!0),s.removeEventListener("keydown",P),s.removeEventListener("blur",x),s.removeEventListener("input",T),Gi(s,u)},h=B=>{if(l)return;l=!0;let O=s.textContent??"";if(d(),B==="cancel"){i?.restore(c),i||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(i?.restore(O),B==="commit"&&O!==c){o.onCommitSnapshot?.({ref:n,initialText:c,...a!==void 0?{initialHtml:a}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:O}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function m(B){let O=B.target;O&&s.contains(O)||h("commit")}function P(B){if(B.key==="Escape"){B.preventDefault(),h("cancel");return}B.key==="Enter"&&(B.metaKey||B.ctrlKey)&&(B.preventDefault(),h("commit"))}function x(){h("commit")}function T(){r({kind:"text-edit-input",payload:{ref:n,hit:de(t,n,void 0,"full")}})}return ji(s),e.document.addEventListener("pointerdown",m,!0),s.addEventListener("keydown",P),s.addEventListener("blur",x),s.addEventListener("input",T),Ji(s),Li(s,e.document),d}function Ki(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Ui(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function ji(e){Yi(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function Gi(e,t){_t(e,"contenteditable",t.contentEditable),_t(e,"spellcheck",t.spellcheck),_t(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Yi(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function _t(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Xi(e){let t=[e.documentElement,e.body].filter(r=>!!r?.style),n=t.map(r=>({element:r,userSelect:r.style.userSelect}));for(let r of t)r.style.userSelect="none";return()=>{for(let r of n)r.element.style.userSelect=r.userSelect}}function Ji(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Li(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ln(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(e){let t=Number(e);return Number.isFinite(t)?t:0}import Qi from"node:http";import{createHash as rr,randomBytes as Zi,timingSafeEqual as es}from"node:crypto";import zt from"node:path";import{WebSocket as or,WebSocketServer as ts}from"ws";import{createPreviewSiteEditEngineRuntime as ns,openFileHistoryStore as rs}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as os,scanNextAppRouterRoutes as is}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ss}from"@vcp-dev/site-edit-engine/source-watcher";var ct=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as as}from"@vcp-dev/contracts";var cs="127.0.0.1",us=30218,ls="/__vcp/site-edit/bridge",ir=6*1024*1024,ds=ir*2,ps=3e3,Qn=50,Zn="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function za(e){let t=ar(e),n=ur(t),r=cr(),o=r.get(n);if(o)return o;let i=new ut(t);r.set(n,i);try{i.start()}catch(s){throw r.delete(n),i.stop(),s}return i}function sr(e,t,n={}){let r=new ut(ar(t),e,!1,n);return r.start({listen:!1}),r}var ut=class{constructor(t,n=Qi.createServer((i,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ct,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=fs({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new ss({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Qn,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=cr(),n=ur(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??ns)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let s of this.eventListeners)s(i)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=o,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:r,resolvedRouteId:o}=await this.activateRoute(t.routeId),i=r.getDocument(o).data;await this.recordRuntimeVersion(i.version);let s=(await r.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:s}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),o=n.getDocument(r);return await this.recordRuntimeVersion(o.data.version),o},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),o=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,o)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=await this.bindHistorySession(this.options.snapshotId);if(!r.ok)return Mt(r,t);let o=await this.getRuntime().executeOperation(this.normalizeRequest(t));return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion),o}),undo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??rs)(hs({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,o),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??Qn;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of t)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:is(this.options.projectRoot),n=new Map(this.routes.map(o=>[o.routeId,o.entryFile])),r=new Set(t.map(o=>o.routeId));this.routes=t;for(let o of t)n.get(o.routeId)!==o.entryFile&&this.runtime?.registerRoute(o.routeId,o.entryFile);for(let o of n.keys())r.has(o)||this.runtime?.unregisterRoute(o)}resolveRouteId(t){let n=os(t,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function ar(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:zt.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??cs,port:e.port??us,path:e.path??ls,sessionKey:e.sessionKey??vs(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function hs(e){return zt.join(zt.resolve(e.root),er(e.siteId),er(e.snapshotId),rr("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function er(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:rr("sha256").update(e).digest("hex").slice(0,32)}function cr(){let e=globalThis;return e[Zn]??=new Map,e[Zn]}function ur(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Mt(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function fs(e){let t=new ts({maxPayload:ir,noServer:!0}),n=new WeakSet,r=i=>{new Ke({socket:new Wt(i),engine:e.engine,validateOperationRequest:s=>as.safeParse(s).success})},o=(i,s,c)=>{if(!ms(i,e))return;let a=gs(i,e);if(!a){s.write(`HTTP/1.1 401 Unauthorized\r
31
+ `,c.appendChild(m);let P=Wo.map(_=>{let A=s.createElement("div");return A.setAttribute(h,_),A.setAttribute("aria-hidden","true"),a.appendChild(A),A}),x=null,T=null,B=()=>{x?.removeAttribute(d),T?.(),T=null,x=null},O=_=>{B(),x=_,T=Ze(_,o),_.setAttribute(d,"true"),P.forEach(A=>A.style.removeProperty("display"))};O(l);let J=!1,g=null,L=()=>{if(!g||!l)return;let _=(A,C,f)=>{C?l.style.setProperty(A,C,f):l.style.removeProperty(A)};_("width",g.widthValue,g.widthPriority),_("height",g.heightValue,g.heightPriority)},H=(_,A,C)=>g?{version:1,phase:_,sessionId:g.sessionId,pointerId:g.pointerId,edge:g.edge,ref:t,startWidth:g.startWidth,startHeight:g.startHeight,width:A,height:C,baselineStyleDeclarations:[{property:"width",value:g.widthValue||null,...g.widthPriority==="important"?{priority:"important"}:{}},{property:"height",value:g.heightValue||null,...g.heightPriority==="important"?{priority:"important"}:{}}]}:null,$=_=>{if(!g||!l?.isConnected||_.pointerId!==g.pointerId)return!1;let A=Number(_.clientX)-g.startX,C=Number(_.clientY)-g.startY,f=Math.max(1,Math.round(g.startWidth+A)),v=Math.max(1,Math.round(g.startHeight+C));return(g.edge==="e"||g.edge==="se")&&l.style.setProperty("width",`${f}px`,"important"),(g.edge==="s"||g.edge==="se")&&l.style.setProperty("height",`${v}px`,"important"),!0},U=()=>{if(J)return;let _=u();if(_===l&&_?.isConnected)return;L();let A=g?.captureTarget,C=g?.pointerId;g=null,C!==void 0&&A?.releasePointerCapture?.(C),B(),l=_,l?.isConnected?O(l):P.forEach(f=>f.style.setProperty("display","none","important"))},z=e.MutationObserver,Y=typeof z=="function"?new z(U):null;return Y?.observe(s.documentElement,{attributeFilter:["data-vcp-edit-key"],attributes:!0,childList:!0,subtree:!0}),{begin(_,A){if(J||g||!l?.isConnected)return null;let C=l.getBoundingClientRect();return g={sessionId:`resize-${r}-${_.pointerId}`,pointerId:_.pointerId,edge:A,startX:Number(_.clientX),startY:Number(_.clientY),startWidth:C.width,startHeight:C.height,widthValue:l.style.getPropertyValue("width"),widthPriority:l.style.getPropertyPriority("width"),heightValue:l.style.getPropertyValue("height"),heightPriority:l.style.getPropertyPriority("height"),captureTarget:_.target},H("start",C.width,C.height)},update:$,finish(_,A){if(!g||_.pointerId!==g.pointerId)return null;A==="commit"&&$(_);let C=Math.max(1,Math.round(g.startWidth+Number(_.clientX)-g.startX)),f=Math.max(1,Math.round(g.startHeight+Number(_.clientY)-g.startY)),v=H(A,A==="commit"?C:g.startWidth,A==="commit"?f:g.startHeight),F=g.captureTarget,k=g.pointerId;return A==="cancel"&&L(),g=null,F?.releasePointerCapture?.(k),v},cleanup(){if(J)return;J=!0,Y?.disconnect(),L();let _=g?.captureTarget,A=g?.pointerId;g=null,A!==void 0&&_?.releasePointerCapture?.(A),B(),l=null,P.forEach(C=>C.remove()),m.remove()}}}function xn(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function Ko(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Uo({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,setCurrentDocument:i,onBridgeRequestError:s,windowLike:c}){let a=c.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let u=await a.initializeSession({routeId:e.payload.routeId});i?.(u.data.document),On(c,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await a.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await a.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.acknowledgeDocumentVersion?await a.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:jo(u,e.payload.key,c.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let u=await a.execute(e.payload.request),l=o?.()?.routeId;if(u.ok&&l&&a.acknowledgeDocumentVersion&&Ko(e.payload.request)){let d=await a.acknowledgeDocumentVersion(l,u.data.resultVersion);i?.(d.data)}n({type:"response",ok:!0,result:u});return}case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let l=a.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:u}})});r.set(u,l),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let u=e.payload.subscriptionId;r.get(u)?.(),r.delete(u),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(u){s?.(u,e),n({type:"response",ok:!1,error:Zo(u)})}}function jo(e,t,n,r){if(!e.ok)return e;let o=he(n,{key:t},r),i=o?Go(o):null;return i?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...i}}}:e}function Go(e){let t=e.ownerDocument.defaultView;if(!t)return null;let n=t.getComputedStyle(e);return{color:n.color,backgroundColor:n.backgroundColor,borderColor:n.borderColor}}function Yo(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,i=n(),s=()=>{let u=n();u!==i&&(i=u,t())},c=()=>s(),a=()=>s();return e.history.pushState=function(...l){let d=r.apply(this,l);return s(),d},e.history.replaceState=function(...l){let d=o.apply(this,l);return s(),d},e.addEventListener("popstate",c),e.addEventListener("hashchange",a),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",a)}}function Xo(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function et(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function tt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function On(e,t){e.dispatchEvent(new CustomEvent(Tt,{detail:t}))}function Jo(e,t){e.dispatchEvent(new CustomEvent(Pt,{detail:t}))}function Lo(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Qo(e,t){return e.routeId===t}function Nt(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Mn(e){let t=Nt(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Zo(e){let t=Nt(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Mn(t)?"Site edit bridge disconnected":t}function xe(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return/authentication|auth failed|auth rejected|bridge key|session|unauthorized|forbidden|expired/i.test(t)}function Vn(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Bt(e){return So.has(Wn(e))}function ei(e){return Eo.has(Wn(e))}function zn(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:ei(e.tagName),canInsertChild:Bt(e.tagName),canMove:!1,canRemove:!1}}function Wn(e){return e?.trim().toLowerCase()??""}function Cn(e,t){return e.key!==t.key||e.instanceIndex!==t.instanceIndex||e.instanceCount!==t.instanceCount?!1:typeof e.textSegmentIndex=="number"&&typeof t.textSegmentIndex=="number"?e.textSegmentIndex===t.textSegmentIndex:!0}function ti(e,t,n){let r=he(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=ni(r,t.ref.textSegmentIndex);return o?(o.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function ni(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function ri(e,t,n,r,o){let i=Me(e,t,n,r),s=Dt(i);if(!s)return null;let c=s.getAttribute("data-vcp-edit-key")??"",a=pe(e,s,r),u=o?.(a.key)??o?.(c);if(!zn({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let d=oi(e,t,n,s);if(d){let h=si(s,d);if(h!==null)return{element:s,textNode:d,textSegmentIndex:h}}return at(s)?null:{element:s}}function oi(e,t,n,r){let o=ii(e,t,n);return!o||o.parentElement!==r?null:o}function ii(e,t,n){let r=e,i=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(nt(i))return i;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return nt(c)?c:null}function si(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function nt(e){return e?.nodeType===3}function ai(e,t,n){return(typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean))[0]??null}function ci(e,t,n){let r=t;for(;r&&!r.getAttribute("data-site-block-id");)r=r.parentElement;if(!r)return null;let o=r.getAttribute("data-site-block-id")??"",i=r.getAttribute("data-vcp-edit-key")??"";return!o||!i?null:{blockId:o,ref:rt(e,r,n),rect:ve(r.getBoundingClientRect()),targetIsSectionRoot:t===r}}function ui(e,t){return Array.from(e.querySelectorAll("[data-site-block-id]")).filter(n=>{let r=n.parentElement;for(;r;){if(r.getAttribute("data-site-block-id"))return!1;r=r.parentElement}return!!(n.getAttribute("data-site-block-id")&&n.getAttribute("data-vcp-edit-key"))}).map(n=>({element:n,blockId:n.getAttribute("data-site-block-id")??"",ref:rt(e,n,t),rect:ve(n.getBoundingClientRect())})).filter(({rect:n})=>n.width>0&&n.height>0).sort((n,r)=>n.rect.top-r.rect.top||n.rect.left-r.rect.left)}function li(e,t,n){let r=ui(e,n),o=r[0],i=r.at(-1);return!o||!i?null:[{anchorBlockId:o.blockId,anchorRef:o.ref,placement:"before",boundary:{top:o.rect.top,left:o.rect.left,width:o.rect.width}},...r.slice(1).map(c=>({anchorBlockId:c.blockId,anchorRef:c.ref,placement:"before",boundary:{top:c.rect.top,left:c.rect.left,width:c.rect.width}})),{anchorBlockId:i.blockId,anchorRef:i.ref,placement:"after",boundary:{top:i.rect.top+i.rect.height,left:i.rect.left,width:i.rect.width}}].find(({boundary:c})=>t.clientX>=c.left&&t.clientX<=c.left+c.width&&Math.abs(t.clientY-c.top)<=pn)??null}function Me(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let i of o){let s=Dt(i),c=s?.getAttribute("data-vcp-edit-key")??"";if(s&&qn(s,r,c))return s}return null}function Dt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ft(t))return n??t;!di(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ft(e){return e.getAttribute(bo)!==null}function di(e){return pi(e.split("::")[0]??"")}function pi(e){if(!e)return!1;let t=hi(e);return t===Ye||t.startsWith(`${Ye}/`)||t.includes(`/${Ye}/`)||t.endsWith(`/${Ye}`)}function hi(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function pe(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,r);if(o.length<=1)return{key:_n(n,r,0)};let i=o.indexOf(t);return i>=0?{key:_n(n,r,i),instanceIndex:i,instanceCount:o.length}:{key:r}}function rt(e,t,n){return pe(e,t,n)}function he(e,t,n){let r=ot(t.key)??t.key,o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,t.key);if(o.length===0)return null;let i=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,s=(ot(t.key)??t.key)!==t.key;if(i!==null&&!s)return o[i]??null;let c=fi(n,t.key);return c!==null&&c>=0&&c<o.length?o[c]??null:i!==null?o[i]??null:o[0]??null}function _n(e,t,n){return Hn(e,t)[n]?.key??t}function fi(e,t){let n=ot(t);if(!n)return null;let o=Hn(e,n).findIndex(i=>i.key===t);return o>=0?o:null}function Hn(e,t){return(e?.entries??[]).filter(n=>(ot(n.key)??n.key)===t)}function $n(e,t,n){let r=Kn(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function qn(e,t,n){let r=Kn(t,n);return!r||e.tagName.toLowerCase()===r}function Kn(e,t){return null}var mi=2,gi=4;function Un(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&gi)!==0?-1:(r&mi)!==0?1:0})}function ot(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Sn);if(n<0)break;let r=Number(t.slice(n+Sn.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function st(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...wt(n),paddingTop:ie(n?.paddingTop),paddingRight:ie(n?.paddingRight),paddingBottom:ie(n?.paddingBottom),paddingLeft:ie(n?.paddingLeft),borderTopWidth:ie(n?.borderTopWidth),borderRightWidth:ie(n?.borderRightWidth),borderBottomWidth:ie(n?.borderBottomWidth),borderLeftWidth:ie(n?.borderLeftWidth),columnGap:ie(n?.columnGap),rowGap:ie(n?.rowGap)}}function wt(e){return{marginTop:ie(e?.marginTop,!0),marginRight:ie(e?.marginRight,!0),marginBottom:ie(e?.marginBottom,!0),marginLeft:ie(e?.marginLeft,!0)}}function ie(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function Ot(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:ve(n.getBoundingClientRect()),margin:wt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function yi(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>ve(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}var Tn=new WeakMap,Pn=0;function we(e){let t=Tn.get(e);if(t)return t;Pn+=1;let n=`runtime-node-${Pn}`;return Tn.set(e,n),n}function jn(e,t,n){let r=n??e.ownerDocument?.defaultView,o=e.ownerDocument?.defaultView?.getComputedStyle(e),i=ve(t),s=K(r?.scrollX),c=K(r?.scrollY),a=o?.position||"static";return{version:xt,runtimeNodeId:we(e),rect:{viewport:i,document:{top:i.top+c,left:i.left+s,width:i.width,height:i.height}},layout:{position:a,transform:o?.transform||"none",containingBlock:Si(e,a)},scrollContext:{scrollX:s,scrollY:c,viewportWidth:K(r?.innerWidth),viewportHeight:K(r?.innerHeight),scrollContainers:bi(e)}}}function bi(e){let t=e.ownerDocument,n=t?.defaultView,r=[],o=e.parentElement;for(;o;){if(o!==t?.body&&o!==t?.documentElement){let i=n?.getComputedStyle(o),s=i?.overflowX||i?.overflow||"visible",c=i?.overflowY||i?.overflow||"visible",a=K(o.scrollLeft),u=K(o.scrollTop),l=a!==0||An(s)&&K(o.scrollWidth)>K(o.clientWidth),d=u!==0||An(c)&&K(o.scrollHeight)>K(o.clientHeight);(l||d)&&r.push({runtimeNodeId:we(o),scrollLeft:a,scrollTop:u})}o=o.parentElement}return r}function An(e){return["auto","scroll","overlay","hidden"].includes(e)}function Si(e,t){if(t==="fixed"){let r=kn(e.parentElement,!0);return r?{kind:"element",runtimeNodeId:we(r)}:{kind:"viewport"}}if(t==="absolute"){let r=e.offsetParent,o=Ei(r)??kn(e.parentElement,!1);return o?{kind:"element",runtimeNodeId:we(o)}:{kind:"document"}}let n=e.parentElement;return n?{kind:"element",runtimeNodeId:we(n)}:{kind:"document"}}function kn(e,t){let n=e;for(;n;){let r=n.ownerDocument?.defaultView?.getComputedStyle(n);if(!!(r?.transform&&r.transform!=="none")||!!(r?.perspective&&r.perspective!=="none")||!!(r?.filter&&r.filter!=="none")||(r?.willChange??"").split(",").some(i=>["transform","perspective","filter"].includes(i.trim()))||!t&&(r?.position||"static")!=="static")return n;n=n.parentElement}return null}function Ei(e){return e&&typeof e.getBoundingClientRect=="function"?e:null}function de(e,t,n,r="full",o){let i=e.getBoundingClientRect(),s=n?.(t.key)??null,c=e.tagName.toLowerCase(),a=Ve(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([T,B])=>[T,B??""])),attributes:Object.fromEntries(e.getAttributeNames().map(T=>[T,e.getAttribute(T)??""]))}:{},l=zn({operationSummary:s?.operationSummary,tagName:c,fallbackMode:"preview"}),d=Ft(e),h=!0,m=Gn(e)?.getAttribute("data-vcp-edit-key")??null,P=Ot(e),x=jn(e,i,o);return{ref:t,key:t.key,detailLevel:r,tagName:c,...s?{sourceKind:"jsx"}:{},...m?{parentKey:m}:{},...s?.pageCompositionUnitKey?{pageCompositionUnitKey:s.pageCompositionUnitKey}:{},...u,runtimeFlags:{selectable:!0,movable:l.canMove,removable:l.canRemove,textEditable:l.canUpdateText,container:d?!1:!!at(e)||l.canInsertChild||h&&Bt(c)},layoutSnapshot:x,layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:P,childRects:P.map(({rect:T})=>T),spacing:st(e)}}function Nn(e,t,n,r){let o=e.getBoundingClientRect(),i=jn(e,o,n);if(r==="light")return{ref:t,layoutSnapshot:i};if(r==="child-rects")return{ref:t,layoutSnapshot:i,childRects:yi(e)};let s=Ot(e);return{ref:t,layoutSnapshot:i,childBoxes:s,childRects:s.map(({rect:c})=>c),layout:Ve(e),spacing:st(e)}}function Bn(e){let t=e.layout?.display??"",n=e.spacing;return["flex","inline-flex","grid","inline-grid"].includes(t)&&!!(n&&(n.columnGap>0||n.rowGap>0)&&(e.childRects?.length??0)>=2)}function vi(e,t,n,r,o){let i=t,s=Nn(i,n,e,"detailed"),c=Bn(s),a=null,u=null,l="mutation",d=Ce(e),h=d,m=!1,P=!1,x=({reason:Y,sourceEventAt:_,forceEmit:A=!1,includeDetailedGeometry:C=!1})=>{(a===null||(Y==="scroll"?0:1)>=(l==="scroll"?0:1))&&(l=Y,d=_),m=m||A,P=P||C,a===null&&(a=et(e,T))},T=()=>{let Y=Ce(e);a=null;let _=l,A=d,C=m,f=P;m=!1,P=!1;let v=he(e.document,n,r?.()??null);if(!v)return;v!==i&&(H?.unobserve(i),i=v,H?.observe(i),f=!0);let F=f?"detailed":c?"child-rects":"light",k=Nn(i,n,e,F),Q=k.layoutSnapshot.rect.viewport;Q.width<=0||Q.height<=0||!C&&!Ii(s,k)||(s=k,F==="detailed"&&(c=Bn(k)),o(_,k,{sourceEventAt:A,captureStartedAt:Y,capturedAt:Ce(e)}))},B=()=>{u!==null&&(e.clearTimeout(u),u=null)},O=()=>{B(),x({reason:"resize",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},J=()=>{B(),x({reason:"mutation",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},g=()=>{h=Ce(e),x({reason:"scroll",sourceEventAt:h}),B(),u=e.setTimeout(()=>{u=null,x({reason:"scroll",sourceEventAt:h,forceEmit:!0,includeDetailedGeometry:!0})},mo)},L=e.ResizeObserver,H=typeof L=="function"?new L(O):null;H?.observe(i);let $=e.MutationObserver,U=typeof $=="function"?new $(J):null;U?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",O,{passive:!0}),e.addEventListener("scroll",g,{passive:!0});let z=e.visualViewport;return z?.addEventListener?.("resize",O,{passive:!0}),z?.addEventListener?.("scroll",g,{passive:!0}),e.document.addEventListener("scroll",g,{capture:!0,passive:!0}),e.document.addEventListener("load",J,!0),()=>{a!==null&&(tt(e,a),a=null),B(),H?.disconnect(),U?.disconnect(),e.removeEventListener("resize",O),e.removeEventListener("scroll",g),z?.removeEventListener?.("resize",O),z?.removeEventListener?.("scroll",g),e.document.removeEventListener("scroll",g,!0),e.document.removeEventListener("load",J,!0)}}function Ce(e){let t=e.performance;return t&&Number.isFinite(t.timeOrigin)&&typeof t.now=="function"?t.timeOrigin+t.now():Date.now()}function Ii(e,t){return Ri(e.layoutSnapshot,t.layoutSnapshot)||t.childBoxes!==void 0&&Ci(e.childBoxes,t.childBoxes)||t.childRects!==void 0&&_i(e.childRects,t.childRects)||t.layout!==void 0&&At(e.layout,t.layout)||t.spacing!==void 0&&At(e.spacing,t.spacing)}function Ri(e,t){return!e||!t?e!==t:e.version!==t.version||e.runtimeNodeId!==t.runtimeNodeId||it(e.rect.viewport,t.rect.viewport)||it(e.rect.document,t.rect.document)||e.layout.position!==t.layout.position||e.layout.transform!==t.layout.transform||e.layout.containingBlock.kind!==t.layout.containingBlock.kind||e.layout.containingBlock.kind==="element"&&t.layout.containingBlock.kind==="element"&&e.layout.containingBlock.runtimeNodeId!==t.layout.containingBlock.runtimeNodeId||e.scrollContext.scrollX!==t.scrollContext.scrollX||e.scrollContext.scrollY!==t.scrollContext.scrollY||e.scrollContext.viewportWidth!==t.scrollContext.viewportWidth||e.scrollContext.viewportHeight!==t.scrollContext.viewportHeight||xi(e.scrollContext.scrollContainers,t.scrollContext.scrollContainers)}function xi(e,t){return e.length!==t.length||e.some((n,r)=>{let o=t[r];return!o||n.runtimeNodeId!==o.runtimeNodeId||n.scrollLeft!==o.scrollLeft||n.scrollTop!==o.scrollTop})}function Ci(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>{let s=r[i];return!s||it(o.rect,s.rect)||At(o.margin,s.margin)})}function _i(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>it(o,r[i]??o))}function At(e,t){let n=e??{},r=t??{},o=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(o).some(i=>n[i]!==r[i])}function ve(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function it(e,t){return Math.abs(e.top-t.top)>.5||Math.abs(e.left-t.left)>.5||Math.abs(e.width-t.width)>.5||Math.abs(e.height-t.height)>.5}function Ti(e,t,n,r,o,i,s){let c=e.document,a=Me(c,t,n,i);if(!a)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?he(c,o,i):null;if(u&&kt(a,u))return Je(c,a,"self-or-descendant",i,s);if(r==="move"&&u){let x=Ni(c,a,u,i,s);if(x){let T=Ct(x.child,x.targetParent,t,n,"nearest");if(T)return Le(c,x.child,x.targetParent,T,i,s)}}let l=null,d=!1,h=a,m=a.parentElement;for(;m;){if(m.getAttribute("data-vcp-edit-key")){if(u&&kt(m,u))return Je(c,a,"self-or-descendant",i,s);let x=Dn(m,r,s);if(x==="accept"){l={child:h,targetParent:m};break}x==="blocked"&&(d=!0),h=m}m=m.parentElement}let P=Dn(a,r,s);if(P==="accept"){if(l){let x=Ct(l.child,l.targetParent,t,n,"edge");if(x)return Le(c,l.child,l.targetParent,x,i,s)}return Le(c,a,a,Pi(a,t,n),i,s)}if(l){let x=Ct(l.child,l.targetParent,t,n,"nearest");return Le(c,l.child,l.targetParent,x??"after",i,s)}return P==="blocked"||d?Je(c,a,"operation-boundary-blocked",i,s):Je(c,a,"no-accepting-parent",i,s)}function Je(e,t,n,r,o){return{anchorHit:de(t,pe(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Le(e,t,n,r,o,i){let s=de(t,pe(e,t,o),i,"summary"),c=de(n,pe(e,n,o),i,"summary"),a=Ve(n).indicatorOrientation,u=r==="append"||r==="prepend"?Ai(n.getBoundingClientRect(),a,r):ki(t.getBoundingClientRect(),a,r);return{anchorHit:s,targetParentHit:c,relation:r,indicatorOrientation:a,indicatorBounds:u}}function Dn(e,t,n){if(Ft(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":at(e)?"blocked":"not-container";let i=e.tagName.toLowerCase();return Bt(i)?"accept":"not-container"}function Ct(e,t,n,r,o){let i=Ve(t).indicatorOrientation,s=e.getBoundingClientRect(),c=i==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return o==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function Pi(e,t,n){let r=Ve(e).indicatorOrientation,o=e.getBoundingClientRect();return(r==="vertical"?o.width>0?(t-o.left)/o.width:.5:o.height>0?(n-o.top)/o.height:.5)<.5?"prepend":"append"}function Ve(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,i=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(i??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...i?{gridAutoFlow:i}:{},indicatorOrientation:s}}function Ai(e,t,n){if(t==="vertical")return{left:n==="prepend"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="prepend"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function ki(e,t,n){if(t==="vertical")return{left:n==="before"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="before"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function kt(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Ni(e,t,n,r,o){let i=Bi(e,t,n,r,o);if(i)return i;let s=Gn(n);if(!s||t===s)return null;let c=t,a=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==s;)c.getAttribute("data-vcp-edit-key")&&(a=c),c=c.parentElement;return c!==s||!a||a===s||a===n||kt(a,n)?null:{child:a,targetParent:s}}function Bi(e,t,n,r,o){return null}function Gn(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function at(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=at(n);if(r)return r}return null}function Qe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:K(e.scrollX),scrollY:K(e.scrollY),scrollWidth:Math.max(K(t?.scrollWidth),K(n?.scrollWidth),K(e.innerWidth)),scrollHeight:Math.max(K(t?.scrollHeight),K(n?.scrollHeight),K(e.innerHeight)),viewportWidth:K(e.innerWidth),viewportHeight:K(e.innerHeight)}}function Di(e,t){Object.entries(t.attributes??{}).forEach(([r,o])=>{if(o===null){e.removeAttribute(r);return}e.setAttribute(r,o)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,o])=>{if(n.has(r))return;let i=e.style,s=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(o==null||o===""){i.removeProperty(s);return}i.setProperty(s,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,i=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),s=r.value;if(s==null||s===""){o.removeProperty(i);return}o.setProperty(i,String(s),r.priority)})}var Fi=500,Fe=new Map;function wi(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Oi(e,t){if(Fe.size>=Fi){let n=Fe.keys().next().value;n&&Fe.delete(n)}Fe.set(e,t)}var Oe=new Set;function Mi(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,i]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,i));for(let o of Oe)r.has(o)||n?.removeProperty(o);Oe.clear();for(let o of r)Oe.add(o);$i(e,t.stylesheets??[])}function Vi(e){let t=e.documentElement?.style;for(let n of Oe)t?.removeProperty(n);Oe.clear();for(let n of Jn(e))n.remove()}function zi(e,t){let n=Array.from(new Set(t.filter(s=>typeof s=="string"&&s.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,i={};for(let s of n){let c=Yn(o,s);c&&(i[s]=c)}return i}function Yn(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Xn(e,r,n)}function Xn(e,t,n){if(!t)return null;let r=Wi(t);if(!r)return t;let o=Yn(e,r.name,n);return o||(r.fallback?Xn(e,r.fallback,n)??r.fallback:null)}function Wi(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Hi(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let i=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:i||null}}function Hi(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function $i(e,t){let n=new Set(t.filter(i=>typeof i=="string"&&i.length>0)),r=new Map;for(let i of Jn(e)){let s=i.getAttribute("href")??"";if(!n.has(s)||r.has(s)){i.remove();continue}r.set(s,i)}let o=e.head;if(o)for(let i of n){if(r.has(i))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(Fn,"true"),s.setAttribute("href",i),o.appendChild(s)}}function Jn(e){return Array.from(e.querySelectorAll(`link[${Fn}]`))}function qi(e,t,n,r,o={}){let i=o.textNode?Ki(e.document,o.textNode):null;if(o.textNode&&!i)throw new Error("Failed to prepare text segment editor");let s=i?.element??t,c=s.textContent??"",a=i?void 0:t.innerHTML,u=Ui(s),l=!1,d=()=>{e.document.removeEventListener("pointerdown",m,!0),s.removeEventListener("keydown",P),s.removeEventListener("blur",x),s.removeEventListener("input",T),Gi(s,u)},h=B=>{if(l)return;l=!0;let O=s.textContent??"";if(d(),B==="cancel"){i?.restore(c),i||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(i?.restore(O),B==="commit"&&O!==c){o.onCommitSnapshot?.({ref:n,initialText:c,...a!==void 0?{initialHtml:a}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:O}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function m(B){let O=B.target;O&&s.contains(O)||h("commit")}function P(B){if(B.key==="Escape"){B.preventDefault(),h("cancel");return}B.key==="Enter"&&(B.metaKey||B.ctrlKey)&&(B.preventDefault(),h("commit"))}function x(){h("commit")}function T(){r({kind:"text-edit-input",payload:{ref:n,hit:de(t,n,void 0,"full")}})}return ji(s),e.document.addEventListener("pointerdown",m,!0),s.addEventListener("keydown",P),s.addEventListener("blur",x),s.addEventListener("input",T),Ji(s),Li(s,e.document),d}function Ki(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Ui(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function ji(e){Yi(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function Gi(e,t){_t(e,"contenteditable",t.contentEditable),_t(e,"spellcheck",t.spellcheck),_t(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Yi(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function _t(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Xi(e){let t=[e.documentElement,e.body].filter(r=>!!r?.style),n=t.map(r=>({element:r,userSelect:r.style.userSelect}));for(let r of t)r.style.userSelect="none";return()=>{for(let r of n)r.element.style.userSelect=r.userSelect}}function Ji(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Li(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ln(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(e){let t=Number(e);return Number.isFinite(t)?t:0}import Qi from"node:http";import{createHash as rr,randomBytes as Zi,timingSafeEqual as es}from"node:crypto";import zt from"node:path";import{WebSocket as or,WebSocketServer as ts}from"ws";import{createPreviewSiteEditEngineRuntime as ns,openFileHistoryStore as rs}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as os,scanNextAppRouterRoutes as is}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ss}from"@vcp-dev/site-edit-engine/source-watcher";var ct=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as as}from"@vcp-dev/contracts";var cs="127.0.0.1",us=30218,ls="/__vcp/site-edit/bridge",ir=6*1024*1024,ds=ir*2,ps=3e3,Qn=50,Zn="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function za(e){let t=ar(e),n=ur(t),r=cr(),o=r.get(n);if(o)return o;let i=new ut(t);r.set(n,i);try{i.start()}catch(s){throw r.delete(n),i.stop(),s}return i}function sr(e,t,n={}){let r=new ut(ar(t),e,!1,n);return r.start({listen:!1}),r}var ut=class{constructor(t,n=Qi.createServer((i,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ct,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=fs({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new ss({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Qn,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=cr(),n=ur(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??ns)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let s of this.eventListeners)s(i)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=o,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:r,resolvedRouteId:o}=await this.activateRoute(t.routeId),i=r.getDocument(o).data;await this.recordRuntimeVersion(i.version);let s=(await r.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:s}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),o=n.getDocument(r);return await this.recordRuntimeVersion(o.data.version),o},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),o=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,o)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=await this.bindHistorySession(this.options.snapshotId);if(!r.ok)return Mt(r,t);let o=await this.getRuntime().executeOperation(this.normalizeRequest(t));return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion),o}),undo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??rs)(hs({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,o),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??Qn;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of t)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:is(this.options.projectRoot),n=new Map(this.routes.map(o=>[o.routeId,o.entryFile])),r=new Set(t.map(o=>o.routeId));this.routes=t;for(let o of t)n.get(o.routeId)!==o.entryFile&&this.runtime?.registerRoute(o.routeId,o.entryFile);for(let o of n.keys())r.has(o)||this.runtime?.unregisterRoute(o)}resolveRouteId(t){let n=os(t,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function ar(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:zt.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??cs,port:e.port??us,path:e.path??ls,sessionKey:e.sessionKey??vs(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function hs(e){return zt.join(zt.resolve(e.root),er(e.siteId),er(e.snapshotId),rr("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function er(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:rr("sha256").update(e).digest("hex").slice(0,32)}function cr(){let e=globalThis;return e[Zn]??=new Map,e[Zn]}function ur(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Mt(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function fs(e){let t=new ts({maxPayload:ir,noServer:!0}),n=new WeakSet,r=i=>{new Ke({socket:new Wt(i),engine:e.engine,validateOperationRequest:s=>as.safeParse(s).success})},o=(i,s,c)=>{if(!ms(i,e))return;let a=gs(i,e);if(!a){s.write(`HTTP/1.1 401 Unauthorized\r
32
32
  Connection: close\r
33
33
  \r
34
- `),s.destroy();return}a.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,s,c,u=>{t.emit("connection",u,i)})};return e.server.on("upgrade",o),t.on("connection",(i,s)=>{if(n.has(s)){r(i);return}ys(i,e.sessionKey,()=>{r(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var Wt=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===or.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ds){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ms(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function gs(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Vt(e.headers["x-vcp-site-edit-key"]),o=lr(r,t.sessionKey),i=Vt(e.headers.host),s=Vt(e.headers.origin);return i&&!bs(i,t.host,s)?null:s?Es(s,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ys(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ps),o,i=()=>{clearTimeout(r),e.off("message",o),e.off("close",i)},s=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let a=oe.parseMessage(c.toString());if(a.type!=="auth"||!lr(a.payload.key,t)){s();return}i(),e.readyState===or.OPEN&&e.send(oe.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",o),e.on("close",i)}function lr(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&es(n,r)}function bs(e,t,n){let r=nr(e),o=nr(t);return r===o||tr(o)&&tr(r)&&(!n||Ht(n,e))||Ss(o)&&(!n||Ht(n,e))}function Ss(e){return e==="0.0.0.0"||e==="::"}function tr(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Es(e,t,n){return n.includes(e)||(t?Ht(e,t):!1)}function Ht(e,t){try{return new URL(e).host===dr(t)}catch{return!1}}function nr(e){let t=dr(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function dr(e){return e.trim().toLowerCase()}function Vt(e){return Array.isArray(e)?e[0]:e}function vs(){return Zi(32).toString("base64url")}import Is from"node:http";import{existsSync as Te,readFileSync as _e}from"node:fs";import{createRequire as mr}from"node:module";import ze from"node:path";import{basename as gr,dirname as We,join as He}from"node:path";import{fileURLToPath as yr}from"node:url";var Rs="next",xs="127.0.0.1",Cs=3e3,dt="/__vcp/site-edit/bridge",br="/__vcp/site-edit/health",pt="/__vcp/site-edit/client/",_s=`${pt}auto-bootstrap.js`,Sr='data-vcp-site-edit-bootstrap="true"',Ts=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ps="@vcp-dev/site-edit-engine/webpack-loader",As=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ks=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ns=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ya(e={},t={}){let n=t.process??process,r=t.createServer??Is.createServer,o=t.attachBridgeServer??sr,i=t.loadNext??ia,s=ze.resolve(e.projectRoot??process.cwd()),c=e.host??xs,a=e.port??ua(n.env.PORT)??Cs,u=e.bridgePath??dt,l=Vs(u),d=ea(),h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",m=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,P=await i(s),x=Bs(s),T=P({dev:!0,dir:s,hostname:c,port:a,...Ds(x)}),B=T.getRequestHandler(),O=e.siteId??n.env.VCP_SITE_ID??"site_preview",J=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ca(s),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,L=b?.trim()?ze.resolve(b):void 0,H=null,$=r((A,C)=>{Us({basePath:h,bridgePath:u,bridgeHealthPath:l,bridgeSessionKey:d,getBridgeHealth:()=>H?.getHealth()??Gs(u),handle:B,request:A,response:C}).catch(f=>{console.error(f),C.headersSent||(C.statusCode=500),C.end("site edit preview request failed")})}),U=null,z=null,Y=()=>z||(lt(()=>n.off("SIGINT",_)),lt(()=>n.off("SIGTERM",_)),lt(()=>U?.()),U=null,lt(()=>H?.stop()),H=null,z=Promise.allSettled([da($),pa(()=>T.close())]).then(()=>{}),z),_=()=>{Y()};try{return await T.prepare(),H=o($,{...m?{tenantId:m}:{},siteId:O,snapshotId:J,projectRoot:s,basePath:h,host:c,port:a,path:u,sessionKey:d,...L?{historyRoot:L}:{}}),U=Os({server:$,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",_),n.on("SIGTERM",_),await la($,a,c),{bundler:x,close:Y,host:c,port:ha($,a),server:$}}catch(A){throw await Y(),A}}function Bs(e){let t=Fs(e);return t&&ws(t)?"webpack":"turbopack"}function Ds(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Fs(e){for(let t of Ts){let n=He(e,t);if(Te(n))return _e(n,"utf8")}return null}function ws(e){return e.includes(Ps)?!0:As.test(e)&&ks.some(t=>t.test(e))}function Os(e){let t=(n,r,o)=>{Ms(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(i=>{console.error(i),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Ms(e,t){return new URL(e??"/","http://localhost").pathname===t}function Vs(e=dt){if(e===dt)return br;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function zs(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ws()});return`<script type="module" ${Sr}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(_s)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ws(){return{bridge:$t("@vcp-dev/site-edit-bridge"),contracts:$t("@vcp-dev/contracts"),engine:$t("@vcp-dev/site-edit-engine")}}function $t(e){let t=mr(import.meta.url);try{let n=t.resolve(e),r=Hs(n,e);if(!r)return;let o=JSON.parse(_e(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Hs(e,t){let n=ze.parse(e).root,r=We(e);for(;r&&r!==n;){let o=He(r,"package.json");if(Te(o))try{if(JSON.parse(_e(o,"utf8")).name===t)return o}catch{return}r=We(r)}}function $s(e,t){if(e.includes(Sr))return e;let n=zs(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Xa(e,t=We(yr(import.meta.url)),n=Te){return Er(e,t,n)?.path??null}function Er(e,t=We(yr(import.meta.url)),n=Te){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(pt))return null;let o=r.slice(pt.length);if(!Ns.has(o))return null;let i=qt(sa(t),o);if(gr(t)!=="src")return{path:i,requiresTranspile:!1};let s=qt(t,o.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function qs(e,t){let n=Er(e.url);if(!n)return!1;if(!Te(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Ks(_e(n.path,"utf8")):_e(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Ks(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Us({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:i,request:s,response:c}){if(js(s,c,n,o)||await qs(s,c))return;let a=Ys(s),u=Xs(s),l=a||u?Qs(c,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await i(s,c)}catch(d){throw l(),d}}function js(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let i=r();return t.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(i)),!0}function Gs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ys(e){return Js(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Xs(e){return Ls(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Js(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(pt)||t===dt||t===br)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Ls(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Qs(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),i=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(c,a,u)=>(c!==void 0&&n.push(pr(c,hr(a))),fr(a),fr(u),!0),r.end=(c,a,u)=>{let l=typeof c=="function"?void 0:c;l!==void 0&&n.push(pr(l,hr(a))),r.write=i,r.end=s,r.flushHeaders=o;let d=Buffer.concat(n),h=Zs(e,d,t);h!==d&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof a=="function"?a:typeof u=="function"?u:void 0;return m?s(h,m):s(h)},()=>{r.write=i,r.end=s,r.flushHeaders=o}}function Zs(e,t,n){if(ta(e,t))return Buffer.from($s(t.toString("utf8"),n));if(n.patchNextDevChunk&&na(e)){let r=t.toString("utf8"),o=ra(r);if(o!==r)return Buffer.from(o)}return t}function ea(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ta(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function na(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function ra(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
34
+ `),s.destroy();return}a.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,s,c,u=>{t.emit("connection",u,i)})};return e.server.on("upgrade",o),t.on("connection",(i,s)=>{if(n.has(s)){r(i);return}ys(i,e.sessionKey,()=>{r(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var Wt=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===or.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ds){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ms(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function gs(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Vt(e.headers["x-vcp-site-edit-key"]),o=lr(r,t.sessionKey),i=Vt(e.headers.host),s=Vt(e.headers.origin);return i&&!bs(i,t.host,s)?null:s?Es(s,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ys(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ps),o,i=()=>{clearTimeout(r),e.off("message",o),e.off("close",i)},s=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let a=oe.parseMessage(c.toString());if(a.type!=="auth"||!lr(a.payload.key,t)){s();return}i(),e.readyState===or.OPEN&&e.send(oe.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",o),e.on("close",i)}function lr(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&es(n,r)}function bs(e,t,n){let r=nr(e),o=nr(t);return r===o||tr(o)&&tr(r)&&(!n||Ht(n,e))||Ss(o)&&(!n||Ht(n,e))}function Ss(e){return e==="0.0.0.0"||e==="::"}function tr(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Es(e,t,n){return n.includes(e)||(t?Ht(e,t):!1)}function Ht(e,t){try{return new URL(e).host===dr(t)}catch{return!1}}function nr(e){let t=dr(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function dr(e){return e.trim().toLowerCase()}function Vt(e){return Array.isArray(e)?e[0]:e}function vs(){return Zi(32).toString("base64url")}import Is from"node:http";import{existsSync as Te,readFileSync as _e}from"node:fs";import{createRequire as mr}from"node:module";import ze from"node:path";import{basename as gr,dirname as We,join as He}from"node:path";import{fileURLToPath as yr}from"node:url";var Rs="next",xs="127.0.0.1",Cs=3e3,dt="/__vcp/site-edit/bridge",br="/__vcp/site-edit/health",pt="/__vcp/site-edit/client/",_s=`${pt}auto-bootstrap.js`,Sr='data-vcp-site-edit-bootstrap="true"',Ts=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ps="@vcp-dev/site-edit-engine/webpack-loader",As=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ks=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ns=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ya(e={},t={}){let n=t.process??process,r=t.createServer??Is.createServer,o=t.attachBridgeServer??sr,i=t.loadNext??ia,s=ze.resolve(e.projectRoot??process.cwd()),c=e.host??xs,a=e.port??ua(n.env.PORT)??Cs,u=e.bridgePath??dt,l=Vs(u),d=ea(),h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",m=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,P=await i(s),x=Bs(s),T=P({dev:!0,dir:s,hostname:c,port:a,...Ds(x)}),B=T.getRequestHandler(),O=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",J=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ca(s),g=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,L=g?.trim()?ze.resolve(g):void 0,H=null,$=r((A,C)=>{Us({basePath:h,bridgePath:u,bridgeHealthPath:l,bridgeSessionKey:d,getBridgeHealth:()=>H?.getHealth()??Gs(u),handle:B,request:A,response:C}).catch(f=>{console.error(f),C.headersSent||(C.statusCode=500),C.end("site edit preview request failed")})}),U=null,z=null,Y=()=>z||(lt(()=>n.off("SIGINT",_)),lt(()=>n.off("SIGTERM",_)),lt(()=>U?.()),U=null,lt(()=>H?.stop()),H=null,z=Promise.allSettled([da($),pa(()=>T.close())]).then(()=>{}),z),_=()=>{Y()};try{return await T.prepare(),H=o($,{...m?{tenantId:m}:{},siteId:O,snapshotId:J,projectRoot:s,basePath:h,host:c,port:a,path:u,sessionKey:d,...L?{historyRoot:L}:{}}),U=Os({server:$,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",_),n.on("SIGTERM",_),await la($,a,c),{bundler:x,close:Y,host:c,port:ha($,a),server:$}}catch(A){throw await Y(),A}}function Bs(e){let t=Fs(e);return t&&ws(t)?"webpack":"turbopack"}function Ds(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Fs(e){for(let t of Ts){let n=He(e,t);if(Te(n))return _e(n,"utf8")}return null}function ws(e){return e.includes(Ps)?!0:As.test(e)&&ks.some(t=>t.test(e))}function Os(e){let t=(n,r,o)=>{Ms(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(i=>{console.error(i),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Ms(e,t){return new URL(e??"/","http://localhost").pathname===t}function Vs(e=dt){if(e===dt)return br;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function zs(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ws()});return`<script type="module" ${Sr}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(_s)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ws(){return{bridge:$t("@vcp-dev/site-edit-bridge"),contracts:$t("@vcp-dev/contracts"),engine:$t("@vcp-dev/site-edit-engine")}}function $t(e){let t=mr(import.meta.url);try{let n=t.resolve(e),r=Hs(n,e);if(!r)return;let o=JSON.parse(_e(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Hs(e,t){let n=ze.parse(e).root,r=We(e);for(;r&&r!==n;){let o=He(r,"package.json");if(Te(o))try{if(JSON.parse(_e(o,"utf8")).name===t)return o}catch{return}r=We(r)}}function $s(e,t){if(e.includes(Sr))return e;let n=zs(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Xa(e,t=We(yr(import.meta.url)),n=Te){return Er(e,t,n)?.path??null}function Er(e,t=We(yr(import.meta.url)),n=Te){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(pt))return null;let o=r.slice(pt.length);if(!Ns.has(o))return null;let i=qt(sa(t),o);if(gr(t)!=="src")return{path:i,requiresTranspile:!1};let s=qt(t,o.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function qs(e,t){let n=Er(e.url);if(!n)return!1;if(!Te(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Ks(_e(n.path,"utf8")):_e(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Ks(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Us({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:i,request:s,response:c}){if(js(s,c,n,o)||await qs(s,c))return;let a=Ys(s),u=Xs(s),l=a||u?Qs(c,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await i(s,c)}catch(d){throw l(),d}}function js(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let i=r();return t.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(i)),!0}function Gs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ys(e){return Js(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Xs(e){return Ls(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Js(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(pt)||t===dt||t===br)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Ls(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Qs(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),i=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(c,a,u)=>(c!==void 0&&n.push(pr(c,hr(a))),fr(a),fr(u),!0),r.end=(c,a,u)=>{let l=typeof c=="function"?void 0:c;l!==void 0&&n.push(pr(l,hr(a))),r.write=i,r.end=s,r.flushHeaders=o;let d=Buffer.concat(n),h=Zs(e,d,t);h!==d&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof a=="function"?a:typeof u=="function"?u:void 0;return m?s(h,m):s(h)},()=>{r.write=i,r.end=s,r.flushHeaders=o}}function Zs(e,t,n){if(ta(e,t))return Buffer.from($s(t.toString("utf8"),n));if(n.patchNextDevChunk&&na(e)){let r=t.toString("utf8"),o=ra(r);if(o!==r)return Buffer.from(o)}return t}function ea(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ta(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function na(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function ra(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
35
35
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
36
36
  `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,o])=>oa(n,r,o),e)}function oa(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function pr(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function hr(e){return typeof e=="string"?e:void 0}function fr(e){typeof e=="function"&&e()}async function ia(e){let n=mr(He(e,"package.json"))(Rs);return n.default??n}function sa(e){return gr(e)!=="src"?e:qt(aa(e),"dist")}function aa(e){return vr(e)?ze.posix.dirname(e):We(e)}function qt(e,t){return vr(e)?ze.posix.join(e,t):He(e,t)}function vr(e){return e.includes("/")&&!e.includes("\\")}function ca(e){let t=He(e,".vcp/current-snapshot.json");if(!Te(t))return"sandbox_worktree";try{let n=JSON.parse(_e(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function ua(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function la(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}function da(e){return new Promise(t=>{e.close(()=>t())})}function lt(e){try{e()}catch{}}function pa(e){try{return e()}catch(t){return Promise.reject(t)}}function ha(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{ds as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,ir as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,dn as SITE_EDIT_FRAME_RUNTIME_CHANNEL,xt as SITE_EDIT_FRAME_RUNTIME_LAYOUT_SNAPSHOT_VERSION,Ne as SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION,ke as SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION,pn as SITE_EDIT_FRAME_SECTION_GAP_RADIUS_PX,ln as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ut as SiteEditBridgeServer,Ke as SiteEditBridgeSocketServer,oe as SiteEditBridgeTransport,Ue as SiteEditWebSocketClient,Pt as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Tt as VCP_SITE_EDIT_ROUTE_READY_EVENT,un as VCP_WINDOW_MESSAGE_SOURCE,Ia as VCP_WINDOW_MESSAGE_VERSION,Os as attachNextDevUpgradeHandler,sr as attachSiteEditBridgeServer,fs as attachSiteEditWebSocketServer,zs as createSiteEditAutoBootstrapHtmlSnippet,cn as createSiteEditBridge,De as createSiteEditFrameRuntimeMessage,$r as createVcpWindowMessageEnvelope,gt as decodeRenderDocument,mt as encodeRenderDocument,za as ensureSiteEditBridgeServerStarted,$s as injectSiteEditAutoBootstrap,Cr as isCompactRenderDocument,Dr as isDesignerTraceEnabled,mn as isSiteEditFrameRuntimeLayoutSnapshot,hn as isSiteEditFrameRuntimeMessage,qr as isVcpWindowMessageEnvelope,ra as patchNextFirefoxDevChunk,Xs as prepareFirefoxNextDevChunkPatchRequest,Ys as prepareSiteEditHtmlInjectionRequest,Vs as resolveSiteEditBridgeHealthPath,Er as resolveSiteEditClientAsset,Xa as resolveSiteEditClientAssetPath,Bs as resolveSiteEditNextDevBundler,vo as resolveSiteEditRouteId,Ro as resolveSiteEditWebSocketUrl,Fr as sanitizeTracePayload,_a as startSiteEditAutoBootstrap,ko as startSiteEditFrameRuntime,Ya as startSiteEditNextDevServer,me as traceDesignerEvent,Ks as transpileSiteEditClientSource};