@vcp-dev/site-edit-bridge 0.11.19 → 0.11.21
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.d.ts +1 -1
- package/dist/auto-bootstrap.js +4 -4
- package/dist/client.d.ts +191 -1
- package/dist/client.js +1 -1
- package/dist/engine-worker-messages.js +2 -0
- package/dist/engine-worker.js +2 -2
- package/dist/index.js +10 -10
- package/dist/next-dev-server.d.ts +1 -0
- package/dist/next-dev-server.js +4 -4
- package/dist/portable-snapshot-proof.js +203 -0
- package/dist/portable-snapshot-workspace.js +97 -0
- package/dist/protocol.d.ts +12 -2
- package/dist/protocol.js +132 -0
- package/dist/server.d.ts +17 -1
- package/dist/server.js +2 -2
- package/dist/window-message.d.ts +18 -2
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants, promises as fs } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
// Same top-level runtime artifacts ignored by sandbox Snapshot reconciliation.
|
|
5
|
+
// They cannot be used as evidence for selected site source.
|
|
6
|
+
const RUNTIME_DIRECTORIES = new Set([
|
|
7
|
+
".vcp",
|
|
8
|
+
".git",
|
|
9
|
+
".next",
|
|
10
|
+
".open-next",
|
|
11
|
+
".turbo",
|
|
12
|
+
".wrangler",
|
|
13
|
+
"node_modules",
|
|
14
|
+
"dist",
|
|
15
|
+
"coverage",
|
|
16
|
+
]);
|
|
17
|
+
const MAX_DIRECTORY_DEPTH = 64;
|
|
18
|
+
/**
|
|
19
|
+
* Fail closed unless the live tree agrees with the independently trusted
|
|
20
|
+
* Snapshot. In particular, an extra module can change import resolution even
|
|
21
|
+
* when every file in the manifest is unchanged. This is not an authority for
|
|
22
|
+
* the Snapshot: the file map must come from a separately authenticated source.
|
|
23
|
+
*/
|
|
24
|
+
export async function workspaceMatchesPortableSnapshot(root, files) {
|
|
25
|
+
try {
|
|
26
|
+
if (!files.size)
|
|
27
|
+
return false;
|
|
28
|
+
for (const [relative, content] of files) {
|
|
29
|
+
if (!relative ||
|
|
30
|
+
relative.startsWith("/") ||
|
|
31
|
+
relative.includes("\\") ||
|
|
32
|
+
relative.includes("\0") ||
|
|
33
|
+
relative
|
|
34
|
+
.split("/")
|
|
35
|
+
.some((part) => !part || part === "." || part === "..") ||
|
|
36
|
+
RUNTIME_DIRECTORIES.has(relative.split("/")[0]) ||
|
|
37
|
+
(typeof content !== "string" && !(content instanceof Uint8Array)))
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
let directories = 0;
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
const walk = async (relativeDirectory, depth) => {
|
|
43
|
+
if (depth > MAX_DIRECTORY_DEPTH ||
|
|
44
|
+
++directories > files.size * MAX_DIRECTORY_DEPTH + 1)
|
|
45
|
+
return false;
|
|
46
|
+
const entries = await fs.readdir(path.join(root, relativeDirectory), {
|
|
47
|
+
withFileTypes: true,
|
|
48
|
+
});
|
|
49
|
+
for (const entry of entries) {
|
|
50
|
+
const relative = relativeDirectory
|
|
51
|
+
? `${relativeDirectory}/${entry.name}`
|
|
52
|
+
: entry.name;
|
|
53
|
+
if (!relativeDirectory && RUNTIME_DIRECTORIES.has(entry.name))
|
|
54
|
+
continue;
|
|
55
|
+
if (entry.isDirectory()) {
|
|
56
|
+
if (!(await walk(relative, depth + 1)))
|
|
57
|
+
return false;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
// Symlinks and special files are never opened or followed.
|
|
61
|
+
if (!entry.isFile())
|
|
62
|
+
return false;
|
|
63
|
+
const expected = files.get(relative);
|
|
64
|
+
if (expected === undefined || seen.has(relative))
|
|
65
|
+
return false;
|
|
66
|
+
seen.add(relative);
|
|
67
|
+
const fullPath = path.join(root, relative);
|
|
68
|
+
const stat = await fs.lstat(fullPath);
|
|
69
|
+
const size = typeof expected === "string"
|
|
70
|
+
? Buffer.byteLength(expected, "utf8")
|
|
71
|
+
: expected.byteLength;
|
|
72
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== size)
|
|
73
|
+
return false;
|
|
74
|
+
const expectedHash = createHash("sha256")
|
|
75
|
+
.update(expected)
|
|
76
|
+
.digest("hex");
|
|
77
|
+
const actualHash = createHash("sha256");
|
|
78
|
+
const handle = await fs.open(fullPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
79
|
+
try {
|
|
80
|
+
const stream = handle.createReadStream({ autoClose: false });
|
|
81
|
+
for await (const chunk of stream)
|
|
82
|
+
actualHash.update(chunk);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
await handle.close();
|
|
86
|
+
}
|
|
87
|
+
if (actualHash.digest("hex") !== expectedHash)
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
};
|
|
92
|
+
return (await walk("", 0)) && seen.size === files.size;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SiteEditClassNameSourceStyleContext, SiteEditCommandSuccess, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditMutationContext, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
1
|
+
import type { SiteEditClassNameSourceStyleContext, SiteEditCommandSuccess, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditMutationContext, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
2
2
|
type Awaitable<T> = T | Promise<T>;
|
|
3
3
|
/** The Bridge keeps this old shape at its boundary for compatibility with the
|
|
4
4
|
* durable history adapter. The selected composition is carried beside it. */
|
|
@@ -21,7 +21,7 @@ export type SiteEditBridgeSessionState = {
|
|
|
21
21
|
export declare const SITE_EDIT_COMPOSITION_SESSION_MISMATCH = "SITE_EDIT_COMPOSITION_SESSION_MISMATCH";
|
|
22
22
|
export declare const SITE_EDIT_COMPOSITION_SESSION_REQUIRED = "SITE_EDIT_COMPOSITION_SESSION_REQUIRED";
|
|
23
23
|
export declare const SITE_EDIT_COMPOSITION_REINITIALIZE_REQUIRED = "SITE_EDIT_COMPOSITION_REINITIALIZE_REQUIRED";
|
|
24
|
-
export type SiteEditBridgeRequestKind = "initialize-session" | "get-document" | "get-history-status" | "get-style-context" | "get-object-edit-context" | "get-class-name-source" | "get-source-tree" | "get-source-file" | "resolve-source-location" | "execute" | "get-operation-result" | "get-history-operation-result" | "undo" | "redo";
|
|
24
|
+
export type SiteEditBridgeRequestKind = "initialize-session" | "get-document" | "get-history-status" | "get-style-context" | "get-object-edit-context" | "get-class-name-source" | "get-source-tree" | "get-source-file" | "export-portable-block" | "export-portable-block-asset" | "resolve-source-location" | "execute" | "get-operation-result" | "get-history-operation-result" | "undo" | "redo";
|
|
25
25
|
type CompositionRequestFields = {
|
|
26
26
|
/** Current protocol selector; required for every composition-sensitive wire request. */
|
|
27
27
|
composition: SiteEditCompositionSelector;
|
|
@@ -57,6 +57,14 @@ export type SiteEditBridgeRequest = {
|
|
|
57
57
|
id: string;
|
|
58
58
|
kind: "get-source-file";
|
|
59
59
|
path: string;
|
|
60
|
+
} & CompositionRequestFields) | ({
|
|
61
|
+
id: string;
|
|
62
|
+
kind: "export-portable-block";
|
|
63
|
+
request: SiteEditPortableExportRequest;
|
|
64
|
+
} & CompositionRequestFields) | ({
|
|
65
|
+
id: string;
|
|
66
|
+
kind: "export-portable-block-asset";
|
|
67
|
+
request: SiteEditPortableAssetRequest;
|
|
60
68
|
} & CompositionRequestFields) | ({
|
|
61
69
|
id: string;
|
|
62
70
|
kind: "execute" | "get-operation-result";
|
|
@@ -145,6 +153,8 @@ export type SiteEditBridgeEngine = {
|
|
|
145
153
|
path: string;
|
|
146
154
|
composition: SiteEditCompositionContext;
|
|
147
155
|
}): Awaitable<SiteEditCommandSuccess<SiteEditSourceFileResponse>>;
|
|
156
|
+
exportPortableBlock?(request: SiteEditPortableExportRequest, composition: SiteEditCompositionContext): Awaitable<SiteEditPortableExportResult>;
|
|
157
|
+
exportPortableBlockAsset?(request: SiteEditPortableAssetRequest, composition: SiteEditCompositionContext): Awaitable<SiteEditPortableAssetResult>;
|
|
148
158
|
resolveSourceLocation(input: SiteEditResolveSourceLocationInput | {
|
|
149
159
|
key: string;
|
|
150
160
|
composition: SiteEditCompositionContext;
|
package/dist/protocol.js
CHANGED
|
@@ -33,6 +33,8 @@ export class SiteEditBridgeTransport {
|
|
|
33
33
|
value === "get-class-name-source" ||
|
|
34
34
|
value === "get-source-tree" ||
|
|
35
35
|
value === "get-source-file" ||
|
|
36
|
+
value === "export-portable-block" ||
|
|
37
|
+
value === "export-portable-block-asset" ||
|
|
36
38
|
value === "resolve-source-location" ||
|
|
37
39
|
value === "execute" ||
|
|
38
40
|
value === "get-operation-result" ||
|
|
@@ -177,6 +179,56 @@ export class SiteEditBridgeSocketServer {
|
|
|
177
179
|
}), context));
|
|
178
180
|
return;
|
|
179
181
|
}
|
|
182
|
+
case "export-portable-block": {
|
|
183
|
+
// handleMessage is public and can be called without parseMessage, so
|
|
184
|
+
// enforce the same narrow wire shape before reaching the engine.
|
|
185
|
+
if (!isPortableExportPayload(payload)) {
|
|
186
|
+
throw new BridgeProtocolError("PORTABLE_EXPORT_REQUEST_INVALID", "The portable export request is invalid.");
|
|
187
|
+
}
|
|
188
|
+
const context = await this.resolveWireContext(payload);
|
|
189
|
+
const targetContext = await this.resolveAndAssert(payload.request.target.composition);
|
|
190
|
+
if (computeSiteEditCompositionKey(context) !==
|
|
191
|
+
computeSiteEditCompositionKey(targetContext)) {
|
|
192
|
+
throw new BridgeProtocolError(SITE_EDIT_COMPOSITION_SESSION_MISMATCH, "The portable export target does not match the active composition.");
|
|
193
|
+
}
|
|
194
|
+
const result = this.options.engine.exportPortableBlock
|
|
195
|
+
? await this.options.engine.exportPortableBlock(payload.request, context)
|
|
196
|
+
: {
|
|
197
|
+
complete: false,
|
|
198
|
+
unresolved: [
|
|
199
|
+
{
|
|
200
|
+
code: "PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",
|
|
201
|
+
path: "<snapshot>",
|
|
202
|
+
message: "No trusted Snapshot proof is available.",
|
|
203
|
+
},
|
|
204
|
+
],
|
|
205
|
+
};
|
|
206
|
+
this.sendResult(id, payload.kind, result);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
case "export-portable-block-asset": {
|
|
210
|
+
if (!isPortableAssetPayload(payload))
|
|
211
|
+
throw new BridgeProtocolError("PORTABLE_LOCAL_ASSET_REQUEST_INVALID", "The portable local image request is invalid.");
|
|
212
|
+
const context = await this.resolveWireContext(payload);
|
|
213
|
+
const targetContext = await this.resolveAndAssert(payload.request.request.target.composition);
|
|
214
|
+
if (computeSiteEditCompositionKey(context) !==
|
|
215
|
+
computeSiteEditCompositionKey(targetContext))
|
|
216
|
+
throw new BridgeProtocolError(SITE_EDIT_COMPOSITION_SESSION_MISMATCH, "The portable asset target does not match the active composition.");
|
|
217
|
+
const result = this.options.engine.exportPortableBlockAsset
|
|
218
|
+
? await this.options.engine.exportPortableBlockAsset(payload.request, context)
|
|
219
|
+
: {
|
|
220
|
+
complete: false,
|
|
221
|
+
unresolved: [
|
|
222
|
+
{
|
|
223
|
+
code: "PORTABLE_LOCAL_ASSET_UNAVAILABLE",
|
|
224
|
+
path: "<asset>",
|
|
225
|
+
message: "The selected local image is unavailable.",
|
|
226
|
+
},
|
|
227
|
+
],
|
|
228
|
+
};
|
|
229
|
+
this.sendResult(id, payload.kind, result);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
180
232
|
case "resolve-source-location": {
|
|
181
233
|
const context = await this.resolveWireContext(payload);
|
|
182
234
|
const result = addComposition(await this.options.engine.resolveSourceLocation({
|
|
@@ -450,6 +502,10 @@ function isRequestPayload(payload, options) {
|
|
|
450
502
|
return compositionOk;
|
|
451
503
|
case "get-source-file":
|
|
452
504
|
return typeof payload.path === "string" && compositionOk;
|
|
505
|
+
case "export-portable-block":
|
|
506
|
+
return isPortableExportPayload(payload);
|
|
507
|
+
case "export-portable-block-asset":
|
|
508
|
+
return isPortableAssetPayload(payload);
|
|
453
509
|
case "execute":
|
|
454
510
|
case "get-operation-result":
|
|
455
511
|
return (compositionOk &&
|
|
@@ -469,6 +525,82 @@ function isRequestPayload(payload, options) {
|
|
|
469
525
|
isMutationContextLike(payload.mutationContext)));
|
|
470
526
|
}
|
|
471
527
|
}
|
|
528
|
+
// protocol.ts is also served directly as a browser module without package
|
|
529
|
+
// imports. The Node runtime additionally parses the shared Zod contract.
|
|
530
|
+
function isPortableExportPayload(payload) {
|
|
531
|
+
if (!isCompositionSelector(payload.composition) ||
|
|
532
|
+
!Object.keys(payload).every((key) => ["id", "kind", "composition", "request"].includes(key)) ||
|
|
533
|
+
!isRecord(payload.request))
|
|
534
|
+
return false;
|
|
535
|
+
const request = payload.request;
|
|
536
|
+
if (!Object.keys(request).every((key) => [
|
|
537
|
+
"site_id",
|
|
538
|
+
"base_snapshot_id",
|
|
539
|
+
"document_version",
|
|
540
|
+
"target",
|
|
541
|
+
"selection_ref",
|
|
542
|
+
].includes(key)) ||
|
|
543
|
+
typeof request.site_id !== "string" ||
|
|
544
|
+
typeof request.base_snapshot_id !== "string" ||
|
|
545
|
+
!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(request.site_id) ||
|
|
546
|
+
!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(request.base_snapshot_id) ||
|
|
547
|
+
typeof request.document_version !== "number" ||
|
|
548
|
+
!Number.isSafeInteger(request.document_version) ||
|
|
549
|
+
request.document_version < 0 ||
|
|
550
|
+
!isRecord(request.target) ||
|
|
551
|
+
request.target.kind !== "page-block" ||
|
|
552
|
+
typeof request.target.blockKey !== "string" ||
|
|
553
|
+
!request.target.blockKey.length ||
|
|
554
|
+
request.target.blockKey.length > 256 ||
|
|
555
|
+
!Object.keys(request.target).every((key) => ["kind", "composition", "blockKey"].includes(key)) ||
|
|
556
|
+
!isCompositionSelector(request.target.composition) ||
|
|
557
|
+
request.target.composition.routeId !== payload.composition.routeId ||
|
|
558
|
+
request.target.composition.templateId !== payload.composition.templateId ||
|
|
559
|
+
request.selection_ref === undefined ||
|
|
560
|
+
!isSelectionRefLike(request.selection_ref))
|
|
561
|
+
return false;
|
|
562
|
+
return true;
|
|
563
|
+
}
|
|
564
|
+
function isPortableAssetPayload(payload) {
|
|
565
|
+
if (!Object.keys(payload).every((key) => ["id", "kind", "composition", "request"].includes(key)) ||
|
|
566
|
+
!isRecord(payload.request))
|
|
567
|
+
return false;
|
|
568
|
+
const asset = payload.request;
|
|
569
|
+
if (!Object.keys(asset).every((key) => [
|
|
570
|
+
"request",
|
|
571
|
+
"snapshot_digest",
|
|
572
|
+
"file_path",
|
|
573
|
+
"occurrence",
|
|
574
|
+
"offset",
|
|
575
|
+
].includes(key)) ||
|
|
576
|
+
!isPortableExportPayload({
|
|
577
|
+
id: payload.id,
|
|
578
|
+
kind: "export-portable-block",
|
|
579
|
+
composition: payload.composition,
|
|
580
|
+
request: asset.request,
|
|
581
|
+
}) ||
|
|
582
|
+
typeof asset.snapshot_digest !== "string" ||
|
|
583
|
+
!/^sha256:[a-f0-9]{64}$/u.test(asset.snapshot_digest) ||
|
|
584
|
+
typeof asset.file_path !== "string" ||
|
|
585
|
+
!asset.file_path.length ||
|
|
586
|
+
asset.file_path.length > 1024 ||
|
|
587
|
+
asset.file_path.startsWith("/") ||
|
|
588
|
+
/[\\\0%]/u.test(asset.file_path) ||
|
|
589
|
+
asset.file_path
|
|
590
|
+
.split("/")
|
|
591
|
+
.some((part) => !part || part.startsWith(".") || part === "node_modules") ||
|
|
592
|
+
typeof asset.occurrence !== "number" ||
|
|
593
|
+
!Number.isSafeInteger(asset.occurrence) ||
|
|
594
|
+
asset.occurrence < 0 ||
|
|
595
|
+
asset.occurrence > 4095 ||
|
|
596
|
+
typeof asset.offset !== "number" ||
|
|
597
|
+
!Number.isSafeInteger(asset.offset) ||
|
|
598
|
+
asset.offset < 0 ||
|
|
599
|
+
asset.offset > 50 * 1024 * 1024 ||
|
|
600
|
+
asset.offset % (1024 * 1024) !== 0)
|
|
601
|
+
return false;
|
|
602
|
+
return true;
|
|
603
|
+
}
|
|
472
604
|
function isHistoryRequestLike(value) {
|
|
473
605
|
return (isRecord(value) &&
|
|
474
606
|
typeof value.request_id === "string" &&
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Server as HttpServer } from "node:http";
|
|
2
2
|
import { WebSocketServer } from "ws";
|
|
3
|
-
import { type PreviewSiteEditEngineRuntime, type PreviewSiteEditEngineRuntimeOptions } from "@vcp-dev/site-edit-engine";
|
|
3
|
+
import { type PreviewSiteEditEngineRuntime, type PortableBlockExportInput, type PreviewSiteEditEngineRuntimeOptions } from "@vcp-dev/site-edit-engine";
|
|
4
4
|
import type { FileHistoryStore } from "@vcp-dev/site-edit-engine";
|
|
5
5
|
import { type SiteEditNextRouteConfig } from "@vcp-dev/site-edit-engine/next-app-router";
|
|
6
6
|
import { type SiteEditBridgeEngine } from "./protocol.js";
|
|
@@ -24,6 +24,8 @@ export type SiteEditBridgeServerOptions = {
|
|
|
24
24
|
port?: number;
|
|
25
25
|
path?: string;
|
|
26
26
|
sessionKey?: string;
|
|
27
|
+
/** Public verifier supplied by the trusted preview launcher, never the browser. */
|
|
28
|
+
portableSnapshotPublicKey?: string;
|
|
27
29
|
/** Private runtime directory for the durable, server-side undo/redo store. */
|
|
28
30
|
historyRoot?: string;
|
|
29
31
|
allowedOrigins?: string[];
|
|
@@ -43,6 +45,16 @@ export type SiteEditBridgeServerOptions = {
|
|
|
43
45
|
export type SiteEditBridgeServerDependencies = {
|
|
44
46
|
createRuntime?: (options: PreviewSiteEditEngineRuntimeOptions) => PreviewSiteEditEngineRuntime;
|
|
45
47
|
openHistoryStore?: (root: string) => Promise<FileHistoryStore>;
|
|
48
|
+
/** Only a trusted server-side authority may provide this proof. Never fill
|
|
49
|
+
* it from a browser request or the mutable sandbox snapshot marker. */
|
|
50
|
+
loadTrustedPortableSnapshot?: (input: {
|
|
51
|
+
site_id: string;
|
|
52
|
+
base_snapshot_id: string;
|
|
53
|
+
}) => Promise<{
|
|
54
|
+
snapshot: PortableBlockExportInput["snapshot"];
|
|
55
|
+
host_capabilities: PortableBlockExportInput["host_capabilities"];
|
|
56
|
+
trusted_host_file_hashes?: PortableBlockExportInput["trusted_host_file_hashes"];
|
|
57
|
+
} | null>;
|
|
46
58
|
};
|
|
47
59
|
export type SiteEditBridgeHealth = {
|
|
48
60
|
ok: boolean;
|
|
@@ -98,6 +110,8 @@ export declare class SiteEditBridgeServer {
|
|
|
98
110
|
private notifyHealthChanged;
|
|
99
111
|
private createRuntime;
|
|
100
112
|
private createBridgeEngine;
|
|
113
|
+
private exportPortableBlock;
|
|
114
|
+
private exportPortableBlockAsset;
|
|
101
115
|
private runHistoryWithReceipt;
|
|
102
116
|
private isActiveReceiptIdentity;
|
|
103
117
|
private operationReceiptKey;
|
|
@@ -138,6 +152,7 @@ export declare function normalizeSiteEditBridgeServerOptions(options: SiteEditBr
|
|
|
138
152
|
port: number;
|
|
139
153
|
path: string;
|
|
140
154
|
sessionKey: string;
|
|
155
|
+
portableSnapshotPublicKey: string | undefined;
|
|
141
156
|
historyRoot: string | undefined;
|
|
142
157
|
allowedOrigins: string[];
|
|
143
158
|
runtime: SiteEditBridgeRuntimeOptions;
|
|
@@ -154,6 +169,7 @@ declare function normalizeOptions(options: SiteEditBridgeServerOptions): {
|
|
|
154
169
|
port: number;
|
|
155
170
|
path: string;
|
|
156
171
|
sessionKey: string;
|
|
172
|
+
portableSnapshotPublicKey: string | undefined;
|
|
157
173
|
historyRoot: string | undefined;
|
|
158
174
|
allowedOrigins: string[];
|
|
159
175
|
runtime: SiteEditBridgeRuntimeOptions;
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import de from"node:http";import T from"node:fs";import{createHash as G,randomBytes as Fe,timingSafeEqual as Ne}from"node:crypto";import y from"node:path";import{WebSocket as ue,WebSocketServer as Ve}from"ws";import{createPreviewSiteEditEngineRuntime as We,openFileHistoryStore as qe,resolveManagedPageTemplateComposition as $e,scanSiteEditCompositionsFromFiles as Ue}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as je,scanNextAppRouterRoutesFromFiles as ze}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Le}from"@vcp-dev/site-edit-engine/source-watcher";function te(e){if(e.pageBlocks!==void 0&&!Ie(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],i=new Map,o=[],s=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(s.map((d,h)=>[d,h])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),c=new Map(e.entries.map((d,h)=>[d.key,h])),l=[];for(let[d,h]of e.entries.entries()){let g=h.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([d,{kind:g.kind}]);continue}let A=g.siblingKeys.map(_=>{let v=c.get(_);if(v===void 0)throw new Error("Render entry "+h.key+" references missing source sibling "+_);return v});l.push([d,{kind:"source-siblings",siblingEntryIndexes:A}])}let b=d=>{let h=t.get(d);if(typeof h=="number")return h;let g=n.length;return n.push(d),t.set(d,g),g},Y=d=>{let h=null;for(let g of _e(d)){let A=`${h??"root"}\0${g}`,_=i.get(A);if(typeof _=="number"){h=_;continue}let v=o.length;o.push([h,b(g)]),i.set(A,v),h=v}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?r.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[Y(d.key),ye(d.operationSummary),...h>=0?[h]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(d=>d.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(d=>d.parentKey===null?null:Y(d.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function ye(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ie(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!C(n)||!x(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!K(n.blockKey,256)||!K(n.definitionKey,512)||!Se(n.rootRef)||!we(n.source)||!be(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>K(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!R(n.placementUnitKey)||!Ce(n.capabilities)||n.unavailableReasons!==void 0&&!ke(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let i=n.owner;for(let o of n.siblingBlockKeys){let s=t.get(o);if(!s)return!1;let r=s.owner;if(i.kind!==r.kind||i.key!==r.key)return!1}}return!0}function Se(e){return!C(e)||!x(e,["key","instanceIndex","instanceCount"])||!R(e.key)||e.instanceIndex!==void 0&&!Z(e.instanceIndex)||e.instanceCount!==void 0&&(!Z(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function we(e){return C(e)&&x(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Re(e.file)&&R(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function be(e){return C(e)&&x(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&K(e.key,512)}function Ce(e){return C(e)&&x(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 ke(e){return C(e)&&Object.entries(e).every(([t,n])=>R(t)&&C(n)&&x(n,["code","reason"])&&R(n.code)&&R(n.reason))}function Re(e){let t=xe(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(s=>!s||s==="."||s===".."||s.startsWith(".")||s==="node_modules"||s.toLowerCase()==="package.json"||s==="recipes"||s.startsWith(".env")))return!1;let i=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(s=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(s.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(s=>e===s||e.startsWith(`${s}/`))||t}function xe(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),i=n.some(r=>X(r)),o=i?n[0]:n.pop(),s=i?n.slice(1):n;if(i&&s.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!Ee(`/${s.join("/")}`)||s.some(r=>r.includes("[")||r.includes("]")?!X(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,l=>l.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function X(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Ee(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function K(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function R(e){return typeof e=="string"&&e.length>0}function x(e,t){let n=new Set(t);return Object.keys(e).every(i=>n.has(i))}function _e(e){if(!e)return[];let t=[],n=0,i=ee(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=ee(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function ee(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}var B="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",U="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var m=class e{constructor(){}static parseMessage(t,n={}){let i=JSON.parse(t);if(!e.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(p(t)&&p(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",i=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:i}}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==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!p(t)||typeof t.type!="string"?!1:t.type==="request"?Oe(t.payload,n):t.type==="response"||t.type==="error"?p(t.payload)&&typeof t.payload.id=="string":t.type==="event"?p(t.payload)&&p(t.payload.event):t.type==="auth"?p(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?p(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&p(t.payload)&&t.payload.ok===!0}},M=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new $,this.eventDispatcher=new q(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let i=Te(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let i=n.payload,{id:o}=i;switch(i.kind){case"initialize-session":{let s=F(i),r=await this.resolve(s),a=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:i.kind,result:w({...a,data:{...a.data,document:ie(a.data.document)}},r.context)}});return}case"get-document":{let s=await this.resolveWireContext(i),r=await this.options.engine.getDocument(s);this.sendResult(o,i.kind,De(r,s));return}case"get-history-status":{let s=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(s);this.sendResult(o,i.kind,w(r,s));return}case"get-style-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getStyleContext(s),s));return}case"get-object-edit-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getObjectEditContext(i.key,s,i.selectionRef),s));return}case"get-class-name-source":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getClassNameSource(i.key,s),s));return}case"get-source-tree":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceTree(s),s));return}case"get-source-file":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceFile({path:i.path,composition:s}),s));return}case"resolve-source-location":{let s=await this.resolveWireContext(i),r=w(await this.options.engine.resolveSourceLocation({key:i.key,composition:s}),s);this.sendResult(o,i.kind,r);return}case"execute":case"get-operation-result":{let s=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(f(s)!==f(r))throw new I(B,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(i.request,s);if(i.kind==="get-operation-result"){this.sendResult(o,i.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,i.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let s=await this.resolveWireContext(i),r=await this.resolveAndAssert(i.request.composition);if(f(s)!==f(r))throw new I(B,"History receipt composition does not match the active session.");this.sendResult(o,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:H(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(i),r=i.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||f(s)!==f(u))throw new I(B,"History request does not match its cursor operation.")}let a=r?{...r,composition:H(s)}:void 0;await this.handleBufferedOperation(o,i.kind,()=>i.kind==="undo"?this.options.engine.undo(s,a):this.options.engine.redo(s,a));return}}}catch(n){let i=m.extractRequestInfo(t);this.sendJson({type:"error",payload:{...i,message:W(n),code:V(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),i=this.session.activeComposition;if(!i)throw new I(U,"Initialize a composition session before issuing this request.");if(f(i)!==f(n.context))throw new I(B,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=F(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=He(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(f(t))}async normalizeOperationRequest(t,n){let i={...t,composition:H(n)};if(i.target.kind==="route"){let o=i.target,s=F(o),r=await this.resolveAndAssert(s);i.target={...o,composition:H(r)}}return i}handleEngineEvent(t){let n=t?.composition;if(!Be(n))return;let i=f(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&i===Me(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(t,n,i){this.sendJson({type:"response",payload:{id:t,kind:n,result:i}})}async handleRawMessage(t){try{await this.handleMessage(m.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=Pe(t);this.sendJson({type:"error",payload:{...i,message:W(n),code:V(n)}})}}sendJson(t){this.options.socket.send(m.stringifyMessage(t))}async handleBufferedOperation(t,n,i){this.eventDispatcher.beginBuffering();try{let o=await i();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:W(o),code:V(o)}})}finally{this.eventDispatcher.flush()}}},ve=256;function Te(e){if(e.length>ve||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return p(t)&&t.type==="ping"&&p(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var I=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},q=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},$=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function Oe(e,t){if(!p(e)||typeof e.id!="string"||!m.isRequestKind(e.kind))return!1;let n=E(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||N(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ae(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"execute":case"get-operation-result":return n&&Ke(e.request)&&(e.request.mutationContext===void 0||N(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&ne(e.request);case"undo":case"redo":return n&&(e.request===void 0||ne(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||N(e.mutationContext))}}function ne(e){return p(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")&&E(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ae(e){if(e===void 0)return!0;if(!p(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function Ke(e){return p(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&E(e.composition)&&typeof e.kind=="string"&&p(e.target)&&(e.target.kind!=="route"||E(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&p(e.params)}function E(e){return p(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 Be(e){return p(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function F(e){if(E(e.composition))return e.composition;throw new I(U,"A composition selector is required for this request.")}function He(e){if(p(e)&&E(e.composition))return e.composition;throw new I(U,"A composition selector is required for execute.")}function H(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Me(e){return e.activeComposition?f(e.activeComposition):null}function f(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function w(e,t){return p(e)&&e.ok===!0?{...e,composition:t}:e}function De(e,t){return!p(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:ie(e.data)}}function ie(e){let t=e;return te(t.routeId?t:{...t,routeId:t.composition.routeId})}function p(e){return typeof e=="object"&&e!==null}function N(e){return p(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 V(e){if(!(!p(e)||typeof e.code!="string"||e.code.length===0))return e.code}function W(e){return e instanceof Error||p(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function Pe(e){try{return m.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var D=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Je,computeSiteEditCompositionKey as k}from"@vcp-dev/contracts";var Qe="127.0.0.1",Ge=30218,Ye="/__vcp/site-edit/bridge",pe=6*1024*1024,Ze=pe*2,Xe=3e3,se=50,z=".vcp/current-snapshot.json",oe="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function vt(e){let t=P(e),n=le(t),i=he(),o=i.get(n);if(o)return o;let s=new O(t);i.set(n,s);try{s.start()}catch(r){throw i.delete(n),s.stop(),r}return s}function Tt(e,t,n={}){let i=new O(P(t),e,!1,n);return i.start({listen:!1}),i}var O=class{constructor(t,n=de.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new D,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{T.mkdirSync(y.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=st({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new Le({projectRoot:this.options.projectRoot,watch_dirs:et(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??se,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=he(),n=le(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let i=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??We)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:s=>{"version"in s&&typeof s.version=="number"&&this.recordRuntimeVersion(s.version,"composition"in s?s.composition:void 0);for(let r of this.eventListeners)r(s)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=nt(t.composition),o=this.getRuntime(),s=S(i);await o.initializeComposition(s);let a=o.getDocument(s).data;await this.recordRuntimeVersion(a.version,i);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),i=S(t);await n.initializeComposition(i);let o=n.getDocument(i);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(S(t)),getObjectEditContext:async(t,n,i)=>this.getRuntime().getObjectEditContext(t,S(n),i),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,S(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(S(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:S(t.composition)}),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:S(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return re(i,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}runHistoryWithReceipt(t,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==t||i.composition.routeId!==n.routeId||i.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return re(s,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return i?this.executeWithReceipt(i,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 G("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let i=this.operationReceiptKey(t),o=this.operationFingerprint(t),s=this.operationReceipts.get(i);if(s)return s.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):s.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(i,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(i)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let i=await(this.dependencies.openHistoryStore??qe)(it({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=i.readDocumentVersion?await i.readDocumentVersion():0,s=this.versionCheckpoints.get(i);s?s.durableVersion=Math.max(s.durableVersion,o):this.versionCheckpoints.set(i,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=k(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(i,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let i=n?k(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=i?this.runtimeVersionFloors.get(i)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),s<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,s),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let i of t)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??se;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let n=t.some(me)?this.scheduleSnapshotIdentityAdvance():!1,i=t.filter(o=>!ht(o));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let o of i)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=T.readFileSync(y.join(this.options.projectRoot,z),"utf8"),n=JSON.parse(t),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||L(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let i=new Date().toISOString();for(let o of this.compositions){let s={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(s)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=tt(this.options.projectRoot),i=ze(n),o=i.length>0?i:(this.options.runtime.routes??[]).map(c=>({...c})),s=Ue({files:n});if(s.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(s.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[k(c.context),c])),u=new Map(s.map(c=>[k(c.context),c]));if(this.runtime){for(let[c,l]of a){let b=u.get(c);(!b||b.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(S(l.context))}for(let[c,l]of u){let b=a.get(c);(!b||b.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=o,this.compositions=s,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,t)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=je(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=$e({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),s=k(o.context);if(!this.compositions.some(r=>k(r.context)===s))throw new Error(`Composition is not registered by the preview bridge: ${s}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(k(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function Ot(e){let t=new O(P(e),de.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function At(e){return P(e)}function P(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:y.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Qe,port:e.port??Ge,path:e.path??Ye,sessionKey:e.sessionKey??pt(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function et(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 tt(e){let t=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!T.existsSync(s))return;let r;try{r=T.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(i.has(a.name))continue;o(y.join(s,a.name));continue}if(!a.isFile())continue;let u=y.join(s,a.name),c="";try{c=T.readFileSync(u,"utf8")}catch{}t.push({path:y.relative(e,u).replaceAll(y.sep,"/"),content:c})}};for(let s of n)o(y.join(e,s));return t.sort((s,r)=>s.path.localeCompare(r.path))}function nt(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 S(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function it(e){return y.join(y.resolve(e.root),L(e.siteId),L(e.snapshotId),G("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function L(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:G("sha256").update(e).digest("hex").slice(0,32)}function he(){let e=globalThis;return e[oe]??=new Map,e[oe]}function le(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function re(e,t,n){let i=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:i,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function st(e){let t=new Ve({maxPayload:pe,noServer:!0}),n=new WeakSet,i=s=>{new M({socket:new J(s),engine:e.engine,validateOperationRequest:r=>Je.safeParse(r).success})},o=(s,r,a)=>{if(!ot(s,e))return;let u=rt(s,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import Te from"node:http";import B from"node:fs";import{createHash as oe,randomBytes as ht,timingSafeEqual as lt}from"node:crypto";import R from"node:path";import{WebSocket as Ae,WebSocketServer as ft}from"ws";import{createPreviewSiteEditEngineRuntime as gt,exportPortableBlockFromSnapshot as mt,readPortableBlockLocalAssetChunk as yt,openFileHistoryStore as _t,resolveManagedPageTemplateComposition as bt,scanSiteEditCompositionsFromFiles as It}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as St,scanNextAppRouterRoutesFromFiles as wt}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Et}from"@vcp-dev/site-edit-engine/source-watcher";function de(e){if(e.pageBlocks!==void 0&&!Le(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((p,l)=>[p,l])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((p,l)=>p.dynamicDataSummary?[[l,p.dynamicDataSummary]]:[]),c=new Map(e.entries.map((p,l)=>[p.key,l])),h=[];for(let[p,l]of e.entries.entries()){let _=l.pageCompositionActionScope;if(!_)continue;if(_.kind!=="source-siblings"){h.push([p,{kind:_.kind}]);continue}let d=_.siblingKeys.map(g=>{let I=c.get(g);if(I===void 0)throw new Error("Render entry "+l.key+" references missing source sibling "+g);return I});h.push([p,{kind:"source-siblings",siblingEntryIndexes:d}])}let m=p=>{let l=t.get(p);if(typeof l=="number")return l;let _=s.length;return s.push(p),t.set(p,_),_},y=p=>{let l=null;for(let _ of ze(p)){let d=`${l??"root"}\0${_}`,g=n.get(d);if(typeof g=="number"){l=g;continue}let I=o.length;o.push([l,m(_)]),n.set(d,I),l=I}if(l===null)throw new Error("Document key must not be empty");return l};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(p=>{let l=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&l<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[y(p.key),Ke(p.operationSummary),...l>=0?[l]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:y(p.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Ke(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Le(e){if(!Array.isArray(e))return!1;let t=new Map;for(let s of e){if(!x(s)||!O(s,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!H(s.blockKey,256)||!H(s.definitionKey,512)||!De(s.rootRef)||!Fe(s.source)||!qe(s.owner)||!Array.isArray(s.siblingBlockKeys)||!s.siblingBlockKeys.every(n=>H(n,256))||new Set(s.siblingBlockKeys).size!==s.siblingBlockKeys.length||s.siblingBlockKeys.includes(s.blockKey)||s.placementUnitKey!==void 0&&!A(s.placementUnitKey)||!Ve(s.capabilities)||s.unavailableReasons!==void 0&&!Ue(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 De(e){return!x(e)||!O(e,["key","instanceIndex","instanceCount"])||!A(e.key)||e.instanceIndex!==void 0&&!re(e.instanceIndex)||e.instanceCount!==void 0&&(!re(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Fe(e){return x(e)&&O(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&We(e.file)&&A(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function qe(e){return x(e)&&O(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&H(e.key,512)}function Ve(e){return x(e)&&O(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 Ue(e){return x(e)&&Object.entries(e).every(([t,s])=>A(t)&&x(s)&&O(s,["code","reason"])&&A(s.code)&&A(s.reason))}function We(e){let t=je(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 je(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=>ae(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)||!$e(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!ae(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)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function ae(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function $e(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 H(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function A(e){return typeof e=="string"&&e.length>0}function O(e,t){let s=new Set(t);return Object.keys(e).every(n=>s.has(n))}function ze(e){if(!e)return[];let t=[],s=0,n=ce(e,s);if(n<0)return t.push(e),t;for(t.push(e.slice(0,n)),s=n;s<e.length;){if(n=ce(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 ce(e,t){let s=e.indexOf("/",t),n=e.indexOf("::",t);return s<0?n:n<0?s:Math.min(s,n)}var v="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",Q="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var E=class e{constructor(){}static parseMessage(t,s={}){let n=JSON.parse(t);if(!e.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(f(t)&&f(t.payload)){let s=typeof t.payload.id=="string"?t.payload.id:"unknown",n=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:s,kind:n}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,s={}){return!f(t)||typeof t.type!="string"?!1:t.type==="request"?Xe(t.payload,s):t.type==="response"||t.type==="error"?f(t.payload)&&typeof t.payload.id=="string":t.type==="event"?f(t.payload)&&f(t.payload.event):t.type==="auth"?f(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?f(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&f(t.payload)&&t.payload.ok===!0}},K=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new J,this.eventDispatcher=new z(s=>{this.sendJson(s)}),this.unsubscribe=t.engine.subscribe(s=>{this.handleEngineEvent(s)}),t.socket.onmessage=s=>{let n=Qe(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=U(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:k({...a,data:{...a.data,document:le(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,tt(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,k(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,k(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,k(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,k(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,k(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(n);this.sendResult(o,n.kind,k(await this.options.engine.getSourceFile({path:n.path,composition:i}),i));return}case"export-portable-block":{if(!X(n))throw new S("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 S(v,"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(!pe(n))throw new S("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 S(v,"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=k(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 S(v,"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 S(v,"History receipt composition does not match the active session.");this.sendResult(o,n.kind,await this.options.engine.getHistoryOperationResult?.({...n.request,composition:M(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 S(v,"History request does not match its cursor operation.")}let a=r?{...r,composition:M(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=E.extractRequestInfo(t);this.sendJson({type:"error",payload:{...n,message:$(s),code:j(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 S(Q,"Initialize a composition session before issuing this request.");if(b(n)!==b(s.context))throw new S(v,"The request composition does not match the active socket session.");return s.context}async resolveWireContext(t){let s=U(t);return this.resolveAndAssert(s)}async resolveOperationWireContext(t){let s=Ze(t);return this.resolveAndAssert(s)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(b(t))}async normalizeOperationRequest(t,s){let n={...t,composition:M(s)};if(n.target.kind==="route"){let o=n.target,i=U(o),r=await this.resolveAndAssert(i);n.target={...o,composition:M(r)}}return n}handleEngineEvent(t){let s=t?.composition;if(!Ge(s))return;let n=b(s);this.session.subscribedCompositionKeys.has(n)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&n===et(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(E.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=st(t);this.sendJson({type:"error",payload:{...n,message:$(s),code:j(s)}})}}sendJson(t){this.options.socket.send(E.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:$(o),code:j(o)}})}finally{this.eventDispatcher.flush()}}},Je=256;function Qe(e){if(e.length>Je||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return f(t)&&t.type==="ping"&&f(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var S=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))}},J=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 Xe(e,t){if(!f(e)||typeof e.id!="string"||!E.isRequestKind(e.kind))return!1;let s=C(e.composition);switch(e.kind){case"initialize-session":return s&&(e.mutationContext===void 0||W(e.mutationContext));case"get-document":case"get-style-context":return s;case"get-object-edit-context":return typeof e.key=="string"&&s&&he(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 X(e);case"export-portable-block-asset":return pe(e);case"execute":case"get-operation-result":return s&&Ye(e.request)&&(e.request.mutationContext===void 0||W(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return s&&ue(e.request);case"undo":case"redo":return s&&(e.request===void 0||ue(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||W(e.mutationContext))}}function X(e){if(!C(e.composition)||!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!f(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(s))||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!f(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(s=>["kind","composition","blockKey"].includes(s))||!C(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!he(t.selection_ref))}function pe(e){if(!Object.keys(e).every(s=>["id","kind","composition","request"].includes(s))||!f(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(s=>["request","snapshot_digest","file_path","occurrence","offset"].includes(s))||!X({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 ue(e){return f(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&C(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function he(e){if(e===void 0)return!0;if(!f(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,s=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||s!==void 0&&(typeof s!="number"||!Number.isInteger(s)||s<=0)||typeof t=="number"&&typeof s=="number"&&t>=s?!1:Object.keys(e).every(n=>n==="key"||n==="instanceIndex"||n==="instanceCount")}function Ye(e){return f(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&C(e.composition)&&typeof e.kind=="string"&&f(e.target)&&(e.target.kind!=="route"||C(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&f(e.params)}function C(e){return f(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Ge(e){return f(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function U(e){if(C(e.composition))return e.composition;throw new S(Q,"A composition selector is required for this request.")}function Ze(e){if(f(e)&&C(e.composition))return e.composition;throw new S(Q,"A composition selector is required for execute.")}function M(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function et(e){return e.activeComposition?b(e.activeComposition):null}function b(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function k(e,t){return f(e)&&e.ok===!0?{...e,composition:t}:e}function tt(e,t){return!f(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:le(e.data)}}function le(e){let t=e;return de(t.routeId?t:{...t,routeId:t.composition.routeId})}function f(e){return typeof e=="object"&&e!==null}function W(e){return f(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function j(e){if(!(!f(e)||typeof e.code!="string"||e.code.length===0))return e.code}function $(e){return e instanceof Error||f(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function st(e){try{return E.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var L=class{constructor(){this.tail=Promise.resolve()}run(t){let s=this.tail.then(t,t);return this.tail=s.then(()=>{},()=>{}),s}};import{createHash as fe}from"node:crypto";import{constants as ge,promises as Y}from"node:fs";import me from"node:path";var ye=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),_e=64;async function D(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==="..")||ye.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let s=0,n=new Set,o=async(i,r)=>{if(r>_e||++s>t.size*_e+1)return!1;let a=await Y.readdir(me.join(e,i),{withFileTypes:!0});for(let u of a){let c=i?`${i}/${u.name}`:u.name;if(!i&&ye.has(u.name))continue;if(u.isDirectory()){if(!await o(c,r+1))return!1;continue}if(!u.isFile())return!1;let h=t.get(c);if(h===void 0||n.has(c))return!1;n.add(c);let m=me.join(e,c),y=await Y.lstat(m),p=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength;if(!y.isFile()||y.isSymbolicLink()||y.size!==p)return!1;let l=fe("sha256").update(h).digest("hex"),_=fe("sha256"),d=await Y.open(m,ge.O_RDONLY|ge.O_NOFOLLOW);try{let g=d.createReadStream({autoClose:!1});for await(let I of g)_.update(I)}finally{await d.close()}if(_.digest("hex")!==l)return!1}return!0};return await o("",0)&&n.size===t.size}catch{return!1}}import{createHash as nt,createPublicKey as it,verify as ot}from"node:crypto";import{constants as be,promises as q}from"node:fs";import Z from"node:path";import{GeneratedSiteCapabilitiesSchema as rt}from"@vcp-dev/contracts";var at=".vcp/portable-snapshot-proof.json",Ie=4*1024*1024,ct=256*1024*1024,dt=1e4,ut=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function we(e){try{if(!e.publicKey||!G(e.publicKey,256))return null;let t=it({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let s=Z.join(e.projectRoot,at),n=await q.lstat(s);if(!n.isFile()||n.isSymbolicLink()||n.size>Ie)return null;let o=JSON.parse(await q.readFile(s,"utf8"));if(!P(o)||!F(o,["payload","signature"])||!G(o.payload,Ie)||!G(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!ot(null,i,t,r))return null;let a=new TextDecoder("utf-8",{fatal:!0}).decode(i),u=JSON.parse(a);if(JSON.stringify(u)!==a||!P(u)||!F(u,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||u.kind!=="vcp-portable-snapshot-v1"||!P(u.manifest))return null;let c=u.manifest;if(c.version!==1||c.site_id!==e.site_id||c.snapshot_id!==e.base_snapshot_id||typeof c.created_at!="string"||!Array.isArray(c.files)||!c.files.length||c.files.length>dt)return null;let h=rt.safeParse(u.host_capabilities);if(!h.success||!Array.isArray(u.trusted_host_file_hashes)||u.trusted_host_file_hashes.length>512)return null;let m=new Map;for(let d of u.trusted_host_file_hashes){if(!P(d)||!F(d,["path","hash"])||typeof d.path!="string"||!/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(d.path)||!Se(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||m.has(d.path))return null;m.set(d.path,d.hash)}let y=0,p=[],l=new Set;for(let d of c.files){if(!P(d)||!F(d,["path","hash","size_bytes"])||typeof d.path!="string"||!Se(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||typeof d.size_bytes!="number"||!Number.isSafeInteger(d.size_bytes)||d.size_bytes<0||l.has(d.path)||(l.add(d.path),y+=d.size_bytes,y>ct))return null;p.push({path:d.path,hash:d.hash,size_bytes:d.size_bytes})}let _=new Map;for(let d of p){let g=await pt(e.projectRoot,d.path,d.size_bytes);if(!g||`sha256:${nt("sha256").update(g).digest("hex")}`!==d.hash)return null;_.set(d.path,g)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:c.created_at,files:p},files:_},host_capabilities:h.data,trusted_host_file_hashes:m}}catch{return null}}async function pt(e,t,s){let n=t.split("/"),o=e;for(let a of n.slice(0,-1)){o=Z.join(o,a);let u=await q.lstat(o);if(!u.isDirectory()||u.isSymbolicLink())return null}let i=Z.join(o,n.at(-1)),r=await q.open(i,be.O_RDONLY|be.O_NOFOLLOW);try{let a=await r.stat();if(!a.isFile()||a.size!==s)return null;let u=[],c=0,h=r.createReadStream({autoClose:!1});for await(let m of h){let y=m;if(c+=y.byteLength,c>s)return h.destroy(),null;u.push(y)}return c===s?Buffer.concat(u,c):null}finally{await r.close()}}function Se(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!ut.has(t[0])&&t.every(s=>s&&s!=="."&&s!=="..")}function P(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function F(e,t){return Object.keys(e).length===t.length&&t.every(s=>Object.hasOwn(e,s))}function G(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 Rt,SiteEditPortableExportRequestSchema as kt,SiteEditPortableExportResultSchema as Ct,SiteEditPortableAssetRequestSchema as xt,SiteEditPortableAssetResultSchema as Tt,computeSiteEditCompositionKey as T}from"@vcp-dev/contracts";var At="127.0.0.1",Ot=30218,vt="/__vcp/site-edit/bridge",Oe=6*1024*1024,Pt=Oe*2,Bt=3e3,Ee=50,te=".vcp/current-snapshot.json",Re="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function bs(e){let t=V(e),s=Pe(t),n=ve(),o=n.get(s);if(o)return o;let i=new N(t);n.set(s,i);try{i.start()}catch(r){throw n.delete(s),i.stop(),r}return i}function Is(e,t,s={}){let n=new N(V(t),e,!1,s);return n.start({listen:!1}),n}var N=class{constructor(t,s=Te.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 L,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{B.mkdirSync(R.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(s){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${s instanceof Error?s.message:String(s)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let s=Lt({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 Et({projectRoot:this.options.projectRoot,watch_dirs:Nt(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Ee,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=Pe(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??gt)({...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=Mt(t.composition),o=this.getRuntime(),i=w(n);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,n);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:n,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let s=this.getRuntime(),n=w(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(w(t)),getObjectEditContext:async(t,s,n)=>this.getRuntime().getObjectEditContext(t,w(s),n),getClassNameSource:async(t,s)=>this.getRuntime().getClassNameSource(t,w(s)),getSourceTree:async t=>this.getRuntime().getSourceTree(w(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:w(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:w(t.composition)}),execute:(t,s)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return ke(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))}}async exportPortableBlock(t,s,n){let o=(g,I,Me)=>({complete:!1,unresolved:[{code:g,path:I,message:Me}]}),i=kt.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=w(s);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let c=()=>{let g=this.getRuntime().getDocument(a).data;return{site_id:g.siteId,snapshot_id:g.snapshotId,document_version:g.version}},h=c();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 m=this.dependencies.loadTrustedPortableSnapshot??(g=>we({...g,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),y;try{y=await m({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!y)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let p=new Map([...y.snapshot.files].map(([g,I])=>[g,typeof I=="string"?I:new Uint8Array(I)])),l={...y,snapshot:{...y.snapshot,files:p}};if(!await D(this.options.projectRoot,p))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let _=await mt({...r,...l,read_current_identity:c}),d=Ct.safeParse(_);if(!d.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(d.data.complete&&(d.data.site_id!==r.site_id||d.data.base_snapshot_id!==r.base_snapshot_id||d.data.document_version!==r.document_version||d.data.target.blockKey!==r.target.blockKey||d.data.target.composition.routeId!==a.routeId||d.data.target.composition.templateId!==a.templateId||d.data.selection_ref.key!==r.selection_ref.key||d.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||d.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(d.data.complete){if(!await D(this.options.projectRoot,p))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let g=c();if(this.options.snapshotId!==r.base_snapshot_id||g.site_id!==r.site_id||g.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(g.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.")}n?.(p)}return d.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=xt.safeParse(t);if(!o.success)return n("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,s,h=>{r=h});if(!a.complete)return a;if(a.snapshot_digest!==i.snapshot_digest)return n("SNAPSHOT_MISMATCH");if(!r)return n("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=yt({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),c=Tt.safeParse(u);if(!c.success)return n("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!c.data.complete)return c.data;if(!await D(this.options.projectRoot,r))return n("SNAPSHOT_WORKSPACE_MISMATCH");try{let h=this.getRuntime().getDocument(w(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 c.data}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 ke(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 oe("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let s=this.operationReceipts.get(this.operationReceiptKey(t));return s?.fingerprint===this.operationFingerprint(t)?s.result:null}executeWithReceipt(t,s){if(!this.isActiveReceiptIdentity(t))return s();let n=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(n);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:s(),settled:!1};return this.operationReceipts.set(n,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(n)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let n=await(this.dependencies.openHistoryStore??_t)(Kt({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=T(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?T(s):null;n&&this.runtimeVersionFloors.set(n,Math.max(this.runtimeVersionFloors.get(n)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=n?this.runtimeVersionFloors.get(n)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let n of t)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??Ee;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(He)?this.scheduleSnapshotIdentityAdvance():!1,n=t.filter(o=>!$t(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=B.readFileSync(R.join(this.options.projectRoot,te),"utf8"),s=JSON.parse(t),n=typeof s.snapshot_id=="string"?s.snapshot_id:"";return!n||se(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=Ht(this.options.projectRoot),n=wt(s),o=n.length>0?n:(this.options.runtime.routes??[]).map(c=>({...c})),i=It({files:s});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[T(c.context),c])),u=new Map(i.map(c=>[T(c.context),c]));if(this.runtime){for(let[c,h]of a){let m=u.get(c);(!m||m.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(w(h.context))}for(let[c,h]of u){let m=a.get(c);(!m||m.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=St(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=bt({selector:{routeId:s,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:n.entryFile}),i=T(o.context);if(!this.compositions.some(r=>T(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(T(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 Ss(e){let t=new N(V(e),Te.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function ws(e){return V(e)}function V(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:R.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??At,port:e.port??Ot,path:e.path??vt,sessionKey:e.sessionKey??jt(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Nt(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 Ht(e){let t=[],s=["app","src/app",".vcp"],n=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!B.existsSync(i))return;let r;try{r=B.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(n.has(a.name))continue;o(R.join(i,a.name));continue}if(!a.isFile())continue;let u=R.join(i,a.name),c="";try{c=B.readFileSync(u,"utf8")}catch{}t.push({path:R.relative(e,u).replaceAll(R.sep,"/"),content:c})}};for(let i of s)o(R.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function Mt(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 w(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Kt(e){return R.join(R.resolve(e.root),se(e.siteId),se(e.snapshotId),oe("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function se(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:oe("sha256").update(e).digest("hex").slice(0,32)}function ve(){let e=globalThis;return e[Re]??=new Map,e[Re]}function Pe(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function ke(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 Lt(e){let t=new ft({maxPayload:Oe,noServer:!0}),s=new WeakSet,n=i=>{new K({socket:new ne(i),engine:e.engine,validateOperationRequest:r=>Rt.safeParse(r).success})},o=(i,r,a)=>{if(!Dt(i,e))return;let u=Ft(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),r.destroy();return}u.authenticatedByHeader&&
|
|
4
|
+
`),r.destroy();return}u.authenticatedByHeader&&s.add(i),t.handleUpgrade(i,r,a,c=>{t.emit("connection",c,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(s.has(r)){n(i);return}qt(i,e.sessionKey,()=>{n(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var ne=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",s=>{this.onmessage?.({data:s.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===Ae.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Pt){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,s){this.socket.close(t,s)}};function Dt(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Ft(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=ee(e.headers["x-vcp-site-edit-key"]),o=Be(n,t.sessionKey),i=ee(e.headers.host),r=ee(e.headers.origin);return i&&!Vt(i,t.host,r)?null:r?Wt(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function qt(e,t,s){let n=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Bt),o,i=()=>{clearTimeout(n),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=a=>{try{let u=E.parseMessage(a.toString());if(u.type!=="auth"||!Be(u.payload.key,t)){r();return}i(),e.readyState===Ae.OPEN&&e.send(E.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),s()}catch{r()}},e.on("message",o),e.on("close",i)}function Be(e,t){if(!e)return!1;let s=Buffer.from(e),n=Buffer.from(t);return s.length===n.length&<(s,n)}function Vt(e,t,s){let n=xe(e),o=xe(t);return n===o||Ce(o)&&Ce(n)&&(!s||ie(s,e))||Ut(o)&&(!s||ie(s,e))}function Ut(e){return e==="0.0.0.0"||e==="::"}function Ce(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Wt(e,t,s){return s.includes(e)||(t?ie(e,t):!1)}function ie(e,t){try{return new URL(e).host===Ne(t)}catch{return!1}}function xe(e){let t=Ne(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Ne(e){return e.trim().toLowerCase()}function ee(e){return Array.isArray(e)?e[0]:e}function jt(){return ht(32).toString("base64url")}function He(e){let t=e.replaceAll("\\","/");return t===te||t.endsWith(`/${te}`)}function $t(e){let t=e.replaceAll("\\","/");return He(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}export{Pt as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,Oe as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,N as SiteEditBridgeServer,Is as attachSiteEditBridgeServer,Lt as attachSiteEditWebSocketServer,Ss as createSiteEditBridgeEngineHost,bs as ensureSiteEditBridgeServerStarted,ws as normalizeSiteEditBridgeServerOptions};
|