@betteroffice/pptx 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 (57) 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 +24 -5
  5. package/dist/chunk-2XA2UH2O.js +1 -0
  6. package/dist/chunk-4WP5ZWYV.js +1 -0
  7. package/dist/chunk-65A2TX24.js +1 -0
  8. package/dist/chunk-663FARNX.js +1 -0
  9. package/dist/chunk-AYLLA7XR.js +1 -0
  10. package/dist/chunk-AZDGFDN2.js +1 -0
  11. package/dist/chunk-CCVGR3MS.js +1 -0
  12. package/dist/chunk-COS6CTH7.js +2 -0
  13. package/dist/chunk-G54T5CXF.js +1 -0
  14. package/dist/chunk-GAM2OAAP.js +2 -0
  15. package/dist/chunk-GHET7GIK.js +1 -0
  16. package/dist/chunk-GR7EGQ2Z.js +1 -0
  17. package/dist/chunk-HZODDD5T.js +1 -0
  18. package/dist/chunk-J54GRQWZ.js +1 -0
  19. package/dist/chunk-JJV35WHH.js +2 -0
  20. package/dist/chunk-KGEED2XY.js +1 -0
  21. package/dist/chunk-O2XFH626.js +1 -0
  22. package/dist/chunk-OUNTNO7R.js +1 -0
  23. package/dist/chunk-QRAGGQDN.js +1 -0
  24. package/dist/chunk-QWRXUT7T.js +1 -0
  25. package/dist/chunk-RNJM2LKC.js +3 -0
  26. package/dist/chunk-S6HKAO2F.js +1 -0
  27. package/dist/chunk-S6UYP4BX.js +1 -0
  28. package/dist/chunk-T6VUFMNC.js +1 -0
  29. package/dist/chunk-TRT2B252.js +10 -0
  30. package/dist/collaboration.js +1 -1
  31. package/dist/{editorSession-Cuqxkg-B.d.ts → editorSession-qQaVvMVR.d.ts} +356 -18
  32. package/dist/generated/metafile_svg_wasm_bg.wasm +0 -0
  33. package/dist/generated/pptx_wasm_bg.wasm +0 -0
  34. package/dist/generated/pptx_wasm_lean_bg.wasm +0 -0
  35. package/dist/generated/preflight/pptx_preflight_bg.wasm +0 -0
  36. package/dist/index.d.ts +21 -18
  37. package/dist/index.js +1 -1
  38. package/dist/pptxSessionWorker.mjs +13 -9
  39. package/dist/pptxSessionWorker.node.mjs +1 -0
  40. package/dist/pptxWorkerStart.d.ts +5 -0
  41. package/dist/pptxWorkerStart.js +1 -0
  42. package/dist/sessionWorker.missing.d.ts +3 -0
  43. package/dist/sessionWorker.missing.js +1 -0
  44. package/dist/sessionWorker.node.d.ts +3 -0
  45. package/dist/sessionWorker.node.js +1 -0
  46. package/dist/transport-BcduBS8X.d.ts +16 -0
  47. package/dist/wasm-preflight.d.ts +26 -0
  48. package/dist/wasm-preflight.js +1 -0
  49. package/dist/worker.d.ts +122 -22
  50. package/dist/worker.js +1 -1
  51. package/package.json +18 -5
  52. package/dist/chunk-2NCQ2IE7.js +0 -3
  53. package/dist/chunk-4FWJR3UX.js +0 -1
  54. package/dist/chunk-H3SEEI4U.js +0 -1
  55. package/dist/chunk-LIYNXEQC.js +0 -1
  56. package/dist/chunk-NNSP5326.js +0 -1
  57. /package/dist/{pptxSessionWorker.d.ts → pptxSessionWorker.node.d.ts} +0 -0
