@vcp-dev/site-edit-bridge 0.11.33 → 0.11.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -389,6 +389,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
389
389
  previewUnavailableReason?: "too-large" | "unsupported-mime" | "bytes-unavailable" | undefined;
390
390
  }>>;
391
391
  exportPortableBlock(request: SiteEditPortableExportRequest): Promise<{
392
+ export_schema_version: 2;
392
393
  complete: true;
393
394
  site_id: string;
394
395
  base_snapshot_id: string;
@@ -431,7 +432,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
431
432
  edges: {
432
433
  from: string;
433
434
  specifier: string | null;
434
- kind: "type" | "import" | "export" | "dynamic";
435
+ kind: "type" | "export" | "import" | "dynamic";
435
436
  target: string | null;
436
437
  resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
437
438
  }[];
@@ -460,7 +461,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
460
461
  edges: {
461
462
  from: string;
462
463
  specifier: string | null;
463
- kind: "type" | "import" | "export" | "dynamic";
464
+ kind: "type" | "export" | "import" | "dynamic";
464
465
  target: string | null;
465
466
  resolution: "unresolved" | "resolved" | "external" | "budget-exhausted" | "non-literal";
466
467
  }[];
@@ -488,35 +489,53 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
488
489
  }[];
489
490
  unresolved: never[];
490
491
  };
