@vcp-dev/site-edit-bridge 0.11.29 → 0.11.31
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 +14 -14
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/engine-worker.js +3 -3
- package/dist/index.js +18 -18
- package/dist/next-dev-server.js +5 -5
- package/dist/portable-remote-asset.js +252 -0
- package/dist/protocol.js +5 -1
- package/dist/server.d.ts +1 -0
- package/dist/server.js +3 -3
- package/dist/window-message.d.ts +2 -1
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import dns from "node:dns/promises";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import https from "node:https";
|
|
5
|
+
import { isIP } from "node:net";
|
|
6
|
+
import { PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as CHUNK, PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as MAX, } from "@vcp-dev/contracts";
|
|
7
|
+
const unavailable = () => new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");
|
|
8
|
+
/** No private, metadata, loopback, multicast or IPv4-mapped IPv6 destinations. */
|
|
9
|
+
export function isPublicPortableAssetAddress(address) {
|
|
10
|
+
if (isIP(address) === 4) {
|
|
11
|
+
const [a, b] = address.split(".").map(Number);
|
|
12
|
+
return !(a === 0 ||
|
|
13
|
+
a === 10 ||
|
|
14
|
+
a === 127 ||
|
|
15
|
+
a >= 224 ||
|
|
16
|
+
(a === 100 && b >= 64 && b <= 127) ||
|
|
17
|
+
(a === 169 && b === 254) ||
|
|
18
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
19
|
+
(a === 192 && [0, 168].includes(b)) ||
|
|
20
|
+
(a === 198 && [18, 19, 51].includes(b)) ||
|
|
21
|
+
(a === 203 && b === 0));
|
|
22
|
+
}
|
|
23
|
+
return (isIP(address) === 6 &&
|
|
24
|
+
/^[23]/u.test(address) &&
|
|
25
|
+
!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(address));
|
|
26
|
+
}
|
|
27
|
+
function publicUrl(value) {
|
|
28
|
+
const url = new URL(value);
|
|
29
|
+
const host = url.hostname.replace(/^\[|\]$/gu, "").replace(/\.$/u, "");
|
|
30
|
+
if (!["http:", "https:"].includes(url.protocol) ||
|
|
31
|
+
url.username ||
|
|
32
|
+
url.password ||
|
|
33
|
+
url.port ||
|
|
34
|
+
url.hash ||
|
|
35
|
+
host === "localhost" ||
|
|
36
|
+
(!host.includes(".") && !isIP(host)) ||
|
|
37
|
+
/\.(?:internal|localhost|local)$/iu.test(host) ||
|
|
38
|
+
(isIP(host) && !isPublicPortableAssetAddress(host)))
|
|
39
|
+
throw unavailable();
|
|
40
|
+
return url;
|
|
41
|
+
}
|
|
42
|
+
function imageMime(bytes) {
|
|
43
|
+
const starts = (signature) => signature.every((byte, index) => bytes[index] === byte);
|
|
44
|
+
if (starts([137, 80, 78, 71, 13, 10, 26, 10]))
|
|
45
|
+
return "image/png";
|
|
46
|
+
if (starts([255, 216, 255]))
|
|
47
|
+
return "image/jpeg";
|
|
48
|
+
if (starts([71, 73, 70, 56, 55, 97]) || starts([71, 73, 70, 56, 57, 97]))
|
|
49
|
+
return "image/gif";
|
|
50
|
+
if (starts([82, 73, 70, 70]) &&
|
|
51
|
+
Buffer.from(bytes.subarray(8, 12)).toString() === "WEBP")
|
|
52
|
+
return "image/webp";
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
async function abortable(pending, signal) {
|
|
56
|
+
let abort = () => undefined;
|
|
57
|
+
try {
|
|
58
|
+
return await Promise.race([
|
|
59
|
+
pending,
|
|
60
|
+
new Promise((_resolve, reject) => {
|
|
61
|
+
abort = () => reject(unavailable());
|
|
62
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
63
|
+
if (signal.aborted)
|
|
64
|
+
abort();
|
|
65
|
+
}),
|
|
66
|
+
]);
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
signal.removeEventListener("abort", abort);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** DNS is checked and pinned on every redirect. No cookies, auth, proxy or env
|
|
73
|
+
* credentials are forwarded. The URL comes exclusively from a verified export. */
|
|
74
|
+
export async function downloadPortableRemoteImage(value, signal) {
|
|
75
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(15_000)]);
|
|
76
|
+
let url = publicUrl(value);
|
|
77
|
+
for (let redirects = 0; redirects <= 3; redirects++) {
|
|
78
|
+
deadline.throwIfAborted();
|
|
79
|
+
const host = url.hostname.replace(/^\[|\]$/gu, "");
|
|
80
|
+
const addresses = isIP(host)
|
|
81
|
+
? [{ address: host, family: isIP(host) }]
|
|
82
|
+
: await abortable(dns.lookup(host, { all: true }), deadline);
|
|
83
|
+
deadline.throwIfAborted();
|
|
84
|
+
if (!addresses.length ||
|
|
85
|
+
addresses.some(({ address }) => !isPublicPortableAssetAddress(address)))
|
|
86
|
+
throw unavailable();
|
|
87
|
+
const pinned = addresses.find((address) => address.family === 4) ?? addresses[0];
|
|
88
|
+
const response = await new Promise((resolve, reject) => {
|
|
89
|
+
const request = (url.protocol === "https:" ? https : http).get(url, {
|
|
90
|
+
agent: false,
|
|
91
|
+
signal: deadline,
|
|
92
|
+
headers: {
|
|
93
|
+
accept: "image/png,image/jpeg,image/gif,image/webp",
|
|
94
|
+
"accept-encoding": "identity",
|
|
95
|
+
},
|
|
96
|
+
lookup: (_hostname, options, callback) => {
|
|
97
|
+
if (options.all)
|
|
98
|
+
callback(null, [
|
|
99
|
+
{ address: pinned.address, family: pinned.family },
|
|
100
|
+
]);
|
|
101
|
+
else
|
|
102
|
+
callback(null, pinned.address, pinned.family);
|
|
103
|
+
},
|
|
104
|
+
}, resolve);
|
|
105
|
+
request.on("error", reject);
|
|
106
|
+
});
|
|
107
|
+
try {
|
|
108
|
+
const status = response.statusCode ?? 0;
|
|
109
|
+
if ([301, 302, 303, 307, 308].includes(status)) {
|
|
110
|
+
if (!response.headers.location || redirects === 3)
|
|
111
|
+
throw unavailable();
|
|
112
|
+
const next = publicUrl(new URL(response.headers.location, url).href);
|
|
113
|
+
if (url.protocol === "https:" && next.protocol !== "https:")
|
|
114
|
+
throw unavailable();
|
|
115
|
+
url = next;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const declared = response.headers["content-length"];
|
|
119
|
+
if (status !== 200 ||
|
|
120
|
+
(response.headers["content-encoding"] &&
|
|
121
|
+
response.headers["content-encoding"] !== "identity") ||
|
|
122
|
+
(declared !== undefined &&
|
|
123
|
+
(!/^\d+$/u.test(declared) ||
|
|
124
|
+
Number(declared) < 1 ||
|
|
125
|
+
Number(declared) > MAX)))
|
|
126
|
+
throw unavailable();
|
|
127
|
+
const chunks = [];
|
|
128
|
+
let size = 0;
|
|
129
|
+
for await (const chunk of response) {
|
|
130
|
+
const bytes = Buffer.from(chunk);
|
|
131
|
+
size += bytes.length;
|
|
132
|
+
if (size > MAX)
|
|
133
|
+
throw unavailable();
|
|
134
|
+
chunks.push(bytes);
|
|
135
|
+
}
|
|
136
|
+
if (!size || (declared !== undefined && Number(declared) !== size))
|
|
137
|
+
throw unavailable();
|
|
138
|
+
const bytes = Buffer.concat(chunks, size);
|
|
139
|
+
const mime_type = imageMime(bytes);
|
|
140
|
+
if (!mime_type ||
|
|
141
|
+
response.headers["content-type"]
|
|
142
|
+
?.split(";", 1)[0]
|
|
143
|
+
?.trim()
|
|
144
|
+
.toLowerCase() !== mime_type)
|
|
145
|
+
throw unavailable();
|
|
146
|
+
return { bytes, mime_type };
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
response.destroy();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
throw unavailable();
|
|
153
|
+
}
|
|
154
|
+
/** Bounded, short-lived chunk transfer. Thumbnail receives the assembled bytes
|
|
155
|
+
* from Web, so the remote server is never read a second time for rasterization. */
|
|
156
|
+
export class PortableRemoteAssetReader {
|
|
157
|
+
constructor(download = downloadPortableRemoteImage) {
|
|
158
|
+
this.download = download;
|
|
159
|
+
this.entries = new Map();
|
|
160
|
+
this.pending = new Set();
|
|
161
|
+
this.controller = new AbortController();
|
|
162
|
+
}
|
|
163
|
+
async read(request, exported) {
|
|
164
|
+
const matches = exported.media.filter((item) => item.file_path === request.file_path &&
|
|
165
|
+
item.occurrence === request.occurrence);
|
|
166
|
+
const reference = matches[0];
|
|
167
|
+
if (this.controller.signal.aborted ||
|
|
168
|
+
request.snapshot_digest !== exported.snapshot_digest ||
|
|
169
|
+
matches.length !== 1 ||
|
|
170
|
+
!reference?.complete ||
|
|
171
|
+
reference.cms_field ||
|
|
172
|
+
reference.kind === "srcset" ||
|
|
173
|
+
!reference.value ||
|
|
174
|
+
!request.capture_id ||
|
|
175
|
+
!/^[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
|
+
!Number.isSafeInteger(request.offset) ||
|
|
177
|
+
request.offset < 0 ||
|
|
178
|
+
request.offset % CHUNK)
|
|
179
|
+
throw unavailable();
|
|
180
|
+
publicUrl(reference.value);
|
|
181
|
+
const key = JSON.stringify([
|
|
182
|
+
request.request,
|
|
183
|
+
request.snapshot_digest,
|
|
184
|
+
request.file_path,
|
|
185
|
+
request.occurrence,
|
|
186
|
+
request.capture_id,
|
|
187
|
+
reference.value,
|
|
188
|
+
]);
|
|
189
|
+
let entry = this.entries.get(key);
|
|
190
|
+
if (!entry) {
|
|
191
|
+
if (request.offset ||
|
|
192
|
+
this.pending.has(key) ||
|
|
193
|
+
this.pending.size >= 2 ||
|
|
194
|
+
this.entries.size >= 16)
|
|
195
|
+
throw unavailable();
|
|
196
|
+
this.pending.add(key);
|
|
197
|
+
try {
|
|
198
|
+
const image = await this.download(reference.value, this.controller.signal);
|
|
199
|
+
if (this.controller.signal.aborted ||
|
|
200
|
+
!image.bytes.length ||
|
|
201
|
+
image.bytes.length > MAX ||
|
|
202
|
+
imageMime(image.bytes) !== image.mime_type ||
|
|
203
|
+
[...this.entries.values()].reduce((sum, item) => sum + item.image.bytes.length, image.bytes.length) >
|
|
204
|
+
64 * 1024 * 1024)
|
|
205
|
+
throw unavailable();
|
|
206
|
+
const timer = setTimeout(() => this.remove(key), 60_000);
|
|
207
|
+
timer.unref();
|
|
208
|
+
entry = { image, timer };
|
|
209
|
+
this.entries.set(key, entry);
|
|
210
|
+
}
|
|
211
|
+
finally {
|
|
212
|
+
this.pending.delete(key);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const { bytes, mime_type } = entry.image;
|
|
216
|
+
if (request.offset >= bytes.length)
|
|
217
|
+
throw unavailable();
|
|
218
|
+
const digest_sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
219
|
+
const extension = {
|
|
220
|
+
"image/png": "png",
|
|
221
|
+
"image/jpeg": "jpg",
|
|
222
|
+
"image/gif": "gif",
|
|
223
|
+
"image/webp": "webp",
|
|
224
|
+
}[mime_type];
|
|
225
|
+
const result = {
|
|
226
|
+
complete: true,
|
|
227
|
+
snapshot_digest: request.snapshot_digest,
|
|
228
|
+
file_path: request.file_path,
|
|
229
|
+
occurrence: request.occurrence,
|
|
230
|
+
path: `public/__portable_remote__/${digest_sha256}.${extension}`,
|
|
231
|
+
mime_type,
|
|
232
|
+
byte_size: bytes.length,
|
|
233
|
+
digest_sha256,
|
|
234
|
+
offset: request.offset,
|
|
235
|
+
data_base64: Buffer.from(bytes.subarray(request.offset, request.offset + CHUNK)).toString("base64"),
|
|
236
|
+
};
|
|
237
|
+
if (request.offset + CHUNK >= bytes.length)
|
|
238
|
+
this.remove(key);
|
|
239
|
+
return result;
|
|
240
|
+
}
|
|
241
|
+
remove(key) {
|
|
242
|
+
const entry = this.entries.get(key);
|
|
243
|
+
if (entry)
|
|
244
|
+
clearTimeout(entry.timer);
|
|
245
|
+
this.entries.delete(key);
|
|
246
|
+
}
|
|
247
|
+
dispose() {
|
|
248
|
+
this.controller.abort();
|
|
249
|
+
for (const key of this.entries.keys())
|
|
250
|
+
this.remove(key);
|
|
251
|
+
}
|
|
252
|
+
}
|
package/dist/protocol.js
CHANGED
|
@@ -604,6 +604,7 @@ function isPortableAssetPayload(payload) {
|
|
|
604
604
|
"file_path",
|
|
605
605
|
"occurrence",
|
|
606
606
|
"offset",
|
|
607
|
+
"capture_id",
|
|
607
608
|
].includes(key)) ||
|
|
608
609
|
!isPortableExportPayload({
|
|
609
610
|
id: payload.id,
|
|
@@ -629,7 +630,10 @@ function isPortableAssetPayload(payload) {
|
|
|
629
630
|
!Number.isSafeInteger(asset.offset) ||
|
|
630
631
|
asset.offset < 0 ||
|
|
631
632
|
asset.offset > 50 * 1024 * 1024 ||
|
|
632
|
-
asset.offset % (1024 * 1024) !== 0
|
|
633
|
+
asset.offset % (1024 * 1024) !== 0 ||
|
|
634
|
+
(asset.capture_id !== undefined &&
|
|
635
|
+
(typeof asset.capture_id !== "string" ||
|
|
636
|
+
!/^[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(asset.capture_id))))
|
|
633
637
|
return false;
|
|
634
638
|
return true;
|
|
635
639
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -109,6 +109,7 @@ export declare class SiteEditBridgeServer {
|
|
|
109
109
|
private createBridgeEngine;
|
|
110
110
|
private verifyCmsSchemaProofs;
|
|
111
111
|
private exportPortableBlock;
|
|
112
|
+
private readonly portableRemoteAssets;
|
|
112
113
|
private exportPortableBlockAsset;
|
|
113
114
|
private runHistoryWithReceipt;
|
|
114
115
|
private isActiveReceiptIdentity;
|
package/dist/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import De from"node:http";import L from"node:fs";import{createHash as ue,randomBytes as Tt,timingSafeEqual as Ot}from"node:crypto";import x from"node:path";import{WebSocket as Ke,WebSocketServer as vt}from"ws";import{createPreviewSiteEditEngineRuntime as Pt,exportPortableBlockFromSnapshot as Bt,readPortableBlockLocalAssetChunk as Nt,openFileHistoryStore as Mt,resolveManagedPageTemplateComposition as Ht,scanSiteEditCompositionsFromFiles as Lt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Dt,scanNextAppRouterRoutesFromFiles as Kt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ft}from"@vcp-dev/site-edit-engine/source-watcher";function fe(e){if(e.pageBlocks!==void 0&&!Je(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,s=[],n=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((u,c)=>[u,c])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(u=>({placementKey:u.placementKey,placementUnitKey:u.placementUnitKey,relation:u.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},p=e.entries.flatMap((u,c)=>u.dynamicDataSummary?[[c,u.dynamicDataSummary]]:[]),d=new Map(e.entries.map((u,c)=>[u.key,c])),h=[];for(let[u,c]of e.entries.entries()){let m=c.pageCompositionActionScope;if(!m)continue;if(m.kind!=="source-siblings"){h.push([u,{kind:m.kind}]);continue}let C=m.siblingKeys.map(w=>{let E=d.get(w);if(E===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+w);return E});h.push([u,{kind:"source-siblings",siblingEntryIndexes:C}])}let f=u=>{let c=t.get(u);if(typeof c=="number")return c;let m=s.length;return s.push(u),t.set(u,m),m},g=u=>{let c=null;for(let m of nt(u)){let C=`${c??"root"}\0${m}`,w=n.get(C);if(typeof w=="number"){c=w;continue}let E=o.length;o.push([c,f(m)]),n.set(C,E),c=E}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:s,nodes:o,entries:e.entries.map(u=>{let c=u.pageCompositionUnitKey?r.get(u.pageCompositionUnitKey)??-1:-1;if(u.pageCompositionUnitKey&&c<0)throw new Error(`Render entry ${u.key} references unknown page composition unit ${u.pageCompositionUnitKey}`);return[g(u.key),We(u.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(u=>u.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(u=>u.parentKey===null?null:g(u.parentKey))}:{},...p.length>0?{dynamicDataSummaries:p}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function We(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Je(e){if(!Array.isArray(e))return!1;let t=new Map;for(let s of e){if(!O(s)||!B(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!K(s.blockKey,256)||!K(s.definitionKey,512)||!Qe(s.rootRef)||!Xe(s.source)||!Ye(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>K(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!P(s.placementUnitKey)||!Ge(s.capabilities)||s.unavailableReasons!==void 0&&!Ze(s.unavailableReasons)||t.has(s.blockKey))return!1;t.set(s.blockKey,s)}for(let s of e){let n=s.owner;for(let o of s.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(n.kind!==r.kind||n.key!==r.key)return!1}}return!0}function Qe(e){return!O(e)||!B(e,["key","instanceIndex","instanceCount"])||!P(e.key)||e.instanceIndex!==void 0&&!pe(e.instanceIndex)||e.instanceCount!==void 0&&(!pe(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Xe(e){return O(e)&&B(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&et(e.file)&&P(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Ye(e){return O(e)&&B(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&K(e.key,512)}function Ge(e){return O(e)&&B(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function Ze(e){return O(e)&&Object.entries(e).every(([t,s])=>P(t)&&O(s)&&B(s,["code","reason"])&&P(s.code)&&P(s.reason))}function et(e){let t=tt(e),s=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||s.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let n=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(n)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(n)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(n)||n.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function tt(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let s=t[1].split("/"),n=s.some(r=>he(r)),o=n?s[0]:s.pop(),i=n?s.slice(1):s;if(n&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!st(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!he(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),p=Uint8Array.from(a,h=>h.charCodeAt(0)),d=new TextDecoder("utf-8",{fatal:!0}).decode(p);return d.length>0&&d.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(d)&&!d.startsWith(" ")&&!d.endsWith(" ")&&new TextEncoder().encode(d).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(d))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function he(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function st(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let s=decodeURIComponent(t);return s==="."||s===".."||/[/\\\x00-\x1f\x7f]/u.test(s)||s.startsWith(".vcp")}catch{return!0}})}function K(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function P(e){return typeof e=="string"&&e.length>0}function B(e,t){let s=new Set(t);return Object.keys(e).every(n=>s.has(n))}function nt(e){if(!e)return[];let t=[],s=0,n=le(e,s);if(n<0)return t.push(e),t;for(t.push(e.slice(0,n)),s=n;s<e.length;){if(n=le(e,s+(e.startsWith("::",s)?2:1)),n<0){t.push(e.slice(s));break}t.push(e.slice(s,n)),s=n}return t}function le(e,t){let s=e.indexOf("/",t),n=e.indexOf("::",t);return s<0?n:n<0?s:Math.min(s,n)}var N="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",te="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var R=class e{constructor(){}static parseMessage(t,s={}){let n=JSON.parse(t);if(!e.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(l(t)&&l(t.payload)){let s=typeof t.payload.id=="string"?t.payload.id:"unknown",n=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,s={}){return!l(t)||typeof t.type!="string"?!1:t.type==="request"?rt(t.payload,s):t.type==="response"||t.type==="error"?l(t.payload)&&typeof t.payload.id=="string":t.type==="event"?l(t.payload)&&l(t.payload.event):t.type==="auth"?l(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?l(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&l(t.payload)&&t.payload.ok===!0}},V=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ee,this.eventDispatcher=new Z(s=>{this.sendJson(s)}),this.unsubscribe=t.engine.subscribe(s=>{this.handleEngineEvent(s)}),t.socket.onmessage=s=>{let n=ot(s.data);if(n!==null){this.sendJson({type:"pong",payload:{id:n}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let s=t;if(s.type!=="request")return;let n=s.payload,{id:o}=n;switch(n.kind){case"initialize-session":{let i=Q(n),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:n.kind,result:A({...a,data:{...a.data,document:_e(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(n),r=await this.options.engine.getDocument(i);this.sendResult(o,n.kind,ht(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(n),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,n.kind,A(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getObjectEditContext(n.key,i,n.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getClassNameSource(n.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,A(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!se(n))throw new b("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.target.composition);if(S(i)!==S(r))throw new b(N,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,n.kind,a);return}case"export-portable-block-asset":{if(!ge(n))throw new b("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.request.target.composition);if(S(i)!==S(r))throw new b(N,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,n.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(n),r=A(await this.options.engine.resolveSourceLocation({key:n.key,composition:i}),i);this.sendResult(o,n.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(n.request),r=await this.resolveWireContext(n);if(S(i)!==S(r))throw new b(N,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(n.request,i);if(n.kind==="get-operation-result"){this.sendResult(o,n.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,n.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.composition);if(S(i)!==S(r))throw new b(N,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:F(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(n),r=n.request;if(r){let p=await this.resolveAndAssert(r.composition);if(r.kind!==n.kind||S(i)!==S(p))throw new b(N,"History request does not match its cursor operation.")}let a=r?{...r,composition:F(i)}:void 0;await this.handleBufferedOperation(o,n.kind,()=>n.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(s){let n=R.extractRequestInfo(t);this.sendJson({type:"error",payload:{...n,message:G(s),code:Y(s)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let s=await this.resolve(t),n=this.session.activeComposition;if(!n)throw new b(te,"Initialize a composition session before issuing this request.");if(S(n)!==S(s.context))throw new b(N,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(t){let s=Q(t);return this.resolveAndAssert(s)}async resolveOperationWireContext(t){let s=ut(t);return this.resolveAndAssert(s)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(S(t))}async normalizeOperationRequest(t,s){let n={...t,composition:F(s)};if(n.target.kind==="route"){let o=n.target,i=Q(o),r=await this.resolveAndAssert(i);n.target={...o,composition:F(r)}}return n}handleEngineEvent(t){let s=t?.composition;if(!dt(s))return;let n=S(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&n===pt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(t,s,n){this.sendJson({type:"response",payload:{id:t,kind:s,result:n}})}async handleRawMessage(t){try{await this.handleMessage(R.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=lt(t);this.sendJson({type:"error",payload:{...n,message:G(s),code:Y(s)}})}}sendJson(t){this.options.socket.send(R.stringifyMessage(t))}async handleBufferedOperation(t,s,n){this.eventDispatcher.beginBuffering();try{let o=await n();this.sendResult(t,s,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:s,message:G(o),code:Y(o)}})}finally{this.eventDispatcher.flush()}}},it=256;function ot(e){if(e.length>it||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return l(t)&&t.type==="ping"&&l(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var b=class extends Error{constructor(t,s){super(s),this.code=t,this.name="BridgeProtocolError"}},Z=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let s={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(s=>this.send(s))}},ee=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await t()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function rt(e,t){if(!l(e)||typeof e.id!="string"||!R.isRequestKind(e.kind))return!1;let s=T(e.composition);switch(e.kind){case"initialize-session":return s&&(e.mutationContext===void 0||X(e.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof e.key=="string"&&s&&ye(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&s;case"get-history-status":return s;case"get-source-tree":return s;case"get-source-file":return typeof e.path=="string"&&s;case"export-portable-block":return se(e);case"export-portable-block-asset":return ge(e);case"execute":case"get-operation-result":return s&&ct(e.request)&&(e.request.mutationContext===void 0||X(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return s&&me(e.request);case"undo":case"redo":return s&&(e.request===void 0||me(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||X(e.mutationContext))}}function se(e){if(!T(e.composition)||!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!l(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(s))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!l(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(s=>["kind","composition","blockKey"].includes(s))||!T(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!ye(t.selection_ref)||t.cms_schema_proofs!==void 0&&!at(t.cms_schema_proofs))}function at(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let s=Object.getOwnPropertyDescriptor(e,String(t));if(!s||!("value"in s))return!1;let n=s.value;if(!l(n)||!Reflect.ownKeys(n).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(n,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function ge(e){if(!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!l(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["request","snapshot_digest","file_path","occurrence","offset"].includes(s))||!se({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(s=>!s||s.startsWith(".")||s==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function me(e){return l(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&T(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function ye(e){if(e===void 0)return!0;if(!l(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,s=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof t=="number"&&typeof s=="number"&&t>=s?!1:Object.keys(e).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function ct(e){return l(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&T(e.composition)&&typeof e.kind=="string"&&l(e.target)&&(e.target.kind!=="route"||T(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&l(e.params)}function T(e){return l(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function dt(e){return l(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Q(e){if(T(e.composition))return e.composition;throw new b(te,"A composition selector is required for this request.")}function ut(e){if(l(e)&&T(e.composition))return e.composition;throw new b(te,"A composition selector is required for execute.")}function F(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function pt(e){return e.activeComposition?S(e.activeComposition):null}function S(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function A(e,t){return l(e)&&e.ok===!0?{...e,composition:t}:e}function ht(e,t){return!l(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:_e(e.data)}}function _e(e){let t=e;return fe(t.routeId?t:{...t,routeId:t.composition.routeId})}function l(e){return typeof e=="object"&&e!==null}function X(e){return l(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function Y(e){if(!(!l(e)||typeof e.code!="string"||e.code.length===0))return e.code}function G(e){return e instanceof Error||l(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function lt(e){try{return R.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var q=class{constructor(){this.tail=Promise.resolve()}run(t){let s=this.tail.then(t,t);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as we}from"node:crypto";import{constants as Ee,promises as ne}from"node:fs";import Re from"node:path";import{createHash as ft}from"node:crypto";var z=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
|
-
`)),Se=Buffer.from(z.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),be=e=>`sha256:${ft("sha256").update(e).digest("hex")}`,mt=be(z),gt=be(Se);function M(e,t,s){return e==="next-env.d.ts"&&t===z.byteLength&&s===mt?Se.byteLength:null}function j(e){return M(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===gt}function Ie(){return Uint8Array.from(z)}var xe=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Ce=64;async function U(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==="..")||xe.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>Ce||++s>t.size*Ce+1)return!1;let a=await ne.readdir(Re.join(e,i),{withFileTypes:!0});for(let p of a){let d=i?`${i}/${p.name}`:p.name;if(!i&&xe.has(p.name))continue;if(p.isDirectory()){if(!await o(d,r+1))return!1;continue}if(!p.isFile())return!1;let h=t.get(d);if(h===void 0||n.has(d))return!1;n.add(d);let f=Re.join(e,d),g=await ne.lstat(f),u=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${we("sha256").update(h).digest("hex")}`;if(!g.isFile()||g.isSymbolicLink()||g.size!==u&&g.size!==M(d,u,c))return!1;let m=we("sha256"),C=await ne.open(f,Ee.O_RDONLY|Ee.O_NOFOLLOW);try{let E=await C.stat();if(!E.isFile()||E.size!==g.size)return!1;let y=0,_=C.createReadStream({autoClose:!1});for await(let k of _){if(y+=k.byteLength,y>g.size)return _.destroy(),!1;m.update(k)}if(y!==g.size)return!1}finally{await C.close()}let w=`sha256:${m.digest("hex")}`;if((g.size!==u||w!==c)&&!j({file:d,expectedSize:u,expectedDigest:c,actualSize:g.size,actualDigest:w}))return!1}return!0};return await o("",0)&&n.size===t.size}catch{return!1}}import{createHash as Oe}from"node:crypto";import{constants as ke,promises as W}from"node:fs";import ie from"node:path";import{GeneratedSiteCapabilitiesSchema as yt}from"@vcp-dev/contracts";var _t=".vcp/portable-snapshot-proof.json",Ae=4*1024*1024,St=256*1024*1024,bt=1e4,It=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function ve(e){try{let t=ie.join(e.projectRoot,_t),s=await W.lstat(t);if(!s.isFile()||s.isSymbolicLink()||s.size>Ae)return null;let n=JSON.parse(await W.readFile(t,"utf8"));if(!H(n)||!$(n,["payload"])||!Rt(n.payload,Ae))return null;let o=Buffer.from(n.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!H(r)||!$(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!H(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>bt)return null;let p=yt.safeParse(r.host_capabilities);if(!p.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of r.trusted_host_file_hashes){if(!H(c)||!$(c,["path","hash"])||typeof c.path!="string"||!wt(c.path)||!Te(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||d.has(c.path))return null;d.set(c.path,c.hash)}let h=0,f=[],g=new Set;for(let c of a.files){if(!H(c)||!$(c,["path","hash","size_bytes"])||typeof c.path!="string"||!Te(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||g.has(c.path)||(g.add(c.path),h+=c.size_bytes,h>St))return null;f.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let u=new Map;for(let c of f){let m=await Et(e.projectRoot,c.path,c.size_bytes,c.hash);if(!m||`sha256:${Oe("sha256").update(m).digest("hex")}`!==c.hash)return null;u.set(c.path,m)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:f},files:u},host_capabilities:p.data,trusted_host_file_hashes:d}}catch{return null}}function wt(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 Et(e,t,s,n){let o=t.split("/"),i=e;for(let p of o.slice(0,-1)){i=ie.join(i,p);let d=await W.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let r=ie.join(i,o.at(-1)),a=await W.open(r,ke.O_RDONLY|ke.O_NOFOLLOW);try{let p=await a.stat(),d=M(t,s,n);if(!p.isFile()||p.size!==s&&p.size!==d)return null;let h=[],f=0,g=a.createReadStream({autoClose:!1});for await(let c of g){let m=c;if(f+=m.byteLength,f>p.size)return g.destroy(),null;h.push(m)}if(f!==p.size)return null;let u=Buffer.concat(h,f);return f===s?u:j({file:t,expectedSize:s,expectedDigest:n,actualSize:f,actualDigest:`sha256:${Oe("sha256").update(u).digest("hex")}`})?Ie():null}finally{await a.close()}}function Te(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!It.has(t[0])&&t.every(s=>s&&s!=="."&&s!=="..")}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.hasOwn(e,s))}function Rt(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{PortableCmsSchemaEnvelopeSchema as xt,PortableCmsSchemaStatementSchema as Ct}from"@vcp-dev/contracts";var kt=3e4;function Pe(e){try{let t=xt.safeParse(e.proof);if(!t.success||!At(t.data.payload,262144))return null;let s=Buffer.from(t.data.payload,"base64url"),n=new TextDecoder("utf-8",{fatal:!0}).decode(s),o=JSON.parse(n);if(JSON.stringify(o)!==n)return null;let i=Ct.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+kt||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 At(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 Vt,SiteEditPortableExportRequestSchema as qt,SiteEditPortableExportResultSchema as zt,SiteEditPortableAssetRequestSchema as jt,SiteEditPortableAssetResultSchema as Ut,computeSiteEditCompositionKey as v}from"@vcp-dev/contracts";var $t="127.0.0.1",Wt=30218,Jt="/__vcp/site-edit/bridge",Fe=6*1024*1024,Qt=Fe*2,Xt=3e3,Be=50,re=".vcp/current-snapshot.json",Ne="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function zs(e){let t=J(e),s=qe(t),n=Ve(),o=n.get(s);if(o)return o;let i=new D(t);n.set(s,i);try{i.start()}catch(r){throw n.delete(s),i.stop(),r}return i}function js(e,t,s={}){let n=new D(J(t),e,!1,s);return n.start({listen:!1}),n}var D=class{constructor(t,s=De.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=t,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new q,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{L.mkdirSync(x.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(s){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${s instanceof Error?s.message:String(s)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let s=ts({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=s.stop}this.stopWatching=new Ft({projectRoot:this.options.projectRoot,watch_dirs:Yt(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Be,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=Ve(),s=qe(this.options);t.get(s)===this&&t.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{t(s)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,s=null){let n=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??Pt)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=Zt(t.composition),o=this.getRuntime(),i=I(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let p=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:p}}}),getDocument:async t=>{let s=this.getRuntime(),n=I(t);await s.initializeComposition(n);let o=s.getDocument(n);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(I(t)),getObjectEditContext:async(t,s,n)=>this.getRuntime().getObjectEditContext(t,I(s),n),getClassNameSource:async(t,s)=>this.getRuntime().getClassNameSource(t,I(s)),getSourceTree:async t=>this.getRuntime().getSourceTree(I(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:I(t.composition)}),exportPortableBlock:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,s)),exportPortableBlockAsset:(t,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,s)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:I(t.composition)}),execute:(t,s)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return Me(n,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,s)=>this.runHistoryWithReceipt("undo",t,s),redo:(t,s)=>this.runHistoryWithReceipt("redo",t,s),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let s=[];for(let n of t.cms_schema_proofs??[]){let o=Pe({proof:n,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;s.push(o)}return s}async exportPortableBlock(t,s,n){let o=(_,k,$e)=>({complete:!1,unresolved:[{code:_,path:k,message:$e}]}),i=qt.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=I(s);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let d=()=>{let _=this.getRuntime().getDocument(a).data;return{site_id:_.siteId,snapshot_id:_.snapshotId,document_version:_.version}},h=d();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let f=this.verifyCmsSchemaProofs(r);if(!f)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let g=this.dependencies.loadTrustedPortableSnapshot??(_=>ve({..._,projectRoot:this.options.projectRoot})),u;try{u=await g({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!u)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...u.snapshot.files].map(([_,k])=>[_,typeof k=="string"?k:new Uint8Array(k)])),m={...u,snapshot:{...u.snapshot,files:c}};if(!await U(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:C,...w}=r,E=await Bt({...w,...m,trusted_cms_schemas:f,read_current_identity:d}),y=zt.safeParse(E);if(!y.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(y.data.complete&&(y.data.site_id!==r.site_id||y.data.base_snapshot_id!==r.base_snapshot_id||y.data.document_version!==r.document_version||y.data.target.blockKey!==r.target.blockKey||y.data.target.composition.routeId!==a.routeId||y.data.target.composition.templateId!==a.templateId||y.data.selection_ref.key!==r.selection_ref.key||y.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||y.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(y.data.complete||y.data.cms_candidates){if(!await U(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=d();if(this.options.snapshotId!==r.base_snapshot_id||_.site_id!==r.site_id||_.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(_.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");y.data.complete&&n?.(c)}return y.data}async exportPortableBlockAsset(t,s){let n=h=>({complete:!1,unresolved:[{code:h,path:"<asset>",message:"The selected local image could not be verified."}]}),o=jt.safeParse(t);if(!o.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,s,h=>{r=h});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!r)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let p=Nt({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),d=Ut.safeParse(p);if(!d.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!d.data.complete)return d.data;if(!await U(this.options.projectRoot,r))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let h=this.getRuntime().getDocument(I(s)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||h.siteId!==i.request.site_id||h.snapshotId!==i.request.base_snapshot_id||h.version!==i.request.document_version)return n("DOCUMENT_VERSION_STALE")}catch{return n("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?d.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==t||n.composition.routeId!==s.routeId||n.composition.templateId!==s.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return Me(i,void 0,s);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??s),r.composition?r:{...r,composition:s}});return n?this.executeWithReceipt(n,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return ue("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let s=this.operationReceipts.get(this.operationReceiptKey(t));return s?.fingerprint===this.operationFingerprint(t)?s.result:null}executeWithReceipt(t,s){if(!this.isActiveReceiptIdentity(t))return s();let n=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(n);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:s(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,p]of this.operationReceipts){if(this.operationReceipts.size<=256)break;p.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let n=await(this.dependencies.openHistoryStore??Mt)(es({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=n.readDocumentVersion?await n.readDocumentVersion():0,i=this.versionCheckpoints.get(n);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(n,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=v(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,t)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,s){let n=s?v(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,p=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=p,this.versionPersistence=p,p}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let n of t)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Be;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let s=t.some(Ue)?this.scheduleSnapshotIdentityAdvance():!1,n=t.filter(o=>!ds(o));if(!(n.length===0&&!s)&&this.refreshCompositions(!1))for(let o of n)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=L.readFileSync(x.join(this.options.projectRoot,re),"utf8"),s=JSON.parse(t),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||ae(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=s,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${s}: ${o instanceof Error?o.message:String(o)}`);return}let n=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:s,at:n};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,s)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let s=Gt(this.options.projectRoot),n=Kt(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),i=Lt({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(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(d=>[v(d.context),d])),p=new Map(i.map(d=>[v(d.context),d]));if(this.runtime){for(let[d,h]of a){let f=p.get(d);(!f||f.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(I(h.context))}for(let[d,h]of p){let f=a.get(d);(!f||f.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=s,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(s){let n=s instanceof Error?s:new Error(String(s));if(this.compositionResolutionError=n,t)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=Dt(t.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let n=this.routes.find(r=>r.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Ht({selector:{routeId:s,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=v(o.context);if(!this.compositions.some(r=>v(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let s=this.runtimeVersionFloors.get(v(t.context));return s===void 0?[]:[{composition:t.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Us(e){let t=new D(J(e),De.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function $s(e){return J(e)}function J(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:x.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??$t,port:e.port??Wt,path:e.path??Jt,sessionKey:e.sessionKey??cs(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Yt(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 Gt(e){let t=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!L.existsSync(i))return;let r;try{r=L.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(x.join(i,a.name));continue}if(!a.isFile())continue;let p=x.join(i,a.name),d="";try{d=L.readFileSync(p,"utf8")}catch{}t.push({path:x.relative(e,p).replaceAll(x.sep,"/"),content:d})}};for(let i of s)o(x.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function Zt(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function I(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function es(e){return x.join(x.resolve(e.root),ae(e.siteId),ae(e.snapshotId),ue("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function ae(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:ue("sha256").update(e).digest("hex").slice(0,32)}function Ve(){let e=globalThis;return e[Ne]??=new Map,e[Ne]}function qe(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Me(e,t,s){let n=s??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!n)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:n,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:n,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function ts(e){let t=new vt({maxPayload:Fe,noServer:!0}),s=new WeakSet,n=i=>{new V({socket:new ce(i),engine:e.engine,validateOperationRequest:r=>Vt.safeParse(r).success})},o=(i,r,a)=>{if(!ss(i,e))return;let p=ns(i,e);if(!p){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import We from"node:http";import K from"node:fs";import{createHash as ge,randomBytes as Ut,timingSafeEqual as $t}from"node:crypto";import k from"node:path";import{WebSocket as qe,WebSocketServer as jt}from"ws";import{createPreviewSiteEditEngineRuntime as Wt,exportPortableBlockFromSnapshot as qt,readPortableBlockLocalAssetChunk as Jt,openFileHistoryStore as Qt,resolveManagedPageTemplateComposition as Xt,scanSiteEditCompositionsFromFiles as Yt}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Gt,scanNextAppRouterRoutesFromFiles as Zt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as es}from"@vcp-dev/site-edit-engine/source-watcher";function Se(t){if(t.pageBlocks!==void 0&&!st(t.pageBlocks))throw new Error("Invalid page block directory");let e=new Map,s=[],n=new Map,o=[],i=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(i.map((p,c)=>[p,c])),a=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},u=t.entries.flatMap((p,c)=>p.dynamicDataSummary?[[c,p.dynamicDataSummary]]:[]),d=new Map(t.entries.map((p,c)=>[p.key,c])),h=[];for(let[p,c]of t.entries.entries()){let m=c.pageCompositionActionScope;if(!m)continue;if(m.kind!=="source-siblings"){h.push([p,{kind:m.kind}]);continue}let w=m.siblingKeys.map(R=>{let C=d.get(R);if(C===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+R);return C});h.push([p,{kind:"source-siblings",siblingEntryIndexes:w}])}let l=p=>{let c=e.get(p);if(typeof c=="number")return c;let m=s.length;return s.push(p),e.set(p,m),m},f=p=>{let c=null;for(let m of pt(p)){let w=`${c??"root"}\0${m}`,R=n.get(w);if(typeof R=="number"){c=R;continue}let C=o.length;o.push([c,l(m)]),n.set(w,C),c=C}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:a,tokens:s,nodes:o,entries:t.entries.map(p=>{let c=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&c<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[f(p.key),tt(p.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...t.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:t.entries.map(p=>p.parentKey===null?null:f(p.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{}}}function tt(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function v(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ye(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function st(t){if(!Array.isArray(t))return!1;let e=new Map;for(let s of t){if(!v(s)||!N(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!V(s.blockKey,256)||!V(s.definitionKey,512)||!nt(s.rootRef)||!it(s.source)||!ot(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>V(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!B(s.placementUnitKey)||!rt(s.capabilities)||s.unavailableReasons!==void 0&&!at(s.unavailableReasons)||e.has(s.blockKey))return!1;e.set(s.blockKey,s)}for(let s of t){let n=s.owner;for(let o of s.siblingBlockKeys){let i=e.get(o);if(!i)return!1;let r=i.owner;if(n.kind!==r.kind||n.key!==r.key)return!1}}return!0}function nt(t){return!v(t)||!N(t,["key","instanceIndex","instanceCount"])||!B(t.key)||t.instanceIndex!==void 0&&!ye(t.instanceIndex)||t.instanceCount!==void 0&&(!ye(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function it(t){return v(t)&&N(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ct(t.file)&&B(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function ot(t){return v(t)&&N(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&V(t.key,512)}function rt(t){return v(t)&&N(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function at(t){return v(t)&&Object.entries(t).every(([e,s])=>B(e)&&v(s)&&N(s,["code","reason"])&&B(s.code)&&B(s.reason))}function ct(t){let e=dt(t),s=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||s.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let n=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(n)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(n)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(n)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(n)||n.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>t===i||t.startsWith(`${i}/`))||e}function dt(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let s=e[1].split("/"),n=s.some(r=>_e(r)),o=n?s[0]:s.pop(),i=n?s.slice(1):s;if(n&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!ut(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!_e(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,h=>h.charCodeAt(0)),d=new TextDecoder("utf-8",{fatal:!0}).decode(u);return d.length>0&&d.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(d)&&!d.startsWith(" ")&&!d.endsWith(" ")&&new TextEncoder().encode(d).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(d))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function _e(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ut(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let s=decodeURIComponent(e);return s==="."||s===".."||/[/\\\x00-\x1f\x7f]/u.test(s)||s.startsWith(".vcp")}catch{return!0}})}function V(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function B(t){return typeof t=="string"&&t.length>0}function N(t,e){let s=new Set(e);return Object.keys(t).every(n=>s.has(n))}function pt(t){if(!t)return[];let e=[],s=0,n=be(t,s);if(n<0)return e.push(t),e;for(e.push(t.slice(0,n)),s=n;s<t.length;){if(n=be(t,s+(t.startsWith("::",s)?2:1)),n<0){e.push(t.slice(s));break}e.push(t.slice(s,n)),s=n}return e}function be(t,e){let s=t.indexOf("/",e),n=t.indexOf("::",e);return s<0?n:n<0?s:Math.min(s,n)}var L="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ie="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var x=class t{constructor(){}static parseMessage(e,s={}){let n=JSON.parse(e);if(!t.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(g(e)&&g(e.payload)){let s=typeof e.payload.id=="string"?e.payload.id:"unknown",n=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="export-portable-block"||e==="export-portable-block-asset"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,s={}){return!g(e)||typeof e.type!="string"?!1:e.type==="request"?ft(e.payload,s):e.type==="response"||e.type==="error"?g(e.payload)&&typeof e.payload.id=="string":e.type==="event"?g(e.payload)&&g(e.payload.event):e.type==="auth"?g(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?g(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&g(e.payload)&&e.payload.ok===!0}},U=class{constructor(e){this.options=e,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ne,this.eventDispatcher=new se(s=>{this.sendJson(s)}),this.unsubscribe=e.engine.subscribe(s=>{this.handleEngineEvent(s)}),e.socket.onmessage=s=>{let n=lt(s.data);if(n!==null){this.sendJson({type:"pong",payload:{id:n}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(e){try{let s=e;if(s.type!=="request")return;let n=s.payload,{id:o}=n;switch(n.kind){case"initialize-session":{let i=G(n),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:n.kind,result:T({...a,data:{...a.data,document:Re(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(n),r=await this.options.engine.getDocument(i);this.sendResult(o,n.kind,St(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(n),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,n.kind,T(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getObjectEditContext(n.key,i,n.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getClassNameSource(n.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,T(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!oe(n))throw new I("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.target.composition);if(b(i)!==b(r))throw new I(L,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,n.kind,a);return}case"export-portable-block-asset":{if(!we(n))throw new I("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.request.target.composition);if(b(i)!==b(r))throw new I(L,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(n.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,n.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(n),r=T(await this.options.engine.resolveSourceLocation({key:n.key,composition:i}),i);this.sendResult(o,n.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(n.request),r=await this.resolveWireContext(n);if(b(i)!==b(r))throw new I(L,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(n.request,i);if(n.kind==="get-operation-result"){this.sendResult(o,n.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,n.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(n),r=await this.resolveAndAssert(n.request.composition);if(b(i)!==b(r))throw new I(L,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:z(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(n),r=n.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==n.kind||b(i)!==b(u))throw new I(L,"History request does not match its cursor operation.")}let a=r?{...r,composition:z(i)}:void 0;await this.handleBufferedOperation(o,n.kind,()=>n.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(s){let n=x.extractRequestInfo(e);this.sendJson({type:"error",payload:{...n,message:te(s),code:ee(s)}})}}async resolve(e){return this.options.engine.resolveComposition(e)}async resolveAndAssert(e){let s=await this.resolve(e),n=this.session.activeComposition;if(!n)throw new I(ie,"Initialize a composition session before issuing this request.");if(b(n)!==b(s.context))throw new I(L,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(e){let s=G(e);return this.resolveAndAssert(s)}async resolveOperationWireContext(e){let s=_t(e);return this.resolveAndAssert(s)}activateSession(e){this.session.activeComposition=e,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(b(e))}async normalizeOperationRequest(e,s){let n={...e,composition:z(s)};if(n.target.kind==="route"){let o=n.target,i=G(o),r=await this.resolveAndAssert(i);n.target={...o,composition:z(r)}}return n}handleEngineEvent(e){let s=e?.composition;if(!yt(s))return;let n=b(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(e),e.type==="site-edit.graph.invalidated"&&n===bt(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(n)))}sendResult(e,s,n){this.sendJson({type:"response",payload:{id:e,kind:s,result:n}})}async handleRawMessage(e){try{await this.handleMessage(x.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=It(e);this.sendJson({type:"error",payload:{...n,message:te(s),code:ee(s)}})}}sendJson(e){this.options.socket.send(x.stringifyMessage(e))}async handleBufferedOperation(e,s,n){this.eventDispatcher.beginBuffering();try{let o=await n();this.sendResult(e,s,o)}catch(o){this.sendJson({type:"error",payload:{id:e,kind:s,message:te(o),code:ee(o)}})}finally{this.eventDispatcher.flush()}}},ht=256;function lt(t){if(t.length>ht||!t.includes('"ping"'))return null;try{let e=JSON.parse(t);return g(e)&&e.type==="ping"&&g(e.payload)&&typeof e.payload.id=="string"?e.payload.id:null}catch{return null}}var I=class extends Error{constructor(e,s){super(s),this.code=e,this.name="BridgeProtocolError"}},se=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let s={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(s=>this.send(s))}},ne=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await e()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function ft(t,e){if(!g(t)||typeof t.id!="string"||!x.isRequestKind(t.kind))return!1;let s=O(t.composition);switch(t.kind){case"initialize-session":return s&&(t.mutationContext===void 0||Z(t.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof t.key=="string"&&s&&Ee(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&s;case"get-history-status":return s;case"get-source-tree":return s;case"get-source-file":return typeof t.path=="string"&&s;case"export-portable-block":return oe(t);case"export-portable-block-asset":return we(t);case"execute":case"get-operation-result":return s&>(t.request)&&(t.request.mutationContext===void 0||Z(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return s&&Ie(t.request);case"undo":case"redo":return s&&(t.request===void 0||Ie(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||Z(t.mutationContext))}}function oe(t){if(!O(t.composition)||!Object.keys(t).every(s=>["id","kind","composition","request"].includes(s))||!g(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(s=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(s))||typeof e.site_id!="string"||typeof e.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.base_snapshot_id)||typeof e.document_version!="number"||!Number.isSafeInteger(e.document_version)||e.document_version<0||!g(e.target)||e.target.kind!=="page-block"||typeof e.target.blockKey!="string"||!e.target.blockKey.length||e.target.blockKey.length>256||!Object.keys(e.target).every(s=>["kind","composition","blockKey"].includes(s))||!O(e.target.composition)||e.target.composition.routeId!==t.composition.routeId||e.target.composition.templateId!==t.composition.templateId||e.selection_ref===void 0||!Ee(e.selection_ref)||e.cms_schema_proofs!==void 0&&!mt(e.cms_schema_proofs))}function mt(t){if(!Array.isArray(t)||t.length>16||!Reflect.ownKeys(t).every(e=>e==="length"||typeof e=="string"&&/^(0|[1-9][0-9]*)$/u.test(e)&&Number(e)<t.length))return!1;for(let e=0;e<t.length;e++){let s=Object.getOwnPropertyDescriptor(t,String(e));if(!s||!("value"in s))return!1;let n=s.value;if(!g(n)||!Reflect.ownKeys(n).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(n,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function we(t){if(!Object.keys(t).every(s=>["id","kind","composition","request"].includes(s))||!g(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(s=>["request","snapshot_digest","file_path","occurrence","offset","capture_id"].includes(s))||!oe({id:t.id,kind:"export-portable-block",composition:t.composition,request:e.request})||typeof e.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.snapshot_digest)||typeof e.file_path!="string"||!e.file_path.length||e.file_path.length>1024||e.file_path.startsWith("/")||/[\\\0%]/u.test(e.file_path)||e.file_path.split("/").some(s=>!s||s.startsWith(".")||s==="node_modules")||typeof e.occurrence!="number"||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||e.occurrence>4095||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0||e.capture_id!==void 0&&(typeof e.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)))}function Ie(t){return g(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&O(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function Ee(t){if(t===void 0)return!0;if(!g(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,s=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof e=="number"&&typeof s=="number"&&e>=s?!1:Object.keys(t).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function gt(t){return g(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&O(t.composition)&&typeof t.kind=="string"&&g(t.target)&&(t.target.kind!=="route"||O(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&g(t.params)}function O(t){return g(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function yt(t){return g(t)&&typeof t.routeId=="string"&&(t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string")}function G(t){if(O(t.composition))return t.composition;throw new I(ie,"A composition selector is required for this request.")}function _t(t){if(g(t)&&O(t.composition))return t.composition;throw new I(ie,"A composition selector is required for execute.")}function z(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function bt(t){return t.activeComposition?b(t.activeComposition):null}function b(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function T(t,e){return g(t)&&t.ok===!0?{...t,composition:e}:t}function St(t,e){return!g(t)||t.ok!==!0?t:{...t,...e?{composition:e}:{},data:Re(t.data)}}function Re(t){let e=t;return Se(e.routeId?e:{...e,routeId:e.composition.routeId})}function g(t){return typeof t=="object"&&t!==null}function Z(t){return g(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}function ee(t){if(!(!g(t)||typeof t.code!="string"||t.code.length===0))return t.code}function te(t){return t instanceof Error||g(t)&&typeof t.message=="string"&&t.message.length>0?t.message:"Unknown websocket operation failure"}function It(t){try{return x.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var $=class{constructor(){this.tail=Promise.resolve()}run(e){let s=this.tail.then(e,e);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as Ae}from"node:crypto";import{constants as Te,promises as re}from"node:fs";import Oe from"node:path";import{createHash as wt}from"node:crypto";var j=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
|
+
`)),Ce=Buffer.from(j.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),xe=t=>`sha256:${wt("sha256").update(t).digest("hex")}`,Et=xe(j),Rt=xe(Ce);function H(t,e,s){return t==="next-env.d.ts"&&e===j.byteLength&&s===Et?Ce.byteLength:null}function W(t){return H(t.file,t.expectedSize,t.expectedDigest)===t.actualSize&&t.actualDigest===Rt}function ke(){return Uint8Array.from(j)}var ve=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),Pe=64;async function q(t,e){try{if(!e.size)return!1;for(let[i,r]of e)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||ve.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>Pe||++s>e.size*Pe+1)return!1;let a=await re.readdir(Oe.join(t,i),{withFileTypes:!0});for(let u of a){let d=i?`${i}/${u.name}`:u.name;if(!i&&ve.has(u.name))continue;if(u.isDirectory()){if(!await o(d,r+1))return!1;continue}if(!u.isFile())return!1;let h=e.get(d);if(h===void 0||n.has(d))return!1;n.add(d);let l=Oe.join(t,d),f=await re.lstat(l),p=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${Ae("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==p&&f.size!==H(d,p,c))return!1;let m=Ae("sha256"),w=await re.open(l,Te.O_RDONLY|Te.O_NOFOLLOW);try{let C=await w.stat();if(!C.isFile()||C.size!==f.size)return!1;let y=0,_=w.createReadStream({autoClose:!1});for await(let A of _){if(y+=A.byteLength,y>f.size)return _.destroy(),!1;m.update(A)}if(y!==f.size)return!1}finally{await w.close()}let R=`sha256:${m.digest("hex")}`;if((f.size!==p||R!==c)&&!W({file:d,expectedSize:p,expectedDigest:c,actualSize:f.size,actualDigest:R}))return!1}return!0};return await o("",0)&&n.size===e.size}catch{return!1}}import{createHash as Me}from"node:crypto";import{constants as Be,promises as Q}from"node:fs";import ae from"node:path";import{GeneratedSiteCapabilitiesSchema as Ct}from"@vcp-dev/contracts";var xt=".vcp/portable-snapshot-proof.json",Ne=4*1024*1024,kt=256*1024*1024,At=1e4,Tt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function He(t){try{let e=ae.join(t.projectRoot,xt),s=await Q.lstat(e);if(!s.isFile()||s.isSymbolicLink()||s.size>Ne)return null;let n=JSON.parse(await Q.readFile(e,"utf8"));if(!D(n)||!J(n,["payload"])||!Pt(n.payload,Ne))return null;let o=Buffer.from(n.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!D(r)||!J(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!D(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==t.site_id||a.snapshot_id!==t.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>At)return null;let u=Ct.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of r.trusted_host_file_hashes){if(!D(c)||!J(c,["path","hash"])||typeof c.path!="string"||!Ot(c.path)||!Le(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||d.has(c.path))return null;d.set(c.path,c.hash)}let h=0,l=[],f=new Set;for(let c of a.files){if(!D(c)||!J(c,["path","hash","size_bytes"])||typeof c.path!="string"||!Le(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||f.has(c.path)||(f.add(c.path),h+=c.size_bytes,h>kt))return null;l.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let p=new Map;for(let c of l){let m=await vt(t.projectRoot,c.path,c.size_bytes,c.hash);if(!m||`sha256:${Me("sha256").update(m).digest("hex")}`!==c.hash)return null;p.set(c.path,m)}return{snapshot:{site_id:t.site_id,snapshot_id:t.base_snapshot_id,manifest:{version:1,site_id:t.site_id,snapshot_id:t.base_snapshot_id,created_at:a.created_at,files:l},files:p},host_capabilities:u.data,trusted_host_file_hashes:d}}catch{return null}}function Ot(t){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(t)||/^(?:src\/)?lib\/utils\.ts$/u.test(t)}async function vt(t,e,s,n){let o=e.split("/"),i=t;for(let u of o.slice(0,-1)){i=ae.join(i,u);let d=await Q.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let r=ae.join(i,o.at(-1)),a=await Q.open(r,Be.O_RDONLY|Be.O_NOFOLLOW);try{let u=await a.stat(),d=H(e,s,n);if(!u.isFile()||u.size!==s&&u.size!==d)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let c of f){let m=c;if(l+=m.byteLength,l>u.size)return f.destroy(),null;h.push(m)}if(l!==u.size)return null;let p=Buffer.concat(h,l);return l===s?p:W({file:e,expectedSize:s,expectedDigest:n,actualSize:l,actualDigest:`sha256:${Me("sha256").update(p).digest("hex")}`})?ke():null}finally{await a.close()}}function Le(t){let e=t.split("/");return t.length>0&&t.length<=1024&&!t.startsWith("/")&&!/[\\\0]/u.test(t)&&!Tt.has(e[0])&&e.every(s=>s&&s!=="."&&s!=="..")}function D(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t,e){return Object.keys(t).length===e.length&&e.every(s=>Object.hasOwn(t,s))}function Pt(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{createHash as Bt}from"node:crypto";import Nt from"node:dns/promises";import Lt from"node:http";import Mt from"node:https";import{isIP as M}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as ce,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as de}from"@vcp-dev/contracts";var S=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function De(t){if(M(t)===4){let[e,s]=t.split(".").map(Number);return!(e===0||e===10||e===127||e>=224||e===100&&s>=64&&s<=127||e===169&&s===254||e===172&&s>=16&&s<=31||e===192&&[0,168].includes(s)||e===198&&[18,19,51].includes(s)||e===203&&s===0)}return M(t)===6&&/^[23]/u.test(t)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(t)}function ue(t){let e=new URL(t),s=e.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.port||e.hash||s==="localhost"||!s.includes(".")&&!M(s)||/\.(?:internal|localhost|local)$/iu.test(s)||M(s)&&!De(s))throw S();return e}function Ke(t){let e=s=>s.every((n,o)=>t[o]===n);return e([137,80,78,71,13,10,26,10])?"image/png":e([255,216,255])?"image/jpeg":e([71,73,70,56,55,97])||e([71,73,70,56,57,97])?"image/gif":e([82,73,70,70])&&Buffer.from(t.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function Ht(t,e){let s=()=>{};try{return await Promise.race([t,new Promise((n,o)=>{s=()=>o(S()),e.addEventListener("abort",s,{once:!0}),e.aborted&&s()})])}finally{e.removeEventListener("abort",s)}}async function Dt(t,e){let s=AbortSignal.any([e,AbortSignal.timeout(15e3)]),n=ue(t);for(let o=0;o<=3;o++){s.throwIfAborted();let i=n.hostname.replace(/^\[|\]$/gu,""),r=M(i)?[{address:i,family:M(i)}]:await Ht(Nt.lookup(i,{all:!0}),s);if(s.throwIfAborted(),!r.length||r.some(({address:d})=>!De(d)))throw S();let a=r.find(d=>d.family===4)??r[0],u=await new Promise((d,h)=>{(n.protocol==="https:"?Mt:Lt).get(n,{agent:!1,signal:s,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,p,c)=>{p.all?c(null,[{address:a.address,family:a.family}]):c(null,a.address,a.family)}},d).on("error",h)});try{let d=u.statusCode??0;if([301,302,303,307,308].includes(d)){if(!u.headers.location||o===3)throw S();let m=ue(new URL(u.headers.location,n).href);if(n.protocol==="https:"&&m.protocol!=="https:")throw S();n=m;continue}let h=u.headers["content-length"];if(d!==200||u.headers["content-encoding"]&&u.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>de))throw S();let l=[],f=0;for await(let m of u){let w=Buffer.from(m);if(f+=w.length,f>de)throw S();l.push(w)}if(!f||h!==void 0&&Number(h)!==f)throw S();let p=Buffer.concat(l,f),c=Ke(p);if(!c||u.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==c)throw S();return{bytes:p,mime_type:c}}finally{u.destroy()}}throw S()}var X=class{constructor(e=Dt){this.download=e,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(e,s){let n=s.media.filter(f=>f.file_path===e.file_path&&f.occurrence===e.occurrence),o=n[0];if(this.controller.signal.aborted||e.snapshot_digest!==s.snapshot_digest||n.length!==1||!o?.complete||o.cms_field||o.kind==="srcset"||!o.value||!e.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%ce)throw S();ue(o.value);let i=JSON.stringify([e.request,e.snapshot_digest,e.file_path,e.occurrence,e.capture_id,o.value]),r=this.entries.get(i);if(!r){if(e.offset||this.pending.has(i)||this.pending.size>=2||this.entries.size>=16)throw S();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>de||Ke(f.bytes)!==f.mime_type||[...this.entries.values()].reduce((c,m)=>c+m.image.bytes.length,f.bytes.length)>64*1024*1024)throw S();let p=setTimeout(()=>this.remove(i),6e4);p.unref(),r={image:f,timer:p},this.entries.set(i,r)}finally{this.pending.delete(i)}}let{bytes:a,mime_type:u}=r.image;if(e.offset>=a.length)throw S();let d=Bt("sha256").update(a).digest("hex"),h={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[u],l={complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:`public/__portable_remote__/${d}.${h}`,mime_type:u,byte_size:a.length,digest_sha256:d,offset:e.offset,data_base64:Buffer.from(a.subarray(e.offset,e.offset+ce)).toString("base64")};return e.offset+ce>=a.length&&this.remove(i),l}remove(e){let s=this.entries.get(e);s&&clearTimeout(s.timer),this.entries.delete(e)}dispose(){this.controller.abort();for(let e of this.entries.keys())this.remove(e)}};import{PortableCmsSchemaEnvelopeSchema as Kt,PortableCmsSchemaStatementSchema as Ft}from"@vcp-dev/contracts";var Vt=3e4;function Fe(t){try{let e=Kt.safeParse(t.proof);if(!e.success||!zt(e.data.payload,262144))return null;let s=Buffer.from(e.data.payload,"base64url"),n=new TextDecoder("utf-8",{fatal:!0}).decode(s),o=JSON.parse(n);if(JSON.stringify(o)!==n)return null;let i=Ft.safeParse(o),r=t.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==t.site_id||i.data.base_snapshot_id!==t.base_snapshot_id||i.data.issued_at>r+Vt||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 zt(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&/^[A-Za-z0-9_-]+$/u.test(t)&&Buffer.from(t,"base64url").toString("base64url")===t}import{SiteEditOperationRequestSchema as ts,SiteEditPortableExportRequestSchema as ss,SiteEditPortableExportResultSchema as ns,SiteEditPortableAssetRequestSchema as is,SiteEditPortableAssetResultSchema as os,computeSiteEditCompositionKey as P}from"@vcp-dev/contracts";var rs="127.0.0.1",as=30218,cs="/__vcp/site-edit/bridge",Je=6*1024*1024,ds=Je*2,us=3e3,Ve=50,he=".vcp/current-snapshot.json",ze="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function hn(t){let e=Y(t),s=Xe(e),n=Qe(),o=n.get(s);if(o)return o;let i=new F(e);n.set(s,i);try{i.start()}catch(r){throw n.delete(s),i.stop(),r}return i}function ln(t,e,s={}){let n=new F(Y(e),t,!1,s);return n.start({listen:!1}),n}var F=class{constructor(e,s=We.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,o={}){this.options=e,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new $,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 X}start(e={}){if(!this.isStarted){this.stopping=!1;try{K.mkdirSync(k.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(s){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${s instanceof Error?s.message:String(s)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let s=ms({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=s.stop}this.stopWatching=new es({projectRoot:this.options.projectRoot,watch_dirs:ps(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Ve,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=Qe(),s=Xe(this.options);e.get(s)===this&&e.delete(s),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let s=this.getHealth(),n=JSON.stringify(s);if(n!==this.lastNotifiedHealth){this.lastNotifiedHealth=n;try{e(s)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(e,s=null){let n=this.runtime;this.activeHistoryStore=e??null;let o=(this.dependencies.createRuntime??Wt)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=s,n?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let n=ls(e.composition),o=this.getRuntime(),i=E(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:u}}}),getDocument:async e=>{let s=this.getRuntime(),n=E(e);await s.initializeComposition(n);let o=s.getDocument(n);return await this.recordRuntimeVersion(o.data.version,e),{...o,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(E(e)),getObjectEditContext:async(e,s,n)=>this.getRuntime().getObjectEditContext(e,E(s),n),getClassNameSource:async(e,s)=>this.getRuntime().getClassNameSource(e,E(s)),getSourceTree:async e=>this.getRuntime().getSourceTree(E(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:E(e.composition)}),exportPortableBlock:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlock(e,s)),exportPortableBlockAsset:(e,s)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(e,s)),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:E(e.composition)}),execute:(e,s)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return Ue(n,e);let o=await this.getRuntime().executeOperation(e);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:e=>this.readOperationReceipt(e),getHistoryOperationResult:e=>this.readOperationReceipt(e),undo:(e,s)=>this.runHistoryWithReceipt("undo",e,s),redo:(e,s)=>this.runHistoryWithReceipt("redo",e,s),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}verifyCmsSchemaProofs(e){let s=[];for(let n of e.cms_schema_proofs??[]){let o=Fe({proof:n,site_id:e.site_id,base_snapshot_id:e.base_snapshot_id});if(!o)return null;s.push(o)}return s}async exportPortableBlock(e,s,n){let o=(_,A,et)=>({complete:!1,unresolved:[{code:_,path:A,message:et}]}),i=ss.safeParse(e);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=E(s);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let d=()=>{let _=this.getRuntime().getDocument(a).data;return{site_id:_.siteId,snapshot_id:_.snapshotId,document_version:_.version}},h=d();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(_=>He({..._,projectRoot:this.options.projectRoot})),p;try{p=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(!p)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...p.snapshot.files].map(([_,A])=>[_,typeof A=="string"?A:new Uint8Array(A)])),m={...p,snapshot:{...p.snapshot,files:c}};if(!await q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:w,...R}=r,C=await qt({...R,...m,trusted_cms_schemas:l,read_current_identity:d}),y=ns.safeParse(C);if(!y.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(y.data.complete&&(y.data.site_id!==r.site_id||y.data.base_snapshot_id!==r.base_snapshot_id||y.data.document_version!==r.document_version||y.data.target.blockKey!==r.target.blockKey||y.data.target.composition.routeId!==a.routeId||y.data.target.composition.templateId!==a.templateId||y.data.selection_ref.key!==r.selection_ref.key||y.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||y.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(y.data.complete||y.data.cms_candidates){if(!await q(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let _=d();if(this.options.snapshotId!==r.base_snapshot_id||_.site_id!==r.site_id||_.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(_.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");y.data.complete&&n?.(c)}return y.data}async exportPortableBlockAsset(e,s){let n=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=is.safeParse(e);if(!o.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,s,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!r)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=a.media.find(l=>l.file_path===i.file_path&&l.occurrence===i.occurrence),d;try{d=u?.value&&/^https?:\/\//iu.test(u.value)?await this.portableRemoteAssets.read(i,a):Jt({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset})}catch{return n("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=os.safeParse(d);if(!h.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await q(this.options.projectRoot,r))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(E(s)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||l.siteId!==i.request.site_id||l.snapshotId!==i.request.base_snapshot_id||l.version!==i.request.document_version)return n("DOCUMENT_VERSION_STALE")}catch{return n("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?h.data:n("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(e,s,n){if(n&&(!this.isActiveReceiptIdentity(n)||n.kind!==e||n.composition.routeId!==s.routeId||n.composition.templateId!==s.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return Ue(i,void 0,s);let r=await this.getRuntime()[e]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??s),r.composition?r:{...r,composition:s}});return n?this.executeWithReceipt(n,o):o()}isActiveReceiptIdentity(e){return"request_id"in e?e.site_id===this.options.siteId&&e.base_snapshot_id===this.options.snapshotId:e.siteId===this.options.siteId&&e.baseSnapshotId===this.options.snapshotId}operationReceiptKey(e){return"request_id"in e?JSON.stringify([e.site_id,e.base_snapshot_id,"history",e.request_id]):JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return ge("sha256").update(JSON.stringify(e)).digest("hex")}readOperationReceipt(e){if(!this.isActiveReceiptIdentity(e))return null;let s=this.operationReceipts.get(this.operationReceiptKey(e));return s?.fingerprint===this.operationFingerprint(e)?s.result:null}executeWithReceipt(e,s){if(!this.isActiveReceiptIdentity(e))return s();let n=this.operationReceiptKey(e),o=this.operationFingerprint(e),i=this.operationReceipts.get(n);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:s(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??Qt)(fs({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let o=n.readDocumentVersion?await n.readDocumentVersion():0,i=this.versionCheckpoints.get(n);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(n,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=P(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(n,e)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e,s){let n=s?P(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,e));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??e:e,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Ve;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let s=e.some(Ze)?this.scheduleSnapshotIdentityAdvance():!1,n=e.filter(o=>!Es(o));if(!(n.length===0&&!s)&&this.refreshCompositions(!1))for(let o of n)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(s=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${s instanceof Error?s.message:String(s)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=K.readFileSync(k.join(this.options.projectRoot,he),"utf8"),s=JSON.parse(e),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||le(n)!==n?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):n}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let s=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let o=await this.bindHistorySession(e);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=s,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${s}: ${o instanceof Error?o.message:String(o)}`);return}let n=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:e,previousSnapshotId:s,at:n};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,s)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(e=!1){try{let s=hs(this.options.projectRoot),n=Zt(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(d=>({...d})),i=Yt({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[P(d.context),d])),u=new Map(i.map(d=>[P(d.context),d]));if(this.runtime){for(let[d,h]of a){let l=u.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(E(h.context))}for(let[d,h]of u){let l=a.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=s,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(s){let n=s instanceof Error?s:new Error(String(s));if(this.compositionResolutionError=n,e)throw n;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let s=Gt(e.routeId,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let n=this.routes.find(r=>r.routeId===s);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let o=Xt({selector:{routeId:s,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=P(o.context);if(!this.compositions.some(r=>P(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let s=this.runtimeVersionFloors.get(P(e.context));return s===void 0?[]:[{composition:e.context,version:s}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function fn(t){let e=new F(Y(t),We.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function mn(t){return Y(t)}function Y(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:k.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??rs,port:t.port??as,path:t.path??cs,sessionKey:t.sessionKey??ws(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function ps(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function hs(t){let e=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!K.existsSync(i))return;let r;try{r=K.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(k.join(i,a.name));continue}if(!a.isFile())continue;let u=k.join(i,a.name),d="";try{d=K.readFileSync(u,"utf8")}catch{}e.push({path:k.relative(t,u).replaceAll(k.sep,"/"),content:d})}};for(let i of s)o(k.join(t,i));return e.sort((i,r)=>i.path.localeCompare(r.path))}function ls(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function E(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function fs(t){return k.join(k.resolve(t.root),le(t.siteId),le(t.snapshotId),ge("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function le(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:ge("sha256").update(t).digest("hex").slice(0,32)}function Qe(){let t=globalThis;return t[ze]??=new Map,t[ze]}function Xe(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function Ue(t,e,s){let n=s??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!n)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:n,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:n,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function ms(t){let e=new jt({maxPayload:Je,noServer:!0}),s=new WeakSet,n=i=>{new U({socket:new fe(i),engine:t.engine,validateOperationRequest:r=>ts.safeParse(r).success})},o=(i,r,a)=>{if(!gs(i,t))return;let u=ys(i,t);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
|
-
`),r.destroy();return}
|
|
5
|
+
`),r.destroy();return}u.authenticatedByHeader&&s.add(i),e.handleUpgrade(i,r,a,d=>{e.emit("connection",d,i)})};return t.server.on("upgrade",o),e.on("connection",(i,r)=>{if(s.has(r)){n(i);return}_s(i,t.sessionKey,()=>{n(i)})}),e.stop=()=>{t.server.off("upgrade",o);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var fe=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",s=>{this.onmessage?.({data:s.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===qe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>ds){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,s){this.socket.close(e,s)}};function gs(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function ys(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=pe(t.headers["x-vcp-site-edit-key"]),o=Ye(n,e.sessionKey),i=pe(t.headers.host),r=pe(t.headers.origin);return i&&!bs(i,e.host,r)?null:r?Is(r,i,e.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function _s(t,e,s){let n=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},us),o,i=()=>{clearTimeout(n),t.off("message",o),t.off("close",i)},r=()=>{i(),t.close(1008,"bridge authentication failed")};o=a=>{try{let u=x.parseMessage(a.toString());if(u.type!=="auth"||!Ye(u.payload.key,e)){r();return}i(),t.readyState===qe.OPEN&&t.send(x.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),s()}catch{r()}},t.on("message",o),t.on("close",i)}function Ye(t,e){if(!t)return!1;let s=Buffer.from(t),n=Buffer.from(e);return s.length===n.length&&$t(s,n)}function bs(t,e,s){let n=je(t),o=je(e);return n===o||$e(o)&&$e(n)&&(!s||me(s,t))||Ss(o)&&(!s||me(s,t))}function Ss(t){return t==="0.0.0.0"||t==="::"}function $e(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Is(t,e,s){return s.includes(t)||(e?me(t,e):!1)}function me(t,e){try{return new URL(t).host===Ge(e)}catch{return!1}}function je(t){let e=Ge(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function Ge(t){return t.trim().toLowerCase()}function pe(t){return Array.isArray(t)?t[0]:t}function ws(){return Ut(32).toString("base64url")}function Ze(t){let e=t.replaceAll("\\","/");return e===he||e.endsWith(`/${he}`)}function Es(t){let e=t.replaceAll("\\","/");return Ze(t)||e===".vcp/workspace-state.json"||e===".vcp/portable-snapshot-proof.json"||e.startsWith(".vcp/snapshot-store/")}export{ds as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,Je as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,F as SiteEditBridgeServer,ln as attachSiteEditBridgeServer,ms as attachSiteEditWebSocketServer,fn as createSiteEditBridgeEngineHost,hn as ensureSiteEditBridgeServerStarted,mn as normalizeSiteEditBridgeServerOptions};
|
package/dist/window-message.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditObjectEditContext, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, PortableFrameThumbnail, SiteEditPageBlockPosition, SiteEditPageBlockTarget, SiteEditRenderDocument, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
1
|
+
import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditObjectEditContext, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, PortableFrameThumbnail, PortableThumbnailAssets, SiteEditPageBlockPosition, SiteEditPageBlockTarget, SiteEditRenderDocument, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
2
2
|
import type { SiteEditOperationSelectionRef } from "@vcp-dev/contracts";
|
|
3
3
|
import type { SiteEditHistoryStatus } from "./protocol.js";
|
|
4
4
|
import type { CmsPreviewIdentityCandidate } from "./cms-preview-identity-registry.js";
|
|
@@ -202,6 +202,7 @@ export type SiteEditFrameRuntimeRequestBody = {
|
|
|
202
202
|
payload: {
|
|
203
203
|
composition: SiteEditCompositionSelector;
|
|
204
204
|
request: SiteEditPortableExportRequest;
|
|
205
|
+
source_assets?: PortableThumbnailAssets;
|
|
205
206
|
};
|
|
206
207
|
} | {
|
|
207
208
|
type: "request";
|