@vcp-dev/site-edit-bridge 0.11.25 → 0.11.27
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 +2 -2
- package/dist/engine-worker.js +3 -3
- package/dist/index.js +18 -18
- package/dist/next-dev-server.d.ts +0 -2
- package/dist/next-dev-server.js +5 -5
- package/dist/portable-cms-schema-proof.js +2 -32
- package/dist/portable-snapshot-proof.js +6 -20
- package/dist/portable-snapshot-workspace.js +3 -4
- package/dist/server.d.ts +1 -10
- package/dist/server.js +3 -3
- package/package.json +3 -3
package/dist/client.d.ts
CHANGED
|
@@ -431,7 +431,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
|
|
|
431
431
|
edges: {
|
|
432
432
|
from: string;
|
|
433
433
|
specifier: string | null;
|
|
434
|
-
kind: "type" | "
|
|
434
|
+
kind: "type" | "import" | "export" | "dynamic";
|
|
435
435
|
target: string | null;
|
|
436
436
|
resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
|
|
437
437
|
}[];
|
|
@@ -460,7 +460,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
|
|
|
460
460
|
edges: {
|
|
461
461
|
from: string;
|
|
462
462
|
specifier: string | null;
|
|
463
|
-
kind: "type" | "
|
|
463
|
+
kind: "type" | "import" | "export" | "dynamic";
|
|
464
464
|
target: string | null;
|
|
465
465
|
resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
|
|
466
466
|
}[];
|
package/dist/engine-worker.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{parentPort as _s,workerData as Ss}from"node:worker_threads";function G(e){let t=e&&typeof e=="object"?e:null,s=typeof t?.message=="string"&&t.message.length>0?t.message:String(e);return{name:typeof t?.name=="string"?t.name:"Error",message:s,...typeof t?.code=="string"&&t.code.length>0?{code:t.code}:{}}}import qe from"node:http";import L from"node:fs";import{createHash as me,randomBytes as Kt,timingSafeEqual as Mt}from"node:crypto";import R from"node:path";import{WebSocket as Ue,WebSocketServer as Ht}from"ws";import{createPreviewSiteEditEngineRuntime as Dt,exportPortableBlockFromSnapshot as Lt,readPortableBlockLocalAssetChunk as Ft,openFileHistoryStore as zt,resolveManagedPageTemplateComposition as Vt,scanSiteEditCompositionsFromFiles as jt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as qt,scanNextAppRouterRoutesFromFiles as Ut}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Wt}from"@vcp-dev/site-edit-engine/source-watcher";function _e(e){if(e.pageBlocks!==void 0&&!Ze(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,s=[],n=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((d,h)=>[d,h])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),c=new Map(e.entries.map((d,h)=>[d.key,h])),l=[];for(let[d,h]of e.entries.entries()){let g=h.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([d,{kind:g.kind}]);continue}let p=g.siblingKeys.map(I=>{let x=c.get(I);if(x===void 0)throw new Error("Render entry "+h.key+" references missing source sibling "+I);return x});l.push([d,{kind:"source-siblings",siblingEntryIndexes:p}])}let m=d=>{let h=t.get(d);if(typeof h=="number")return h;let g=s.length;return s.push(d),t.set(d,g),g},y=d=>{let h=null;for(let g of ct(d)){let p=`${h??"root"}\0${g}`,I=n.get(p);if(typeof I=="number"){h=I;continue}let x=o.length;o.push([h,m(g)]),n.set(p,x),h=x}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:s,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?r.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[y(d.key),Ye(d.operationSummary),...h>=0?[h]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(d=>d.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(d=>d.parentKey===null?null:y(d.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Ye(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ze(e){if(!Array.isArray(e))return!1;let t=new Map;for(let s of e){if(!O(s)||!B(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!z(s.blockKey,256)||!z(s.definitionKey,512)||!et(s.rootRef)||!tt(s.source)||!st(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>z(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!P(s.placementUnitKey)||!nt(s.capabilities)||s.unavailableReasons!==void 0&&!it(s.unavailableReasons)||t.has(s.blockKey))return!1;t.set(s.blockKey,s)}for(let s of e){let n=s.owner;for(let o of s.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(n.kind!==r.kind||n.key!==r.key)return!1}}return!0}function et(e){return!O(e)||!B(e,["key","instanceIndex","instanceCount"])||!P(e.key)||e.instanceIndex!==void 0&&!ge(e.instanceIndex)||e.instanceCount!==void 0&&(!ge(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function tt(e){return O(e)&&B(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&ot(e.file)&&P(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function st(e){return O(e)&&B(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&z(e.key,512)}function nt(e){return O(e)&&B(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function it(e){return O(e)&&Object.entries(e).every(([t,s])=>P(t)&&O(s)&&B(s,["code","reason"])&&P(s.code)&&P(s.reason))}function ot(e){let t=rt(e),s=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.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=e.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(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function rt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let s=t[1].split("/"),n=s.some(r=>ye(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)||!at(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!ye(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,l=>l.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function ye(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function at(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let s=decodeURIComponent(t);return s==="."||s===".."||/[/\\\x00-\x1f\x7f]/u.test(s)||s.startsWith(".vcp")}catch{return!0}})}function z(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function P(e){return typeof e=="string"&&e.length>0}function B(e,t){let s=new Set(t);return Object.keys(e).every(n=>s.has(n))}function ct(e){if(!e)return[];let t=[],s=0,n=be(e,s);if(n<0)return t.push(e),t;for(t.push(e.slice(0,n)),s=n;s<e.length;){if(n=be(e,s+(e.startsWith("::",s)?2:1)),n<0){t.push(e.slice(s));break}t.push(e.slice(s,n)),s=n}return t}function be(e,t){let s=e.indexOf("/",t),n=e.indexOf("::",t);return s<0?n:n<0?s:Math.min(s,n)}var N="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ie="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var C=class e{constructor(){}static parseMessage(t,s={}){let n=JSON.parse(t);if(!e.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(f(t)&&f(t.payload)){let s=typeof t.payload.id=="string"?t.payload.id:"unknown",n=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,s={}){return!f(t)||typeof t.type!="string"?!1:t.type==="request"?pt(t.payload,s):t.type==="response"||t.type==="error"?f(t.payload)&&typeof t.payload.id=="string":t.type==="event"?f(t.payload)&&f(t.payload.event):t.type==="auth"?f(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?f(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&f(t.payload)&&t.payload.ok===!0}},j=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ne,this.eventDispatcher=new se(s=>{this.sendJson(s)}),this.unsubscribe=t.engine.subscribe(s=>{this.handleEngineEvent(s)}),t.socket.onmessage=s=>{let n=dt(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"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let s=t;if(s.type!=="request")return;let n=s.payload,{id:o}=n;switch(n.kind){case"initialize-session":{let i=Y(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:A({...a,data:{...a.data,document:Ee(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,yt(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,A(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(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,A(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,A(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!oe(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(S(i)!==S(r))throw new w(N,"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(!Ie(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(S(i)!==S(r))throw new w(N,"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=A(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(S(i)!==S(r))throw new w(N,"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(S(i)!==S(r))throw new w(N,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:V(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(n),r=n.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==n.kind||S(i)!==S(u))throw new w(N,"History request does not match its cursor operation.")}let a=r?{...r,composition:V(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(t);this.sendJson({type:"error",payload:{...n,message:te(s),code:ee(s)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let s=await this.resolve(t),n=this.session.activeComposition;if(!n)throw new w(ie,"Initialize a composition session before issuing this request.");if(S(n)!==S(s.context))throw new w(N,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(t){let s=Y(t);return this.resolveAndAssert(s)}async resolveOperationWireContext(t){let s=mt(t);return this.resolveAndAssert(s)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(S(t))}async normalizeOperationRequest(t,s){let n={...t,composition:V(s)};if(n.target.kind==="route"){let o=n.target,i=Y(o),r=await this.resolveAndAssert(i);n.target={...o,composition:V(r)}}return n}handleEngineEvent(t){let s=t?.composition;if(!ft(s))return;let n=S(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&n===gt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(t,s,n){this.sendJson({type:"response",payload:{id:t,kind:s,result:n}})}async handleRawMessage(t){try{await this.handleMessage(C.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=bt(t);this.sendJson({type:"error",payload:{...n,message:te(s),code:ee(s)}})}}sendJson(t){this.options.socket.send(C.stringifyMessage(t))}async handleBufferedOperation(t,s,n){this.eventDispatcher.beginBuffering();try{let o=await n();this.sendResult(t,s,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:s,message:te(o),code:ee(o)}})}finally{this.eventDispatcher.flush()}}},ut=256;function dt(e){if(e.length>ut||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return f(t)&&t.type==="ping"&&f(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var w=class extends Error{constructor(t,s){super(s),this.code=t,this.name="BridgeProtocolError"}},se=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let s={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(s=>this.send(s))}},ne=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await t()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function pt(e,t){if(!f(e)||typeof e.id!="string"||!C.isRequestKind(e.kind))return!1;let s=T(e.composition);switch(e.kind){case"initialize-session":return s&&(e.mutationContext===void 0||Z(e.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof e.key=="string"&&s&&we(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&s;case"get-history-status":return s;case"get-source-tree":return s;case"get-source-file":return typeof e.path=="string"&&s;case"export-portable-block":return oe(e);case"export-portable-block-asset":return Ie(e);case"execute":case"get-operation-result":return s&&ht(e.request)&&(e.request.mutationContext===void 0||Z(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return s&&Se(e.request);case"undo":case"redo":return s&&(e.request===void 0||Se(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||Z(e.mutationContext))}}function oe(e){if(!T(e.composition)||!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!f(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(s))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!f(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(s=>["kind","composition","blockKey"].includes(s))||!T(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!we(t.selection_ref)||t.cms_schema_proofs!==void 0&&!lt(t.cms_schema_proofs))}function lt(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let s=Object.getOwnPropertyDescriptor(e,String(t));if(!s||!("value"in s))return!1;let n=s.value;if(!f(n)||!Reflect.ownKeys(n).every(r=>typeof r=="string"&&["payload","signature"].includes(r)))return!1;let o=Object.getOwnPropertyDescriptor(n,"payload"),i=Object.getOwnPropertyDescriptor(n,"signature");if(!o||!("value"in o)||!i||!("value"in i)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value)||typeof i.value!="string"||!/^[A-Za-z0-9_-]{86}$/u.test(i.value))return!1}return!0}function Ie(e){if(!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!f(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["request","snapshot_digest","file_path","occurrence","offset"].includes(s))||!oe({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(s=>!s||s.startsWith(".")||s==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function Se(e){return f(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&T(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function we(e){if(e===void 0)return!0;if(!f(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,s=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof t=="number"&&typeof s=="number"&&t>=s?!1:Object.keys(e).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function ht(e){return f(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&T(e.composition)&&typeof e.kind=="string"&&f(e.target)&&(e.target.kind!=="route"||T(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&f(e.params)}function T(e){return f(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function ft(e){return f(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Y(e){if(T(e.composition))return e.composition;throw new w(ie,"A composition selector is required for this request.")}function mt(e){if(f(e)&&T(e.composition))return e.composition;throw new w(ie,"A composition selector is required for execute.")}function V(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function gt(e){return e.activeComposition?S(e.activeComposition):null}function S(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function A(e,t){return f(e)&&e.ok===!0?{...e,composition:t}:e}function yt(e,t){return!f(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Ee(e.data)}}function Ee(e){let t=e;return _e(t.routeId?t:{...t,routeId:t.composition.routeId})}function f(e){return typeof e=="object"&&e!==null}function Z(e){return f(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function ee(e){if(!(!f(e)||typeof e.code!="string"||e.code.length===0))return e.code}function te(e){return e instanceof Error||f(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function bt(e){try{return C.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var q=class{constructor(){this.tail=Promise.resolve()}run(t){let s=this.tail.then(t,t);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as ke}from"node:crypto";import{constants as Ae,promises as re}from"node:fs";import Te from"node:path";import{createHash as _t}from"node:crypto";var U=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
|
-
`)),xe=Buffer.from(U.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Ce=e=>`sha256:${_t("sha256").update(e).digest("hex")}`,St=Ce(U),It=Ce(xe);function H(e,t,s){return e==="next-env.d.ts"&&t===U.byteLength&&s===St?xe.byteLength:null}function W(e){return H(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===It}function Re(){return Uint8Array.from(U)}var Oe=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),ve=64;async function $(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||Oe.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>ve||++s>t.size*ve+1)return!1;let a=await re.readdir(Te.join(e,i),{withFileTypes:!0});for(let u of a){let c=i?`${i}/${u.name}`:u.name;if(!i&&Oe.has(u.name))continue;if(u.isDirectory()){if(!await o(c,r+1))return!1;continue}if(!u.isFile())return!1;let l=t.get(c);if(l===void 0||n.has(c))return!1;n.add(c);let m=Te.join(e,c),y=await re.lstat(m),d=typeof l=="string"?Buffer.byteLength(l,"utf8"):l.byteLength,h=`sha256:${ke("sha256").update(l).digest("hex")}`;if(!y.isFile()||y.isSymbolicLink()||y.size!==d&&y.size!==H(c,d,h))return!1;let g=ke("sha256"),p=await re.open(m,Ae.O_RDONLY|Ae.O_NOFOLLOW);try{let x=await p.stat();if(!x.isFile()||x.size!==y.size)return!1;let b=0,_=p.createReadStream({autoClose:!1});for await(let k of _){if(b+=k.byteLength,b>y.size)return _.destroy(),!1;g.update(k)}if(b!==y.size)return!1}finally{await p.close()}let I=`sha256:${g.digest("hex")}`;if((y.size!==d||I!==h)&&!W({file:c,expectedSize:d,expectedDigest:h,actualSize:y.size,actualDigest:I}))return!1}return!0};return await o("",0)&&n.size===t.size}catch{return!1}}import{createHash as Ke,createPublicKey as wt,verify as Et}from"node:crypto";import{constants as Pe,promises as Q}from"node:fs";import ce from"node:path";import{GeneratedSiteCapabilitiesSchema as xt}from"@vcp-dev/contracts";var Ct=".vcp/portable-snapshot-proof.json",Be=4*1024*1024,Rt=256*1024*1024,kt=1e4,At=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function Me(e){try{if(!e.publicKey||!ae(e.publicKey,256))return null;let t=wt({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let s=ce.join(e.projectRoot,Ct),n=await Q.lstat(s);if(!n.isFile()||n.isSymbolicLink()||n.size>Be)return null;let o=JSON.parse(await Q.readFile(s,"utf8"));if(!D(o)||!J(o,["payload","signature"])||!ae(o.payload,Be)||!ae(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!Et(null,i,t,r))return null;let a=new TextDecoder("utf-8",{fatal:!0}).decode(i),u=JSON.parse(a);if(JSON.stringify(u)!==a||!D(u)||!J(u,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||u.kind!=="vcp-portable-snapshot-v1"||!D(u.manifest))return null;let c=u.manifest;if(c.version!==1||c.site_id!==e.site_id||c.snapshot_id!==e.base_snapshot_id||typeof c.created_at!="string"||!Array.isArray(c.files)||!c.files.length||c.files.length>kt)return null;let l=xt.safeParse(u.host_capabilities);if(!l.success||!Array.isArray(u.trusted_host_file_hashes)||u.trusted_host_file_hashes.length>512)return null;let m=new Map;for(let p of u.trusted_host_file_hashes){if(!D(p)||!J(p,["path","hash"])||typeof p.path!="string"||!Tt(p.path)||!Ne(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||m.has(p.path))return null;m.set(p.path,p.hash)}let y=0,d=[],h=new Set;for(let p of c.files){if(!D(p)||!J(p,["path","hash","size_bytes"])||typeof p.path!="string"||!Ne(p.path)||typeof p.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(p.hash)||typeof p.size_bytes!="number"||!Number.isSafeInteger(p.size_bytes)||p.size_bytes<0||h.has(p.path)||(h.add(p.path),y+=p.size_bytes,y>Rt))return null;d.push({path:p.path,hash:p.hash,size_bytes:p.size_bytes})}let g=new Map;for(let p of d){let I=await Ot(e.projectRoot,p.path,p.size_bytes,p.hash);if(!I||`sha256:${Ke("sha256").update(I).digest("hex")}`!==p.hash)return null;g.set(p.path,I)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:c.created_at,files:d},files:g},host_capabilities:l.data,trusted_host_file_hashes:m}}catch{return null}}function Tt(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?lib\/utils\.ts$/u.test(e)}async function Ot(e,t,s,n){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=ce.join(i,u);let c=await Q.lstat(i);if(!c.isDirectory()||c.isSymbolicLink())return null}let r=ce.join(i,o.at(-1)),a=await Q.open(r,Pe.O_RDONLY|Pe.O_NOFOLLOW);try{let u=await a.stat(),c=H(t,s,n);if(!u.isFile()||u.size!==s&&u.size!==c)return null;let l=[],m=0,y=a.createReadStream({autoClose:!1});for await(let h of y){let g=h;if(m+=g.byteLength,m>u.size)return y.destroy(),null;l.push(g)}if(m!==u.size)return null;let d=Buffer.concat(l,m);return m===s?d:W({file:t,expectedSize:s,expectedDigest:n,actualSize:m,actualDigest:`sha256:${Ke("sha256").update(d).digest("hex")}`})?Re():null}finally{await a.close()}}function Ne(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!At.has(t[0])&&t.every(s=>s&&s!=="."&&s!=="..")}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.hasOwn(e,s))}function ae(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{createPublicKey as He,verify as vt}from"node:crypto";import{PortableCmsSchemaEnvelopeSchema as Pt,PortableCmsSchemaStatementSchema as Bt}from"@vcp-dev/contracts";var Nt=3e4;function De(e){try{let t=Pt.safeParse(e.proof);if(!t.success||!X(e.publicKey,256)||!X(e.snapshotPublicKey,256)||e.publicKey===e.snapshotPublicKey||!X(t.data.payload,262144)||!X(t.data.signature,86))return null;let s=He({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"}),n=He({key:Buffer.from(e.snapshotPublicKey,"base64url"),type:"spki",format:"der"});if(s.asymmetricKeyType!=="ed25519"||n.asymmetricKeyType!=="ed25519"||n.export({type:"spki",format:"der"}).toString("base64url")!==e.snapshotPublicKey||s.export({type:"spki",format:"der"}).toString("base64url")!==e.publicKey)return null;let o=Buffer.from(t.data.payload,"base64url"),i=Buffer.from(t.data.signature,"base64url");if(i.byteLength!==64||!vt(null,o,s,i))return null;let r=new TextDecoder("utf-8",{fatal:!0}).decode(o),a=JSON.parse(r);if(JSON.stringify(a)!==r)return null;let u=Bt.safeParse(a),c=e.now??Date.now();return!u.success||!Number.isSafeInteger(c)||u.data.site_id!==e.site_id||u.data.base_snapshot_id!==e.base_snapshot_id||u.data.issued_at>c+Nt||u.data.expires_at<=c?null:{source_slug:u.data.slug,evidence_path:`trusted-cms-schema:${u.data.slug}`,fields:u.data.fields}}catch{return null}}function X(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as $t,SiteEditPortableExportRequestSchema as Jt,SiteEditPortableExportResultSchema as Qt,SiteEditPortableAssetRequestSchema as Xt,SiteEditPortableAssetResultSchema as Gt,computeSiteEditCompositionKey as v}from"@vcp-dev/contracts";var Yt="127.0.0.1",Zt=30218,es="/__vcp/site-edit/bridge",We=6*1024*1024,ts=We*2,ss=3e3,Le=50,de=".vcp/current-snapshot.json",Fe="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var pe=class{constructor(t,s=qe.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=t,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new q,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{L.mkdirSync(R.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(),t.webSocket!==!1){let s=ds({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 Wt({projectRoot:this.options.projectRoot,watch_dirs:is(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Le,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(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=cs(),s=us(this.options);t.get(s)===this&&t.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{t(s)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,s=null){let n=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??Dt)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=rs(t.composition),o=this.getRuntime(),i=E(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let s=this.getRuntime(),n=E(t);await s.initializeComposition(n);let o=s.getDocument(n);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(E(t)),getObjectEditContext:async(t,s,n)=>this.getRuntime().getObjectEditContext(t,E(s),n),getClassNameSource:async(t,s)=>this.getRuntime().getClassNameSource(t,E(s)),getSourceTree:async t=>this.getRuntime().getSourceTree(E(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:E(t.composition)}),exportPortableBlock:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,s)),exportPortableBlockAsset:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,s)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:E(t.composition)}),execute:(t,s)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return ze(n,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,s)=>this.runHistoryWithReceipt("undo",t,s),redo:(t,s)=>this.runHistoryWithReceipt("redo",t,s),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let s=[];for(let n of t.cms_schema_proofs??[]){let o=De({proof:n,publicKey:this.options.portableCmsSchemaPublicKey,snapshotPublicKey:this.options.portableSnapshotPublicKey,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;s.push(o)}return s}async exportPortableBlock(t,s,n){let o=(_,k,Ge)=>({complete:!1,unresolved:[{code:_,path:k,message:Ge}]}),i=Jt.safeParse(t);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 c=()=>{let _=this.getRuntime().getDocument(a).data;return{site_id:_.siteId,snapshot_id:_.snapshotId,document_version:_.version}},l=c();if(l.site_id!==r.site_id||l.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(l.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let m=this.verifyCmsSchemaProofs(r);if(!m)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let y=this.dependencies.loadTrustedPortableSnapshot??(_=>Me({..._,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),d;try{d=await y({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(!d)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let h=new Map([...d.snapshot.files].map(([_,k])=>[_,typeof k=="string"?k:new Uint8Array(k)])),g={...d,snapshot:{...d.snapshot,files:h}};if(!await $(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:p,...I}=r,x=await Lt({...I,...g,trusted_cms_schemas:m,read_current_identity:c}),b=Qt.safeParse(x);if(!b.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(b.data.complete&&(b.data.site_id!==r.site_id||b.data.base_snapshot_id!==r.base_snapshot_id||b.data.document_version!==r.document_version||b.data.target.blockKey!==r.target.blockKey||b.data.target.composition.routeId!==a.routeId||b.data.target.composition.templateId!==a.templateId||b.data.selection_ref.key!==r.selection_ref.key||b.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||b.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(b.data.complete||b.data.cms_candidates){if(!await $(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=c();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.");b.data.complete&&n?.(h)}return b.data}async exportPortableBlockAsset(t,s){let n=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Xt.safeParse(t);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 u=Ft({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),c=Gt.safeParse(u);if(!c.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!c.data.complete)return c.data;if(!await $(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)?c.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==t||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 ze(i,void 0,s);let r=await this.getRuntime()[t]();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(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return me("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let s=this.operationReceipts.get(this.operationReceiptKey(t));return s?.fingerprint===this.operationFingerprint(t)?s.result:null}executeWithReceipt(t,s){if(!this.isActiveReceiptIdentity(t))return s();let n=this.operationReceiptKey(t),o=this.operationFingerprint(t),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,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let n=await(this.dependencies.openHistoryStore??zt)(as({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));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=v(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,t)});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(t,s){let n=s?v(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let n of t)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Le;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 t=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let s=t.some(Xe)?this.scheduleSnapshotIdentityAdvance():!1,n=t.filter(o=>!bs(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 t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=L.readFileSync(R.join(this.options.projectRoot,de),"utf8"),s=JSON.parse(t),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||le(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=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:t,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?.(t,s)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let s=os(this.options.projectRoot),n=Ut(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(c=>({...c})),i=jt({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(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[v(c.context),c])),u=new Map(i.map(c=>[v(c.context),c]));if(this.runtime){for(let[c,l]of a){let m=u.get(c);(!m||m.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(E(l.context))}for(let[c,l]of u){let m=a.get(c);(!m||m.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.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,t)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=qt(t.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let n=this.routes.find(r=>r.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Vt({selector:{routeId:s,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=v(o.context);if(!this.compositions.some(r=>v(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let s=this.runtimeVersionFloors.get(v(t.context));return s===void 0?[]:[{composition:t.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function $e(e){let t=new pe(ns(e),qe.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function ns(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:R.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Yt,port:e.port??Zt,path:e.path??es,sessionKey:e.sessionKey??ys(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,portableCmsSchemaPublicKey:e.portableCmsSchemaPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function is(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function os(e){let t=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!L.existsSync(i))return;let r;try{r=L.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(R.join(i,a.name));continue}if(!a.isFile())continue;let u=R.join(i,a.name),c="";try{c=L.readFileSync(u,"utf8")}catch{}t.push({path:R.relative(e,u).replaceAll(R.sep,"/"),content:c})}};for(let i of s)o(R.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function rs(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function E(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function as(e){return R.join(R.resolve(e.root),le(e.siteId),le(e.snapshotId),me("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function le(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:me("sha256").update(e).digest("hex").slice(0,32)}function cs(){let e=globalThis;return e[Fe]??=new Map,e[Fe]}function us(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function ze(e,t,s){let n=s??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.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:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:n,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function ds(e){let t=new Ht({maxPayload:We,noServer:!0}),s=new WeakSet,n=i=>{new j({socket:new he(i),engine:e.engine,validateOperationRequest:r=>$t.safeParse(r).success})},o=(i,r,a)=>{if(!ps(i,e))return;let u=ls(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import{parentPort as gs,workerData as ms}from"node:worker_threads";function X(e){let t=e&&typeof e=="object"?e:null,s=typeof t?.message=="string"&&t.message.length>0?t.message:String(e);return{name:typeof t?.name=="string"?t.name:"Error",message:s,...typeof t?.code=="string"&&t.code.length>0?{code:t.code}:{}}}import ze from"node:http";import F from"node:fs";import{createHash as le,randomBytes as vt,timingSafeEqual as Pt}from"node:crypto";import R from"node:path";import{WebSocket as Ve,WebSocketServer as Bt}from"ws";import{createPreviewSiteEditEngineRuntime as Nt,exportPortableBlockFromSnapshot as Mt,readPortableBlockLocalAssetChunk as Ht,openFileHistoryStore as Dt,resolveManagedPageTemplateComposition as Lt,scanSiteEditCompositionsFromFiles as Kt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Ft,scanNextAppRouterRoutesFromFiles as zt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Vt}from"@vcp-dev/site-edit-engine/source-watcher";function ye(e){if(e.pageBlocks!==void 0&&!Xe(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,s=[],n=new Map,r=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],o=new Map(i.map((u,c)=>[u,c])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(u=>({placementKey:u.placementKey,placementUnitKey:u.placementUnitKey,relation:u.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},p=e.entries.flatMap((u,c)=>u.dynamicDataSummary?[[c,u.dynamicDataSummary]]:[]),d=new Map(e.entries.map((u,c)=>[u.key,c])),h=[];for(let[u,c]of e.entries.entries()){let g=c.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){h.push([u,{kind:g.kind}]);continue}let C=g.siblingKeys.map(w=>{let E=d.get(w);if(E===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+w);return E});h.push([u,{kind:"source-siblings",siblingEntryIndexes:C}])}let f=u=>{let c=t.get(u);if(typeof c=="number")return c;let g=s.length;return s.push(u),t.set(u,g),g},m=u=>{let c=null;for(let g of ot(u)){let C=`${c??"root"}\0${g}`,w=n.get(C);if(typeof w=="number"){c=w;continue}let E=r.length;r.push([c,f(g)]),n.set(C,E),c=E}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:s,nodes:r,entries:e.entries.map(u=>{let c=u.pageCompositionUnitKey?o.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[m(u.key),Qe(u.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(u=>u.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(u=>u.parentKey===null?null:m(u.parentKey))}:{},...p.length>0?{dynamicDataSummaries:p}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Qe(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Xe(e){if(!Array.isArray(e))return!1;let t=new Map;for(let s of e){if(!O(s)||!B(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!V(s.blockKey,256)||!V(s.definitionKey,512)||!Ge(s.rootRef)||!Ye(s.source)||!Ze(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>V(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!P(s.placementUnitKey)||!et(s.capabilities)||s.unavailableReasons!==void 0&&!tt(s.unavailableReasons)||t.has(s.blockKey))return!1;t.set(s.blockKey,s)}for(let s of e){let n=s.owner;for(let r of s.siblingBlockKeys){let i=t.get(r);if(!i)return!1;let o=i.owner;if(n.kind!==o.kind||n.key!==o.key)return!1}}return!0}function Ge(e){return!O(e)||!B(e,["key","instanceIndex","instanceCount"])||!P(e.key)||e.instanceIndex!==void 0&&!fe(e.instanceIndex)||e.instanceCount!==void 0&&(!fe(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Ye(e){return O(e)&&B(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&st(e.file)&&P(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Ze(e){return O(e)&&B(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&V(e.key,512)}function et(e){return O(e)&&B(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function tt(e){return O(e)&&Object.entries(e).every(([t,s])=>P(t)&&O(s)&&B(s,["code","reason"])&&P(s.code)&&P(s.reason))}function st(e){let t=nt(e),s=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.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=e.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(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function nt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let s=t[1].split("/"),n=s.some(o=>ge(o)),r=n?s[0]:s.pop(),i=n?s.slice(1):s;if(n&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(r)||!it(`/${i.join("/")}`)||i.some(o=>o.includes("[")||o.includes("]")?!ge(o):/[\[\]()%]/u.test(o)||o.startsWith("_")||o.startsWith("@")))return!1;try{let o=r.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(o),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,"")===r}catch{return!1}}function ge(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function it(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let s=decodeURIComponent(t);return s==="."||s===".."||/[/\\\x00-\x1f\x7f]/u.test(s)||s.startsWith(".vcp")}catch{return!0}})}function V(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function P(e){return typeof e=="string"&&e.length>0}function B(e,t){let s=new Set(t);return Object.keys(e).every(n=>s.has(n))}function ot(e){if(!e)return[];let t=[],s=0,n=me(e,s);if(n<0)return t.push(e),t;for(t.push(e.slice(0,n)),s=n;s<e.length;){if(n=me(e,s+(e.startsWith("::",s)?2:1)),n<0){t.push(e.slice(s));break}t.push(e.slice(s,n)),s=n}return t}function me(e,t){let s=e.indexOf("/",t),n=e.indexOf("::",t);return s<0?n:n<0?s:Math.min(s,n)}var N="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ne="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var x=class e{constructor(){}static parseMessage(t,s={}){let n=JSON.parse(t);if(!e.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(l(t)&&l(t.payload)){let s=typeof t.payload.id=="string"?t.payload.id:"unknown",n=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,s={}){return!l(t)||typeof t.type!="string"?!1:t.type==="request"?ct(t.payload,s):t.type==="response"||t.type==="error"?l(t.payload)&&typeof t.payload.id=="string":t.type==="event"?l(t.payload)&&l(t.payload.event):t.type==="auth"?l(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?l(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&l(t.payload)&&t.payload.ok===!0}},q=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new se,this.eventDispatcher=new te(s=>{this.sendJson(s)}),this.unsubscribe=t.engine.subscribe(s=>{this.handleEngineEvent(s)}),t.socket.onmessage=s=>{let n=at(s.data);if(n!==null){this.sendJson({type:"pong",payload:{id:n}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let s=t;if(s.type!=="request")return;let n=s.payload,{id:r}=n;switch(n.kind){case"initialize-session":{let i=G(n),o=await this.resolve(i),a=await this.options.engine.initializeSession({composition:o.context,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.activateSession(o.context),this.sendJson({type:"response",payload:{id:r,kind:n.kind,result:A({...a,data:{...a.data,document:Ie(a.data.document)}},o.context)}});return}case"get-document":{let i=await this.resolveWireContext(n),o=await this.options.engine.getDocument(i);this.sendResult(r,n.kind,ft(o,i));return}case"get-history-status":{let i=await this.resolveWireContext(n),o=await this.options.engine.getHistoryStatus(i);this.sendResult(r,n.kind,A(o,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(r,n.kind,A(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(r,n.kind,A(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(r,n.kind,A(await this.options.engine.getClassNameSource(n.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(n);this.sendResult(r,n.kind,A(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(r,n.kind,A(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!ie(n))throw new b("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(n),o=await this.resolveAndAssert(n.request.target.composition);if(S(i)!==S(o))throw new b(N,"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(r,n.kind,a);return}case"export-portable-block-asset":{if(!Se(n))throw new b("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(n),o=await this.resolveAndAssert(n.request.request.target.composition);if(S(i)!==S(o))throw new b(N,"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(r,n.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(n),o=A(await this.options.engine.resolveSourceLocation({key:n.key,composition:i}),i);this.sendResult(r,n.kind,o);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(n.request),o=await this.resolveWireContext(n);if(S(i)!==S(o))throw new b(N,"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(r,n.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(r,n.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(n),o=await this.resolveAndAssert(n.request.composition);if(S(i)!==S(o))throw new b(N,"History receipt composition does not match the active session.");this.sendResult(r,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:j(o)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(n),o=n.request;if(o){let p=await this.resolveAndAssert(o.composition);if(o.kind!==n.kind||S(i)!==S(p))throw new b(N,"History request does not match its cursor operation.")}let a=o?{...o,composition:j(i)}:void 0;await this.handleBufferedOperation(r,n.kind,()=>n.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(s){let n=x.extractRequestInfo(t);this.sendJson({type:"error",payload:{...n,message:ee(s),code:Z(s)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let s=await this.resolve(t),n=this.session.activeComposition;if(!n)throw new b(ne,"Initialize a composition session before issuing this request.");if(S(n)!==S(s.context))throw new b(N,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(t){let s=G(t);return this.resolveAndAssert(s)}async resolveOperationWireContext(t){let s=ht(t);return this.resolveAndAssert(s)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(S(t))}async normalizeOperationRequest(t,s){let n={...t,composition:j(s)};if(n.target.kind==="route"){let r=n.target,i=G(r),o=await this.resolveAndAssert(i);n.target={...r,composition:j(o)}}return n}handleEngineEvent(t){let s=t?.composition;if(!pt(s))return;let n=S(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&n===lt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(t,s,n){this.sendJson({type:"response",payload:{id:t,kind:s,result:n}})}async handleRawMessage(t){try{await this.handleMessage(x.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=gt(t);this.sendJson({type:"error",payload:{...n,message:ee(s),code:Z(s)}})}}sendJson(t){this.options.socket.send(x.stringifyMessage(t))}async handleBufferedOperation(t,s,n){this.eventDispatcher.beginBuffering();try{let r=await n();this.sendResult(t,s,r)}catch(r){this.sendJson({type:"error",payload:{id:t,kind:s,message:ee(r),code:Z(r)}})}finally{this.eventDispatcher.flush()}}},rt=256;function at(e){if(e.length>rt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return l(t)&&t.type==="ping"&&l(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var b=class extends Error{constructor(t,s){super(s),this.code=t,this.name="BridgeProtocolError"}},te=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let s={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(s=>this.send(s))}},se=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await t()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function ct(e,t){if(!l(e)||typeof e.id!="string"||!x.isRequestKind(e.kind))return!1;let s=T(e.composition);switch(e.kind){case"initialize-session":return s&&(e.mutationContext===void 0||Y(e.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof e.key=="string"&&s&&be(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&s;case"get-history-status":return s;case"get-source-tree":return s;case"get-source-file":return typeof e.path=="string"&&s;case"export-portable-block":return ie(e);case"export-portable-block-asset":return Se(e);case"execute":case"get-operation-result":return s&&ut(e.request)&&(e.request.mutationContext===void 0||Y(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return s&&_e(e.request);case"undo":case"redo":return s&&(e.request===void 0||_e(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||Y(e.mutationContext))}}function ie(e){if(!T(e.composition)||!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!l(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(s))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!l(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(s=>["kind","composition","blockKey"].includes(s))||!T(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!be(t.selection_ref)||t.cms_schema_proofs!==void 0&&!dt(t.cms_schema_proofs))}function dt(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let s=Object.getOwnPropertyDescriptor(e,String(t));if(!s||!("value"in s))return!1;let n=s.value;if(!l(n)||!Reflect.ownKeys(n).every(o=>typeof o=="string"&&["payload","signature"].includes(o)))return!1;let r=Object.getOwnPropertyDescriptor(n,"payload"),i=Object.getOwnPropertyDescriptor(n,"signature");if(!r||!("value"in r)||!i||!("value"in i)||typeof r.value!="string"||r.value.length<1||r.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(r.value)||typeof i.value!="string"||!/^[A-Za-z0-9_-]{86}$/u.test(i.value))return!1}return!0}function Se(e){if(!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!l(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["request","snapshot_digest","file_path","occurrence","offset"].includes(s))||!ie({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(s=>!s||s.startsWith(".")||s==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function _e(e){return l(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&T(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function be(e){if(e===void 0)return!0;if(!l(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,s=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof t=="number"&&typeof s=="number"&&t>=s?!1:Object.keys(e).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function ut(e){return l(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&T(e.composition)&&typeof e.kind=="string"&&l(e.target)&&(e.target.kind!=="route"||T(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&l(e.params)}function T(e){return l(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function pt(e){return l(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function G(e){if(T(e.composition))return e.composition;throw new b(ne,"A composition selector is required for this request.")}function ht(e){if(l(e)&&T(e.composition))return e.composition;throw new b(ne,"A composition selector is required for execute.")}function j(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function lt(e){return e.activeComposition?S(e.activeComposition):null}function S(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function A(e,t){return l(e)&&e.ok===!0?{...e,composition:t}:e}function ft(e,t){return!l(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Ie(e.data)}}function Ie(e){let t=e;return ye(t.routeId?t:{...t,routeId:t.composition.routeId})}function l(e){return typeof e=="object"&&e!==null}function Y(e){return l(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function Z(e){if(!(!l(e)||typeof e.code!="string"||e.code.length===0))return e.code}function ee(e){return e instanceof Error||l(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function gt(e){try{return x.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var U=class{constructor(){this.tail=Promise.resolve()}run(t){let s=this.tail.then(t,t);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as Re}from"node:crypto";import{constants as Ce,promises as oe}from"node:fs";import ke from"node:path";import{createHash as mt}from"node:crypto";var W=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
|
+
`)),we=Buffer.from(W.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Ee=e=>`sha256:${mt("sha256").update(e).digest("hex")}`,yt=Ee(W),_t=Ee(we);function D(e,t,s){return e==="next-env.d.ts"&&t===W.byteLength&&s===yt?we.byteLength:null}function $(e){return D(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===_t}function xe(){return Uint8Array.from(W)}var Ae=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Te=64;async function J(e,t){try{if(!t.size)return!1;for(let[i,o]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||Ae.has(i.split("/")[0])||typeof o!="string"&&!(o instanceof Uint8Array))return!1;let s=0,n=new Set,r=async(i,o)=>{if(o>Te||++s>t.size*Te+1)return!1;let a=await oe.readdir(ke.join(e,i),{withFileTypes:!0});for(let p of a){let d=i?`${i}/${p.name}`:p.name;if(!i&&Ae.has(p.name))continue;if(p.isDirectory()){if(!await r(d,o+1))return!1;continue}if(!p.isFile())return!1;let h=t.get(d);if(h===void 0||n.has(d))return!1;n.add(d);let f=ke.join(e,d),m=await oe.lstat(f),u=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${Re("sha256").update(h).digest("hex")}`;if(!m.isFile()||m.isSymbolicLink()||m.size!==u&&m.size!==D(d,u,c))return!1;let g=Re("sha256"),C=await oe.open(f,Ce.O_RDONLY|Ce.O_NOFOLLOW);try{let E=await C.stat();if(!E.isFile()||E.size!==m.size)return!1;let y=0,_=C.createReadStream({autoClose:!1});for await(let k of _){if(y+=k.byteLength,y>m.size)return _.destroy(),!1;g.update(k)}if(y!==m.size)return!1}finally{await C.close()}let w=`sha256:${g.digest("hex")}`;if((m.size!==u||w!==c)&&!$({file:d,expectedSize:u,expectedDigest:c,actualSize:m.size,actualDigest:w}))return!1}return!0};return await r("",0)&&n.size===t.size}catch{return!1}}import{createHash as Be}from"node:crypto";import{constants as Oe,promises as Q}from"node:fs";import re from"node:path";import{GeneratedSiteCapabilitiesSchema as St}from"@vcp-dev/contracts";var bt=".vcp/portable-snapshot-proof.json",ve=4*1024*1024,It=256*1024*1024,wt=1e4,Et=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function Ne(e){try{let t=re.join(e.projectRoot,bt),s=await Q.lstat(t);if(!s.isFile()||s.isSymbolicLink()||s.size>ve)return null;let n=JSON.parse(await Q.readFile(t,"utf8"));if(!L(n)||!(K(n,["payload"])||K(n,["payload","signature"]))||!Ct(n.payload,ve))return null;let r=Buffer.from(n.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(r),o=JSON.parse(i);if(JSON.stringify(o)!==i||!L(o)||!K(o,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||o.kind!=="vcp-portable-snapshot-v1"||!L(o.manifest))return null;let a=o.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>wt)return null;let p=St.safeParse(o.host_capabilities);if(!p.success||!Array.isArray(o.trusted_host_file_hashes)||o.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of o.trusted_host_file_hashes){if(!L(c)||!K(c,["path","hash"])||typeof c.path!="string"||!xt(c.path)||!Pe(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,f=[],m=new Set;for(let c of a.files){if(!L(c)||!K(c,["path","hash","size_bytes"])||typeof c.path!="string"||!Pe(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||m.has(c.path)||(m.add(c.path),h+=c.size_bytes,h>It))return null;f.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let u=new Map;for(let c of f){let g=await Rt(e.projectRoot,c.path,c.size_bytes,c.hash);if(!g||`sha256:${Be("sha256").update(g).digest("hex")}`!==c.hash)return null;u.set(c.path,g)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:f},files:u},host_capabilities:p.data,trusted_host_file_hashes:d}}catch{return null}}function xt(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?lib\/utils\.ts$/u.test(e)}async function Rt(e,t,s,n){let r=t.split("/"),i=e;for(let p of r.slice(0,-1)){i=re.join(i,p);let d=await Q.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let o=re.join(i,r.at(-1)),a=await Q.open(o,Oe.O_RDONLY|Oe.O_NOFOLLOW);try{let p=await a.stat(),d=D(t,s,n);if(!p.isFile()||p.size!==s&&p.size!==d)return null;let h=[],f=0,m=a.createReadStream({autoClose:!1});for await(let c of m){let g=c;if(f+=g.byteLength,f>p.size)return m.destroy(),null;h.push(g)}if(f!==p.size)return null;let u=Buffer.concat(h,f);return f===s?u:$({file:t,expectedSize:s,expectedDigest:n,actualSize:f,actualDigest:`sha256:${Be("sha256").update(u).digest("hex")}`})?xe():null}finally{await a.close()}}function Pe(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!Et.has(t[0])&&t.every(s=>s&&s!=="."&&s!=="..")}function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function K(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.hasOwn(e,s))}function Ct(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{PortableCmsSchemaEnvelopeSchema as kt,PortableCmsSchemaStatementSchema as At}from"@vcp-dev/contracts";var Tt=3e4;function Me(e){try{let t=kt.safeParse(e.proof);if(!t.success||!Ot(t.data.payload,262144))return null;let s=Buffer.from(t.data.payload,"base64url"),n=new TextDecoder("utf-8",{fatal:!0}).decode(s),r=JSON.parse(n);if(JSON.stringify(r)!==n)return null;let i=At.safeParse(r),o=e.now??Date.now();return!i.success||!Number.isSafeInteger(o)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>o+Tt||i.data.expires_at<=o?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Ot(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as jt,SiteEditPortableExportRequestSchema as qt,SiteEditPortableExportResultSchema as Ut,SiteEditPortableAssetRequestSchema as Wt,SiteEditPortableAssetResultSchema as $t,computeSiteEditCompositionKey as v}from"@vcp-dev/contracts";var Jt="127.0.0.1",Qt=30218,Xt="/__vcp/site-edit/bridge",je=6*1024*1024,Gt=je*2,Yt=3e3,He=50,ce=".vcp/current-snapshot.json",De="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var de=class{constructor(t,s=ze.createServer((i,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),n=!0,r={}){this.options=t,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=r,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new U,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{F.mkdirSync(R.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(),t.webSocket!==!1){let s=rs({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 Vt({projectRoot:this.options.projectRoot,watch_dirs:es(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??He,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(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=is(),s=os(this.options);t.get(s)===this&&t.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{t(s)}catch(r){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${r instanceof Error?r.message:String(r)}`)}}}createRuntime(t,s=null){let n=this.runtime;this.activeHistoryStore=t??null;let r=(this.dependencies.createRuntime??Nt)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let o of this.eventListeners)o(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=r,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=ss(t.composition),r=this.getRuntime(),i=I(n);await r.initializeComposition(i);let a=r.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let p=(await r.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:p}}}),getDocument:async t=>{let s=this.getRuntime(),n=I(t);await s.initializeComposition(n);let r=s.getDocument(n);return await this.recordRuntimeVersion(r.data.version,t),{...r,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(I(t)),getObjectEditContext:async(t,s,n)=>this.getRuntime().getObjectEditContext(t,I(s),n),getClassNameSource:async(t,s)=>this.getRuntime().getClassNameSource(t,I(s)),getSourceTree:async t=>this.getRuntime().getSourceTree(I(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:I(t.composition)}),exportPortableBlock:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,s)),exportPortableBlockAsset:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,s)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:I(t.composition)}),execute:(t,s)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return Le(n,t);let r=await this.getRuntime().executeOperation(t);return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition),r})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,s)=>this.runHistoryWithReceipt("undo",t,s),redo:(t,s)=>this.runHistoryWithReceipt("redo",t,s),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let s=[];for(let n of t.cms_schema_proofs??[]){let r=Me({proof:n,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!r)return null;s.push(r)}return s}async exportPortableBlock(t,s,n){let r=(_,k,Je)=>({complete:!1,unresolved:[{code:_,path:k,message:Je}]}),i=qt.safeParse(t);if(!i.success)return r("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let o=i.data,a=I(s);if(o.target.composition.routeId!==a.routeId||o.target.composition.templateId!==a.templateId)return r("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(o.site_id!==this.options.siteId||o.base_snapshot_id!==this.options.snapshotId)return r("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!==o.site_id||h.snapshot_id!==o.base_snapshot_id)return r("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==o.document_version)return r("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let f=this.verifyCmsSchemaProofs(o);if(!f)return r("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let m=this.dependencies.loadTrustedPortableSnapshot??(_=>Ne({..._,projectRoot:this.options.projectRoot})),u;try{u=await m({site_id:o.site_id,base_snapshot_id:o.base_snapshot_id})}catch{return r("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!u)return r("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...u.snapshot.files].map(([_,k])=>[_,typeof k=="string"?k:new Uint8Array(k)])),g={...u,snapshot:{...u.snapshot,files:c}};if(!await J(this.options.projectRoot,c))return r("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:C,...w}=o,E=await Mt({...w,...g,trusted_cms_schemas:f,read_current_identity:d}),y=Ut.safeParse(E);if(!y.success)return r("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(y.data.complete&&(y.data.site_id!==o.site_id||y.data.base_snapshot_id!==o.base_snapshot_id||y.data.document_version!==o.document_version||y.data.target.blockKey!==o.target.blockKey||y.data.target.composition.routeId!==a.routeId||y.data.target.composition.templateId!==a.templateId||y.data.selection_ref.key!==o.selection_ref.key||y.data.selection_ref.instanceIndex!==o.selection_ref.instanceIndex||y.data.selection_ref.instanceCount!==o.selection_ref.instanceCount))return r("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 J(this.options.projectRoot,c))return r("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=d();if(this.options.snapshotId!==o.base_snapshot_id||_.site_id!==o.site_id||_.snapshot_id!==o.base_snapshot_id)return r("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(_.document_version!==o.document_version)return r("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return r("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(o))return r("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");y.data.complete&&n?.(c)}return y.data}async exportPortableBlockAsset(t,s){let n=h=>({complete:!1,unresolved:[{code:h,path:"<asset>",message:"The selected local image could not be verified."}]}),r=Wt.safeParse(t);if(!r.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=r.data,o,a=await this.exportPortableBlock(i.request,s,h=>{o=h});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!o)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let p=Ht({exported:a,snapshot_files:o,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),d=$t.safeParse(p);if(!d.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!d.data.complete)return d.data;if(!await J(this.options.projectRoot,o))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let h=this.getRuntime().getDocument(I(s)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||h.siteId!==i.request.site_id||h.snapshotId!==i.request.base_snapshot_id||h.version!==i.request.document_version)return n("DOCUMENT_VERSION_STALE")}catch{return n("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?d.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==t||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 r=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return Le(i,void 0,s);let o=await this.getRuntime()[t]();return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition??s),o.composition?o:{...o,composition:s}});return n?this.executeWithReceipt(n,r):r()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return le("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let s=this.operationReceipts.get(this.operationReceiptKey(t));return s?.fingerprint===this.operationFingerprint(t)?s.result:null}executeWithReceipt(t,s){if(!this.isActiveReceiptIdentity(t))return s();let n=this.operationReceiptKey(t),r=this.operationFingerprint(t),i=this.operationReceipts.get(n);if(i)return i.fingerprint!==r?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let o={fingerprint:r,result:s(),settled:!1};return this.operationReceipts.set(n,o),o.result.then(()=>{o.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)}),o.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let n=await(this.dependencies.openHistoryStore??Dt)(ns({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let r=n.readDocumentVersion?await n.readDocumentVersion():0,i=this.versionCheckpoints.get(n);i?i.durableVersion=Math.max(i.durableVersion,r):this.versionCheckpoints.set(n,{durableVersion:r,requestedVersion:r,pending:null});let o=this.compositions[0]?.context;if(o){let a=v(o);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,r))}this.createRuntime(n,t)});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(t,s){let n=s?v(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,t));let r=this.activeHistoryStore;if(!r?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??t:t,o=this.versionCheckpoints.get(r);if(o||(o={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(r,o)),i<=o.durableVersion)return Promise.resolve();if(o.requestedVersion=Math.max(o.requestedVersion,i),o.pending)return o.pending;let a=o,p=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await r.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(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let n of t)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??He;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 t=[...this.pendingChangedFiles].sort((r,i)=>r.localeCompare(i));this.pendingChangedFiles.clear();let s=t.some($e)?this.scheduleSnapshotIdentityAdvance():!1,n=t.filter(r=>!fs(r));if(!(n.length===0&&!s)&&this.refreshCompositions(!1))for(let r of n)this.runtime?.notifyFileChanged(r)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=F.readFileSync(R.join(this.options.projectRoot,ce),"utf8"),s=JSON.parse(t),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||ue(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let r=await this.bindHistorySession(t);if(!r.ok)throw new Error(`${r.code}: ${r.message}`)}else this.createRuntime()}catch(r){this.options.snapshotId=s,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${s}: ${r instanceof Error?r.message:String(r)}`);return}let n=new Date().toISOString();for(let r of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:r.context,snapshotId:t,previousSnapshotId:s,at:n};for(let o of this.eventListeners)try{o(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,s)}catch(r){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${r instanceof Error?r.message:String(r)}`)}}refreshCompositions(t=!1){try{let s=ts(this.options.projectRoot),n=zt(s),r=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),i=Kt({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let o=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(t&&(this.launchCandidateEntries=o),this.launchCandidateEntries!==o)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[v(d.context),d])),p=new Map(i.map(d=>[v(d.context),d]));if(this.runtime){for(let[d,h]of a){let f=p.get(d);(!f||f.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(I(h.context))}for(let[d,h]of p){let f=a.get(d);(!f||f.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=r,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,t)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=Ft(t.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let n=this.routes.find(o=>o.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let r=Lt({selector:{routeId:s,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=v(r.context);if(!this.compositions.some(o=>v(o.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return r}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let s=this.runtimeVersionFloors.get(v(t.context));return s===void 0?[]:[{composition:t.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function qe(e){let t=new de(Zt(e),ze.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function Zt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:R.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Jt,port:e.port??Qt,path:e.path??Xt,sessionKey:e.sessionKey??ls(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function es(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function ts(e){let t=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),r=i=>{if(!F.existsSync(i))return;let o;try{o=F.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of o){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;r(R.join(i,a.name));continue}if(!a.isFile())continue;let p=R.join(i,a.name),d="";try{d=F.readFileSync(p,"utf8")}catch{}t.push({path:R.relative(e,p).replaceAll(R.sep,"/"),content:d})}};for(let i of s)r(R.join(e,i));return t.sort((i,o)=>i.path.localeCompare(o.path))}function ss(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function I(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function ns(e){return R.join(R.resolve(e.root),ue(e.siteId),ue(e.snapshotId),le("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function ue(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:le("sha256").update(e).digest("hex").slice(0,32)}function is(){let e=globalThis;return e[De]??=new Map,e[De]}function os(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Le(e,t,s){let n=s??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.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:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:n,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function rs(e){let t=new Bt({maxPayload:je,noServer:!0}),s=new WeakSet,n=i=>{new q({socket:new pe(i),engine:e.engine,validateOperationRequest:o=>jt.safeParse(o).success})},r=(i,o,a)=>{if(!as(i,e))return;let p=cs(i,e);if(!p){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
`),
|
|
5
|
+
`),o.destroy();return}p.authenticatedByHeader&&s.add(i),t.handleUpgrade(i,o,a,d=>{t.emit("connection",d,i)})};return e.server.on("upgrade",r),t.on("connection",(i,o)=>{if(s.has(o)){n(i);return}ds(i,e.sessionKey,()=>{n(i)})}),t.stop=()=>{e.server.off("upgrade",r);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var pe=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",s=>{this.onmessage?.({data:s.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===Ve.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Gt){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,s){this.socket.close(t,s)}};function as(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function cs(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=ae(e.headers["x-vcp-site-edit-key"]),r=Ue(n,t.sessionKey),i=ae(e.headers.host),o=ae(e.headers.origin);return i&&!us(i,t.host,o)?null:o?hs(o,i,t.allowedOrigins)?{authenticatedByHeader:r}:null:r?{authenticatedByHeader:!0}:null}function ds(e,t,s){let n=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Yt),r,i=()=>{clearTimeout(n),e.off("message",r),e.off("close",i)},o=()=>{i(),e.close(1008,"bridge authentication failed")};r=a=>{try{let p=x.parseMessage(a.toString());if(p.type!=="auth"||!Ue(p.payload.key,t)){o();return}i(),e.readyState===Ve.OPEN&&e.send(x.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),s()}catch{o()}},e.on("message",r),e.on("close",i)}function Ue(e,t){if(!e)return!1;let s=Buffer.from(e),n=Buffer.from(t);return s.length===n.length&&Pt(s,n)}function us(e,t,s){let n=Fe(e),r=Fe(t);return n===r||Ke(r)&&Ke(n)&&(!s||he(s,e))||ps(r)&&(!s||he(s,e))}function ps(e){return e==="0.0.0.0"||e==="::"}function Ke(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function hs(e,t,s){return s.includes(e)||(t?he(e,t):!1)}function he(e,t){try{return new URL(e).host===We(t)}catch{return!1}}function Fe(e){let t=We(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function We(e){return e.trim().toLowerCase()}function ae(e){return Array.isArray(e)?e[0]:e}function ls(){return vt(32).toString("base64url")}function $e(e){let t=e.replaceAll("\\","/");return t===ce||t.endsWith(`/${ce}`)}function fs(e){let t=e.replaceAll("\\","/");return $e(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var H=gs;if(!H)throw new Error("site edit engine worker must run inside worker_threads");var M=e=>{H.postMessage(e)},ys=(e,t)=>{try{H.postMessage({type:"result",id:e,ok:!0,value:t})}catch(s){if(s instanceof Error&&s.name==="DataCloneError"){H.postMessage({type:"result",id:e,ok:!0,value:t===void 0?void 0:JSON.parse(JSON.stringify(t))});return}throw s}},{options:_s}=ms,z;try{z=qe({..._s,onSnapshotIdChanged:(e,t)=>{M({type:"snapshot-id-changed",next:e,previous:t})},onHealthChanged:e=>{M({type:"health",health:e})}})}catch(e){M({type:"start-failed",error:X(e)}),process.exit(1)}z.engine.subscribe(e=>{M({type:"event",event:e})});var Ss=async e=>{try{let t=z.engine[e.method],s=await t(...e.args);ys(e.id,s)}catch(t){M({type:"result",id:e.id,ok:!1,error:X(t)})}};H.on("message",e=>{if(e.type==="call"){Ss(e);return}e.type==="stop"&&(z.stop(),H.close())});M({type:"ready",health:z.getHealth()});
|