@vcp-dev/site-edit-bridge 0.4.7 → 0.4.9

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.
@@ -1 +1 @@
1
- function Ae(e){if(!ut(e))return e;let t=new Map,n=r=>{let s=t.get(r);if(s)return s;let o=e.nodes[r];if(!o)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[o.token];if(typeof i!="string")throw new Error(`Missing compact document token ${o.token}`);let c=`${o.parent===null?"":n(o.parent)}${i}`;return t.set(r,c),c};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function ut(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}var G=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",s=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||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!K(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?K(t.payload)&&typeof t.payload.id=="string":t.type==="event"?K(t.payload)&&K(t.payload.event):t.type==="auth"?K(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?K(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!K(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":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-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return at(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}};function K(e){return typeof e=="object"&&e!==null}function at(e){return K(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"&&K(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&K(e.params)}var lt="vcp:designer:trace",dt="designer_trace",Be="__VCP_DESIGNER_TRACE__";var ft=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function pt(e=globalThis){let t=e;try{if(t.localStorage?.getItem(lt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(dt)==="1"}catch{return!1}}function H(e,t={},n=globalThis){if(!pt(n))return;let r={type:e,timestamp:Date.now(),payload:mt(t)},s=n,o=s[Be]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),s[Be]=o;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function mt(e){return Se(e,0)}function Se(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Se(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,s]of Object.entries(e)){if(ft.test(r)){n[r]="[redacted]";continue}n[r]=Se(s,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===Ee&&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 u=ee(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:r,settled:!1,reject:n};this.connectAttempt=s,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==s||(s.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(c,u)=>{this.cleanupSocket(r,c,u)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==s)){if(this.options.authKey){try{r.send(G.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){i(ee(c,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=c=>{if(this.socket!==r)return;let u=ee(c,"WebSocket failed");i(u,"failed")},r.onmessage=c=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(c.data,r,s,()=>{o()});return}this.handleMessage(c.data)}},r.onclose=c=>{if(this.socket!==r)return;let u=this.intentionalClose,m=new Error(bt(c,{intentional:u}));i(m,u?"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})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}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){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){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!==Ee||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let s=`${t}-${this.sequence+=1}`,o=vt(s,t,n);return H("bridge.request",{id:s,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Oe(n.request,"kind"),documentVersion:Oe(n.request,"documentVersion")}),new Promise((i,c)=>{let u=this.resolveRequestTimeoutMs(t),m=u>0?setTimeout(()=>{let p=this.pending.get(s);p&&(this.pending.delete(s),H("bridge.response",{id:s,kind:t,ok:!1,timedOut:!0}),p.reject(new Error(`Bridge request timed out after ${u}ms: ${t}`)))},u):null;m?.unref?.(),this.pending.set(s,{kind:t,timeout:m,resolve:p=>i(p),reject:c});try{r.send(G.stringifyMessage(o))}catch(p){let h=ee(p,"WebSocket send failed");this.clearPendingRequest(s),c(h),this.cleanupSocket(r,h,"failed")}})}handleAuthHandshakeMessage(t,n,r,s){try{if(G.parseMessage(t).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(o){let i=ee(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=G.parseMessage(t);if(n.type==="event"){for(let s of this.listeners)s(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"){H("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}H("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:St(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Ae(n.payload.result.data)}: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):yt[t]??gt}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let s=this.connectAttempt;this.connectAttempt=null,s.settled||(s.settled=!0,s.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===ht||t.readyState===Ee)&&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 s of this.connectionStatusListeners)s(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)}},ht=0,Ee=1,gt=15e3,yt={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function ee(e,t){return e instanceof Error?e:new Error(t)}function bt(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 Oe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function St(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 Me(e){return new ve(e)}var ve=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,It(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ct(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return Et(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}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 getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let s=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,s.data),s}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let s=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,s.data),s}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}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){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){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.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return H("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){H("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let s=await this.refreshInFlight;if(typeof t!="number"||s.version>=t||this.currentDocument.version>=t)return this.currentDocument}H("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(s=>(this.currentDocument=s.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function Et(e){return e.version===0&&e.rootKeys.length===0}function vt(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};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}}}}function It(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Ct(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var Fe="vcp-window-message";function _t(e){return{source:Fe,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Rt(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===Fe&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Ke="site-edit",qe="frame-runtime";function te(e,t={}){return _t({namespace:Ke,channel:qe,sessionKey:t.sessionKey,body:e})}function We(e){return!Rt(e)||e.namespace!==Ke||e.channel!==qe?!1:typeof e.body?.type=="string"}var _e="vcp-site-edit:route-ready",Re="vcp-site-edit:bridge-status",xt=1e3,Tt="data-vcp-ui-component",Ge="data-vcp-theme-preview",Ve="::repeat-item#",ae="components/ui",kt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Nt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Dt(e,t=""){let n=Xe(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,s=r.startsWith("/")?r:`/${r}`;return s==="/"?"/":s.replace(/\/+$/,"")}function Pt(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 At(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 er(e=window,t={}){let n=At(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Bt({bridgeUrl:n,options:t}),s=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(s?.started){if(Ot(s.signature,r)){await s.syncRoute?.();return}s.cleanup?.()}let o={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},i,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===i,u=t.create_client??(d=>new ue({url:d,authKey:t.bridge_session_key})),m=t.schedule_after_navigation??Ht,p=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},h=()=>Dt(e.location.pathname,t.basePath||""),E=d=>{Gt(e,d)},I=d=>{o.currentDocument=d,o.currentEntriesByKey=new Map((d?.entries??[]).map(g=>[g.key,g]))},k=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},C=(d,g)=>!o.disposed&&g===o.routeSequence&&d===h(),M=async(d,g)=>{let _=o.activeBridge;if(!_)return null;let R=await _.getDocument(d);return C(d,g)&&I(R.data),R.data},N=()=>{k(),I(null);let d=o.activeBridge;o.activeBridge=null,d&&e.__VCP_SITE_EDIT__===d&&delete e.__VCP_SITE_EDIT__;let g=o.activeClient;o.activeClient=null,g?.disconnect()},F=d=>d===i.routeId&&!!o.activeBridge&&!!(o.currentDocument&&zt(o.currentDocument,d))&&wt(o.activeClient),ge=d=>Math.min(xt*2**Math.max(0,d),8e3),J=(d,g,_)=>{if(o.disposed)return;p();let R=ge(_);E({state:"reconnecting",routeId:d,attempt:_,retryInMs:R,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||g!==o.routeSequence)&&ie(_+1).catch(f=>{let l=h();if(d===l){if(z(f)){E({state:"reload-required",routeId:d,attempt:_,messageKey:"studio.errors.previewBridgeReloadRequired"});return}J(d,o.routeSequence,_+1)}})},R)},X=(d,g,_)=>{if(!C(d,g)||o.activeClient===null)return;if(z(_.message)){N(),p(),E({state:"reload-required",routeId:d,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let R=o.activeClient;k(),I(null);let f=o.activeBridge;o.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,R?.disconnect(),J(d,g,0)},se=d=>{let g=h(),_=o.routeSequence;if(!(!C(g,_)||o.activeClient===null)){if(z(d)){N(),p(),E({state:"reload-required",routeId:g,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Je(d)&&X(g,_,{state:"failed",message:ke(d,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Wt(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:d=>o.currentEntriesByKey.get(d)??null,onBridgeRequestError:d=>{se(d)}});let Q=async()=>ie(0),ie=async d=>{if(o.disposed)return;let g=h();if(F(g))return;let _=o.syncInFlight;if(_?.routeId===g)return _.promise;let R=o.routeSequence+1,f=ye(g,R,d);o.syncInFlight={routeId:g,sequence:R,promise:f};try{await f}finally{o.syncInFlight?.promise===f&&(o.syncInFlight=null)}},ye=async(d,g,_)=>{o.routeSequence=g,p(),N(),E({state:_>0?"reconnecting":"connecting",routeId:d,attempt:_,messageKey:_>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let R=u(n),f=!1;o.activeClient=R,o.unsubscribeConnectionStatus=R.subscribeConnectionStatus?.(l=>{f&&(l.state==="closed"||l.state==="failed")&&X(d,g,l)});try{if(await R.connect(),!C(d,g)){R.disconnect();return}let l=Me({routeId:d,client:R,initialDocument:qt(d)});o.activeBridge=l,c()&&(e.__VCP_SITE_EDIT__=l),o.activeClient=R,o.unsubscribeDocument=l.subscribe(x=>{x.type==="site-edit.document.changed"&&x.routeId===d&&M(d,g).catch(()=>{})}),c()&&(i.routeId=d);let a=await M(d,g);if(!C(d,g)){R.disconnect();return}f=!0,E({state:"ready",routeId:d,attempt:_,messageKey:"studio.status.previewReady"}),Pt(e,{documentVersion:a?.version??0,routeId:d,versions:t.runtime_versions}),Yt(e,{routeId:d,version:a?.version??0})}catch(l){if(k(),o.activeClient===R&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,R.disconnect(),I(null),!C(d,g))return;throw E({state:z(l)?"reload-required":"failed",routeId:d,attempt:_,messageKey:z(l)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),l}},be=d=>{if(o.disposed)return;let g=h();if(z(d)){p(),E({state:"reload-required",routeId:g,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}J(g,o.routeSequence,0)},W=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,m(()=>{o.syncScheduled=!1,!o.disposed&&Q().catch(d=>be(d))}))},V=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,p(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),N(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(i={started:!0,signature:r,syncRoute:Q,cleanup:V},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=i,o.unbindBootstrapLifecycle=Ft(e,V),o.unbindRouteChange=$t(e,W,h),t.defer_initial_sync){W();return}await Q()}function Bt(e){return{basePath:Xe(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:Mt(e.options.bridge_session_key)}}function Ot(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Mt(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 Ft(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Kt(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Kt(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function qt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Wt(e=window,t={}){let n=null,r=null,s=null,o=null,i=null,c=null,u=null,m=null,p=null,h=new Map,E=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,I=()=>{n?.(),n=null,r=null},k=()=>{s?.(),s=null,o?.(),o=null},C=(f,l,a)=>{let x=i?.sessionKey!==f||i?.sourceWindow!==l||i?.targetOrigin!==a;i={sessionKey:f,sourceWindow:l,targetOrigin:a},x&&(m=null,p=null)},M=(f,l)=>{let a=e.parent&&e.parent!==e?e.parent:null;return!a||l!==a?!1:!E||f===E},N=()=>{for(let f of h.values())f();h.clear()},F=f=>JSON.stringify([f.routeId,f.version]),ge=()=>!u||u.state==="ready",J=f=>JSON.stringify([f.state,f.routeId??null,f.attempt??null,f.retryInMs??null,f.messageKey??null]),X=f=>{if(!ge())return;let l=F(f);m!==l&&(o?.(),o=null,W({kind:"route-ready",payload:{routeId:f.routeId,version:f.version}}),i&&(m=l))},se=f=>{let l=J(f);p!==l&&(f.state!=="ready"&&(m=null,c=null),W({kind:"bridge-status",payload:f}),i&&(p=l))},Q=f=>{c=f,X(f)},ie=f=>{u=f,se(f)},ye=()=>{c&&X(c)},be=()=>{u&&se(u)},W=f=>{i&&i.sourceWindow.postMessage(te({type:"event",...f},{sessionKey:i.sessionKey}),i.targetOrigin)},V=(f,l,a,x)=>{let T=me(e.document,l.clientX,l.clientY,t.getCurrentDocument?.()??null),D=T?O(T,a==="full"?A(e.document,T,t.getCurrentDocument?.()??null):$e(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,a):null;x&&D&&(f==="pointer-click"||f==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),W({kind:f,payload:{clientX:l.clientX,clientY:l.clientY,buttons:Number(l.buttons??0),hit:D}})},d=(f,l,a)=>{k(),i={sessionKey:f,sourceWindow:l,targetOrigin:a};let x=Wn(e.document),T=null,D=null,y=()=>{D=null;let b=T;T=null,b&&V("pointer-move",b,"summary")},B=b=>{T={clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},D===null&&(D=we(e,y))},$=b=>{V("pointer-down",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},w=b=>{V("pointer-up",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},j=b=>{V("pointer-cancel",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},Y=b=>{V("pointer-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},Z=b=>{V("pointer-double-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},L=()=>{W({kind:"scroll",payload:{metrics:fe(e)}})};e.document.addEventListener("pointerdown",$,!0),e.document.addEventListener("pointermove",B,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",w,!0),e.document.addEventListener("pointercancel",j,!0),e.document.addEventListener("click",Y,!0),e.document.addEventListener("dblclick",Z,!0),e.addEventListener("scroll",L,{passive:!0}),s=()=>{D!==null&&(ze(e,D),D=null),T=null,x(),e.document.removeEventListener("pointerdown",$,!0),e.document.removeEventListener("pointermove",B,!0),e.document.removeEventListener("pointerup",w,!0),e.document.removeEventListener("pointercancel",j,!0),e.document.removeEventListener("click",Y,!0),e.document.removeEventListener("dblclick",Z,!0),e.removeEventListener("scroll",L)}},g=f=>{let l=f.detail;l?.routeId&&Q(l)},_=f=>{let l=f.detail;l?.state&&ie(l)},R=f=>{let l=f.data;if(!We(l)||l.body.type!=="request"||l.body.kind!=="apply-node-patch"&&l.body.kind!=="get-hit-by-ref"&&l.body.kind!=="get-path-by-ref"&&l.body.kind!=="get-scroll-metrics"&&l.body.kind!=="scroll-to"&&l.body.kind!=="scroll-by"&&l.body.kind!=="set-interaction-mode"&&l.body.kind!=="set-theme-override"&&l.body.kind!=="clear-theme-override"&&l.body.kind!=="get-theme-variables"&&l.body.kind!=="compute-drop-target-at-point"&&l.body.kind!=="observe-node-bounds"&&l.body.kind!=="clear-node-bounds-observer"&&l.body.kind!=="restore-text-edit"&&l.body.kind!=="clear-text-edit-rollback"&&l.body.kind!=="start-text-edit-at-point"&&l.body.kind!=="hit-test-at-point"&&!je(l.body))return;let a=l.body,x=typeof l.sessionKey=="string"?l.sessionKey:null,T=f.source,D=f.origin;if(!x||!D||!T||typeof T.postMessage!="function"||!M(x,T))return;if(i){if(i.sourceWindow!==T||i.targetOrigin!==D)return;i.sessionKey!==x&&(I(),k(),N(),i=null)}C(x,T,D),be(),ye();let y=B=>{let $=typeof a.id=="string"?a.id:"unknown";T.postMessage(te({id:$,...B},{sessionKey:x}),D)};try{if(je(a)){Vt({message:a,sendEvent:S=>{T.postMessage(te({type:"event",...S},{sessionKey:x}),D)},sendResponse:y,subscriptions:h,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(a.kind==="apply-node-patch"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for patch target"});return}let v=a.payload.preview,P=v?Rn(v.sessionId,a.payload.ref):null;if(P&&v){let ce=ne.get(P)??-1;if(v.revision<ce){y({type:"response",ok:!0,result:{applied:!1,appliedRevision:v.revision,stale:!0,latestRevision:ce}});return}if(v.revision===ce){y({type:"response",ok:!0,result:{applied:!1,appliedRevision:v.revision,duplicate:!0,latestRevision:ce}});return}}if(Cn(S,a.payload.patch),P&&v&&xn(P,v.revision),v?.responseDetail==="none"){y({type:"response",ok:!0,result:{applied:!0,appliedRevision:v.revision}});return}y({type:"response",ok:!0,result:O(S,A(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,v?.responseDetail??"full")});return}if(a.kind==="get-hit-by-ref"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for hit target"});return}y({type:"response",ok:!0,result:O(S,A(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(a.kind==="get-path-by-ref"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for path target"});return}let v=[],P=S;for(;P;)P.getAttribute("data-vcp-edit-key")&&v.push(O(P,A(e.document,P,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),P=P.parentElement;y({type:"response",ok:!0,result:v.reverse()});return}if(a.kind==="restore-text-edit"||a.kind==="clear-text-edit-rollback"){let S=a.payload.ref;if(a.kind==="clear-text-edit-rollback"){r&&Ue(r.ref,S)&&(r=null),y({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!Ue(r.ref,S)){y({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let v=Qt(e.document,r,t.getCurrentDocument?.()??null);r=null,y(v?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(a.kind==="get-scroll-metrics"){y({type:"response",ok:!0,result:fe(e)});return}if(a.kind==="scroll-to"){let S=Number(a.payload.x),v=Number(a.payload.y);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:S,top:v}),y({type:"response",ok:!0,result:fe(e)});return}if(a.kind==="scroll-by"){let S=Number(a.payload.deltaX),v=Number(a.payload.deltaY);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:S,top:v}),y({type:"response",ok:!0,result:{...fe(e),scrolled:!0}});return}if(a.kind==="set-interaction-mode"){a.payload.enabled?d(x,T,D):i?.sourceWindow===T&&i.targetOrigin===D&&i.sessionKey===x&&k(),y({type:"response",ok:!0,result:{interactionEnabled:a.payload.enabled}});return}if(a.kind==="set-theme-override"){Tn(e.document,a.payload),y({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(a.kind==="clear-theme-override"){kn(e.document),y({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(a.kind==="get-theme-variables"){y({type:"response",ok:!0,result:Nn(e.document,a.payload.names)});return}if(a.kind==="compute-drop-target-at-point"){let S=Number(a.payload?.x),v=Number(a.payload?.y);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid drop target point"});return}y({type:"response",ok:!0,result:hn(e,S,v,a.payload.dragKind,a.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(a.kind==="observe-node-bounds"){let S=a.payload.ref;if(!S){y({type:"response",ok:!1,error:"Missing bounds observer target"});return}let v=U(e.document,S,t.getCurrentDocument?.()??null);if(!v){y({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=pn(e,v,S,t.getDocumentEntry,P=>W({kind:"node-bounds-change",payload:{hit:P}})),y({type:"response",ok:!0,result:{observing:!0}}),W({kind:"node-bounds-change",payload:{hit:O(v,S,t.getDocumentEntry,"summary")}});return}if(a.kind==="clear-node-bounds-observer"){o?.(),o=null,y({type:"response",ok:!0,result:{cleared:!0}});return}if(a.kind!=="hit-test-at-point"&&a.kind!=="start-text-edit-at-point")return;let B=Number(a.payload?.x),$=Number(a.payload?.y);if(!Number.isFinite(B)||!Number.isFinite($)){y({type:"response",ok:!1,error:"Invalid text edit point"});return}let w=a.kind==="hit-test-at-point"?me(e.document,B,$,t.getCurrentDocument?.()??null):Lt(e.document,B,$,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!w){y({type:"response",ok:!1,error:a.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let j=a.kind==="start-text-edit-at-point"?w:null,Y=a.kind==="hit-test-at-point"?w:j.element,Z=a.payload.detailLevel??"full",L=Z==="full"?A(e.document,Y,t.getCurrentDocument?.()??null):$e(e.document,Y,t.getCurrentDocument?.()??null),b=j&&typeof j.textSegmentIndex=="number"?{...L,textSegmentIndex:j.textSegmentIndex}:L,ct=O(Y,b,t.getDocumentEntry,Z);if(a.kind==="hit-test-at-point"){y({type:"response",ok:!0,result:ct});return}I(),n=Bn(e,Y,b,S=>{T.postMessage(te({type:"event",...S},{sessionKey:x}),D)},{...j?.textNode?{textNode:j.textNode}:{},onCommitSnapshot:S=>{r=S}}),y({type:"response",ok:!0,result:{ref:b}})}catch(B){y({type:"response",ok:!1,error:B instanceof Error?B.message:"Failed to start text edit"})}};return e.addEventListener("message",R),e.addEventListener(_e,g),e.addEventListener(Re,_),()=>{I(),k(),i=null,N(),e.removeEventListener("message",R),e.removeEventListener(_e,g),e.removeEventListener(Re,_)}}function je(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||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"}async function Vt({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:s,onBridgeRequestError:o,windowLike:i}){let c=i.__VCP_SITE_EDIT__;if(!c){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await c.getDocument(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}n({type:"response",ok:!0,result:c.ensureDocumentVersion?await c.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await c.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await c.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await c.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await c.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:jt(u,e.payload.key,i.document,s?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await c.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await c.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await c.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":n({type:"response",ok:!0,result:await c.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await c.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await c.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let m=c.subscribe(p=>{t({kind:"bridge-event",payload:{event:p,subscriptionId:u}})});r.set(u,m),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){o?.(u,e),n({type:"response",ok:!1,error:Jt(u)})}}function jt(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let s=U(n,{key:t},r),o=s?Ut(s):null;return o?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...o}}}}:e}function Ut(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 $t(e,t,n=()=>e.location.pathname){let r=e.history.pushState,s=e.history.replaceState,o=n(),i=()=>{let m=n();m!==o&&(o=m,t())},c=()=>i(),u=()=>i();return e.history.pushState=function(...p){let h=r.apply(this,p);return i(),h},e.history.replaceState=function(...p){let h=s.apply(this,p);return i(),h},e.addEventListener("popstate",c),e.addEventListener("hashchange",u),()=>{e.history.pushState=r,e.history.replaceState=s,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",u)}}function Ht(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function we(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ze(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Yt(e,t){e.dispatchEvent(new CustomEvent(_e,{detail:t}))}function Gt(e,t){e.dispatchEvent(new CustomEvent(Re,{detail:t}))}function wt(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function zt(e,t){return e.routeId===t}function ke(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Je(e){let t=ke(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Jt(e){let t=ke(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Je(t)?"Site edit bridge disconnected":t}function z(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 Xe(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Ne(e){return kt.has(Ze(e))}function Xt(e){return Nt.has(Ze(e))}function Qe(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:Xt(e.tagName),canInsertChild:Ne(e.tagName),canMove:!1,canRemove:!1}}function Ze(e){return e?.trim().toLowerCase()??""}function Ue(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 Qt(e,t,n){let r=U(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let s=Zt(r,t.ref.textSegmentIndex);return s?(s.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function Zt(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!pe(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Lt(e,t,n,r,s){let o=me(e,t,n,r),i=Le(o);if(!i)return null;let c=i.getAttribute("data-vcp-edit-key")??"",u=A(e,i,r),m=s?.(u.key)??s?.(c);if(!Qe({operationSummary:m?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;let h=en(e,t,n,i);if(h){let E=nn(i,h);if(E!==null)return{element:i,textNode:h,textSegmentIndex:E}}return(m?.childKeys.length??0)===0?{element:i}:null}function en(e,t,n,r){let s=tn(e,t,n);return!s||s.parentElement!==r?null:s}function tn(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(pe(o))return o;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return pe(c)?c:null}function nn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!pe(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function pe(e){return e?.nodeType===3}function me(e,t,n,r=null){let s=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of s){let i=Le(o),c=i?.getAttribute("data-vcp-edit-key")??"";if(i&&un(i,r,c))return i}return null}function Le(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(De(t))return n??t;!rn(r)&&!n&&(n=t)}t=t.parentElement}return n}function De(e){return e.getAttribute(Tt)!==null}function rn(e){return on(e.split("::")[0]??"")}function on(e){if(!e)return!1;let t=sn(e);return t===ae||t.startsWith(`${ae}/`)||t.includes(`/${ae}/`)||t.endsWith(`/${ae}`)}function sn(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let s of n.split("/"))if(!(!s||s===".")){if(s===".."){r.pop();continue}r.push(s)}return r.join("/")}function A(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",s=et(nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${it(r)}"]`))),n,r);if(s.length<=1)return{key:He(n,r,0)};let o=s.indexOf(t);return o>=0?{key:He(n,r,o),instanceIndex:o,instanceCount:s.length}:{key:r}}function $e(e,t,n){return A(e,t,n)}function U(e,t,n){let r=oe(t.key)??t.key,s=et(nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${it(r)}"]`))),n,t.key);if(s.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<s.length?t.instanceIndex:null,i=(oe(t.key)??t.key)!==t.key;if(o!==null&&!i)return s[o]??null;let c=cn(n,t.key);return c!==null&&c>=0&&c<s.length?s[c]??null:o!==null?s[o]??null:s[0]??null}function He(e,t,n){return Pe(e,t)[n]?.key??t}function cn(e,t){let n=oe(t);if(!n)return null;let s=Pe(e,n).findIndex(o=>o.key===t);return s>=0?s:null}function Pe(e,t){return(e?.entries??[]).filter(n=>(oe(n.key)??n.key)===t)}function et(e,t,n){let r=tt(t,n);return r?e.filter(s=>s.tagName.toLowerCase()===r):e}function un(e,t,n){let r=tt(t,n);return!r||e.tagName.toLowerCase()===r}function tt(e,t){let n=oe(t)??t,s=(e?.entries.find(o=>o.key===t)??Pe(e,n)[0])?.tag.trim();return!s||s!==s.toLowerCase()?null:s}var an=2,ln=4;function nt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&ln)!==0?-1:(r&an)!==0?1:0})}function oe(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Ve);if(n<0)break;let r=Number(t.slice(n+Ve.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function dn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=s=>{let o=Number.parseFloat(s??"");return Number.isFinite(o)&&o>0?o:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function fn(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>xe(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function O(e,t,n,r="full"){let s=e.getBoundingClientRect(),o=n?.(t.key)??null,i=e.tagName.toLowerCase(),c=he(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([I,k])=>[I,k??""])),attributes:Object.fromEntries(e.getAttributeNames().map(I=>[I,e.getAttribute(I)??""]))}:{},m=Qe({operationSummary:o?.operationSummary,tagName:i,fallbackMode:"preview"}),p=De(e),h=!!(o&&/^[A-Z]/.test(o.tag)),E=!o||!h;return{ref:t,key:t.key,detailLevel:r,tagName:i,...o?{sourceKind:h?"component-call":"jsx"}:{},...h&&o?.tag?{componentName:o.tag}:{},...o?.parentKey?{parentKey:o.parentKey}:{},...u,runtimeFlags:{selectable:!0,movable:m.canMove,removable:m.canRemove,textEditable:m.canUpdateText,container:p?!1:(o?.childKeys.length??0)>0||m.canInsertChild||E&&Ne(i)},layout:c,rect:{top:s.top,left:s.left,width:s.width,height:s.height},childRects:fn(e),spacing:dn(e)}}function pn(e,t,n,r,s){let o=xe(t.getBoundingClientRect()),i=null,c=()=>{i===null&&(i=we(e,u))},u=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let k=xe(t.getBoundingClientRect());mn(o,k)&&(o=k,s(O(t,n,r,"summary")))},m=e.ResizeObserver,p=typeof m=="function"?new m(c):null;p?.observe(t);let h=e.MutationObserver,E=typeof h=="function"?new h(c):null;E?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",c,{passive:!0});let I=e.visualViewport;return I?.addEventListener?.("resize",c,{passive:!0}),e.document.addEventListener("load",c,!0),()=>{i!==null&&(ze(e,i),i=null),p?.disconnect(),E?.disconnect(),e.removeEventListener("resize",c),I?.removeEventListener?.("resize",c),e.document.removeEventListener("load",c,!0)}}function xe(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function mn(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 hn(e,t,n,r,s,o,i){let c=e.document,u=me(c,t,n,o);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let m=s?U(c,s,o):null;if(m&&Te(u,m))return le(c,u,"self-or-descendant",o,i);if(r==="move"&&m){let C=Sn(c,u,m,o,i);if(C){let M=Ie(C.child,C.targetParent,t,n,"nearest");if(M)return de(c,C.child,C.targetParent,M,o,i)}}let p=null,h=!1,E=u,I=u.parentElement;for(;I;){if(I.getAttribute("data-vcp-edit-key")){if(m&&Te(I,m))return le(c,u,"self-or-descendant",o,i);let C=Ye(I,r,i);if(C==="accept"){p={child:E,targetParent:I};break}C==="blocked"&&(h=!0),E=I}I=I.parentElement}let k=Ye(u,r,i);if(k==="accept"){if(p){let C=Ie(p.child,p.targetParent,t,n,"edge");if(C)return de(c,p.child,p.targetParent,C,o,i)}return de(c,u,u,gn(u,t,n),o,i)}if(p){let C=Ie(p.child,p.targetParent,t,n,"nearest");return de(c,p.child,p.targetParent,C??"after",o,i)}return k==="blocked"||h?le(c,u,"operation-boundary-blocked",o,i):le(c,u,"no-accepting-parent",o,i)}function le(e,t,n,r,s){return{anchorHit:O(t,A(e,t,r),s,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function de(e,t,n,r,s,o){let i=O(t,A(e,t,s),o,"summary"),c=O(n,A(e,n,s),o,"summary"),u=he(n).indicatorOrientation,m=r==="append"||r==="prepend"?yn(n.getBoundingClientRect(),u,r):bn(t.getBoundingClientRect(),u,r);return{anchorHit:i,targetParentHit:c,relation:r,indicatorOrientation:u,indicatorBounds:m}}function Ye(e,t,n){if(De(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",s=n?.(r)??null;if(s)return s.operationSummary.canInsertChild===!0?"accept":s.childKeys.length>0?"blocked":"not-container";let o=e.tagName.toLowerCase();return Ne(o)?"accept":"not-container"}function Ie(e,t,n,r,s){let o=he(t).indicatorOrientation,i=e.getBoundingClientRect(),c=o==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return s==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function gn(e,t,n){let r=he(e).indicatorOrientation,s=e.getBoundingClientRect();return(r==="vertical"?s.width>0?(t-s.left)/s.width:.5:s.height>0?(n-s.top)/s.height:.5)<.5?"prepend":"append"}function he(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",s=n?.flexDirection,o=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(s??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...s?{flexDirection:s}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:i}}function yn(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 bn(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 Te(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Sn(e,t,n,r,s){let o=En(e,t,n,r,s);if(o)return o;let i=In(n);if(!i||t===i)return null;let c=t,u=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==i;)c.getAttribute("data-vcp-edit-key")&&(u=c),c=c.parentElement;return c!==i||!u||u===i||u===n||Te(u,n)?null:{child:u,targetParent:i}}function En(e,t,n,r,s){if(!s)return null;let o=A(e,n,r),c=s(o.key)?.parentKey??null;if(!c)return null;let m=A(e,t,r).key;for(;m;){let p=s(m);if(!p?.parentKey)return null;if(p.parentKey===c){if(m===o.key||vn(m,o.key,s))return null;let h=U(e,{key:m},r),E=U(e,{key:c},r);return h&&E?{child:h,targetParent:E}:null}m=p.parentKey}return null}function vn(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n(r)?.parentKey}return!1}function In(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function fe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:q(e.scrollX),scrollY:q(e.scrollY),scrollWidth:Math.max(q(t?.scrollWidth),q(n?.scrollWidth),q(e.innerWidth)),scrollHeight:Math.max(q(t?.scrollHeight),q(n?.scrollHeight),q(e.innerHeight)),viewportWidth:q(e.innerWidth),viewportHeight:q(e.innerHeight)}}function Cn(e,t){Object.entries(t.attributes??{}).forEach(([r,s])=>{if(s===null){e.removeAttribute(r);return}e.setAttribute(r,s)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,s])=>{if(n.has(r))return;let o=e.style,i=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(s==null||s===""){o.removeProperty(i);return}o.setProperty(i,String(s))}),t.styleDeclarations?.forEach(r=>{let s=e.style,o=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),i=r.value;if(i==null||i===""){s.removeProperty(o);return}s.setProperty(o,String(i),r.priority)})}var _n=500,ne=new Map;function Rn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function xn(e,t){if(ne.size>=_n){let n=ne.keys().next().value;n&&ne.delete(n)}ne.set(e,t)}var re=new Set;function Tn(e,t){let n=e.documentElement?.style,r=new Set;for(let[s,o]of Object.entries(t.variables??{}))s.startsWith("--")&&(r.add(s),n?.setProperty(s,o));for(let s of re)r.has(s)||n?.removeProperty(s);re.clear();for(let s of r)re.add(s);An(e,t.stylesheets??[])}function kn(e){let t=e.documentElement?.style;for(let n of re)t?.removeProperty(n);re.clear();for(let n of st(e))n.remove()}function Nn(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,s=r?e.defaultView?.getComputedStyle(r):null,o={};for(let i of n){let c=rt(s,i);c&&(o[i]=c)}return o}function rt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return ot(e,r,n)}function ot(e,t,n){if(!t)return null;let r=Dn(t);if(!r)return t;let s=rt(e,r.name,n);return s||(r.fallback?ot(e,r.fallback,n)??r.fallback:null)}function Dn(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Pn(n),s=r>=0?n.slice(0,r).trim():n;if(!s.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:s,fallback:o||null}}function Pn(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 An(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of st(e)){let i=o.getAttribute("href")??"";if(!n.has(i)||r.has(i)){o.remove();continue}r.set(i,o)}let s=e.head;if(s)for(let o of n){if(r.has(o))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(Ge,"true"),i.setAttribute("href",o),s.appendChild(i)}}function st(e){return Array.from(e.querySelectorAll(`link[${Ge}]`))}function Bn(e,t,n,r,s={}){let o=s.textNode?On(e.document,s.textNode):null;if(s.textNode&&!o)throw new Error("Failed to prepare text segment editor");let i=o?.element??t,c=i.textContent??"",u=o?void 0:t.innerHTML,m=Mn(i),p=!1,h=()=>{e.document.removeEventListener("pointerdown",I,!0),i.removeEventListener("keydown",k),i.removeEventListener("blur",C),i.removeEventListener("input",M),Kn(i,m)},E=N=>{if(p)return;p=!0;let F=i.textContent??"";if(h(),N==="cancel"){o?.restore(c),o||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(F),N==="commit"&&F!==c){s.onCommitSnapshot?.({ref:n,initialText:c,...u!==void 0?{initialHtml:u}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:F}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function I(N){let F=N.target;F&&i.contains(F)||E("commit")}function k(N){if(N.key==="Escape"){N.preventDefault(),E("cancel");return}N.key==="Enter"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),E("commit"))}function C(){E("commit")}function M(){r({kind:"text-edit-input",payload:{ref:n,hit:O(t,n,void 0,"full")}})}return Fn(i),e.document.addEventListener("pointerdown",I,!0),i.addEventListener("keydown",k),i.addEventListener("blur",C),i.addEventListener("input",M),Vn(i),jn(i,e.document),h}function On(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(s){t.nodeValue=s,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Mn(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 Fn(e){qn(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 Kn(e,t){Ce(e,"contenteditable",t.contentEditable),Ce(e,"spellcheck",t.spellcheck),Ce(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function qn(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 Ce(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Wn(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 Vn(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function jn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function it(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function q(e){let t=Number(e);return Number.isFinite(t)?t:0}export{Re as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,_e as VCP_SITE_EDIT_ROUTE_READY_EVENT,Dt as resolveSiteEditRouteId,At as resolveSiteEditWebSocketUrl,er as startSiteEditAutoBootstrap,Wt as startSiteEditFrameRuntime};
1
+ function Pe(e){if(!at(e))return e;let t=new Map,n=r=>{let s=t.get(r);if(s)return s;let o=e.nodes[r];if(!o)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[o.token];if(typeof i!="string")throw new Error(`Missing compact document token ${o.token}`);let c=`${o.parent===null?"":n(o.parent)}${i}`;return t.set(r,c),c};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function at(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}var G=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",s=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||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!K(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?K(t.payload)&&typeof t.payload.id=="string":t.type==="event"?K(t.payload)&&K(t.payload.event):t.type==="auth"?K(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?K(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!K(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":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-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return lt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}};function K(e){return typeof e=="object"&&e!==null}function lt(e){return K(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"&&K(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&K(e.params)}var dt="vcp:designer:trace",ft="designer_trace",Ae="__VCP_DESIGNER_TRACE__";var pt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function mt(e=globalThis){let t=e;try{if(t.localStorage?.getItem(dt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(ft)==="1"}catch{return!1}}function H(e,t={},n=globalThis){if(!mt(n))return;let r={type:e,timestamp:Date.now(),payload:ht(t)},s=n,o=s[Ae]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),s[Ae]=o;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function ht(e){return Se(e,0)}function Se(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Se(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,s]of Object.entries(e)){if(pt.test(r)){n[r]="[redacted]";continue}n[r]=Se(s,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===Ee&&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 u=ee(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:r,settled:!1,reject:n};this.connectAttempt=s,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==s||(s.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(c,u)=>{this.cleanupSocket(r,c,u)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==s)){if(this.options.authKey){try{r.send(G.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){i(ee(c,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=c=>{if(this.socket!==r)return;let u=ee(c,"WebSocket failed");i(u,"failed")},r.onmessage=c=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(c.data,r,s,()=>{o()});return}this.handleMessage(c.data)}},r.onclose=c=>{if(this.socket!==r)return;let u=this.intentionalClose,m=new Error(St(c,{intentional:u}));i(m,u?"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})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}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){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){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!==Ee||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let s=`${t}-${this.sequence+=1}`,o=It(s,t,n);return H("bridge.request",{id:s,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Oe(n.request,"kind"),documentVersion:Oe(n.request,"documentVersion")}),new Promise((i,c)=>{let u=this.resolveRequestTimeoutMs(t),m=u>0?setTimeout(()=>{let p=this.pending.get(s);p&&(this.pending.delete(s),H("bridge.response",{id:s,kind:t,ok:!1,timedOut:!0}),p.reject(new Error(`Bridge request timed out after ${u}ms: ${t}`)))},u):null;m?.unref?.(),this.pending.set(s,{kind:t,timeout:m,resolve:p=>i(p),reject:c});try{r.send(G.stringifyMessage(o))}catch(p){let h=ee(p,"WebSocket send failed");this.clearPendingRequest(s),c(h),this.cleanupSocket(r,h,"failed")}})}handleAuthHandshakeMessage(t,n,r,s){try{if(G.parseMessage(t).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(o){let i=ee(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=G.parseMessage(t);if(n.type==="event"){for(let s of this.listeners)s(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"){H("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}H("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Et(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Pe(n.payload.result.data)}: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):bt[t]??yt}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let s=this.connectAttempt;this.connectAttempt=null,s.settled||(s.settled=!0,s.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===gt||t.readyState===Ee)&&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 s of this.connectionStatusListeners)s(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)}},gt=0,Ee=1,yt=15e3,bt={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function ee(e,t){return e instanceof Error?e:new Error(t)}function St(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 Oe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Et(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 Be(e){return new ve(e)}var ve=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Rt(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ct(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return vt(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}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 getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let s=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,s.data),s}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let s=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,s.data),s}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}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){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){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.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return H("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){H("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let s=await this.refreshInFlight;if(typeof t!="number"||s.version>=t||this.currentDocument.version>=t)return this.currentDocument}H("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(s=>(this.currentDocument=s.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function vt(e){return e.version===0&&e.rootKeys.length===0}function It(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};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}}}}function Rt(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Ct(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var Fe="vcp-window-message";function _t(e){return{source:Fe,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function xt(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===Fe&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Me="site-edit",Ke="frame-runtime";function te(e,t={}){return _t({namespace:Me,channel:Ke,sessionKey:t.sessionKey,body:e})}function qe(e){return!xt(e)||e.namespace!==Me||e.channel!==Ke?!1:typeof e.body?.type=="string"}var Ce="vcp-site-edit:route-ready",_e="vcp-site-edit:bridge-status",Tt=1e3,kt="data-vcp-ui-component",Ge="data-vcp-theme-preview",We="::repeat-item#",ae="components/ui",Nt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Dt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Pt(e,t=""){let n=Xe(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,s=r.startsWith("/")?r:`/${r}`;return s==="/"?"/":s.replace(/\/+$/,"")}function At(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 Ot(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 rr(e=window,t={}){let n=Ot(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Bt({bridgeUrl:n,options:t}),s=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(s?.started){if(Ft(s.signature,r)){await s.syncRoute?.();return}s.cleanup?.()}let o={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},i,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===i,u=t.create_client??(d=>new ue({url:d,authKey:t.bridge_session_key})),m=t.schedule_after_navigation??Yt,p=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},h=()=>Pt(e.location.pathname,t.basePath||""),E=d=>{wt(e,d)},I=d=>{o.currentDocument=d,o.currentEntriesByKey=new Map((d?.entries??[]).map(g=>[g.key,g]))},T=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},R=(d,g)=>!o.disposed&&g===o.routeSequence&&d===h(),F=async(d,g)=>{let C=o.activeBridge;if(!C)return null;let _=await C.getDocument(d);return R(d,g)&&I(_.data),_.data},N=()=>{T(),I(null);let d=o.activeBridge;o.activeBridge=null,d&&e.__VCP_SITE_EDIT__===d&&delete e.__VCP_SITE_EDIT__;let g=o.activeClient;o.activeClient=null,g?.disconnect()},M=d=>d===i.routeId&&!!o.activeBridge&&!!(o.currentDocument&&Jt(o.currentDocument,d))&&zt(o.activeClient),ge=d=>Math.min(Tt*2**Math.max(0,d),8e3),J=(d,g,C)=>{if(o.disposed)return;p();let _=ge(C);E({state:"reconnecting",routeId:d,attempt:C,retryInMs:_,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||g!==o.routeSequence)&&ie(C+1).catch(f=>{let l=h();if(d===l){if(z(f)){E({state:"reload-required",routeId:d,attempt:C,messageKey:"studio.errors.previewBridgeReloadRequired"});return}J(d,o.routeSequence,C+1)}})},_)},X=(d,g,C)=>{if(!R(d,g)||o.activeClient===null)return;if(z(C.message)){N(),p(),E({state:"reload-required",routeId:d,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let _=o.activeClient;T(),I(null);let f=o.activeBridge;o.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,_?.disconnect(),J(d,g,0)},se=d=>{let g=h(),C=o.routeSequence;if(!(!R(g,C)||o.activeClient===null)){if(z(d)){N(),p(),E({state:"reload-required",routeId:g,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Je(d)&&X(g,C,{state:"failed",message:Te(d,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Vt(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:d=>o.currentEntriesByKey.get(d)??null,onBridgeRequestError:d=>{se(d)}});let Q=async()=>ie(0),ie=async d=>{if(o.disposed)return;let g=h();if(M(g))return;let C=o.syncInFlight;if(C?.routeId===g)return C.promise;let _=o.routeSequence+1,f=ye(g,_,d);o.syncInFlight={routeId:g,sequence:_,promise:f};try{await f}finally{o.syncInFlight?.promise===f&&(o.syncInFlight=null)}},ye=async(d,g,C)=>{o.routeSequence=g,p(),N(),E({state:C>0?"reconnecting":"connecting",routeId:d,attempt:C,messageKey:C>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let _=u(n),f=!1;o.activeClient=_,o.unsubscribeConnectionStatus=_.subscribeConnectionStatus?.(l=>{f&&(l.state==="closed"||l.state==="failed")&&X(d,g,l)});try{if(await _.connect(),!R(d,g)){_.disconnect();return}let l=Be({routeId:d,client:_,initialDocument:Wt(d)});o.activeBridge=l,c()&&(e.__VCP_SITE_EDIT__=l),o.activeClient=_,o.unsubscribeDocument=l.subscribe(x=>{x.type==="site-edit.document.changed"&&x.routeId===d&&F(d,g).catch(()=>{})}),c()&&(i.routeId=d);let a=await F(d,g);if(!R(d,g)){_.disconnect();return}f=!0,E({state:"ready",routeId:d,attempt:C,messageKey:"studio.status.previewReady"}),At(e,{documentVersion:a?.version??0,routeId:d,versions:t.runtime_versions}),Gt(e,{routeId:d,version:a?.version??0})}catch(l){if(T(),o.activeClient===_&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,_.disconnect(),I(null),!R(d,g))return;throw E({state:z(l)?"reload-required":"failed",routeId:d,attempt:C,messageKey:z(l)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),l}},be=d=>{if(o.disposed)return;let g=h();if(z(d)){p(),E({state:"reload-required",routeId:g,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}J(g,o.routeSequence,0)},W=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,m(()=>{o.syncScheduled=!1,!o.disposed&&Q().catch(d=>be(d))}))},V=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,p(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),N(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(i={started:!0,signature:r,syncRoute:Q,cleanup:V},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=i,o.unbindBootstrapLifecycle=Kt(e,V),o.unbindRouteChange=Ht(e,W,h),t.defer_initial_sync){W();return}await Q()}function Bt(e){return{basePath:Xe(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:Mt(e.options.bridge_session_key)}}function Ft(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Mt(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 Kt(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),qt(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function qt(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Wt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Vt(e=window,t={}){let n=null,r=null,s=null,o=null,i=null,c=null,u=null,m=null,p=null,h=new Map,E=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,I=()=>{n?.(),n=null,r=null},T=()=>{s?.(),s=null,o?.(),o=null},R=(f,l,a)=>{let x=i?.sessionKey!==f||i?.sourceWindow!==l||i?.targetOrigin!==a;i={sessionKey:f,sourceWindow:l,targetOrigin:a},x&&(m=null,p=null)},F=(f,l)=>{let a=e.parent&&e.parent!==e?e.parent:null;return!a||l!==a?!1:!E||f===E},N=()=>{for(let f of h.values())f();h.clear()},M=f=>JSON.stringify([f.routeId,f.version]),ge=()=>!u||u.state==="ready",J=f=>JSON.stringify([f.state,f.routeId??null,f.attempt??null,f.retryInMs??null,f.messageKey??null]),X=f=>{if(!ge())return;let l=M(f);m!==l&&(o?.(),o=null,W({kind:"route-ready",payload:{routeId:f.routeId,version:f.version}}),i&&(m=l))},se=f=>{let l=J(f);p!==l&&(f.state!=="ready"&&(m=null,c=null),W({kind:"bridge-status",payload:f}),i&&(p=l))},Q=f=>{c=f,X(f)},ie=f=>{u=f,se(f)},ye=()=>{c&&X(c)},be=()=>{u&&se(u)},W=f=>{i&&i.sourceWindow.postMessage(te({type:"event",...f},{sessionKey:i.sessionKey}),i.targetOrigin)},V=(f,l,a,x)=>{let k=me(e.document,l.clientX,l.clientY,t.getCurrentDocument?.()??null),D=k?A(k,a==="full"?O(e.document,k,t.getCurrentDocument?.()??null):Ue(e.document,k,t.getCurrentDocument?.()??null),t.getDocumentEntry,a):null;x&&D&&(f==="pointer-click"||f==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),W({kind:f,payload:{clientX:l.clientX,clientY:l.clientY,buttons:Number(l.buttons??0),hit:D}})},d=(f,l,a)=>{T(),i={sessionKey:f,sourceWindow:l,targetOrigin:a};let x=Un(e.document),k=null,D=null,y=()=>{D=null;let b=k;k=null,b&&V("pointer-move",b,"summary")},B=b=>{k={clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},D===null&&(D=we(e,y))},$=b=>{V("pointer-down",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},w=b=>{V("pointer-up",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},j=b=>{V("pointer-cancel",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},Y=b=>{V("pointer-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},Z=b=>{V("pointer-double-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},L=()=>{W({kind:"scroll",payload:{metrics:fe(e)}})};e.document.addEventListener("pointerdown",$,!0),e.document.addEventListener("pointermove",B,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",w,!0),e.document.addEventListener("pointercancel",j,!0),e.document.addEventListener("click",Y,!0),e.document.addEventListener("dblclick",Z,!0),e.addEventListener("scroll",L,{passive:!0}),s=()=>{D!==null&&(ze(e,D),D=null),k=null,x(),e.document.removeEventListener("pointerdown",$,!0),e.document.removeEventListener("pointermove",B,!0),e.document.removeEventListener("pointerup",w,!0),e.document.removeEventListener("pointercancel",j,!0),e.document.removeEventListener("click",Y,!0),e.document.removeEventListener("dblclick",Z,!0),e.removeEventListener("scroll",L)}},g=f=>{let l=f.detail;l?.routeId&&Q(l)},C=f=>{let l=f.detail;l?.state&&ie(l)},_=f=>{let l=f.data;if(!qe(l)||l.body.type!=="request"||l.body.kind!=="apply-node-patch"&&l.body.kind!=="get-hit-by-ref"&&l.body.kind!=="get-path-by-ref"&&l.body.kind!=="get-scroll-metrics"&&l.body.kind!=="scroll-to"&&l.body.kind!=="scroll-by"&&l.body.kind!=="set-interaction-mode"&&l.body.kind!=="set-theme-override"&&l.body.kind!=="clear-theme-override"&&l.body.kind!=="get-theme-variables"&&l.body.kind!=="compute-drop-target-at-point"&&l.body.kind!=="observe-node-bounds"&&l.body.kind!=="clear-node-bounds-observer"&&l.body.kind!=="restore-text-edit"&&l.body.kind!=="clear-text-edit-rollback"&&l.body.kind!=="start-text-edit-at-point"&&l.body.kind!=="hit-test-at-point"&&!Ve(l.body))return;let a=l.body,x=typeof l.sessionKey=="string"?l.sessionKey:null,k=f.source,D=f.origin;if(!x||!D||!k||typeof k.postMessage!="function"||!F(x,k))return;if(i){if(i.sourceWindow!==k||i.targetOrigin!==D)return;i.sessionKey!==x&&(I(),T(),N(),i=null)}R(x,k,D),be(),ye();let y=B=>{let $=typeof a.id=="string"?a.id:"unknown";k.postMessage(te({id:$,...B},{sessionKey:x}),D)};try{if(Ve(a)){jt({message:a,sendEvent:S=>{k.postMessage(te({type:"event",...S},{sessionKey:x}),D)},sendResponse:y,subscriptions:h,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(a.kind==="apply-node-patch"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for patch target"});return}let v=a.payload.preview,P=v?kn(v.sessionId,a.payload.ref):null;if(P&&v){let ce=ne.get(P)??-1;if(v.revision<ce){y({type:"response",ok:!0,result:{applied:!1,appliedRevision:v.revision,stale:!0,latestRevision:ce}});return}if(v.revision===ce){y({type:"response",ok:!0,result:{applied:!1,appliedRevision:v.revision,duplicate:!0,latestRevision:ce}});return}}if(xn(S,a.payload.patch),P&&v&&Nn(P,v.revision),v?.responseDetail==="none"){y({type:"response",ok:!0,result:{applied:!0,appliedRevision:v.revision}});return}y({type:"response",ok:!0,result:A(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,v?.responseDetail??"full")});return}if(a.kind==="get-hit-by-ref"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for hit target"});return}y({type:"response",ok:!0,result:A(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(a.kind==="get-path-by-ref"){let S=U(e.document,a.payload.ref,t.getCurrentDocument?.()??null);if(!S){y({type:"response",ok:!1,error:"No editable element found for path target"});return}let v=[],P=S;for(;P;)P.getAttribute("data-vcp-edit-key")&&v.push(A(P,O(e.document,P,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),P=P.parentElement;y({type:"response",ok:!0,result:v.reverse()});return}if(a.kind==="restore-text-edit"||a.kind==="clear-text-edit-rollback"){let S=a.payload.ref;if(a.kind==="clear-text-edit-rollback"){r&&je(r.ref,S)&&(r=null),y({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!je(r.ref,S)){y({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let v=Zt(e.document,r,t.getCurrentDocument?.()??null);r=null,y(v?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(a.kind==="get-scroll-metrics"){y({type:"response",ok:!0,result:fe(e)});return}if(a.kind==="scroll-to"){let S=Number(a.payload.x),v=Number(a.payload.y);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:S,top:v}),y({type:"response",ok:!0,result:fe(e)});return}if(a.kind==="scroll-by"){let S=Number(a.payload.deltaX),v=Number(a.payload.deltaY);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:S,top:v}),y({type:"response",ok:!0,result:{...fe(e),scrolled:!0}});return}if(a.kind==="set-interaction-mode"){a.payload.enabled?d(x,k,D):i?.sourceWindow===k&&i.targetOrigin===D&&i.sessionKey===x&&T(),y({type:"response",ok:!0,result:{interactionEnabled:a.payload.enabled}});return}if(a.kind==="set-theme-override"){Dn(e.document,a.payload),y({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(a.kind==="clear-theme-override"){Pn(e.document),y({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(a.kind==="get-theme-variables"){y({type:"response",ok:!0,result:An(e.document,a.payload.names)});return}if(a.kind==="compute-drop-target-at-point"){let S=Number(a.payload?.x),v=Number(a.payload?.y);if(!Number.isFinite(S)||!Number.isFinite(v)){y({type:"response",ok:!1,error:"Invalid drop target point"});return}y({type:"response",ok:!0,result:bn(e,S,v,a.payload.dragKind,a.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(a.kind==="observe-node-bounds"){let S=a.payload.ref;if(!S){y({type:"response",ok:!1,error:"Missing bounds observer target"});return}let v=U(e.document,S,t.getCurrentDocument?.()??null);if(!v){y({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=mn(e,v,S,t.getDocumentEntry,P=>W({kind:"node-bounds-change",payload:{hit:P}})),y({type:"response",ok:!0,result:{observing:!0}}),W({kind:"node-bounds-change",payload:{hit:A(v,S,t.getDocumentEntry,"summary")}});return}if(a.kind==="clear-node-bounds-observer"){o?.(),o=null,y({type:"response",ok:!0,result:{cleared:!0}});return}if(a.kind!=="hit-test-at-point"&&a.kind!=="start-text-edit-at-point")return;let B=Number(a.payload?.x),$=Number(a.payload?.y);if(!Number.isFinite(B)||!Number.isFinite($)){y({type:"response",ok:!1,error:"Invalid text edit point"});return}let w=a.kind==="hit-test-at-point"?me(e.document,B,$,t.getCurrentDocument?.()??null):en(e.document,B,$,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!w){y({type:"response",ok:!1,error:a.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let j=a.kind==="start-text-edit-at-point"?w:null,Y=a.kind==="hit-test-at-point"?w:j.element,Z=a.payload.detailLevel??"full",L=Z==="full"?O(e.document,Y,t.getCurrentDocument?.()??null):Ue(e.document,Y,t.getCurrentDocument?.()??null),b=j&&typeof j.textSegmentIndex=="number"?{...L,textSegmentIndex:j.textSegmentIndex}:L,ut=A(Y,b,t.getDocumentEntry,Z);if(a.kind==="hit-test-at-point"){y({type:"response",ok:!0,result:ut});return}I(),n=Mn(e,Y,b,S=>{k.postMessage(te({type:"event",...S},{sessionKey:x}),D)},{...j?.textNode?{textNode:j.textNode}:{},onCommitSnapshot:S=>{r=S}}),y({type:"response",ok:!0,result:{ref:b}})}catch(B){y({type:"response",ok:!1,error:B instanceof Error?B.message:"Failed to start text edit"})}};return e.addEventListener("message",_),e.addEventListener(Ce,g),e.addEventListener(_e,C),()=>{I(),T(),i=null,N(),e.removeEventListener("message",_),e.removeEventListener(Ce,g),e.removeEventListener(_e,C)}}function Ve(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||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"}async function jt({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:s,onBridgeRequestError:o,windowLike:i}){let c=i.__VCP_SITE_EDIT__;if(!c){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await c.getDocument(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}n({type:"response",ok:!0,result:c.ensureDocumentVersion?await c.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await c.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await c.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await c.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await c.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Ut(u,e.payload.key,i.document,s?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await c.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await c.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await c.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":n({type:"response",ok:!0,result:await c.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await c.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await c.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let m=c.subscribe(p=>{t({kind:"bridge-event",payload:{event:p,subscriptionId:u}})});r.set(u,m),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){o?.(u,e),n({type:"response",ok:!1,error:Xt(u)})}}function Ut(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let s=U(n,{key:t},r),o=s?$t(s):null;return o?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...o}}}}:e}function $t(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 Ht(e,t,n=()=>e.location.pathname){let r=e.history.pushState,s=e.history.replaceState,o=n(),i=()=>{let m=n();m!==o&&(o=m,t())},c=()=>i(),u=()=>i();return e.history.pushState=function(...p){let h=r.apply(this,p);return i(),h},e.history.replaceState=function(...p){let h=s.apply(this,p);return i(),h},e.addEventListener("popstate",c),e.addEventListener("hashchange",u),()=>{e.history.pushState=r,e.history.replaceState=s,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",u)}}function Yt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function we(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ze(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Gt(e,t){e.dispatchEvent(new CustomEvent(Ce,{detail:t}))}function wt(e,t){e.dispatchEvent(new CustomEvent(_e,{detail:t}))}function zt(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Jt(e,t){return e.routeId===t}function Te(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Je(e){let t=Te(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Xt(e){let t=Te(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Je(t)?"Site edit bridge disconnected":t}function z(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 Xe(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ke(e){return Nt.has(Ze(e))}function Qt(e){return Dt.has(Ze(e))}function Qe(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:Qt(e.tagName),canInsertChild:ke(e.tagName),canMove:!1,canRemove:!1}}function Ze(e){return e?.trim().toLowerCase()??""}function je(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 Zt(e,t,n){let r=U(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let s=Lt(r,t.ref.textSegmentIndex);return s?(s.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function Lt(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!pe(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function en(e,t,n,r,s){let o=me(e,t,n,r),i=Le(o);if(!i)return null;let c=i.getAttribute("data-vcp-edit-key")??"",u=O(e,i,r),m=s?.(u.key)??s?.(c);if(!Qe({operationSummary:m?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;let h=tn(e,t,n,i);if(h){let E=rn(i,h);if(E!==null)return{element:i,textNode:h,textSegmentIndex:E}}return(m?.childKeys.length??0)===0?{element:i}:null}function tn(e,t,n,r){let s=nn(e,t,n);return!s||s.parentElement!==r?null:s}function nn(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(pe(o))return o;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return pe(c)?c:null}function rn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!pe(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function pe(e){return e?.nodeType===3}function me(e,t,n,r=null){let s=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of s){let i=Le(o),c=i?.getAttribute("data-vcp-edit-key")??"";if(i&&an(i,r,c))return i}return null}function Le(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ne(t))return n??t;!on(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ne(e){return e.getAttribute(kt)!==null}function on(e){return sn(e.split("::")[0]??"")}function sn(e){if(!e)return!1;let t=cn(e);return t===ae||t.startsWith(`${ae}/`)||t.includes(`/${ae}/`)||t.endsWith(`/${ae}`)}function cn(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let s of n.split("/"))if(!(!s||s===".")){if(s===".."){r.pop();continue}r.push(s)}return r.join("/")}function O(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",s=et(nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${ct(r)}"]`))),n,r);if(s.length<=1)return{key:$e(n,r,0)};let o=s.indexOf(t);return o>=0?{key:$e(n,r,o),instanceIndex:o,instanceCount:s.length}:{key:r}}function Ue(e,t,n){return O(e,t,n)}function U(e,t,n){let r=oe(t.key)??t.key,s=et(nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${ct(r)}"]`))),n,t.key);if(s.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<s.length?t.instanceIndex:null,i=(oe(t.key)??t.key)!==t.key;if(o!==null&&!i)return s[o]??null;let c=un(n,t.key);return c!==null&&c>=0&&c<s.length?s[c]??null:o!==null?s[o]??null:s[0]??null}function $e(e,t,n){return De(e,t)[n]?.key??t}function un(e,t){let n=oe(t);if(!n)return null;let s=De(e,n).findIndex(o=>o.key===t);return s>=0?s:null}function De(e,t){return(e?.entries??[]).filter(n=>(oe(n.key)??n.key)===t)}function et(e,t,n){let r=tt(t,n);return r?e.filter(s=>s.tagName.toLowerCase()===r):e}function an(e,t,n){let r=tt(t,n);return!r||e.tagName.toLowerCase()===r}function tt(e,t){let n=oe(t)??t,s=(e?.entries.find(o=>o.key===t)??De(e,n)[0])?.tag.trim();return!s||s!==s.toLowerCase()?null:s}var ln=2,dn=4;function nt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&dn)!==0?-1:(r&ln)!==0?1:0})}function oe(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(We);if(n<0)break;let r=Number(t.slice(n+We.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function fn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=s=>{let o=Number.parseFloat(s??"");return Number.isFinite(o)&&o>0?o:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function pn(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>yn(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function A(e,t,n,r="full"){let s=e.getBoundingClientRect(),o=n?.(t.key)??null,i=e.tagName.toLowerCase(),c=he(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([I,T])=>[I,T??""])),attributes:Object.fromEntries(e.getAttributeNames().map(I=>[I,e.getAttribute(I)??""]))}:{},m=Qe({operationSummary:o?.operationSummary,tagName:i,fallbackMode:"preview"}),p=Ne(e),h=!!(o&&/^[A-Z]/.test(o.tag)),E=!o||!h;return{ref:t,key:t.key,detailLevel:r,tagName:i,...o?{sourceKind:h?"component-call":"jsx"}:{},...h&&o?.tag?{componentName:o.tag}:{},...o?.parentKey?{parentKey:o.parentKey}:{},...u,runtimeFlags:{selectable:!0,movable:m.canMove,removable:m.canRemove,textEditable:m.canUpdateText,container:p?!1:(o?.childKeys.length??0)>0||m.canInsertChild||E&&ke(i)},layout:c,rect:{top:s.top,left:s.left,width:s.width,height:s.height},childRects:pn(e),spacing:fn(e)}}function mn(e,t,n,r,s){let o=A(t,n,r,"summary"),i=null,c=()=>{i===null&&(i=we(e,u))},u=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let T=A(t,n,r,"summary");hn(o,T)&&(o=T,s(T))},m=e.ResizeObserver,p=typeof m=="function"?new m(c):null;p?.observe(t);let h=e.MutationObserver,E=typeof h=="function"?new h(c):null;E?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",c,{passive:!0});let I=e.visualViewport;return I?.addEventListener?.("resize",c,{passive:!0}),e.document.addEventListener("load",c,!0),()=>{i!==null&&(ze(e,i),i=null),p?.disconnect(),E?.disconnect(),e.removeEventListener("resize",c),I?.removeEventListener?.("resize",c),e.document.removeEventListener("load",c,!0)}}function hn(e,t){return rt(e.rect,t.rect)||gn(e.childRects,t.childRects)||He(e.spacing,t.spacing)||He(e.layout,t.layout)}function gn(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((s,o)=>rt(s,r[o]??s))}function He(e,t){let n=e??{},r=t??{},s=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(s).some(o=>n[o]!==r[o])}function yn(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function rt(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 bn(e,t,n,r,s,o,i){let c=e.document,u=me(c,t,n,o);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let m=s?U(c,s,o):null;if(m&&xe(u,m))return le(c,u,"self-or-descendant",o,i);if(r==="move"&&m){let R=In(c,u,m,o,i);if(R){let F=Ie(R.child,R.targetParent,t,n,"nearest");if(F)return de(c,R.child,R.targetParent,F,o,i)}}let p=null,h=!1,E=u,I=u.parentElement;for(;I;){if(I.getAttribute("data-vcp-edit-key")){if(m&&xe(I,m))return le(c,u,"self-or-descendant",o,i);let R=Ye(I,r,i);if(R==="accept"){p={child:E,targetParent:I};break}R==="blocked"&&(h=!0),E=I}I=I.parentElement}let T=Ye(u,r,i);if(T==="accept"){if(p){let R=Ie(p.child,p.targetParent,t,n,"edge");if(R)return de(c,p.child,p.targetParent,R,o,i)}return de(c,u,u,Sn(u,t,n),o,i)}if(p){let R=Ie(p.child,p.targetParent,t,n,"nearest");return de(c,p.child,p.targetParent,R??"after",o,i)}return T==="blocked"||h?le(c,u,"operation-boundary-blocked",o,i):le(c,u,"no-accepting-parent",o,i)}function le(e,t,n,r,s){return{anchorHit:A(t,O(e,t,r),s,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function de(e,t,n,r,s,o){let i=A(t,O(e,t,s),o,"summary"),c=A(n,O(e,n,s),o,"summary"),u=he(n).indicatorOrientation,m=r==="append"||r==="prepend"?En(n.getBoundingClientRect(),u,r):vn(t.getBoundingClientRect(),u,r);return{anchorHit:i,targetParentHit:c,relation:r,indicatorOrientation:u,indicatorBounds:m}}function Ye(e,t,n){if(Ne(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",s=n?.(r)??null;if(s)return s.operationSummary.canInsertChild===!0?"accept":s.childKeys.length>0?"blocked":"not-container";let o=e.tagName.toLowerCase();return ke(o)?"accept":"not-container"}function Ie(e,t,n,r,s){let o=he(t).indicatorOrientation,i=e.getBoundingClientRect(),c=o==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return s==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function Sn(e,t,n){let r=he(e).indicatorOrientation,s=e.getBoundingClientRect();return(r==="vertical"?s.width>0?(t-s.left)/s.width:.5:s.height>0?(n-s.top)/s.height:.5)<.5?"prepend":"append"}function he(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",s=n?.flexDirection,o=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(s??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...s?{flexDirection:s}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:i}}function En(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 vn(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 xe(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function In(e,t,n,r,s){let o=Rn(e,t,n,r,s);if(o)return o;let i=_n(n);if(!i||t===i)return null;let c=t,u=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==i;)c.getAttribute("data-vcp-edit-key")&&(u=c),c=c.parentElement;return c!==i||!u||u===i||u===n||xe(u,n)?null:{child:u,targetParent:i}}function Rn(e,t,n,r,s){if(!s)return null;let o=O(e,n,r),c=s(o.key)?.parentKey??null;if(!c)return null;let m=O(e,t,r).key;for(;m;){let p=s(m);if(!p?.parentKey)return null;if(p.parentKey===c){if(m===o.key||Cn(m,o.key,s))return null;let h=U(e,{key:m},r),E=U(e,{key:c},r);return h&&E?{child:h,targetParent:E}:null}m=p.parentKey}return null}function Cn(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n(r)?.parentKey}return!1}function _n(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function fe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:q(e.scrollX),scrollY:q(e.scrollY),scrollWidth:Math.max(q(t?.scrollWidth),q(n?.scrollWidth),q(e.innerWidth)),scrollHeight:Math.max(q(t?.scrollHeight),q(n?.scrollHeight),q(e.innerHeight)),viewportWidth:q(e.innerWidth),viewportHeight:q(e.innerHeight)}}function xn(e,t){Object.entries(t.attributes??{}).forEach(([r,s])=>{if(s===null){e.removeAttribute(r);return}e.setAttribute(r,s)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,s])=>{if(n.has(r))return;let o=e.style,i=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(s==null||s===""){o.removeProperty(i);return}o.setProperty(i,String(s))}),t.styleDeclarations?.forEach(r=>{let s=e.style,o=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),i=r.value;if(i==null||i===""){s.removeProperty(o);return}s.setProperty(o,String(i),r.priority)})}var Tn=500,ne=new Map;function kn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Nn(e,t){if(ne.size>=Tn){let n=ne.keys().next().value;n&&ne.delete(n)}ne.set(e,t)}var re=new Set;function Dn(e,t){let n=e.documentElement?.style,r=new Set;for(let[s,o]of Object.entries(t.variables??{}))s.startsWith("--")&&(r.add(s),n?.setProperty(s,o));for(let s of re)r.has(s)||n?.removeProperty(s);re.clear();for(let s of r)re.add(s);Fn(e,t.stylesheets??[])}function Pn(e){let t=e.documentElement?.style;for(let n of re)t?.removeProperty(n);re.clear();for(let n of it(e))n.remove()}function An(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,s=r?e.defaultView?.getComputedStyle(r):null,o={};for(let i of n){let c=ot(s,i);c&&(o[i]=c)}return o}function ot(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return st(e,r,n)}function st(e,t,n){if(!t)return null;let r=On(t);if(!r)return t;let s=ot(e,r.name,n);return s||(r.fallback?st(e,r.fallback,n)??r.fallback:null)}function On(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Bn(n),s=r>=0?n.slice(0,r).trim():n;if(!s.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:s,fallback:o||null}}function Bn(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 Fn(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of it(e)){let i=o.getAttribute("href")??"";if(!n.has(i)||r.has(i)){o.remove();continue}r.set(i,o)}let s=e.head;if(s)for(let o of n){if(r.has(o))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(Ge,"true"),i.setAttribute("href",o),s.appendChild(i)}}function it(e){return Array.from(e.querySelectorAll(`link[${Ge}]`))}function Mn(e,t,n,r,s={}){let o=s.textNode?Kn(e.document,s.textNode):null;if(s.textNode&&!o)throw new Error("Failed to prepare text segment editor");let i=o?.element??t,c=i.textContent??"",u=o?void 0:t.innerHTML,m=qn(i),p=!1,h=()=>{e.document.removeEventListener("pointerdown",I,!0),i.removeEventListener("keydown",T),i.removeEventListener("blur",R),i.removeEventListener("input",F),Vn(i,m)},E=N=>{if(p)return;p=!0;let M=i.textContent??"";if(h(),N==="cancel"){o?.restore(c),o||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(M),N==="commit"&&M!==c){s.onCommitSnapshot?.({ref:n,initialText:c,...u!==void 0?{initialHtml:u}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:M}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function I(N){let M=N.target;M&&i.contains(M)||E("commit")}function T(N){if(N.key==="Escape"){N.preventDefault(),E("cancel");return}N.key==="Enter"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),E("commit"))}function R(){E("commit")}function F(){r({kind:"text-edit-input",payload:{ref:n,hit:A(t,n,void 0,"full")}})}return Wn(i),e.document.addEventListener("pointerdown",I,!0),i.addEventListener("keydown",T),i.addEventListener("blur",R),i.addEventListener("input",F),$n(i),Hn(i,e.document),h}function Kn(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(s){t.nodeValue=s,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function qn(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 Wn(e){jn(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 Vn(e,t){Re(e,"contenteditable",t.contentEditable),Re(e,"spellcheck",t.spellcheck),Re(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function jn(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 Re(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Un(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 $n(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Hn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function ct(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function q(e){let t=Number(e);return Number.isFinite(t)?t:0}export{_e as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Ce as VCP_SITE_EDIT_ROUTE_READY_EVENT,Pt as resolveSiteEditRouteId,Ot as resolveSiteEditWebSocketUrl,rr as startSiteEditAutoBootstrap,Vt as startSiteEditFrameRuntime};
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- function Ye(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let c=t.get(a);if(typeof c=="number")return c;let u=n.length;return n.push(a),t.set(a,u),u},i=a=>{let c=null;for(let u of Jt(a)){let f=`${c??"root"}\0${u}`,m=r.get(f);if(typeof m=="number"){c=m;continue}let g=o.length;o.push({parent:c,token:s(u)}),r.set(f,g),c=g}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,tokens:n,nodes:o,rootKeyNodeIds:e.rootKeys.map(i),entries:e.entries.map(a=>({keyNodeId:i(a.key),tag:a.tag,label:a.label,parentKeyNodeId:a.parentKey?i(a.parentKey):null,childKeyNodeIds:a.childKeys.map(i),operationSummary:a.operationSummary}))}}function Xe(e){if(!zt(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let a=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,a),a};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function zt(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Jt(e){if(!e)return[];let t=[],n=0,r=Je(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=Je(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 Je(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var B=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==="get-document"||t==="get-object-summary"||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!q(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?q(t.payload)&&typeof t.payload.id=="string":t.type==="event"?q(t.payload)&&q(t.payload.event):t.type==="auth"?q(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?q(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!q(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":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-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Yt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},fe=class{constructor(t){this.options=t,this.messageQueue=new Pe,this.eventDispatcher=new ke(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"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Ye((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,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=B.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(t){try{await this.handleMessage(B.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Xt(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(B.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:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ke=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)})}},Pe=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 q(e){return typeof e=="object"&&e!==null}function Yt(e){return q(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"&&q(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&q(e.params)}function Xt(e){try{return B.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Qt="vcp:designer:trace",Zt="designer_trace",Qe="__VCP_DESIGNER_TRACE__";var Lt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function en(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Qt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Zt)==="1"}catch{return!1}}function $(e,t={},n=globalThis){if(!en(n))return;let r={type:e,timestamp:Date.now(),payload:tn(t)},o=n,s=o[Qe]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Qe]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function tn(e){return Ne(e,0)}function Ne(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Ne(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Lt.test(r)){n[r]="[redacted]";continue}n[r]=Ne(o,t+1)}return n}var pe=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===De&&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(a){let c=ne(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let s=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(B.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(ne(a,"WebSocket auth failed"),"failed")}return}s()}},r.onerror=a=>{if(this.socket!==r)return;let c=ne(a,"WebSocket failed");i(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,r,o,()=>{s()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let c=this.intentionalClose,u=new Error(sn(a,{intentional:c}));i(u,c?"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})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}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){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){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!==De||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}`,s=un(o,t,n);return $("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Ze(n.request,"kind"),documentVersion:Ze(n.request,"documentVersion")}),new Promise((i,a)=>{let c=this.resolveRequestTimeoutMs(t),u=c>0?setTimeout(()=>{let f=this.pending.get(o);f&&(this.pending.delete(o),$("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),f.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:f=>i(f),reject:a});try{r.send(B.stringifyMessage(s))}catch(f){let m=ne(f,"WebSocket send failed");this.clearPendingRequest(o),a(m),this.cleanupSocket(r,m,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(B.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(s){let i=ne(s,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=B.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"){$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:an(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Xe(n.payload.result.data)}: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):on[t]??rn}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===nn||t.readyState===De)&&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)}},nn=0,De=1,rn=15e3,on={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function ne(e,t){return e instanceof Error?e:new Error(t)}function sn(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 Ze(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function an(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 Le(e){return new Be(e)}var Be=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,ln(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,dn(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return cn(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}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 getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}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){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){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.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return $("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){$("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}$("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.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function cn(e){return e.version===0&&e.rootKeys.length===0}function un(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};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}}}}function ln(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function dn(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var et="vcp-window-message",Xo=1;function fn(e){return{source:et,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function pn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===et&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var tt="site-edit",nt="frame-runtime";function re(e,t={}){return fn({namespace:tt,channel:nt,sessionKey:t.sessionKey,body:e})}function rt(e){return!pn(e)||e.namespace!==tt||e.channel!==nt?!1:typeof e.body?.type=="string"}var Fe="vcp-site-edit:route-ready",Me="vcp-site-edit:bridge-status",hn=1e3,mn="data-vcp-ui-component",lt="data-vcp-theme-preview",ot="::repeat-item#",he="components/ui",gn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),yn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function bn(e,t=""){let n=ht(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function Sn(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 En(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 es(e=window,t={}){let n=En(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=vn({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(In(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let s={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},i,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===i,c=t.create_client??(p=>new pe({url:p,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Bn,f=()=>{s.retryTimer&&(e.clearTimeout(s.retryTimer),s.retryTimer=void 0)},m=()=>bn(e.location.pathname,t.basePath||""),g=p=>{On(e,p)},y=p=>{s.currentDocument=p,s.currentEntriesByKey=new Map((p?.entries??[]).map(b=>[b.key,b]))},C=()=>{s.unsubscribeConnectionStatus?.(),s.unsubscribeConnectionStatus=void 0,s.unsubscribeDocument?.(),s.unsubscribeDocument=void 0},R=(p,b)=>!s.disposed&&b===s.routeSequence&&p===m(),D=async(p,b)=>{let x=s.activeBridge;if(!x)return null;let _=await x.getDocument(p);return R(p,b)&&y(_.data),_.data},k=()=>{C(),y(null);let p=s.activeBridge;s.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let b=s.activeClient;s.activeClient=null,b?.disconnect()},K=p=>p===i.routeId&&!!s.activeBridge&&!!(s.currentDocument&&Mn(s.currentDocument,p))&&Fn(s.activeClient),_e=p=>Math.min(hn*2**Math.max(0,p),8e3),Q=(p,b,x)=>{if(s.disposed)return;f();let _=_e(x);g({state:"reconnecting",routeId:p,attempt:x,retryInMs:_,messageKey:"studio.status.previewBridgeConnecting"}),s.retryTimer=e.setTimeout(()=>{s.retryTimer=void 0,!(s.disposed||b!==s.routeSequence)&&le(x+1).catch(h=>{let d=m();if(p===d){if(J(h)){g({state:"reload-required",routeId:p,attempt:x,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(p,s.routeSequence,x+1)}})},_)},Z=(p,b,x)=>{if(!R(p,b)||s.activeClient===null)return;if(J(x.message)){k(),f(),g({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let _=s.activeClient;C(),y(null);let h=s.activeBridge;s.activeBridge=null,h&&e.__VCP_SITE_EDIT__===h&&delete e.__VCP_SITE_EDIT__,s.activeClient=null,_?.disconnect(),Q(p,b,0)},ue=p=>{let b=m(),x=s.routeSequence;if(!(!R(b,x)||s.activeClient===null)){if(J(p)){k(),f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}pt(p)&&Z(b,x,{state:"failed",message:we(p,"Site edit bridge request failed")})}};s.cleanupFrameRuntime=Tn(e,{getCurrentDocument:()=>s.currentDocument,getDocumentEntry:p=>s.currentEntriesByKey.get(p)??null,onBridgeRequestError:p=>{ue(p)}});let L=async()=>le(0),le=async p=>{if(s.disposed)return;let b=m();if(K(b))return;let x=s.syncInFlight;if(x?.routeId===b)return x.promise;let _=s.routeSequence+1,h=Ce(b,_,p);s.syncInFlight={routeId:b,sequence:_,promise:h};try{await h}finally{s.syncInFlight?.promise===h&&(s.syncInFlight=null)}},Ce=async(p,b,x)=>{s.routeSequence=b,f(),k(),g({state:x>0?"reconnecting":"connecting",routeId:p,attempt:x,messageKey:x>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let _=c(n),h=!1;s.activeClient=_,s.unsubscribeConnectionStatus=_.subscribeConnectionStatus?.(d=>{h&&(d.state==="closed"||d.state==="failed")&&Z(p,b,d)});try{if(await _.connect(),!R(p,b)){_.disconnect();return}let d=Le({routeId:p,client:_,initialDocument:Cn(p)});s.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),s.activeClient=_,s.unsubscribeDocument=d.subscribe(T=>{T.type==="site-edit.document.changed"&&T.routeId===p&&D(p,b).catch(()=>{})}),a()&&(i.routeId=p);let l=await D(p,b);if(!R(p,b)){_.disconnect();return}h=!0,g({state:"ready",routeId:p,attempt:x,messageKey:"studio.status.previewReady"}),Sn(e,{documentVersion:l?.version??0,routeId:p,versions:t.runtime_versions}),An(e,{routeId:p,version:l?.version??0})}catch(d){if(C(),s.activeClient===_&&(s.activeClient=null),s.activeBridge&&e.__VCP_SITE_EDIT__===s.activeBridge&&delete e.__VCP_SITE_EDIT__,s.activeBridge=null,_.disconnect(),y(null),!R(p,b))return;throw g({state:J(d)?"reload-required":"failed",routeId:p,attempt:x,messageKey:J(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},Te=p=>{if(s.disposed)return;let b=m();if(J(p)){f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(b,s.routeSequence,0)},j=()=>{s.syncScheduled||s.disposed||(s.syncScheduled=!0,u(()=>{s.syncScheduled=!1,!s.disposed&&L().catch(p=>Te(p))}))},W=()=>{s.disposed||(s.disposed=!0,s.syncScheduled=!1,s.syncInFlight=null,f(),s.routeSequence+=1,s.unbindRouteChange?.(),s.unbindRouteChange=void 0,s.unbindBootstrapLifecycle?.(),s.unbindBootstrapLifecycle=void 0,s.cleanupFrameRuntime(),k(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(i={started:!0,signature:r,syncRoute:L,cleanup:W},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=i,s.unbindBootstrapLifecycle=xn(e,W),s.unbindRouteChange=Dn(e,j,m),t.defer_initial_sync){j();return}await L()}function vn(e){return{basePath:ht(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:Rn(e.options.bridge_session_key)}}function In(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Rn(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 xn(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),_n(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function _n(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Cn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Tn(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,c=null,u=null,f=null,m=new Map,g=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,y=()=>{n?.(),n=null,r=null},C=()=>{o?.(),o=null,s?.(),s=null},R=(h,d,l)=>{let T=i?.sessionKey!==h||i?.sourceWindow!==d||i?.targetOrigin!==l;i={sessionKey:h,sourceWindow:d,targetOrigin:l},T&&(u=null,f=null)},D=(h,d)=>{let l=e.parent&&e.parent!==e?e.parent:null;return!l||d!==l?!1:!g||h===g},k=()=>{for(let h of m.values())h();m.clear()},K=h=>JSON.stringify([h.routeId,h.version]),_e=()=>!c||c.state==="ready",Q=h=>JSON.stringify([h.state,h.routeId??null,h.attempt??null,h.retryInMs??null,h.messageKey??null]),Z=h=>{if(!_e())return;let d=K(h);u!==d&&(s?.(),s=null,j({kind:"route-ready",payload:{routeId:h.routeId,version:h.version}}),i&&(u=d))},ue=h=>{let d=Q(h);f!==d&&(h.state!=="ready"&&(u=null,a=null),j({kind:"bridge-status",payload:h}),i&&(f=d))},L=h=>{a=h,Z(h)},le=h=>{c=h,ue(h)},Ce=()=>{a&&Z(a)},Te=()=>{c&&ue(c)},j=h=>{i&&i.sourceWindow.postMessage(re({type:"event",...h},{sessionKey:i.sessionKey}),i.targetOrigin)},W=(h,d,l,T)=>{let P=Se(e.document,d.clientX,d.clientY,t.getCurrentDocument?.()??null),N=P?M(P,l==="full"?O(e.document,P,t.getCurrentDocument?.()??null):at(e.document,P,t.getCurrentDocument?.()??null),t.getDocumentEntry,l):null;T&&N&&(h==="pointer-click"||h==="pointer-double-click")&&(T.preventDefault(),T.stopPropagation(),typeof T.stopImmediatePropagation=="function"&&T.stopImmediatePropagation()),j({kind:h,payload:{clientX:d.clientX,clientY:d.clientY,buttons:Number(d.buttons??0),hit:N}})},p=(h,d,l)=>{C(),i={sessionKey:h,sourceWindow:d,targetOrigin:l};let T=Cr(e.document),P=null,N=null,S=()=>{N=null;let E=P;P=null,E&&W("pointer-move",E,"summary")},F=E=>{P={clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},N===null&&(N=dt(e,S))},V=E=>{W("pointer-down",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},z=E=>{W("pointer-up",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},H=E=>{W("pointer-cancel",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},G=E=>{W("pointer-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},ee=E=>{W("pointer-double-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},te=()=>{j({kind:"scroll",payload:{metrics:ye(e)}})};e.document.addEventListener("pointerdown",V,!0),e.document.addEventListener("pointermove",F,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",z,!0),e.document.addEventListener("pointercancel",H,!0),e.document.addEventListener("click",G,!0),e.document.addEventListener("dblclick",ee,!0),e.addEventListener("scroll",te,{passive:!0}),o=()=>{N!==null&&(ft(e,N),N=null),P=null,T(),e.document.removeEventListener("pointerdown",V,!0),e.document.removeEventListener("pointermove",F,!0),e.document.removeEventListener("pointerup",z,!0),e.document.removeEventListener("pointercancel",H,!0),e.document.removeEventListener("click",G,!0),e.document.removeEventListener("dblclick",ee,!0),e.removeEventListener("scroll",te)}},b=h=>{let d=h.detail;d?.routeId&&L(d)},x=h=>{let d=h.detail;d?.state&&le(d)},_=h=>{let d=h.data;if(!rt(d)||d.body.type!=="request"||d.body.kind!=="apply-node-patch"&&d.body.kind!=="get-hit-by-ref"&&d.body.kind!=="get-path-by-ref"&&d.body.kind!=="get-scroll-metrics"&&d.body.kind!=="scroll-to"&&d.body.kind!=="scroll-by"&&d.body.kind!=="set-interaction-mode"&&d.body.kind!=="set-theme-override"&&d.body.kind!=="clear-theme-override"&&d.body.kind!=="get-theme-variables"&&d.body.kind!=="compute-drop-target-at-point"&&d.body.kind!=="observe-node-bounds"&&d.body.kind!=="clear-node-bounds-observer"&&d.body.kind!=="restore-text-edit"&&d.body.kind!=="clear-text-edit-rollback"&&d.body.kind!=="start-text-edit-at-point"&&d.body.kind!=="hit-test-at-point"&&!st(d.body))return;let l=d.body,T=typeof d.sessionKey=="string"?d.sessionKey:null,P=h.source,N=h.origin;if(!T||!N||!P||typeof P.postMessage!="function"||!D(T,P))return;if(i){if(i.sourceWindow!==P||i.targetOrigin!==N)return;i.sessionKey!==T&&(y(),C(),k(),i=null)}R(T,P,N),Te(),Ce();let S=F=>{let V=typeof l.id=="string"?l.id:"unknown";P.postMessage(re({id:V,...F},{sessionKey:T}),N)};try{if(st(l)){kn({message:l,sendEvent:v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},sendResponse:S,subscriptions:m,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(l.kind==="apply-node-patch"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let I=l.payload.preview,A=I?fr(I.sessionId,l.payload.ref):null;if(A&&I){let de=oe.get(A)??-1;if(I.revision<de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,stale:!0,latestRevision:de}});return}if(I.revision===de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,duplicate:!0,latestRevision:de}});return}}if(lr(v,l.payload.patch),A&&I&&pr(A,I.revision),I?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:I.revision}});return}S({type:"response",ok:!0,result:M(v,O(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,I?.responseDetail??"full")});return}if(l.kind==="get-hit-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:M(v,O(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(l.kind==="get-path-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let I=[],A=v;for(;A;)A.getAttribute("data-vcp-edit-key")&&I.push(M(A,O(e.document,A,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),A=A.parentElement;S({type:"response",ok:!0,result:I.reverse()});return}if(l.kind==="restore-text-edit"||l.kind==="clear-text-edit-rollback"){let v=l.payload.ref;if(l.kind==="clear-text-edit-rollback"){r&&it(r.ref,v)&&(r=null),S({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!it(r.ref,v)){S({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let I=wn(e.document,r,t.getCurrentDocument?.()??null);r=null,S(I?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(l.kind==="get-scroll-metrics"){S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-to"){let v=Number(l.payload.x),I=Number(l.payload.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:I}),S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-by"){let v=Number(l.payload.deltaX),I=Number(l.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:I}),S({type:"response",ok:!0,result:{...ye(e),scrolled:!0}});return}if(l.kind==="set-interaction-mode"){l.payload.enabled?p(T,P,N):i?.sourceWindow===P&&i.targetOrigin===N&&i.sessionKey===T&&C(),S({type:"response",ok:!0,result:{interactionEnabled:l.payload.enabled}});return}if(l.kind==="set-theme-override"){hr(e.document,l.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(l.kind==="clear-theme-override"){mr(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(l.kind==="get-theme-variables"){S({type:"response",ok:!0,result:gr(e.document,l.payload.names)});return}if(l.kind==="compute-drop-target-at-point"){let v=Number(l.payload?.x),I=Number(l.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:nr(e,v,I,l.payload.dragKind,l.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(l.kind==="observe-node-bounds"){let v=l.payload.ref;if(!v){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let I=U(e.document,v,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}s?.(),s=er(e,I,v,t.getDocumentEntry,A=>j({kind:"node-bounds-change",payload:{hit:A}})),S({type:"response",ok:!0,result:{observing:!0}}),j({kind:"node-bounds-change",payload:{hit:M(I,v,t.getDocumentEntry,"summary")}});return}if(l.kind==="clear-node-bounds-observer"){s?.(),s=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(l.kind!=="hit-test-at-point"&&l.kind!=="start-text-edit-at-point")return;let F=Number(l.payload?.x),V=Number(l.payload?.y);if(!Number.isFinite(F)||!Number.isFinite(V)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let z=l.kind==="hit-test-at-point"?Se(e.document,F,V,t.getCurrentDocument?.()??null):Wn(e.document,F,V,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!z){S({type:"response",ok:!1,error:l.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let H=l.kind==="start-text-edit-at-point"?z:null,G=l.kind==="hit-test-at-point"?z:H.element,ee=l.payload.detailLevel??"full",te=ee==="full"?O(e.document,G,t.getCurrentDocument?.()??null):at(e.document,G,t.getCurrentDocument?.()??null),E=H&&typeof H.textSegmentIndex=="number"?{...te,textSegmentIndex:H.textSegmentIndex}:te,Gt=M(G,E,t.getDocumentEntry,ee);if(l.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:Gt});return}y(),n=Er(e,G,E,v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},{...H?.textNode?{textNode:H.textNode}:{},onCommitSnapshot:v=>{r=v}}),S({type:"response",ok:!0,result:{ref:E}})}catch(F){S({type:"response",ok:!1,error:F instanceof Error?F.message:"Failed to start text edit"})}};return e.addEventListener("message",_),e.addEventListener(Fe,b),e.addEventListener(Me,x),()=>{y(),C(),i=null,k(),e.removeEventListener("message",_),e.removeEventListener(Fe,b),e.removeEventListener(Me,x)}}function st(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||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"}async function kn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,onBridgeRequestError:s,windowLike:i}){let a=i.__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-get-document":n({type:"response",ok:!0,result:await a.getDocument(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}n({type:"response",ok:!0,result:a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await a.getObjectSummary(e.payload.key,e.payload.routeId)});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 c=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Pn(c,e.payload.key,i.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":n({type:"response",ok:!0,result:await a.execute(e.payload.request)});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 c=e.payload.subscriptionId;r.get(c)?.();let u=a.subscribe(f=>{t({kind:"bridge-event",payload:{event:f,subscriptionId:c}})});r.set(c,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let c=e.payload.subscriptionId;r.get(c)?.(),r.delete(c),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(c){s?.(c,e),n({type:"response",ok:!1,error:Kn(c)})}}function Pn(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=U(n,{key:t},r),s=o?Nn(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Nn(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 Dn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,s=n(),i=()=>{let u=n();u!==s&&(s=u,t())},a=()=>i(),c=()=>i();return e.history.pushState=function(...f){let m=r.apply(this,f);return i(),m},e.history.replaceState=function(...f){let m=o.apply(this,f);return i(),m},e.addEventListener("popstate",a),e.addEventListener("hashchange",c),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",c)}}function Bn(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function dt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ft(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function An(e,t){e.dispatchEvent(new CustomEvent(Fe,{detail:t}))}function On(e,t){e.dispatchEvent(new CustomEvent(Me,{detail:t}))}function Fn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Mn(e,t){return e.routeId===t}function we(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function pt(e){let t=we(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Kn(e){let t=we(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":pt(t)?"Site edit bridge disconnected":t}function J(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 ht(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function je(e){return gn.has(gt(e))}function qn(e){return yn.has(gt(e))}function mt(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:qn(e.tagName),canInsertChild:je(e.tagName),canMove:!1,canRemove:!1}}function gt(e){return e?.trim().toLowerCase()??""}function it(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 wn(e,t,n){let r=U(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=jn(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 jn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Wn(e,t,n,r,o){let s=Se(e,t,n,r),i=yt(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=O(e,i,r),u=o?.(c.key)??o?.(a);if(!mt({operationSummary:u?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;let m=Hn(e,t,n,i);if(m){let g=Vn(i,m);if(g!==null)return{element:i,textNode:m,textSegmentIndex:g}}return(u?.childKeys.length??0)===0?{element:i}:null}function Hn(e,t,n,r){let o=Un(e,t,n);return!o||o.parentElement!==r?null:o}function Un(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(be(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return be(a)?a:null}function Vn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function be(e){return e?.nodeType===3}function Se(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let s of o){let i=yt(s),a=i?.getAttribute("data-vcp-edit-key")??"";if(i&&Yn(i,r,a))return i}return null}function yt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(We(t))return n??t;!$n(r)&&!n&&(n=t)}t=t.parentElement}return n}function We(e){return e.getAttribute(mn)!==null}function $n(e){return Gn(e.split("::")[0]??"")}function Gn(e){if(!e)return!1;let t=zn(e);return t===he||t.startsWith(`${he}/`)||t.includes(`/${he}/`)||t.endsWith(`/${he}`)}function zn(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 O(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${xt(r)}"]`))),n,r);if(o.length<=1)return{key:ct(n,r,0)};let s=o.indexOf(t);return s>=0?{key:ct(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function at(e,t,n){return O(e,t,n)}function U(e,t,n){let r=ie(t.key)??t.key,o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${xt(r)}"]`))),n,t.key);if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(ie(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=Jn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function ct(e,t,n){return He(e,t)[n]?.key??t}function Jn(e,t){let n=ie(t);if(!n)return null;let o=He(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function He(e,t){return(e?.entries??[]).filter(n=>(ie(n.key)??n.key)===t)}function bt(e,t,n){let r=St(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function Yn(e,t,n){let r=St(t,n);return!r||e.tagName.toLowerCase()===r}function St(e,t){let n=ie(t)??t,o=(e?.entries.find(s=>s.key===t)??He(e,n)[0])?.tag.trim();return!o||o!==o.toLowerCase()?null:o}var Xn=2,Qn=4;function Et(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&Qn)!==0?-1:(r&Xn)!==0?1:0})}function ie(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(ot);if(n<0)break;let r=Number(t.slice(n+ot.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Zn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function Ln(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>Ke(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function M(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=Ee(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([y,C])=>[y,C??""])),attributes:Object.fromEntries(e.getAttributeNames().map(y=>[y,e.getAttribute(y)??""]))}:{},u=mt({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),f=We(e),m=!!(s&&/^[A-Z]/.test(s.tag)),g=!s||!m;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:m?"component-call":"jsx"}:{},...m&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:f?!1:(s?.childKeys.length??0)>0||u.canInsertChild||g&&je(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:Ln(e),spacing:Zn(e)}}function er(e,t,n,r,o){let s=Ke(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=dt(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let C=Ke(t.getBoundingClientRect());tr(s,C)&&(s=C,o(M(t,n,r,"summary")))},u=e.ResizeObserver,f=typeof u=="function"?new u(a):null;f?.observe(t);let m=e.MutationObserver,g=typeof m=="function"?new m(a):null;g?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",a,{passive:!0});let y=e.visualViewport;return y?.addEventListener?.("resize",a,{passive:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(ft(e,i),i=null),f?.disconnect(),g?.disconnect(),e.removeEventListener("resize",a),y?.removeEventListener?.("resize",a),e.document.removeEventListener("load",a,!0)}}function Ke(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function tr(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 nr(e,t,n,r,o,s,i){let a=e.document,c=Se(a,t,n,s);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?U(a,o,s):null;if(u&&qe(c,u))return me(a,c,"self-or-descendant",s,i);if(r==="move"&&u){let R=ir(a,c,u,s,i);if(R){let D=Ae(R.child,R.targetParent,t,n,"nearest");if(D)return ge(a,R.child,R.targetParent,D,s,i)}}let f=null,m=!1,g=c,y=c.parentElement;for(;y;){if(y.getAttribute("data-vcp-edit-key")){if(u&&qe(y,u))return me(a,c,"self-or-descendant",s,i);let R=ut(y,r,i);if(R==="accept"){f={child:g,targetParent:y};break}R==="blocked"&&(m=!0),g=y}y=y.parentElement}let C=ut(c,r,i);if(C==="accept"){if(f){let R=Ae(f.child,f.targetParent,t,n,"edge");if(R)return ge(a,f.child,f.targetParent,R,s,i)}return ge(a,c,c,rr(c,t,n),s,i)}if(f){let R=Ae(f.child,f.targetParent,t,n,"nearest");return ge(a,f.child,f.targetParent,R??"after",s,i)}return C==="blocked"||m?me(a,c,"operation-boundary-blocked",s,i):me(a,c,"no-accepting-parent",s,i)}function me(e,t,n,r,o){return{anchorHit:M(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function ge(e,t,n,r,o,s){let i=M(t,O(e,t,o),s,"summary"),a=M(n,O(e,n,o),s,"summary"),c=Ee(n).indicatorOrientation,u=r==="append"||r==="prepend"?or(n.getBoundingClientRect(),c,r):sr(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:u}}function ut(e,t,n){if(We(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return je(s)?"accept":"not-container"}function Ae(e,t,n,r,o){let s=Ee(t).indicatorOrientation,i=e.getBoundingClientRect(),a=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function rr(e,t,n){let r=Ee(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 Ee(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function or(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 sr(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 qe(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ir(e,t,n,r,o){let s=ar(e,t,n,r,o);if(s)return s;let i=ur(n);if(!i||t===i)return null;let a=t,c=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==i;)a.getAttribute("data-vcp-edit-key")&&(c=a),a=a.parentElement;return a!==i||!c||c===i||c===n||qe(c,n)?null:{child:c,targetParent:i}}function ar(e,t,n,r,o){if(!o)return null;let s=O(e,n,r),a=o(s.key)?.parentKey??null;if(!a)return null;let u=O(e,t,r).key;for(;u;){let f=o(u);if(!f?.parentKey)return null;if(f.parentKey===a){if(u===s.key||cr(u,s.key,o))return null;let m=U(e,{key:u},r),g=U(e,{key:a},r);return m&&g?{child:m,targetParent:g}:null}u=f.parentKey}return null}function cr(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n(r)?.parentKey}return!1}function ur(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function ye(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:w(e.scrollX),scrollY:w(e.scrollY),scrollWidth:Math.max(w(t?.scrollWidth),w(n?.scrollWidth),w(e.innerWidth)),scrollHeight:Math.max(w(t?.scrollHeight),w(n?.scrollHeight),w(e.innerHeight)),viewportWidth:w(e.innerWidth),viewportHeight:w(e.innerHeight)}}function lr(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 s=e.style,i=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(o==null||o===""){s.removeProperty(i);return}s.setProperty(i,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,s=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),i=r.value;if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i),r.priority)})}var dr=500,oe=new Map;function fr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function pr(e,t){if(oe.size>=dr){let n=oe.keys().next().value;n&&oe.delete(n)}oe.set(e,t)}var se=new Set;function hr(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of se)r.has(o)||n?.removeProperty(o);se.clear();for(let o of r)se.add(o);Sr(e,t.stylesheets??[])}function mr(e){let t=e.documentElement?.style;for(let n of se)t?.removeProperty(n);se.clear();for(let n of Rt(e))n.remove()}function gr(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let a=vt(o,i);a&&(s[i]=a)}return s}function vt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return It(e,r,n)}function It(e,t,n){if(!t)return null;let r=yr(t);if(!r)return t;let o=vt(e,r.name,n);return o||(r.fallback?It(e,r.fallback,n)??r.fallback:null)}function yr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=br(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function br(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 Sr(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Rt(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(lt,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Rt(e){return Array.from(e.querySelectorAll(`link[${lt}]`))}function Er(e,t,n,r,o={}){let s=o.textNode?vr(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,a=i.textContent??"",c=s?void 0:t.innerHTML,u=Ir(i),f=!1,m=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",C),i.removeEventListener("blur",R),i.removeEventListener("input",D),xr(i,u)},g=k=>{if(f)return;f=!0;let K=i.textContent??"";if(m(),k==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(K),k==="commit"&&K!==a){o.onCommitSnapshot?.({ref:n,initialText:a,...c!==void 0?{initialHtml:c}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:K}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(k){let K=k.target;K&&i.contains(K)||g("commit")}function C(k){if(k.key==="Escape"){k.preventDefault(),g("cancel");return}k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g("commit"))}function R(){g("commit")}function D(){r({kind:"text-edit-input",payload:{ref:n,hit:M(t,n,void 0,"full")}})}return Rr(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",C),i.addEventListener("blur",R),i.addEventListener("input",D),Tr(i),kr(i,e.document),m}function vr(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 Ir(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 Rr(e){_r(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 xr(e,t){Oe(e,"contenteditable",t.contentEditable),Oe(e,"spellcheck",t.spellcheck),Oe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function _r(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 Oe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Cr(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 Tr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function kr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function xt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function w(e){let t=Number(e);return Number.isFinite(t)?t:0}import Pr from"node:http";import{randomBytes as Nr,timingSafeEqual as Dr}from"node:crypto";import Br from"node:path";import{WebSocket as Pt,WebSocketServer as Ar}from"ws";import{createPreviewSiteEditEngineRuntime as Or}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Fr,scanNextAppRouterRoutes as Mr}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Kr}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as qr}from"@vcp-dev/contracts";var wr="127.0.0.1",jr=30218,Wr="/__vcp/site-edit/bridge",Hr=6*1024*1024,Ur=3e3,_t=50,Ct="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function ds(e){let t=Dt(e),n=At(t),r=Bt(),o=r.get(n);if(o)return o;let s=new ve(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function Nt(e,t){let n=new ve(Dt(t),e,!1);return n.start({listen:!1}),n}var ve=class{constructor(t,n=Pr.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Or({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Vr({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 Kr({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??_t,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),this.isStarted=!0}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=Bt(),n=At(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getDocument(r)},getObjectSummary:async(t,n)=>this.getRuntime().getObjectSummary(t,n?this.resolveRouteId(n):void 0),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 await r.refreshSourceForKey(t,o),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:async t=>this.getRuntime().executeOperation(this.normalizeRequest(t)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:t=>this.getRuntime().subscribe(t)}}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??_t;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:Mr(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=Fr(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 Dt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Br.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??wr,port:e.port??jr,path:e.path??Wr,sessionKey:e.sessionKey??Qr(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function Bt(){let e=globalThis;return e[Ct]??=new Map,e[Ct]}function At(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Vr(e){let t=new Ar({maxPayload:Hr,noServer:!0}),n=new WeakSet,r=s=>{new fe({socket:new Ve(s),engine:e.engine,validateOperationRequest:i=>qr.safeParse(i).success})},o=(s,i,a)=>{if(!$r(s,e))return;let c=Gr(s,e);if(!c){i.write(`HTTP/1.1 401 Unauthorized\r
1
+ function Je(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let c=t.get(a);if(typeof c=="number")return c;let u=n.length;return n.push(a),t.set(a,u),u},i=a=>{let c=null;for(let u of Yt(a)){let f=`${c??"root"}\0${u}`,m=r.get(f);if(typeof m=="number"){c=m;continue}let g=o.length;o.push({parent:c,token:s(u)}),r.set(f,g),c=g}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,tokens:n,nodes:o,rootKeyNodeIds:e.rootKeys.map(i),entries:e.entries.map(a=>({keyNodeId:i(a.key),tag:a.tag,label:a.label,parentKeyNodeId:a.parentKey?i(a.parentKey):null,childKeyNodeIds:a.childKeys.map(i),operationSummary:a.operationSummary}))}}function Ye(e){if(!Jt(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let a=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,a),a};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function Jt(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Yt(e){if(!e)return[];let t=[],n=0,r=ze(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=ze(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 ze(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var B=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==="get-document"||t==="get-object-summary"||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!q(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?q(t.payload)&&typeof t.payload.id=="string":t.type==="event"?q(t.payload)&&q(t.payload.event):t.type==="auth"?q(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?q(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!q(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":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-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Xt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},fe=class{constructor(t){this.options=t,this.messageQueue=new Pe,this.eventDispatcher=new ke(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"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Je((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,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=B.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(t){try{await this.handleMessage(B.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Qt(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(B.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:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ke=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)})}},Pe=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 q(e){return typeof e=="object"&&e!==null}function Xt(e){return q(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"&&q(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&q(e.params)}function Qt(e){try{return B.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Zt="vcp:designer:trace",Lt="designer_trace",Xe="__VCP_DESIGNER_TRACE__";var en=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function tn(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Zt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Lt)==="1"}catch{return!1}}function $(e,t={},n=globalThis){if(!tn(n))return;let r={type:e,timestamp:Date.now(),payload:nn(t)},o=n,s=o[Xe]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Xe]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function nn(e){return Ne(e,0)}function Ne(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Ne(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(en.test(r)){n[r]="[redacted]";continue}n[r]=Ne(o,t+1)}return n}var pe=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===De&&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(a){let c=ne(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let s=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(B.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(ne(a,"WebSocket auth failed"),"failed")}return}s()}},r.onerror=a=>{if(this.socket!==r)return;let c=ne(a,"WebSocket failed");i(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,r,o,()=>{s()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let c=this.intentionalClose,u=new Error(an(a,{intentional:c}));i(u,c?"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})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}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){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){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!==De||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}`,s=ln(o,t,n);return $("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Qe(n.request,"kind"),documentVersion:Qe(n.request,"documentVersion")}),new Promise((i,a)=>{let c=this.resolveRequestTimeoutMs(t),u=c>0?setTimeout(()=>{let f=this.pending.get(o);f&&(this.pending.delete(o),$("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),f.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:f=>i(f),reject:a});try{r.send(B.stringifyMessage(s))}catch(f){let m=ne(f,"WebSocket send failed");this.clearPendingRequest(o),a(m),this.cleanupSocket(r,m,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(B.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(s){let i=ne(s,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=B.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"){$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:cn(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Ye(n.payload.result.data)}: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):sn[t]??on}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===rn||t.readyState===De)&&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)}},rn=0,De=1,on=15e3,sn={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function ne(e,t){return e instanceof Error?e:new Error(t)}function an(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 Qe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function cn(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 Ze(e){return new Be(e)}var Be=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,dn(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,fn(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return un(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}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 getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}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){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){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.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return $("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){$("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}$("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.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function un(e){return e.version===0&&e.rootKeys.length===0}function ln(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};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}}}}function dn(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function fn(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var Le="vcp-window-message",Lo=1;function pn(e){return{source:Le,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function hn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===Le&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var et="site-edit",tt="frame-runtime";function re(e,t={}){return pn({namespace:et,channel:tt,sessionKey:t.sessionKey,body:e})}function nt(e){return!hn(e)||e.namespace!==et||e.channel!==tt?!1:typeof e.body?.type=="string"}var Fe="vcp-site-edit:route-ready",Me="vcp-site-edit:bridge-status",mn=1e3,gn="data-vcp-ui-component",lt="data-vcp-theme-preview",rt="::repeat-item#",he="components/ui",yn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),bn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Sn(e,t=""){let n=ht(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function En(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 vn(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 rs(e=window,t={}){let n=vn(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Rn({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(In(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let s={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},i,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===i,c=t.create_client??(p=>new pe({url:p,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??An,f=()=>{s.retryTimer&&(e.clearTimeout(s.retryTimer),s.retryTimer=void 0)},m=()=>Sn(e.location.pathname,t.basePath||""),g=p=>{Fn(e,p)},y=p=>{s.currentDocument=p,s.currentEntriesByKey=new Map((p?.entries??[]).map(b=>[b.key,b]))},_=()=>{s.unsubscribeConnectionStatus?.(),s.unsubscribeConnectionStatus=void 0,s.unsubscribeDocument?.(),s.unsubscribeDocument=void 0},I=(p,b)=>!s.disposed&&b===s.routeSequence&&p===m(),D=async(p,b)=>{let x=s.activeBridge;if(!x)return null;let C=await x.getDocument(p);return I(p,b)&&y(C.data),C.data},k=()=>{_(),y(null);let p=s.activeBridge;s.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let b=s.activeClient;s.activeClient=null,b?.disconnect()},K=p=>p===i.routeId&&!!s.activeBridge&&!!(s.currentDocument&&Kn(s.currentDocument,p))&&Mn(s.activeClient),_e=p=>Math.min(mn*2**Math.max(0,p),8e3),Q=(p,b,x)=>{if(s.disposed)return;f();let C=_e(x);g({state:"reconnecting",routeId:p,attempt:x,retryInMs:C,messageKey:"studio.status.previewBridgeConnecting"}),s.retryTimer=e.setTimeout(()=>{s.retryTimer=void 0,!(s.disposed||b!==s.routeSequence)&&le(x+1).catch(h=>{let d=m();if(p===d){if(J(h)){g({state:"reload-required",routeId:p,attempt:x,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(p,s.routeSequence,x+1)}})},C)},Z=(p,b,x)=>{if(!I(p,b)||s.activeClient===null)return;if(J(x.message)){k(),f(),g({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let C=s.activeClient;_(),y(null);let h=s.activeBridge;s.activeBridge=null,h&&e.__VCP_SITE_EDIT__===h&&delete e.__VCP_SITE_EDIT__,s.activeClient=null,C?.disconnect(),Q(p,b,0)},ue=p=>{let b=m(),x=s.routeSequence;if(!(!I(b,x)||s.activeClient===null)){if(J(p)){k(),f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}pt(p)&&Z(b,x,{state:"failed",message:qe(p,"Site edit bridge request failed")})}};s.cleanupFrameRuntime=kn(e,{getCurrentDocument:()=>s.currentDocument,getDocumentEntry:p=>s.currentEntriesByKey.get(p)??null,onBridgeRequestError:p=>{ue(p)}});let L=async()=>le(0),le=async p=>{if(s.disposed)return;let b=m();if(K(b))return;let x=s.syncInFlight;if(x?.routeId===b)return x.promise;let C=s.routeSequence+1,h=Ce(b,C,p);s.syncInFlight={routeId:b,sequence:C,promise:h};try{await h}finally{s.syncInFlight?.promise===h&&(s.syncInFlight=null)}},Ce=async(p,b,x)=>{s.routeSequence=b,f(),k(),g({state:x>0?"reconnecting":"connecting",routeId:p,attempt:x,messageKey:x>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let C=c(n),h=!1;s.activeClient=C,s.unsubscribeConnectionStatus=C.subscribeConnectionStatus?.(d=>{h&&(d.state==="closed"||d.state==="failed")&&Z(p,b,d)});try{if(await C.connect(),!I(p,b)){C.disconnect();return}let d=Ze({routeId:p,client:C,initialDocument:Tn(p)});s.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),s.activeClient=C,s.unsubscribeDocument=d.subscribe(T=>{T.type==="site-edit.document.changed"&&T.routeId===p&&D(p,b).catch(()=>{})}),a()&&(i.routeId=p);let l=await D(p,b);if(!I(p,b)){C.disconnect();return}h=!0,g({state:"ready",routeId:p,attempt:x,messageKey:"studio.status.previewReady"}),En(e,{documentVersion:l?.version??0,routeId:p,versions:t.runtime_versions}),On(e,{routeId:p,version:l?.version??0})}catch(d){if(_(),s.activeClient===C&&(s.activeClient=null),s.activeBridge&&e.__VCP_SITE_EDIT__===s.activeBridge&&delete e.__VCP_SITE_EDIT__,s.activeBridge=null,C.disconnect(),y(null),!I(p,b))return;throw g({state:J(d)?"reload-required":"failed",routeId:p,attempt:x,messageKey:J(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},Te=p=>{if(s.disposed)return;let b=m();if(J(p)){f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(b,s.routeSequence,0)},j=()=>{s.syncScheduled||s.disposed||(s.syncScheduled=!0,u(()=>{s.syncScheduled=!1,!s.disposed&&L().catch(p=>Te(p))}))},W=()=>{s.disposed||(s.disposed=!0,s.syncScheduled=!1,s.syncInFlight=null,f(),s.routeSequence+=1,s.unbindRouteChange?.(),s.unbindRouteChange=void 0,s.unbindBootstrapLifecycle?.(),s.unbindBootstrapLifecycle=void 0,s.cleanupFrameRuntime(),k(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(i={started:!0,signature:r,syncRoute:L,cleanup:W},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=i,s.unbindBootstrapLifecycle=_n(e,W),s.unbindRouteChange=Bn(e,j,m),t.defer_initial_sync){j();return}await L()}function Rn(e){return{basePath:ht(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:xn(e.options.bridge_session_key)}}function In(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function xn(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 _n(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Cn(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Cn(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Tn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function kn(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,c=null,u=null,f=null,m=new Map,g=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,y=()=>{n?.(),n=null,r=null},_=()=>{o?.(),o=null,s?.(),s=null},I=(h,d,l)=>{let T=i?.sessionKey!==h||i?.sourceWindow!==d||i?.targetOrigin!==l;i={sessionKey:h,sourceWindow:d,targetOrigin:l},T&&(u=null,f=null)},D=(h,d)=>{let l=e.parent&&e.parent!==e?e.parent:null;return!l||d!==l?!1:!g||h===g},k=()=>{for(let h of m.values())h();m.clear()},K=h=>JSON.stringify([h.routeId,h.version]),_e=()=>!c||c.state==="ready",Q=h=>JSON.stringify([h.state,h.routeId??null,h.attempt??null,h.retryInMs??null,h.messageKey??null]),Z=h=>{if(!_e())return;let d=K(h);u!==d&&(s?.(),s=null,j({kind:"route-ready",payload:{routeId:h.routeId,version:h.version}}),i&&(u=d))},ue=h=>{let d=Q(h);f!==d&&(h.state!=="ready"&&(u=null,a=null),j({kind:"bridge-status",payload:h}),i&&(f=d))},L=h=>{a=h,Z(h)},le=h=>{c=h,ue(h)},Ce=()=>{a&&Z(a)},Te=()=>{c&&ue(c)},j=h=>{i&&i.sourceWindow.postMessage(re({type:"event",...h},{sessionKey:i.sessionKey}),i.targetOrigin)},W=(h,d,l,T)=>{let P=Se(e.document,d.clientX,d.clientY,t.getCurrentDocument?.()??null),N=P?O(P,l==="full"?F(e.document,P,t.getCurrentDocument?.()??null):it(e.document,P,t.getCurrentDocument?.()??null),t.getDocumentEntry,l):null;T&&N&&(h==="pointer-click"||h==="pointer-double-click")&&(T.preventDefault(),T.stopPropagation(),typeof T.stopImmediatePropagation=="function"&&T.stopImmediatePropagation()),j({kind:h,payload:{clientX:d.clientX,clientY:d.clientY,buttons:Number(d.buttons??0),hit:N}})},p=(h,d,l)=>{_(),i={sessionKey:h,sourceWindow:d,targetOrigin:l};let T=Pr(e.document),P=null,N=null,S=()=>{N=null;let E=P;P=null,E&&W("pointer-move",E,"summary")},M=E=>{P={clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},N===null&&(N=dt(e,S))},V=E=>{W("pointer-down",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},z=E=>{W("pointer-up",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},H=E=>{W("pointer-cancel",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},G=E=>{W("pointer-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},ee=E=>{W("pointer-double-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},te=()=>{j({kind:"scroll",payload:{metrics:ye(e)}})};e.document.addEventListener("pointerdown",V,!0),e.document.addEventListener("pointermove",M,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",z,!0),e.document.addEventListener("pointercancel",H,!0),e.document.addEventListener("click",G,!0),e.document.addEventListener("dblclick",ee,!0),e.addEventListener("scroll",te,{passive:!0}),o=()=>{N!==null&&(ft(e,N),N=null),P=null,T(),e.document.removeEventListener("pointerdown",V,!0),e.document.removeEventListener("pointermove",M,!0),e.document.removeEventListener("pointerup",z,!0),e.document.removeEventListener("pointercancel",H,!0),e.document.removeEventListener("click",G,!0),e.document.removeEventListener("dblclick",ee,!0),e.removeEventListener("scroll",te)}},b=h=>{let d=h.detail;d?.routeId&&L(d)},x=h=>{let d=h.detail;d?.state&&le(d)},C=h=>{let d=h.data;if(!nt(d)||d.body.type!=="request"||d.body.kind!=="apply-node-patch"&&d.body.kind!=="get-hit-by-ref"&&d.body.kind!=="get-path-by-ref"&&d.body.kind!=="get-scroll-metrics"&&d.body.kind!=="scroll-to"&&d.body.kind!=="scroll-by"&&d.body.kind!=="set-interaction-mode"&&d.body.kind!=="set-theme-override"&&d.body.kind!=="clear-theme-override"&&d.body.kind!=="get-theme-variables"&&d.body.kind!=="compute-drop-target-at-point"&&d.body.kind!=="observe-node-bounds"&&d.body.kind!=="clear-node-bounds-observer"&&d.body.kind!=="restore-text-edit"&&d.body.kind!=="clear-text-edit-rollback"&&d.body.kind!=="start-text-edit-at-point"&&d.body.kind!=="hit-test-at-point"&&!ot(d.body))return;let l=d.body,T=typeof d.sessionKey=="string"?d.sessionKey:null,P=h.source,N=h.origin;if(!T||!N||!P||typeof P.postMessage!="function"||!D(T,P))return;if(i){if(i.sourceWindow!==P||i.targetOrigin!==N)return;i.sessionKey!==T&&(y(),_(),k(),i=null)}I(T,P,N),Te(),Ce();let S=M=>{let V=typeof l.id=="string"?l.id:"unknown";P.postMessage(re({id:V,...M},{sessionKey:T}),N)};try{if(ot(l)){Pn({message:l,sendEvent:v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},sendResponse:S,subscriptions:m,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(l.kind==="apply-node-patch"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let R=l.payload.preview,A=R?mr(R.sessionId,l.payload.ref):null;if(A&&R){let de=oe.get(A)??-1;if(R.revision<de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:R.revision,stale:!0,latestRevision:de}});return}if(R.revision===de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:R.revision,duplicate:!0,latestRevision:de}});return}}if(pr(v,l.payload.patch),A&&R&&gr(A,R.revision),R?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:R.revision}});return}S({type:"response",ok:!0,result:O(v,F(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,R?.responseDetail??"full")});return}if(l.kind==="get-hit-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:O(v,F(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(l.kind==="get-path-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let R=[],A=v;for(;A;)A.getAttribute("data-vcp-edit-key")&&R.push(O(A,F(e.document,A,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),A=A.parentElement;S({type:"response",ok:!0,result:R.reverse()});return}if(l.kind==="restore-text-edit"||l.kind==="clear-text-edit-rollback"){let v=l.payload.ref;if(l.kind==="clear-text-edit-rollback"){r&&st(r.ref,v)&&(r=null),S({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!st(r.ref,v)){S({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let R=jn(e.document,r,t.getCurrentDocument?.()??null);r=null,S(R?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(l.kind==="get-scroll-metrics"){S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-to"){let v=Number(l.payload.x),R=Number(l.payload.y);if(!Number.isFinite(v)||!Number.isFinite(R)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:R}),S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-by"){let v=Number(l.payload.deltaX),R=Number(l.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(R)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:R}),S({type:"response",ok:!0,result:{...ye(e),scrolled:!0}});return}if(l.kind==="set-interaction-mode"){l.payload.enabled?p(T,P,N):i?.sourceWindow===P&&i.targetOrigin===N&&i.sessionKey===T&&_(),S({type:"response",ok:!0,result:{interactionEnabled:l.payload.enabled}});return}if(l.kind==="set-theme-override"){yr(e.document,l.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(l.kind==="clear-theme-override"){br(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(l.kind==="get-theme-variables"){S({type:"response",ok:!0,result:Sr(e.document,l.payload.names)});return}if(l.kind==="compute-drop-target-at-point"){let v=Number(l.payload?.x),R=Number(l.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(R)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:sr(e,v,R,l.payload.dragKind,l.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(l.kind==="observe-node-bounds"){let v=l.payload.ref;if(!v){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let R=U(e.document,v,t.getCurrentDocument?.()??null);if(!R){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}s?.(),s=tr(e,R,v,t.getDocumentEntry,A=>j({kind:"node-bounds-change",payload:{hit:A}})),S({type:"response",ok:!0,result:{observing:!0}}),j({kind:"node-bounds-change",payload:{hit:O(R,v,t.getDocumentEntry,"summary")}});return}if(l.kind==="clear-node-bounds-observer"){s?.(),s=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(l.kind!=="hit-test-at-point"&&l.kind!=="start-text-edit-at-point")return;let M=Number(l.payload?.x),V=Number(l.payload?.y);if(!Number.isFinite(M)||!Number.isFinite(V)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let z=l.kind==="hit-test-at-point"?Se(e.document,M,V,t.getCurrentDocument?.()??null):Hn(e.document,M,V,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!z){S({type:"response",ok:!1,error:l.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let H=l.kind==="start-text-edit-at-point"?z:null,G=l.kind==="hit-test-at-point"?z:H.element,ee=l.payload.detailLevel??"full",te=ee==="full"?F(e.document,G,t.getCurrentDocument?.()??null):it(e.document,G,t.getCurrentDocument?.()??null),E=H&&typeof H.textSegmentIndex=="number"?{...te,textSegmentIndex:H.textSegmentIndex}:te,zt=O(G,E,t.getDocumentEntry,ee);if(l.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:zt});return}y(),n=Ir(e,G,E,v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},{...H?.textNode?{textNode:H.textNode}:{},onCommitSnapshot:v=>{r=v}}),S({type:"response",ok:!0,result:{ref:E}})}catch(M){S({type:"response",ok:!1,error:M instanceof Error?M.message:"Failed to start text edit"})}};return e.addEventListener("message",C),e.addEventListener(Fe,b),e.addEventListener(Me,x),()=>{y(),_(),i=null,k(),e.removeEventListener("message",C),e.removeEventListener(Fe,b),e.removeEventListener(Me,x)}}function ot(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||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"}async function Pn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,onBridgeRequestError:s,windowLike:i}){let a=i.__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-get-document":n({type:"response",ok:!0,result:await a.getDocument(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}n({type:"response",ok:!0,result:a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await a.getObjectSummary(e.payload.key,e.payload.routeId)});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 c=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Nn(c,e.payload.key,i.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":n({type:"response",ok:!0,result:await a.execute(e.payload.request)});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 c=e.payload.subscriptionId;r.get(c)?.();let u=a.subscribe(f=>{t({kind:"bridge-event",payload:{event:f,subscriptionId:c}})});r.set(c,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let c=e.payload.subscriptionId;r.get(c)?.(),r.delete(c),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(c){s?.(c,e),n({type:"response",ok:!1,error:qn(c)})}}function Nn(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=U(n,{key:t},r),s=o?Dn(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Dn(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 Bn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,s=n(),i=()=>{let u=n();u!==s&&(s=u,t())},a=()=>i(),c=()=>i();return e.history.pushState=function(...f){let m=r.apply(this,f);return i(),m},e.history.replaceState=function(...f){let m=o.apply(this,f);return i(),m},e.addEventListener("popstate",a),e.addEventListener("hashchange",c),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",c)}}function An(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function dt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ft(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function On(e,t){e.dispatchEvent(new CustomEvent(Fe,{detail:t}))}function Fn(e,t){e.dispatchEvent(new CustomEvent(Me,{detail:t}))}function Mn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Kn(e,t){return e.routeId===t}function qe(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function pt(e){let t=qe(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function qn(e){let t=qe(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":pt(t)?"Site edit bridge disconnected":t}function J(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 ht(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function we(e){return yn.has(gt(e))}function wn(e){return bn.has(gt(e))}function mt(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:wn(e.tagName),canInsertChild:we(e.tagName),canMove:!1,canRemove:!1}}function gt(e){return e?.trim().toLowerCase()??""}function st(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 jn(e,t,n){let r=U(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=Wn(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 Wn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Hn(e,t,n,r,o){let s=Se(e,t,n,r),i=yt(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=F(e,i,r),u=o?.(c.key)??o?.(a);if(!mt({operationSummary:u?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;let m=Un(e,t,n,i);if(m){let g=$n(i,m);if(g!==null)return{element:i,textNode:m,textSegmentIndex:g}}return(u?.childKeys.length??0)===0?{element:i}:null}function Un(e,t,n,r){let o=Vn(e,t,n);return!o||o.parentElement!==r?null:o}function Vn(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(be(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return be(a)?a:null}function $n(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function be(e){return e?.nodeType===3}function Se(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let s of o){let i=yt(s),a=i?.getAttribute("data-vcp-edit-key")??"";if(i&&Xn(i,r,a))return i}return null}function yt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(je(t))return n??t;!Gn(r)&&!n&&(n=t)}t=t.parentElement}return n}function je(e){return e.getAttribute(gn)!==null}function Gn(e){return zn(e.split("::")[0]??"")}function zn(e){if(!e)return!1;let t=Jn(e);return t===he||t.startsWith(`${he}/`)||t.includes(`/${he}/`)||t.endsWith(`/${he}`)}function Jn(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 F(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${_t(r)}"]`))),n,r);if(o.length<=1)return{key:at(n,r,0)};let s=o.indexOf(t);return s>=0?{key:at(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function it(e,t,n){return F(e,t,n)}function U(e,t,n){let r=ie(t.key)??t.key,o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${_t(r)}"]`))),n,t.key);if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(ie(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=Yn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function at(e,t,n){return We(e,t)[n]?.key??t}function Yn(e,t){let n=ie(t);if(!n)return null;let o=We(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function We(e,t){return(e?.entries??[]).filter(n=>(ie(n.key)??n.key)===t)}function bt(e,t,n){let r=St(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function Xn(e,t,n){let r=St(t,n);return!r||e.tagName.toLowerCase()===r}function St(e,t){let n=ie(t)??t,o=(e?.entries.find(s=>s.key===t)??We(e,n)[0])?.tag.trim();return!o||o!==o.toLowerCase()?null:o}var Qn=2,Zn=4;function Et(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&Zn)!==0?-1:(r&Qn)!==0?1:0})}function ie(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(rt);if(n<0)break;let r=Number(t.slice(n+rt.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Ln(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function er(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>or(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function O(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=Ee(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([y,_])=>[y,_??""])),attributes:Object.fromEntries(e.getAttributeNames().map(y=>[y,e.getAttribute(y)??""]))}:{},u=mt({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),f=je(e),m=!!(s&&/^[A-Z]/.test(s.tag)),g=!s||!m;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:m?"component-call":"jsx"}:{},...m&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:f?!1:(s?.childKeys.length??0)>0||u.canInsertChild||g&&we(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:er(e),spacing:Ln(e)}}function tr(e,t,n,r,o){let s=O(t,n,r,"summary"),i=null,a=()=>{i===null&&(i=dt(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let _=O(t,n,r,"summary");nr(s,_)&&(s=_,o(_))},u=e.ResizeObserver,f=typeof u=="function"?new u(a):null;f?.observe(t);let m=e.MutationObserver,g=typeof m=="function"?new m(a):null;g?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",a,{passive:!0});let y=e.visualViewport;return y?.addEventListener?.("resize",a,{passive:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(ft(e,i),i=null),f?.disconnect(),g?.disconnect(),e.removeEventListener("resize",a),y?.removeEventListener?.("resize",a),e.document.removeEventListener("load",a,!0)}}function nr(e,t){return vt(e.rect,t.rect)||rr(e.childRects,t.childRects)||ct(e.spacing,t.spacing)||ct(e.layout,t.layout)}function rr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,s)=>vt(o,r[s]??o))}function ct(e,t){let n=e??{},r=t??{},o=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(o).some(s=>n[s]!==r[s])}function or(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function vt(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 sr(e,t,n,r,o,s,i){let a=e.document,c=Se(a,t,n,s);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?U(a,o,s):null;if(u&&Ke(c,u))return me(a,c,"self-or-descendant",s,i);if(r==="move"&&u){let I=ur(a,c,u,s,i);if(I){let D=Ae(I.child,I.targetParent,t,n,"nearest");if(D)return ge(a,I.child,I.targetParent,D,s,i)}}let f=null,m=!1,g=c,y=c.parentElement;for(;y;){if(y.getAttribute("data-vcp-edit-key")){if(u&&Ke(y,u))return me(a,c,"self-or-descendant",s,i);let I=ut(y,r,i);if(I==="accept"){f={child:g,targetParent:y};break}I==="blocked"&&(m=!0),g=y}y=y.parentElement}let _=ut(c,r,i);if(_==="accept"){if(f){let I=Ae(f.child,f.targetParent,t,n,"edge");if(I)return ge(a,f.child,f.targetParent,I,s,i)}return ge(a,c,c,ir(c,t,n),s,i)}if(f){let I=Ae(f.child,f.targetParent,t,n,"nearest");return ge(a,f.child,f.targetParent,I??"after",s,i)}return _==="blocked"||m?me(a,c,"operation-boundary-blocked",s,i):me(a,c,"no-accepting-parent",s,i)}function me(e,t,n,r,o){return{anchorHit:O(t,F(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function ge(e,t,n,r,o,s){let i=O(t,F(e,t,o),s,"summary"),a=O(n,F(e,n,o),s,"summary"),c=Ee(n).indicatorOrientation,u=r==="append"||r==="prepend"?ar(n.getBoundingClientRect(),c,r):cr(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:u}}function ut(e,t,n){if(je(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return we(s)?"accept":"not-container"}function Ae(e,t,n,r,o){let s=Ee(t).indicatorOrientation,i=e.getBoundingClientRect(),a=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function ir(e,t,n){let r=Ee(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 Ee(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function ar(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 cr(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 Ke(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ur(e,t,n,r,o){let s=lr(e,t,n,r,o);if(s)return s;let i=fr(n);if(!i||t===i)return null;let a=t,c=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==i;)a.getAttribute("data-vcp-edit-key")&&(c=a),a=a.parentElement;return a!==i||!c||c===i||c===n||Ke(c,n)?null:{child:c,targetParent:i}}function lr(e,t,n,r,o){if(!o)return null;let s=F(e,n,r),a=o(s.key)?.parentKey??null;if(!a)return null;let u=F(e,t,r).key;for(;u;){let f=o(u);if(!f?.parentKey)return null;if(f.parentKey===a){if(u===s.key||dr(u,s.key,o))return null;let m=U(e,{key:u},r),g=U(e,{key:a},r);return m&&g?{child:m,targetParent:g}:null}u=f.parentKey}return null}function dr(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n(r)?.parentKey}return!1}function fr(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function ye(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:w(e.scrollX),scrollY:w(e.scrollY),scrollWidth:Math.max(w(t?.scrollWidth),w(n?.scrollWidth),w(e.innerWidth)),scrollHeight:Math.max(w(t?.scrollHeight),w(n?.scrollHeight),w(e.innerHeight)),viewportWidth:w(e.innerWidth),viewportHeight:w(e.innerHeight)}}function pr(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 s=e.style,i=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(o==null||o===""){s.removeProperty(i);return}s.setProperty(i,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,s=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),i=r.value;if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i),r.priority)})}var hr=500,oe=new Map;function mr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function gr(e,t){if(oe.size>=hr){let n=oe.keys().next().value;n&&oe.delete(n)}oe.set(e,t)}var se=new Set;function yr(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of se)r.has(o)||n?.removeProperty(o);se.clear();for(let o of r)se.add(o);Rr(e,t.stylesheets??[])}function br(e){let t=e.documentElement?.style;for(let n of se)t?.removeProperty(n);se.clear();for(let n of xt(e))n.remove()}function Sr(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let a=Rt(o,i);a&&(s[i]=a)}return s}function Rt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return It(e,r,n)}function It(e,t,n){if(!t)return null;let r=Er(t);if(!r)return t;let o=Rt(e,r.name,n);return o||(r.fallback?It(e,r.fallback,n)??r.fallback:null)}function Er(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=vr(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function vr(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 Rr(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of xt(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(lt,"true"),i.setAttribute("href",s),o.appendChild(i)}}function xt(e){return Array.from(e.querySelectorAll(`link[${lt}]`))}function Ir(e,t,n,r,o={}){let s=o.textNode?xr(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,a=i.textContent??"",c=s?void 0:t.innerHTML,u=_r(i),f=!1,m=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",_),i.removeEventListener("blur",I),i.removeEventListener("input",D),Tr(i,u)},g=k=>{if(f)return;f=!0;let K=i.textContent??"";if(m(),k==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(K),k==="commit"&&K!==a){o.onCommitSnapshot?.({ref:n,initialText:a,...c!==void 0?{initialHtml:c}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:K}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(k){let K=k.target;K&&i.contains(K)||g("commit")}function _(k){if(k.key==="Escape"){k.preventDefault(),g("cancel");return}k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g("commit"))}function I(){g("commit")}function D(){r({kind:"text-edit-input",payload:{ref:n,hit:O(t,n,void 0,"full")}})}return Cr(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",_),i.addEventListener("blur",I),i.addEventListener("input",D),Nr(i),Dr(i,e.document),m}function xr(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 _r(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 Cr(e){kr(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 Tr(e,t){Oe(e,"contenteditable",t.contentEditable),Oe(e,"spellcheck",t.spellcheck),Oe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function kr(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 Oe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Pr(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 Nr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Dr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function _t(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function w(e){let t=Number(e);return Number.isFinite(t)?t:0}import Br from"node:http";import{randomBytes as Ar,timingSafeEqual as Or}from"node:crypto";import Fr from"node:path";import{WebSocket as Nt,WebSocketServer as Mr}from"ws";import{createPreviewSiteEditEngineRuntime as Kr}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as qr,scanNextAppRouterRoutes as wr}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as jr}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as Wr}from"@vcp-dev/contracts";var Hr="127.0.0.1",Ur=30218,Vr="/__vcp/site-edit/bridge",$r=6*1024*1024,Gr=3e3,Ct=50,Tt="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function hs(e){let t=Bt(e),n=Ot(t),r=At(),o=r.get(n);if(o)return o;let s=new ve(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function Dt(e,t){let n=new ve(Bt(t),e,!1);return n.start({listen:!1}),n}var ve=class{constructor(t,n=Br.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Kr({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=zr({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 jr({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??Ct,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),this.isStarted=!0}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=At(),n=Ot(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getDocument(r)},getObjectSummary:async(t,n)=>this.getRuntime().getObjectSummary(t,n?this.resolveRouteId(n):void 0),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 await r.refreshSourceForKey(t,o),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:async t=>this.getRuntime().executeOperation(this.normalizeRequest(t)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:t=>this.getRuntime().subscribe(t)}}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??Ct;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:wr(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=qr(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 Bt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Fr.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Hr,port:e.port??Ur,path:e.path??Vr,sessionKey:e.sessionKey??eo(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function At(){let e=globalThis;return e[Tt]??=new Map,e[Tt]}function Ot(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function zr(e){let t=new Mr({maxPayload:$r,noServer:!0}),n=new WeakSet,r=s=>{new fe({socket:new Ue(s),engine:e.engine,validateOperationRequest:i=>Wr.safeParse(i).success})},o=(s,i,a)=>{if(!Jr(s,e))return;let c=Yr(s,e);if(!c){i.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),i.destroy();return}c.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,i,a,u=>{t.emit("connection",u,s)})};return e.server.on("upgrade",o),t.on("connection",(s,i)=>{if(n.has(i)){r(s);return}zr(s,e.sessionKey,()=>{r(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var Ve=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){this.socket.readyState===Pt.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function $r(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Gr(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Ue(e.headers["x-vcp-site-edit-key"]),o=Ot(r,t.sessionKey),s=Ue(e.headers.host),i=Ue(e.headers.origin);return s&&!Jr(s,t.host,i)?null:i?Xr(i,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function zr(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Ur),o,s=()=>{clearTimeout(r),e.off("message",o),e.off("close",s)},i=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let c=B.parseMessage(a.toString());if(c.type!=="auth"||!Ot(c.payload.key,t)){i();return}s(),e.readyState===Pt.OPEN&&e.send(B.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{i()}},e.on("message",o),e.on("close",s)}function Ot(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Dr(n,r)}function Jr(e,t,n){let r=kt(e),o=kt(t);return r===o||Tt(o)&&Tt(r)&&(!n||$e(n,e))||Yr(o)&&(!n||$e(n,e))}function Yr(e){return e==="0.0.0.0"||e==="::"}function Tt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Xr(e,t,n){return n.includes(e)||(t?$e(e,t):!1)}function $e(e,t){try{return new URL(e).host===Ft(t)}catch{return!1}}function kt(e){let t=Ft(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Ft(e){return e.trim().toLowerCase()}function Ue(e){return Array.isArray(e)?e[0]:e}function Qr(){return Nr(32).toString("base64url")}import Zr from"node:http";import{existsSync as X,readFileSync as Y}from"node:fs";import{createRequire as wt}from"node:module";import xe from"node:path";import{basename as jt,dirname as ae,join as ce}from"node:path";import{fileURLToPath as Wt}from"node:url";var Lr="next",eo="127.0.0.1",to=3e3,Ie="/__vcp/site-edit/bridge",Ht="/__vcp/site-edit/health",Re="/__vcp/site-edit/client/",no=`${Re}auto-bootstrap.js`,Ut='data-vcp-site-edit-bootstrap="true"',ro=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],oo="@vcp-dev/site-edit-engine/webpack-loader",so=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,io=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ao=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Es(e={}){let t=xe.resolve(e.projectRoot??process.cwd()),n=e.host??eo,r=e.port??jo(process.env.PORT)??to,o=e.bridgePath??Ie,s=mo(o),i=Do(),a=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",c=await Mo(t),u=co(t),f=c({dev:!0,dir:t,hostname:n,port:r,...uo(u)}),m=f.getRequestHandler();await f.prepare();let g=null,y=Zr.createServer((R,D)=>{Io({basePath:a,bridgePath:o,bridgeHealthPath:s,bridgeSessionKey:i,getBridgeHealth:()=>g?.getHealth()??xo(o),handle:m,request:R,response:D}).catch(k=>{console.error(k),D.headersSent||(D.statusCode=500),D.end("site edit preview request failed")})});g=Nt(y,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??wo(t),projectRoot:t,basePath:a,host:n,port:r,path:o,sessionKey:i}),po({server:y,bridgePath:o,handleUpgrade:f.getUpgradeHandler()});let C=()=>{g?.stop(),f.close().catch(()=>{}),y.close()};return process.on("SIGINT",C),process.on("SIGTERM",C),await Wo(y,r,n),{bundler:u,close:C,server:y}}function co(e){let t=lo(e);return t&&fo(t)?"webpack":"turbopack"}function uo(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function lo(e){for(let t of ro){let n=ce(e,t);if(X(n))return Y(n,"utf8")}return null}function fo(e){return e.includes(oo)?!0:so.test(e)&&io.some(t=>t.test(e))}function po(e){let t=(n,r,o)=>{ho(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(s=>{console.error(s),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function ho(e,t){return new URL(e??"/","http://localhost").pathname===t}function mo(e=Ie){if(e===Ie)return Ht;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function go(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??yo()});return`<script type="module" ${Ut}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(no)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function yo(){return{bridge:Ge("@vcp-dev/site-edit-bridge"),contracts:Ge("@vcp-dev/contracts"),engine:Ge("@vcp-dev/site-edit-engine")}}function Ge(e){let t=wt(import.meta.url);try{let n=t.resolve(e),r=bo(n,e);if(!r)return;let o=JSON.parse(Y(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function bo(e,t){let n=xe.parse(e).root,r=ae(e);for(;r&&r!==n;){let o=ce(r,"package.json");if(X(o))try{if(JSON.parse(Y(o,"utf8")).name===t)return o}catch{return}r=ae(r)}}function So(e,t){if(e.includes(Ut))return e;let n=go(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function vs(e,t=ae(Wt(import.meta.url)),n=X){return Vt(e,t,n)?.path??null}function Vt(e,t=ae(Wt(import.meta.url)),n=X){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Re))return null;let o=r.slice(Re.length);if(!ao.has(o))return null;let s=ze(Ko(t),o);if(jt(t)!=="src")return{path:s,requiresTranspile:!1};let i=ze(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function Eo(e,t){let n=Vt(e.url);if(!n)return!1;if(!X(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await vo(Y(n.path,"utf8")):Y(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function vo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Io({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:s,request:i,response:a}){if(Ro(i,a,n,o)||await Eo(i,a))return;let c=_o(i),u=Co(i),f=c||u?Po(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await s(i,a)}catch(m){throw f(),m}}function Ro(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let s=r();return t.writeHead(s.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(s)),!0}function xo(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function _o(e){return To(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Co(e){return ko(e)?(e.headers["accept-encoding"]="identity",!0):!1}function To(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Re)||t===Ie||t===Ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function ko(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 Po(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),s=r.write.bind(e),i=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,c,u)=>(a!==void 0&&n.push(Mt(a,Kt(c))),qt(c),qt(u),!0),r.end=(a,c,u)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(Mt(f,Kt(c))),r.write=s,r.end=i,r.flushHeaders=o;let m=Buffer.concat(n),g=No(e,m,t);g!==m&&!e.headersSent&&e.removeHeader("content-length");let y=typeof a=="function"?a:typeof c=="function"?c:typeof u=="function"?u:void 0;return y?i(g,y):i(g)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function No(e,t,n){if(Bo(e,t))return Buffer.from(So(t.toString("utf8"),n));if(n.patchNextDevChunk&&Ao(e)){let r=t.toString("utf8"),o=Oo(r);if(o!==r)return Buffer.from(o)}return t}function Do(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Bo(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 Ao(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 Oo(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(`
4
+ `),i.destroy();return}c.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,i,a,u=>{t.emit("connection",u,s)})};return e.server.on("upgrade",o),t.on("connection",(s,i)=>{if(n.has(i)){r(s);return}Xr(s,e.sessionKey,()=>{r(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var Ue=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){this.socket.readyState===Nt.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function Jr(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Yr(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=He(e.headers["x-vcp-site-edit-key"]),o=Ft(r,t.sessionKey),s=He(e.headers.host),i=He(e.headers.origin);return s&&!Qr(s,t.host,i)?null:i?Lr(i,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Xr(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Gr),o,s=()=>{clearTimeout(r),e.off("message",o),e.off("close",s)},i=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let c=B.parseMessage(a.toString());if(c.type!=="auth"||!Ft(c.payload.key,t)){i();return}s(),e.readyState===Nt.OPEN&&e.send(B.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{i()}},e.on("message",o),e.on("close",s)}function Ft(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Or(n,r)}function Qr(e,t,n){let r=Pt(e),o=Pt(t);return r===o||kt(o)&&kt(r)&&(!n||Ve(n,e))||Zr(o)&&(!n||Ve(n,e))}function Zr(e){return e==="0.0.0.0"||e==="::"}function kt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Lr(e,t,n){return n.includes(e)||(t?Ve(e,t):!1)}function Ve(e,t){try{return new URL(e).host===Mt(t)}catch{return!1}}function Pt(e){let t=Mt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Mt(e){return e.trim().toLowerCase()}function He(e){return Array.isArray(e)?e[0]:e}function eo(){return Ar(32).toString("base64url")}import to from"node:http";import{existsSync as X,readFileSync as Y}from"node:fs";import{createRequire as jt}from"node:module";import xe from"node:path";import{basename as Wt,dirname as ae,join as ce}from"node:path";import{fileURLToPath as Ht}from"node:url";var no="next",ro="127.0.0.1",oo=3e3,Re="/__vcp/site-edit/bridge",Ut="/__vcp/site-edit/health",Ie="/__vcp/site-edit/client/",so=`${Ie}auto-bootstrap.js`,Vt='data-vcp-site-edit-bootstrap="true"',io=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ao="@vcp-dev/site-edit-engine/webpack-loader",co=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,uo=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],lo=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Is(e={}){let t=xe.resolve(e.projectRoot??process.cwd()),n=e.host??ro,r=e.port??Uo(process.env.PORT)??oo,o=e.bridgePath??Re,s=bo(o),i=Oo(),a=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",c=await wo(t),u=fo(t),f=c({dev:!0,dir:t,hostname:n,port:r,...po(u)}),m=f.getRequestHandler();await f.prepare();let g=null,y=to.createServer((I,D)=>{_o({basePath:a,bridgePath:o,bridgeHealthPath:s,bridgeSessionKey:i,getBridgeHealth:()=>g?.getHealth()??To(o),handle:m,request:I,response:D}).catch(k=>{console.error(k),D.headersSent||(D.statusCode=500),D.end("site edit preview request failed")})});g=Dt(y,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??Ho(t),projectRoot:t,basePath:a,host:n,port:r,path:o,sessionKey:i}),go({server:y,bridgePath:o,handleUpgrade:f.getUpgradeHandler()});let _=()=>{g?.stop(),f.close().catch(()=>{}),y.close()};return process.on("SIGINT",_),process.on("SIGTERM",_),await Vo(y,r,n),{bundler:u,close:_,server:y}}function fo(e){let t=ho(e);return t&&mo(t)?"webpack":"turbopack"}function po(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function ho(e){for(let t of io){let n=ce(e,t);if(X(n))return Y(n,"utf8")}return null}function mo(e){return e.includes(ao)?!0:co.test(e)&&uo.some(t=>t.test(e))}function go(e){let t=(n,r,o)=>{yo(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(s=>{console.error(s),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function yo(e,t){return new URL(e??"/","http://localhost").pathname===t}function bo(e=Re){if(e===Re)return Ut;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function So(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Eo()});return`<script type="module" ${Vt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(so)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Eo(){return{bridge:$e("@vcp-dev/site-edit-bridge"),contracts:$e("@vcp-dev/contracts"),engine:$e("@vcp-dev/site-edit-engine")}}function $e(e){let t=jt(import.meta.url);try{let n=t.resolve(e),r=vo(n,e);if(!r)return;let o=JSON.parse(Y(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function vo(e,t){let n=xe.parse(e).root,r=ae(e);for(;r&&r!==n;){let o=ce(r,"package.json");if(X(o))try{if(JSON.parse(Y(o,"utf8")).name===t)return o}catch{return}r=ae(r)}}function Ro(e,t){if(e.includes(Vt))return e;let n=So(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function xs(e,t=ae(Ht(import.meta.url)),n=X){return $t(e,t,n)?.path??null}function $t(e,t=ae(Ht(import.meta.url)),n=X){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Ie))return null;let o=r.slice(Ie.length);if(!lo.has(o))return null;let s=Ge(jo(t),o);if(Wt(t)!=="src")return{path:s,requiresTranspile:!1};let i=Ge(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function Io(e,t){let n=$t(e.url);if(!n)return!1;if(!X(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await xo(Y(n.path,"utf8")):Y(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function xo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function _o({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:s,request:i,response:a}){if(Co(i,a,n,o)||await Io(i,a))return;let c=ko(i),u=Po(i),f=c||u?Bo(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await s(i,a)}catch(m){throw f(),m}}function Co(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let s=r();return t.writeHead(s.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(s)),!0}function To(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function ko(e){return No(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Po(e){return Do(e)?(e.headers["accept-encoding"]="identity",!0):!1}function No(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Ie)||t===Re||t===Ut)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Do(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 Bo(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),s=r.write.bind(e),i=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,c,u)=>(a!==void 0&&n.push(Kt(a,qt(c))),wt(c),wt(u),!0),r.end=(a,c,u)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(Kt(f,qt(c))),r.write=s,r.end=i,r.flushHeaders=o;let m=Buffer.concat(n),g=Ao(e,m,t);g!==m&&!e.headersSent&&e.removeHeader("content-length");let y=typeof a=="function"?a:typeof c=="function"?c:typeof u=="function"?u:void 0;return y?i(g,y):i(g)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function Ao(e,t,n){if(Fo(e,t))return Buffer.from(Ro(t.toString("utf8"),n));if(n.patchNextDevChunk&&Mo(e)){let r=t.toString("utf8"),o=Ko(r);if(o!==r)return Buffer.from(o)}return t}function Oo(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Fo(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 Mo(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 Ko(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(`
5
5
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
6
- `)],[["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])=>Fo(n,r,o),e)}function Fo(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 Mt(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Kt(e){return typeof e=="string"?e:void 0}function qt(e){typeof e=="function"&&e()}async function Mo(e){let n=wt(ce(e,"package.json"))(Lr);return n.default??n}function Ko(e){return jt(e)!=="src"?e:ze(qo(e),"dist")}function qo(e){return $t(e)?xe.posix.dirname(e):ae(e)}function ze(e,t){return $t(e)?xe.posix.join(e,t):ce(e,t)}function $t(e){return e.includes("/")&&!e.includes("\\")}function wo(e){let t=ce(e,".vcp/current-snapshot.json");if(!X(t))return"sandbox_worktree";try{let n=JSON.parse(Y(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function jo(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Wo(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Hr as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,nt as SITE_EDIT_FRAME_RUNTIME_CHANNEL,tt as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ve as SiteEditBridgeServer,fe as SiteEditBridgeSocketServer,B as SiteEditBridgeTransport,pe as SiteEditWebSocketClient,Me as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Fe as VCP_SITE_EDIT_ROUTE_READY_EVENT,et as VCP_WINDOW_MESSAGE_SOURCE,Xo as VCP_WINDOW_MESSAGE_VERSION,po as attachNextDevUpgradeHandler,Nt as attachSiteEditBridgeServer,Vr as attachSiteEditWebSocketServer,go as createSiteEditAutoBootstrapHtmlSnippet,Le as createSiteEditBridge,re as createSiteEditFrameRuntimeMessage,fn as createVcpWindowMessageEnvelope,Xe as decodeRenderDocument,Ye as encodeRenderDocument,ds as ensureSiteEditBridgeServerStarted,So as injectSiteEditAutoBootstrap,zt as isCompactRenderDocument,en as isDesignerTraceEnabled,rt as isSiteEditFrameRuntimeMessage,pn as isVcpWindowMessageEnvelope,Oo as patchNextFirefoxDevChunk,Co as prepareFirefoxNextDevChunkPatchRequest,_o as prepareSiteEditHtmlInjectionRequest,mo as resolveSiteEditBridgeHealthPath,Vt as resolveSiteEditClientAsset,vs as resolveSiteEditClientAssetPath,co as resolveSiteEditNextDevBundler,bn as resolveSiteEditRouteId,En as resolveSiteEditWebSocketUrl,tn as sanitizeTracePayload,es as startSiteEditAutoBootstrap,Tn as startSiteEditFrameRuntime,Es as startSiteEditNextDevServer,$ as traceDesignerEvent,vo as transpileSiteEditClientSource};
6
+ `)],[["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])=>qo(n,r,o),e)}function qo(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 Kt(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function qt(e){return typeof e=="string"?e:void 0}function wt(e){typeof e=="function"&&e()}async function wo(e){let n=jt(ce(e,"package.json"))(no);return n.default??n}function jo(e){return Wt(e)!=="src"?e:Ge(Wo(e),"dist")}function Wo(e){return Gt(e)?xe.posix.dirname(e):ae(e)}function Ge(e,t){return Gt(e)?xe.posix.join(e,t):ce(e,t)}function Gt(e){return e.includes("/")&&!e.includes("\\")}function Ho(e){let t=ce(e,".vcp/current-snapshot.json");if(!X(t))return"sandbox_worktree";try{let n=JSON.parse(Y(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Uo(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Vo(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{$r as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,tt as SITE_EDIT_FRAME_RUNTIME_CHANNEL,et as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ve as SiteEditBridgeServer,fe as SiteEditBridgeSocketServer,B as SiteEditBridgeTransport,pe as SiteEditWebSocketClient,Me as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Fe as VCP_SITE_EDIT_ROUTE_READY_EVENT,Le as VCP_WINDOW_MESSAGE_SOURCE,Lo as VCP_WINDOW_MESSAGE_VERSION,go as attachNextDevUpgradeHandler,Dt as attachSiteEditBridgeServer,zr as attachSiteEditWebSocketServer,So as createSiteEditAutoBootstrapHtmlSnippet,Ze as createSiteEditBridge,re as createSiteEditFrameRuntimeMessage,pn as createVcpWindowMessageEnvelope,Ye as decodeRenderDocument,Je as encodeRenderDocument,hs as ensureSiteEditBridgeServerStarted,Ro as injectSiteEditAutoBootstrap,Jt as isCompactRenderDocument,tn as isDesignerTraceEnabled,nt as isSiteEditFrameRuntimeMessage,hn as isVcpWindowMessageEnvelope,Ko as patchNextFirefoxDevChunk,Po as prepareFirefoxNextDevChunkPatchRequest,ko as prepareSiteEditHtmlInjectionRequest,bo as resolveSiteEditBridgeHealthPath,$t as resolveSiteEditClientAsset,xs as resolveSiteEditClientAssetPath,fo as resolveSiteEditNextDevBundler,Sn as resolveSiteEditRouteId,vn as resolveSiteEditWebSocketUrl,nn as sanitizeTracePayload,rs as startSiteEditAutoBootstrap,kn as startSiteEditFrameRuntime,Is as startSiteEditNextDevServer,$ as traceDesignerEvent,xo as transpileSiteEditClientSource};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-bridge",
3
- "version": "0.4.7",
3
+ "version": "0.4.9",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -74,8 +74,8 @@
74
74
  "typecheck": "tsc -p tsconfig.json --noEmit"
75
75
  },
76
76
  "dependencies": {
77
- "@vcp-dev/contracts": "0.4.7",
78
- "@vcp-dev/site-edit-engine": "0.4.7",
77
+ "@vcp-dev/contracts": "0.4.9",
78
+ "@vcp-dev/site-edit-engine": "0.4.9",
79
79
  "@types/ws": "^8.18.1",
80
80
  "ws": "^8.20.1"
81
81
  },