@vcp-dev/site-edit-bridge 0.4.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- function Ye(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let c=t.get(a);if(typeof c=="number")return c;let u=n.length;return n.push(a),t.set(a,u),u},i=a=>{let c=null;for(let u of Jt(a)){let f=`${c??"root"}\0${u}`,m=r.get(f);if(typeof m=="number"){c=m;continue}let g=o.length;o.push({parent:c,token:s(u)}),r.set(f,g),c=g}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,tokens:n,nodes:o,rootKeyNodeIds:e.rootKeys.map(i),entries:e.entries.map(a=>({keyNodeId:i(a.key),tag:a.tag,label:a.label,parentKeyNodeId:a.parentKey?i(a.parentKey):null,childKeyNodeIds:a.childKeys.map(i),operationSummary:a.operationSummary}))}}function Xe(e){if(!zt(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let a=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,a),a};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function zt(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Jt(e){if(!e)return[];let t=[],n=0,r=Je(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=Je(e,n+(e.startsWith("::",n)?2:1)),r<0){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r}return t}function Je(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var B=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!q(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?q(t.payload)&&typeof t.payload.id=="string":t.type==="event"?q(t.payload)&&q(t.payload.event):t.type==="auth"?q(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?q(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!q(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Yt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},fe=class{constructor(t){this.options=t,this.messageQueue=new Pe,this.eventDispatcher=new ke(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Ye((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=B.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(t){try{await this.handleMessage(B.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Xt(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(B.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ke=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},Pe=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function q(e){return typeof e=="object"&&e!==null}function Yt(e){return q(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&q(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&q(e.params)}function Xt(e){try{return B.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Qt="vcp:designer:trace",Zt="designer_trace",Qe="__VCP_DESIGNER_TRACE__";var Lt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function en(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Qt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Zt)==="1"}catch{return!1}}function $(e,t={},n=globalThis){if(!en(n))return;let r={type:e,timestamp:Date.now(),payload:tn(t)},o=n,s=o[Qe]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Qe]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function tn(e){return Ne(e,0)}function Ne(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Ne(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Lt.test(r)){n[r]="[redacted]";continue}n[r]=Ne(o,t+1)}return n}var pe=class{constructor(t){this.options=t,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===De&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((t,n)=>{let r;try{r=this.createSocket(this.options.url)}catch(a){let c=ne(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let s=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(B.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(ne(a,"WebSocket auth failed"),"failed")}return}s()}},r.onerror=a=>{if(this.socket!==r)return;let c=ne(a,"WebSocket failed");i(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,r,o,()=>{s()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let c=this.intentionalClose,u=new Error(sn(a,{intentional:c}));i(u,c?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let t=this.socket;if(!t){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(t,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(t){return this.connectionStatusListeners.add(t),t({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(t)}}getDocument(t){return this.request("get-document",{routeId:t})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}getSourceTree(){return this.request("get-source-tree",{})}getSourceFile(t){return this.request("get-source-file",t)}resolveSourceLocation(t){return this.request("resolve-source-location",t)}execute(t){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r||r.readyState!==De||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let o=`${t}-${this.sequence+=1}`,s=un(o,t,n);return $("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Ze(n.request,"kind"),documentVersion:Ze(n.request,"documentVersion")}),new Promise((i,a)=>{let c=this.resolveRequestTimeoutMs(t),u=c>0?setTimeout(()=>{let f=this.pending.get(o);f&&(this.pending.delete(o),$("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),f.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:f=>i(f),reject:a});try{r.send(B.stringifyMessage(s))}catch(f){let m=ne(f,"WebSocket send failed");this.clearPendingRequest(o),a(m),this.cleanupSocket(r,m,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(B.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(s){let i=ne(s,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=B.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.clearPendingRequest(n.payload.id),n.type==="error"){$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:an(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Xe(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let[n,r]of[...this.pending])this.clearPendingRequest(n),r.reject(t)}clearPendingRequest(t){let n=this.pending.get(t);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(t))}resolveRequestTimeoutMs(t){let n=this.options.requestTimeoutMsByKind?.[t];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):on[t]??rn}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let o=this.connectAttempt;this.connectAttempt=null,o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(r,n.message),t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{(t.readyState===nn||t.readyState===De)&&t.close()}catch{}}setConnectionState(t,n){if(this.connectionState===t&&!n)return;this.connectionState=t;let r={state:t,...n?{message:n}:{}};this.options.onConnectionStatus?.(r);for(let o of this.connectionStatusListeners)o(r)}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}},nn=0,De=1,rn=15e3,on={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function ne(e,t){return e instanceof Error?e:new Error(t)}function sn(e,t){return t.intentional?"WebSocket disconnected":e?.code===1008?e.reason?`Bridge session authentication failed: ${e.reason}`:"Bridge session authentication failed":e?.reason?`WebSocket closed: ${e.reason}`:typeof e?.code=="number"&&e.code!==1005?`WebSocket closed with code ${e.code}`:"WebSocket closed"}function Ze(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function an(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function Le(e){return new Be(e)}var Be=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,ln(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,dn(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return cn(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}async getSourceTree(){return this.params.client.getSourceTree()}async getSourceFile(t){return this.params.client.getSourceFile(t)}async resolveSourceLocation(t){return this.params.client.resolveSourceLocation({...t,routeId:t.routeId??this.params.routeId})}async execute(t){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId){this.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return $("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){$("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}$("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function cn(e){return e.version===0&&e.rootKeys.length===0}function un(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-source-tree":return{type:"request",payload:{id:e,kind:t}};case"get-source-file":return{type:"request",payload:{id:e,kind:t,path:String(n.path)}};case"resolve-source-location":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t}}}}function ln(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function dn(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var et="vcp-window-message",Xo=1;function fn(e){return{source:et,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function pn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===et&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var tt="site-edit",nt="frame-runtime";function re(e,t={}){return fn({namespace:tt,channel:nt,sessionKey:t.sessionKey,body:e})}function rt(e){return!pn(e)||e.namespace!==tt||e.channel!==nt?!1:typeof e.body?.type=="string"}var Fe="vcp-site-edit:route-ready",Me="vcp-site-edit:bridge-status",hn=1e3,mn="data-vcp-ui-component",lt="data-vcp-theme-preview",ot="::repeat-item#",he="components/ui",gn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),yn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function bn(e,t=""){let n=ht(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function Sn(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function En(e,t={}){if(t.explicit_ws_url)return t.explicit_ws_url.startsWith("/")?`${e.location.protocol==="https:"?"wss:":"ws:"}//${e.location.host}${t.explicit_ws_url}`:t.explicit_ws_url;let n=e.location.protocol==="https:"?"wss:":"ws:",r=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return`${n}//${r}${t.path??"/__vcp/site-edit/bridge"}`}async function es(e=window,t={}){let n=En(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=vn({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(In(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let s={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},i,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===i,c=t.create_client??(p=>new pe({url:p,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Bn,f=()=>{s.retryTimer&&(e.clearTimeout(s.retryTimer),s.retryTimer=void 0)},m=()=>bn(e.location.pathname,t.basePath||""),g=p=>{On(e,p)},y=p=>{s.currentDocument=p,s.currentEntriesByKey=new Map((p?.entries??[]).map(b=>[b.key,b]))},C=()=>{s.unsubscribeConnectionStatus?.(),s.unsubscribeConnectionStatus=void 0,s.unsubscribeDocument?.(),s.unsubscribeDocument=void 0},R=(p,b)=>!s.disposed&&b===s.routeSequence&&p===m(),D=async(p,b)=>{let x=s.activeBridge;if(!x)return null;let _=await x.getDocument(p);return R(p,b)&&y(_.data),_.data},k=()=>{C(),y(null);let p=s.activeBridge;s.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let b=s.activeClient;s.activeClient=null,b?.disconnect()},K=p=>p===i.routeId&&!!s.activeBridge&&!!(s.currentDocument&&Mn(s.currentDocument,p))&&Fn(s.activeClient),_e=p=>Math.min(hn*2**Math.max(0,p),8e3),Q=(p,b,x)=>{if(s.disposed)return;f();let _=_e(x);g({state:"reconnecting",routeId:p,attempt:x,retryInMs:_,messageKey:"studio.status.previewBridgeConnecting"}),s.retryTimer=e.setTimeout(()=>{s.retryTimer=void 0,!(s.disposed||b!==s.routeSequence)&&le(x+1).catch(h=>{let d=m();if(p===d){if(J(h)){g({state:"reload-required",routeId:p,attempt:x,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(p,s.routeSequence,x+1)}})},_)},Z=(p,b,x)=>{if(!R(p,b)||s.activeClient===null)return;if(J(x.message)){k(),f(),g({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let _=s.activeClient;C(),y(null);let h=s.activeBridge;s.activeBridge=null,h&&e.__VCP_SITE_EDIT__===h&&delete e.__VCP_SITE_EDIT__,s.activeClient=null,_?.disconnect(),Q(p,b,0)},ue=p=>{let b=m(),x=s.routeSequence;if(!(!R(b,x)||s.activeClient===null)){if(J(p)){k(),f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}pt(p)&&Z(b,x,{state:"failed",message:we(p,"Site edit bridge request failed")})}};s.cleanupFrameRuntime=Tn(e,{getCurrentDocument:()=>s.currentDocument,getDocumentEntry:p=>s.currentEntriesByKey.get(p)??null,onBridgeRequestError:p=>{ue(p)}});let L=async()=>le(0),le=async p=>{if(s.disposed)return;let b=m();if(K(b))return;let x=s.syncInFlight;if(x?.routeId===b)return x.promise;let _=s.routeSequence+1,h=Ce(b,_,p);s.syncInFlight={routeId:b,sequence:_,promise:h};try{await h}finally{s.syncInFlight?.promise===h&&(s.syncInFlight=null)}},Ce=async(p,b,x)=>{s.routeSequence=b,f(),k(),g({state:x>0?"reconnecting":"connecting",routeId:p,attempt:x,messageKey:x>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let _=c(n),h=!1;s.activeClient=_,s.unsubscribeConnectionStatus=_.subscribeConnectionStatus?.(d=>{h&&(d.state==="closed"||d.state==="failed")&&Z(p,b,d)});try{if(await _.connect(),!R(p,b)){_.disconnect();return}let d=Le({routeId:p,client:_,initialDocument:Cn(p)});s.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),s.activeClient=_,s.unsubscribeDocument=d.subscribe(T=>{T.type==="site-edit.document.changed"&&T.routeId===p&&D(p,b).catch(()=>{})}),a()&&(i.routeId=p);let l=await D(p,b);if(!R(p,b)){_.disconnect();return}h=!0,g({state:"ready",routeId:p,attempt:x,messageKey:"studio.status.previewReady"}),Sn(e,{documentVersion:l?.version??0,routeId:p,versions:t.runtime_versions}),An(e,{routeId:p,version:l?.version??0})}catch(d){if(C(),s.activeClient===_&&(s.activeClient=null),s.activeBridge&&e.__VCP_SITE_EDIT__===s.activeBridge&&delete e.__VCP_SITE_EDIT__,s.activeBridge=null,_.disconnect(),y(null),!R(p,b))return;throw g({state:J(d)?"reload-required":"failed",routeId:p,attempt:x,messageKey:J(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},Te=p=>{if(s.disposed)return;let b=m();if(J(p)){f(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Q(b,s.routeSequence,0)},j=()=>{s.syncScheduled||s.disposed||(s.syncScheduled=!0,u(()=>{s.syncScheduled=!1,!s.disposed&&L().catch(p=>Te(p))}))},W=()=>{s.disposed||(s.disposed=!0,s.syncScheduled=!1,s.syncInFlight=null,f(),s.routeSequence+=1,s.unbindRouteChange?.(),s.unbindRouteChange=void 0,s.unbindBootstrapLifecycle?.(),s.unbindBootstrapLifecycle=void 0,s.cleanupFrameRuntime(),k(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(i={started:!0,signature:r,syncRoute:L,cleanup:W},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=i,s.unbindBootstrapLifecycle=xn(e,W),s.unbindRouteChange=Dn(e,j,m),t.defer_initial_sync){j();return}await L()}function vn(e){return{basePath:ht(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:Rn(e.options.bridge_session_key)}}function In(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Rn(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function xn(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),_n(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function _n(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Cn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Tn(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,c=null,u=null,f=null,m=new Map,g=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,y=()=>{n?.(),n=null,r=null},C=()=>{o?.(),o=null,s?.(),s=null},R=(h,d,l)=>{let T=i?.sessionKey!==h||i?.sourceWindow!==d||i?.targetOrigin!==l;i={sessionKey:h,sourceWindow:d,targetOrigin:l},T&&(u=null,f=null)},D=(h,d)=>{let l=e.parent&&e.parent!==e?e.parent:null;return!l||d!==l?!1:!g||h===g},k=()=>{for(let h of m.values())h();m.clear()},K=h=>JSON.stringify([h.routeId,h.version]),_e=()=>!c||c.state==="ready",Q=h=>JSON.stringify([h.state,h.routeId??null,h.attempt??null,h.retryInMs??null,h.messageKey??null]),Z=h=>{if(!_e())return;let d=K(h);u!==d&&(s?.(),s=null,j({kind:"route-ready",payload:{routeId:h.routeId,version:h.version}}),i&&(u=d))},ue=h=>{let d=Q(h);f!==d&&(h.state!=="ready"&&(u=null,a=null),j({kind:"bridge-status",payload:h}),i&&(f=d))},L=h=>{a=h,Z(h)},le=h=>{c=h,ue(h)},Ce=()=>{a&&Z(a)},Te=()=>{c&&ue(c)},j=h=>{i&&i.sourceWindow.postMessage(re({type:"event",...h},{sessionKey:i.sessionKey}),i.targetOrigin)},W=(h,d,l,T)=>{let P=Se(e.document,d.clientX,d.clientY,t.getCurrentDocument?.()??null),N=P?M(P,l==="full"?O(e.document,P,t.getCurrentDocument?.()??null):at(e.document,P,t.getCurrentDocument?.()??null),t.getDocumentEntry,l):null;T&&N&&(h==="pointer-click"||h==="pointer-double-click")&&(T.preventDefault(),T.stopPropagation(),typeof T.stopImmediatePropagation=="function"&&T.stopImmediatePropagation()),j({kind:h,payload:{clientX:d.clientX,clientY:d.clientY,buttons:Number(d.buttons??0),hit:N}})},p=(h,d,l)=>{C(),i={sessionKey:h,sourceWindow:d,targetOrigin:l};let T=Cr(e.document),P=null,N=null,S=()=>{N=null;let E=P;P=null,E&&W("pointer-move",E,"summary")},F=E=>{P={clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},N===null&&(N=dt(e,S))},V=E=>{W("pointer-down",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},z=E=>{W("pointer-up",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},H=E=>{W("pointer-cancel",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},G=E=>{W("pointer-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},ee=E=>{W("pointer-double-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},te=()=>{j({kind:"scroll",payload:{metrics:ye(e)}})};e.document.addEventListener("pointerdown",V,!0),e.document.addEventListener("pointermove",F,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",z,!0),e.document.addEventListener("pointercancel",H,!0),e.document.addEventListener("click",G,!0),e.document.addEventListener("dblclick",ee,!0),e.addEventListener("scroll",te,{passive:!0}),o=()=>{N!==null&&(ft(e,N),N=null),P=null,T(),e.document.removeEventListener("pointerdown",V,!0),e.document.removeEventListener("pointermove",F,!0),e.document.removeEventListener("pointerup",z,!0),e.document.removeEventListener("pointercancel",H,!0),e.document.removeEventListener("click",G,!0),e.document.removeEventListener("dblclick",ee,!0),e.removeEventListener("scroll",te)}},b=h=>{let d=h.detail;d?.routeId&&L(d)},x=h=>{let d=h.detail;d?.state&&le(d)},_=h=>{let d=h.data;if(!rt(d)||d.body.type!=="request"||d.body.kind!=="apply-node-patch"&&d.body.kind!=="get-hit-by-ref"&&d.body.kind!=="get-path-by-ref"&&d.body.kind!=="get-scroll-metrics"&&d.body.kind!=="scroll-to"&&d.body.kind!=="scroll-by"&&d.body.kind!=="set-interaction-mode"&&d.body.kind!=="set-theme-override"&&d.body.kind!=="clear-theme-override"&&d.body.kind!=="get-theme-variables"&&d.body.kind!=="compute-drop-target-at-point"&&d.body.kind!=="observe-node-bounds"&&d.body.kind!=="clear-node-bounds-observer"&&d.body.kind!=="restore-text-edit"&&d.body.kind!=="clear-text-edit-rollback"&&d.body.kind!=="start-text-edit-at-point"&&d.body.kind!=="hit-test-at-point"&&!st(d.body))return;let l=d.body,T=typeof d.sessionKey=="string"?d.sessionKey:null,P=h.source,N=h.origin;if(!T||!N||!P||typeof P.postMessage!="function"||!D(T,P))return;if(i){if(i.sourceWindow!==P||i.targetOrigin!==N)return;i.sessionKey!==T&&(y(),C(),k(),i=null)}R(T,P,N),Te(),Ce();let S=F=>{let V=typeof l.id=="string"?l.id:"unknown";P.postMessage(re({id:V,...F},{sessionKey:T}),N)};try{if(st(l)){kn({message:l,sendEvent:v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},sendResponse:S,subscriptions:m,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(l.kind==="apply-node-patch"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let I=l.payload.preview,A=I?fr(I.sessionId,l.payload.ref):null;if(A&&I){let de=oe.get(A)??-1;if(I.revision<de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,stale:!0,latestRevision:de}});return}if(I.revision===de){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,duplicate:!0,latestRevision:de}});return}}if(lr(v,l.payload.patch),A&&I&&pr(A,I.revision),I?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:I.revision}});return}S({type:"response",ok:!0,result:M(v,O(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,I?.responseDetail??"full")});return}if(l.kind==="get-hit-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:M(v,O(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(l.kind==="get-path-by-ref"){let v=U(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let I=[],A=v;for(;A;)A.getAttribute("data-vcp-edit-key")&&I.push(M(A,O(e.document,A,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),A=A.parentElement;S({type:"response",ok:!0,result:I.reverse()});return}if(l.kind==="restore-text-edit"||l.kind==="clear-text-edit-rollback"){let v=l.payload.ref;if(l.kind==="clear-text-edit-rollback"){r&&it(r.ref,v)&&(r=null),S({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!it(r.ref,v)){S({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let I=wn(e.document,r,t.getCurrentDocument?.()??null);r=null,S(I?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(l.kind==="get-scroll-metrics"){S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-to"){let v=Number(l.payload.x),I=Number(l.payload.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:I}),S({type:"response",ok:!0,result:ye(e)});return}if(l.kind==="scroll-by"){let v=Number(l.payload.deltaX),I=Number(l.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:I}),S({type:"response",ok:!0,result:{...ye(e),scrolled:!0}});return}if(l.kind==="set-interaction-mode"){l.payload.enabled?p(T,P,N):i?.sourceWindow===P&&i.targetOrigin===N&&i.sessionKey===T&&C(),S({type:"response",ok:!0,result:{interactionEnabled:l.payload.enabled}});return}if(l.kind==="set-theme-override"){hr(e.document,l.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(l.kind==="clear-theme-override"){mr(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(l.kind==="get-theme-variables"){S({type:"response",ok:!0,result:gr(e.document,l.payload.names)});return}if(l.kind==="compute-drop-target-at-point"){let v=Number(l.payload?.x),I=Number(l.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:nr(e,v,I,l.payload.dragKind,l.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(l.kind==="observe-node-bounds"){let v=l.payload.ref;if(!v){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let I=U(e.document,v,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}s?.(),s=er(e,I,v,t.getDocumentEntry,A=>j({kind:"node-bounds-change",payload:{hit:A}})),S({type:"response",ok:!0,result:{observing:!0}}),j({kind:"node-bounds-change",payload:{hit:M(I,v,t.getDocumentEntry,"summary")}});return}if(l.kind==="clear-node-bounds-observer"){s?.(),s=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(l.kind!=="hit-test-at-point"&&l.kind!=="start-text-edit-at-point")return;let F=Number(l.payload?.x),V=Number(l.payload?.y);if(!Number.isFinite(F)||!Number.isFinite(V)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let z=l.kind==="hit-test-at-point"?Se(e.document,F,V,t.getCurrentDocument?.()??null):Wn(e.document,F,V,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!z){S({type:"response",ok:!1,error:l.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let H=l.kind==="start-text-edit-at-point"?z:null,G=l.kind==="hit-test-at-point"?z:H.element,ee=l.payload.detailLevel??"full",te=ee==="full"?O(e.document,G,t.getCurrentDocument?.()??null):at(e.document,G,t.getCurrentDocument?.()??null),E=H&&typeof H.textSegmentIndex=="number"?{...te,textSegmentIndex:H.textSegmentIndex}:te,Gt=M(G,E,t.getDocumentEntry,ee);if(l.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:Gt});return}y(),n=Er(e,G,E,v=>{P.postMessage(re({type:"event",...v},{sessionKey:T}),N)},{...H?.textNode?{textNode:H.textNode}:{},onCommitSnapshot:v=>{r=v}}),S({type:"response",ok:!0,result:{ref:E}})}catch(F){S({type:"response",ok:!1,error:F instanceof Error?F.message:"Failed to start text edit"})}};return e.addEventListener("message",_),e.addEventListener(Fe,b),e.addEventListener(Me,x),()=>{y(),C(),i=null,k(),e.removeEventListener("message",_),e.removeEventListener(Fe,b),e.removeEventListener(Me,x)}}function st(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function kn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,onBridgeRequestError:s,windowLike:i}){let a=i.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await a.getDocument(e.payload.routeId)});return;case"bridge-ensure-document-version":if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}n({type:"response",ok:!0,result:a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await a.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let c=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Pn(c,e.payload.key,i.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":n({type:"response",ok:!0,result:await a.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let c=e.payload.subscriptionId;r.get(c)?.();let u=a.subscribe(f=>{t({kind:"bridge-event",payload:{event:f,subscriptionId:c}})});r.set(c,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let c=e.payload.subscriptionId;r.get(c)?.(),r.delete(c),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(c){s?.(c,e),n({type:"response",ok:!1,error:Kn(c)})}}function Pn(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=U(n,{key:t},r),s=o?Nn(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Nn(e){let t=e.ownerDocument.defaultView;if(!t)return null;let n=t.getComputedStyle(e);return{color:n.color,backgroundColor:n.backgroundColor,borderColor:n.borderColor}}function Dn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,s=n(),i=()=>{let u=n();u!==s&&(s=u,t())},a=()=>i(),c=()=>i();return e.history.pushState=function(...f){let m=r.apply(this,f);return i(),m},e.history.replaceState=function(...f){let m=o.apply(this,f);return i(),m},e.addEventListener("popstate",a),e.addEventListener("hashchange",c),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",c)}}function Bn(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function dt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ft(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function An(e,t){e.dispatchEvent(new CustomEvent(Fe,{detail:t}))}function On(e,t){e.dispatchEvent(new CustomEvent(Me,{detail:t}))}function Fn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Mn(e,t){return e.routeId===t}function we(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function pt(e){let t=we(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Kn(e){let t=we(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":pt(t)?"Site edit bridge disconnected":t}function J(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return/authentication|auth failed|auth rejected|bridge key|session|unauthorized|forbidden|expired/i.test(t)}function ht(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function je(e){return gn.has(gt(e))}function qn(e){return yn.has(gt(e))}function mt(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:qn(e.tagName),canInsertChild:je(e.tagName),canMove:!1,canRemove:!1}}function gt(e){return e?.trim().toLowerCase()??""}function it(e,t){return e.key!==t.key||e.instanceIndex!==t.instanceIndex||e.instanceCount!==t.instanceCount?!1:typeof e.textSegmentIndex=="number"&&typeof t.textSegmentIndex=="number"?e.textSegmentIndex===t.textSegmentIndex:!0}function wn(e,t,n){let r=U(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=jn(r,t.ref.textSegmentIndex);return o?(o.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function jn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Wn(e,t,n,r,o){let s=Se(e,t,n,r),i=yt(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=O(e,i,r),u=o?.(c.key)??o?.(a);if(!mt({operationSummary:u?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;let m=Hn(e,t,n,i);if(m){let g=Vn(i,m);if(g!==null)return{element:i,textNode:m,textSegmentIndex:g}}return(u?.childKeys.length??0)===0?{element:i}:null}function Hn(e,t,n,r){let o=Un(e,t,n);return!o||o.parentElement!==r?null:o}function Un(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(be(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return be(a)?a:null}function Vn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!be(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function be(e){return e?.nodeType===3}function Se(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let s of o){let i=yt(s),a=i?.getAttribute("data-vcp-edit-key")??"";if(i&&Yn(i,r,a))return i}return null}function yt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(We(t))return n??t;!$n(r)&&!n&&(n=t)}t=t.parentElement}return n}function We(e){return e.getAttribute(mn)!==null}function $n(e){return Gn(e.split("::")[0]??"")}function Gn(e){if(!e)return!1;let t=zn(e);return t===he||t.startsWith(`${he}/`)||t.includes(`/${he}/`)||t.endsWith(`/${he}`)}function zn(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function O(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${xt(r)}"]`))),n,r);if(o.length<=1)return{key:ct(n,r,0)};let s=o.indexOf(t);return s>=0?{key:ct(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function at(e,t,n){return O(e,t,n)}function U(e,t,n){let r=ie(t.key)??t.key,o=bt(Et(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${xt(r)}"]`))),n,t.key);if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(ie(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=Jn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function ct(e,t,n){return He(e,t)[n]?.key??t}function Jn(e,t){let n=ie(t);if(!n)return null;let o=He(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function He(e,t){return(e?.entries??[]).filter(n=>(ie(n.key)??n.key)===t)}function bt(e,t,n){let r=St(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function Yn(e,t,n){let r=St(t,n);return!r||e.tagName.toLowerCase()===r}function St(e,t){let n=ie(t)??t,o=(e?.entries.find(s=>s.key===t)??He(e,n)[0])?.tag.trim();return!o||o!==o.toLowerCase()?null:o}var Xn=2,Qn=4;function Et(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&Qn)!==0?-1:(r&Xn)!==0?1:0})}function ie(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(ot);if(n<0)break;let r=Number(t.slice(n+ot.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Zn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function Ln(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>Ke(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function M(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=Ee(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([y,C])=>[y,C??""])),attributes:Object.fromEntries(e.getAttributeNames().map(y=>[y,e.getAttribute(y)??""]))}:{},u=mt({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),f=We(e),m=!!(s&&/^[A-Z]/.test(s.tag)),g=!s||!m;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:m?"component-call":"jsx"}:{},...m&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:f?!1:(s?.childKeys.length??0)>0||u.canInsertChild||g&&je(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:Ln(e),spacing:Zn(e)}}function er(e,t,n,r,o){let s=Ke(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=dt(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let C=Ke(t.getBoundingClientRect());tr(s,C)&&(s=C,o(M(t,n,r,"summary")))},u=e.ResizeObserver,f=typeof u=="function"?new u(a):null;f?.observe(t);let m=e.MutationObserver,g=typeof m=="function"?new m(a):null;g?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",a,{passive:!0});let y=e.visualViewport;return y?.addEventListener?.("resize",a,{passive:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(ft(e,i),i=null),f?.disconnect(),g?.disconnect(),e.removeEventListener("resize",a),y?.removeEventListener?.("resize",a),e.document.removeEventListener("load",a,!0)}}function Ke(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function tr(e,t){return Math.abs(e.top-t.top)>.5||Math.abs(e.left-t.left)>.5||Math.abs(e.width-t.width)>.5||Math.abs(e.height-t.height)>.5}function nr(e,t,n,r,o,s,i){let a=e.document,c=Se(a,t,n,s);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?U(a,o,s):null;if(u&&qe(c,u))return me(a,c,"self-or-descendant",s,i);if(r==="move"&&u){let R=ir(a,c,u,s,i);if(R){let D=Ae(R.child,R.targetParent,t,n,"nearest");if(D)return ge(a,R.child,R.targetParent,D,s,i)}}let f=null,m=!1,g=c,y=c.parentElement;for(;y;){if(y.getAttribute("data-vcp-edit-key")){if(u&&qe(y,u))return me(a,c,"self-or-descendant",s,i);let R=ut(y,r,i);if(R==="accept"){f={child:g,targetParent:y};break}R==="blocked"&&(m=!0),g=y}y=y.parentElement}let C=ut(c,r,i);if(C==="accept"){if(f){let R=Ae(f.child,f.targetParent,t,n,"edge");if(R)return ge(a,f.child,f.targetParent,R,s,i)}return ge(a,c,c,rr(c,t,n),s,i)}if(f){let R=Ae(f.child,f.targetParent,t,n,"nearest");return ge(a,f.child,f.targetParent,R??"after",s,i)}return C==="blocked"||m?me(a,c,"operation-boundary-blocked",s,i):me(a,c,"no-accepting-parent",s,i)}function me(e,t,n,r,o){return{anchorHit:M(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function ge(e,t,n,r,o,s){let i=M(t,O(e,t,o),s,"summary"),a=M(n,O(e,n,o),s,"summary"),c=Ee(n).indicatorOrientation,u=r==="append"||r==="prepend"?or(n.getBoundingClientRect(),c,r):sr(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:u}}function ut(e,t,n){if(We(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return je(s)?"accept":"not-container"}function Ae(e,t,n,r,o){let s=Ee(t).indicatorOrientation,i=e.getBoundingClientRect(),a=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function rr(e,t,n){let r=Ee(e).indicatorOrientation,o=e.getBoundingClientRect();return(r==="vertical"?o.width>0?(t-o.left)/o.width:.5:o.height>0?(n-o.top)/o.height:.5)<.5?"prepend":"append"}function Ee(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function or(e,t,n){if(t==="vertical")return{left:n==="prepend"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="prepend"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function sr(e,t,n){if(t==="vertical")return{left:n==="before"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="before"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function qe(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ir(e,t,n,r,o){let s=ar(e,t,n,r,o);if(s)return s;let i=ur(n);if(!i||t===i)return null;let a=t,c=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==i;)a.getAttribute("data-vcp-edit-key")&&(c=a),a=a.parentElement;return a!==i||!c||c===i||c===n||qe(c,n)?null:{child:c,targetParent:i}}function ar(e,t,n,r,o){if(!o)return null;let s=O(e,n,r),a=o(s.key)?.parentKey??null;if(!a)return null;let u=O(e,t,r).key;for(;u;){let f=o(u);if(!f?.parentKey)return null;if(f.parentKey===a){if(u===s.key||cr(u,s.key,o))return null;let m=U(e,{key:u},r),g=U(e,{key:a},r);return m&&g?{child:m,targetParent:g}:null}u=f.parentKey}return null}function cr(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n(r)?.parentKey}return!1}function ur(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function ye(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:w(e.scrollX),scrollY:w(e.scrollY),scrollWidth:Math.max(w(t?.scrollWidth),w(n?.scrollWidth),w(e.innerWidth)),scrollHeight:Math.max(w(t?.scrollHeight),w(n?.scrollHeight),w(e.innerHeight)),viewportWidth:w(e.innerWidth),viewportHeight:w(e.innerHeight)}}function lr(e,t){Object.entries(t.attributes??{}).forEach(([r,o])=>{if(o===null){e.removeAttribute(r);return}e.setAttribute(r,o)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,o])=>{if(n.has(r))return;let s=e.style,i=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(o==null||o===""){s.removeProperty(i);return}s.setProperty(i,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,s=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),i=r.value;if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i),r.priority)})}var dr=500,oe=new Map;function fr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function pr(e,t){if(oe.size>=dr){let n=oe.keys().next().value;n&&oe.delete(n)}oe.set(e,t)}var se=new Set;function hr(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of se)r.has(o)||n?.removeProperty(o);se.clear();for(let o of r)se.add(o);Sr(e,t.stylesheets??[])}function mr(e){let t=e.documentElement?.style;for(let n of se)t?.removeProperty(n);se.clear();for(let n of Rt(e))n.remove()}function gr(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let a=vt(o,i);a&&(s[i]=a)}return s}function vt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return It(e,r,n)}function It(e,t,n){if(!t)return null;let r=yr(t);if(!r)return t;let o=vt(e,r.name,n);return o||(r.fallback?It(e,r.fallback,n)??r.fallback:null)}function yr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=br(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function br(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function Sr(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Rt(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(lt,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Rt(e){return Array.from(e.querySelectorAll(`link[${lt}]`))}function Er(e,t,n,r,o={}){let s=o.textNode?vr(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,a=i.textContent??"",c=s?void 0:t.innerHTML,u=Ir(i),f=!1,m=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",C),i.removeEventListener("blur",R),i.removeEventListener("input",D),xr(i,u)},g=k=>{if(f)return;f=!0;let K=i.textContent??"";if(m(),k==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(K),k==="commit"&&K!==a){o.onCommitSnapshot?.({ref:n,initialText:a,...c!==void 0?{initialHtml:c}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:K}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(k){let K=k.target;K&&i.contains(K)||g("commit")}function C(k){if(k.key==="Escape"){k.preventDefault(),g("cancel");return}k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g("commit"))}function R(){g("commit")}function D(){r({kind:"text-edit-input",payload:{ref:n,hit:M(t,n,void 0,"full")}})}return Rr(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",C),i.addEventListener("blur",R),i.addEventListener("input",D),Tr(i),kr(i,e.document),m}function vr(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Ir(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function Rr(e){_r(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function xr(e,t){Oe(e,"contenteditable",t.contentEditable),Oe(e,"spellcheck",t.spellcheck),Oe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function _r(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function Oe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Cr(e){let t=[e.documentElement,e.body].filter(r=>!!r?.style),n=t.map(r=>({element:r,userSelect:r.style.userSelect}));for(let r of t)r.style.userSelect="none";return()=>{for(let r of n)r.element.style.userSelect=r.userSelect}}function Tr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function kr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function xt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function w(e){let t=Number(e);return Number.isFinite(t)?t:0}import Pr from"node:http";import{randomBytes as Nr,timingSafeEqual as Dr}from"node:crypto";import Br from"node:path";import{WebSocket as Pt,WebSocketServer as Ar}from"ws";import{createPreviewSiteEditEngineRuntime as Or}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Fr,scanNextAppRouterRoutes as Mr}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Kr}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as qr}from"@vcp-dev/contracts";var wr="127.0.0.1",jr=30218,Wr="/__vcp/site-edit/bridge",Hr=6*1024*1024,Ur=3e3,_t=50,Ct="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function ds(e){let t=Dt(e),n=At(t),r=Bt(),o=r.get(n);if(o)return o;let s=new ve(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function Nt(e,t){let n=new ve(Dt(t),e,!1);return n.start({listen:!1}),n}var ve=class{constructor(t,n=Pr.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Or({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Vr({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new Kr({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??_t,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=Bt(),n=At(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getDocument(r)},getObjectSummary:async(t,n)=>this.getRuntime().getObjectSummary(t,n?this.resolveRouteId(n):void 0),getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),o=n?this.resolveRouteId(n):void 0;return await r.refreshSourceForKey(t,o),r.getClassNameSource(t,o)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:async t=>this.getRuntime().executeOperation(this.normalizeRequest(t)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:t=>this.getRuntime().subscribe(t)}}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??_t;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of t)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:Mr(this.options.projectRoot),n=new Map(this.routes.map(o=>[o.routeId,o.entryFile])),r=new Set(t.map(o=>o.routeId));this.routes=t;for(let o of t)n.get(o.routeId)!==o.entryFile&&this.runtime?.registerRoute(o.routeId,o.entryFile);for(let o of n.keys())r.has(o)||this.runtime?.unregisterRoute(o)}resolveRouteId(t){let n=Fr(t,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Dt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Br.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??wr,port:e.port??jr,path:e.path??Wr,sessionKey:e.sessionKey??Qr(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function Bt(){let e=globalThis;return e[Ct]??=new Map,e[Ct]}function At(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Vr(e){let t=new Ar({maxPayload:Hr,noServer:!0}),n=new WeakSet,r=s=>{new fe({socket:new Ve(s),engine:e.engine,validateOperationRequest:i=>qr.safeParse(i).success})},o=(s,i,a)=>{if(!$r(s,e))return;let c=Gr(s,e);if(!c){i.write(`HTTP/1.1 401 Unauthorized\r
1
+ function Ae(e){let t=new Map,n=[],r=new Map,i=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(o.map((l,h)=>[l,h])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(l=>({placementKey:l.placementKey,placementUnitKey:l.placementUnitKey,relation:l.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=l=>{let h=t.get(l);if(typeof h=="number")return h;let y=n.length;return n.push(l),t.set(l,y),y},c=l=>{let h=null;for(let y of dn(l)){let g=`${h??"root"}\0${y}`,x=r.get(g);if(typeof x=="number"){h=x;continue}let v=i.length;i.push([h,u(y)]),r.set(g,v),h=v}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:a,tokens:n,nodes:i,entries:e.entries.map(l=>{let h=l.pageCompositionUnitKey?s.get(l.pageCompositionUnitKey)??-1:-1;if(l.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${l.key} references unknown page composition unit ${l.pageCompositionUnitKey}`);return[c(l.key),un(l.operationSummary),...h>=0?[h]:[]]})}}function Be(e){if(!ln(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=i=>{let o=t.get(i);if(o)return o;let s=e.nodes[i];if(!s)throw new Error(`Missing compact document node ${i}`);let[a,u]=s,c=e.tokens[u];if(typeof c!="string")throw new Error(`Missing compact document token ${u}`);let l=`${a===null?"":r(a)}${c}`;return t.set(i,l),l};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map(i=>{let[o,s,a]=i,u=a===void 0?void 0:n[a];if(a!==void 0&&!u)throw new Error(`Missing page composition unit ${a}`);return{key:r(o),...u?{pageCompositionUnitKey:u}:{},operationSummary:cn(s)}})}}function un(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function cn(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function ln(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function dn(e){if(!e)return[];let t=[],n=0,r=Le(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=Le(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 Le(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var A=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",i=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!M(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?M(t.payload)&&typeof t.payload.id=="string":t.type==="event"?M(t.payload)&&M(t.payload.event):t.type==="auth"?M(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?M(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!M(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||Q(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"get-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return fn(t.request)&&Q(t.request.mutationContext)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return Q(t.mutationContext)}}},ge=class{constructor(t){this.options=t,this.messageQueue=new we,this.eventDispatcher=new Fe(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:i}=r;switch(r.kind){case"initialize-session":{let o=await this.options.engine.initializeSession({routeId:r.routeId,...r.mutationContext?{mutationContext:r.mutationContext}:{}});this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:{document:Ae(o.data.document),historyStatus:o.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:Ae((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getStyleContext(r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:i,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:i,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":{if(!Q(r.request.mutationContext))throw new Error("Invalid site edit bridge message");let o=r.request.mutationContext;await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.execute(r.request,o));return}case"undo":if(!Q(r.mutationContext))throw new Error("Invalid site edit bridge message");await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.undo(r.mutationContext));return;case"redo":if(!Q(r.mutationContext))throw new Error("Invalid site edit bridge message");await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.redo(r.mutationContext));return}}catch(n){let r=A.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:tt(n),code:et(n)}})}}async handleRawMessage(t){try{await this.handleMessage(A.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",i=pn(t);this.sendJson({type:"error",payload:{...i,message:r}})}}sendJson(t){this.options.socket.send(A.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let i=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:i}}),this.eventDispatcher.flush()}catch(i){this.sendJson({type:"error",payload:{id:t,kind:n,message:tt(i),code:et(i)}}),this.eventDispatcher.flush()}}},Fe=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)})}},we=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 M(e){return typeof e=="object"&&e!==null}function fn(e){return M(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"&&M(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&M(e.params)}function Q(e){return hn(e)}function et(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function tt(e){if(e instanceof Error)return e.message;if(!e||typeof e!="object")return"Unknown websocket operation failure";let t=e.message;return typeof t=="string"&&t.length>0?t:"Unknown websocket operation failure"}function hn(e){return M(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}function pn(e){try{return A.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var mn="vcp:designer:trace",gn="designer_trace",nt="__VCP_DESIGNER_TRACE__";var yn=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function bn(e=globalThis){let t=e;try{if(t.localStorage?.getItem(mn)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(gn)==="1"}catch{return!1}}function z(e,t={},n=globalThis){if(!bn(n))return;let r={type:e,timestamp:Date.now(),payload:Sn(t)},i=n,o=i[nt]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),i[nt]=o;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Sn(e){return Me(e,0)}function Me(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Me(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,i]of Object.entries(e)){if(yn.test(r)){n[r]="[redacted]";continue}n[r]=Me(i,t+1)}return n}var ye=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===Oe&&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 u=se(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let i={socket:r,settled:!1,reject:n};this.connectAttempt=i,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==i||(i.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(a,u)=>{this.cleanupSocket(r,a,u)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==i)){if(this.options.authKey){try{r.send(A.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){s(se(a,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=a=>{if(this.socket!==r)return;let u=se(a,"WebSocket failed");s(u,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===i&&!i.settled){this.handleAuthHandshakeMessage(a.data,r,i,()=>{o()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let u=this.intentionalClose,c=new Error(Cn(a,{intentional:u}));s(c,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})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}getSourceTree(){return this.request("get-source-tree",{})}getSourceFile(t){return this.request("get-source-file",t)}resolveSourceLocation(t){return this.request("resolve-source-location",t)}execute(t,n){return this.request("execute",{request:{...t,mutationContext:n}})}undo(t){return this.request("undo",{mutationContext:t})}redo(t){return this.request("redo",{mutationContext:t})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r||r.readyState!==Oe||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let i=`${t}-${this.sequence+=1}`,o=_n(i,t,n);return z("bridge.request",{id:i,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:rt(n.request,"kind"),documentVersion:rt(n.request,"documentVersion")}),new Promise((s,a)=>{let u=this.resolveRequestTimeoutMs(t),c=u>0?setTimeout(()=>{let l=this.pending.get(i);l&&(this.pending.delete(i),z("bridge.response",{id:i,kind:t,ok:!1,timedOut:!0}),l.reject(new Error(`Bridge request timed out after ${u}ms: ${t}`)))},u):null;c?.unref?.(),this.pending.set(i,{kind:t,timeout:c,resolve:l=>s(l),reject:a});try{r.send(A.stringifyMessage(o))}catch(l){let h=se(l,"WebSocket send failed");this.clearPendingRequest(i),a(h),this.cleanupSocket(r,h,"failed")}})}handleAuthHandshakeMessage(t,n,r,i){try{if(A.parseMessage(t).type==="auth-ok"){i();return}throw new Error("Bridge authentication failed")}catch(o){let s=se(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=A.parseMessage(t);if(n.type==="event"){for(let i of this.listeners)i(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"){z("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}z("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:xn(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Be(n.payload.result.data)}:r.kind==="initialize-session"?Rn(n.payload.result):n.payload.result)}}rejectAll(t){for(let[n,r]of[...this.pending])this.clearPendingRequest(n),r.reject(t)}clearPendingRequest(t){let n=this.pending.get(t);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(t))}resolveRequestTimeoutMs(t){let n=this.options.requestTimeoutMsByKind?.[t];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):vn[t]??In}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let i=this.connectAttempt;this.connectAttempt=null,i.settled||(i.settled=!0,i.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===En||t.readyState===Oe)&&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 i of this.connectionStatusListeners)i(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)}},En=0,Oe=1,In=15e3,vn={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function se(e,t){return e instanceof Error?e:new Error(t)}function Cn(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 rt(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function xn(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 ot(e){return new Ve(e)}var Ve=class{constructor(t){this.params=t,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!it(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=it(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let i=this.styleGeneration,o=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===i&&(this.styleContextCache={generation:i,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===o&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:i,request:o},o}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),i=this.editContextCache.get(r);if(i)return{ok:!0,data:i};let o=this.editContextInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(u=>(this.objectGeneration===s&&this.editContextCache.set(r,u.data),u)).finally(()=>{this.editContextInFlight.get(r)===a&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,a),a}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),i=this.classNameSourceCache.get(r);if(i)return i;let o=this.classNameSourceInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getClassNameSource(t,n??this.params.routeId).then(u=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,u),u)).finally(()=>{this.classNameSourceInFlight.get(r)===a&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,a),a}async getSourceTree(){return this.params.client.getSourceTree()}async getSourceFile(t){return this.params.client.getSourceFile(t)}async resolveSourceLocation(t){return this.params.client.resolveSourceLocation({...t,routeId:t.routeId??this.params.routeId})}async execute(t,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute({...r,mutationContext:n},n)}async undo(t){return this.params.client.undo(t)}async redo(t){return this.params.client.redo(t)}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId&&this.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return z("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){z("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let i=await this.refreshInFlight;if(typeof t!="number"||i.version>=t||this.currentDocument.version>=t)return this.currentDocument}z("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(i=>(this.currentDocument=i.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,i.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function it(e){return e.version===0&&e.entries.length===0}function Rn(e){let t=e;return{...t,data:{...t.data,document:Be(t.data.document)}}}function _n(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-source-tree":return{type:"request",payload:{id:e,kind:t}};case"get-source-file":return{type:"request",payload:{id:e,kind:t,path:String(n.path)}};case"resolve-source-location":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t,mutationContext:n.mutationContext}}}}var st="vcp-window-message",go=1;function Tn(e){return{source:st,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function kn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===st&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var at="site-edit",ut="frame-runtime";function ae(e,t={}){return Tn({namespace:at,channel:ut,sessionKey:t.sessionKey,body:e})}function ct(e){return!kn(e)||e.namespace!==at||e.channel!==ut?!1:typeof e.body?.type=="string"}var He="vcp-site-edit:route-ready",Ue="vcp-site-edit:bridge-status",Dn=1e3,Pn="data-vcp-ui-component",yt="data-vcp-theme-preview",lt="::repeat-item#",be="components/ui",Nn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),An=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Bn(e,t=""){let n=vt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,i=r.startsWith("/")?r:`/${r}`;return i==="/"?"/":i.replace(/\/+$/,"")}function Fn(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 wn(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 Eo(e=window,t={}){let n=wn(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Mn({bridgeUrl:n,options:t}),i=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(i?.started){if(On(i.signature,r)){await i.syncRoute?.();return}i.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},s,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,u=t.create_client??(p=>new ye({url:p,authKey:t.bridge_session_key})),c=t.schedule_after_navigation??Yn,l=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},h=()=>Bn(e.location.pathname,t.basePath||""),y=!!e.parent&&e.parent!==e,g=p=>{Jn(e,p)},x=p=>{o.currentDocument=p,o.currentEntriesByKey=new Map((p?.entries??[]).map(b=>[b.key,b]))},v=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},D=(p,b)=>!o.disposed&&b===o.routeSequence&&p===h(),_=async(p,b)=>{let T=o.activeBridge;if(!T)return null;let f=await T.getDocument(p);return D(p,b)&&x(f.data),f.data},N=()=>{v(),x(null);let p=o.activeBridge;o.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let b=o.activeClient;o.activeClient=null,b?.disconnect()},q=p=>p===s.routeId&&!!o.activeBridge&&(y||!!(o.currentDocument&&Qn(o.currentDocument,p)))&&Xn(o.activeClient),Y=p=>Math.min(Dn*2**Math.max(0,p),8e3),j=(p,b,T)=>{if(o.disposed)return;l();let f=Y(T);g({state:"reconnecting",routeId:p,attempt:T,retryInMs:f,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||b!==o.routeSequence)&&he(T+1).catch(m=>{let d=h();if(p===d){if(Z(m)){g({state:"reload-required",routeId:p,attempt:T,messageKey:"studio.errors.previewBridgeReloadRequired"});return}j(p,o.routeSequence,T+1)}})},f)},O=(p,b,T)=>{if(!D(p,b)||o.activeClient===null)return;if(Z(T.message)){N(),l(),g({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let f=o.activeClient;v(),x(null);let m=o.activeBridge;o.activeBridge=null,m&&e.__VCP_SITE_EDIT__===m&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,f?.disconnect(),j(p,b,0)},ne=p=>{let b=h(),T=o.routeSequence;if(!(!D(b,T)||o.activeClient===null)){if(Z(p)){N(),l(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}It(p)&&O(b,T,{state:"failed",message:We(p,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Un(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:p=>o.currentEntriesByKey.get(p)??null,setCurrentDocument:x,onBridgeRequestError:p=>{ne(p)}});let re=async()=>he(0),he=async p=>{if(o.disposed)return;let b=h();if(q(b))return;let T=o.syncInFlight;if(T?.routeId===b)return T.promise;let f=o.routeSequence+1,m=Ne(b,f,p);o.syncInFlight={routeId:b,sequence:f,promise:m};try{await m}finally{o.syncInFlight?.promise===m&&(o.syncInFlight=null)}},Ne=async(p,b,T)=>{o.routeSequence=b,l(),N(),g({state:T>0?"reconnecting":"connecting",routeId:p,attempt:T,messageKey:T>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let f=u(n),m=!1;o.activeClient=f,o.unsubscribeConnectionStatus=f.subscribeConnectionStatus?.(d=>{m&&(d.state==="closed"||d.state==="failed")&&O(p,b,d)});try{if(await f.connect(),!D(p,b)){f.disconnect();return}let d=ot({routeId:p,client:f,initialDocument:Hn(p)});o.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),o.activeClient=f,o.unsubscribeDocument=d.subscribe(k=>{k.type==="site-edit.document.changed"&&k.routeId===p&&o.currentDocument&&k.version>o.currentDocument.version&&_(p,b).catch(()=>{})}),a()&&(s.routeId=p);let R=(y?null:await d.initializeSession({routeId:p}))?.data.document??null;if(R&&x(R),!D(p,b)){f.disconnect();return}m=!0,g({state:"ready",routeId:p,attempt:T,messageKey:"studio.status.previewReady"}),Fn(e,{documentVersion:R?.version??0,routeId:p,versions:t.runtime_versions}),R&&Et(e,{routeId:p,version:R.version})}catch(d){if(v(),o.activeClient===f&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,f.disconnect(),x(null),!D(p,b))return;throw g({state:Z(d)?"reload-required":"failed",routeId:p,attempt:T,messageKey:Z(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},W=p=>{if(o.disposed)return;let b=h();if(Z(p)){l(),g({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}j(b,o.routeSequence,0)},H=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,c(()=>{o.syncScheduled=!1,!o.disposed&&re().catch(p=>W(p))}))},pe=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,l(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),N(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:re,cleanup:pe},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,o.unbindBootstrapLifecycle=Kn(e,pe),o.unbindRouteChange=Gn(e,H,h),t.defer_initial_sync){H();return}await re()}function Mn(e){return{basePath:vt(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:Vn(e.options.bridge_session_key)}}function On(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Vn(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 Kn(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),qn(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function qn(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Hn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function Un(e=window,t={}){let n=null,r=null,i=null,o=null,s=null,a=null,u=null,c=null,l=null,h=new Map,y=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,g=()=>{n?.(),n=null,r=null},x=()=>{i?.(),i=null,o?.(),o=null},v=(f,m,d)=>{let P=s?.sessionKey!==f||s?.sourceWindow!==m||s?.targetOrigin!==d;s={sessionKey:f,sourceWindow:m,targetOrigin:d},P&&(c=null,l=null)},D=(f,m)=>{let d=e.parent&&e.parent!==e?e.parent:null;return!d||m!==d?!1:!y||f===y},_=()=>{for(let f of h.values())f();h.clear()},N=f=>JSON.stringify([f.routeId,f.version]),q=()=>!u||u.state==="ready",Y=f=>JSON.stringify([f.state,f.routeId??null,f.attempt??null,f.retryInMs??null,f.messageKey??null]),j=f=>{if(!q())return;let m=N(f);c!==m&&(o?.(),o=null,W({kind:"route-ready",payload:{routeId:f.routeId,version:f.version}}),s&&(c=m))},O=f=>{let m=Y(f);l!==m&&(f.state!=="ready"&&(c=null,a=null),W({kind:"bridge-status",payload:f}),s&&(l=m))},ne=f=>{a=f,j(f)},re=f=>{u=f,O(f)},he=()=>{a&&j(a)},Ne=()=>{u&&O(u)},W=f=>{s&&s.sourceWindow.postMessage(ae({type:"event",...f},{sessionKey:s.sessionKey}),s.targetOrigin)},H=(f,m,d,P)=>{let R=Ce(e.document,m.clientX,m.clientY,t.getCurrentDocument?.()??null),k=R?F(R,d==="full"?K(e.document,R,t.getCurrentDocument?.()??null):ht(e.document,R,t.getCurrentDocument?.()??null),t.getDocumentEntry,d):null;P&&k&&(f==="pointer-click"||f==="pointer-double-click")&&(P.preventDefault(),P.stopPropagation(),typeof P.stopImmediatePropagation=="function"&&P.stopImmediatePropagation()),W({kind:f,payload:{clientX:m.clientX,clientY:m.clientY,buttons:Number(m.buttons??0),hit:k}})},pe=(f,m,d)=>{x(),s={sessionKey:f,sourceWindow:m,targetOrigin:d};let P=Hr(e.document),R=null,k=null,S=()=>{k=null;let E=R;R=null,E&&H("pointer-move",E,"summary")},w=E=>{R={clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},k===null&&(k=bt(e,S))},$=E=>{H("pointer-down",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},X=E=>{H("pointer-up",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},U=E=>{H("pointer-cancel",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},J=E=>{H("pointer-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},ie=E=>{H("pointer-double-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},oe=()=>{W({kind:"scroll",payload:{metrics:Ie(e)}})};e.document.addEventListener("pointerdown",$,!0),e.document.addEventListener("pointermove",w,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",X,!0),e.document.addEventListener("pointercancel",U,!0),e.document.addEventListener("click",J,!0),e.document.addEventListener("dblclick",ie,!0),e.addEventListener("scroll",oe,{passive:!0}),i=()=>{k!==null&&(St(e,k),k=null),R=null,P(),e.document.removeEventListener("pointerdown",$,!0),e.document.removeEventListener("pointermove",w,!0),e.document.removeEventListener("pointerup",X,!0),e.document.removeEventListener("pointercancel",U,!0),e.document.removeEventListener("click",J,!0),e.document.removeEventListener("dblclick",ie,!0),e.removeEventListener("scroll",oe)}},p=f=>{let m=f.detail;m?.routeId&&ne(m)},b=f=>{let m=f.detail;m?.state&&re(m)},T=f=>{let m=f.data;if(!ct(m)||m.body.type!=="request"||m.body.kind!=="apply-node-patch"&&m.body.kind!=="get-hit-by-ref"&&m.body.kind!=="get-path-by-ref"&&m.body.kind!=="get-scroll-metrics"&&m.body.kind!=="scroll-to"&&m.body.kind!=="scroll-by"&&m.body.kind!=="set-interaction-mode"&&m.body.kind!=="set-theme-override"&&m.body.kind!=="clear-theme-override"&&m.body.kind!=="get-theme-variables"&&m.body.kind!=="compute-drop-target-at-point"&&m.body.kind!=="observe-node-bounds"&&m.body.kind!=="clear-node-bounds-observer"&&m.body.kind!=="restore-text-edit"&&m.body.kind!=="clear-text-edit-rollback"&&m.body.kind!=="start-text-edit-at-point"&&m.body.kind!=="hit-test-at-point"&&!dt(m.body))return;let d=m.body,P=typeof m.sessionKey=="string"?m.sessionKey:null,R=f.source,k=f.origin;if(!P||!k||!R||typeof R.postMessage!="function"||!D(P,R))return;if(s){if(s.sourceWindow!==R||s.targetOrigin!==k)return;s.sessionKey!==P&&(g(),x(),_(),s=null)}v(P,R,k),Ne(),he();let S=w=>{let $=typeof d.id=="string"?d.id:"unknown";R.postMessage(ae({id:$,...w},{sessionKey:P}),k)};try{if(dt(d)){Wn({message:d,sendEvent:I=>{R.postMessage(ae({type:"event",...I},{sessionKey:P}),k)},sendResponse:S,subscriptions:h,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(d.kind==="apply-node-patch"){let I=G(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let C=d.payload.preview,B=C?Tr(C.sessionId,d.payload.ref):null;if(B&&C){let me=ue.get(B)??-1;if(C.revision<me){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,stale:!0,latestRevision:me}});return}if(C.revision===me){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,duplicate:!0,latestRevision:me}});return}}if(Rr(I,d.payload.patch),B&&C&&kr(B,C.revision),C?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:C.revision}});return}S({type:"response",ok:!0,result:F(I,K(e.document,I,t.getCurrentDocument?.()??null),t.getDocumentEntry,C?.responseDetail??"full")});return}if(d.kind==="get-hit-by-ref"){let I=G(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:F(I,K(e.document,I,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(d.kind==="get-path-by-ref"){let I=G(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let C=[],B=I;for(;B;)B.getAttribute("data-vcp-edit-key")&&C.push(F(B,K(e.document,B,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),B=B.parentElement;S({type:"response",ok:!0,result:C.reverse()});return}if(d.kind==="restore-text-edit"||d.kind==="clear-text-edit-rollback"){let I=d.payload.ref;if(d.kind==="clear-text-edit-rollback"){r&&ft(r.ref,I)&&(r=null),S({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!ft(r.ref,I)){S({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let C=er(e.document,r,t.getCurrentDocument?.()??null);r=null,S(C?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(d.kind==="get-scroll-metrics"){S({type:"response",ok:!0,result:Ie(e)});return}if(d.kind==="scroll-to"){let I=Number(d.payload.x),C=Number(d.payload.y);if(!Number.isFinite(I)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:I,top:C}),S({type:"response",ok:!0,result:Ie(e)});return}if(d.kind==="scroll-by"){let I=Number(d.payload.deltaX),C=Number(d.payload.deltaY);if(!Number.isFinite(I)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:I,top:C}),S({type:"response",ok:!0,result:{...Ie(e),scrolled:!0}});return}if(d.kind==="set-interaction-mode"){d.payload.enabled?pe(P,R,k):s?.sourceWindow===R&&s.targetOrigin===k&&s.sessionKey===P&&x(),S({type:"response",ok:!0,result:{interactionEnabled:d.payload.enabled}});return}if(d.kind==="set-theme-override"){Dr(e.document,d.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(d.kind==="clear-theme-override"){Pr(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(d.kind==="get-theme-variables"){S({type:"response",ok:!0,result:Nr(e.document,d.payload.names)});return}if(d.kind==="compute-drop-target-at-point"){let I=Number(d.payload?.x),C=Number(d.payload?.y);if(!Number.isFinite(I)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:Sr(e,I,C,d.payload.dragKind,d.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(d.kind==="observe-node-bounds"){let I=d.payload.ref;if(!I){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let C=G(e.document,I,t.getCurrentDocument?.()??null);if(!C){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=mr(e,C,I,t.getCurrentDocument,t.getDocumentEntry,B=>W({kind:"node-bounds-change",payload:{hit:B}})),S({type:"response",ok:!0,result:{observing:!0}}),W({kind:"node-bounds-change",payload:{hit:F(C,I,t.getDocumentEntry,"summary")}});return}if(d.kind==="clear-node-bounds-observer"){o?.(),o=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(d.kind!=="hit-test-at-point"&&d.kind!=="start-text-edit-at-point")return;let w=Number(d.payload?.x),$=Number(d.payload?.y);if(!Number.isFinite(w)||!Number.isFinite($)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let X=d.kind==="hit-test-at-point"?Ce(e.document,w,$,t.getCurrentDocument?.()??null):nr(e.document,w,$,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!X){S({type:"response",ok:!1,error:d.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let U=d.kind==="start-text-edit-at-point"?X:null,J=d.kind==="hit-test-at-point"?X:U.element,ie=d.payload.detailLevel??"full",oe=ie==="full"?K(e.document,J,t.getCurrentDocument?.()??null):ht(e.document,J,t.getCurrentDocument?.()??null),E=U&&typeof U.textSegmentIndex=="number"?{...oe,textSegmentIndex:U.textSegmentIndex}:oe,an=F(J,E,t.getDocumentEntry,ie);if(d.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:an});return}g(),n=wr(e,J,E,I=>{R.postMessage(ae({type:"event",...I},{sessionKey:P}),k)},{...U?.textNode?{textNode:U.textNode}:{},onCommitSnapshot:I=>{r=I}}),S({type:"response",ok:!0,result:{ref:E}})}catch(w){S({type:"response",ok:!1,error:w instanceof Error?w.message:"Failed to start text edit"})}};return e.addEventListener("message",T),e.addEventListener(He,p),e.addEventListener(Ue,b),()=>{g(),x(),s=null,_(),e.removeEventListener("message",T),e.removeEventListener(He,p),e.removeEventListener(Ue,b)}}function dt(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function jn(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Wn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:i,setCurrentDocument:o,onBridgeRequestError:s,windowLike:a}){let u=a.__VCP_SITE_EDIT__;if(!u){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let c=await u.initializeSession({routeId:e.payload.routeId,...e.payload.mutationContext?{mutationContext:e.payload.mutationContext}:{}});o?.(c.data.document),Et(a,{routeId:c.data.document.routeId,version:c.data.document.version}),n({type:"response",ok:!0,result:c});return}case"bridge-get-document":{let c=await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await u.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await u.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let c=u.ensureDocumentVersion?await u.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let c=u.acknowledgeDocumentVersion?await u.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await u.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let c=await u.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:$n(c,e.payload.key,a.document,i?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await u.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await u.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await u.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let c=await u.execute(e.payload.request,e.payload.mutationContext),l=i?.()?.routeId;if(c.ok&&l&&u.acknowledgeDocumentVersion&&jn(e.payload.request)){let h=await u.acknowledgeDocumentVersion(l,c.data.resultVersion);o?.(h.data)}n({type:"response",ok:!0,result:c});return}case"bridge-undo":n({type:"response",ok:!0,result:await u.undo(e.payload.mutationContext)});return;case"bridge-redo":n({type:"response",ok:!0,result:await u.redo(e.payload.mutationContext)});return;case"bridge-subscribe":{let c=e.payload.subscriptionId;r.get(c)?.();let l=u.subscribe(h=>{t({kind:"bridge-event",payload:{event:h,subscriptionId:c}})});r.set(c,l),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:Zn(c)})}}function $n(e,t,n,r){if(!e.ok)return e;let i=G(n,{key:t},r),o=i?zn(i):null;return o?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...o}}}:e}function zn(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 Gn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,i=e.history.replaceState,o=n(),s=()=>{let c=n();c!==o&&(o=c,t())},a=()=>s(),u=()=>s();return e.history.pushState=function(...l){let h=r.apply(this,l);return s(),h},e.history.replaceState=function(...l){let h=i.apply(this,l);return s(),h},e.addEventListener("popstate",a),e.addEventListener("hashchange",u),()=>{e.history.pushState=r,e.history.replaceState=i,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",u)}}function Yn(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function bt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function St(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Et(e,t){e.dispatchEvent(new CustomEvent(He,{detail:t}))}function Jn(e,t){e.dispatchEvent(new CustomEvent(Ue,{detail:t}))}function Xn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Qn(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 It(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 Zn(e){let t=We(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":It(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 vt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function $e(e){return Nn.has(xt(e))}function Ln(e){return An.has(xt(e))}function Ct(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:Ln(e.tagName),canInsertChild:$e(e.tagName),canMove:!1,canRemove:!1}}function xt(e){return e?.trim().toLowerCase()??""}function ft(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 er(e,t,n){let r=G(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let i=tr(r,t.ref.textSegmentIndex);return i?(i.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function tr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!ve(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function nr(e,t,n,r,i){let o=Ce(e,t,n,r),s=Rt(o);if(!s)return null;let a=s.getAttribute("data-vcp-edit-key")??"",u=K(e,s,r),c=i?.(u.key)??i?.(a);if(!Ct({operationSummary:c?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let h=rr(e,t,n,s);if(h){let y=or(s,h);if(y!==null)return{element:s,textNode:h,textSegmentIndex:y}}return _e(s)?null:{element:s}}function rr(e,t,n,r){let i=ir(e,t,n);return!i||i.parentElement!==r?null:i}function ir(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(ve(o))return o;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return ve(a)?a:null}function or(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!ve(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function ve(e){return e?.nodeType===3}function Ce(e,t,n,r=null){let i=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of i){let s=Rt(o),a=s?.getAttribute("data-vcp-edit-key")??"";if(s&&lr(s,r,a))return s}return null}function Rt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(ze(t))return n??t;!sr(r)&&!n&&(n=t)}t=t.parentElement}return n}function ze(e){return e.getAttribute(Pn)!==null}function sr(e){return ar(e.split("::")[0]??"")}function ar(e){if(!e)return!1;let t=ur(e);return t===be||t.startsWith(`${be}/`)||t.includes(`/${be}/`)||t.endsWith(`/${be}`)}function ur(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let i of n.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}return r.join("/")}function K(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",i=Tt(Dt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${wt(r)}"]`))),n,r);if(i.length<=1)return{key:pt(n,r,0)};let o=i.indexOf(t);return o>=0?{key:pt(n,r,o),instanceIndex:o,instanceCount:i.length}:{key:r}}function ht(e,t,n){return K(e,t,n)}function G(e,t,n){let r=xe(t.key)??t.key,i=Tt(Dt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${wt(r)}"]`))),n,t.key);if(i.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<i.length?t.instanceIndex:null,s=(xe(t.key)??t.key)!==t.key;if(o!==null&&!s)return i[o]??null;let a=cr(n,t.key);return a!==null&&a>=0&&a<i.length?i[a]??null:o!==null?i[o]??null:i[0]??null}function pt(e,t,n){return _t(e,t)[n]?.key??t}function cr(e,t){let n=xe(t);if(!n)return null;let i=_t(e,n).findIndex(o=>o.key===t);return i>=0?i:null}function _t(e,t){return(e?.entries??[]).filter(n=>(xe(n.key)??n.key)===t)}function Tt(e,t,n){let r=kt(t,n);return r?e.filter(i=>i.tagName.toLowerCase()===r):e}function lr(e,t,n){let r=kt(t,n);return!r||e.tagName.toLowerCase()===r}function kt(e,t){return null}var dr=2,fr=4;function Dt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&fr)!==0?-1:(r&dr)!==0?1:0})}function xe(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(lt);if(n<0)break;let r=Number(t.slice(n+lt.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function hr(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=i=>{let o=Number.parseFloat(i??"");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 pr(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>br(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function F(e,t,n,r="full"){let i=e.getBoundingClientRect(),o=n?.(t.key)??null,s=e.tagName.toLowerCase(),a=Re(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([g,x])=>[g,x??""])),attributes:Object.fromEntries(e.getAttributeNames().map(g=>[g,e.getAttribute(g)??""]))}:{},c=Ct({operationSummary:o?.operationSummary,tagName:s,fallbackMode:"preview"}),l=ze(e),h=!0,y=Nt(e)?.getAttribute("data-vcp-edit-key")??null;return{ref:t,key:t.key,detailLevel:r,tagName:s,...o?{sourceKind:"jsx"}:{},...y?{parentKey:y}:{},...o?.pageCompositionUnitKey?{pageCompositionUnitKey:o.pageCompositionUnitKey}:{},...u,runtimeFlags:{selectable:!0,movable:c.canMove,removable:c.canRemove,textEditable:c.canUpdateText,container:l?!1:!!_e(e)||c.canInsertChild||h&&$e(s)},layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childRects:pr(e),spacing:hr(e)}}function mr(e,t,n,r,i,o){let s=t,a=F(s,n,i,"summary"),u=null,c=()=>{u===null&&(u=bt(e,l))},l=()=>{u=null;let D=G(e.document,n,r?.()??null);if(!D)return;D!==s&&(y?.unobserve(s),s=D,y?.observe(s));let _=F(s,n,i,"summary");_.rect.width<=0||_.rect.height<=0||gr(a,_)&&(a=_,o(_))},h=e.ResizeObserver,y=typeof h=="function"?new h(c):null;y?.observe(s);let g=e.MutationObserver,x=typeof g=="function"?new g(c):null;x?.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),()=>{u!==null&&(St(e,u),u=null),y?.disconnect(),x?.disconnect(),e.removeEventListener("resize",c),v?.removeEventListener?.("resize",c),e.document.removeEventListener("load",c,!0)}}function gr(e,t){return Pt(e.rect,t.rect)||yr(e.childRects,t.childRects)||mt(e.spacing,t.spacing)||mt(e.layout,t.layout)}function yr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>Pt(i,r[o]??i))}function mt(e,t){let n=e??{},r=t??{},i=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(i).some(o=>n[o]!==r[o])}function br(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function Pt(e,t){return Math.abs(e.top-t.top)>.5||Math.abs(e.left-t.left)>.5||Math.abs(e.width-t.width)>.5||Math.abs(e.height-t.height)>.5}function Sr(e,t,n,r,i,o,s){let a=e.document,u=Ce(a,t,n,o);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let c=i?G(a,i,o):null;if(c&&je(u,c))return Se(a,u,"self-or-descendant",o,s);if(r==="move"&&c){let v=Cr(a,u,c,o,s);if(v){let D=Ke(v.child,v.targetParent,t,n,"nearest");if(D)return Ee(a,v.child,v.targetParent,D,o,s)}}let l=null,h=!1,y=u,g=u.parentElement;for(;g;){if(g.getAttribute("data-vcp-edit-key")){if(c&&je(g,c))return Se(a,u,"self-or-descendant",o,s);let v=gt(g,r,s);if(v==="accept"){l={child:y,targetParent:g};break}v==="blocked"&&(h=!0),y=g}g=g.parentElement}let x=gt(u,r,s);if(x==="accept"){if(l){let v=Ke(l.child,l.targetParent,t,n,"edge");if(v)return Ee(a,l.child,l.targetParent,v,o,s)}return Ee(a,u,u,Er(u,t,n),o,s)}if(l){let v=Ke(l.child,l.targetParent,t,n,"nearest");return Ee(a,l.child,l.targetParent,v??"after",o,s)}return x==="blocked"||h?Se(a,u,"operation-boundary-blocked",o,s):Se(a,u,"no-accepting-parent",o,s)}function Se(e,t,n,r,i){return{anchorHit:F(t,K(e,t,r),i,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Ee(e,t,n,r,i,o){let s=F(t,K(e,t,i),o,"summary"),a=F(n,K(e,n,i),o,"summary"),u=Re(n).indicatorOrientation,c=r==="append"||r==="prepend"?Ir(n.getBoundingClientRect(),u,r):vr(t.getBoundingClientRect(),u,r);return{anchorHit:s,targetParentHit:a,relation:r,indicatorOrientation:u,indicatorBounds:c}}function gt(e,t,n){if(ze(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",i=n?.(r)??null;if(i)return i.operationSummary.canInsertChild===!0?"accept":_e(e)?"blocked":"not-container";let o=e.tagName.toLowerCase();return $e(o)?"accept":"not-container"}function Ke(e,t,n,r,i){let o=Re(t).indicatorOrientation,s=e.getBoundingClientRect(),a=o==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return i==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function Er(e,t,n){let r=Re(e).indicatorOrientation,i=e.getBoundingClientRect();return(r==="vertical"?i.width>0?(t-i.left)/i.width:.5:i.height>0?(n-i.top)/i.height:.5)<.5?"prepend":"append"}function Re(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",i=n?.flexDirection,o=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(i??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...i?{flexDirection:i}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:s}}function Ir(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 vr(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 je(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Cr(e,t,n,r,i){let o=xr(e,t,n,r,i);if(o)return o;let s=Nt(n);if(!s||t===s)return null;let a=t,u=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==s;)a.getAttribute("data-vcp-edit-key")&&(u=a),a=a.parentElement;return a!==s||!u||u===s||u===n||je(u,n)?null:{child:u,targetParent:s}}function xr(e,t,n,r,i){return null}function Nt(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function _e(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=_e(n);if(r)return r}return null}function Ie(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 Rr(e,t){Object.entries(t.attributes??{}).forEach(([r,i])=>{if(i===null){e.removeAttribute(r);return}e.setAttribute(r,i)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,i])=>{if(n.has(r))return;let o=e.style,s=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i))}),t.styleDeclarations?.forEach(r=>{let i=e.style,o=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),s=r.value;if(s==null||s===""){i.removeProperty(o);return}i.setProperty(o,String(s),r.priority)})}var _r=500,ue=new Map;function Tr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function kr(e,t){if(ue.size>=_r){let n=ue.keys().next().value;n&&ue.delete(n)}ue.set(e,t)}var ce=new Set;function Dr(e,t){let n=e.documentElement?.style,r=new Set;for(let[i,o]of Object.entries(t.variables??{}))i.startsWith("--")&&(r.add(i),n?.setProperty(i,o));for(let i of ce)r.has(i)||n?.removeProperty(i);ce.clear();for(let i of r)ce.add(i);Fr(e,t.stylesheets??[])}function Pr(e){let t=e.documentElement?.style;for(let n of ce)t?.removeProperty(n);ce.clear();for(let n of Ft(e))n.remove()}function Nr(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,i=r?e.defaultView?.getComputedStyle(r):null,o={};for(let s of n){let a=At(i,s);a&&(o[s]=a)}return o}function At(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Bt(e,r,n)}function Bt(e,t,n){if(!t)return null;let r=Ar(t);if(!r)return t;let i=At(e,r.name,n);return i||(r.fallback?Bt(e,r.fallback,n)??r.fallback:null)}function Ar(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Br(n),i=r>=0?n.slice(0,r).trim():n;if(!i.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:i,fallback:o||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 Fr(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of Ft(e)){let s=o.getAttribute("href")??"";if(!n.has(s)||r.has(s)){o.remove();continue}r.set(s,o)}let i=e.head;if(i)for(let o of n){if(r.has(o))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(yt,"true"),s.setAttribute("href",o),i.appendChild(s)}}function Ft(e){return Array.from(e.querySelectorAll(`link[${yt}]`))}function wr(e,t,n,r,i={}){let o=i.textNode?Mr(e.document,i.textNode):null;if(i.textNode&&!o)throw new Error("Failed to prepare text segment editor");let s=o?.element??t,a=s.textContent??"",u=o?void 0:t.innerHTML,c=Or(s),l=!1,h=()=>{e.document.removeEventListener("pointerdown",g,!0),s.removeEventListener("keydown",x),s.removeEventListener("blur",v),s.removeEventListener("input",D),Kr(s,c)},y=_=>{if(l)return;l=!0;let N=s.textContent??"";if(h(),_==="cancel"){o?.restore(a),o||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(N),_==="commit"&&N!==a){i.onCommitSnapshot?.({ref:n,initialText:a,...u!==void 0?{initialHtml:u}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function g(_){let N=_.target;N&&s.contains(N)||y("commit")}function x(_){if(_.key==="Escape"){_.preventDefault(),y("cancel");return}_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&(_.preventDefault(),y("commit"))}function v(){y("commit")}function D(){r({kind:"text-edit-input",payload:{ref:n,hit:F(t,n,void 0,"full")}})}return Vr(s),e.document.addEventListener("pointerdown",g,!0),s.addEventListener("keydown",x),s.addEventListener("blur",v),s.addEventListener("input",D),Ur(s),jr(s,e.document),h}function Mr(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(i){t.nodeValue=i,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Or(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 Vr(e){qr(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 Kr(e,t){qe(e,"contenteditable",t.contentEditable),qe(e,"spellcheck",t.spellcheck),qe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function qr(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 qe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Hr(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 Ur(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function jr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function wt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function V(e){let t=Number(e);return Number.isFinite(t)?t:0}import Wr from"node:http";import{createHash as Ht,randomBytes as $r,timingSafeEqual as zr}from"node:crypto";import Ye from"node:path";import{WebSocket as Ut,WebSocketServer as Gr}from"ws";import{createPreviewSiteEditEngineRuntime as Yr,openFileHistoryStore as Jr}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Xr,scanNextAppRouterRoutes as Qr}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Zr}from"@vcp-dev/site-edit-engine/source-watcher";var Te=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Lr}from"@vcp-dev/contracts";var ei="127.0.0.1",ti=30218,ni="/__vcp/site-edit/bridge",jt=6*1024*1024,ri=jt*2,ii=3e3,Mt=50,Ot="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Bo(e){let t=$t(e),n=Gt(t),r=zt(),i=r.get(n);if(i)return i;let o=new ke(t);r.set(n,o);try{o.start()}catch(s){throw r.delete(n),o.stop(),s}return o}function Wt(e,t,n={}){let r=new ke($t(t),e,!1,n);return r.start({listen:!1}),r}var ke=class{constructor(t,n=Wr.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,i={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new Te,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=si({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 Zr({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??Mt,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=zt(),n=Gt(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let i=(this.dependencies.createRuntime??Yr)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version);for(let s of this.eventListeners)s(o)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor,...this.options.mutationContextVerifier?{mutationContextVerifier:this.options.mutationContextVerifier}:{}});this.runtime=i,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{if(t.mutationContext){let s=await this.verifyMutationContext(t.mutationContext);if(!s.ok)throw new Error(`${s.code}: ${s.message??"Mutation session verification failed"}`);let a=await this.bindHistorySession(t.mutationContext.editingSessionId);if(!a.ok)throw new Error(`${a.code}: ${a.message}`)}let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t.routeId),i=n.getDocument(r).data;await this.recordRuntimeVersion(i.version);let o=(await n.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:o}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),i=n.getDocument(r);return await this.recordRuntimeVersion(i.data.version),i},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),i=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,i)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=n??t.mutationContext,i=await this.verifyMutationContext(r);if(!i.ok)return L(i,t);let o=await this.bindHistorySession(r.editingSessionId);if(!o.ok)return L(o,t);let s=await this.getRuntime().executeOperation(this.normalizeRequest(t),r);return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion),s}),undo:t=>this.mutationQueue.run(async()=>{let n=await this.verifyMutationContext(t);if(!n.ok)return L(n);let r=await this.bindHistorySession(t.editingSessionId);if(!r.ok)return L(r);let i=await this.getRuntime().undo(t);return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),redo:t=>this.mutationQueue.run(async()=>{let n=await this.verifyMutationContext(t);if(!n.ok)return L(n);let r=await this.bindHistorySession(t.editingSessionId);if(!r.ok)return L(r);let i=await this.getRuntime().redo(t);return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??Jr)(oi({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let i=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,i),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??Mt;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:Qr(this.options.projectRoot),n=new Map(this.routes.map(i=>[i.routeId,i.entryFile])),r=new Set(t.map(i=>i.routeId));this.routes=t;for(let i of t)n.get(i.routeId)!==i.entryFile&&this.runtime?.registerRoute(i.routeId,i.entryFile);for(let i of n.keys())r.has(i)||this.runtime?.unregisterRoute(i)}resolveRouteId(t){let n=Xr(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}async verifyMutationContext(t){if(!t)return{ok:!1,code:"MUTATION_SESSION_REQUIRED",message:"A mutation session is required for write operations."};if(!this.options.mutationContextVerifier||!this.options.tenantId)return{ok:!1,code:"LEASE_ASSERTION_INVALID",message:"Lease assertion verification is unavailable."};try{return await this.options.mutationContextVerifier.verify(t,{tenantId:this.options.tenantId,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t.editingSessionId,lockId:t.lockId,ownerId:t.ownerId})}catch{return{ok:!1,code:"LEASE_ASSERTION_INVALID",message:"Lease assertion verification failed."}}}};function $t(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Ye.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??ei,port:e.port??ti,path:e.path??ni,sessionKey:e.sessionKey??hi(),historyRoot:e.historyRoot,mutationContextVerifier:e.mutationContextVerifier,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function oi(e){return Ye.join(Ye.resolve(e.root),Vt(e.siteId),Vt(e.snapshotId),Ht("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Vt(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ht("sha256").update(e).digest("hex").slice(0,32)}function zt(){let e=globalThis;return e[Ot]??=new Map,e[Ot]}function Gt(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function L(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function si(e){let t=new Gr({maxPayload:jt,noServer:!0}),n=new WeakSet,r=o=>{new ge({socket:new Je(o),engine:e.engine,validateOperationRequest:s=>Lr.safeParse(s).success})},i=(o,s,a)=>{if(!ai(o,e))return;let u=ui(o,e);if(!u){s.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),i.destroy();return}c.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,i,a,u=>{t.emit("connection",u,s)})};return e.server.on("upgrade",o),t.on("connection",(s,i)=>{if(n.has(i)){r(s);return}zr(s,e.sessionKey,()=>{r(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var Ve=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){this.socket.readyState===Pt.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function $r(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Gr(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Ue(e.headers["x-vcp-site-edit-key"]),o=Ot(r,t.sessionKey),s=Ue(e.headers.host),i=Ue(e.headers.origin);return s&&!Jr(s,t.host,i)?null:i?Xr(i,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function zr(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Ur),o,s=()=>{clearTimeout(r),e.off("message",o),e.off("close",s)},i=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let c=B.parseMessage(a.toString());if(c.type!=="auth"||!Ot(c.payload.key,t)){i();return}s(),e.readyState===Pt.OPEN&&e.send(B.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{i()}},e.on("message",o),e.on("close",s)}function Ot(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Dr(n,r)}function Jr(e,t,n){let r=kt(e),o=kt(t);return r===o||Tt(o)&&Tt(r)&&(!n||$e(n,e))||Yr(o)&&(!n||$e(n,e))}function Yr(e){return e==="0.0.0.0"||e==="::"}function Tt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Xr(e,t,n){return n.includes(e)||(t?$e(e,t):!1)}function $e(e,t){try{return new URL(e).host===Ft(t)}catch{return!1}}function kt(e){let t=Ft(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Ft(e){return e.trim().toLowerCase()}function Ue(e){return Array.isArray(e)?e[0]:e}function Qr(){return Nr(32).toString("base64url")}import Zr from"node:http";import{existsSync as X,readFileSync as Y}from"node:fs";import{createRequire as wt}from"node:module";import xe from"node:path";import{basename as jt,dirname as ae,join as ce}from"node:path";import{fileURLToPath as Wt}from"node:url";var Lr="next",eo="127.0.0.1",to=3e3,Ie="/__vcp/site-edit/bridge",Ht="/__vcp/site-edit/health",Re="/__vcp/site-edit/client/",no=`${Re}auto-bootstrap.js`,Ut='data-vcp-site-edit-bootstrap="true"',ro=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],oo="@vcp-dev/site-edit-engine/webpack-loader",so=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,io=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ao=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Es(e={}){let t=xe.resolve(e.projectRoot??process.cwd()),n=e.host??eo,r=e.port??jo(process.env.PORT)??to,o=e.bridgePath??Ie,s=mo(o),i=Do(),a=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",c=await Mo(t),u=co(t),f=c({dev:!0,dir:t,hostname:n,port:r,...uo(u)}),m=f.getRequestHandler();await f.prepare();let g=null,y=Zr.createServer((R,D)=>{Io({basePath:a,bridgePath:o,bridgeHealthPath:s,bridgeSessionKey:i,getBridgeHealth:()=>g?.getHealth()??xo(o),handle:m,request:R,response:D}).catch(k=>{console.error(k),D.headersSent||(D.statusCode=500),D.end("site edit preview request failed")})});g=Nt(y,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??wo(t),projectRoot:t,basePath:a,host:n,port:r,path:o,sessionKey:i}),po({server:y,bridgePath:o,handleUpgrade:f.getUpgradeHandler()});let C=()=>{g?.stop(),f.close().catch(()=>{}),y.close()};return process.on("SIGINT",C),process.on("SIGTERM",C),await Wo(y,r,n),{bundler:u,close:C,server:y}}function co(e){let t=lo(e);return t&&fo(t)?"webpack":"turbopack"}function uo(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function lo(e){for(let t of ro){let n=ce(e,t);if(X(n))return Y(n,"utf8")}return null}function fo(e){return e.includes(oo)?!0:so.test(e)&&io.some(t=>t.test(e))}function po(e){let t=(n,r,o)=>{ho(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(s=>{console.error(s),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function ho(e,t){return new URL(e??"/","http://localhost").pathname===t}function mo(e=Ie){if(e===Ie)return Ht;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function go(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??yo()});return`<script type="module" ${Ut}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(no)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function yo(){return{bridge:Ge("@vcp-dev/site-edit-bridge"),contracts:Ge("@vcp-dev/contracts"),engine:Ge("@vcp-dev/site-edit-engine")}}function Ge(e){let t=wt(import.meta.url);try{let n=t.resolve(e),r=bo(n,e);if(!r)return;let o=JSON.parse(Y(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function bo(e,t){let n=xe.parse(e).root,r=ae(e);for(;r&&r!==n;){let o=ce(r,"package.json");if(X(o))try{if(JSON.parse(Y(o,"utf8")).name===t)return o}catch{return}r=ae(r)}}function So(e,t){if(e.includes(Ut))return e;let n=go(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function vs(e,t=ae(Wt(import.meta.url)),n=X){return Vt(e,t,n)?.path??null}function Vt(e,t=ae(Wt(import.meta.url)),n=X){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Re))return null;let o=r.slice(Re.length);if(!ao.has(o))return null;let s=ze(Ko(t),o);if(jt(t)!=="src")return{path:s,requiresTranspile:!1};let i=ze(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function Eo(e,t){let n=Vt(e.url);if(!n)return!1;if(!X(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await vo(Y(n.path,"utf8")):Y(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function vo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Io({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:s,request:i,response:a}){if(Ro(i,a,n,o)||await Eo(i,a))return;let c=_o(i),u=Co(i),f=c||u?Po(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await s(i,a)}catch(m){throw f(),m}}function Ro(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let s=r();return t.writeHead(s.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(s)),!0}function xo(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function _o(e){return To(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Co(e){return ko(e)?(e.headers["accept-encoding"]="identity",!0):!1}function To(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Re)||t===Ie||t===Ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function ko(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Po(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),s=r.write.bind(e),i=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,c,u)=>(a!==void 0&&n.push(Mt(a,Kt(c))),qt(c),qt(u),!0),r.end=(a,c,u)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(Mt(f,Kt(c))),r.write=s,r.end=i,r.flushHeaders=o;let m=Buffer.concat(n),g=No(e,m,t);g!==m&&!e.headersSent&&e.removeHeader("content-length");let y=typeof a=="function"?a:typeof c=="function"?c:typeof u=="function"?u:void 0;return y?i(g,y):i(g)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function No(e,t,n){if(Bo(e,t))return Buffer.from(So(t.toString("utf8"),n));if(n.patchNextDevChunk&&Ao(e)){let r=t.toString("utf8"),o=Oo(r);if(o!==r)return Buffer.from(o)}return t}function Do(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Bo(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function Ao(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Oo(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
4
+ `),s.destroy();return}u.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,s,a,c=>{t.emit("connection",c,o)})};return e.server.on("upgrade",i),t.on("connection",(o,s)=>{if(n.has(s)){r(o);return}ci(o,e.sessionKey,()=>{r(o)})}),t.stop=()=>{e.server.off("upgrade",i);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var Je=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===Ut.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ri){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ai(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function ui(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Ge(e.headers["x-vcp-site-edit-key"]),i=Yt(r,t.sessionKey),o=Ge(e.headers.host),s=Ge(e.headers.origin);return o&&!li(o,t.host,s)?null:s?fi(s,o,t.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function ci(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ii),i,o=()=>{clearTimeout(r),e.off("message",i),e.off("close",o)},s=()=>{o(),e.close(1008,"bridge authentication failed")};i=a=>{try{let u=A.parseMessage(a.toString());if(u.type!=="auth"||!Yt(u.payload.key,t)){s();return}o(),e.readyState===Ut.OPEN&&e.send(A.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",i),e.on("close",o)}function Yt(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&zr(n,r)}function li(e,t,n){let r=qt(e),i=qt(t);return r===i||Kt(i)&&Kt(r)&&(!n||Xe(n,e))||di(i)&&(!n||Xe(n,e))}function di(e){return e==="0.0.0.0"||e==="::"}function Kt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function fi(e,t,n){return n.includes(e)||(t?Xe(e,t):!1)}function Xe(e,t){try{return new URL(e).host===Jt(t)}catch{return!1}}function qt(e){let t=Jt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Jt(e){return e.trim().toLowerCase()}function Ge(e){return Array.isArray(e)?e[0]:e}function hi(){return $r(32).toString("base64url")}import pi from"node:http";import{existsSync as te,readFileSync as ee}from"node:fs";import{createRequire as Lt}from"node:module";import le from"node:path";import{basename as en,dirname as de,join as fe}from"node:path";import{fileURLToPath as tn}from"node:url";import{createEd25519MutationContextVerifier as mi}from"@vcp-dev/site-edit-engine";var gi="next",yi="127.0.0.1",bi=3e3,De="/__vcp/site-edit/bridge",nn="/__vcp/site-edit/health",Pe="/__vcp/site-edit/client/",Si=`${Pe}auto-bootstrap.js`,rn='data-vcp-site-edit-bootstrap="true"',Ei=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ii="@vcp-dev/site-edit-engine/webpack-loader",vi=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Ci=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],xi=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function jo(e={}){let t=le.resolve(e.projectRoot??process.cwd()),n=e.host??yi,r=e.port??oo(process.env.PORT)??bi,i=e.bridgePath??De,o=Fi(i),s=Xi(),a=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",{tenantId:u,mutationContextVerifier:c}=Ri(e,process.env),l=await to(t),h=ki(t),y=l({dev:!0,dir:t,hostname:n,port:r,...Di(h)}),g=y.getRequestHandler(),x=e.siteId??process.env.VCP_SITE_ID??"site_preview",v=e.snapshotId??process.env.VCP_SNAPSHOT_ID??io(t),D=e.historyRoot??process.env.VCP_SITE_EDIT_HISTORY_ROOT,_=D?.trim()?le.resolve(D):void 0;await y.prepare();let N=null,q=pi.createServer((j,O)=>{Hi({basePath:a,bridgePath:i,bridgeHealthPath:o,bridgeSessionKey:s,getBridgeHealth:()=>N?.getHealth()??ji(i),handle:g,request:j,response:O}).catch(ne=>{console.error(ne),O.headersSent||(O.statusCode=500),O.end("site edit preview request failed")})});N=Wt(q,{...u?{tenantId:u}:{},siteId:x,snapshotId:v,projectRoot:t,basePath:a,host:n,port:r,path:i,sessionKey:s,..._?{historyRoot:_}:{},...c?{mutationContextVerifier:c}:{}}),Ai({server:q,bridgePath:i,handleUpgrade:y.getUpgradeHandler()});let Y=()=>{N?.stop(),y.close().catch(()=>{}),q.close()};return process.on("SIGINT",Y),process.on("SIGTERM",Y),await so(q,r,n),{bundler:h,close:Y,server:q}}function Ri(e,t){let n=(e.tenantId??t.VCP_TENANT_ID)?.trim()||void 0,r=e.requireMutationContextVerifier??Ti(t.VCP_DESIGNER_SESSION_REQUIRE_VERIFIER),i=_i(e,t);if(r&&!n)throw new Error("tenantId is required when mutation context verification is enabled.");if(r&&!i)throw new Error("A mutation context verifier is required when mutation context verification is enabled.");return{...n?{tenantId:n}:{},...i?{mutationContextVerifier:i}:{},requireMutationContextVerifier:r}}function _i(e,t){if(e.mutationContextVerifier)return e.mutationContextVerifier;let n=(e.mutationContextPublicKeyPem??t.VCP_DESIGNER_SESSION_PUBLIC_KEY_PEM)?.trim();if(n)try{let r=t.VCP_DESIGNER_SESSION_KEY_ID?.trim();if(!r)throw new Error("VCP_DESIGNER_SESSION_KEY_ID is required.");return mi({publicKey:n.replace(/\\n/g,`
5
+ `),issuer:t.VCP_DESIGNER_SESSION_ISSUER??"vcp-api",audience:t.VCP_DESIGNER_SESSION_AUDIENCE??"site-edit-engine",keyId:r})}catch(r){throw new Error("VCP_DESIGNER_SESSION_PUBLIC_KEY_PEM is invalid.",{cause:r})}}function Ti(e){return e==="1"||e==="true"}function ki(e){let t=Pi(e);return t&&Ni(t)?"webpack":"turbopack"}function Di(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Pi(e){for(let t of Ei){let n=fe(e,t);if(te(n))return ee(n,"utf8")}return null}function Ni(e){return e.includes(Ii)?!0:vi.test(e)&&Ci.some(t=>t.test(e))}function Ai(e){let t=(n,r,i)=>{Bi(n.url,e.bridgePath)||e.handleUpgrade(n,r,i).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Bi(e,t){return new URL(e??"/","http://localhost").pathname===t}function Fi(e=De){if(e===De)return nn;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function wi(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Mi()});return`<script type="module" ${rn}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Si)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Mi(){return{bridge:Qe("@vcp-dev/site-edit-bridge"),contracts:Qe("@vcp-dev/contracts"),engine:Qe("@vcp-dev/site-edit-engine")}}function Qe(e){let t=Lt(import.meta.url);try{let n=t.resolve(e),r=Oi(n,e);if(!r)return;let i=JSON.parse(ee(r,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function Oi(e,t){let n=le.parse(e).root,r=de(e);for(;r&&r!==n;){let i=fe(r,"package.json");if(te(i))try{if(JSON.parse(ee(i,"utf8")).name===t)return i}catch{return}r=de(r)}}function Vi(e,t){if(e.includes(rn))return e;let n=wi(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Wo(e,t=de(tn(import.meta.url)),n=te){return on(e,t,n)?.path??null}function on(e,t=de(tn(import.meta.url)),n=te){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Pe))return null;let i=r.slice(Pe.length);if(!xi.has(i))return null;let o=Ze(no(t),i);if(en(t)!=="src")return{path:o,requiresTranspile:!1};let s=Ze(t,i.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Ki(e,t){let n=on(e.url);if(!n)return!1;if(!te(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await qi(ee(n.path,"utf8")):ee(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function qi(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Hi({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:i,handle:o,request:s,response:a}){if(Ui(s,a,n,i)||await Ki(s,a))return;let u=Wi(s),c=$i(s),l=u||c?Yi(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:c}):()=>{};try{await o(s,a)}catch(h){throw l(),h}}function Ui(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let o=r();return t.writeHead(o.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(o)),!0}function ji(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Wi(e){return zi(e)?(e.headers["accept-encoding"]="identity",!0):!1}function $i(e){return Gi(e)?(e.headers["accept-encoding"]="identity",!0):!1}function zi(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Pe)||t===De||t===nn)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Gi(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 Yi(e,t){let n=[],r=e,i=r.flushHeaders.bind(e),o=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,u,c)=>(a!==void 0&&n.push(Xt(a,Qt(u))),Zt(u),Zt(c),!0),r.end=(a,u,c)=>{let l=typeof a=="function"?void 0:a;l!==void 0&&n.push(Xt(l,Qt(u))),r.write=o,r.end=s,r.flushHeaders=i;let h=Buffer.concat(n),y=Ji(e,h,t);y!==h&&!e.headersSent&&e.removeHeader("content-length");let g=typeof a=="function"?a:typeof u=="function"?u:typeof c=="function"?c:void 0;return g?s(y,g):s(y)},()=>{r.write=o,r.end=s,r.flushHeaders=i}}function Ji(e,t,n){if(Qi(e,t))return Buffer.from(Vi(t.toString("utf8"),n));if(n.patchNextDevChunk&&Zi(e)){let r=t.toString("utf8"),i=Li(r);if(i!==r)return Buffer.from(i)}return t}function Xi(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Qi(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 Zi(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 Li(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
6
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
6
- `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,o])=>Fo(n,r,o),e)}function Fo(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function Mt(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Kt(e){return typeof e=="string"?e:void 0}function qt(e){typeof e=="function"&&e()}async function Mo(e){let n=wt(ce(e,"package.json"))(Lr);return n.default??n}function Ko(e){return jt(e)!=="src"?e:ze(qo(e),"dist")}function qo(e){return $t(e)?xe.posix.dirname(e):ae(e)}function ze(e,t){return $t(e)?xe.posix.join(e,t):ce(e,t)}function $t(e){return e.includes("/")&&!e.includes("\\")}function wo(e){let t=ce(e,".vcp/current-snapshot.json");if(!X(t))return"sandbox_worktree";try{let n=JSON.parse(Y(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function jo(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Wo(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Hr as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,nt as SITE_EDIT_FRAME_RUNTIME_CHANNEL,tt as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ve as SiteEditBridgeServer,fe as SiteEditBridgeSocketServer,B as SiteEditBridgeTransport,pe as SiteEditWebSocketClient,Me as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Fe as VCP_SITE_EDIT_ROUTE_READY_EVENT,et as VCP_WINDOW_MESSAGE_SOURCE,Xo as VCP_WINDOW_MESSAGE_VERSION,po as attachNextDevUpgradeHandler,Nt as attachSiteEditBridgeServer,Vr as attachSiteEditWebSocketServer,go as createSiteEditAutoBootstrapHtmlSnippet,Le as createSiteEditBridge,re as createSiteEditFrameRuntimeMessage,fn as createVcpWindowMessageEnvelope,Xe as decodeRenderDocument,Ye as encodeRenderDocument,ds as ensureSiteEditBridgeServerStarted,So as injectSiteEditAutoBootstrap,zt as isCompactRenderDocument,en as isDesignerTraceEnabled,rt as isSiteEditFrameRuntimeMessage,pn as isVcpWindowMessageEnvelope,Oo as patchNextFirefoxDevChunk,Co as prepareFirefoxNextDevChunkPatchRequest,_o as prepareSiteEditHtmlInjectionRequest,mo as resolveSiteEditBridgeHealthPath,Vt as resolveSiteEditClientAsset,vs as resolveSiteEditClientAssetPath,co as resolveSiteEditNextDevBundler,bn as resolveSiteEditRouteId,En as resolveSiteEditWebSocketUrl,tn as sanitizeTracePayload,es as startSiteEditAutoBootstrap,Tn as startSiteEditFrameRuntime,Es as startSiteEditNextDevServer,$ as traceDesignerEvent,vo as transpileSiteEditClientSource};
7
+ `)],[["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,i])=>eo(n,r,i),e)}function eo(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 Xt(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Qt(e){return typeof e=="string"?e:void 0}function Zt(e){typeof e=="function"&&e()}async function to(e){let n=Lt(fe(e,"package.json"))(gi);return n.default??n}function no(e){return en(e)!=="src"?e:Ze(ro(e),"dist")}function ro(e){return sn(e)?le.posix.dirname(e):de(e)}function Ze(e,t){return sn(e)?le.posix.join(e,t):fe(e,t)}function sn(e){return e.includes("/")&&!e.includes("\\")}function io(e){let t=fe(e,".vcp/current-snapshot.json");if(!te(t))return"sandbox_worktree";try{let n=JSON.parse(ee(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function oo(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function so(e,t,n){return new Promise((r,i)=>{e.once("error",i),e.listen(t,n,()=>{e.off("error",i),r()})})}export{ri as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,jt as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,ut as SITE_EDIT_FRAME_RUNTIME_CHANNEL,at as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ke as SiteEditBridgeServer,ge as SiteEditBridgeSocketServer,A as SiteEditBridgeTransport,ye as SiteEditWebSocketClient,Ue as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,He as VCP_SITE_EDIT_ROUTE_READY_EVENT,st as VCP_WINDOW_MESSAGE_SOURCE,go as VCP_WINDOW_MESSAGE_VERSION,Ai as attachNextDevUpgradeHandler,Wt as attachSiteEditBridgeServer,si as attachSiteEditWebSocketServer,wi as createSiteEditAutoBootstrapHtmlSnippet,ot as createSiteEditBridge,ae as createSiteEditFrameRuntimeMessage,Tn as createVcpWindowMessageEnvelope,Be as decodeRenderDocument,Ae as encodeRenderDocument,Bo as ensureSiteEditBridgeServerStarted,Vi as injectSiteEditAutoBootstrap,ln as isCompactRenderDocument,bn as isDesignerTraceEnabled,ct as isSiteEditFrameRuntimeMessage,kn as isVcpWindowMessageEnvelope,Li as patchNextFirefoxDevChunk,$i as prepareFirefoxNextDevChunkPatchRequest,Wi as prepareSiteEditHtmlInjectionRequest,Fi as resolveSiteEditBridgeHealthPath,on as resolveSiteEditClientAsset,Wo as resolveSiteEditClientAssetPath,ki as resolveSiteEditNextDevBundler,Ri as resolveSiteEditNextDevServerMutationConfig,Bn as resolveSiteEditRouteId,wn as resolveSiteEditWebSocketUrl,Sn as sanitizeTracePayload,Eo as startSiteEditAutoBootstrap,Un as startSiteEditFrameRuntime,jo as startSiteEditNextDevServer,z as traceDesignerEvent,qi as transpileSiteEditClientSource};
@@ -1,5 +1,6 @@
1
1
  import http, { type IncomingMessage, type Server as HttpServer } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
+ import { type SiteEditMutationContextVerifier } from "@vcp-dev/site-edit-engine";
3
4
  import type { SiteEditRuntimeVersions } from "./auto-bootstrap.js";
4
5
  export type SiteEditNextDevServerOptions = {
5
6
  basePath?: string;
@@ -7,8 +8,19 @@ export type SiteEditNextDevServerOptions = {
7
8
  host?: string;
8
9
  port?: number;
9
10
  projectRoot?: string;
11
+ tenantId?: string;
10
12
  siteId?: string;
11
13
  snapshotId?: string;
14
+ historyRoot?: string;
15
+ mutationContextVerifier?: SiteEditMutationContextVerifier;
16
+ mutationContextPublicKeyPem?: string;
17
+ requireMutationContextVerifier?: boolean;
18
+ };
19
+ export type SiteEditNextDevServerEnvironment = Readonly<Partial<Record<string, string | undefined>>>;
20
+ export type SiteEditNextDevServerMutationConfig = {
21
+ tenantId?: string;
22
+ mutationContextVerifier?: SiteEditMutationContextVerifier;
23
+ requireMutationContextVerifier: boolean;
12
24
  };
13
25
  export type SiteEditNextDevBundler = "turbopack" | "webpack";
14
26
  type SiteEditClientAsset = {
@@ -20,6 +32,7 @@ export declare function startSiteEditNextDevServer(options?: SiteEditNextDevServ
20
32
  close: () => void;
21
33
  server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
22
34
  }>;
35
+ export declare function resolveSiteEditNextDevServerMutationConfig(options: SiteEditNextDevServerOptions, env: SiteEditNextDevServerEnvironment): SiteEditNextDevServerMutationConfig;
23
36
  export declare function resolveSiteEditNextDevBundler(projectRoot: string): SiteEditNextDevBundler;
24
37
  export declare function attachNextDevUpgradeHandler(input: {
25
38
  server: HttpServer;