@vcp-dev/site-edit-bridge 0.10.70 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- import be from"node:http";import{existsSync as K,readFileSync as U}from"node:fs";import{randomUUID as sn}from"node:crypto";import{createRequire as ze}from"node:module";import{Socket as $e}from"node:net";import z from"node:path";import{basename as Je,dirname as J,join as G}from"node:path";import{fileURLToPath as Ge}from"node:url";import{createRequire as Lt}from"node:module";import{pathToFileURL as qt}from"node:url";import{Worker as zt}from"node:worker_threads";var ve=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function se(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import ft from"node:http";import q from"node:fs";import{createHash as Se,randomBytes as gt,timingSafeEqual as mt}from"node:crypto";import v from"node:path";import{WebSocket as De,WebSocketServer as yt}from"ws";import{createPreviewSiteEditEngineRuntime as St,openFileHistoryStore as It,resolveManagedPageTemplateComposition as wt,scanSiteEditCompositionsFromFiles as Et}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as xt,scanNextAppRouterRoutesFromFiles as Rt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as bt}from"@vcp-dev/site-edit-engine/source-watcher";function ke(e){let t=new Map,n=[],i=new Map,s=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(o.map((p,f)=>[p,f])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},d=e.entries.flatMap((p,f)=>p.dynamicDataSummary?[[f,p.dynamicDataSummary]]:[]),c=new Map(e.entries.map((p,f)=>[p.key,f])),l=[];for(let[p,f]of e.entries.entries()){let y=f.pageCompositionActionScope;if(!y)continue;if(y.kind!=="source-siblings"){l.push([p,{kind:y.kind}]);continue}let x=y.siblingKeys.map(w=>{let E=c.get(w);if(E===void 0)throw new Error("Render entry "+f.key+" references missing source sibling "+w);return E});l.push([p,{kind:"source-siblings",siblingEntryIndexes:x}])}let u=p=>{let f=t.get(p);if(typeof f=="number")return f;let y=n.length;return n.push(p),t.set(p,y),y},S=p=>{let f=null;for(let y of it(p)){let x=`${f??"root"}\0${y}`,w=i.get(x);if(typeof w=="number"){f=w;continue}let E=s.length;s.push([f,u(y)]),i.set(x,E),f=E}if(f===null)throw new Error("Document key must not be empty");return f};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:s,entries:e.entries.map(p=>{let f=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&f<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[S(p.key),nt(p.operationSummary),...f>=0?[f]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:S(p.parentKey))}:{},...d.length>0?{dynamicDataSummaries:d}:{}}}function nt(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function it(e){if(!e)return[];let t=[],n=0,i=_e(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=_e(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function _e(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}var Q="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",pe="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var C=class e{constructor(){}static parseMessage(t,n={}){let i=JSON.parse(t);if(!e.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(m(t)&&m(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",i=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!m(t)||typeof t.type!="string"?!1:t.type==="request"?rt(t.payload,n):t.type==="response"||t.type==="error"?m(t.payload)&&typeof t.payload.id=="string":t.type==="event"?m(t.payload)&&m(t.payload.event):t.type==="auth"?m(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?m(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&m(t.payload)&&t.payload.ok===!0}},Y=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ue,this.eventDispatcher=new de(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let i=ot(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(s){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:s instanceof Error?s.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let i=n.payload,{id:s}=i;switch(i.kind){case"initialize-session":{let o=oe(i),r=await this.resolve(o),a=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:s,kind:i.kind,result:O({...a,data:{...a.data,document:Ae(a.data.document)}},r.context)}});return}case"get-document":{let o=await this.resolveWireContext(i),r=await this.options.engine.getDocument(o);this.sendResult(s,i.kind,ht(r,o));return}case"get-history-status":{let o=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(o);this.sendResult(s,i.kind,O(r,o));return}case"get-style-context":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,O(await this.options.engine.getStyleContext(o),o));return}case"get-object-edit-context":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,O(await this.options.engine.getObjectEditContext(i.key,o,i.selectionRef),o));return}case"get-class-name-source":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,O(await this.options.engine.getClassNameSource(i.key,o),o));return}case"get-source-tree":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,O(await this.options.engine.getSourceTree(o),o));return}case"get-source-file":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,O(await this.options.engine.getSourceFile({path:i.path,composition:o}),o));return}case"resolve-source-location":{let o=await this.resolveWireContext(i),r=O(await this.options.engine.resolveSourceLocation({key:i.key,composition:o}),o);this.sendResult(s,i.kind,r);return}case"execute":case"get-operation-result":{let o=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(R(o)!==R(r))throw new k(Q,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(i.request,o);if(i.kind==="get-operation-result"){this.sendResult(s,i.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(s,i.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let o=await this.resolveWireContext(i),r=await this.resolveAndAssert(i.request.composition);if(R(o)!==R(r))throw new k(Q,"History receipt composition does not match the active session.");this.sendResult(s,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:X(r)})??null);return}case"undo":case"redo":{let o=await this.resolveWireContext(i),r=i.request;if(r){let d=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||R(o)!==R(d))throw new k(Q,"History request does not match its cursor operation.")}let a=r?{...r,composition:X(o)}:void 0;await this.handleBufferedOperation(s,i.kind,()=>i.kind==="undo"?this.options.engine.undo(o,a):this.options.engine.redo(o,a));return}}}catch(n){let i=C.extractRequestInfo(t);this.sendJson({type:"error",payload:{...i,message:ce(n),code:ae(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),i=this.session.activeComposition;if(!i)throw new k(pe,"Initialize a composition session before issuing this request.");if(R(i)!==R(n.context))throw new k(Q,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=oe(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=ut(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(R(t))}async normalizeOperationRequest(t,n){let i={...t,composition:X(n)};if(i.target.kind==="route"){let s=i.target,o=oe(s),r=await this.resolveAndAssert(o);i.target={...s,composition:X(r)}}return i}handleEngineEvent(t){let n=t?.composition;if(!dt(n))return;let i=R(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&i===pt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(t,n,i){this.sendJson({type:"response",payload:{id:t,kind:n,result:i}})}async handleRawMessage(t){try{await this.handleMessage(C.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=lt(t);this.sendJson({type:"error",payload:{...i,message:ce(n),code:ae(n)}})}}sendJson(t){this.options.socket.send(C.stringifyMessage(t))}async handleBufferedOperation(t,n,i){this.eventDispatcher.beginBuffering();try{let s=await i();this.sendResult(t,n,s)}catch(s){this.sendJson({type:"error",payload:{id:t,kind:n,message:ce(s),code:ae(s)}})}finally{this.eventDispatcher.flush()}}},st=256;function ot(e){if(e.length>st||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return m(t)&&t.type==="ping"&&m(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},de=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()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function rt(e,t){if(!m(e)||typeof e.id!="string"||!C.isRequestKind(e.kind))return!1;let n=F(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||re(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&at(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"execute":case"get-operation-result":return n&&ct(e.request)&&(e.request.mutationContext===void 0||re(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Te(e.request);case"undo":case"redo":return n&&(e.request===void 0||Te(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||re(e.mutationContext))}}function Te(e){return m(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&F(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function at(e){if(e===void 0)return!0;if(!m(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function ct(e){return m(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&F(e.composition)&&typeof e.kind=="string"&&m(e.target)&&(e.target.kind!=="route"||F(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&m(e.params)}function F(e){return m(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function dt(e){return m(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function oe(e){if(F(e.composition))return e.composition;throw new k(pe,"A composition selector is required for this request.")}function ut(e){if(m(e)&&F(e.composition))return e.composition;throw new k(pe,"A composition selector is required for execute.")}function X(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function pt(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function O(e,t){return m(e)&&e.ok===!0?{...e,composition:t}:e}function ht(e,t){return!m(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Ae(e.data)}}function Ae(e){let t=e;return ke(t.routeId?t:{...t,routeId:t.composition.routeId})}function m(e){return typeof e=="object"&&e!==null}function re(e){return m(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function ae(e){if(!(!m(e)||typeof e.code!="string"||e.code.length===0))return e.code}function ce(e){return e instanceof Error||m(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function lt(e){try{return C.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Z=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Ct,computeSiteEditCompositionKey as M}from"@vcp-dev/contracts";var vt="127.0.0.1",_t=30218,kt="/__vcp/site-edit/bridge",Be=6*1024*1024,Tt=Be*2,At=3e3,Pe=50,le=".vcp/current-snapshot.json",He="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function je(e,t,n={}){let i=new fe(Ue(t),e,!1,n);return i.start({listen:!1}),i}var fe=class{constructor(t,n=ft.createServer((o,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,s={}){this.options=t,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=s,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new Z,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{q.mkdirSync(v.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=Ie({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new bt({projectRoot:this.options.projectRoot,watch_dirs:Pt(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Pe,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=Mt(),n=Dt(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{t(n)}catch(s){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${s instanceof Error?s.message:String(s)}`)}}}createRuntime(t,n=null){let i=this.runtime;this.activeHistoryStore=t??null;let s=(this.dependencies.createRuntime??St)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version,"composition"in o?o.composition:void 0);for(let r of this.eventListeners)r(o)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=s,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=Nt(t.composition),s=this.getRuntime(),o=T(i);await s.initializeComposition(o);let a=s.getDocument(o).data;await this.recordRuntimeVersion(a.version,i);let d=(await s.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),i=T(t);await n.initializeComposition(i);let s=n.getDocument(i);return await this.recordRuntimeVersion(s.data.version,t),{...s,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,i)=>this.getRuntime().getObjectEditContext(t,T(n),i),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return Ne(i,t);let s=await this.getRuntime().executeOperation(t);return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion,s.composition),s})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}runHistoryWithReceipt(t,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==t||i.composition.routeId!==n.routeId||i.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let s=()=>this.mutationQueue.run(async()=>{let o=await this.bindHistorySession(this.options.snapshotId);if(!o.ok)return Ne(o,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return i?this.executeWithReceipt(i,s):s()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return Se("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let i=this.operationReceiptKey(t),s=this.operationFingerprint(t),o=this.operationReceipts.get(i);if(o)return o.fingerprint!==s?Promise.reject(new Error("Operation ID was reused with a different request.")):o.result;let r={fingerprint:s,result:n(),settled:!1};return this.operationReceipts.set(i,r),r.result.then(()=>{r.settled=!0;for(let[a,d]of this.operationReceipts){if(this.operationReceipts.size<=256)break;d.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let i=await(this.dependencies.openHistoryStore??It)(Ot({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let s=i.readDocumentVersion?await i.readDocumentVersion():0,o=this.versionCheckpoints.get(i);o?o.durableVersion=Math.max(o.durableVersion,s):this.versionCheckpoints.set(i,{durableVersion:s,requestedVersion:s,pending:null});let r=this.compositions[0]?.context;if(r){let a=M(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,s))}this.createRuntime(i,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let i=n?M(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,t));let s=this.activeHistoryStore;if(!s?.writeDocumentVersion)return Promise.resolve();let o=i?this.runtimeVersionFloors.get(i)??t:t,r=this.versionCheckpoints.get(s);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(s,r)),o<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,o),r.pending)return r.pending;let a=r,d=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await s.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=d,this.versionPersistence=d,d}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let i of t)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??Pe;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((s,o)=>s.localeCompare(o));this.pendingChangedFiles.clear();let n=t.some(Ve)?this.scheduleSnapshotIdentityAdvance():!1,i=t.filter(s=>!$t(s));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let s of i)this.runtime?.notifyFileChanged(s)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=q.readFileSync(v.join(this.options.projectRoot,le),"utf8"),n=JSON.parse(t),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||ge(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let s=await this.bindHistorySession(t);if(!s.ok)throw new Error(`${s.code}: ${s.message}`)}else this.createRuntime()}catch(s){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${s instanceof Error?s.message:String(s)}`);return}let i=new Date().toISOString();for(let s of this.compositions){let o={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:s.context,snapshotId:t,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(o)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(s){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${s instanceof Error?s.message:String(s)}`)}}refreshCompositions(t=!1){try{let n=Ht(this.options.projectRoot),i=Rt(n),s=i.length>0?i:(this.options.runtime.routes??[]).map(c=>({...c})),o=Et({files:n});if(o.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(o.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[M(c.context),c])),d=new Map(o.map(c=>[M(c.context),c]));if(this.runtime){for(let[c,l]of a){let u=d.get(c);(!u||u.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(T(l.context))}for(let[c,l]of d){let u=a.get(c);(!u||u.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=s,this.compositions=o,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,t)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=xt(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=wt({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),o=M(s.context);if(!this.compositions.some(r=>M(r.context)===o))throw new Error(`Composition is not registered by the preview bridge: ${o}`);return s}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(M(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Fe(e){return Ue(e)}function Ue(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:v.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??vt,port:e.port??_t,path:e.path??kt,sessionKey:e.sessionKey??Vt(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Pt(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function Ht(e){let t=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),s=o=>{if(!q.existsSync(o))return;let r;try{r=q.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(i.has(a.name))continue;s(v.join(o,a.name));continue}if(!a.isFile())continue;let d=v.join(o,a.name),c="";try{c=q.readFileSync(d,"utf8")}catch{}t.push({path:v.relative(e,d).replaceAll(v.sep,"/"),content:c})}};for(let o of n)s(v.join(e,o));return t.sort((o,r)=>o.path.localeCompare(r.path))}function Nt(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Ot(e){return v.join(v.resolve(e.root),ge(e.siteId),ge(e.snapshotId),Se("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function ge(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Se("sha256").update(e).digest("hex").slice(0,32)}function Mt(){let e=globalThis;return e[He]??=new Map,e[He]}function Dt(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Ne(e,t,n){let i=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:i,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function Ie(e){let t=new yt({maxPayload:Be,noServer:!0}),n=new WeakSet,i=o=>{new Y({socket:new me(o),engine:e.engine,validateOperationRequest:r=>Ct.safeParse(r).success})},s=(o,r,a)=>{if(!Bt(o,e))return;let d=jt(o,e);if(!d){r.write(`HTTP/1.1 401 Unauthorized\r
1
+ import ve from"node:http";import{existsSync as V,readFileSync as F}from"node:fs";import{randomUUID as In}from"node:crypto";import{createRequire as Ze}from"node:module";import{Socket as Qe}from"node:net";import Q from"node:path";import{basename as et,dirname as X,join as Y}from"node:path";import{fileURLToPath as tt}from"node:url";import{createRequire as an}from"node:module";import{pathToFileURL as cn}from"node:url";import{Worker as dn}from"node:worker_threads";var Pe=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function ce(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import Tt from"node:http";import G from"node:fs";import{createHash as be,randomBytes as Pt,timingSafeEqual as At}from"node:crypto";import k from"node:path";import{WebSocket as $e,WebSocketServer as Ht}from"ws";import{createPreviewSiteEditEngineRuntime as Nt,openFileHistoryStore as Ot,resolveManagedPageTemplateComposition as Bt,scanSiteEditCompositionsFromFiles as Mt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Dt,scanNextAppRouterRoutesFromFiles as jt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Kt}from"@vcp-dev/site-edit-engine/source-watcher";function Oe(e){if(e.pageBlocks!==void 0&&!dt(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],i=new Map,o=[],s=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(s.map((p,f)=>[p,f])),c=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},d=e.entries.flatMap((p,f)=>p.dynamicDataSummary?[[f,p.dynamicDataSummary]]:[]),a=new Map(e.entries.map((p,f)=>[p.key,f])),l=[];for(let[p,f]of e.entries.entries()){let y=f.pageCompositionActionScope;if(!y)continue;if(y.kind!=="source-siblings"){l.push([p,{kind:y.kind}]);continue}let b=y.siblingKeys.map(w=>{let E=a.get(w);if(E===void 0)throw new Error("Render entry "+f.key+" references missing source sibling "+w);return E});l.push([p,{kind:"source-siblings",siblingEntryIndexes:b}])}let u=p=>{let f=t.get(p);if(typeof f=="number")return f;let y=n.length;return n.push(p),t.set(p,y),y},S=p=>{let f=null;for(let y of St(p)){let b=`${f??"root"}\0${y}`,w=i.get(b);if(typeof w=="number"){f=w;continue}let E=o.length;o.push([f,u(y)]),i.set(b,E),f=E}if(f===null)throw new Error("Document key must not be empty");return f};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:c,tokens:n,nodes:o,entries:e.entries.map(p=>{let f=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&f<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[S(p.key),ct(p.operationSummary),...f>=0?[f]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:S(p.parentKey))}:{},...d.length>0?{dynamicDataSummaries:d}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function ct(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ae(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function dt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!B(n)||!U(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!Z(n.blockKey,256)||!Z(n.definitionKey,512)||!ut(n.rootRef)||!pt(n.source)||!ht(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>Z(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!lt(n.capabilities)||n.unavailableReasons!==void 0&&!ft(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let i=n.owner;for(let o of n.siblingBlockKeys){let s=t.get(o);if(!s)return!1;let r=s.owner;if(i.kind!==r.kind||i.key!==r.key)return!1}}return!0}function ut(e){return!B(e)||!U(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!Ae(e.instanceIndex)||e.instanceCount!==void 0&&(!Ae(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function pt(e){return B(e)&&U(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&gt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function ht(e){return B(e)&&U(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&Z(e.key,512)}function lt(e){return B(e)&&U(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function ft(e){return B(e)&&Object.entries(e).every(([t,n])=>W(t)&&B(n)&&U(n,["code","reason"])&&W(n.code)&&W(n.reason))}function gt(e){let t=mt(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(s=>!s||s==="."||s===".."||s.startsWith(".")||s==="node_modules"||s.toLowerCase()==="package.json"||s==="recipes"||s.startsWith(".env")))return!1;let i=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(s=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(s.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(s=>e===s||e.startsWith(`${s}/`))||t}function mt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),i=n.some(r=>He(r)),o=i?n[0]:n.pop(),s=i?n.slice(1):n;if(i&&s.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!yt(`/${s.join("/")}`)||s.some(r=>r.includes("[")||r.includes("]")?!He(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),c=atob(r),d=Uint8Array.from(c,l=>l.charCodeAt(0)),a=new TextDecoder("utf-8",{fatal:!0}).decode(d);return a.length>0&&a.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(a)&&!a.startsWith(" ")&&!a.endsWith(" ")&&new TextEncoder().encode(a).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(a))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function He(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function yt(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function Z(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function U(e,t){let n=new Set(t);return Object.keys(e).every(i=>n.has(i))}function St(e){if(!e)return[];let t=[],n=0,i=Ne(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=Ne(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function Ne(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}var ee="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ge="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var C=class e{constructor(){}static parseMessage(t,n={}){let i=JSON.parse(t);if(!e.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(m(t)&&m(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",i=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!m(t)||typeof t.type!="string"?!1:t.type==="request"?Et(t.payload,n):t.type==="response"||t.type==="error"?m(t.payload)&&typeof t.payload.id=="string":t.type==="event"?m(t.payload)&&m(t.payload.event):t.type==="auth"?m(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?m(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&m(t.payload)&&t.payload.ok===!0}},ne=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new fe,this.eventDispatcher=new le(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let i=wt(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let i=n.payload,{id:o}=i;switch(i.kind){case"initialize-session":{let s=de(i),r=await this.resolve(s),c=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:i.kind,result:O({...c,data:{...c.data,document:Me(c.data.document)}},r.context)}});return}case"get-document":{let s=await this.resolveWireContext(i),r=await this.options.engine.getDocument(s);this.sendResult(o,i.kind,_t(r,s));return}case"get-history-status":{let s=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(s);this.sendResult(o,i.kind,O(r,s));return}case"get-style-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,O(await this.options.engine.getStyleContext(s),s));return}case"get-object-edit-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,O(await this.options.engine.getObjectEditContext(i.key,s,i.selectionRef),s));return}case"get-class-name-source":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,O(await this.options.engine.getClassNameSource(i.key,s),s));return}case"get-source-tree":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,O(await this.options.engine.getSourceTree(s),s));return}case"get-source-file":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,O(await this.options.engine.getSourceFile({path:i.path,composition:s}),s));return}case"resolve-source-location":{let s=await this.resolveWireContext(i),r=O(await this.options.engine.resolveSourceLocation({key:i.key,composition:s}),s);this.sendResult(o,i.kind,r);return}case"execute":case"get-operation-result":{let s=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(x(s)!==x(r))throw new v(ee,"The execute request composition does not match its operation composition.");let c=await this.normalizeOperationRequest(i.request,s);if(i.kind==="get-operation-result"){this.sendResult(o,i.kind,await this.options.engine.getOperationResult?.(c)??null);return}await this.handleBufferedOperation(o,i.kind,()=>this.options.engine.execute(c));return}case"get-history-operation-result":{let s=await this.resolveWireContext(i),r=await this.resolveAndAssert(i.request.composition);if(x(s)!==x(r))throw new v(ee,"History receipt composition does not match the active session.");this.sendResult(o,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:te(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(i),r=i.request;if(r){let d=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||x(s)!==x(d))throw new v(ee,"History request does not match its cursor operation.")}let c=r?{...r,composition:te(s)}:void 0;await this.handleBufferedOperation(o,i.kind,()=>i.kind==="undo"?this.options.engine.undo(s,c):this.options.engine.redo(s,c));return}}}catch(n){let i=C.extractRequestInfo(t);this.sendJson({type:"error",payload:{...i,message:he(n),code:pe(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),i=this.session.activeComposition;if(!i)throw new v(ge,"Initialize a composition session before issuing this request.");if(x(i)!==x(n.context))throw new v(ee,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=de(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=Ct(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(x(t))}async normalizeOperationRequest(t,n){let i={...t,composition:te(n)};if(i.target.kind==="route"){let o=i.target,s=de(o),r=await this.resolveAndAssert(s);i.target={...o,composition:te(r)}}return i}handleEngineEvent(t){let n=t?.composition;if(!Rt(n))return;let i=x(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&i===kt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(t,n,i){this.sendJson({type:"response",payload:{id:t,kind:n,result:i}})}async handleRawMessage(t){try{await this.handleMessage(C.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=vt(t);this.sendJson({type:"error",payload:{...i,message:he(n),code:pe(n)}})}}sendJson(t){this.options.socket.send(C.stringifyMessage(t))}async handleBufferedOperation(t,n,i){this.eventDispatcher.beginBuffering();try{let o=await i();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:he(o),code:pe(o)}})}finally{this.eventDispatcher.flush()}}},It=256;function wt(e){if(e.length>It||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return m(t)&&t.type==="ping"&&m(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var v=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},le=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))}},fe=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()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function Et(e,t){if(!m(e)||typeof e.id!="string"||!C.isRequestKind(e.kind))return!1;let n=$(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||ue(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&bt(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"execute":case"get-operation-result":return n&&xt(e.request)&&(e.request.mutationContext===void 0||ue(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Be(e.request);case"undo":case"redo":return n&&(e.request===void 0||Be(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||ue(e.mutationContext))}}function Be(e){return m(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&$(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function bt(e){if(e===void 0)return!0;if(!m(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function xt(e){return m(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&$(e.composition)&&typeof e.kind=="string"&&m(e.target)&&(e.target.kind!=="route"||$(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&m(e.params)}function $(e){return m(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Rt(e){return m(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function de(e){if($(e.composition))return e.composition;throw new v(ge,"A composition selector is required for this request.")}function Ct(e){if(m(e)&&$(e.composition))return e.composition;throw new v(ge,"A composition selector is required for execute.")}function te(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function kt(e){return e.activeComposition?x(e.activeComposition):null}function x(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function O(e,t){return m(e)&&e.ok===!0?{...e,composition:t}:e}function _t(e,t){return!m(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Me(e.data)}}function Me(e){let t=e;return Oe(t.routeId?t:{...t,routeId:t.composition.routeId})}function m(e){return typeof e=="object"&&e!==null}function ue(e){return m(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function pe(e){if(!(!m(e)||typeof e.code!="string"||e.code.length===0))return e.code}function he(e){return e instanceof Error||m(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function vt(e){try{return C.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var ie=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Wt,computeSiteEditCompositionKey as M}from"@vcp-dev/contracts";var Ut="127.0.0.1",$t=30218,Ft="/__vcp/site-edit/bridge",Fe=6*1024*1024,Vt=Fe*2,Lt=3e3,De=50,ye=".vcp/current-snapshot.json",je="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ve(e,t,n={}){let i=new Se(qe(t),e,!1,n);return i.start({listen:!1}),i}var Se=class{constructor(t,n=Tt.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ie,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{G.mkdirSync(k.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=xe({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new Kt({projectRoot:this.options.projectRoot,watch_dirs:qt(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??De,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=Qt(),n=Xt(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let i=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??Nt)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:s=>{"version"in s&&typeof s.version=="number"&&this.recordRuntimeVersion(s.version,"composition"in s?s.composition:void 0);for(let r of this.eventListeners)r(s)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=Jt(t.composition),o=this.getRuntime(),s=T(i);await o.initializeComposition(s);let c=o.getDocument(s).data;await this.recordRuntimeVersion(c.version,i);let d=(await o.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:c,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),i=T(t);await n.initializeComposition(i);let o=n.getDocument(i);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,i)=>this.getRuntime().getObjectEditContext(t,T(n),i),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return Ke(i,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}runHistoryWithReceipt(t,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==t||i.composition.routeId!==n.routeId||i.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return Ke(s,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return i?this.executeWithReceipt(i,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return be("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let i=this.operationReceiptKey(t),o=this.operationFingerprint(t),s=this.operationReceipts.get(i);if(s)return s.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):s.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(i,r),r.result.then(()=>{r.settled=!0;for(let[c,d]of this.operationReceipts){if(this.operationReceipts.size<=256)break;d.settled&&this.operationReceipts.delete(c)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let i=await(this.dependencies.openHistoryStore??Ot)(Gt({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=i.readDocumentVersion?await i.readDocumentVersion():0,s=this.versionCheckpoints.get(i);s?s.durableVersion=Math.max(s.durableVersion,o):this.versionCheckpoints.set(i,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let c=M(r);this.runtimeVersionFloors.set(c,Math.max(this.runtimeVersionFloors.get(c)??0,o))}this.createRuntime(i,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let i=n?M(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=i?this.runtimeVersionFloors.get(i)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),s<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,s),r.pending)return r.pending;let c=r,d=this.versionPersistence.then(async()=>{try{for(;c.requestedVersion>c.durableVersion;){let a=c.requestedVersion;await o.writeDocumentVersion(a),c.durableVersion=Math.max(c.durableVersion,a)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{c.pending=null}});return c.pending=d,this.versionPersistence=d,d}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let i of t)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??De;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let n=t.some(Ge)?this.scheduleSnapshotIdentityAdvance():!1,i=t.filter(o=>!rn(o));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let o of i)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=G.readFileSync(k.join(this.options.projectRoot,ye),"utf8"),n=JSON.parse(t),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||Ie(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let i=new Date().toISOString();for(let o of this.compositions){let s={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(s)}catch(c){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${c instanceof Error?c.message:String(c)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=zt(this.options.projectRoot),i=jt(n),o=i.length>0?i:(this.options.runtime.routes??[]).map(a=>({...a})),s=Mt({files:n});if(s.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(s.filter(a=>a.context.effectiveTemplateId!==void 0).map(a=>a.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let c=new Map(this.compositions.map(a=>[M(a.context),a])),d=new Map(s.map(a=>[M(a.context),a]));if(this.runtime){for(let[a,l]of c){let u=d.get(a);(!u||u.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(T(l.context))}for(let[a,l]of d){let u=c.get(a);(!u||u.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=o,this.compositions=s,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,t)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Dt(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Bt({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),s=M(o.context);if(!this.compositions.some(r=>M(r.context)===s))throw new Error(`Composition is not registered by the preview bridge: ${s}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(M(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Le(e){return qe(e)}function qe(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:k.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Ut,port:e.port??$t,path:e.path??Ft,sessionKey:e.sessionKey??on(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function qt(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function zt(e){let t=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!G.existsSync(s))return;let r;try{r=G.readdirSync(s,{withFileTypes:!0})}catch{return}for(let c of r){if(c.name.startsWith(".")&&c.name!==".vcp")continue;if(c.isDirectory()){if(i.has(c.name))continue;o(k.join(s,c.name));continue}if(!c.isFile())continue;let d=k.join(s,c.name),a="";try{a=G.readFileSync(d,"utf8")}catch{}t.push({path:k.relative(e,d).replaceAll(k.sep,"/"),content:a})}};for(let s of n)o(k.join(e,s));return t.sort((s,r)=>s.path.localeCompare(r.path))}function Jt(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Gt(e){return k.join(k.resolve(e.root),Ie(e.siteId),Ie(e.snapshotId),be("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Ie(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:be("sha256").update(e).digest("hex").slice(0,32)}function Qt(){let e=globalThis;return e[je]??=new Map,e[je]}function Xt(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Ke(e,t,n){let i=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:i,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function xe(e){let t=new Ht({maxPayload:Fe,noServer:!0}),n=new WeakSet,i=s=>{new ne({socket:new we(s),engine:e.engine,validateOperationRequest:r=>Wt.safeParse(r).success})},o=(s,r,c)=>{if(!Yt(s,e))return;let d=Zt(s,e);if(!d){r.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),r.destroy();return}d.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,r,a,c=>{t.emit("connection",c,o)})};return e.server.on("upgrade",s),t.on("connection",(o,r)=>{if(n.has(r)){i(o);return}Ft(o,e.sessionKey,()=>{i(o)})}),t.stop=()=>{e.server.off("upgrade",s);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var me=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===De.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Tt){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Bt(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function jt(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=he(e.headers["x-vcp-site-edit-key"]),s=Ke(i,t.sessionKey),o=he(e.headers.host),r=he(e.headers.origin);return o&&!Ut(o,t.host,r)?null:r?Wt(r,o,t.allowedOrigins)?{authenticatedByHeader:s}:null:s?{authenticatedByHeader:!0}:null}function Ft(e,t,n){let i=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},At),s,o=()=>{clearTimeout(i),e.off("message",s),e.off("close",o)},r=()=>{o(),e.close(1008,"bridge authentication failed")};s=a=>{try{let d=C.parseMessage(a.toString());if(d.type!=="auth"||!Ke(d.payload.key,t)){r();return}o(),e.readyState===De.OPEN&&e.send(C.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",s),e.on("close",o)}function Ke(e,t){if(!e)return!1;let n=Buffer.from(e),i=Buffer.from(t);return n.length===i.length&&mt(n,i)}function Ut(e,t,n){let i=Me(e),s=Me(t);return i===s||Oe(s)&&Oe(i)&&(!n||ye(n,e))||Kt(s)&&(!n||ye(n,e))}function Kt(e){return e==="0.0.0.0"||e==="::"}function Oe(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Wt(e,t,n){return n.includes(e)||(t?ye(e,t):!1)}function ye(e,t){try{return new URL(e).host===We(t)}catch{return!1}}function Me(e){let t=We(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function We(e){return e.trim().toLowerCase()}function he(e){return Array.isArray(e)?e[0]:e}function Vt(){return gt(32).toString("base64url")}function Ve(e){let t=e.replaceAll("\\","/");return t===le||t.endsWith(`/${le}`)}function $t(e){let t=e.replaceAll("\\","/");return Ve(e)||t===".vcp/workspace-state.json"||t.startsWith(".vcp/snapshot-store/")}var Jt="SITE_EDIT_ENGINE_UNAVAILABLE",Gt=5e3,Qt=1024,Xt="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",Yt=3,Zt=10*6e4,en=1012;function we(e,t,n={}){let i=Fe(t),{onSnapshotIdChanged:s,onHealthChanged:o,...r}=i,a={options:r},d=n.maxHeapMb??nn(process.env[Xt])??Qt,c=n.maxRestarts??Yt,l=n.restartWindowMs??Zt,u="starting",S,p=0,f=[],y=null,x=0,w=new Map,E=new Set,W,D,V=new Promise((h,g)=>{W=h,D=g});V.catch(()=>{});let b=h=>{let g=new Error(`VCP site edit preview bridge runtime is not ready: ${h}`);return g.code=Jt,g},$=h=>{for(let g of w.values())g.reject(h);w.clear()},A=h=>{switch(h.type){case"ready":y=h.health,u==="starting"?(u="ready",W()):u==="restarting"&&(u="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":u==="starting"&&P(se(h.error));return;case"result":{let g=w.get(h.id);if(!g)return;w.delete(h.id),h.ok?g.resolve(h.value):g.reject(se(h.error));return}case"event":for(let g of E)try{g(h.event)}catch(I){console.warn(`[vcp-site-edit] engine event listener failed: ${I instanceof Error?I.message:String(I)}`)}return;case"health":y=h.health;return;case"snapshot-id-changed":a.options.snapshotId=h.next;try{s?.(h.next,h.previous)}catch(g){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${g instanceof Error?g.message:String(g)}`)}return}},B=()=>{let h=p+=1,g=n.workerUrl??new URL("./engine-worker.js",import.meta.url),I=new zt(tn(g),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:d},...n.execArgv?{execArgv:n.execArgv}:{}});I.unref();let N=()=>h===p;I.on("message",_=>{N()&&A(_)}),I.on("error",_=>{N()&&P(_ instanceof Error?_:new Error(String(_)))}),I.on("exit",_=>{N()&&P(new Error(`engine worker exited with code ${_}`))}),S=I,n.onWorker?.(I)},P=h=>{if(u==="stopped"||u==="failed")return;if($(b(h.message)),y=null,u==="starting"){u="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${h.message}`),D(h);return}let g=Date.now();for(;f.length>0&&g-f[0]>l;)f.shift();if(f.length>=c){u="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${c} restarts: ${h.message}`);return}f.push(g),u="restarting";for(let I of H.clients)I.close(en,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${f.length}/${c}): ${h.message}`),B()},L=(h,g)=>{if(u==="failed"||u==="stopped"||u==="restarting")return Promise.reject(b(u));let I=x+=1;return new Promise((N,_)=>{w.set(I,{resolve:N,reject:_});let tt={type:"call",id:I,method:h,args:g};S.postMessage(tt)})},j=Object.fromEntries(ve.map(h=>[h,(...g)=>L(h,g)])),H=Ie({server:e,path:i.path,sessionKey:i.sessionKey,host:i.host,allowedOrigins:i.allowedOrigins,engine:{...j,subscribe(h){return E.add(h),()=>E.delete(h)}}});return B(),{getHealth(){return u==="ready"&&y?y:{ok:!1,bridgePath:i.path,runtimeReady:!1,routesIndexed:y?.routesIndexed??0,sessionRequired:!!i.sessionKey}},stop(){if(u==="stopped")return;let h=u==="starting";u="stopped",H.stop(),h&&D(b("bridge stopped")),$(b("bridge stopped")),E.clear();let g=S,I={type:"stop"};g.postMessage(I);let N=setTimeout(()=>{g.terminate()},Gt);N.unref(),g.once("exit",()=>clearTimeout(N))},whenReady(){return V},eventListeners:E}}function tn(e){if(!e.pathname.endsWith(".ts"))return e;let t=qt(Lt(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
5
- `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function nn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var on="next",rn="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Qe="127.0.0.1",an=3e3,ne="/__vcp/site-edit/bridge",Xe="/__vcp/site-edit/health",cn="probe",dn="render",Le="/_error",ie="/__vcp/site-edit/client/",un=`${ie}auto-bootstrap.js`,Ye='data-vcp-site-edit-bootstrap="true"',pn=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],hn="@vcp-dev/site-edit-engine/webpack-loader",ln=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,fn=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],gn=new Set(["auto-bootstrap.js","client.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Oi(e={},t={}){let n=t.process??process,i=t.createServer??be.createServer,s=t.attachBridgeServer??(n.env[rn]==="1"?je:we),o=t.loadNext??qn,r=z.resolve(e.projectRoot??process.cwd()),a=e.host??Qe,d=e.port??Qn(n.env.PORT)??an,c=e.bridgePath??ne,l=xn(c),u=Kn(),S=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",p=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,f=await o(r),y=mn(r),x=f({dev:!0,dir:r,hostname:a,port:d,...yn(y)}),w=x.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",W=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Gn(r),D=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,V=D?.trim()?z.resolve(D):void 0,b=null,$={launchId:sn(),pid:process.pid,snapshotId:W},A=i((H,h)=>{Tn({basePath:S,bridgePath:c,bridgeHealthPath:l,bridgeSessionKey:u,getBridgeHealth:()=>b?.getHealth()??Mn(c),launch:$,runRenderProbe:()=>Hn(x),handle:w,request:H,response:h}).catch(g=>{console.error(g),h.headersSent||(h.statusCode=500),h.end("site edit preview request failed")})}),B=null,P=null,L=()=>P||(te(()=>n.off("SIGINT",j)),te(()=>n.off("SIGTERM",j)),te(()=>B?.()),B=null,te(()=>b?.stop()),b=null,P=Promise.allSettled([Yn(A),Zn(()=>x.close())]).then(()=>{}),P),j=()=>{L()};try{return await x.prepare(),b=s(A,{...p?{tenantId:p}:{},siteId:E,snapshotId:W,projectRoot:r,basePath:S,host:a,port:d,path:c,sessionKey:u,...V?{historyRoot:V}:{},onSnapshotIdChanged:H=>{$.snapshotId=H}}),B=wn({server:A,bridgePath:c,handleUpgrade:x.getUpgradeHandler()}),n.on("SIGINT",j),n.on("SIGTERM",j),await b.whenReady?.(),await Xn(A,d,a),{bundler:y,close:L,host:a,port:ei(A,d),server:A}}catch(H){throw await L(),H}}function mn(e){let t=Sn(e);return t&&In(t)?"webpack":"turbopack"}function yn(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Sn(e){for(let t of pn){let n=G(e,t);if(K(n))return U(n,"utf8")}return null}function In(e){return e.includes(hn)?!0:ln.test(e)&&fn.some(t=>t.test(e))}function wn(e){let t=(n,i,s)=>{En(n.url,e.bridgePath)||e.handleUpgrade(n,i,s).catch(o=>{console.error(o),i.destroyed||i.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function En(e,t){return new URL(e??"/","http://localhost").pathname===t}function xn(e=ne){if(e===ne)return Xe;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Rn(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??bn()});return`<script type="module" ${Ye}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(un)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function bn(){return{bridge:Ee("@vcp-dev/site-edit-bridge"),contracts:Ee("@vcp-dev/contracts"),engine:Ee("@vcp-dev/site-edit-engine")}}function Ee(e){let t=ze(import.meta.url);try{let n=t.resolve(e),i=Cn(n,e);if(!i)return;let s=JSON.parse(U(i,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function Cn(e,t){let n=z.parse(e).root,i=J(e);for(;i&&i!==n;){let s=G(i,"package.json");if(K(s))try{if(JSON.parse(U(s,"utf8")).name===t)return s}catch{return}i=J(i)}}function vn(e,t){if(e.includes(Ye))return e;let n=Rn(t),i=/<\/body\s*>/i.exec(e);return i?`${e.slice(0,i.index)}${n}${e.slice(i.index)}`:`${e}${n}`}function Mi(e,t=J(Ge(import.meta.url)),n=K){return Ze(e,t,n)?.path??null}function Ze(e,t=J(Ge(import.meta.url)),n=K){let i=new URL(e??"/","http://localhost").pathname;if(!i.startsWith(ie))return null;let s=i.slice(ie.length);if(!gn.has(s))return null;let o=Ce(zn(t),s);if(Je(t)!=="src")return{path:o,requiresTranspile:!1};let r=Ce(t,s.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function _n(e,t){let n=Ze(e.url);if(!n)return!1;if(!K(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let i=n.requiresTranspile?await kn(U(n.path,"utf8")):U(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(i),!0}async function kn(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Tn({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:i,getBridgeHealth:s,launch:o,runRenderProbe:r,handle:a,request:d,response:c}){if(An(d.url,e)){c.statusCode=404,c.end();return}if(await On(d,c,n,s,o,r)||await _n(d,c))return;let l=Dn(d),u=Bn(d),S=l||u?Un(c,{basePath:e,bridgePath:t,bridgeSessionKey:i,patchNextDevChunk:u,launch:{...o}}):()=>{};try{await a(d,c)}catch(p){throw S(),p}}function An(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let i;try{i=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let s=new URL(i,"http://namespace.invalid").pathname,o=t.replace(/\/+$/,"");return(o&&(s===o||s.startsWith(o+"/"))?s.slice(o.length)||"/":s).startsWith("/.vcp")}function Pn(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function Hn(e){let t=new be.IncomingMessage(new $e);t.method="GET",t.url=Le,t.headers={host:Qe};let n=new be.ServerResponse(t);n.assignSocket(new $e);try{return await e.renderToHTML(t,n,Le,{}),{verdict:"ok"}}catch(i){return Pn(i)}finally{try{let i=n.socket;i&&(n.detachSocket(i),i.destroy())}catch{}}}function Nn(e){return new URL(e??"/","http://localhost").searchParams.get(cn)===dn}async function On(e,t,n,i,s,o){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=i(),d=Nn(e.url)?await o():void 0,c={...a,launch:s,...d?{render:d}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function Mn(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Dn(e){return jn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Bn(e){return Fn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function jn(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(ie)||n===ne||n===Xe)return!1;let i=e.headers.accept??"";return i===""||i.includes("text/html")}function Fn(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 Un(e,t){let n=[],i=e,s=i.flushHeaders.bind(e),o=i.write.bind(e),r=i.end.bind(e),a=!1;i.flushHeaders=()=>{};let d=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let l=qe(e,c,t);return l!==c&&!e.headersSent&&e.removeHeader("content-length"),o(l),n.length=0,a=!0,!0};return i.write=(c,l,u)=>a?(c!==void 0&&o(xe(c,Re(l))),ee(l),ee(u),!0):(c!==void 0&&(n.push(xe(c,Re(l))),d()),ee(l),ee(u),!0),i.end=(c,l,u)=>{let S=typeof c=="function"?void 0:c;if(a)return i.write=o,i.end=r,i.flushHeaders=s,S===void 0?typeof c=="function"?r(c):typeof l=="function"?r(l):typeof u=="function"?r(u):r():typeof l=="function"?r(S,l):typeof u=="function"?r(S,l,u):r(S,l);S!==void 0&&n.push(xe(S,Re(l))),i.write=o,i.end=r,i.flushHeaders=s;let p=Buffer.concat(n),f=qe(e,p,t);f!==p&&!e.headersSent&&e.removeHeader("content-length");let y=typeof c=="function"?c:typeof l=="function"?l:typeof u=="function"?u:void 0;return y?r(f,y):r(f)},()=>{i.write=o,i.end=r,i.flushHeaders=s}}function qe(e,t,n){if(Wn(e,t))return Buffer.from(vn(t.toString("utf8"),n));if(n.patchNextDevChunk&&Vn(e)){let i=t.toString("utf8"),s=$n(i);if(s!==i)return Buffer.from(s)}return t}function Kn(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Wn(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),i=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(i===""||i.includes("text/html"))}function Vn(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 $n(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
4
+ `),r.destroy();return}d.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,r,c,a=>{t.emit("connection",a,s)})};return e.server.on("upgrade",o),t.on("connection",(s,r)=>{if(n.has(r)){i(s);return}en(s,e.sessionKey,()=>{i(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var we=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===$e.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Vt){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Yt(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Zt(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=me(e.headers["x-vcp-site-edit-key"]),o=ze(i,t.sessionKey),s=me(e.headers.host),r=me(e.headers.origin);return s&&!tn(s,t.host,r)?null:r?sn(r,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function en(e,t,n){let i=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Lt),o,s=()=>{clearTimeout(i),e.off("message",o),e.off("close",s)},r=()=>{s(),e.close(1008,"bridge authentication failed")};o=c=>{try{let d=C.parseMessage(c.toString());if(d.type!=="auth"||!ze(d.payload.key,t)){r();return}s(),e.readyState===$e.OPEN&&e.send(C.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",s)}function ze(e,t){if(!e)return!1;let n=Buffer.from(e),i=Buffer.from(t);return n.length===i.length&&At(n,i)}function tn(e,t,n){let i=Ue(e),o=Ue(t);return i===o||We(o)&&We(i)&&(!n||Ee(n,e))||nn(o)&&(!n||Ee(n,e))}function nn(e){return e==="0.0.0.0"||e==="::"}function We(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function sn(e,t,n){return n.includes(e)||(t?Ee(e,t):!1)}function Ee(e,t){try{return new URL(e).host===Je(t)}catch{return!1}}function Ue(e){let t=Je(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Je(e){return e.trim().toLowerCase()}function me(e){return Array.isArray(e)?e[0]:e}function on(){return Pt(32).toString("base64url")}function Ge(e){let t=e.replaceAll("\\","/");return t===ye||t.endsWith(`/${ye}`)}function rn(e){let t=e.replaceAll("\\","/");return Ge(e)||t===".vcp/workspace-state.json"||t.startsWith(".vcp/snapshot-store/")}var un="SITE_EDIT_ENGINE_UNAVAILABLE",pn=5e3,hn=1024,ln="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",fn=3,gn=10*6e4,mn=1012;function Re(e,t,n={}){let i=Le(t),{onSnapshotIdChanged:o,onHealthChanged:s,...r}=i,c={options:r},d=n.maxHeapMb??Sn(process.env[ln])??hn,a=n.maxRestarts??fn,l=n.restartWindowMs??gn,u="starting",S,p=0,f=[],y=null,b=0,w=new Map,E=new Set,L,D,q=new Promise((h,g)=>{L=h,D=g});q.catch(()=>{});let R=h=>{let g=new Error(`VCP site edit preview bridge runtime is not ready: ${h}`);return g.code=un,g},z=h=>{for(let g of w.values())g.reject(h);w.clear()},P=h=>{switch(h.type){case"ready":y=h.health,u==="starting"?(u="ready",L()):u==="restarting"&&(u="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":u==="starting"&&A(ce(h.error));return;case"result":{let g=w.get(h.id);if(!g)return;w.delete(h.id),h.ok?g.resolve(h.value):g.reject(ce(h.error));return}case"event":for(let g of E)try{g(h.event)}catch(I){console.warn(`[vcp-site-edit] engine event listener failed: ${I instanceof Error?I.message:String(I)}`)}return;case"health":y=h.health;return;case"snapshot-id-changed":c.options.snapshotId=h.next;try{o?.(h.next,h.previous)}catch(g){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${g instanceof Error?g.message:String(g)}`)}return}},j=()=>{let h=p+=1,g=n.workerUrl??new URL("./engine-worker.js",import.meta.url),I=new dn(yn(g),{workerData:c,resourceLimits:{maxOldGenerationSizeMb:d},...n.execArgv?{execArgv:n.execArgv}:{}});I.unref();let N=()=>h===p;I.on("message",_=>{N()&&P(_)}),I.on("error",_=>{N()&&A(_ instanceof Error?_:new Error(String(_)))}),I.on("exit",_=>{N()&&A(new Error(`engine worker exited with code ${_}`))}),S=I,n.onWorker?.(I)},A=h=>{if(u==="stopped"||u==="failed")return;if(z(R(h.message)),y=null,u==="starting"){u="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${h.message}`),D(h);return}let g=Date.now();for(;f.length>0&&g-f[0]>l;)f.shift();if(f.length>=a){u="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${a} restarts: ${h.message}`);return}f.push(g),u="restarting";for(let I of H.clients)I.close(mn,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${f.length}/${a}): ${h.message}`),j()},J=(h,g)=>{if(u==="failed"||u==="stopped"||u==="restarting")return Promise.reject(R(u));let I=b+=1;return new Promise((N,_)=>{w.set(I,{resolve:N,reject:_});let at={type:"call",id:I,method:h,args:g};S.postMessage(at)})},K=Object.fromEntries(Pe.map(h=>[h,(...g)=>J(h,g)])),H=xe({server:e,path:i.path,sessionKey:i.sessionKey,host:i.host,allowedOrigins:i.allowedOrigins,engine:{...K,subscribe(h){return E.add(h),()=>E.delete(h)}}});return j(),{getHealth(){return u==="ready"&&y?y:{ok:!1,bridgePath:i.path,runtimeReady:!1,routesIndexed:y?.routesIndexed??0,sessionRequired:!!i.sessionKey}},stop(){if(u==="stopped")return;let h=u==="starting";u="stopped",H.stop(),h&&D(R("bridge stopped")),z(R("bridge stopped")),E.clear();let g=S,I={type:"stop"};g.postMessage(I);let N=setTimeout(()=>{g.terminate()},pn);N.unref(),g.once("exit",()=>clearTimeout(N))},whenReady(){return q},eventListeners:E}}function yn(e){if(!e.pathname.endsWith(".ts"))return e;let t=cn(an(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
5
+ `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function Sn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var wn="next",En="VCP_SITE_EDIT_ENGINE_IN_PROCESS",nt="127.0.0.1",bn=3e3,re="/__vcp/site-edit/bridge",it="/__vcp/site-edit/health",xn="probe",Rn="render",Xe="/_error",ae="/__vcp/site-edit/client/",Cn=`${ae}auto-bootstrap.js`,st='data-vcp-site-edit-bootstrap="true"',kn=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],_n="@vcp-dev/site-edit-engine/webpack-loader",vn=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Tn=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Pn=new Set(["auto-bootstrap.js","client.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Gi(e={},t={}){let n=t.process??process,i=t.createServer??ve.createServer,o=t.attachBridgeServer??(n.env[En]==="1"?Ve:Re),s=t.loadNext??ai,r=Q.resolve(e.projectRoot??process.cwd()),c=e.host??nt,d=e.port??pi(n.env.PORT)??bn,a=e.bridgePath??re,l=Dn(a),u=ni(),S=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",p=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,f=await s(r),y=An(r),b=f({dev:!0,dir:r,hostname:c,port:d,...Hn(y)}),w=b.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",L=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ui(r),D=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,q=D?.trim()?Q.resolve(D):void 0,R=null,z={launchId:In(),pid:process.pid,snapshotId:L},P=i((H,h)=>{Vn({basePath:S,bridgePath:a,bridgeHealthPath:l,bridgeSessionKey:u,getBridgeHealth:()=>R?.getHealth()??Qn(a),launch:z,runRenderProbe:()=>zn(b),handle:w,request:H,response:h}).catch(g=>{console.error(g),h.headersSent||(h.statusCode=500),h.end("site edit preview request failed")})}),j=null,A=null,J=()=>A||(oe(()=>n.off("SIGINT",K)),oe(()=>n.off("SIGTERM",K)),oe(()=>j?.()),j=null,oe(()=>R?.stop()),R=null,A=Promise.allSettled([li(P),fi(()=>b.close())]).then(()=>{}),A),K=()=>{J()};try{return await b.prepare(),R=o(P,{...p?{tenantId:p}:{},siteId:E,snapshotId:L,projectRoot:r,basePath:S,host:c,port:d,path:a,sessionKey:u,...q?{historyRoot:q}:{},onSnapshotIdChanged:H=>{z.snapshotId=H}}),j=Bn({server:P,bridgePath:a,handleUpgrade:b.getUpgradeHandler()}),n.on("SIGINT",K),n.on("SIGTERM",K),await R.whenReady?.(),await hi(P,d,c),{bundler:y,close:J,host:c,port:gi(P,d),server:P}}catch(H){throw await J(),H}}function An(e){let t=Nn(e);return t&&On(t)?"webpack":"turbopack"}function Hn(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Nn(e){for(let t of kn){let n=Y(e,t);if(V(n))return F(n,"utf8")}return null}function On(e){return e.includes(_n)?!0:vn.test(e)&&Tn.some(t=>t.test(e))}function Bn(e){let t=(n,i,o)=>{Mn(n.url,e.bridgePath)||e.handleUpgrade(n,i,o).catch(s=>{console.error(s),i.destroyed||i.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Mn(e,t){return new URL(e??"/","http://localhost").pathname===t}function Dn(e=re){if(e===re)return it;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function jn(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Kn()});return`<script type="module" ${st}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Cn)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Kn(){return{bridge:Ce("@vcp-dev/site-edit-bridge"),contracts:Ce("@vcp-dev/contracts"),engine:Ce("@vcp-dev/site-edit-engine")}}function Ce(e){let t=Ze(import.meta.url);try{let n=t.resolve(e),i=Wn(n,e);if(!i)return;let o=JSON.parse(F(i,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Wn(e,t){let n=Q.parse(e).root,i=X(e);for(;i&&i!==n;){let o=Y(i,"package.json");if(V(o))try{if(JSON.parse(F(o,"utf8")).name===t)return o}catch{return}i=X(i)}}function Un(e,t){if(e.includes(st))return e;let n=jn(t),i=/<\/body\s*>/i.exec(e);return i?`${e.slice(0,i.index)}${n}${e.slice(i.index)}`:`${e}${n}`}function Qi(e,t=X(tt(import.meta.url)),n=V){return ot(e,t,n)?.path??null}function ot(e,t=X(tt(import.meta.url)),n=V){let i=new URL(e??"/","http://localhost").pathname;if(!i.startsWith(ae))return null;let o=i.slice(ae.length);if(!Pn.has(o))return null;let s=Te(ci(t),o);if(et(t)!=="src")return{path:s,requiresTranspile:!1};let r=Te(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function $n(e,t){let n=ot(e.url);if(!n)return!1;if(!V(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let i=n.requiresTranspile?await Fn(F(n.path,"utf8")):F(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(i),!0}async function Fn(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Vn({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:i,getBridgeHealth:o,launch:s,runRenderProbe:r,handle:c,request:d,response:a}){if(Ln(d.url,e)){a.statusCode=404,a.end();return}if(await Gn(d,a,n,o,s,r)||await $n(d,a))return;let l=Xn(d),u=Yn(d),S=l||u?ti(a,{basePath:e,bridgePath:t,bridgeSessionKey:i,patchNextDevChunk:u,launch:{...s}}):()=>{};try{await c(d,a)}catch(p){throw S(),p}}function Ln(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let i;try{i=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(i,"http://namespace.invalid").pathname,s=t.replace(/\/+$/,"");return(s&&(o===s||o.startsWith(s+"/"))?o.slice(s.length)||"/":o).startsWith("/.vcp")}function qn(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function zn(e){let t=new ve.IncomingMessage(new Qe);t.method="GET",t.url=Xe,t.headers={host:nt};let n=new ve.ServerResponse(t);n.assignSocket(new Qe);try{return await e.renderToHTML(t,n,Xe,{}),{verdict:"ok"}}catch(i){return qn(i)}finally{try{let i=n.socket;i&&(n.detachSocket(i),i.destroy())}catch{}}}function Jn(e){return new URL(e??"/","http://localhost").searchParams.get(xn)===Rn}async function Gn(e,t,n,i,o,s){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let c=i(),d=Jn(e.url)?await s():void 0,a={...c,launch:o,...d?{render:d}:{}};return t.writeHead(c.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(a)),!0}function Qn(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Xn(e){return Zn(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Yn(e){return ei(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Zn(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(ae)||n===re||n===it)return!1;let i=e.headers.accept??"";return i===""||i.includes("text/html")}function ei(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 ti(e,t){let n=[],i=e,o=i.flushHeaders.bind(e),s=i.write.bind(e),r=i.end.bind(e),c=!1;i.flushHeaders=()=>{};let d=()=>{if(t.patchNextDevChunk||c)return!1;let a=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(a.toString("utf8")))return!1;let l=Ye(e,a,t);return l!==a&&!e.headersSent&&e.removeHeader("content-length"),s(l),n.length=0,c=!0,!0};return i.write=(a,l,u)=>c?(a!==void 0&&s(ke(a,_e(l))),se(l),se(u),!0):(a!==void 0&&(n.push(ke(a,_e(l))),d()),se(l),se(u),!0),i.end=(a,l,u)=>{let S=typeof a=="function"?void 0:a;if(c)return i.write=s,i.end=r,i.flushHeaders=o,S===void 0?typeof a=="function"?r(a):typeof l=="function"?r(l):typeof u=="function"?r(u):r():typeof l=="function"?r(S,l):typeof u=="function"?r(S,l,u):r(S,l);S!==void 0&&n.push(ke(S,_e(l))),i.write=s,i.end=r,i.flushHeaders=o;let p=Buffer.concat(n),f=Ye(e,p,t);f!==p&&!e.headersSent&&e.removeHeader("content-length");let y=typeof a=="function"?a:typeof l=="function"?l:typeof u=="function"?u:void 0;return y?r(f,y):r(f)},()=>{i.write=s,i.end=r,i.flushHeaders=o}}function Ye(e,t,n){if(ii(e,t))return Buffer.from(Un(t.toString("utf8"),n));if(n.patchNextDevChunk&&si(e)){let i=t.toString("utf8"),o=oi(i);if(o!==i)return Buffer.from(o)}return t}function ni(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ii(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),i=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(i===""||i.includes("text/html"))}function si(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 oi(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(`
6
6
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
7
- `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[i,s])=>Ln(n,i,s),e)}function Ln(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 xe(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Re(e){return typeof e=="string"?e:void 0}function ee(e){typeof e=="function"&&e()}async function qn(e){let n=ze(G(e,"package.json"))(on);return n.default??n}function zn(e){return Je(e)!=="src"?e:Ce(Jn(e),"dist")}function Jn(e){return et(e)?z.posix.dirname(e):J(e)}function Ce(e,t){return et(e)?z.posix.join(e,t):G(e,t)}function et(e){return e.includes("/")&&!e.includes("\\")}function Gn(e){let t=G(e,".vcp/current-snapshot.json");if(!K(t))return"sandbox_worktree";try{let n=JSON.parse(U(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Qn(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Xn(e,t,n){return new Promise((i,s)=>{e.once("error",s),e.listen(t,n,()=>{e.off("error",s),i()})})}function Yn(e){return new Promise(t=>{e.close(()=>t())})}function te(e){try{e()}catch{}}function Zn(e){try{return e()}catch(t){return Promise.reject(t)}}function ei(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{wn as attachNextDevUpgradeHandler,we as attachSiteEditBridgeServerInWorker,Pn as classifySiteEditRenderProbeError,Rn as createSiteEditAutoBootstrapHtmlSnippet,vn as injectSiteEditAutoBootstrap,Nn as isSiteEditRenderProbeRequested,$n as patchNextFirefoxDevChunk,Bn as prepareFirefoxNextDevChunkPatchRequest,Dn as prepareSiteEditHtmlInjectionRequest,xn as resolveSiteEditBridgeHealthPath,Ze as resolveSiteEditClientAsset,Mi as resolveSiteEditClientAssetPath,mn as resolveSiteEditNextDevBundler,Hn as runSiteEditRenderProbe,Oi as startSiteEditNextDevServer,kn as transpileSiteEditClientSource};
7
+ `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[i,o])=>ri(n,i,o),e)}function ri(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 ke(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function _e(e){return typeof e=="string"?e:void 0}function se(e){typeof e=="function"&&e()}async function ai(e){let n=Ze(Y(e,"package.json"))(wn);return n.default??n}function ci(e){return et(e)!=="src"?e:Te(di(e),"dist")}function di(e){return rt(e)?Q.posix.dirname(e):X(e)}function Te(e,t){return rt(e)?Q.posix.join(e,t):Y(e,t)}function rt(e){return e.includes("/")&&!e.includes("\\")}function ui(e){let t=Y(e,".vcp/current-snapshot.json");if(!V(t))return"sandbox_worktree";try{let n=JSON.parse(F(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function pi(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function hi(e,t,n){return new Promise((i,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),i()})})}function li(e){return new Promise(t=>{e.close(()=>t())})}function oe(e){try{e()}catch{}}function fi(e){try{return e()}catch(t){return Promise.reject(t)}}function gi(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{Bn as attachNextDevUpgradeHandler,Re as attachSiteEditBridgeServerInWorker,qn as classifySiteEditRenderProbeError,jn as createSiteEditAutoBootstrapHtmlSnippet,Un as injectSiteEditAutoBootstrap,Jn as isSiteEditRenderProbeRequested,oi as patchNextFirefoxDevChunk,Yn as prepareFirefoxNextDevChunkPatchRequest,Xn as prepareSiteEditHtmlInjectionRequest,Dn as resolveSiteEditBridgeHealthPath,ot as resolveSiteEditClientAsset,Qi as resolveSiteEditClientAssetPath,An as resolveSiteEditNextDevBundler,zn as runSiteEditRenderProbe,Gi as startSiteEditNextDevServer,Fn as transpileSiteEditClientSource};
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import ne from"node:http";import k from"node:fs";import{createHash as z,randomBytes as Ee,timingSafeEqual as be}from"node:crypto";import y from"node:path";import{WebSocket as se,WebSocketServer as xe}from"ws";import{createPreviewSiteEditEngineRuntime as ke,openFileHistoryStore as ve,resolveManagedPageTemplateComposition as _e,scanSiteEditCompositionsFromFiles as Te}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Oe,scanNextAppRouterRoutesFromFiles as Ae}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as He}from"@vcp-dev/site-edit-engine/source-watcher";function Q(t){let e=new Map,i=[],n=new Map,o=[],s=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(s.map((c,p)=>[c,p])),a=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(c=>({placementKey:c.placementKey,placementUnitKey:c.placementUnitKey,relation:c.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},h=t.entries.flatMap((c,p)=>c.dynamicDataSummary?[[p,c.dynamicDataSummary]]:[]),d=new Map(t.entries.map((c,p)=>[c.key,p])),l=[];for(let[c,p]of t.entries.entries()){let g=p.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([c,{kind:g.kind}]);continue}let _=g.siblingKeys.map(b=>{let x=d.get(b);if(x===void 0)throw new Error("Render entry "+p.key+" references missing source sibling "+b);return x});l.push([c,{kind:"source-siblings",siblingEntryIndexes:_}])}let C=c=>{let p=e.get(c);if(typeof p=="number")return p;let g=i.length;return i.push(c),e.set(c,g),g},L=c=>{let p=null;for(let g of pe(c)){let _=`${p??"root"}\0${g}`,b=n.get(_);if(typeof b=="number"){p=b;continue}let x=o.length;o.push([p,C(g)]),n.set(_,x),p=x}if(p===null)throw new Error("Document key must not be empty");return p};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:a,tokens:i,nodes:o,entries:t.entries.map(c=>{let p=c.pageCompositionUnitKey?r.get(c.pageCompositionUnitKey)??-1:-1;if(c.pageCompositionUnitKey&&p<0)throw new Error(`Render entry ${c.key} references unknown page composition unit ${c.pageCompositionUnitKey}`);return[L(c.key),he(c.operationSummary),...p>=0?[p]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...t.entries.every(c=>c.parentKey!==void 0)?{entryParentNodeIds:t.entries.map(c=>c.parentKey===null?null:L(c.parentKey))}:{},...h.length>0?{dynamicDataSummaries:h}:{}}}function he(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function pe(t){if(!t)return[];let e=[],i=0,n=J(t,i);if(n<0)return e.push(t),e;for(e.push(t.slice(0,n)),i=n;i<t.length;){if(n=J(t,i+(t.startsWith("::",i)?2:1)),n<0){e.push(t.slice(i));break}e.push(t.slice(i,n)),i=n}return e}function J(t,e){let i=t.indexOf("/",e),n=t.indexOf("::",e);return i<0?n:n<0?i:Math.min(i,n)}var T="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",P="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var m=class t{constructor(){}static parseMessage(e,i={}){let n=JSON.parse(e);if(!t.isMessage(n,i))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(u(e)&&u(e.payload)){let i=typeof e.payload.id=="string"?e.payload.id:"unknown",n=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:i,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,i={}){return!u(e)||typeof e.type!="string"?!1:e.type==="request"?ge(e.payload,i):e.type==="response"||e.type==="error"?u(e.payload)&&typeof e.payload.id=="string":e.type==="event"?u(e.payload)&&u(e.payload.event):e.type==="auth"?u(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?u(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&u(e.payload)&&e.payload.ok===!0}},A=class{constructor(e){this.options=e,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new B,this.eventDispatcher=new V(i=>{this.sendJson(i)}),this.unsubscribe=e.engine.subscribe(i=>{this.handleEngineEvent(i)}),e.socket.onmessage=i=>{let n=fe(i.data);if(n!==null){this.sendJson({type:"pong",payload:{id:n}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(i.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(e){try{let i=e;if(i.type!=="request")return;let n=i.payload,{id:o}=n;switch(n.kind){case"initialize-session":{let s=D(n),r=await this.resolve(s),a=await this.options.engine.initializeSession({composition:r.context,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:n.kind,result:w({...a,data:{...a.data,document:Y(a.data.document)}},r.context)}});return}case"get-document":{let s=await this.resolveWireContext(n),r=await this.options.engine.getDocument(s);this.sendResult(o,n.kind,Ce(r,s));return}case"get-history-status":{let s=await this.resolveWireContext(n),r=await this.options.engine.getHistoryStatus(s);this.sendResult(o,n.kind,w(r,s));return}case"get-style-context":{let s=await this.resolveWireContext(n);this.sendResult(o,n.kind,w(await this.options.engine.getStyleContext(s),s));return}case"get-object-edit-context":{let s=await this.resolveWireContext(n);this.sendResult(o,n.kind,w(await this.options.engine.getObjectEditContext(n.key,s,n.selectionRef),s));return}case"get-class-name-source":{let s=await this.resolveWireContext(n);this.sendResult(o,n.kind,w(await this.options.engine.getClassNameSource(n.key,s),s));return}case"get-source-tree":{let s=await this.resolveWireContext(n);this.sendResult(o,n.kind,w(await this.options.engine.getSourceTree(s),s));return}case"get-source-file":{let s=await this.resolveWireContext(n);this.sendResult(o,n.kind,w(await this.options.engine.getSourceFile({path:n.path,composition:s}),s));return}case"resolve-source-location":{let s=await this.resolveWireContext(n),r=w(await this.options.engine.resolveSourceLocation({key:n.key,composition:s}),s);this.sendResult(o,n.kind,r);return}case"execute":case"get-operation-result":{let s=await this.resolveOperationWireContext(n.request),r=await this.resolveWireContext(n);if(f(s)!==f(r))throw new I(T,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(n.request,s);if(n.kind==="get-operation-result"){this.sendResult(o,n.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,n.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let s=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.composition);if(f(s)!==f(r))throw new I(T,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:O(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(n),r=n.request;if(r){let h=await this.resolveAndAssert(r.composition);if(r.kind!==n.kind||f(s)!==f(h))throw new I(T,"History request does not match its cursor operation.")}let a=r?{...r,composition:O(s)}:void 0;await this.handleBufferedOperation(o,n.kind,()=>n.kind==="undo"?this.options.engine.undo(s,a):this.options.engine.redo(s,a));return}}}catch(i){let n=m.extractRequestInfo(e);this.sendJson({type:"error",payload:{...n,message:N(i),code:K(i)}})}}async resolve(e){return this.options.engine.resolveComposition(e)}async resolveAndAssert(e){let i=await this.resolve(e),n=this.session.activeComposition;if(!n)throw new I(P,"Initialize a composition session before issuing this request.");if(f(n)!==f(i.context))throw new I(T,"The request composition does not match the active socket session.");return i.context}async resolveWireContext(e){let i=D(e);return this.resolveAndAssert(i)}async resolveOperationWireContext(e){let i=Se(e);return this.resolveAndAssert(i)}activateSession(e){this.session.activeComposition=e,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(f(e))}async normalizeOperationRequest(e,i){let n={...e,composition:O(i)};if(n.target.kind==="route"){let o=n.target,s=D(o),r=await this.resolveAndAssert(s);n.target={...o,composition:O(r)}}return n}handleEngineEvent(e){let i=e?.composition;if(!Ie(i))return;let n=f(i);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(e),e.type==="site-edit.graph.invalidated"&&n===we(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(e,i,n){this.sendJson({type:"response",payload:{id:e,kind:i,result:n}})}async handleRawMessage(e){try{await this.handleMessage(m.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(i){let n=Re(e);this.sendJson({type:"error",payload:{...n,message:N(i),code:K(i)}})}}sendJson(e){this.options.socket.send(m.stringifyMessage(e))}async handleBufferedOperation(e,i,n){this.eventDispatcher.beginBuffering();try{let o=await n();this.sendResult(e,i,o)}catch(o){this.sendJson({type:"error",payload:{id:e,kind:i,message:N(o),code:K(o)}})}finally{this.eventDispatcher.flush()}}},le=256;function fe(t){if(t.length>le||!t.includes('"ping"'))return null;try{let e=JSON.parse(t);return u(e)&&e.type==="ping"&&u(e.payload)&&typeof e.payload.id=="string"?e.payload.id:null}catch{return null}}var I=class extends Error{constructor(e,i){super(i),this.code=e,this.name="BridgeProtocolError"}},V=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let i={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(i);return}this.send(i)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(i=>this.send(i))}},B=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 i=async()=>{this.queued-=1,await e()},n=this.queue.then(i,i);return this.queue=n.then(()=>{},()=>{}),n}};function ge(t,e){if(!u(t)||typeof t.id!="string"||!m.isRequestKind(t.kind))return!1;let i=E(t.composition);switch(t.kind){case"initialize-session":return i&&(t.mutationContext===void 0||F(t.mutationContext));case"get-document":case"get-style-context":return i;case"get-object-edit-context":return typeof t.key=="string"&&i&&me(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&i;case"get-history-status":return i;case"get-source-tree":return i;case"get-source-file":return typeof t.path=="string"&&i;case"execute":case"get-operation-result":return i&&ye(t.request)&&(t.request.mutationContext===void 0||F(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return i&&G(t.request);case"undo":case"redo":return i&&(t.request===void 0||G(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||F(t.mutationContext))}}function G(t){return u(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&E(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function me(t){if(t===void 0)return!0;if(!u(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,i=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||i!==void 0&&(typeof i!="number"||!Number.isInteger(i)||i<=0)||typeof e=="number"&&typeof i=="number"&&e>=i?!1:Object.keys(t).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function ye(t){return u(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&E(t.composition)&&typeof t.kind=="string"&&u(t.target)&&(t.target.kind!=="route"||E(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&u(t.params)}function E(t){return u(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function Ie(t){return u(t)&&typeof t.routeId=="string"&&(t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string")}function D(t){if(E(t.composition))return t.composition;throw new I(P,"A composition selector is required for this request.")}function Se(t){if(u(t)&&E(t.composition))return t.composition;throw new I(P,"A composition selector is required for execute.")}function O(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function we(t){return t.activeComposition?f(t.activeComposition):null}function f(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function w(t,e){return u(t)&&t.ok===!0?{...t,composition:e}:t}function Ce(t,e){return!u(t)||t.ok!==!0?t:{...t,...e?{composition:e}:{},data:Y(t.data)}}function Y(t){let e=t;return Q(e.routeId?e:{...e,routeId:e.composition.routeId})}function u(t){return typeof t=="object"&&t!==null}function F(t){return u(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}function K(t){if(!(!u(t)||typeof t.code!="string"||t.code.length===0))return t.code}function N(t){return t instanceof Error||u(t)&&typeof t.message=="string"&&t.message.length>0?t.message:"Unknown websocket operation failure"}function Re(t){try{return m.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var H=class{constructor(){this.tail=Promise.resolve()}run(e){let i=this.tail.then(e,e);return this.tail=i.then(()=>{},()=>{}),i}};import{SiteEditOperationRequestSchema as Me,computeSiteEditCompositionKey as R}from"@vcp-dev/contracts";var De="127.0.0.1",Fe=30218,Ke="/__vcp/site-edit/bridge",oe=6*1024*1024,Ne=oe*2,Ve=3e3,Z=50,W=".vcp/current-snapshot.json",X="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function lt(t){let e=M(t),i=ae(e),n=re(),o=n.get(i);if(o)return o;let s=new v(e);n.set(i,s);try{s.start()}catch(r){throw n.delete(i),s.stop(),r}return s}function ft(t,e,i={}){let n=new v(M(e),t,!1,i);return n.start({listen:!1}),n}var v=class{constructor(e,i=ne.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=e,this.server=i,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new H,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(e={}){if(!this.isStarted){this.stopping=!1;try{k.mkdirSync(y.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(i){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${i instanceof Error?i.message:String(i)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let i=Ue({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=i.stop}this.stopWatching=new He({projectRoot:this.options.projectRoot,watch_dirs:Be(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Z,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:i=>this.handleFileChanged(i),on_batch_change:i=>this.handleFilesChanged(i)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=re(),i=ae(this.options);e.get(i)===this&&e.delete(i),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let i=this.getHealth(),n=JSON.stringify(i);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{e(i)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(e,i=null){let n=this.runtime;this.activeHistoryStore=e??null;let o=(this.dependencies.createRuntime??ke)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:s=>{"version"in s&&typeof s.version=="number"&&this.recordRuntimeVersion(s.version,"composition"in s?s.composition:void 0);for(let r of this.eventListeners)r(s)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=i,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)throw new Error(`${i.code}: ${i.message}`);let n=qe(e.composition),o=this.getRuntime(),s=S(n);await o.initializeComposition(s);let a=o.getDocument(s).data;await this.recordRuntimeVersion(a.version,n);let h=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:h}}}),getDocument:async e=>{let i=this.getRuntime(),n=S(e);await i.initializeComposition(n);let o=i.getDocument(n);return await this.recordRuntimeVersion(o.data.version,e),{...o,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(S(e)),getObjectEditContext:async(e,i,n)=>this.getRuntime().getObjectEditContext(e,S(i),n),getClassNameSource:async(e,i)=>this.getRuntime().getClassNameSource(e,S(i)),getSourceTree:async e=>this.getRuntime().getSourceTree(S(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:S(e.composition)}),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:S(e.composition)}),execute:(e,i)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return ee(n,e);let o=await this.getRuntime().executeOperation(e);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:e=>this.readOperationReceipt(e),getHistoryOperationResult:e=>this.readOperationReceipt(e),undo:(e,i)=>this.runHistoryWithReceipt("undo",e,i),redo:(e,i)=>this.runHistoryWithReceipt("redo",e,i),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}runHistoryWithReceipt(e,i,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==e||n.composition.routeId!==i.routeId||n.composition.templateId!==i.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return ee(s,void 0,i);let r=await this.getRuntime()[e]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??i),r.composition?r:{...r,composition:i}});return n?this.executeWithReceipt(n,o):o()}isActiveReceiptIdentity(e){return"request_id"in e?e.site_id===this.options.siteId&&e.base_snapshot_id===this.options.snapshotId:e.siteId===this.options.siteId&&e.baseSnapshotId===this.options.snapshotId}operationReceiptKey(e){return"request_id"in e?JSON.stringify([e.site_id,e.base_snapshot_id,"history",e.request_id]):JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return z("sha256").update(JSON.stringify(e)).digest("hex")}readOperationReceipt(e){if(!this.isActiveReceiptIdentity(e))return null;let i=this.operationReceipts.get(this.operationReceiptKey(e));return i?.fingerprint===this.operationFingerprint(e)?i.result:null}executeWithReceipt(e,i){if(!this.isActiveReceiptIdentity(e))return i();let n=this.operationReceiptKey(e),o=this.operationFingerprint(e),s=this.operationReceipts.get(n);if(s)return s.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):s.result;let r={fingerprint:o,result:i(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,h]of this.operationReceipts){if(this.operationReceipts.size<=256)break;h.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let i=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??ve)(We({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let o=n.readDocumentVersion?await n.readDocumentVersion():0,s=this.versionCheckpoints.get(n);s?s.durableVersion=Math.max(s.durableVersion,o):this.versionCheckpoints.set(n,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=R(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,e)});this.historySessionTransition=i.catch(()=>{});try{return await i,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e,i){let n=i?R(i):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,e));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=n?this.runtimeVersionFloors.get(n)??e:e,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),s<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,s),r.pending)return r.pending;let a=r,h=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=h,this.versionPersistence=h,h}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let i=this.options.runtime.watch_debounce_ms??Z;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},i),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let i=e.some(ue)?this.scheduleSnapshotIdentityAdvance():!1,n=e.filter(o=>!Ye(o));if(!(n.length===0&&!i)&&this.refreshCompositions(!1))for(let o of n)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(i=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${i instanceof Error?i.message:String(i)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=k.readFileSync(y.join(this.options.projectRoot,W),"utf8"),i=JSON.parse(e),n=typeof i.snapshot_id=="string"?i.snapshot_id:"";return!n||U(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let i=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let o=await this.bindHistorySession(e);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=i,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${i}: ${o instanceof Error?o.message:String(o)}`);return}let n=new Date().toISOString();for(let o of this.compositions){let s={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:e,previousSnapshotId:i,at:n};for(let r of this.eventListeners)try{r(s)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,i)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(e=!1){try{let i=Pe(this.options.projectRoot),n=Ae(i),o=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),s=Te({files:i});if(s.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(s.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[R(d.context),d])),h=new Map(s.map(d=>[R(d.context),d]));if(this.runtime){for(let[d,l]of a){let C=h.get(d);(!C||C.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(S(l.context))}for(let[d,l]of h){let C=a.get(d);(!C||C.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=o,this.compositions=s,this.compositionFiles=i,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(i){let n=i instanceof Error?i:new Error(String(i));if(this.compositionResolutionError=n,e)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let i=Oe(e.routeId,this.routes,this.options.basePath);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let n=this.routes.find(r=>r.routeId===i);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let o=_e({selector:{routeId:i,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),s=R(o.context);if(!this.compositions.some(r=>R(r.context)===s))throw new Error(`Composition is not registered by the preview bridge: ${s}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let i=this.runtimeVersionFloors.get(R(e.context));return i===void 0?[]:[{composition:e.context,version:i}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function gt(t){let e=new v(M(t),ne.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function mt(t){return M(t)}function M(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:y.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??De,port:t.port??Fe,path:t.path??Ke,sessionKey:t.sessionKey??Ge(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function Be(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function Pe(t){let e=[],i=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!k.existsSync(s))return;let r;try{r=k.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(y.join(s,a.name));continue}if(!a.isFile())continue;let h=y.join(s,a.name),d="";try{d=k.readFileSync(h,"utf8")}catch{}e.push({path:y.relative(t,h).replaceAll(y.sep,"/"),content:d})}};for(let s of i)o(y.join(t,s));return e.sort((s,r)=>s.path.localeCompare(r.path))}function qe(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function S(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function We(t){return y.join(y.resolve(t.root),U(t.siteId),U(t.snapshotId),z("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function U(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:z("sha256").update(t).digest("hex").slice(0,32)}function re(){let t=globalThis;return t[X]??=new Map,t[X]}function ae(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function ee(t,e,i){let n=i??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!n)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:n,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:n,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ue(t){let e=new xe({maxPayload:oe,noServer:!0}),i=new WeakSet,n=s=>{new A({socket:new j(s),engine:t.engine,validateOperationRequest:r=>Me.safeParse(r).success})},o=(s,r,a)=>{if(!je(s,t))return;let h=$e(s,t);if(!h){r.write(`HTTP/1.1 401 Unauthorized\r
1
+ import de from"node:http";import T from"node:fs";import{createHash as G,randomBytes as Fe,timingSafeEqual as Ne}from"node:crypto";import y from"node:path";import{WebSocket as ue,WebSocketServer as Ve}from"ws";import{createPreviewSiteEditEngineRuntime as We,openFileHistoryStore as qe,resolveManagedPageTemplateComposition as $e,scanSiteEditCompositionsFromFiles as Ue}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as je,scanNextAppRouterRoutesFromFiles as ze}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Le}from"@vcp-dev/site-edit-engine/source-watcher";function te(e){if(e.pageBlocks!==void 0&&!Ie(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],i=new Map,o=[],s=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(s.map((d,h)=>[d,h])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),c=new Map(e.entries.map((d,h)=>[d.key,h])),l=[];for(let[d,h]of e.entries.entries()){let g=h.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([d,{kind:g.kind}]);continue}let A=g.siblingKeys.map(_=>{let v=c.get(_);if(v===void 0)throw new Error("Render entry "+h.key+" references missing source sibling "+_);return v});l.push([d,{kind:"source-siblings",siblingEntryIndexes:A}])}let b=d=>{let h=t.get(d);if(typeof h=="number")return h;let g=n.length;return n.push(d),t.set(d,g),g},Y=d=>{let h=null;for(let g of _e(d)){let A=`${h??"root"}\0${g}`,_=i.get(A);if(typeof _=="number"){h=_;continue}let v=o.length;o.push([h,b(g)]),i.set(A,v),h=v}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?r.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[Y(d.key),ye(d.operationSummary),...h>=0?[h]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(d=>d.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(d=>d.parentKey===null?null:Y(d.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function ye(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ie(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!C(n)||!x(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!K(n.blockKey,256)||!K(n.definitionKey,512)||!Se(n.rootRef)||!we(n.source)||!be(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>K(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!R(n.placementUnitKey)||!Ce(n.capabilities)||n.unavailableReasons!==void 0&&!ke(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let i=n.owner;for(let o of n.siblingBlockKeys){let s=t.get(o);if(!s)return!1;let r=s.owner;if(i.kind!==r.kind||i.key!==r.key)return!1}}return!0}function Se(e){return!C(e)||!x(e,["key","instanceIndex","instanceCount"])||!R(e.key)||e.instanceIndex!==void 0&&!Z(e.instanceIndex)||e.instanceCount!==void 0&&(!Z(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function we(e){return C(e)&&x(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Re(e.file)&&R(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function be(e){return C(e)&&x(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&K(e.key,512)}function Ce(e){return C(e)&&x(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function ke(e){return C(e)&&Object.entries(e).every(([t,n])=>R(t)&&C(n)&&x(n,["code","reason"])&&R(n.code)&&R(n.reason))}function Re(e){let t=xe(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(s=>!s||s==="."||s===".."||s.startsWith(".")||s==="node_modules"||s.toLowerCase()==="package.json"||s==="recipes"||s.startsWith(".env")))return!1;let i=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(s=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(s.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(s=>e===s||e.startsWith(`${s}/`))||t}function xe(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),i=n.some(r=>X(r)),o=i?n[0]:n.pop(),s=i?n.slice(1):n;if(i&&s.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!Ee(`/${s.join("/")}`)||s.some(r=>r.includes("[")||r.includes("]")?!X(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,l=>l.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function X(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Ee(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function K(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function R(e){return typeof e=="string"&&e.length>0}function x(e,t){let n=new Set(t);return Object.keys(e).every(i=>n.has(i))}function _e(e){if(!e)return[];let t=[],n=0,i=ee(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=ee(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function ee(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}var B="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",U="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var m=class e{constructor(){}static parseMessage(t,n={}){let i=JSON.parse(t);if(!e.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(p(t)&&p(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",i=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!p(t)||typeof t.type!="string"?!1:t.type==="request"?Oe(t.payload,n):t.type==="response"||t.type==="error"?p(t.payload)&&typeof t.payload.id=="string":t.type==="event"?p(t.payload)&&p(t.payload.event):t.type==="auth"?p(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?p(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&p(t.payload)&&t.payload.ok===!0}},M=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new $,this.eventDispatcher=new q(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let i=Te(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let i=n.payload,{id:o}=i;switch(i.kind){case"initialize-session":{let s=F(i),r=await this.resolve(s),a=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:i.kind,result:w({...a,data:{...a.data,document:ie(a.data.document)}},r.context)}});return}case"get-document":{let s=await this.resolveWireContext(i),r=await this.options.engine.getDocument(s);this.sendResult(o,i.kind,De(r,s));return}case"get-history-status":{let s=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(s);this.sendResult(o,i.kind,w(r,s));return}case"get-style-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getStyleContext(s),s));return}case"get-object-edit-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getObjectEditContext(i.key,s,i.selectionRef),s));return}case"get-class-name-source":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getClassNameSource(i.key,s),s));return}case"get-source-tree":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceTree(s),s));return}case"get-source-file":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceFile({path:i.path,composition:s}),s));return}case"resolve-source-location":{let s=await this.resolveWireContext(i),r=w(await this.options.engine.resolveSourceLocation({key:i.key,composition:s}),s);this.sendResult(o,i.kind,r);return}case"execute":case"get-operation-result":{let s=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(f(s)!==f(r))throw new I(B,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(i.request,s);if(i.kind==="get-operation-result"){this.sendResult(o,i.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,i.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let s=await this.resolveWireContext(i),r=await this.resolveAndAssert(i.request.composition);if(f(s)!==f(r))throw new I(B,"History receipt composition does not match the active session.");this.sendResult(o,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:H(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(i),r=i.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||f(s)!==f(u))throw new I(B,"History request does not match its cursor operation.")}let a=r?{...r,composition:H(s)}:void 0;await this.handleBufferedOperation(o,i.kind,()=>i.kind==="undo"?this.options.engine.undo(s,a):this.options.engine.redo(s,a));return}}}catch(n){let i=m.extractRequestInfo(t);this.sendJson({type:"error",payload:{...i,message:W(n),code:V(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),i=this.session.activeComposition;if(!i)throw new I(U,"Initialize a composition session before issuing this request.");if(f(i)!==f(n.context))throw new I(B,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=F(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=He(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(f(t))}async normalizeOperationRequest(t,n){let i={...t,composition:H(n)};if(i.target.kind==="route"){let o=i.target,s=F(o),r=await this.resolveAndAssert(s);i.target={...o,composition:H(r)}}return i}handleEngineEvent(t){let n=t?.composition;if(!Be(n))return;let i=f(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&i===Me(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(t,n,i){this.sendJson({type:"response",payload:{id:t,kind:n,result:i}})}async handleRawMessage(t){try{await this.handleMessage(m.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=Pe(t);this.sendJson({type:"error",payload:{...i,message:W(n),code:V(n)}})}}sendJson(t){this.options.socket.send(m.stringifyMessage(t))}async handleBufferedOperation(t,n,i){this.eventDispatcher.beginBuffering();try{let o=await i();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:W(o),code:V(o)}})}finally{this.eventDispatcher.flush()}}},ve=256;function Te(e){if(e.length>ve||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return p(t)&&t.type==="ping"&&p(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var I=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},q=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))}},$=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()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function Oe(e,t){if(!p(e)||typeof e.id!="string"||!m.isRequestKind(e.kind))return!1;let n=E(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||N(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ae(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"execute":case"get-operation-result":return n&&Ke(e.request)&&(e.request.mutationContext===void 0||N(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&ne(e.request);case"undo":case"redo":return n&&(e.request===void 0||ne(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||N(e.mutationContext))}}function ne(e){return p(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&E(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ae(e){if(e===void 0)return!0;if(!p(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function Ke(e){return p(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&E(e.composition)&&typeof e.kind=="string"&&p(e.target)&&(e.target.kind!=="route"||E(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&p(e.params)}function E(e){return p(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Be(e){return p(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function F(e){if(E(e.composition))return e.composition;throw new I(U,"A composition selector is required for this request.")}function He(e){if(p(e)&&E(e.composition))return e.composition;throw new I(U,"A composition selector is required for execute.")}function H(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Me(e){return e.activeComposition?f(e.activeComposition):null}function f(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function w(e,t){return p(e)&&e.ok===!0?{...e,composition:t}:e}function De(e,t){return!p(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:ie(e.data)}}function ie(e){let t=e;return te(t.routeId?t:{...t,routeId:t.composition.routeId})}function p(e){return typeof e=="object"&&e!==null}function N(e){return p(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function V(e){if(!(!p(e)||typeof e.code!="string"||e.code.length===0))return e.code}function W(e){return e instanceof Error||p(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function Pe(e){try{return m.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var D=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Je,computeSiteEditCompositionKey as k}from"@vcp-dev/contracts";var Qe="127.0.0.1",Ge=30218,Ye="/__vcp/site-edit/bridge",pe=6*1024*1024,Ze=pe*2,Xe=3e3,se=50,z=".vcp/current-snapshot.json",oe="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function vt(e){let t=P(e),n=le(t),i=he(),o=i.get(n);if(o)return o;let s=new O(t);i.set(n,s);try{s.start()}catch(r){throw i.delete(n),s.stop(),r}return s}function Tt(e,t,n={}){let i=new O(P(t),e,!1,n);return i.start({listen:!1}),i}var O=class{constructor(t,n=de.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new D,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{T.mkdirSync(y.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=st({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new Le({projectRoot:this.options.projectRoot,watch_dirs:et(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??se,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=he(),n=le(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let i=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??We)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:s=>{"version"in s&&typeof s.version=="number"&&this.recordRuntimeVersion(s.version,"composition"in s?s.composition:void 0);for(let r of this.eventListeners)r(s)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=nt(t.composition),o=this.getRuntime(),s=S(i);await o.initializeComposition(s);let a=o.getDocument(s).data;await this.recordRuntimeVersion(a.version,i);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),i=S(t);await n.initializeComposition(i);let o=n.getDocument(i);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(S(t)),getObjectEditContext:async(t,n,i)=>this.getRuntime().getObjectEditContext(t,S(n),i),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,S(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(S(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:S(t.composition)}),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:S(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return re(i,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}runHistoryWithReceipt(t,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==t||i.composition.routeId!==n.routeId||i.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return re(s,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return i?this.executeWithReceipt(i,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return G("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let i=this.operationReceiptKey(t),o=this.operationFingerprint(t),s=this.operationReceipts.get(i);if(s)return s.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):s.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(i,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let i=await(this.dependencies.openHistoryStore??qe)(it({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=i.readDocumentVersion?await i.readDocumentVersion():0,s=this.versionCheckpoints.get(i);s?s.durableVersion=Math.max(s.durableVersion,o):this.versionCheckpoints.set(i,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=k(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(i,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let i=n?k(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=i?this.runtimeVersionFloors.get(i)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),s<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,s),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let i of t)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??se;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let n=t.some(me)?this.scheduleSnapshotIdentityAdvance():!1,i=t.filter(o=>!ht(o));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let o of i)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=T.readFileSync(y.join(this.options.projectRoot,z),"utf8"),n=JSON.parse(t),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||L(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let i=new Date().toISOString();for(let o of this.compositions){let s={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(s)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=tt(this.options.projectRoot),i=ze(n),o=i.length>0?i:(this.options.runtime.routes??[]).map(c=>({...c})),s=Ue({files:n});if(s.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(s.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[k(c.context),c])),u=new Map(s.map(c=>[k(c.context),c]));if(this.runtime){for(let[c,l]of a){let b=u.get(c);(!b||b.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(S(l.context))}for(let[c,l]of u){let b=a.get(c);(!b||b.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=o,this.compositions=s,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,t)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=je(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=$e({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),s=k(o.context);if(!this.compositions.some(r=>k(r.context)===s))throw new Error(`Composition is not registered by the preview bridge: ${s}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(k(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Ot(e){let t=new O(P(e),de.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function At(e){return P(e)}function P(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:y.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Qe,port:e.port??Ge,path:e.path??Ye,sessionKey:e.sessionKey??pt(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function et(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function tt(e){let t=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!T.existsSync(s))return;let r;try{r=T.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(i.has(a.name))continue;o(y.join(s,a.name));continue}if(!a.isFile())continue;let u=y.join(s,a.name),c="";try{c=T.readFileSync(u,"utf8")}catch{}t.push({path:y.relative(e,u).replaceAll(y.sep,"/"),content:c})}};for(let s of n)o(y.join(e,s));return t.sort((s,r)=>s.path.localeCompare(r.path))}function nt(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function S(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function it(e){return y.join(y.resolve(e.root),L(e.siteId),L(e.snapshotId),G("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function L(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:G("sha256").update(e).digest("hex").slice(0,32)}function he(){let e=globalThis;return e[oe]??=new Map,e[oe]}function le(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function re(e,t,n){let i=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:i,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function st(e){let t=new Ve({maxPayload:pe,noServer:!0}),n=new WeakSet,i=s=>{new M({socket:new J(s),engine:e.engine,validateOperationRequest:r=>Je.safeParse(r).success})},o=(s,r,a)=>{if(!ot(s,e))return;let u=rt(s,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),r.destroy();return}h.authenticatedByHeader&&i.add(s),e.handleUpgrade(s,r,a,d=>{e.emit("connection",d,s)})};return t.server.on("upgrade",o),e.on("connection",(s,r)=>{if(i.has(r)){n(s);return}ze(s,t.sessionKey,()=>{n(s)})}),e.stop=()=>{t.server.off("upgrade",o);for(let s of e.clients)s.close(1001,"bridge stopped");e.close()},e}var j=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",i=>{this.onmessage?.({data:i.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===se.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Ne){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,i){this.socket.close(e,i)}};function je(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function $e(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=q(t.headers["x-vcp-site-edit-key"]),o=ce(n,e.sessionKey),s=q(t.headers.host),r=q(t.headers.origin);return s&&!Le(s,e.host,r)?null:r?Qe(r,s,e.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ze(t,e,i){let n=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},Ve),o,s=()=>{clearTimeout(n),t.off("message",o),t.off("close",s)},r=()=>{s(),t.close(1008,"bridge authentication failed")};o=a=>{try{let h=m.parseMessage(a.toString());if(h.type!=="auth"||!ce(h.payload.key,e)){r();return}s(),t.readyState===se.OPEN&&t.send(m.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),i()}catch{r()}},t.on("message",o),t.on("close",s)}function ce(t,e){if(!t)return!1;let i=Buffer.from(t),n=Buffer.from(e);return i.length===n.length&&be(i,n)}function Le(t,e,i){let n=ie(t),o=ie(e);return n===o||te(o)&&te(n)&&(!i||$(i,t))||Je(o)&&(!i||$(i,t))}function Je(t){return t==="0.0.0.0"||t==="::"}function te(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Qe(t,e,i){return i.includes(t)||(e?$(t,e):!1)}function $(t,e){try{return new URL(t).host===de(e)}catch{return!1}}function ie(t){let e=de(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function de(t){return t.trim().toLowerCase()}function q(t){return Array.isArray(t)?t[0]:t}function Ge(){return Ee(32).toString("base64url")}function ue(t){let e=t.replaceAll("\\","/");return e===W||e.endsWith(`/${W}`)}function Ye(t){let e=t.replaceAll("\\","/");return ue(t)||e===".vcp/workspace-state.json"||e.startsWith(".vcp/snapshot-store/")}export{Ne as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,oe as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,v as SiteEditBridgeServer,ft as attachSiteEditBridgeServer,Ue as attachSiteEditWebSocketServer,gt as createSiteEditBridgeEngineHost,lt as ensureSiteEditBridgeServerStarted,mt as normalizeSiteEditBridgeServerOptions};
4
+ `),r.destroy();return}u.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,r,a,c=>{t.emit("connection",c,s)})};return e.server.on("upgrade",o),t.on("connection",(s,r)=>{if(n.has(r)){i(s);return}at(s,e.sessionKey,()=>{i(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var J=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===ue.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Ze){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ot(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function rt(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=j(e.headers["x-vcp-site-edit-key"]),o=fe(i,t.sessionKey),s=j(e.headers.host),r=j(e.headers.origin);return s&&!ct(s,t.host,r)?null:r?ut(r,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function at(e,t,n){let i=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Xe),o,s=()=>{clearTimeout(i),e.off("message",o),e.off("close",s)},r=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let u=m.parseMessage(a.toString());if(u.type!=="auth"||!fe(u.payload.key,t)){r();return}s(),e.readyState===ue.OPEN&&e.send(m.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",s)}function fe(e,t){if(!e)return!1;let n=Buffer.from(e),i=Buffer.from(t);return n.length===i.length&&Ne(n,i)}function ct(e,t,n){let i=ce(e),o=ce(t);return i===o||ae(o)&&ae(i)&&(!n||Q(n,e))||dt(o)&&(!n||Q(n,e))}function dt(e){return e==="0.0.0.0"||e==="::"}function ae(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ut(e,t,n){return n.includes(e)||(t?Q(e,t):!1)}function Q(e,t){try{return new URL(e).host===ge(t)}catch{return!1}}function ce(e){let t=ge(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function ge(e){return e.trim().toLowerCase()}function j(e){return Array.isArray(e)?e[0]:e}function pt(){return Fe(32).toString("base64url")}function me(e){let t=e.replaceAll("\\","/");return t===z||t.endsWith(`/${z}`)}function ht(e){let t=e.replaceAll("\\","/");return me(e)||t===".vcp/workspace-state.json"||t.startsWith(".vcp/snapshot-store/")}export{Ze as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,pe as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,O as SiteEditBridgeServer,Tt as attachSiteEditBridgeServer,st as attachSiteEditWebSocketServer,Ot as createSiteEditBridgeEngineHost,vt as ensureSiteEditBridgeServerStarted,At as normalizeSiteEditBridgeServerOptions};
@@ -1,4 +1,4 @@
1
- import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditObjectEditContext, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditRenderDocument, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
1
+ import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditObjectEditContext, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPageBlockPosition, SiteEditPageBlockTarget, SiteEditRenderDocument, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
2
2
  import type { SiteEditOperationSelectionRef } from "@vcp-dev/contracts";
3
3
  import type { SiteEditHistoryStatus } from "./protocol.js";
4
4
  export { getPropertyPreviewDomAttributeName, planPropertyPreview, type SiteEditPropertyPreviewElement, type SiteEditPropertyPreviewInput, type SiteEditPropertyPreviewResult, } from "./property-preview.js";
@@ -461,12 +461,14 @@ export type SiteEditFrameRuntimeSectionContext = {
461
461
  ref: SiteEditFrameRuntimeRef;
462
462
  rect: SiteEditFrameRuntimeRect;
463
463
  targetIsSectionRoot: boolean;
464
+ blockTarget?: SiteEditPageBlockTarget;
464
465
  };
465
466
  export type SiteEditFrameRuntimeSectionGapCandidate = {
466
467
  anchorBlockId: string;
467
468
  positionIndex?: number;
468
469
  anchorRef: SiteEditFrameRuntimeRef;
469
470
  placement: "before" | "after";
471
+ blockPosition?: SiteEditPageBlockPosition;
470
472
  boundary: {
471
473
  top: number;
472
474
  left: number;
@@ -483,6 +485,7 @@ export type SiteEditFrameRuntimeHit = {
483
485
  sourceFile?: string;
484
486
  parentKey?: string;
485
487
  pageCompositionUnitKey?: string;
488
+ blockTarget?: SiteEditPageBlockTarget;
486
489
  textPreview?: string;
487
490
  dataset?: Record<string, string>;
488
491
  attributes?: Record<string, string>;