@betteroffice/docx 0.0.3 → 0.1.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 (73) hide show
  1. package/README.md +22 -8
  2. package/dist/chunk-24DL53QL.mjs +1 -0
  3. package/dist/chunk-5F6DLQZP.mjs +1 -0
  4. package/dist/chunk-BUZ2X5CT.mjs +16 -0
  5. package/dist/chunk-CTBUQRYQ.mjs +1 -0
  6. package/dist/{chunk-B4IR6YP4.mjs → chunk-GHEHBYQK.mjs} +1 -1
  7. package/dist/{chunk-NJHOPXZW.mjs → chunk-HLDJMU3R.mjs} +1 -1
  8. package/dist/chunk-HTDNSQ44.mjs +1 -0
  9. package/dist/{chunk-IFT6DUJX.mjs → chunk-LTVVQMHB.mjs} +1 -1
  10. package/dist/chunk-PI2I3TO5.mjs +57 -0
  11. package/dist/chunk-TMHG7OAZ.mjs +1 -0
  12. package/dist/chunk-VRGUAKOC.mjs +1 -0
  13. package/dist/collaboration/index.d.mts +32 -8
  14. package/dist/collaboration/index.mjs +1 -1
  15. package/dist/{content-MOZ6hKP4.d.mts → content-DrqzbIr7.d.mts} +582 -666
  16. package/dist/core.d.mts +7 -7
  17. package/dist/core.mjs +1 -1
  18. package/dist/{displayListQueries-BJlo7Jkz.d.mts → displayListQueries-DGDR-OWc.d.mts} +98 -50
  19. package/dist/docx/index.d.mts +5 -5
  20. package/dist/docx/index.mjs +1 -1
  21. package/dist/editor/index.d.mts +8 -8
  22. package/dist/{fontLoader-aSewHMKF.d.mts → fontLoader-DnixuYST.d.mts} +127 -2
  23. package/dist/{formatting-D1EPSaJP.d.mts → formatting-BqrFPeev.d.mts} +85 -203
  24. package/dist/{frameDelta-D965X8yK.d.mts → frameDelta-DMgR8n13.d.mts} +17 -10
  25. package/dist/generated/edit/docx_edit_bg.wasm +0 -0
  26. package/dist/generated/layout/docx_layout_bg.wasm +0 -0
  27. package/dist/generated/opc/ooxml_opc_bg.wasm +0 -0
  28. package/dist/generated/parse/docx_parse_bg.wasm +0 -0
  29. package/dist/{index-Dx4Z3lkz.d.mts → index-ImoMd0Ju.d.mts} +97 -67
  30. package/dist/layout/index.d.mts +40 -12
  31. package/dist/layout/index.mjs +1 -1
  32. package/dist/layout/pagination/index.d.mts +4 -4
  33. package/dist/layout/pagination/index.mjs +1 -1
  34. package/dist/layout/render/index.d.mts +33 -77
  35. package/dist/layout/render/index.mjs +1 -1
  36. package/dist/plugin-api/RenderedDomContext.d.mts +7 -7
  37. package/dist/plugin-api/index.d.mts +3 -3
  38. package/dist/plugin-api/resolveItemPositions.d.mts +3 -3
  39. package/dist/{rustDisplayList-BRuZBqdL.d.mts → rustDisplayList-B9dQoLHI.d.mts} +79 -50
  40. package/dist/{rustMeasureSource-D1KsQvVC.d.mts → rustMeasureSource-C0EZB055.d.mts} +5 -2
  41. package/dist/{selectiveSave-CVoajSKE.d.mts → selectiveSave-CRh-_Y_C.d.mts} +3 -3
  42. package/dist/styles/index.d.mts +3 -3
  43. package/dist/{styles-Dn_o3Vo5.d.mts → styles-CMybYYHS.d.mts} +1 -1
  44. package/dist/types/content.d.mts +2 -2
  45. package/dist/types/document.d.mts +7 -7
  46. package/dist/{types-BfqUl2h_.d.mts → types-CXLxVF1t.d.mts} +27 -23
  47. package/dist/utils/comments.d.mts +2 -2
  48. package/dist/utils/index.d.mts +11 -13
  49. package/dist/utils/index.mjs +1 -1
  50. package/dist/utils/stylePreview.d.mts +2 -2
  51. package/dist/utils/units.d.mts +4 -34
  52. package/dist/utils/units.mjs +1 -1
  53. package/dist/wasm-CJHQHBDE.mjs +1 -0
  54. package/dist/wasm-T2CRCO7S.mjs +1 -0
  55. package/dist/wasm-edit.d.mts +524 -168
  56. package/dist/wasm-edit.mjs +1 -1
  57. package/dist/wasm-layout.d.mts +35 -28
  58. package/dist/wasm-layout.mjs +1 -1
  59. package/dist/wasm-opc.mjs +1 -1
  60. package/dist/wasm-parse.mjs +1 -1
  61. package/dist/yrs/index.d.mts +6 -6
  62. package/dist/yrs/index.mjs +1 -1
  63. package/dist/yrs/residentEngineWorker.mjs +1 -1
  64. package/package.json +19 -3
  65. package/dist/chunk-3UBMCDME.mjs +0 -1
  66. package/dist/chunk-AEQOEQJ7.mjs +0 -57
  67. package/dist/chunk-AZ52IWB6.mjs +0 -16
  68. package/dist/chunk-GGEGIQRK.mjs +0 -1
  69. package/dist/chunk-T4EZMUXM.mjs +0 -1
  70. package/dist/chunk-WON6K4FY.mjs +0 -1
  71. package/dist/chunk-Y7RUNRU2.mjs +0 -1
  72. package/dist/wasm-DO3BUV7C.mjs +0 -1
  73. package/dist/wasm-NWXX4H5G.mjs +0 -1
