@betteroffice/xlsx 0.5.0 → 0.6.0

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.
Files changed (50) hide show
  1. package/LICENSES/MIT-ruzstd.txt +21 -0
  2. package/LICENSES/MIT-twox-hash.txt +21 -0
  3. package/LICENSES/MIT-wuff.txt +20 -0
  4. package/README.md +45 -10
  5. package/dist/chunk-3HDY7PGX.js +1 -0
  6. package/dist/chunk-4YUSZI3G.js +2 -0
  7. package/dist/chunk-6OSHYRMV.js +1 -0
  8. package/dist/chunk-AZDGFDN2.js +1 -0
  9. package/dist/chunk-B5K4E4KI.js +1 -0
  10. package/dist/chunk-E4HKBJOP.js +7 -0
  11. package/dist/chunk-FEO7P5TH.js +1 -0
  12. package/dist/chunk-GHET7GIK.js +1 -0
  13. package/dist/chunk-JABP2QRG.js +1 -0
  14. package/dist/chunk-K2GIAESV.js +2 -0
  15. package/dist/chunk-KNQOCV7P.js +1 -0
  16. package/dist/chunk-OUNTNO7R.js +1 -0
  17. package/dist/chunk-QUHWI3QK.js +1 -0
  18. package/dist/chunk-S6UYP4BX.js +1 -0
  19. package/dist/chunk-T4GUPT57.js +1 -0
  20. package/dist/chunk-VJDPZ75R.js +1 -0
  21. package/dist/chunk-X5HR6GJB.js +4 -0
  22. package/dist/collaboration.js +1 -1
  23. package/dist/{editPeer-DN6JDr8Z.d.ts → editPeer-CVhOkqsr.d.ts} +732 -365
  24. package/dist/generated/preflight/xlsx_preflight_bg.wasm +0 -0
  25. package/dist/generated/xlsx_wasm_bg.wasm +0 -0
  26. package/dist/generated/xlsx_wasm_lean_bg.wasm +0 -0
  27. package/dist/headless.d.ts +8 -2
  28. package/dist/headless.js +1 -1
  29. package/dist/index.d.ts +27 -5
  30. package/dist/index.js +1 -4
  31. package/dist/sessionWorker.missing.d.ts +3 -0
  32. package/dist/sessionWorker.missing.js +1 -0
  33. package/dist/sessionWorker.node.d.ts +3 -0
  34. package/dist/sessionWorker.node.js +1 -0
  35. package/dist/{types-DdoEoFSX.d.ts → types-BXjmeL2E.d.ts} +71 -3
  36. package/dist/wasm-preflight.d.ts +26 -0
  37. package/dist/wasm-preflight.js +1 -0
  38. package/dist/worker.d.ts +3 -3
  39. package/dist/worker.js +1 -1
  40. package/dist/xlsxSessionWorker.mjs +7 -1
  41. package/dist/xlsxSessionWorker.node.mjs +1 -0
  42. package/dist/xlsxWorkerStart.d.ts +11 -0
  43. package/dist/xlsxWorkerStart.js +1 -0
  44. package/package.json +20 -6
  45. package/dist/chunk-DIDVDN7H.js +0 -1
  46. package/dist/chunk-HJJEOLPD.js +0 -1
  47. package/dist/chunk-JGTBRHCP.js +0 -1
  48. package/dist/chunk-K7TMSGNA.js +0 -1
  49. package/dist/chunk-SXM2HKJL.js +0 -4
  50. /package/dist/{xlsxSessionWorker.d.ts → xlsxSessionWorker.node.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-4YUSZI3G.js';import'./chunk-K2GIAESV.js';import'./chunk-E4HKBJOP.js';import'./chunk-VJDPZ75R.js';import'./chunk-S6UYP4BX.js';import'./chunk-GHET7GIK.js';import'./chunk-JABP2QRG.js';import {b}from'./chunk-AZDGFDN2.js';import'./chunk-OUNTNO7R.js';import'./chunk-O2XFH626.js';a(b());
@@ -0,0 +1,11 @@
1
+ interface SessionScope {
2
+ postMessage(message: unknown, transfer: Transferable[]): void;
3
+ addEventListener(type: string, listener: EventListener): void;
4
+ removeEventListener(type: string, listener: EventListener): void;
5
+ close?(): void;
6
+ start?(): void;
7
+ }
8
+
9
+ declare function startSessionWorker(scope: SessionScope): void;
10
+
11
+ export { startSessionWorker };
@@ -0,0 +1 @@
1
+ export{a as startSessionWorker}from'./chunk-4YUSZI3G.js';import'./chunk-K2GIAESV.js';import'./chunk-E4HKBJOP.js';import'./chunk-VJDPZ75R.js';import'./chunk-S6UYP4BX.js';import'./chunk-GHET7GIK.js';import'./chunk-JABP2QRG.js';import'./chunk-O2XFH626.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@betteroffice/xlsx",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Excel-faithful XLSX spreadsheet editor and viewer core: full OOXML fidelity, real-time human + AI agent collaboration. Framework-free (Rust/Wasm).",
5
5
  "keywords": [
6
6
  "xlsx",
@@ -32,32 +32,46 @@
32
32
  "main": "./dist/index.js",
33
33
  "module": "./dist/index.js",
34
34
  "types": "./dist/index.d.ts",
35
+ "imports": {
36
+ "#session-worker": {
37
+ "node": "./dist/sessionWorker.node.js",
38
+ "default": "./dist/sessionWorker.missing.js"
39
+ }
40
+ },
35
41
  "exports": {
36
42
  ".": {
37
43
  "types": "./dist/index.d.ts",
38
- "import": "./dist/index.js"
44
+ "import": "./dist/index.js",
45
+ "default": "./dist/index.js"
39
46
  },
40
47
  "./headless": {
41
48
  "types": "./dist/headless.d.ts",
42
- "import": "./dist/headless.js"
49
+ "import": "./dist/headless.js",
50
+ "default": "./dist/headless.js"
43
51
  },
44
52
  "./worker": {
45
53
  "types": "./dist/worker.d.ts",
46
- "import": "./dist/worker.js"
54
+ "import": "./dist/worker.js",
55
+ "default": "./dist/worker.js"
47
56
  },
48
57
  "./collaboration": {
49
58
  "types": "./dist/collaboration.d.ts",
50
- "import": "./dist/collaboration.js"
59
+ "import": "./dist/collaboration.js",
60
+ "default": "./dist/collaboration.js"
51
61
  }
52
62
  },
53
63
  "files": [
54
- "dist"
64
+ "dist",
65
+ "LICENSES"
55
66
  ],
56
67
  "scripts": {
57
68
  "build": "bun run build:wasm && tsup",
58
69
  "build:wasm": "bun ../../scripts/build-xlsx-wasm.ts",
59
70
  "typecheck": "tsc --noEmit -p ."
60
71
  },
72
+ "dependencies": {
73
+ "@betteroffice/fonts": "^0.5.0"
74
+ },
61
75
  "devDependencies": {
62
76
  "@types/bun": "^1.4.2",
63
77
  "@types/node": "^26.0.0",
@@ -1 +0,0 @@
1
- import {I,u,v,o,K as K$1,r,t,F,x,B,H,p,C,w,G as G$1,D,y,A,z as z$1,q,a as a$1,d as d$1}from'./chunk-JGTBRHCP.js';import {a}from'./chunk-O2XFH626.js';var h=class extends Error{constructor(t,s,r){super(s);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=r;}};function G(o){return o instanceof Error&&o.message?o.message:typeof o=="string"&&o?o:"Unknown error"}var Y=["backpressure","protocol","replica","transport"],E=64,j=250;function K(o){if(o[0]!==0||o[1]!==2)return false;let e=0;for(let t=2,s=0;t<Math.min(o.byteLength,7);t++,s+=7)if(e+=(o[t]&127)*2**s,o[t]<128)return t+1+e===o.byteLength;return false}var b=class{constructor(e,t,s){a(this,"transport",t);a(this,"options",s);a(this,"endpoint");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"peerListeners",new Map);a(this,"nextListenerId",0);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"peerList",[]);a(this,"seq",0);a(this,"floor",0);a(this,"sendFloor",0);a(this,"inboundBytes",0);a(this,"flushingFrames",false);a(this,"queue",[]);a(this,"posting",false);a(this,"flushQueued",false);a(this,"heldTimer",null);a(this,"urgent",false);a(this,"unsubscribeTransport",null);a(this,"subscription",0);a(this,"wantsConnection",false);a(this,"connectAttempt",0);a(this,"leaveFrame",null);a(this,"pendingFrames",[]);a(this,"queuedBytes",0);a(this,"isDestroyed",false);a(this,"closed",false);this.endpoint=e.open(r=>this.receive(r),r=>this.lose(r)),this.enqueue({op:"create",seq:++this.seq,options:s.worker});}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return this.peerList}setCursor(e,t){this.isDestroyed||this.enqueue({op:"cursor",seq:++this.seq,cursor:e,broadcast:t});}onPeers(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.peerListeners.set(t,e),e(this.peers),()=>this.peerListeners.delete(t)}onStatus(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}connect(){if(this.isDestroyed||this.connectionStatus==="connected"||this.connectionStatus==="connecting")return;if(this.closed){this.report(this.options.makeError("replica","Collaboration replica is retired"));return}this.wantsConnection=true,this.floor=++this.seq,this.enqueue({op:"connect",seq:this.floor});let e=++this.connectAttempt;if(this.setStatus("connecting",false),!(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt)){if(!this.unsubscribeTransport){let t=++this.subscription,s;try{if(s=this.transport.onEvent(r=>this.forward(t,r)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(r){this.subscription+=1,this.fail(this.transportError("Failed to subscribe to transport events",r));return}if(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt||t!==this.subscription){try{s();}catch(r){this.isDestroyed||this.report(this.transportError("Failed to unsubscribe from stale transport events",r));}return}this.unsubscribeTransport=s;}try{let t=this.transport.connect();t&&t.catch(s=>{!this.isDestroyed&&this.wantsConnection&&this.connectAttempt===e&&this.fail(this.transportError("Transport connect failed",s));});}catch(t){this.fail(this.transportError("Transport connect failed",t));}}}disconnect(){if(this.isDestroyed)return;if(this.closed){this.setStatus("disconnected",false);return}if(!(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus!=="disconnected"))return;this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"disconnect",seq:this.floor});let t=this.release(true);this.setStatus("disconnected",false);for(let s of t)this.report(s);}destroy(){if(this.isDestroyed)return;let e=!this.closed&&(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus==="connecting"||this.connectionStatus==="connected");e&&this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"destroy",seq:this.floor});let t=this.closed?[]:this.release(e);this.isDestroyed=true,this.setStatus("destroyed",false);for(let s of t)this.report(s);this.statusListeners.clear(),this.errorListeners.clear(),this.peerListeners.clear();}transportError(e,t){return this.options.normalize("transport",e,t)}release(e){this.wantsConnection=false,this.connectAttempt+=1,this.leaveFrame=null,this.clearQueue(),this.clearPeers();let t=[],s=this.unsubscribeTransport;if(this.unsubscribeTransport=null,this.subscription+=1,s)try{s();}catch(r){t.push(this.transportError("Failed to unsubscribe from transport events",r));}if(!e)return t;try{let r=this.transport.disconnect();r&&r.catch(a=>{this.isDestroyed||this.report(this.transportError("Transport disconnect failed",a));});}catch(r){t.push(this.transportError("Transport disconnect failed",r));}return t}fail(e){if(this.isDestroyed||!this.wantsConnection)return;let t=e.code;this.floor=++this.seq,this.enqueue({op:"fail",seq:this.floor,error:{code:typeof t=="string"&&Y.includes(t)?t:"transport",message:e.message}});let s=this.release(true);this.setStatus("disconnected",false),this.report(e);for(let r of s)this.report(r);}sendLeave(){let e=this.leaveFrame;if(this.leaveFrame=null,!(!e||!this.options.hasUser||!this.unsubscribeTransport||this.connectionStatus!=="connected"))try{this.transport.send(e);}catch(t){this.report(this.transportError("Failed to send awareness leave",t));}}enqueue(e,t=false){this.closed||(this.queue.push(e),this.schedule(t));}schedule(e){if(e||(this.urgent=true),!(this.posting||this.flushQueued)){if(e){this.heldTimer??(this.heldTimer=setTimeout(()=>{this.heldTimer=null,this.flush();},j));return}this.flushQueued=true,queueMicrotask(()=>{this.flushQueued=false,this.flush();});}}flush(){if(this.posting||this.closed||this.queue.length===0)return;this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null);let e=this.queue;this.queue=[],this.urgent=false,this.posting=true;let t=e.some(a=>a.op==="destroy"),s=e.reduce((a,n)=>n.op==="event"&&n.event.type==="message"?a+n.event.data.byteLength+E:a,0),r;try{r=this.endpoint.post(e,a$1(e));}catch(a){r=Promise.reject(a);}r.then(()=>{this.posting=false,this.inboundBytes-=s,t?this.close():this.urgent?this.flush():this.queue.length>0&&this.schedule(true);},a=>{this.posting=false,this.inboundBytes-=s,this.lose(G(a));});}forward(e,t){if(!(this.closed||this.isDestroyed||e!==this.subscription))switch(t.type){case "message":if(this.inboundBytes===0?t.data.byteLength>this.options.maxPendingBytes:t.data.byteLength+E>this.options.maxPendingBytes-this.inboundBytes){this.fail(this.options.makeError("backpressure","Pending replica data exceeds the byte limit"));return}this.inboundBytes+=t.data.byteLength+E,this.enqueue({op:"event",seq:++this.seq,event:{type:"message",data:t.data.slice().buffer}},!this.isSynced&&K(t.data)&&this.inboundBytes<=this.options.maxPendingBytes/2);return;case "open":case "close":this.clearQueue(),t.type==="close"&&(this.connectAttempt+=1,this.leaveFrame=null),this.sendFloor=++this.seq,this.enqueue({op:"event",seq:this.sendFloor,event:t.type==="open"?{type:"open"}:{type:"close",...t.reason!==void 0&&{reason:t.reason}}}),t.type==="close"&&(this.clearPeers(),this.setStatus("disconnected",false));return;case "drain":this.flushPending();return;case "error":this.fail(this.transportError("Transport error",t.error));return;default:this.fail(this.options.makeError("transport","Unknown transport event"));}}receive(e){for(let t of e){if(this.closed||this.isDestroyed)return;if(t.do==="lost"){this.lose("Collaboration replica is retired");return}if(!(t.through<this.floor))switch(t.do){case "unsubscribe":{let s=this.release(false);for(let r of s)this.report(r);break}case "disconnect":{this.wantsConnection=false;let s=this.release(true);for(let r of s)this.report(r);break}case "send":t.through>=this.sendFloor&&this.send(new Uint8Array(t.data));break;case "leave":t.through>=this.sendFloor&&(this.leaveFrame=t.data?new Uint8Array(t.data):null);break;case "status":t.through>=this.sendFloor&&this.setStatus(t.status,t.synced);break;case "peers":{if(t.through<this.sendFloor||t.peers.length===0&&this.peerList.length===0)break;let s=this.options.rebasePeer,r=t.timeOrigin-d$1();this.peerList=s?t.peers.map(a=>s(a,r)):t.peers,this.emitPeers();break}case "error":this.report(this.options.makeError(t.error.code,t.error.message));break}}}send(e){if(!this.unsubscribeTransport)return;if(this.pendingFrames.length>0){this.queueFrame(e);return}let t=this.sendFloor,s;try{s=this.transport.send(e.slice());}catch(r){this.fail(this.transportError("Transport send failed",r));return}if(typeof s!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}!s&&this.unsubscribeTransport!==null&&t===this.sendFloor&&this.queueFrame(e);}queueFrame(e){if(e.byteLength>this.options.maxPendingBytes-this.queuedBytes){this.fail(this.options.makeError("backpressure",`Pending collaboration data exceeds ${this.options.maxPendingBytes} bytes`));return}this.pendingFrames.push(e),this.queuedBytes+=e.byteLength;}flushPending(){if(!this.flushingFrames){this.flushingFrames=true;try{for(;this.unsubscribeTransport&&this.pendingFrames.length>0;){let e=this.pendingFrames[0],t;try{t=this.transport.send(e.slice());}catch(s){this.fail(this.transportError("Transport send failed",s));return}if(typeof t!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}if(!t||this.pendingFrames[0]!==e)return;this.pendingFrames.shift(),this.queuedBytes-=e.byteLength;}}finally{this.flushingFrames=false;}}}clearQueue(){this.pendingFrames.length=0,this.queuedBytes=0;}lose(e){if(this.closed||(this.close(),this.isDestroyed))return;this.sendLeave();let t=this.release(this.wantsConnection||this.connectionStatus!=="disconnected");setTimeout(()=>{if(!this.isDestroyed){this.setStatus("disconnected",false),this.report(this.options.makeError("replica",e));for(let s of t)this.report(s);}},0);}close(){this.closed||(this.closed=true,this.queue=[],this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null),this.endpoint.close());}clearPeers(){this.peerList.length!==0&&(this.peerList=[],this.emitPeers());}setStatus(e,t){if(!(this.connectionStatus===e&&this.isSynced===t)){this.connectionStatus=e,t&&!this.isSynced&&this.queue.length>0&&this.schedule(false),this.isSynced=t;for(let[s,r]of [...this.statusListeners])if(this.statusListeners.get(s)===r)try{r({status:e,synced:t});}catch{}}}emitPeers(){let e=this.peers;for(let[t,s]of [...this.peerListeners])if(this.peerListeners.get(t)===s)try{s(e);}catch{}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};var Z=u,ee=1e3;function T(o,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${o} must be ${t?"a non-negative":"a positive"} integer`);return e}function te(o){return o instanceof Error&&o.message?o.message:typeof o=="string"&&o?o:"Unknown error"}function c(o,e,t){return t instanceof h?t:new h(o,`${e}: ${te(t)}`,t)}function d(o,e){if(!(o instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return o.slice()}function P(o){o.unref?.();}var X=new WeakMap,z=new WeakMap;function le(o){return X.get(o)()}function de(o){return z.get(o)()}var W=class{constructor(e,t,s={}){a(this,"replica");a(this,"piped");a(this,"asyncReplica");a(this,"replicaTail",Promise.resolve());a(this,"replicaBytes",0);a(this,"updateBatch",null);a(this,"syncArrival");a(this,"openEpoch",0);a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"awarenessListeners",new Map);a(this,"awarenessStore",new Map);a(this,"awarenessUser");a(this,"pendingFrames",[]);a(this,"unsubscribeReplica");a(this,"unsubscribeTransport",()=>{});a(this,"hasTransportSubscription",false);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"wantsConnection",false);a(this,"isOpen",false);a(this,"isDestroyed",false);a(this,"epoch",0);a(this,"connectAttempt",0);a(this,"nextListenerId",0);a(this,"queuedBytes",0);a(this,"isFlushing",false);a(this,"transportCleanup");a(this,"statusRevision",0);a(this,"awarenessClock",0);a(this,"reportedClockExhaustion",false);a(this,"awarenessCursor",null);a(this,"lastAwarenessSentAt",Number.NEGATIVE_INFINITY);a(this,"awarenessBroadcastTimer");a(this,"awarenessHeartbeatTimer");a(this,"awarenessExpiryTimer");a(this,"hasPublishedAwarenessForOpen",false);this.replica=e,this.asyncReplica=I(e),this.transport=t,this.maxFrameBytes=T("maxFrameBytes",s.maxFrameBytes??u,false),this.maxMessagesPerFrame=T("maxMessagesPerFrame",s.maxMessagesPerFrame??v,false),this.maxPendingBytes=T("maxPendingBytes",s.maxPendingBytes??Z,true),this.awarenessUser=o(s.user,e.clientId),X.set(this,()=>this.beginArrival()),z.set(this,()=>this.leaveFrame());let r=K$1(e);if(r){this.unsubscribeReplica=()=>{};let a;this.piped=new b(r,{connect:()=>this.connectPipedTransport(()=>a?.()),disconnect:()=>{this.wantsConnection=false,this.connectAttempt+=1;let n=this.cleanupTransport(()=>{},true);if(n.length)throw n[0]},send:n=>t.send(n),onEvent:n=>{if(!this.transportCleanup)return t.onEvent(n);let p=true,l=()=>{},u=()=>{a=void 0;try{let y=t.onEvent(n);if(typeof y!="function")throw new TypeError("Transport event subscription must return a function");p?l=y:y();}catch(y){throw c("transport","Failed to subscribe to transport events",y)}};return a=u,()=>{p=false,a===u&&(a=void 0),l();}}},{worker:{maxFrameBytes:this.maxFrameBytes,maxMessagesPerFrame:this.maxMessagesPerFrame,user:{...this.awarenessUser}},maxPendingBytes:this.maxPendingBytes,hasUser:true,makeError:(n,p,l)=>new h(n,p,l),normalize:c});return}try{this.unsubscribeReplica=e.onUpdate((a,n)=>{n==="local"&&this.forwardLocalUpdate(a);});}catch(a){throw c("replica","Failed to observe replica updates",a)}}get status(){return this.piped?this.piped.status:this.connectionStatus}get synced(){return this.piped?this.piped.synced:this.isSynced}get pendingBytes(){return this.piped?this.piped.pendingBytes:this.queuedBytes}get peers(){return this.piped?this.piped.peers:r(this.awarenessStore)}connect(){if(this.piped)return this.piped.connect();this.isDestroyed||this.isOpen||this.connectionStatus==="connecting"||(this.wantsConnection=true,this.setStatus("connecting",false),!(this.transportCleanup||this.isDestroyed||!this.wantsConnection)&&this.startConnection());}connectPipedTransport(e){this.wantsConnection=true;let t=++this.connectAttempt;return this.transportCleanup?this.transportCleanup.then(()=>{if(!(this.isDestroyed||!this.wantsConnection||t!==this.connectAttempt)&&(e(),!(this.isDestroyed||!this.wantsConnection||t!==this.connectAttempt)))return this.transport.connect()}):this.transport.connect()}startConnection(){if(this.isDestroyed||!this.wantsConnection||this.isOpen||this.transportCleanup)return;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let s;try{if(s=this.transport.onEvent(r=>this.handleTransportEvent(e,r)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(r){this.failConnection(e,c("transport","Failed to subscribe to transport events",r));return}if(!this.isCurrent(e)){try{s();}catch(r){this.isDestroyed||this.report(c("transport","Failed to unsubscribe from stale transport events",r));}return}this.unsubscribeTransport=s,this.hasTransportSubscription=true;}try{let s=this.transport.connect();s&&s.catch(r=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,c("transport","Transport connect failed",r));});}catch(s){this.failConnection(e,c("transport","Transport connect failed",s));}}}disconnect(){if(this.piped)return this.piped.disconnect();if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.clearPending(),this.resetReplicaQueue(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let r of s)this.report(r);}destroy(){if(this.piped){this.isDestroyed=true,this.piped.destroy(),this.errorListeners.clear();return}if(this.isDestroyed)return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.clearPending(),this.resetReplicaQueue(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),s=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let r of s)this.report(r);try{this.unsubscribeReplica();}catch(r){this.report(c("replica","Failed to unsubscribe from replica updates",r));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.awarenessListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");if(this.piped)return this.piped.onStatus(e);let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("error listener must be a function");let t=this.piped?.onError(e),s=this.nextListenerId++;return this.errorListeners.set(s,e),()=>{t?.(),this.errorListeners.delete(s);}}onAwareness(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("awareness listener must be a function");if(this.piped)return this.piped.onPeers(s=>{try{e(s);}catch{}});let t=this.nextListenerId++;this.awarenessListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.awarenessListeners.delete(t)}setCursor(e){if(this.isDestroyed)return;let t$1=e?t(e):false;if(this.awarenessCursor=e&&t$1?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null,e&&!t$1&&this.report(new h("protocol",`Awareness cursor needs a sheet identifier of 1 to ${256} characters and non-negative cell coordinates; cursor dropped`)),this.piped){this.piped.setCursor(this.awarenessCursor,true);return}if(!this.isOpen||!this.wantsConnection)return;let s=80-(Date.now()-this.lastAwarenessSentAt);if(s<=0){this.publishAwareness();return}this.awarenessBroadcastTimer||(this.awarenessBroadcastTimer=setTimeout(()=>{this.awarenessBroadcastTimer=void 0,this.publishAwareness();},s),P(this.awarenessBroadcastTimer));}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.resetReplicaQueue(),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let s=this.takeTransportSubscription();this.clearPending();let r=this.cleanupTransport(s,true);this.setStatus("disconnected",false),this.report(t);for(let a of r)this.report(a);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let s=[];try{e();}catch(r){s.push(c("transport","Failed to unsubscribe from transport events",r));}if(!t||this.transportCleanup)return s;try{let r=this.transport.disconnect();if(r){let a=!1,n=Promise.resolve(r).catch(p=>{a=!0,this.isDestroyed||this.report(c("transport","Transport disconnect failed",p));}).finally(()=>{this.transportCleanup===n&&(a&&!this.isDestroyed&&(this.wantsConnection=!1,this.piped?.disconnect()),this.transportCleanup=void 0,!this.isDestroyed&&(a?this.piped||this.setStatus("disconnected",!1):this.wantsConnection&&!this.piped&&this.startConnection()));});this.transportCleanup=n;}}catch(r){s.push(c("transport","Transport disconnect failed",r));}return s}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.handleMessage(e,t.data);break;case "close":this.resetReplicaQueue(),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isOpen=false,this.connectAttempt+=1,this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,c("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new h("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen)return;let t=++this.openEpoch;if(this.replicaTail=Promise.resolve(),this.replicaBytes=0,this.updateBatch=null,this.isOpen=true,this.hasPublishedAwarenessForOpen=false,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen)return;if(this.asyncReplica){Promise.resolve().then(()=>{if(this.isCurrentOpen(e,t))return this.asyncReplica.encodeStateVector()}).then(a=>{this.isCurrentOpen(e,t)&&this.sendHandshake(e,d(a,"encodeStateVector"),t);}).catch(a=>{this.isCurrentOpen(e,t)&&this.failConnection(e,c("replica","Failed to encode replica state vector",a));});return}let s;try{s=d(this.replica.encodeStateVector(),"encodeStateVector");}catch(r){this.failConnection(e,c("replica","Failed to encode replica state vector",r));return}this.sendHandshake(e,s,t);}sendHandshake(e,t,s){if(!this.isCurrentOpen(e,s))return;let r;try{r=F(t),this.sendFrame(x(r??t,this.maxFrameBytes));}catch(a){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",a));return}if(!r&&this.isCurrentOpen(e,s)&&this.sendFullUpdate(e,s),!!this.isCurrentOpen(e,s)){try{this.sendFrame(B(this.maxFrameBytes));}catch(a){this.report(c("protocol","Failed to encode awareness query",a));}this.isCurrentOpen(e,s)&&(this.hasPublishedAwarenessForOpen||this.publishAwareness(),this.isCurrentOpen(e,s)&&this.startAwarenessTimers());}}sendFullUpdate(e,t){let s=n=>{if(this.isCurrentOpen(e,t))try{this.sendFrame(z$1(n,this.maxFrameBytes));}catch(p){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",p));}},r=n=>{this.isCurrentOpen(e,t)&&this.failConnection(e,c("replica","Failed to encode replica update",n));};if(this.asyncReplica){this.asyncReplica.encodeStateAsUpdate().then(n=>d(n,"encodeStateAsUpdate")).then(s,r);return}let a;try{a=d(this.replica.encodeStateAsUpdate(),"encodeStateAsUpdate");}catch(n){r(n);return}s(a);}handleMessage(e,t,s){let r;try{if(!(t instanceof Uint8Array))throw new TypeError("Frame must be a Uint8Array");if(t.byteLength>this.maxFrameBytes)throw new RangeError(`Frame exceeds ${this.maxFrameBytes} bytes`);r=s??H(t,this.maxFrameBytes,this.maxMessagesPerFrame);}catch(a){this.failConnection(e,c("protocol","Invalid collaboration frame",a));return}if(this.asyncReplica&&!s){let a=[];for(let n of r){if(!this.isCurrent(e)||!this.isOpen)return;n.type==="sync-step-1"||n.type==="sync-step-2"||n.type==="update"?a.push(n):this.handleMessage(e,new Uint8Array,[n]);}a.length&&this.isCurrent(e)&&this.isOpen&&(this.asyncReplica.applyUpdateChunks&&a.every(n=>n.type==="update")?this.enqueueRemoteUpdates(e,t.byteLength,a.map(n=>n.update)):this.enqueueReplicaMessages(e,t.byteLength,a));return}for(let a of r){if(!this.isCurrent(e)||!this.isOpen)return;switch(a.type){case "sync-step-1":this.respondToSyncStep1(e,a.stateVector);break;case "sync-step-2":{let n=this.syncArrival,p=this.syncArrival={deferred:false};try{this.applyRemoteUpdate(e,a.update)&&this.isCurrent(e)&&!p.deferred&&this.setStatus("connected",!0);}finally{this.syncArrival=n;}break}case "update":this.applyRemoteUpdate(e,a.update);break;case "awareness":try{let n=[],p$1=0,l=p(this.awarenessStore,C(a.update,w,u=>n.push(u)),this.replica.clientId,Date.now(),{onPeersDiscarded:u=>{p$1=u;}});for(let u of n)this.report(c("protocol","Invalid awareness update",u));if(p$1>0&&this.report(new h("protocol",`${p$1} awareness ${p$1===1?"entry was":"entries were"} discarded because the tracked peer limit of ${1024} was reached`)),!this.isCurrent(e)||!this.isOpen)return;l&&this.emitAwareness();}catch(n){this.report(c("protocol","Invalid awareness update",n));}break;case "auth":this.failConnection(e,new h("protocol",a.reason?`Authentication denied: ${a.reason}`:"Authentication denied"));return;case "query-awareness":this.publishAwareness();break}}}isCurrentOpen(e,t){return this.isCurrent(e)&&this.isOpen&&t===this.openEpoch}resetReplicaQueue(){this.openEpoch+=1,this.replicaTail=Promise.resolve(),this.replicaBytes=0,this.updateBatch=null;}enqueueReplicaMessages(e,t,s){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new h("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t,this.updateBatch=null;let r=this.openEpoch,a=this.replicaTail.then(async()=>{for(let n of s){if(!this.isCurrentOpen(e,r))return;try{if(n.type==="sync-step-1"){let p=G$1(n.stateVector),l=await this.asyncReplica.encodeStateAsUpdate(D(p.stateVector).slice());if(!this.isCurrentOpen(e,r))return;if(this.sendFrame(y(d(l,"encodeStateAsUpdate"),this.maxFrameBytes)),p.open&&this.isCurrentOpen(e,r)){let u=d(await this.asyncReplica.encodeStateVector(),"encodeStateVector");this.isCurrentOpen(e,r)&&this.sendFrame(x(u,this.maxFrameBytes));}}else (n.type==="sync-step-2"||n.type==="update")&&(await this.asyncReplica.applyUpdate(D(n.update).slice()),n.type==="sync-step-2"&&this.isCurrentOpen(e,r)&&this.setStatus("connected",!0));}catch(p){this.isCurrentOpen(e,r)&&this.failConnection(e,c("replica","Async replica operation failed",p));return}}}).finally(()=>{r===this.openEpoch&&(this.replicaBytes-=t);});this.replicaTail=a.catch(()=>{});}enqueueRemoteUpdates(e,t,s){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new h("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t;let r=this.openEpoch,a=s.map(u=>D(u).slice()),n=this.updateBatch;if(n?.connection===r){n.updates.push(...a),n.bytes+=t;return}let p={connection:r,bytes:t,updates:a};this.updateBatch=p;let l=this.replicaTail.then(async()=>{if(this.updateBatch===p&&(this.updateBatch=null),!!this.isCurrentOpen(e,r))try{p.updates.length===1?await this.asyncReplica.applyUpdate(p.updates[0]):await this.asyncReplica.applyUpdateChunks(p.updates);}catch(u){this.isCurrentOpen(e,r)&&this.failConnection(e,c("replica","Async replica operation failed",u));}}).finally(()=>{r===this.openEpoch&&(this.replicaBytes-=p.bytes);});this.replicaTail=l.catch(()=>{});}respondToSyncStep1(e,t){let s=G$1(t),r;try{r=d(this.replica.encodeStateAsUpdate(D(s.stateVector).slice()),"encodeStateAsUpdate");}catch(n){this.failConnection(e,c("replica","Failed to encode replica update",n));return}try{this.sendFrame(y(r,this.maxFrameBytes));}catch(n){this.failConnection(e,c("protocol","Failed to encode SyncStep2",n));return}if(!s.open||!this.isCurrent(e)||!this.isOpen)return;let a;try{a=d(this.replica.encodeStateVector(),"encodeStateVector");}catch(n){this.failConnection(e,c("replica","Failed to encode replica state vector",n));return}try{this.sendFrame(x(a,this.maxFrameBytes));}catch(n){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",n));}}beginArrival(){let e=this.epoch,t=this.openEpoch,s=this.syncArrival;s&&(s.deferred=true);let r=false,a=n=>{r||(r=true,this.isCurrentOpen(e,t)&&n());};return {settle:()=>a(()=>{s&&this.setStatus("connected",true);}),fail:n=>a(()=>this.failConnection(e,c("replica","Failed to apply remote update",n)))}}leaveFrame(){if(!this.isOpen||this.isDestroyed||!this.wantsConnection||this.awarenessClock>=Number.MAX_SAFE_INTEGER)return null;try{let e=this.awarenessClock+1;return {clock:e,frame:A([{clientId:this.replica.clientId,clock:e,state:null}],this.maxFrameBytes)}}catch{return null}}applyRemoteUpdate(e,t){try{return this.replica.applyUpdate(D(t).slice()),!0}catch(s){return this.failConnection(e,c("replica","Failed to apply remote update",s)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,s;try{s=d(e,"Replica update");}catch(r){this.failConnection(t,c("replica","Invalid replica update",r));return}try{this.sendFrame(z$1(s,this.maxFrameBytes));}catch(r){this.failConnection(t,c("protocol","Failed to encode update",r));}}publishAwareness(e="current",t="queued"){if(!(!this.isOpen||this.isDestroyed||!this.wantsConnection)){if(this.awarenessBroadcastTimer&&(clearTimeout(this.awarenessBroadcastTimer),this.awarenessBroadcastTimer=void 0),this.awarenessClock>=Number.MAX_SAFE_INTEGER){t==="queued"&&!this.reportedClockExhaustion&&(this.reportedClockExhaustion=true,this.report(new h("protocol","Awareness clock exhausted")));return}this.awarenessClock+=1;try{this.hasPublishedAwarenessForOpen=!0;let s=A([{clientId:this.replica.clientId,clock:this.awarenessClock,state:e===null?null:{user:this.awarenessUser,cursor:this.awarenessCursor}}],this.maxFrameBytes);t==="best-effort"?this.sendBestEffort(s):this.sendFrame(s),this.lastAwarenessSentAt=Date.now();}catch(s){t==="queued"&&this.report(c("protocol","Failed to encode awareness update",s));}}}startAwarenessTimers(){this.stopAwarenessTimers(),this.awarenessHeartbeatTimer=setInterval(()=>{this.publishAwareness();},2e4),this.awarenessExpiryTimer=setInterval(()=>{q(this.awarenessStore,Date.now(),45e3)&&this.emitAwareness();},ee),P(this.awarenessHeartbeatTimer),P(this.awarenessExpiryTimer);}stopAwarenessTimers(){this.awarenessBroadcastTimer&&clearTimeout(this.awarenessBroadcastTimer),this.awarenessHeartbeatTimer&&clearInterval(this.awarenessHeartbeatTimer),this.awarenessExpiryTimer&&clearInterval(this.awarenessExpiryTimer),this.awarenessBroadcastTimer=void 0,this.awarenessHeartbeatTimer=void 0,this.awarenessExpiryTimer=void 0;}clearAwarenessPeers(){if(this.awarenessStore.size===0)return;let e=this.peers.length>0;this.awarenessStore.clear(),e&&this.emitAwareness();}emitAwareness(){let e=this.peers;for(let[t,s]of [...this.awarenessListeners])if(this.awarenessListeners.get(t)===s)try{s(e);}catch{}}sendFrame(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let t=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(t,e);return}let s;try{s=this.transport.send(e.slice());}catch(r){this.failConnection(t,c("transport","Transport send failed",r));return}if(typeof s!="boolean"){this.failConnection(t,new h("transport","Transport send must return a boolean"));return}!s&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}sendBestEffort(e){try{this.transport.send(e.slice());}catch{}}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new h("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let s=t.slice();this.pendingFrames.push(s),this.queuedBytes+=s.byteLength;}flushPending(){if(!this.isFlushing){this.isFlushing=true;try{for(;this.isOpen&&!this.isDestroyed&&this.pendingFrames.length>0;){let e=this.epoch,t=this.pendingFrames[0],s;try{s=this.transport.send(t.slice());}catch(r){this.failConnection(e,c("transport","Transport send failed",r));return}if(typeof s!="boolean"){this.failConnection(e,new h("transport","Transport send must return a boolean"));return}if(!s||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(e,t){if(this.connectionStatus===e&&this.isSynced===t)return;this.connectionStatus=e,this.isSynced=t;let s=++this.statusRevision,r={status:e,synced:t};for(let[a,n]of [...this.statusListeners]){if(this.statusRevision!==s)return;if(this.statusListeners.get(a)===n)try{n(r);}catch{}}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};export{h as a,le as b,de as c,W as d};
@@ -1 +0,0 @@
1
- import {g,_,h,j,P,J,G,L,H,I,z,ba,M,O,N,n,x,A,f,d,F,k,T,X,Q,U}from'./chunk-K7TMSGNA.js';import {a as a$1,L as L$1,J as J$1}from'./chunk-JGTBRHCP.js';import {a}from'./chunk-O2XFH626.js';var Po=new WeakMap;function Ko(o){Po.get(o)?.fence();}function Wo(o,n){return Po.get(o)?.cancel(n)??[]}function go(){let o=new Map,n=Array.from({length:11},()=>new Map);function p(f,F){o.set(f,F);let E=f;for(let x of n){let O=Math.floor(E/32),M=x.get(O)??0;if(x.set(O,M|1<<E%32),M!==0)break;E=O;}}function m(f){if(!o.delete(f))return;let F=f;for(let E of n){let x=Math.floor(F/32),O=(E.get(x)??0)&~(1<<F%32);if(O!==0){E.set(x,O);break}E.delete(x),F=x;}}function*W(f,F){let E=n[f].get(F)??0;for(;E!==0;){let x=31-Math.clz32(E&-E),O=F*32+x;f===0?yield o.get(O):yield*W(f-1,O),E&=E-1;}}return {set:p,delete:m,values:()=>W(n.length-1,0)}}function wo(){return {size:0,lanes:{input:go(),collab:go(),background:go()}}}function Qo(o){let n=new Map,p=new WeakMap,m=new Map,W=new Set,f=wo(),F=f,E,x=0,O=Number.isSafeInteger(o.inputBurstCap)&&o.inputBurstCap>0?o.inputBurstCap:8,M=0;function S(){if(F.size===0)return;let s=wo();F.next=s,F=s;}function w(s){s.segment.lanes[Ue(s.entry.draft)].set(s.order,s);}function Q(s,y){let k=s.entry.draft,P=y.options.after,T=P&&p.get(P)===p.get(s.tickets[0])?{...y,options:{...y.options,after:k.options.after}}:y,a=wt(k,T)?o.coalesce?.(k,T):void 0;return a&&Ue(a)===Ue(k)&&a.options.after===k.options.after&&!a.options.fence?a:void 0}function j(s,y){let k=E?.segment===F?E:void 0,P=k&&Q(k,s);if(P&&k)return k.tickets.push(y),k.entry={id:k.entry.id,draft:P,tickets:k.tickets},p.set(y,p.get(k.tickets[0])),k.entry;if(s.options.fence&&S(),x===Number.MAX_SAFE_INTEGER)throw new RangeError("Outbox order space is exhausted");let T=[y],a={id:y.id,draft:s,tickets:T},h={entry:a,tickets:T,segment:F,order:++x,previous:E};E&&(E.next=h),E=h,n.set(a.id,h),p.set(y,{id:a.id}),F.size+=1;let g=s.options.after;if(g){h.afterId=p.get(g)?.id??g.id;let R=m.get(h.afterId);R||m.set(h.afterId,R=new Set),R.add(h);}return (!g||!n.has(h.afterId))&&w(h),s.options.fence&&S(),a}function D(s){if(n.delete(s.entry.id),s.segment.lanes[Ue(s.entry.draft)].delete(s.order),s.segment.size-=1,s.previous&&(s.previous.next=s.next),s.next&&(s.next.previous=s.previous),E===s&&(E=s.previous),s.afterId!==void 0){let k=m.get(s.afterId);k?.delete(s),k?.size===0&&m.delete(s.afterId);}let y=m.get(s.entry.id);if(y)for(let k of y)w(k);for(;f.size===0&&f.next;)f=f.next;n.size===0&&(M=0);}function I(s,y,k){for(let P of f.lanes[s].values()){if(k?.(P.entry))return;let T=P.entry.draft.options.after;if(!(T&&(n.has(P.afterId)||T.seq===void 0))&&y(P.entry))return P}}function L(s,y){for(;f.size===0&&f.next;)f=f.next;let P=(M>=O?I("collab",s,y):void 0)??I("input",s,y)??I("collab",s,y)??I("background",s,y);if(!P)return;let T=Ue(P.entry.draft)==="input"?Math.min(O,M+1):0;return D(P),M=T,P.entry}function Z(s,y){let k=s.map(P=>p.get(P)?.id??P.id);for(let P=0;P<k.length;P+=1){let T=m.get(k[P]);if(T)for(let a of T)y.has(a)||(y.add(a),k.push(a.entry.id));}}function H(s){for(let k of s){let P=p.get(k)?.id??k.id,T=m.get(P);T&&(W.add(T.values()),m.delete(P));}let y=[];for(;W.size&&y.length<64;){let k=W.values().next().value,P=k.next();if(P.done){W.delete(k);continue}let T=P.value;if(!n.has(T.entry.id))continue;let a=m.get(T.entry.id);a&&(W.add(a.values()),m.delete(T.entry.id)),y.push(T.entry),D(T);}return y}function te(s){let y=new Set,k=[];for(let T of n.values())s(T.entry)&&(y.add(T),k.push(T.tickets[0]));Z(k,y);let P=[];for(let T of n.values())y.has(T)&&(P.push(T.entry),D(T));return P}let l={get size(){return n.size},get entries(){return [...n.values()].map(s=>s.entry)},enqueue:j,takeNext:L,remove:te,clear(){let s=[...n.values()].map(y=>y.entry);return n.clear(),p=new WeakMap,m.clear(),W.clear(),f=wo(),F=f,E=void 0,M=0,s}};return Po.set(l,{fence:S,cancel:H}),l}function Ue(o){return o.options.lane??"input"}function wt(o,n){let p=o.options,m=n.options;return !p.fence&&!m.fence&&p.coalesceKey!==void 0&&p.coalesceKey===m.coalesceKey&&o.kind===n.kind&&Ue(o)===Ue(n)&&p.group===m.group&&p.after?.id===m.after?.id&&(p.expectVersion??false)===(m.expectVersion??false)}function $o(o){let n=Number.isSafeInteger(o.maxEchoEntries)&&o.maxEchoEntries>=0?o.maxEchoEntries:64,p=o.now??Date.now,m=new Map,W=new Set,f=[],F=-1,E=-1,x=-1,O,M,S=0,w=false,Q=0,j=0;function D(a){Q===0&&(j=0),Q+=1;try{return a()}finally{Q-=1;}}function I(a,h){let g=L(),R=j;try{return h(),!0}catch{return false}finally{let $=Math.max(0,L()-g);if(j=R+$,j>2)try{o.onEchoOverrun?.({hook:a,elapsedMs:$,eventTotalMs:j});}catch{}}}function L(){try{let a=p();return Number.isFinite(a)?a:0}catch{return 0}}function Z(a,h){let g=m.get(a);g&&(m.delete(a),g.resolve(h));}function H(a){W.has(a)||(W.size>=256&&W.delete(W.values().next().value),W.add(a)),Z(a,"dropped");}function te(a){return D(()=>{if(w||n===0)return !1;if(f.length>=n){if(o.echoOverflow!=="evict-oldest")return !1;f=f.slice(f.length-n+1);}return f=[...f,a],o.echo&&I("paint",()=>o.echo.paint(f)),!0})}function l(a){return D(()=>{if(w)return !1;let h=[...f,...a].sort((g,R)=>g.ticket.id-R.ticket.id);return h.length>n?!1:(f=h,a.length>0&&o.echo&&I("paint",()=>o.echo.paint(f)),!0)})}function s(a,h){D(()=>{if(w)return;let g=new Set(a.map(ae=>ae.id)),R=f.filter(ae=>!g.has(ae.ticket.id)),$=R.length!==f.length;h!==void 0&&n>0&&R.length>=n&&o.echoOverflow==="evict-oldest"&&(R=R.slice(R.length-n+1));let B=h!==void 0&&R.length<n;f=B?[...R,h]:R,($||B)&&o.echo&&I("paint",()=>o.echo.paint(f));});}function y(a,h){D(()=>{if(w)return;let g=new Set(a.map($=>$.id)),R=f.filter($=>g.has($.ticket.id));f=f.filter($=>!g.has($.ticket.id));for(let $ of R){let B=$.seq??$.ticket.seq;B!==void 0&&H(B);}for(let $ of a)$.seq!==void 0&&H($.seq);R.length>0&&o.echo&&I("drop",()=>o.echo.drop(R,h));});}function k(a,h,g){let R=[],$=[];for(let ne of f){let r=ne.seq??ne.ticket.seq;(!h&&r!==void 0&&r<=a.coversThroughSeq?R:$).push(ne);}let B=M,ae=S;M={coverage:a.coversThroughSeq,revision:a.revision};try{if(!g(R,$)||w||ae!==S)return "stale";if(F=Math.max(F,a.coversThroughSeq),O=O===void 0?a.revision:Math.max(O,a.revision),h)return "presented";let ne=new Set(R);f=f.filter(A=>!ne.has(A));let r=Math.min(F,a.coversThroughSeq);x=Math.max(x,r);for(let A of m.keys())A<=r&&Z(A,W.has(A)?"dropped":"presented");return E=Math.max(E,r),"presented"}finally{ae===S&&(M=B);}}function P(a){return D(()=>{let h=!1;function g(R,$){return o.echo?I("present",()=>{let ae=o.echo.present(a,R,$);h=!o.transactionalPresentation||ae!==!1;})&&h:(h=!0,!0)}try{let R=a.coversThroughSeq===F;if(w||a.coversThroughSeq<F||R&&(!o.sameCoverageFrames||F<0||O===void 0||a.revision<=O)||M&&(a.coversThroughSeq<M.coverage||a.coversThroughSeq===M.coverage&&(!o.sameCoverageFrames||a.revision<=M.revision)))return "stale";if(a.baseRevision!==void 0&&a.baseRevision!==O)return o.requestFullFrame(),"base-mismatch";if(o.transactionalPresentation&&o.echo)return k(a,R,g);if(R)return O=a.revision,g([],f),w?"stale":"presented";let $=[],B=[],ae=F,ne=x;for(let X of f){let Y=X.seq??X.ticket.seq;(Y!==void 0&&Y<=a.coversThroughSeq?$:B).push(X);}f=B,F=a.coversThroughSeq,O=a.revision;let r=g($,B);if(w)return "stale";let A=Math.min(F,a.coversThroughSeq);if(r&&(x=Math.max(x,A)),!r)for(let X of $){let Y=X.seq??X.ticket.seq;Y!==void 0&&Y<=a.coversThroughSeq&&(x===ne||Y>x)&&H(Y);}for(let X of m.keys())X>A||(r?Z(X,W.has(X)?"dropped":"presented"):X>ae&&H(X));if(!r)for(let X=Math.max(ae+1,x+1,A-256+1);X<=A;X+=1)H(X);return E=Math.max(E,A),"presented"}finally{if(!h)try{o.discardFrame?.(a);}catch{}}})}function T(a){if(w||W.has(a))return Promise.resolve("dropped");if(a<=E)return Promise.resolve("presented");let h=m.get(a);if(h)return h.promise;m.size>=1024&&H(m.keys().next().value);let g,R=new Promise($=>{g=$;});return m.set(a,{promise:R,resolve:g}),R}return {get presentedThroughSeq(){return F},get revision(){return O},get pending(){return f.slice()},event:D,add:te,attach:l,replace:s,drop:y,present:P,whenPresented:T,reset(){w||(S+=1,M=void 0,F=-1,E=-1,x=-1,O=void 0);},dispose(){D(()=>{if(w)return;w=!0;let a=f;f=[];for(let h of m.keys())Z(h,"dropped");W.clear(),a.length>0&&o.echo&&I("drop",()=>o.echo.drop(a,"disposed"));});}}}var Pt=4096;function Go(){let o=[];function n(m){let W=0,f=o.length;for(;W<f;){let F=Math.floor((W+f)/2),E=o[F];if(m<E[0])f=F;else if(m>E[1])W=F+1;else return true}return false}function p(m){let W=0;for(;W<o.length&&o[W][1]<m-1;)W+=1;let f=o[W];if(f&&f[0]<=m+1){f[0]=Math.min(f[0],m),f[1]=Math.max(f[1],m);let F=o[W+1];F&&F[0]<=f[1]+1&&(f[1]=Math.max(f[1],F[1]),o.splice(W+1,1));return}if(o.length===Pt)throw new g("out-of-memory","Command replay ledger exhausted: 4096 disjoint ranges per epoch");o.splice(W,0,[m,m]);}return {contains:n,add:p,values(){let m=[];for(let[W,f]of o)for(let F=W;F<=f;F+=1)m.push(F);return m},clear(){o.length=0;}}}function Le(){let o,n,p=new Promise((m,W)=>{o=m,n=W;});return p.catch(()=>{}),{promise:p,resolve:o,reject:n}}function me(o){return o instanceof g?o:new g("crash",o instanceof Error?o.message:String(o))}function Eo(o){return o.code==="crash"||o.code==="trap"||o.code==="out-of-memory"||o.code==="silence"}function Ae(o){return o?.status==="refused"||o?.status==="cancelled"}function $e(o){return o?.status==="applied"&&o.committed!==false}function Jo(o,n){return o!==void 0&&Number.isSafeInteger(o)&&o>0?o:n}function Yo(o){let n=o.connection.initial,p=o.maxRecoveryAttempts===0?0:Jo(o.maxRecoveryAttempts,2),m=p===0?void 0:Q(o.source),W=n.session,f=n.epoch,F=Jo(o.maxInFlight,4),E=o.enqueue??queueMicrotask,x=new WeakMap,O=new WeakMap,M=new Set,S=new Set,w=new Map,Q$1=new Map,j=new Set,D=false,I,L=new Map,Z=new Map,H=new Map,te=Go(),l=new Map,s=0,y=n.throughSeq,k=n.incarnation,P,T$1,a={epoch:f,version:n.version,throughSeq:n.throughSeq,presentedThroughSeq:-1,selection:n.selection,editState:n.editState},h=false,g$1,R=false,$=false,B=false,ae=-1,ne=true,r=n.throughSeq,A=0,X$1,Y=0,b=n.throughSeq,V=n.throughSeq,se=n.throughSeq,ke=n.revisions?.selection??0,Se=n.revisions?.layout??0,re=0,le=0,ve=0,pe=new Set,ce=o.holdTimeoutMs??2e3;if(!Number.isFinite(ce)||ce<0)throw new TypeError("Invalid hold timeout");let We=o.now??Date.now,Je=o.timer??((e,t)=>{let c=setTimeout(e,t);return ()=>{clearTimeout(c);}}),Xe=new Map,Oe=new Set,ge=new Set,Ce=Qo({inputBurstCap:o.inputBurstCap,coalesce:o.coalesce}),G=$o({echo:o.echo&&{paint:e=>o.echo.paint(e),drop:(e,t)=>o.echo.drop(e,t),present(e,t,c){ne=false;let d=o.echo.present(e,t,c);return ne=!o.transactionalPresentation||d!==false,d}},maxEchoEntries:o.maxEchoEntries,now:o.now,sameCoverageFrames:o.sameCoverageFrames,transactionalPresentation:o.transactionalPresentation,echoOverflow:o.echoOverflow,discardFrame:i,onEchoOverrun:o.onEchoOverrun,requestFullFrame:()=>lt(r,A)});function ie(e){return !h&&!g$1&&e.active&&T$1===e}function _(e,t){e.done||(e.done=true,Oe.delete(e),ge.delete(e),e.cleanup(),t instanceof g?e.result.reject(t):e.result.resolve(t));}function Ee(e,t){return {ok:false,refusal:{code:e,...t===void 0?{}:{detail:t}}}}function be(){if(h||g$1||R)return;let e=T$1;if(!(!e||!ie(e)))for(let t of ge){if(!ie(e)||R)return;if(t.signal?.aborted){_(t,Ee("superseded","aborted"));continue}let c=false;for(let N of M)if(N.ticket.id<=t.watermark&&N.seq===void 0&&!N.ackSettled){c=true;break}if(c)continue;ge.delete(t);let d=e.connection.client.call.query;if(!d){_(t,Ee("unsupported"));continue}let v={session:W,incarnation:k,epoch:f,afterSeq:y>e.seenMark?y:e.seenSeq},u=++t.attempt;t.connection=e;let C=()=>!t.done&&t.attempt===u&&ie(e);try{d.call(e.connection.client.call,v,t.kind,t.args).then(N=>{if(!C())return;if(!X(N)||N.ok&&(N.at.incarnation!==v.incarnation||N.at.epoch!==v.epoch||N.at.throughSeq<v.afterSeq)){he(new g("message","Malformed or unfenced query reply"));return}let J=o.queries[t.kind].stale;N.ok&&J!=="answer-at-fence"&&J.reject.some(ee=>(ee==="doc"?a.version:ee==="selection"?ke:Se)>N.at[ee])?_(t,Ee("superseded")):_(t,N);},N=>{C()&&he(me(N));}).catch(N=>{C()&&he(me(N));});}catch(N){C()&&he(me(N));}}}function mo(e,t={}){let c=h||g$1!==void 0,d={hold:void 0,opened:We(),waiters:new Set},v=t.signal,u={reason:e,get released(){return c},release(){if(!c){c=true,Xe.delete(u),v?.removeEventListener("abort",u.release);for(let C of d.waiters)C();d.waiters.clear();}}};return d.hold=u,c||(Xe.set(u,d),v?.aborted?u.release():v?.addEventListener("abort",u.release,{once:true})),u}function Te(e,t,c={}){let d$1=Le(),v={kind:e,args:t,watermark:s,attempt:0,done:false,signal:c.signal,result:d$1,cleanup:()=>{}},u=[...Xe.values()].filter(ee=>ee.hold!==c.within),C=new Map,N=c.signal,J=()=>_(v,Ee("superseded","aborted"));if(v.cleanup=()=>{N?.removeEventListener("abort",J);for(let[ee,fe]of C)ee.waiters.delete(fe.release),fe.cancel();C.clear();},Oe.add(v),h)_(v,Ee("disposed"));else if(g$1)_(v,g$1);else if(!o.queries||!d(o.queries,e)||!T$1?.connection.client.call.query)_(v,Ee("unsupported"));else if(N?.aborted)J();else if(u.some(ee=>We()-ee.opened>=ce))_(v,Ee("busy"));else if(N?.addEventListener("abort",J,{once:true}),u.length===0)ge.add(v),be();else for(let ee of u){let fe=()=>{if(N?.aborted){J();return}if(We()-ee.opened>=ce){_(v,Ee("busy"));return}C.get(ee).cancel(),C.delete(ee),ee.waiters.delete(fe),C.size===0&&!v.done&&(v.watermark=s,ge.add(v),be());},De={release:fe,cancel:()=>{}};C.set(ee,De),ee.waiters.add(fe),De.cancel=Je(()=>_(v,Ee("busy")),Math.max(0,ce-(We()-ee.opened)));}return d$1.promise}function Ye(){for(let e of Xe.keys())e.release();}function i(e){if(e!==void 0)try{o.discardFrame?.(e);}catch{}}function q(){a={...a,presentedThroughSeq:G.presentedThroughSeq};let e=a;for(let t of [...S]){if(h||g$1||a!==e)break;if(S.has(t))try{t(e);}catch{}}}function K(e){!e.ackSettled||!e.presentationSettled||e.released||(e.released=true,M.delete(e));}function z(e,t){e.presentationSettled||(e.presentationSettled=true,O.delete(e),e.presentation.resolve(t),e.seq!==void 0&&(L.delete(e.seq),Z.delete(e.seq),H.get(e.seq)?.resolve(t),H.delete(e.seq)),K(e));}function oe(e,t){e.ackSettled||(e.ackSettled=true,e.outcome=t,e.ack.resolve(t),K(e));}function Fe(){let e=Le(),t=Le(),c={ticket:{id:++s,get seq(){return x.get(c.ticket).seq},get ack(){return x.get(c.ticket).ack.promise},get presented(){return x.get(c.ticket).presentation.promise}},ack:e,presentation:t,ackSettled:false,presentationSettled:false};return x.set(c.ticket,c),M.add(c),c}function de(e,t){for(let c of e){let d=x.get(c);oe(d,{seq:d.seq,status:"cancelled",reason:t}),z(d,"dropped");}G.drop(e,t);}function ye(e,t=false){let c=Wo(Ce,e);for(;;){if(de(c.map(d=>d.tickets[0]),"dependency-refused"),c.length<64){ge.size&&be();return}if(!t){ue(()=>ye([]));return}c=Wo(Ce,[]);}}function ue(e){try{E(()=>{if(!(h||g$1))try{G.event(e);}catch(t){we(me(t));}});}catch(t){we(me(t));}}function _e(e){let t=x.get(e);if(t?.seq!==void 0&&te.contains(t.seq))return true;let c=t?.seq===void 0?void 0:w.get(t.seq);return Ae(c?.outcome??t?.outcome)}function Re(e){try{te.add(e);}catch(t){throw we(me(t)),t}}function qe(e,t){try{o.recovery.onRecovery?.({phase:e,incarnation:k,attempt:Y,diverged:[...pe].sort((c,d)=>c-d),historyReset:P!==void 0,failure:t});}catch{}}function Ze(e,t,c,d=false){if(e.outcome&&!c&&!d||e.outcome&&t.status==="duplicate")return;let v=e.outcome,u=e.group;if(v||(ve-=1),$e(v)&&(re-=1),e.outcome=t,$e(t)&&(re+=1),l.delete(t.seq),Ae(t)&&Re(t.seq),u.outcome=t,oe(u,t),!Ae(t)){e.presentationStatus!==void 0&&z(u,e.presentationStatus);return}z(u,"dropped"),G.drop([e.ticket],t.reason??t.status),ye([e.ticket]),c&&!Ae(v)&&(pe.add(e.envelope.seq),Ro(e.envelope.seq),qe("diverged"));}function Ro(e){let t=Q$1.get(e);t&&(j.add(t.values()),Q$1.delete(e)),!D&&po();}function po(e=false){if(D=true,h||g$1)return;let t=e?1/0:64;for(;j.size&&t>0;){t-=1;let c=j.values().next().value,d=c.next();if(d.done){j.delete(c);continue}let v=Q$1.get(d.value);v&&(j.add(v.values()),Q$1.delete(d.value));let u=w.get(d.value);!u||Ae(u.outcome)||(Re(u.envelope.seq),u.outcome||(ve-=1),$e(u.outcome)&&(re-=1),u.outcome={seq:u.envelope.seq,status:"cancelled",reason:"dependency-refused"},l.delete(u.envelope.seq),R&&pe.add(u.envelope.seq),u.group.outcome=u.outcome,oe(u.group,u.outcome),z(u.group,"dropped"),G.drop([u.ticket],"dependency-refused"),ye([u.ticket],e));}j.size?(I??(I=Le()),ue(po)):(D=false,I?.resolve(),I=void 0);}function je(e,t,c=false){let d=t?.frame;if(!ie(e))return i(d),false;if(!T(t))return i(d),he(new g("message","Malformed command acknowledgement")),false;if(t.session!==W||t.incarnation!==k||t.epoch!==f)return i(t.frame),false;if(t.throughSeq>y||t.frame&&t.frame.coversThroughSeq>y||t.outcomes.some(C=>C.seq>t.throughSeq))return i(t.frame),he(new g("message","Command acknowledgement exceeds sent coverage")),false;let v=false,u=false;try{G.event(()=>{for(let N of t.outcomes){let J=w.get(N.seq);J&&Ze(J,N,c);}let C=w.get(t.throughSeq);C&&(C.confirmedVersion=t.version),(t.throughSeq>a.throughSeq||t.throughSeq===a.throughSeq&&t.version>=a.version)&&(a={...a,throughSeq:t.throughSeq,version:t.version}),"selection"in t&&t.throughSeq>=b&&(a={...a,selection:t.selection},b=t.throughSeq),"editState"in t&&t.throughSeq>=V&&(a={...a,editState:t.editState},V=t.throughSeq),t.revisions&&t.throughSeq>=se&&(ke=t.throughSeq===se?Math.max(ke,t.revisions.selection):t.revisions.selection,Se=t.throughSeq===se?Math.max(Se,t.revisions.layout):t.revisions.layout,se=t.throughSeq),t.frame&&(u=!0,v=Oo(t.frame)),p===0&&j.size===0&&yo(a.throughSeq,!0),q(),o.onAck?.(t);});}catch(C){return u||i(t.frame),we(C instanceof g?C:new g("message",C instanceof Error?C.message:String(C))),false}return Ne(),v}function Oo(e){let t=G.presentedThroughSeq,c=ne;ne=true,r=e.coversThroughSeq,A=e.revision;try{let d=G.present(e),v=!!o.transactionalPresentation&&!ne;if(d!=="presented"||G.presentedThroughSeq<=t)return v;let u=ne?"presented":"dropped",C=Math.min(G.presentedThroughSeq,e.coversThroughSeq);for(let[N,J]of Z){if(N>C)break;Z.delete(N),J.presentationStatus=u,!(!J.outcome||Ae(J.outcome))&&z(J.group,u);}return v}finally{ne=c;}}function at(e,t){if(!ie(e)||R){i(t);return}if(t===void 0||!T({session:W,incarnation:k,epoch:f,throughSeq:a.throughSeq,version:a.version,outcomes:[],frame:t})){i(t),he(new g("message","Malformed command frame"));return}if(t.coversThroughSeq>a.throughSeq){i(t);return}try{G.event(()=>{Oo(t),q();});}catch(c){we(c instanceof g?c:new g("message",c instanceof Error?c.message:String(c)));}}function xe(e,t){if(!e.active)return Promise.resolve();e.active=false,e.failure=t;try{e.unsubscribe();}catch{}try{e.unsubscribeFrame?.();}catch{}try{e.unsubscribeAck?.();}catch{}for(let c of Oe)c.connection===e&&(c.connection=void 0,c.attempt+=1,ge.add(c));e.cancelReplay?.(t),e.cancelReplay=void 0;try{return Promise.resolve(e.connection.client.dispose()).catch(()=>{})}catch{return Promise.resolve()}}function To(e){let t={connection:e,active:true,fullFrameBusy:false,fullFrameThroughSeq:-1,fullFrameRetries:0,seenSeq:y,seenMark:y,unsubscribe:()=>{}};T$1=t;let c=e.client.onFailure(d=>{ie(t)&&(R?xe(t,d):he(d));});if(t.active?t.unsubscribe=c:c(),t.active&&e.client.onFrame){let d=e.client.onFrame(v=>at(t,v));t.active?t.unsubscribeFrame=d:d();}if(t.active&&e.client.onAck){let d=e.client.onAck(v=>je(t,v));t.active?t.unsubscribeAck=d:d();}return t}function we(e){if(!(h||g$1)){g$1=e,R=false;for(let t of Oe)_(t,e);Ye(),T$1&&xe(T$1,e),Ce.clear(),l.clear(),G.dispose();for(let t of [...M])t.ackSettled||(t.ackSettled=true,t.ack.reject(e)),z(t,"dropped");w.clear(),Q$1.clear(),j.clear(),I?.resolve(),I=void 0,L.clear(),Z.clear();for(let t of H.values())t.resolve("dropped");H.clear(),te.clear(),S.clear(),qe("failed",e),pe.clear();}}function he(e){if(!(h||g$1)){if(R){T$1&&xe(T$1,e);return}if(p===0||!Eo(e)){if(p===0&&Eo(e))try{G.event(()=>{ye([],!0),po(!0);});}catch(t){we(me(t));return}we(e);return}R=true,Y=0,pe.clear(),T$1&&xe(T$1,e),l.clear(),B=false,dt(e).catch(t=>we(me(t)));}}function ko(e,t,c){let d=U(t)?t.refusal.seq:e.envelope.seq,v=w.get(d)??e;return G.event(()=>{Ze(v,{seq:v.envelope.seq,status:"refused",reason:"unknown-outcome"},c,true),Ro(v.envelope.seq);}),me(t)}function ct(e,t){return new Promise((c,d)=>{let v=false;function u(N){v||(v=true,e.cancelReplay===C&&(e.cancelReplay=void 0),N());}let C=N=>u(()=>d(N));if(e.cancelReplay=C,!ie(e)){C(e.failure??new g("disposed","Command connection is closed"));return}try{e.connection.client.call.edit(o.copyCommandForDispatch?.(t)??Q(t)).then(N=>{v?i(N?.frame):u(()=>c(N));},N=>u(()=>d(N)));}catch(N){u(()=>d(N));}})}async function dt(e){let t=e;for(;!h&&!g$1&&Y<p;){if(Y+=1,k+=1,qe("recovering",t),h||g$1)return;let c;try{if(I&&await I.promise,h||g$1)return;let d=P&&{...P,state:P.state.slice()},v=await o.recovery.reopen({source:Q(m),checkpoint:d,session:W,incarnation:k,epoch:f,refusedSeqs:te.values(),replayAppliedSeqs:[...w.values()].filter(ee=>$e(ee.outcome)).map(ee=>ee.envelope.seq)}),u=v.initial;if(c=u?.frame,h||g$1){i(c),c=void 0;try{await v.client.dispose();}catch{}return}let C=To(v);if(!T(u)||u.session!==W||u.incarnation!==k||u.epoch!==f||u.throughSeq!==(P?.throughSeq??n.throughSeq)||u.version!==(P?.version??n.version))throw new g("message","Reopened command connection has invalid initial state");if(v.client.failure)throw v.client.failure;G.reset(),Z.clear();for(let[ee,fe]of L)fe.presentationStatus=void 0,Z.set(ee,fe);a={epoch:f,version:u.version,throughSeq:u.throughSeq,presentedThroughSeq:-1,selection:u.selection,editState:u.editState},b=u.throughSeq,V=u.throughSeq,se=u.throughSeq,ke=u.revisions?.selection??0,Se=u.revisions?.layout??0,c=void 0,je(C,u);let N=[...w.values()].sort((ee,fe)=>ee.envelope.seq-fe.envelope.seq),J=u.throughSeq;for(let ee of N){if(!ie(C))throw C.failure;if(Ae(ee.outcome))continue;let fe={...ee.envelope,incarnation:k,replay:!0},De;try{De=await ct(C,fe);}catch(Ke){throw Ke instanceof g?Ke:ko(ee,Ke,!0)}if(J=Math.max(J,ee.envelope.seq),je(C,De,!0),I&&await I.promise,!ie(C)){if(h||g$1)return;throw C.failure}if(!De.outcomes.some(Ke=>Ke.seq===ee.envelope.seq))throw new g("message","Replay acknowledgement omitted command outcome")}if(!ie(C))throw C.failure;C.seenSeq=J,C.seenMark=y,R=!1,ae=-1,qe("recovered"),pe.clear(),ge.size&&be(),Ne();return}catch(d){if(t=me(d),T$1&&xe(T$1,t),h||g$1)return;if(!Eo(t))break}finally{i(c);}}!h&&!g$1&&we(t);}function lt(e,t){let c=T$1;!c||!ie(c)||((c.fullFrameRevision===void 0||e>c.fullFrameThroughSeq||e===c.fullFrameThroughSeq&&t>c.fullFrameRevision)&&(c.fullFrameThroughSeq=e,c.fullFrameRevision=t),ho(c));}function xo(e){return G.presentedThroughSeq>e.fullFrameThroughSeq||G.presentedThroughSeq===e.fullFrameThroughSeq&&(!o.sameCoverageFrames||G.revision!==void 0&&G.revision>=e.fullFrameRevision)}function ho(e){if(!ie(e)||e.fullFrameBusy)return;e.fullFrameBusy=true;let t=e.fullFrameThroughSeq,c=e.fullFrameRevision;try{o.requestFullFrame(e.connection).then(d=>{if(!ie(e)){i(d?.frame);return}let v=G.presentedThroughSeq,u=je(e,d);if(e.fullFrameBusy=!1,!!ie(e)){if(u){if(e.fullFrameRetries=0,(e.fullFrameThroughSeq>t||e.fullFrameThroughSeq===t&&e.fullFrameRevision>c)&&!xo(e)){ho(e);return}e.fullFrameThroughSeq=-1,e.fullFrameRevision=void 0;return}if(xo(e)){e.fullFrameRetries=0,e.fullFrameThroughSeq=-1,e.fullFrameRevision=void 0;return}if(e.fullFrameRetries=G.presentedThroughSeq>v?0:e.fullFrameRetries+1,e.fullFrameRetries>=4){let C=new g("message","Full frame responses did not satisfy requested coverage and revision");R?xe(e,C):we(C);return}ho(e);}},d=>{ie(e)&&(e.fullFrameBusy=!1,R?xe(e,me(d)):he(me(d)));}).catch(d=>{ie(e)&&(e.fullFrameBusy=!1,he(me(d)));});}catch(d){e.fullFrameBusy=false,R?xe(e,me(d)):he(me(d));}}function ut(){if(p===0||!o.recovery.checkpoint||a.throughSeq===ae)return false;let e=re,t=le;return e===0&&t===0?false:o.checkpointPolicy?o.checkpointPolicy({applied:e,bytes:t}):e>=128||t>=1024*1024}function ft(e){if(!e||typeof e!="object"||!(e.state instanceof Uint8Array)||e.epoch!==f||!Number.isSafeInteger(e.throughSeq)||e.throughSeq<0||e.throughSeq>a.throughSeq||!Number.isFinite(e.version)||e.version>a.version||P&&(e.throughSeq<P.throughSeq||e.version<P.version)||e.throughSeq===a.throughSeq&&e.version!==a.version)return false;let t=w.get(e.throughSeq),c=P?.throughSeq===e.throughSeq?P.version:n.throughSeq===e.throughSeq?n.version:t?.confirmedVersion;if(c===void 0||c!==e.version)return false;for(let d of w.values())if(d.envelope.seq<=e.throughSeq&&!d.outcome)return false;return true}function mt(e){B=true,ae=a.throughSeq;let t=o.recovery.checkpoint,c;try{c=t(e.connection);}catch(d){B=false,d instanceof g?he(d):Ne();return}c.then(d=>{ie(e)&&(ft(d)&&(P={...d,state:d.state.slice()},yo(d.throughSeq)),B=false,Ne());},d=>{ie(e)&&(B=false,d instanceof g?he(d):Ne());}).catch(d=>{ie(e)&&(B=false,he(me(d)));});}function yo(e,t=false){for(let[c,d]of w){if(c>e||t&&(!d.outcome||!d.rpcSettled))break;$e(d.outcome)&&(re-=1),le-=d.bytes;let v=d.envelope.afterSeq;if(v!==void 0){let u=Q$1.get(v);u?.delete(c),u?.size===0&&Q$1.delete(v);}w.delete(c);}}function bo(e){e.rpcSettled=true,p===0&&j.size===0&&yo(a.throughSeq,true);}function pt(e){if(o.holdForCoalescing?.(e.draft)!==true)return false;let t=e.draft.options.after;if(t)return t.seq!==void 0&&l.get(t.seq)===true;for(let c of l.values())if(c)return true;return false}function kt(e){let t=e.draft.options.after;if(!t)return true;let c=x.get(t);return c!==void 0&&c.seq!==void 0&&!_e(t)}function ht(e,t){if(y>=Number.MAX_SAFE_INTEGER){we(new g("message","Command sequence space is exhausted"));return}let c=++y,d=e.draft,v=d.options,u={session:W,incarnation:k,seq:c,basis:{epoch:f,version:a.version},kind:d.kind,payload:d.payload,...v.after?{afterSeq:v.after.seq}:{},...v.expectVersion!==void 0?{expectVersion:v.expectVersion}:{},...v.inputTime!==void 0?{inputTime:v.inputTime}:{},...v.lastInputTime!==void 0?{lastInputTime:v.lastInputTime}:{},...v.group!==void 0?{group:v.group}:{}},C=x.get(e.tickets[0]),N={envelope:u,ticket:e.tickets[0],group:C,rpcSettled:false,bytes:0};if(w.set(c,N),L.set(c,N),Z.set(c,N),ve+=1,C.seq=c,u.afterSeq!==void 0){let J=Q$1.get(u.afterSeq);J||Q$1.set(u.afterSeq,J=new Set),J.add(c);}if(L.size>1024){let J=L.values().next().value;J.presentationStatus="dropped",z(J.group,"dropped"),G.drop([J.ticket],"presentation-overflow");}if(ie(t)){l.set(c,o.holdForCoalescing?.(d)===true);try{N.envelope=Q(u);let J=o.commandBytes?.(N.envelope)??0;N.bytes=Number.isFinite(J)&&J>=0?J:0,le+=N.bytes;let ee=o.copyCommandForDispatch?.(u)??Q(N.envelope);t.connection.client.call.edit(ee).then(fe=>{try{je(t,fe);}finally{bo(N);}},fe=>{try{ie(t)&&he(fe instanceof g?fe:ko(N,fe,!1));}finally{bo(N);}}).catch(fe=>{ie(t)&&he(me(fe));});}catch(J){try{ie(t)&&he(J instanceof g?J:ko(N,J,!1));}finally{bo(N);}}ge.size&&be();}}function yt(){let e=T$1;if(!(!e||!ie(e)||R||B)){if(ut()){l.size===0&&ve===0&&mt(e);return}for(;ie(e)&&!R&&l.size<F;){let t=Ce.takeNext(kt,o.holdForCoalescing?pt:void 0);if(!t)break;ht(t,e);}}}function Ne(){if(!(h||g$1||R||$)){$=true;try{E(()=>{$=!1;try{yt();}catch(e){we(me(e));}});}catch(e){$=false,we(me(e));}}}function bt(e,t,c={}){let d=Fe();if(h)return oe(d,{status:"cancelled",reason:"disposed"}),z(d,"dropped"),d.ticket;if(g$1)return d.ackSettled=true,d.ack.reject(g$1),z(d,"dropped"),d.ticket;let v=c.after&&x.get(c.after);if(c.after&&(!v||_e(c.after)))return oe(d,{status:"cancelled",reason:"dependency-refused"}),z(d,"dropped"),d.ticket;let u={kind:e,payload:t,options:{...c}};try{G.event(()=>{let C=Ce.enqueue(u,d.ticket);C.tickets.length>1&&(x.set(d.ticket,x.get(C.tickets[0])),M.delete(d)),O.set(x.get(C.tickets[0]),{draft:C.draft,originalIntentCount:C.tickets.length});let N=C.draft.options.echo,J=N===void 0?void 0:{ticket:C.tickets[0],value:N};C.tickets.length>1?G.replace([C.tickets[0]],J):J&&G.add(J);});}catch(C){we(me(C));}return Ne(),d.ticket}function vt(e,t){if(h||g$1||R)return false;let c=new Set,d=[];for(let v of e){let u=x.get(v);if(!u||u.presentationSettled||Ae(u.outcome)||u.seq!==void 0&&u.seq<=G.presentedThroughSeq)return false;c.add(u);}for(let v of [...c].sort((u,C)=>u.ticket.id-C.ticket.id)){let u=O.get(v);if(!u||u.draft.options.echo!==void 0)return false;let C=t(u.draft,u.originalIntentCount);if(C===void 0)return false;d.push({record:v,entry:u,value:C});}return G.event(()=>{if(h||g$1||R||d.some(({record:u,entry:C})=>u.presentationSettled||Ae(u.outcome)||u.seq!==void 0&&u.seq<=G.presentedThroughSeq||O.get(u)!==C||C.draft.options.echo!==void 0))return false;for(let{entry:u,value:C}of d)u.draft.options.echo=C;let v=G.attach(d.map(({record:u,value:C})=>({ticket:u.ticket,value:C})));if(!v)for(let{entry:u}of d)u.draft.options.echo=void 0;return v})}let St={backend:"worker",get state(){return a},submit:bt,attachEcho:vt,read:Te,hold:mo,get stage(){return h?"disposed":g$1?"failed":R?"recovering":"ready"},whenPresented(e){if(h||g$1)return Promise.resolve("dropped");let t=w.get(e)??L.get(e);if(te.contains(e))return Promise.resolve("dropped");let c=t&&x.get(t.ticket);if(c)return c.presentation.promise;if(e<=y)return G.whenPresented(e);let d=H.get(e);if(d)return d.promise;if(H.size>=1024){let u=H.keys().next().value;H.get(u).resolve("dropped"),H.delete(u);}let v=Le();return H.set(e,v),v.promise},subscribe(e){return h||g$1?()=>{}:(S.add(e),()=>{S.delete(e);})},flush(){if(Ko(Ce),g$1)return Promise.reject(g$1);let e=[...M].filter(c=>!c.ackSettled).map(c=>c.ack.promise);Ne();let t=Promise.all(e).then(()=>{});return t.catch(()=>{}),t},dispose(){if(X$1)return X$1;let e=Le();X$1=e.promise,h=true,R=false;for(let c of Oe)_(c,Ee("disposed"));Ye();let t=T$1?xe(T$1,new g("disposed","Edit session was disposed")):Promise.resolve();Ce.clear(),l.clear(),G.dispose();for(let c of [...M])oe(c,{seq:c.seq,status:"cancelled",reason:"disposed"}),z(c,"dropped");w.clear(),Q$1.clear(),j.clear(),I?.resolve(),I=void 0,L.clear(),Z.clear();for(let c of H.values())c.resolve("dropped");return H.clear(),te.clear(),S.clear(),pe.clear(),t.then(()=>e.resolve()),X$1}},gt=To(o.connection);return je(gt,n),o.connection.client.failure&&he(o.connection.client.failure),St}function qo(o){let n=o.connection.initial,p=o.identity??{session:n.session,incarnation:String(n.incarnation)},m=new Set,W=new Set,f=new Set,F=[],E=new Map,x=new Set,O=new Set,M=new Set,S=[],w=n.engineVersion,Q=n.throughSeq,j=o.echo,D=n.frame,I=false,L,Z=-1,H=n.throughSeq+1,te=0,l,s=n.editState,y=n.throughSeq,k,P=false;function T(r){return {...r.compatibility??{throughSeq:r.throughSeq,version:r.engineVersion,statuses:r.outcomes.map(A=>A.workbook??{...A,status:A.status==="duplicate"?"noop":A.status,committed:A.status==="applied"&&A.committed!==false}),...r.selection?{selection:r.selection}:{},...r.editState?{editState:r.editState}:{}},...r.frame?{frame:r.frame.payload}:{}}}function a(r){if(k||P)return;r.throughSeq>=Q&&(Q=r.throughSeq,w=r.engineVersion);let A=T(r);for(let X of r.outcomes)E.get(X.seq)?.resolve(A),E.delete(X.seq);for(let X of [...W])if(W.has(X))try{X(A);}catch{}}function h(r){for(let A of E.values())A.reject(r);E.clear();for(let A of x)A.reject(r);x.clear();}function g$1(){if(k)throw k;if(P)throw new g("disposed","Session was disposed")}async function R(r){let A=[...M].filter(V=>(r.payload.dispatchOrder??0)>V.order),X=l;if(A.length||X){let V=Promise.all([X,...A.map(se=>se.done)]).then(()=>{});l=V;try{await V;}finally{l===V&&(l=void 0);}}g$1();let Y=r.payload.compatibility;if(Y&&Y.seq!==r.seq)throw new g("message","Workbook compatibility sequence differs from shared dispatch");let b=await o.connection.client.call.edit(Y?{...r,...Y.afterSeq===void 0?{}:{afterSeq:Y.afterSeq}}:r);return g$1(),b.session===n.session&&b.incarnation===n.incarnation&&b.epoch===n.epoch&&b.editState&&b.throughSeq>=y?(s={...s,...b.editState},y=b.throughSeq,{...b,editState:s}):b}let B=Yo({source:void 0,connection:{initial:n,client:{call:{edit:r=>{o.onAdmit?.(r),H=Math.max(H,r.seq+1);let A=R(r).catch(X=>{throw X instanceof g?X:new g("crash",X instanceof Error?X.message:String(X))});return A.then(X=>{!k&&!P&&X.session===n.session&&X.incarnation===n.incarnation&&X.epoch===n.epoch&&F.push(X);},()=>{}),A},checkpoint:()=>o.connection.client.call.checkpoint()},get failure(){return o.connection.client.failure},onFailure:r=>o.connection.client.onFailure(r),dispose:()=>o.connection.client.dispose(),onFrame(r){m.add(r);let A=o.connection.client.onFrame?.(r);return ()=>{m.delete(r),A?.();}}}},recovery:{reopen:o.recovery?.reopen??(async()=>{throw new Error("Workbook command recovery is disabled")}),checkpoint:o.recovery?.checkpoint,onRecovery(r){if(r.phase==="failed"&&r.failure){k=r.failure,D=void 0,F.length=0,S.length=0,h(k),O.clear();for(let A of [...f])if(f.has(A))try{A(k);}catch{}}o.recovery?.onRecovery?.(r);}},maxRecoveryAttempts:0,transactionalPresentation:true,echoOverflow:"evict-oldest",sameCoverageFrames:true,maxInFlight:o.maxInFlight??64,maxEchoEntries:o.maxEchoEntries??256,inputBurstCap:o.inputBurstCap,coalesce:o.coalesce&&((r,A)=>{let X=o.coalesce(r,A);return X&&{...X,payload:{...X.payload,dispatchOrder:Math.max(r.payload.dispatchOrder??0,A.payload.dispatchOrder??0)}}}),enqueue:o.enqueue,now:o.now,commandBytes:o.commandBytes,checkpointPolicy:o.checkpointPolicy,onEchoOverrun:o.onEchoOverrun,requestFullFrame:o.requestFullFrame,echo:{paint:r=>j?.paint(r),drop:(r,A)=>j?.drop(r,A),present(r,A,X){if(r.payload.coversThroughSeq!==r.coversThroughSeq||o.identity&&(r.payload.session!==p.session||r.payload.incarnation!==p.incarnation)||(D=r,!I&&!j))return false;let Y=I||j.present(r,A,X)!==false;return Y&&(S.push(r),D===r&&(D=void 0)),Y}}});function ae(){for(let r of S.splice(0))r.coversThroughSeq<=B.state.presentedThroughSeq&&(r.coversThroughSeq>Z?L=r.revision:r.coversThroughSeq===Z&&(L=Math.max(L??r.revision,r.revision)),Z=Math.max(Z,r.coversThroughSeq));}ae(),B.subscribe(()=>{ae();let r=F[0];r&&r.throughSeq<=B.state.throughSeq&&(F.shift(),a(r));});function ne(r){if(!(k||P))for(let A of [...m])A(r);}return {backend:B.backend,get state(){return k?{...B.state,editState:{...B.state.editState,readOnly:true}}:B.state},get engineVersion(){return w},get failure(){return k},get presentationRevision(){return L},submit(r,A,X){let Y={};O.add(Y);try{if(o.normalizePayload){let V=o.normalizePayload(A.payload);A={...A,payload:V,...A.compatibility?{compatibility:{...A.compatibility,payload:V}}:{}};}let b=B.submit(r,{...A,dispatchOrder:++te},X);return Y.ticket=b,b.ack.then(()=>{O.delete(Y);},()=>{O.delete(Y);}),b.seq!==void 0&&(H=Math.max(H,b.seq+1)),b}catch(b){throw O.delete(Y),b}},subscribe:r=>B.subscribe(r),flush:()=>B.flush(),whenPresented:r=>B.whenPresented(r),runAfterEdits(r){if(k)return Promise.reject(k);if(P)return Promise.reject(new g("disposed","Session was disposed"));let A=te===0?void 0:B.flush(),X=()=>{if(k)throw k;if(P)throw new g("disposed","Session was disposed");return r()},Y=A?A.then(X):X(),b={order:te,done:Y.then(()=>{},()=>{})};return M.add(b),b.done.then(()=>{M.delete(b);}),Y},async command(r){if(_(r),o.onAdmit&&(r=structuredClone(r)),g$1(),r.session!==p.session||r.incarnation!==p.incarnation||r.basis.epoch!==n.epoch)throw new Error("Workbook command identity or epoch mismatch");o.normalizePayload&&(r.payload=o.normalizePayload(r.payload));let A={payload:r.payload,compatibility:r,frame:r.frame};if(r.seq<H){let re,le,ve=new Promise((ce,We)=>{re=ce,le=We;}),pe={reject:le};x.add(pe),R({session:n.session,incarnation:n.incarnation,seq:r.seq,basis:{epoch:n.epoch,version:B.state.version},afterSeq:r.afterSeq,kind:r.kind,payload:{...A,frame:void 0}}).then(re,le);try{let ce=await ve;return g$1(),a(ce),g$1(),T(ce)}finally{x.delete(pe);}}if([...O].some(re=>re.ticket?.seq===void 0))throw new Error("Workbook command sequence is awaiting native dispatch");if(r.seq!==H)throw new Error(`Expected workbook command sequence ${H}`);o.onAdmit?.({session:n.session,incarnation:n.incarnation,seq:r.seq,basis:{epoch:n.epoch,version:B.state.version},afterSeq:r.afterSeq,kind:r.kind,payload:A}),H+=1;let X,Y,b=new Promise((re,le)=>{X=re,Y=le;});b.catch(()=>{}),E.set(r.seq,{resolve:X,reject:Y});let V=r.payload&&typeof r.payload=="object"?r.payload:void 0,se=V&&"inputTime"in V?V.inputTime:void 0,ke=V&&"undoGroupId"in V?V.undoGroupId:void 0,Se=B.submit(r.kind,{...A,dispatchOrder:++te},{lane:r.kind==="applyUpdate"||r.kind==="collabPipe"?"collab":"input",fence:true,...typeof se=="number"&&Number.isFinite(se)?{inputTime:se}:{},...typeof ke=="string"?{group:ke}:{}});try{let re=await Se.ack;if(g$1(),re.seq===void 0||re.status==="cancelled"){E.delete(r.seq);let{workbook:ve,...pe}=re;return {throughSeq:B.state.throughSeq,version:w,selection:B.state.selection,editState:B.state.editState,statuses:[ve??{...pe,seq:r.seq,status:re.status==="duplicate"?"noop":re.status,committed:!1,affectedSeqs:[r.seq]}]}}let le=await b;return g$1(),le}catch(re){throw E.delete(r.seq),re}},onAck(r){return W.add(r),()=>{W.delete(r);}},onFailure(r){return k?(r(k),()=>{}):(f.add(r),()=>{f.delete(r);})},bindPresenter(r){return j=r,D&&ne(D),()=>{j===r&&(j=void 0);}},present:ne,markPresented(r){if(k||P||r.session!==p.session||r.incarnation!==p.incarnation||!Number.isSafeInteger(r.coversThroughSeq)||r.coversThroughSeq<0||r.coversThroughSeq<B.state.presentedThroughSeq||r.coversThroughSeq>B.state.throughSeq)return false;I=true;try{ne({coversThroughSeq:r.coversThroughSeq,revision:Math.max(r.epoch??0,(L??0)+1),payload:r});}finally{I=false;}return B.state.presentedThroughSeq>=r.coversThroughSeq},dispose(){return P=true,D=void 0,h(new g("disposed","Session was disposed")),O.clear(),F.length=0,S.length=0,W.clear(),f.clear(),B.dispose()}}}var Wt=6e4;function Zo(o){try{o.post({protocol:1,kind:"wasm-compile"});}catch(n){try{o.close();}catch{}throw n}}function ao(o,n){let p=new Map,m=new Map,W=new Set,f$1=new Set(Object.keys(n.methods)),F=n.now??Date.now,E=n.timer??((l,s)=>{let y=setTimeout(l,s);return ()=>clearTimeout(y)}),x=n.silenceMs??Wt,O=1,M,S,w,Q=()=>{},j=()=>{};function D(){S?.(),S=void 0;}function I(l,s,y=false){for(let k of [...l])if(!(!l.has(k)||y&&M))try{k(s);}catch{}}function L(l,s=true){if(!M){M=l,D(),Q(),j();for(let y of p.values())y.reject(l);if(p.clear(),m.clear(),s){try{o.close();}catch{}I(W,l);}W.clear();}}function Z(){if(D(),p.size===0||M)return;let l=F();S=E(()=>L(new g("silence",`Session received no message within ${x}ms`,`Waiting for ${p.size} call(s); silent for ${F()-l}ms`)),x);}function H(l,s,y=[]){if(M)return Promise.reject(M);if(!f$1.has(l))return Promise.reject(new Error(`Unknown session method: ${l}`));let k=O++;return new Promise((P,T)=>{let a=p.size===0;p.set(k,{resolve:P,reject:T}),a&&Z();try{o.post({protocol:1,kind:"call",id:k,method:l,args:s},y);}catch(h){p.delete(k),p.size===0&&D(),T(h instanceof Error?h:new Error(`Session call could not be posted: ${String(h)}`));}})}Q=o.listen(l=>{if(!M)if(Z(),f(l))if(l.kind==="failure")L(new g(l.code,l.message,l.diagnostics));else if(l.kind==="wasm-module"){try{n.onWasmModule?.(l.url,l.module);}catch{}try{n.onWasmModuleMessage?.(l);}catch{}}else {if(l.kind==="progress")return;if(l.kind==="event"){let s=m.get(l.name);s&&I(s,l.payload,true);}else {let s=p.get(l.id);if(!s)return;if(p.delete(l.id),p.size===0&&D(),l.ok)s.resolve(l.value);else {let y=new Error(l.error.message);y.name=l.error.name,d(l.error,"refusal")&&Object.assign(y,{refusal:l.error.refusal}),s.reject(y);}}}else {if(l!==null&&typeof l=="object"&&"kind"in l&&l.kind==="wasm-module")return;L(new g("message","Session received a malformed host message"));}}),j=o.onError(l=>L(l instanceof g?l:new g("crash",l instanceof Error?l.message:String(l))));let te=Object.create(null);for(let l of f$1)Object.defineProperty(te,l,{enumerable:true,value:(...s)=>H(l,s)});return {call:te,callWithTransfer:(l,s,y)=>H(l,s,y),on(l,s){if(M)return ()=>{};let y=m.get(l)??new Set;m.set(l,y);let k=s;return y.add(k),()=>{y.delete(k);}},onFailure(l){return M||W.add(l),()=>{W.delete(l);}},get failure(){return M},dispose(){if(w)return w;let l=M!==void 0;return L(new g("disposed","Session was disposed"),false),w=new Promise(s=>{if(!l)try{o.post({protocol:1,kind:"dispose"});}catch{}setTimeout(()=>{try{o.close();}catch{}s();},0);}),w}}}var et=256,ot=4096,Me=class extends Error{constructor(p,m){super(`Workbook recovery refused sequence ${p}: ${m}`);a(this,"seq",p);a(this,"reason",m);a(this,"code","workbook-recovery-refused");this.name="WorkbookRecoveryReplayError";}},Co=new WeakMap,Et={open(o,n,p,m){if(n.collaborative)return Promise.reject(new Error("Recovery is unavailable for collaborative workbooks"));let W=h(n.worker?n.worker():new Worker(new URL("./xlsxSessionWorker.mjs",import.meta.url),{type:"module"}));return qt(o,n,W,p,m)}};async function qt(o,n,p,m,W){let f=ao(p,{methods:G});try{if(n.collaborative)throw new Error("Recovery is unavailable for collaborative workbooks");let F=n.wasm instanceof ArrayBuffer?n.wasm.slice(0):n.wasm,x=(m?await f.call.openRecovery({...m,state:m.state.slice()},{wasm:F}):await f.call.open(o.slice().buffer,{collaborative:n.collaborative,clientId:n.clientId,calculation:n.calculation,wasm:F,initialViewport:n.initialViewport,includeEditState:!0,recoveryVersion:W})).commandContext;if(!x)throw new Error("Workbook recovery omitted command context");let O=x.basis.version,M=m?.version??0;return {async replay(S,w=!1){let Q=S.payload.compatibility,j=await f.call.edit({...S,session:x.session,incarnation:1,replay:!0,...w?{basis:{epoch:x.basis.epoch,version:M}}:{},payload:{...S.payload,...Q?{compatibility:{...Q,session:x.session,incarnation:x.incarnation,...w?{basis:{epoch:x.basis.epoch,version:O}}:{}}}:{}}});O=j.engineVersion,M=j.version;let D=j.outcomes.find(I=>I.seq===S.seq);if(!D||j.throughSeq<S.seq)throw new Me(S.seq,"missing-outcome");return D.workbook??{...D,status:D.status==="duplicate"?"noop":D.status}},save:async()=>new Uint8Array(await f.call.save()),dispose:()=>f.dispose()}}catch(F){throw await f.dispose(),F}}function tt(o){let n=o.result;if(!(!n||typeof n!="object")){if("formatToken"in n&&typeof n.formatToken=="string")return n.formatToken;if("id"in n&&typeof n.id=="string")return n.id}}function nt(o,n,p,m,W=false,f,F){let E=o,x={...n,signal:void 0,retainPeerHydration:false,calculation:n.calculation?{...n.calculation}:void 0,initialViewport:n.initialViewport?{...n.initialViewport}:void 0,wasm:n.wasm instanceof ArrayBuffer?n.wasm.slice(0):n.wasm},O=new Map,M,S,w,Q=0,j=false,D=0,I=et,L=()=>{if(!E)throw new g("disposed","Workbook recovery was disposed")},Z=l=>!W||!("args"in l)||l.calculation?l:{...l,calculation:{nowSerial:ba(Date.now()),randSeed:globalThis.crypto.getRandomValues(new Uint32Array(1))[0]>>>0}},H={get throughSeq(){return M?.throughSeq??0},get retainedCommands(){return O.size},get checkpointIdleMs(){return Math.max(150,2*(M?.encodeMs??0))},async capture(l){return L(),S||(D&&O.size<I?false:(S=(async()=>{if(!l())return false;let s=await p(l);if(L(),!s)return false;if(!(s.state instanceof Uint8Array)||s.epoch!==m||!Number.isSafeInteger(s.throughSeq)||s.throughSeq<(M?.throughSeq??0)||s.throughSeq>Q||!Number.isSafeInteger(s.version)||s.version<(M?.version??0)||s.encodeMs!==void 0&&(!Number.isFinite(s.encodeMs)||s.encodeMs<0))throw new Me(s.throughSeq,"invalid-checkpoint");M={...s,state:s.state.slice()};for(let y of O.keys())y<=s.throughSeq&&O.delete(y);return D=0,I=et,true})().catch(s=>{if(!E||s instanceof g||s instanceof Me)throw E&&F?.(s),s;let y=s instanceof Error?s.message:String(s);if(O.size>=ot){let k=Object.assign(new Me(Q,"log-full"),{cause:s});throw F?.(k),k}return D=Math.min(1024,D*2||64),I=Math.min(ot,O.size+D),console.warn(`xlsx recovery: checkpoint failed, retaining ${O.size} commands until a later capture: ${y}`),false}).finally(()=>{S=void 0;}),S))},async save(l,s=[]){return L(),l(),w||(w=(async()=>{let y=[...O.values()].sort((P,T)=>P.command.seq-T.command.seq);for(let[P,T]of s.entries()){let a=Q+P+1,h=Z(structuredClone(T.payload));y.push({pending:true,command:{session:"",incarnation:1,seq:a,basis:{epoch:m,version:0},kind:T.kind,payload:{payload:h,compatibility:{session:"",incarnation:"",seq:a,basis:{epoch:m,version:""},kind:T.kind,payload:h}}}});}let k=await Et.open(E,x,M,f);try{l(),L();let P=new Map;for(let a of y){let h=structuredClone(a.command),g=h.payload.payload;if("formatToken"in g&&(g.formatToken=P.get(g.formatToken)??g.formatToken),(h.kind==="acceptProposal"||h.kind==="rejectProposal")&&"args"in g){let ne=g.args;ne[0]=P.get(ne[0])??ne[0];}h.payload.compatibility&&(h.payload.compatibility.payload=g);let R=await k.replay(h,a.pending);l(),L();let $=R.status==="refused"||R.status==="cancelled",B=a.outcome;if($&&!B||B&&(B.status!==R.status||B.reason!==R.reason||B.committed!==R.committed||JSON.stringify(B.affectedSeqs)!==JSON.stringify(R.affectedSeqs)||$&&JSON.stringify(B.result)!==JSON.stringify(R.result)))throw new Me(h.seq,R.reason??"outcome-mismatch");let ae=tt(R);a.identifier&&ae&&P.set(a.identifier,ae);}let T=await k.save();return l(),L(),T}finally{await k.dispose();}})().finally(()=>{w=void 0;}),w)}},te=()=>{j||!E||O.size<I||(j=true,(S??Promise.resolve(true)).then(()=>{if(j=false,E&&O.size>=I)return H.capture(()=>E!==void 0)},()=>{j=false;}).catch(()=>{}));};return {recovery:H,normalizePayload:Z,admit(l){if(L(),l.seq<=Q)return;if(l.seq!==Q+1)throw new Me(l.seq,"sequence-gap");let s=structuredClone(l);s.payload.frame=void 0,s.payload.compatibility&&(s.payload.compatibility.frame=void 0),O.set(s.seq,{command:s}),Q=s.seq,te();},acknowledge(l){for(let s of l.statuses){let y=O.get(s.seq);y&&(y.outcome=structuredClone(s),y.identifier=tt(s));}},dispose(){E=void 0,M=void 0,O.clear();}}}var Fo=new WeakMap;var lo=new Map,co={records:256,bytes:16*1024},Ct=8;function rt(o){return ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength).slice():new Uint8Array(o).slice()}function Ve(o){return {...o,displayList:JSON.parse(new TextDecoder().decode(o.displayList))}}async function it(o){try{return new Uint8Array(await o)}catch(n){throw n instanceof Error&&n.name==="WorkbookPngUnavailableError"?new F:n}}function Ft(o,n){let p=rt(o).buffer,m=[p],W=n.calculation??(n.includeEditState&&!n.retainPeerHydration&&!n.collaborative?{nowSerial:ba(Date.now()),randSeed:globalThis.crypto.getRandomValues(new Uint32Array(1))[0]>>>0}:void 0),f={collaborative:n.collaborative,clientId:n.clientId,calculation:W?{...W}:void 0,retainPeerHydration:n.retainPeerHydration,initialViewport:n.initialViewport?{...n.initialViewport}:void 0,includeEditState:n.includeEditState,initialUpdate:n.initialUpdate?.slice()};return n.wasm instanceof ArrayBuffer||Object.prototype.toString.call(n.wasm)==="[object ArrayBuffer]"?(f.wasm=rt(n.wasm).buffer,m.push(f.wasm)):n.wasm!==void 0?f.wasm=n.wasm:n.worker||(f.wasm=lo.get(j().href)),{document:p,input:f,transfer:m}}async function Rt(o){if(!o.module)throw new P("missing-module","Workbook peer hydration requires a worker-compiled module");if(await n(o.module),o.disposed)throw new g("disposed","Workbook session was disposed");if(o.hydration===void 0)throw new P("missing-hydration","Workbook worker did not retain peer calculation state");if(o.snapshot){let n=o.snapshot,p,m;try{let W=await n.beginPeerSnapshot(co.records,co.bytes);if(W.version!==o.version||W.sequence!==o.sequence)throw new Error("Workbook snapshot differs from retained peer hydration");for(p=x(o.options);;){if(o.disposed)throw new g("disposed","Workbook session was disposed");let F=await n.pullPeerSnapshot();if(F===void 0)break;for(let E of F)p.push(new Uint8Array(E));}let f=!1;for(;;){await new Promise(E=>setTimeout(E,0));let F=performance.now()+Ct;do{if(o.disposed)throw new g("disposed","Workbook session was disposed");f=p.advance(co.records,co.bytes);}while(!f&&performance.now()<F);if(f)break}if(m=p.finish(),m.version()!==W.version)throw new Error("Workbook snapshot peer version differs from worker");if(await n.endPeerSnapshot(!1),o.disposed)throw new g("disposed","Workbook session was disposed");return o.bytes=void 0,o.hydration=void 0,m}catch(W){try{m?.dispose();}catch{}try{await n.endPeerSnapshot(!0);}catch{}if(o.disposed)throw new g("disposed","Workbook session was disposed");try{console.warn(`xlsx worker editor: snapshot hydration fell back: ${W instanceof Error?W.message:String(W)}`);}catch{}}finally{try{p?.dispose();}catch{}}}if(o.bytes===void 0||o.hydration===void 0)throw new P("missing-hydration","Workbook worker did not retain peer source bytes or calculation state");try{return A(o.bytes,o.options,o.hydration)}catch(n){throw new P("missing-hydration",`Workbook worker supplied invalid peer hydration: ${n instanceof Error?n.message:String(n)}`)}}function Wn(o){let n=Fo.get(o);if(!n)return Promise.reject(new TypeError("Workbook session does not retain peer hydration state"));if(n.disposed)return Promise.reject(new g("disposed","Workbook session was disposed"));if(!n.pending){let p=Rt(n);n.pending=p,p.catch(()=>{n.pending===p&&(n.pending=void 0);});}return n.pending}async function Ot(o,n={}){let p=h(n.worker?n.worker():new Worker(new URL("./xlsxSessionWorker.mjs",import.meta.url),{type:"module"}));return !n.worker&&n.wasm===void 0&&!lo.has(j().href)&&Zo(p),Tt(o,n,p)}async function Tt(o,n,p){let m=new Map,W=0,f$1=i=>{for(let q of i)m.get(q.provider)?.receive(q.out);},F=i=>{let q=[...m.values()];m.clear();for(let K of q)K.lost(i);},E={...p,listen(i){return p.listen(q=>{if(f(q)&&q.kind==="reply"){let K=q.collabPipe;K&&f$1(K);}i(q);})}},x,O,M,S,w,Q,j$1,D;try{(({document:x,input:O,transfer:M}=Ft(o,n))),n.includeEditState&&!n.retainPeerHydration&&!O.collaborative&&(D=new Uint8Array(x).slice()),n.retainPeerHydration&&(j$1=new Promise((i,q)=>{Q=q;}),j$1.catch(()=>{}),w={bytes:new Uint8Array(x).slice(),options:{collaborative:O.collaborative,clientId:O.clientId,calculation:O.calculation},module:O.wasm instanceof WebAssembly.Module?O.wasm:void 0,disposed:!1}),S=ao(E,{methods:{...G,...J},onWasmModuleMessage:({url:i,module:q,hydration:K,version:z,sequence:oe})=>{if(i===j().href){if(w){if(K===void 0){Q(new P("missing-hydration","Workbook worker did not retain peer calculation state"));return}if(typeof z!="string"||typeof oe!="number"||!Number.isSafeInteger(oe)||oe<0){Q(new P("missing-hydration","Workbook worker hydration is missing its committed version or sequence"));return}w.module=q,w.hydration=K,w.version=z,w.sequence=oe;}n.wasm===void 0&&!n.worker&&!lo.has(i)&&lo.set(i,q);}}});}catch(i){try{p.close();}catch{}throw i}let I,L$2,Z,H$1,te,l,s=false,y;w&&S.on("peerOpened",i=>{Z=i.version,w&&(w.initialCalculation=i.initialCalculation);}),S.on("collaborationPipe",f$1),S.on("changed",i=>{I={...I,...i};}),S.onFailure(()=>{I={...I,stage:"failed"},F("Collaboration worker failed");});let k=n.signal,P$1=()=>{w&&(w.disposed=true),S.dispose().catch(()=>{});try{p.close();}catch{}};try{k?.addEventListener("abort",P$1,{once:!0}),k?.aborted&&P$1();let i=S.callWithTransfer("open",[x,O],M),q=await(j$1?Promise.race([i,j$1]):i),{commandContext:K,initialPaint:z,clientId:oe,editState:Fe,selection:de,pngExport:ye,...ue}=q;if(s=ye===!0,z&&(H$1={...z,frame:{...z.frame,...Ve(z.frame)}}),te=Fe??z?.editState,l=de,y=oe,L$2=K,Z??(Z=K?.basis.version),I=ue,k?.aborted)throw new g("disposed","Session was disposed");if(w&&!w.module)throw new P("missing-module","Workbook worker did not retain a compiled module for peer hydration");if(w&&w.hydration===void 0)throw new P("missing-hydration","Workbook worker did not retain peer calculation state")}catch(i){throw await S.dispose(),i}finally{k?.removeEventListener("abort",P$1);}let T={...S.call};for(let i of Object.keys(G))Object.defineProperty(T,i,{value:(...q)=>{if(i==="command"&&(w||L.get(be)?.editPeerAttached))return Promise.reject(new Error("Workbook commands require a session without an edit peer"));if(i==="applyEdits"&&Je)return Promise.reject(new Error("Workbook command sessions require command batches"));if(w||L.get(be)?.editPeerAttached){let z=H[i];if((typeof z=="function"?z(...q):z).mutates)return w?Promise.reject(new P("mutation-outside-replay",`Cannot call ${i} outside workbook edit-peer replay in retained hydration mode`)):Promise.reject(new Error(`Cannot call ${i} while a workbook edit peer is attached`))}let K=S.call[i];try{if(i==="renderPng"||i==="renderRangePng"){let z=q[1];q=structuredClone([q[0],{...z,sheet:z?.sheet??I.activeSheet}]);}else (i==="exportStructured"||i==="exportMarkdown"||i==="printDisplayList")&&(q=structuredClone(q));}catch(z){return Promise.reject(z)}return _.runAfterEdits(()=>K(...q))}});let{version:a,listDefinedNames:h,readCells:g$1,findText:R,validateEdits:$,applyEdits:B,frame:ae,sheetView:ne,cellGeometry:r,selectionData:A,cellInputs:X,captureFormat:Y,sheets:b,calculationStatus:V,save:se,renderPng:ke,renderRangePng:Se,exportStructured:re,exportMarkdown:le,printDisplayList:ve,collaborationStateVector:pe,collaborationStateAsUpdate:ce}=T,We=Object.freeze(L$2?{session:L$2.session,incarnation:L$2.incarnation}:{session:"",incarnation:""}),Je=false,Xe=l!==void 0,Oe=L$2?.basis??{epoch:1,version:Z??""},ge,Ce=new Set,G$1=D?nt(D,{...n,calculation:O.calculation},async i=>(await _.runAfterEdits(()=>Promise.resolve({reply:i()?S.call.checkpoint(true):void 0}))).reply,Oe.epoch,n.calculation===void 0,Z,i=>{if(!(ge||S.failure||_.failure)){ge=i instanceof g?i:Object.assign(new g("message",`Workbook recovery checkpoint failed: ${i instanceof Error?i.message:String(i)}`),{cause:i});for(let q of [...Ce])try{q(ge);}catch{}}}):void 0;D=void 0;function ie(i){let{frame:q,compatibility:K,...z}=i,oe={...z,...q?{frame:{...q,payload:{...q.payload,...Ve(q.payload)}}}:{}};if(K){let{frame:Fe,...de}=K;oe.compatibility={...de,...Fe?{frame:{...Fe,...Ve(Fe)}}:{}};}return oe}let _=qo({identity:We,onAdmit:G$1?i=>G$1.admit(i):void 0,normalizePayload:G$1?i=>G$1.normalizePayload(i):void 0,connection:{initial:{session:We.session,incarnation:1,epoch:Oe.epoch,throughSeq:0,version:0,engineVersion:Oe.version,outcomes:[],...te?{editState:te}:{},...l?{selection:l}:{},...H$1?{frame:{coversThroughSeq:0,revision:H$1.frame.epoch,payload:H$1.frame}}:{}},client:{call:{edit:async i=>{let q=i.payload.compatibility;if(!q||q.kind==="applyUpdate"||q.kind==="collabPipe"){let z=i.payload.payload,oe=i.kind==="collabPipe"&&"ops"in z?a$1(z.ops):[];return ie(await S.callWithTransfer("edit",[i],oe))}let K=await S.call.command(q);if(!K.shared)throw new Error("Workbook command omitted shared acknowledgement");return ie(K.shared)},checkpoint:()=>S.call.checkpoint()},get failure(){return S.failure??ge},onFailure:i=>{Ce.add(i);let q=S.onFailure(i);return ()=>{Ce.delete(i),q();}},dispose:()=>S.dispose()}},enqueue:i=>{i();},requestFullFrame:async()=>{let i=await S.call.commandFrame();return {session:We.session,incarnation:1,epoch:Oe.epoch,throughSeq:_.state.throughSeq,version:_.state.version,engineVersion:_.engineVersion,outcomes:[],...i?{frame:{...i,payload:{...i.payload,...Ve(i.payload)}}}:{}}}});_.onFailure(()=>{I={...I,stage:"failed"},F("Collaboration worker failed");}),_.onAck(i=>{G$1?.acknowledge(i),i.selection&&(Xe||i.statuses.some(q=>q.status==="applied"||q.status==="noop"))&&(Xe=true);}),_.subscribe(i=>{i.editState&&(I={...I,...i.editState.activeSheet===void 0?{}:{activeSheet:i.editState.activeSheet},...i.editState.sheets===void 0?{}:{sheets:i.editState.sheets}});});async function Ee(i){if(Je=true,w||L.get(be)?.editPeerAttached)throw new Error("Workbook commands require a session without an edit peer");return _.command(i)}let be={pngExport:s,get state(){return I},initialPaint:H$1,commandIdentity:We,get confirmedBasis(){return Object.freeze({epoch:_.state.epoch,version:_.engineVersion})},get throughSeq(){return _.state.throughSeq},get presentedThroughSeq(){return Math.max(0,_.state.presentedThroughSeq)},get editState(){return _.state.editState??{}},get selection(){return Xe?_.state.selection:void 0},editSession:_,submit:async i=>{let K=(await Ee(i)).statuses.find(z=>z.seq===i.seq);if(!K)throw new Error(`Workbook acknowledgement omitted sequence ${i.seq}`);return K},onAck:i=>_.onAck(i),markPresented:i=>_.markPresented(i),whenPresented:async i=>{if(!Number.isSafeInteger(i)||i<0)return Promise.reject(new RangeError("Invalid presentation sequence"));if(S.failure||_.failure)throw S.failure??_.failure;if(!(i===0&&!H$1)&&await _.whenPresented(i)!=="presented")throw S.failure??_.failure??new g("disposed","Presentation was dropped")},call:{version:a,listDefinedNames:h,readCells:g$1,findText:R,validateEdits:$,applyEdits:B,sheetView:ne,cellGeometry:r,selectionData:A,cellInputs:X,captureFormat:Y,sheets:b,calculationStatus:V,save:se,command:Ee,exportStructured:re,exportMarkdown:le,collaborationStateVector:pe,collaborationStateAsUpdate:ce,renderPng:(i,q)=>it(ke(i,q)),renderRangePng:(i,q)=>it(Se(i,q)),printDisplayList:async(...i)=>JSON.parse(new TextDecoder().decode(await ve(...i))),frame:async(i,q)=>Ve(await ae(i,q))},save:async()=>new Uint8Array(await se()),on:(i,q)=>S.on(i,q),onFailure:i=>_.onFailure(i),get failure(){return _.failure??S.failure},dispose:()=>(w&&(w.disposed=true),F("Collaboration replica is retired"),G$1?.dispose(),_.dispose())};if(y!==void 0&&!w){let i,q,K,z=async de=>{let[ye,...ue]=de.map(Ze=>Ze.slice()),Re=await _.submit("applyUpdate",{payload:{update:ye,...ue.length?{updates:ue}:{}}},{lane:"collab",fence:true}).ack;if(Re.status!=="applied"&&Re.status!=="noop")throw new Error(Re.reason??"Remote update refused");let qe=Re.workbook?.result?.refusedUpdate;if(qe)throw new Error(qe);return Re},oe=L$1({clientId:y,encodeStateVector:()=>pe(),encodeStateAsUpdate:de=>ce(de?.slice()),applyUpdate:async de=>i?i(de.slice()):z([de]),applyUpdateChunks:async de=>{if(de.length===0)throw new RangeError("applyUpdateChunks requires at least one update");if(q)return q(de.map(ue=>ue.slice()));if(!i)return z([...de]);let ye;for(let ue of de)ye=await i(ue.slice());return ye},onUpdate:de=>S.on("collaborationUpdate",({update:ye,origin:ue})=>de(ye.slice(),ue))}),Fe={open(de,ye){let ue=++W;return m.set(ue,{receive:de,lost:ye}),{async post(_e){if(!m.has(ue)||be.failure)throw new Error("Collaboration replica is retired");let Re={provider:ue,ops:_e};if(K)return K(Re);let qe=await _.submit("collabPipe",{payload:Re},{lane:"collab",fence:true}).ack;if(qe.status!=="applied"&&qe.status!=="noop")throw new Error(qe.reason??"Collaboration pipe refused");return qe},close:()=>{m.delete(ue);}}}};J$1(oe,Fe),Object.defineProperty(be,"replica",{value:oe,enumerable:true}),be.bindCollaboration=(de,ye,ue)=>(i=de,q=ye,K=ue,J$1(oe,ue?Fe:void 0),()=>{i===de&&(i=void 0,q=void 0,K=void 0,J$1(oe,Fe));});}let mo=async i=>{let q=await S.call.replay(i).catch(K=>{throw K instanceof Error&&K.name==="WorkbookPeerHydrationError"?new P("mutation-outside-replay",K.message):K});if(i.op.method==="setActiveSheet")I={...I,activeSheet:i.op.args[0]};else if(q.result!==null&&typeof q.result=="object"&&"sheetInfo"in q.result){let K=q.result.sheetInfo;I={...I,activeSheet:K.activeSheet,sheets:K.sheetIds.map((z,oe)=>({id:z,index:oe,name:K.sheetNames[oe]}))};}return q},Te=w;Te&&(Te.snapshot={beginPeerSnapshot:(...i)=>S.call.beginPeerSnapshot(...i),pullPeerSnapshot:()=>S.call.pullPeerSnapshot(),endPeerSnapshot:i=>S.call.endPeerSnapshot(i)});let Ye=Te?async i=>{try{await S.call.attachPeer(i,Te.sequence);}catch(q){throw q instanceof Error&&q.name==="WorkbookPeerHydrationError"?new P("version-mismatch",q.message):q}}:void 0;return L.set(be,{replay:mo,initialVersion:w?.version??Z,attachPeer:Ye,detachPeer:Te?()=>S.call.detachPeer():void 0,editPeerAttached:false,cellInput:Te?async(i,q,K)=>{let z="";for(let oe=K+1;oe>0;oe=Math.floor((oe-1)/26))z=String.fromCharCode(65+(oe-1)%26)+z;return (await S.call.cellInputs(i,`${z}${q+1}`)).cells[0]?.[0]?.input??""}:void 0,preview:Te?async(i,q,K)=>Ve(await S.call.preview(i,q,K)):void 0,get initialCalculation(){return Te?.initialCalculation}}),w&&Fo.set(be,w),G$1&&Co.set(be,G$1.recovery),be}var uo=class extends Error{constructor(p){super(`Engine refused workbook recovery: ${JSON.stringify(p)}`);a(this,"result",p);this.name="WorkbookRecoveryRefusal";}},fo=new WeakMap;function xn(o,n){fo.get(o)?.fail(n);}function xt(o){let n=fo.get(o);if(!n)throw new TypeError("Workbook edit peer does not support retained operations");return n}function An(o){let n=xt(o);return Object.fromEntries(Object.keys(I).map(p=>[p,(...m)=>n.applyRecoveryOp({method:p,args:m})]))}var Ge=class extends Error{constructor(p){super(`Workbook edit peer failed: ${p.message}`);a(this,"failure",p);this.name="WorkbookEditPeerFailedError";}};function At(){return globalThis.crypto.getRandomValues(new Uint32Array(1))[0]}function st(o){return new Uint8Array(o).buffer}function $n(o){let{session:n,peer:p}=o,m=L.get(n);if(!m)throw new TypeError("Workbook session does not support edit replay");if(m.editPeerAttached)throw new Error("Workbook session already has an attached edit peer");if(m.initialVersion!==void 0&&p.version()!==m.initialVersion){if(m.attachPeer)throw new P("version-mismatch","Workbook peer version differs from retained worker hydration");z(p,m.initialVersion);}let W=m.replay,f=o.now??Date.now,F=o.randomSeed??At,E,x=m.attachPeer?m.initialCalculation:void 0,O$1=!!m.attachPeer&&x!==void 0,M$1=0,S=0,w=false,Q=false,j=Promise.resolve(),D=m.attachPeer?.(p.version());D&&(j=D.catch(b=>{a(b);}));let I$1=()=>{},L$1,Z=new Promise((b,V)=>{L$1=V;});Z.catch(()=>{});let H=new WeakMap,te=new WeakSet,l=0,s=[],y=[],k$1=new Set,P$1=false;function T(){for(let b of y.splice(0))b();}function a(b,V=true){if(!E){E=b instanceof Error?b:new Error(String(b)),L$1(new Ge(E));for(let se of k$1)se.reject(new Ge(E));if(k$1.clear(),s.length=0,T(),I$1(),V)try{o.onError?.(E);}catch{}}}function h(){n.failure&&a(n.failure);}function g$1(){if(h(),E)throw new Ge(E)}function R(b){let V=W(b);j=Promise.all([j,V]).then(([,se])=>{if(se.sequence!==b.sequence)throw new Error(`Workbook replay acknowledgement mismatch at sequence ${b.sequence} (${b.op.method})`);g$1(),M$1=se.sequence;for(let ke of k$1)ke.sequence>M$1||(k$1.delete(ke),ke.resolve());}).catch(se=>{a(se);});}function $(){if(!P$1){P$1=true;try{for(h();!E&&s[0]?.resolved;){let b=s.shift()?.envelope;if(b){S+=1;try{R({sequence:S,...b});}catch(V){a(V);}h();}}}finally{P$1=false,s.length||T();}}}function B(b){if(N(b))throw new uo(b);return b}function ae(b,V){let se=H.get(b);if(se){if("error"in se)throw se.error;return V?B(se.result):se.result}if(te.has(b))throw new Error("Workbook queued operation is already applying");let ke=x,Se=b.calculation??{nowSerial:ba(f()),randSeed:F()},re={resolved:false};V||s.push(re),te.add(b),l+=1;let le,ve,pe;try{b.method==="acceptProposal"&&(pe=JSON.stringify(p.listProposals()));try{le=structuredClone({calculation:Se,op:b});}catch(We){ve=We;}if(V){if(!le)throw ve;M({sequence:1,...le});}p.setCalculationContext(Se),O$1&&(x=Se);let ce=O(p,b);return H.set(b,{result:ce}),V?B(ce):(N(ce)?O$1&&x===Se&&(p.setCalculationContext(ke??null),x=ke):le?re.envelope=le:a(ve),ce)}catch(ce){throw !V&&ce instanceof k&&pe!==void 0&&pe!==JSON.stringify(p.listProposals())&&(le?re.envelope={...le,staleProposal:structuredClone({cells:ce.cells,targets:ce.targets})}:a(ve)),!re.envelope&&O$1&&x===Se&&(p.setCalculationContext(ke??null),x=ke),H.has(b)||H.set(b,{error:ce}),ce}finally{te.delete(b),l-=1,re.resolved=true,V||$();}}function ne(b){return g$1(),ae(b,false)}function r(){if(h(),!E)throw new Error("Recovery requires a failed workbook edit peer");if(Q&&m?.attachPeer)throw new Error("Workbook edit peer was disposed");if(w)throw new Error("Workbook edit peer recovery was already saved");if(l)throw new Error("Workbook queued operation is still applying")}let A={};for(let b of Object.keys(I))Object.defineProperty(A,b,{enumerable:true,value:(...V)=>ne({method:b,args:V})});m.editPeerAttached=true,I$1=n.onFailure(a),h();async function X(){do{g$1(),(s.length||P$1)&&(await new Promise(V=>{y.push(V);}),g$1());let b=S;if(await Promise.race([j,Z]),g$1(),!s.length&&!P$1&&S===b&&M$1>=b)return}while(true)}let Y={...A,get state(){return h(),E?"failed":"ready"},get error(){return h(),E},get acknowledgedSequence(){return M$1},get sentSequence(){return S},flush:X,async save(){await X();try{let b=await Promise.race([n.save(),Z]);return g$1(),st(b)}catch(b){throw a(b),b}},recoverySave(){r();let b=st(p.save());return w=true,{bytes:b,recovery:true}},dispose(){Q||(Q=true,a(new g("disposed","Workbook edit peer was disposed"),false),I$1(),m.editPeerAttached=false,m.detachPeer?.().catch(()=>{}));}};return fo.set(Y,{fail:a,whenAcknowledged(){try{g$1();}catch(b){return Promise.reject(b)}return M$1>=S?Promise.resolve():new Promise((b,V)=>{k$1.add({sequence:S,resolve:b,reject:V});})},applyQueuedOp:ne,applyRecoveryOp(b){return r(),ae(b,true)}}),Y}export{qo as a,Me as b,Co as c,Wn as d,Ot as e,uo as f,xn as g,xt as h,An as i,Ge as j,$n as k};
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-O2XFH626.js';var oe=80,se=2e4,ae=45e3,ie=3e3,ce=1048576,ue=16384;var le=1024,P=["#0B57D0","#B3261E","#146C2E","#6B4EFF","#8E24AA","#00639B","#8E4E00","#7D5260"];function C(e){return e?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null}function q(e){return {user:{...e.user},cursor:C(e.cursor)}}function x(e,n){return !e||!n?e===n:e.sheet===n.sheet&&e.anchor.row===n.anchor.row&&e.anchor.col===n.anchor.col&&e.head.row===n.head.row&&e.head.col===n.head.col}function D(e,n){return !e||!n?e===n:e.user.name===n.user.name&&e.user.color===n.user.color&&x(e.cursor,n.cursor)}function G(e){return P[e%P.length]}function m(e,n){if(typeof e!="string"||!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(e))return G(n);let r=e.slice(1).toUpperCase();return r.length===6?`#${r}`:`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`}function pe(e,n){return {name:e?.name.trim().slice(0,128)||"Anonymous",color:m(e?.color,n)}}function de(e,n,r,t,o={}){let s=o.maxPeers??1024;if(!Number.isSafeInteger(s)||s<1)throw new RangeError("Awareness peer limit must be a positive integer");let i=false,c=0;for(let u of n){if(u.clientId===r)continue;let l=e.get(u.clientId);if(l&&u.clock<l.clock)continue;if(l&&u.clock===l.clock){l.lastSeen=t;continue}if(!l&&e.size>=s){c+=1;continue}let y=u.state?.cursor!=null&&(!l?.state||!x(l.state.cursor,u.state.cursor)),d=u.state?q(u.state):null;i||(i=!D(l?.state??null,d)),e.set(u.clientId,{clock:u.clock,state:d,lastSeen:t,cursorMovedAt:y?t:l?.cursorMovedAt??0});}return c>0&&o.onPeersDiscarded?.(c),i}function fe(e,n,r=45e3){let t=false;for(let[o,s]of e)n-s.lastSeen<r||(t||(t=s.state!==null),e.delete(o));return t}function Ae(e){let n=[];for(let[r,t]of e)t.state&&n.push({clientId:r,clock:t.clock,user:{...t.state.user},cursor:C(t.state.cursor),lastSeen:t.lastSeen,cursorMovedAt:t.cursorMovedAt});return n.sort((r,t)=>r.clientId-t.clientId),n}function ye(e,n,r=1048576,t=16384){let o=n.indexOf(e.sheet);return o<0||r<1||t<1||[e.anchor,e.head].some(({row:i,col:c})=>!Number.isSafeInteger(i)||!Number.isSafeInteger(c)||i<0||c<0||i>=r||c>=t)?null:{sheetIndex:o,range:{top:Math.min(e.anchor.row,e.head.row),left:Math.min(e.anchor.col,e.head.col),bottom:Math.max(e.anchor.row,e.head.row),right:Math.max(e.anchor.col,e.head.col)}}}function be(e,n){if(typeof e!="object"||e===null)return false;let r=e,t=o=>!!o&&Number.isSafeInteger(o.row)&&o.row>=0&&Number.isSafeInteger(o.col)&&o.col>=0;return typeof r.sheet=="string"&&r.sheet.length>0&&r.sheet.length<=256&&t(r.anchor)&&t(r.head)}var R=new WeakMap;function he(e){return R.get(e)}var E=new WeakMap;function me(e,n){n?E.set(e,n):E.delete(e);}function Ee(e){return E.get(e)}function ge(e){let n=()=>{throw new Error("Worker replica encoding requires the async adapter")},r={clientId:e.clientId,async:e,encodeStateVector:n,encodeStateAsUpdate:n,applyUpdate:t=>e.applyUpdate(t.slice()),onUpdate:t=>e.onUpdate(t)};return R.set(r,e),r}function _e(e){let n=[];for(let r of e)r.op==="event"&&r.event.type==="message"&&n.push(r.event.data);return n}function Ue(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}var Y=new Set(["backpressure","protocol","replica","transport"]);var H=e=>Number.isSafeInteger(e)&&e>=0;function j(e){let n=e;return typeof n=="object"&&n!==null&&Y.has(n.code)&&typeof n.message=="string"}function z(e,n){if(typeof e!="object"||e===null)return false;let r=e;switch(r.type){case "open":return true;case "message":return r.data instanceof ArrayBuffer&&r.data.byteLength<=n;case "close":return r.reason===void 0||typeof r.reason=="string";default:return false}}function Pe(e,n,r){if(typeof e!="object"||e===null)return false;let{provider:t,ops:o}=e;return !Number.isSafeInteger(t)||t<0||!Array.isArray(o)||o.length===0?false:o.every(s=>{if(typeof s!="object"||s===null)return false;let i=s;if(!H(i.seq))return false;switch(i.op){case "create":return typeof i.options=="object"&&i.options!==null&&Object.keys(i.options).every(c=>r.optionKeys.has(c));case "connect":case "disconnect":case "destroy":return true;case "fail":return j(i.error);case "cursor":return typeof i.broadcast=="boolean"&&(i.cursor===null||r.validCursor(i.cursor,n));case "event":return z(i.event,n);default:return false}})}function Ce(){let e=globalThis.performance;return typeof e?.now!="function"?0:typeof e.timeOrigin=="number"?e.timeOrigin:Date.now()-e.now()}var A=16777216,J=4096,S=1024,I=0,O=1,Q=2,k=3,L=0,v=1,V=2,Z=0,ee=Number.MAX_SAFE_INTEGER,ne=10,g=new TextEncoder().encode("\0betteroffice-document-fingerprint-v1\0"),a=class extends Error{constructor(n){super(n),this.name="ProtocolError";}},w=class{constructor(n){a$1(this,"bytes",n);a$1(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let n=0,r=1,t=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new a("Truncated varUint");let o=this.bytes[this.offset++],s=o&127;if(s>Math.floor((ee-n)/r))throw new a("varUint exceeds Number.MAX_SAFE_INTEGER");if(n+=s*r,t+=1,(o&128)===0){if(t>1&&s===0)throw new a("Non-canonical varUint");return n}if(t>=8)throw new a("varUint exceeds Number.MAX_SAFE_INTEGER");r*=128;}}readVarUint8Array(){let n=this.readVarUint(),r=this.bytes.byteLength-this.offset;if(n>r)throw new a("Truncated varUint8Array");let t=this.bytes.slice(this.offset,this.offset+n);return this.offset+=n,t}readVarString(){let n=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(r){throw new a(`Invalid UTF-8 string${r instanceof Error?`: ${r.message}`:""}`)}}};function p(e){if(!Number.isSafeInteger(e)||e<0)throw new a("varUint value must be a non-negative safe integer");let n=[],r=e;for(;r>=128;)n.push(r%128|128),r=Math.floor(r/128);return n.push(r),Uint8Array.from(n)}function f(e,n){let r=0;for(let s of e)if(r+=s.byteLength,r>n)throw new a(`Frame exceeds ${n} bytes`);let t=new Uint8Array(r),o=0;for(let s of e)t.set(s,o),o+=s.byteLength;return t}function re(e){let n=new TextEncoder().encode(e);return [p(n.byteLength),n]}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e){if(!b(e))throw new a("Awareness cell must be an object");let{row:n,col:r}=e;if(!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||n<0||r<0)throw new a("Awareness cell coordinates must be non-negative safe integers");return {row:n,col:r}}function X(e,n){if(e===null)return null;if(!b(e)||!b(e.user))throw new a("Awareness state must contain a user");let{name:r,color:t}=e.user;if(typeof r!="string"||r.length===0||r.length>128)throw new a(`Awareness user name must contain 1 to ${128} characters`);let o=m(t,n),s=e.cursor;if(s==null)return {user:{name:r,color:o},cursor:null};if(!b(s)||typeof s.sheet!="string")throw new a("Awareness cursor must contain a sheet identifier");if(s.sheet.length===0||s.sheet.length>256)throw new a(`Awareness sheet identifier must contain 1 to ${256} characters`);return {user:{name:r,color:o},cursor:{sheet:s.sheet,anchor:M(s.anchor),head:M(s.head)}}}function _(e,n,r){return f([p(I),p(e),p(n.byteLength),n],r)}function Me(e,n=A){return _(L,e,n)}function Ie(e,n=A){return _(v,e,n)}function Oe(e,n=A){return _(V,e,n)}function ke(e,n=A){if(e.length>S)throw new a(`Awareness update exceeds ${S} states`);let r=[p(e.length)];for(let o of e){if(!Number.isSafeInteger(o.clientId)||o.clientId<=0)throw new a("Awareness clientId must be a positive safe integer");if(!Number.isSafeInteger(o.clock)||o.clock<0)throw new a("Awareness clock must be a non-negative safe integer");let s=X(o.state,o.clientId);r.push(p(o.clientId),p(o.clock),...re(JSON.stringify(s)));}let t=f(r,n);return f([p(O),p(t.byteLength),t],n)}function Le(e=A){return f([p(k)],e)}function ve(e,n=S,r){if(!(e instanceof Uint8Array))throw new a("Awareness update must be a Uint8Array");if(!Number.isSafeInteger(n)||n<1)throw new a("Awareness state limit must be a positive integer");let t=new w(e),o=t.readVarUint();if(o>n){let c=new a(`Awareness update exceeds ${n} states`);if(!r)throw c;r(c);}let s=[],i=Math.min(o,n);for(let c=0;c<i;c++){let u,l,y;try{u=t.readVarUint(),l=t.readVarUint(),y=t.readVarString();}catch(d){if(!r)throw d;return r(new a(`Awareness entry ${c+1} could not be decoded: ${d instanceof Error?d.message:"Unknown error"}`)),s}try{if(u<=0)throw new a("Awareness clientId must be a positive safe integer");let d=JSON.parse(y);s.push({clientId:u,clock:l,state:X(d,u)});}catch(d){let U=d instanceof a?d:new a(`Invalid awareness JSON${d instanceof Error?`: ${d.message}`:""}`);if(!r)throw U;r(new a(`Awareness entry ${c+1} discarded: ${U.message}`));}}if(o<=n&&!t.done){let c=new a("Trailing awareness update data");if(!r)throw c;r(c);}return s}function B(e){let n=g.byteLength+32,r=e.byteLength-n;if(r<0)return e;for(let t=0;t<g.byteLength;t+=1)if(e[r+t]!==g[t])return e;return e.subarray(0,r)}var F=Number.MAX_SAFE_INTEGER-1,$=BigInt(F),te=65536;function W(e){let n=0,r=()=>{let i=0n;for(let c=0;c<ne&&n<e.byteLength;c+=1){let u=e[n++];if(i|=BigInt(u&127)<<BigInt(7*c),u<128)return i}},t=r();if(t===void 0)return;let o=n,s=[];for(let i=t;i>0n;i-=1n){let c=n,u=r(),l=r();if(u===void 0||l===void 0)return;s.push({client:u,clock:l,start:c,end:n});}return n===e.byteLength?{header:o,entries:s}:void 0}function Ve(e){let n=B(e),r=W(n);if(!r)return e;let{header:t,entries:o}=r;if(!(o.length>=te||o.some(({client:s})=>s===$)))return f([p(o.length+1),n.subarray(t),p(F),p(0),e.subarray(n.byteLength)],Number.MAX_SAFE_INTEGER)}function Xe(e){let n=B(e),r=W(n);if(!r)return {stateVector:e,open:false};let t=r.entries.filter(({client:o,clock:s})=>o!==$||s!==0n);return t.length===r.entries.length?{stateVector:e,open:false}:{stateVector:f([p(t.length),...t.map(({start:o,end:s})=>n.subarray(o,s)),e.subarray(n.byteLength)],Number.MAX_SAFE_INTEGER),open:true}}function Be(e,n=A,r=J){if(!(e instanceof Uint8Array))throw new a("Frame must be a Uint8Array");if(e.byteLength===0)throw new a("Frame is empty");if(e.byteLength>n)throw new a(`Frame exceeds ${n} bytes`);if(!Number.isSafeInteger(r)||r<1)throw new a("Message limit must be a positive integer");let t=new w(e),o=[];for(;!t.done;){if(o.length>=r)throw new a(`Frame exceeds ${r} messages`);let s=t.readVarUint();switch(s){case I:{let i=t.readVarUint(),c=t.readVarUint8Array();if(i===L)o.push({type:"sync-step-1",stateVector:c});else if(i===v)o.push({type:"sync-step-2",update:c});else if(i===V)o.push({type:"update",update:c});else throw new a(`Unknown sync message type ${i}`);break}case O:o.push({type:"awareness",update:t.readVarUint8Array()});break;case Q:{let i=t.readVarUint();if(i!==Z)throw new a(`Unknown auth message type ${i}`);o.push({type:"auth",reason:t.readVarString()});break}case k:o.push({type:"query-awareness"});break;default:throw new a(`Unknown top-level message type ${s}`)}}return o}export{ke as A,Le as B,ve as C,B as D,F as E,Ve as F,Xe as G,Be as H,he as I,me as J,Ee as K,ge as L,_e as a,Ue as b,Pe as c,Ce as d,oe as e,se as f,ae as g,ie as h,ce as i,ue as j,le as k,P as l,G as m,m as n,pe as o,de as p,fe as q,Ae as r,ye as s,be as t,A as u,J as v,S as w,Me as x,Ie as y,Oe as z};
@@ -1 +0,0 @@
1
- import {E,c,t,u}from'./chunk-JGTBRHCP.js';import {a as a$1}from'./chunk-O2XFH626.js';var Me=Symbol("session-transfer"),Je=Symbol("session-deferred");function rt(e){return {[Je]:true,promise:e}}function Ie(e){return oe(e)&&e[Je]===true}function tt(e,r){return {[Me]:true,value:e,transfer:r}}function De(e){return oe(e)&&e[Me]===true}function D(e,r){return Object.prototype.hasOwnProperty.call(e,r)}function oe(e){return e!==null&&typeof e=="object"}function he(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Xe(e){return !oe(e)||e.protocol!==1?false:e.kind==="wasm-compile"||e.kind==="dispose"||e.kind==="call"&&he(e.id)&&typeof e.method=="string"&&Array.isArray(e.args)}function nt(e){if(!oe(e)||e.protocol!==1)return false;switch(e.kind){case "wasm-module":try{return typeof e.url=="string"&&(e.hydration===void 0||typeof e.hydration=="string")&&Object.prototype.toString.call(e.module)==="[object WebAssembly.Module]"}catch{return false}case "reply":return he(e.id)&&(e.ok===true&&D(e,"value")||e.ok===false&&oe(e.error)&&typeof e.error.name=="string"&&typeof e.error.message=="string");case "event":return typeof e.name=="string"&&D(e,"payload");case "progress":return he(e.id);case "failure":return ["crash","trap","out-of-memory","message","silence","disposed"].includes(e.code)&&typeof e.message=="string"&&(e.diagnostics===void 0||typeof e.diagnostics=="string");default:return false}}var Ne="SessionSuperseded",M=class extends Error{constructor(t,n,o){super(n);a$1(this,"code",t);a$1(this,"diagnostics",o);this.name="SessionFailure";}};function qe(e,r){let t=new Set,n=false;function o(i,u){if(n)return ()=>{};e.addEventListener(i,u);let c=()=>{e.removeEventListener(i,u),t.delete(c);};return t.add(c),e.start?.(),c}return {post(i,u=[]){if(n)throw new M("disposed","Session transport is closed");e.postMessage(i,u);},listen(i){return o("message",u=>i(u.data))},onError(i){let u=o("error",l=>i(new M("crash",l.message||"Session worker crashed"))),c=o("messageerror",()=>i(new M("message","Session transport received an unreadable message")));return ()=>{u(),c();}},close(){if(!n){n=true;for(let i of [...t])i();r();}}}}function lt(e){return qe(e,()=>e.terminate())}function dt(e){return qe(e,()=>e.close?.())}function Ue(){return new URL("./generated/xlsx_wasm_bg.wasm",import.meta.url)}var A=class e{static __wrap(r){let t=Object.create(e.prototype);return t.__wbg_ptr=r,Le.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,Le.unregister(this),r}free(){let r=this.__destroy_into_raw();a.__wbg_xlsxdocument_free(r,0);}acceptProposalJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_acceptProposalJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}adoptPeerVersion(r){let t=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),n=m,o=a.xlsxdocument_adoptPeerVersion(this.__wbg_ptr,t,n);if(o[1])throw f(o[0])}applyEditsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_applyEditsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}applyFormatJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_applyFormatJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}applyOpsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_applyOpsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}applyOpsProfiledJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_applyOpsProfiledJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}applyUpdateJson(r){let t,n;try{let u=N(r,a.__wbindgen_malloc),c=m,l=a.xlsxdocument_applyUpdateJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}beginPeerSnapshot(r,t){let n=a.xlsxdocument_beginPeerSnapshot(this.__wbg_ptr,r,t);if(n[1])throw f(n[0])}calculationStatusJson(){let r,t;try{let i=a.xlsxdocument_calculationStatusJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}captureFormatJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_captureFormatJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}cellJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_cellJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}cellPositionJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_cellPositionJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}cellRectJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_cellRectJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}chartAtPointJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_chartAtPointJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}chartsJson(r){let t,n;try{let u=a.xlsxdocument_chartsJson(this.__wbg_ptr,r);var o=u[0],i=u[1];if(u[3])throw o=0,i=0,f(u[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}clearUpdateObservation(){a.xlsxdocument_clearUpdateObservation(this.__wbg_ptr);}get clientId(){return a.xlsxdocument_clientId(this.__wbg_ptr)}conditionalFormatsJson(r){let t,n;try{let u=a.xlsxdocument_conditionalFormatsJson(this.__wbg_ptr,r);var o=u[0],i=u[1];if(u[3])throw o=0,i=0,f(u[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}displayListForJson(r,t){let n,o;try{let c=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=m,S=a.xlsxdocument_displayListForJson(this.__wbg_ptr,r,c,l);var i=S[0],u=S[1];if(S[3])throw i=0,u=0,f(S[2]);return n=i,o=u,b(i,u)}finally{a.__wbindgen_free(n,o,1);}}displayListJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_displayListJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}displayListProfiledJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_displayListProfiledJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}documentVersion(){let r,t;try{let n=a.xlsxdocument_documentVersion(this.__wbg_ptr);return r=n[0],t=n[1],b(n[0],n[1])}finally{a.__wbindgen_free(r,t,1);}}drainUpdateEvent(){let r=a.xlsxdocument_drainUpdateEvent(this.__wbg_ptr);if(r[3])throw f(r[2]);var t=X(r[0],r[1]).slice();return a.__wbindgen_free(r[0],r[1]*1,1),t}editCellJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_editCellJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}editCellProfiledJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_editCellProfiledJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}editCellsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_editCellsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}editChartsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_editChartsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}encodeDiff(r){let t=N(r,a.__wbindgen_malloc),n=m,o=a.xlsxdocument_encodeDiff(this.__wbg_ptr,t,n);if(o[3])throw f(o[2]);var i=X(o[0],o[1]).slice();return a.__wbindgen_free(o[0],o[1]*1,1),i}encodeStateAsUpdate(){let r=a.xlsxdocument_encodeStateAsUpdate(this.__wbg_ptr);var t=X(r[0],r[1]).slice();return a.__wbindgen_free(r[0],r[1]*1,1),t}encodeStateVector(){let r=a.xlsxdocument_encodeStateVector(this.__wbg_ptr);var t=X(r[0],r[1]).slice();return a.__wbindgen_free(r[0],r[1]*1,1),t}endPeerSnapshot(){a.xlsxdocument_endPeerSnapshot(this.__wbg_ptr);}exportMarkdownJson(r,t){let n,o;try{let c=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),l=m,S=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),h=m,x=a.xlsxdocument_exportMarkdownJson(this.__wbg_ptr,c,l,S,h);var i=x[0],u=x[1];if(x[3])throw i=0,u=0,f(x[2]);return n=i,o=u,b(i,u)}finally{a.__wbindgen_free(n,o,1);}}exportStructuredJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_exportStructuredJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}findTextJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_findTextJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}historyStateJson(){let r,t;try{let i=a.xlsxdocument_historyStateJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}listDefinedNamesJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_listDefinedNamesJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}listProposalsJson(){let r,t;try{let i=a.xlsxdocument_listProposalsJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}mergedRangesJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_mergedRangesJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}moveChartJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_moveChartJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}moveRangeJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_moveRangeJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}nextPeerSnapshotChunk(){let r=a.xlsxdocument_nextPeerSnapshotChunk(this.__wbg_ptr);if(r[2])throw f(r[1]);return f(r[0])}static openCollaborative(r,t){let n=N(r,a.__wbindgen_malloc),o=m,i=a.xlsxdocument_openCollaborative(n,o,t);if(i[2])throw f(i[1]);return e.__wrap(i[0])}static openRecoveryCheckpoint(r,t){let n=N(r,a.__wbindgen_malloc),o=m,i=a.xlsxdocument_openRecoveryCheckpoint(n,o,t);if(i[2])throw f(i[1]);return e.__wrap(i[0])}static openWithCalculationJson(r,t){let n=N(r,a.__wbindgen_malloc),o=m,i=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),u=m,c=a.xlsxdocument_openWithCalculationJson(n,o,i,u);if(c[2])throw f(c[1]);return e.__wrap(c[0])}static openWithPeerHydrationJson(r,t){let n=N(r,a.__wbindgen_malloc),o=m,i=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),u=m,c=a.xlsxdocument_openWithPeerHydrationJson(n,o,i,u);if(c[2])throw f(c[1]);return e.__wrap(c[0])}static open(r){let t=N(r,a.__wbindgen_malloc),n=m,o=a.xlsxdocument_open(t,n);if(o[2])throw f(o[1]);return e.__wrap(o[0])}patchRangeStyleJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_patchRangeStyleJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}peerHydrationJson(){let r,t;try{let i=a.xlsxdocument_peerHydrationJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}printDisplayListJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_printDisplayListJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}proposeJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_proposeJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}rangeCellsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_rangeCellsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}readCellsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_readCellsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}recoveryCheckpoint(r,t){let n=a.xlsxdocument_recoveryCheckpoint(this.__wbg_ptr,r,ae(t)?16777215:t?1:0);if(n[3])throw f(n[2]);var o=X(n[0],n[1]).slice();return a.__wbindgen_free(n[0],n[1]*1,1),o}redoJson(){let r,t;try{let i=a.xlsxdocument_redoJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}rejectProposalJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_rejectProposalJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}renderPng(r){let t=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),n=m,o=a.xlsxdocument_renderPng(this.__wbg_ptr,t,n);if(o[3])throw f(o[2]);var i=X(o[0],o[1]).slice();return a.__wbindgen_free(o[0],o[1]*1,1),i}renderRangePng(r){let t=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),n=m,o=a.xlsxdocument_renderRangePng(this.__wbg_ptr,t,n);if(o[3])throw f(o[2]);var i=X(o[0],o[1]).slice();return a.__wbindgen_free(o[0],o[1]*1,1),i}saveBytes(){let r=a.xlsxdocument_saveBytes(this.__wbg_ptr);if(r[3])throw f(r[2]);var t=X(r[0],r[1]).slice();return a.__wbindgen_free(r[0],r[1]*1,1),t}searchTextJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_searchTextJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}selectionDataJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_selectionDataJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}selectionFormattingJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_selectionFormattingJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}setActiveSheet(r){let t=a.xlsxdocument_setActiveSheet(this.__wbg_ptr,r);if(t[1])throw f(t[0])}setCalculationContextJson(r){let t=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),n=m,o=a.xlsxdocument_setCalculationContextJson(this.__wbg_ptr,t,n);if(o[1])throw f(o[0])}setRangeNumberFormatJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_setRangeNumberFormatJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}sheetCount(){return a.xlsxdocument_sheetCount(this.__wbg_ptr)>>>0}sheetInfoForJson(r){let t,n;try{let u=a.xlsxdocument_sheetInfoForJson(this.__wbg_ptr,r);var o=u[0],i=u[1];if(u[3])throw o=0,i=0,f(u[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}sheetInfoJson(){let r,t;try{let i=a.xlsxdocument_sheetInfoJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}startUpdateObservation(){let r=a.xlsxdocument_startUpdateObservation(this.__wbg_ptr);if(r[1])throw f(r[0])}undoJson(){let r,t;try{let i=a.xlsxdocument_undoJson(this.__wbg_ptr);var n=i[0],o=i[1];if(i[3])throw n=0,o=0,f(i[2]);return r=n,t=o,b(n,o)}finally{a.__wbindgen_free(r,t,1);}}validateEditsJson(r){let t,n;try{let u=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=a.xlsxdocument_validateEditsJson(this.__wbg_ptr,u,c);var o=l[0],i=l[1];if(l[3])throw o=0,i=0,f(l[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}static version(){let r,t;try{let n=a.xlsxdocument_version();return r=n[0],t=n[1],b(n[0],n[1])}finally{a.__wbindgen_free(r,t,1);}}visibleMergedRangesJson(r,t){let n,o;try{let c=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),l=m,S=a.xlsxdocument_visibleMergedRangesJson(this.__wbg_ptr,r,c,l);var i=S[0],u=S[1];if(S[3])throw i=0,u=0,f(S[2]);return n=i,o=u,b(i,u)}finally{a.__wbindgen_free(n,o,1);}}};Symbol.dispose&&(A.prototype[Symbol.dispose]=A.prototype.free);var ee=class{__destroy_into_raw(){let r=this.__wbg_ptr;return this.__wbg_ptr=0,He.unregister(this),r}free(){let r=this.__destroy_into_raw();a.__wbg_xlsxsnapshotbuilder_free(r,0);}advance(r,t){let n=a.xlsxsnapshotbuilder_advance(this.__wbg_ptr,r,t);if(n[2])throw f(n[1]);return n[0]!==0}finish(){let r=this.__destroy_into_raw(),t=a.xlsxsnapshotbuilder_finish(r);if(t[2])throw f(t[1]);return A.__wrap(t[0])}constructor(){let r=a.xlsxsnapshotbuilder_new();return this.__wbg_ptr=r,He.register(this,this.__wbg_ptr,this),this}push(r){let t=N(r,a.__wbindgen_malloc),n=m,o=a.xlsxsnapshotbuilder_push(this.__wbg_ptr,t,n);if(o[1])throw f(o[0])}};Symbol.dispose&&(ee.prototype[Symbol.dispose]=ee.prototype.free);function Ve(){return a.allocationFailure()}function Be(){return a.displayListCellLimit()}function Ke(e,r,t){let n,o;try{let c=N(e,a.__wbindgen_malloc),l=m,S=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),h=m,x=w(t,a.__wbindgen_malloc,a.__wbindgen_realloc),R=m,E=a.exportXlsxMarkdownJson(c,l,S,h,x,R);var i=E[0],u=E[1];if(E[3])throw i=0,u=0,f(E[2]);return n=i,o=u,b(i,u)}finally{a.__wbindgen_free(n,o,1);}}function ze(e,r){let t,n;try{let u=N(e,a.__wbindgen_malloc),c=m,l=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),S=m,h=a.exportXlsxStructuredJson(u,c,l,S);var o=h[0],i=h[1];if(h[3])throw o=0,i=0,f(h[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}function Qe(e,r){let t,n;try{let u=w(e,a.__wbindgen_malloc,a.__wbindgen_realloc),c=m,l=w(r,a.__wbindgen_malloc,a.__wbindgen_realloc),S=m,h=a.renderXlsxMarkdownJson(u,c,l,S);var o=h[0],i=h[1];if(h[3])throw o=0,i=0,f(h[2]);return t=o,n=i,b(o,i)}finally{a.__wbindgen_free(t,n,1);}}function wr(){return {__proto__:null,"./xlsx_wasm_bg.js":{__proto__:null,__wbg___wbindgen_is_function_1f9d30630b8b1d3d:function(r){return typeof r=="function"},__wbg___wbindgen_is_undefined_8865fb403f8fe9d8:function(r){return r===void 0},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(r,t){throw new Error(b(r,t))},__wbg_call_6137034ef55c9d0f:function(){return we(function(r,t){return r.call(t)},arguments)},__wbg_error_1ca51171bd9a2708:function(r,t){console.error(b(r,t));},__wbg_getRandomValues_a608c4436c19407a:function(){return we(function(r,t){globalThis.crypto.getRandomValues(X(r,t));},arguments)},__wbg_getTimezoneOffset_2e851fdaecc2dc92:function(r){return r.getTimezoneOffset()},__wbg_get_31af05bd4842a84f:function(){return we(function(r,t){return Reflect.get(r,t)},arguments)},__wbg_new_2bdcdfcebdfc34d2:function(r,t){return new TypeError(b(r,t))},__wbg_new_343a093a3c2ffb4e:function(r,t){return new Error(b(r,t))},__wbg_new_34e56228080aa9f8:function(r){return new Date(r)},__wbg_new_from_slice_9a868026ffa4208a:function(r,t){return new Uint8Array(X(r,t))},__wbg_now_aa4ccb83129e9e55:function(){return Date.now()},__wbg_now_b64b08137b67aa67:function(){return performance.now()},__wbg_static_accessor_GLOBAL_266715b9d96ba635:function(){let r=typeof global>"u"?null:global;return ae(r)?0:ie(r)},__wbg_static_accessor_GLOBAL_THIS_10fb7dc1ae063179:function(){let r=typeof globalThis>"u"?null:globalThis;return ae(r)?0:ie(r)},__wbg_static_accessor_SELF_0b583911f537483a:function(){let r=typeof self>"u"?null:self;return ae(r)?0:ie(r)},__wbg_static_accessor_WINDOW_d7f903d1508cbdc4:function(){let r=typeof window>"u"?null:window;return ae(r)?0:ie(r)},__wbindgen_generic_0000000000000001:function(r){return r},__wbindgen_generic_0000000000000002:function(r,t){return b(r,t)},__wbindgen_init_externref_table:function(){let r=a.__wbindgen_externrefs,t=r.grow(4);r.set(0,void 0),r.set(t+0,void 0),r.set(t+1,null),r.set(t+2,true),r.set(t+3,false);}}}}var Le=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>a.__wbg_xlsxdocument_free(e,1)),He=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>a.__wbg_xlsxsnapshotbuilder_free(e,1));function ie(e){let r=a.__externref_table_alloc();return a.__wbindgen_externrefs.set(r,e),r}function X(e,r){return e=e>>>0,Z().subarray(e/1,e/1+r)}function b(e,r){return Sr(e>>>0,r)}var se=null;function Z(){return (se===null||se.byteLength===0)&&(se=new Uint8Array(a.memory.buffer)),se}function we(e,r){try{return e.apply(this,r)}catch(t){let n=ie(t);a.__wbindgen_exn_store(n);}}function ae(e){return e==null}function N(e,r){let t=r(e.length*1,1)>>>0;return Z().set(e,t/1),m=e.length,t}function w(e,r,t){if(t===void 0){let c=le.encode(e),l=r(c.length,1)>>>0;return Z().subarray(l,l+c.length).set(c),m=c.length,l}let n=e.length,o=r(n,1)>>>0,i=Z(),u=0;for(;u<n;u++){let c=e.charCodeAt(u);if(c>127)break;i[o+u]=c;}if(u!==n){u!==0&&(e=e.slice(u)),o=t(o,n,n=u+e.length*3,1)>>>0;let c=Z().subarray(o+u,o+n),l=le.encodeInto(e,c);u+=l.written,o=t(o,n,u,1)>>>0;}return m=u,o}function f(e){let r=a.__wbindgen_externrefs.get(e);return a.__externref_table_dealloc(e),r}var be=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});be.decode();var xr=2146435072,xe=0;function Sr(e,r){return xe+=r,xe>=xr&&(be=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),be.decode(),xe=r),be.decode(Z().subarray(e,e+r))}var le=new TextEncoder;"encodeInto"in le||(le.encodeInto=function(e,r){let t=le.encode(e);return r.set(t),{read:e.length,written:t.length}});var m=0,a;function Er(e,r){return a=e.exports,se=null,a.__wbindgen_start(),a}async function vr(e,r){if(typeof Response=="function"&&e instanceof Response){if(!e.ok)throw new Error(`failed to fetch Wasm: ${e.status} ${e.statusText} fetching '${e.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,r)}catch(o){if(t(e.type)&&e.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",o);else throw o}let n=await e.arrayBuffer();return await WebAssembly.instantiate(n,r)}else {let n=await WebAssembly.instantiate(e,r);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function t(n){switch(n){case "basic":case "cors":case "default":return true}return false}}async function je(e){if(a!==void 0)return a;if(e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),e===void 0)throw new Error("xlsx-wasm requires an explicit module or URL");let r=wr();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:t,module:n}=await vr(await e,r);return Er(t)}var Se=class extends Error{constructor(t,n=[]){super(`stale: ${t.join(", ")}`);a$1(this,"cells");a$1(this,"targets");this.name="StaleProposalError",this.cells=t,this.targets=n;}},Ce=class extends Error{constructor(t,n){super(`requested viewport spans ${t} cells, exceeds the ${n}-cell display-list cap`);a$1(this,"cells",t);a$1(this,"maxCells",n);a$1(this,"code","displayTooLarge");this.name="DisplayTooLargeError";}};function Fr(e){if(!e.startsWith("{"))return null;try{let r=JSON.parse(e);return r.code!=="displayTooLarge"||typeof r.cells!="number"||!Number.isSafeInteger(r.cells)||typeof r.maxCells!="number"||!Number.isSafeInteger(r.maxCells)||r.maxCells<=0||r.cells<=r.maxCells?null:new Ce(r.cells,r.maxCells)}catch{return null}}function Wr(e){if(!e.startsWith("{"))return null;try{let r=JSON.parse(e);return r.code!=="staleProposal"||!Array.isArray(r.cells)?null:new Se(r.cells,Array.isArray(r.targets)?r.targets:[])}catch{return null}}var ye=false,Ye,de,$e=new WeakMap;function bt(e,r,t){let n=$e.get(e);if(!n)throw new Error("Workbook display list is unavailable");return n(r,t)}function Re(e=Ue()){return ye?Promise.resolve():de||(de=je({module_or_path:e}).then(r=>{Ye=r.memory,ye=true;},r=>{throw de=void 0,q(r)}),de)}function ue(){if(!ye)throw new Error("xlsx wasm is not initialized; call initWasm() first")}function q(e){if(e instanceof Error)return e;let r=typeof e=="string"?e:String(e);return Fr(r)??new Error(r)}function yt(){if(!ye)return null;let e=Ve();return e>0?{bytes:e,memoryBytes:Ye?.buffer.byteLength??0}:null}function gt(){return ue(),Be()}function _t(){return typeof WebAssembly=="object"}function kt(){return typeof A.prototype.renderPng=="function"}function ht(){return typeof A.prototype.proposeJson=="function"}function wt(e,r={}){return nr(e,r)}var Ze=new WeakMap,er=new WeakMap;function xt(e,r,t=false){let n=er.get(e);if(!n)throw new TypeError("Workbook does not support recovery checkpoints");return n(r,t)}function St(e,r,t={}){ue();try{let n=A.openRecoveryCheckpoint(e,r);return Ee(n,t,!0)}catch(n){throw q(n)}}var rr=new WeakMap,tr=new WeakMap;function Ct(e){let r=tr.get(e);if(!r)throw new TypeError("Workbook does not support peer snapshots");return r}function Rt(e){ue();let r=ee;if(!r)throw new Error("Workbook wasm does not support peer snapshots");let t=new r;function n(){if(!t)throw new Error("Workbook snapshot builder is disposed");return t}return {push(o){try{n().push(o);}catch(i){throw q(i)}},advance(o,i){try{return n().advance(o,i)}catch(u){throw q(u)}},finish(){let o=n();t=void 0;try{return Ee(o.finish(),e,!0)}catch(i){throw q(i)}},dispose(){let o=t;t=void 0,o?.free();}}}function Et(e){let r=Ze.get(e);if(!r)throw new TypeError("Workbook does not support peer hydration");return r()}function vt(e,r){let t=rr.get(e);if(!t)throw new TypeError("Workbook does not support peer version adoption");t(r);}function Pt(e,r,t){return nr(e,r,t)}function nr(e,r,t){if(r.calculation!==void 0&&(or(r.calculation),r.collaborative===true))throw new TypeError("calculation context is unavailable for collaborative workbooks");ue();let n=ir(r),o;try{t!==void 0?o=A.openWithPeerHydrationJson(e,t):r.calculation!==void 0?o=A.openWithCalculationJson(e,JSON.stringify(r.calculation)):o=n===void 0?A.open(e):A.openCollaborative(e,n);}catch(i){throw q(i)}return Ee(o,r,t!==void 0)}function Ee(e,r,t){let n=ir(r),o=new Map,i=[],u=0,c=0,l=false,S=r.calculation!==void 0||t&&n===void 0,h=false,x=0,R=false,E=false;function v(s){!s.truncated||E||(E=true,console.warn("xlsx: displayTooLarge: frame truncated at the display cell limit"));}function F(){if(l)throw new Error("workbook handle is disposed")}function G(){if(!(l||R||x!==0)){R=true;try{for(;!l&&i.length>0;){let s=i.shift();if(!s)break;for(let[d,p]of [...o]){if(l)return;if(o.get(d)===p)try{p(s.update.slice(),s.origin,{fromPeer:s.fromPeer});}catch{}}}}finally{R=false,l&&(i.length=0);}}}function L(){if(!(!h||l))for(;;){let s=e.drainUpdateEvent();if(s.byteLength===0)return;let d=s[0];if(d!==0&&d!==1)throw new Error(`xlsx wasm returned unknown update origin ${d}`);i.push({update:s.subarray(1),origin:d===0?"local":"remote",fromPeer:d===1||u>0});}}function P(s,d=false){F(),x+=1;try{let p,g,J=!1;try{p=s();}catch(I){g=I,J=!0;}if(d)try{L();}catch(I){J||(g=I,J=!0);}if(J)throw q(g);return p}finally{x-=1,x===0&&G();}}function H(s){return P(s,true)}function _(s,d=false){return P(()=>JSON.parse(s()),d)}function $(s,d){let p=JSON.stringify(s);return d===void 0?e.displayListJson(p):e.displayListForJson(d,p)}function B(){h||(P(()=>e.startUpdateObservation()),h=true);}function y(){!h||o.size>0||l||(i.length=0,P(()=>e.clearUpdateObservation()),h=false);}let k={get clientId(){return P(()=>e.clientId)},setCalculationContext(s){if(F(),s!==null&&(or(s),n!==void 0))throw new TypeError("calculation context is unavailable for collaborative workbooks");P(()=>e.setCalculationContextJson(JSON.stringify(s))),S=s!==null;},encodeStateVector(){return P(()=>e.encodeStateVector())},encodeStateAsUpdate(s){return P(()=>s===void 0?e.encodeStateAsUpdate():e.encodeDiff(s))},applyUpdate(s){u+=1;try{return _(()=>e.applyUpdateJson(s),!0)}finally{u-=1;}},onUpdate(s){if(F(),typeof s!="function")throw new TypeError("update listener must be a function");let d=c++;o.set(d,s);try{B();}catch(g){throw o.delete(d),g}let p=true;return ()=>{p&&(p=false,o.delete(d),y());}},sheetInfo(){return _(()=>e.sheetInfoJson())},sheetCount(){return P(()=>e.sheetCount())},sheetInfoFor(s){if(!Number.isInteger(s)||s<0||s>=k.sheetCount())throw new RangeError("Sheet index is out of range");return _(()=>e.sheetInfoForJson(s))},calculationStatus(){return P(()=>{let s=e.calculationStatusJson;return typeof s!="function"?{limitedCells:[]}:JSON.parse(s.call(e))})},displayList(s){let d=_(()=>$(s));return v(d),d},displayListProfiled(s){let d=_(()=>e.displayListProfiledJson(JSON.stringify(s)));return v(d.displayList),d},printDisplayList(s,d,p,g){return _(()=>e.printDisplayListJson(JSON.stringify({sheet:s,range:d,metrics:p,gridlines:g})))},chartAtPoint(s,d,p){return _(()=>e.chartAtPointJson(JSON.stringify({viewport:s,x:d,y:p})))},moveChart(s,d,p,g){return _(()=>e.moveChartJson(JSON.stringify({sheet:s,chart:d,dx:p,dy:g})),true)},setActiveSheet(s){H(()=>e.setActiveSheet(s));},editCell(s,d,p,g){return _(()=>e.editCellJson(JSON.stringify({sheet:s,row:d,col:p,input:g})),true)},editCellProfiled(s,d,p,g){return _(()=>e.editCellProfiledJson(JSON.stringify({sheet:s,row:d,col:p,input:g})),true)},editCells(s,d){return _(()=>e.editCellsJson(JSON.stringify({sheet:s,edits:d})),true)},moveRange(s,d,p){return _(()=>e.moveRangeJson(JSON.stringify({sheet:s,source:d,destination:p})),true)},setHyperlink(s,d){return _(()=>e.applyOpsJson(JSON.stringify({ops:[{type:"setHyperlink",sheet:s,hyperlink:{range:d.range,external_target:d.externalTarget??null,location:d.location??null,tooltip:d.tooltip??null,display:d.display??null}}]})),true)},removeHyperlink(s,d){return _(()=>e.applyOpsJson(JSON.stringify({ops:[{type:"removeHyperlink",sheet:s,range:d}]})),true)},charts(s){return _(()=>e.chartsJson(s))},editCharts(s){return _(()=>e.editChartsJson(JSON.stringify(s)),true)},conditionalFormats(s){return _(()=>e.conditionalFormatsJson(s))},applyOps(s){return _(()=>e.applyOpsJson(JSON.stringify({ops:s})),true)},applyOpsProfiled(s){return _(()=>e.applyOpsProfiledJson(JSON.stringify({ops:s})),true)},undo(){return _(()=>e.undoJson(),true)},redo(){return _(()=>e.redoJson(),true)},cell(s,d,p){return _(()=>e.cellJson(JSON.stringify({sheet:s,row:d,col:p})))},searchText(s,d){if(!s)return [];let p=d?.limit;if(p!==void 0&&(!Number.isSafeInteger(p)||p<0||p>4294967295))throw new RangeError("search limit must be an unsigned 32-bit integer");return _(()=>e.searchTextJson(JSON.stringify({query:s,caseSensitive:d?.caseSensitive??false,...p===void 0?{}:{limit:p}})))},cellPosition(s,d,p){return _(()=>e.cellPositionJson(JSON.stringify({sheet:s,row:d,col:p})))},selectionData(s,d,p,g){return _(()=>e.selectionDataJson(JSON.stringify({sheet:s,row:d,col:p,direction:g})))},cellRect(s,d,p){return _(()=>e.cellRectJson(JSON.stringify({sheet:s,row:d,col:p})))},rangeCells(s,d){return _(()=>e.rangeCellsJson(JSON.stringify({sheet:s,range:d}))).cells},patchRangeStyle(s,d,p){return _(()=>e.patchRangeStyleJson(JSON.stringify({sheet:s,range:d,patch:p})),true)},setNumberFormat(s,d,p){let g=typeof p=="string"?{type:p}:p;return _(()=>e.setRangeNumberFormatJson(JSON.stringify({sheet:s,range:d,format:g})),true)},selectionFormatting(s,d){return _(()=>e.selectionFormattingJson(JSON.stringify({sheet:s,range:d})))},captureFormat(s,d){return _(()=>e.captureFormatJson(JSON.stringify({sheet:s,range:d})))},applyFormat(s,d,p){return _(()=>e.applyFormatJson(JSON.stringify({sheet:s,range:d,format:p})),true)},mergedRanges(s,d){return _(()=>e.mergedRangesJson(JSON.stringify({sheet:s,range:d}))).ranges},visibleMergedRanges(s,d){if(!Number.isInteger(s)||s<0||s>=k.sheetCount())throw new RangeError("Sheet index is out of range");return _(()=>e.visibleMergedRangesJson(s,JSON.stringify(d))).ranges},historyState(){return _(()=>e.historyStateJson())},renderPng(s){return P(()=>{let d=e.renderPng;if(typeof d!="function")throw new Error("png export not in this build");return d.call(e,JSON.stringify(s)).slice()})},renderRangePng(s){return P(()=>{let d=e.renderRangePng;if(typeof d!="function")throw new Error("png export not in this build");return d.call(e,JSON.stringify(s??{})).slice()})},save(){return P(()=>e.saveBytes())},propose(s,d,p){return H(()=>{let g=e.proposeJson;if(typeof g!="function")throw new Error("proposals not in this build");let J=p.map(({numberFormat:I,...hr})=>({...hr,...I===void 0?{}:{numberFormat:typeof I=="string"?{type:I}:I}}));return JSON.parse(g.call(e,JSON.stringify({agentId:s,note:d,edits:J})))})},listProposals(){return P(()=>{let s=e.listProposalsJson;return typeof s!="function"?[]:JSON.parse(s.call(e)).proposals})},acceptProposal(s,d){try{return H(()=>{let p=e.acceptProposalJson;if(typeof p!="function")throw new Error("proposals not in this build");return JSON.parse(p.call(e,JSON.stringify({id:s,force:d?.force??!1})))})}catch(p){let g=p instanceof Error?p.message:typeof p=="string"?p:String(p);throw Wr(g)??q(p)}},rejectProposal(s){return H(()=>{let d=e.rejectProposalJson;return typeof d!="function"?false:JSON.parse(d.call(e,JSON.stringify({id:s}))).removed})},isProposalsAvailable(){return P(()=>typeof e.proposeJson=="function")},version(){return P(()=>e.documentVersion())},listDefinedNames(s={}){return _(()=>e.listDefinedNamesJson(JSON.stringify(s)))},readCells(s){return _(()=>e.readCellsJson(JSON.stringify(s)))},findText(s){return _(()=>e.findTextJson(JSON.stringify(s)))},validateEdits(s){return S&&s.calculation!==void 0&&Ge(s.calculation),_(()=>e.validateEditsJson(JSON.stringify(s)))},applyEdits(s){return S&&s.calculation!==void 0&&Ge(s.calculation),_(()=>e.applyEditsJson(JSON.stringify(s)),true)},exportStructured(s={}){return _(()=>e.exportStructuredJson(JSON.stringify(s)))},exportMarkdown(s={},d={}){return _(()=>e.exportMarkdownJson(JSON.stringify(s),JSON.stringify(d)))},dispose(){if(l)return;l=true,o.clear(),i.length=0;let s;if(h){try{e.clearUpdateObservation();}catch(d){s=d;}h=false;}try{e.free();}catch(d){s??(s=d);}if(s!==void 0)throw q(s)}};return $e.set(k,(s,d)=>{let p=P(()=>$(s,d));return !E&&p.includes('"truncated":true')&&v(JSON.parse(p)),p}),er.set(k,(s,d)=>P(()=>e.recoveryCheckpoint(s,d))),Ze.set(k,()=>P(()=>e.peerHydrationJson())),rr.set(k,s=>P(()=>e.adoptPeerVersion(s))),tr.set(k,{begin:(s,d)=>P(()=>e.beginPeerSnapshot(s,d)),next:()=>P(()=>e.nextPeerSnapshotChunk()),end:()=>P(()=>e.endPeerSnapshot())}),k}function or(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).some(n=>n!=="nowSerial"&&n!=="randSeed"))throw new TypeError("calculation must be an object with nowSerial and randSeed");let{nowSerial:r,randSeed:t}=e;if(typeof r!="number"||!Number.isFinite(r))throw new TypeError("nowSerial must be a finite number");if(typeof t!="number"||!Number.isInteger(t)||t<0||t>4294967295)throw new TypeError("randSeed must be an integer from 0 to 4294967295")}function Ge(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).some(t=>t!=="nowSerial"))throw new TypeError("calculation must be an object with an optional nowSerial");let{nowSerial:r}=e;if(r!==void 0&&(typeof r!="number"||!Number.isFinite(r)))throw new TypeError("nowSerial must be a finite number")}function ir(e){if(!e.collaborative){if(e.clientId!==void 0)throw new TypeError("clientId requires collaborative mode");return}if(e.clientId!==void 0){if(!Number.isSafeInteger(e.clientId)||e.clientId<=0||e.clientId>=E)throw new RangeError("clientId must be a nonzero safe integer below Number.MAX_SAFE_INTEGER - 1");return e.clientId}let r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("crypto.getRandomValues is required to generate a collaboration client ID");let t=new Uint32Array(2),n;do r.getRandomValues(t),n=(t[0]&2097151)*4294967296+t[1];while(n===0||n>=E);return n}function ve(e){try{return JSON.parse(e())}catch(r){throw q(r)}}async function Ft(e,r={}){return await Re(),ve(()=>ze(e,JSON.stringify(r)))}async function Wt(e,r={},t={}){return await Re(),ve(()=>Ke(e,JSON.stringify(r),JSON.stringify(t)))}async function Ot(e,r={}){return await Re(),ve(()=>Qe(JSON.stringify(e),JSON.stringify(r)))}function At(){return ue(),A.version()}var sr=class extends Error{constructor(){super("PNG export is unavailable");a$1(this,"code","png-unavailable");this.name="WorkbookPngUnavailableError";}},Jt={open:true,openRecovery:true,version:true,collaborationStateVector:true,collaborationStateAsUpdate:true,listDefinedNames:true,readCells:true,findText:true,validateEdits:true,applyEdits:true,command:true,edit:true,checkpoint:true,commandFrame:true,frame:true,sheetView:true,cellGeometry:true,cellInputs:true,selectionData:true,captureFormat:true,sheets:true,calculationStatus:true,renderPng:true,renderRangePng:true,exportStructured:true,exportMarkdown:true,printDisplayList:true,save:true,dispose:true},It={open:{lane:"interactive"},openRecovery:{lane:"input",reorderable:false},version:{lane:"interactive"},collaborationStateVector:{lane:"collab",reorderable:false},collaborationStateAsUpdate:{lane:"collab",reorderable:false},listDefinedNames:{lane:"interactive"},readCells:{lane:"interactive"},findText:{lane:"interactive"},validateEdits:{lane:"interactive"},applyEdits:{lane:"input",mutates:true,userInput:true},command:{lane:"input",userInput:true,reorderable:false},edit:{lane:"input",userInput:true,mutates:true,reframes:true,reorderable:false},checkpoint:{lane:"input",reorderable:false},commandFrame:{lane:"input",reorderable:false},frame:{lane:"interactive",reframes:true,key:"frame",replaceableBy:"frame"},sheetView:{lane:"interactive"},cellGeometry:{lane:"interactive"},cellInputs:{lane:"interactive"},selectionData:{lane:"interactive",reorderable:false},captureFormat:{lane:"interactive",reorderable:false},sheets:{lane:"interactive"},calculationStatus:{lane:"interactive"},renderPng:{lane:"interactive",reorderable:false},renderRangePng:{lane:"interactive",reorderable:false},exportStructured:{lane:"interactive",reorderable:false},exportMarkdown:{lane:"interactive",reorderable:false},printDisplayList:{lane:"interactive",reorderable:false},save:{lane:"interactive"},dispose:{lane:"interactive"}};var Nt={editCell:true,editCells:true,applyEdits:true,applyOps:true,propose:true,acceptProposal:true,rejectProposal:true,patchRangeStyle:true,setNumberFormat:true,applyFormat:true,moveChart:true,moveRange:true,undo:true,redo:true,setActiveSheet:true},qt={beginPeerSnapshot:true,pullPeerSnapshot:true,endPeerSnapshot:true,attachPeer:true,detachPeer:true,replay:true,preview:true},Ut={beginPeerSnapshot:{lane:"interactive",reorderable:false},pullPeerSnapshot:{lane:"interactive",reorderable:false},endPeerSnapshot:{lane:"interactive",reorderable:false},preview:{lane:"input",reorderable:false},attachPeer:{lane:"input",reorderable:false},detachPeer:{lane:"input",reorderable:false},replay:{lane:"input",mutates:true,userInput:true,reorderable:false}},Lt=new WeakMap;function C(e){if(e===null||typeof e!="object")return false;let r=Object.getPrototypeOf(e);return r===null||r===Object.prototype}function W(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function pe(e){return typeof e=="number"&&Number.isFinite(e)}function ce(e){return C(e)&&W(e.row)&&W(e.col)}function Or(e){return !C(e)||typeof e.sheetId!="string"||!C(e.range)?false:e.range.kind==="a1"?typeof e.range.a1=="string":e.range.kind==="rowCol"&&ce(e.range.start)&&ce(e.range.end)}function dr(e){return Array.isArray(e)&&Array.from(e).every(r=>typeof r=="string")}function ar(e){return Array.isArray(e)&&Array.from(e).every(dr)}function K(e,r){return Object.entries(r).every(([t,n])=>e[t]===void 0||n(e[t]))}function U(e){return r=>typeof r=="string"&&e.includes(r)}function ur(e){return C(e)&&K(e,{bold:r=>typeof r=="boolean",italic:r=>typeof r=="boolean",strikethrough:r=>typeof r=="boolean",fontFamily:r=>typeof r=="string",fontSize:pe,textColor:r=>typeof r=="string",fillColor:r=>typeof r=="string",border:r=>C(r)&&K(r,{preset:U(["all","inner","horizontal","vertical","outer","left","top","right","bottom","none"]),style:U(["solid","dashed","dotted","double"]),color:t=>typeof t=="string"}),horizontalAlignment:U(["left","center","right"]),verticalAlignment:U(["top","middle","bottom"]),textWrapping:U(["overflow","wrap","clip"]),clear:r=>Array.isArray(r)&&Array.from(r).every(U(["bold","italic","strikethrough","fontFamily","fontSize","textColor","fillColor","borders","horizontalAlignment","verticalAlignment","textWrapping"]))})}function Pe(e){return U(["automatic","plainText","number","percent","scientific","currency","date","time","increaseDecimal","decreaseDecimal"])(e)||C(e)&&e.type==="custom"&&typeof e.pattern=="string"}function lr(e){return C(e)&&K(e,{formula:r=>r===null||typeof r=="string",displayText:r=>typeof r=="string",value:r=>C(r)&&(r.kind==="empty"||r.kind==="number"&&pe(r.value)||r.kind==="text"&&typeof r.value=="string"||r.kind==="bool"&&typeof r.value=="boolean"||r.kind==="error"&&U(["#DIV/0!","#N/A","#NAME?","#NULL!","#NUM!","#REF!","#VALUE!","#SPILL!","#CALC!"])(r.value))})}function Ar(e){return !C(e)||typeof e.expectVersion!="string"||!Array.isArray(e.steps)?false:K(e,{source:U(["host","agent"]),history:U(["separate","none"]),calculation:r=>C(r)&&Object.keys(r).every(t=>t==="nowSerial")&&K(r,{nowSerial:pe})})&&Array.from(e.steps).every(r=>{if(!C(r)||!Or(r.target)||!K(r,{expect:t=>C(t)&&Array.isArray(t.cells)&&Array.from(t.cells).every(n=>Array.isArray(n)&&Array.from(n).every(lr))}))return false;switch(r.op){case "setCellInputs":return ar(r.inputs);case "setCellValues":return Array.isArray(r.values)&&Array.from(r.values).every(t=>Array.isArray(t)&&Array.from(t).every(n=>C(n)&&lr({value:n})));case "setFormulas":return ar(r.formulas);case "setNumberFormat":return Pe(r.format);case "patchStyle":return ur(r.patch);default:return false}})}function Tr(e){return C(e)&&C(e.font)&&Ir(e.fill)&&Xr(e.border)&&C(e.numberFormat)&&typeof e.numberFormat.kind=="string"&&C(e.alignment)}var Mr=new Set(["gray125","gray0625","mediumGray","darkGray","lightGray","darkHorizontal","darkVertical","darkDown","darkUp","darkGrid","darkTrellis","lightHorizontal","lightVertical","lightDown","lightUp","lightGrid","lightTrellis"]),Jr=new Set(["Thin","Medium","Thick","Dashed","Dotted","Double","Hair","MediumDashed","DashDot","MediumDashDot","DashDotDot","MediumDashDotDot","SlantDashDot"]);function cr(e){return e==="Auto"?true:!C(e)||Object.keys(e).length!==1?false:"Rgb"in e?typeof e.Rgb=="string":"Indexed"in e?W(e.Indexed)&&e.Indexed<=255:C(e.Theme)&&W(e.Theme.idx)&&e.Theme.idx<=255&&typeof e.Theme.tint=="number"&&Number.isFinite(e.Theme.tint)}function Fe(e){return e==null||cr(e)}function Ir(e){if(e==="None")return true;if(!C(e)||Object.keys(e).length!==1)return false;if("Solid"in e)return cr(e.Solid);let r=e.Pattern;return C(r)&&typeof r.pattern=="string"&&Mr.has(r.pattern)&&Fe(r.fg)&&Fe(r.bg)}function Dr(e){return e==null||C(e)&&typeof e.style=="string"&&Jr.has(e.style)&&Fe(e.color)}function Xr(e){return C(e)&&["left","right","top","bottom"].every(r=>Dr(e[r]))}function Nr(e){if(!C(e)||!Array.isArray(e.args))return false;let r=Array.from(e.args);switch(e.method){case "editCell":return r.length===4&&r.slice(0,3).every(W)&&typeof r[3]=="string";case "editCells":return r.length===2&&W(r[0])&&Array.isArray(r[1])&&Array.from(r[1]).every(t=>ce(t)&&C(t)&&typeof t.input=="string"&&(t.copyFrom===void 0||C(t.copyFrom)&&ce(t.copyFrom)&&t.copyFrom.row<1048576&&t.copyFrom.col<16384));case "applyEdits":return r.length===1&&Ar(r[0]);case "applyOps":return r.length===1&&Array.isArray(r[0])&&Array.from(r[0]).every(t=>C(t)&&typeof t.type=="string");case "propose":return r.length===3&&typeof r[0]=="string"&&(r[1]===null||typeof r[1]=="string")&&Array.isArray(r[2])&&Array.from(r[2]).every(t=>C(t)&&W(t.sheet)&&ce(t)&&typeof t.input=="string"&&K(t,{numberFormat:Pe}));case "acceptProposal":return r.length>=1&&r.length<=2&&typeof r[0]=="string"&&(r[1]===void 0||C(r[1])&&K(r[1],{force:t=>typeof t=="boolean"}));case "rejectProposal":return r.length===1&&typeof r[0]=="string";case "patchRangeStyle":return r.length===3&&W(r[0])&&typeof r[1]=="string"&&ur(r[2]);case "setNumberFormat":return r.length===3&&W(r[0])&&typeof r[1]=="string"&&Pe(r[2]);case "applyFormat":return r.length===3&&W(r[0])&&typeof r[1]=="string"&&C(r[2])&&W(r[2].rows)&&W(r[2].columns)&&Array.isArray(r[2].formats)&&Array.from(r[2].formats).every(Tr);case "moveChart":return r.length===4&&W(r[0])&&typeof r[1]=="string"&&r.slice(2).every(pe);case "moveRange":return r.length===3&&W(r[0])&&typeof r[1]=="string"&&typeof r[2]=="string";case "undo":case "redo":return r.length===0;case "setActiveSheet":return r.length===1&&W(r[0]);default:return false}}function pr(e){if(!C(e)||!W(e.sequence)||e.sequence===0||!C(e.calculation)||!pe(e.calculation.nowSerial)||!W(e.calculation.randSeed)||e.calculation.randSeed>4294967295||!Nr(e.op)||e.staleProposal!==void 0&&(!C(e.staleProposal)||!dr(e.staleProposal.cells)||!Array.isArray(e.staleProposal.targets)||!Array.from(e.staleProposal.targets).every(r=>C(r)&&W(r.sheet)&&W(r.row)&&W(r.col)&&typeof r.sheetId=="string"&&typeof r.a1=="string")||!C(e.op)||e.op.method!=="acceptProposal")){let r=new TypeError("Malformed workbook replay envelope");throw r.name="WorkbookReplayValidationError",r}}function Ht(e){return C(e)&&e.ok===false}function Vt(e,r){switch(r.method){case "editCell":return e.editCell(...r.args);case "editCells":return e.editCells(...r.args);case "applyEdits":return e.applyEdits(...r.args);case "applyOps":return e.applyOps(...r.args);case "propose":return e.propose(...r.args);case "acceptProposal":return e.acceptProposal(...r.args);case "rejectProposal":return e.rejectProposal(...r.args);case "patchRangeStyle":return e.patchRangeStyle(...r.args);case "setNumberFormat":return e.setNumberFormat(...r.args);case "applyFormat":return e.applyFormat(...r.args);case "moveChart":return e.moveChart(...r.args);case "moveRange":return e.moveRange(...r.args);case "undo":return e.undo(...r.args);case "redo":return e.redo(...r.args);case "setActiveSheet":return e.setActiveSheet(...r.args)}}var fr=class extends Error{constructor(t,n){super(n);a$1(this,"code",t);a$1(this,"refusal");this.name="WorkbookPeerHydrationError",this.refusal={code:t};}};function Qt(e){return (e-new Date(e).getTimezoneOffset()*6e4)/864e5+25569}var mr=[8,9,10,11,12,14,16,18,20,24,28,36,48,72],qr=4096;function br(e,r){if(e==="bold"||e==="italic"||e==="strikethrough"||e==="paintFormat"||e==="clear"||e==="refreshProposals")return r===null;if((e==="merge"||e==="textWrapping")&&r===null)return true;if(!r||typeof r!="object"||Array.isArray(r))return false;let t=r,n=o=>typeof t.value=="string"&&o.includes(t.value);switch(e){case "fontFamily":return typeof t.family=="string"&&t.family.trim()!=="";case "fontSize":return typeof t.points=="number"&&Number.isFinite(t.points)&&t.points>=1&&t.points<=400;case "fontSizeStep":case "decimalPlaces":return t.direction==="increase"||t.direction==="decrease";case "textColor":case "fillColor":case "borderColor":return typeof t.color=="string"&&/^#[0-9a-f]{6}$/i.test(t.color);case "numberFormat":return n(["automatic","plainText","number","percent","scientific","currency","date","time","custom"]);case "borderPreset":return n(["all","inner","horizontal","vertical","outer","left","top","right","bottom","none"]);case "borderStyle":return n(["solid","dashed","dotted","double"]);case "merge":return n(["all","horizontal","vertical","unmerge"]);case "horizontalAlignment":return n(["left","center","right"]);case "verticalAlignment":return n(["top","middle","bottom"]);case "textWrapping":return n(["overflow","wrap","clip"]);default:return false}}function Yt(e,r,t,n){let{id:o,args:i}=e,{sheet:u,range:c,start:l,end:S}=r,h=i,x=R=>({method:"patchRangeStyle",args:[u,c,R]});switch(o){case "clear":{let R=[];for(let E=l.row;E<=S.row;E++)for(let v=l.col;v<=S.col;v++)R.push({row:E,col:v,input:""});return {method:"editCells",args:[u,R]}}case "bold":return x({bold:t.bold!==true});case "italic":return x({italic:t.italic!==true});case "strikethrough":return x({strikethrough:t.strikethrough!==true});case "fontFamily":return x({fontFamily:h.family});case "fontSize":return x({fontSize:h.points});case "fontSizeStep":{let R=t.fontSize??10,E=h.direction==="increase"?mr.find(v=>v>R)??R+1:[...mr].reverse().find(v=>v<R)??Math.max(1,R-1);return x({fontSize:E})}case "textColor":return x({textColor:h.color});case "fillColor":return x({fillColor:h.color});case "horizontalAlignment":return x({horizontalAlignment:h.value});case "verticalAlignment":return x({verticalAlignment:h.value});case "textWrapping":return x({textWrapping:i===null?t.textWrapping==="wrap"?"overflow":"wrap":h.value});case "borderPreset":return x({border:{preset:h.value,style:t.borderStyle??"solid",color:t.borderColor??"#000000"}});case "borderStyle":return x({border:{style:h.value}});case "borderColor":return x({border:{color:h.color}});case "numberFormat":return {method:"setNumberFormat",args:[u,c,h.value==="custom"?{type:"custom",pattern:t.numberFormatPattern??"0.00"}:h.value]};case "decimalPlaces":return {method:"setNumberFormat",args:[u,c,h.direction==="increase"?"increaseDecimal":"decreaseDecimal"]};case "merge":{let R=i===null?n.length>0?"unmerge":"all":h.value;if((R==="horizontal"?S.row-l.row+1:R==="vertical"?S.col-l.col+1:R==="all"?1:n.length)>qr)throw new re("limit-exceeded");let v=[];if(R==="all")v.push({type:"mergeCells",sheet:u,range:{start:l,end:S}});else if(R==="horizontal")for(let F=l.row;F<=S.row;F++)v.push({type:"mergeCells",sheet:u,range:{start:{row:F,col:l.col},end:{row:F,col:S.col}}});else if(R==="vertical")for(let F=l.col;F<=S.col;F++)v.push({type:"mergeCells",sheet:u,range:{start:{row:l.row,col:F},end:{row:S.row,col:F}}});else for(let F of n)v.push({type:"unmergeCells",sheet:u,range:F});return {method:"applyOps",args:[v]}}default:return}}var Ur=new Set(["maxFrameBytes","maxMessagesPerFrame","user"]);function Lr(e,r){if(!c(e,Number.MAX_SAFE_INTEGER,{validCursor:t,optionKeys:Ur}))return false;let t$1=r?.get(e.provider);for(let n of e.ops){if(n.op==="create"&&t$1===void 0&&(t$1=n.options.maxFrameBytes??u,!Number.isSafeInteger(t$1)||t$1<=0)||n.op==="event"&&n.event.type==="message"&&n.event.data.byteLength>(t$1??u))return false;n.op==="destroy"&&(t$1=void 0);}return true}function T(e){if(!e||typeof e!="object")return false;let r=Object.getPrototypeOf(e);return r===null||r===Object.prototype}function Q(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function z(e){return typeof e=="number"&&Number.isFinite(e)}function Hr(e){let r=1e6,t=16777216,n=new Set,o=(i,u)=>{if(--r<0||u>64)return false;if(typeof i=="string")return t-=i.length,t>=0;if(i==null||typeof i=="boolean")return true;if(typeof i=="number")return z(i);if(!Array.isArray(i)&&!T(i)||n.has(i))return false;n.add(i);let c=true;if(Array.isArray(i)){if(i.length>r)c=false;else for(let l=0;l<i.length;l++)if(!Object.prototype.hasOwnProperty.call(i,l)||!o(i[l],u+1)){c=false;break}}else for(let l in i)if(t-=l.length,t<0||!o(i[l],u+1)){c=false;break}return n.delete(i),c};return o(e,0)}function We(e){return T(e)&&Q(e.row)&&Q(e.col)}function Y(e){return T(e)&&typeof e.sheetId=="string"&&T(e.range)&&(e.range.kind==="a1"?typeof e.range.a1=="string":e.range.kind==="rowCol"&&We(e.range.start)&&We(e.range.end))}function yr(e){return Y(e)&&T(e)&&(e.activeCell===void 0||We(e.activeCell))}function Vr(e){return T(e)&&Q(e.sheet)&&Q(e.generation)&&(e.requestGeneration===void 0||Q(e.requestGeneration))&&z(e.zoom)&&e.zoom>0&&z(e.dpr)&&e.dpr>0&&T(e.viewport)&&z(e.viewport.x)&&z(e.viewport.y)&&z(e.viewport.width)&&e.viewport.width>0&&z(e.viewport.height)&&e.viewport.height>0}function on(e){if(!T(e)||typeof e.session!="string"||typeof e.incarnation!="string"||!Q(e.seq)||e.seq===0||!T(e.basis)||!Q(e.basis.epoch)||typeof e.basis.version!="string"||e.afterSeq!==void 0&&(!Q(e.afterSeq)||e.afterSeq===0||e.afterSeq>=e.seq))throw new TypeError("Malformed workbook command envelope")}function sn(e,r){let t=e.payload,{frame:n}=e,o=T(t)&&(t.selection===void 0||yr(t.selection));if(o&&T(t))if(o=(t.inputTime===void 0||z(t.inputTime))&&(t.undoGroupId===void 0||typeof t.undoGroupId=="string")&&(t.target===void 0||Y(t.target)),e.kind==="setActiveSheet"&&t.expectVersion!==void 0&&o&&(o=typeof t.expectVersion=="string"),e.kind==="select")o&&(o=yr(t.selection));else if(e.kind==="collabPipe")o&&(o=Lr(t,r));else if(e.kind==="applyUpdate")o&&(o=t.update instanceof Uint8Array&&(t.updates===void 0||Array.isArray(t.updates)&&t.updates.every(i=>i instanceof Uint8Array)));else if(e.kind==="setReadOnly")o&&(o=typeof t.readOnly=="boolean");else if(e.kind==="applyOps"&&"toolbar"in t)o&&(o=!("args"in t)&&T(t.toolbar)&&(t.toolbar.id==="refreshProposals"?t.toolbar.target===void 0:Y(t.toolbar.target))&&br(t.toolbar.id,t.toolbar.args));else if(e.kind==="applyFormat"&&"formatToken"in t)o&&(o=!("args"in t)&&!("capturedFrom"in t)&&Y(t.target)&&typeof t.formatToken=="string"&&t.formatToken.length>0);else if(e.kind==="applyFormat"&&"capturedFrom"in t)o&&(o=Y(t.target)&&Y(t.capturedFrom));else {if(e.kind==="applyOps"||e.kind==="propose"){let i=Array.isArray(t.args)?t.args[e.kind==="applyOps"?0:2]:void 0;o&&(o=Array.isArray(i)&&i.every(u=>T(u)&&(u.target===void 0||Y(u.target))));}try{if(e.kind==="applyEdits"&&!Hr(t.args))throw new re("invalid-command");pr({sequence:e.seq,calculation:t.calculation??{nowSerial:0,randSeed:0},op:{method:e.kind,args:t.args}});}catch(i){if(e.kind!=="applyEdits"&&(!(i instanceof Error)||i.name!=="WorkbookReplayValidationError"))throw i;o=false;}}if(n!==void 0&&o&&(o=Vr(n)),!o)throw new re("invalid-command")}var re=class extends Error{constructor(t,n){super(t);a$1(this,"reason",t);a$1(this,"result",n);this.name="WorkbookCommandRefusal";}};var gr=["input","collab","interactive"],_r={input:0,collab:1,interactive:2,background:3},Br=8,Kr=24,zr=1e3;function kr(e){let r={input:[],collab:[],interactive:[]},t=[],n=0,o=0,i=0,u=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=false,S=false,h=null,x=()=>e.now()-u<zr?Br:Kr;function R(y=false){l||S||(S=true,(y?queueMicrotask:e.turn)(()=>{S=false,_();}));}function E(y){for(let k of gr)if(k!==y.lane)for(let s of r[k]){if(s.seq>y.seq)break;if(!(s.reorderable&&_r[y.lane]<_r[s.lane]))return true}return false}function v(){for(let y of gr){let k=r[y][0];if(k&&!E(k))return k}return null}function F(){let y=v();if(!y)return null;let k=[r[y.lane].shift()];if(y.lane==="collab")for(;r.collab[0]&&!E(r.collab[0]);)k.push(r.collab.shift());return k}function G(y){return y.idleAfterInputMs===void 0?Number.NEGATIVE_INFINITY:c+y.idleAfterInputMs}async function L(y){for(let k of y){k.mutates&&(o+=1),(k.mutates||k.reframes)&&(i+=1);try{await k.run();}catch(s){e.failed?.(s);}}}async function P(){let y=e.now(),k=t.findIndex(d=>G(d)<=y);if(k<0)return false;let[s]=t.splice(k,1);try{if(s.version!==o||s.generation!==i){if((s.onStale?.()??"cancel")==="cancel")return s.cancel?.(),!0;s.version=o,s.generation=i;}await s.run(x())==="yield"&&t.push(s);}catch(d){s.fail?s.fail(d):e.failed?.(d);}return true}function H(){if(h?.(),h=null,t.length===0)return;let y=Math.min(...t.map(G));h=e.timer(()=>{h=null,R();},Math.max(1,y-e.now()));}async function _(){if(l)return;l=true;let y=false;try{let s=F();s?(y=!0,await L(s)):t.length>0&&(y=await P());}catch(s){y=true,e.failed?.(s);}finally{l=false;}let k=y?v():null;k?R(!k.reorderable):y&&t.length>0?R():H();}function $(y,k){B({kind:`${y.kind}:install`,version:y.version,generation:y.generation,onStale:()=>"cancel",cancel:()=>y.cancel?.(),fail:s=>y.cancel?.(s),run:async()=>(await y.install(k),"done")});}function B(y){t.push(y),l||(h?.(),h=null),R();}return {submit(y){if(y.userInput&&(u=e.now()),y.holdsIdleTasks&&(c=e.now()),y.key!==void 0){let k=r[y.lane];for(let s=k.length-1;s>=0;s-=1)if(k[s].replaceableBy===y.key)try{k.splice(s,1)[0].supersede?.();}catch(d){e.failed?.(d);}}r[y.lane].push({...y,seq:n++}),h?.(),h=null,R(true);},schedule:B,dispatch(y){let k=y,s=()=>B({kind:k.kind,version:k.version,generation:k.generation,onStale:()=>"cancel",cancel:()=>k.cancel?.(),fail:p=>k.cancel?.(p),run:async()=>(await k.install(k.compute(k.input)),"done")});if(!e.executor){s();return}let d=(k.transfer?.length??0)>0;e.executor.run({kind:k.kind,input:k.input,transfer:k.transfer}).then(p=>$(k,p),p=>d?k.cancel?.(p):s());},budget:x,get version(){return o},get generation(){return i},bump(y){y.version&&(o+=1),(y.version||y.generation)&&(i+=1);},pending(){return {foreground:r.input.length+r.collab.length+r.interactive.length,background:t.length}}}}var Qr=1e3;function Oe(e){let r={name:e instanceof Error?e.name:"Error",message:e instanceof Error?e.message:String(e)};return e!==null&&typeof e=="object"&&"refusal"in e&&(r.refusal=e.refusal),r}function fe(e){return e instanceof M||typeof WebAssembly<"u"&&e instanceof WebAssembly.RuntimeError}function jr(e){return e instanceof M?e:new M(fe(e)?"trap":"crash",Oe(e).message)}function fn(e,r){let t,n=s=>{let d=jr(s);return d.code==="trap"?r.trapFailure?.(d)??d:d},o=false,i=()=>{},u=()=>{},c,l=0,S=new Set,h=new Set,x=()=>o||t!==void 0;function R(){i(),u();for(let s of S)clearTimeout(s);S.clear();for(let s of h)try{s.cancel();}catch{}h.clear();try{r.onDispose?.();}catch{}}function E(s){if(!x()){t=s;try{e.post({protocol:1,kind:"failure",code:s.code,message:s.message,...s.diagnostics===void 0?{}:{diagnostics:s.diagnostics}});}catch{}R();}}function v(s,d){if(!x())try{e.post(s,d);}catch(p){E(new M("message",`Session could not post a message: ${Oe(p).message}`));}}function F(s,d){if(x())return ()=>{};let p=setTimeout(()=>{S.delete(p),x()||s();},d);return S.add(p),()=>{clearTimeout(p),S.delete(p);}}function G(s){let d={end(){h.delete(d);},cancel(){d.end(),s?.();}};return s&&h.add(d),d}function L(s,d){if(x())return d;let p=g=>{if(x())return d;if(!fe(g))throw g;return E(n(g)),d};try{let g=s();return g instanceof Promise?g.catch(p):g}catch(g){return p(g)}}function P(s){let d=s.then(),p=g=>J=>{if(!x())try{return g(J)}catch(I){E(n(I));return}};return d.then=((g,J)=>Promise.prototype.then.call(d,g&&p(g),J&&p(J))),d}let H=r.executor,_=kr({now:Date.now,turn:s=>{F(s,0);},timer:F,executor:H&&{run(s){return P(H.run(s))}},failed:s=>E(n(s))}),$={schedule(s){if(x()){try{s.cancel?.();}catch{}return}let d=G(s.cancel&&(()=>s.cancel()));_.schedule({kind:s.kind,idleAfterInputMs:s.idleAfterInputMs,get version(){return s.version},set version(p){s.version=p;},get generation(){return s.generation},set generation(p){s.generation=p;},...s.onStale?{onStale:()=>L(()=>s.onStale(),"cancel")}:{},...s.cancel?{cancel(){return d.end(),L(()=>s.cancel(),void 0)}}:{},...s.fail?{fail(p){return d.end(),L(()=>s.fail(p),void 0)}}:{},async run(p){if(x())return "done";try{let g=await s.run(p);return g==="done"&&d.end(),x()?"done":g}catch(g){if(d.end(),x())return "done";if(fe(g))return E(n(g)),"done";throw g}}});},dispatch(s){if(x()){try{s.cancel?.();}catch{}return}let d=G(s.cancel&&(()=>s.cancel()));_.dispatch({kind:s.kind,input:s.input,transfer:s.transfer,get version(){return s.version},set version(p){s.version=p;},get generation(){return s.generation},set generation(p){s.generation=p;},...s.cancel?{cancel(p){return d.end(),L(()=>s.cancel(p),void 0)}}:{},compute(p){return L(()=>s.compute(p),void 0)},async install(p){if(!x())try{await s.install(p);}catch(g){if(d.end(),x())return;if(fe(g)){E(n(g));return}throw g}finally{d.end();}}});},bump:s=>_.bump(s),budget:()=>_.budget(),pending:()=>_.pending(),get version(){return _.version},get generation(){return _.generation}};function B(s,d){De(d)?v({protocol:1,kind:"reply",id:s,ok:true,value:d.value},d.transfer):v({protocol:1,kind:"reply",id:s,ok:true,value:d});}function y(s,d){fe(d)?E(n(d)):v({protocol:1,kind:"reply",id:s,ok:false,error:Oe(d)});}async function k(s){if(!x()){c=s.id,l=Date.now();try{let d=r.handlers[s.method],p=await d(r.context,...s.args);Ie(p)?p.promise.then(g=>B(s.id,g),g=>y(s.id,g)):B(s.id,p);}catch(d){y(s.id,d);}finally{c===s.id&&(c=void 0);}}}return i=e.listen(s=>{if(!x()){if(!Xe(s))E(new M("message","Session received a malformed client message"));else if(s.kind==="dispose")o=true,R(),e.close();else if(s.kind==="call"&&!t){let d=D(r.policies,s.method)?r.policies[s.method]:void 0;if(!D(r.handlers,s.method)||!d){v({protocol:1,kind:"reply",id:s.id,ok:false,error:{name:"Error",message:`Unknown session method: ${s.method}`}});return}let p;try{p=typeof d=="function"?d(...s.args):d;}catch(g){y(s.id,g);return}_.submit({...p,run:()=>k(s),supersede:()=>v({protocol:1,kind:"reply",id:s.id,ok:false,error:{name:Ne,message:"Superseded by a newer request"}})});}}}),u=e.onError(s=>E(n(s))),{scheduler:$,emit:(s,d,p)=>v({protocol:1,kind:"event",name:s,payload:d},p),progress(){let s=Date.now();c===void 0||s-l<Qr||(l=s,v({protocol:1,kind:"progress",id:c}));}}}function bn(e){let r=globalThis;return typeof r.structuredClone=="function"?r.structuredClone(e):te(e,new Map)}function te(e,r){if(typeof e=="function"||typeof e=="symbol")throw new TypeError("Unsupported command data");if(e===null||typeof e!="object")return e;if(r.has(e))return r.get(e);if(typeof Blob<"u"&&e instanceof Blob||typeof File<"u"&&e instanceof File)return r.set(e,e),e;if(ArrayBuffer.isView(e)){let n=te(e.buffer,r),o=e.constructor,i=e instanceof DataView?new DataView(n,e.byteOffset,e.byteLength):new o(n,e.byteOffset,e.byteLength/o.BYTES_PER_ELEMENT);return r.set(e,i),i}if(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return r.set(e,e),e;if(e instanceof ArrayBuffer){let n=e.slice(0);return r.set(e,n),n}if(e instanceof Date){let n=new Date(e.getTime());return r.set(e,n),n}if(e instanceof RegExp){let n=new RegExp(e.source,e.flags);return r.set(e,n),n}if(e instanceof Number||e instanceof String||e instanceof Boolean||Object.getPrototypeOf(e)===BigInt.prototype){let n=Object(e.valueOf());return r.set(e,n),n}if(e instanceof Map){let n=new Map;r.set(e,n);for(let[o,i]of e)n.set(te(o,r),te(i,r));return n}if(e instanceof Set){let n=new Set;r.set(e,n);for(let o of e)n.add(te(o,r));return n}let t=Array.isArray(e)?new Array(e.length):{};r.set(e,t);for(let n of Object.keys(e))Object.defineProperty(t,n,{value:te(e[n],r),enumerable:true,configurable:true,writable:true});return t}var Gr="CommandOutcomeUnknown";function _n(e){return j(e)&&typeof e.session=="string"&&V(e.incarnation)&&me(e.seq)&&j(e.basis)&&V(e.basis.epoch)&&ne(e.basis.version)&&(e.afterSeq===void 0||me(e.afterSeq))&&(e.expectVersion===void 0||typeof e.expectVersion=="boolean")&&typeof e.kind=="string"&&D(e,"payload")&&(e.inputTime===void 0||ne(e.inputTime))&&(e.lastInputTime===void 0||ne(e.lastInputTime))&&(e.group===void 0||typeof e.group=="string")&&(e.replay===void 0||e.replay===true)}function kn(e){return j(e)&&typeof e.session=="string"&&V(e.incarnation)&&V(e.epoch)&&V(e.throughSeq)&&ne(e.version)&&Array.isArray(e.outcomes)&&e.outcomes.every(Yr)&&(e.frame===void 0||$r(e.frame))&&(e.revisions===void 0||j(e.revisions)&&V(e.revisions.selection)&&V(e.revisions.layout))}function hn(e){return e instanceof Error&&e.name===Gr&&j(e)&&j(e.refusal)&&me(e.refusal.seq)}function j(e){return e!==null&&typeof e=="object"}function ne(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function me(e){return V(e)&&e>0}function Yr(e){return j(e)&&me(e.seq)&&(e.status==="applied"||e.status==="noop"||e.status==="refused"||e.status==="cancelled"||e.status==="duplicate")&&(e.reason===void 0||typeof e.reason=="string")&&(e.committed===void 0||e.committed===false)&&(e.affectedSeqs===void 0||Array.isArray(e.affectedSeqs)&&e.affectedSeqs.every(me))}function $r(e){return j(e)&&V(e.coversThroughSeq)&&ne(e.revision)&&(e.baseRevision===void 0||ne(e.baseRevision))&&D(e,"payload")}var Sn=["read-only","stale","superseded","not-ready","busy","disposed","invalid-payload","unsupported","dependency-refused","unknown-outcome"],Zr=Symbol("session-refusal");function Cn(e){return ge(e)&&e[Zr]===true}function Rn(e){return ge(e)?e.ok===false?ge(e.refusal)&&typeof e.refusal.code=="string"&&(e.refusal.detail===void 0||typeof e.refusal.detail=="string"):e.ok===true&&D(e,"value")&&ge(e.at)&&["incarnation","epoch","throughSeq","doc","selection","layout"].every(r=>et(e.at[r])):false}function ge(e){return e!==null&&typeof e=="object"}function et(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}export{sn as $,Pt as A,Ft as B,Wt as C,Ot as D,At as E,sr as F,Jt as G,It as H,Nt as I,qt as J,Ut as K,Lt as L,pr as M,Ht as N,Vt as O,fr as P,bn as Q,Gr as R,_n as S,kn as T,hn as U,Sn as V,Cn as W,Rn as X,Yt as Y,Vr as Z,on as _,rt as a,re as aa,tt as b,Qt as ba,De as c,fn as ca,D as d,Xe as e,nt as f,M as g,lt as h,dt as i,Ue as j,Se as k,Ce as l,bt as m,Re as n,yt as o,gt as p,_t as q,kt as r,ht as s,wt as t,xt as u,St as v,Ct as w,Rt as x,Et as y,vt as z};
@@ -1,4 +0,0 @@
1
- function v(e){return Math.max(0,e.length-1)}function P(e){return e.length>0?e[e.length-1]:0}function I(e,n,t){return Math.max(n,Math.min(t,e))}function T(e,n,t,r){let o=t,l=r;for(;o<l;){let s=o+l+1>>1;e[s]<=n?o=s:l=s-1;}return o}function D(e,n,t,r){let o=v(e);if(o===0)return {first:0,last:-1};let l=I(Math.trunc(n),0,o);if(l>=o)return {first:0,last:-1};let s=e[l]-e[0],i=e[l]+Math.max(0,t),c=Math.max(0,r-s),u=i+c,f=T(e,i,l,o-1);if(e[f+1]<=i||c===0)return {first:0,last:-1};let a=T(e,u,f,o-1);return {first:f,last:a}}function $(e,n,t){return {cols:D(n,e.frozenCols,e.scrollX,e.width),rows:D(t,e.frozenRows,e.scrollY,e.height)}}function K(e,n,t){let r=v(e),o=I(Math.trunc(n),0,r),l=P(e)-e[o],s=Math.max(0,t-(e[o]-e[0]));return Math.max(0,l-s)}function N(e,n,t){let r=I(e.scrollX,0,K(n,e.frozenCols,e.width)),o=I(e.scrollY,0,K(t,e.frozenRows,e.height));return r===e.scrollX&&o===e.scrollY?e:{...e,scrollX:r,scrollY:o}}function U(e,n){let t=new Array(e+1);for(let r=0;r<=e;r++)t[r]=r*n;return t}function E(e,n,t){return Math.max(n,Math.min(t,e))}function h(e){return {anchor:{...e},focus:{...e}}}function x(e){return e.range?{...e.range}:{top:Math.min(e.anchor.row,e.focus.row),bottom:Math.max(e.anchor.row,e.focus.row),left:Math.min(e.anchor.col,e.focus.col),right:Math.max(e.anchor.col,e.focus.col)}}function W(e,n){let t=x(e);return n.row>=t.top&&n.row<=t.bottom&&n.col>=t.left&&n.col<=t.right}function B(e){let n=x(e);return (n.bottom-n.top+1)*(n.right-n.left+1)}function C(e,n,t){let r=t?{row:E(n.row,0,t.rows-1),col:E(n.col,0,t.cols-1)}:{...n};return {anchor:{...e.anchor},focus:r}}function A(e,n){let t=n?.mergeAt(e.row,e.col);return t?{row:t.top,col:t.left}:{...e}}function S(e,n,t){let{limits:r,hidden:o,merges:l}=t,s=n==="up"||n==="down",i=n==="up"||n==="left",c=l?.mergeAt(e.focus.row,e.focus.col),u=c?s?i?c.top:c.bottom:i?c.left:c.right:s?e.focus.row:e.focus.col,f=s?r.rows:r.cols,a=u;if(!o)a=E(u+(i?-1:1)*(t.step??1),0,f-1);else {let g=s?o.isRowHidden:o.isColHidden,H=t.step??1;for(;H>0;){let b=a+(i?-1:1);for(;b>=0&&b<f&&g(b);)b+=i?-1:1;if(b<0||b>=f)break;a=b,H-=1;}}let O=a!==u,p=s?{row:a,col:e.focus.col}:{row:e.focus.row,col:a},d=O?p:e.focus,w=t.extend?d:A(d,l);return o&&w.row===e.focus.row&&w.col===e.focus.col?e:t.extend?C(e,w):h(w)}var X={ArrowUp:"up",ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right"};function R(e){return !!(e.metaKey||e.ctrlKey)}function Y(e,n,t){switch(n){case "up":return {row:0,col:e.col};case "down":return {row:t.rows-1,col:e.col};case "left":return {row:e.row,col:0};case "right":return {row:e.row,col:t.cols-1}}}function m(e){return {type:"move",selection:e}}function y(e,n,t,r){let o=e;for(;o>=0&&o<t&&r?.(o);)o+=n;return o>=0&&o<t?o:null}function j(e,n,t,r,o){let{row:l,col:s}=e.focus,i=o?.mergeAt(l,s),c=n?-1:1,u=y((i?n?i.left:i.right:s)+c,c,t.cols,r?.isColHidden);if(u!==null)return h(A({row:l,col:u},o));let f=y(n?t.cols-1:0,c,t.cols,r?.isColHidden),a=y((i?n?i.top:i.bottom:l)+c,c,t.rows,r?.isRowHidden);return f===null||r&&a===null?e:h(A({row:a??l,col:f},o))}function q(e,n,t,r,o){if(!o||!o.isRowHidden(n.row)&&!o.isColHidden(n.col))return n;let l=t==="up"||t==="down",s=t==="up"||t==="left",i=l?e.focus.row:e.focus.col,c=l?n.row:n.col,u=l?r.rows:r.cols,f=l?o.isRowHidden:o.isColHidden,a=y(c,s?-1:1,u,f)??y(c,s?1:-1,u,f);return a===null||(s?a>=i:a<=i)?e.focus:l?{row:a,col:n.col}:{row:n.row,col:a}}function J(e,n,t,r){let o=y(0,1,t.cols,r?.isColHidden),l=n?y(0,1,t.rows,r?.isRowHidden):e.focus.row;return l===null||o===null||r&&l===e.focus.row&&o===e.focus.col?e:h({row:l,col:o})}function Z(e){return e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey}function Q(e,n,t,r,o,l){let s=c=>h(A(c,l)),i=X[n.key];if(i){if(R(n)){let c=q(e,r?.edge??Y(e.focus,i,t),i,t,o);return o&&c.row===e.focus.row&&c.col===e.focus.col?m(e):m(n.shiftKey?C(e,c):s(c))}return m(S(e,i,{extend:n.shiftKey,limits:t,hidden:o,merges:l}))}switch(n.key){case "Tab":return m(j(e,!!n.shiftKey,t,o,l));case "Enter":return m(S(e,n.shiftKey?"up":"down",{extend:false,limits:t,hidden:o,merges:l}));case "Home":{let c=J(e,R(n),t,o);return m(c===e?e:s(c.focus))}case "End":{let c=r?.usedRange,u=R(n)?c===void 0?void 0:r?.edge??(c&&{row:c.bottom,col:c.right}):r?.edge;if(u===void 0)return {type:"none"};if(u===null&&!R(n))return m(e);let f={row:Math.max(0,Math.min(u?.row??0,t.rows-1)),col:Math.max(0,Math.min(u?.col??0,t.cols-1))};return m(n.shiftKey?C(e,f,t):s(f))}case "PageDown":return m(S(e,"down",{extend:n.shiftKey,step:t.rowsPerPage,limits:t,hidden:o,merges:l}));case "PageUp":return m(S(e,"up",{extend:n.shiftKey,step:t.rowsPerPage,limits:t,hidden:o,merges:l}));case "F2":return {type:"startEdit"};case "Delete":case "Backspace":return {type:"clear"}}if((n.key==="a"||n.key==="A")&&R(n)){if(r){let c=x(e),u=r.region,f=u&&(c.top!==u.top||c.left!==u.left||c.bottom!==u.bottom||c.right!==u.right)?u:{top:0,left:0,bottom:t.rows-1,right:t.cols-1};return m({...h(e.focus),range:{...f}})}return m({anchor:{row:0,col:0},focus:{row:t.rows-1,col:t.cols-1}})}return Z(n)?{type:"startEdit",initialInput:n.key}:{type:"none"}}function ge(e,n,t){if(!e)return null;let r=Math.fround(n),o=Math.fround(t);if(!Number.isFinite(r)||!Number.isFinite(o))return null;for(let l=e.length-1;l>=0;l--){let s=e[l].clip,i=Math.fround(s.x),c=Math.fround(s.y),u=Math.fround(i+Math.fround(s.w)),f=Math.fround(c+Math.fround(s.h));if(r>=i&&r<u&&o>=c&&o<f)return e[l]}return null}function F(e,n){let t=e.length-1;if(t<=0||n<e[0]||n>=e[t])return -1;let r=0,o=t-1;for(;r<o;){let l=r+o+1>>1;e[l]<=n?r=l:o=l-1;}return r}function xe(e,n,t){if(!e)return null;let r=F(e.colOffsets,n),o=F(e.rowOffsets,t);return r<0||o<0?null:{row:e.rowIndices?.[o]??e.startRow+o,col:e.colIndices?.[r]??e.startCol+r}}function k(e,n,t,r){if(n){let l=0,s=n.length-1;for(;l<=s;){let i=l+s>>1,c=n[i];if(c===r)return i;c<r?l=i+1:s=i-1;}return -1}let o=r-e;return o>=0&&o<t.length-1?o:-1}function ye(e,n,t){if(!e)return null;let r=k(e.startCol,e.colIndices,e.colOffsets,t),o=k(e.startRow,e.rowIndices,e.rowOffsets,n);return r<0||o<0?null:{x:e.colOffsets[r],y:e.rowOffsets[o],w:e.colOffsets[r+1]-e.colOffsets[r],h:e.rowOffsets[o+1]-e.rowOffsets[o]}}function ee(e,n,t){return n?.[t]??e+t}function z(e,n,t,r,o){let l=-1,s=-1;for(let i=0;i<t;i++){let c=ee(e,n,i);if(!(c<r)){if(c>o)break;l<0&&(l=i),s=i;}}return l<0?null:[l,s]}function Se(e,n){if(!e)return null;let t=e.colOffsets.length-1,r=e.rowOffsets.length-1;if(t<=0||r<=0)return null;let o=z(e.startCol,e.colIndices,t,n.left,n.right),l=z(e.startRow,e.rowIndices,r,n.top,n.bottom);if(!o||!l)return null;let[s,i]=o,[c,u]=l;return {x:e.colOffsets[s],y:e.rowOffsets[c],w:e.colOffsets[i+1]-e.colOffsets[s],h:e.rowOffsets[u+1]-e.rowOffsets[c]}}function Ae(e,n,t){return e.hyperlinks?.find(r=>n>=r.top&&n<=r.bottom&&t>=r.left&&t<=r.right)??null}function Re(e){if(!e.externalTarget)return null;let n;try{n=new URL(e.externalTarget);}catch{return null}return ["http:","https:","mailto:","tel:"].includes(n.protocol)?(e.location&&!n.hash&&(n.hash=e.location.replace(/^#/,"")),n.href):null}function Me(e,n){let t=e.replace(/^#/,""),r=t.lastIndexOf("!"),o=r<0?n:t.slice(0,r),l=(r<0?t:t.slice(r+1)).split(":",1)[0],s=/^\$?([A-Za-z]{1,3})\$?([1-9]\d*)$/.exec(l);if(!s)return null;let i=0;for(let f of s[1].toUpperCase())i=i*26+f.charCodeAt(0)-64;let c=Number(s[2]);if(i<1||i>16384||c<1||c>1048576)return null;let u=o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1).replace(/''/g,"'"):o;return u?{sheetName:u,row:c-1,col:i-1}:null}var ne=new Set(["=","+","-","@"]);function te(e){let n=e.charCodeAt(0);return ne.has(e[0])||n===9||n===13||n===10}function oe(e){return /[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function re(e){let n=!e.isFormula&&e.input.length>0&&te(e.input);return oe(n?`'${e.input}`:e.input)}function He(e){return e.map(n=>n.map(re).join(" ")).join(`\r
2
- `)}function Ie(e){let n=[],t=[],r="",o=false,l=0,s=()=>{t.push(r),r="";},i=()=>{s(),n.push(t),t=[];};for(;l<e.length;){let c=e[l];if(o){if(c==='"'){if(e[l+1]==='"'){r+='"',l+=2;continue}o=false,l+=1;continue}r+=c,l+=1;continue}if(c==='"'){o=true,l+=1;continue}if(c===" "){s(),l+=1;continue}if(c==="\r"){i(),e[l+1]===`
3
- `&&(l+=1),l+=1;continue}if(c===`
4
- `){i(),l+=1;continue}r+=c,l+=1;}return (r.length>0||t.length>0)&&i(),n}function G(e){let n=e,t="";do t=String.fromCharCode(65+n%26)+t,n=Math.floor(n/26)-1;while(n>=0);return t}function le(e,n){return `${G(n)}${e+1}`}function L(e,n){return e.replace(/\{(\w+)\}/g,(t,r)=>String(n[r]??""))}function V(e,n){return `${Math.round(e*1e3)},${Math.round(n*1e3)}`}function ce(e){let n=new Map;for(let t of e.commands)t.op==="text"&&t.clip&&!t.ghost&&!t.chart&&n.set(V(t.clip.x,t.clip.y),t.text);return n}function ie(e,n,t){return e?n>=e.top&&n<=e.bottom&&t>=e.left&&t<=e.right:false}function M(e,n,t){return n?.[t]??e+t}function se(e,n,t,r,o,l){let s=M(e.startRow,e.rowIndices,n),i=M(e.startCol,e.colIndices,t),c=le(s,i),f=r.length===0?o?l.emptyCellLabelSelected:l.emptyCellLabel:o?l.cellLabelSelected:l.cellLabel;return {row:s,col:i,address:c,text:r,selected:o,label:L(f,{address:c,value:r})}}function ve(e,n,t,r){let o=e.grid,l=L(r.gridLabel,{sheet:t}),s=(e.charts??[]).map(p=>({label:p.label,placeholder:p.placeholder??false}));if(!o)return {label:l,sheetName:t,columnHeaders:[],rows:[],charts:s};let i=o.colOffsets.length-1,c=o.rowOffsets.length-1,u=n?x(n):null,f=ce(e),a=[];for(let p=0;p<i;p++){let d=M(o.startCol,o.colIndices,p),w=G(d);a.push({col:d,text:w,label:L(r.columnHeaderLabel,{column:w})});}let O=[];for(let p=0;p<c;p++){let d=M(o.startRow,o.rowIndices,p),w=[];for(let g=0;g<i;g++){let H=V(o.colOffsets[g],o.rowOffsets[p]),b=f.get(H)??"",_=M(o.startCol,o.colIndices,g);w.push(se(o,p,g,b,ie(u,d,_),r));}O.push({row:d,header:L(r.rowHeaderLabel,{row:d+1}),cells:w});}return {label:l,sheetName:t,columnHeaders:a,rows:O,charts:s}}export{v as a,P as b,D as c,$ as d,N as e,U as f,h as g,x as h,W as i,B as j,C as k,S as l,Q as m,ge as n,xe as o,ye as p,Se as q,Ae as r,Re as s,Me as t,He as u,Ie as v,ve as w};