@20baht/live 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,404 @@
1
+ import { applyPatch, requestKey, requestTarget, stableJson, } from './protocol.js';
2
+ export class LiveMutationError extends Error {
3
+ constructor(status, body) {
4
+ super(`the write answered ${status}`);
5
+ this.status = status;
6
+ this.body = body;
7
+ this.name = 'LiveMutationError';
8
+ }
9
+ }
10
+ const GUESS = Symbol('guess');
11
+ export function guess(subscription, apply) {
12
+ return { [GUESS]: { handle: subscription, apply: apply } };
13
+ }
14
+ const browserEnvironment = () => ({
15
+ fetch: (url, init) => globalThis.fetch(url, init),
16
+ setTimeout: (run, ms) => globalThis.setTimeout(run, ms),
17
+ clearTimeout: (handle) => {
18
+ globalThis.clearTimeout(handle);
19
+ },
20
+ onWake: (wake) => {
21
+ if (typeof window === 'undefined')
22
+ return () => undefined;
23
+ const visible = () => {
24
+ if (document.visibilityState === 'visible')
25
+ wake();
26
+ };
27
+ window.addEventListener('online', wake);
28
+ document.addEventListener('visibilitychange', visible);
29
+ return () => {
30
+ window.removeEventListener('online', wake);
31
+ document.removeEventListener('visibilitychange', visible);
32
+ };
33
+ },
34
+ uuid: () => crypto.randomUUID(),
35
+ });
36
+ const MIN_BACKOFF = 1000;
37
+ const MAX_BACKOFF = 60_000;
38
+ export function createLiveClient(options) {
39
+ const env = { ...browserEnvironment(), ...options.environment };
40
+ const base = options.base ?? options.url.replace(/\/[^/]*\/?$/, '');
41
+ const debounceMs = options.debounceMs ?? 20;
42
+ const settleMs = options.settleMs ?? 5000;
43
+ const wires = new Map();
44
+ let nextId = 0;
45
+ let connection;
46
+ let pending;
47
+ let retry;
48
+ let backoff = MIN_BACKOFF;
49
+ let closed = false;
50
+ const view = (wire) => {
51
+ let data = wire.body;
52
+ for (const layer of wire.layers)
53
+ if (data !== undefined)
54
+ data = layer.apply(data);
55
+ return { status: wire.status, data, error: wire.error, pending: wire.layers.length > 0 };
56
+ };
57
+ const notify = (wire) => {
58
+ const state = view(wire);
59
+ for (const listener of [...wire.listeners])
60
+ listener(state);
61
+ };
62
+ const setStatus = (status) => {
63
+ for (const wire of wires.values()) {
64
+ if (wire.status === status || (status === 'connecting' && wire.body !== undefined))
65
+ continue;
66
+ wire.status = status;
67
+ notify(wire);
68
+ }
69
+ };
70
+ const schedule = (ms = debounceMs) => {
71
+ env.clearTimeout(pending);
72
+ pending = env.setTimeout(() => {
73
+ void connect();
74
+ }, ms);
75
+ };
76
+ const again = () => {
77
+ env.clearTimeout(retry);
78
+ retry = env.setTimeout(() => {
79
+ void connect();
80
+ }, backoff);
81
+ backoff = Math.min(backoff * 2, MAX_BACKOFF);
82
+ };
83
+ const connect = async () => {
84
+ env.clearTimeout(retry);
85
+ connection?.abort();
86
+ connection = undefined;
87
+ if (closed || wires.size === 0)
88
+ return;
89
+ const abort = new AbortController();
90
+ connection = abort;
91
+ setStatus('connecting');
92
+ const subscriptions = [...wires.values()].map((wire) => ({
93
+ id: wire.id,
94
+ ...wire.request,
95
+ ...(wire.version === undefined ? {} : { version: wire.version }),
96
+ }));
97
+ let response;
98
+ try {
99
+ response = await env.fetch(options.url, {
100
+ method: 'POST',
101
+ headers: await headersWith({
102
+ 'content-type': 'application/json',
103
+ accept: 'text/event-stream',
104
+ }),
105
+ body: JSON.stringify({ subscriptions }),
106
+ credentials: options.credentials ?? 'include',
107
+ signal: abort.signal,
108
+ });
109
+ }
110
+ catch {
111
+ if (abort.signal.aborted)
112
+ return;
113
+ setStatus('offline');
114
+ again();
115
+ return;
116
+ }
117
+ if (!response.ok || response.body === null) {
118
+ if (response.status === 401)
119
+ await options.onUnauthorized?.();
120
+ setStatus('offline');
121
+ again();
122
+ return;
123
+ }
124
+ const ended = await read(response.body, abort.signal);
125
+ if (abort.signal.aborted)
126
+ return;
127
+ if (ended === 'unauthorized' || ended === 'signed-out')
128
+ await options.onUnauthorized?.();
129
+ if (ended === 'caller-changed')
130
+ schedule(0);
131
+ else {
132
+ setStatus('offline');
133
+ again();
134
+ }
135
+ };
136
+ const read = async (body, signal) => {
137
+ const reader = body.getReader();
138
+ const decoder = new TextDecoder();
139
+ let buffer = '';
140
+ try {
141
+ for (;;) {
142
+ const { value, done } = await reader.read();
143
+ if (done)
144
+ return undefined;
145
+ buffer += decoder.decode(value, { stream: true });
146
+ let cut = buffer.indexOf('\n\n');
147
+ while (cut !== -1) {
148
+ const frame = parseFrame(buffer.slice(0, cut));
149
+ buffer = buffer.slice(cut + 2);
150
+ if (frame?.event === 'end')
151
+ return frame.data.reason;
152
+ if (frame !== undefined && !signal.aborted)
153
+ apply(frame);
154
+ cut = buffer.indexOf('\n\n');
155
+ }
156
+ }
157
+ }
158
+ catch {
159
+ return undefined;
160
+ }
161
+ };
162
+ const apply = (frame) => {
163
+ const wire = wires.get(frame.data.id);
164
+ if (wire === undefined)
165
+ return;
166
+ backoff = MIN_BACKOFF;
167
+ switch (frame.event) {
168
+ case 'snapshot':
169
+ wire.body = frame.data.body;
170
+ wire.version = frame.data.version;
171
+ break;
172
+ case 'patch': {
173
+ const { key, rows, upsert, remove, order, rest } = frame.data;
174
+ const list = (rows === undefined ? wire.body : wire.body[rows]);
175
+ const next = applyPatch(list, { upsert, remove, ...(order === undefined ? {} : { order }) }, key);
176
+ wire.body = rows === undefined ? next : { ...rest, [rows]: next };
177
+ wire.version = frame.data.version;
178
+ break;
179
+ }
180
+ case 'unchanged':
181
+ wire.version = frame.data.version;
182
+ break;
183
+ case 'error':
184
+ wire.status = 'error';
185
+ wire.error = { status: frame.data.status, body: frame.data.body };
186
+ notify(wire);
187
+ return;
188
+ }
189
+ wire.status = 'live';
190
+ wire.error = undefined;
191
+ wire.layers = wire.layers.filter((layer) => !layer.answered);
192
+ notify(wire);
193
+ };
194
+ const headersWith = async (extra) => {
195
+ const headers = new Headers(await options.headers?.());
196
+ for (const [name, value] of Object.entries(extra))
197
+ headers.set(name, value);
198
+ return headers;
199
+ };
200
+ const stopWaking = env.onWake(() => {
201
+ if (connection !== undefined && retry === undefined)
202
+ return;
203
+ backoff = MIN_BACKOFF;
204
+ schedule(0);
205
+ });
206
+ const handleOf = new WeakMap();
207
+ const subscribe = (request, listener) => {
208
+ const key = requestKey(request);
209
+ let wire = [...wires.values()].find((w) => requestKey(w.request) === key);
210
+ if (wire === undefined) {
211
+ nextId += 1;
212
+ wire = {
213
+ id: `s${nextId}`,
214
+ request,
215
+ version: undefined,
216
+ body: undefined,
217
+ status: 'connecting',
218
+ error: undefined,
219
+ layers: [],
220
+ listeners: new Set(),
221
+ handles: 0,
222
+ };
223
+ wires.set(wire.id, wire);
224
+ schedule();
225
+ }
226
+ const held = wire;
227
+ held.handles += 1;
228
+ const mine = new Set();
229
+ const listen = (fn) => {
230
+ const wrapped = fn;
231
+ mine.add(wrapped);
232
+ held.listeners.add(wrapped);
233
+ return () => {
234
+ mine.delete(wrapped);
235
+ held.listeners.delete(wrapped);
236
+ };
237
+ };
238
+ if (listener !== undefined)
239
+ listen(listener);
240
+ let open = true;
241
+ const handle = {
242
+ state: () => view(held),
243
+ listen,
244
+ close: () => {
245
+ if (!open)
246
+ return;
247
+ open = false;
248
+ for (const fn of mine)
249
+ held.listeners.delete(fn);
250
+ held.handles -= 1;
251
+ if (held.handles === 0) {
252
+ wires.delete(held.id);
253
+ schedule();
254
+ }
255
+ },
256
+ };
257
+ handleOf.set(handle, held);
258
+ return handle;
259
+ };
260
+ const mutate = async (request, mutateOptions = {}) => {
261
+ const id = env.uuid();
262
+ const touched = [];
263
+ for (const { [GUESS]: { handle, apply }, } of mutateOptions.optimistic ?? []) {
264
+ const wire = handleOf.get(handle);
265
+ if (wire === undefined)
266
+ continue;
267
+ const layer = { id, apply, answered: false };
268
+ wire.layers.push(layer);
269
+ touched.push({ wire, layer });
270
+ notify(wire);
271
+ }
272
+ const takeOff = () => {
273
+ for (const { wire, layer } of touched) {
274
+ const before = wire.layers.length;
275
+ wire.layers = wire.layers.filter((l) => l !== layer);
276
+ if (wire.layers.length !== before)
277
+ notify(wire);
278
+ }
279
+ };
280
+ let response;
281
+ try {
282
+ const headers = await headersWith({ 'idempotency-key': id });
283
+ const init = {
284
+ method: request.method,
285
+ headers,
286
+ credentials: options.credentials ?? 'include',
287
+ };
288
+ if (request.body !== undefined) {
289
+ headers.set('content-type', 'application/json');
290
+ init.body = JSON.stringify(request.body);
291
+ }
292
+ response = await env.fetch(`${base}${requestTarget({ ...request, method: 'POST' })}`, init);
293
+ }
294
+ catch (error) {
295
+ takeOff();
296
+ throw error;
297
+ }
298
+ const answer = await bodyOf(response);
299
+ if (!response.ok) {
300
+ takeOff();
301
+ throw new LiveMutationError(response.status, answer);
302
+ }
303
+ for (const { layer } of touched)
304
+ layer.answered = true;
305
+ if (touched.length > 0)
306
+ env.setTimeout(takeOff, settleMs);
307
+ return answer;
308
+ };
309
+ return {
310
+ subscribe,
311
+ mutate,
312
+ close: () => {
313
+ closed = true;
314
+ stopWaking();
315
+ env.clearTimeout(pending);
316
+ env.clearTimeout(retry);
317
+ connection?.abort();
318
+ wires.clear();
319
+ },
320
+ };
321
+ }
322
+ function parseFrame(block) {
323
+ let event = '';
324
+ let data = '';
325
+ for (const line of block.split('\n')) {
326
+ if (line.startsWith('event: '))
327
+ event = line.slice(7);
328
+ else if (line.startsWith('data: '))
329
+ data += line.slice(6);
330
+ }
331
+ if (event === '')
332
+ return undefined;
333
+ try {
334
+ return { event, data: JSON.parse(data) };
335
+ }
336
+ catch {
337
+ return undefined;
338
+ }
339
+ }
340
+ async function bodyOf(response) {
341
+ const text = await response.text();
342
+ if (text === '')
343
+ return undefined;
344
+ try {
345
+ return JSON.parse(text);
346
+ }
347
+ catch {
348
+ return text;
349
+ }
350
+ }
351
+ const REGISTRY = Symbol.for('@20baht/live/clients');
352
+ export function liveClient(options) {
353
+ const holder = globalThis;
354
+ const registry = holder[REGISTRY] ?? new Map();
355
+ holder[REGISTRY] = registry;
356
+ const found = registry.get(options.url);
357
+ if (found !== undefined)
358
+ return found;
359
+ const client = createLiveClient(options);
360
+ registry.set(options.url, client);
361
+ return client;
362
+ }
363
+ export function rebase(base, local, incoming) {
364
+ const same = (a, b) => stableJson(a) === stableJson(b);
365
+ const value = {};
366
+ const conflicts = [];
367
+ for (const key of new Set([
368
+ ...Object.keys(base),
369
+ ...Object.keys(local),
370
+ ...Object.keys(incoming),
371
+ ])) {
372
+ const mine = !same(local[key], base[key]);
373
+ const theirs = !same(incoming[key], base[key]);
374
+ const chosen = mine ? local[key] : incoming[key];
375
+ if (chosen !== undefined)
376
+ value[key] = chosen;
377
+ if (mine && theirs && !same(local[key], incoming[key])) {
378
+ conflicts.push({ key, local: local[key], server: incoming[key] });
379
+ }
380
+ }
381
+ return { value: value, base: incoming, conflicts };
382
+ }
383
+ export function fillPath(path, params = {}) {
384
+ return path.replace(/:(\w+)\??/g, (_match, name) => {
385
+ const value = params[name];
386
+ if (value === undefined)
387
+ throw new Error(`live: ${path} needs the parameter "${name}"`);
388
+ return encodeURIComponent(value);
389
+ });
390
+ }
391
+ export function typedLive(client) {
392
+ const toRequest = (method, path, input = {}) => ({
393
+ method,
394
+ path: fillPath(path, input.params),
395
+ ...(input.query === undefined ? {} : { query: input.query }),
396
+ ...(input.body === undefined ? {} : { body: input.body }),
397
+ });
398
+ return {
399
+ subscribe: (method, path, input) => client.subscribe(toRequest(method, path, input)),
400
+ request: (method, path, input) => toRequest(method, path, input),
401
+ mutate: client.mutate,
402
+ close: client.close,
403
+ };
404
+ }