@vcp-dev/site-edit-bridge 0.4.5 → 0.4.6

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