@itrocks/sync 0.0.0-stage → 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 (156) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +249 -2
  3. package/config.yaml +2 -0
  4. package/demo/src/demo.css +458 -0
  5. package/dist/client/author-background.d.ts +2 -0
  6. package/dist/client/author-background.js +28 -0
  7. package/dist/client/clock.d.ts +10 -0
  8. package/dist/client/clock.js +30 -0
  9. package/dist/client/collections/order.d.ts +10 -0
  10. package/dist/client/collections/order.js +77 -0
  11. package/dist/client/collections/reorder-nodes.d.ts +2 -0
  12. package/dist/client/collections/reorder-nodes.js +67 -0
  13. package/dist/client/collections/row-changes.d.ts +12 -0
  14. package/dist/client/collections/row-changes.js +26 -0
  15. package/dist/client/collections/row-history.d.ts +16 -0
  16. package/dist/client/collections/row-history.js +61 -0
  17. package/dist/client/collections/table-columns.d.ts +19 -0
  18. package/dist/client/collections/table-columns.js +200 -0
  19. package/dist/client/collections.d.ts +54 -0
  20. package/dist/client/collections.js +262 -0
  21. package/dist/client/discovery.d.ts +1 -0
  22. package/dist/client/discovery.js +57 -0
  23. package/dist/client/field-address.d.ts +38 -0
  24. package/dist/client/field-address.js +225 -0
  25. package/dist/client/field-value.d.ts +7 -0
  26. package/dist/client/field-value.js +105 -0
  27. package/dist/client/form-identity.d.ts +1 -0
  28. package/dist/client/form-identity.js +43 -0
  29. package/dist/client/form-session.d.ts +53 -0
  30. package/dist/client/form-session.js +218 -0
  31. package/dist/client/identity.d.ts +3 -0
  32. package/dist/client/identity.js +27 -0
  33. package/dist/client/index.d.ts +43 -0
  34. package/dist/client/index.js +109 -0
  35. package/dist/client/journal.d.ts +13 -0
  36. package/dist/client/journal.js +59 -0
  37. package/dist/client/lifecycle.d.ts +26 -0
  38. package/dist/client/lifecycle.js +112 -0
  39. package/dist/client/observation.d.ts +11 -0
  40. package/dist/client/observation.js +46 -0
  41. package/dist/client/outbox.d.ts +15 -0
  42. package/dist/client/outbox.js +71 -0
  43. package/dist/client/plugin.d.ts +42 -0
  44. package/dist/client/plugin.js +1 -0
  45. package/dist/client/plugins/column-order/apply.d.ts +2 -0
  46. package/dist/client/plugins/column-order/apply.js +30 -0
  47. package/dist/client/plugins/column-order/colgroups.d.ts +2 -0
  48. package/dist/client/plugins/column-order/colgroups.js +78 -0
  49. package/dist/client/plugins/column-order/index.d.ts +2 -0
  50. package/dist/client/plugins/column-order/index.js +98 -0
  51. package/dist/client/plugins/cursor/editable.d.ts +16 -0
  52. package/dist/client/plugins/cursor/editable.js +67 -0
  53. package/dist/client/plugins/cursor/geometry.d.ts +16 -0
  54. package/dist/client/plugins/cursor/geometry.js +122 -0
  55. package/dist/client/plugins/cursor/index.d.ts +4 -0
  56. package/dist/client/plugins/cursor/index.js +13 -0
  57. package/dist/client/plugins/cursor/indicators.d.ts +31 -0
  58. package/dist/client/plugins/cursor/indicators.js +144 -0
  59. package/dist/client/plugins/cursor/local-selection.d.ts +19 -0
  60. package/dist/client/plugins/cursor/local-selection.js +234 -0
  61. package/dist/client/plugins/cursor/selection.d.ts +9 -0
  62. package/dist/client/plugins/cursor/selection.js +49 -0
  63. package/dist/client/plugins/cursor/text-presence.d.ts +15 -0
  64. package/dist/client/plugins/cursor/text-presence.js +95 -0
  65. package/dist/client/plugins/fields/author.d.ts +7 -0
  66. package/dist/client/plugins/fields/author.js +22 -0
  67. package/dist/client/plugins/fields/index.d.ts +4 -0
  68. package/dist/client/plugins/fields/index.js +192 -0
  69. package/dist/client/plugins/fields/writes.d.ts +19 -0
  70. package/dist/client/plugins/fields/writes.js +51 -0
  71. package/dist/client/plugins/focus/index.d.ts +9 -0
  72. package/dist/client/plugins/focus/index.js +92 -0
  73. package/dist/client/plugins/focus/indicators.d.ts +19 -0
  74. package/dist/client/plugins/focus/indicators.js +163 -0
  75. package/dist/client/plugins/naming/algorithm.d.ts +7 -0
  76. package/dist/client/plugins/naming/algorithm.js +65 -0
  77. package/dist/client/plugins/naming/attributes.d.ts +16 -0
  78. package/dist/client/plugins/naming/attributes.js +195 -0
  79. package/dist/client/plugins/naming/index.d.ts +5 -0
  80. package/dist/client/plugins/naming/index.js +185 -0
  81. package/dist/client/plugins/range/index.d.ts +4 -0
  82. package/dist/client/plugins/range/index.js +15 -0
  83. package/dist/client/plugins/reconciliation/index.d.ts +6 -0
  84. package/dist/client/plugins/reconciliation/index.js +282 -0
  85. package/dist/client/plugins/reconciliation/matching.d.ts +12 -0
  86. package/dist/client/plugins/reconciliation/matching.js +37 -0
  87. package/dist/client/plugins/reconciliation/proposals.d.ts +11 -0
  88. package/dist/client/plugins/reconciliation/proposals.js +32 -0
  89. package/dist/client/plugins/row-order/index.d.ts +2 -0
  90. package/dist/client/plugins/row-order/index.js +99 -0
  91. package/dist/client/plugins/rows/clone.d.ts +2 -0
  92. package/dist/client/plugins/rows/clone.js +123 -0
  93. package/dist/client/plugins/rows/index.d.ts +2 -0
  94. package/dist/client/plugins/rows/index.js +191 -0
  95. package/dist/client/plugins/rows/materialize.d.ts +4 -0
  96. package/dist/client/plugins/rows/materialize.js +43 -0
  97. package/dist/client/plugins/rows/remove.d.ts +1 -0
  98. package/dist/client/plugins/rows/remove.js +13 -0
  99. package/dist/client/plugins/rows/template.d.ts +2 -0
  100. package/dist/client/plugins/rows/template.js +21 -0
  101. package/dist/client/transport.d.ts +23 -0
  102. package/dist/client/transport.js +128 -0
  103. package/dist/client/user-colour.d.ts +3 -0
  104. package/dist/client/user-colour.js +11 -0
  105. package/dist/server/acknowledgments.d.ts +3 -0
  106. package/dist/server/acknowledgments.js +8 -0
  107. package/dist/server/broadcast.d.ts +3 -0
  108. package/dist/server/broadcast.js +7 -0
  109. package/dist/server/cli.d.ts +2 -0
  110. package/dist/server/cli.js +44 -0
  111. package/dist/server/clock.d.ts +2 -0
  112. package/dist/server/clock.js +3 -0
  113. package/dist/server/configuration.d.ts +3 -0
  114. package/dist/server/configuration.js +7 -0
  115. package/dist/server/connection.d.ts +13 -0
  116. package/dist/server/connection.js +1 -0
  117. package/dist/server/express.d.ts +2 -0
  118. package/dist/server/express.js +1 -0
  119. package/dist/server/fastify.d.ts +10 -0
  120. package/dist/server/fastify.js +15 -0
  121. package/dist/server/index.d.ts +7 -0
  122. package/dist/server/index.js +1 -0
  123. package/dist/server/journal.d.ts +7 -0
  124. package/dist/server/journal.js +16 -0
  125. package/dist/server/messages.d.ts +4 -0
  126. package/dist/server/messages.js +106 -0
  127. package/dist/server/participants.d.ts +9 -0
  128. package/dist/server/participants.js +7 -0
  129. package/dist/server/receipts.d.ts +13 -0
  130. package/dist/server/receipts.js +28 -0
  131. package/dist/server/recovery.d.ts +3 -0
  132. package/dist/server/recovery.js +9 -0
  133. package/dist/server/server.d.ts +34 -0
  134. package/dist/server/server.js +189 -0
  135. package/dist/server/sessions.d.ts +16 -0
  136. package/dist/server/sessions.js +37 -0
  137. package/dist/server/standalone.d.ts +9 -0
  138. package/dist/server/standalone.js +12 -0
  139. package/dist/server/transactions.d.ts +15 -0
  140. package/dist/server/transactions.js +50 -0
  141. package/dist/server/websocket-connection.d.ts +3 -0
  142. package/dist/server/websocket-connection.js +38 -0
  143. package/dist/server/websocket.d.ts +11 -0
  144. package/dist/server/websocket.js +26 -0
  145. package/dist/shared/field-update.d.ts +12 -0
  146. package/dist/shared/field-update.js +18 -0
  147. package/dist/shared/journal-entries.d.ts +9 -0
  148. package/dist/shared/journal-entries.js +33 -0
  149. package/dist/shared/protocol.d.ts +105 -0
  150. package/dist/shared/protocol.js +15 -0
  151. package/docs/dependencies.md +130 -0
  152. package/docs/spec-addendum-dependencies.md +10 -0
  153. package/docs/spec-addendum.md +717 -0
  154. package/docs/spec.md +1165 -0
  155. package/docs/testing.md +39 -0
  156. package/package.json +96 -5