491
- media: {
492
- file_path: string;
493
- occurrence: number;
494
- kind: "object" | "thumbnail" | "src" | "poster" | "import" | "srcset" | "array-item" | "manifest" | "host-fallback";
495
- source: "import" | "array-item" | "host-fallback" | "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;
492
+ asset_catalog: {
493
+ asset_key: string;
494
+ origin: {
495
+ kind: "snapshot";
496
+ path: string;
497
+ } | {
498
+ kind: "remote";
499
+ url: string;
506
500
  };
501
+ source_urls: string[];
502
+ }[];
503
+ asset_bindings: ({
504
+ kind: "source-token" | "module-import" | "css-url";
505
+ asset_key: string;
506
+ file_path: string;
507
+ start_offset: number;
508
+ end_offset: number;
509
+ original_text: string;
507
510
  content_digest: string;
508
- complete: true;
509
- host_fallback?: {
510
- file_path: string;
511
- digest_sha256: "196f0a9da4796aa5effa1da57fa2d68aa4477e047868e7d31aca9051e4a69eea";
512
- } | undefined;
513
- cms_field?: {
514
- sources: {
515
- slug: string;
516
- field_path: string;
517
- }[];
518
- } | undefined;
511
+ } | {
512
+ kind: "host-dependency";
513
+ asset_key: string;
514
+ file_path: string;
515
+ source_digest: string;
516
+ } | {
517
+ kind: "source-string-url";
518
+ asset_key: string;
519
+ file_path: string;
520
+ start_offset: number;
521
+ end_offset: number;
522
+ original_text: string;
523
+ content_digest: string;
524
+ value_start: number;
525
+ value_end: number;
526
+ value_text: string;
527
+ })[];
528
+ source_projections: {
529
+ source_path: string;
530
+ source_digest: string;
531
+ output_path: string;
532
+ output_digest: string;
519
533
  }[];
534
+ compiler: {
535
+ name: "rollup-typescript";
536
+ rollup_version: string;
537
+ typescript_version: string;
538
+ };
520
539
  invocation_bindings: {
521
540
  propName: string;
522
541
  value: {
@@ -639,8 +658,7 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
639
658
  exportPortableBlockAsset(request: SiteEditPortableAssetRequest): Promise<{
640
659
  complete: true;
641
660
  snapshot_digest: string;
642
- file_path: string;
643
- occurrence: number;
661
+ asset_key: string;
644
662
  path: string;
645
663
  mime_type: "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/svg+xml";
646
664
  byte_size: number;
package/dist/client.js CHANGED
@@ -1 +1 @@
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"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!Y(n.rootRef)||!Z(n.source)||!X(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>w(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")&&w(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 w(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 ce(t);case"execute":case"get-operation-result":return n&&ae(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","cms_schema_proofs"].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)||e.cms_schema_proofs!==void 0&&!re(e.cms_schema_proofs))}function re(t){if(!Array.isArray(t)||t.length>16||!Reflect.ownKeys(t).every(e=>e==="length"||typeof e=="string"&&/^(0|[1-9][0-9]*)$/u.test(e)&&Number(e)<t.length))return!1;for(let e=0;e<t.length;e++){let n=Object.getOwnPropertyDescriptor(t,String(e));if(!n||!("value"in n))return!1;let s=n.value;if(!l(s)||!Reflect.ownKeys(s).every(r=>typeof r=="string"&&r==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function ce(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","capture_id"].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||e.capture_id!==void 0&&(typeof e.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)))}function 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 ae(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 ue="vcp:designer:trace",de="designer_trace",L="__VCP_DESIGNER_TRACE__";var le=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function pe(t=globalThis){let e=t;try{if(e.localStorage?.getItem(ue)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(de)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!pe(n))return;let s={type:t,timestamp:Date.now(),payload:he(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 he(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(le.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??me);r>0&&(o.deadline=setTimeout(()=>{this.connectAttempt!==o||o.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(s,$(ye,`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(ke(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=_(e),o={...e,composition:y(s)};return this.request("execute",{request:o})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(_(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:xe(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"?Ee(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):Se[e]??Ce}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===fe||e.readyState===R)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?ge: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?Ie():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,$(be,`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)}},fe=0,R=1,me=1e4,ge={intervalMs:2e4,timeoutMs:1e4},ye="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",be="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function Ie(){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 Ce=15e3,Se={"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 ke(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 xe(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 ve(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=_(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${_e(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 Ee(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 _e(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 _(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"?_(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:_(n.request)??s}}}}}export{ye as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,be as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,U as SiteEditWebSocketClient,ve 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"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!Y(n.rootRef)||!Z(n.source)||!X(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>w(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")&&w(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 w(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 N(t);case"export-portable-block-asset":return ce(t);case"execute":case"get-operation-result":return n&&ae(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&P(t.request);case"undo":case"redo":return n&&(t.request===void 0||P(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function N(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=>["export_schema_version","site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||e.export_schema_version!==2||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)||e.cms_schema_proofs!==void 0&&!re(e.cms_schema_proofs))}function re(t){if(!Array.isArray(t)||t.length>16||!Reflect.ownKeys(t).every(e=>e==="length"||typeof e=="string"&&/^(0|[1-9][0-9]*)$/u.test(e)&&Number(e)<t.length))return!1;for(let e=0;e<t.length;e++){let n=Object.getOwnPropertyDescriptor(t,String(e));if(!n||!("value"in n))return!1;let s=n.value;if(!l(s)||!Reflect.ownKeys(s).every(r=>typeof r=="string"&&r==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function ce(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","asset_key","offset","capture_id"].includes(n))||!N({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.asset_key!="string"||!/^asset-[a-f0-9]{64}$/u.test(e.asset_key)||typeof e.offset!="number"||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset>50*1024*1024||e.offset%(1024*1024)!==0||e.capture_id!==void 0&&(typeof e.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.capture_id)))}function P(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 ae(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 ue="vcp:designer:trace",de="designer_trace",L="__VCP_DESIGNER_TRACE__";var le=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function pe(t=globalThis){let e=t;try{if(e.localStorage?.getItem(ue)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(de)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!pe(n))return;let s={type:t,timestamp:Date.now(),payload:he(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 he(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(le.test(s)){n[s]="[redacted]";continue}n[s]=A(o,e+1)}return n}var $=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??me);r>0&&(o.deadline=setTimeout(()=>{this.connectAttempt!==o||o.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(s,U(ye,`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(ke(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=_(e),o={...e,composition:y(s)};return this.request("execute",{request:o})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(_(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:F(n.request,"kind"),documentVersion:F(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:xe(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"?Ee(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):Se[e]??Ce}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===fe||e.readyState===R)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?ge: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?Ie():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,U(be,`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)}},fe=0,R=1,me=1e4,ge={intervalMs:2e4,timeoutMs:1e4},ye="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",be="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function Ie(){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 Ce=15e3,Se={"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 ke(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 F(t,e){if(!t||typeof t!="object")return null;let s=t[e];return typeof s=="string"||typeof s=="number"?s:null}function xe(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 ve(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=!W(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=W(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=_(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${_e(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 W(t){return t.version===0&&t.entries.length===0}function Ee(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 _e(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 _(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"?_(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:_(n.request)??s}}}}}export{ye as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,be as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,$ as SiteEditWebSocketClient,ve as createSiteEditBridge};