@vcp-dev/site-edit-bridge 0.11.40 → 0.11.42

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 CHANGED
@@ -1,4 +1,4 @@
1
- import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
1
+ import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/platform-shared/contracts";
2
2
  import { type SiteEditBridgeInitializeInput, type SiteEditHistoryStatus, type SiteEditBridgeRequestKind } from "./protocol.js";
3
3
  export type { SiteEditHistoryStatus } from "./protocol.js";
4
4
  type SiteEditBridgeCompositionInput = SiteEditCompositionSelector;
@@ -297,7 +297,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
297
297
  };
298
298
  resolution: {
299
299
  status: "resolved";
300
- value: import("@vcp-dev/contracts").SiteEditOperationValue;
300
+ value: import("@vcp-dev/platform-shared/contracts").SiteEditOperationValue;
301
301
  } | {
302
302
  status: "undefined";
303
303
  } | {
@@ -348,7 +348,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
348
348
  routeId: string;
349
349
  effectiveTemplateId?: string | undefined;
350
350
  };
351
- nodes: import("@vcp-dev/contracts").SiteEditSourceTreeNode[];
351
+ nodes: import("@vcp-dev/platform-shared/contracts").SiteEditSourceTreeNode[];
352
352
  totalFiles: number;
353
353
  defaultPath?: string | undefined;
