@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,218 @@
1
+ import { compareTransactions } from '../shared/protocol.js';
2
+ import { sameCursor } from '../shared/protocol.js';
3
+ import { sameRange } from '../shared/protocol.js';
4
+ import { newId } from './identity.js';
5
+ import { Journal } from './journal.js';
6
+ import { FormLifecycle } from './lifecycle.js';
7
+ import { Outbox } from './outbox.js';
8
+ export class FormSession {
9
+ session;
10
+ services;
11
+ connection;
12
+ field = null;
13
+ journal;
14
+ lifecycle;
15
+ outbox;
16
+ position = null;
17
+ ready = false;
18
+ retired = false;
19
+ selection = null;
20
+ timer;
21
+ constructor(session, services) {
22
+ this.session = session;
23
+ this.services = services;
24
+ this.outbox = new Outbox(services.debounce);
25
+ }
26
+ attach(form, connection) {
27
+ const { client, collections, ignore, inputPairs, plugins, user } = this.services;
28
+ const journal = new Journal();
29
+ const entries = this.outbox.transactions().sort(compareTransactions);
30
+ for (const transaction of entries) {
31
+ journal.add(transaction);
32
+ }
33
+ this.journal = journal;
34
+ this.lifecycle = new FormLifecycle(form, client, collections, plugins, journal, (type, data, key) => this.publish(type, data, key), field => this.focus(field), position => this.cursor(position), selection => this.range(selection), user, ignore, inputPairs);
35
+ if (entries.length) {
36
+ this.lifecycle.receive(entries);
37
+ }
38
+ if (connection) {
39
+ this.join(connection);
40
+ }
41
+ }
42
+ correct(offset) {
43
+ if (this.journal) {
44
+ this.journal.correct(offset);
45
+ return;
46
+ }
47
+ for (const transaction of this.outbox.transactions()) {
48
+ transaction.timestamp += offset;
49
+ }
50
+ }
51
+ detach() {
52
+ this.lifecycle?.destroy();
53
+ this.lifecycle = undefined;
54
+ this.journal = undefined;
55
+ this.focus(null);
56
+ this.cursor(null);
57
+ this.range(null);
58
+ this.outbox.resume(performance.now());
59
+ this.pump();
60
+ }
61
+ disconnect() {
62
+ clearTimeout(this.timer);
63
+ this.connection = undefined;
64
+ this.ready = false;
65
+ this.lifecycle?.presence([]);
66
+ }
67
+ dispose() {
68
+ this.retired = true;
69
+ this.lifecycle?.destroy();
70
+ this.lifecycle = undefined;
71
+ this.journal = undefined;
72
+ this.disconnect();
73
+ }
74
+ join(connection) {
75
+ this.connection = connection;
76
+ this.ready = false;
77
+ const known = new Set(this.journal?.ids());
78
+ for (const id of this.outbox.ids()) {
79
+ known.add(id);
80
+ }
81
+ this.services.send({ type: 'join', session: this.session, known: [...known] });
82
+ }
83
+ receive(message) {
84
+ const journal = this.journal;
85
+ switch (message.type) {
86
+ case 'ack':
87
+ for (const transaction of message.transactions) {
88
+ journal?.confirm(transaction);
89
+ }
90
+ this.outbox.acknowledge(message.ids);
91
+ this.lifecycle?.changed();
92
+ this.pump();
93
+ break;
94
+ case 'denied':
95
+ this.ready = false;
96
+ clearTimeout(this.timer);
97
+ this.lifecycle?.presence([]);
98
+ break;
99
+ case 'history': {
100
+ this.receiveTransactions(message.transactions, true);
101
+ const now = performance.now();
102
+ this.outbox.resume(now);
103
+ for (const id of message.missing) {
104
+ if (this.outbox.get(id))
105
+ continue;
106
+ const previous = journal?.get(id);
107
+ if (previous) {
108
+ this.outbox.plan(previous, now);
109
+ }
110
+ }
111
+ this.ready = true;
112
+ this.focus(this.field, true);
113
+ if (this.position) {
114
+ this.sendCursor();
115
+ }
116
+ if (this.selection) {
117
+ this.sendRange();
118
+ }
119
+ this.lifecycle?.changed();
120
+ this.pump();
121
+ break;
122
+ }
123
+ case 'presence':
124
+ this.lifecycle?.presence(message.participants, this.connection);
125
+ break;
126
+ case 'cursor':
127
+ this.lifecycle?.cursor(message.client, message.position);
128
+ break;
129
+ case 'range':
130
+ this.lifecycle?.range(message.client, message.selection);
131
+ break;
132
+ case 'transactions':
133
+ this.receiveTransactions(message.transactions, message.recovered);
134
+ break;
135
+ }
136
+ }
137
+ cursor(position) {
138
+ if (sameCursor(this.position, position))
139
+ return;
140
+ this.position = position;
141
+ if (this.ready) {
142
+ this.sendCursor();
143
+ }
144
+ }
145
+ sendCursor() {
146
+ this.services.send({ type: 'cursor', session: this.session, position: this.position });
147
+ }
148
+ range(selection) {
149
+ if (sameRange(this.selection, selection))
150
+ return;
151
+ this.selection = selection;
152
+ if (this.ready) {
153
+ this.sendRange();
154
+ }
155
+ }
156
+ sendRange() {
157
+ this.services.send({ type: 'range', session: this.session, selection: this.selection });
158
+ }
159
+ focus(field, always = false) {
160
+ if (!always && (this.field === field))
161
+ return;
162
+ this.field = field;
163
+ if (this.ready) {
164
+ this.services.send({ type: 'focus', session: this.session, field });
165
+ }
166
+ }
167
+ publish(type, data, key) {
168
+ const transaction = {
169
+ id: newId(),
170
+ client: this.services.client,
171
+ timestamp: this.services.clock.now(),
172
+ type,
173
+ data
174
+ };
175
+ this.journal?.add(transaction);
176
+ const replaced = this.outbox.plan(transaction, performance.now(), key);
177
+ if (replaced) {
178
+ this.journal?.discardPending(replaced);
179
+ }
180
+ this.pump();
181
+ return transaction;
182
+ }
183
+ pump() {
184
+ clearTimeout(this.timer);
185
+ if (this.retired)
186
+ return;
187
+ if (!this.lifecycle && this.outbox.empty) {
188
+ this.retired = true;
189
+ if (this.connection) {
190
+ this.services.send({ type: 'leave', session: this.session });
191
+ }
192
+ this.services.retired();
193
+ return;
194
+ }
195
+ if (!this.ready)
196
+ return;
197
+ const now = performance.now();
198
+ const next = this.outbox.pump(now, transactions => {
199
+ const detached = this.lifecycle ? undefined : true;
200
+ return this.services.send({ type: 'push', session: this.session, transactions, detached });
201
+ }, transaction => this.lifecycle?.prepare(transaction));
202
+ if (next < Infinity) {
203
+ this.timer = setTimeout(() => this.pump(), Math.max(1, Math.ceil(next - now)));
204
+ }
205
+ }
206
+ receiveTransactions(transactions, replay = false) {
207
+ if (!this.journal)
208
+ return;
209
+ this.lifecycle?.drain();
210
+ const journal = this.journal;
211
+ const fresh = transactions.filter(transaction => journal.add(transaction, true))
212
+ .filter(transaction => journal.get(transaction.id) === transaction)
213
+ .sort(compareTransactions);
214
+ if (fresh.length) {
215
+ this.lifecycle?.receive(fresh, replay);
216
+ }
217
+ }
218
+ }
@@ -0,0 +1,3 @@
1
+ export declare function domPath(element: Element, root: Element): string;
2
+ export declare function newId(): string;
3
+ export declare function pageIdentity(url: string): string;
@@ -0,0 +1,27 @@
1
+ export function domPath(element, root) {
2
+ const steps = [];
3
+ for (let node = element; node && (node !== root); node = node.parentElement) {
4
+ let index = 0;
5
+ for (let previous = node.previousElementSibling; previous; previous = previous.previousElementSibling) {
6
+ if (previous.localName === node.localName) {
7
+ index++;
8
+ }
9
+ }
10
+ steps.unshift(node.localName + ':' + index);
11
+ }
12
+ return steps.join('/');
13
+ }
14
+ export function newId() {
15
+ if (typeof crypto.randomUUID === 'function') {
16
+ return crypto.randomUUID();
17
+ }
18
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
19
+ bytes[6] = (bytes[6] & 15) | 64;
20
+ bytes[8] = (bytes[8] & 63) | 128;
21
+ const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
22
+ return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
23
+ }
24
+ export function pageIdentity(url) {
25
+ const page = new URL(url);
26
+ return page.origin + page.pathname;
27
+ }
@@ -0,0 +1,43 @@
1
+ import { autoCollections } from './collections.js';
2
+ import type { CollectionOptions } from './collections.js';
3
+ import type { InputPairOptions } from './field-address.js';
4
+ import type { Plugin } from './plugin.js';
5
+ import { columnOrder } from './plugins/column-order/index.js';
6
+ import { cursor } from './plugins/cursor/index.js';
7
+ import { fields } from './plugins/fields/index.js';
8
+ import { focus } from './plugins/focus/index.js';
9
+ import { naming } from './plugins/naming/index.js';
10
+ import { range } from './plugins/range/index.js';
11
+ import { reconciliation } from './plugins/reconciliation/index.js';
12
+ import { rowOrder } from './plugins/row-order/index.js';
13
+ import { rows } from './plugins/rows/index.js';
14
+ import type { ConnectionStatus } from './transport.js';
15
+ export type { CollectionOptions, RowCreation } from './collections.js';
16
+ export type { FieldValue } from './field-value.js';
17
+ export type { InputPairOptions } from './field-address.js';
18
+ export type { Lifecycle, Plugin, PluginContext } from './plugin.js';
19
+ export type { FocusOptions } from './plugins/focus/index.js';
20
+ export type { FindNamingIndex, NamingIndex } from './plugins/naming/index.js';
21
+ export type { MatchRows, RowAssociation, RowSnapshot } from './plugins/reconciliation/index.js';
22
+ export type { ConnectionStatus } from './transport.js';
23
+ export type { CursorPosition, CursorRange, Participant, RangeSelection, User } from '../shared/protocol.js';
24
+ export { columnOrder, cursor, fields, focus, naming, range, reconciliation, rowOrder, rows };
25
+ export interface SyncOptions {
26
+ collections?: readonly CollectionOptions[];
27
+ debounce?: number;
28
+ endpoint?: string | URL;
29
+ ignore?: string;
30
+ inputPairs?: string | InputPairOptions;
31
+ onStatus?: (status: ConnectionStatus) => void;
32
+ plugins?: readonly Plugin[];
33
+ selector?: string;
34
+ server?: string | URL;
35
+ session?: (form: HTMLFormElement) => string;
36
+ }
37
+ export declare function sync(options?: SyncOptions): {
38
+ destroy(): void;
39
+ };
40
+ export declare namespace sync {
41
+ export { autoCollections };
42
+ }
43
+ export declare function defaultPlugins(): Plugin[];
@@ -0,0 +1,109 @@
1
+ import { DEFAULT_PATH } from '../shared/protocol.js';
2
+ import { Clock } from './clock.js';
3
+ import { autoCollections } from './collections.js';
4
+ import { discoverForms } from './discovery.js';
5
+ import { FormSession } from './form-session.js';
6
+ import { newId } from './identity.js';
7
+ import { columnOrder } from './plugins/column-order/index.js';
8
+ import { cursor } from './plugins/cursor/index.js';
9
+ import { fields } from './plugins/fields/index.js';
10
+ import { focus } from './plugins/focus/index.js';
11
+ import { naming } from './plugins/naming/index.js';
12
+ import { range } from './plugins/range/index.js';
13
+ import { reconciliation } from './plugins/reconciliation/index.js';
14
+ import { rowOrder } from './plugins/row-order/index.js';
15
+ import { rows } from './plugins/rows/index.js';
16
+ import { Transport } from './transport.js';
17
+ export { columnOrder, cursor, fields, focus, naming, range, reconciliation, rowOrder, rows };
18
+ export function sync(options = {}) {
19
+ let connection;
20
+ let user;
21
+ const clock = new Clock();
22
+ const client = newId();
23
+ const debounce = options.debounce ?? 0;
24
+ const plugins = orderedPlugins(options.plugins ?? defaultPlugins());
25
+ const sessions = new Map();
26
+ const transport = new Transport(webSocketURL(options.endpoint ?? options.server), clock, receive, status => {
27
+ if (status === 'disconnected') {
28
+ connection = undefined;
29
+ for (const session of sessions.values()) {
30
+ session.disconnect();
31
+ }
32
+ }
33
+ options.onStatus?.(status);
34
+ });
35
+ if (!Number.isFinite(debounce) || (debounce < 0)) {
36
+ throw new RangeError('Sync debounce must be a non-negative number');
37
+ }
38
+ function receive(message) {
39
+ if (message.type === 'hello') {
40
+ connection = message.client;
41
+ user = message.user;
42
+ const correction = clock.seal();
43
+ for (const session of sessions.values()) {
44
+ if (correction) {
45
+ session.correct(correction);
46
+ }
47
+ session.join(connection);
48
+ }
49
+ }
50
+ else if ('session' in message) {
51
+ sessions.get(message.session)?.receive(message);
52
+ }
53
+ }
54
+ const stop = discoverForms(options.selector ?? 'form', (form, key) => {
55
+ let session = sessions.get(key);
56
+ if (!session) {
57
+ session = new FormSession(key, {
58
+ client, clock, debounce, ignore: options.ignore, inputPairs: options.inputPairs, plugins,
59
+ collections: options.collections ?? autoCollections,
60
+ retired: () => sessions.delete(key),
61
+ send: message => transport.send(message),
62
+ user: () => user
63
+ });
64
+ sessions.set(key, session);
65
+ }
66
+ session.attach(form, connection);
67
+ transport.connect();
68
+ }, key => sessions.get(key)?.detach(), options.session);
69
+ if (!options.session) {
70
+ transport.connect();
71
+ }
72
+ return {
73
+ destroy() {
74
+ stop();
75
+ for (const session of sessions.values()) {
76
+ session.dispose();
77
+ }
78
+ sessions.clear();
79
+ transport.close();
80
+ }
81
+ };
82
+ }
83
+ sync.autoCollections = autoCollections;
84
+ // Let range initialise the shared selection tracker when both text plugins are enabled.
85
+ const pluginOrder = ['reconciliation', 'rows', 'row-order', 'column-order', 'naming', 'fields', 'focus', 'range', 'cursor'];
86
+ export function defaultPlugins() {
87
+ return [reconciliation(), rows(), rowOrder(), columnOrder(), naming(), fields(), focus()];
88
+ }
89
+ function orderedPlugins(plugins) {
90
+ const rank = (name) => {
91
+ const index = pluginOrder.indexOf(name);
92
+ return (index < 0) ? pluginOrder.length : index;
93
+ };
94
+ const unique = new Map(plugins.map(plugin => [plugin.name, plugin]));
95
+ return [...unique.values()].sort((first, second) => rank(first.name) - rank(second.name));
96
+ }
97
+ function webSocketURL(endpoint) {
98
+ const url = new URL(endpoint ?? DEFAULT_PATH, window.location.href);
99
+ if (url.protocol === 'http:') {
100
+ url.protocol = 'ws:';
101
+ }
102
+ if (url.protocol === 'https:') {
103
+ url.protocol = 'wss:';
104
+ }
105
+ if ((url.protocol !== 'ws:') && (url.protocol !== 'wss:')) {
106
+ throw new TypeError('Sync needs a ws: or wss: endpoint');
107
+ }
108
+ return url.href;
109
+ }
@@ -0,0 +1,13 @@
1
+ import type { Transaction } from '../shared/protocol.js';
2
+ export declare class Journal {
3
+ private readonly confirmed;
4
+ private readonly pending;
5
+ private sorted?;
6
+ add(transaction: Transaction, shared?: boolean): boolean;
7
+ confirm(transaction: Transaction): void;
8
+ correct(offset: number): void;
9
+ discardPending(transaction: Transaction): void;
10
+ get(id: string): Transaction | undefined;
11
+ ids(): string[];
12
+ transactions(): readonly Transaction[];
13
+ }
@@ -0,0 +1,59 @@
1
+ import { fieldUpdate } from '../shared/field-update.js';
2
+ import { JournalEntries } from '../shared/journal-entries.js';
3
+ import { compareTransactions } from '../shared/protocol.js';
4
+ export class Journal {
5
+ confirmed = new JournalEntries();
6
+ pending = new Map();
7
+ sorted;
8
+ add(transaction, shared = false) {
9
+ if (shared) {
10
+ if (this.pending.has(transaction.id)) {
11
+ this.confirm(transaction);
12
+ return false;
13
+ }
14
+ if (!this.confirmed.add(transaction))
15
+ return false;
16
+ }
17
+ else {
18
+ if (this.get(transaction.id))
19
+ return false;
20
+ this.pending.set(transaction.id, transaction);
21
+ }
22
+ this.sorted = undefined;
23
+ return true;
24
+ }
25
+ confirm(transaction) {
26
+ const earlier = this.get(transaction.id);
27
+ if (!earlier)
28
+ return;
29
+ earlier.proof = transaction.proof;
30
+ earlier.user = transaction.user;
31
+ if (this.pending.delete(earlier.id)) {
32
+ this.confirmed.add(earlier);
33
+ this.sorted = undefined;
34
+ }
35
+ }
36
+ correct(offset) {
37
+ for (const transaction of this.confirmed.values()) {
38
+ transaction.timestamp += offset;
39
+ }
40
+ for (const transaction of this.pending.values()) {
41
+ transaction.timestamp += offset;
42
+ }
43
+ this.sorted = undefined;
44
+ }
45
+ discardPending(transaction) {
46
+ if ((transaction.type === 'field') && fieldUpdate(transaction.data) && this.pending.delete(transaction.id)) {
47
+ this.sorted = undefined;
48
+ }
49
+ }
50
+ get(id) {
51
+ return this.confirmed.get(id) ?? this.pending.get(id);
52
+ }
53
+ ids() {
54
+ return [...this.confirmed.ids()];
55
+ }
56
+ transactions() {
57
+ return this.sorted ??= [...this.confirmed.values(), ...this.pending.values()].sort(compareTransactions);
58
+ }
59
+ }
@@ -0,0 +1,26 @@
1
+ import type { CursorPosition } from '../shared/protocol.js';
2
+ import type { Participant } from '../shared/protocol.js';
3
+ import type { RangeSelection } from '../shared/protocol.js';
4
+ import type { Transaction } from '../shared/protocol.js';
5
+ import type { User } from '../shared/protocol.js';
6
+ import type { CollectionOptions } from './collections.js';
7
+ import type { InputPairOptions } from './field-address.js';
8
+ import type { Journal } from './journal.js';
9
+ import type { Plugin } from './plugin.js';
10
+ export declare class FormLifecycle {
11
+ private destroyed;
12
+ private observation;
13
+ private plugins;
14
+ private replay;
15
+ private scheduled;
16
+ constructor(form: HTMLFormElement, client: string, options: readonly CollectionOptions[], plugins: readonly Plugin[], journal: Journal, publish: (type: string, data: unknown, key?: string) => Transaction, focus: (field: string | null) => void, cursor: (position: CursorPosition | null) => void, range: (selection: RangeSelection | null) => void, user: () => User | undefined, ignore?: string, inputPairs?: string | InputPairOptions);
17
+ changed(): void;
18
+ drain(): void;
19
+ destroy(): void;
20
+ prepare(transaction: Transaction): void;
21
+ presence(participants: readonly Participant[], self?: string): void;
22
+ cursor(client: string, position: CursorPosition | null): void;
23
+ range(client: string, selection: RangeSelection | null): void;
24
+ receive(transactions: readonly Transaction[], replay?: boolean): void;
25
+ private flush;
26
+ }
@@ -0,0 +1,112 @@
1
+ import { autoCollections } from './collections.js';
2
+ import { Collections } from './collections.js';
3
+ import { FieldAddresses } from './field-address.js';
4
+ import { changesFieldStructure } from './observation.js';
5
+ import { Observation } from './observation.js';
6
+ export class FormLifecycle {
7
+ destroyed = false;
8
+ observation;
9
+ plugins = [];
10
+ replay = false;
11
+ scheduled = false;
12
+ constructor(form, client, options, plugins, journal, publish, focus, cursor, range, user, ignore, inputPairs) {
13
+ const collections = new Collections(form, options, client);
14
+ const configured = options.some(option => !autoCollections.includes(option));
15
+ const addresses = new FieldAddresses(form, collections, ignore, inputPairs);
16
+ const display = { caret: true };
17
+ this.observation = new Observation(form, records => {
18
+ const structure = changesFieldStructure(records);
19
+ if (structure || configured) {
20
+ collections.refresh();
21
+ }
22
+ if (structure) {
23
+ addresses.invalidate();
24
+ }
25
+ for (const plugin of this.plugins) {
26
+ plugin.observe?.(records);
27
+ }
28
+ this.flush('local');
29
+ });
30
+ try {
31
+ for (const plugin of plugins) {
32
+ this.plugins.push(plugin.init({
33
+ addresses, client, collections, cursor, display, focus, form, publish, range, user,
34
+ changed: () => this.changed(),
35
+ history: () => journal.transactions(),
36
+ mute: change => this.observation.mute(change),
37
+ muted: () => this.observation.muted(),
38
+ replaying: () => this.replay,
39
+ snapshot: row => addresses.snapshot(row)
40
+ }));
41
+ }
42
+ }
43
+ catch (error) {
44
+ this.destroy();
45
+ throw error;
46
+ }
47
+ }
48
+ changed() {
49
+ if (this.scheduled || this.destroyed)
50
+ return;
51
+ this.scheduled = true;
52
+ queueMicrotask(() => {
53
+ this.scheduled = false;
54
+ if (this.destroyed)
55
+ return;
56
+ this.flush('local');
57
+ });
58
+ }
59
+ drain() {
60
+ this.observation.drain();
61
+ }
62
+ destroy() {
63
+ this.observation.drain();
64
+ this.observation.stop();
65
+ this.destroyed = true;
66
+ for (const plugin of this.plugins.slice().reverse()) {
67
+ plugin.destroy?.();
68
+ }
69
+ this.plugins = [];
70
+ }
71
+ prepare(transaction) {
72
+ for (const plugin of this.plugins) {
73
+ plugin.prepare?.(transaction);
74
+ }
75
+ }
76
+ presence(participants, self) {
77
+ for (const plugin of this.plugins) {
78
+ plugin.presence?.(participants, self);
79
+ }
80
+ }
81
+ cursor(client, position) {
82
+ for (const plugin of this.plugins) {
83
+ plugin.cursor?.(client, position);
84
+ }
85
+ }
86
+ range(client, selection) {
87
+ for (const plugin of this.plugins) {
88
+ plugin.range?.(client, selection);
89
+ }
90
+ }
91
+ receive(transactions, replay = false) {
92
+ this.observation.mute(() => {
93
+ this.replay = replay;
94
+ try {
95
+ for (const transaction of transactions) {
96
+ for (const plugin of this.plugins) {
97
+ plugin.receive?.(transaction);
98
+ }
99
+ }
100
+ this.flush('remote');
101
+ }
102
+ finally {
103
+ this.replay = false;
104
+ }
105
+ });
106
+ }
107
+ flush(source) {
108
+ for (const plugin of this.plugins) {
109
+ plugin.flush?.(source);
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,11 @@
1
+ export declare class Observation {
2
+ private changed;
3
+ private depth;
4
+ private observer;
5
+ constructor(target: HTMLFormElement, changed: (records: MutationRecord[]) => void);
6
+ drain(): void;
7
+ mute(change: () => void): void;
8
+ muted(): boolean;
9
+ stop(): void;
10
+ }
11
+ export declare function changesFieldStructure(records: readonly MutationRecord[]): boolean;
@@ -0,0 +1,46 @@
1
+ export class Observation {
2
+ changed;
3
+ depth = 0;
4
+ observer;
5
+ constructor(target, changed) {
6
+ this.changed = changed;
7
+ this.observer = new MutationObserver(records => this.changed(records));
8
+ this.observer.observe(target, { attributes: true, characterData: true, childList: true, subtree: true });
9
+ }
10
+ drain() {
11
+ const records = this.observer.takeRecords();
12
+ if (records.length) {
13
+ this.changed(records);
14
+ }
15
+ }
16
+ mute(change) {
17
+ if (!this.depth) {
18
+ this.drain();
19
+ }
20
+ this.depth++;
21
+ try {
22
+ change();
23
+ }
24
+ finally {
25
+ this.depth--;
26
+ if (!this.depth) {
27
+ this.observer.takeRecords();
28
+ }
29
+ }
30
+ }
31
+ muted() {
32
+ return !!this.depth;
33
+ }
34
+ stop() {
35
+ this.observer.disconnect();
36
+ }
37
+ }
38
+ export function changesFieldStructure(records) {
39
+ return records.some(record => {
40
+ if (record.type === 'attributes') {
41
+ return !['checked', 'selected', 'style', 'value'].includes(record.attributeName ?? '');
42
+ }
43
+ return (record.type === 'childList') && (record.target instanceof Element)
44
+ && !record.target.closest('[contenteditable]:not([contenteditable="false"])');
45
+ });
46
+ }