@@ -1 +0,0 @@
1
- import {a,d as d$1,h,i,j as j$1,e,g as g$1,n,s,k,o,m,u,t,q,l as l$1,p as p$1,v,y as y$1}from'./chunk-H3SEEI4U.js';var O=new WeakMap;function ee(n,e){O.set(n,e);}function D(n){return O.get(n)}var l=class extends Error{constructor(t,r,s){super(r);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=s;}};function G(n){return n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:"Unknown error"}var $=["backpressure","protocol","replica","transport"],g=64,Q=250;function X(n){if(n[0]!==0||n[1]!==2)return false;let e=0;for(let t=2,r=0;t<Math.min(n.byteLength,7);t++,r+=7)if(e+=(n[t]&127)*2**r,n[t]<128)return t+1+e===n.byteLength;return false}var y=class{constructor(e,t,r){a(this,"transport",t);a(this,"options",r);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(s=>this.receive(s),s=>this.lose(s)),this.enqueue({op:"create",seq:++this.seq,options:r.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,r;try{if(r=this.transport.onEvent(s=>this.forward(t,s)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(s){this.subscription+=1,this.fail(this.transportError("Failed to subscribe to transport events",s));return}if(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt||t!==this.subscription){try{r();}catch(s){this.isDestroyed||this.report(this.transportError("Failed to unsubscribe from stale transport events",s));}return}this.unsubscribeTransport=r;}try{let t=this.transport.connect();t&&t.catch(r=>{!this.isDestroyed&&this.wantsConnection&&this.connectAttempt===e&&this.fail(this.transportError("Transport connect failed",r));});}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 r of t)this.report(r);}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 r of t)this.report(r);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=[],r=this.unsubscribeTransport;if(this.unsubscribeTransport=null,this.subscription+=1,r)try{r();}catch(s){t.push(this.transportError("Failed to unsubscribe from transport events",s));}if(!e)return t;try{let s=this.transport.disconnect();s&&s.catch(o=>{this.isDestroyed||this.report(this.transportError("Transport disconnect failed",o));});}catch(s){t.push(this.transportError("Transport disconnect failed",s));}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"&&$.includes(t)?t:"transport",message:e.message}});let r=this.release(true);this.setStatus("disconnected",false),this.report(e);for(let s of r)this.report(s);}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();},Q));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(o=>o.op==="destroy"),r=e.reduce((o,a)=>a.op==="event"&&a.event.type==="message"?o+a.event.data.byteLength+g:o,0),s;try{s=this.endpoint.post(e,v(e));}catch(o){s=Promise.reject(o);}s.then(()=>{this.posting=false,this.inboundBytes-=r,t?this.close():this.urgent?this.flush():this.queue.length>0&&this.schedule(true);},o=>{this.posting=false,this.inboundBytes-=r,this.lose(G(o));});}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+g>this.options.maxPendingBytes-this.inboundBytes){this.fail(this.options.makeError("backpressure","Pending replica data exceeds the byte limit"));return}this.inboundBytes+=t.data.byteLength+g,this.enqueue({op:"event",seq:++this.seq,event:{type:"message",data:t.data.slice().buffer}},!this.isSynced&&X(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 r=this.release(false);for(let s of r)this.report(s);break}case "disconnect":{this.wantsConnection=false;let r=this.release(true);for(let s of r)this.report(s);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 r=this.options.rebasePeer,s=t.timeOrigin-y$1();this.peerList=r?t.peers.map(o=>r(o,s)):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,r;try{r=this.transport.send(e.slice());}catch(s){this.fail(this.transportError("Transport send failed",s));return}if(typeof r!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}!r&&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(r){this.fail(this.transportError("Transport send failed",r));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 r of t)this.report(r);}},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[r,s]of [...this.statusListeners])if(this.statusListeners.get(r)===s)try{s({status:e,synced:t});}catch{}}}emitPeers(){let e=this.peers;for(let[t,r]of [...this.peerListeners])if(this.peerListeners.get(t)===r)try{r(e);}catch{}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};var j=16*1024*1024,Y=16*1024*1024;function C(n,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${n} must be ${t?"a non-negative":"a positive"} integer`);return e}function J(n){return n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:"Unknown error"}function p(n,e,t){return t instanceof l?t:new l(n,`${e}: ${J(t)}`,t)}function d(n,e){if(!(n instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return n.slice()}function T(n){typeof n=="object"&&n&&"unref"in n&&n.unref();}function K(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("Replica clientId must be a non-negative safe integer");return n}function Z(n){if(n===null)return null;if(!n||typeof n.slideId!="string"||n.slideId.length===0)throw new TypeError("Presence cursor slideId must be a non-empty string");if(n.shapeId!==void 0&&(typeof n.shapeId!="string"||n.shapeId.length===0))throw new TypeError("Presence cursor shapeId must be a non-empty string");return n.shapeId?{slideId:n.slideId,shapeId:n.shapeId}:{slideId:n.slideId}}var _=new WeakMap,N=new WeakMap;function ue(n){return _.get(n)()}function de(n){return N.get(n)()}var M=class{constructor(e,t,r={}){a(this,"piped");a(this,"openEpoch",0);a(this,"replica");a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"localClientId");a(this,"localUser");a(this,"remotePresence");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"presenceListeners",new Map);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,"incoming",[]);a(this,"incomingBytes",0);a(this,"incomingBusy",false);a(this,"asyncReplica",false);a(this,"incomingGeneration",0);a(this,"isFlushing",false);a(this,"localClock",0);a(this,"reportedClockExhaustion",false);a(this,"localCursor",null);a(this,"applyingArrival");a(this,"lastAwarenessSentAt",0);a(this,"cursorTimer",null);a(this,"heartbeatTimer",null);a(this,"expiryTimer",null);this.replica=e,"setCollaborative"in e&&e.setCollaborative?.(),this.transport=t,this.localClientId=K(e.clientId),this.localUser=d$1(this.localClientId,r.user),this.remotePresence=new h(this.localClientId),this.maxFrameBytes=C("maxFrameBytes",r.maxFrameBytes??i,false),this.maxMessagesPerFrame=C("maxMessagesPerFrame",r.maxMessagesPerFrame??j$1,false),this.maxPendingBytes=C("maxPendingBytes",r.maxPendingBytes??j,true),_.set(this,()=>this.beginArrival()),N.set(this,()=>this.leaveFrame());let s=D(e);if(s){this.unsubscribeReplica=()=>{},this.piped=new y(s,t,{worker:{maxFrameBytes:this.maxFrameBytes,maxMessagesPerFrame:this.maxMessagesPerFrame,user:{...this.localUser}},maxPendingBytes:this.maxPendingBytes,hasUser:true,makeError:(o,a,c)=>new l(o,a,c),normalize:p});return}try{this.unsubscribeReplica=e.onUpdate((o,a)=>{a==="local"&&this.forwardLocalUpdate(o);});}catch(o){throw p("replica","Failed to observe replica updates",o)}}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:this.remotePresence.peers}setCursor(e$1){if(this.isDestroyed||this.piped?.status==="destroyed")return;let t=Z(e$1),r=!t||e(t)?t:null;if(t&&!r){let s=new l("protocol",`Presence cursor identifiers exceed ${1024} characters; cursor dropped`);this.report(s);}if(!g$1(this.localCursor,r)){if(this.localCursor=r,this.piped)return this.piped.setCursor(r,true);this.isOpen&&this.wantsConnection&&this.scheduleCursorBroadcast();}}connect(){if(this.piped)return this.piped.connect();if(this.isDestroyed||this.isOpen||this.connectionStatus==="connecting")return;this.wantsConnection=true;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let r;try{if(r=this.transport.onEvent(s=>this.handleTransportEvent(e,s)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(s){this.failConnection(e,p("transport","Failed to subscribe to transport events",s));return}if(!this.isCurrent(e)){try{r();}catch(s){this.isDestroyed||this.report(p("transport","Failed to unsubscribe from stale transport events",s));}return}this.unsubscribeTransport=r,this.hasTransportSubscription=true;}try{let r=this.transport.connect();r&&r.catch(s=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,p("transport","Transport connect failed",s));});}catch(r){this.failConnection(e,p("transport","Transport connect failed",r));}}}disconnect(){if(this.piped)return this.piped.disconnect();if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;if(this.isOpen&&this.wantsConnection){let s=this.epoch;if(this.broadcastLocalPresence(true),!this.isCurrent(s))return}this.stopPresenceTimers(),this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let r=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let s of r)this.report(s);}destroy(){if(this.piped){this.piped.destroy(),this.isDestroyed=true,this.errorListeners.clear();return}if(this.isDestroyed||(this.isOpen&&this.wantsConnection&&this.broadcastLocalPresence(true),this.isDestroyed))return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.stopPresenceTimers(),this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let r=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let s of r)this.report(s);try{this.unsubscribeReplica();}catch(s){this.report(p("replica","Failed to unsubscribe from replica updates",s));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.presenceListeners.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");if(this.piped){let r=this.piped.onError(e),s=this.nextListenerId++;return this.errorListeners.set(s,e),()=>{r(),this.errorListeners.delete(s);}}let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}onPresence(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("presence listener must be a function");if(this.piped)return this.piped.onPeers(r=>{try{e(r);}catch{}});let t=this.nextListenerId++;this.presenceListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.presenceListeners.delete(t)}beginArrival(){let e=this.epoch,t=this.openEpoch,r=this.applyingArrival;r&&(r.deferred=true);let s=false,o=a=>{s||(s=true,this.isCurrent(e)&&this.isOpen&&this.openEpoch===t&&a());};return {settle:()=>o(()=>{r?.synced&&this.setStatus("connected",true);}),fail:a=>o(()=>this.failConnection(e,p("replica","Failed to apply remote update",a)))}}leaveFrame(){if(!this.isOpen||this.isDestroyed||!this.wantsConnection||this.localClock>=Number.MAX_SAFE_INTEGER)return null;try{let e=this.localClock+1;return {clock:e,frame:n([{clientId:this.localClientId,clock:e,state:null}],this.maxFrameBytes)}}catch{return null}}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1,this.stopPresenceTimers();let r=this.takeTransportSubscription();this.clearPending(),this.clearRemotePresence();let s=this.cleanupTransport(r,true);this.setStatus("disconnected",false),this.report(t);for(let o of s)this.report(o);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let r=[];try{e();}catch(s){r.push(p("transport","Failed to unsubscribe from transport events",s));}if(!t)return r;try{let s=this.transport.disconnect();s&&s.catch(o=>{this.isDestroyed||this.report(p("transport","Transport disconnect failed",o));});}catch(s){r.push(p("transport","Transport disconnect failed",s));}return r}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.enqueueMessage(e,t.data);break;case "close":this.isOpen=false,this.connectAttempt+=1,this.stopPresenceTimers(),this.clearPending(),this.clearRemotePresence(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,p("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new l("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen||(this.isOpen=true,this.openEpoch+=1,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen))return;let t=this.connectAttempt;this.replicaResult(e,t,()=>this.replica.encodeStateVector(),r=>{try{let s$1=d(r,"encodeStateVector"),o$1=s(s$1);if(this.sendFrame(k(o$1??s$1,this.maxFrameBytes)),!this.isCurrent(e)||!this.isOpen||(o$1||this.sendFullUpdate(e,t),!this.isCurrent(e)||!this.isOpen)||(this.startPresenceTimers(),this.broadcastLocalPresence(!1),!this.isCurrent(e)||!this.isOpen))return;this.sendFrame(o(this.maxFrameBytes));}catch(s){this.failConnection(e,p("protocol","Failed to encode handshake",s));}});}sendFullUpdate(e,t){this.replicaResult(e,t,()=>this.replica.encodeStateAsUpdate(),r=>{try{this.sendFrame(m(d(r,"encodeStateAsUpdate"),this.maxFrameBytes));}catch(s){this.failConnection(e,p("protocol","Failed to encode handshake",s));}});}replicaResult(e,t,r,s){let o=c=>{this.isCurrent(e)&&this.isOpen&&this.connectAttempt===t&&s(c);},a=c=>{this.isCurrent(e)&&this.isOpen&&this.connectAttempt===t&&this.failConnection(e,p("replica","Collaboration replica operation failed",c));};try{let c=r();if(c instanceof Promise)return this.asyncReplica=!0,c.then(o,a).catch(a);o(c);}catch(c){a(c);}}handleMessage(e,t){let r;try{r=u(t.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);}catch(a){this.failConnection(e,p("protocol","Invalid collaboration frame",a));return}let s=this.connectAttempt,o=a=>{for(;a<r.length;a++){if(!this.isCurrent(e)||!this.isOpen||this.connectAttempt!==s)return;let c=r[a],h;switch(c.type){case "sync-step-1":h=this.answerSyncStep1(e,s,c.stateVector);break;case "sync-step-2":case "update":{let u={deferred:false,synced:c.type==="sync-step-2"};h=this.replicaResult(e,s,()=>{let V=this.applyingArrival;this.applyingArrival=u;try{return this.replica.applyUpdate(q(c.update).slice())}finally{this.applyingArrival=V;}},()=>{u.synced&&!u.deferred&&this.setStatus("connected",true);});break}case "awareness":try{let u=p$1(c.update,this.maxMessagesPerFrame);this.remotePresence.apply(u,Date.now())&&this.emitPresence(),this.schedulePresenceExpiry();}catch(u){this.report(p("protocol","Invalid awareness update",u));}break;case "auth":this.failConnection(e,new l("protocol",c.reason?`Authentication denied: ${c.reason}`:"Authentication denied"));return;case "query-awareness":this.broadcastLocalPresence(false);break}if(h instanceof Promise)return h.then(()=>o(a+1))}};return o(0)}answerSyncStep1(e,t$1,r){let s=t(r),o=this.replicaResult(e,t$1,()=>this.replica.encodeStateAsUpdate(q(s.stateVector).slice()),c=>{try{this.sendFrame(l$1(d(c,"encodeStateAsUpdate"),this.maxFrameBytes));}catch(h){this.failConnection(e,p("protocol","Failed to encode SyncStep2",h));}});if(!s.open)return o;let a=()=>{if(!(!this.isCurrent(e)||!this.isOpen||this.connectAttempt!==t$1))return this.replicaResult(e,t$1,()=>this.replica.encodeStateVector(),c=>{try{this.sendFrame(k(d(c,"encodeStateVector"),this.maxFrameBytes));}catch(h){this.failConnection(e,p("protocol","Failed to encode handshake",h));}})};return o instanceof Promise?o.then(a):a()}enqueueMessage(e,t){if(this.asyncReplica&&this.incomingBytes+t.byteLength>this.maxPendingBytes){this.failConnection(e,new l("backpressure","Incoming collaboration queue is full"));return}this.incoming.push({token:e,data:t.slice()}),this.incomingBytes+=t.byteLength,this.drainIncoming();}drainIncoming(){if(this.incomingBusy)return;let e=this.incomingGeneration;for(;this.incoming.length;){let t=this.takeUpdateBatch(),r=t?.items??[this.incoming.shift()],s=r.reduce((a,c)=>a+c.data.byteLength,0);this.incomingBusy=true;let o=t?this.applyUpdateBatch(r[0].token,t.updates):this.handleMessage(r[0].token,r[0].data);if(e!==this.incomingGeneration)return;if(o instanceof Promise){o.finally(()=>{e===this.incomingGeneration&&(this.incomingBusy=false,this.incomingBytes-=s,this.drainIncoming());}).catch(()=>{});return}this.incomingBusy=false,this.incomingBytes-=s;}}takeUpdateBatch(){if(!this.asyncReplica||typeof this.replica.applyUpdateChunks!="function")return null;let e=[],t=[],r=Math.min(this.maxFrameBytes,Y),s=0;for(let o of this.incoming){if(o.token!==this.incoming[0].token)break;let a=this.remoteUpdates(o.data),c=a?.reduce((h,u)=>h+u.byteLength,0)??0;if(!a?.length||e.length&&s+c>r)break;e.push(o),t.push(...a),s+=c;}return e.length<2?null:(this.incoming.splice(0,e.length),{items:e,updates:t})}remoteUpdates(e){try{let t=u(e.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);return t.every(r=>r.type==="update")?t.map(r=>q(r.update).slice()):null}catch{return null}}applyUpdateBatch(e,t){if(!this.isCurrent(e)||!this.isOpen)return;let r=this.replica;return this.replicaResult(e,this.connectAttempt,()=>r.applyUpdateChunks(t),()=>{})}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,r;try{r=d(e,"Replica update");}catch(s){this.failConnection(t,p("replica","Invalid replica update",s));return}try{this.sendFrame(m(r,this.maxFrameBytes));}catch(s){this.failConnection(t,p("protocol","Failed to encode update",s));}}scheduleCursorBroadcast(){if(this.cursorTimer)return;let e=Math.max(0,80-(Date.now()-this.lastAwarenessSentAt));if(e===0){this.broadcastLocalPresence(false);return}this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.broadcastLocalPresence(false);},e),T(this.cursorTimer);}broadcastLocalPresence(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;if(this.localClock>=Number.MAX_SAFE_INTEGER){this.reportedClockExhaustion||(this.reportedClockExhaustion=true,this.report(new l("protocol","Awareness clock exceeds Number.MAX_SAFE_INTEGER")));return}this.localClock+=1;let t=this.localClock,r=e?null:{clientId:this.localClientId,clock:t,user:{...this.localUser},cursor:this.localCursor?{...this.localCursor}:null};this.cursorTimer&&clearTimeout(this.cursorTimer),this.cursorTimer=null,this.lastAwarenessSentAt=Date.now();try{let s=n([{clientId:this.localClientId,clock:t,state:r}],this.maxFrameBytes);e?this.sendLeaveFrameBestEffort(s):this.sendFrame(s);}catch(s){this.report(p("protocol","Failed to encode awareness update",s));}}sendLeaveFrameBestEffort(e){try{this.transport.send(e.slice());}catch{}}startPresenceTimers(){this.stopPresenceTimers(),this.heartbeatTimer=setInterval(()=>{this.broadcastLocalPresence(false);},2e4),T(this.heartbeatTimer),this.schedulePresenceExpiry();}stopPresenceTimers(){this.cursorTimer&&clearTimeout(this.cursorTimer),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.expiryTimer&&clearTimeout(this.expiryTimer),this.cursorTimer=null,this.heartbeatTimer=null,this.expiryTimer=null;}schedulePresenceExpiry(){if(this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null,!this.isOpen||this.isDestroyed)return;let e=this.remotePresence.nextExpiryAt;e!==void 0&&(this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.remotePresence.expire(Date.now())&&this.emitPresence(),this.schedulePresenceExpiry();},Math.max(0,e-Date.now())),T(this.expiryTimer));}clearRemotePresence(){this.remotePresence.clear()&&this.emitPresence();}emitPresence(){let e=this.peers;for(let[t,r]of [...this.presenceListeners])if(this.presenceListeners.get(t)===r)try{r(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 r;try{r=this.transport.send(e.slice());}catch(s){this.failConnection(t,p("transport","Transport send failed",s));return}if(typeof r!="boolean"){this.failConnection(t,new l("transport","Transport send must return a boolean"));return}!r&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new l("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let r=t.slice();this.pendingFrames.push(r),this.queuedBytes+=r.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],r;try{r=this.transport.send(t.slice());}catch(s){this.failConnection(e,p("transport","Transport send failed",s));return}if(typeof r!="boolean"){this.failConnection(e,new l("transport","Transport send must return a boolean"));return}if(!r||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.incoming.length=0,this.incomingBytes=0,this.incomingBusy=false,this.incomingGeneration+=1,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 r={status:e,synced:t};for(let[s,o]of [...this.statusListeners])if(this.statusListeners.get(s)===o)try{o(r);}catch{}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};export{ee as a,D as b,l as c,ue as d,de as e,M as f};
@@ -1 +0,0 @@
1
- import {a,L,N,J,O,b,W,F,E,R,B,s,g,h,i,Y,Q,C,D,S,U,m,V as V$1,e}from'./chunk-4FWJR3UX.js';function fe(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<10)return;let r=0,i=0;if(t.length>=24&&e.getUint32(0)===2303741511&&e.getUint32(4)===218765834&&e.getUint32(12)===1229472850)r=e.getUint32(16),i=e.getUint32(20);else if(e.getUint32(0)===1195984440&&[55,57].includes(t[4])&&t[5]===97)r=e.getUint16(6,true),i=e.getUint16(8,true);else if(t.length>=26&&e.getUint16(0,true)===19778)e.getUint32(14,true)===12?(r=e.getUint16(18,true),i=e.getUint16(20,true)):(r=e.getInt32(18,true),i=Math.abs(e.getInt32(22,true)));else if(t.length>=20&&e.getUint32(0)===1380533830&&e.getUint32(8)===1464156752){let s=e.getUint32(12);if(s===1448097880&&t.length>=30)r=1+t[24]+(t[25]<<8)+(t[26]<<16),i=1+t[27]+(t[28]<<8)+(t[29]<<16);else if(s===1448097868&&t.length>=25&&t[20]===47){let n=e.getUint32(21,true);r=1+(n&16383),i=1+(n>>>14&16383);}else s===1448097824&&t.length>=30&&t[23]===157&&t[24]===1&&t[25]===42&&(r=e.getUint16(26,true)&16383,i=e.getUint16(28,true)&16383);}else if(e.getUint16(0)===65496){let s=false;for(let n=2;n+4<=t.length;){if(t[n++]!==255)return;for(;t[n]===255;)n+=1;let o=t[n++];if(o===217||o===218)break;if(o===1||o>=208&&o<=216)continue;if(n+2>t.length)return;let l=e.getUint16(n);if(l<2||n+l>t.length)return;o===225&&(s=s||Se(t.subarray(n+2,n+l))),o>=192&&o<=207&&![196,200,204].includes(o)&&l>=7&&(i=e.getUint16(n+3),r=e.getUint16(n+5)),n+=l;}s&&([r,i]=[i,r]);}return r>0&&i>0?{width:r,height:i}:void 0}function Se(t){if(t.length<14||![69,120,105,102,0,0].every((n,o)=>t[o]===n))return false;let e=new DataView(t.buffer,t.byteOffset+6,t.byteLength-6),r=e.getUint16(0)===18761;if(!r&&e.getUint16(0)!==19789||e.getUint16(2,r)!==42)return false;let i=e.getUint32(4,r);if(i>e.byteLength-2)return false;let s=e.getUint16(i,r);for(let n=0;n<s;n+=1){let o=i+2+n*12;if(o>e.byteLength-12)return false;if(e.getUint16(o,r)===274&&e.getUint16(o+2,r)===3&&e.getUint32(o+4,r)===1)return [5,6,7,8].includes(e.getUint16(o+8,r))}return false}var ke=33554432,ue="image/svg+xml",be=4194304,Ue=4096,pe=new WeakMap;function Ne(t){return pe.get(t)??{x:1,y:1}}function We(t,e){pe.set(t,e);}function Ae(t){if(a(t))throw new Error("TIFF images require worker conversion");let e=Ce(t)??Be(t);return e?new Blob([e],{type:"image/bmp"}):Me(t)??new Blob([t.slice()])}function Ie(t){return t.type===ue}async function Ke(t,e,r={}){let i=Ae(t);return Oe(i,e,r)}async function Oe(t,e,r={}){let i=r.maxDimension??Ue;if(!Number.isSafeInteger(i)||i<1)throw new Error("invalid image dimension limit");if(typeof createImageBitmap=="function"&&!Ie(t)){let n=fe(new Uint8Array(await t.arrayBuffer()));if(n&&Math.max(n.width,n.height)>i){let l=i/Math.max(n.width,n.height),u=await createImageBitmap(t,{resizeWidth:Math.max(1,Math.floor(n.width*l)),resizeHeight:Math.max(1,Math.floor(n.height*l))});return K(u,n,i)}let o=await createImageBitmap(t);return K(o,{width:o.width,height:o.height},i)}let s=URL.createObjectURL(t);try{let n=await new Promise((o,l)=>{let u=new Image;u.onload=()=>o(u),u.onerror=()=>l(new Error(e)),u.src=s;});return await K(n,{width:n.naturalWidth,height:n.naturalHeight},i)}finally{URL.revokeObjectURL(s);}}async function K(t,e,r){let i="naturalWidth"in t?t.naturalWidth:t.width,s="naturalHeight"in t?t.naturalHeight:t.height,n=t;if(Math.max(i,s)>r){let u=r/Math.max(i,s),f={width:Math.max(1,Math.floor(i*u)),height:Math.max(1,Math.floor(s*u))},d,m;try{typeof OffscreenCanvas=="function"&&(d=new OffscreenCanvas(f.width,f.height),m=d.getContext("2d"));}catch{d=void 0;}if(!m&&typeof document<"u")try{d=document.createElement("canvas"),d.width=f.width,d.height=f.height,m=d.getContext("2d");}catch{d=void 0;}if(d&&m){m.drawImage(t,0,0,f.width,f.height),"close"in t&&typeof t.close=="function"&&t.close();try{n=typeof createImageBitmap=="function"?await createImageBitmap(d):d;}catch{n=d;}}}let o="naturalWidth"in n?n.naturalWidth:n.width,l="naturalHeight"in n?n.naturalHeight:n.height;return (e.width!==o||e.height!==l)&&We(n,{x:e.width/o,y:e.height/l}),n}function Me(t){if(t.byteLength>be)return;let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t).replace(/^\ufeff/,"");}catch{return}if(!(!/^\s*</.test(e)||!e.slice(0,1024).includes("<svg")))return new Blob([Fe(e)],{type:ue})}function Fe(t){let e=Te(t);if(!e||/\s(?:width|height)\s*=/.test(t.slice(e.start,e.end)))return t;let r=t.slice(e.start,e.end).match(/\sviewBox\s*=\s*(["'])\s*[-+.\deE]+[\s,]+[-+.\deE]+[\s,]+([-+.\deE]+)[\s,]+([-+.\deE]+)\s*\1/),[i,s]=[Number(r?.[2]),Number(r?.[3])];if(!(i>0)||!(s>0))return t;let n=e.start+4;return `${t.slice(0,n)} width="${i}" height="${s}"${t.slice(n)}`}function Te(t){let e=0;for(;e<t.length;){if(/\s/.test(t[e]))e+=1;else if(t.startsWith("<!--",e))e=j(t.indexOf("-->",e+4),3);else if(t.startsWith("<?",e))e=j(t.indexOf("?>",e+2),2);else if(t.startsWith("<!",e))e=j(le(t,e+2),1);else break;if(e<0)return}if(!/^<svg[\s/>]/.test(t.slice(e,e+5)))return;let r=le(t,e+4);return r<0?void 0:{start:e,end:r}}function j(t,e){return t<0?-1:t+e}function le(t,e){let r="",i=false;for(let s=e;s<t.length;s+=1){let n=t[s];if(r)n===r&&(r="");else if(i&&t.startsWith("<!--",s)){if(s=j(t.indexOf("-->",s+4),2),s<0)return -1}else if(i&&t.startsWith("<?",s)){if(s=j(t.indexOf("?>",s+2),1),s<0)return -1}else if(n==='"'||n==="'")r=n;else if(n==="[")i=true;else if(n==="]")i=false;else if(n===">"&&!i)return s}return -1}function Be(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e.byteLength<108||e.getUint32(0,true)!==1||e.getUint32(40,true)!==1179469088)return;let r=e.getUint32(4,true);if(r<88||r%4||r>e.byteLength-8)return;let i=e.getInt32(16,true)-e.getInt32(8,true)+1,s=e.getInt32(20,true)-e.getInt32(12,true)+1,n=e.getUint32(r+4,true);if(e.getUint32(r,true)!==81||n<80||n>e.byteLength-r-8)return;let o=m=>e.getInt32(r+m,true),l=e.getUint32(r+48,true),u=e.getUint32(r+56,true),f=e.getUint32(r+60,true);if(o(24)!==e.getInt32(8,true)||o(28)!==e.getInt32(12,true)||o(72)!==i||o(76)!==s||o(32)!==0||o(36)!==0||o(40)!==i||o(44)!==s||e.getUint32(r+64,true)!==0||e.getUint32(r+68,true)!==13369376||l<80||l+e.getUint32(r+52,true)!==u||u+f!==n)return;let d=r+n;if(!(e.getUint32(d,true)!==14||e.getUint32(d+4,true)!==e.byteLength-d))return me(t.subarray(r+l,d),i,s)}function Ce(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e.byteLength<18)return;let r=e.getUint32(0,true)===2596720087?22:0;if(e.byteLength<r+18||![1,2].includes(e.getUint16(r,true))||e.getUint16(r+2,true)!==9||e.getUint16(r+4,true)!==768||e.getUint32(r+6,true)*2!==e.byteLength-r)return;let i=0,s=0,n=0,o=0,l=false,u;for(let f=r+18;f+6<=e.byteLength;){let d=e.getUint32(f,true)*2,m=e.getUint16(f+4,true);if(d<6||d>e.byteLength-f)return;if(m===0)return d===6&&f+d===e.byteLength?u:void 0;if(u)return;if(m===259){if(d<8||e.getUint16(f+6,true)!==8)return;l=true;}else if(m===263){if(d<8||![1,2,3,4].includes(e.getUint16(f+6,true)))return}else if(m===523||m===524){if(d!==10)return;let E=e.getInt16(f+6,true),U=e.getInt16(f+8,true);if(m===523)i=U,s=E;else {if(!l)return;n=U,o=E;}}else if(m===2881){if(d<66||e.getUint32(f+6,true)!==13369376||e.getInt16(f+14,true)!==0||e.getInt16(f+16,true)!==0||e.getInt16(f+18,true)!==o||e.getInt16(f+20,true)!==n||e.getInt16(f+22,true)!==s||e.getInt16(f+24,true)!==i||!n||!o||(u=me(t.subarray(f+26,f+d),e.getInt16(f+12,true),e.getInt16(f+10,true)),!u))return}else return;f+=d;}}function me(t,e,r){if(t.length<40)return;let i=new DataView(t.buffer,t.byteOffset,t.byteLength),s=i.getInt32(4,true),n=i.getInt32(8,true),o=i.getUint16(14,true);if(i.getUint32(0,true)!==40||s<1||!n||s*Math.abs(n)>ke||e!==s||r!==Math.abs(n)||i.getUint16(12,true)!==1||![24,32].includes(o)||i.getUint32(16,true)!==0||i.getUint32(32,true)!==0)return;let l=Math.ceil(s*o/32)*4*Math.abs(n),u=i.getUint32(20,true);if(40+l!==t.length||u!==0&&u!==l)return;let f=new Uint8Array(14+t.length),d=new DataView(f.buffer);return d.setUint16(0,19778,true),d.setUint32(2,f.length,true),d.setUint32(10,54,true),f.set(t,14),f}var Le=6e4;function ge(t){try{t.post({protocol:1,kind:"wasm-compile"});}catch(e){try{t.close();}catch{}throw e}}function V(t,e){let r=new Map,i=new Map,s=new Set,n=new Set(Object.keys(e.methods)),o=e.now??Date.now,l=e.timer??((a,h)=>{let w=setTimeout(a,h);return ()=>clearTimeout(w)}),u=e.silenceMs??Le,f=1,d,m,E,U=()=>{},k=()=>{};function x(){m?.(),m=void 0;}function P(a,h,w=false){for(let W of [...a])if(!(!a.has(W)||w&&d))try{W(h);}catch{}}function b(a,h=true){if(!d){d=a,x(),U(),k();for(let w of r.values())w.reject(a);if(r.clear(),i.clear(),h){try{t.close();}catch{}P(s,a);}s.clear();}}function y(){if(x(),r.size===0||d)return;let a=o();m=l(()=>b(new N("silence",`Session received no message within ${u}ms`,`Waiting for ${r.size} call(s); silent for ${o()-a}ms`)),u);}function v(a,h,w=[]){if(d)return Promise.reject(d);if(!n.has(a))return Promise.reject(new Error(`Unknown session method: ${a}`));let W=f++;return new Promise((F,g)=>{let c=r.size===0;r.set(W,{resolve:F,reject:g}),c&&y();try{t.post({protocol:1,kind:"call",id:W,method:a,args:h},w);}catch(p){r.delete(W),r.size===0&&x(),g(p instanceof Error?p:new Error(`Session call could not be posted: ${String(p)}`));}})}U=t.listen(a=>{if(!d)if(y(),L(a))if(a.kind==="failure")b(new N(a.code,a.message,a.diagnostics));else if(a.kind==="wasm-module"){try{e.onWasmModule?.(a.url,a.module);}catch{}try{e.onWasmModuleMessage?.(a);}catch{}}else {if(a.kind==="progress")return;if(a.kind==="event"){let h=i.get(a.name);h&&P(h,a.payload,true);}else {let h=r.get(a.id);if(!h)return;if(r.delete(a.id),r.size===0&&x(),a.ok)h.resolve(a.value);else {let w=new Error(a.error.message);w.name=a.error.name,J(a.error,"refusal")&&Object.assign(w,{refusal:a.error.refusal}),h.reject(w);}}}else {if(a!==null&&typeof a=="object"&&"kind"in a&&a.kind==="wasm-module")return;b(new N("message","Session received a malformed host message"));}}),k=t.onError(a=>b(a instanceof N?a:new N("crash",a instanceof Error?a.message:String(a))));let M=Object.create(null);for(let a of n)Object.defineProperty(M,a,{enumerable:true,value:(...h)=>v(a,h)});return {call:M,callWithTransfer:(a,h,w)=>v(a,h,w),on(a,h){if(d)return ()=>{};let w=i.get(a)??new Set;i.set(a,w);let W=h;return w.add(W),()=>{w.delete(W);}},onFailure(a){return d||s.add(a),()=>{s.delete(a);}},get failure(){return d},dispose(){if(E)return E;let a=d!==void 0;return b(new N("disposed","Session was disposed"),false),E=new Promise(h=>{if(!a)try{t.post({protocol:1,kind:"dispose"});}catch{}setTimeout(()=>{try{t.close();}catch{}h();},0);}),E}}}var z=new Map;function $(t){return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():new Uint8Array(t).slice()}function ye(t,e){for(let{assetId:s,bytes:n}of t.media)e.set(s,new Uint8Array(n));let r=JSON.parse(new TextDecoder().decode(t.displayList)),i=new Map;for(let s of Q(r)){let n=e.get(s);n!==void 0&&i.set(s,n);}return {...t,displayList:r,media:i}}function he(t,e){return t?.map(r=>{let i=$(r.bytes).buffer;return e.push(i),{family:r.family,bytes:i,bold:r.bold,italic:r.italic}})}function we(t,e){let r=$(t).buffer,i=[r],s={clientId:e.clientId,fonts:he(e.fonts,i),fallbackFonts:he(e.fallbackFonts,i)};if(e.initialUpdate!==void 0){let n=$(e.initialUpdate);s.initialUpdate=n,i.push(n.buffer);}return e.wasm instanceof ArrayBuffer?(s.wasm=e.wasm.slice(0),i.push(s.wasm)):e.wasm!==void 0?s.wasm=e.wasm:e.worker||(s.wasm=z.get(b().href)),{document:r,input:s,transfer:i}}function Pe(t,e,r){try{let{document:i,input:s,transfer:n}=we(t,e);e.wasm===void 0&&delete s.wasm;let o=V(r,{methods:S}),l=new Map,u=!1,f={get failure(){return o.failure},onFailure:d=>o.onFailure(d),begin:()=>o.callWithTransfer("beginEditor",[i,s],n),frame:async d=>{if(u)throw new E;let m=await o.call.editorFrame(d);if(u)throw new E;return {...ye(m,l),slideId:m.slideId,sequence:m.sequence}},dispose:async()=>{u=!0;try{await o.dispose();}finally{l.clear();}}};return R.set(f,{client:o,peerAttached:!1}),f}catch(i){try{r.close();}catch{}throw i}}async function nt(t,e={}){let r=O(e.worker?e.worker():new Worker(new URL("./pptxSessionWorker.mjs",import.meta.url),{type:"module"}));return !e.worker&&e.wasm===void 0&&!z.has(b().href)&&ge(r),Re(t,e,r)}async function Re(t,e,r){let i,s,n,o;try{(({document:i,input:s,transfer:n}=we(t,e))),o=V(r,{methods:W,onWasmModule:e.wasm===void 0&&!e.worker?(y,v)=>{y===b().href&&!z.has(y)&&z.set(y,v);}:void 0});}catch(y){try{r.close();}catch{}throw y}let l;o.on("changed",y=>{l={...l,...y};}),o.onFailure(()=>{l={...l,stage:"failed"};});try{l=await o.callWithTransfer("open",[i,s],n);}catch(y){throw await o.dispose(),y}let u=new Map,{version:f,readContent:d,findText:m,validateEdits:E,applyEdits:U,frame:k,slides:x,slideSize:P,save:b$1}=o.call;return {get state(){return l},call:{version:f,readContent:d,findText:m,validateEdits:E,applyEdits:U,slides:x,slideSize:P,save:b$1,frame:async y=>ye(await k(y),u)},save:async()=>new Uint8Array(await b$1()),on:(y,v)=>o.on(y,v),onFailure:y=>o.onFailure(y),get failure(){return o.failure},dispose:async()=>{try{await o.dispose();}finally{u.clear();}}}}var _=new WeakMap;var je=["snapshot","story","anchorCaret","resolveCaretAnchor","version","readContent","findText","validateEdits","searchText","isProposalsAvailable","listProposals","layoutSlide","hitTest","mediaBytes","comments","canUndo","canRedo","undoCaptureMode","onUpdate"];function He(t){let e=structuredClone(t),r=new WeakSet;function i(s){if(typeof s=="number"&&!Number.isFinite(s))throw new B("arguments","Editor arguments must be finite");if(s!==null&&typeof s=="object"){if(r.has(s))throw new B("arguments","Editor arguments must be acyclic");r.add(s);for(let n of Object.values(s))i(n);r.delete(s),Object.freeze(s);}}return i(e),e}function xe(t){let{peer:e$1,session:r}=t,i=R.get(r);if(!i)throw new TypeError("Presentation session does not support editor replay");if(i.peerAttached)throw new B("attachment","Presentation peer is already attached");let{client:s}=i,n=0,o=0,l=e$1.version(),u,f=false,d=false,m$1=Promise.resolve(),E$1,U$1=new Promise((g,c)=>{E$1=c;});U$1.catch(()=>{});function k(g){u||f||(u=g instanceof D?g:new D(Y(g)),E$1(u),t.onFailure(u));}function x(){if(t.guard(),f)throw new E;if(s.failure&&k(s.failure),u)throw u}function P(g){let c=m$1.then(async()=>{x();let p=await Promise.race([g(),U$1]);return x(),p}).catch(p=>{throw k(p),u??p});return m$1=c.then(()=>{},()=>{}),Promise.race([c,U$1])}function b(g){if(x(),d)throw new B("reentrant","Presentation editor mutation cannot reenter");d=true;let c=false,p=false;try{let S={sequence:n+1,baseVersion:l,op:He(g)};return p=!0,m(e$1,S,A=>{if(c=!0,!A.consumed)return;n=A.sequence,l=A.version;let N=Object.freeze({...S,expectedOutcome:A.outcome});P(async()=>{let L=await s.call.replay(N);if(!V$1(A,L))throw new B("ack-mismatch","Presentation replay acknowledgement differs");o=L.sequence,t.onProgress(n,o,L.projection);}).catch(()=>{}),t.onProgress(n,o);})}catch(S){throw (c||p&&!(S instanceof e&&["arguments","invalidJson","method"].includes(S.code)))&&k(S),u??S}finally{d=false;}}function y(g){try{x();}catch(S){return Promise.reject(S)}let c=n,p=l;return P(async()=>{let S=await s.call.flush(c,p);if(S.sequence!==c||S.version!==p||o!==c)throw new B("ack-mismatch","Presentation flush acknowledgement differs");return g(c,p)})}let v={};function M(g,c){return (...p)=>(x(),g[c](...p))}Object.defineProperty(v,"clientId",{enumerable:true,get:()=>(x(),e$1.clientId)});for(let g of je)Object.defineProperty(v,g,{enumerable:true,value:M(e$1,g)});let a=Symbol.for("@betteroffice/pptx/slide-layout-cache"),h=e$1[a],w=Object.freeze(Object.fromEntries(["snapshot","key","activate","hitTest"].map(g=>[g,M(h,g)])));Object.defineProperty(v,"interaction",{enumerable:true,value:w}),Object.defineProperty(v,a,{value:w});for(let g of Object.keys(U))Object.defineProperty(v,g,{enumerable:true,value:(...c)=>b({method:g,args:c}).outcome.result});let W=s.onFailure(k),F={access:Object.freeze(v),get sequence(){return n},get acknowledgedSequence(){return o},get version(){return l},apply:b,flush:()=>y(async()=>{}),saveAsync:()=>y(async(g,c)=>new Uint8Array(await s.call.editorSave(g,c))),dispose(){f||(f=true,E$1(new E),W());}};return i.peerAttached=true,_.set(F,{fail:k,whenAcknowledged:()=>{try{x();}catch(g){return Promise.reject(g)}return Promise.race([m$1,U$1])}}),F}function xt(t,e={}){ve(e);let r=O(e.worker?e.worker():new Worker(new URL("./pptxSessionWorker.mjs",import.meta.url),{type:"module"}));return De(t,e,r)}function ve(t){if(t.collaboration!=null)throw new F;if(t.signal?.aborted)throw new E}function Ee(t){return t?.map(e=>({...e,bytes:new Uint8Array(e.bytes).slice()}))}function De(t,e,r){ve(e);let i$1,s$1,n;try{s$1=ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():new Uint8Array(t).slice(),n={fonts:Ee(e.fonts),fallbackFonts:Ee(e.fallbackFonts),initialUpdate:e.initialUpdate?.slice()},i$1=Pe(s$1,{...e,...n},r);}catch(c){try{r.close();}catch{}throw c}let o={stage:"opening",sequence:0,acknowledgedSequence:0},l,u,f,d,m,E$1=new Set,U,k=new Promise((c,p)=>{U=p;});k.catch(()=>{});function x(c){o=Object.freeze({...o,...c});for(let p of [...E$1])if(E$1.has(p))try{p(o);}catch{}}function P(){if(o.stage==="disposed")throw new E;if(o.failure)throw o.failure}function b(){if(P(),o.stage!=="ready"||!f)throw new C;return f}function y(){let c=u;u=void 0,l===c&&(l=void 0);try{c?.dispose();}catch{}}function v(c){if(o.failure||o.stage==="disposed")return;let p=c instanceof D?c:new D(c);y(),x({stage:"failed",failure:p}),U(p),f&&_.get(f)?.fail(p);try{e.onError?.(p);}catch{}i$1.dispose();}function M(){if(!d){if(!l)throw new C;d=new Uint8Array(l.save()).slice();}return o.stage==="disposed"&&l&&(l.dispose(),l=void 0),d.slice()}let{client:a}=R.get(i$1),h$1=i$1.onFailure(v),w=()=>new Promise(c=>setTimeout(c,0)),W=(async()=>{try{let c=await Promise.race([i$1.begin(),k]);if(P(),c.sequence!==0)throw new B("sequence","Editor baseline is not at zero");if(x({stage:"hydrating",projection:c.state,version:c.version}),P(),await s(c.module),await w(),P(),u=g(s$1,c.hydration,n),await w(),P(),await h(u),await w(),P(),i(u),u.version()!==c.version)throw new B("version","Hydrated peer version differs");let p=await Promise.race([a.call.attachPeer(u.version(),0),k]);if(P(),p.sequence!==0||p.version!==u.version())throw new B("attachment","Worker attachment acknowledgement differs");let S=c.state.slides[0]?.id,A=S===void 0?void 0:await Promise.race([i$1.frame(S),k]);if(P(),A&&(A.sequence!==0||A.version!==c.version||A.slideId!==S))throw new B("frame","Initial worker frame differs");l=u,f=xe({peer:l,session:i$1,guard:()=>{b();},onFailure:v,onProgress:(N,L,X)=>{o.stage==="ready"&&x({sequence:N,acknowledgedSequence:L,version:f?.version,...X?{projection:X}:{}});}}),u=void 0,x({stage:"ready",initialFrame:A}),P();}catch(c){let p=Y(c);throw v(p),o.stage==="disposed"?new E:o.failure??p}finally{y();}})();W.catch(()=>{});let F={get state(){return o},get hydrated(){return o.stage==="ready"},get failure(){return o.failure},subscribe(c){if(o.stage==="disposed")throw new E;return E$1.add(c),()=>{E$1.delete(c);}},whenHydrated:async()=>{P(),await Promise.race([W,k]),P();},handleAsync:async()=>(await F.whenHydrated(),b().access),apply:c=>b().apply(c),flush:async()=>b().flush(),saveAsync:async()=>b().saveAsync(),frame:async c=>{if(P(),!o.projection)throw new C;try{let p=await Promise.race([i$1.frame(c),k]);return P(),p}catch(p){throw P(),p instanceof Error&&p.name==="RangeError"||(v(p),P()),p}},recoverySave:async()=>{if(o.stage==="recovering")throw new B("stage","Recovery is already in progress");if(o.stage!=="disposed"&&!o.failure)throw new C;o.stage==="disposed"||x({stage:"recovering"});try{return {bytes:M(),recovery:!0}}finally{o.stage!=="disposed"&&x({stage:"failed"});}},dispose(){if(m)return m;let c,p;m=new Promise((S,A)=>{c=S,p=A;}),x({stage:"disposed"}),y(),U(new E),f?.dispose(),h$1(),e.signal?.removeEventListener("abort",g$1);try{l&&M();}catch{}return E$1.clear(),i$1.dispose().then(c,p),m}},g$1=()=>{F.dispose();};return e.signal?.addEventListener("abort",g$1,{once:true}),e.signal?.aborted&&g$1(),F}export{Ne as a,We as b,Ae as c,Ie as d,Ke as e,Oe as f,ge as g,V as h,nt as i,xt as j};