354
354
  truncated?: {
@@ -1,4 +1,4 @@
1
- import type { SiteEditDynamicDataSummary, SiteEditRenderDocument } from "@vcp-dev/contracts";
1
+ import type { SiteEditDynamicDataSummary, SiteEditRenderDocument } from "@vcp-dev/platform-shared/contracts";
2
2
  export type CompactRenderDocument = {
3
3
  encoding: "segment-trie-v1";
4
4
  siteId: string;
@@ -1,6 +1,6 @@
1
1
  import type { Server as HttpServer } from "node:http";
2
2
  import { Worker } from "node:worker_threads";
3
- import type { SiteEditEvent } from "@vcp-dev/contracts";
3
+ import type { SiteEditEvent } from "@vcp-dev/platform-shared/contracts";
4
4
  import { type SiteEditBridgeHealth, type SiteEditBridgeServerOptions } from "./server.js";
5
5
  /** @internal 测试与运维调参:从源码起线程时换入口、加载 TS 运行器,或改重起预算。 */
6
6
  export type SiteEditBridgeWorkerDependencies = {
@@ -1,5 +1,5 @@
1
1
  import{parentPort as Ts,workerData as Os}from"node:worker_threads";function Z(t){let e=t&&typeof t=="object"?t:null,s=typeof e?.message=="string"&&e.message.length>0?e.message:String(t);return{name:typeof e?.name=="string"?e.name:"Error",message:s,...typeof e?.code=="string"&&e.code.length>0?{code:e.code}:{}}}import Qe from"node:http";import z from"node:fs";import{createHash as be,randomBytes as jt,timingSafeEqual as Wt}from"node:crypto";import k from"node:path";import{WebSocket as Xe,WebSocketServer as qt}from"ws";import{createPreviewSiteEditEngineRuntime as Jt,exportPortableBlockFromSnapshot as Qt,readPortableBlockLocalAssetChunk as Xt,openFileHistoryStore as Yt,resolveManagedPageTemplateComposition as Gt,scanSiteEditCompositionsFromFiles as Zt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as es,scanNextAppRouterRoutesFromFiles as ts}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ss}from"@vcp-dev/site-edit-engine/source-watcher";function Ee(t){if(t.pageBlocks!==void 0&&!it(t.pageBlocks))throw new Error("Invalid page block directory");let e=new Map,s=[],n=new Map,o=[],i=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(i.map((u,c)=>[u,c])),a=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(u=>({placementKey:u.placementKey,placementUnitKey:u.placementUnitKey,relation:u.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},p=t.entries.flatMap((u,c)=>u.dynamicDataSummary?[[c,u.dynamicDataSummary]]:[]),d=new Map(t.entries.map((u,c)=>[u.key,c])),h=[];for(let[u,c]of t.entries.entries()){let g=c.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){h.push([u,{kind:g.kind}]);continue}let S=g.siblingKeys.map(x=>{let R=d.get(x);if(R===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+x);return R});h.push([u,{kind:"source-siblings",siblingEntryIndexes:S}])}let l=u=>{let c=e.get(u);if(typeof c=="number")return c;let g=s.length;return s.push(u),e.set(u,g),g},f=u=>{let c=null;for(let g of lt(u)){let S=`${c??"root"}\0${g}`,x=n.get(S);if(typeof x=="number"){c=x;continue}let R=o.length;o.push([c,l(g)]),n.set(S,R),c=R}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:a,tokens:s,nodes:o,entries:t.entries.map(u=>{let c=u.pageCompositionUnitKey?r.get(u.pageCompositionUnitKey)??-1:-1;if(u.pageCompositionUnitKey&&c<0)throw new Error(`Render entry ${u.key} references unknown page composition unit ${u.pageCompositionUnitKey}`);return[f(u.key),nt(u.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...t.entries.every(u=>u.parentKey!==void 0)?{entryParentNodeIds:t.entries.map(u=>u.parentKey===null?null:f(u.parentKey))}:{},...p.length>0?{dynamicDataSummaries:p}:{},...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{}}}function nt(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function v(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Se(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function it(t){if(!Array.isArray(t))return!1;let e=new Map;for(let s of t){if(!v(s)||!N(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!$(s.blockKey,256)||!$(s.definitionKey,512)||!ot(s.rootRef)||!rt(s.source)||!at(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>$(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!B(s.placementUnitKey)||!ct(s.capabilities)||s.unavailableReasons!==void 0&&!dt(s.unavailableReasons)||e.has(s.blockKey))return!1;e.set(s.blockKey,s)}for(let s of t){let n=s.owner;for(let o of s.siblingBlockKeys){let i=e.get(o);if(!i)return!1;let r=i.owner;if(n.kind!==r.kind||n.key!==r.key)return!1}}return!0}function ot(t){return!v(t)||!N(t,["key","instanceIndex","instanceCount"])||!B(t.key)||t.instanceIndex!==void 0&&!Se(t.instanceIndex)||t.instanceCount!==void 0&&(!Se(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function rt(t){return v(t)&&N(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ut(t.file)&&B(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function at(t){return v(t)&&N(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&$(t.key,512)}function ct(t){return v(t)&&N(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function dt(t){return v(t)&&Object.entries(t).every(([e,s])=>B(e)&&v(s)&&N(s,["code","reason"])&&B(s.code)&&B(s.reason))}function ut(t){let e=pt(t),s=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||s.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let n=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(n)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(n)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(n)||n.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(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>t===i||t.startsWith(`${i}/`))||e}function pt(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let s=e[1].split("/"),n=s.some(r=>Ie(r)),o=n?s[0]:s.pop(),i=n?s.slice(1):s;if(n&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!ht(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Ie(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),p=Uint8Array.from(a,h=>h.charCodeAt(0)),d=new TextDecoder("utf-8",{fatal:!0}).decode(p);return d.length>0&&d.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(d)&&!d.startsWith(" ")&&!d.endsWith(" ")&&new TextEncoder().encode(d).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(d))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function Ie(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ht(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let s=decodeURIComponent(e);return s==="."||s===".."||/[/\\\x00-\x1f\x7f]/u.test(s)||s.startsWith(".vcp")}catch{return!0}})}function $(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function B(t){return typeof t=="string"&&t.length>0}function N(t,e){let s=new Set(e);return Object.keys(t).every(n=>s.has(n))}function lt(t){if(!t)return[];let e=[],s=0,n=we(t,s);if(n<0)return e.push(t),e;for(e.push(t.slice(0,n)),s=n;s<t.length;){if(n=we(t,s+(t.startsWith("::",s)?2:1)),n<0){e.push(t.slice(s));break}e.push(t.slice(s,n)),s=n}return e}function we(t,e){let s=t.indexOf("/",e),n=t.indexOf("::",e);return s<0?n:n<0?s:Math.min(s,n)}var L="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",re="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var C=class t{constructor(){}static parseMessage(e,s={}){let n=JSON.parse(e);if(!t.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(m(e)&&m(e.payload)){let s=typeof e.payload.id=="string"?e.payload.id:"unknown",n=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="export-portable-block"||e==="export-portable-block-asset"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,s={}){return!m(e)||typeof e.type!="string"?!1:e.type==="request"?mt(e.payload,s):e.type==="response"||e.type==="error"?m(e.payload)&&typeof e.payload.id=="string":e.type==="event"?m(e.payload)&&m(e.payload.event):e.type==="auth"?m(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?m(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&m(e.payload)&&e.payload.ok===!0}},j=class{constructor(e){this.options=e,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new oe,this.eventDispatcher=new ie(s=>{this.sendJson(s)}),this.unsubscribe=e.engine.subscribe(s=>{this.handleEngineEvent(s)}),e.socket.onmessage=s=>{let n=gt(s.data);if(n!==null){this.sendJson({type:"pong",payload:{id:n}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(e){try{let s=e;if(s.type!=="request")return;let n=s.payload,{id:o}=n;switch(n.kind){case"initialize-session":{let i=ee(n),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:n.kind,result:T({...a,data:{...a.data,document:ke(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(n),r=await this.options.engine.getDocument(i);this.sendResult(o,n.kind,wt(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(n),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,n.kind,T(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getObjectEditContext(n.key,i,n.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getClassNameSource(n.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!ae(n))throw new w("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.target.composition);if(b(i)!==b(r))throw new w(L,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,n.kind,a);return}case"export-portable-block-asset":{if(!Re(n))throw new w("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.request.target.composition);if(b(i)!==b(r))throw new w(L,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,n.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(n),r=T(await this.options.engine.resolveSourceLocation({key:n.key,composition:i}),i);this.sendResult(o,n.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(n.request),r=await this.resolveWireContext(n);if(b(i)!==b(r))throw new w(L,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(n.request,i);if(n.kind==="get-operation-result"){this.sendResult(o,n.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,n.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.composition);if(b(i)!==b(r))throw new w(L,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:U(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(n),r=n.request;if(r){let p=await this.resolveAndAssert(r.composition);if(r.kind!==n.kind||b(i)!==b(p))throw new w(L,"History request does not match its cursor operation.")}let a=r?{...r,composition:U(i)}:void 0;await this.handleBufferedOperation(o,n.kind,()=>n.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(s){let n=C.extractRequestInfo(e);this.sendJson({type:"error",payload:{...n,message:ne(s),code:se(s)}})}}async resolve(e){return this.options.engine.resolveComposition(e)}async resolveAndAssert(e){let s=await this.resolve(e),n=this.session.activeComposition;if(!n)throw new w(re,"Initialize a composition session before issuing this request.");if(b(n)!==b(s.context))throw new w(L,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(e){let s=ee(e);return this.resolveAndAssert(s)}async resolveOperationWireContext(e){let s=St(e);return this.resolveAndAssert(s)}activateSession(e){this.session.activeComposition=e,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(b(e))}async normalizeOperationRequest(e,s){let n={...e,composition:U(s)};if(n.target.kind==="route"){let o=n.target,i=ee(o),r=await this.resolveAndAssert(i);n.target={...o,composition:U(r)}}return n}handleEngineEvent(e){let s=e?.composition;if(!bt(s))return;let n=b(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(e),e.type==="site-edit.graph.invalidated"&&n===It(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(e,s,n){this.sendJson({type:"response",payload:{id:e,kind:s,result:n}})}async handleRawMessage(e){try{await this.handleMessage(C.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=Et(e);this.sendJson({type:"error",payload:{...n,message:ne(s),code:se(s)}})}}sendJson(e){this.options.socket.send(C.stringifyMessage(e))}async handleBufferedOperation(e,s,n){this.eventDispatcher.beginBuffering();try{let o=await n();this.sendResult(e,s,o)}catch(o){this.sendJson({type:"error",payload:{id:e,kind:s,message:ne(o),code:se(o)}})}finally{this.eventDispatcher.flush()}}},ft=256;function gt(t){if(t.length>ft||!t.includes('"ping"'))return null;try{let e=JSON.parse(t);return m(e)&&e.type==="ping"&&m(e.payload)&&typeof e.payload.id=="string"?e.payload.id:null}catch{return null}}var w=class extends Error{constructor(e,s){super(s),this.code=e,this.name="BridgeProtocolError"}},ie=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let s={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(s=>this.send(s))}},oe=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await e()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function mt(t,e){if(!m(t)||typeof t.id!="string"||!C.isRequestKind(t.kind))return!1;let s=O(t.composition);switch(t.kind){case"initialize-session":return s&&(t.mutationContext===void 0||te(t.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof t.key=="string"&&s&&Ce(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&s;case"get-history-status":return s;case"get-source-tree":return s;case"get-source-file":return typeof t.path=="string"&&s;case"export-portable-block":return ae(t);case"export-portable-block-asset":return Re(t);case"execute":case"get-operation-result":return s&&_t(t.request)&&(t.request.mutationContext===void 0||te(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return s&&xe(t.request);case"undo":case"redo":return s&&(t.request===void 0||xe(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||te(t.mutationContext))}}function ae(t){if(!O(t.composition)||!Object.keys(t).every(s=>["id","kind","composition","request"].includes(s))||!m(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(s=>["export_schema_version","site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(s))||e.export_schema_version!==2||typeof e.site_id!="string"||typeof e.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(e.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(e.base_snapshot_id)||typeof e.document_version!="number"||!Number.isSafeInteger(e.document_version)||e.document_version<0||!m(e.target)||e.target.kind!=="page-block"||typeof e.target.blockKey!="string"||!e.target.blockKey.length||e.target.blockKey.length>256||!Object.keys(e.target).every(s=>["kind","composition","blockKey"].includes(s))||!O(e.target.composition)||e.target.composition.routeId!==t.composition.routeId||e.target.composition.templateId!==t.composition.templateId||e.selection_ref===void 0||!Ce(e.selection_ref)||e.cms_schema_proofs!==void 0&&!yt(e.cms_schema_proofs))}function yt(t){if(!Array.isArray(t)||t.length>16||!Reflect.ownKeys(t).every(e=>e==="length"||typeof e=="string"&&/^(0|[1-9][0-9]*)$/u.test(e)&&Number(e)<t.length))return!1;for(let e=0;e<t.length;e++){let s=Object.getOwnPropertyDescriptor(t,String(e));if(!s||!("value"in s))return!1;let n=s.value;if(!m(n)||!Reflect.ownKeys(n).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(n,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function Re(t){if(!Object.keys(t).every(s=>["id","kind","composition","request"].includes(s))||!m(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(s=>["request","snapshot_digest","asset_key","offset","capture_id"].includes(s))||!ae({id:t.id,kind:"export-portable-block",composition:t.composition,request:e.request})||typeof e.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.snapshot_digest)||typeof e.asset_key!="string"||!/^asset-[a-f0-9]{64}$/u.test(e.asset_key)||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0||e.capture_id!==void 0&&(typeof e.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)))}function xe(t){return m(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&O(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function Ce(t){if(t===void 0)return!0;if(!m(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,s=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof e=="number"&&typeof s=="number"&&e>=s?!1:Object.keys(t).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function _t(t){return m(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&O(t.composition)&&typeof t.kind=="string"&&m(t.target)&&(t.target.kind!=="route"||O(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&m(t.params)}function O(t){return m(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function bt(t){return m(t)&&typeof t.routeId=="string"&&(t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string")}function ee(t){if(O(t.composition))return t.composition;throw new w(re,"A composition selector is required for this request.")}function St(t){if(m(t)&&O(t.composition))return t.composition;throw new w(re,"A composition selector is required for execute.")}function U(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function It(t){return t.activeComposition?b(t.activeComposition):null}function b(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function T(t,e){return m(t)&&t.ok===!0?{...t,composition:e}:t}function wt(t,e){return!m(t)||t.ok!==!0?t:{...t,...e?{composition:e}:{},data:ke(t.data)}}function ke(t){let e=t;return Ee(e.routeId?e:{...e,routeId:e.composition.routeId})}function m(t){return typeof t=="object"&&t!==null}function te(t){return m(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}function se(t){if(!(!m(t)||typeof t.code!="string"||t.code.length===0))return t.code}function ne(t){return t instanceof Error||m(t)&&typeof t.message=="string"&&t.message.length>0?t.message:"Unknown websocket operation failure"}function Et(t){try{return C.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var W=class{constructor(){this.tail=Promise.resolve()}run(e){let s=this.tail.then(e,e);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as ve}from"node:crypto";import{constants as Pe,promises as ce}from"node:fs";import Be from"node:path";import{createHash as xt}from"node:crypto";var q=Buffer.from(['/// <reference types="next" />','/// <reference types="next/image-types/global" />','import "./.next/types/routes.d.ts";','import "./.next/types/root-params.d.ts";',"","// NOTE: This file should not be edited","// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.",""].join(`
2
- `)),Ae=Buffer.from(q.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Te=t=>`sha256:${xt("sha256").update(t).digest("hex")}`,Rt=Te(q),Ct=Te(Ae);function K(t,e,s){return t==="next-env.d.ts"&&e===q.byteLength&&s===Rt?Ae.byteLength:null}function J(t){return K(t.file,t.expectedSize,t.expectedDigest)===t.actualSize&&t.actualDigest===Ct}function Oe(){return Uint8Array.from(q)}var Ne=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Le=64;async function Q(t,e){try{if(!e.size)return!1;for(let[i,r]of e)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||Ne.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>Le||++s>e.size*Le+1)return!1;let a=await ce.readdir(Be.join(t,i),{withFileTypes:!0});for(let p of a){let d=i?`${i}/${p.name}`:p.name;if(!i&&Ne.has(p.name))continue;if(p.isDirectory()){if(!await o(d,r+1))return!1;continue}if(!p.isFile())return!1;let h=e.get(d);if(h===void 0||n.has(d))return!1;n.add(d);let l=Be.join(t,d),f=await ce.lstat(l),u=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${ve("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==u&&f.size!==K(d,u,c))return!1;let g=ve("sha256"),S=await ce.open(l,Pe.O_RDONLY|Pe.O_NOFOLLOW);try{let R=await S.stat();if(!R.isFile()||R.size!==f.size)return!1;let y=0,_=S.createReadStream({autoClose:!1});for await(let A of _){if(y+=A.byteLength,y>f.size)return _.destroy(),!1;g.update(A)}if(y!==f.size)return!1}finally{await S.close()}let x=`sha256:${g.digest("hex")}`;if((f.size!==u||x!==c)&&!J({file:d,expectedSize:u,expectedDigest:c,actualSize:f.size,actualDigest:x}))return!1}return!0};return await o("",0)&&n.size===e.size}catch{return!1}}import{createHash as Ke}from"node:crypto";import{constants as Me,promises as Y}from"node:fs";import de from"node:path";import{GeneratedSiteCapabilitiesSchema as kt}from"@vcp-dev/contracts";var At=".vcp/portable-snapshot-proof.json",He=4*1024*1024,Tt=256*1024*1024,Ot=1e4,vt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function Fe(t){try{let e=de.join(t.projectRoot,At),s=await Y.lstat(e);if(!s.isFile()||s.isSymbolicLink()||s.size>He)return null;let n=JSON.parse(await Y.readFile(e,"utf8"));if(!F(n)||!X(n,["payload"])||!Nt(n.payload,He))return null;let o=Buffer.from(n.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!F(r)||!X(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!F(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==t.site_id||a.snapshot_id!==t.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>Ot)return null;let p=kt.safeParse(r.host_capabilities);if(!p.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of r.trusted_host_file_hashes){if(!F(c)||!X(c,["path","hash"])||typeof c.path!="string"||!Pt(c.path)||!De(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||d.has(c.path))return null;d.set(c.path,c.hash)}let h=0,l=[],f=new Set;for(let c of a.files){if(!F(c)||!X(c,["path","hash","size_bytes"])||typeof c.path!="string"||!De(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||f.has(c.path)||(f.add(c.path),h+=c.size_bytes,h>Tt))return null;l.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let u=new Map;for(let c of l){let g=await Bt(t.projectRoot,c.path,c.size_bytes,c.hash);if(!g||`sha256:${Ke("sha256").update(g).digest("hex")}`!==c.hash)return null;u.set(c.path,g)}return{snapshot:{site_id:t.site_id,snapshot_id:t.base_snapshot_id,manifest:{version:1,site_id:t.site_id,snapshot_id:t.base_snapshot_id,created_at:a.created_at,files:l},files:u},host_capabilities:p.data,trusted_host_file_hashes:d}}catch{return null}}function Pt(t){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?lib\/utils\.ts$/u.test(t)}async function Bt(t,e,s,n){let o=e.split("/"),i=t;for(let p of o.slice(0,-1)){i=de.join(i,p);let d=await Y.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let r=de.join(i,o.at(-1)),a=await Y.open(r,Me.O_RDONLY|Me.O_NOFOLLOW);try{let p=await a.stat(),d=K(e,s,n);if(!p.isFile()||p.size!==s&&p.size!==d)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let c of f){let g=c;if(l+=g.byteLength,l>p.size)return f.destroy(),null;h.push(g)}if(l!==p.size)return null;let u=Buffer.concat(h,l);return l===s?u:J({file:e,expectedSize:s,expectedDigest:n,actualSize:l,actualDigest:`sha256:${Ke("sha256").update(u).digest("hex")}`})?Oe():null}finally{await a.close()}}function De(t){let e=t.split("/");return t.length>0&&t.length<=1024&&!t.startsWith("/")&&!/[\\\0]/u.test(t)&&!vt.has(e[0])&&e.every(s=>s&&s!=="."&&s!=="..")}function F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function X(t,e){return Object.keys(t).length===e.length&&e.every(s=>Object.hasOwn(t,s))}function Nt(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{createHash as Lt}from"node:crypto";import Mt from"node:dns/promises";import Ht from"node:http";import Dt from"node:https";import{isIP as M}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as ue,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as pe}from"@vcp-dev/contracts";var I=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function ze(t){if(M(t)===4){let[e,s]=t.split(".").map(Number);return!(e===0||e===10||e===127||e>=224||e===100&&s>=64&&s<=127||e===169&&s===254||e===172&&s>=16&&s<=31||e===192&&[0,168].includes(s)||e===198&&[18,19,51].includes(s)||e===203&&s===0)}return M(t)===6&&/^[23]/u.test(t)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(t)}function he(t){let e=new URL(t),s=e.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.port||e.hash||s==="localhost"||!s.includes(".")&&!M(s)||/\.(?:internal|localhost|local)$/iu.test(s)||M(s)&&!ze(s))throw I();return e}function Ve(t){let e=s=>s.every((n,o)=>t[o]===n);return e([137,80,78,71,13,10,26,10])?"image/png":e([255,216,255])?"image/jpeg":e([71,73,70,56,55,97])||e([71,73,70,56,57,97])?"image/gif":e([82,73,70,70])&&Buffer.from(t.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function Kt(t,e){let s=()=>{};try{return await Promise.race([t,new Promise((n,o)=>{s=()=>o(I()),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})])}finally{e.removeEventListener("abort",s)}}async function Ft(t,e){let s=AbortSignal.any([e,AbortSignal.timeout(15e3)]),n=he(t);for(let o=0;o<=3;o++){s.throwIfAborted();let i=n.hostname.replace(/^\[|\]$/gu,""),r=M(i)?[{address:i,family:M(i)}]:await Kt(Mt.lookup(i,{all:!0}),s);if(s.throwIfAborted(),!r.length||r.some(({address:d})=>!ze(d)))throw I();let a=r.find(d=>d.family===4)??r[0],p=await new Promise((d,h)=>{(n.protocol==="https:"?Dt:Ht).get(n,{agent:!1,signal:s,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,u,c)=>{u.all?c(null,[{address:a.address,family:a.family}]):c(null,a.address,a.family)}},d).on("error",h)});try{let d=p.statusCode??0;if([301,302,303,307,308].includes(d)){if(!p.headers.location||o===3)throw I();let g=he(new URL(p.headers.location,n).href);if(n.protocol==="https:"&&g.protocol!=="https:")throw I();n=g;continue}let h=p.headers["content-length"];if(d!==200||p.headers["content-encoding"]&&p.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>pe))throw I();let l=[],f=0;for await(let g of p){let S=Buffer.from(g);if(f+=S.length,f>pe)throw I();l.push(S)}if(!f||h!==void 0&&Number(h)!==f)throw I();let u=Buffer.concat(l,f),c=Ve(u);if(!c||p.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==c)throw I();return{bytes:u,mime_type:c}}finally{p.destroy()}}throw I()}var G=class{constructor(e=Ft){this.download=e,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(e,s){let n=s.asset_catalog.filter(u=>u.asset_key===e.asset_key),o=n[0];if(this.controller.signal.aborted||e.snapshot_digest!==s.snapshot_digest||n.length!==1||o?.origin.kind!=="remote"||!e.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%ue)throw I();let i=o.origin.url;he(i);let r=JSON.stringify([e.request,e.snapshot_digest,e.asset_key,e.capture_id,i]),a=this.entries.get(r);if(!a){if(e.offset||this.pending.has(r)||this.pending.size>=2||this.entries.size>=16)throw I();this.pending.add(r);try{let u=await this.download(i,this.controller.signal);if(this.controller.signal.aborted||!u.bytes.length||u.bytes.length>pe||Ve(u.bytes)!==u.mime_type||[...this.entries.values()].reduce((g,S)=>g+S.image.bytes.length,u.bytes.length)>64*1024*1024)throw I();let c=setTimeout(()=>this.remove(r),6e4);c.unref(),a={image:u,timer:c},this.entries.set(r,a)}finally{this.pending.delete(r)}}let{bytes:p,mime_type:d}=a.image;if(e.offset>=p.length)throw I();let h=Lt("sha256").update(p).digest("hex"),l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[d],f={complete:!0,snapshot_digest:e.snapshot_digest,asset_key:e.asset_key,path:`public/__portable_remote__/${h}.${l}`,mime_type:d,byte_size:p.length,digest_sha256:h,offset:e.offset,data_base64:Buffer.from(p.subarray(e.offset,e.offset+ue)).toString("base64")};return e.offset+ue>=p.length&&this.remove(r),f}remove(e){let s=this.entries.get(e);s&&clearTimeout(s.timer),this.entries.delete(e)}dispose(){this.controller.abort();for(let e of this.entries.keys())this.remove(e)}};import{PortableCmsSchemaEnvelopeSchema as zt,PortableCmsSchemaStatementSchema as Vt}from"@vcp-dev/contracts";var $t=3e4;function $e(t){try{let e=zt.safeParse(t.proof);if(!e.success||!Ut(e.data.payload,262144))return null;let s=Buffer.from(e.data.payload,"base64url"),n=new TextDecoder("utf-8",{fatal:!0}).decode(s),o=JSON.parse(n);if(JSON.stringify(o)!==n)return null;let i=Vt.safeParse(o),r=t.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==t.site_id||i.data.base_snapshot_id!==t.base_snapshot_id||i.data.issued_at>r+$t||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Ut(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{SiteEditOperationRequestSchema as ns,SiteEditPortableExportRequestSchema as is,SiteEditPortableExportResultSchema as os,SiteEditPortableAssetRequestSchema as rs,SiteEditPortableAssetResultSchema as as,computeSiteEditCompositionKey as P}from"@vcp-dev/contracts";var cs="127.0.0.1",ds=30218,us="/__vcp/site-edit/bridge",Ye=6*1024*1024,ps=Ye*2,hs=3e3,Ue=50,fe=".vcp/current-snapshot.json",je="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var ge=class{constructor(e,s=Qe.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=e,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new W,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,this.portableRemoteAssets=new G}start(e={}){if(!this.isStarted){this.stopping=!1;try{z.mkdirSync(k.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(s){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${s instanceof Error?s.message:String(s)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let s=Ss({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=s.stop}this.stopWatching=new ss({projectRoot:this.options.projectRoot,watch_dirs:fs(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Ue,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:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=_s(),s=bs(this.options);e.get(s)===this&&e.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{e(s)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(e,s=null){let n=this.runtime;this.activeHistoryStore=e??null;let o=(this.dependencies.createRuntime??Jt)({...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)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=ms(e.composition),o=this.getRuntime(),i=E(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let p=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:p}}}),getDocument:async e=>{let s=this.getRuntime(),n=E(e);await s.initializeComposition(n);let o=s.getDocument(n);return await this.recordRuntimeVersion(o.data.version,e),{...o,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(E(e)),getObjectEditContext:async(e,s,n)=>this.getRuntime().getObjectEditContext(e,E(s),n),getClassNameSource:async(e,s)=>this.getRuntime().getClassNameSource(e,E(s)),getSourceTree:async e=>this.getRuntime().getSourceTree(E(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:E(e.composition)}),exportPortableBlock:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(e,s)),exportPortableBlockAsset:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(e,s)),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:E(e.composition)}),execute:(e,s)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return We(n,e);let o=await this.getRuntime().executeOperation(e);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:e=>this.readOperationReceipt(e),getHistoryOperationResult:e=>this.readOperationReceipt(e),undo:(e,s)=>this.runHistoryWithReceipt("undo",e,s),redo:(e,s)=>this.runHistoryWithReceipt("redo",e,s),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}verifyCmsSchemaProofs(e){let s=[];for(let n of e.cms_schema_proofs??[]){let o=$e({proof:n,site_id:e.site_id,base_snapshot_id:e.base_snapshot_id});if(!o)return null;s.push(o)}return s}async exportPortableBlock(e,s,n){let o=(_,A,st)=>({complete:!1,unresolved:[{code:_,path:A,message:st}]}),i=is.safeParse(e);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=E(s);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.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(a);let d=()=>{let _=this.getRuntime().getDocument(a).data;return{site_id:_.siteId,snapshot_id:_.snapshotId,document_version:_.version}},h=d();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(_=>Fe({..._,projectRoot:this.options.projectRoot})),u;try{u=await f({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(!u)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...u.snapshot.files].map(([_,A])=>[_,typeof A=="string"?A:new Uint8Array(A)])),g={...u,snapshot:{...u.snapshot,files:c}};if(!await Q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:S,...x}=r,R=await Qt({...x,...g,trusted_cms_schemas:l,read_current_identity:d}),y=os.safeParse(R);if(!y.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(y.data.complete&&(y.data.site_id!==r.site_id||y.data.base_snapshot_id!==r.base_snapshot_id||y.data.document_version!==r.document_version||y.data.target.blockKey!==r.target.blockKey||y.data.target.composition.routeId!==a.routeId||y.data.target.composition.templateId!==a.templateId||y.data.selection_ref.key!==r.selection_ref.key||y.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||y.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(y.data.complete||y.data.cms_candidates){if(!await Q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=d();if(this.options.snapshotId!==r.base_snapshot_id||_.site_id!==r.site_id||_.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(_.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.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");y.data.complete&&n?.(c)}return y.data}async exportPortableBlockAsset(e,s){let n=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=rs.safeParse(e);if(!o.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,s,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!r)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let p=a.asset_catalog.find(l=>l.asset_key===i.asset_key),d;try{d=p?.origin.kind==="remote"?await this.portableRemoteAssets.read(i,a):Xt({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,asset_key:i.asset_key,offset:i.offset})}catch{return n("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=as.safeParse(d);if(!h.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await Q(this.options.projectRoot,r))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(E(s)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||l.siteId!==i.request.site_id||l.snapshotId!==i.request.base_snapshot_id||l.version!==i.request.document_version)return n("DOCUMENT_VERSION_STALE")}catch{return n("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?h.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(e,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==e||n.composition.routeId!==s.routeId||n.composition.templateId!==s.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 We(i,void 0,s);let r=await this.getRuntime()[e]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??s),r.composition?r:{...r,composition:s}});return n?this.executeWithReceipt(n,o):o()}isActiveReceiptIdentity(e){return"request_id"in e?e.site_id===this.options.siteId&&e.base_snapshot_id===this.options.snapshotId:e.siteId===this.options.siteId&&e.baseSnapshotId===this.options.snapshotId}operationReceiptKey(e){return"request_id"in e?JSON.stringify([e.site_id,e.base_snapshot_id,"history",e.request_id]):JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return be("sha256").update(JSON.stringify(e)).digest("hex")}readOperationReceipt(e){if(!this.isActiveReceiptIdentity(e))return null;let s=this.operationReceipts.get(this.operationReceiptKey(e));return s?.fingerprint===this.operationFingerprint(e)?s.result:null}executeWithReceipt(e,s){if(!this.isActiveReceiptIdentity(e))return s();let n=this.operationReceiptKey(e),o=this.operationFingerprint(e),i=this.operationReceipts.get(n);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:s(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,p]of this.operationReceipts){if(this.operationReceipts.size<=256)break;p.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??Yt)(ys({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let o=n.readDocumentVersion?await n.readDocumentVersion():0,i=this.versionCheckpoints.get(n);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(n,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=P(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,e)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e,s){let n=s?P(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,e));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??e:e,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,p=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=p,this.versionPersistence=p,p}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Ue;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let s=e.some(tt)?this.scheduleSnapshotIdentityAdvance():!1,n=e.filter(o=>!As(o));if(!(n.length===0&&!s)&&this.refreshCompositions(!1))for(let o of n)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=z.readFileSync(k.join(this.options.projectRoot,fe),"utf8"),s=JSON.parse(e),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||me(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let o=await this.bindHistorySession(e);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=s,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${s}: ${o instanceof Error?o.message:String(o)}`);return}let n=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:e,previousSnapshotId:s,at:n};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,s)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(e=!1){try{let s=gs(this.options.projectRoot),n=ts(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),i=Zt({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[P(d.context),d])),p=new Map(i.map(d=>[P(d.context),d]));if(this.runtime){for(let[d,h]of a){let l=p.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(E(h.context))}for(let[d,h]of p){let l=a.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=s,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(s){let n=s instanceof Error?s:new Error(String(s));if(this.compositionResolutionError=n,e)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=es(e.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let n=this.routes.find(r=>r.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let o=Gt({selector:{routeId:s,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=P(o.context);if(!this.compositions.some(r=>P(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let s=this.runtimeVersionFloors.get(P(e.context));return s===void 0?[]:[{composition:e.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Ge(t){let e=new ge(ls(t),Qe.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function ls(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:k.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??cs,port:t.port??ds,path:t.path??us,sessionKey:t.sessionKey??ks(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function fs(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function gs(t){let e=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!z.existsSync(i))return;let r;try{r=z.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(k.join(i,a.name));continue}if(!a.isFile())continue;let p=k.join(i,a.name),d="";try{d=z.readFileSync(p,"utf8")}catch{}e.push({path:k.relative(t,p).replaceAll(k.sep,"/"),content:d})}};for(let i of s)o(k.join(t,i));return e.sort((i,r)=>i.path.localeCompare(r.path))}function ms(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function E(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function ys(t){return k.join(k.resolve(t.root),me(t.siteId),me(t.snapshotId),be("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function me(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:be("sha256").update(t).digest("hex").slice(0,32)}function _s(){let t=globalThis;return t[je]??=new Map,t[je]}function bs(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function We(t,e,s){let n=s??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!n)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:n,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:n,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ss(t){let e=new qt({maxPayload:Ye,noServer:!0}),s=new WeakSet,n=i=>{new j({socket:new ye(i),engine:t.engine,validateOperationRequest:r=>ns.safeParse(r).success})},o=(i,r,a)=>{if(!Is(i,t))return;let p=ws(i,t);if(!p){r.write(`HTTP/1.1 401 Unauthorized\r
2
+ `)),Ae=Buffer.from(q.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Te=t=>`sha256:${xt("sha256").update(t).digest("hex")}`,Rt=Te(q),Ct=Te(Ae);function K(t,e,s){return t==="next-env.d.ts"&&e===q.byteLength&&s===Rt?Ae.byteLength:null}function J(t){return K(t.file,t.expectedSize,t.expectedDigest)===t.actualSize&&t.actualDigest===Ct}function Oe(){return Uint8Array.from(q)}var Ne=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Le=64;async function Q(t,e){try{if(!e.size)return!1;for(let[i,r]of e)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||Ne.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>Le||++s>e.size*Le+1)return!1;let a=await ce.readdir(Be.join(t,i),{withFileTypes:!0});for(let p of a){let d=i?`${i}/${p.name}`:p.name;if(!i&&Ne.has(p.name))continue;if(p.isDirectory()){if(!await o(d,r+1))return!1;continue}if(!p.isFile())return!1;let h=e.get(d);if(h===void 0||n.has(d))return!1;n.add(d);let l=Be.join(t,d),f=await ce.lstat(l),u=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${ve("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==u&&f.size!==K(d,u,c))return!1;let g=ve("sha256"),S=await ce.open(l,Pe.O_RDONLY|Pe.O_NOFOLLOW);try{let R=await S.stat();if(!R.isFile()||R.size!==f.size)return!1;let y=0,_=S.createReadStream({autoClose:!1});for await(let A of _){if(y+=A.byteLength,y>f.size)return _.destroy(),!1;g.update(A)}if(y!==f.size)return!1}finally{await S.close()}let x=`sha256:${g.digest("hex")}`;if((f.size!==u||x!==c)&&!J({file:d,expectedSize:u,expectedDigest:c,actualSize:f.size,actualDigest:x}))return!1}return!0};return await o("",0)&&n.size===e.size}catch{return!1}}import{createHash as Ke}from"node:crypto";import{constants as Me,promises as Y}from"node:fs";import de from"node:path";import{GeneratedSiteCapabilitiesSchema as kt}from"@vcp-dev/platform-shared/contracts";var At=".vcp/portable-snapshot-proof.json",He=4*1024*1024,Tt=256*1024*1024,Ot=1e4,vt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function Fe(t){try{let e=de.join(t.projectRoot,At),s=await Y.lstat(e);if(!s.isFile()||s.isSymbolicLink()||s.size>He)return null;let n=JSON.parse(await Y.readFile(e,"utf8"));if(!F(n)||!X(n,["payload"])||!Nt(n.payload,He))return null;let o=Buffer.from(n.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!F(r)||!X(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!F(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==t.site_id||a.snapshot_id!==t.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>Ot)return null;let p=kt.safeParse(r.host_capabilities);if(!p.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of r.trusted_host_file_hashes){if(!F(c)||!X(c,["path","hash"])||typeof c.path!="string"||!Pt(c.path)||!De(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||d.has(c.path))return null;d.set(c.path,c.hash)}let h=0,l=[],f=new Set;for(let c of a.files){if(!F(c)||!X(c,["path","hash","size_bytes"])||typeof c.path!="string"||!De(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||f.has(c.path)||(f.add(c.path),h+=c.size_bytes,h>Tt))return null;l.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let u=new Map;for(let c of l){let g=await Bt(t.projectRoot,c.path,c.size_bytes,c.hash);if(!g||`sha256:${Ke("sha256").update(g).digest("hex")}`!==c.hash)return null;u.set(c.path,g)}return{snapshot:{site_id:t.site_id,snapshot_id:t.base_snapshot_id,manifest:{version:1,site_id:t.site_id,snapshot_id:t.base_snapshot_id,created_at:a.created_at,files:l},files:u},host_capabilities:p.data,trusted_host_file_hashes:d}}catch{return null}}function Pt(t){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?lib\/utils\.ts$/u.test(t)}async function Bt(t,e,s,n){let o=e.split("/"),i=t;for(let p of o.slice(0,-1)){i=de.join(i,p);let d=await Y.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let r=de.join(i,o.at(-1)),a=await Y.open(r,Me.O_RDONLY|Me.O_NOFOLLOW);try{let p=await a.stat(),d=K(e,s,n);if(!p.isFile()||p.size!==s&&p.size!==d)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let c of f){let g=c;if(l+=g.byteLength,l>p.size)return f.destroy(),null;h.push(g)}if(l!==p.size)return null;let u=Buffer.concat(h,l);return l===s?u:J({file:e,expectedSize:s,expectedDigest:n,actualSize:l,actualDigest:`sha256:${Ke("sha256").update(u).digest("hex")}`})?Oe():null}finally{await a.close()}}function De(t){let e=t.split("/");return t.length>0&&t.length<=1024&&!t.startsWith("/")&&!/[\\\0]/u.test(t)&&!vt.has(e[0])&&e.every(s=>s&&s!=="."&&s!=="..")}function F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function X(t,e){return Object.keys(t).length===e.length&&e.every(s=>Object.hasOwn(t,s))}function Nt(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{createHash as Lt}from"node:crypto";import Mt from"node:dns/promises";import Ht from"node:http";import Dt from"node:https";import{isIP as M}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as ue,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as pe}from"@vcp-dev/platform-shared/contracts";var I=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function ze(t){if(M(t)===4){let[e,s]=t.split(".").map(Number);return!(e===0||e===10||e===127||e>=224||e===100&&s>=64&&s<=127||e===169&&s===254||e===172&&s>=16&&s<=31||e===192&&[0,168].includes(s)||e===198&&[18,19,51].includes(s)||e===203&&s===0)}return M(t)===6&&/^[23]/u.test(t)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(t)}function he(t){let e=new URL(t),s=e.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.port||e.hash||s==="localhost"||!s.includes(".")&&!M(s)||/\.(?:internal|localhost|local)$/iu.test(s)||M(s)&&!ze(s))throw I();return e}function Ve(t){let e=s=>s.every((n,o)=>t[o]===n);return e([137,80,78,71,13,10,26,10])?"image/png":e([255,216,255])?"image/jpeg":e([71,73,70,56,55,97])||e([71,73,70,56,57,97])?"image/gif":e([82,73,70,70])&&Buffer.from(t.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function Kt(t,e){let s=()=>{};try{return await Promise.race([t,new Promise((n,o)=>{s=()=>o(I()),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})])}finally{e.removeEventListener("abort",s)}}async function Ft(t,e){let s=AbortSignal.any([e,AbortSignal.timeout(15e3)]),n=he(t);for(let o=0;o<=3;o++){s.throwIfAborted();let i=n.hostname.replace(/^\[|\]$/gu,""),r=M(i)?[{address:i,family:M(i)}]:await Kt(Mt.lookup(i,{all:!0}),s);if(s.throwIfAborted(),!r.length||r.some(({address:d})=>!ze(d)))throw I();let a=r.find(d=>d.family===4)??r[0],p=await new Promise((d,h)=>{(n.protocol==="https:"?Dt:Ht).get(n,{agent:!1,signal:s,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,u,c)=>{u.all?c(null,[{address:a.address,family:a.family}]):c(null,a.address,a.family)}},d).on("error",h)});try{let d=p.statusCode??0;if([301,302,303,307,308].includes(d)){if(!p.headers.location||o===3)throw I();let g=he(new URL(p.headers.location,n).href);if(n.protocol==="https:"&&g.protocol!=="https:")throw I();n=g;continue}let h=p.headers["content-length"];if(d!==200||p.headers["content-encoding"]&&p.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>pe))throw I();let l=[],f=0;for await(let g of p){let S=Buffer.from(g);if(f+=S.length,f>pe)throw I();l.push(S)}if(!f||h!==void 0&&Number(h)!==f)throw I();let u=Buffer.concat(l,f),c=Ve(u);if(!c||p.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==c)throw I();return{bytes:u,mime_type:c}}finally{p.destroy()}}throw I()}var G=class{constructor(e=Ft){this.download=e,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(e,s){let n=s.asset_catalog.filter(u=>u.asset_key===e.asset_key),o=n[0];if(this.controller.signal.aborted||e.snapshot_digest!==s.snapshot_digest||n.length!==1||o?.origin.kind!=="remote"||!e.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%ue)throw I();let i=o.origin.url;he(i);let r=JSON.stringify([e.request,e.snapshot_digest,e.asset_key,e.capture_id,i]),a=this.entries.get(r);if(!a){if(e.offset||this.pending.has(r)||this.pending.size>=2||this.entries.size>=16)throw I();this.pending.add(r);try{let u=await this.download(i,this.controller.signal);if(this.controller.signal.aborted||!u.bytes.length||u.bytes.length>pe||Ve(u.bytes)!==u.mime_type||[...this.entries.values()].reduce((g,S)=>g+S.image.bytes.length,u.bytes.length)>64*1024*1024)throw I();let c=setTimeout(()=>this.remove(r),6e4);c.unref(),a={image:u,timer:c},this.entries.set(r,a)}finally{this.pending.delete(r)}}let{bytes:p,mime_type:d}=a.image;if(e.offset>=p.length)throw I();let h=Lt("sha256").update(p).digest("hex"),l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[d],f={complete:!0,snapshot_digest:e.snapshot_digest,asset_key:e.asset_key,path:`public/__portable_remote__/${h}.${l}`,mime_type:d,byte_size:p.length,digest_sha256:h,offset:e.offset,data_base64:Buffer.from(p.subarray(e.offset,e.offset+ue)).toString("base64")};return e.offset+ue>=p.length&&this.remove(r),f}remove(e){let s=this.entries.get(e);s&&clearTimeout(s.timer),this.entries.delete(e)}dispose(){this.controller.abort();for(let e of this.entries.keys())this.remove(e)}};import{PortableCmsSchemaEnvelopeSchema as zt,PortableCmsSchemaStatementSchema as Vt}from"@vcp-dev/platform-shared/contracts";var $t=3e4;function $e(t){try{let e=zt.safeParse(t.proof);if(!e.success||!Ut(e.data.payload,262144))return null;let s=Buffer.from(e.data.payload,"base64url"),n=new TextDecoder("utf-8",{fatal:!0}).decode(s),o=JSON.parse(n);if(JSON.stringify(o)!==n)return null;let i=Vt.safeParse(o),r=t.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==t.site_id||i.data.base_snapshot_id!==t.base_snapshot_id||i.data.issued_at>r+$t||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Ut(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{SiteEditOperationRequestSchema as ns,SiteEditPortableExportRequestSchema as is,SiteEditPortableExportResultSchema as os,SiteEditPortableAssetRequestSchema as rs,SiteEditPortableAssetResultSchema as as,computeSiteEditCompositionKey as P}from"@vcp-dev/platform-shared/contracts";var cs="127.0.0.1",ds=30218,us="/__vcp/site-edit/bridge",Ye=6*1024*1024,ps=Ye*2,hs=3e3,Ue=50,fe=".vcp/current-snapshot.json",je="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var ge=class{constructor(e,s=Qe.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=e,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new W,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,this.portableRemoteAssets=new G}start(e={}){if(!this.isStarted){this.stopping=!1;try{z.mkdirSync(k.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(s){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${s instanceof Error?s.message:String(s)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let s=Ss({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=s.stop}this.stopWatching=new ss({projectRoot:this.options.projectRoot,watch_dirs:fs(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Ue,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:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=_s(),s=bs(this.options);e.get(s)===this&&e.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{e(s)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(e,s=null){let n=this.runtime;this.activeHistoryStore=e??null;let o=(this.dependencies.createRuntime??Jt)({...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)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=ms(e.composition),o=this.getRuntime(),i=E(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let p=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:p}}}),getDocument:async e=>{let s=this.getRuntime(),n=E(e);await s.initializeComposition(n);let o=s.getDocument(n);return await this.recordRuntimeVersion(o.data.version,e),{...o,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(E(e)),getObjectEditContext:async(e,s,n)=>this.getRuntime().getObjectEditContext(e,E(s),n),getClassNameSource:async(e,s)=>this.getRuntime().getClassNameSource(e,E(s)),getSourceTree:async e=>this.getRuntime().getSourceTree(E(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:E(e.composition)}),exportPortableBlock:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(e,s)),exportPortableBlockAsset:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(e,s)),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:E(e.composition)}),execute:(e,s)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return We(n,e);let o=await this.getRuntime().executeOperation(e);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:e=>this.readOperationReceipt(e),getHistoryOperationResult:e=>this.readOperationReceipt(e),undo:(e,s)=>this.runHistoryWithReceipt("undo",e,s),redo:(e,s)=>this.runHistoryWithReceipt("redo",e,s),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}verifyCmsSchemaProofs(e){let s=[];for(let n of e.cms_schema_proofs??[]){let o=$e({proof:n,site_id:e.site_id,base_snapshot_id:e.base_snapshot_id});if(!o)return null;s.push(o)}return s}async exportPortableBlock(e,s,n){let o=(_,A,st)=>({complete:!1,unresolved:[{code:_,path:A,message:st}]}),i=is.safeParse(e);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=E(s);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.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(a);let d=()=>{let _=this.getRuntime().getDocument(a).data;return{site_id:_.siteId,snapshot_id:_.snapshotId,document_version:_.version}},h=d();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(_=>Fe({..._,projectRoot:this.options.projectRoot})),u;try{u=await f({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(!u)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...u.snapshot.files].map(([_,A])=>[_,typeof A=="string"?A:new Uint8Array(A)])),g={...u,snapshot:{...u.snapshot,files:c}};if(!await Q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:S,...x}=r,R=await Qt({...x,...g,trusted_cms_schemas:l,read_current_identity:d}),y=os.safeParse(R);if(!y.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(y.data.complete&&(y.data.site_id!==r.site_id||y.data.base_snapshot_id!==r.base_snapshot_id||y.data.document_version!==r.document_version||y.data.target.blockKey!==r.target.blockKey||y.data.target.composition.routeId!==a.routeId||y.data.target.composition.templateId!==a.templateId||y.data.selection_ref.key!==r.selection_ref.key||y.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||y.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(y.data.complete||y.data.cms_candidates){if(!await Q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=d();if(this.options.snapshotId!==r.base_snapshot_id||_.site_id!==r.site_id||_.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(_.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.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");y.data.complete&&n?.(c)}return y.data}async exportPortableBlockAsset(e,s){let n=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=rs.safeParse(e);if(!o.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,s,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!r)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let p=a.asset_catalog.find(l=>l.asset_key===i.asset_key),d;try{d=p?.origin.kind==="remote"?await this.portableRemoteAssets.read(i,a):Xt({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,asset_key:i.asset_key,offset:i.offset})}catch{return n("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=as.safeParse(d);if(!h.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await Q(this.options.projectRoot,r))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(E(s)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||l.siteId!==i.request.site_id||l.snapshotId!==i.request.base_snapshot_id||l.version!==i.request.document_version)return n("DOCUMENT_VERSION_STALE")}catch{return n("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?h.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(e,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==e||n.composition.routeId!==s.routeId||n.composition.templateId!==s.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 We(i,void 0,s);let r=await this.getRuntime()[e]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??s),r.composition?r:{...r,composition:s}});return n?this.executeWithReceipt(n,o):o()}isActiveReceiptIdentity(e){return"request_id"in e?e.site_id===this.options.siteId&&e.base_snapshot_id===this.options.snapshotId:e.siteId===this.options.siteId&&e.baseSnapshotId===this.options.snapshotId}operationReceiptKey(e){return"request_id"in e?JSON.stringify([e.site_id,e.base_snapshot_id,"history",e.request_id]):JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return be("sha256").update(JSON.stringify(e)).digest("hex")}readOperationReceipt(e){if(!this.isActiveReceiptIdentity(e))return null;let s=this.operationReceipts.get(this.operationReceiptKey(e));return s?.fingerprint===this.operationFingerprint(e)?s.result:null}executeWithReceipt(e,s){if(!this.isActiveReceiptIdentity(e))return s();let n=this.operationReceiptKey(e),o=this.operationFingerprint(e),i=this.operationReceipts.get(n);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:s(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,p]of this.operationReceipts){if(this.operationReceipts.size<=256)break;p.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??Yt)(ys({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let o=n.readDocumentVersion?await n.readDocumentVersion():0,i=this.versionCheckpoints.get(n);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(n,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=P(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,e)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e,s){let n=s?P(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,e));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??e:e,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,p=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=p,this.versionPersistence=p,p}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Ue;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let s=e.some(tt)?this.scheduleSnapshotIdentityAdvance():!1,n=e.filter(o=>!As(o));if(!(n.length===0&&!s)&&this.refreshCompositions(!1))for(let o of n)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=z.readFileSync(k.join(this.options.projectRoot,fe),"utf8"),s=JSON.parse(e),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||me(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let o=await this.bindHistorySession(e);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=s,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${s}: ${o instanceof Error?o.message:String(o)}`);return}let n=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:e,previousSnapshotId:s,at:n};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,s)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(e=!1){try{let s=gs(this.options.projectRoot),n=ts(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),i=Zt({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[P(d.context),d])),p=new Map(i.map(d=>[P(d.context),d]));if(this.runtime){for(let[d,h]of a){let l=p.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(E(h.context))}for(let[d,h]of p){let l=a.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=s,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(s){let n=s instanceof Error?s:new Error(String(s));if(this.compositionResolutionError=n,e)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=es(e.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let n=this.routes.find(r=>r.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let o=Gt({selector:{routeId:s,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=P(o.context);if(!this.compositions.some(r=>P(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let s=this.runtimeVersionFloors.get(P(e.context));return s===void 0?[]:[{composition:e.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Ge(t){let e=new ge(ls(t),Qe.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function ls(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:k.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??cs,port:t.port??ds,path:t.path??us,sessionKey:t.sessionKey??ks(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function fs(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function gs(t){let e=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!z.existsSync(i))return;let r;try{r=z.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(k.join(i,a.name));continue}if(!a.isFile())continue;let p=k.join(i,a.name),d="";try{d=z.readFileSync(p,"utf8")}catch{}e.push({path:k.relative(t,p).replaceAll(k.sep,"/"),content:d})}};for(let i of s)o(k.join(t,i));return e.sort((i,r)=>i.path.localeCompare(r.path))}function ms(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function E(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function ys(t){return k.join(k.resolve(t.root),me(t.siteId),me(t.snapshotId),be("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function me(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:be("sha256").update(t).digest("hex").slice(0,32)}function _s(){let t=globalThis;return t[je]??=new Map,t[je]}function bs(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function We(t,e,s){let n=s??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!n)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:n,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:n,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ss(t){let e=new qt({maxPayload:Ye,noServer:!0}),s=new WeakSet,n=i=>{new j({socket:new ye(i),engine:t.engine,validateOperationRequest:r=>ns.safeParse(r).success})},o=(i,r,a)=>{if(!Is(i,t))return;let p=ws(i,t);if(!p){r.write(`HTTP/1.1 401 Unauthorized\r
3
3
  Connection: close\r
4
4
  \r
5
5
  `),r.destroy();return}p.authenticatedByHeader&&s.add(i),e.handleUpgrade(i,r,a,d=>{e.emit("connection",d,i)})};return t.server.on("upgrade",o),e.on("connection",(i,r)=>{if(s.has(r)){n(i);return}Es(i,t.sessionKey,()=>{n(i)})}),e.stop=()=>{t.server.off("upgrade",o);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var ye=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",s=>{this.onmessage?.({data:s.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===Xe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>ps){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,s){this.socket.close(e,s)}};function Is(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function ws(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=le(t.headers["x-vcp-site-edit-key"]),o=Ze(n,e.sessionKey),i=le(t.headers.host),r=le(t.headers.origin);return i&&!xs(i,e.host,r)?null:r?Cs(r,i,e.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Es(t,e,s){let n=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},hs),o,i=()=>{clearTimeout(n),t.off("message",o),t.off("close",i)},r=()=>{i(),t.close(1008,"bridge authentication failed")};o=a=>{try{let p=C.parseMessage(a.toString());if(p.type!=="auth"||!Ze(p.payload.key,e)){r();return}i(),t.readyState===Xe.OPEN&&t.send(C.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),s()}catch{r()}},t.on("message",o),t.on("close",i)}function Ze(t,e){if(!t)return!1;let s=Buffer.from(t),n=Buffer.from(e);return s.length===n.length&&Wt(s,n)}function xs(t,e,s){let n=Je(t),o=Je(e);return n===o||qe(o)&&qe(n)&&(!s||_e(s,t))||Rs(o)&&(!s||_e(s,t))}function Rs(t){return t==="0.0.0.0"||t==="::"}function qe(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Cs(t,e,s){return s.includes(t)||(e?_e(t,e):!1)}function _e(t,e){try{return new URL(t).host===et(e)}catch{return!1}}function Je(t){let e=et(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function et(t){return t.trim().toLowerCase()}function le(t){return Array.isArray(t)?t[0]:t}function ks(){return jt(32).toString("base64url")}function tt(t){let e=t.replaceAll("\\","/");return e===fe||e.endsWith(`/${fe}`)}function As(t){let e=t.replaceAll("\\","/");return tt(t)||e===".vcp/workspace-state.json"||e===".vcp/portable-snapshot-proof.json"||e.startsWith(".vcp/snapshot-store/")}var D=Ts;if(!D)throw new Error("site edit engine worker must run inside worker_threads");var H=t=>{D.postMessage(t)},vs=(t,e)=>{try{D.postMessage({type:"result",id:t,ok:!0,value:e})}catch(s){if(s instanceof Error&&s.name==="DataCloneError"){D.postMessage({type:"result",id:t,ok:!0,value:e===void 0?void 0:JSON.parse(JSON.stringify(e))});return}throw s}},{options:Ps}=Os,V;try{V=Ge({...Ps,onSnapshotIdChanged:(t,e)=>{H({type:"snapshot-id-changed",next:t,previous:e})},onHealthChanged:t=>{H({type:"health",health:t})}})}catch(t){H({type:"start-failed",error:Z(t)}),process.exit(1)}V.engine.subscribe(t=>{H({type:"event",event:t})});var Bs=async t=>{try{let e=V.engine[t.method],s=await e(...t.args);vs(t.id,s)}catch(e){H({type:"result",id:t.id,ok:!1,error:Z(e)})}};D.on("message",t=>{if(t.type==="call"){Bs(t);return}t.type==="stop"&&(V.stop(),D.close())});H({type:"ready",health:V.getHealth()});