@veltdev/quill-crdt 1.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/esm/index.js ADDED
@@ -0,0 +1,1214 @@
1
+ import { createVeltStore } from '@veltdev/crdt';
2
+ import { QuillBinding } from 'y-quill';
3
+ import * as Y from 'yjs';
4
+
5
+ // POLICY: Every function/method in this file MUST be wrapped in try/catch.
6
+ // The package must NEVER throw an exception to the consumer's code.
7
+ const LOG_PREFIX = '[VeltQuillCRDT]';
8
+ /**
9
+ * Log an error/warning — only visible when debug mode is enabled
10
+ * via sessionStorage.setItem('forceCrdtDebugMode', 'true').
11
+ */
12
+ function logError(message, error) {
13
+ try {
14
+ if (typeof sessionStorage !== 'undefined' &&
15
+ sessionStorage.getItem('forceCrdtDebugMode')) {
16
+ console.warn(`${LOG_PREFIX} ${message}`, error !== undefined ? error : '');
17
+ }
18
+ }
19
+ catch {
20
+ // sessionStorage may not be available (SSR / iframe restrictions)
21
+ }
22
+ }
23
+
24
+ // POLICY: Every function/method in this file MUST be wrapped in try/catch.
25
+ // The package must NEVER throw an exception to the consumer's code.
26
+ const CONFIG_MAP_KEY = 'veltConfig';
27
+ const INITIALIZED_FLAG = '__docInitialized';
28
+ const LEGACY_FLAG = 'hasContentSet';
29
+ function normalizeText(value) {
30
+ try {
31
+ if (typeof value !== 'string')
32
+ return '';
33
+ return value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
34
+ }
35
+ catch (error) {
36
+ logError('Failed to normalize text', error);
37
+ return '';
38
+ }
39
+ }
40
+ function getDeltaOps(value) {
41
+ try {
42
+ if (typeof value === 'string') {
43
+ const text = normalizeText(value);
44
+ return text ? [{ insert: text }] : [];
45
+ }
46
+ const raw = Array.isArray(value) ? value : value?.ops;
47
+ if (!Array.isArray(raw))
48
+ return [];
49
+ return raw.map((op) => ({
50
+ ...op,
51
+ attributes: op.attributes ? { ...op.attributes } : undefined,
52
+ insert: typeof op.insert === 'object' && op.insert !== null ? { ...op.insert } : op.insert,
53
+ }));
54
+ }
55
+ catch (error) {
56
+ logError('Failed to read Quill Delta operations', error);
57
+ return [];
58
+ }
59
+ }
60
+ function normalizeDocumentDelta(value) {
61
+ try {
62
+ const ops = getDeltaOps(value).filter((op) => op.insert !== undefined);
63
+ if (ops.length === 0)
64
+ return [];
65
+ const last = ops[ops.length - 1];
66
+ if (last && last.attributes === undefined && typeof last.insert === 'string' && last.insert.endsWith('\n')) {
67
+ const normalized = last.insert.replace(/\n+$/, '');
68
+ if (normalized)
69
+ last.insert = normalized;
70
+ else
71
+ ops.pop();
72
+ }
73
+ return ops;
74
+ }
75
+ catch (error) {
76
+ logError('Failed to normalize Quill document Delta', error);
77
+ return [];
78
+ }
79
+ }
80
+ function replaceYTextWithDelta(doc, ytext, value, origin) {
81
+ try {
82
+ const ops = normalizeDocumentDelta(value);
83
+ doc.transact(() => {
84
+ try {
85
+ if (ytext.length > 0)
86
+ ytext.delete(0, ytext.length);
87
+ if (ops.length > 0)
88
+ ytext.applyDelta(ops);
89
+ }
90
+ catch (error) {
91
+ logError('Failed inside Quill Delta replacement transaction', error);
92
+ }
93
+ }, origin);
94
+ return true;
95
+ }
96
+ catch (error) {
97
+ logError('Failed to replace Y.Text with Quill Delta', error);
98
+ return false;
99
+ }
100
+ }
101
+ function applyInitialContent(doc, ytext, initialContent, force = false) {
102
+ try {
103
+ const configMap = doc.getMap(CONFIG_MAP_KEY);
104
+ if (!force) {
105
+ if (configMap.get(INITIALIZED_FLAG) || configMap.get(LEGACY_FLAG))
106
+ return false;
107
+ if (ytext.length > 0) {
108
+ configMap.set(INITIALIZED_FLAG, true);
109
+ return false;
110
+ }
111
+ }
112
+ doc.transact(() => {
113
+ try {
114
+ if (ytext.length > 0)
115
+ ytext.delete(0, ytext.length);
116
+ const ops = normalizeDocumentDelta(initialContent);
117
+ if (ops.length > 0)
118
+ ytext.applyDelta(ops);
119
+ configMap.set(INITIALIZED_FLAG, true);
120
+ }
121
+ catch (error) {
122
+ logError('Failed inside initial Quill content transaction', error);
123
+ }
124
+ }, 'velt-quill-initial-content');
125
+ return true;
126
+ }
127
+ catch (error) {
128
+ logError('Failed to apply initial Quill content', error);
129
+ return false;
130
+ }
131
+ }
132
+ function normalizeRange(range, maxLength) {
133
+ try {
134
+ if (!range)
135
+ return null;
136
+ const index = Math.max(0, Math.min(Number(range.index) || 0, Math.max(0, maxLength)));
137
+ const length = Math.max(0, Math.min(Number(range.length) || 0, Math.max(0, maxLength - index)));
138
+ return { index, length };
139
+ }
140
+ catch (error) {
141
+ logError('Failed to normalize Quill range', error);
142
+ return null;
143
+ }
144
+ }
145
+
146
+ // POLICY: Every function/method in this file MUST be wrapped in try/catch.
147
+ // The package must NEVER throw an exception to the consumer's code.
148
+ const CONTENT_KEY = 'content';
149
+ const DEFAULT_EDITOR_ID = 'velt-quill-crdt-document';
150
+ const DEFAULT_CURSOR_COLOR = '#2563eb';
151
+ class CollaborationManager {
152
+ constructor(config) {
153
+ this.store = null;
154
+ this.provider = null;
155
+ this.binding = null;
156
+ this.undoManager = null;
157
+ this.editor = null;
158
+ this.initializedValue = false;
159
+ this.syncedValue = false;
160
+ this.statusValue = 'connecting';
161
+ this.lastFlushReasonValue = null;
162
+ this.statusListeners = new Set();
163
+ this.syncedListeners = new Set();
164
+ this.awarenessListeners = new Set();
165
+ this.cleanupFns = [];
166
+ try {
167
+ this.config = this.normalizeConfig(config);
168
+ this.editor = this.config.editor ?? null;
169
+ }
170
+ catch (error) {
171
+ logError('Failed to construct CollaborationManager', error);
172
+ this.config = this.normalizeConfig({});
173
+ }
174
+ }
175
+ async initialize() {
176
+ try {
177
+ if (this.initializedValue)
178
+ return;
179
+ try {
180
+ await this.setupStoreAndContent();
181
+ }
182
+ catch (error) {
183
+ if (this.isCorruptionError(error)) {
184
+ await this.tryRecoverFromCorruption();
185
+ }
186
+ else {
187
+ throw error;
188
+ }
189
+ }
190
+ if (!this.store)
191
+ return;
192
+ this.initializedValue = true;
193
+ if (this.editor)
194
+ this.bindEditor(this.editor);
195
+ this.setupUndoManager();
196
+ this.updateProviderState();
197
+ this.emitAwareness();
198
+ }
199
+ catch (error) {
200
+ this.reportError('Failed to initialize collaboration', error);
201
+ }
202
+ }
203
+ createStore() {
204
+ const initialText = typeof this.config.initialContent === 'string'
205
+ ? normalizeText(this.config.initialContent)
206
+ : undefined;
207
+ return createVeltStore({
208
+ id: this.config.editorId,
209
+ type: 'text',
210
+ contentKey: CONTENT_KEY,
211
+ source: 'quill',
212
+ veltClient: this.config.veltClient,
213
+ userId: this.readUser().userId,
214
+ debounceMs: this.config.debounceMs,
215
+ initialValue: initialText,
216
+ forceResetInitialContent: false,
217
+ enablePresence: true,
218
+ });
219
+ }
220
+ /** Create the Store, wire listeners/awareness, and apply initial content. */
221
+ async setupStoreAndContent() {
222
+ this.store = await this.createStore();
223
+ if (!this.store) {
224
+ this.reportError('Velt CRDT Store initialization returned no Store');
225
+ return;
226
+ }
227
+ this.provider = this.store.getProvider();
228
+ this.setupProviderListeners();
229
+ this.setupAwareness();
230
+ const ytext = this.getText();
231
+ const doc = this.getDoc();
232
+ if (ytext && doc && this.config.initialContent !== undefined) {
233
+ if (this.config.forceResetInitialContent) {
234
+ replaceYTextWithDelta(doc, ytext, this.config.initialContent, this);
235
+ }
236
+ else if (typeof this.config.initialContent !== 'string') {
237
+ applyInitialContent(doc, ytext, this.config.initialContent);
238
+ }
239
+ }
240
+ }
241
+ /** Check if an error is a known Yjs corruption error. */
242
+ isCorruptionError(error) {
243
+ try {
244
+ const msg = String(error);
245
+ return msg.includes('contentRefs') || msg.includes('Unexpected end of array');
246
+ }
247
+ catch {
248
+ return false;
249
+ }
250
+ }
251
+ /**
252
+ * Attempt recovery from Yjs corruption: tear the store down and rebuild it
253
+ * once. If recovery fails, the manager enters degraded state (no throw).
254
+ */
255
+ async tryRecoverFromCorruption() {
256
+ logError('Encountered Yjs corruption error, attempting recovery');
257
+ try {
258
+ for (const cleanup of this.cleanupFns.splice(0)) {
259
+ try {
260
+ cleanup();
261
+ }
262
+ catch { /* cleanup is best-effort */ }
263
+ }
264
+ try {
265
+ this.store?.destroy();
266
+ }
267
+ catch { /* cleanup is best-effort */ }
268
+ this.store = null;
269
+ this.provider = null;
270
+ await this.setupStoreAndContent();
271
+ }
272
+ catch (error) {
273
+ logError('Recovery failed, editor will function in degraded state', error);
274
+ this.reportError('Failed to recover from Yjs corruption', error);
275
+ }
276
+ }
277
+ destroy() {
278
+ try {
279
+ this.detachEditor();
280
+ for (const cleanup of this.cleanupFns.splice(0)) {
281
+ try {
282
+ cleanup();
283
+ }
284
+ catch { /* cleanup is best-effort */ }
285
+ }
286
+ try {
287
+ this.undoManager?.destroy();
288
+ }
289
+ catch { /* cleanup is best-effort */ }
290
+ this.undoManager = null;
291
+ try {
292
+ this.getAwareness()?.setLocalState(null);
293
+ }
294
+ catch { /* cleanup is best-effort */ }
295
+ try {
296
+ this.store?.destroy();
297
+ }
298
+ catch { /* cleanup is best-effort */ }
299
+ this.store = null;
300
+ this.provider = null;
301
+ this.initializedValue = false;
302
+ this.syncedValue = false;
303
+ this.statusValue = 'disconnected';
304
+ this.statusListeners.clear();
305
+ this.syncedListeners.clear();
306
+ this.awarenessListeners.clear();
307
+ }
308
+ catch (error) {
309
+ logError('Failed to destroy collaboration', error);
310
+ }
311
+ }
312
+ attachEditor(editor, options = {}) {
313
+ try {
314
+ if (!editor)
315
+ return false;
316
+ if (options.destroyExisting !== false)
317
+ this.detachEditor();
318
+ this.editor = editor;
319
+ if (this.initializedValue)
320
+ this.bindEditor(editor);
321
+ return true;
322
+ }
323
+ catch (error) {
324
+ this.reportError('Failed to attach Quill editor', error);
325
+ return false;
326
+ }
327
+ }
328
+ detachEditor() {
329
+ try {
330
+ try {
331
+ this.binding?.destroy();
332
+ }
333
+ catch { /* cleanup is best-effort */ }
334
+ this.binding = null;
335
+ this.editor = null;
336
+ this.rebuildUndoManager();
337
+ }
338
+ catch (error) {
339
+ logError('Failed to detach Quill editor', error);
340
+ }
341
+ }
342
+ get initialized() {
343
+ try {
344
+ return this.initializedValue;
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ }
350
+ get synced() {
351
+ try {
352
+ return this.syncedValue;
353
+ }
354
+ catch {
355
+ return false;
356
+ }
357
+ }
358
+ get status() {
359
+ try {
360
+ return this.statusValue;
361
+ }
362
+ catch {
363
+ return 'disconnected';
364
+ }
365
+ }
366
+ get editorAttached() {
367
+ try {
368
+ return this.editor !== null;
369
+ }
370
+ catch {
371
+ return false;
372
+ }
373
+ }
374
+ getCollaborationPrimitives() {
375
+ try {
376
+ return {
377
+ store: this.store,
378
+ ytext: this.getText(),
379
+ awareness: this.getAwareness(),
380
+ undoManager: this.undoManager,
381
+ doc: this.getDoc(),
382
+ provider: this.provider,
383
+ binding: this.binding,
384
+ };
385
+ }
386
+ catch (error) {
387
+ logError('Failed to expose collaboration primitives', error);
388
+ return { store: null, ytext: null, awareness: null, undoManager: null, doc: null, provider: null, binding: null };
389
+ }
390
+ }
391
+ getStore() {
392
+ try {
393
+ return this.store;
394
+ }
395
+ catch (error) {
396
+ logError('Failed to get Store', error);
397
+ return null;
398
+ }
399
+ }
400
+ getProvider() {
401
+ try {
402
+ return this.provider;
403
+ }
404
+ catch (error) {
405
+ logError('Failed to get provider', error);
406
+ return null;
407
+ }
408
+ }
409
+ getValue() {
410
+ try {
411
+ return this.getText()?.toString() ?? '';
412
+ }
413
+ catch (error) {
414
+ logError('Failed to get text', error);
415
+ return '';
416
+ }
417
+ }
418
+ getTextValue() {
419
+ try {
420
+ return this.getValue();
421
+ }
422
+ catch (error) {
423
+ logError('Failed to get text value', error);
424
+ return '';
425
+ }
426
+ }
427
+ getContents() {
428
+ try {
429
+ const ops = [...(this.getText()?.toDelta() ?? [])];
430
+ const last = ops[ops.length - 1];
431
+ const endsWithNewline = typeof last?.insert === 'string' && last.insert.endsWith('\n');
432
+ if (!endsWithNewline)
433
+ ops.push({ insert: '\n' });
434
+ return { ops };
435
+ }
436
+ catch (error) {
437
+ logError('Failed to get Quill contents', error);
438
+ return { ops: [{ insert: '\n' }] };
439
+ }
440
+ }
441
+ getYTextDelta() {
442
+ try {
443
+ return { ops: [...(this.getText()?.toDelta() ?? [])] };
444
+ }
445
+ catch (error) {
446
+ logError('Failed to get Y.Text Delta', error);
447
+ return { ops: [] };
448
+ }
449
+ }
450
+ getSemanticHTML() {
451
+ try {
452
+ return this.editor?.getSemanticHTML() ?? '';
453
+ }
454
+ catch (error) {
455
+ logError('Failed to get semantic HTML', error);
456
+ return '';
457
+ }
458
+ }
459
+ setValue(value, reason = 'set-text') {
460
+ try {
461
+ return this.setContents(normalizeText(value), reason);
462
+ }
463
+ catch (error) {
464
+ this.reportError('Failed to set text', error);
465
+ return false;
466
+ }
467
+ }
468
+ setContents(value, reason = 'set-contents') {
469
+ try {
470
+ const doc = this.getDoc();
471
+ const ytext = this.getText();
472
+ if (!doc || !ytext)
473
+ return false;
474
+ const changed = replaceYTextWithDelta(doc, ytext, value, this);
475
+ if (changed)
476
+ this.lastFlushReasonValue = reason;
477
+ return changed;
478
+ }
479
+ catch (error) {
480
+ this.reportError('Failed to set Quill contents', error);
481
+ return false;
482
+ }
483
+ }
484
+ updateContents(delta, reason = 'update-contents') {
485
+ try {
486
+ const doc = this.getDoc();
487
+ const ytext = this.getText();
488
+ if (!doc || !ytext)
489
+ return false;
490
+ const ops = getDeltaOps(delta);
491
+ doc.transact(() => {
492
+ try {
493
+ ytext.applyDelta(ops);
494
+ }
495
+ catch (error) {
496
+ logError('Failed inside Delta update', error);
497
+ }
498
+ }, this);
499
+ this.lastFlushReasonValue = reason;
500
+ return true;
501
+ }
502
+ catch (error) {
503
+ this.reportError('Failed to update Quill contents', error);
504
+ return false;
505
+ }
506
+ }
507
+ insertText(index, text, formats = {}) {
508
+ try {
509
+ const doc = this.getDoc();
510
+ const ytext = this.getText();
511
+ if (!doc || !ytext)
512
+ return false;
513
+ const at = Math.max(0, Math.min(Number(index) || 0, ytext.length));
514
+ const value = normalizeText(text);
515
+ doc.transact(() => {
516
+ try {
517
+ if (value)
518
+ ytext.insert(at, value, formats);
519
+ }
520
+ catch (error) {
521
+ logError('Failed inside text insert', error);
522
+ }
523
+ }, this);
524
+ this.lastFlushReasonValue = 'insert-text';
525
+ return true;
526
+ }
527
+ catch (error) {
528
+ this.reportError('Failed to insert text', error);
529
+ return false;
530
+ }
531
+ }
532
+ deleteText(index, length) {
533
+ try {
534
+ const doc = this.getDoc();
535
+ const ytext = this.getText();
536
+ if (!doc || !ytext)
537
+ return false;
538
+ const range = normalizeRange({ index, length }, ytext.length);
539
+ if (!range)
540
+ return false;
541
+ doc.transact(() => {
542
+ try {
543
+ if (range.length > 0)
544
+ ytext.delete(range.index, range.length);
545
+ }
546
+ catch (error) {
547
+ logError('Failed inside text delete', error);
548
+ }
549
+ }, this);
550
+ this.lastFlushReasonValue = 'delete-text';
551
+ return true;
552
+ }
553
+ catch (error) {
554
+ this.reportError('Failed to delete text', error);
555
+ return false;
556
+ }
557
+ }
558
+ insertEmbed(index, type, value, attributes = {}) {
559
+ try {
560
+ const doc = this.getDoc();
561
+ const ytext = this.getText();
562
+ if (!doc || !ytext || !type)
563
+ return false;
564
+ const at = Math.max(0, Math.min(Number(index) || 0, ytext.length));
565
+ doc.transact(() => {
566
+ try {
567
+ ytext.insertEmbed(at, { [type]: value }, attributes);
568
+ }
569
+ catch (error) {
570
+ logError('Failed inside embed insert', error);
571
+ }
572
+ }, this);
573
+ this.lastFlushReasonValue = 'insert-embed';
574
+ return true;
575
+ }
576
+ catch (error) {
577
+ this.reportError('Failed to insert embed', error);
578
+ return false;
579
+ }
580
+ }
581
+ formatText(index, length, formats) {
582
+ try {
583
+ const doc = this.getDoc();
584
+ const ytext = this.getText();
585
+ if (!doc || !ytext || !formats || typeof formats !== 'object')
586
+ return false;
587
+ const range = normalizeRange({ index, length }, ytext.length);
588
+ if (!range || range.length === 0)
589
+ return false;
590
+ doc.transact(() => {
591
+ try {
592
+ ytext.format(range.index, range.length, formats);
593
+ }
594
+ catch (error) {
595
+ logError('Failed inside text format', error);
596
+ }
597
+ }, this);
598
+ this.lastFlushReasonValue = 'format-text';
599
+ return true;
600
+ }
601
+ catch (error) {
602
+ this.reportError('Failed to format text', error);
603
+ return false;
604
+ }
605
+ }
606
+ highlightRange(index, length, color = '#fef08a') {
607
+ try {
608
+ return this.formatText(index, length, { background: color });
609
+ }
610
+ catch (error) {
611
+ this.reportError('Failed to highlight text', error);
612
+ return false;
613
+ }
614
+ }
615
+ clearHighlight(index, length) {
616
+ try {
617
+ return this.formatText(index, length, { background: null });
618
+ }
619
+ catch (error) {
620
+ this.reportError('Failed to clear highlight', error);
621
+ return false;
622
+ }
623
+ }
624
+ getFormat(index, length) {
625
+ try {
626
+ if (this.editor)
627
+ return this.editor.getFormat(index, length);
628
+ const ytext = this.getText();
629
+ if (!ytext)
630
+ return {};
631
+ const at = Math.max(0, Math.min(Number(index) || 0, Math.max(0, ytext.length - 1)));
632
+ const delta = ytext.toDelta();
633
+ const op = delta.find((_item, opIndex, all) => {
634
+ try {
635
+ const start = all.slice(0, opIndex).reduce((total, entry) => total + (typeof entry.insert === 'string' ? entry.insert.length : 1), 0);
636
+ const size = typeof _item.insert === 'string' ? _item.insert.length : 1;
637
+ return at >= start && at < start + size;
638
+ }
639
+ catch {
640
+ return false;
641
+ }
642
+ });
643
+ return { ...(op?.attributes ?? {}) };
644
+ }
645
+ catch (error) {
646
+ logError('Failed to get text format', error);
647
+ return {};
648
+ }
649
+ }
650
+ flushEditorToStore(reason = 'manual') {
651
+ try {
652
+ if (!this.editor)
653
+ return false;
654
+ return this.setContents(this.editor.getContents(), reason);
655
+ }
656
+ catch (error) {
657
+ this.reportError('Failed to flush Quill editor', error);
658
+ return false;
659
+ }
660
+ }
661
+ async forceReset(initialContent = '') {
662
+ try {
663
+ const changed = this.setContents(initialContent, 'force-reset');
664
+ if (changed)
665
+ this.clearUndoHistory();
666
+ return changed;
667
+ }
668
+ catch (error) {
669
+ this.reportError('Failed to force reset content', error);
670
+ return false;
671
+ }
672
+ }
673
+ setLocalSelection(range) {
674
+ try {
675
+ const awareness = this.getAwareness();
676
+ const ytext = this.getText();
677
+ if (!awareness || !ytext)
678
+ return false;
679
+ const normalized = range ? normalizeRange(range, ytext.length) : null;
680
+ if (range && !normalized)
681
+ return false;
682
+ if (this.editor && this.binding) {
683
+ // y-quill owns the awareness `cursor` field. Drive it through the
684
+ // editor selection so there is a single writer (review QL-18).
685
+ try {
686
+ if (normalized)
687
+ this.editor.setSelection(normalized.index, normalized.length, 'user');
688
+ else
689
+ this.editor.setSelection(null, 'user');
690
+ }
691
+ catch (error) {
692
+ logError('Failed to set editor selection', error);
693
+ }
694
+ }
695
+ else if (normalized) {
696
+ const anchor = Y.createRelativePositionFromTypeIndex(ytext, normalized.index);
697
+ const head = Y.createRelativePositionFromTypeIndex(ytext, normalized.index + normalized.length);
698
+ awareness.setLocalStateField('cursor', { anchor, head });
699
+ }
700
+ else {
701
+ awareness.setLocalStateField('cursor', null);
702
+ }
703
+ awareness.setLocalStateField('selection', normalized ? {
704
+ index: normalized.index,
705
+ length: normalized.length,
706
+ kind: normalized.length > 0 ? 'selection' : 'cursor',
707
+ } : null);
708
+ return true;
709
+ }
710
+ catch (error) {
711
+ this.reportError('Failed to publish local selection', error);
712
+ return false;
713
+ }
714
+ }
715
+ publishCurrentSelection() {
716
+ try {
717
+ return this.setLocalSelection(this.editor?.getSelection() ?? null);
718
+ }
719
+ catch (error) {
720
+ this.reportError('Failed to publish current selection', error);
721
+ return false;
722
+ }
723
+ }
724
+ getRemoteSelections() {
725
+ try {
726
+ const awareness = this.getAwareness();
727
+ const doc = this.getDoc();
728
+ const ytext = this.getText();
729
+ if (!awareness || !doc || !ytext)
730
+ return [];
731
+ const result = [];
732
+ awareness.getStates().forEach((state, clientId) => {
733
+ try {
734
+ if (clientId === doc.clientID || !state?.cursor?.anchor || !state?.cursor?.head)
735
+ return;
736
+ const anchor = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(state.cursor.anchor), doc);
737
+ const head = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(state.cursor.head), doc);
738
+ if (!anchor || !head || anchor.type !== ytext || head.type !== ytext)
739
+ return;
740
+ const user = state.user ?? {};
741
+ result.push({
742
+ clientId,
743
+ kind: Math.abs(head.index - anchor.index) > 0 ? 'selection' : 'cursor',
744
+ index: Math.min(anchor.index, head.index),
745
+ length: Math.abs(head.index - anchor.index),
746
+ userId: user.userId,
747
+ name: user.name || `User ${clientId}`,
748
+ email: user.email,
749
+ color: user.color || DEFAULT_CURSOR_COLOR,
750
+ colorLight: user.colorLight,
751
+ });
752
+ }
753
+ catch (error) {
754
+ logError('Failed to decode a remote Quill selection', error);
755
+ }
756
+ });
757
+ return result;
758
+ }
759
+ catch (error) {
760
+ logError('Failed to read remote selections', error);
761
+ return [];
762
+ }
763
+ }
764
+ onStatusChange(callback) {
765
+ try {
766
+ this.statusListeners.add(callback);
767
+ callback(this.statusValue);
768
+ }
769
+ catch (error) {
770
+ logError('Failed to subscribe to status', error);
771
+ }
772
+ return () => { try {
773
+ this.statusListeners.delete(callback);
774
+ }
775
+ catch { /* no-op */ } };
776
+ }
777
+ onSynced(callback) {
778
+ try {
779
+ this.syncedListeners.add(callback);
780
+ callback(this.syncedValue);
781
+ }
782
+ catch (error) {
783
+ logError('Failed to subscribe to sync state', error);
784
+ }
785
+ return () => { try {
786
+ this.syncedListeners.delete(callback);
787
+ }
788
+ catch { /* no-op */ } };
789
+ }
790
+ onRemoteSelectionsChange(callback) {
791
+ try {
792
+ this.awarenessListeners.add(callback);
793
+ callback(this.getRemoteSelections());
794
+ }
795
+ catch (error) {
796
+ logError('Failed to subscribe to selections', error);
797
+ }
798
+ return () => { try {
799
+ this.awarenessListeners.delete(callback);
800
+ }
801
+ catch { /* no-op */ } };
802
+ }
803
+ getUndoManager() {
804
+ try {
805
+ return this.undoManager;
806
+ }
807
+ catch (error) {
808
+ logError('Failed to get undo manager', error);
809
+ return null;
810
+ }
811
+ }
812
+ undo() {
813
+ try {
814
+ if (!this.undoManager?.canUndo())
815
+ return false;
816
+ this.undoManager.undo();
817
+ this.lastFlushReasonValue = 'undo';
818
+ return true;
819
+ }
820
+ catch (error) {
821
+ this.reportError('Failed to undo', error);
822
+ return false;
823
+ }
824
+ }
825
+ redo() {
826
+ try {
827
+ if (!this.undoManager?.canRedo())
828
+ return false;
829
+ this.undoManager.redo();
830
+ this.lastFlushReasonValue = 'redo';
831
+ return true;
832
+ }
833
+ catch (error) {
834
+ this.reportError('Failed to redo', error);
835
+ return false;
836
+ }
837
+ }
838
+ clearUndoHistory() {
839
+ try {
840
+ this.undoManager?.clear();
841
+ }
842
+ catch (error) {
843
+ logError('Failed to clear undo history', error);
844
+ }
845
+ }
846
+ async saveVersion(name) {
847
+ try {
848
+ this.flushEditorToStore('save-version');
849
+ return await this.store?.saveVersion(name || 'Checkpoint') ?? '';
850
+ }
851
+ catch (error) {
852
+ this.reportError('Failed to save version', error);
853
+ return '';
854
+ }
855
+ }
856
+ async getVersions() {
857
+ try {
858
+ return await this.store?.getVersions() ?? [];
859
+ }
860
+ catch (error) {
861
+ this.reportError('Failed to get versions', error);
862
+ return [];
863
+ }
864
+ }
865
+ async getVersionById(versionId) {
866
+ try {
867
+ return await this.store?.getVersionById(versionId) ?? null;
868
+ }
869
+ catch (error) {
870
+ this.reportError('Failed to get version', error);
871
+ return null;
872
+ }
873
+ }
874
+ async setStateFromVersion(version) {
875
+ try {
876
+ const doc = this.getDoc();
877
+ const ytext = this.getText();
878
+ const state = version?.state;
879
+ if (!doc || !ytext || !state)
880
+ return false;
881
+ const tempDoc = new Y.Doc();
882
+ try {
883
+ const update = state instanceof Uint8Array ? state : new Uint8Array(state);
884
+ Y.applyUpdate(tempDoc, update);
885
+ const source = tempDoc.getText(CONTENT_KEY);
886
+ const restored = replaceYTextWithDelta(doc, ytext, source.toDelta(), this);
887
+ if (restored) {
888
+ this.lastFlushReasonValue = 'restore-version';
889
+ this.clearUndoHistory();
890
+ }
891
+ return restored;
892
+ }
893
+ finally {
894
+ try {
895
+ tempDoc.destroy();
896
+ }
897
+ catch { /* cleanup is best-effort */ }
898
+ }
899
+ }
900
+ catch (error) {
901
+ this.reportError('Failed to apply version', error);
902
+ return false;
903
+ }
904
+ }
905
+ async restoreVersion(versionId) {
906
+ try {
907
+ const version = await this.getVersionById(versionId);
908
+ if (!version)
909
+ return false;
910
+ return await this.setStateFromVersion(version);
911
+ }
912
+ catch (error) {
913
+ this.reportError('Failed to restore version', error);
914
+ return false;
915
+ }
916
+ }
917
+ getStats() {
918
+ try {
919
+ return {
920
+ initialized: this.initializedValue,
921
+ synced: this.syncedValue,
922
+ status: this.statusValue,
923
+ hasEditor: this.editor !== null,
924
+ hasStore: this.store !== null,
925
+ hasBinding: this.binding !== null,
926
+ remoteSelectionCount: this.getRemoteSelections().length,
927
+ textLength: this.getText()?.length ?? 0,
928
+ deltaOpCount: this.getText()?.toDelta().length ?? 0,
929
+ lastFlushReason: this.lastFlushReasonValue,
930
+ };
931
+ }
932
+ catch (error) {
933
+ logError('Failed to collect collaboration stats', error);
934
+ return { initialized: false, synced: false, status: 'disconnected', hasEditor: false, hasStore: false, hasBinding: false, remoteSelectionCount: 0, textLength: 0, deltaOpCount: 0, lastFlushReason: null };
935
+ }
936
+ }
937
+ bindEditor(editor) {
938
+ try {
939
+ const ytext = this.getText();
940
+ if (!ytext)
941
+ return;
942
+ try {
943
+ this.binding?.destroy();
944
+ }
945
+ catch { /* cleanup is best-effort */ }
946
+ this.binding = new QuillBinding(ytext, editor, this.getAwareness() ?? undefined);
947
+ this.rebuildUndoManager();
948
+ }
949
+ catch (error) {
950
+ this.reportError('Failed to create y-quill binding', error);
951
+ }
952
+ }
953
+ setupUndoManager() {
954
+ try {
955
+ this.rebuildUndoManager();
956
+ }
957
+ catch (error) {
958
+ logError('Failed to set up undo manager', error);
959
+ }
960
+ }
961
+ rebuildUndoManager() {
962
+ try {
963
+ try {
964
+ this.undoManager?.destroy();
965
+ }
966
+ catch { /* cleanup is best-effort */ }
967
+ const ytext = this.getText();
968
+ if (!ytext) {
969
+ this.undoManager = null;
970
+ return;
971
+ }
972
+ const origins = new Set([this]);
973
+ if (this.binding)
974
+ origins.add(this.binding);
975
+ this.undoManager = new Y.UndoManager(ytext, {
976
+ captureTimeout: this.config.undoCaptureTimeout,
977
+ trackedOrigins: origins,
978
+ });
979
+ }
980
+ catch (error) {
981
+ logError('Failed to rebuild undo manager', error);
982
+ this.undoManager = null;
983
+ }
984
+ }
985
+ setupAwareness() {
986
+ try {
987
+ const awareness = this.getAwareness();
988
+ if (!awareness)
989
+ return;
990
+ const user = this.readUser();
991
+ this.store?.updateAwareness({});
992
+ awareness.setLocalStateField('user', user);
993
+ const handler = () => {
994
+ try {
995
+ this.emitAwareness();
996
+ }
997
+ catch (error) {
998
+ logError('Failed to handle awareness update', error);
999
+ }
1000
+ };
1001
+ awareness.on('change', handler);
1002
+ this.cleanupFns.push(() => {
1003
+ try {
1004
+ awareness.off('change', handler);
1005
+ }
1006
+ catch { /* no-op */ }
1007
+ });
1008
+ }
1009
+ catch (error) {
1010
+ this.reportError('Failed to set up awareness', error);
1011
+ }
1012
+ }
1013
+ setupProviderListeners() {
1014
+ try {
1015
+ if (!this.provider)
1016
+ return;
1017
+ const statusHandler = (payload) => {
1018
+ try {
1019
+ const next = typeof payload === 'string' ? payload : payload?.status;
1020
+ if (next === 'connecting' || next === 'connected' || next === 'disconnected')
1021
+ this.setStatus(next);
1022
+ else
1023
+ this.updateProviderState();
1024
+ }
1025
+ catch (error) {
1026
+ logError('Failed to process provider status', error);
1027
+ }
1028
+ };
1029
+ const syncedHandler = (payload) => {
1030
+ try {
1031
+ const next = typeof payload === 'boolean' ? payload : payload?.synced;
1032
+ this.setSynced(typeof next === 'boolean' ? next : Boolean(this.provider?.synced));
1033
+ this.updateProviderState();
1034
+ }
1035
+ catch (error) {
1036
+ logError('Failed to process provider sync', error);
1037
+ }
1038
+ };
1039
+ this.provider.on('status', statusHandler);
1040
+ this.provider.on('synced', syncedHandler);
1041
+ this.cleanupFns.push(() => { try {
1042
+ this.provider?.off('status', statusHandler);
1043
+ }
1044
+ catch { /* no-op */ } });
1045
+ this.cleanupFns.push(() => { try {
1046
+ this.provider?.off('synced', syncedHandler);
1047
+ }
1048
+ catch { /* no-op */ } });
1049
+ }
1050
+ catch (error) {
1051
+ this.reportError('Failed to set up provider listeners', error);
1052
+ }
1053
+ }
1054
+ updateProviderState() {
1055
+ try {
1056
+ if (!this.provider)
1057
+ return;
1058
+ this.setStatus(this.provider.status);
1059
+ this.setSynced(this.provider.synced);
1060
+ }
1061
+ catch (error) {
1062
+ logError('Failed to update provider state', error);
1063
+ }
1064
+ }
1065
+ setStatus(status) {
1066
+ try {
1067
+ if (this.statusValue === status)
1068
+ return;
1069
+ this.statusValue = status;
1070
+ this.statusListeners.forEach((callback) => {
1071
+ try {
1072
+ callback(status);
1073
+ }
1074
+ catch (error) {
1075
+ logError('Status listener failed', error);
1076
+ }
1077
+ });
1078
+ }
1079
+ catch (error) {
1080
+ logError('Failed to set status', error);
1081
+ }
1082
+ }
1083
+ setSynced(synced) {
1084
+ try {
1085
+ if (this.syncedValue === synced)
1086
+ return;
1087
+ this.syncedValue = synced;
1088
+ this.syncedListeners.forEach((callback) => {
1089
+ try {
1090
+ callback(synced);
1091
+ }
1092
+ catch (error) {
1093
+ logError('Sync listener failed', error);
1094
+ }
1095
+ });
1096
+ }
1097
+ catch (error) {
1098
+ logError('Failed to set sync state', error);
1099
+ }
1100
+ }
1101
+ emitAwareness() {
1102
+ try {
1103
+ const selections = this.getRemoteSelections();
1104
+ this.awarenessListeners.forEach((callback) => {
1105
+ try {
1106
+ callback(selections);
1107
+ }
1108
+ catch (error) {
1109
+ logError('Awareness listener failed', error);
1110
+ }
1111
+ });
1112
+ }
1113
+ catch (error) {
1114
+ logError('Failed to emit awareness', error);
1115
+ }
1116
+ }
1117
+ getDoc() {
1118
+ try {
1119
+ return this.store?.getDoc() ?? null;
1120
+ }
1121
+ catch (error) {
1122
+ logError('Failed to get Y.Doc', error);
1123
+ return null;
1124
+ }
1125
+ }
1126
+ getText() {
1127
+ try {
1128
+ return this.store?.getText() ?? null;
1129
+ }
1130
+ catch (error) {
1131
+ logError('Failed to get Y.Text', error);
1132
+ return null;
1133
+ }
1134
+ }
1135
+ getYText() {
1136
+ try {
1137
+ return this.getText();
1138
+ }
1139
+ catch (error) {
1140
+ logError('Failed to get Y.Text alias', error);
1141
+ return null;
1142
+ }
1143
+ }
1144
+ getAwareness() {
1145
+ try {
1146
+ return this.store?.getAwareness() ?? null;
1147
+ }
1148
+ catch (error) {
1149
+ logError('Failed to get awareness', error);
1150
+ return null;
1151
+ }
1152
+ }
1153
+ readUser() {
1154
+ try {
1155
+ const current = this.config.veltClient?.getUser?.();
1156
+ const configured = this.config.cursorData ?? {};
1157
+ const color = configured.color || current?.color || DEFAULT_CURSOR_COLOR;
1158
+ return {
1159
+ userId: configured.userId || current?.userId || 'anonymous',
1160
+ name: configured.name || current?.name || current?.email || 'Anonymous',
1161
+ email: configured.email || current?.email || '',
1162
+ color,
1163
+ colorLight: configured.colorLight || `${color}33`,
1164
+ };
1165
+ }
1166
+ catch (error) {
1167
+ logError('Failed to read Velt user', error);
1168
+ return { userId: 'anonymous', name: 'Anonymous', email: '', color: DEFAULT_CURSOR_COLOR, colorLight: `${DEFAULT_CURSOR_COLOR}33` };
1169
+ }
1170
+ }
1171
+ normalizeConfig(config) {
1172
+ try {
1173
+ return {
1174
+ ...config,
1175
+ editorId: config?.editorId?.trim() || DEFAULT_EDITOR_ID,
1176
+ debounceMs: Number.isFinite(config?.debounceMs) ? Math.max(0, Number(config.debounceMs)) : 100,
1177
+ undoCaptureTimeout: Number.isFinite(config?.undoCaptureTimeout) ? Math.max(0, Number(config.undoCaptureTimeout)) : 500,
1178
+ };
1179
+ }
1180
+ catch (error) {
1181
+ logError('Failed to normalize collaboration config', error);
1182
+ return { editorId: DEFAULT_EDITOR_ID, veltClient: config?.veltClient };
1183
+ }
1184
+ }
1185
+ reportError(message, value) {
1186
+ try {
1187
+ const error = value instanceof Error ? value : new Error(value ? `${message}: ${String(value)}` : message);
1188
+ logError(message, error);
1189
+ try {
1190
+ this.config.onError?.(error);
1191
+ }
1192
+ catch (callbackError) {
1193
+ logError('onError callback failed', callbackError);
1194
+ }
1195
+ }
1196
+ catch (error) {
1197
+ logError(message, error);
1198
+ }
1199
+ }
1200
+ }
1201
+ async function createCollaboration(config) {
1202
+ try {
1203
+ const manager = new CollaborationManager(config);
1204
+ await manager.initialize();
1205
+ return manager;
1206
+ }
1207
+ catch (error) {
1208
+ logError('Failed to create collaboration manager', error);
1209
+ return new CollaborationManager(config);
1210
+ }
1211
+ }
1212
+
1213
+ export { CollaborationManager, createCollaboration };
1214
+ //# sourceMappingURL=index.js.map