@vcp-dev/site-edit-bridge 0.11.21 → 0.11.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +7 -0
- package/dist/engine-worker.js +2 -2
- package/dist/index.js +5 -5
- package/dist/next-dev-server.js +4 -4
- package/dist/portable-snapshot-proof.js +6 -1
- package/dist/server.js +2 -2
- package/package.json +3 -3
package/dist/next-dev-server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import Me from"node:http";import{existsSync as q,readFileSync as $}from"node:fs";import{randomUUID as Yn}from"node:crypto";import{createRequire as St}from"node:module";import{Socket as gt}from"node:net";import X from"node:path";import{basename as _t,dirname as Y,join as Z}from"node:path";import{fileURLToPath as bt}from"node:url";import{createRequire as Kn}from"node:module";import{pathToFileURL as Un}from"node:url";import{Worker as Wn}from"node:worker_threads";var De=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function le(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import nn from"node:http";import Q from"node:fs";import{createHash as Ae,randomBytes as sn,timingSafeEqual as on}from"node:crypto";import C from"node:path";import{WebSocket as at,WebSocketServer as rn}from"ws";import{createPreviewSiteEditEngineRuntime as an,exportPortableBlockFromSnapshot as cn,readPortableBlockLocalAssetChunk as dn,openFileHistoryStore as un,resolveManagedPageTemplateComposition as pn,scanSiteEditCompositionsFromFiles as ln}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as hn,scanNextAppRouterRoutesFromFiles as fn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as gn}from"@vcp-dev/site-edit-engine/source-watcher";function We(e){if(e.pageBlocks!==void 0&&!Tt(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((h,f)=>[h,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(h=>({placementKey:h.placementKey,placementUnitKey:h.placementUnitKey,relation:h.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},d=e.entries.flatMap((h,f)=>h.dynamicDataSummary?[[f,h.dynamicDataSummary]]:[]),a=new Map(e.entries.map((h,f)=>[h.key,f])),u=[];for(let[h,f]of e.entries.entries()){let _=f.pageCompositionActionScope;if(!_)continue;if(_.kind!=="source-siblings"){u.push([h,{kind:_.kind}]);continue}let p=_.siblingKeys.map(m=>{let I=a.get(m);if(I===void 0)throw new Error("Render entry "+f.key+" references missing source sibling "+m);return I});u.push([h,{kind:"source-siblings",siblingEntryIndexes:p}])}let l=h=>{let f=t.get(h);if(typeof f=="number")return f;let _=n.length;return n.push(h),t.set(h,_),_},y=h=>{let f=null;for(let _ of Lt(h)){let p=`${f??"root"}\0${_}`,m=s.get(p);if(typeof m=="number"){f=m;continue}let I=o.length;o.push([f,l(_)]),s.set(p,I),f=I}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(h=>{let f=h.pageCompositionUnitKey?r.get(h.pageCompositionUnitKey)??-1:-1;if(h.pageCompositionUnitKey&&f<0)throw new Error(`Render entry ${h.key} references unknown page composition unit ${h.pageCompositionUnitKey}`);return[y(h.key),Ct(h.operationSummary),...f>=0?[f]:[]]}),...u.length>0?{pageCompositionActionScopes:u}:{},...e.entries.every(h=>h.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(h=>h.parentKey===null?null:y(h.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 L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function je(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Tt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!L(n)||!F(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!te(n.blockKey,256)||!te(n.definitionKey,512)||!vt(n.rootRef)||!At(n.source)||!Pt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>te(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!Ot(n.capabilities)||n.unavailableReasons!==void 0&&!Nt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let o of n.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function vt(e){return!L(e)||!F(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!je(e.instanceIndex)||e.instanceCount!==void 0&&(!je(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function At(e){return L(e)&&F(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Bt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Pt(e){return L(e)&&F(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&te(e.key,512)}function Ot(e){return L(e)&&F(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 Nt(e){return L(e)&&Object.entries(e).every(([t,n])=>W(t)&&L(n)&&F(n,["code","reason"])&&W(n.code)&&W(n.reason))}function Bt(e){let t=Ht(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.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(i=>e===i||e.startsWith(`${i}/`))||t}function Ht(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Ke(r)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!Mt(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Ke(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,u=>u.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 Ke(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Mt(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 te(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function F(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Lt(e){if(!e)return[];let t=[],n=0,s=Ue(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Ue(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Ue(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var V="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",_e="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var k=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(b(t)&&b(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}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==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!b(t)||typeof t.type!="string"?!1:t.type==="request"?Kt(t.payload,n):t.type==="response"||t.type==="error"?b(t.payload)&&typeof t.payload.id=="string":t.type==="event"?b(t.payload)&&b(t.payload.event):t.type==="auth"?b(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?b(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&b(t.payload)&&t.payload.ok===!0}},se=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Se,this.eventDispatcher=new ye(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=jt(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});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 s=n.payload,{id:o}=s;switch(s.kind){case"initialize-session":{let i=he(s),r=await this.resolve(i),c=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:O({...c,data:{...c.data,document:qe(c.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,$t(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,O(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!be(s))throw new x("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(w(i)!==w(r))throw new x(V,"The portable export target does not match the active composition.");let c=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,c);return}case"export-portable-block-asset":{if(!Ve(s))throw new x("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(w(i)!==w(r))throw new x(V,"The portable asset target does not match the active composition.");let c=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,c);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=O(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(w(i)!==w(r))throw new x(V,"The execute request composition does not match its operation composition.");let c=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(c)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(c));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(w(i)!==w(r))throw new x(V,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:ne(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(s),r=s.request;if(r){let d=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||w(i)!==w(d))throw new x(V,"History request does not match its cursor operation.")}let c=r?{...r,composition:ne(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,c):this.options.engine.redo(i,c));return}}}catch(n){let s=k.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:me(n),code:ge(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new x(_e,"Initialize a composition session before issuing this request.");if(w(s)!==w(n.context))throw new x(V,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=he(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=Ft(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(w(t))}async normalizeOperationRequest(t,n){let s={...t,composition:ne(n)};if(s.target.kind==="route"){let o=s.target,i=he(o),r=await this.resolveAndAssert(i);s.target={...o,composition:ne(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Wt(n))return;let s=w(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===Vt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(k.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=qt(t);this.sendJson({type:"error",payload:{...s,message:me(n),code:ge(n)}})}}sendJson(t){this.options.socket.send(k.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let o=await s();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:me(o),code:ge(o)}})}finally{this.eventDispatcher.flush()}}},Dt=256;function jt(e){if(e.length>Dt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return b(t)&&t.type==="ping"&&b(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var x=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},ye=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))}},Se=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()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function Kt(e,t){if(!b(e)||typeof e.id!="string"||!k.isRequestKind(e.kind))return!1;let n=N(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||fe(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&$e(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"export-portable-block":return be(e);case"export-portable-block-asset":return Ve(e);case"execute":case"get-operation-result":return n&&Ut(e.request)&&(e.request.mutationContext===void 0||fe(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Fe(e.request);case"undo":case"redo":return n&&(e.request===void 0||Fe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||fe(e.mutationContext))}}function be(e){if(!N(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(n))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!b(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!N(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!$e(t.selection_ref))}function Ve(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!be({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function Fe(e){return b(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")&&N(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function $e(e){if(e===void 0)return!0;if(!b(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(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function Ut(e){return b(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&N(e.composition)&&typeof e.kind=="string"&&b(e.target)&&(e.target.kind!=="route"||N(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&b(e.params)}function N(e){return b(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 Wt(e){return b(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function he(e){if(N(e.composition))return e.composition;throw new x(_e,"A composition selector is required for this request.")}function Ft(e){if(b(e)&&N(e.composition))return e.composition;throw new x(_e,"A composition selector is required for execute.")}function ne(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Vt(e){return e.activeComposition?w(e.activeComposition):null}function w(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function O(e,t){return b(e)&&e.ok===!0?{...e,composition:t}:e}function $t(e,t){return!b(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:qe(e.data)}}function qe(e){let t=e;return We(t.routeId?t:{...t,routeId:t.composition.routeId})}function b(e){return typeof e=="object"&&e!==null}function fe(e){return b(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 ge(e){if(!(!b(e)||typeof e.code!="string"||e.code.length===0))return e.code}function me(e){return e instanceof Error||b(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function qt(e){try{return k.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{createHash as ze}from"node:crypto";import{constants as Je,promises as Ie}from"node:fs";import Ge from"node:path";var Qe=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Xe=64;async function oe(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(c=>!c||c==="."||c==="..")||Qe.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>Xe||++n>t.size*Xe+1)return!1;let c=await Ie.readdir(Ge.join(e,i),{withFileTypes:!0});for(let d of c){let a=i?`${i}/${d.name}`:d.name;if(!i&&Qe.has(d.name))continue;if(d.isDirectory()){if(!await o(a,r+1))return!1;continue}if(!d.isFile())return!1;let u=t.get(a);if(u===void 0||s.has(a))return!1;s.add(a);let l=Ge.join(e,a),y=await Ie.lstat(l),h=typeof u=="string"?Buffer.byteLength(u,"utf8"):u.byteLength;if(!y.isFile()||y.isSymbolicLink()||y.size!==h)return!1;let f=ze("sha256").update(u).digest("hex"),_=ze("sha256"),p=await Ie.open(l,Je.O_RDONLY|Je.O_NOFOLLOW);try{let m=p.createReadStream({autoClose:!1});for await(let I of m)_.update(I)}finally{await p.close()}if(_.digest("hex")!==f)return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as zt,createPublicKey as Jt,verify as Gt}from"node:crypto";import{constants as Ye,promises as ae}from"node:fs";import we from"node:path";import{GeneratedSiteCapabilitiesSchema as Qt}from"@vcp-dev/contracts";var Xt=".vcp/portable-snapshot-proof.json",Ze=4*1024*1024,Yt=256*1024*1024,Zt=1e4,en=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function tt(e){try{if(!e.publicKey||!Ee(e.publicKey,256))return null;let t=Jt({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let n=we.join(e.projectRoot,Xt),s=await ae.lstat(n);if(!s.isFile()||s.isSymbolicLink()||s.size>Ze)return null;let o=JSON.parse(await ae.readFile(n,"utf8"));if(!G(o)||!re(o,["payload","signature"])||!Ee(o.payload,Ze)||!Ee(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!Gt(null,i,t,r))return null;let c=new TextDecoder("utf-8",{fatal:!0}).decode(i),d=JSON.parse(c);if(JSON.stringify(d)!==c||!G(d)||!re(d,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||d.kind!=="vcp-portable-snapshot-v1"||!G(d.manifest))return null;let a=d.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>Zt)return null;let u=Qt.safeParse(d.host_capabilities);if(!u.success||!Array.isArray(d.trusted_host_file_hashes)||d.trusted_host_file_hashes.length>512)return null;let l=new Map;for(let p of d.trusted_host_file_hashes){if(!G(p)||!re(p,["path","hash"])||typeof p.path!="string"||!/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(p.path)||!et(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||l.has(p.path))return null;l.set(p.path,p.hash)}let y=0,h=[],f=new Set;for(let p of a.files){if(!G(p)||!re(p,["path","hash","size_bytes"])||typeof p.path!="string"||!et(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||typeof p.size_bytes!="number"||!Number.isSafeInteger(p.size_bytes)||p.size_bytes<0||f.has(p.path)||(f.add(p.path),y+=p.size_bytes,y>Yt))return null;h.push({path:p.path,hash:p.hash,size_bytes:p.size_bytes})}let _=new Map;for(let p of h){let m=await tn(e.projectRoot,p.path,p.size_bytes);if(!m||`sha256:${zt("sha256").update(m).digest("hex")}`!==p.hash)return null;_.set(p.path,m)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:h},files:_},host_capabilities:u.data,trusted_host_file_hashes:l}}catch{return null}}async function tn(e,t,n){let s=t.split("/"),o=e;for(let c of s.slice(0,-1)){o=we.join(o,c);let d=await ae.lstat(o);if(!d.isDirectory()||d.isSymbolicLink())return null}let i=we.join(o,s.at(-1)),r=await ae.open(i,Ye.O_RDONLY|Ye.O_NOFOLLOW);try{let c=await r.stat();if(!c.isFile()||c.size!==n)return null;let d=[],a=0,u=r.createReadStream({autoClose:!1});for await(let l of u){let y=l;if(a+=y.byteLength,a>n)return u.destroy(),null;d.push(y)}return a===n?Buffer.concat(d,a):null}finally{await r.close()}}function et(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!en.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Ee(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as mn,SiteEditPortableExportRequestSchema as yn,SiteEditPortableExportResultSchema as Sn,SiteEditPortableAssetRequestSchema as _n,SiteEditPortableAssetResultSchema as bn,computeSiteEditCompositionKey as D}from"@vcp-dev/contracts";var In="127.0.0.1",En=30218,wn="/__vcp/site-edit/bridge",ct=6*1024*1024,xn=ct*2,Rn=3e3,nt=50,Re=".vcp/current-snapshot.json",st="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function dt(e,t,n={}){let s=new ke(pt(t),e,!1,n);return s.start({listen:!1}),s}var ke=class{constructor(t,n=nn.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,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{Q.mkdirSync(C.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=Pe({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 gn({projectRoot:this.options.projectRoot,watch_dirs:kn(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??nt,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=An(),n=Pn(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(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;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 s=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??an)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,s?.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 s=Tn(t.composition),o=this.getRuntime(),i=R(s);await o.initializeComposition(i);let c=o.getDocument(i).data;await this.recordRuntimeVersion(c.version,s);let d=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:c,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),s=R(t);await n.initializeComposition(s);let o=n.getDocument(s);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(R(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,R(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,R(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(R(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:R(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:R(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return it(s,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))}}async exportPortableBlock(t,n,s){let o=(m,I,j)=>({complete:!1,unresolved:[{code:m,path:I,message:j}]}),i=yn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,c=R(n);if(r.target.composition.routeId!==c.routeId||r.target.composition.templateId!==c.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(c);let a=()=>{let m=this.getRuntime().getDocument(c).data;return{site_id:m.siteId,snapshot_id:m.snapshotId,document_version:m.version}},u=a();if(u.site_id!==r.site_id||u.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(u.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.dependencies.loadTrustedPortableSnapshot??(m=>tt({...m,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),y;try{y=await l({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!y)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let h=new Map([...y.snapshot.files].map(([m,I])=>[m,typeof I=="string"?I:new Uint8Array(I)])),f={...y,snapshot:{...y.snapshot,files:h}};if(!await oe(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let _=await cn({...r,...f,read_current_identity:a}),p=Sn.safeParse(_);if(!p.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(p.data.complete&&(p.data.site_id!==r.site_id||p.data.base_snapshot_id!==r.base_snapshot_id||p.data.document_version!==r.document_version||p.data.target.blockKey!==r.target.blockKey||p.data.target.composition.routeId!==c.routeId||p.data.target.composition.templateId!==c.templateId||p.data.selection_ref.key!==r.selection_ref.key||p.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||p.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(p.data.complete){if(!await oe(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let m=a();if(this.options.snapshotId!==r.base_snapshot_id||m.site_id!==r.site_id||m.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(m.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}s?.(h)}return p.data}async exportPortableBlockAsset(t,n){let s=u=>({complete:!1,unresolved:[{code:u,path:"<asset>",message:"The selected local image could not be verified."}]}),o=_n.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,c=await this.exportPortableBlock(i.request,n,u=>{r=u});if(!c.complete)return c;if(c.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let d=dn({exported:c,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),a=bn.safeParse(d);if(!a.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!a.data.complete)return a.data;if(!await oe(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let u=this.getRuntime().getDocument(R(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||u.siteId!==i.request.site_id||u.snapshotId!==i.request.base_snapshot_id||u.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return a.data}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.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 i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return it(i,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 s?this.executeWithReceipt(s,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 Ae("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 s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,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(s)}),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 s=await(this.dependencies.openHistoryStore??un)(vn({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let c=D(r);this.runtimeVersionFloors.set(c,Math.max(this.runtimeVersionFloors.get(c)??0,o))}this.createRuntime(s,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 s=n?D(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),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 s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??nt;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,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let n=t.some(ft)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!jn(o));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let o of s)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=Q.readFileSync(C.join(this.options.projectRoot,Re),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Ce(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}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 s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}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=Cn(this.options.projectRoot),s=fn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(a=>({...a})),i=ln({files:n});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.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=>[D(a.context),a])),d=new Map(i.map(a=>[D(a.context),a]));if(this.runtime){for(let[a,u]of c){let l=d.get(a);(!l||l.entryFile!==u.entryFile)&&this.runtime.unregisterComposition(R(u.context))}for(let[a,u]of d){let l=c.get(a);(!l||l.entryFile!==u.entryFile)&&this.runtime.registerComposition(u.context,u.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=hn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=pn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=D(o.context);if(!this.compositions.some(r=>D(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(D(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 ut(e){return pt(e)}function pt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:C.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??In,port:e.port??En,path:e.path??wn,sessionKey:e.sessionKey??Dn(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function kn(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 Cn(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!Q.existsSync(i))return;let r;try{r=Q.readdirSync(i,{withFileTypes:!0})}catch{return}for(let c of r){if(c.name.startsWith(".")&&c.name!==".vcp")continue;if(c.isDirectory()){if(s.has(c.name))continue;o(C.join(i,c.name));continue}if(!c.isFile())continue;let d=C.join(i,c.name),a="";try{a=Q.readFileSync(d,"utf8")}catch{}t.push({path:C.relative(e,d).replaceAll(C.sep,"/"),content:a})}};for(let i of n)o(C.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function Tn(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 R(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function vn(e){return C.join(C.resolve(e.root),Ce(e.siteId),Ce(e.snapshotId),Ae("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Ce(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ae("sha256").update(e).digest("hex").slice(0,32)}function An(){let e=globalThis;return e[st]??=new Map,e[st]}function Pn(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function it(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function Pe(e){let t=new rn({maxPayload:ct,noServer:!0}),n=new WeakSet,s=i=>{new se({socket:new Te(i),engine:e.engine,validateOperationRequest:r=>mn.safeParse(r).success})},o=(i,r,c)=>{if(!On(i,e))return;let d=Nn(i,e);if(!d){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import Me from"node:http";import{existsSync as q,readFileSync as $}from"node:fs";import{randomUUID as Zn}from"node:crypto";import{createRequire as St}from"node:module";import{Socket as gt}from"node:net";import X from"node:path";import{basename as _t,dirname as Y,join as Z}from"node:path";import{fileURLToPath as bt}from"node:url";import{createRequire as Un}from"node:module";import{pathToFileURL as Wn}from"node:url";import{Worker as Fn}from"node:worker_threads";var De=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function le(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import sn from"node:http";import Q from"node:fs";import{createHash as Ae,randomBytes as on,timingSafeEqual as rn}from"node:crypto";import C from"node:path";import{WebSocket as at,WebSocketServer as an}from"ws";import{createPreviewSiteEditEngineRuntime as cn,exportPortableBlockFromSnapshot as dn,readPortableBlockLocalAssetChunk as un,openFileHistoryStore as pn,resolveManagedPageTemplateComposition as ln,scanSiteEditCompositionsFromFiles as hn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as fn,scanNextAppRouterRoutesFromFiles as gn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as mn}from"@vcp-dev/site-edit-engine/source-watcher";function We(e){if(e.pageBlocks!==void 0&&!Tt(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((h,f)=>[h,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(h=>({placementKey:h.placementKey,placementUnitKey:h.placementUnitKey,relation:h.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},d=e.entries.flatMap((h,f)=>h.dynamicDataSummary?[[f,h.dynamicDataSummary]]:[]),a=new Map(e.entries.map((h,f)=>[h.key,f])),u=[];for(let[h,f]of e.entries.entries()){let _=f.pageCompositionActionScope;if(!_)continue;if(_.kind!=="source-siblings"){u.push([h,{kind:_.kind}]);continue}let p=_.siblingKeys.map(m=>{let I=a.get(m);if(I===void 0)throw new Error("Render entry "+f.key+" references missing source sibling "+m);return I});u.push([h,{kind:"source-siblings",siblingEntryIndexes:p}])}let l=h=>{let f=t.get(h);if(typeof f=="number")return f;let _=n.length;return n.push(h),t.set(h,_),_},y=h=>{let f=null;for(let _ of Lt(h)){let p=`${f??"root"}\0${_}`,m=s.get(p);if(typeof m=="number"){f=m;continue}let I=o.length;o.push([f,l(_)]),s.set(p,I),f=I}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(h=>{let f=h.pageCompositionUnitKey?r.get(h.pageCompositionUnitKey)??-1:-1;if(h.pageCompositionUnitKey&&f<0)throw new Error(`Render entry ${h.key} references unknown page composition unit ${h.pageCompositionUnitKey}`);return[y(h.key),Ct(h.operationSummary),...f>=0?[f]:[]]}),...u.length>0?{pageCompositionActionScopes:u}:{},...e.entries.every(h=>h.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(h=>h.parentKey===null?null:y(h.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 L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function je(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Tt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!L(n)||!F(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!te(n.blockKey,256)||!te(n.definitionKey,512)||!vt(n.rootRef)||!At(n.source)||!Pt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>te(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!Ot(n.capabilities)||n.unavailableReasons!==void 0&&!Nt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let o of n.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function vt(e){return!L(e)||!F(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!je(e.instanceIndex)||e.instanceCount!==void 0&&(!je(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function At(e){return L(e)&&F(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Bt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Pt(e){return L(e)&&F(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&te(e.key,512)}function Ot(e){return L(e)&&F(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 Nt(e){return L(e)&&Object.entries(e).every(([t,n])=>W(t)&&L(n)&&F(n,["code","reason"])&&W(n.code)&&W(n.reason))}function Bt(e){let t=Ht(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.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(i=>e===i||e.startsWith(`${i}/`))||t}function Ht(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Ke(r)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!Mt(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Ke(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,u=>u.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 Ke(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Mt(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 te(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function F(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Lt(e){if(!e)return[];let t=[],n=0,s=Ue(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Ue(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Ue(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var V="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",_e="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var k=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(b(t)&&b(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}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==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!b(t)||typeof t.type!="string"?!1:t.type==="request"?Kt(t.payload,n):t.type==="response"||t.type==="error"?b(t.payload)&&typeof t.payload.id=="string":t.type==="event"?b(t.payload)&&b(t.payload.event):t.type==="auth"?b(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?b(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&b(t.payload)&&t.payload.ok===!0}},se=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Se,this.eventDispatcher=new ye(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=jt(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});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 s=n.payload,{id:o}=s;switch(s.kind){case"initialize-session":{let i=he(s),r=await this.resolve(i),c=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:O({...c,data:{...c.data,document:qe(c.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,$t(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,O(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,O(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!be(s))throw new x("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(w(i)!==w(r))throw new x(V,"The portable export target does not match the active composition.");let c=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,c);return}case"export-portable-block-asset":{if(!Ve(s))throw new x("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(w(i)!==w(r))throw new x(V,"The portable asset target does not match the active composition.");let c=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,c);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=O(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(w(i)!==w(r))throw new x(V,"The execute request composition does not match its operation composition.");let c=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(c)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(c));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(w(i)!==w(r))throw new x(V,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:ne(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(s),r=s.request;if(r){let d=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||w(i)!==w(d))throw new x(V,"History request does not match its cursor operation.")}let c=r?{...r,composition:ne(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,c):this.options.engine.redo(i,c));return}}}catch(n){let s=k.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:me(n),code:ge(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new x(_e,"Initialize a composition session before issuing this request.");if(w(s)!==w(n.context))throw new x(V,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=he(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=Ft(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(w(t))}async normalizeOperationRequest(t,n){let s={...t,composition:ne(n)};if(s.target.kind==="route"){let o=s.target,i=he(o),r=await this.resolveAndAssert(i);s.target={...o,composition:ne(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Wt(n))return;let s=w(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===Vt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(k.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=qt(t);this.sendJson({type:"error",payload:{...s,message:me(n),code:ge(n)}})}}sendJson(t){this.options.socket.send(k.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let o=await s();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:me(o),code:ge(o)}})}finally{this.eventDispatcher.flush()}}},Dt=256;function jt(e){if(e.length>Dt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return b(t)&&t.type==="ping"&&b(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var x=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},ye=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))}},Se=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()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function Kt(e,t){if(!b(e)||typeof e.id!="string"||!k.isRequestKind(e.kind))return!1;let n=N(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||fe(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&$e(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"export-portable-block":return be(e);case"export-portable-block-asset":return Ve(e);case"execute":case"get-operation-result":return n&&Ut(e.request)&&(e.request.mutationContext===void 0||fe(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Fe(e.request);case"undo":case"redo":return n&&(e.request===void 0||Fe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||fe(e.mutationContext))}}function be(e){if(!N(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(n))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!b(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!N(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!$e(t.selection_ref))}function Ve(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!be({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function Fe(e){return b(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")&&N(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function $e(e){if(e===void 0)return!0;if(!b(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(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function Ut(e){return b(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&N(e.composition)&&typeof e.kind=="string"&&b(e.target)&&(e.target.kind!=="route"||N(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&b(e.params)}function N(e){return b(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 Wt(e){return b(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function he(e){if(N(e.composition))return e.composition;throw new x(_e,"A composition selector is required for this request.")}function Ft(e){if(b(e)&&N(e.composition))return e.composition;throw new x(_e,"A composition selector is required for execute.")}function ne(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Vt(e){return e.activeComposition?w(e.activeComposition):null}function w(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function O(e,t){return b(e)&&e.ok===!0?{...e,composition:t}:e}function $t(e,t){return!b(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:qe(e.data)}}function qe(e){let t=e;return We(t.routeId?t:{...t,routeId:t.composition.routeId})}function b(e){return typeof e=="object"&&e!==null}function fe(e){return b(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 ge(e){if(!(!b(e)||typeof e.code!="string"||e.code.length===0))return e.code}function me(e){return e instanceof Error||b(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function qt(e){try{return k.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{createHash as ze}from"node:crypto";import{constants as Je,promises as Ie}from"node:fs";import Ge from"node:path";var Qe=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Xe=64;async function oe(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(c=>!c||c==="."||c==="..")||Qe.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>Xe||++n>t.size*Xe+1)return!1;let c=await Ie.readdir(Ge.join(e,i),{withFileTypes:!0});for(let d of c){let a=i?`${i}/${d.name}`:d.name;if(!i&&Qe.has(d.name))continue;if(d.isDirectory()){if(!await o(a,r+1))return!1;continue}if(!d.isFile())return!1;let u=t.get(a);if(u===void 0||s.has(a))return!1;s.add(a);let l=Ge.join(e,a),y=await Ie.lstat(l),h=typeof u=="string"?Buffer.byteLength(u,"utf8"):u.byteLength;if(!y.isFile()||y.isSymbolicLink()||y.size!==h)return!1;let f=ze("sha256").update(u).digest("hex"),_=ze("sha256"),p=await Ie.open(l,Je.O_RDONLY|Je.O_NOFOLLOW);try{let m=p.createReadStream({autoClose:!1});for await(let I of m)_.update(I)}finally{await p.close()}if(_.digest("hex")!==f)return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as zt,createPublicKey as Jt,verify as Gt}from"node:crypto";import{constants as Ye,promises as ae}from"node:fs";import we from"node:path";import{GeneratedSiteCapabilitiesSchema as Qt}from"@vcp-dev/contracts";var Xt=".vcp/portable-snapshot-proof.json",Ze=4*1024*1024,Yt=256*1024*1024,Zt=1e4,en=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function tt(e){try{if(!e.publicKey||!Ee(e.publicKey,256))return null;let t=Jt({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let n=we.join(e.projectRoot,Xt),s=await ae.lstat(n);if(!s.isFile()||s.isSymbolicLink()||s.size>Ze)return null;let o=JSON.parse(await ae.readFile(n,"utf8"));if(!G(o)||!re(o,["payload","signature"])||!Ee(o.payload,Ze)||!Ee(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!Gt(null,i,t,r))return null;let c=new TextDecoder("utf-8",{fatal:!0}).decode(i),d=JSON.parse(c);if(JSON.stringify(d)!==c||!G(d)||!re(d,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||d.kind!=="vcp-portable-snapshot-v1"||!G(d.manifest))return null;let a=d.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>Zt)return null;let u=Qt.safeParse(d.host_capabilities);if(!u.success||!Array.isArray(d.trusted_host_file_hashes)||d.trusted_host_file_hashes.length>512)return null;let l=new Map;for(let p of d.trusted_host_file_hashes){if(!G(p)||!re(p,["path","hash"])||typeof p.path!="string"||!tn(p.path)||!et(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||l.has(p.path))return null;l.set(p.path,p.hash)}let y=0,h=[],f=new Set;for(let p of a.files){if(!G(p)||!re(p,["path","hash","size_bytes"])||typeof p.path!="string"||!et(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||typeof p.size_bytes!="number"||!Number.isSafeInteger(p.size_bytes)||p.size_bytes<0||f.has(p.path)||(f.add(p.path),y+=p.size_bytes,y>Yt))return null;h.push({path:p.path,hash:p.hash,size_bytes:p.size_bytes})}let _=new Map;for(let p of h){let m=await nn(e.projectRoot,p.path,p.size_bytes);if(!m||`sha256:${zt("sha256").update(m).digest("hex")}`!==p.hash)return null;_.set(p.path,m)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:h},files:_},host_capabilities:u.data,trusted_host_file_hashes:l}}catch{return null}}function tn(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?lib\/utils\.ts$/u.test(e)}async function nn(e,t,n){let s=t.split("/"),o=e;for(let c of s.slice(0,-1)){o=we.join(o,c);let d=await ae.lstat(o);if(!d.isDirectory()||d.isSymbolicLink())return null}let i=we.join(o,s.at(-1)),r=await ae.open(i,Ye.O_RDONLY|Ye.O_NOFOLLOW);try{let c=await r.stat();if(!c.isFile()||c.size!==n)return null;let d=[],a=0,u=r.createReadStream({autoClose:!1});for await(let l of u){let y=l;if(a+=y.byteLength,a>n)return u.destroy(),null;d.push(y)}return a===n?Buffer.concat(d,a):null}finally{await r.close()}}function et(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!en.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Ee(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as yn,SiteEditPortableExportRequestSchema as Sn,SiteEditPortableExportResultSchema as _n,SiteEditPortableAssetRequestSchema as bn,SiteEditPortableAssetResultSchema as In,computeSiteEditCompositionKey as D}from"@vcp-dev/contracts";var En="127.0.0.1",wn=30218,xn="/__vcp/site-edit/bridge",ct=6*1024*1024,Rn=ct*2,kn=3e3,nt=50,Re=".vcp/current-snapshot.json",st="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function dt(e,t,n={}){let s=new ke(pt(t),e,!1,n);return s.start({listen:!1}),s}var ke=class{constructor(t,n=sn.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,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{Q.mkdirSync(C.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=Pe({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 mn({projectRoot:this.options.projectRoot,watch_dirs:Cn(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??nt,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=Pn(),n=On(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(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;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 s=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??cn)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,s?.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 s=vn(t.composition),o=this.getRuntime(),i=R(s);await o.initializeComposition(i);let c=o.getDocument(i).data;await this.recordRuntimeVersion(c.version,s);let d=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:c,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),s=R(t);await n.initializeComposition(s);let o=n.getDocument(s);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(R(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,R(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,R(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(R(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:R(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:R(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return it(s,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))}}async exportPortableBlock(t,n,s){let o=(m,I,j)=>({complete:!1,unresolved:[{code:m,path:I,message:j}]}),i=Sn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,c=R(n);if(r.target.composition.routeId!==c.routeId||r.target.composition.templateId!==c.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(c);let a=()=>{let m=this.getRuntime().getDocument(c).data;return{site_id:m.siteId,snapshot_id:m.snapshotId,document_version:m.version}},u=a();if(u.site_id!==r.site_id||u.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(u.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.dependencies.loadTrustedPortableSnapshot??(m=>tt({...m,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),y;try{y=await l({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!y)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let h=new Map([...y.snapshot.files].map(([m,I])=>[m,typeof I=="string"?I:new Uint8Array(I)])),f={...y,snapshot:{...y.snapshot,files:h}};if(!await oe(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let _=await dn({...r,...f,read_current_identity:a}),p=_n.safeParse(_);if(!p.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(p.data.complete&&(p.data.site_id!==r.site_id||p.data.base_snapshot_id!==r.base_snapshot_id||p.data.document_version!==r.document_version||p.data.target.blockKey!==r.target.blockKey||p.data.target.composition.routeId!==c.routeId||p.data.target.composition.templateId!==c.templateId||p.data.selection_ref.key!==r.selection_ref.key||p.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||p.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(p.data.complete){if(!await oe(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let m=a();if(this.options.snapshotId!==r.base_snapshot_id||m.site_id!==r.site_id||m.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(m.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}s?.(h)}return p.data}async exportPortableBlockAsset(t,n){let s=u=>({complete:!1,unresolved:[{code:u,path:"<asset>",message:"The selected local image could not be verified."}]}),o=bn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,c=await this.exportPortableBlock(i.request,n,u=>{r=u});if(!c.complete)return c;if(c.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let d=un({exported:c,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),a=In.safeParse(d);if(!a.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!a.data.complete)return a.data;if(!await oe(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let u=this.getRuntime().getDocument(R(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||u.siteId!==i.request.site_id||u.snapshotId!==i.request.base_snapshot_id||u.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return a.data}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.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 i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return it(i,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 s?this.executeWithReceipt(s,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 Ae("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 s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,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(s)}),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 s=await(this.dependencies.openHistoryStore??pn)(An({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let c=D(r);this.runtimeVersionFloors.set(c,Math.max(this.runtimeVersionFloors.get(c)??0,o))}this.createRuntime(s,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 s=n?D(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),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 s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??nt;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,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let n=t.some(ft)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!Kn(o));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let o of s)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=Q.readFileSync(C.join(this.options.projectRoot,Re),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Ce(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}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 s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}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=Tn(this.options.projectRoot),s=gn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(a=>({...a})),i=hn({files:n});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.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=>[D(a.context),a])),d=new Map(i.map(a=>[D(a.context),a]));if(this.runtime){for(let[a,u]of c){let l=d.get(a);(!l||l.entryFile!==u.entryFile)&&this.runtime.unregisterComposition(R(u.context))}for(let[a,u]of d){let l=c.get(a);(!l||l.entryFile!==u.entryFile)&&this.runtime.registerComposition(u.context,u.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=fn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=ln({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=D(o.context);if(!this.compositions.some(r=>D(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(D(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 ut(e){return pt(e)}function pt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:C.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??En,port:e.port??wn,path:e.path??xn,sessionKey:e.sessionKey??jn(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Cn(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 Tn(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!Q.existsSync(i))return;let r;try{r=Q.readdirSync(i,{withFileTypes:!0})}catch{return}for(let c of r){if(c.name.startsWith(".")&&c.name!==".vcp")continue;if(c.isDirectory()){if(s.has(c.name))continue;o(C.join(i,c.name));continue}if(!c.isFile())continue;let d=C.join(i,c.name),a="";try{a=Q.readFileSync(d,"utf8")}catch{}t.push({path:C.relative(e,d).replaceAll(C.sep,"/"),content:a})}};for(let i of n)o(C.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function vn(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 R(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function An(e){return C.join(C.resolve(e.root),Ce(e.siteId),Ce(e.snapshotId),Ae("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Ce(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ae("sha256").update(e).digest("hex").slice(0,32)}function Pn(){let e=globalThis;return e[st]??=new Map,e[st]}function On(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function it(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function Pe(e){let t=new an({maxPayload:ct,noServer:!0}),n=new WeakSet,s=i=>{new se({socket:new Te(i),engine:e.engine,validateOperationRequest:r=>yn.safeParse(r).success})},o=(i,r,c)=>{if(!Nn(i,e))return;let d=Bn(i,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(i),t.handleUpgrade(i,r,c,a=>{t.emit("connection",a,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}
|
|
5
|
-
`);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function Xn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var Zn="next",es="VCP_SITE_EDIT_ENGINE_IN_PROCESS",It="127.0.0.1",ts=3e3,ue="/__vcp/site-edit/bridge",Et="/__vcp/site-edit/health",ns="probe",ss="render",mt="/_error",pe="/__vcp/site-edit/client/",is=`${pe}auto-bootstrap.js`,wt='data-vcp-site-edit-bootstrap="true"',os=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],rs="@vcp-dev/site-edit-engine/webpack-loader",as=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,cs=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ds=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.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 ji(e={},t={}){let n=t.process??process,s=t.createServer??Me.createServer,o=t.attachBridgeServer??(n.env[es]==="1"?dt:Oe),i=t.loadNext??Ks,r=X.resolve(e.projectRoot??process.cwd()),c=e.host??It,d=e.port??Vs(n.env.PORT)??ts,a=e.bridgePath??ue,u=ms(a),l=Hs(),y=e.portableSnapshotPublicKey??n.env.VCP_PORTABLE_SNAPSHOT_PUBLIC_KEY,h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",f=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,_=await i(r),p=us(r),m=_({dev:!0,dir:r,hostname:c,port:d,...ps(p)}),I=m.getRequestHandler(),j=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",K=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Fs(r),z=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,B=z?.trim()?X.resolve(z):void 0,A=null,ee={launchId:Yn(),pid:process.pid,snapshotId:K},T=s((g,S)=>{ws({basePath:h,bridgePath:a,bridgeHealthPath:u,bridgeSessionKey:l,getBridgeHealth:()=>A?.getHealth()??vs(a),launch:ee,runRenderProbe:()=>ks(m),handle:I,request:g,response:S}).catch(E=>{console.error(E),S.headersSent||(S.statusCode=500),S.end("site edit preview request failed")})}),H=null,U=null,J=()=>U||(de(()=>n.off("SIGINT",M)),de(()=>n.off("SIGTERM",M)),de(()=>H?.()),H=null,de(()=>A?.stop()),A=null,U=Promise.allSettled([qs(T),zs(()=>m.close())]).then(()=>{}),U),M=()=>{J()};try{return await m.prepare(),A=o(T,{...f?{tenantId:f}:{},siteId:j,snapshotId:K,projectRoot:r,basePath:h,host:c,port:d,path:a,sessionKey:l,...y?{portableSnapshotPublicKey:y}:{},...B?{historyRoot:B}:{},onSnapshotIdChanged:g=>{ee.snapshotId=g}}),H=fs({server:T,bridgePath:a,handleUpgrade:m.getUpgradeHandler()}),n.on("SIGINT",M),n.on("SIGTERM",M),await A.whenReady?.(),await $s(T,d,c),{bundler:p,close:J,host:c,port:Js(T,d),server:T}}catch(g){throw await J(),g}}function us(e){let t=ls(e);return t&&hs(t)?"webpack":"turbopack"}function ps(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function ls(e){for(let t of os){let n=Z(e,t);if(q(n))return $(n,"utf8")}return null}function hs(e){return e.includes(rs)?!0:as.test(e)&&cs.some(t=>t.test(e))}function fs(e){let t=(n,s,o)=>{gs(n.url,e.bridgePath)||e.handleUpgrade(n,s,o).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function gs(e,t){return new URL(e??"/","http://localhost").pathname===t}function ms(e=ue){if(e===ue)return Et;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function ys(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??Ss()});return`<script type="module" ${wt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(is)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ss(){return{bridge:Ne("@vcp-dev/site-edit-bridge"),contracts:Ne("@vcp-dev/contracts"),engine:Ne("@vcp-dev/site-edit-engine")}}function Ne(e){let t=St(import.meta.url);try{let n=t.resolve(e),s=_s(n,e);if(!s)return;let o=JSON.parse($(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function _s(e,t){let n=X.parse(e).root,s=Y(e);for(;s&&s!==n;){let o=Z(s,"package.json");if(q(o))try{if(JSON.parse($(o,"utf8")).name===t)return o}catch{return}s=Y(s)}}function bs(e,t){if(e.includes(wt))return e;let n=ys(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function Ki(e,t=Y(bt(import.meta.url)),n=q){return xt(e,t,n)?.path??null}function xt(e,t=Y(bt(import.meta.url)),n=q){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(pe))return null;let o=s.slice(pe.length);if(!ds.has(o))return null;let i=Le(Us(t),o);if(_t(t)!=="src")return{path:i,requiresTranspile:!1};let r=Le(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Is(e,t){let n=xt(e.url);if(!n)return!1;if(!q(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await Es($(n.path,"utf8")):$(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function Es(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function ws({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:c,request:d,response:a}){if(xs(d.url,e)){a.statusCode=404,a.end();return}if(await Ts(d,a,n,o,i,r)||await Is(d,a))return;let u=As(d),l=Ps(d),y=u||l?Bs(a,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...i}}):()=>{};try{await c(d,a)}catch(h){throw y(),h}}function xs(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(s,"http://namespace.invalid").pathname,i=t.replace(/\/+$/,"");return(i&&(o===i||o.startsWith(i+"/"))?o.slice(i.length)||"/":o).startsWith("/.vcp")}function Rs(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 ks(e){let t=new Me.IncomingMessage(new gt);t.method="GET",t.url=mt,t.headers={host:It};let n=new Me.ServerResponse(t);n.assignSocket(new gt);try{return await e.renderToHTML(t,n,mt,{}),{verdict:"ok"}}catch(s){return Rs(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Cs(e){return new URL(e??"/","http://localhost").searchParams.get(ns)===ss}async function Ts(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let c=s(),d=Cs(e.url)?await i():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 vs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function As(e){return Os(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ps(e){return Ns(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Os(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(pe)||n===ue||n===Et)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function Ns(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 Bs(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),c=!1;s.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 u=yt(e,a,t);return u!==a&&!e.headersSent&&e.removeHeader("content-length"),i(u),n.length=0,c=!0,!0};return s.write=(a,u,l)=>c?(a!==void 0&&i(Be(a,He(u))),ce(u),ce(l),!0):(a!==void 0&&(n.push(Be(a,He(u))),d()),ce(u),ce(l),!0),s.end=(a,u,l)=>{let y=typeof a=="function"?void 0:a;if(c)return s.write=i,s.end=r,s.flushHeaders=o,y===void 0?typeof a=="function"?r(a):typeof u=="function"?r(u):typeof l=="function"?r(l):r():typeof u=="function"?r(y,u):typeof l=="function"?r(y,u,l):r(y,u);y!==void 0&&n.push(Be(y,He(u))),s.write=i,s.end=r,s.flushHeaders=o;let h=Buffer.concat(n),f=yt(e,h,t);f!==h&&!e.headersSent&&e.removeHeader("content-length");let _=typeof a=="function"?a:typeof u=="function"?u:typeof l=="function"?l:void 0;return _?r(f,_):r(f)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function yt(e,t,n){if(Ms(e,t))return Buffer.from(bs(t.toString("utf8"),n));if(n.patchNextDevChunk&&Ls(e)){let s=t.toString("utf8"),o=Ds(s);if(o!==s)return Buffer.from(o)}return t}function Hs(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Ms(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function Ls(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 Ds(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(i),t.handleUpgrade(i,r,c,a=>{t.emit("connection",a,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}Hn(i,e.sessionKey,()=>{s(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var Te=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===at.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Rn){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Nn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Bn(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=xe(e.headers["x-vcp-site-edit-key"]),o=lt(s,t.sessionKey),i=xe(e.headers.host),r=xe(e.headers.origin);return i&&!Mn(i,t.host,r)?null:r?Dn(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Hn(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},kn),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let d=k.parseMessage(c.toString());if(d.type!=="auth"||!lt(d.payload.key,t)){r();return}i(),e.readyState===at.OPEN&&e.send(k.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function lt(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&rn(n,s)}function Mn(e,t,n){let s=rt(e),o=rt(t);return s===o||ot(o)&&ot(s)&&(!n||ve(n,e))||Ln(o)&&(!n||ve(n,e))}function Ln(e){return e==="0.0.0.0"||e==="::"}function ot(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Dn(e,t,n){return n.includes(e)||(t?ve(e,t):!1)}function ve(e,t){try{return new URL(e).host===ht(t)}catch{return!1}}function rt(e){let t=ht(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function ht(e){return e.trim().toLowerCase()}function xe(e){return Array.isArray(e)?e[0]:e}function jn(){return on(32).toString("base64url")}function ft(e){let t=e.replaceAll("\\","/");return t===Re||t.endsWith(`/${Re}`)}function Kn(e){let t=e.replaceAll("\\","/");return ft(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var Vn="SITE_EDIT_ENGINE_UNAVAILABLE",$n=5e3,qn=1024,zn="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",Jn=3,Gn=10*6e4,Qn=1012;function Oe(e,t,n={}){let s=ut(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,c={options:r},d=n.maxHeapMb??Yn(process.env[zn])??qn,a=n.maxRestarts??Jn,u=n.restartWindowMs??Gn,l="starting",y,h=0,f=[],_=null,p=0,m=new Map,I=new Set,j,K,z=new Promise((g,S)=>{j=g,K=S});z.catch(()=>{});let B=g=>{let S=new Error(`VCP site edit preview bridge runtime is not ready: ${g}`);return S.code=Vn,S},A=g=>{for(let S of m.values())S.reject(g);m.clear()},ee=g=>{switch(g.type){case"ready":_=g.health,l==="starting"?(l="ready",j()):l==="restarting"&&(l="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":l==="starting"&&H(le(g.error));return;case"result":{let S=m.get(g.id);if(!S)return;m.delete(g.id),g.ok?S.resolve(g.value):S.reject(le(g.error));return}case"event":for(let S of I)try{S(g.event)}catch(E){console.warn(`[vcp-site-edit] engine event listener failed: ${E instanceof Error?E.message:String(E)}`)}return;case"health":_=g.health;return;case"snapshot-id-changed":c.options.snapshotId=g.next;try{o?.(g.next,g.previous)}catch(S){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${S instanceof Error?S.message:String(S)}`)}return}},T=()=>{let g=h+=1,S=n.workerUrl??new URL("./engine-worker.js",import.meta.url),E=new Fn(Xn(S),{workerData:c,resourceLimits:{maxOldGenerationSizeMb:d},...n.execArgv?{execArgv:n.execArgv}:{}});E.unref();let P=()=>g===h;E.on("message",v=>{P()&&ee(v)}),E.on("error",v=>{P()&&H(v instanceof Error?v:new Error(String(v)))}),E.on("exit",v=>{P()&&H(new Error(`engine worker exited with code ${v}`))}),y=E,n.onWorker?.(E)},H=g=>{if(l==="stopped"||l==="failed")return;if(A(B(g.message)),_=null,l==="starting"){l="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${g.message}`),K(g);return}let S=Date.now();for(;f.length>0&&S-f[0]>u;)f.shift();if(f.length>=a){l="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${a} restarts: ${g.message}`);return}f.push(S),l="restarting";for(let E of M.clients)E.close(Qn,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${f.length}/${a}): ${g.message}`),T()},U=(g,S)=>{if(l==="failed"||l==="stopped"||l==="restarting")return Promise.reject(B(l));let E=p+=1;return new Promise((P,v)=>{m.set(E,{resolve:P,reject:v});let kt={type:"call",id:E,method:g,args:S};y.postMessage(kt)})},J=Object.fromEntries(De.map(g=>[g,(...S)=>U(g,S)])),M=Pe({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...J,subscribe(g){return I.add(g),()=>I.delete(g)}}});return T(),{getHealth(){return l==="ready"&&_?_:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:_?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(l==="stopped")return;let g=l==="starting";l="stopped",M.stop(),g&&K(B("bridge stopped")),A(B("bridge stopped")),I.clear();let S=y,E={type:"stop"};S.postMessage(E);let P=setTimeout(()=>{S.terminate()},$n);P.unref(),S.once("exit",()=>clearTimeout(P))},whenReady(){return z},eventListeners:I}}function Xn(e){if(!e.pathname.endsWith(".ts"))return e;let t=Wn(Un(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 Yn(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var es="next",ts="VCP_SITE_EDIT_ENGINE_IN_PROCESS",It="127.0.0.1",ns=3e3,ue="/__vcp/site-edit/bridge",Et="/__vcp/site-edit/health",ss="probe",is="render",mt="/_error",pe="/__vcp/site-edit/client/",os=`${pe}auto-bootstrap.js`,wt='data-vcp-site-edit-bootstrap="true"',rs=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],as="@vcp-dev/site-edit-engine/webpack-loader",cs=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ds=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],us=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.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 Ki(e={},t={}){let n=t.process??process,s=t.createServer??Me.createServer,o=t.attachBridgeServer??(n.env[ts]==="1"?dt:Oe),i=t.loadNext??Us,r=X.resolve(e.projectRoot??process.cwd()),c=e.host??It,d=e.port??$s(n.env.PORT)??ns,a=e.bridgePath??ue,u=ys(a),l=Ms(),y=e.portableSnapshotPublicKey??n.env.VCP_PORTABLE_SNAPSHOT_PUBLIC_KEY,h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",f=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,_=await i(r),p=ps(r),m=_({dev:!0,dir:r,hostname:c,port:d,...ls(p)}),I=m.getRequestHandler(),j=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",K=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Vs(r),z=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,B=z?.trim()?X.resolve(z):void 0,A=null,ee={launchId:Zn(),pid:process.pid,snapshotId:K},T=s((g,S)=>{xs({basePath:h,bridgePath:a,bridgeHealthPath:u,bridgeSessionKey:l,getBridgeHealth:()=>A?.getHealth()??As(a),launch:ee,runRenderProbe:()=>Cs(m),handle:I,request:g,response:S}).catch(E=>{console.error(E),S.headersSent||(S.statusCode=500),S.end("site edit preview request failed")})}),H=null,U=null,J=()=>U||(de(()=>n.off("SIGINT",M)),de(()=>n.off("SIGTERM",M)),de(()=>H?.()),H=null,de(()=>A?.stop()),A=null,U=Promise.allSettled([zs(T),Js(()=>m.close())]).then(()=>{}),U),M=()=>{J()};try{return await m.prepare(),A=o(T,{...f?{tenantId:f}:{},siteId:j,snapshotId:K,projectRoot:r,basePath:h,host:c,port:d,path:a,sessionKey:l,...y?{portableSnapshotPublicKey:y}:{},...B?{historyRoot:B}:{},onSnapshotIdChanged:g=>{ee.snapshotId=g}}),H=gs({server:T,bridgePath:a,handleUpgrade:m.getUpgradeHandler()}),n.on("SIGINT",M),n.on("SIGTERM",M),await A.whenReady?.(),await qs(T,d,c),{bundler:p,close:J,host:c,port:Gs(T,d),server:T}}catch(g){throw await J(),g}}function ps(e){let t=hs(e);return t&&fs(t)?"webpack":"turbopack"}function ls(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function hs(e){for(let t of rs){let n=Z(e,t);if(q(n))return $(n,"utf8")}return null}function fs(e){return e.includes(as)?!0:cs.test(e)&&ds.some(t=>t.test(e))}function gs(e){let t=(n,s,o)=>{ms(n.url,e.bridgePath)||e.handleUpgrade(n,s,o).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function ms(e,t){return new URL(e??"/","http://localhost").pathname===t}function ys(e=ue){if(e===ue)return Et;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Ss(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??_s()});return`<script type="module" ${wt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(os)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function _s(){return{bridge:Ne("@vcp-dev/site-edit-bridge"),contracts:Ne("@vcp-dev/contracts"),engine:Ne("@vcp-dev/site-edit-engine")}}function Ne(e){let t=St(import.meta.url);try{let n=t.resolve(e),s=bs(n,e);if(!s)return;let o=JSON.parse($(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function bs(e,t){let n=X.parse(e).root,s=Y(e);for(;s&&s!==n;){let o=Z(s,"package.json");if(q(o))try{if(JSON.parse($(o,"utf8")).name===t)return o}catch{return}s=Y(s)}}function Is(e,t){if(e.includes(wt))return e;let n=Ss(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function Ui(e,t=Y(bt(import.meta.url)),n=q){return xt(e,t,n)?.path??null}function xt(e,t=Y(bt(import.meta.url)),n=q){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(pe))return null;let o=s.slice(pe.length);if(!us.has(o))return null;let i=Le(Ws(t),o);if(_t(t)!=="src")return{path:i,requiresTranspile:!1};let r=Le(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Es(e,t){let n=xt(e.url);if(!n)return!1;if(!q(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await ws($(n.path,"utf8")):$(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function ws(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function xs({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:c,request:d,response:a}){if(Rs(d.url,e)){a.statusCode=404,a.end();return}if(await vs(d,a,n,o,i,r)||await Es(d,a))return;let u=Ps(d),l=Os(d),y=u||l?Hs(a,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...i}}):()=>{};try{await c(d,a)}catch(h){throw y(),h}}function Rs(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(s,"http://namespace.invalid").pathname,i=t.replace(/\/+$/,"");return(i&&(o===i||o.startsWith(i+"/"))?o.slice(i.length)||"/":o).startsWith("/.vcp")}function ks(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 Cs(e){let t=new Me.IncomingMessage(new gt);t.method="GET",t.url=mt,t.headers={host:It};let n=new Me.ServerResponse(t);n.assignSocket(new gt);try{return await e.renderToHTML(t,n,mt,{}),{verdict:"ok"}}catch(s){return ks(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Ts(e){return new URL(e??"/","http://localhost").searchParams.get(ss)===is}async function vs(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let c=s(),d=Ts(e.url)?await i():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 As(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ps(e){return Ns(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Os(e){return Bs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ns(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(pe)||n===ue||n===Et)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function Bs(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 Hs(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),c=!1;s.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 u=yt(e,a,t);return u!==a&&!e.headersSent&&e.removeHeader("content-length"),i(u),n.length=0,c=!0,!0};return s.write=(a,u,l)=>c?(a!==void 0&&i(Be(a,He(u))),ce(u),ce(l),!0):(a!==void 0&&(n.push(Be(a,He(u))),d()),ce(u),ce(l),!0),s.end=(a,u,l)=>{let y=typeof a=="function"?void 0:a;if(c)return s.write=i,s.end=r,s.flushHeaders=o,y===void 0?typeof a=="function"?r(a):typeof u=="function"?r(u):typeof l=="function"?r(l):r():typeof u=="function"?r(y,u):typeof l=="function"?r(y,u,l):r(y,u);y!==void 0&&n.push(Be(y,He(u))),s.write=i,s.end=r,s.flushHeaders=o;let h=Buffer.concat(n),f=yt(e,h,t);f!==h&&!e.headersSent&&e.removeHeader("content-length");let _=typeof a=="function"?a:typeof u=="function"?u:typeof l=="function"?l:void 0;return _?r(f,_):r(f)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function yt(e,t,n){if(Ls(e,t))return Buffer.from(Is(t.toString("utf8"),n));if(n.patchNextDevChunk&&Ds(e)){let s=t.toString("utf8"),o=js(s);if(o!==s)return Buffer.from(o)}return t}function Ms(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Ls(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function Ds(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 js(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,[s,o])=>
|
|
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,[s,o])=>Ks(n,s,o),e)}function Ks(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 Be(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function He(e){return typeof e=="string"?e:void 0}function ce(e){typeof e=="function"&&e()}async function Us(e){let n=St(Z(e,"package.json"))(es);return n.default??n}function Ws(e){return _t(e)!=="src"?e:Le(Fs(e),"dist")}function Fs(e){return Rt(e)?X.posix.dirname(e):Y(e)}function Le(e,t){return Rt(e)?X.posix.join(e,t):Z(e,t)}function Rt(e){return e.includes("/")&&!e.includes("\\")}function Vs(e){let t=Z(e,".vcp/current-snapshot.json");if(!q(t))return"sandbox_worktree";try{let n=JSON.parse($(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 $s(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function qs(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function zs(e){return new Promise(t=>{e.close(()=>t())})}function de(e){try{e()}catch{}}function Js(e){try{return e()}catch(t){return Promise.reject(t)}}function Gs(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{gs as attachNextDevUpgradeHandler,Oe as attachSiteEditBridgeServerInWorker,ks as classifySiteEditRenderProbeError,Ss as createSiteEditAutoBootstrapHtmlSnippet,Is as injectSiteEditAutoBootstrap,Ts as isSiteEditRenderProbeRequested,js as patchNextFirefoxDevChunk,Os as prepareFirefoxNextDevChunkPatchRequest,Ps as prepareSiteEditHtmlInjectionRequest,ys as resolveSiteEditBridgeHealthPath,xt as resolveSiteEditClientAsset,Ui as resolveSiteEditClientAssetPath,ps as resolveSiteEditNextDevBundler,Cs as runSiteEditRenderProbe,Ki as startSiteEditNextDevServer,ws as transpileSiteEditClientSource};
|
|
@@ -82,7 +82,7 @@ export async function readVerifiedPortableSnapshot(input) {
|
|
|
82
82
|
if (!isRecord(item) ||
|
|
83
83
|
!exactKeys(item, ["path", "hash"]) ||
|
|
84
84
|
typeof item.path !== "string" ||
|
|
85
|
-
|
|
85
|
+
!isTrustedHostPath(item.path) ||
|
|
86
86
|
!safePath(item.path) ||
|
|
87
87
|
typeof item.hash !== "string" ||
|
|
88
88
|
!/^sha256:[a-f0-9]{64}$/u.test(item.hash) ||
|
|
@@ -145,6 +145,11 @@ export async function readVerifiedPortableSnapshot(input) {
|
|
|
145
145
|
return null;
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
|
+
function isTrustedHostPath(file) {
|
|
149
|
+
return (/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(file) ||
|
|
150
|
+
/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(file) ||
|
|
151
|
+
/^(?:src\/)?lib\/utils\.ts$/u.test(file));
|
|
152
|
+
}
|
|
148
153
|
async function readSnapshotFile(root, relative, expectedSize) {
|
|
149
154
|
const parts = relative.split("/");
|
|
150
155
|
let directory = root;
|