@@ -1,11 +1,11 @@
1
- import { C as CollaborationReplica, b as CollaborationTransport, c as CollaborationProviderOptions, d as CollaborationStatus, e as CollaborationStatusListener, f as CollaborationErrorListener, g as YrsSelection, Y as YrsSession } from '../index-Dx4Z3lkz.mjs';
2
- export { h as CollaborationError, i as CollaborationErrorCode, j as CollaborationStatusChange, k as CollaborationTransportEvent, l as CollaborationUpdateOrigin } from '../index-Dx4Z3lkz.mjs';
3
- import '../frameDelta-D965X8yK.mjs';
4
- import '../content-MOZ6hKP4.mjs';
5
- import '../formatting-D1EPSaJP.mjs';
6
- import '../docx/wrapTypes.mjs';
1
+ import { C as CollaborationReplica, b as CollaborationTransport, c as CollaborationProviderOptions, d as CollaborationStatus, e as CollaborationPeer, f as CollaborationCursor, g as CollaborationPeerListener, h as CollaborationStatusListener, i as CollaborationErrorListener, j as YrsSelection, Y as YrsSession } from '../index-ImoMd0Ju.mjs';
2
+ export { k as CollaborationAwarenessState, l as CollaborationError, m as CollaborationErrorCode, n as CollaborationPresence, o as CollaborationResolvedUser, p as CollaborationStatusChange, q as CollaborationTextInsertion, r as CollaborationTransportEvent, s as CollaborationUpdateOrigin, t as CollaborationUser } from '../index-ImoMd0Ju.mjs';
7
3
  import '../types/document.mjs';
8
- import '../styles-Dn_o3Vo5.mjs';
4
+ import '../content-DrqzbIr7.mjs';
5
+ import '../formatting-BqrFPeev.mjs';
6
+ import '../docx/wrapTypes.mjs';
7
+ import '../styles-CMybYYHS.mjs';
8
+ import '../frameDelta-DMgR8n13.mjs';
9
9
 
