@vcp-dev/site-edit-bridge 0.11.32 → 0.11.34
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/auto-bootstrap.js +11 -11
- package/dist/client.d.ts +48 -30
- package/dist/client.js +1 -1
- package/dist/engine-worker.js +3 -3
- package/dist/index.js +15 -15
- package/dist/next-dev-server.js +5 -5
- package/dist/portable-remote-asset.js +8 -13
- package/dist/protocol.js +5 -14
- package/dist/server.js +3 -3
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
package/dist/next-dev-server.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import We from"node:http";import{existsSync as G,readFileSync as J}from"node:fs";import{randomUUID as Cs}from"node:crypto";import{createRequire as Nt}from"node:module";import{Socket as Tt}from"node:net";import te from"node:path";import{basename as Bt,dirname as ne,join as se}from"node:path";import{fileURLToPath as Ht}from"node:url";import{createRequire as fs}from"node:module";import{pathToFileURL as gs}from"node:url";import{Worker as ms}from"node:worker_threads";var ze=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function _e(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import Pn from"node:http";import ee from"node:fs";import{createHash as De,randomBytes as On,timingSafeEqual as Nn}from"node:crypto";import O from"node:path";import{WebSocket as It,WebSocketServer as Bn}from"ws";import{createPreviewSiteEditEngineRuntime as Hn,exportPortableBlockFromSnapshot as Ln,readPortableBlockLocalAssetChunk as Mn,openFileHistoryStore as Dn,resolveManagedPageTemplateComposition as jn,scanSiteEditCompositionsFromFiles as Un}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Kn,scanNextAppRouterRoutesFromFiles as $n}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Fn}from"@vcp-dev/site-edit-engine/source-watcher";function Qe(e){if(e.pageBlocks!==void 0&&!Ft(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((h,d)=>[h,d])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(h=>({placementKey:h.placementKey,placementUnitKey:h.placementUnitKey,relation:h.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((h,d)=>h.dynamicDataSummary?[[d,h.dynamicDataSummary]]:[]),c=new Map(e.entries.map((h,d)=>[h.key,d])),p=[];for(let[h,d]of e.entries.entries()){let g=d.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){p.push([h,{kind:g.kind}]);continue}let w=g.siblingKeys.map(I=>{let E=c.get(I);if(E===void 0)throw new Error("Render entry "+d.key+" references missing source sibling "+I);return E});p.push([h,{kind:"source-siblings",siblingEntryIndexes:w}])}let l=h=>{let d=t.get(h);if(typeof d=="number")return d;let g=n.length;return n.push(h),t.set(h,g),g},f=h=>{let d=null;for(let g of Yt(h)){let w=`${d??"root"}\0${g}`,I=s.get(w);if(typeof I=="number"){d=I;continue}let E=o.length;o.push([d,l(g)]),s.set(w,E),d=E}if(d===null)throw new Error("Document key must not be empty");return d};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(h=>{let d=h.pageCompositionUnitKey?r.get(h.pageCompositionUnitKey)??-1:-1;if(h.pageCompositionUnitKey&&d<0)throw new Error(`Render entry ${h.key} references unknown page composition unit ${h.pageCompositionUnitKey}`);return[f(h.key),$t(h.operationSummary),...d>=0?[d]:[]]}),...p.length>0?{pageCompositionActionScopes:p}:{},...e.entries.every(h=>h.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(h=>h.parentKey===null?null:f(h.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function $t(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ft(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!U(n)||!V(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!ie(n.blockKey,256)||!ie(n.definitionKey,512)||!Wt(n.rootRef)||!Vt(n.source)||!zt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>ie(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!qt(n.capabilities)||n.unavailableReasons!==void 0&&!Jt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let o of n.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function Wt(e){return!U(e)||!V(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!qe(e.instanceIndex)||e.instanceCount!==void 0&&(!qe(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Vt(e){return U(e)&&V(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Gt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function zt(e){return U(e)&&V(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&ie(e.key,512)}function qt(e){return U(e)&&V(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 Jt(e){return U(e)&&Object.entries(e).every(([t,n])=>W(t)&&U(n)&&V(n,["code","reason"])&&W(n.code)&&W(n.reason))}function Gt(e){let t=Qt(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function Qt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Je(r)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!Xt(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Je(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,p=>p.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 Je(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Xt(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function ie(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function V(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Yt(e){if(!e)return[];let t=[],n=0,s=Ge(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Ge(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Ge(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var z="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",Re="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var P=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(_(t)&&_(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!_(t)||typeof t.type!="string"?!1:t.type==="request"?tn(t.payload,n):t.type==="response"||t.type==="error"?_(t.payload)&&typeof t.payload.id=="string":t.type==="event"?_(t.payload)&&_(t.payload.event):t.type==="auth"?_(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?_(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&_(t.payload)&&t.payload.ok===!0}},re=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new xe,this.eventDispatcher=new Ee(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=en(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let s=n.payload,{id:o}=s;switch(s.kind){case"initialize-session":{let i=Se(s),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:D({...a,data:{...a.data,document:et(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,cn(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,D(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!Ce(s))throw new k("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,a);return}case"export-portable-block-asset":{if(!Ye(s))throw new k("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(i)!==R(r))throw new k(z,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(i)!==R(r))throw new k(z,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:oe(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(s),r=s.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||R(i)!==R(u))throw new k(z,"History request does not match its cursor operation.")}let a=r?{...r,composition:oe(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(n){let s=P.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:Ie(n),code:we(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new k(Re,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(z,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=Se(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=rn(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(R(t))}async normalizeOperationRequest(t,n){let s={...t,composition:oe(n)};if(s.target.kind==="route"){let o=s.target,i=Se(o),r=await this.resolveAndAssert(i);s.target={...o,composition:oe(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!on(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===an(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(P.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=dn(t);this.sendJson({type:"error",payload:{...s,message:Ie(n),code:we(n)}})}}sendJson(t){this.options.socket.send(P.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let o=await s();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:Ie(o),code:we(o)}})}finally{this.eventDispatcher.flush()}}},Zt=256;function en(e){if(e.length>Zt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return _(t)&&t.type==="ping"&&_(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},Ee=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},xe=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function tn(e,t){if(!_(e)||typeof e.id!="string"||!P.isRequestKind(e.kind))return!1;let n=j(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||be(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ze(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"export-portable-block":return Ce(e);case"export-portable-block-asset":return Ye(e);case"execute":case"get-operation-result":return n&&sn(e.request)&&(e.request.mutationContext===void 0||be(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Xe(e.request);case"undo":case"redo":return n&&(e.request===void 0||Xe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||be(e.mutationContext))}}function Ce(e){if(!j(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!_(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!j(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!Ze(t.selection_ref)||t.cms_schema_proofs!==void 0&&!nn(t.cms_schema_proofs))}function nn(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 n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!_(s)||!Reflect.ownKeys(s).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function Ye(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","file_path","occurrence","offset","capture_id"].includes(n))||!Ce({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0||t.capture_id!==void 0&&(typeof t.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)))}function Xe(e){return _(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")&&j(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ze(e){if(e===void 0)return!0;if(!_(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function sn(e){return _(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&j(e.composition)&&typeof e.kind=="string"&&_(e.target)&&(e.target.kind!=="route"||j(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&_(e.params)}function j(e){return _(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 on(e){return _(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Se(e){if(j(e.composition))return e.composition;throw new k(Re,"A composition selector is required for this request.")}function rn(e){if(_(e)&&j(e.composition))return e.composition;throw new k(Re,"A composition selector is required for execute.")}function oe(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function an(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return _(e)&&e.ok===!0?{...e,composition:t}:e}function cn(e,t){return!_(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:et(e.data)}}function et(e){let t=e;return Qe(t.routeId?t:{...t,routeId:t.composition.routeId})}function _(e){return typeof e=="object"&&e!==null}function be(e){return _(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 we(e){if(!(!_(e)||typeof e.code!="string"||e.code.length===0))return e.code}function Ie(e){return e instanceof Error||_(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function dn(e){try{return P.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var ae=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as it}from"node:crypto";import{constants as ot,promises as ve}from"node:fs";import rt from"node:path";import{createHash as un}from"node:crypto";var ce=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
|
-
`)),tt=Buffer.from(ce.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),nt=e=>`sha256:${un("sha256").update(e).digest("hex")}`,ln=nt(ce),pn=nt(tt);function Y(e,t,n){return e==="next-env.d.ts"&&t===ce.byteLength&&n===ln?tt.byteLength:null}function de(e){return Y(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===pn}function st(){return Uint8Array.from(ce)}var at=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),ct=64;async function ue(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==="..")||at.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>ct||++n>t.size*ct+1)return!1;let a=await ve.readdir(rt.join(e,i),{withFileTypes:!0});for(let u of a){let c=i?`${i}/${u.name}`:u.name;if(!i&&at.has(u.name))continue;if(u.isDirectory()){if(!await o(c,r+1))return!1;continue}if(!u.isFile())return!1;let p=t.get(c);if(p===void 0||s.has(c))return!1;s.add(c);let l=rt.join(e,c),f=await ve.lstat(l),h=typeof p=="string"?Buffer.byteLength(p,"utf8"):p.byteLength,d=`sha256:${it("sha256").update(p).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==h&&f.size!==Y(c,h,d))return!1;let g=it("sha256"),w=await ve.open(l,ot.O_RDONLY|ot.O_NOFOLLOW);try{let E=await w.stat();if(!E.isFile()||E.size!==f.size)return!1;let S=0,b=w.createReadStream({autoClose:!1});for await(let C of b){if(S+=C.byteLength,S>f.size)return b.destroy(),!1;g.update(C)}if(S!==f.size)return!1}finally{await w.close()}let I=`sha256:${g.digest("hex")}`;if((f.size!==h||I!==d)&&!de({file:c,expectedSize:h,expectedDigest:d,actualSize:f.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as pt}from"node:crypto";import{constants as dt,promises as pe}from"node:fs";import ke from"node:path";import{GeneratedSiteCapabilitiesSchema as hn}from"@vcp-dev/contracts";var fn=".vcp/portable-snapshot-proof.json",ut=4*1024*1024,gn=256*1024*1024,mn=1e4,yn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function ht(e){try{let t=ke.join(e.projectRoot,fn),n=await pe.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>ut)return null;let s=JSON.parse(await pe.readFile(t,"utf8"));if(!Z(s)||!le(s,["payload"])||!bn(s.payload,ut))return null;let o=Buffer.from(s.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!Z(r)||!le(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!Z(r.manifest))return null;let a=r.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>mn)return null;let u=hn.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let c=new Map;for(let d of r.trusted_host_file_hashes){if(!Z(d)||!le(d,["path","hash"])||typeof d.path!="string"||!_n(d.path)||!lt(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||c.has(d.path))return null;c.set(d.path,d.hash)}let p=0,l=[],f=new Set;for(let d of a.files){if(!Z(d)||!le(d,["path","hash","size_bytes"])||typeof d.path!="string"||!lt(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||typeof d.size_bytes!="number"||!Number.isSafeInteger(d.size_bytes)||d.size_bytes<0||f.has(d.path)||(f.add(d.path),p+=d.size_bytes,p>gn))return null;l.push({path:d.path,hash:d.hash,size_bytes:d.size_bytes})}let h=new Map;for(let d of l){let g=await Sn(e.projectRoot,d.path,d.size_bytes,d.hash);if(!g||`sha256:${pt("sha256").update(g).digest("hex")}`!==d.hash)return null;h.set(d.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:l},files:h},host_capabilities:u.data,trusted_host_file_hashes:c}}catch{return null}}function _n(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 Sn(e,t,n,s){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=ke.join(i,u);let c=await pe.lstat(i);if(!c.isDirectory()||c.isSymbolicLink())return null}let r=ke.join(i,o.at(-1)),a=await pe.open(r,dt.O_RDONLY|dt.O_NOFOLLOW);try{let u=await a.stat(),c=Y(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==c)return null;let p=[],l=0,f=a.createReadStream({autoClose:!1});for await(let d of f){let g=d;if(l+=g.byteLength,l>u.size)return f.destroy(),null;p.push(g)}if(l!==u.size)return null;let h=Buffer.concat(p,l);return l===n?h:de({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${pt("sha256").update(h).digest("hex")}`})?st():null}finally{await a.close()}}function lt(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!yn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function le(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function bn(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{createHash as wn}from"node:crypto";import In from"node:dns/promises";import En from"node:http";import xn from"node:https";import{isIP as q}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Ae,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Te}from"@vcp-dev/contracts";var v=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function ft(e){if(q(e)===4){let[t,n]=e.split(".").map(Number);return!(t===0||t===10||t===127||t>=224||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&[0,168].includes(n)||t===198&&[18,19,51].includes(n)||t===203&&n===0)}return q(e)===6&&/^[23]/u.test(e)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(e)}function Pe(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.port||t.hash||n==="localhost"||!n.includes(".")&&!q(n)||/\.(?:internal|localhost|local)$/iu.test(n)||q(n)&&!ft(n))throw v();return t}function gt(e){let t=n=>n.every((s,o)=>e[o]===s);return t([137,80,78,71,13,10,26,10])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56,55,97])||t([71,73,70,56,57,97])?"image/gif":t([82,73,70,70])&&Buffer.from(e.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function Rn(e,t){let n=()=>{};try{return await Promise.race([e,new Promise((s,o)=>{n=()=>o(v()),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()})])}finally{t.removeEventListener("abort",n)}}async function Cn(e,t){let n=AbortSignal.any([t,AbortSignal.timeout(15e3)]),s=Pe(e);for(let o=0;o<=3;o++){n.throwIfAborted();let i=s.hostname.replace(/^\[|\]$/gu,""),r=q(i)?[{address:i,family:q(i)}]:await Rn(In.lookup(i,{all:!0}),n);if(n.throwIfAborted(),!r.length||r.some(({address:c})=>!ft(c)))throw v();let a=r.find(c=>c.family===4)??r[0],u=await new Promise((c,p)=>{(s.protocol==="https:"?xn:En).get(s,{agent:!1,signal:n,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,h,d)=>{h.all?d(null,[{address:a.address,family:a.family}]):d(null,a.address,a.family)}},c).on("error",p)});try{let c=u.statusCode??0;if([301,302,303,307,308].includes(c)){if(!u.headers.location||o===3)throw v();let g=Pe(new URL(u.headers.location,s).href);if(s.protocol==="https:"&&g.protocol!=="https:")throw v();s=g;continue}let p=u.headers["content-length"];if(c!==200||u.headers["content-encoding"]&&u.headers["content-encoding"]!=="identity"||p!==void 0&&(!/^\d+$/u.test(p)||Number(p)<1||Number(p)>Te))throw v();let l=[],f=0;for await(let g of u){let w=Buffer.from(g);if(f+=w.length,f>Te)throw v();l.push(w)}if(!f||p!==void 0&&Number(p)!==f)throw v();let h=Buffer.concat(l,f),d=gt(h);if(!d||u.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==d)throw v();return{bytes:h,mime_type:d}}finally{u.destroy()}}throw v()}var he=class{constructor(t=Cn){this.download=t,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(t,n){let s=n.media.filter(f=>f.file_path===t.file_path&&f.occurrence===t.occurrence),o=s[0];if(this.controller.signal.aborted||t.snapshot_digest!==n.snapshot_digest||s.length!==1||!o?.complete||o.cms_field||o.kind==="srcset"||!o.value||!t.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset%Ae)throw v();Pe(o.value);let i=JSON.stringify([t.request,t.snapshot_digest,t.file_path,t.occurrence,t.capture_id,o.value]),r=this.entries.get(i);if(!r){if(t.offset||this.pending.has(i)||this.pending.size>=2||this.entries.size>=16)throw v();this.pending.add(i);try{let f=await this.download(o.value,this.controller.signal);if(this.controller.signal.aborted||!f.bytes.length||f.bytes.length>Te||gt(f.bytes)!==f.mime_type||[...this.entries.values()].reduce((d,g)=>d+g.image.bytes.length,f.bytes.length)>64*1024*1024)throw v();let h=setTimeout(()=>this.remove(i),6e4);h.unref(),r={image:f,timer:h},this.entries.set(i,r)}finally{this.pending.delete(i)}}let{bytes:a,mime_type:u}=r.image;if(t.offset>=a.length)throw v();let c=wn("sha256").update(a).digest("hex"),p={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[u],l={complete:!0,snapshot_digest:t.snapshot_digest,file_path:t.file_path,occurrence:t.occurrence,path:`public/__portable_remote__/${c}.${p}`,mime_type:u,byte_size:a.length,digest_sha256:c,offset:t.offset,data_base64:Buffer.from(a.subarray(t.offset,t.offset+Ae)).toString("base64")};return t.offset+Ae>=a.length&&this.remove(i),l}remove(t){let n=this.entries.get(t);n&&clearTimeout(n.timer),this.entries.delete(t)}dispose(){this.controller.abort();for(let t of this.entries.keys())this.remove(t)}};import{PortableCmsSchemaEnvelopeSchema as vn,PortableCmsSchemaStatementSchema as kn}from"@vcp-dev/contracts";var An=3e4;function mt(e){try{let t=vn.safeParse(e.proof);if(!t.success||!Tn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),o=JSON.parse(s);if(JSON.stringify(o)!==s)return null;let i=kn.safeParse(o),r=e.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>r+An||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Tn(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 Wn,SiteEditPortableExportRequestSchema as Vn,SiteEditPortableExportResultSchema as zn,SiteEditPortableAssetRequestSchema as qn,SiteEditPortableAssetResultSchema as Jn,computeSiteEditCompositionKey as K}from"@vcp-dev/contracts";var Gn="127.0.0.1",Qn=30218,Xn="/__vcp/site-edit/bridge",Et=6*1024*1024,Yn=Et*2,Zn=3e3,yt=50,Ne=".vcp/current-snapshot.json",_t="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function xt(e,t,n={}){let s=new Be(Ct(t),e,!1,n);return s.start({listen:!1}),s}var Be=class{constructor(t,n=Pn.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ae,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null,this.portableRemoteAssets=new he}start(t={}){if(!this.isStarted){this.stopping=!1;try{ee.mkdirSync(O.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=je({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new Fn({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??yt,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=is(),n=os(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let s=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??Hn)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,s?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let s=ns(t.composition),o=this.getRuntime(),i=T(s);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,s);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let o=n.getDocument(s);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return St(s,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let o=mt({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;n.push(o)}return n}async exportPortableBlock(t,n,s){let o=(b,C,A)=>({complete:!1,unresolved:[{code:b,path:C,message:A}]}),i=Vn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=T(n);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 b=this.getRuntime().getDocument(a).data;return{site_id:b.siteId,snapshot_id:b.snapshotId,document_version:b.version}},p=c();if(p.site_id!==r.site_id||p.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(p.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(b=>ht({...b,projectRoot:this.options.projectRoot})),h;try{h=await f({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!h)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let d=new Map([...h.snapshot.files].map(([b,C])=>[b,typeof C=="string"?C:new Uint8Array(C)])),g={...h,snapshot:{...h.snapshot,files:d}};if(!await ue(this.options.projectRoot,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:w,...I}=r,E=await Ln({...I,...g,trusted_cms_schemas:l,read_current_identity:c}),S=zn.safeParse(E);if(!S.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(S.data.complete&&(S.data.site_id!==r.site_id||S.data.base_snapshot_id!==r.base_snapshot_id||S.data.document_version!==r.document_version||S.data.target.blockKey!==r.target.blockKey||S.data.target.composition.routeId!==a.routeId||S.data.target.composition.templateId!==a.templateId||S.data.selection_ref.key!==r.selection_ref.key||S.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||S.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(S.data.complete||S.data.cms_candidates){if(!await ue(this.options.projectRoot,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let b=c();if(this.options.snapshotId!==r.base_snapshot_id||b.site_id!==r.site_id||b.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(b.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.");S.data.complete&&s?.(d)}return S.data}async exportPortableBlockAsset(t,n){let s=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=qn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,n,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=a.media.find(l=>l.file_path===i.file_path&&l.occurrence===i.occurrence),c;try{c=u?.value&&/^https?:\/\//iu.test(u.value)?await this.portableRemoteAssets.read(i,a):Mn({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset})}catch{return s("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let p=Jn.safeParse(c);if(!p.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!p.data.complete)return p.data;if(!await ue(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(T(n)).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 s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?p.data:s("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return St(i,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return s?this.executeWithReceipt(s,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return De("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??Dn)(ss({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=K(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?K(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let 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 s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??yt;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let n=t.some(At)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!hs(o));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let o of s)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=ee.readFileSync(O.join(this.options.projectRoot,Ne),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||He(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=ts(this.options.projectRoot),s=$n(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(c=>({...c})),i=Un({files:n});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[K(c.context),c])),u=new Map(i.map(c=>[K(c.context),c]));if(this.runtime){for(let[c,p]of a){let l=u.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.unregisterComposition(T(p.context))}for(let[c,p]of u){let l=a.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.registerComposition(p.context,p.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Kn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=jn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=K(o.context);if(!this.compositions.some(r=>K(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(K(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Rt(e){return Ct(e)}function Ct(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:O.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Gn,port:e.port??Qn,path:e.path??Xn,sessionKey:e.sessionKey??ps(),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=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!ee.existsSync(i))return;let r;try{r=ee.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;o(O.join(i,a.name));continue}if(!a.isFile())continue;let u=O.join(i,a.name),c="";try{c=ee.readFileSync(u,"utf8")}catch{}t.push({path:O.relative(e,u).replaceAll(O.sep,"/"),content:c})}};for(let i of n)o(O.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function ns(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function ss(e){return O.join(O.resolve(e.root),He(e.siteId),He(e.snapshotId),De("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function He(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:De("sha256").update(e).digest("hex").slice(0,32)}function is(){let e=globalThis;return e[_t]??=new Map,e[_t]}function os(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function St(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function je(e){let t=new Bn({maxPayload:Et,noServer:!0}),n=new WeakSet,s=i=>{new re({socket:new Le(i),engine:e.engine,validateOperationRequest:r=>Wn.safeParse(r).success})},o=(i,r,a)=>{if(!rs(i,e))return;let u=as(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import Ve from"node:http";import{existsSync as G,readFileSync as J}from"node:fs";import{randomUUID as Cs}from"node:crypto";import{createRequire as Nt}from"node:module";import{Socket as Tt}from"node:net";import te from"node:path";import{basename as Bt,dirname as ne,join as se}from"node:path";import{fileURLToPath as Ht}from"node:url";import{createRequire as fs}from"node:module";import{pathToFileURL as gs}from"node:url";import{Worker as ms}from"node:worker_threads";var ze=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function _e(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import Pn from"node:http";import ee from"node:fs";import{createHash as De,randomBytes as On,timingSafeEqual as Nn}from"node:crypto";import O from"node:path";import{WebSocket as It,WebSocketServer as Bn}from"ws";import{createPreviewSiteEditEngineRuntime as Hn,exportPortableBlockFromSnapshot as Ln,readPortableBlockLocalAssetChunk as Mn,openFileHistoryStore as Dn,resolveManagedPageTemplateComposition as jn,scanSiteEditCompositionsFromFiles as Un}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Kn,scanNextAppRouterRoutesFromFiles as $n}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Fn}from"@vcp-dev/site-edit-engine/source-watcher";function Qe(e){if(e.pageBlocks!==void 0&&!Ft(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,i=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(o.map((p,d)=>[p,d])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((p,d)=>p.dynamicDataSummary?[[d,p.dynamicDataSummary]]:[]),c=new Map(e.entries.map((p,d)=>[p.key,d])),h=[];for(let[p,d]of e.entries.entries()){let g=d.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){h.push([p,{kind:g.kind}]);continue}let w=g.siblingKeys.map(I=>{let E=c.get(I);if(E===void 0)throw new Error("Render entry "+d.key+" references missing source sibling "+I);return E});h.push([p,{kind:"source-siblings",siblingEntryIndexes:w}])}let l=p=>{let d=t.get(p);if(typeof d=="number")return d;let g=n.length;return n.push(p),t.set(p,g),g},f=p=>{let d=null;for(let g of Yt(p)){let w=`${d??"root"}\0${g}`,I=s.get(w);if(typeof I=="number"){d=I;continue}let E=i.length;i.push([d,l(g)]),s.set(w,E),d=E}if(d===null)throw new Error("Document key must not be empty");return d};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:i,entries:e.entries.map(p=>{let d=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&d<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[f(p.key),$t(p.operationSummary),...d>=0?[d]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:f(p.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function $t(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ft(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!U(n)||!W(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!oe(n.blockKey,256)||!oe(n.definitionKey,512)||!Vt(n.rootRef)||!Wt(n.source)||!zt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>oe(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!V(n.placementUnitKey)||!qt(n.capabilities)||n.unavailableReasons!==void 0&&!Jt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let i of n.siblingBlockKeys){let o=t.get(i);if(!o)return!1;let r=o.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function Vt(e){return!U(e)||!W(e,["key","instanceIndex","instanceCount"])||!V(e.key)||e.instanceIndex!==void 0&&!qe(e.instanceIndex)||e.instanceCount!==void 0&&(!qe(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Wt(e){return U(e)&&W(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Gt(e.file)&&V(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function zt(e){return U(e)&&W(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&oe(e.key,512)}function qt(e){return U(e)&&W(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 Jt(e){return U(e)&&Object.entries(e).every(([t,n])=>V(t)&&U(n)&&W(n,["code","reason"])&&V(n.code)&&V(n.reason))}function Gt(e){let t=Qt(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(o=>!o||o==="."||o===".."||o.startsWith(".")||o==="node_modules"||o.toLowerCase()==="package.json"||o==="recipes"||o.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(o=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(o.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(o=>e===o||e.startsWith(`${o}/`))||t}function Qt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Je(r)),i=s?n[0]:n.pop(),o=s?n.slice(1):n;if(s&&o.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(i)||!Xt(`/${o.join("/")}`)||o.some(r=>r.includes("[")||r.includes("]")?!Je(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=i.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,h=>h.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,"")===i}catch{return!1}}function Je(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Xt(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function oe(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function V(e){return typeof e=="string"&&e.length>0}function W(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Yt(e){if(!e)return[];let t=[],n=0,s=Ge(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Ge(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Ge(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var z="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",Re="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var P=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(_(t)&&_(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!_(t)||typeof t.type!="string"?!1:t.type==="request"?tn(t.payload,n):t.type==="response"||t.type==="error"?_(t.payload)&&typeof t.payload.id=="string":t.type==="event"?_(t.payload)&&_(t.payload.event):t.type==="auth"?_(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?_(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&_(t.payload)&&t.payload.ok===!0}},re=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new xe,this.eventDispatcher=new Ee(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=en(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(i){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:i instanceof Error?i.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let s=n.payload,{id:i}=s;switch(s.kind){case"initialize-session":{let o=Se(s),r=await this.resolve(o),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:i,kind:s.kind,result:D({...a,data:{...a.data,document:et(a.data.document)}},r.context)}});return}case"get-document":{let o=await this.resolveWireContext(s),r=await this.options.engine.getDocument(o);this.sendResult(i,s.kind,cn(r,o));return}case"get-history-status":{let o=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(o);this.sendResult(i,s.kind,D(r,o));return}case"get-style-context":{let o=await this.resolveWireContext(s);this.sendResult(i,s.kind,D(await this.options.engine.getStyleContext(o),o));return}case"get-object-edit-context":{let o=await this.resolveWireContext(s);this.sendResult(i,s.kind,D(await this.options.engine.getObjectEditContext(s.key,o,s.selectionRef),o));return}case"get-class-name-source":{let o=await this.resolveWireContext(s);this.sendResult(i,s.kind,D(await this.options.engine.getClassNameSource(s.key,o),o));return}case"get-source-tree":{let o=await this.resolveWireContext(s);this.sendResult(i,s.kind,D(await this.options.engine.getSourceTree(o),o));return}case"get-source-file":{let o=await this.resolveWireContext(s);this.sendResult(i,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:o}),o));return}case"export-portable-block":{if(!Ce(s))throw new v("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let o=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(R(o)!==R(r))throw new v(z,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,o):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(i,s.kind,a);return}case"export-portable-block-asset":{if(!Ye(s))throw new v("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let o=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(R(o)!==R(r))throw new v(z,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,o):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(i,s.kind,a);return}case"resolve-source-location":{let o=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:o}),o);this.sendResult(i,s.kind,r);return}case"execute":case"get-operation-result":{let o=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(o)!==R(r))throw new v(z,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,o);if(s.kind==="get-operation-result"){this.sendResult(i,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(i,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let o=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(o)!==R(r))throw new v(z,"History receipt composition does not match the active session.");this.sendResult(i,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:ie(r)})??null);return}case"undo":case"redo":{let o=await this.resolveWireContext(s),r=s.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||R(o)!==R(u))throw new v(z,"History request does not match its cursor operation.")}let a=r?{...r,composition:ie(o)}:void 0;await this.handleBufferedOperation(i,s.kind,()=>s.kind==="undo"?this.options.engine.undo(o,a):this.options.engine.redo(o,a));return}}}catch(n){let s=P.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:Ie(n),code:we(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new v(Re,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new v(z,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=Se(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=rn(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(R(t))}async normalizeOperationRequest(t,n){let s={...t,composition:ie(n)};if(s.target.kind==="route"){let i=s.target,o=Se(i),r=await this.resolveAndAssert(o);s.target={...i,composition:ie(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!on(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===an(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(P.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=dn(t);this.sendJson({type:"error",payload:{...s,message:Ie(n),code:we(n)}})}}sendJson(t){this.options.socket.send(P.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let i=await s();this.sendResult(t,n,i)}catch(i){this.sendJson({type:"error",payload:{id:t,kind:n,message:Ie(i),code:we(i)}})}finally{this.eventDispatcher.flush()}}},Zt=256;function en(e){if(e.length>Zt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return _(t)&&t.type==="ping"&&_(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var v=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},Ee=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},xe=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function tn(e,t){if(!_(e)||typeof e.id!="string"||!P.isRequestKind(e.kind))return!1;let n=j(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||be(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ze(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"export-portable-block":return Ce(e);case"export-portable-block-asset":return Ye(e);case"execute":case"get-operation-result":return n&&sn(e.request)&&(e.request.mutationContext===void 0||be(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Xe(e.request);case"undo":case"redo":return n&&(e.request===void 0||Xe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||be(e.mutationContext))}}function Ce(e){if(!j(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["export_schema_version","site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||t.export_schema_version!==2||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||!_(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!j(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!Ze(t.selection_ref)||t.cms_schema_proofs!==void 0&&!nn(t.cms_schema_proofs))}function nn(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 n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!_(s)||!Reflect.ownKeys(s).every(o=>typeof o=="string"&&o==="payload"))return!1;let i=Object.getOwnPropertyDescriptor(s,"payload");if(!i||!("value"in i)||typeof i.value!="string"||i.value.length<1||i.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(i.value))return!1}return!0}function Ye(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","asset_key","offset","capture_id"].includes(n))||!Ce({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.asset_key!="string"||!/^asset-[a-f0-9]{64}$/u.test(t.asset_key)||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0||t.capture_id!==void 0&&(typeof t.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)))}function Xe(e){return _(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")&&j(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ze(e){if(e===void 0)return!0;if(!_(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function sn(e){return _(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&j(e.composition)&&typeof e.kind=="string"&&_(e.target)&&(e.target.kind!=="route"||j(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&_(e.params)}function j(e){return _(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 on(e){return _(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Se(e){if(j(e.composition))return e.composition;throw new v(Re,"A composition selector is required for this request.")}function rn(e){if(_(e)&&j(e.composition))return e.composition;throw new v(Re,"A composition selector is required for execute.")}function ie(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function an(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return _(e)&&e.ok===!0?{...e,composition:t}:e}function cn(e,t){return!_(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:et(e.data)}}function et(e){let t=e;return Qe(t.routeId?t:{...t,routeId:t.composition.routeId})}function _(e){return typeof e=="object"&&e!==null}function be(e){return _(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 we(e){if(!(!_(e)||typeof e.code!="string"||e.code.length===0))return e.code}function Ie(e){return e instanceof Error||_(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function dn(e){try{return P.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var ae=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as ot}from"node:crypto";import{constants as it,promises as ke}from"node:fs";import rt from"node:path";import{createHash as un}from"node:crypto";var ce=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
|
+
`)),tt=Buffer.from(ce.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),nt=e=>`sha256:${un("sha256").update(e).digest("hex")}`,ln=nt(ce),pn=nt(tt);function Y(e,t,n){return e==="next-env.d.ts"&&t===ce.byteLength&&n===ln?tt.byteLength:null}function de(e){return Y(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===pn}function st(){return Uint8Array.from(ce)}var at=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),ct=64;async function ue(e,t){try{if(!t.size)return!1;for(let[o,r]of t)if(!o||o.startsWith("/")||o.includes("\\")||o.includes("\0")||o.split("/").some(a=>!a||a==="."||a==="..")||at.has(o.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,i=async(o,r)=>{if(r>ct||++n>t.size*ct+1)return!1;let a=await ke.readdir(rt.join(e,o),{withFileTypes:!0});for(let u of a){let c=o?`${o}/${u.name}`:u.name;if(!o&&at.has(u.name))continue;if(u.isDirectory()){if(!await i(c,r+1))return!1;continue}if(!u.isFile())return!1;let h=t.get(c);if(h===void 0||s.has(c))return!1;s.add(c);let l=rt.join(e,c),f=await ke.lstat(l),p=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,d=`sha256:${ot("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==p&&f.size!==Y(c,p,d))return!1;let g=ot("sha256"),w=await ke.open(l,it.O_RDONLY|it.O_NOFOLLOW);try{let E=await w.stat();if(!E.isFile()||E.size!==f.size)return!1;let S=0,b=w.createReadStream({autoClose:!1});for await(let C of b){if(S+=C.byteLength,S>f.size)return b.destroy(),!1;g.update(C)}if(S!==f.size)return!1}finally{await w.close()}let I=`sha256:${g.digest("hex")}`;if((f.size!==p||I!==d)&&!de({file:c,expectedSize:p,expectedDigest:d,actualSize:f.size,actualDigest:I}))return!1}return!0};return await i("",0)&&s.size===t.size}catch{return!1}}import{createHash as pt}from"node:crypto";import{constants as dt,promises as pe}from"node:fs";import ve from"node:path";import{GeneratedSiteCapabilitiesSchema as hn}from"@vcp-dev/contracts";var fn=".vcp/portable-snapshot-proof.json",ut=4*1024*1024,gn=256*1024*1024,mn=1e4,yn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function ht(e){try{let t=ve.join(e.projectRoot,fn),n=await pe.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>ut)return null;let s=JSON.parse(await pe.readFile(t,"utf8"));if(!Z(s)||!le(s,["payload"])||!bn(s.payload,ut))return null;let i=Buffer.from(s.payload,"base64url"),o=new TextDecoder("utf-8",{fatal:!0}).decode(i),r=JSON.parse(o);if(JSON.stringify(r)!==o||!Z(r)||!le(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!Z(r.manifest))return null;let a=r.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>mn)return null;let u=hn.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let c=new Map;for(let d of r.trusted_host_file_hashes){if(!Z(d)||!le(d,["path","hash"])||typeof d.path!="string"||!_n(d.path)||!lt(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||c.has(d.path))return null;c.set(d.path,d.hash)}let h=0,l=[],f=new Set;for(let d of a.files){if(!Z(d)||!le(d,["path","hash","size_bytes"])||typeof d.path!="string"||!lt(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||typeof d.size_bytes!="number"||!Number.isSafeInteger(d.size_bytes)||d.size_bytes<0||f.has(d.path)||(f.add(d.path),h+=d.size_bytes,h>gn))return null;l.push({path:d.path,hash:d.hash,size_bytes:d.size_bytes})}let p=new Map;for(let d of l){let g=await Sn(e.projectRoot,d.path,d.size_bytes,d.hash);if(!g||`sha256:${pt("sha256").update(g).digest("hex")}`!==d.hash)return null;p.set(d.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:l},files:p},host_capabilities:u.data,trusted_host_file_hashes:c}}catch{return null}}function _n(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 Sn(e,t,n,s){let i=t.split("/"),o=e;for(let u of i.slice(0,-1)){o=ve.join(o,u);let c=await pe.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())return null}let r=ve.join(o,i.at(-1)),a=await pe.open(r,dt.O_RDONLY|dt.O_NOFOLLOW);try{let u=await a.stat(),c=Y(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==c)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let d of f){let g=d;if(l+=g.byteLength,l>u.size)return f.destroy(),null;h.push(g)}if(l!==u.size)return null;let p=Buffer.concat(h,l);return l===n?p:de({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${pt("sha256").update(p).digest("hex")}`})?st():null}finally{await a.close()}}function lt(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!yn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function le(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function bn(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{createHash as wn}from"node:crypto";import In from"node:dns/promises";import En from"node:http";import xn from"node:https";import{isIP as q}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Ae,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Te}from"@vcp-dev/contracts";var k=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function ft(e){if(q(e)===4){let[t,n]=e.split(".").map(Number);return!(t===0||t===10||t===127||t>=224||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&[0,168].includes(n)||t===198&&[18,19,51].includes(n)||t===203&&n===0)}return q(e)===6&&/^[23]/u.test(e)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(e)}function Pe(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.port||t.hash||n==="localhost"||!n.includes(".")&&!q(n)||/\.(?:internal|localhost|local)$/iu.test(n)||q(n)&&!ft(n))throw k();return t}function gt(e){let t=n=>n.every((s,i)=>e[i]===s);return t([137,80,78,71,13,10,26,10])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56,55,97])||t([71,73,70,56,57,97])?"image/gif":t([82,73,70,70])&&Buffer.from(e.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function Rn(e,t){let n=()=>{};try{return await Promise.race([e,new Promise((s,i)=>{n=()=>i(k()),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()})])}finally{t.removeEventListener("abort",n)}}async function Cn(e,t){let n=AbortSignal.any([t,AbortSignal.timeout(15e3)]),s=Pe(e);for(let i=0;i<=3;i++){n.throwIfAborted();let o=s.hostname.replace(/^\[|\]$/gu,""),r=q(o)?[{address:o,family:q(o)}]:await Rn(In.lookup(o,{all:!0}),n);if(n.throwIfAborted(),!r.length||r.some(({address:c})=>!ft(c)))throw k();let a=r.find(c=>c.family===4)??r[0],u=await new Promise((c,h)=>{(s.protocol==="https:"?xn:En).get(s,{agent:!1,signal:n,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,p,d)=>{p.all?d(null,[{address:a.address,family:a.family}]):d(null,a.address,a.family)}},c).on("error",h)});try{let c=u.statusCode??0;if([301,302,303,307,308].includes(c)){if(!u.headers.location||i===3)throw k();let g=Pe(new URL(u.headers.location,s).href);if(s.protocol==="https:"&&g.protocol!=="https:")throw k();s=g;continue}let h=u.headers["content-length"];if(c!==200||u.headers["content-encoding"]&&u.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>Te))throw k();let l=[],f=0;for await(let g of u){let w=Buffer.from(g);if(f+=w.length,f>Te)throw k();l.push(w)}if(!f||h!==void 0&&Number(h)!==f)throw k();let p=Buffer.concat(l,f),d=gt(p);if(!d||u.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==d)throw k();return{bytes:p,mime_type:d}}finally{u.destroy()}}throw k()}var he=class{constructor(t=Cn){this.download=t,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(t,n){let s=n.asset_catalog.filter(p=>p.asset_key===t.asset_key),i=s[0];if(this.controller.signal.aborted||t.snapshot_digest!==n.snapshot_digest||s.length!==1||i?.origin.kind!=="remote"||!t.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset%Ae)throw k();let o=i.origin.url;Pe(o);let r=JSON.stringify([t.request,t.snapshot_digest,t.asset_key,t.capture_id,o]),a=this.entries.get(r);if(!a){if(t.offset||this.pending.has(r)||this.pending.size>=2||this.entries.size>=16)throw k();this.pending.add(r);try{let p=await this.download(o,this.controller.signal);if(this.controller.signal.aborted||!p.bytes.length||p.bytes.length>Te||gt(p.bytes)!==p.mime_type||[...this.entries.values()].reduce((g,w)=>g+w.image.bytes.length,p.bytes.length)>64*1024*1024)throw k();let d=setTimeout(()=>this.remove(r),6e4);d.unref(),a={image:p,timer:d},this.entries.set(r,a)}finally{this.pending.delete(r)}}let{bytes:u,mime_type:c}=a.image;if(t.offset>=u.length)throw k();let h=wn("sha256").update(u).digest("hex"),l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[c],f={complete:!0,snapshot_digest:t.snapshot_digest,asset_key:t.asset_key,path:`public/__portable_remote__/${h}.${l}`,mime_type:c,byte_size:u.length,digest_sha256:h,offset:t.offset,data_base64:Buffer.from(u.subarray(t.offset,t.offset+Ae)).toString("base64")};return t.offset+Ae>=u.length&&this.remove(r),f}remove(t){let n=this.entries.get(t);n&&clearTimeout(n.timer),this.entries.delete(t)}dispose(){this.controller.abort();for(let t of this.entries.keys())this.remove(t)}};import{PortableCmsSchemaEnvelopeSchema as kn,PortableCmsSchemaStatementSchema as vn}from"@vcp-dev/contracts";var An=3e4;function mt(e){try{let t=kn.safeParse(e.proof);if(!t.success||!Tn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),i=JSON.parse(s);if(JSON.stringify(i)!==s)return null;let o=vn.safeParse(i),r=e.now??Date.now();return!o.success||!Number.isSafeInteger(r)||o.data.site_id!==e.site_id||o.data.base_snapshot_id!==e.base_snapshot_id||o.data.issued_at>r+An||o.data.expires_at<=r?null:{source_slug:o.data.slug,evidence_path:`trusted-cms-schema:${o.data.slug}`,fields:o.data.fields}}catch{return null}}function Tn(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 Vn,SiteEditPortableExportRequestSchema as Wn,SiteEditPortableExportResultSchema as zn,SiteEditPortableAssetRequestSchema as qn,SiteEditPortableAssetResultSchema as Jn,computeSiteEditCompositionKey as K}from"@vcp-dev/contracts";var Gn="127.0.0.1",Qn=30218,Xn="/__vcp/site-edit/bridge",Et=6*1024*1024,Yn=Et*2,Zn=3e3,yt=50,Ne=".vcp/current-snapshot.json",_t="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function xt(e,t,n={}){let s=new Be(Ct(t),e,!1,n);return s.start({listen:!1}),s}var Be=class{constructor(t,n=Pn.createServer((o,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,i={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ae,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null,this.portableRemoteAssets=new he}start(t={}){if(!this.isStarted){this.stopping=!1;try{ee.mkdirSync(O.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=je({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new Fn({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??yt,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=os(),n=is(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;try{t(n)}catch(i){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${i instanceof Error?i.message:String(i)}`)}}}createRuntime(t,n=null){let s=this.runtime;this.activeHistoryStore=t??null;let i=(this.dependencies.createRuntime??Hn)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version,"composition"in o?o.composition:void 0);for(let r of this.eventListeners)r(o)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=i,this.activeHistorySessionId=n,s?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let s=ns(t.composition),i=this.getRuntime(),o=T(s);await i.initializeComposition(o);let a=i.getDocument(o).data;await this.recordRuntimeVersion(a.version,s);let u=(await i.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let i=n.getDocument(s);return await this.recordRuntimeVersion(i.data.version,t),{...i,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return St(s,t);let i=await this.getRuntime().executeOperation(t);return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion,i.composition),i})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let i=mt({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!i)return null;n.push(i)}return n}async exportPortableBlock(t,n,s){let i=(b,C,A)=>({complete:!1,unresolved:[{code:b,path:C,message:A}]}),o=Wn.safeParse(t);if(!o.success)return i("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=o.data,a=T(n);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return i("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 i("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let c=()=>{let b=this.getRuntime().getDocument(a).data;return{site_id:b.siteId,snapshot_id:b.snapshotId,document_version:b.version}},h=c();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return i("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return i("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return i("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(b=>ht({...b,projectRoot:this.options.projectRoot})),p;try{p=await f({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return i("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!p)return i("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let d=new Map([...p.snapshot.files].map(([b,C])=>[b,typeof C=="string"?C:new Uint8Array(C)])),g={...p,snapshot:{...p.snapshot,files:d}};if(!await ue(this.options.projectRoot,d))return i("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:w,...I}=r,E=await Ln({...I,...g,trusted_cms_schemas:l,read_current_identity:c}),S=zn.safeParse(E);if(!S.success)return i("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(S.data.complete&&(S.data.site_id!==r.site_id||S.data.base_snapshot_id!==r.base_snapshot_id||S.data.document_version!==r.document_version||S.data.target.blockKey!==r.target.blockKey||S.data.target.composition.routeId!==a.routeId||S.data.target.composition.templateId!==a.templateId||S.data.selection_ref.key!==r.selection_ref.key||S.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||S.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return i("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(S.data.complete||S.data.cms_candidates){if(!await ue(this.options.projectRoot,d))return i("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let b=c();if(this.options.snapshotId!==r.base_snapshot_id||b.site_id!==r.site_id||b.snapshot_id!==r.base_snapshot_id)return i("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(b.document_version!==r.document_version)return i("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return i("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(r))return i("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");S.data.complete&&s?.(d)}return S.data}async exportPortableBlockAsset(t,n){let s=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),i=qn.safeParse(t);if(!i.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let o=i.data,r,a=await this.exportPortableBlock(o.request,n,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==o.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=a.asset_catalog.find(l=>l.asset_key===o.asset_key),c;try{c=u?.origin.kind==="remote"?await this.portableRemoteAssets.read(o,a):Mn({exported:a,snapshot_files:r,snapshot_digest:o.snapshot_digest,asset_key:o.asset_key,offset:o.offset})}catch{return s("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=Jn.safeParse(c);if(!h.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await ue(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(T(n)).data;if(this.options.snapshotId!==o.request.base_snapshot_id||l.siteId!==o.request.site_id||l.snapshotId!==o.request.base_snapshot_id||l.version!==o.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(o.request)?h.data:s("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let i=()=>this.mutationQueue.run(async()=>{let o=await this.bindHistorySession(this.options.snapshotId);if(!o.ok)return St(o,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return s?this.executeWithReceipt(s,i):i()}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 De("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),i=this.operationFingerprint(t),o=this.operationReceipts.get(s);if(o)return o.fingerprint!==i?Promise.reject(new Error("Operation ID was reused with a different request.")):o.result;let r={fingerprint:i,result:n(),settled:!1};return this.operationReceipts.set(s,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(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??Dn)(ss({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let i=s.readDocumentVersion?await s.readDocumentVersion():0,o=this.versionCheckpoints.get(s);o?o.durableVersion=Math.max(o.durableVersion,i):this.versionCheckpoints.set(s,{durableVersion:i,requestedVersion:i,pending:null});let r=this.compositions[0]?.context;if(r){let a=K(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,i))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?K(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let i=this.activeHistoryStore;if(!i?.writeDocumentVersion)return Promise.resolve();let o=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(i);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(i,r)),o<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,o),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await i.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 s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??yt;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((i,o)=>i.localeCompare(o));this.pendingChangedFiles.clear();let n=t.some(At)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(i=>!hs(i));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let i of s)this.runtime?.notifyFileChanged(i)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=ee.readFileSync(O.join(this.options.projectRoot,Ne),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||He(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let i=await this.bindHistorySession(t);if(!i.ok)throw new Error(`${i.code}: ${i.message}`)}else this.createRuntime()}catch(i){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${i instanceof Error?i.message:String(i)}`);return}let s=new Date().toISOString();for(let i of this.compositions){let o={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:i.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(o)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(i){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${i instanceof Error?i.message:String(i)}`)}}refreshCompositions(t=!1){try{let n=ts(this.options.projectRoot),s=$n(n),i=s.length>0?s:(this.options.runtime.routes??[]).map(c=>({...c})),o=Un({files:n});if(o.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(o.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[K(c.context),c])),u=new Map(o.map(c=>[K(c.context),c]));if(this.runtime){for(let[c,h]of a){let l=u.get(c);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(T(h.context))}for(let[c,h]of u){let l=a.get(c);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=i,this.compositions=o,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Kn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=jn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),o=K(i.context);if(!this.compositions.some(r=>K(r.context)===o))throw new Error(`Composition is not registered by the preview bridge: ${o}`);return i}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(K(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Rt(e){return Ct(e)}function Ct(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:O.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Gn,port:e.port??Qn,path:e.path??Xn,sessionKey:e.sessionKey??ps(),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=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),i=o=>{if(!ee.existsSync(o))return;let r;try{r=ee.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;i(O.join(o,a.name));continue}if(!a.isFile())continue;let u=O.join(o,a.name),c="";try{c=ee.readFileSync(u,"utf8")}catch{}t.push({path:O.relative(e,u).replaceAll(O.sep,"/"),content:c})}};for(let o of n)i(O.join(e,o));return t.sort((o,r)=>o.path.localeCompare(r.path))}function ns(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function ss(e){return O.join(O.resolve(e.root),He(e.siteId),He(e.snapshotId),De("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function He(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:De("sha256").update(e).digest("hex").slice(0,32)}function os(){let e=globalThis;return e[_t]??=new Map,e[_t]}function is(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function St(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function je(e){let t=new Bn({maxPayload:Et,noServer:!0}),n=new WeakSet,s=o=>{new re({socket:new Le(o),engine:e.engine,validateOperationRequest:r=>Vn.safeParse(r).success})},i=(o,r,a)=>{if(!rs(o,e))return;let u=as(o,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
`),r.destroy();return}u.authenticatedByHeader&&n.add(
|
|
6
|
-
`);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function Rs(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var vs="next",ks="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Lt="127.0.0.1",As=3e3,me="/__vcp/site-edit/bridge",Mt="/__vcp/site-edit/health",Ts="probe",Ps="render",Pt="/_error",ye="/__vcp/site-edit/client/",Os=`${ye}auto-bootstrap.js`,Dt='data-vcp-site-edit-bootstrap="true"',Ns=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Bs="@vcp-dev/site-edit-engine/webpack-loader",Hs=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Ls=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ms=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-block-thumbnail.js","frame-block-thumbnail-renderer.js","frame-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Ao(e={},t={}){let n=t.process??process,s=t.createServer??We.createServer,o=t.attachBridgeServer??(n.env[ks]==="1"?xt:Ue),i=t.loadNext??fi,r=te.resolve(e.projectRoot??process.cwd()),a=e.host??Lt,u=e.port??_i(n.env.PORT)??As,c=e.bridgePath??me,p=Ws(c),l=di(),f=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",h=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,d=await i(r),g=Ds(r),w=d({dev:!0,dir:r,hostname:a,port:u,...js(g)}),I=w.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",S=e.snapshotId??n.env.VCP_SNAPSHOT_ID??yi(r),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=b?.trim()?te.resolve(b):void 0,A=null,Q={launchId:Cs(),pid:process.pid,snapshotId:S},B=s((L,m)=>{Xs({basePath:f,bridgePath:c,bridgeHealthPath:p,bridgeSessionKey:l,getBridgeHealth:()=>A?.getHealth()??si(c),launch:Q,runRenderProbe:()=>ei(w),handle:I,request:L,response:m}).catch(y=>{console.error(y),m.headersSent||(m.statusCode=500),m.end("site edit preview request failed")})}),$=null,H=null,X=()=>H||(ge(()=>n.off("SIGINT",F)),ge(()=>n.off("SIGTERM",F)),ge(()=>$?.()),$=null,ge(()=>A?.stop()),A=null,H=Promise.allSettled([bi(B),wi(()=>w.close())]).then(()=>{}),H),F=()=>{X()};try{return await w.prepare(),A=o(B,{...h?{tenantId:h}:{},siteId:E,snapshotId:S,projectRoot:r,basePath:f,host:a,port:u,path:c,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:L=>{Q.snapshotId=L}}),$=$s({server:B,bridgePath:c,handleUpgrade:w.getUpgradeHandler()}),n.on("SIGINT",F),n.on("SIGTERM",F),await A.whenReady?.(),await Si(B,u,a),{bundler:g,close:X,host:a,port:Ii(B,u),server:B}}catch(L){throw await X(),L}}function Ds(e){let t=Us(e);return t&&Ks(t)?"webpack":"turbopack"}function js(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Us(e){for(let t of Ns){let n=se(e,t);if(G(n))return J(n,"utf8")}return null}function Ks(e){return e.includes(Bs)?!0:Hs.test(e)&&Ls.some(t=>t.test(e))}function $s(e){let t=(n,s,o)=>{Fs(n.url,e.bridgePath)||e.handleUpgrade(n,s,o).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Fs(e,t){return new URL(e??"/","http://localhost").pathname===t}function Ws(e=me){if(e===me)return Mt;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Vs(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??zs()});return`<script type="module" ${Dt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Os)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function zs(){return{bridge:Ke("@vcp-dev/site-edit-bridge"),contracts:Ke("@vcp-dev/contracts"),engine:Ke("@vcp-dev/site-edit-engine")}}function Ke(e){let t=Nt(import.meta.url);try{let n=t.resolve(e),s=qs(n,e);if(!s)return;let o=JSON.parse(J(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function qs(e,t){let n=te.parse(e).root,s=ne(e);for(;s&&s!==n;){let o=se(s,"package.json");if(G(o))try{if(JSON.parse(J(o,"utf8")).name===t)return o}catch{return}s=ne(s)}}function Js(e,t){if(e.includes(Dt))return e;let n=Vs(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function To(e,t=ne(Ht(import.meta.url)),n=G){return jt(e,t,n)?.path??null}function jt(e,t=ne(Ht(import.meta.url)),n=G){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(ye))return null;let o=s.slice(ye.length);if(!Ms.has(o))return null;let i=Ve(gi(t),o);if(Bt(t)!=="src")return{path:i,requiresTranspile:!1};let r=Ve(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Gs(e,t){let n=jt(e.url);if(!n)return!1;if(!G(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await Qs(J(n.path,"utf8")):J(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function Qs(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Xs({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:a,request:u,response:c}){if(Ys(u.url,e)){c.statusCode=404,c.end();return}if(await ni(u,c,n,o,i,r)||await Gs(u,c))return;let p=ii(u),l=oi(u),f=p||l?ci(c,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...i}}):()=>{};try{await a(u,c)}catch(h){throw f(),h}}function Ys(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(s,"http://namespace.invalid").pathname,i=t.replace(/\/+$/,"");return(i&&(o===i||o.startsWith(i+"/"))?o.slice(i.length)||"/":o).startsWith("/.vcp")}function Zs(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function ei(e){let t=new We.IncomingMessage(new Tt);t.method="GET",t.url=Pt,t.headers={host:Lt};let n=new We.ServerResponse(t);n.assignSocket(new Tt);try{return await e.renderToHTML(t,n,Pt,{}),{verdict:"ok"}}catch(s){return Zs(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function ti(e){return new URL(e??"/","http://localhost").searchParams.get(Ts)===Ps}async function ni(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=s(),u=ti(e.url)?await i():void 0,c={...a,launch:o,...u?{render:u}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function si(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function ii(e){return ri(e)?(e.headers["accept-encoding"]="identity",!0):!1}function oi(e){return ai(e)?(e.headers["accept-encoding"]="identity",!0):!1}function ri(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(ye)||n===me||n===Mt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function ai(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function ci(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),a=!1;s.flushHeaders=()=>{};let u=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let p=Ot(e,c,t);return p!==c&&!e.headersSent&&e.removeHeader("content-length"),i(p),n.length=0,a=!0,!0};return s.write=(c,p,l)=>a?(c!==void 0&&i($e(c,Fe(p))),fe(p),fe(l),!0):(c!==void 0&&(n.push($e(c,Fe(p))),u()),fe(p),fe(l),!0),s.end=(c,p,l)=>{let f=typeof c=="function"?void 0:c;if(a)return s.write=i,s.end=r,s.flushHeaders=o,f===void 0?typeof c=="function"?r(c):typeof p=="function"?r(p):typeof l=="function"?r(l):r():typeof p=="function"?r(f,p):typeof l=="function"?r(f,p,l):r(f,p);f!==void 0&&n.push($e(f,Fe(p))),s.write=i,s.end=r,s.flushHeaders=o;let h=Buffer.concat(n),d=Ot(e,h,t);d!==h&&!e.headersSent&&e.removeHeader("content-length");let g=typeof c=="function"?c:typeof p=="function"?p:typeof l=="function"?l:void 0;return g?r(d,g):r(d)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function Ot(e,t,n){if(ui(e,t))return Buffer.from(Js(t.toString("utf8"),n));if(n.patchNextDevChunk&&li(e)){let s=t.toString("utf8"),o=pi(s);if(o!==s)return Buffer.from(o)}return t}function di(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ui(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function li(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function pi(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
5
|
+
`),r.destroy();return}u.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,r,a,c=>{t.emit("connection",c,o)})};return e.server.on("upgrade",i),t.on("connection",(o,r)=>{if(n.has(r)){s(o);return}cs(o,e.sessionKey,()=>{s(o)})}),t.stop=()=>{e.server.off("upgrade",i);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var Le=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===It.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Yn){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function rs(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function as(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=Oe(e.headers["x-vcp-site-edit-key"]),i=kt(s,t.sessionKey),o=Oe(e.headers.host),r=Oe(e.headers.origin);return o&&!ds(o,t.host,r)?null:r?ls(r,o,t.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function cs(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Zn),i,o=()=>{clearTimeout(s),e.off("message",i),e.off("close",o)},r=()=>{o(),e.close(1008,"bridge authentication failed")};i=a=>{try{let u=P.parseMessage(a.toString());if(u.type!=="auth"||!kt(u.payload.key,t)){r();return}o(),e.readyState===It.OPEN&&e.send(P.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",i),e.on("close",o)}function kt(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&Nn(n,s)}function ds(e,t,n){let s=wt(e),i=wt(t);return s===i||bt(i)&&bt(s)&&(!n||Me(n,e))||us(i)&&(!n||Me(n,e))}function us(e){return e==="0.0.0.0"||e==="::"}function bt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ls(e,t,n){return n.includes(e)||(t?Me(e,t):!1)}function Me(e,t){try{return new URL(e).host===vt(t)}catch{return!1}}function wt(e){let t=vt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function vt(e){return e.trim().toLowerCase()}function Oe(e){return Array.isArray(e)?e[0]:e}function ps(){return On(32).toString("base64url")}function At(e){let t=e.replaceAll("\\","/");return t===Ne||t.endsWith(`/${Ne}`)}function hs(e){let t=e.replaceAll("\\","/");return At(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var ys="SITE_EDIT_ENGINE_UNAVAILABLE",_s=5e3,Ss=1024,bs="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",ws=3,Is=10*6e4,Es=1012;function Ue(e,t,n={}){let s=Rt(t),{onSnapshotIdChanged:i,onHealthChanged:o,...r}=s,a={options:r},u=n.maxHeapMb??Rs(process.env[bs])??Ss,c=n.maxRestarts??ws,h=n.restartWindowMs??Is,l="starting",f,p=0,d=[],g=null,w=0,I=new Map,E=new Set,S,b,C=new Promise((m,y)=>{S=m,b=y});C.catch(()=>{});let A=m=>{let y=new Error(`VCP site edit preview bridge runtime is not ready: ${m}`);return y.code=ys,y},Q=m=>{for(let y of I.values())y.reject(m);I.clear()},B=m=>{switch(m.type){case"ready":g=m.health,l==="starting"?(l="ready",S()):l==="restarting"&&(l="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":l==="starting"&&H(_e(m.error));return;case"result":{let y=I.get(m.id);if(!y)return;I.delete(m.id),m.ok?y.resolve(m.value):y.reject(_e(m.error));return}case"event":for(let y of E)try{y(m.event)}catch(x){console.warn(`[vcp-site-edit] engine event listener failed: ${x instanceof Error?x.message:String(x)}`)}return;case"health":g=m.health;return;case"snapshot-id-changed":a.options.snapshotId=m.next;try{i?.(m.next,m.previous)}catch(y){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${y instanceof Error?y.message:String(y)}`)}return}},$=()=>{let m=p+=1,y=n.workerUrl??new URL("./engine-worker.js",import.meta.url),x=new ms(xs(y),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:u},...n.execArgv?{execArgv:n.execArgv}:{}});x.unref();let M=()=>m===p;x.on("message",N=>{M()&&B(N)}),x.on("error",N=>{M()&&H(N instanceof Error?N:new Error(String(N)))}),x.on("exit",N=>{M()&&H(new Error(`engine worker exited with code ${N}`))}),f=x,n.onWorker?.(x)},H=m=>{if(l==="stopped"||l==="failed")return;if(Q(A(m.message)),g=null,l==="starting"){l="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${m.message}`),b(m);return}let y=Date.now();for(;d.length>0&&y-d[0]>h;)d.shift();if(d.length>=c){l="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${c} restarts: ${m.message}`);return}d.push(y),l="restarting";for(let x of L.clients)x.close(Es,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${d.length}/${c}): ${m.message}`),$()},X=(m,y)=>{if(l==="failed"||l==="stopped"||l==="restarting")return Promise.reject(A(l));let x=w+=1;return new Promise((M,N)=>{I.set(x,{resolve:M,reject:N});let Kt={type:"call",id:x,method:m,args:y};f.postMessage(Kt)})},F=Object.fromEntries(ze.map(m=>[m,(...y)=>X(m,y)])),L=je({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...F,subscribe(m){return E.add(m),()=>E.delete(m)}}});return $(),{getHealth(){return l==="ready"&&g?g:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:g?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(l==="stopped")return;let m=l==="starting";l="stopped",L.stop(),m&&b(A("bridge stopped")),Q(A("bridge stopped")),E.clear();let y=f,x={type:"stop"};y.postMessage(x);let M=setTimeout(()=>{y.terminate()},_s);M.unref(),y.once("exit",()=>clearTimeout(M))},whenReady(){return C},eventListeners:E}}function xs(e){if(!e.pathname.endsWith(".ts"))return e;let t=gs(fs(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
|
|
6
|
+
`);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function Rs(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var ks="next",vs="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Lt="127.0.0.1",As=3e3,me="/__vcp/site-edit/bridge",Mt="/__vcp/site-edit/health",Ts="probe",Ps="render",Pt="/_error",ye="/__vcp/site-edit/client/",Os=`${ye}auto-bootstrap.js`,Dt='data-vcp-site-edit-bootstrap="true"',Ns=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Bs="@vcp-dev/site-edit-engine/webpack-loader",Hs=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Ls=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ms=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-block-thumbnail.js","frame-block-thumbnail-renderer.js","frame-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Ai(e={},t={}){let n=t.process??process,s=t.createServer??Ve.createServer,i=t.attachBridgeServer??(n.env[vs]==="1"?xt:Ue),o=t.loadNext??go,r=te.resolve(e.projectRoot??process.cwd()),a=e.host??Lt,u=e.port??So(n.env.PORT)??As,c=e.bridgePath??me,h=Vs(c),l=uo(),f=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",p=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,d=await o(r),g=Ds(r),w=d({dev:!0,dir:r,hostname:a,port:u,...js(g)}),I=w.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",S=e.snapshotId??n.env.VCP_SNAPSHOT_ID??_o(r),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=b?.trim()?te.resolve(b):void 0,A=null,Q={launchId:Cs(),pid:process.pid,snapshotId:S},B=s((L,m)=>{Xs({basePath:f,bridgePath:c,bridgeHealthPath:h,bridgeSessionKey:l,getBridgeHealth:()=>A?.getHealth()??so(c),launch:Q,runRenderProbe:()=>eo(w),handle:I,request:L,response:m}).catch(y=>{console.error(y),m.headersSent||(m.statusCode=500),m.end("site edit preview request failed")})}),$=null,H=null,X=()=>H||(ge(()=>n.off("SIGINT",F)),ge(()=>n.off("SIGTERM",F)),ge(()=>$?.()),$=null,ge(()=>A?.stop()),A=null,H=Promise.allSettled([wo(B),Io(()=>w.close())]).then(()=>{}),H),F=()=>{X()};try{return await w.prepare(),A=i(B,{...p?{tenantId:p}:{},siteId:E,snapshotId:S,projectRoot:r,basePath:f,host:a,port:u,path:c,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:L=>{Q.snapshotId=L}}),$=$s({server:B,bridgePath:c,handleUpgrade:w.getUpgradeHandler()}),n.on("SIGINT",F),n.on("SIGTERM",F),await A.whenReady?.(),await bo(B,u,a),{bundler:g,close:X,host:a,port:Eo(B,u),server:B}}catch(L){throw await X(),L}}function Ds(e){let t=Us(e);return t&&Ks(t)?"webpack":"turbopack"}function js(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Us(e){for(let t of Ns){let n=se(e,t);if(G(n))return J(n,"utf8")}return null}function Ks(e){return e.includes(Bs)?!0:Hs.test(e)&&Ls.some(t=>t.test(e))}function $s(e){let t=(n,s,i)=>{Fs(n.url,e.bridgePath)||e.handleUpgrade(n,s,i).catch(o=>{console.error(o),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Fs(e,t){return new URL(e??"/","http://localhost").pathname===t}function Vs(e=me){if(e===me)return Mt;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Ws(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??zs()});return`<script type="module" ${Dt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Os)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function zs(){return{bridge:Ke("@vcp-dev/site-edit-bridge"),contracts:Ke("@vcp-dev/contracts"),engine:Ke("@vcp-dev/site-edit-engine")}}function Ke(e){let t=Nt(import.meta.url);try{let n=t.resolve(e),s=qs(n,e);if(!s)return;let i=JSON.parse(J(s,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function qs(e,t){let n=te.parse(e).root,s=ne(e);for(;s&&s!==n;){let i=se(s,"package.json");if(G(i))try{if(JSON.parse(J(i,"utf8")).name===t)return i}catch{return}s=ne(s)}}function Js(e,t){if(e.includes(Dt))return e;let n=Ws(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function Ti(e,t=ne(Ht(import.meta.url)),n=G){return jt(e,t,n)?.path??null}function jt(e,t=ne(Ht(import.meta.url)),n=G){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(ye))return null;let i=s.slice(ye.length);if(!Ms.has(i))return null;let o=We(mo(t),i);if(Bt(t)!=="src")return{path:o,requiresTranspile:!1};let r=We(t,i.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Gs(e,t){let n=jt(e.url);if(!n)return!1;if(!G(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await Qs(J(n.path,"utf8")):J(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function Qs(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Xs({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:i,launch:o,runRenderProbe:r,handle:a,request:u,response:c}){if(Ys(u.url,e)){c.statusCode=404,c.end();return}if(await no(u,c,n,i,o,r)||await Gs(u,c))return;let h=oo(u),l=io(u),f=h||l?co(c,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...o}}):()=>{};try{await a(u,c)}catch(p){throw f(),p}}function Ys(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let i=new URL(s,"http://namespace.invalid").pathname,o=t.replace(/\/+$/,"");return(o&&(i===o||i.startsWith(o+"/"))?i.slice(o.length)||"/":i).startsWith("/.vcp")}function Zs(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function eo(e){let t=new Ve.IncomingMessage(new Tt);t.method="GET",t.url=Pt,t.headers={host:Lt};let n=new Ve.ServerResponse(t);n.assignSocket(new Tt);try{return await e.renderToHTML(t,n,Pt,{}),{verdict:"ok"}}catch(s){return Zs(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function to(e){return new URL(e??"/","http://localhost").searchParams.get(Ts)===Ps}async function no(e,t,n,s,i,o){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=s(),u=to(e.url)?await o():void 0,c={...a,launch:i,...u?{render:u}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function so(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function oo(e){return ro(e)?(e.headers["accept-encoding"]="identity",!0):!1}function io(e){return ao(e)?(e.headers["accept-encoding"]="identity",!0):!1}function ro(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(ye)||n===me||n===Mt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function ao(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function co(e,t){let n=[],s=e,i=s.flushHeaders.bind(e),o=s.write.bind(e),r=s.end.bind(e),a=!1;s.flushHeaders=()=>{};let u=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let h=Ot(e,c,t);return h!==c&&!e.headersSent&&e.removeHeader("content-length"),o(h),n.length=0,a=!0,!0};return s.write=(c,h,l)=>a?(c!==void 0&&o($e(c,Fe(h))),fe(h),fe(l),!0):(c!==void 0&&(n.push($e(c,Fe(h))),u()),fe(h),fe(l),!0),s.end=(c,h,l)=>{let f=typeof c=="function"?void 0:c;if(a)return s.write=o,s.end=r,s.flushHeaders=i,f===void 0?typeof c=="function"?r(c):typeof h=="function"?r(h):typeof l=="function"?r(l):r():typeof h=="function"?r(f,h):typeof l=="function"?r(f,h,l):r(f,h);f!==void 0&&n.push($e(f,Fe(h))),s.write=o,s.end=r,s.flushHeaders=i;let p=Buffer.concat(n),d=Ot(e,p,t);d!==p&&!e.headersSent&&e.removeHeader("content-length");let g=typeof c=="function"?c:typeof h=="function"?h:typeof l=="function"?l:void 0;return g?r(d,g):r(d)},()=>{s.write=o,s.end=r,s.flushHeaders=i}}function Ot(e,t,n){if(lo(e,t))return Buffer.from(Js(t.toString("utf8"),n));if(n.patchNextDevChunk&&po(e)){let s=t.toString("utf8"),i=ho(s);if(i!==s)return Buffer.from(i)}return t}function uo(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function lo(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function po(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function ho(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
7
7
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
8
|
-
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[s,
|
|
8
|
+
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[s,i])=>fo(n,s,i),e)}function fo(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function $e(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Fe(e){return typeof e=="string"?e:void 0}function fe(e){typeof e=="function"&&e()}async function go(e){let n=Nt(se(e,"package.json"))(ks);return n.default??n}function mo(e){return Bt(e)!=="src"?e:We(yo(e),"dist")}function yo(e){return Ut(e)?te.posix.dirname(e):ne(e)}function We(e,t){return Ut(e)?te.posix.join(e,t):se(e,t)}function Ut(e){return e.includes("/")&&!e.includes("\\")}function _o(e){let t=se(e,".vcp/current-snapshot.json");if(!G(t))return"sandbox_worktree";try{let n=JSON.parse(J(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function So(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function bo(e,t,n){return new Promise((s,i)=>{e.once("error",i),e.listen(t,n,()=>{e.off("error",i),s()})})}function wo(e){return new Promise(t=>{e.close(()=>t())})}function ge(e){try{e()}catch{}}function Io(e){try{return e()}catch(t){return Promise.reject(t)}}function Eo(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{$s as attachNextDevUpgradeHandler,Ue as attachSiteEditBridgeServerInWorker,Zs as classifySiteEditRenderProbeError,Ws as createSiteEditAutoBootstrapHtmlSnippet,Js as injectSiteEditAutoBootstrap,to as isSiteEditRenderProbeRequested,ho as patchNextFirefoxDevChunk,io as prepareFirefoxNextDevChunkPatchRequest,oo as prepareSiteEditHtmlInjectionRequest,Vs as resolveSiteEditBridgeHealthPath,jt as resolveSiteEditClientAsset,Ti as resolveSiteEditClientAssetPath,Ds as resolveSiteEditNextDevBundler,eo as runSiteEditRenderProbe,Ai as startSiteEditNextDevServer,Qs as transpileSiteEditClientSource};
|
|
@@ -161,30 +161,26 @@ export class PortableRemoteAssetReader {
|
|
|
161
161
|
this.controller = new AbortController();
|
|
162
162
|
}
|
|
163
163
|
async read(request, exported) {
|
|
164
|
-
const matches = exported.
|
|
165
|
-
item.occurrence === request.occurrence);
|
|
164
|
+
const matches = exported.asset_catalog.filter((item) => item.asset_key === request.asset_key);
|
|
166
165
|
const reference = matches[0];
|
|
167
166
|
if (this.controller.signal.aborted ||
|
|
168
167
|
request.snapshot_digest !== exported.snapshot_digest ||
|
|
169
168
|
matches.length !== 1 ||
|
|
170
|
-
|
|
171
|
-
reference.cms_field ||
|
|
172
|
-
reference.kind === "srcset" ||
|
|
173
|
-
!reference.value ||
|
|
169
|
+
reference?.origin.kind !== "remote" ||
|
|
174
170
|
!request.capture_id ||
|
|
175
171
|
!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(request.capture_id) ||
|
|
176
172
|
!Number.isSafeInteger(request.offset) ||
|
|
177
173
|
request.offset < 0 ||
|
|
178
174
|
request.offset % CHUNK)
|
|
179
175
|
throw unavailable();
|
|
180
|
-
|
|
176
|
+
const value = reference.origin.url;
|
|
177
|
+
publicUrl(value);
|
|
181
178
|
const key = JSON.stringify([
|
|
182
179
|
request.request,
|
|
183
180
|
request.snapshot_digest,
|
|
184
|
-
request.
|
|
185
|
-
request.occurrence,
|
|
181
|
+
request.asset_key,
|
|
186
182
|
request.capture_id,
|
|
187
|
-
|
|
183
|
+
value,
|
|
188
184
|
]);
|
|
189
185
|
let entry = this.entries.get(key);
|
|
190
186
|
if (!entry) {
|
|
@@ -195,7 +191,7 @@ export class PortableRemoteAssetReader {
|
|
|
195
191
|
throw unavailable();
|
|
196
192
|
this.pending.add(key);
|
|
197
193
|
try {
|
|
198
|
-
const image = await this.download(
|
|
194
|
+
const image = await this.download(value, this.controller.signal);
|
|
199
195
|
if (this.controller.signal.aborted ||
|
|
200
196
|
!image.bytes.length ||
|
|
201
197
|
image.bytes.length > MAX ||
|
|
@@ -225,8 +221,7 @@ export class PortableRemoteAssetReader {
|
|
|
225
221
|
const result = {
|
|
226
222
|
complete: true,
|
|
227
223
|
snapshot_digest: request.snapshot_digest,
|
|
228
|
-
|
|
229
|
-
occurrence: request.occurrence,
|
|
224
|
+
asset_key: request.asset_key,
|
|
230
225
|
path: `public/__portable_remote__/${digest_sha256}.${extension}`,
|
|
231
226
|
mime_type,
|
|
232
227
|
byte_size: bytes.length,
|
package/dist/protocol.js
CHANGED
|
@@ -534,6 +534,7 @@ function isPortableExportPayload(payload) {
|
|
|
534
534
|
return false;
|
|
535
535
|
const request = payload.request;
|
|
536
536
|
if (!Object.keys(request).every((key) => [
|
|
537
|
+
"export_schema_version",
|
|
537
538
|
"site_id",
|
|
538
539
|
"base_snapshot_id",
|
|
539
540
|
"document_version",
|
|
@@ -541,6 +542,7 @@ function isPortableExportPayload(payload) {
|
|
|
541
542
|
"selection_ref",
|
|
542
543
|
"cms_schema_proofs",
|
|
543
544
|
].includes(key)) ||
|
|
545
|
+
request.export_schema_version !== 2 ||
|
|
544
546
|
typeof request.site_id !== "string" ||
|
|
545
547
|
typeof request.base_snapshot_id !== "string" ||
|
|
546
548
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(request.site_id) ||
|
|
@@ -601,8 +603,7 @@ function isPortableAssetPayload(payload) {
|
|
|
601
603
|
if (!Object.keys(asset).every((key) => [
|
|
602
604
|
"request",
|
|
603
605
|
"snapshot_digest",
|
|
604
|
-
"
|
|
605
|
-
"occurrence",
|
|
606
|
+
"asset_key",
|
|
606
607
|
"offset",
|
|
607
608
|
"capture_id",
|
|
608
609
|
].includes(key)) ||
|
|
@@ -614,18 +615,8 @@ function isPortableAssetPayload(payload) {
|
|
|
614
615
|
}) ||
|
|
615
616
|
typeof asset.snapshot_digest !== "string" ||
|
|
616
617
|
!/^sha256:[a-f0-9]{64}$/u.test(asset.snapshot_digest) ||
|
|
617
|
-
typeof asset.
|
|
618
|
-
|
|
619
|
-
asset.file_path.length > 1024 ||
|
|
620
|
-
asset.file_path.startsWith("/") ||
|
|
621
|
-
/[\\\0%]/u.test(asset.file_path) ||
|
|
622
|
-
asset.file_path
|
|
623
|
-
.split("/")
|
|
624
|
-
.some((part) => !part || part.startsWith(".") || part === "node_modules") ||
|
|
625
|
-
typeof asset.occurrence !== "number" ||
|
|
626
|
-
!Number.isSafeInteger(asset.occurrence) ||
|
|
627
|
-
asset.occurrence < 0 ||
|
|
628
|
-
asset.occurrence > 4095 ||
|
|
618
|
+
typeof asset.asset_key !== "string" ||
|
|
619
|
+
!/^asset-[a-f0-9]{64}$/u.test(asset.asset_key) ||
|
|
629
620
|
typeof asset.offset !== "number" ||
|
|
630
621
|
!Number.isSafeInteger(asset.offset) ||
|
|
631
622
|
asset.offset < 0 ||
|