@vcp-dev/site-edit-bridge 0.3.15 → 0.4.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,6 @@
|
|
|
1
|
-
function Ce(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let u=t.get(a);if(typeof u=="number")return u;let d=n.length;return n.push(a),t.set(a,d),d},i=a=>{let u=null;for(let d of Et(a)){let p=`${u??"root"}\0${d}`,g=r.get(p);if(typeof g=="number"){u=g;continue}let y=o.length;o.push({parent:u,token:s(d)}),r.set(p,y),u=y}if(u===null)throw new Error("Document key must not be empty");return u};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 Te(e){if(!St(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 St(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Et(e){if(!e)return[];let t=[],n=0,r=xe(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=xe(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 xe(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var F=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==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!B(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?B(t.payload)&&typeof t.payload.id=="string":t.type==="event"?B(t.payload)&&B(t.payload.event):!1}static isRequestPayload(t,n={}){if(!B(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":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return vt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},X=class{constructor(t){this.options=t,this.messageQueue=new ce,this.eventDispatcher=new ue(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:Ce((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"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=F.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(F.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=It(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(F.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()}}},ue=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)})}},ce=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 B(e){return typeof e=="object"&&e!==null}function vt(e){return B(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"&&B(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&B(e.params)}function It(e){try{return F.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Rt="vcp:designer:trace",_t="designer_trace",Ne="__VCP_DESIGNER_TRACE__";var xt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ct(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Rt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(_t)==="1"}catch{return!1}}function w(e,t={},n=globalThis){if(!Ct(n))return;let r={type:e,timestamp:Date.now(),payload:Tt(t)},o=n,s=o[Ne]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Ne]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Tt(e){return le(e,0)}function le(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>le(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(xt.test(r)){n[r]="[redacted]";continue}n[r]=le(o,t+1)}return n}var Q=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}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})}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)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=Pt(o,t,n);return w("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:ke(n.request,"kind"),documentVersion:ke(n.request,"documentVersion")}),new Promise((i,a)=>{this.pending.set(o,{kind:t,resolve:u=>i(u),reject:a}),r.send(F.stringifyMessage(s))})}handleMessage(t){let n=F.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.pending.delete(n.payload.id),n.type==="error"){w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Nt(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Te(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}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)}};function ke(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Nt(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 Pe(e){return new de(e)}var de=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,Dt(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ot(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 kt(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 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 w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){w("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}w("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 kt(e){return e.version===0&&e.rootKeys.length===0}function Pt(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"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 Dt(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 Ot(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 De="vcp-window-message",$r=1;function At(e){return{source:De,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===De&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Oe="site-edit",Ae="frame-runtime";function U(e,t={}){return At({namespace:Oe,channel:Ae,sessionKey:t.sessionKey,body:e})}function Fe(e){return!Ft(e)||e.namespace!==Oe||e.channel!==Ae?!1:typeof e.body?.type=="string"}var he="vcp-site-edit:route-ready",Mt=1e3,Bt="data-vcp-ui-component",Ve="data-vcp-theme-preview",Me="::repeat-item#",Z="components/ui",jt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),wt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Kt(e,t=""){let n=Xt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function qt(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 Wt(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function Jr(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=Ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:l=>n.currentEntriesByKey.get(l)??null});let r=t.create_client??(l=>new Q({url:l})),o=t.schedule_after_navigation??zt,s=Wt(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},a=l=>{n.currentDocument=l,n.currentEntriesByKey=new Map((l?.entries??[]).map(R=>[R.key,R]))},u=async(l,R)=>{let E=e.__VCP_SITE_EDIT__;if(!E)return null;let v=await E.getDocument(l);return R!==n.routeSequence||l!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||a(v.data),v.data},d=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,a(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},p=async()=>{let l=Kt(e.location.pathname,t.basePath||"");if(l===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),d();let E=r(s);try{if(await E.connect(),R!==n.routeSequence){E.disconnect();return}e.__VCP_SITE_EDIT__=Pe({routeId:l,client:E,initialDocument:Vt(l)}),n.activeClient=E,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===l&&u(l,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=l;let v=await u(l,R);qt(e,{documentVersion:v?.version??0,routeId:l,versions:t.runtime_versions}),Jt(e,{routeId:l,version:v?.version??0})}catch(v){throw E.disconnect(),v}},g=()=>{i(),n.retryTimer=e.setTimeout(()=>{p().catch(()=>g())},Mt)},y=()=>{o(()=>{p().catch(()=>g())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:p,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),d(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=Yt(e,y),t.defer_initial_sync){y();return}await p()}function Vt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,u=new Map,d=()=>{n?.(),n=null},p=()=>{r?.(),r=null,o?.(),o=null},g=(I,f,c)=>{let x=s?.sessionKey!==I||s?.sourceWindow!==f||s?.targetOrigin!==c;s={sessionKey:I,sourceWindow:f,targetOrigin:c},x&&(a=null)},y=()=>{for(let I of u.values())I();u.clear()},l=I=>{i=I.routeId==="/"?null:I;let f=`${I.routeId}:${I.version}`;a!==f&&(o?.(),o=null,E({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(a=f))},R=()=>{i&&l(i)},E=I=>{s&&s.sourceWindow.postMessage(U({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},v=(I,f,c,x)=>{let _=te(e.document,f.clientX,f.clientY),C=_?P(_,c==="full"?O(e.document,_,t.getCurrentDocument?.()??null):je(e.document,_,t.getCurrentDocument?.()??null),t.getDocumentEntry,c):null;x&&C&&(I==="pointer-click"||I==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),E({kind:I,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:C}})},N=(I,f,c)=>{p(),s={sessionKey:I,sourceWindow:f,targetOrigin:c};let x=An(e.document),_=null,C=null,m=()=>{C=null;let h=_;_=null,h&&v("pointer-move",h,"summary")},k=h=>{_={clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},C===null&&(C=Ue(e,m))},M=h=>{v("pointer-down",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},K=h=>{v("pointer-up",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},A=h=>{v("pointer-cancel",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},j=h=>{v("pointer-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},W=h=>{v("pointer-double-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},V=()=>{E({kind:"scroll",payload:{metrics:ee(e)}})};e.document.addEventListener("pointerdown",M,!0),e.document.addEventListener("pointermove",k,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",K,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",j,!0),e.document.addEventListener("dblclick",W,!0),e.addEventListener("scroll",V,{passive:!0}),r=()=>{C!==null&&(He(e,C),C=null),_=null,x(),e.document.removeEventListener("pointerdown",M,!0),e.document.removeEventListener("pointermove",k,!0),e.document.removeEventListener("pointerup",K,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",j,!0),e.document.removeEventListener("dblclick",W,!0),e.removeEventListener("scroll",V)}},Re=I=>{let f=I.detail;f?.routeId&&l(f)},_e=I=>{let f=I.data;if(!Fe(f)||f.body.type!=="request"||f.body.kind!=="apply-node-patch"&&f.body.kind!=="get-hit-by-ref"&&f.body.kind!=="get-path-by-ref"&&f.body.kind!=="get-scroll-metrics"&&f.body.kind!=="scroll-to"&&f.body.kind!=="scroll-by"&&f.body.kind!=="set-interaction-mode"&&f.body.kind!=="set-theme-override"&&f.body.kind!=="clear-theme-override"&&f.body.kind!=="get-theme-variables"&&f.body.kind!=="compute-drop-target-at-point"&&f.body.kind!=="observe-node-bounds"&&f.body.kind!=="clear-node-bounds-observer"&&f.body.kind!=="start-text-edit-at-point"&&f.body.kind!=="hit-test-at-point"&&!Be(f.body))return;let c=f.body,x=typeof f.sessionKey=="string"?f.sessionKey:null,_=I.source,C=I.origin;if(!x||!C||!_||typeof _.postMessage!="function"||s&&(s.sessionKey!==x||s.sourceWindow!==_||s.targetOrigin!==C))return;g(x,_,C),R();let m=k=>{let M=typeof c.id=="string"?c.id:"unknown";_.postMessage(U({id:M,...k},{sessionKey:x}),C)};try{if(Be(c)){Ht({message:c,sendEvent:b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},sendResponse:m,subscriptions:u,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(c.kind==="apply-node-patch"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for patch target"});return}let S=c.payload.preview,T=S?Sn(S.sessionId,c.payload.ref):null;if(T&&S){let J=H.get(T)??-1;if(S.revision<J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,stale:!0,latestRevision:J}});return}if(S.revision===J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,duplicate:!0,latestRevision:J}});return}}if(yn(b,c.payload.patch),T&&S&&En(T,S.revision),S?.responseDetail==="none"){m({type:"response",ok:!0,result:{applied:!0,appliedRevision:S.revision}});return}m({type:"response",ok:!0,result:P(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,S?.responseDetail??"full")});return}if(c.kind==="get-hit-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for hit target"});return}m({type:"response",ok:!0,result:P(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(c.kind==="get-path-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for path target"});return}let S=[],T=b;for(;T;)T.getAttribute("data-vcp-edit-key")&&S.push(P(T,O(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),T=T.parentElement;m({type:"response",ok:!0,result:S.reverse()});return}if(c.kind==="get-scroll-metrics"){m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-to"){let b=Number(c.payload.x),S=Number(c.payload.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:b,top:S}),m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-by"){let b=Number(c.payload.deltaX),S=Number(c.payload.deltaY);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:b,top:S}),m({type:"response",ok:!0,result:{...ee(e),scrolled:!0}});return}if(c.kind==="set-interaction-mode"){c.payload.enabled?N(x,_,C):s?.sourceWindow===_&&s.targetOrigin===C&&s.sessionKey===x&&p(),m({type:"response",ok:!0,result:{interactionEnabled:c.payload.enabled}});return}if(c.kind==="set-theme-override"){vn(e.document,c.payload),m({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(c.kind==="clear-theme-override"){In(e.document),m({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(c.kind==="get-theme-variables"){m({type:"response",ok:!0,result:Rn(e.document,c.payload.names)});return}if(c.kind==="compute-drop-target-at-point"){let b=Number(c.payload?.x),S=Number(c.payload?.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid drop target point"});return}m({type:"response",ok:!0,result:fn(e,b,S,c.payload.dragKind,c.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(c.kind==="observe-node-bounds"){let b=c.payload.ref;if(!b){m({type:"response",ok:!1,error:"Missing bounds observer target"});return}let S=q(e.document,b,t.getCurrentDocument?.()??null);if(!S){m({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=dn(e,S,b,t.getDocumentEntry,T=>E({kind:"node-bounds-change",payload:{hit:T}})),m({type:"response",ok:!0,result:{observing:!0}}),E({kind:"node-bounds-change",payload:{hit:P(S,b,t.getDocumentEntry,"summary")}});return}if(c.kind==="clear-node-bounds-observer"){o?.(),o=null,m({type:"response",ok:!0,result:{cleared:!0}});return}if(c.kind!=="hit-test-at-point"&&c.kind!=="start-text-edit-at-point")return;let k=Number(c.payload?.x),M=Number(c.payload?.y);if(!Number.isFinite(k)||!Number.isFinite(M)){m({type:"response",ok:!1,error:"Invalid text edit point"});return}let K=c.kind==="hit-test-at-point"?te(e.document,k,M):Zt(e.document,k,M,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!K){m({type:"response",ok:!1,error:c.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=c.kind==="start-text-edit-at-point"?K:null,j=c.kind==="hit-test-at-point"?K:A.element,W=c.payload.detailLevel??"full",V=W==="full"?O(e.document,j,t.getCurrentDocument?.()??null):je(e.document,j,t.getCurrentDocument?.()??null),h=A&&typeof A.textSegmentIndex=="number"?{...V,textSegmentIndex:A.textSegmentIndex}:V,bt=P(j,h,t.getDocumentEntry,W);if(c.kind==="hit-test-at-point"){m({type:"response",ok:!0,result:bt});return}d(),n=Tn(e,j,h,b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},A?{textNode:A.textNode}:void 0),m({type:"response",ok:!0,result:{ref:h}})}catch(k){m({type:"response",ok:!1,error:k instanceof Error?k.message:"Failed to start text edit"})}};return e.addEventListener("message",_e),e.addEventListener(he,Re),()=>{d(),p(),s=null,y(),e.removeEventListener("message",_e),e.removeEventListener(he,Re)}}function Be(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-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function Ht({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){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 i.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:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let a=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:$t(a,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let a=e.payload.subscriptionId;r.get(a)?.();let u=i.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:a}})});r.set(a,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let a=e.payload.subscriptionId;r.get(a)?.(),r.delete(a),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(a){n({type:"response",ok:!1,error:a instanceof Error?a.message:"Site edit bridge request failed"})}}function $t(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=q(n,{key:t},r),s=o?Gt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Gt(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 Yt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let a=n.apply(this,i);return t(),a},e.history.replaceState=function(...i){let a=r.apply(this,i);return t(),a},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function zt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ue(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function He(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Jt(e,t){e.dispatchEvent(new CustomEvent(he,{detail:t}))}function Xt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ye(e){return jt.has(Ge(e))}function Qt(e){return wt.has(Ge(e))}function $e(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:Qt(e.tagName),canInsertChild:ye(e.tagName),canMove:!1,canRemove:!1}}function Ge(e){return e?.trim().toLowerCase()??""}function Zt(e,t,n,r,o){let s=te(e,t,n),i=Ye(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",u=O(e,i,r),d=o?.(u.key)??o?.(a);if(!$e({operationSummary:d?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((d?.childKeys.length??0)===0)return{element:i};let g=Lt(e,t,n,i);if(!g)return null;let y=tn(i,g);return y===null?null:{element:i,textNode:g,textSegmentIndex:y}}function Lt(e,t,n,r){let o=en(e,t,n);return!o||o.parentElement!==r?null:o}function en(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(me(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return me(a)?a:null}function tn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!me(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function me(e){return e?.nodeType===3}function te(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=Ye(o);if(s)return s}return null}function Ye(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(be(t))return n??t;!nn(r)&&!n&&(n=t)}t=t.parentElement}return n}function be(e){return e.getAttribute(Bt)!==null}function nn(e){return rn(e.split("::")[0]??"")}function rn(e){if(!e)return!1;let t=on(e);return t===Z||t.startsWith(`${Z}/`)||t.includes(`/${Z}/`)||t.endsWith(`/${Z}`)}function on(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=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length<=1)return{key:we(n,r,0)};let s=o.indexOf(t);return s>=0?{key:we(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function je(e,t,n){return O(e,t,n)}function q(e,t,n){let r=ne(t.key)??t.key,o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(ne(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=sn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function we(e,t,n){return ze(e,t)[n]?.key??t}function sn(e,t){let n=ne(t);if(!n)return null;let o=ze(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function ze(e,t){return(e?.entries??[]).filter(n=>(ne(n.key)??n.key)===t)}var an=2,un=4;function Je(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&un)!==0?-1:(r&an)!==0?1:0})}function ne(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Me);if(n<0)break;let r=Number(t.slice(n+Me.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function cn(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=>ge(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function P(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=re(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([l,R])=>[l,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(l=>[l,e.getAttribute(l)??""]))}:{},d=$e({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),p=be(e),g=!!(s&&/^[A-Z]/.test(s.tag)),y=!s||!g;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:g?"component-call":"jsx"}:{},...g&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...u,runtimeFlags:{selectable:!0,movable:d.canMove,removable:d.canRemove,textEditable:d.canUpdateText,container:p?!1:(s?.childKeys.length??0)>0||d.canInsertChild||y&&ye(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:ln(e),spacing:cn(e)}}function dn(e,t,n,r,o){let s=ge(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=Ue(e,u))},u=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let l=ge(t.getBoundingClientRect());pn(s,l)&&(s=l,o(P(t,n,r,"summary")))},d=e.ResizeObserver,p=typeof d=="function"?new d(a):null;p?.observe(t);let g=e.MutationObserver,y=typeof g=="function"?new g(a):null;return y?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(He(e,i),i=null),p?.disconnect(),y?.disconnect(),e.document.removeEventListener("load",a,!0)}}function ge(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function pn(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 fn(e,t,n,r,o,s,i){let a=e.document,u=te(a,t,n);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let d=o?q(a,o,s):null;if(d&&We(u,d))return L(a,u,"self-or-descendant",s,i);let p=null,g=!1,y=u,l=u.parentElement;for(;l;){if(l.getAttribute("data-vcp-edit-key")){if(d&&We(l,d))return L(a,u,"self-or-descendant",s,i);let E=Ke(l,r,i);if(E==="accept"){p={child:y,targetParent:l};break}E==="blocked"&&(g=!0),y=l}l=l.parentElement}let R=Ke(u,r,i);if(R==="accept"){if(p){let E=qe(p.child,p.targetParent,t,n,"edge");if(E)return pe(a,p.child,p.targetParent,E,s,i)}return pe(a,u,u,hn(u,t,n),s,i)}if(p){let E=qe(p.child,p.targetParent,t,n,"nearest");return pe(a,p.child,p.targetParent,E??"after",s,i)}return R==="blocked"||g?L(a,u,"operation-boundary-blocked",s,i):L(a,u,"no-accepting-parent",s,i)}function L(e,t,n,r,o){return{anchorHit:P(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function pe(e,t,n,r,o,s){let i=P(t,O(e,t,o),s,"summary"),a=P(n,O(e,n,o),s,"summary"),u=re(n).indicatorOrientation,d=r==="append"||r==="prepend"?mn(n.getBoundingClientRect(),u,r):gn(t.getBoundingClientRect(),u,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:u,indicatorBounds:d}}function Ke(e,t,n){if(be(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 ye(s)?"accept":"not-container"}function qe(e,t,n,r,o){let s=re(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 hn(e,t,n){let r=re(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 re(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 mn(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 gn(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 We(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ee(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:D(e.scrollX),scrollY:D(e.scrollY),scrollWidth:Math.max(D(t?.scrollWidth),D(n?.scrollWidth),D(e.innerWidth)),scrollHeight:Math.max(D(t?.scrollHeight),D(n?.scrollHeight),D(e.innerHeight)),viewportWidth:D(e.innerWidth),viewportHeight:D(e.innerHeight)}}function yn(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var bn=500,H=new Map;function Sn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function En(e,t){if(H.size>=bn){let n=H.keys().next().value;n&&H.delete(n)}H.set(e,t)}var $=new Set;function vn(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 $)r.has(o)||n?.removeProperty(o);$.clear();for(let o of r)$.add(o);Cn(e,t.stylesheets??[])}function In(e){let t=e.documentElement?.style;for(let n of $)t?.removeProperty(n);$.clear();for(let n of Ze(e))n.remove()}function Rn(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=Xe(o,i);a&&(s[i]=a)}return s}function Xe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Qe(e,r,n)}function Qe(e,t,n){if(!t)return null;let r=_n(t);if(!r)return t;let o=Xe(e,r.name,n);return o||(r.fallback?Qe(e,r.fallback,n)??r.fallback:null)}function _n(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=xn(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function xn(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function Cn(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Ze(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(Ve,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Ze(e){return Array.from(e.querySelectorAll(`link[${Ve}]`))}function Tn(e,t,n,r,o={}){let s=o.textNode?Nn(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??"",u=kn(i),d=!1,p=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",l),i.removeEventListener("blur",R),i.removeEventListener("input",E),Dn(i,u)},g=v=>{if(d)return;d=!0;let N=i.textContent??"";if(p(),v==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(N),v==="commit"&&N!==a){r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(v){let N=v.target;N&&i.contains(N)||g("commit")}function l(v){if(v.key==="Escape"){v.preventDefault(),g("cancel");return}v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),g("commit"))}function R(){g("commit")}function E(){r({kind:"text-edit-input",payload:{ref:n,hit:P(t,n,void 0,"full")}})}return Pn(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",l),i.addEventListener("blur",R),i.addEventListener("input",E),Fn(i),Mn(i,e.document),p}function Nn(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function kn(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function Pn(e){On(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function Dn(e,t){fe(e,"contenteditable",t.contentEditable),fe(e,"spellcheck",t.spellcheck),fe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function On(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function fe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function An(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 Fn(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Mn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function D(e){let t=Number(e);return Number.isFinite(t)?t:0}import Bn from"node:http";import{randomBytes as jn,timingSafeEqual as wn}from"node:crypto";import Kn from"node:path";import{WebSocket as qn,WebSocketServer as Wn}from"ws";import{createPreviewSiteEditEngineRuntime as Vn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Un,scanNextAppRouterRoutes as Hn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as $n}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as Gn}from"@vcp-dev/contracts";var Yn="127.0.0.1",zn=30218,Jn="/__vcp/site-edit/bridge",Xn=128*1024,et="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function io(e){let t=rt(e),n=st(t),r=ot(),o=r.get(n);if(o)return o;let s=new oe(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 oe(rt(t),e,!1);return n.start({listen:!1}),n}var oe=class{constructor(t,n=Bn.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.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Vn({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Qn({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 $n({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=ot(),n=st(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)},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.refreshRoutes(),this.runtime?.notifyFileChanged(t)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:Hn(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=Un(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 rt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Kn.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Yn,port:e.port??zn,path:e.path??Jn,sessionKey:e.sessionKey??or(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function ot(){let e=globalThis;return e[et]??=new Map,e[et]}function st(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Qn(e){let t=new Wn({maxPayload:Xn,noServer:!0}),n=(r,o,s)=>{if(Zn(r,e)){if(!Ln(r,e)){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
function Ce(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let c=t.get(a);if(typeof c=="number")return c;let d=n.length;return n.push(a),t.set(a,d),d},i=a=>{let c=null;for(let d of Et(a)){let p=`${c??"root"}\0${d}`,h=r.get(p);if(typeof h=="number"){c=h;continue}let v=o.length;o.push({parent:c,token:s(d)}),r.set(p,v),c=v}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 Te(e){if(!St(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 St(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Et(e){if(!e)return[];let t=[],n=0,r=_e(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=_e(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 _e(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var F=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==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!B(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?B(t.payload)&&typeof t.payload.id=="string":t.type==="event"?B(t.payload)&&B(t.payload.event):!1}static isRequestPayload(t,n={}){if(!B(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":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return vt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},Q=class{constructor(t){this.options=t,this.messageQueue=new ue,this.eventDispatcher=new ce(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Ce((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"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=F.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(F.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=It(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(F.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ce=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},ue=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 B(e){return typeof e=="object"&&e!==null}function vt(e){return B(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"&&B(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&B(e.params)}function It(e){try{return F.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Rt="vcp:designer:trace",xt="designer_trace",ke="__VCP_DESIGNER_TRACE__";var _t=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ct(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Rt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(xt)==="1"}catch{return!1}}function w(e,t={},n=globalThis){if(!Ct(n))return;let r={type:e,timestamp:Date.now(),payload:Tt(t)},o=n,s=o[ke]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[ke]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Tt(e){return le(e,0)}function le(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>le(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(_t.test(r)){n[r]="[redacted]";continue}n[r]=le(o,t+1)}return n}var Z=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}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})}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)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=Pt(o,t,n);return w("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Ne(n.request,"kind"),documentVersion:Ne(n.request,"documentVersion")}),new Promise((i,a)=>{this.pending.set(o,{kind:t,resolve:c=>i(c),reject:a}),r.send(F.stringifyMessage(s))})}handleMessage(t){let n=F.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.pending.delete(n.payload.id),n.type==="error"){w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:kt(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Te(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}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)}};function Ne(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function kt(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 Pe(e){return new de(e)}var de=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,Dt(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ot(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 Nt(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 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 w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){w("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}w("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 Nt(e){return e.version===0&&e.rootKeys.length===0}function Pt(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"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 Dt(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 Ot(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 De="vcp-window-message",Lr=1;function At(e){return{source:De,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===De&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Oe="site-edit",Ae="frame-runtime";function $(e,t={}){return At({namespace:Oe,channel:Ae,sessionKey:t.sessionKey,body:e})}function Fe(e){return!Ft(e)||e.namespace!==Oe||e.channel!==Ae?!1:typeof e.body?.type=="string"}var he="vcp-site-edit:route-ready",jt=1e3,Bt="data-vcp-ui-component",Ve="data-vcp-theme-preview",je="::repeat-item#",L="components/ui",Mt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),wt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Kt(e,t=""){let n=Xt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function qt(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 Wt(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function ro(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=Ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:l=>n.currentEntriesByKey.get(l)??null});let r=t.create_client??(l=>new Z({url:l})),o=t.schedule_after_navigation??Yt,s=Wt(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},a=l=>{n.currentDocument=l,n.currentEntriesByKey=new Map((l?.entries??[]).map(R=>[R.key,R]))},c=async(l,R)=>{let y=e.__VCP_SITE_EDIT__;if(!y)return null;let b=await y.getDocument(l);return R!==n.routeSequence||l!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||a(b.data),b.data},d=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,a(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},p=async()=>{let l=Kt(e.location.pathname,t.basePath||"");if(l===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),d();let y=r(s);try{if(await y.connect(),R!==n.routeSequence){y.disconnect();return}e.__VCP_SITE_EDIT__=Pe({routeId:l,client:y,initialDocument:Vt(l)}),n.activeClient=y,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(k=>{k.type==="site-edit.document.changed"&&k.routeId===l&&c(l,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=l;let b=await c(l,R);qt(e,{documentVersion:b?.version??0,routeId:l,versions:t.runtime_versions}),Jt(e,{routeId:l,version:b?.version??0})}catch(b){throw y.disconnect(),b}},h=()=>{i(),n.retryTimer=e.setTimeout(()=>{p().catch(()=>h())},jt)},v=()=>{o(()=>{p().catch(()=>h())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:p,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),d(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=zt(e,v),t.defer_initial_sync){v();return}await p()}function Vt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,c=new Map,d=()=>{n?.(),n=null},p=()=>{r?.(),r=null,o?.(),o=null},h=(I,f,u)=>{let _=s?.sessionKey!==I||s?.sourceWindow!==f||s?.targetOrigin!==u;s={sessionKey:I,sourceWindow:f,targetOrigin:u},_&&(a=null)},v=()=>{for(let I of c.values())I();c.clear()},l=I=>{i=I.routeId==="/"?null:I;let f=`${I.routeId}:${I.version}`;a!==f&&(o?.(),o=null,y({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(a=f))},R=()=>{i&&l(i)},y=I=>{s&&s.sourceWindow.postMessage($({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},b=(I,f,u,_)=>{let x=ne(e.document,f.clientX,f.clientY),C=x?P(x,u==="full"?O(e.document,x,t.getCurrentDocument?.()??null):Me(e.document,x,t.getCurrentDocument?.()??null),t.getDocumentEntry,u):null;_&&C&&(I==="pointer-click"||I==="pointer-double-click")&&(_.preventDefault(),_.stopPropagation(),typeof _.stopImmediatePropagation=="function"&&_.stopImmediatePropagation()),y({kind:I,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:C}})},k=(I,f,u)=>{p(),s={sessionKey:I,sourceWindow:f,targetOrigin:u};let _=An(e.document),x=null,C=null,g=()=>{C=null;let m=x;x=null,m&&b("pointer-move",m,"summary")},N=m=>{x={clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},C===null&&(C=Ue(e,g))},j=m=>{b("pointer-down",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},K=m=>{b("pointer-up",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"summary",m)},A=m=>{b("pointer-cancel",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"summary",m)},M=m=>{b("pointer-click",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},U=m=>{b("pointer-double-click",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},H=()=>{y({kind:"scroll",payload:{metrics:te(e)}})};e.document.addEventListener("pointerdown",j,!0),e.document.addEventListener("pointermove",N,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",K,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",M,!0),e.document.addEventListener("dblclick",U,!0),e.addEventListener("scroll",H,{passive:!0}),r=()=>{C!==null&&(He(e,C),C=null),x=null,_(),e.document.removeEventListener("pointerdown",j,!0),e.document.removeEventListener("pointermove",N,!0),e.document.removeEventListener("pointerup",K,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",M,!0),e.document.removeEventListener("dblclick",U,!0),e.removeEventListener("scroll",H)}},Re=I=>{let f=I.detail;f?.routeId&&l(f)},xe=I=>{let f=I.data;if(!Fe(f)||f.body.type!=="request"||f.body.kind!=="apply-node-patch"&&f.body.kind!=="get-hit-by-ref"&&f.body.kind!=="get-path-by-ref"&&f.body.kind!=="get-scroll-metrics"&&f.body.kind!=="scroll-to"&&f.body.kind!=="scroll-by"&&f.body.kind!=="set-interaction-mode"&&f.body.kind!=="set-theme-override"&&f.body.kind!=="clear-theme-override"&&f.body.kind!=="get-theme-variables"&&f.body.kind!=="compute-drop-target-at-point"&&f.body.kind!=="observe-node-bounds"&&f.body.kind!=="clear-node-bounds-observer"&&f.body.kind!=="start-text-edit-at-point"&&f.body.kind!=="hit-test-at-point"&&!Be(f.body))return;let u=f.body,_=typeof f.sessionKey=="string"?f.sessionKey:null,x=I.source,C=I.origin;if(!_||!C||!x||typeof x.postMessage!="function"||s&&(s.sessionKey!==_||s.sourceWindow!==x||s.targetOrigin!==C))return;h(_,x,C),R();let g=N=>{let j=typeof u.id=="string"?u.id:"unknown";x.postMessage($({id:j,...N},{sessionKey:_}),C)};try{if(Be(u)){Ht({message:u,sendEvent:S=>{x.postMessage($({type:"event",...S},{sessionKey:_}),C)},sendResponse:g,subscriptions:c,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(u.kind==="apply-node-patch"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for patch target"});return}let E=u.payload.preview,T=E?Sn(E.sessionId,u.payload.ref):null;if(T&&E){let X=G.get(T)??-1;if(E.revision<X){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:E.revision,stale:!0,latestRevision:X}});return}if(E.revision===X){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:E.revision,duplicate:!0,latestRevision:X}});return}}if(yn(S,u.payload.patch),T&&E&&En(T,E.revision),E?.responseDetail==="none"){g({type:"response",ok:!0,result:{applied:!0,appliedRevision:E.revision}});return}g({type:"response",ok:!0,result:P(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,E?.responseDetail??"full")});return}if(u.kind==="get-hit-by-ref"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for hit target"});return}g({type:"response",ok:!0,result:P(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(u.kind==="get-path-by-ref"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for path target"});return}let E=[],T=S;for(;T;)T.getAttribute("data-vcp-edit-key")&&E.push(P(T,O(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),T=T.parentElement;g({type:"response",ok:!0,result:E.reverse()});return}if(u.kind==="get-scroll-metrics"){g({type:"response",ok:!0,result:te(e)});return}if(u.kind==="scroll-to"){let S=Number(u.payload.x),E=Number(u.payload.y);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:S,top:E}),g({type:"response",ok:!0,result:te(e)});return}if(u.kind==="scroll-by"){let S=Number(u.payload.deltaX),E=Number(u.payload.deltaY);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:S,top:E}),g({type:"response",ok:!0,result:{...te(e),scrolled:!0}});return}if(u.kind==="set-interaction-mode"){u.payload.enabled?k(_,x,C):s?.sourceWindow===x&&s.targetOrigin===C&&s.sessionKey===_&&p(),g({type:"response",ok:!0,result:{interactionEnabled:u.payload.enabled}});return}if(u.kind==="set-theme-override"){vn(e.document,u.payload),g({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(u.kind==="clear-theme-override"){In(e.document),g({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(u.kind==="get-theme-variables"){g({type:"response",ok:!0,result:Rn(e.document,u.payload.names)});return}if(u.kind==="compute-drop-target-at-point"){let S=Number(u.payload?.x),E=Number(u.payload?.y);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid drop target point"});return}g({type:"response",ok:!0,result:pn(e,S,E,u.payload.dragKind,u.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(u.kind==="observe-node-bounds"){let S=u.payload.ref;if(!S){g({type:"response",ok:!1,error:"Missing bounds observer target"});return}let E=q(e.document,S,t.getCurrentDocument?.()??null);if(!E){g({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=dn(e,E,S,t.getDocumentEntry,T=>y({kind:"node-bounds-change",payload:{hit:T}})),g({type:"response",ok:!0,result:{observing:!0}}),y({kind:"node-bounds-change",payload:{hit:P(E,S,t.getDocumentEntry,"summary")}});return}if(u.kind==="clear-node-bounds-observer"){o?.(),o=null,g({type:"response",ok:!0,result:{cleared:!0}});return}if(u.kind!=="hit-test-at-point"&&u.kind!=="start-text-edit-at-point")return;let N=Number(u.payload?.x),j=Number(u.payload?.y);if(!Number.isFinite(N)||!Number.isFinite(j)){g({type:"response",ok:!1,error:"Invalid text edit point"});return}let K=u.kind==="hit-test-at-point"?ne(e.document,N,j):Zt(e.document,N,j,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!K){g({type:"response",ok:!1,error:u.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=u.kind==="start-text-edit-at-point"?K:null,M=u.kind==="hit-test-at-point"?K:A.element,U=u.payload.detailLevel??"full",H=U==="full"?O(e.document,M,t.getCurrentDocument?.()??null):Me(e.document,M,t.getCurrentDocument?.()??null),m=A&&typeof A.textSegmentIndex=="number"?{...H,textSegmentIndex:A.textSegmentIndex}:H,bt=P(M,m,t.getDocumentEntry,U);if(u.kind==="hit-test-at-point"){g({type:"response",ok:!0,result:bt});return}d(),n=Tn(e,M,m,S=>{x.postMessage($({type:"event",...S},{sessionKey:_}),C)},A?{textNode:A.textNode}:void 0),g({type:"response",ok:!0,result:{ref:m}})}catch(N){g({type:"response",ok:!1,error:N instanceof Error?N.message:"Failed to start text edit"})}};return e.addEventListener("message",xe),e.addEventListener(he,Re),()=>{d(),p(),s=null,v(),e.removeEventListener("message",xe),e.removeEventListener(he,Re)}}function Be(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-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function Ht({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){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 i.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:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let a=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:$t(a,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let a=e.payload.subscriptionId;r.get(a)?.();let c=i.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:a}})});r.set(a,c),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let a=e.payload.subscriptionId;r.get(a)?.(),r.delete(a),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(a){n({type:"response",ok:!1,error:a instanceof Error?a.message:"Site edit bridge request failed"})}}function $t(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=q(n,{key:t},r),s=o?Gt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Gt(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 zt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let a=n.apply(this,i);return t(),a},e.history.replaceState=function(...i){let a=r.apply(this,i);return t(),a},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function Yt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ue(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function He(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Jt(e,t){e.dispatchEvent(new CustomEvent(he,{detail:t}))}function Xt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ye(e){return Mt.has(Ge(e))}function Qt(e){return wt.has(Ge(e))}function $e(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:Qt(e.tagName),canInsertChild:ye(e.tagName),canMove:!1,canRemove:!1}}function Ge(e){return e?.trim().toLowerCase()??""}function Zt(e,t,n,r,o){let s=ne(e,t,n),i=ze(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=O(e,i,r),d=o?.(c.key)??o?.(a);if(!$e({operationSummary:d?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((d?.childKeys.length??0)===0)return{element:i};let h=Lt(e,t,n,i);if(!h)return null;let v=tn(i,h);return v===null?null:{element:i,textNode:h,textSegmentIndex:v}}function Lt(e,t,n,r){let o=en(e,t,n);return!o||o.parentElement!==r?null:o}function en(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(me(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return me(a)?a:null}function tn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!me(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function me(e){return e?.nodeType===3}function ne(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=ze(o);if(s)return s}return null}function ze(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(be(t))return n??t;!nn(r)&&!n&&(n=t)}t=t.parentElement}return n}function be(e){return e.getAttribute(Bt)!==null}function nn(e){return rn(e.split("::")[0]??"")}function rn(e){if(!e)return!1;let t=on(e);return t===L||t.startsWith(`${L}/`)||t.includes(`/${L}/`)||t.endsWith(`/${L}`)}function on(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=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length<=1)return{key:we(n,r,0)};let s=o.indexOf(t);return s>=0?{key:we(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function Me(e,t,n){return O(e,t,n)}function q(e,t,n){let r=re(t.key)??t.key,o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(re(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=sn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function we(e,t,n){return Ye(e,t)[n]?.key??t}function sn(e,t){let n=re(t);if(!n)return null;let o=Ye(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function Ye(e,t){return(e?.entries??[]).filter(n=>(re(n.key)??n.key)===t)}var an=2,cn=4;function Je(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&cn)!==0?-1:(r&an)!==0?1:0})}function re(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(je);if(n<0)break;let r=Number(t.slice(n+je.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function un(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=>ge(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function P(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=oe(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([l,R])=>[l,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(l=>[l,e.getAttribute(l)??""]))}:{},d=$e({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),p=be(e),h=!!(s&&/^[A-Z]/.test(s.tag)),v=!s||!h;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:h?"component-call":"jsx"}:{},...h&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:d.canMove,removable:d.canRemove,textEditable:d.canUpdateText,container:p?!1:(s?.childKeys.length??0)>0||d.canInsertChild||v&&ye(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:ln(e),spacing:un(e)}}function dn(e,t,n,r,o){let s=ge(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=Ue(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let l=ge(t.getBoundingClientRect());fn(s,l)&&(s=l,o(P(t,n,r,"summary")))},d=e.ResizeObserver,p=typeof d=="function"?new d(a):null;p?.observe(t);let h=e.MutationObserver,v=typeof h=="function"?new h(a):null;return v?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(He(e,i),i=null),p?.disconnect(),v?.disconnect(),e.document.removeEventListener("load",a,!0)}}function ge(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function fn(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 pn(e,t,n,r,o,s,i){let a=e.document,c=ne(a,t,n);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let d=o?q(a,o,s):null;if(d&&We(c,d))return ee(a,c,"self-or-descendant",s,i);let p=null,h=!1,v=c,l=c.parentElement;for(;l;){if(l.getAttribute("data-vcp-edit-key")){if(d&&We(l,d))return ee(a,c,"self-or-descendant",s,i);let y=Ke(l,r,i);if(y==="accept"){p={child:v,targetParent:l};break}y==="blocked"&&(h=!0),v=l}l=l.parentElement}let R=Ke(c,r,i);if(R==="accept"){if(p){let y=qe(p.child,p.targetParent,t,n,"edge");if(y)return fe(a,p.child,p.targetParent,y,s,i)}return fe(a,c,c,hn(c,t,n),s,i)}if(p){let y=qe(p.child,p.targetParent,t,n,"nearest");return fe(a,p.child,p.targetParent,y??"after",s,i)}return R==="blocked"||h?ee(a,c,"operation-boundary-blocked",s,i):ee(a,c,"no-accepting-parent",s,i)}function ee(e,t,n,r,o){return{anchorHit:P(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function fe(e,t,n,r,o,s){let i=P(t,O(e,t,o),s,"summary"),a=P(n,O(e,n,o),s,"summary"),c=oe(n).indicatorOrientation,d=r==="append"||r==="prepend"?mn(n.getBoundingClientRect(),c,r):gn(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:d}}function Ke(e,t,n){if(be(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 ye(s)?"accept":"not-container"}function qe(e,t,n,r,o){let s=oe(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 hn(e,t,n){let r=oe(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 oe(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 mn(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 gn(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 We(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function te(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:D(e.scrollX),scrollY:D(e.scrollY),scrollWidth:Math.max(D(t?.scrollWidth),D(n?.scrollWidth),D(e.innerWidth)),scrollHeight:Math.max(D(t?.scrollHeight),D(n?.scrollHeight),D(e.innerHeight)),viewportWidth:D(e.innerWidth),viewportHeight:D(e.innerHeight)}}function yn(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var bn=500,G=new Map;function Sn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function En(e,t){if(G.size>=bn){let n=G.keys().next().value;n&&G.delete(n)}G.set(e,t)}var z=new Set;function vn(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 z)r.has(o)||n?.removeProperty(o);z.clear();for(let o of r)z.add(o);Cn(e,t.stylesheets??[])}function In(e){let t=e.documentElement?.style;for(let n of z)t?.removeProperty(n);z.clear();for(let n of Ze(e))n.remove()}function Rn(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=Xe(o,i);a&&(s[i]=a)}return s}function Xe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Qe(e,r,n)}function Qe(e,t,n){if(!t)return null;let r=xn(t);if(!r)return t;let o=Xe(e,r.name,n);return o||(r.fallback?Qe(e,r.fallback,n)??r.fallback:null)}function xn(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=_n(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 _n(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 Cn(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Ze(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(Ve,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Ze(e){return Array.from(e.querySelectorAll(`link[${Ve}]`))}function Tn(e,t,n,r,o={}){let s=o.textNode?kn(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=Nn(i),d=!1,p=()=>{e.document.removeEventListener("pointerdown",v,!0),i.removeEventListener("keydown",l),i.removeEventListener("blur",R),i.removeEventListener("input",y),Dn(i,c)},h=b=>{if(d)return;d=!0;let k=i.textContent??"";if(p(),b==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(k),b==="commit"&&k!==a){r({kind:"text-edit-commit",payload:{ref:n,value:k}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function v(b){let k=b.target;k&&i.contains(k)||h("commit")}function l(b){if(b.key==="Escape"){b.preventDefault(),h("cancel");return}b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),h("commit"))}function R(){h("commit")}function y(){r({kind:"text-edit-input",payload:{ref:n,hit:P(t,n,void 0,"full")}})}return Pn(i),e.document.addEventListener("pointerdown",v,!0),i.addEventListener("keydown",l),i.addEventListener("blur",R),i.addEventListener("input",y),Fn(i),jn(i,e.document),p}function kn(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Nn(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function Pn(e){On(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function Dn(e,t){pe(e,"contenteditable",t.contentEditable),pe(e,"spellcheck",t.spellcheck),pe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function On(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function pe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function An(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 Fn(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function jn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function D(e){let t=Number(e);return Number.isFinite(t)?t:0}import Bn from"node:http";import{randomBytes as Mn,timingSafeEqual as wn}from"node:crypto";import Kn from"node:path";import{WebSocket as qn,WebSocketServer as Wn}from"ws";import{createPreviewSiteEditEngineRuntime as Vn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Un,scanNextAppRouterRoutes as Hn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as $n}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as Gn}from"@vcp-dev/contracts";var zn="127.0.0.1",Yn=30218,Jn="/__vcp/site-edit/bridge",Xn=128*1024,et="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function mo(e){let t=rt(e),n=st(t),r=ot(),o=r.get(n);if(o)return o;let s=new se(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 se(rt(t),e,!1);return n.start({listen:!1}),n}var se=class{constructor(t,n=Bn.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.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Vn({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Qn({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 $n({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=ot(),n=st(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)},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.refreshRoutes(),this.runtime?.notifyFileChanged(t)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:Hn(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=Un(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 rt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Kn.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??zn,port:e.port??Yn,path:e.path??Jn,sessionKey:e.sessionKey??or(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function ot(){let e=globalThis;return e[et]??=new Map,e[et]}function st(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Qn(e){let t=new Wn({maxPayload:Xn,noServer:!0}),n=(r,o,s)=>{if(Zn(r,e)){if(!Ln(r,e)){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),o.destroy();return}t.handleUpgrade(r,o,s,i=>{t.emit("connection",i,r)})}};return e.server.on("upgrade",n),t.on("connection",r=>{new
|
|
4
|
+
`),o.destroy();return}t.handleUpgrade(r,o,s,i=>{t.emit("connection",i,r)})}};return e.server.on("upgrade",n),t.on("connection",r=>{new Q({socket:new Ee(r),engine:e.engine,validateOperationRequest:o=>Gn.safeParse(o).success})}),t.stop=()=>{e.server.off("upgrade",n);for(let r of t.clients)r.close(1001,"bridge stopped");t.close()},t}var Ee=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===qn.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function Zn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Ln(e,t){let r=new URL(e.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??Se(e.headers["x-vcp-site-edit-key"]);if(!er(r,t.sessionKey))return!1;let o=Se(e.headers.host),s=Se(e.headers.origin);return o&&!tr(o,t.host,s)?!1:s?t.allowedOrigins.includes(s)||rr(s)||(o?it(s,o):!1):!0}function er(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&wn(n,r)}function tr(e,t,n){let r=tt(e),o=tt(t);return r===o||r==="localhost"||r==="127.0.0.1"||r==="::1"||nr(o)&&!!(n&&it(n,e))}function nr(e){return e==="0.0.0.0"||e==="::"}function rr(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}}function it(e,t){try{return new URL(e).host===at(t)}catch{return!1}}function tt(e){let t=at(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function at(e){return e.trim().toLowerCase()}function Se(e){return Array.isArray(e)?e[0]:e}function or(){return Mn(32).toString("base64url")}import sr from"node:http";import{existsSync as V,readFileSync as W}from"node:fs";import{createRequire as dt}from"node:module";import ae from"node:path";import{basename as ft,dirname as Y,join as J}from"node:path";import{fileURLToPath as pt}from"node:url";var ir="next",ar="127.0.0.1",cr=3e3,ht="/__vcp/site-edit/bridge",ie="/__vcp/site-edit/client/",ur=`${ie}auto-bootstrap.js`,mt='data-vcp-site-edit-bootstrap="true"',lr=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],dr="@vcp-dev/site-edit-engine/webpack-loader",fr=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,pr=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],hr=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function xo(e={}){let t=ae.resolve(e.projectRoot??process.cwd()),n=e.host??ar,r=e.port??Ur(process.env.PORT)??cr,o=e.bridgePath??ht,s=Fr(),i=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=await Kr(t),c=mr(t),d=a({dev:!0,dir:t,hostname:n,port:r,...gr(c)}),p=d.getRequestHandler();await d.prepare();let h=sr.createServer((R,y)=>{Tr({basePath:i,bridgePath:o,bridgeSessionKey:s,handle:p,request:R,response:y}).catch(b=>{console.error(b),y.headersSent||(y.statusCode=500),y.end("site edit preview request failed")})}),v=nt(h,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??Vr(t),projectRoot:t,basePath:i,host:n,port:r,path:o,sessionKey:s});Sr({server:h,bridgePath:o,handleUpgrade:d.getUpgradeHandler()});let l=()=>{v.stop(),d.close().catch(()=>{}),h.close()};return process.on("SIGINT",l),process.on("SIGTERM",l),await Hr(h,r,n),{bundler:c,close:l,server:h}}function mr(e){let t=yr(e);return t&&br(t)?"webpack":"turbopack"}function gr(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function yr(e){for(let t of lr){let n=J(e,t);if(V(n))return W(n,"utf8")}return null}function br(e){return e.includes(dr)?!0:fr.test(e)&&pr.some(t=>t.test(e))}function Sr(e){let t=(n,r,o)=>{Er(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 Er(e,t){return new URL(e??"/","http://localhost").pathname===t}function vr(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ir()});return`<script type="module" ${mt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(ur)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ir(){return{bridge:ve("@vcp-dev/site-edit-bridge"),contracts:ve("@vcp-dev/contracts"),engine:ve("@vcp-dev/site-edit-engine")}}function ve(e){let t=dt(import.meta.url);try{let n=t.resolve(e),r=Rr(n,e);if(!r)return;let o=JSON.parse(W(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Rr(e,t){let n=ae.parse(e).root,r=Y(e);for(;r&&r!==n;){let o=J(r,"package.json");if(V(o))try{if(JSON.parse(W(o,"utf8")).name===t)return o}catch{return}r=Y(r)}}function xr(e,t){if(e.includes(mt))return e;let n=vr(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function _o(e,t=Y(pt(import.meta.url)),n=V){return gt(e,t,n)?.path??null}function gt(e,t=Y(pt(import.meta.url)),n=V){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(ie))return null;let o=r.slice(ie.length);if(!hr.has(o))return null;let s=Ie(qr(t),o);if(ft(t)!=="src")return{path:s,requiresTranspile:!1};let i=Ie(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function _r(e,t){let n=gt(e.url);if(!n)return!1;if(!V(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Cr(W(n.path,"utf8")):W(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Cr(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Tr({basePath:e,bridgePath:t,bridgeSessionKey:n,handle:r,request:o,response:s}){if(await _r(o,s))return;let i=kr(o),a=Nr(o),c=i||a?Or(s,{basePath:e,bridgePath:t,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(o,s)}catch(d){throw c(),d}}function kr(e){return Pr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Nr(e){return Dr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Pr(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(ie)||t===ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Dr(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 Or(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,d)=>(a!==void 0&&n.push(ct(a,ut(c))),lt(c),lt(d),!0),r.end=(a,c,d)=>{let p=typeof a=="function"?void 0:a;p!==void 0&&n.push(ct(p,ut(c))),r.write=s,r.end=i,r.flushHeaders=o;let h=Buffer.concat(n),v=Ar(e,h,t);v!==h&&!e.headersSent&&e.removeHeader("content-length");let l=typeof a=="function"?a:typeof c=="function"?c:typeof d=="function"?d:void 0;return l?i(v,l):i(v)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function Ar(e,t,n){if(jr(e,t))return Buffer.from(xr(t.toString("utf8"),n));if(n.patchNextDevChunk&&Br(e)){let r=t.toString("utf8"),o=Mr(r);if(o!==r)return Buffer.from(o)}return t}function Fr(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function jr(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 Br(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 Mr(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
5
5
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
6
|
-
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,o])=>
|
|
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])=>wr(n,r,o),e)}function wr(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 ct(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function ut(e){return typeof e=="string"?e:void 0}function lt(e){typeof e=="function"&&e()}async function Kr(e){let n=dt(J(e,"package.json"))(ir);return n.default??n}function qr(e){return ft(e)!=="src"?e:Ie(Wr(e),"dist")}function Wr(e){return yt(e)?ae.posix.dirname(e):Y(e)}function Ie(e,t){return yt(e)?ae.posix.join(e,t):J(e,t)}function yt(e){return e.includes("/")&&!e.includes("\\")}function Vr(e){let t=J(e,".vcp/current-snapshot.json");if(!V(t))return"sandbox_worktree";try{let n=JSON.parse(W(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Ur(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Hr(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Ae as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Oe as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,se as SiteEditBridgeServer,Q as SiteEditBridgeSocketServer,F as SiteEditBridgeTransport,Z as SiteEditWebSocketClient,he as VCP_SITE_EDIT_ROUTE_READY_EVENT,De as VCP_WINDOW_MESSAGE_SOURCE,Lr as VCP_WINDOW_MESSAGE_VERSION,Sr as attachNextDevUpgradeHandler,nt as attachSiteEditBridgeServer,Qn as attachSiteEditWebSocketServer,vr as createSiteEditAutoBootstrapHtmlSnippet,Pe as createSiteEditBridge,$ as createSiteEditFrameRuntimeMessage,At as createVcpWindowMessageEnvelope,Te as decodeRenderDocument,Ce as encodeRenderDocument,mo as ensureSiteEditBridgeServerStarted,xr as injectSiteEditAutoBootstrap,St as isCompactRenderDocument,Ct as isDesignerTraceEnabled,Fe as isSiteEditFrameRuntimeMessage,Ft as isVcpWindowMessageEnvelope,Mr as patchNextFirefoxDevChunk,Nr as prepareFirefoxNextDevChunkPatchRequest,kr as prepareSiteEditHtmlInjectionRequest,gt as resolveSiteEditClientAsset,_o as resolveSiteEditClientAssetPath,mr as resolveSiteEditNextDevBundler,Kt as resolveSiteEditRouteId,Wt as resolveSiteEditWebSocketUrl,Tt as sanitizeTracePayload,ro as startSiteEditAutoBootstrap,Ut as startSiteEditFrameRuntime,xo as startSiteEditNextDevServer,w as traceDesignerEvent,Cr as transpileSiteEditClientSource};
|
|
@@ -10,14 +10,17 @@ export type SiteEditNextDevServerOptions = {
|
|
|
10
10
|
siteId?: string;
|
|
11
11
|
snapshotId?: string;
|
|
12
12
|
};
|
|
13
|
+
export type SiteEditNextDevBundler = "turbopack" | "webpack";
|
|
13
14
|
type SiteEditClientAsset = {
|
|
14
15
|
path: string;
|
|
15
16
|
requiresTranspile: boolean;
|
|
16
17
|
};
|
|
17
18
|
export declare function startSiteEditNextDevServer(options?: SiteEditNextDevServerOptions): Promise<{
|
|
19
|
+
bundler: SiteEditNextDevBundler;
|
|
18
20
|
close: () => void;
|
|
19
21
|
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
20
22
|
}>;
|
|
23
|
+
export declare function resolveSiteEditNextDevBundler(projectRoot: string): SiteEditNextDevBundler;
|
|
21
24
|
export declare function attachNextDevUpgradeHandler(input: {
|
|
22
25
|
server: HttpServer;
|
|
23
26
|
bridgePath: string;
|
package/dist/next-dev-server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import ve from"node:http";import{existsSync as y,readFileSync as g}from"node:fs";import{createRequire as D}from"node:module";import x from"node:path";import{basename as J,dirname as m,join as I}from"node:path";import{fileURLToPath as W}from"node:url";import Y from"node:http";import{randomBytes as Z,timingSafeEqual as ee}from"node:crypto";import te from"node:path";import{WebSocket as ne,WebSocketServer as re}from"ws";import{createPreviewSiteEditEngineRuntime as se}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as oe,scanNextAppRouterRoutes as ie}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ae}from"@vcp-dev/site-edit-engine/source-watcher";function _(t){let e=new Map,n=[],r=new Map,s=[],o=i=>{let a=e.get(i);if(typeof a=="number")return a;let c=n.length;return n.push(i),e.set(i,c),c},u=i=>{let a=null;for(let c of G(i)){let d=`${a??"root"}\0${c}`,l=r.get(d);if(typeof l=="number"){a=l;continue}let h=s.length;s.push({parent:a,token:o(c)}),r.set(d,h),a=h}if(a===null)throw new Error("Document key must not be empty");return a};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,tokens:n,nodes:s,rootKeyNodeIds:t.rootKeys.map(u),entries:t.entries.map(i=>({keyNodeId:u(i.key),tag:i.tag,label:i.label,parentKeyNodeId:i.parentKey?u(i.parentKey):null,childKeyNodeIds:i.childKeys.map(u),operationSummary:i.operationSummary}))}}function G(t){if(!t)return[];let e=[],n=0,r=N(t,n);if(r<0)return e.push(t),e;for(e.push(t.slice(0,r)),n=r;n<t.length;){if(r=N(t,n+(t.startsWith("::",n)?2:1)),r<0){e.push(t.slice(n));break}e.push(t.slice(n,r)),n=r}return e}function N(t,e){let n=t.indexOf("/",e),r=t.indexOf("::",e);return n<0?r:r<0?n:Math.min(n,r)}var p=class t{constructor(){}static parseMessage(e,n={}){let r=JSON.parse(e);if(!t.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let n=e.payload,r=typeof n.id=="string"?n.id:"unknown",s=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="get-document"||e==="get-object-summary"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="execute"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!f(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?f(e.payload)&&typeof e.payload.id=="string":e.type==="event"?f(e.payload)&&f(e.payload.event):!1}static isRequestPayload(e,n={}){if(!f(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"get-document":return typeof e.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"execute":return Q(e.request)&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return!0}}},w=class{constructor(e){this.options=e,this.messageQueue=new k,this.eventDispatcher=new v(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.eventDispatcher.push(n)}),e.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"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let r=n.payload,{id:s}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:{ok:!0,data:_((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:s,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:s,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:s,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"execute":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=p.extractRequestInfo(e);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(e){try{await this.handleMessage(p.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",s=X(e);this.sendJson({type:"error",payload:{...s,message:r}})}}sendJson(e){this.options.socket.send(p.stringifyMessage(e))}async handleBufferedOperation(e,n,r){this.eventDispatcher.beginBuffering();try{let s=await r();this.sendJson({type:"response",payload:{id:e,kind:n,result:s}}),this.eventDispatcher.flush()}catch(s){this.sendJson({type:"error",payload:{id:e,kind:n,message:s instanceof Error?s.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},v=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},k=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function f(t){return typeof t=="object"&&t!==null}function Q(t){return f(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&f(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&f(t.params)}function X(t){try{return p.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}import{SiteEditOperationRequestSchema as ue}from"@vcp-dev/contracts";var ce="127.0.0.1",de=30218,he="/__vcp/site-edit/bridge",fe=128*1024,H="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function K(t,e){let n=new P(le(e),t,!1);return n.start({listen:!1}),n}var P=class{constructor(e,n=Y.createServer((s,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),r=!0){this.options=e,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.isStarted=!1}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=se({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=me({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 ae({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=pe(),n=ge(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async e=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(e);return n.getDocument(r)},getObjectSummary:async(e,n)=>this.getRuntime().getObjectSummary(e,n?this.resolveRouteId(n):void 0),getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let r=this.getRuntime(),s=n?this.resolveRouteId(n):void 0;return await r.refreshSourceForKey(e,s),r.getClassNameSource(e,s)},execute:async e=>this.getRuntime().executeOperation(this.normalizeRequest(e)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:e=>this.getRuntime().subscribe(e)}}async activateRoute(e){let n=this.getRuntime(),r=this.resolveRouteId(e);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.refreshRoutes(),this.runtime?.notifyFileChanged(e)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:ie(this.options.projectRoot),n=new Map(this.routes.map(s=>[s.routeId,s.entryFile])),r=new Set(e.map(s=>s.routeId));this.routes=e;for(let s of e)n.get(s.routeId)!==s.entryFile&&this.runtime?.registerRoute(s.routeId,s.entryFile);for(let s of n.keys())r.has(s)||this.runtime?.unregisterRoute(s)}resolveRouteId(e){let n=oe(e,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function le(t){return{siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:te.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??ce,port:t.port??de,path:t.path??he,sessionKey:t.sessionKey??Ie(),allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function pe(){let t=globalThis;return t[H]??=new Map,t[H]}function ge(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}`}function me(t){let e=new re({maxPayload:fe,noServer:!0}),n=(r,s,o)=>{if(ye(r,t)){if(!Se(r,t)){s.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import ke from"node:http";import{existsSync as y,readFileSync as m}from"node:fs";import{createRequire as U}from"node:module";import v from"node:path";import{basename as J,dirname as b,join as S}from"node:path";import{fileURLToPath as W}from"node:url";import Y from"node:http";import{randomBytes as ee,timingSafeEqual as te}from"node:crypto";import ne from"node:path";import{WebSocket as re,WebSocketServer as se}from"ws";import{createPreviewSiteEditEngineRuntime as oe}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as ie,scanNextAppRouterRoutes as ae}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ce}from"@vcp-dev/site-edit-engine/source-watcher";function _(t){let e=new Map,n=[],r=new Map,s=[],o=i=>{let a=e.get(i);if(typeof a=="number")return a;let u=n.length;return n.push(i),e.set(i,u),u},c=i=>{let a=null;for(let u of Q(i)){let p=`${a??"root"}\0${u}`,d=r.get(p);if(typeof d=="number"){a=d;continue}let f=s.length;s.push({parent:a,token:o(u)}),r.set(p,f),a=f}if(a===null)throw new Error("Document key must not be empty");return a};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,tokens:n,nodes:s,rootKeyNodeIds:t.rootKeys.map(c),entries:t.entries.map(i=>({keyNodeId:c(i.key),tag:i.tag,label:i.label,parentKeyNodeId:i.parentKey?c(i.parentKey):null,childKeyNodeIds:i.childKeys.map(c),operationSummary:i.operationSummary}))}}function Q(t){if(!t)return[];let e=[],n=0,r=B(t,n);if(r<0)return e.push(t),e;for(e.push(t.slice(0,r)),n=r;n<t.length;){if(r=B(t,n+(t.startsWith("::",n)?2:1)),r<0){e.push(t.slice(n));break}e.push(t.slice(n,r)),n=r}return e}function B(t,e){let n=t.indexOf("/",e),r=t.indexOf("::",e);return n<0?r:r<0?n:Math.min(n,r)}var g=class t{constructor(){}static parseMessage(e,n={}){let r=JSON.parse(e);if(!t.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let n=e.payload,r=typeof n.id=="string"?n.id:"unknown",s=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="get-document"||e==="get-object-summary"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="execute"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):!1}static isRequestPayload(e,n={}){if(!h(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"get-document":return typeof e.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"execute":return Z(e.request)&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return!0}}},R=class{constructor(e){this.options=e,this.messageQueue=new k,this.eventDispatcher=new I(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.eventDispatcher.push(n)}),e.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"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let r=n.payload,{id:s}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:{ok:!0,data:_((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:s,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:s,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:s,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"execute":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=g.extractRequestInfo(e);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(e){try{await this.handleMessage(g.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",s=X(e);this.sendJson({type:"error",payload:{...s,message:r}})}}sendJson(e){this.options.socket.send(g.stringifyMessage(e))}async handleBufferedOperation(e,n,r){this.eventDispatcher.beginBuffering();try{let s=await r();this.sendJson({type:"response",payload:{id:e,kind:n,result:s}}),this.eventDispatcher.flush()}catch(s){this.sendJson({type:"error",payload:{id:e,kind:n,message:s instanceof Error?s.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},I=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},k=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function h(t){return typeof t=="object"&&t!==null}function Z(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&h(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function X(t){try{return g.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}import{SiteEditOperationRequestSchema as ue}from"@vcp-dev/contracts";var de="127.0.0.1",fe=30218,he="/__vcp/site-edit/bridge",pe=128*1024,H="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function K(t,e){let n=new P(le(e),t,!1);return n.start({listen:!1}),n}var P=class{constructor(e,n=Y.createServer((s,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),r=!0){this.options=e,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.isStarted=!1}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=oe({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=ye({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 ce({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=ge(),n=me(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async e=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(e);return n.getDocument(r)},getObjectSummary:async(e,n)=>this.getRuntime().getObjectSummary(e,n?this.resolveRouteId(n):void 0),getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let r=this.getRuntime(),s=n?this.resolveRouteId(n):void 0;return await r.refreshSourceForKey(e,s),r.getClassNameSource(e,s)},execute:async e=>this.getRuntime().executeOperation(this.normalizeRequest(e)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:e=>this.getRuntime().subscribe(e)}}async activateRoute(e){let n=this.getRuntime(),r=this.resolveRouteId(e);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.refreshRoutes(),this.runtime?.notifyFileChanged(e)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:ae(this.options.projectRoot),n=new Map(this.routes.map(s=>[s.routeId,s.entryFile])),r=new Set(e.map(s=>s.routeId));this.routes=e;for(let s of e)n.get(s.routeId)!==s.entryFile&&this.runtime?.registerRoute(s.routeId,s.entryFile);for(let s of n.keys())r.has(s)||this.runtime?.unregisterRoute(s)}resolveRouteId(e){let n=ie(e,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function le(t){return{siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:ne.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??de,port:t.port??fe,path:t.path??he,sessionKey:t.sessionKey??Ie(),allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function ge(){let t=globalThis;return t[H]??=new Map,t[H]}function me(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}`}function ye(t){let e=new se({maxPayload:pe,noServer:!0}),n=(r,s,o)=>{if(be(r,t)){if(!Se(r,t)){s.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),s.destroy();return}e.handleUpgrade(r,s,o,
|
|
4
|
+
`),s.destroy();return}e.handleUpgrade(r,s,o,c=>{e.emit("connection",c,r)})}};return t.server.on("upgrade",n),e.on("connection",r=>{new R({socket:new j(r),engine:t.engine,validateOperationRequest:s=>ue.safeParse(s).success})}),e.stop=()=>{t.server.off("upgrade",n);for(let r of e.clients)r.close(1001,"bridge stopped");e.close()},e}var j=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){this.socket.readyState===re.OPEN&&this.socket.send(e)}close(e,n){this.socket.close(e,n)}};function be(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Se(t,e){let r=new URL(t.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??E(t.headers["x-vcp-site-edit-key"]);if(!we(r,e.sessionKey))return!1;let s=E(t.headers.host),o=E(t.headers.origin);return s&&!Re(s,e.host,o)?!1:o?e.allowedOrigins.includes(o)||ve(o)||(s?q(o,s):!1):!0}function we(t,e){if(!t)return!1;let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&te(n,r)}function Re(t,e,n){let r=O(t),s=O(e);return r===s||r==="localhost"||r==="127.0.0.1"||r==="::1"||xe(s)&&!!(n&&q(n,t))}function xe(t){return t==="0.0.0.0"||t==="::"}function ve(t){try{let e=new URL(t);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"}catch{return!1}}function q(t,e){try{return new URL(t).host===T(e)}catch{return!1}}function O(t){let e=T(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function T(t){return t.trim().toLowerCase()}function E(t){return Array.isArray(t)?t[0]:t}function Ie(){return ee(32).toString("base64url")}var Ee="next",Pe="127.0.0.1",je=3e3,$="/__vcp/site-edit/bridge",x="/__vcp/site-edit/client/",Ce=`${x}auto-bootstrap.js`,L='data-vcp-site-edit-bootstrap="true"',Ne=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Be="@vcp-dev/site-edit-engine/webpack-loader",_e=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,He=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Oe=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Bt(t={}){let e=v.resolve(t.projectRoot??process.cwd()),n=t.host??Pe,r=t.port??ut(process.env.PORT)??je,s=t.bridgePath??$,o=et(),c=t.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",i=await ot(e),a=Ke(e),u=i({dev:!0,dir:e,hostname:n,port:r,...qe(a)}),p=u.getRequestHandler();await u.prepare();let d=ke.createServer((z,w)=>{Ve({basePath:c,bridgePath:s,bridgeSessionKey:o,handle:p,request:z,response:w}).catch(G=>{console.error(G),w.headersSent||(w.statusCode=500),w.end("site edit preview request failed")})}),f=K(d,{siteId:t.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:t.snapshotId??process.env.VCP_SNAPSHOT_ID??ct(e),projectRoot:e,basePath:c,host:n,port:r,path:s,sessionKey:o});Ae({server:d,bridgePath:s,handleUpgrade:u.getUpgradeHandler()});let l=()=>{f.stop(),u.close().catch(()=>{}),d.close()};return process.on("SIGINT",l),process.on("SIGTERM",l),await dt(d,r,n),{bundler:a,close:l,server:d}}function Ke(t){let e=Te(t);return e&&Me(e)?"webpack":"turbopack"}function qe(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function Te(t){for(let e of Ne){let n=S(t,e);if(y(n))return m(n,"utf8")}return null}function Me(t){return t.includes(Be)?!0:_e.test(t)&&He.some(e=>e.test(t))}function Ae(t){let e=(n,r,s)=>{De(n.url,t.bridgePath)||t.handleUpgrade(n,r,s).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function De(t,e){return new URL(t??"/","http://localhost").pathname===e}function Ue(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??Je()});return`<script type="module" ${L}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ce)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function Je(){return{bridge:C("@vcp-dev/site-edit-bridge"),contracts:C("@vcp-dev/contracts"),engine:C("@vcp-dev/site-edit-engine")}}function C(t){let e=U(import.meta.url);try{let n=e.resolve(t),r=We(n,t);if(!r)return;let s=JSON.parse(m(r,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function We(t,e){let n=v.parse(t).root,r=b(t);for(;r&&r!==n;){let s=S(r,"package.json");if(y(s))try{if(JSON.parse(m(s,"utf8")).name===e)return s}catch{return}r=b(r)}}function $e(t,e){if(t.includes(L))return t;let n=Ue(e),r=/<\/body\s*>/i.exec(t);return r?`${t.slice(0,r.index)}${n}${t.slice(r.index)}`:`${t}${n}`}function _t(t,e=b(W(import.meta.url)),n=y){return F(t,e,n)?.path??null}function F(t,e=b(W(import.meta.url)),n=y){let r=new URL(t??"/","http://localhost").pathname;if(!r.startsWith(x))return null;let s=r.slice(x.length);if(!Oe.has(s))return null;let o=N(it(e),s);if(J(e)!=="src")return{path:o,requiresTranspile:!1};let c=N(e,s.replace(/\.js$/,".ts"));return n(c)?{path:c,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Le(t,e){let n=F(t.url);if(!n)return!1;if(!y(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Fe(m(n.path,"utf8")):m(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(r),!0}async function Fe(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ve({basePath:t,bridgePath:e,bridgeSessionKey:n,handle:r,request:s,response:o}){if(await Le(s,o))return;let c=ze(s),i=Ge(s),a=c||i?Xe(o,{basePath:t,bridgePath:e,bridgeSessionKey:n,patchNextDevChunk:i}):()=>{};try{await r(s,o)}catch(u){throw a(),u}}function ze(t){return Qe(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ge(t){return Ze(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Qe(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(x)||e===$)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Ze(t){if(t.method!=="GET"||!String(t.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(t.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Xe(t,e){let n=[],r=t,s=r.flushHeaders.bind(t),o=r.write.bind(t),c=r.end.bind(t);return r.flushHeaders=()=>{},r.write=(i,a,u)=>(i!==void 0&&n.push(M(i,A(a))),D(a),D(u),!0),r.end=(i,a,u)=>{let p=typeof i=="function"?void 0:i;p!==void 0&&n.push(M(p,A(a))),r.write=o,r.end=c,r.flushHeaders=s;let d=Buffer.concat(n),f=Ye(t,d,e);f!==d&&!t.headersSent&&t.removeHeader("content-length");let l=typeof i=="function"?i:typeof a=="function"?a:typeof u=="function"?u:void 0;return l?c(f,l):c(f)},()=>{r.write=o,r.end=c,r.flushHeaders=s}}function Ye(t,e,n){if(tt(t,e))return Buffer.from($e(e.toString("utf8"),n));if(n.patchNextDevChunk&&nt(t)){let r=e.toString("utf8"),s=rt(r);if(s!==r)return Buffer.from(s)}return e}function et(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function tt(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function nt(t){if(t.statusCode<200||t.statusCode>=300)return!1;let e=t.getHeader("content-type"),n=Array.isArray(e)?e.join(";"):String(e??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function rt(t){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
5
5
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
6
|
-
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,s])=>
|
|
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,s])=>st(n,r,s),t)}function st(t,e,n){if(n.length>e.length)throw new Error("Replacement must not be longer than the search string.");return t.replaceAll(e,n.padEnd(e.length," "))}function M(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function A(t){return typeof t=="string"?t:void 0}function D(t){typeof t=="function"&&t()}async function ot(t){let n=U(S(t,"package.json"))(Ee);return n.default??n}function it(t){return J(t)!=="src"?t:N(at(t),"dist")}function at(t){return V(t)?v.posix.dirname(t):b(t)}function N(t,e){return V(t)?v.posix.join(t,e):S(t,e)}function V(t){return t.includes("/")&&!t.includes("\\")}function ct(t){let e=S(t,".vcp/current-snapshot.json");if(!y(e))return"sandbox_worktree";try{let n=JSON.parse(m(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function ut(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function dt(t,e,n){return new Promise((r,s)=>{t.once("error",s),t.listen(e,n,()=>{t.off("error",s),r()})})}export{Ae as attachNextDevUpgradeHandler,Ue as createSiteEditAutoBootstrapHtmlSnippet,$e as injectSiteEditAutoBootstrap,rt as patchNextFirefoxDevChunk,Ge as prepareFirefoxNextDevChunkPatchRequest,ze as prepareSiteEditHtmlInjectionRequest,F as resolveSiteEditClientAsset,_t as resolveSiteEditClientAssetPath,Ke as resolveSiteEditNextDevBundler,Bt as startSiteEditNextDevServer,Fe as transpileSiteEditClientSource};
|
|
@@ -17,6 +17,7 @@ console.log(JSON.stringify({
|
|
|
17
17
|
projectRoot: projectRoot,
|
|
18
18
|
preview_url: `http://127.0.0.1:${port}`,
|
|
19
19
|
bridge_path: "/__vcp/site-edit/bridge",
|
|
20
|
+
bundler: preview.bundler,
|
|
20
21
|
}, null, 2));
|
|
21
22
|
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
22
23
|
process.on(signal, () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vcp-dev/site-edit-bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -74,8 +74,8 @@
|
|
|
74
74
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@vcp-dev/contracts": "0.
|
|
78
|
-
"@vcp-dev/site-edit-engine": "0.
|
|
77
|
+
"@vcp-dev/contracts": "0.4.0",
|
|
78
|
+
"@vcp-dev/site-edit-engine": "0.4.0",
|
|
79
79
|
"@types/ws": "^8.18.1",
|
|
80
80
|
"ws": "^8.20.1"
|
|
81
81
|
},
|