10
10
  declare class CollaborationProvider {
11
11
  private readonly replica;
@@ -13,9 +13,12 @@ declare class CollaborationProvider {
13
13
  private readonly maxFrameBytes;
14
14
  private readonly maxMessagesPerFrame;
15
15
  private readonly maxPendingBytes;
16
+ private readonly localUser;
16
17
  private readonly statusListeners;
17
18
  private readonly errorListeners;
19
+ private readonly peerListeners;
18
20
  private readonly pendingFrames;
21
+ private awarenessRecords;
19
22
  private unsubscribeReplica;
20
23
  private unsubscribeTransport;
21
24
  private hasTransportSubscription;
@@ -29,10 +32,20 @@ declare class CollaborationProvider {
29
32
  private nextListenerId;
30
33
  private queuedBytes;
31
34
  private isFlushing;
35
+ private localClock;
36
+ private reportedClockExhaustion;
37
+ private localCursor;
38
+ private lastAwarenessSentAt;
39
+ private cursorBroadcastTimer;
40
+ private heartbeatTimer;
41
+ private expiryTimer;
32
42
  constructor(replica: CollaborationReplica, transport: CollaborationTransport, options?: CollaborationProviderOptions);
33
43
  get status(): CollaborationStatus;
34
44
  get synced(): boolean;
35
45
  get pendingBytes(): number;
46
+ get peers(): readonly CollaborationPeer[];
47
+ setCursor(cursor: CollaborationCursor | null, broadcast?: boolean): void;
48
+ onPeers(listener: CollaborationPeerListener): () => void;
36
49
  connect(): void;
37
50
  disconnect(): void;
38
51
  destroy(): void;
@@ -48,6 +61,15 @@ declare class CollaborationProvider {
48
61
  private respondToSyncStep1;
49
62
  private applyRemoteUpdate;
50
63
  private forwardLocalUpdate;
64
+ private nextAwarenessClock;
65
+ private encodeLocalAwareness;
66
+ private broadcastLocalAwareness;
67
+ private scheduleCursorBroadcast;
68
+ private clearCursorBroadcastTimer;
69
+ private startPresence;
70
+ private stopPresence;
71
+ private sendLeaveBestEffort;
72
+ private emitPeers;
51
73
  private sendFrame;
52
74
  private queueFrame;
53
75
  private flushPending;
@@ -56,10 +78,12 @@ declare class CollaborationProvider {
56
78
  private report;
57
79
  }
58
80
 
81
+ declare function resolvePresenceColor(clientId: number, color: unknown): string;
82
+
59
83
  interface WorkerCollaborationTarget {
60
84
  invalidate(update: Uint8Array, selection: YrsSelection | null): void;
61
85
  }
62
86
  declare function createDirectCollaborationReplica(session: YrsSession): CollaborationReplica;
63
87
  declare function createWorkerCollaborationReplica(session: YrsSession, worker: WorkerCollaborationTarget): CollaborationReplica;
64
88
 
65
- export { CollaborationErrorListener, CollaborationProvider, CollaborationProviderOptions, CollaborationReplica, CollaborationStatus, CollaborationStatusListener, CollaborationTransport, type WorkerCollaborationTarget, createDirectCollaborationReplica, createWorkerCollaborationReplica };
89
+ export { CollaborationCursor, CollaborationErrorListener, CollaborationPeer, CollaborationPeerListener, CollaborationProvider, CollaborationProviderOptions, CollaborationReplica, CollaborationStatus, CollaborationStatusListener, CollaborationTransport, type WorkerCollaborationTarget, createDirectCollaborationReplica, createWorkerCollaborationReplica, resolvePresenceColor };
@@ -1 +1 @@
1
- import {b as b$1}from'../chunk-TTRUPDAB.mjs';var w=Number.MAX_SAFE_INTEGER,c=class extends Error{constructor(t){super(t),this.name="ProtocolError";}},b=class{constructor(t){b$1(this,"bytes",t);b$1(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let t=0,e=1,r=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new c("Truncated varUint");let n=this.bytes[this.offset++],i=n&127;if(i>Math.floor((w-t)/e))throw new c("varUint exceeds Number.MAX_SAFE_INTEGER");if(t+=i*e,r+=1,(n&128)===0){if(r>1&&i===0)throw new c("Non-canonical varUint");return t}if(r>=8)throw new c("varUint exceeds Number.MAX_SAFE_INTEGER");e*=128;}}readVarUint8Array(){let t=this.readVarUint(),e=this.bytes.byteLength-this.offset;if(t>e)throw new c("Truncated varUint8Array");let r=this.bytes.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarString(){let t=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch(e){throw new c(`Invalid UTF-8 string${e instanceof Error?`: ${e.message}`:""}`)}}};function u(o){if(!Number.isSafeInteger(o)||o<0)throw new c("varUint value must be a non-negative safe integer");let t=[],e=o;for(;e>=128;)t.push(e%128|128),e=Math.floor(e/128);return t.push(e),Uint8Array.from(t)}function C(o,t){let e=0;for(let i of o)if(e+=i.byteLength,e>t)throw new c(`Frame exceeds ${t} bytes`);let r=new Uint8Array(e),n=0;for(let i of o)r.set(i,n),n+=i.byteLength;return r}function f(o,t,e){return C([u(0),u(o),u(t.byteLength),t],e)}function A(o,t=16777216){return f(0,o,t)}function g(o,t=16777216){return f(1,o,t)}function U(o,t=16777216){return f(2,o,t)}function v(o=16777216){let t=Uint8Array.of(0);return C([u(1),u(t.byteLength),t],o)}function T(o,t=16777216,e=4096){if(!(o instanceof Uint8Array))throw new c("Frame must be a Uint8Array");if(o.byteLength===0)throw new c("Frame is empty");if(o.byteLength>t)throw new c(`Frame exceeds ${t} bytes`);if(!Number.isSafeInteger(e)||e<1)throw new c("Message limit must be a positive integer");let r=new b(o),n=[];for(;!r.done;){if(n.length>=e)throw new c(`Frame exceeds ${e} messages`);let i=r.readVarUint();switch(i){case 0:{let l=r.readVarUint(),y=r.readVarUint8Array();if(l===0)n.push({type:"sync-step-1",stateVector:y});else if(l===1)n.push({type:"sync-step-2",update:y});else if(l===2)n.push({type:"update",update:y});else throw new c(`Unknown sync message type ${l}`);break}case 1:n.push({type:"awareness",update:r.readVarUint8Array()});break;case 2:{let l=r.readVarUint();if(l!==0)throw new c(`Unknown auth message type ${l}`);n.push({type:"auth",reason:r.readVarString()});break}case 3:n.push({type:"query-awareness"});break;default:throw new c(`Unknown top-level message type ${i}`)}}return n}var p=class extends Error{constructor(e,r,n){super(r);b$1(this,"code");b$1(this,"cause");this.name="CollaborationError",this.code=e,this.cause=n;}};var L=16*1024*1024;function m(o,t,e){if(!Number.isSafeInteger(t)||t<(e?0:1))throw new RangeError(`${o} must be ${e?"a non-negative":"a positive"} integer`);return t}function x(o){return o instanceof Error&&o.message?o.message:typeof o=="string"&&o?o:"Unknown error"}function a(o,t,e){return e instanceof p?e:new p(o,`${t}: ${x(e)}`,e)}function E(o,t){if(!(o instanceof Uint8Array))throw new TypeError(`${t} must return a Uint8Array`);return o.slice()}var S=class{constructor(t,e,r={}){b$1(this,"replica");b$1(this,"transport");b$1(this,"maxFrameBytes");b$1(this,"maxMessagesPerFrame");b$1(this,"maxPendingBytes");b$1(this,"statusListeners",new Map);b$1(this,"errorListeners",new Map);b$1(this,"pendingFrames",[]);b$1(this,"unsubscribeReplica");b$1(this,"unsubscribeTransport",()=>{});b$1(this,"hasTransportSubscription",false);b$1(this,"connectionStatus","disconnected");b$1(this,"isSynced",false);b$1(this,"wantsConnection",false);b$1(this,"isOpen",false);b$1(this,"isDestroyed",false);b$1(this,"epoch",0);b$1(this,"connectAttempt",0);b$1(this,"nextListenerId",0);b$1(this,"queuedBytes",0);b$1(this,"isFlushing",false);this.replica=t,this.transport=e,this.maxFrameBytes=m("maxFrameBytes",r.maxFrameBytes??16777216,false),this.maxMessagesPerFrame=m("maxMessagesPerFrame",r.maxMessagesPerFrame??4096,false),this.maxPendingBytes=m("maxPendingBytes",r.maxPendingBytes??L,true);try{this.unsubscribeReplica=t.onUpdate((n,i)=>{i==="local"&&this.forwardLocalUpdate(n);});}catch(n){throw a("replica","Failed to observe replica updates",n)}}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}connect(){if(this.isDestroyed||this.isOpen||this.connectionStatus==="connecting")return;this.wantsConnection=true;let t=this.hasTransportSubscription?this.epoch:++this.epoch,e=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(t)){if(!this.hasTransportSubscription){let r;try{if(r=this.transport.onEvent(n=>this.handleTransportEvent(t,n)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(n){this.failConnection(t,a("transport","Failed to subscribe to transport events",n));return}if(!this.isCurrent(t)){try{r();}catch(n){this.isDestroyed||this.report(a("transport","Failed to unsubscribe from stale transport events",n));}return}this.unsubscribeTransport=r,this.hasTransportSubscription=true;}try{let r=this.transport.connect();r&&r.catch(n=>{this.isCurrent(t)&&this.connectAttempt===e&&this.failConnection(t,a("transport","Transport connect failed",n));});}catch(r){this.failConnection(t,a("transport","Transport connect failed",r));}}}disconnect(){if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let e=this.takeTransportSubscription();this.clearPending();let r=this.cleanupTransport(e,true);this.setStatus("disconnected",false);for(let n of r)this.report(n);}destroy(){if(this.isDestroyed)return;let t=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let e=this.takeTransportSubscription();this.clearPending();let r=this.cleanupTransport(e,t);this.setStatus("destroyed",false);for(let n of r)this.report(n);try{this.unsubscribeReplica();}catch(n){this.report(a("replica","Failed to unsubscribe from replica updates",n));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear();}onStatus(t){if(this.isDestroyed)return ()=>{};if(typeof t!="function")throw new TypeError("status listener must be a function");let e=this.nextListenerId++;return this.statusListeners.set(e,t),()=>this.statusListeners.delete(e)}onError(t){if(this.isDestroyed)return ()=>{};if(typeof t!="function")throw new TypeError("error listener must be a function");let e=this.nextListenerId++;return this.errorListeners.set(e,t),()=>this.errorListeners.delete(e)}isCurrent(t){return !this.isDestroyed&&this.wantsConnection&&t===this.epoch}failConnection(t,e){if(!this.isCurrent(t))return;this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let r=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(r,true);this.setStatus("disconnected",false),this.report(e);for(let i of n)this.report(i);}takeTransportSubscription(){let t=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,t}cleanupTransport(t,e){let r=[];try{t();}catch(n){r.push(a("transport","Failed to unsubscribe from transport events",n));}if(!e)return r;try{let n=this.transport.disconnect();n&&n.catch(i=>{this.isDestroyed||this.report(a("transport","Transport disconnect failed",i));});}catch(n){r.push(a("transport","Transport disconnect failed",n));}return r}handleTransportEvent(t,e){if(this.isCurrent(t))switch(e.type){case "open":this.handleOpen(t);break;case "message":this.isOpen&&this.handleMessage(t,e.data);break;case "close":this.isOpen=false,this.connectAttempt+=1,this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(t,a("transport","Transport error",e.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(t,new p("transport","Unknown transport event"));}}handleOpen(t){if(this.isOpen||(this.isOpen=true,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(t)||!this.isOpen))return;let e;try{e=E(this.replica.encodeStateVector(),"encodeStateVector");}catch(r){this.failConnection(t,a("replica","Failed to encode replica state vector",r));return}try{this.sendFrame(A(e,this.maxFrameBytes));}catch(r){this.failConnection(t,a("protocol","Failed to encode SyncStep1",r));}}handleMessage(t,e){let r;try{r=T(e.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);}catch(n){this.failConnection(t,a("protocol","Invalid collaboration frame",n));return}for(let n of r){if(!this.isCurrent(t)||!this.isOpen)return;switch(n.type){case "sync-step-1":this.respondToSyncStep1(t,n.stateVector);break;case "sync-step-2":this.applyRemoteUpdate(t,n.update)&&this.isCurrent(t)&&this.setStatus("connected",true);break;case "update":this.applyRemoteUpdate(t,n.update);break;case "awareness":break;case "auth":this.failConnection(t,new p("protocol",n.reason?`Authentication denied: ${n.reason}`:"Authentication denied"));return;case "query-awareness":try{this.sendFrame(v(this.maxFrameBytes));}catch(i){this.failConnection(t,a("protocol","Failed to encode awareness response",i));return}break}}}respondToSyncStep1(t,e){let r;try{r=E(this.replica.encodeStateAsUpdate(e.slice()),"encodeStateAsUpdate");}catch(n){this.failConnection(t,a("replica","Failed to encode replica update",n));return}try{this.sendFrame(g(r,this.maxFrameBytes));}catch(n){this.failConnection(t,a("protocol","Failed to encode SyncStep2",n));}}applyRemoteUpdate(t,e){try{return this.replica.applyUpdate(e.slice()),!0}catch(r){return this.failConnection(t,a("replica","Failed to apply remote update",r)),false}}forwardLocalUpdate(t){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let e=this.epoch,r;try{r=E(t,"Replica update");}catch(n){this.failConnection(e,a("replica","Invalid replica update",n));return}try{this.sendFrame(U(r,this.maxFrameBytes));}catch(n){this.failConnection(e,a("protocol","Failed to encode update",n));}}sendFrame(t){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let e=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(e,t);return}let r;try{r=this.transport.send(t.slice());}catch(n){this.failConnection(e,a("transport","Transport send failed",n));return}if(typeof r!="boolean"){this.failConnection(e,new p("transport","Transport send must return a boolean"));return}!r&&this.isCurrent(e)&&this.isOpen&&this.queueFrame(e,t);}queueFrame(t,e){if(e.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(t,new p("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let r=e.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 t=this.epoch,e=this.pendingFrames[0],r;try{r=this.transport.send(e.slice());}catch(n){this.failConnection(t,a("transport","Transport send failed",n));return}if(typeof r!="boolean"){this.failConnection(t,new p("transport","Transport send must return a boolean"));return}if(!r||!this.isOpen||this.pendingFrames[0]!==e)return;this.pendingFrames.shift(),this.queuedBytes-=e.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(t,e){if(this.connectionStatus===t&&this.isSynced===e)return;this.connectionStatus=t,this.isSynced=e;let r={status:t,synced:e};for(let[n,i]of [...this.statusListeners])if(this.statusListeners.get(n)===i)try{i(r);}catch{}}report(t){for(let[e,r]of [...this.errorListeners])if(this.errorListeners.get(e)===r)try{r(t);}catch{}}};function P(o){return o}function M(o,t){return {clientId:o.clientId,encodeStateVector:()=>o.encodeStateVector(),encodeStateAsUpdate:e=>o.encodeStateAsUpdate(e?.slice()),applyUpdate:e=>{let r=e.slice();o.applyUpdate(r),t.invalidate(r,o.selection());},onUpdate:e=>o.onUpdate(e)}}export{p as CollaborationError,S as CollaborationProvider,P as createDirectCollaborationReplica,M as createWorkerCollaborationReplica};
1
+ import {b as b$1}from'../chunk-TTRUPDAB.mjs';var B=["#0B57D0","#B3261E","#137333","#7B1FA2","#A142F4","#A04B00","#006A6A","#455A64"],oe=/^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/;function S(r,e){if(typeof e=="string"&&oe.test(e))return e;let t=Number.isSafeInteger(r)&&r>=0?r%B.length:0;return B[t]}function D(r,e){return r.byteLength===e.byteLength&&r.every((t,n)=>t===e[n])}function ae(r,e){return r===e||!!(r&&e&&r.story===e.story&&D(r.anchor,e.anchor)&&D(r.head,e.head))}function ie(r,e){return r?.clientId===e.clientId&&r.story===e.story&&r.paraId===e.paraId&&r.endOffset===e.endOffset}function V(r){return r?{story:r.story,anchor:r.anchor.slice(),head:r.head.slice()}:null}function ce(r){return r?{user:{...r.user},cursor:V(r.cursor)}:null}function X(r,e,t,n){let s=r,o=false;for(let a of e){if(a.clientId===t)continue;let u=s.get(a.clientId);if(!u&&s.size>=1024)continue;if(u&&a.clock<=u.clock){a.clock===u.clock&&n>u.lastSeenAt&&(s===r&&(s=new Map(r)),s.set(a.clientId,{...u,lastSeenAt:n}));continue}s===r&&(s=new Map(r));let h=a.state?.cursor!=null&&(u?.inferredCursor!=null||u?.state==null||!ae(u.state.cursor,a.state.cursor));s.set(a.clientId,{clientId:a.clientId,clock:a.clock,state:ce(a.state),lastSeenAt:n,cursorMovedAt:h?n:u?.cursorMovedAt??0,inferredCursor:null}),o=true;}return {records:s,peersChanged:o}}function $(r,e,t,n){if(e.clientId===t)return {records:r,peersChanged:false};let s=r.get(e.clientId);if(!s&&r.size>=1024)return {records:r,peersChanged:false};let o=new Map(r);return o.set(e.clientId,{clientId:e.clientId,clock:s?.clock??-1,state:s?.state??null,lastSeenAt:s?.lastSeenAt??n,cursorMovedAt:ie(s?.inferredCursor??null,e)?s?.cursorMovedAt??n:n,inferredCursor:{...e}}),{records:o,peersChanged:s?.state!=null}}function Y(r,e,t){let n=r,s=false;for(let[o,a]of r)e-a.lastSeenAt<t||(n===r&&(n=new Map(r)),n.delete(o),a.state&&(s=true));return {records:n,peersChanged:s}}function I(r){let e=[];for(let t of r.values()){if(!t.state)continue;let n={clientId:t.clientId,clock:t.clock,user:{...t.state.user},cursor:V(t.state.cursor)};e.push({...n,lastSeenAt:t.lastSeenAt,cursorMovedAt:t.cursorMovedAt,inferredCursor:t.inferredCursor?{...t.inferredCursor}:null});}return e.sort((t,n)=>t.clientId-n.clientId),e}var b=16777216,_=4096,q=0,j=1,ue=2,H=3,z=0,K=1,J=2,de=0,pe=Number.MAX_SAFE_INTEGER,c=class extends Error{constructor(e){super(e),this.name="ProtocolError";}},f=class extends c{},U=class{constructor(e){b$1(this,"bytes",e);b$1(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let e=0,t=1,n=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new c("Truncated varUint");let s=this.bytes[this.offset++],o=s&127;if(o>Math.floor((pe-e)/t))throw new c("varUint exceeds Number.MAX_SAFE_INTEGER");if(e+=o*t,n+=1,(s&128)===0){if(n>1&&o===0)throw new c("Non-canonical varUint");return e}if(n>=8)throw new c("varUint exceeds Number.MAX_SAFE_INTEGER");t*=128;}}readVarUint8Array(){let e=this.readVarUint(),t=this.bytes.byteLength-this.offset;if(e>t)throw new c("Truncated varUint8Array");let n=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,n}skipVarUint8Array(){let e=this.readVarUint(),t=this.bytes.byteLength-this.offset;if(e>t)throw new c("Truncated varUint8Array");this.offset+=e;}readVarString(){let e=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(t){throw new c(`Invalid UTF-8 string${t instanceof Error?`: ${t.message}`:""}`)}}};function p(r){if(!Number.isSafeInteger(r)||r<0)throw new c("varUint value must be a non-negative safe integer");let e=[],t=r;for(;t>=128;)e.push(t%128|128),t=Math.floor(t/128);return e.push(t),Uint8Array.from(e)}function g(r,e){let t=0;for(let o of r)if(t+=o.byteLength,t>e)throw new c(`Frame exceeds ${e} bytes`);let n=new Uint8Array(t),s=0;for(let o of r)n.set(o,s),s+=o.byteLength;return n}function he(r){let e=new TextEncoder().encode(r);return g([p(e.byteLength),e],Number.MAX_SAFE_INTEGER)}function P(r,e,t){return g([p(q),p(r),p(e.byteLength),e],t)}function Q(r,e=b){return P(z,r,e)}function Z(r,e=b){return P(K,r,e)}function ee(r,e=b){return P(J,r,e)}function ye(r){return r.state===null?"null":JSON.stringify({user:r.state.user,cursor:r.state.cursor?{story:r.state.cursor.story,anchor:[...r.state.cursor.anchor],head:[...r.state.cursor.head]}:null})}function fe(r){let e=[p(r.length)];for(let t of r)e.push(p(t.clientId),p(t.clock),he(ye(t)));return g(e,Number.MAX_SAFE_INTEGER)}function R(r,e=b){let t=fe(r);return g([p(j),p(t.byteLength),t],e)}function L(r=b){return g([p(H)],r)}function G(r,e){if(!Array.isArray(r))throw new c(`${e} must be a byte array`);if(r.length>1024)throw new f(`${e} exceeds ${1024} bytes`);if(r.some(t=>!Number.isInteger(t)||t<0||t>255))throw new c(`${e} must be a byte array`);return Uint8Array.from(r)}function be(r,e){let t;try{t=JSON.parse(r);}catch{throw new c("Invalid awareness JSON")}if(t===null)return null;if(typeof t!="object"||Array.isArray(t))throw new c("Awareness state must be an object or null");let n=t,s=n.user;if(typeof s!="object"||s===null||Array.isArray(s))throw new c("Awareness user must be an object");let o=s;if(typeof o.name!="string")throw new c("Awareness user requires a string name");if(o.name.length>1024)throw new f(`Awareness user name exceeds ${1024} characters`);let a={name:o.name,color:S(e,o.color)},u=n.cursor;if(u==null)return {user:a,cursor:null};if(typeof u!="object"||Array.isArray(u))throw new c("Awareness cursor must be an object or null");let h=u;if(typeof h.story!="string")throw new c("Awareness cursor requires a string story");if(h.story.length>1024)throw new f(`Awareness cursor story exceeds ${1024} characters`);return {user:a,cursor:{story:h.story,anchor:G(h.anchor,"Awareness cursor anchor"),head:G(h.head,"Awareness cursor head")}}}function te(r,e={}){let t=new U(r),n=t.readVarUint();if(n>r.byteLength)throw new c("Invalid awareness entry count");let s=new Set(e.trackedClientIds);e.localClientId!==void 0&&s.delete(e.localClientId);let o=new Set,a=m=>{o.has(m.message)||(o.add(m.message),e.onDiscard?.(m));};n>1024&&a(new f(`Awareness update exceeds ${1024} entries`));let u=[],h=Math.min(n,1024);for(let m=0;m<h;m+=1){let A=t.readVarUint(),ne=t.readVarUint();if(!(A===e.localClientId||s.has(A))&&s.size>=1024){t.skipVarUint8Array(),a(new f(`Awareness peer limit of ${1024} reached`));continue}let se=t.readVarString(),O;try{O=be(se,A);}catch(x){if(!(x instanceof f))throw x;a(x);continue}u.push({clientId:A,clock:ne,state:O}),A!==e.localClientId&&s.add(A);}if(n<=1024&&!t.done)throw new c("Trailing awareness data");return u}function re(r,e=b,t=_){if(!(r instanceof Uint8Array))throw new c("Frame must be a Uint8Array");if(r.byteLength===0)throw new c("Frame is empty");if(r.byteLength>e)throw new c(`Frame exceeds ${e} bytes`);if(!Number.isSafeInteger(t)||t<1)throw new c("Message limit must be a positive integer");let n=new U(r),s=[];for(;!n.done;){if(s.length>=t)throw new c(`Frame exceeds ${t} messages`);let o=n.readVarUint();switch(o){case q:{let a=n.readVarUint(),u=n.readVarUint8Array();if(a===z)s.push({type:"sync-step-1",stateVector:u});else if(a===K)s.push({type:"sync-step-2",update:u});else if(a===J)s.push({type:"update",update:u});else throw new c(`Unknown sync message type ${a}`);break}case j:s.push({type:"awareness",update:n.readVarUint8Array()});break;case ue:{let a=n.readVarUint();if(a!==de)throw new c(`Unknown auth message type ${a}`);s.push({type:"auth",reason:n.readVarString()});break}case H:s.push({type:"query-awareness"});break;default:throw new c(`Unknown top-level message type ${o}`)}}return s}var d=class extends Error{constructor(t,n,s){super(n);b$1(this,"code");b$1(this,"cause");this.name="CollaborationError",this.code=t,this.cause=s;}};var me=16*1024*1024,Ae=80,Ce=2e4,we=45e3,Ee=5e3;function F(r,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${r} must be ${t?"a non-negative":"a positive"} integer`);return e}function Se(r){return r instanceof Error&&r.message?r.message:typeof r=="string"&&r?r:"Unknown error"}function l(r,e,t){return t instanceof d?t:new d(r,`${e}: ${Se(t)}`,t)}function M(r,e){if(!(r instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return r.slice()}function v(){return globalThis.performance?.now?.()??Date.now()}function k(r){r.unref?.();}function ge(r,e){if(!r)return null;if(!Number.isSafeInteger(e)||e<0)throw new RangeError("clientId must be a non-negative safe integer for awareness");if(typeof r.name!="string"||r.name.trim().length===0)throw new TypeError("user.name must be a non-empty string");return {name:r.name.trim().slice(0,1024),color:S(e,r.color)}}function ve(r){if(r===null)return null;if(typeof r.story!="string"||!r.story||!(r.anchor instanceof Uint8Array)||!(r.head instanceof Uint8Array))throw new TypeError("cursor requires a story and Uint8Array anchor/head");return {story:r.story,anchor:r.anchor.slice(),head:r.head.slice()}}function Te(r){return r.story.length<=1024&&r.anchor.byteLength<=1024&&r.head.byteLength<=1024}function Ue(r){if(typeof r!="object"||r===null)return null;let e=r;return !Number.isSafeInteger(e.clientId)||(e.clientId??-1)<0||typeof e.story!="string"||typeof e.paraId!="string"||!Number.isSafeInteger(e.endOffset)||(e.endOffset??-1)<0?null:{clientId:e.clientId,story:e.story,paraId:e.paraId,endOffset:e.endOffset}}var N=class{constructor(e,t,n={}){b$1(this,"replica");b$1(this,"transport");b$1(this,"maxFrameBytes");b$1(this,"maxMessagesPerFrame");b$1(this,"maxPendingBytes");b$1(this,"localUser");b$1(this,"statusListeners",new Map);b$1(this,"errorListeners",new Map);b$1(this,"peerListeners",new Map);b$1(this,"pendingFrames",[]);b$1(this,"awarenessRecords",new Map);b$1(this,"unsubscribeReplica");b$1(this,"unsubscribeTransport",()=>{});b$1(this,"hasTransportSubscription",false);b$1(this,"connectionStatus","disconnected");b$1(this,"isSynced",false);b$1(this,"wantsConnection",false);b$1(this,"isOpen",false);b$1(this,"isDestroyed",false);b$1(this,"epoch",0);b$1(this,"connectAttempt",0);b$1(this,"nextListenerId",0);b$1(this,"queuedBytes",0);b$1(this,"isFlushing",false);b$1(this,"localClock",0);b$1(this,"reportedClockExhaustion",false);b$1(this,"localCursor",null);b$1(this,"lastAwarenessSentAt",Number.NEGATIVE_INFINITY);b$1(this,"cursorBroadcastTimer",null);b$1(this,"heartbeatTimer",null);b$1(this,"expiryTimer",null);this.replica=e,this.transport=t,this.maxFrameBytes=F("maxFrameBytes",n.maxFrameBytes??b,false),this.maxMessagesPerFrame=F("maxMessagesPerFrame",n.maxMessagesPerFrame??_,false),this.maxPendingBytes=F("maxPendingBytes",n.maxPendingBytes??me,true),this.localUser=ge(n.user,e.clientId);try{this.unsubscribeReplica=e.onUpdate((s,o)=>{o==="local"&&this.forwardLocalUpdate(s);});}catch(s){throw l("replica","Failed to observe replica updates",s)}}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return I(this.awarenessRecords)}setCursor(e,t=true){if(this.isDestroyed||!this.localUser)return;let n=ve(e);if(this.localCursor=!n||Te(n)?n:null,n&&!this.localCursor&&this.report(new d("protocol",`Presence cursor exceeds ${1024} story characters or ${1024} position bytes; cursor dropped`)),!t){this.clearCursorBroadcastTimer();return}this.scheduleCursorBroadcast();}onPeers(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("peer listener must be a function");let t=this.nextListenerId++;return this.peerListeners.set(t,e),e(this.peers),()=>this.peerListeners.delete(t)}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 n;try{if(n=this.transport.onEvent(s=>this.handleTransportEvent(e,s)),typeof n!="function")throw new TypeError("Transport event subscription must return a function")}catch(s){this.failConnection(e,l("transport","Failed to subscribe to transport events",s));return}if(!this.isCurrent(e)){try{n();}catch(s){this.isDestroyed||this.report(l("transport","Failed to unsubscribe from stale transport events",s));}return}this.unsubscribeTransport=n,this.hasTransportSubscription=true;}try{let n=this.transport.connect();n&&n.catch(s=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,l("transport","Transport connect failed",s));});}catch(n){this.failConnection(e,l("transport","Transport connect failed",n));}}}disconnect(){if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.sendLeaveBestEffort(),this.stopPresence(),this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let s of n)this.report(s);}destroy(){if(this.isDestroyed)return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.sendLeaveBestEffort(),this.stopPresence(),this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let s of n)this.report(s);try{this.unsubscribeReplica();}catch(s){this.report(l("replica","Failed to unsubscribe from replica updates",s));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.peerListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");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.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.stopPresence(),this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let n=this.takeTransportSubscription();this.clearPending();let s=this.cleanupTransport(n,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 n=[];try{e();}catch(s){n.push(l("transport","Failed to unsubscribe from transport events",s));}if(!t)return n;try{let s=this.transport.disconnect();s&&s.catch(o=>{this.isDestroyed||this.report(l("transport","Transport disconnect failed",o));});}catch(s){n.push(l("transport","Transport disconnect failed",s));}return n}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.isOpen=false,this.connectAttempt+=1,this.stopPresence(),this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,l("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new d("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen||(this.isOpen=true,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen))return;let t;try{t=M(this.replica.encodeStateVector(),"encodeStateVector");}catch(n){this.failConnection(e,l("replica","Failed to encode replica state vector",n));return}try{this.sendFrame(Q(t,this.maxFrameBytes));}catch(n){this.failConnection(e,l("protocol","Failed to encode collaboration handshake",n));return}if(!(!this.localUser||!this.isCurrent(e)||!this.isOpen)){try{this.sendFrame(L(this.maxFrameBytes));}catch(n){this.report(l("protocol","Failed to encode awareness query",n));}!this.isCurrent(e)||!this.isOpen||(this.broadcastLocalAwareness(),!(!this.isCurrent(e)||!this.isOpen)&&this.startPresence());}}handleMessage(e,t){let n;try{n=re(t.slice(),this.maxFrameBytes,this.maxMessagesPerFrame);}catch(s){this.failConnection(e,l("protocol","Invalid collaboration frame",s));return}for(let s of n){if(!this.isCurrent(e)||!this.isOpen)return;switch(s.type){case "sync-step-1":this.respondToSyncStep1(e,s.stateVector);break;case "sync-step-2":if(this.applyRemoteUpdate(e,s.update,false)&&this.isCurrent(e)&&(this.setStatus("connected",true),this.localUser))try{this.sendFrame(L(this.maxFrameBytes));}catch(o){this.report(l("protocol","Failed to query awareness after sync",o));}break;case "update":this.applyRemoteUpdate(e,s.update,true);break;case "awareness":{let o=[];try{let a=X(this.awarenessRecords,te(s.update,{trackedClientIds:this.awarenessRecords.keys(),localClientId:this.replica.clientId,onDiscard:u=>o.push(u)}),this.replica.clientId,v());this.awarenessRecords=a.records,a.peersChanged&&this.emitPeers();}catch(a){this.report(l("protocol","Failed to apply awareness update",a));}for(let a of o)this.report(l("protocol","Discarded over-limit awareness data",a));break}case "auth":this.failConnection(e,new d("protocol",s.reason?`Authentication denied: ${s.reason}`:"Authentication denied"));return;case "query-awareness":try{this.localUser?this.broadcastLocalAwareness():this.sendFrame(R([],this.maxFrameBytes));}catch(o){this.report(l("protocol","Failed to encode awareness response",o));}break}}}respondToSyncStep1(e,t){let n;try{n=M(this.replica.encodeStateAsUpdate(t.slice()),"encodeStateAsUpdate");}catch(s){this.failConnection(e,l("replica","Failed to encode replica update",s));return}try{this.sendFrame(Z(n,this.maxFrameBytes));}catch(s){this.failConnection(e,l("protocol","Failed to encode SyncStep2",s));}}applyRemoteUpdate(e,t,n){try{let s=this.replica.applyUpdate(t.slice()),o=n?Ue(s):null;if(o){let a=$(this.awarenessRecords,o,this.replica.clientId,v());this.awarenessRecords=a.records,a.peersChanged&&this.emitPeers();}return !0}catch(s){return this.failConnection(e,l("replica","Failed to apply remote update",s)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,n;try{n=M(e,"Replica update");}catch(s){this.failConnection(t,l("replica","Invalid replica update",s));return}try{this.sendFrame(ee(n,this.maxFrameBytes));}catch(s){this.failConnection(t,l("protocol","Failed to encode update",s));}}nextAwarenessClock(){if(this.localClock>=Number.MAX_SAFE_INTEGER)throw new RangeError("Awareness clock exceeds Number.MAX_SAFE_INTEGER");return this.localClock+=1,this.localClock}encodeLocalAwareness(e,t,n){return R([{clientId:this.replica.clientId,clock:t,state:{user:e,cursor:n}}],this.maxFrameBytes)}broadcastLocalAwareness(){if(!this.localUser||!this.isOpen||this.isDestroyed||!this.wantsConnection)return;if(this.clearCursorBroadcastTimer(),this.localClock>=Number.MAX_SAFE_INTEGER){this.reportedClockExhaustion||(this.reportedClockExhaustion=true,this.report(new d("protocol","Awareness clock exceeds Number.MAX_SAFE_INTEGER")));return}let e=this.localUser,t=this.nextAwarenessClock(),n;try{n=this.encodeLocalAwareness(e,t,this.localCursor);}catch(s){let o=this.localCursor;if(this.localCursor=null,!o){this.report(l("protocol","Failed to encode local awareness",s));return}try{n=this.encodeLocalAwareness(e,t,null);}catch(a){this.report(l("protocol","Failed to encode local awareness",a));return}this.report(l("protocol","Dropped an unencodable presence cursor",s));}this.sendFrame(n),this.lastAwarenessSentAt=v();}scheduleCursorBroadcast(){if(!this.localUser||!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let e=Ae-(v()-this.lastAwarenessSentAt);if(e<=0){this.broadcastLocalAwareness();return}this.cursorBroadcastTimer||(this.cursorBroadcastTimer=setTimeout(()=>{this.cursorBroadcastTimer=null,!(!this.isOpen||this.isDestroyed||!this.wantsConnection)&&this.broadcastLocalAwareness();},e),k(this.cursorBroadcastTimer));}clearCursorBroadcastTimer(){this.cursorBroadcastTimer&&clearTimeout(this.cursorBroadcastTimer),this.cursorBroadcastTimer=null;}startPresence(){!this.localUser||!this.isOpen||this.isDestroyed||!this.wantsConnection||this.heartbeatTimer||this.expiryTimer||(this.heartbeatTimer=setInterval(()=>{this.broadcastLocalAwareness();},Ce),this.expiryTimer=setInterval(()=>{let e=Y(this.awarenessRecords,v(),we);this.awarenessRecords=e.records,e.peersChanged&&this.emitPeers();},Ee),k(this.heartbeatTimer),k(this.expiryTimer));}stopPresence(){this.clearCursorBroadcastTimer(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.expiryTimer&&clearInterval(this.expiryTimer),this.heartbeatTimer=null,this.expiryTimer=null;let e=I(this.awarenessRecords).length>0;this.awarenessRecords=new Map,e&&this.emitPeers();}sendLeaveBestEffort(){if(!(!this.localUser||!this.isOpen||this.isDestroyed||!this.wantsConnection)){this.clearCursorBroadcastTimer();try{let e=R([{clientId:this.replica.clientId,clock:this.nextAwarenessClock(),state:null}],this.maxFrameBytes);this.transport.send(e.slice());}catch(e){this.report(l("transport","Failed to send awareness leave",e));}}}emitPeers(){let e=this.peers;for(let[t,n]of [...this.peerListeners])if(this.peerListeners.get(t)===n)try{n(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 n;try{n=this.transport.send(e.slice());}catch(s){this.failConnection(t,l("transport","Transport send failed",s));return}if(typeof n!="boolean"){this.failConnection(t,new d("transport","Transport send must return a boolean"));return}!n&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new d("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let n=t.slice();this.pendingFrames.push(n),this.queuedBytes+=n.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],n;try{n=this.transport.send(t.slice());}catch(s){this.failConnection(e,l("transport","Transport send failed",s));return}if(typeof n!="boolean"){this.failConnection(e,new d("transport","Transport send must return a boolean"));return}if(!n||!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 n={status:e,synced:t};for(let[s,o]of [...this.statusListeners])if(this.statusListeners.get(s)===o)try{o(n);}catch{}}report(e){for(let[t,n]of [...this.errorListeners])if(this.errorListeners.get(t)===n)try{n(e);}catch{}}};function Re(r){return r}function xe(r,e){return {clientId:r.clientId,encodeStateVector:()=>r.encodeStateVector(),encodeStateAsUpdate:t=>r.encodeStateAsUpdate(t?.slice()),applyUpdate:t=>{let n=t.slice();r.applyUpdate(n),e.invalidate(n,r.selection());},onUpdate:t=>r.onUpdate(t)}}export{d as CollaborationError,N as CollaborationProvider,Re as createDirectCollaborationReplica,xe as createWorkerCollaborationReplica,S as resolvePresenceColor};