@grapecity-software/js-collaboration-ot 18.0.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.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # SpreadJS Collaboration Plugin
2
+
3
+ js collaboration ot 是 [SpreadJS](https://www.grapecity.com.cn/developer/spreadjs) 的插件之一
4
+
5
+ 它通过增加 协同 支持,扩展了 SpreadJS 的功能。
6
+
7
+ 有关 SpreadJS 模块和插件的详细列表,请参见 [SpreadJS 组件库](https://demo.grapecity.com.cn/spreadjs/help/docs/getstarted/modules)
8
+
9
+ ## 安装模块/插件
10
+ ```sh
11
+ npm install @grapecity-software/js-collaboration-ot
12
+ ```
13
+
14
+ ## 获取更多帮助
15
+ 想需要获取更多产品信息,请浏览 [SpreadJS 主页](https://www.grapecity.com.cn/developer/spreadjs)
16
+
17
+ 您可以在论坛中提出任何您使用产品过程中遇到的问题: [技术支持论坛](https://gcdn.grapecity.com.cn/showforum-232-1.html)
@@ -0,0 +1,468 @@
1
+ import { IMiddleware, IHook, Connection, IFeature } from "@grapecity-software/js-collaboration";
2
+
3
+ /**
4
+ * The interface of ot type, user can customize the ot behavior of the collaboration.
5
+ * @template S The type of snapshot data.
6
+ * @template T The type of op data.
7
+ */
8
+ export interface OT_Type<S = unknown, T = unknown> {
9
+ /**
10
+ * The type uri of the document.
11
+ */
12
+ uri: string;
13
+ /**
14
+ * Create a snapshot data from op data.
15
+ * @param data - snapshot data
16
+ * @returns snapshot data
17
+ */
18
+ create?(data: S): S;
19
+ /**
20
+ * Create snapshot fragments from op data.
21
+ * @param data - snapshot data
22
+ * @returns snapshot fragments
23
+ */
24
+ createFragments?(data: S): ISnapshotFragments;
25
+ /**
26
+ * Create snapshot data from snapshot fragments.
27
+ * @param fragments - snapshot fragments
28
+ * @returns snapshot data
29
+ */
30
+ composeFragments?(fragments: ISnapshotFragments): S;
31
+ /**
32
+ * Transform op1, to handling conflicts.
33
+ * @param op1 The op to be transformed.
34
+ * @param op2 The basis of the operation being transformed (op1 is transformed based on op2).
35
+ * @param side Indicates which parameter's corresponding op arrives at the server later.
36
+ * @returns The transformed op1.
37
+ */
38
+ transform(op1: T, op2: T, side: 'left' | 'right'): T;
39
+ /**
40
+ * Apply op to snapshot data.
41
+ * @param snapshot - snapshot data
42
+ * @param op - op data
43
+ * @returns snapshot data
44
+ */
45
+ apply?(snapshot: S, op: T): S;
46
+ /**
47
+ * Apply op to snapshot fragments.
48
+ * @param request - snapshot fragments request
49
+ * @param op - op data
50
+ * @returns snapshot data
51
+ */
52
+ applyFragments?(request: ISnapshotFragmentsRequest, op: T): S;
53
+ }
54
+
55
+ /**
56
+ * The types manager for collaboration, provide a way to register ot type and get types through type uri.
57
+ */
58
+ export class TypesManager {
59
+ /**
60
+ * Register ot type.
61
+ * @param {OT_Type} type The type object which is user-defined.
62
+ */
63
+ static register<S, T> (type: OT_Type<S, T>): void;
64
+ /**
65
+ * Get ot type through the type uri.
66
+ * @param {string} typeUri The type uri.
67
+ * @return {OT_Type} The type object of specified type uri.
68
+ */
69
+ static getType<S, T> (typeUri: string): OT_Type<S, T>;
70
+ }
71
+
72
+ /**
73
+ * The feature of ot document.
74
+ * @param service - service to be used by document services
75
+ * @returns The ot document feature.
76
+ * @example
77
+ * const server = new Server({ httpServer });
78
+ * server.useFeature(documentFeature());
79
+ */
80
+ export declare function documentFeature<S = unknown, T = unknown>(service?: DocumentServices<S, T>): IFeature;
81
+
82
+ /**
83
+ * The document services for collaboration.
84
+ * @template S The type of snapshot data.
85
+ * @template T The type of op data.
86
+ */
87
+ export declare class DocumentServices<S, T> {
88
+ /**
89
+ * The database adapter.
90
+ * @template S The type of snapshot data.
91
+ * @template T The type of op data.
92
+ */
93
+ db: IDataBaseAdapter<S, T>;
94
+ /**
95
+ * The milestone database adapter.
96
+ * @template S The type of snapshot data.
97
+ */
98
+ milestoneDb: IMilestoneDataBaseAdapter<S>;
99
+ /**
100
+ * The maximum number of retries when submitting an operation.
101
+ * @default undefined - no limitation
102
+ */
103
+ maxSubmitRetries?: number;
104
+ /**
105
+ * The batch size of snapshot when submit snapshot.
106
+ * @default 100
107
+ */
108
+ submitSnapshotBatchSize: number;
109
+
110
+ constructor(config?: IDocConfig<S, T>);
111
+
112
+ /**
113
+ * Register middleware to document services
114
+ * @param action - action name
115
+ * @param middleware - the middleware to register
116
+ */
117
+ use<K extends keyof IDocMiddlewareContext<S, T>>(action: K, middleware: IMiddleware<IDocMiddlewareContext<S, T>[K]>): void;
118
+ /**
119
+ * Register hook to document services
120
+ * @param hookName - hook name
121
+ * @param hook - the hook to register
122
+ */
123
+ on<K extends keyof IDocHookContext>(hookName: K, hook: IHook<IDocHookContext[K]>): void;
124
+
125
+ /**
126
+ * Fetch latest snapshot
127
+ * @param id - document id
128
+ */
129
+ fetch(id: string, context?: IContext): Promise<ISnapshot<S>>;
130
+ /**
131
+ * Get operations between two versions, include from version, but not include to version
132
+ * @param id - document id
133
+ * @param from - from version
134
+ * @param to - to version
135
+ */
136
+ getOps(id: string, from: number, to?: number, context?: IContext): Promise<IOp<T>[]>;
137
+ /**
138
+ * Submit operation.
139
+ * @param id - document id
140
+ * @param op - operation
141
+ * @param context - context
142
+ * @param afterCommitCallback - callback after commit op to database
143
+ */
144
+ submit(id: string, op: IOp<T>, context?: IContext, afterCommitCallback?: IAfterCommitCallback<S, T>): Promise<IOp<T>[]>;
145
+ /**
146
+ * Fetch history snapshot by version
147
+ * @param id - document id
148
+ */
149
+ fetchHistorySnapshot(id: string, version?: number, context?: IContext): Promise<ISnapshot<S>>;
150
+ }
151
+
152
+ export interface IDocConfig<S, T> {
153
+ db?: IDataBaseAdapter<S, T>,
154
+ milestoneDb?: IMilestoneDataBaseAdapter<S>,
155
+ maxSubmitRetries?: number;
156
+ submitSnapshotBatchSize?: number;
157
+ }
158
+
159
+ /**
160
+ * The context of doc middleware.
161
+ */
162
+ export interface IDocMiddlewareContext<S, T> {
163
+ /**
164
+ * The doc received a message from a client.
165
+ */
166
+ receive: IDocReceiveMiddlewareContext<T>;
167
+
168
+ /**
169
+ * Start submitting an operation.
170
+ */
171
+ submit: IDocSubmitMiddlewareContext<S, T>;
172
+ /**
173
+ * An operation prepare commit to the database.
174
+ */
175
+ commit: IDocSubmitMiddlewareContext<S, T>;
176
+ /**
177
+ * An operation were successfully written to the database.
178
+ */
179
+ afterWrite: IDocSubmitMiddlewareContext<S, T>;
180
+
181
+ /**
182
+ * Start submitting snapshot.
183
+ */
184
+ submitSnapshot: IDocSubmitSnapshotMiddlewareContext<S, T>;
185
+ /**
186
+ * The operation is to be applied to the snapshot.
187
+ */
188
+ apply: IDocSubmitSnapshotMiddlewareContext<S, T>;
189
+ /**
190
+ * An snapshot prepare commit to the database.
191
+ */
192
+ commitSnapshot: IDocSubmitSnapshotMiddlewareContext<S, T>;
193
+
194
+ /**
195
+ * One or more snapshots were loaded from the database for a fetch or subscribe.
196
+ */
197
+ readSnapshots: IDocReadSnapshotsMiddlewareContext<S>;
198
+ /**
199
+ * An operation was loaded from the database.
200
+ */
201
+ readOp: IDocReadOpMiddlewareContext<T>;
202
+
203
+ /**
204
+ * The doc is about to send a non-error reply to a client message.
205
+ */
206
+ reply: IDocReplyMiddlewareContext<S, T>;
207
+ }
208
+ export interface IDocMiddlewareContextBase {
209
+ connection?: Connection;
210
+ }
211
+ export interface IDocReceiveMiddlewareContext<T> extends IDocMiddlewareContextBase {
212
+ request: IRequestMessage<T>;
213
+ }
214
+ export interface IDocReadOpMiddlewareContext<T> extends IDocMiddlewareContextBase {
215
+ id: string;
216
+ op: IOp<T>;
217
+ }
218
+ export interface IDocReplyMiddlewareContext<S, T> extends IDocMiddlewareContextBase {
219
+ request: IRequestMessage<T>;
220
+ reply: IReplyMessage<S, T>;
221
+ }
222
+ export interface IDocSubmitMiddlewareContext<S, T> extends IDocMiddlewareContextBase {
223
+ request: SubmitRequest<S, T>;
224
+ }
225
+ export interface IDocSubmitSnapshotMiddlewareContext<S, T> extends IDocMiddlewareContextBase {
226
+ request: SubmitSnapshotRequest<S, T>;
227
+ }
228
+ export interface IDocReadSnapshotsMiddlewareContext<S> extends IDocMiddlewareContextBase {
229
+ request: ReadSnapshotsRequest<S>;
230
+ }
231
+
232
+ export interface IDocHookContext {
233
+ submitRequestEnd: unknown,
234
+ timing: unknown
235
+ }
236
+
237
+ export declare class SubmitRequest<S, T> {
238
+ doc: DocumentServices<S, T>;
239
+ id: string;
240
+ context: IContext;
241
+ op: IOp<T>;
242
+ extra: unknown;
243
+ retries: number;
244
+ maxRetries?: number;
245
+ start: number;
246
+ document: IDocument | null;
247
+ ops: IOp<T>[];
248
+ }
249
+ export declare class SubmitSnapshotRequest<S, T> {
250
+ doc: DocumentServices<S, T>;
251
+ id: string;
252
+ context: ISubmitSnapshotContext<T>;
253
+ fromVersion: number;
254
+ toVersion: number;
255
+ ops: IOp<T>[] | null;
256
+ extra: unknown;
257
+ retries: number;
258
+ maxRetries?: number;
259
+ start: number;
260
+ saveSnapshot: boolean | null;
261
+ saveMilestoneSnapshot: boolean | null;
262
+ document: IDocument | null;
263
+ snapshot: ICommitSnapshot<S> | null;
264
+ }
265
+ export interface ISubmitSnapshotContext<T> extends IContext {
266
+ trigger?: SubmitSnapshotTrigger;
267
+ op?: IOp<T>;
268
+ }
269
+ /**
270
+ * The trigger source of submit snapshot.
271
+ */
272
+ export declare enum SubmitSnapshotTrigger {
273
+ submitOp = 'submitOp',
274
+ fetchSnapshot = 'fetchSnapshot',
275
+ manual = 'manual'
276
+ }
277
+
278
+ export declare class ReadSnapshotsRequest<S> {
279
+ snapshots: ISnapshot<S>[];
280
+ snapshotType: SnapshotTypes;
281
+ rejectSnapshotReadSilent(snapshot: ISnapshot<S>, errorMessage: string): void;
282
+ }
283
+
284
+ export type SnapshotTypes = 'current' | 'byVersion';
285
+
286
+ export interface IDocument {
287
+ id: string;
288
+ version: number;
289
+ snapshotVersion: number;
290
+ type?: string;
291
+ }
292
+
293
+ export interface ISnapshot<S = unknown> {
294
+ id: string;
295
+ v: number;
296
+ type?: string;
297
+ data?: S;
298
+ fragments?: ISnapshotFragments;
299
+ m?: ISnapshotMeta;
300
+ }
301
+ export interface ISnapshotMeta {
302
+ mtime?: number;
303
+ ctime?: number;
304
+ }
305
+
306
+ export type ISnapshotFragments<S = unknown> = { [key: string]: S };
307
+
308
+ export interface ISnapshotFragmentsChanges<S = unknown> {
309
+ createFragments?: { [key: string]: S };
310
+ updateFragments?: { [key: string]: S };
311
+ deleteFragments?: string[];
312
+ deleteSnapshot?: boolean;
313
+ }
314
+
315
+ export interface ICommitSnapshot<S = unknown> extends ISnapshot<S> {
316
+ fromVersion: number;
317
+ fragmentsChanges: ISnapshotFragmentsChanges;
318
+ }
319
+
320
+ export interface ISnapshotFragmentsRequest<S = unknown> {
321
+ getFragment(id: string): Promise<S | undefined>;
322
+
323
+ createFragment(id: string, data: S): void;
324
+ updateFragment(id: string, data: S): void;
325
+ deleteFragment(id: string): void;
326
+ }
327
+
328
+ export interface IOp<T = unknown> {
329
+ v: number;
330
+ create?: ICreateComponent;
331
+ op?: T;
332
+ del?: boolean;
333
+ }
334
+ export interface ICreateComponent {
335
+ type: string;
336
+ data: unknown;
337
+ }
338
+
339
+
340
+ export interface IRequestMessage<T> {
341
+ /**
342
+ * message action
343
+ */
344
+ a: MessageActions;
345
+ /**
346
+ * version
347
+ */
348
+ v?: number;
349
+ create?: ICreateComponent;
350
+ op?: T;
351
+ del?: boolean;
352
+ error?: IErrorData;
353
+ }
354
+ export interface IRequestMessageExtra {
355
+ source?: unknown;
356
+ }
357
+ /**
358
+ * Message actions.
359
+ */
360
+ export declare enum MessageActions {
361
+ fetch = 'fetch',
362
+ fetchOps = 'fetchOps',
363
+ fetchHistorySnapshot = 'fetchHistorySnapshot',
364
+ subscribe = 'subscribe',
365
+ unsubscribe = 'unsubscribe',
366
+ op = 'op',
367
+ }
368
+
369
+ export interface IReplyMessage<S, T> {
370
+ a: string;
371
+ v?: number;
372
+ create?: ICreateComponent;
373
+ op?: T;
374
+ del?: boolean;
375
+ error?: IErrorData;
376
+ data?: ISnapshot<S>;
377
+ }
378
+
379
+ /**
380
+ * The data base adapter interface.
381
+ */
382
+ export interface IDataBaseAdapter<S = unknown, T = unknown> {
383
+ /**
384
+ * Get the ops between two versions, include from version, exclude to version.
385
+ */
386
+ getOps(id: string, from: number, to?: number, options?: unknown): Promise<IOp<T>[]>;
387
+ /**
388
+ * Get the document info by id.
389
+ */
390
+ getDocument(id: string, options?: unknown): Promise<IDocument | undefined | null>;
391
+
392
+ /**
393
+ * Get the snapshot by id.
394
+ */
395
+ getSnapshot(id: string, options?: unknown): Promise<ISnapshot<S> | undefined | null>;
396
+ getFragment(id: string, fragmentId: string, options?: unknown): Promise<S | undefined | null>;
397
+ getFragments(id: string, fragmentIds?: string[], options?: unknown): Promise<{ [id: string]: S }>;
398
+
399
+ commitOp(id: string, op: IOp<T>, document: IDocument, options?: unknown): Promise<boolean>;
400
+ commitSnapshot(id: string, snapshot: ICommitSnapshot<S>, options?: unknown): Promise<boolean>;
401
+
402
+ /**
403
+ * Get the committed op version, if the op is committed, return the committed version, otherwise return undefined.
404
+ */
405
+ getCommittedOpVersion(id: string, to: number, op: IOp): Promise<number | undefined>;
406
+
407
+ /**
408
+ * Close the database.
409
+ */
410
+ close(): Promise<void>;
411
+ }
412
+
413
+ /**
414
+ * The milestone data base adapter interface.
415
+ */
416
+ export interface IMilestoneDataBaseAdapter<S> {
417
+ /**
418
+ * The interval of saving milestone snapshot.
419
+ * default is 1000.
420
+ */
421
+ interval: number;
422
+ saveMilestoneSnapshot(snapshot: ISnapshot<S>): Promise<boolean>;
423
+ getMilestoneSnapshot(id: string, version: number): Promise<ISnapshot<S> | undefined>;
424
+ }
425
+
426
+ export declare abstract class Db<S, T> implements IDataBaseAdapter<S, T> {
427
+ abstract getOps(id: string, from: number, to?: number, options?: unknown): Promise<IOp<T>[]>;
428
+ abstract getDocument(id: string, options?: unknown): Promise<IDocument | undefined | null>;
429
+ abstract getSnapshot(id: string, options?: unknown): Promise<ISnapshot<S> | undefined | null>;
430
+ abstract getFragment(id: string, fragmentId: string, options?: unknown): Promise<S | undefined | null>;
431
+ abstract getFragments(id: string, fragmentIds?: string[], options?: unknown): Promise<{
432
+ [id: string]: S;
433
+ }>;
434
+ abstract commitOp(id: string, op: IOp<T>, document: IDocument, options?: unknown): Promise<boolean>;
435
+ abstract commitSnapshot(id: string, snapshot: ICommitSnapshot<S>, options?: unknown): Promise<boolean>;
436
+ abstract close(): Promise<void>;
437
+ getCommittedOpVersion(id: string, to: number, op: IOp<object>): Promise<number | undefined>;
438
+ }
439
+
440
+ export declare class MemoryDb<S = unknown, T = unknown> extends Db<S, T> {
441
+ getSnapshot(roomId: string): Promise<ISnapshot<S> | undefined>;
442
+ getDocument(roomId: string): Promise<IDocument | undefined>;
443
+ getFragments(roomId: string): Promise<{
444
+ [key: string]: S;
445
+ }>;
446
+ getFragment(roomId: string, fragmentId: string): Promise<S | undefined>;
447
+ getOps(roomId: string, fromVersion: number, toVersion?: number): Promise<IOp<T>[]>;
448
+ commitOp(id: string, op: IOp<T>, document: IDocument): Promise<boolean>;
449
+ commitSnapshot(roomId: string, snapshot: ICommitSnapshot<S>): Promise<boolean>;
450
+ close(): Promise<void>;
451
+ }
452
+
453
+ export interface IContext {
454
+ connection?: Connection;
455
+ options?: ICustomOptions;
456
+ }
457
+
458
+ export interface ICustomOptions {
459
+ [key: string]: unknown;
460
+ }
461
+ export interface IErrorData {
462
+ code: string;
463
+ message: string;
464
+ }
465
+
466
+ export interface IAfterCommitCallback<S, T> {
467
+ (request: SubmitRequest<S, T>): void;
468
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("@grapecity-software/js-collaboration"));else if("function"==typeof define&&define.amd)define(["@grapecity-software/js-collaboration"],e);else{var s="object"==typeof exports?e(require("@grapecity-software/js-collaboration")):e(t["@grapecity-software/js-collaboration"]);for(var r in s)("object"==typeof exports?exports:t)[r]=s[r]}}(this,(t=>(()=>{"use strict";var e={619:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Db=void 0,e.Db=class{async getCommittedOpVersion(t,e,s){const r=await this.getOps(t,0,e);for(let t=r.length;t--;){const e=r[t];if(s.src===e.src&&s.seq===e.seq)return e.v}}}},985:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MemoryDb=void 0;const r=s(619);class n extends r.Db{constructor(t){var e;super(),this.ops=new Map,this.documents=new Map,this.fragments=new Map,this.mockWaitTime=null!==(e=null==t?void 0:t.mockWaitTime)&&void 0!==e?e:0}async getSnapshot(t){return this.execute((async()=>{const e=this.documents.get(t);if(!e)return;const s=await this.getFragments(t);return{id:t,v:e.snapshotVersion,type:e.type,fragments:s}}))}getDocument(t){return this.execute((()=>{const e=this.documents.get(t);if(e)return JSON.parse(JSON.stringify(e))}))}getFragments(t){return this.execute((()=>{const e=this.fragments.get(t);return e?JSON.parse(JSON.stringify(Object.fromEntries(e))):void 0}))}getFragment(t,e){return this.execute((()=>{var s;const r=null===(s=this.fragments.get(t))||void 0===s?void 0:s.get(e);if(r)return JSON.parse(JSON.stringify(r))}))}getOps(t,e,s){return this.execute((()=>{const r=this.ops.get(t);if(!r)return[];s=null!=s?s:Number.MAX_SAFE_INTEGER;const n=r.filter((t=>t.v>=e&&t.v<s));return JSON.parse(JSON.stringify(n))}))}commitOp(t,e,s){return this.execute((()=>{var r;if(e=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(s)),e.create){if(this.documents.has(t))return!1;const{version:r,snapshotVersion:n,type:i}=s;return this.documents.set(t,{id:t,version:r,snapshotVersion:n,type:i}),this.ops.set(t,[e]),this.fragments.set(t,new Map),!0}if(e.del)return!!this.documents.has(t)&&(this.documents.delete(t),this.ops.delete(t),this.fragments.delete(t),!0);{const n=null===(r=this.ops.get(t))||void 0===r?void 0:r.length;return e.v===n&&(this.ops.get(t).push(e),this.documents.get(t).version=s.version,!0)}}))}commitSnapshot(t,e){return this.execute((()=>{var s,r,n;e=JSON.parse(JSON.stringify(e));const i=this.documents.get(t);if(e.fromVersion!==i.snapshotVersion)return!1;if(e.v<=i.snapshotVersion)return!1;i.snapshotVersion=e.v;const o=e.fragmentsChanges;if(o.deleteSnapshot)this.fragments.delete(t);else{const e=this.fragments.get(t);Object.entries(null!==(s=o.createFragments)&&void 0!==s?s:{}).forEach((async([t,s])=>{e.set(t,s)})),Object.entries(null!==(r=o.updateFragments)&&void 0!==r?r:{}).forEach((async([t,s])=>{e.set(t,s)})),null===(n=o.deleteFragments)||void 0===n||n.forEach((t=>{e.delete(t)}))}return!0}))}close(){return this.execute((()=>{}))}dump(){const t={ops:this.ops,documents:this.documents,fragments:this.fragments};return JSON.parse(JSON.stringify(t,((t,e)=>e instanceof Map?Object.fromEntries(e.entries()):e)))}_wait(){return new Promise((t=>setTimeout(t,this.mockWaitTime)))}async execute(t){return await this._wait(),await t()}}e.MemoryDb=n},347:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DocumentController=void 0;const r=s(127),n=s(961),i=s(660),o=i.MessageActions,a=i.OTError.CODES;function c(t){return{id:t.id,v:t.v,data:t.data,type:t.type}}e.DocumentController=class{constructor(t){this.service=t}async trigger(t,e){await this.service.trigger(t,e)}send(t,e){t.send(JSON.stringify(e),i.OT_DOC_MESSAGE_TYPE)}_sendOp(t,e){const s={a:o.op,v:e.v,src:e.src,seq:e.seq};"op"in e&&(s.op=e.op),e.create&&(s.create=e.create),e.del&&(s.del=!0),this.send(t,s)}_broadcastOp(t,e){const s={a:i.MessageActions.op,v:e.v,src:e.src,seq:e.seq};"op"in e&&(s.op=e.op),e.create&&(s.create=e.create),e.del&&(s.del=!0),t.broadcast(JSON.stringify(s),i.OT_DOC_MESSAGE_TYPE)}_sendOps(t,e){for(let s=0;s<e.length;s++)this._sendOp(t,e[s])}async _reply(t,e,s){s.a=e.a;const r={connection:t,request:e,reply:s};try{await this.trigger("reply",r),this.send(t,r.reply)}catch(s){this._replyError(t,e,s)}}async _replyError(t,e,s){e.error=function(t){return t instanceof i.OTError?{code:t.code,message:t.message}:"string"==typeof t?{code:a.ERR_UNKNOWN_ERROR,message:t}:(r.logger.warn("unknown error",t),void((null==t?void 0:t.stack)&&r.logger.info(t.stack)))}(s),this.send(t,e)}async _messageHandler(t,e){const s=this;if("string"!=typeof e)return void s.close(t,new i.OTError(a.ERR_MESSAGE_BADLY_FORMED,"Received non-object message"));let r;try{r=JSON.parse(e)}catch(e){return void s.close(t,new i.OTError(a.ERR_MESSAGE_BADLY_FORMED,"Received non-object message"))}try{this.trigger("receive",Object.assign(Object.assign({},s),{request:r}));const e=await s._handleMessage(t,r);s._reply(t,r,e||{})}catch(e){s._replyError(t,r,e)}}_checkRequest(t){if(t.a===o.op&&!(0,n.isNullOrUndefined)(t.v)&&("number"!=typeof t.v||t.v<0))return"Invalid version"}async _handleMessage(t,e){const s=this._checkRequest(e);if(s)throw new i.OTError(a.ERR_MESSAGE_BADLY_FORMED,s);switch(e.a){case o.fetch:return await this._fetch(t,e.v);case o.subscribe:return await this._subscribe(t,e.v);case o.unsubscribe:return this._unsubscribe();case o.op:return await this._submit(t,e);case o.fetchHistorySnapshot:return await this._fetchSnapshot(t,e);default:throw new i.OTError(a.ERR_MESSAGE_BADLY_FORMED,"Invalid or unknown message")}}async _fetch(t,e){return(0,n.isNullOrUndefined)(e)?{data:c(await this.service.fetch(t.roomId,void 0))}:await this._fetchOps(t,e)}async _fetchOps(t,e){const s=await this.service.getOps(t.roomId,e,void 0,void 0);this._sendOps(t,s)}async _subscribe(t,e){const s=await this.service.subscribe(t.roomId,e);if((null==s?void 0:s.ops)&&this._sendOps(t,s),null==s?void 0:s.snapshot)return{data:c(s.snapshot)}}_unsubscribe(){}async _submit(t,e){const s=function(t,e){const s=t.src||e;return t.op?function(t,e,s,r,n){return{src:t,seq:e,v:s,op:r,x:n,m:void 0}}(s,t.seq,t.v,t.op,t.x):t.create?function(t,e,s,r,n){return{src:t,seq:e,v:s,create:r,x:n,m:void 0}}(s,t.seq,t.v,t.create,t.x):t.del?function(t,e,s,r,n){return{src:t,seq:e,v:s,del:r,x:n,m:void 0}}(s,t.seq,t.v,t.del,t.x):void 0}(e,t.id);if(!s)throw new i.OTError(a.ERR_MESSAGE_BADLY_FORMED,"Invalid op message");if(s.seq>=i.util.MAX_SAFE_INTEGER)throw new i.OTError(a.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long");return await this._submitOp(t,s)}async _submitOp(t,e){const s=this;try{const r=await this.service.submit(t.roomId,e,{connection:t},(e=>{s._broadcastOp(t,e.op)}));return s._sendOps(t,r),{src:e.src,seq:e.seq,v:e.v}}catch(t){if(t instanceof i.OTError&&t.code===a.ERR_OP_ALREADY_SUBMITTED)return{src:e.src,seq:e.seq,v:e.v};throw t}}async _fetchSnapshot(t,e){return void 0!==e.v?{id:e.id,data:await this.service.fetchHistorySnapshot(t.roomId,e.v)}:void 0!==e.ts?{id:e.id,data:await this.service.fetchHistorySnapshotByTimestamp(t.roomId,e.ts)}:void 0}close(t,e){e&&r.logger.warn("Connection closed due to error",t.id,e.stack||e),t.close()}}},763:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.documentFeature=function(t){const e=t||new r.DocumentServices,s=new n.DocumentController(e);return{middlewares:{message:async(t,e)=>t.type!==i.OT_DOC_MESSAGE_TYPE?await e():s._messageHandler(t.connection,t.data)}}};const r=s(89),n=s(347),i=s(660)},89:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DocumentServices=void 0;const r=s(660),n=s(127),i=s(961),o=s(985),a=s(259),c=s(551),_=s(155),u=s(936),p=s(469),h=s(36),d=s(769),O=r.OTError.CODES;class E extends n.Middleware{constructor(t){var e,s,r;super(),t=null!=t?t:{},this.db=null!==(e=t.db)&&void 0!==e?e:new o.MemoryDb,this.milestoneDb=null!==(s=t.milestoneDb)&&void 0!==s?s:new u.MilestoneDB,this.maxSubmitRetries=t.maxSubmitRetries,this.submitSnapshotBatchSize=null!==(r=t.submitSnapshotBatchSize)&&void 0!==r?r:10}async fetch(t,e){const s=Date.now(),r=this;let n=await r._getSnapshot(t,e);return[n]=await r._sanitizeSnapshots([n],a.SnapshotTypes.current,e),r._emitTiming("fetch",Date.now()-s,{context:e,id:t}),n}async getOps(t,e,s,r){const n=Date.now(),i=await this._getSanitizedOps(t,e,s,r);return this._emitTiming("getOps",Date.now()-n,Object.assign(Object.assign({},r),{id:t,from:e,to:s})),i}async subscribe(t,e,s){const r=this,n=Date.now();if((0,i.isNullOrUndefined)(e)){const i=await r.fetch(t,s);return r._emitTiming("subscribe.snapshot",Date.now()-n,Object.assign(Object.assign({},s),{id:t,version:e})),{snapshot:i}}{const i=await r._getSanitizedOps(t,e,void 0,s);return r._emitTiming("subscribe.ops",Date.now()-n,Object.assign(Object.assign({},s),{id:t,version:e})),{ops:i}}}async submit(t,e,s,r){const n=this,i=new c.SubmitRequest(this,t,e,s),o=Object.assign(Object.assign({},s),{request:i});try{const s=_.ot.checkOp(e);if(s)throw s;return await n.trigger("submit",o),await i.submit(r),await n.trigger("afterWrite",o),await n._sanitizeOps(t,i.ops,o),n._emitTiming("submit.total",Date.now()-i.start,i),n.emit("submitRequestEnd",{request:i}),i.ops}catch(t){throw n.emit("submitRequestEnd",{error:t,request:i}),t}}async fetchHistorySnapshotByTimestamp(t,e,s){const r=Date.now();let n=await this._fetchHistorySnapshotByTimestamp(t,e);const i=[n],o=a.SnapshotTypes.byTimestamp;return[n]=await this._sanitizeSnapshots(i,o,s),this._emitTiming("fetchSnapshot",Date.now()-r,Object.assign({},s)),n}async _fetchHistorySnapshotByTimestamp(t,e){const s=this.db,r=this.milestoneDb;let n,i=0;if(void 0===e)return await this._getSnapshot(t);let o=await r.getMilestoneSnapshotAtOrBeforeTime(t,e);const a=o;o&&(i=o.v),o=await r.getMilestoneSnapshotAtOrAfterTime(t,e),o&&(n=o.v);const c=await s.getOps(t,i,n,{metadata:!0});return function(t,e){for(let s=0;s<t.length;s++){const r=t[s];if((r.m&&r.m.ts)>e)return void(t.length=s)}}(c,e),o=await this._buildSnapshotFromOps(t,a,c),o}async fetchHistorySnapshot(t,e,s){const r=Date.now();let n=await this._fetchHistorySnapshot(t,e);const i=[n],o=a.SnapshotTypes.byVersion;return[n]=await this._sanitizeSnapshots(i,o,s),this._emitTiming("fetchSnapshot",Date.now()-r,Object.assign(Object.assign({},s),{version:e})),n}async _fetchHistorySnapshot(t,e){const s=this.db;if(void 0===e)return await this._getSnapshot(t);const n=await this.milestoneDb.getMilestoneSnapshot(t,e),i=n?n.v:0,o=await s.getOps(t,i,e),a=await this._buildSnapshotFromOps(t,n,o);if(e>a.v)throw new r.OTError(O.ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT,"Requested version exceeds latest snapshot version");return a}async _buildSnapshotFromOps(t,e,s){const r=null!=e?e:{id:t,v:0},n=new h.SnapshotFragmentsRequest(t,void 0,r.fragments),i=await _.ot.applyOps(r,s,n);if(i)throw i;return n.applyChangesToSnapshot(r),_.ot.composeFragments(r),r}async _sanitizeSnapshots(t,e,s){const r=new p.ReadSnapshotsRequest(t,e);if(await this.trigger("readSnapshots",Object.assign(Object.assign({},s),{request:r})),r.hasSnapshotRejection())throw r.getReadSnapshotsError();return t}async _getSanitizedOps(t,e,s,r){const n=await this.db.getOps(t,e,s,null==r?void 0:r.options);return await this._sanitizeOps(t,n,r),n}async _sanitizeOps(t,e,s){for(const r of e)await this._sanitizeOp(t,r,s)}async _sanitizeOp(t,e,s){await this.trigger("readOp",Object.assign(Object.assign({},s),{id:t,op:e}))}async _getSnapshot(t,e){var s;const r=null==e?void 0:e.options,n=await this.db.getDocument(t,r);if(!n)return{id:t,v:0};if(n.snapshotVersion<n.version){const s=new d.SubmitSnapshotRequest(this,t,n,Object.assign(Object.assign({},e),{trigger:d.SubmitSnapshotTrigger.fetchSnapshot}));await s.submitSnapshot()}const i=null!==(s=await this.db.getSnapshot(t,r))&&void 0!==s?s:{id:t,v:0};return _.ot.composeFragments(i),i}_emitTiming(t,e,s){this.emit("timing",{action:t,cost:e,m:s})}}e.DocumentServices=E},259:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Hooks=e.SnapshotTypes=void 0,e.SnapshotTypes={current:"current",byVersion:"byVersion",byTimestamp:"byTimestamp"},e.Hooks={submitRequestEnd:"submitRequestEnd",timing:"timing"}},936:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MilestoneDB=void 0;const r=s(660),n=s(961),i=r.OTError.CODES;e.MilestoneDB=class{constructor(t){var e;this.interval=null!==(e=null==t?void 0:t.interval)&&void 0!==e?e:1e3,this.map=new Map}saveMilestoneSnapshot(t){return new Promise((e=>{let s=this.map.get(t.id);s||(s=[],this.map.set(t.id,s)),s.push(t),s.sort(((t,e)=>t.v-e.v)),e(!0)}))}getMilestoneSnapshot(t,e){const s=function(t){return function(e,s){return!(0,n.isNullOrUndefined)(t)&&s.v>t}}(e);return this._findMilestoneSnapshot(t,s)}getMilestoneSnapshotAtOrBeforeTime(t,e){const s=function(t){return function(e,s){if((0,n.isNullOrUndefined)(t))return!!e;const r=s&&s.m&&s.m.mtime;return void 0!==r&&r>t}}(e);return this._findMilestoneSnapshot(t,s)}getMilestoneSnapshotAtOrAfterTime(t,e){const s=function(t){return function(e){if((0,n.isNullOrUndefined)(t))return!1;const s=e&&e.m&&e.m.mtime;return void 0!==s&&s>=t}}(e);return this._findMilestoneSnapshot(t,s)}_findMilestoneSnapshot(t,e){return new Promise((s=>{if(!t)throw new r.OTError(i.ERR_MILESTONE_ARGUMENT_INVALID,"Missing ID");const n=this._getMilestoneSnapshots(t);let o;for(let t=0;t<n.length;t++){const s=n[t];if(e(o,s))break;o=s}s(o)}))}_getMilestoneSnapshots(t){var e;return null!==(e=this.map.get(t))&&void 0!==e?e:[]}}},155:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ot=e.composeFragments=e.applyOps=e.transform=e.apply=e.normalizeType=e.checkOp=void 0;const r=s(961),n=s(660),i=n.OTError.CODES,o="default";e.checkOp=function(t){if((0,r.isNullOrUndefined)(t)||"object"!=typeof t)return new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if((0,r.isNullOrUndefined)(t.create)){if((0,r.isNullOrUndefined)(t.del)){if(!("op"in t))return new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del")}else if(!0!==t.del)return new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else{if("object"!=typeof t.create)return new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");const e=t.create.type;if("string"!=typeof e)return new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");const s=n.TypesManager.map[e];if((0,r.isNullOrUndefined)(s)||"object"!=typeof s)return new n.OTError(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}return(0,r.isNullOrUndefined)(t.src)||"string"==typeof t.src?(0,r.isNullOrUndefined)(t.seq)||"number"==typeof t.seq?(0,r.isNullOrUndefined)(t.src)&&!(0,r.isNullOrUndefined)(t.seq)||!(0,r.isNullOrUndefined)(t.src)&&(0,r.isNullOrUndefined)(t.seq)?new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together"):(0,r.isNullOrUndefined)(t.m)||"object"==typeof t.m?void 0:new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null"):new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"seq must be a number"):new n.OTError(i.ERR_OT_OP_BADLY_FORMED,"src must be a string")},e.normalizeType=function(t){return n.TypesManager.map[t]&&n.TypesManager.map[t].uri},e.apply=async function(t,e,s){if("object"!=typeof t)return new n.OTError(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(!(0,r.isNullOrUndefined)(t.v)&&!(0,r.isNullOrUndefined)(e.v)&&t.v!==e.v)return new n.OTError(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(e.create){const r=e.create,a=n.TypesManager.map[r.type];if(!a)return new n.OTError(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{let e;e=a.createFragments?a.createFragments(r.data):{[o]:a.create(r.data)},s.create(e),t.type=a.uri,t.v++}catch(t){return t}}else if(e.del)s.delete(),t.data=void 0,t.type=void 0,t.v++;else if("op"in e){const r=await async function(t,e,s){if(!t.type)return new n.OTError(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(void 0===e)return new n.OTError(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");const r=n.TypesManager.map[t.type];if(!r)return new n.OTError(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{if(r.applyFragments)await r.applyFragments(s,e);else{const t=await s.getFragment(o),n=r.apply(t,e);s.updateFragment(o,n)}}catch(t){return new n.OTError(i.ERR_OT_OP_NOT_APPLIED,t.message)}}(t,e.op,s);if(r)return r;t.v++}else t.v++},e.transform=function(t,e,s){if(!(0,r.isNullOrUndefined)(e.v)&&e.v!==s.v)return new n.OTError(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(s.del){if(e.create||"op"in e)return new n.OTError(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(s.create&&("op"in e||e.create||e.del)||"op"in s&&e.create)return new n.OTError(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in s&&"op"in e){if(!t)return new n.OTError(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if("string"==typeof t&&!(t=n.TypesManager.map[t]))return new n.OTError(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{e.op=t.transform(e.op,s.op,"left")}catch(t){return new n.OTError(i.ERR_OT_OP_TRANSFORM_FAILED,"Op transform failed")}}}(0,r.isNullOrUndefined)(e.v)||e.v++},e.applyOps=async function(t,s,r){for(let n=0;n<s.length;n++){const i=s[n];t.v=i.v;const o=await(0,e.apply)(t,i,r);if(o)return o}},e.composeFragments=function(t){if(!t.type)return;const e=n.TypesManager.map[t.type];e&&t.fragments&&(e.composeFragments?t.data=e.composeFragments(t.fragments):t.data=t.fragments[o])},e.ot={checkOp:e.checkOp,normalizeType:e.normalizeType,apply:e.apply,transform:e.transform,applyOps:e.applyOps,composeFragments:e.composeFragments}},469:(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadSnapshotsRequest=void 0;const r=s(660),n=s(961);e.ReadSnapshotsRequest=class{constructor(t,e){this.snapshots=t,this.snapshotType=e,this._idToError=null}rejectSnapshotRead(t,e){this._idToError||(this._idToError=Object.create(null)),this._idToError[t.id]=e}rejectSnapshotReadSilent(t,e){this.rejectSnapshotRead(t,this.silentRejectionError(e))}silentRejectionError(t){return new r.OTError(r.OTError.CODES.ERR_SNAPSHOT_READ_SILENT_REJECTION,t)}hasSnapshotRejection(){return!(0,n.isNullOrUndefined)(this._idToError)}getReadSnapshotsError(){const t=this.snapshots,e=this._idToError;if(0===t.length)return;if(1===t.length){return e[t[0].id]||void 0}const s=new r.OTError(r.OTError.CODES.ERR_SNAPSHOT_READS_REJECTED);return s.idToError=e,s}}},36:(t,e)=>{function s(t,e){var s,r,n;const i=null!==(s=t.fragments)&&void 0!==s?s:{};if(e.deleteSnapshot)t.fragments={};else{for(const[t,s]of Object.entries(null!==(r=e.createFragments)&&void 0!==r?r:{}))i[t]=s;for(const[t,s]of Object.entries(null!==(n=e.updateFragments)&&void 0!==n?n:{}))i[t]=s;e.deleteFragments&&e.deleteFragments.length>0&&e.deleteFragments.forEach((t=>delete i[t])),t.fragments=i}}Object.defineProperty(e,"__esModule",{value:!0}),e.SnapshotFragmentsRequest=void 0,e.applyChangesToSnapshot=s,e.SnapshotFragmentsRequest=class{constructor(t,e,s){this._fragmentsMap=new Map,this._createFragments=new Map,this._updateFragments=new Map,this._deleteFragments=new Set,this._deleteSnapshot=!1,this._docId=t,this._db=e,s&&Object.entries(s).forEach((([t,e])=>{this._fragmentsMap.set(t,e)}))}async _loadFragment(t){const e=await this._db.getFragment(this._docId,t);this._fragmentsMap.set(t,e)}async getFragment(t){return this._db&&!this._fragmentsMap.has(t)&&await this._loadFragment(t),this._fragmentsMap.get(t)}createFragment(t,e){this._createFragments.set(t,e),this._fragmentsMap.set(t,e)}updateFragment(t,e){this._createFragments.has(t)?this._createFragments.set(t,e):this._updateFragments.set(t,e),this._fragmentsMap.set(t,e)}deleteFragment(t){this._deleteFragments.add(t),this._createFragments.delete(t),this._updateFragments.delete(t),this._fragmentsMap.delete(t)}create(t){Object.entries(t).forEach((([t,e])=>{this.createFragment(t,e)}))}delete(){this._deleteSnapshot=!0,this._createFragments.clear(),this._updateFragments.clear(),this._deleteFragments.clear(),this._fragmentsMap.clear()}getChanges(){return{createFragments:Object.fromEntries(this._createFragments.entries()),updateFragments:Object.fromEntries(this._updateFragments.entries()),deleteFragments:Array.from(this._deleteFragments),deleteSnapshot:this._deleteSnapshot}}applyChangesToSnapshot(t){s(t,this.getChanges())}}},551:function(t,e,s){var r=this&&this.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,r,n)}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),n=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var s in t)"default"!==s&&Object.prototype.hasOwnProperty.call(t,s)&&r(e,t,s);return n(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.SubmitRequest=void 0;const o=s(961),a=s(660),c=i(s(155)),_=s(769),u=a.OTError.CODES,p=a.TypesManager.getType;e.SubmitRequest=class{constructor(t,e,s,r){this.doc=t,this.context=r||{},this.id=e,this.op=s,this.extra=s.x,delete s.x,this.start=Date.now(),this._addOpMeta(),this.maxRetries=t.maxSubmitRetries,this.retries=0,this.ops=[]}async submit(t){var e;const s=this,r=this.doc.db,n=this.id,i=this.op,a=null!==(e=await r.getDocument(n))&&void 0!==e?e:{id:n,version:0,snapshotVersion:0};s.document=a;const c=a.version;if((0,o.isNullOrUndefined)(i.v)){if(i.create&&a.type&&i.src){const t=await r.getCommittedOpVersion(n,c,i);throw(0,o.isNullOrUndefined)(t)?s.alreadyCreatedError():(i.v=t,s.alreadySubmittedError())}i.v=c}if(i.v>c)throw s.newerVersionError();if(i.v<c){const t=Date.now(),e=i.v,o=await r.getOps(n,e,c);if(!o||o.length!==c-e)throw s.missingOpsError();const a=s._transformOp(o);if(a)throw a;if(i.v!==c)throw s.versionAfterTransformError();s.doc._emitTiming("submit.transform",Date.now()-t,s)}if(i.create&&a.type)throw s.alreadyCreatedError();s._updateDocument(),await s.commitOp(t)}_addOpMeta(){this.op.m={ts:this.start},this.op.create&&(this.op.create.type=c.normalizeType(this.op.create.type))}_updateDocument(){if(!this.document)return;const t=this.document,e=this.op;e.create?(t.type=c.normalizeType(e.create.type),t.snapshotVersion=0):e.del&&(t.type=void 0),t.version++,this._updateDocumentMeta()}_updateDocumentMeta(){const t=this.document.m||(this.document.m={});this.op.create&&(t.ctime=this.start),t.mtime=this.start}_transformOp(t){const e=p(this.document.type);for(let s=0;s<t.length;s++){const r=t[s];if(this.op.src&&this.op.src===r.src&&this.op.seq===r.seq)return this.alreadySubmittedError();if(this.op.v!==r.v)return this.versionDuringTransformError();const n=c.transform(e,this.op,r);if(n)return n;delete r.m,this.ops.push(r)}}async commitOp(t){const e=this,s=this.doc;await e._trigger("commit");const r=Date.now();if(!await s.db.commitOp(e.id,e.op,e.document,e.options))return await e._retry(t);e.op.m=void 0,s._emitTiming("commit.op",Date.now()-r,e),null==t||t(e);const n=new _.SubmitSnapshotRequest(s,e.id,e.document,Object.assign(Object.assign({},e.context),{trigger:_.SubmitSnapshotTrigger.submitOp,op:e.op}));await n.submitSnapshot()}async _retry(t){if(this.retries++,null!=this.maxRetries&&this.retries>this.maxRetries)throw this.maxRetriesError();this.doc._emitTiming("submit.retry",Date.now()-this.start,this),await this.submit(t)}async _trigger(t){const e=Object.assign(Object.assign({},this.context),{request:this});await this.doc.trigger(t,e),this.context.options=e.options}alreadyCreatedError(){return new a.OTError(u.ERR_DOC_ALREADY_CREATED,"Invalid op submitted. Document already created")}rejectedError(){return new a.OTError(u.ERR_OP_SUBMIT_REJECTED,"Op submit rejected")}alreadySubmittedError(){return new a.OTError(u.ERR_OP_ALREADY_SUBMITTED,"Op already submitted")}maxRetriesError(){return new a.OTError(u.ERR_MAX_SUBMIT_RETRIES_EXCEEDED,"Op submit failed. Exceeded max submit retries of "+this.maxRetries)}versionDuringTransformError(){return new a.OTError(u.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Op submit failed. Versions mismatched during op transform")}newerVersionError(){return new a.OTError(u.ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT,"Invalid op submitted. Op version newer than current snapshot")}missingOpsError(){return new a.OTError(u.ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND,"Op submit failed. DB missing ops needed to transform it up to the current snapshot version")}versionAfterTransformError(){return new a.OTError(u.ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM,"Op submit failed. Op version mismatches snapshot after op transform")}}},769:function(t,e,s){var r=this&&this.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,r,n)}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),n=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var s in t)"default"!==s&&Object.prototype.hasOwnProperty.call(t,s)&&r(e,t,s);return n(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.SubmitSnapshotRequest=e.SubmitSnapshotTrigger=void 0;const o=s(127),a=s(660),c=s(36),_=i(s(155)),u=a.OTError.CODES;var p;!function(t){t.submitOp="submitOp",t.fetchSnapshot="fetchSnapshot",t.manual="manual"}(p||(e.SubmitSnapshotTrigger=p={})),e.SubmitSnapshotRequest=class{constructor(t,e,s,r){this.doc=t,this.context=r||{},this.id=e,this.document=s,this.fromVersion=s.snapshotVersion,this.toVersion=s.version,this.start=Date.now(),this.saveSnapshot=null,this.saveMilestoneSnapshot=null,this.maxRetries=t.maxSubmitRetries,this.retries=0,this.snapshot=null}async submitSnapshot(){const t=this,e=this.doc;if(await t._trigger("submitSnapshot"),!t._shouldSubmitSnapshot())return;const s=await e.db.getOps(t.id,t.fromVersion,t.toVersion);s&&s.length===t.toVersion-t.fromVersion&&(t.ops=s,await this.apply())}_addSnapshotMeta(){if(!this.snapshot)return;const t=this.snapshot;this.ops.forEach((e=>{const s=t.m||(t.m={});e.create&&(s.ctime=this.start),s.mtime=this.start}))}async apply(){const t=this,e=this.doc.db,s=this.id,r=this.ops,n=t.document,i=Date.now();t.snapshot={id:s,fromVersion:n.snapshotVersion,v:n.snapshotVersion,type:n.type},t._addSnapshotMeta(),await t._trigger("apply");const a=t.snapshot,u=new c.SnapshotFragmentsRequest(s,e),p=await _.applyOps(a,r,u);p?o.logger.error("submit.snapshot.apply",p):(a.fragmentsChanges=u.getChanges(),t.doc._emitTiming("submit.snapshot.apply",Date.now()-i,t),await this.commitSnapshot())}async commitSnapshot(){const t=this,e=this.doc;await t._trigger("commitSnapshot");const s=Date.now();if(!await e.db.commitSnapshot(t.id,t.snapshot,t.context.options))return this._retry();if(e._emitTiming("commit.snapshot",Date.now()-s,t),t._shouldSaveMilestoneSnapshot(t.snapshot)){const e=await t.doc.db.getSnapshot(t.id);(0,c.applyChangesToSnapshot)(e,t.snapshot.fragmentsChanges),t.doc.milestoneDb.saveMilestoneSnapshot(e)}}async _retry(){if(this.retries++,null!=this.maxRetries&&this.retries>this.maxRetries)throw this.maxRetriesError();const t=await this.doc.db.getDocument(this.id,this.context.options);if(t){if(t.snapshotVersion!==this.fromVersion){if(t.snapshotVersion>=this.toVersion)return;return this.document=t,this.fromVersion=t.snapshotVersion,this.doc._emitTiming("submit.snapshot.retry",Date.now()-this.start,this),await this.submitSnapshot()}return this.doc._emitTiming("submit.snapshot.retry",Date.now()-this.start,this),await this.submitSnapshot()}}_shouldSubmitSnapshot(){var t,e;const s=this.fromVersion,r=this.toVersion,n=null===(t=this.context)||void 0===t?void 0:t.trigger,i=null===(e=this.context)||void 0===e?void 0:e.op;return!(n!==p.submitOp||!i||!i.create&&!i.del)||n===p.fetchSnapshot||0===s||!(r<=s)&&(null===this.saveSnapshot?r-s>=this.doc.submitSnapshotBatchSize:this.saveSnapshot)}_shouldSaveMilestoneSnapshot(t){return null===this.saveMilestoneSnapshot?t&&t.v%this.doc.milestoneDb.interval==0:this.saveMilestoneSnapshot}async _trigger(t){const e=Object.assign(Object.assign({},this.context),{request:this});await this.doc.trigger(t,e),this.context.options=e.options}maxRetriesError(){return new a.OTError(u.ERR_MAX_SUBMIT_SNAPSHOT_RETRIES_EXCEEDED,"Snapshot submit failed. Exceeded max submit retries of "+this.maxRetries)}}},961:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isNullOrUndefined=function(t){return null==t}},127:e=>{e.exports=t},872:(t,e)=>{var s;Object.defineProperty(e,"__esModule",{value:!0}),e.OTError=e.ERROR_CODES=void 0,function(t){t[t.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT=0]="ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",t[t.ERR_APPLY_SNAPSHOT_NOT_PROVIDED=1]="ERR_APPLY_SNAPSHOT_NOT_PROVIDED",t[t.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW=2]="ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",t[t.ERR_DOC_MISSING_VERSION=3]="ERR_DOC_MISSING_VERSION",t[t.ERR_DOC_ALREADY_CREATED=4]="ERR_DOC_ALREADY_CREATED",t[t.ERR_DOC_DOES_NOT_EXIST=5]="ERR_DOC_DOES_NOT_EXIST",t[t.ERR_DOC_TYPE_NOT_RECOGNIZED=6]="ERR_DOC_TYPE_NOT_RECOGNIZED",t[t.ERR_DOC_WAS_DELETED=7]="ERR_DOC_WAS_DELETED",t[t.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION=8]="ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",t[t.ERR_MAX_SUBMIT_RETRIES_EXCEEDED=9]="ERR_MAX_SUBMIT_RETRIES_EXCEEDED",t[t.ERR_MAX_SUBMIT_SNAPSHOT_RETRIES_EXCEEDED=10]="ERR_MAX_SUBMIT_SNAPSHOT_RETRIES_EXCEEDED",t[t.ERR_MESSAGE_BADLY_FORMED=11]="ERR_MESSAGE_BADLY_FORMED",t[t.ERR_MILESTONE_ARGUMENT_INVALID=12]="ERR_MILESTONE_ARGUMENT_INVALID",t[t.ERR_OP_ALREADY_SUBMITTED=13]="ERR_OP_ALREADY_SUBMITTED",t[t.ERR_OP_SUBMIT_REJECTED=14]="ERR_OP_SUBMIT_REJECTED",t[t.ERR_PENDING_OP_REMOVED_BY_OP_SUBMIT_REJECTED=15]="ERR_PENDING_OP_REMOVED_BY_OP_SUBMIT_REJECTED",t[t.ERR_HARD_ROLLBACK_FETCH_FAILED=16]="ERR_HARD_ROLLBACK_FETCH_FAILED",t[t.ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM=17]="ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",t[t.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM=18]="ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",t[t.ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT=19]="ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",t[t.ERR_OT_OP_BADLY_FORMED=20]="ERR_OT_OP_BADLY_FORMED",t[t.ERR_OT_OP_NOT_APPLIED=21]="ERR_OT_OP_NOT_APPLIED",t[t.ERR_OT_OP_NOT_PROVIDED=22]="ERR_OT_OP_NOT_PROVIDED",t[t.ERR_OT_OP_TRANSFORM_FAILED=23]="ERR_OT_OP_TRANSFORM_FAILED",t[t.ERR_SNAPSHOT_READ_SILENT_REJECTION=24]="ERR_SNAPSHOT_READ_SILENT_REJECTION",t[t.ERR_SNAPSHOT_READS_REJECTED=25]="ERR_SNAPSHOT_READS_REJECTED",t[t.ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND=26]="ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",t[t.ERR_UNKNOWN_ERROR=27]="ERR_UNKNOWN_ERROR",t[t.ERR_INFLIGHT_OP_MISSING=28]="ERR_INFLIGHT_OP_MISSING"}(s||(e.ERROR_CODES=s={}));class r extends Error{constructor(t,e){super(e),this.code=t,this.name="OTError",this.code=t}}e.OTError=r,r.CODES=s},660:function(t,e,s){var r=this&&this.__createBinding||(Object.create?function(t,e,s,r){void 0===r&&(r=s);var n=Object.getOwnPropertyDescriptor(e,s);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[s]}}),Object.defineProperty(t,r,n)}:function(t,e,s,r){void 0===r&&(r=s),t[r]=e[s]}),n=this&&this.__exportStar||function(t,e){for(var s in t)"default"===s||Object.prototype.hasOwnProperty.call(e,s)||r(e,t,s)};Object.defineProperty(e,"__esModule",{value:!0}),e.OT_DOC_MESSAGE_TYPE=void 0,n(s(872),e),n(s(549),e),n(s(712),e),n(s(802),e),e.OT_DOC_MESSAGE_TYPE="ot-doc"},549:(t,e)=>{var s;Object.defineProperty(e,"__esModule",{value:!0}),e.MessageActions=void 0,function(t){t.fetch="fetch",t.fetchOps="fetchOps",t.fetchHistorySnapshot="fetchHistorySnapshot",t.subscribe="subscribe",t.unsubscribe="unsubscribe",t.op="op"}(s||(e.MessageActions=s={}))},712:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TypesManager=void 0;const s={uri:"default",create:()=>{throw new Error("Function not implemented.")},apply:()=>{throw new Error("Function not implemented.")},transform:()=>{throw new Error("Function not implemented.")}};class r{static get defaultType(){return s}static register(t){t.uri&&(r.map[t.uri]=t),t.name&&(r.map[t.name]=t)}static getType(t){return r.map[t]}}e.TypesManager=r,r.map={},r.register(s)},802:(t,e)=>{function s(t,e,s){let r=!1;return t.forEach((function(t){t&&(t(e,s),r=!0)})),r}function r(t){return t?JSON.parse(JSON.stringify(t)):t}Object.defineProperty(e,"__esModule",{value:!0}),e.util=e.nextTick=e.MAX_SAFE_INTEGER=void 0,e.callEach=s,e.clone=r,e.MAX_SAFE_INTEGER=9007199254740991,e.nextTick=function(t){if("undefined"!=typeof process&&process.nextTick)return process.nextTick(t);setTimeout((function(){t()}))},e.util={MAX_SAFE_INTEGER:e.MAX_SAFE_INTEGER,callEach:s,nextTick:e.nextTick,clone:r}}},s={};function r(t){var n=s[t];if(void 0!==n)return n.exports;var i=s[t]={exports:{}};return e[t].call(i.exports,i,i.exports,r),i.exports}var n={};return(()=>{var t=n;Object.defineProperty(t,"__esModule",{value:!0}),t.documentFeature=t.MemoryDb=t.Db=t.DocumentServices=t.TypesManager=void 0,r(259),r(36);const e=r(660);Object.defineProperty(t,"TypesManager",{enumerable:!0,get:function(){return e.TypesManager}});const s=r(89);Object.defineProperty(t,"DocumentServices",{enumerable:!0,get:function(){return s.DocumentServices}});const i=r(619);Object.defineProperty(t,"Db",{enumerable:!0,get:function(){return i.Db}});const o=r(985);Object.defineProperty(t,"MemoryDb",{enumerable:!0,get:function(){return o.MemoryDb}});const a=r(763);Object.defineProperty(t,"documentFeature",{enumerable:!0,get:function(){return a.documentFeature}})})(),n})()));
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@grapecity-software/js-collaboration-ot",
3
+ "version": "18.0.0",
4
+ "type": "commonjs",
5
+ "main": "./dist/index.js",
6
+ "exports": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./wrapper.mjs",
9
+ "require": "./dist/index.js"
10
+ },
11
+ "keywords": [
12
+ "js-collaboration-ot",
13
+ "js-collaboration",
14
+ "collaboration",
15
+ "spread",
16
+ "sheet",
17
+ "javascript",
18
+ "excel",
19
+ "spreadjs"
20
+ ],
21
+ "author": {
22
+ "email": "info.xa@grapecity.com",
23
+ "name": "GrapeCity Software inc"
24
+ },
25
+ "license": "Commercial",
26
+ "description": "SpreadJS Collaboration plugin",
27
+ "dependencies": {
28
+ "@grapecity-software/js-collaboration": "18.0.0"
29
+ },
30
+ "homepage": "http://www.grapecity.com.cn/"
31
+ }
package/wrapper.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import * as OTModule from "./dist/index.js";
2
+ import OT from "./dist/index.js";
3
+ const { TypesManager, DocumentServices, Db, MemoryDb, documentFeature } = { ...(OT ?? {}), ...OTModule };
4
+ export { OT as default, TypesManager, DocumentServices, Db, MemoryDb, documentFeature };