@@ -0,0 +1,191 @@
1
+ import { rowSequence } from '../../collections/order.js';
2
+ import { reorderByParent } from '../../collections/reorder-nodes.js';
3
+ import { rowHistory } from '../../collections/row-history.js';
4
+ import { rowPlacements } from '../../collections/row-history.js';
5
+ import { rowTransactions } from '../../collections/row-history.js';
6
+ import { insertionParent } from './materialize.js';
7
+ import { materialize } from './materialize.js';
8
+ import { removeRows } from './remove.js';
9
+ function capture(context, collection, identity) {
10
+ const { collections } = context;
11
+ return new Map(collection.items().map(element => [
12
+ (identity === 'raw') ? collections.rawIdentity(collection, element) : collections.identify(collection, element),
13
+ element
14
+ ]));
15
+ }
16
+ function replay(context, collection, history, plans, displaced) {
17
+ const { collections } = context;
18
+ const canonical = (row) => collections.canonical(collection.id, row);
19
+ const changes = rowHistory(history, canonical);
20
+ const { additions, rawRemoved, removed } = changes;
21
+ if (!additions.size && !removed.size)
22
+ return false;
23
+ const existing = capture(context, collection, 'canonical');
24
+ const deleted = removeRows(existing, removed, row => {
25
+ const raw = collections.rawIdentity(collection, row);
26
+ // An alias can move the tombstone later. Keep rows without their own tombstone available to restore.
27
+ if (!rawRemoved.has(raw))
28
+ displaced.set(raw, row);
29
+ });
30
+ const returning = new Map();
31
+ for (const [raw, element] of displaced) {
32
+ if (rawRemoved.has(raw)) {
33
+ displaced.delete(raw);
34
+ continue;
35
+ }
36
+ const id = canonical(raw);
37
+ if (removed.has(id) || existing.has(id))
38
+ continue;
39
+ const previous = returning.get(id);
40
+ if (!previous || (raw === id) || ((previous.raw !== id) && (raw < previous.raw))) {
41
+ returning.set(id, { raw, element });
42
+ }
43
+ }
44
+ const initial = collection.initial.map(canonical);
45
+ const roots = collections.managedRowOrder ? undefined : [...existing.keys()].filter(id => !additions.has(id));
46
+ const sequence = rowSequence(initial, rowPlacements(changes, initial), removed, roots);
47
+ const next = sequence.find(id => existing.has(id));
48
+ const plan = JSON.stringify(sequence);
49
+ let inserted = false;
50
+ let pending = false;
51
+ let previous;
52
+ for (const id of sequence) {
53
+ let row = existing.get(id);
54
+ if (!row) {
55
+ const insertion = additions.get(id);
56
+ const original = returning.get(id);
57
+ if (!original && !insertion)
58
+ continue;
59
+ row = original?.element ?? (insertion && materialize(collection, insertion.change, collections.managedNaming));
60
+ if (!row) {
61
+ pending = true;
62
+ continue;
63
+ }
64
+ const attached = collection.contains(row);
65
+ if (!attached && row.isConnected) {
66
+ pending = true;
67
+ continue;
68
+ }
69
+ if (!original && insertion) {
70
+ collections.adopt(collection, row, insertion.change.row, insertion.transaction.client);
71
+ }
72
+ if (!attached) {
73
+ const following = next ? existing.get(next) : undefined;
74
+ const parent = insertionParent(collection, previous ?? following);
75
+ parent.insertBefore(row, previous ? previous.nextSibling : following ?? null);
76
+ if (!collection.contains(row)) {
77
+ row.remove();
78
+ pending = true;
79
+ continue;
80
+ }
81
+ }
82
+ else if (previous && (row.parentElement === previous.parentElement) && (row !== previous.nextElementSibling)) {
83
+ previous.after(row);
84
+ }
85
+ else if (!previous && next) {
86
+ existing.get(next)?.before(row);
87
+ }
88
+ if (original)
89
+ displaced.delete(original.raw);
90
+ existing.set(id, row);
91
+ inserted = true;
92
+ }
93
+ previous = row;
94
+ }
95
+ if (!collections.managedRowOrder && (inserted || (plans.get(collection) !== plan))) {
96
+ reorderByParent(sequence.map(id => existing.get(id)));
97
+ plans.set(collection, plan);
98
+ }
99
+ if (inserted || deleted)
100
+ collections.structureChanged();
101
+ return pending;
102
+ }
103
+ export function rows() {
104
+ return {
105
+ name: 'rows',
106
+ init(context) {
107
+ const { collections } = context;
108
+ const observed = new Map();
109
+ const plans = new WeakMap();
110
+ const displaced = new Map();
111
+ let dirty = false;
112
+ let pending = false;
113
+ let revision = collections.revision;
114
+ const remember = () => {
115
+ const mounted = collections.states();
116
+ for (const collection of displaced.keys()) {
117
+ if (!mounted.includes(collection))
118
+ displaced.delete(collection);
119
+ }
120
+ observed.clear();
121
+ for (const collection of mounted) {
122
+ observed.set(collection, [...capture(context, collection, 'raw').keys()]);
123
+ }
124
+ };
125
+ remember();
126
+ return {
127
+ destroy() {
128
+ displaced.clear();
129
+ observed.clear();
130
+ },
131
+ observe(records) {
132
+ dirty ||= pending && records.length > 0;
133
+ for (const collection of collections.states()) {
134
+ const before = observed.get(collection);
135
+ if (before && !collection.affected(records))
136
+ continue;
137
+ const previous = before ?? collection.initial;
138
+ const current = capture(context, collection, 'raw');
139
+ const known = new Set(previous);
140
+ observed.set(collection, [...current.keys()]);
141
+ previous.forEach((row, index) => {
142
+ if (!current.has(row)) {
143
+ const after = previous[index - 1] ?? null;
144
+ context.publish('remove-row', { after, collection: collection.id, row });
145
+ dirty = true;
146
+ }
147
+ });
148
+ let after = null;
149
+ for (const [row, element] of current) {
150
+ if (!known.has(row)) {
151
+ context.publish('add-row', {
152
+ after,
153
+ collection: collection.id,
154
+ row,
155
+ values: context.snapshot(element)
156
+ });
157
+ dirty = true;
158
+ }
159
+ after = row;
160
+ }
161
+ }
162
+ },
163
+ flush() {
164
+ if (!dirty && (revision === collections.revision))
165
+ return;
166
+ dirty = false;
167
+ pending = false;
168
+ const history = rowTransactions(context.history());
169
+ context.mute(() => {
170
+ for (const collection of collections.states()) {
171
+ const held = displaced.get(collection) ?? new Map();
172
+ const unavailable = replay(context, collection, history.get(collection.id) ?? [], plans, held);
173
+ pending ||= unavailable;
174
+ if (held.size) {
175
+ displaced.set(collection, held);
176
+ }
177
+ else {
178
+ displaced.delete(collection);
179
+ }
180
+ }
181
+ });
182
+ revision = collections.revision;
183
+ remember();
184
+ },
185
+ receive(transaction) {
186
+ dirty ||= (transaction.type === 'add-row') || (transaction.type === 'remove-row');
187
+ }
188
+ };
189
+ }
190
+ };
191
+ }
@@ -0,0 +1,4 @@
1
+ import type { Collection } from '../../collections.js';
2
+ import type { RowCreation } from '../../collections.js';
3
+ export declare function insertionParent(collection: Collection, existing?: Element): Element;
4
+ export declare function materialize(collection: Collection, change: RowCreation, managedNaming: boolean): Element | undefined;
@@ -0,0 +1,43 @@
1
+ import { bindRowColumns } from '../../collections/table-columns.js';
2
+ import { cloneRow } from './clone.js';
3
+ import { prepareClone } from './clone.js';
4
+ import { cloneTemplate } from './template.js';
5
+ export function insertionParent(collection, existing) {
6
+ if (existing?.parentElement)
7
+ return existing.parentElement;
8
+ const { element } = collection;
9
+ if ((element instanceof HTMLTableElement) && element.tBodies.length) {
10
+ return element.tBodies[0];
11
+ }
12
+ return element;
13
+ }
14
+ export function materialize(collection, change, managedNaming) {
15
+ const { create, key } = collection.options;
16
+ const existing = collection.items();
17
+ if (typeof create === 'function') {
18
+ const before = new Set(existing);
19
+ const result = create(collection.element, change);
20
+ if (result instanceof Element) {
21
+ return before.has(result) ? undefined : result;
22
+ }
23
+ if (typeof result === 'string' && result.trim()) {
24
+ const range = collection.element.ownerDocument.createRange();
25
+ range.selectNodeContents(insertionParent(collection, existing[0]));
26
+ const element = range.createContextualFragment(result).firstElementChild;
27
+ if (element)
28
+ return element;
29
+ }
30
+ return collection.items().find(item => !before.has(item));
31
+ }
32
+ const model = create ? undefined : existing[0];
33
+ const row = create
34
+ ? cloneTemplate(collection, create)
35
+ : model ? cloneRow(model) : cloneTemplate(collection);
36
+ if (!row)
37
+ return undefined;
38
+ const table = collection.element.closest('table');
39
+ if (table && (row instanceof HTMLTableRowElement)) {
40
+ bindRowColumns(table, row, (model instanceof HTMLTableRowElement) ? model : undefined);
41
+ }
42
+ return prepareClone(row, change.row, key, managedNaming);
43
+ }
@@ -0,0 +1 @@
1
+ export declare function removeRows(existing: Map<string, Element>, removed: ReadonlySet<string>, preserve: (row: Element) => void): boolean;
@@ -0,0 +1,13 @@
1
+ export function removeRows(existing, removed, preserve) {
2
+ let changed = false;
3
+ for (const id of removed) {
4
+ const row = existing.get(id);
5
+ if (!row)
6
+ continue;
7
+ preserve(row);
8
+ row.remove();
9
+ existing.delete(id);
10
+ changed = true;
11
+ }
12
+ return changed;
13
+ }
@@ -0,0 +1,2 @@
1
+ import type { Collection } from '../../collections.js';
2
+ export declare function cloneTemplate(collection: Collection, selector?: string): Element | undefined;
@@ -0,0 +1,21 @@
1
+ import { cloneRow } from './clone.js';
2
+ function adjacentTemplate(element) {
3
+ for (const candidate of [element.nextElementSibling, element.previousElementSibling]) {
4
+ if (candidate instanceof HTMLTemplateElement)
5
+ return candidate;
6
+ }
7
+ return undefined;
8
+ }
9
+ export function cloneTemplate(collection, selector) {
10
+ const { element } = collection;
11
+ const adjacent = adjacentTemplate(element);
12
+ const parent = element.closest('table') ?? element.parentElement;
13
+ const model = selector
14
+ ? element.ownerDocument.querySelector(selector)
15
+ : adjacent ?? ((parent && (parent !== element)) ? adjacentTemplate(parent) : undefined);
16
+ if (model instanceof HTMLTemplateElement) {
17
+ const item = model.content.firstElementChild;
18
+ return item ? cloneRow(item, element.ownerDocument) : undefined;
19
+ }
20
+ return model ? cloneRow(model, element.ownerDocument) : undefined;
21
+ }
@@ -0,0 +1,23 @@
1
+ import type { ClientMessage } from '../shared/protocol.js';
2
+ import type { ServerMessage } from '../shared/protocol.js';
3
+ import type { Clock } from './clock.js';
4
+ export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected';
5
+ export declare class Transport {
6
+ private url;
7
+ private clock;
8
+ private onMessage;
9
+ private onStatus;
10
+ private closed;
11
+ private heartbeat?;
12
+ private readyTimer?;
13
+ private retryTimer?;
14
+ private socket?;
15
+ private status?;
16
+ private tries;
17
+ constructor(url: string, clock: Clock, onMessage: (message: ServerMessage) => void, onStatus: (status: ConnectionStatus) => void);
18
+ close(): void;
19
+ connect(): void;
20
+ send(message: ClientMessage): boolean;
21
+ private clearTimers;
22
+ private setStatus;
23
+ }
@@ -0,0 +1,128 @@
1
+ export class Transport {
2
+ url;
3
+ clock;
4
+ onMessage;
5
+ onStatus;
6
+ closed = false;
7
+ heartbeat;
8
+ readyTimer;
9
+ retryTimer;
10
+ socket;
11
+ status;
12
+ tries = 0;
13
+ constructor(url, clock, onMessage, onStatus) {
14
+ this.url = url;
15
+ this.clock = clock;
16
+ this.onMessage = onMessage;
17
+ this.onStatus = onStatus;
18
+ }
19
+ close() {
20
+ this.closed = true;
21
+ this.clearTimers();
22
+ this.socket?.close();
23
+ this.socket = undefined;
24
+ this.setStatus('disconnected');
25
+ }
26
+ connect() {
27
+ if (this.closed || this.socket)
28
+ return;
29
+ this.setStatus('connecting');
30
+ const socket = new WebSocket(this.url);
31
+ let hello;
32
+ let probes = 0;
33
+ let lastPong = this.clock.local();
34
+ this.socket = socket;
35
+ const ping = () => this.send({ type: 'ping', sent: this.clock.local() });
36
+ const ready = () => {
37
+ if (!hello || (this.status === 'connected') || (this.socket !== socket))
38
+ return;
39
+ clearTimeout(this.readyTimer);
40
+ if (this.tries) {
41
+ console.log('%c[@itrocks/sync] Websocket connection restored.', 'color: #14532d; background-color: #dcfce7; padding: 2px 5px');
42
+ }
43
+ this.tries = 0;
44
+ this.setStatus('connected');
45
+ if (this.socket === socket) {
46
+ this.onMessage(hello);
47
+ }
48
+ };
49
+ this.readyTimer = setTimeout(() => socket.close(), 10_000);
50
+ socket.addEventListener('message', event => {
51
+ if (this.socket !== socket)
52
+ return;
53
+ const message = decode(event.data);
54
+ if (!message)
55
+ return;
56
+ if (message.type === 'hello') {
57
+ if (hello)
58
+ return;
59
+ hello = message;
60
+ lastPong = this.clock.local();
61
+ for (let index = 0; index < 3; index++) {
62
+ ping();
63
+ }
64
+ clearTimeout(this.readyTimer);
65
+ this.readyTimer = setTimeout(ready, 250);
66
+ this.heartbeat = setInterval(() => {
67
+ if ((this.clock.local() - lastPong) > 90_000) {
68
+ socket.close();
69
+ return;
70
+ }
71
+ ping();
72
+ }, 30_000);
73
+ return;
74
+ }
75
+ if (message.type === 'pong') {
76
+ lastPong = this.clock.local();
77
+ this.clock.measure(message.sent, message.time, lastPong);
78
+ probes++;
79
+ if (probes >= 3) {
80
+ ready();
81
+ }
82
+ return;
83
+ }
84
+ this.onMessage(message);
85
+ });
86
+ socket.addEventListener('close', () => {
87
+ if (this.socket !== socket)
88
+ return;
89
+ this.socket = undefined;
90
+ this.clearTimers();
91
+ this.setStatus('disconnected');
92
+ if (this.closed)
93
+ return;
94
+ const wait = Math.min(250 * (2 ** this.tries), 5000);
95
+ this.tries++;
96
+ this.retryTimer = setTimeout(() => this.connect(), wait);
97
+ });
98
+ }
99
+ send(message) {
100
+ if (!this.socket || (this.socket.readyState !== WebSocket.OPEN))
101
+ return false;
102
+ this.socket.send(JSON.stringify(message));
103
+ return true;
104
+ }
105
+ clearTimers() {
106
+ clearInterval(this.heartbeat);
107
+ clearTimeout(this.readyTimer);
108
+ clearTimeout(this.retryTimer);
109
+ }
110
+ setStatus(status) {
111
+ if (this.status === status)
112
+ return;
113
+ this.status = status;
114
+ this.onStatus(status);
115
+ }
116
+ }
117
+ function decode(text) {
118
+ if (typeof text !== 'string')
119
+ return;
120
+ try {
121
+ const message = JSON.parse(text);
122
+ if (message && (typeof message.type === 'string'))
123
+ return message;
124
+ }
125
+ catch {
126
+ return;
127
+ }
128
+ }
@@ -0,0 +1,3 @@
1
+ import type { User } from '../shared/protocol.js';
2
+ export declare function initials(user: User): string;
3
+ export declare function userColour(user: User): string;
@@ -0,0 +1,11 @@
1
+ const palette = ['#3569aa', '#8b49a0', '#2a775d', '#a55325', '#a24466', '#5c58ac', '#5e671c', '#08727d'];
2
+ export function initials(user) {
3
+ return user.name.trim().split(/\s+/u).slice(0, 2).map(part => Array.from(part)[0] ?? '').join('').toUpperCase();
4
+ }
5
+ export function userColour(user) {
6
+ let hash = 0;
7
+ for (const letter of user.id) {
8
+ hash = (((hash * 31) >>> 0) + (letter.codePointAt(0) ?? 0)) >>> 0;
9
+ }
10
+ return palette[hash % palette.length];
11
+ }
@@ -0,0 +1,3 @@
1
+ import type { ServerMessage } from '../shared/protocol.js';
2
+ import type { Transaction } from '../shared/protocol.js';
3
+ export declare function acknowledge(session: string, transactions: Transaction[]): ServerMessage;
@@ -0,0 +1,8 @@
1
+ export function acknowledge(session, transactions) {
2
+ return {
3
+ type: 'ack',
4
+ session,
5
+ ids: transactions.map(transaction => transaction.id),
6
+ transactions
7
+ };
8
+ }
@@ -0,0 +1,3 @@
1
+ import type { ServerMessage } from '../shared/protocol.js';
2
+ import type { Participants } from './participants.js';
3
+ export declare function broadcast(participants: Participants, message: ServerMessage, except?: string): void;
@@ -0,0 +1,7 @@
1
+ export function broadcast(participants, message, except) {
2
+ for (const [client, participant] of participants) {
3
+ if (client === except)
4
+ continue;
5
+ participant.send(message);
6
+ }
7
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ import { once } from 'node:events';
3
+ import { parseArgs } from 'node:util';
4
+ import { DEFAULT_PATH } from '../shared/protocol.js';
5
+ import { createStandaloneServer } from './standalone.js';
6
+ async function main() {
7
+ const { values } = parseArgs({ options: {
8
+ help: { type: 'boolean', short: 'h' },
9
+ host: { type: 'string', default: '127.0.0.1' },
10
+ path: { type: 'string', default: DEFAULT_PATH },
11
+ port: { type: 'string', short: 'p', default: '3001' }
12
+ } });
13
+ if (values.help) {
14
+ console.log('Usage: sync-server [--host HOST] [--port PORT] [--path PATH]\n'
15
+ + `\nDefaults to 127.0.0.1:3001${DEFAULT_PATH}.`);
16
+ return;
17
+ }
18
+ const port = Number(values.port);
19
+ if (!/^\d+$/.test(values.port) || (port > 65_535)) {
20
+ throw new RangeError('--port must be an integer between 0 and 65535');
21
+ }
22
+ if (!values.host.trim()) {
23
+ throw new TypeError('--host must be a non-empty hostname or address');
24
+ }
25
+ if (!/^\/(?!\/)[^?#\\\s]*$/.test(values.path)) {
26
+ throw new TypeError('--path must be an absolute URL path');
27
+ }
28
+ const { server } = createStandaloneServer({ path: values.path });
29
+ const listening = once(server, 'listening');
30
+ server.listen(port, values.host);
31
+ await listening;
32
+ const address = server.address();
33
+ if (address && (typeof address !== 'string')) {
34
+ const host = (address.family === 'IPv6') ? ('[' + address.address + ']') : address.address;
35
+ console.log(`Sync server listening at ws://${host}:${address.port}${values.path}`);
36
+ }
37
+ }
38
+ try {
39
+ await main();
40
+ }
41
+ catch (error) {
42
+ console.error(error instanceof Error ? error.message : error);
43
+ process.exitCode = 1;
44
+ }
@@ -0,0 +1,2 @@
1
+ import type { ServerMessage } from '../shared/protocol.js';
2
+ export declare function pong(sent: number): ServerMessage;
@@ -0,0 +1,3 @@
1
+ export function pong(sent) {
2
+ return { type: 'pong', sent, time: Date.now() };
3
+ }
@@ -0,0 +1,3 @@
1
+ import type { SyncOptions } from './server.js';
2
+ import type { SyncServer } from './server.js';
3
+ export declare function createSyncServer<Request>(options: SyncOptions<Request>): SyncServer<Request>;
@@ -0,0 +1,7 @@
1
+ import { Receipts } from './receipts.js';
2
+ import { SyncEngine } from './server.js';
3
+ import { Sessions } from './sessions.js';
4
+ import { Transactions } from './transactions.js';
5
+ export function createSyncServer(options) {
6
+ return new SyncEngine(options, new Sessions(), new Transactions(new Receipts(options.replaySecret)));
7
+ }
@@ -0,0 +1,13 @@
1
+ import type { ServerMessage } from '../shared/protocol.js';
2
+ export interface Connection {
3
+ client: string;
4
+ closed: boolean;
5
+ sessions: Set<string>;
6
+ send(message: ServerMessage): void;
7
+ }
8
+ export interface ServerSocket {
9
+ close(code: number, reason: string): void;
10
+ onClose(listener: () => void): void;
11
+ onMessage(listener: (data: string) => void): void;
12
+ send(message: string): void;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export { sync } from './websocket.js';
2
+ export type { WebSocketSyncOptions as ExpressSyncOptions } from './websocket.js';
@@ -0,0 +1 @@
1
+ export { sync } from './websocket.js';
@@ -0,0 +1,10 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import type { FastifyRequest } from 'fastify';
3
+ import type { SyncOptions } from './server.js';
4
+ export interface FastifySyncOptions extends SyncOptions<FastifyRequest> {
5
+ path?: string;
6
+ server: FastifyInstance;
7
+ }
8
+ export declare function sync({ path, server, ...options }: FastifySyncOptions): {
9
+ close: () => void;
10
+ };
@@ -0,0 +1,15 @@
1
+ import websocket from '@fastify/websocket';
2
+ import { DEFAULT_PATH } from '../shared/protocol.js';
3
+ import { createSyncServer } from './configuration.js';
4
+ import { connectWebSocket } from './websocket-connection.js';
5
+ export function sync({ path = DEFAULT_PATH, server, ...options }) {
6
+ const core = createSyncServer(options);
7
+ server.register(async (scope) => {
8
+ if (!scope.hasDecorator('websocketServer')) {
9
+ await scope.register(websocket);
10
+ }
11
+ scope.get(path, { websocket: true }, (socket, request) => connectWebSocket(core, socket, request));
12
+ scope.addHook('onClose', async () => core.close());
13
+ });
14
+ return { close: () => core.close() };
15
+ }
@@ -0,0 +1,7 @@
1
+ export { createSyncServer } from './configuration.js';
2
+ export type { ServerSocket } from './connection.js';
3
+ export type { ReplaySecret } from './receipts.js';
4
+ export type { SessionAccess } from './server.js';
5
+ export type { SyncOptions } from './server.js';
6
+ export type { SyncServer } from './server.js';
7
+ export type { User } from '../shared/protocol.js';
@@ -0,0 +1 @@
1
+ export { createSyncServer } from './configuration.js';
@@ -0,0 +1,7 @@
1
+ import type { Transaction } from '../shared/protocol.js';
2
+ export declare class Journal {
3
+ private readonly transactions;
4
+ add(transaction: Transaction): void;
5
+ get(id: string): Transaction | undefined;
6
+ missingFrom(known: ReadonlySet<string>): Transaction[];
7
+ }
@@ -0,0 +1,16 @@
1
+ import { JournalEntries } from '../shared/journal-entries.js';
2
+ import { compareTransactions } from '../shared/protocol.js';
3
+ export class Journal {
4
+ transactions = new JournalEntries();
5
+ add(transaction) {
6
+ this.transactions.add(transaction);
7
+ }
8
+ get(id) {
9
+ return this.transactions.get(id);
10
+ }
11
+ missingFrom(known) {
12
+ return [...this.transactions.values()]
13
+ .filter(transaction => !known.has(transaction.id))
14
+ .sort(compareTransactions);
15
+ }
16
+ }
@@ -0,0 +1,4 @@
1
+ import type { ClientMessage } from '../shared/protocol.js';
2
+ import type { User } from '../shared/protocol.js';
3
+ export declare function readClientMessage(data: string): ClientMessage | undefined;
4
+ export declare function isUser(value: unknown): value is User;