@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
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
1
|
+
import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
|
|
2
2
|
import { type SiteEditBridgeInitializeInput, type SiteEditHistoryStatus, type SiteEditBridgeRequestKind } from "./protocol.js";
|
|
3
3
|
export type { SiteEditHistoryStatus } from "./protocol.js";
|
|
4
4
|
type SiteEditBridgeCompositionInput = SiteEditCompositionSelector;
|
|
@@ -40,6 +40,8 @@ export type SiteEditBridgeClient = {
|
|
|
40
40
|
path: string;
|
|
41
41
|
composition: SiteEditBridgeCompositionInput;
|
|
42
42
|
}): Promise<SiteEditCommandSuccess<SiteEditSourceFileResponse>>;
|
|
43
|
+
exportPortableBlock?(request: SiteEditPortableExportRequest): Promise<SiteEditPortableExportResult>;
|
|
44
|
+
exportPortableBlockAsset?(request: SiteEditPortableAssetRequest): Promise<SiteEditPortableAssetResult>;
|
|
43
45
|
resolveSourceLocation(input: SiteEditResolveSourceLocationInput): Promise<SiteEditCommandSuccess<SiteEditSourceLocation>>;
|
|
44
46
|
execute(request: SiteEditOperationRequest | Record<string, unknown>, mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
|
|
45
47
|
getOperationResult?(request: SiteEditOperationRequest): Promise<SiteEditOperationCommandResult | null>;
|
|
@@ -386,6 +388,194 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
|
|
|
386
388
|
contentBase64?: string | undefined;
|
|
387
389
|
previewUnavailableReason?: "too-large" | "unsupported-mime" | "bytes-unavailable" | undefined;
|
|
388
390
|
}>>;
|
|
391
|
+
exportPortableBlock(request: SiteEditPortableExportRequest): Promise<{
|
|
392
|
+
complete: true;
|
|
393
|
+
site_id: string;
|
|
394
|
+
base_snapshot_id: string;
|
|
395
|
+
snapshot_digest: string;
|
|
396
|
+
document_version: number;
|
|
397
|
+
target: {
|
|
398
|
+
kind: "page-block";
|
|
399
|
+
composition: {
|
|
400
|
+
routeId: string;
|
|
401
|
+
templateId?: string | undefined;
|
|
402
|
+
};
|
|
403
|
+
blockKey: string;
|
|
404
|
+
};
|
|
405
|
+
selection_ref: {
|
|
406
|
+
key: string;
|
|
407
|
+
instanceIndex?: number | undefined;
|
|
408
|
+
instanceCount?: number | undefined;
|
|
409
|
+
};
|
|
410
|
+
entry: {
|
|
411
|
+
file: string;
|
|
412
|
+
export: {
|
|
413
|
+
kind: "default";
|
|
414
|
+
} | {
|
|
415
|
+
kind: "named";
|
|
416
|
+
name: string;
|
|
417
|
+
};
|
|
418
|
+
};
|
|
419
|
+
files: {
|
|
420
|
+
path: string;
|
|
421
|
+
content: string;
|
|
422
|
+
}[];
|
|
423
|
+
source_closure: {
|
|
424
|
+
entry_files: string[];
|
|
425
|
+
nodes: {
|
|
426
|
+
path: string;
|
|
427
|
+
kind: "source" | "external" | "asset";
|
|
428
|
+
depth: number | null;
|
|
429
|
+
status: "complete" | "unresolved" | "parse-failed" | "depth-exhausted" | "budget-exhausted";
|
|
430
|
+
}[];
|
|
431
|
+
edges: {
|
|
432
|
+
from: string;
|
|
433
|
+
specifier: string | null;
|
|
434
|
+
kind: "type" | "export" | "import" | "dynamic";
|
|
435
|
+
target: string | null;
|
|
436
|
+
resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
|
|
437
|
+
}[];
|
|
438
|
+
errors: {
|
|
439
|
+
code: string;
|
|
440
|
+
path: string;
|
|
441
|
+
message: string;
|
|
442
|
+
specifier?: string | undefined;
|
|
443
|
+
}[];
|
|
444
|
+
complete: boolean;
|
|
445
|
+
budget: {
|
|
446
|
+
max_depth: number;
|
|
447
|
+
max_nodes: number;
|
|
448
|
+
};
|
|
449
|
+
};
|
|
450
|
+
dependency_audit: {
|
|
451
|
+
complete: boolean;
|
|
452
|
+
nodes: {
|
|
453
|
+
path: string;
|
|
454
|
+
kind: "source" | "external" | "asset";
|
|
455
|
+
depth: number | null;
|
|
456
|
+
status: "complete" | "unresolved" | "parse-failed" | "depth-exhausted" | "budget-exhausted";
|
|
457
|
+
ownership: "unknown" | "private" | "host-public" | "platform-managed" | "unsupported-external-private";
|
|
458
|
+
ownership_reason: string;
|
|
459
|
+
}[];
|
|
460
|
+
edges: {
|
|
461
|
+
from: string;
|
|
462
|
+
specifier: string | null;
|
|
463
|
+
kind: "type" | "export" | "import" | "dynamic";
|
|
464
|
+
target: string | null;
|
|
465
|
+
resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
|
|
466
|
+
}[];
|
|
467
|
+
errors: {
|
|
468
|
+
code: string;
|
|
469
|
+
path: string;
|
|
470
|
+
message: string;
|
|
471
|
+
specifier?: string | undefined;
|
|
472
|
+
}[];
|
|
473
|
+
};
|
|
474
|
+
cms: {
|
|
475
|
+
complete: true;
|
|
476
|
+
dependencies: {
|
|
477
|
+
requirement_key: string;
|
|
478
|
+
slug: string;
|
|
479
|
+
evidence: {
|
|
480
|
+
source_path: string;
|
|
481
|
+
operation: string;
|
|
482
|
+
binding: "trusted-cms";
|
|
483
|
+
call_site: {
|
|
484
|
+
line: number;
|
|
485
|
+
column: number;
|
|
486
|
+
};
|
|
487
|
+
}[];
|
|
488
|
+
}[];
|
|
489
|
+
unresolved: never[];
|
|
490
|
+
};
|
|
491
|
+
media: {
|
|
492
|
+
file_path: string;
|
|
493
|
+
occurrence: number;
|
|
494
|
+
kind: "object" | "srcset" | "poster" | "src" | "manifest" | "thumbnail" | "import" | "array-item";
|
|
495
|
+
source: "import" | "array-item" | "jsx-attribute" | "object-property" | "media-manifest";
|
|
496
|
+
value: string | null;
|
|
497
|
+
expression: string;
|
|
498
|
+
asset_key: string | null;
|
|
499
|
+
source_range: {
|
|
500
|
+
start_offset: number;
|
|
501
|
+
end_offset: number;
|
|
502
|
+
start_line: number;
|
|
503
|
+
start_column: number;
|
|
504
|
+
end_line: number;
|
|
505
|
+
end_column: number;
|
|
506
|
+
};
|
|
507
|
+
content_digest: string;
|
|
508
|
+
complete: true;
|
|
509
|
+
}[];
|
|
510
|
+
invocation_bindings: {
|
|
511
|
+
propName: string;
|
|
512
|
+
value: {
|
|
513
|
+
kind: "json-literal";
|
|
514
|
+
value: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[] | {
|
|
515
|
+
[key: string]: any;
|
|
516
|
+
} | null)[] | {
|
|
517
|
+
[key: string]: any;
|
|
518
|
+
} | null)[] | {
|
|
519
|
+
[key: string]: any;
|
|
520
|
+
} | null)[] | {
|
|
521
|
+
[key: string]: any;
|
|
522
|
+
} | null)[] | {
|
|
523
|
+
[key: string]: any;
|
|
524
|
+
} | null)[] | {
|
|
525
|
+
[key: string]: any;
|
|
526
|
+
} | null)[] | {
|
|
527
|
+
[key: string]: any;
|
|
528
|
+
} | null)[] | {
|
|
529
|
+
[key: string]: any;
|
|
530
|
+
} | null)[] | {
|
|
531
|
+
[key: string]: any;
|
|
532
|
+
} | null)[] | {
|
|
533
|
+
[key: string]: any;
|
|
534
|
+
} | null)[] | {
|
|
535
|
+
[key: string]: any;
|
|
536
|
+
} | null;
|
|
537
|
+
} | {
|
|
538
|
+
kind: "route-search-params";
|
|
539
|
+
} | {
|
|
540
|
+
kind: "target-block-id";
|
|
541
|
+
};
|
|
542
|
+
}[];
|
|
543
|
+
host_contract_digest: string;
|
|
544
|
+
} | {
|
|
545
|
+
complete: false;
|
|
546
|
+
unresolved: {
|
|
547
|
+
code: string;
|
|
548
|
+
path: string;
|
|
549
|
+
message: string;
|
|
550
|
+
call_site?: {
|
|
551
|
+
line: number;
|
|
552
|
+
column: number;
|
|
553
|
+
} | undefined;
|
|
554
|
+
}[];
|
|
555
|
+
}>;
|
|
556
|
+
exportPortableBlockAsset(request: SiteEditPortableAssetRequest): Promise<{
|
|
557
|
+
complete: true;
|
|
558
|
+
snapshot_digest: string;
|
|
559
|
+
file_path: string;
|
|
560
|
+
occurrence: number;
|
|
561
|
+
path: string;
|
|
562
|
+
mime_type: "image/png" | "image/jpeg" | "image/webp" | "image/gif";
|
|
563
|
+
byte_size: number;
|
|
564
|
+
digest_sha256: string;
|
|
565
|
+
offset: number;
|
|
566
|
+
data_base64: string;
|
|
567
|
+
} | {
|
|
568
|
+
complete: false;
|
|
569
|
+
unresolved: {
|
|
570
|
+
code: string;
|
|
571
|
+
path: string;
|
|
572
|
+
message: string;
|
|
573
|
+
call_site?: {
|
|
574
|
+
line: number;
|
|
575
|
+
column: number;
|
|
576
|
+
} | undefined;
|
|
577
|
+
}[];
|
|
578
|
+
}>;
|
|
389
579
|
resolveSourceLocation(input: SiteEditResolveSourceLocationInput): Promise<SiteEditCommandSuccess<{
|
|
390
580
|
key: string;
|
|
391
581
|
composition: {
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function N(t){if(!V(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],i=new Map(t.dynamicDataSummaries??[]),s=new Map(t.pageCompositionActionScopes??[]),r=c=>{let o=e.get(c);if(o)return o;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,o)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[o],_=s.get(o),O=_?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:_.siblingEntryIndexes.map(M=>{let B=t.entries[M];if(!B)throw new Error(`Missing source sibling entry ${M}`);return r(B[0])})}:_;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...O?{pageCompositionActionScope:O}:{},operationSummary:z(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function z(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function V(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!H(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!l(e.pageComposition)||e.pageBlocks!==void 0&&!G(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(o=>typeof o=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((o,a)=>Array.isArray(o)&&o.length===2&&(o[0]===null||p(o[0])&&o[0]<a)&&p(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&p(o[0])&&o[0]<n.length&&p(o[1])&&o[1]<=15&&(o.length===2||p(o[2]))))return!1;let i=e.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==e.entries.length||!i.every(o=>o===null||p(o)&&o<n.length)))return!1;let s=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(o=>{if(!Array.isArray(o)||o.length!==2||!p(o[0])||o[0]>=e.entries.length||!l(o[1])||!["route-unit","source-siblings","unavailable"].includes(String(o[1].kind)))return!1;let a=o[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(o[0])}))&&(s===void 0||Array.isArray(s)&&s.every(o=>Array.isArray(o)&&o.length===2&&p(o[0])&&o[0]<e.entries.length&&l(o[1])))}function l(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return!l(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function G(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!l(n)||!b(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!J(n.rootRef)||!Q(n.source)||!Y(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>w(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!I(n.placementUnitKey)||!Z(n.capabilities)||n.unavailableReasons!==void 0&&!X(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let i=n.owner;for(let s of n.siblingBlockKeys){let r=e.get(s);if(!r)return!1;let c=r.owner;if(i.kind!==c.kind||i.key!==c.key)return!1}}return!0}function J(t){return!l(t)||!b(t,["key","instanceIndex","instanceCount"])||!I(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Q(t){return l(t)&&b(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ee(t.file)&&I(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function Y(t){return l(t)&&b(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&w(t.key,512)}function Z(t){return l(t)&&b(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function X(t){return l(t)&&Object.entries(t).every(([e,n])=>I(e)&&l(n)&&b(n,["code","reason"])&&I(n.code)&&I(n.reason))}function ee(t){let e=te(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let i=t.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(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function te(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),i=n.some(c=>K(c)),s=i?n[0]:n.pop(),r=i?n.slice(1):n;if(i&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(s)||!ne(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!K(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=s.replace(/-/gu,"+").replace(/_/gu,"/"),o=atob(c),a=Uint8Array.from(o,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===s}catch{return!1}}function K(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ne(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function w(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function I(t){return typeof t=="string"&&t.length>0}function b(t,e){let n=new Set(e);return Object.keys(t).every(i=>n.has(i))}var g=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(h(e)&&h(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?h(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&h(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!h(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=T(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&se(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&oe(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&v(t.request);case"undo":case"redo":return n&&(t.request===void 0||v(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function v(t){return h(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&T(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function se(t){if(t===void 0)return!0;if(!h(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function oe(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&T(t.composition)&&typeof t.kind=="string"&&h(t.target)&&(t.target.kind!=="route"||T(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function T(t){return h(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function h(t){return typeof t=="object"&&t!==null}function q(t){return h(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var re="vcp:designer:trace",ce="designer_trace",P="__VCP_DESIGNER_TRACE__";var ae=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function ue(t=globalThis){let e=t;try{if(e.localStorage?.getItem(re)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ce)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!ue(n))return;let i={type:t,timestamp:Date.now(),payload:de(e)},s=n,r=s[P]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[P]=r;let c=n.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",i)}function de(t){return R(t,0)}function R(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(i=>R(i,e+1));if(!t||typeof t!="object")return t;let n={};for(let[i,s]of Object.entries(t)){if(ae.test(i)){n[i]="[redacted]";continue}n[i]=R(s,e+1)}return n}var j=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===D&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let i;try{i=this.createSocket(this.options.url)}catch(a){let u=C(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:i,settled:!1,reject:n};this.connectAttempt=s,this.socket=i;let r=Math.max(0,this.options.connectTimeoutMs??pe);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,U(fe,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==i||this.connectAttempt!==s||(s.settled=!0,clearTimeout(s.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(i),e())},o=(a,u)=>{this.cleanupSocket(i,a,u)};i.onopen=()=>{if(!(this.socket!==i||this.connectAttempt!==s)){if(this.options.authKey){try{i.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(C(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=C(a,"WebSocket failed");o(u,"failed")},i.onmessage=a=>{if(this.socket===i){if(this.noteInboundMessage(i),this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(a.data,i,s,()=>{c()});return}this.handleMessage(a.data)}},i.onclose=a=>{if(this.socket!==i)return;let u=this.intentionalClose,d=new Error(be(a,{intentional:u}));o(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,i){let s=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:s,...i?{selectionRef:i}:{}})}getClassNameSource(e,n){let i=this.selector(n);return this.request("get-class-name-source",{key:e,composition:i})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let i=E(e),s={...e,composition:y(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(E(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,i){return this.request("undo",{composition:this.selector(e),...i?{request:i}:{}})}redo(e,n,i){return this.request("redo",{composition:this.selector(e),...i?{request:i}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let i=this.socket;if(!i||i.readyState!==D||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${i?.readyState??"none"})`));let s=`${e}-${this.sequence+=1}`,r=ke(s,e,n);return f("bridge.request",{id:s,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:$(n.request,"kind"),documentVersion:$(n.request,"documentVersion")}),new Promise((c,o)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(s);d&&(this.pending.delete(s),f("bridge.response",{id:s,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(s,{kind:e,timeout:u,resolve:d=>c(d),reject:o});try{i.send(g.stringifyMessage(r))}catch(d){let m=C(d,"WebSocket send failed");this.clearPendingRequest(s),o(m),this.cleanupSocket(i,m,"failed")}})}handleAuthHandshakeMessage(e,n,i,s){try{if(g.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=C(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let s of this.listeners)s(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let i=this.pending.get(n.payload.id);if(i){if(this.clearPendingRequest(n.payload.id),n.type==="error"){f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!1});let s=new Error(n.payload.message);n.payload.code&&(s.code=n.payload.code),i.reject(s);return}f("bridge.response",{id:n.payload.id,kind:i.kind,ok:!0,resultVersion:Ce(n.payload.result)}),i.resolve(i.kind==="get-document"?{...n.payload.result,data:L(n.payload.result.data,n.payload.result.composition)}:i.kind==="initialize-session"?Se(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,i]of[...this.pending])this.clearPendingRequest(n),i.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Ie[e]??ye}cleanupSocket(e,n,i){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let s=this.connectAttempt;this.connectAttempt=null,clearTimeout(s.deadline),s.settled||(s.settled=!0,s.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(i,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===he||e.readyState===D)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?le:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let i=this.options.visibility===void 0?ge():this.options.visibility,s=()=>i?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!s())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,C(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,U(me,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},o=()=>{s()?c():r()};i?.addEventListener("visibilitychange",o),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>i?.removeEventListener("visibilitychange",o)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let i={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(i);for(let s of this.connectionStatusListeners)s(i)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},he=0,D=1,pe=1e4,le={intervalMs:2e4,timeoutMs:1e4},fe="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",me="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ge(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function U(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var ye=15e3,Ie={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function C(t,e){return t instanceof Error?t:new Error(e)}function be(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function $(t,e){if(!t||typeof t!="object")return null;let i=t[e];return typeof i=="string"||typeof i=="number"?i:null}function Ce(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Oe(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new A({composition:e,initialDocument:t.initialDocument,client:t.client})}var A=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let i=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=i.data.document,this.observedDocumentVersion=i.data.document.version,this.activeCompositionContext={...i.composition},this.rememberServerConfirmedComposition(i.composition),this.sessionInitialized=!0,this.clearObjectCaches(),i}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),i=k(n),s=this.styleContextCache.get(i);if(s?.generation===this.styleGeneration)return{ok:!0,data:s.value};let r=this.styleContextInFlight.get(i);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,o=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(i,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(i)?.request===o&&this.styleContextInFlight.delete(i)});return this.styleContextInFlight.set(i,{generation:c,request:o}),o}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,i){let s=this.requireBoundComposition(n),r=this.objectCacheKey(e,s,i),c=this.editContextCache.get(r);if(c)return{ok:!0,composition:c.composition,data:c};let o=this.editContextInFlight.get(r);if(o)return o;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,s,...i?[i]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let i=this.requireBoundComposition(n),s=this.objectCacheKey(e,i),r=this.classNameSourceCache.get(s);if(r)return r;let c=this.classNameSourceInFlight.get(s);if(c)return c;let o=this.objectGeneration,a=this.params.client.getClassNameSource(e,i).then(u=>(this.objectGeneration===o&&this.classNameSourceCache.set(s,u),u)).finally(()=>{this.classNameSourceInFlight.get(s)===a&&this.classNameSourceInFlight.delete(s)});return this.classNameSourceInFlight.set(s,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let i=E(e);i&&this.composition.templateId!==void 0&&this.requireBoundComposition(i);let s={...e,composition:i??this.composition};return this.params.client.execute(s)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.undo(s,void 0,i):this.params.client.undo(s)}async redo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.redo(s,void 0,i):this.params.client.redo(s)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let i=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),i&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let i=k(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await s.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let o=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&S(c.data.composition)===S(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),o||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:i,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,i){return`${k(n)}\0${e}\0${xe(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(k(e)===k(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&S(n)===S(W(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??W(this.composition);return S(e)===S(n)}};function F(t){return t.version===0&&t.entries.length===0}function Se(t){let e=t;return{...e,data:{...e.data,document:L(e.data.document,e.composition)}}}function L(t,e){let n=t,i=N(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...i,composition:e}:i}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function k(t){return JSON.stringify([t.routeId,t.templateId??null])}function xe(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function S(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function W(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function E(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function ke(t,e,n){let i=y(e==="execute"?E(n.request):n.composition),s={id:t,kind:e,composition:i};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...s,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...s,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...s,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...s,path:String(n.path)}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...s,request:{...n.request,composition:E(n.request)??i}}}}}export{fe as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,me as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,j as SiteEditWebSocketClient,Oe as createSiteEditBridge};
|
|
1
|
+
function K(t){if(!G(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],s=new Map(t.dynamicDataSummaries??[]),o=new Map(t.pageCompositionActionScopes??[]),r=c=>{let i=e.get(c);if(i)return i;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,i)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[i],T=o.get(i),D=T?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:T.siblingEntryIndexes.map(B=>{let M=t.entries[B];if(!M)throw new Error(`Missing source sibling entry ${B}`);return r(M[0])})}:T;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...D?{pageCompositionActionScope:D}:{},operationSummary:H(u),...s.get(i)?{dynamicDataSummary:s.get(i)}:{}}})}}function H(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function G(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!J(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!h(e.pageComposition)||e.pageBlocks!==void 0&&!Q(e.pageBlocks)||!Array.isArray(e.tokens)||!e.tokens.every(i=>typeof i=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((i,a)=>Array.isArray(i)&&i.length===2&&(i[0]===null||p(i[0])&&i[0]<a)&&p(i[1])&&i[1]<e.tokens.length)||!e.entries.every(i=>Array.isArray(i)&&(i.length===2||i.length===3)&&p(i[0])&&i[0]<n.length&&p(i[1])&&i[1]<=15&&(i.length===2||p(i[2]))))return!1;let s=e.entryParentNodeIds;if(s!==void 0&&(!Array.isArray(s)||s.length!==e.entries.length||!s.every(i=>i===null||p(i)&&i<n.length)))return!1;let o=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(i=>{if(!Array.isArray(i)||i.length!==2||!p(i[0])||i[0]>=e.entries.length||!h(i[1])||!["route-unit","source-siblings","unavailable"].includes(String(i[1].kind)))return!1;let a=i[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>p(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(i[0])}))&&(o===void 0||Array.isArray(o)&&o.every(i=>Array.isArray(i)&&i.length===2&&p(i[0])&&i[0]<e.entries.length&&h(i[1])))}function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){return!h(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function Q(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!h(n)||!I(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!_(n.blockKey,256)||!_(n.definitionKey,512)||!Y(n.rootRef)||!Z(n.source)||!X(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>_(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!b(n.placementUnitKey)||!ee(n.capabilities)||n.unavailableReasons!==void 0&&!te(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let s=n.owner;for(let o of n.siblingBlockKeys){let r=e.get(o);if(!r)return!1;let c=r.owner;if(s.kind!==c.kind||s.key!==c.key)return!1}}return!0}function Y(t){return!h(t)||!I(t,["key","instanceIndex","instanceCount"])||!b(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Z(t){return h(t)&&I(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ne(t.file)&&b(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function X(t){return h(t)&&I(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&_(t.key,512)}function ee(t){return h(t)&&I(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function te(t){return h(t)&&Object.entries(t).every(([e,n])=>b(e)&&h(n)&&I(n,["code","reason"])&&b(n.code)&&b(n.reason))}function ne(t){let e=se(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let s=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function se(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),s=n.some(c=>v(c)),o=s?n[0]:n.pop(),r=s?n.slice(1):n;if(s&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!oe(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!v(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=o.replace(/-/gu,"+").replace(/_/gu,"/"),i=atob(c),a=Uint8Array.from(i,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function v(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function oe(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function _(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function b(t){return typeof t=="string"&&t.length>0}function I(t,e){let n=new Set(e);return Object.keys(t).every(s=>n.has(s))}var g=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(l(e)&&l(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",s=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="export-portable-block"||e==="export-portable-block-asset"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!l(e)||typeof e.type!="string"?!1:e.type==="request"?ie(e.payload,n):e.type==="response"||e.type==="error"?l(e.payload)&&typeof e.payload.id=="string":e.type==="event"?l(e.payload)&&l(e.payload.event):e.type==="auth"?l(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?l(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&l(e.payload)&&e.payload.ok===!0}};function ie(t,e){if(!l(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=C(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&j(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"export-portable-block":return P(t);case"export-portable-block-asset":return re(t);case"execute":case"get-operation-result":return n&&ce(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&N(t.request);case"undo":case"redo":return n&&(t.request===void 0||N(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function P(t){if(!C(t.composition)||!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(n))||typeof e.site_id!="string"||typeof e.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(e.base_snapshot_id)||typeof e.document_version!="number"||!Number.isSafeInteger(e.document_version)||e.document_version<0||!l(e.target)||e.target.kind!=="page-block"||typeof e.target.blockKey!="string"||!e.target.blockKey.length||e.target.blockKey.length>256||!Object.keys(e.target).every(n=>["kind","composition","blockKey"].includes(n))||!C(e.target.composition)||e.target.composition.routeId!==t.composition.routeId||e.target.composition.templateId!==t.composition.templateId||e.selection_ref===void 0||!j(e.selection_ref))}function re(t){if(!Object.keys(t).every(n=>["id","kind","composition","request"].includes(n))||!l(t.request))return!1;let e=t.request;return!(!Object.keys(e).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!P({id:t.id,kind:"export-portable-block",composition:t.composition,request:e.request})||typeof e.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.snapshot_digest)||typeof e.file_path!="string"||!e.file_path.length||e.file_path.length>1024||e.file_path.startsWith("/")||/[\\\0%]/u.test(e.file_path)||e.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof e.occurrence!="number"||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||e.occurrence>4095||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0)}function N(t){return l(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&C(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function j(t){if(t===void 0)return!0;if(!l(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function ce(t){return l(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&C(t.composition)&&typeof t.kind=="string"&&l(t.target)&&(t.target.kind!=="route"||C(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&l(t.params)}function C(t){return l(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function l(t){return typeof t=="object"&&t!==null}function q(t){return l(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var ae="vcp:designer:trace",ue="designer_trace",L="__VCP_DESIGNER_TRACE__";var de=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function le(t=globalThis){let e=t;try{if(e.localStorage?.getItem(ae)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ue)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!le(n))return;let s={type:t,timestamp:Date.now(),payload:pe(e)},o=n,r=o[L]??[];r.push(s),r.length>1e3&&r.splice(0,r.length-1e3),o[L]=r;let c=n.console?.debug;s.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",s)}function pe(t){return A(t,0)}function A(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(s=>A(s,e+1));if(!t||typeof t!="object")return t;let n={};for(let[s,o]of Object.entries(t)){if(de.test(s)){n[s]="[redacted]";continue}n[s]=A(o,e+1)}return n}var U=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===R&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let s;try{s=this.createSocket(this.options.url)}catch(a){let u=S(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let o={socket:s,settled:!1,reject:n};this.connectAttempt=o,this.socket=s;let r=Math.max(0,this.options.connectTimeoutMs??fe);r>0&&(o.deadline=setTimeout(()=>{this.connectAttempt!==o||o.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(s,$(ge,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==s||this.connectAttempt!==o||(o.settled=!0,clearTimeout(o.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(s),e())},i=(a,u)=>{this.cleanupSocket(s,a,u)};s.onopen=()=>{if(!(this.socket!==s||this.connectAttempt!==o)){if(this.options.authKey){try{s.send(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(S(a,"WebSocket auth failed"),"failed")}return}c()}},s.onerror=a=>{if(this.socket!==s)return;let u=S(a,"WebSocket failed");i(u,"failed")},s.onmessage=a=>{if(this.socket===s){if(this.noteInboundMessage(s),this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,s,o,()=>{c()});return}this.handleMessage(a.data)}},s.onclose=a=>{if(this.socket!==s)return;let u=this.intentionalClose,d=new Error(Se(a,{intentional:u}));i(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,s){let o=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:o,...s?{selectionRef:s}:{}})}getClassNameSource(e,n){let s=this.selector(n);return this.request("get-class-name-source",{key:e,composition:s})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}exportPortableBlock(e){return this.request("export-portable-block",{composition:this.selector(e.target.composition),request:e})}exportPortableBlockAsset(e){return this.request("export-portable-block-asset",{composition:this.selector(e.request.target.composition),request:e})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let s=w(e),o={...e,composition:y(s)};return this.request("execute",{request:o})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(w(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,s){return this.request("undo",{composition:this.selector(e),...s?{request:s}:{}})}redo(e,n,s){return this.request("redo",{composition:this.selector(e),...s?{request:s}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return y(e)}request(e,n){let s=this.socket;if(!s||s.readyState!==R||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${s?.readyState??"none"})`));let o=`${e}-${this.sequence+=1}`,r=we(o,e,n);return f("bridge.request",{id:o,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:W(n.request,"kind"),documentVersion:W(n.request,"documentVersion")}),new Promise((c,i)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(o);d&&(this.pending.delete(o),f("bridge.response",{id:o,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:e,timeout:u,resolve:d=>c(d),reject:i});try{s.send(g.stringifyMessage(r))}catch(d){let m=S(d,"WebSocket send failed");this.clearPendingRequest(o),i(m),this.cleanupSocket(s,m,"failed")}})}handleAuthHandshakeMessage(e,n,s,o){try{if(g.parseMessage(e).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(r){let c=S(r,"Bridge authentication failed");this.connectAttempt===s&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.parseMessage(e);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let s=this.pending.get(n.payload.id);if(s){if(this.clearPendingRequest(n.payload.id),(s.kind==="export-portable-block"||s.kind==="export-portable-block-asset")&&n.payload.kind!==s.kind){s.reject(new Error("Portable export response kind does not match the request."));return}if(n.type==="error"){f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!1});let o=new Error(n.payload.message);n.payload.code&&(o.code=n.payload.code),s.reject(o);return}f("bridge.response",{id:n.payload.id,kind:s.kind,ok:!0,resultVersion:ke(n.payload.result)}),s.resolve(s.kind==="get-document"?{...n.payload.result,data:z(n.payload.result.data,n.payload.result.composition)}:s.kind==="initialize-session"?xe(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,s]of[...this.pending])this.clearPendingRequest(n),s.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):Ce[e]??Ie}cleanupSocket(e,n,s){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let o=this.connectAttempt;this.connectAttempt=null,clearTimeout(o.deadline),o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(s,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===he||e.readyState===R)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?me:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let s=this.options.visibility===void 0?be():this.options.visibility,o=()=>s?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!o())){try{e.send(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,S(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,o()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,$(ye,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},i=()=>{o()?c():r()};s?.addEventListener("visibilitychange",i),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>s?.removeEventListener("visibilitychange",i)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let s={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(s);for(let o of this.connectionStatusListeners)o(s)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},he=0,R=1,fe=1e4,me={intervalMs:2e4,timeoutMs:1e4},ge="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",ye="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function be(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function $(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var Ie=15e3,Ce={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function S(t,e){return t instanceof Error?t:new Error(e)}function Se(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function W(t,e){if(!t||typeof t!="object")return null;let s=t[e];return typeof s=="string"||typeof s=="number"?s:null}function ke(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Me(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new O({composition:e,initialDocument:t.initialDocument,client:t.client})}var O=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=y(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let s=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=s.data.document,this.observedDocumentVersion=s.data.document.version,this.activeCompositionContext={...s.composition},this.rememberServerConfirmedComposition(s.composition),this.sessionInitialized=!0,this.clearObjectCaches(),s}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),s=E(n),o=this.styleContextCache.get(s);if(o?.generation===this.styleGeneration)return{ok:!0,data:o.value};let r=this.styleContextInFlight.get(s);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,i=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(s,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(s)?.request===i&&this.styleContextInFlight.delete(s)});return this.styleContextInFlight.set(s,{generation:c,request:i}),i}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let s=await this.refreshSnapshot(n,"ensure-version");if(s.version<n)throw new Error(`Document refresh returned version ${s.version}, expected at least ${n}`);return{ok:!0,data:s}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,s){let o=this.requireBoundComposition(n),r=this.objectCacheKey(e,o,s),c=this.editContextCache.get(r);if(c)return{ok:!0,composition:c.composition,data:c};let i=this.editContextInFlight.get(r);if(i)return i;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,o,...s?[s]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let s=this.requireBoundComposition(n),o=this.objectCacheKey(e,s),r=this.classNameSourceCache.get(o);if(r)return r;let c=this.classNameSourceInFlight.get(o);if(c)return c;let i=this.objectGeneration,a=this.params.client.getClassNameSource(e,s).then(u=>(this.objectGeneration===i&&this.classNameSourceCache.set(o,u),u)).finally(()=>{this.classNameSourceInFlight.get(o)===a&&this.classNameSourceInFlight.delete(o)});return this.classNameSourceInFlight.set(o,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async exportPortableBlock(e){return this.requireBoundComposition(e.target.composition),this.params.client.exportPortableBlock?this.params.client.exportPortableBlock(e):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]}}async exportPortableBlockAsset(e){return this.requireBoundComposition(e.request.target.composition),this.params.client.exportPortableBlockAsset?this.params.client.exportPortableBlockAsset(e):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]}}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let s=w(e);s&&this.composition.templateId!==void 0&&this.requireBoundComposition(s);let o={...e,composition:s??this.composition};return this.params.client.execute(o)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.undo(o,void 0,s):this.params.client.undo(o)}async redo(e,n,s){let o=this.requireBoundComposition(e);return s?this.params.client.redo(o,void 0,s):this.params.client.redo(o)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let s=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),s&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let s=E(this.composition),o=this.refreshInFlight;if(o?.compositionKey===s){f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await o.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}f("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let i=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&k(c.data.composition)===k(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),i||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:s,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,s){return`${E(n)}\0${e}\0${Ee(s)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(E(e)===E(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&k(n)===k(V(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??V(this.composition);return k(e)===k(n)}};function F(t){return t.version===0&&t.entries.length===0}function xe(t){let e=t;return{...e,data:{...e.data,document:z(e.data.document,e.composition)}}}function z(t,e){let n=t,s=K(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...s,composition:e}:s}function y(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function E(t){return JSON.stringify([t.routeId,t.templateId??null])}function Ee(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function k(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function V(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function w(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function we(t,e,n){let s=y(e==="execute"?w(n.request):n.composition),o={id:t,kind:e,composition:s};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...o,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...o,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...o,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...o,path:String(n.path)}};case"export-portable-block":case"export-portable-block-asset":return{type:"request",payload:{...o,request:n.request}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...o,request:{...n.request,composition:w(n.request)??s}}}}}export{ge as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,ye as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,U as SiteEditWebSocketClient,Me as createSiteEditBridge};
|