plsremind 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.
@@ -0,0 +1,540 @@
1
+ const settleAfter = 5000;
2
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3
+ const shown = {
4
+ item: ["items", "history"],
5
+ list: ["lists"],
6
+ plan: ["plans"],
7
+ profile: ["profile"],
8
+ };
9
+ const views = new WeakMap();
10
+ function randomText(length) {
11
+ const bytes = crypto.getRandomValues(new Uint8Array(length));
12
+ let text = "";
13
+ for (const byte of bytes)
14
+ text += alphabet[byte % alphabet.length];
15
+ return text;
16
+ }
17
+ function same(a, b) {
18
+ if (a === b)
19
+ return true;
20
+ if (a instanceof Date && b instanceof Date)
21
+ return a.getTime() === b.getTime();
22
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object")
23
+ return false;
24
+ if (Array.isArray(a) !== Array.isArray(b))
25
+ return false;
26
+ const keys = Object.keys(a);
27
+ if (keys.length !== Object.keys(b).length)
28
+ return false;
29
+ return keys.every((key) => key in b && same(a[key], b[key]));
30
+ }
31
+ function eventKind(name) {
32
+ if (name.startsWith("item."))
33
+ return "item";
34
+ if (name.startsWith("list."))
35
+ return "list";
36
+ if (name === "plan.updated")
37
+ return "plan";
38
+ if (name === "user.updated")
39
+ return "profile";
40
+ return undefined;
41
+ }
42
+ function completedAt(item) {
43
+ return item.completedAt?.getTime() ?? Number.POSITIVE_INFINITY;
44
+ }
45
+ /** The array from before if nothing in it changed, so that readers see the same snapshot. */
46
+ function kept(before, now) {
47
+ if (before && before.length === now.length && before.every((value, i) => value === now[i])) {
48
+ return before;
49
+ }
50
+ return Object.freeze(now);
51
+ }
52
+ class ViewUser {
53
+ entries = [];
54
+ #base;
55
+ #keepsHistory;
56
+ #stamps = new Map();
57
+ #memos = new Map();
58
+ #items;
59
+ #lists;
60
+ #plans;
61
+ constructor(base, keepsHistory) {
62
+ this.#base = base;
63
+ this.#keepsHistory = keepsHistory;
64
+ }
65
+ get userId() {
66
+ return this.#base.userId;
67
+ }
68
+ get historyCursor() {
69
+ return this.#base.historyCursor;
70
+ }
71
+ touch(kind, id) {
72
+ this.#stamps.set(kind, (this.#stamps.get(kind) ?? 0) + 1);
73
+ const key = `${kind}:${id}`;
74
+ this.#stamps.set(key, (this.#stamps.get(key) ?? 0) + 1);
75
+ }
76
+ forget(kind, id) {
77
+ this.#stamps.delete(`${kind}:${id}`);
78
+ this.#memos.delete(`${kind}:${id}`);
79
+ }
80
+ #of(kind) {
81
+ return this.entries.filter((entry) => entry.kind === kind);
82
+ }
83
+ #overlay(kind, confirmed) {
84
+ const finals = new Map();
85
+ for (const entry of this.#of(kind)) {
86
+ const current = finals.has(entry.id) ? finals.get(entry.id) : confirmed(entry.id);
87
+ if (entry.create)
88
+ finals.set(entry.id, entry.create);
89
+ else if (!entry.update)
90
+ finals.set(entry.id, null);
91
+ else if (current) {
92
+ try {
93
+ finals.set(entry.id, entry.update(current));
94
+ }
95
+ catch (error) {
96
+ console.error("plsremind: a pending change could not be applied", error);
97
+ }
98
+ }
99
+ }
100
+ for (const [id, result] of finals) {
101
+ const key = `${kind}:${id}`;
102
+ const base = confirmed(id);
103
+ const stamp = this.#stamps.get(key) ?? 0;
104
+ const memo = this.#memos.get(key);
105
+ if (memo && memo.base === base && memo.stamp === stamp) {
106
+ finals.set(id, memo.result);
107
+ }
108
+ else {
109
+ this.#memos.set(key, { base, stamp, result });
110
+ }
111
+ }
112
+ return finals;
113
+ }
114
+ #itemsState() {
115
+ const stamp = this.#stamps.get("item") ?? 0;
116
+ const baseItems = this.#base.items();
117
+ const baseHistory = this.#base.history();
118
+ const cached = this.#items;
119
+ if (cached &&
120
+ cached.stamp === stamp &&
121
+ cached.baseItems === baseItems &&
122
+ cached.baseHistory === baseHistory) {
123
+ return cached;
124
+ }
125
+ if (!this.entries.some((entry) => entry.kind === "item")) {
126
+ this.#items = undefined;
127
+ return undefined;
128
+ }
129
+ const finals = this.#overlay("item", (id) => this.#base.item(id));
130
+ const items = [];
131
+ for (const item of baseItems) {
132
+ const final = finals.has(item.id) ? finals.get(item.id) : item;
133
+ if (final && final.status === "open")
134
+ items.push(final);
135
+ }
136
+ let history = [];
137
+ for (const [id, final] of finals) {
138
+ if (!final)
139
+ continue;
140
+ const before = this.#base.item(id)?.status;
141
+ if (final.status === "open" && before !== "open")
142
+ items.push(final);
143
+ else if (final.status === "done" && before !== "done")
144
+ history.push(final);
145
+ }
146
+ for (const item of baseHistory) {
147
+ const final = finals.has(item.id) ? finals.get(item.id) : item;
148
+ if (final && final.status === "done")
149
+ history.push(final);
150
+ }
151
+ history.sort((a, b) => completedAt(b) - completedAt(a));
152
+ if (!this.#keepsHistory())
153
+ history = [];
154
+ this.#items = {
155
+ baseItems,
156
+ baseHistory,
157
+ stamp,
158
+ finals,
159
+ items: kept(cached?.items, items),
160
+ history: kept(cached?.history, history),
161
+ };
162
+ return this.#items;
163
+ }
164
+ items() {
165
+ return this.#itemsState()?.items ?? this.#base.items();
166
+ }
167
+ history() {
168
+ return this.#itemsState()?.history ?? this.#base.history();
169
+ }
170
+ item(id) {
171
+ const state = this.#itemsState();
172
+ if (!state?.finals.has(id))
173
+ return this.#base.item(id);
174
+ const final = state.finals.get(id);
175
+ if (!final || (final.status === "done" && !this.#keepsHistory()))
176
+ return undefined;
177
+ return final;
178
+ }
179
+ #listsState() {
180
+ const stamp = this.#stamps.get("list") ?? 0;
181
+ const base = this.#base.lists();
182
+ const cached = this.#lists;
183
+ if (cached && cached.stamp === stamp && cached.base === base)
184
+ return cached;
185
+ if (!this.entries.some((entry) => entry.kind === "list")) {
186
+ this.#lists = undefined;
187
+ return undefined;
188
+ }
189
+ const finals = this.#overlay("list", (id) => this.#base.list(id));
190
+ const lists = [];
191
+ for (const list of base) {
192
+ const final = finals.has(list.id) ? finals.get(list.id) : list;
193
+ if (final)
194
+ lists.push(final);
195
+ }
196
+ for (const [id, final] of finals) {
197
+ if (final && !this.#base.list(id))
198
+ lists.push(final);
199
+ }
200
+ lists.sort((a, b) => a.position - b.position);
201
+ this.#lists = { base, stamp, finals, lists: kept(cached?.lists, lists) };
202
+ return this.#lists;
203
+ }
204
+ lists() {
205
+ return this.#listsState()?.lists ?? this.#base.lists();
206
+ }
207
+ list(id) {
208
+ const state = this.#listsState();
209
+ if (!state?.finals.has(id))
210
+ return this.#base.list(id);
211
+ return state.finals.get(id) ?? undefined;
212
+ }
213
+ #plansState() {
214
+ const stamp = this.#stamps.get("plan") ?? 0;
215
+ const base = this.#base.plans();
216
+ const cached = this.#plans;
217
+ if (cached && cached.stamp === stamp && cached.base === base)
218
+ return cached;
219
+ if (!this.entries.some((entry) => entry.kind === "plan")) {
220
+ this.#plans = undefined;
221
+ return undefined;
222
+ }
223
+ const finals = this.#overlay("plan", (priority) => this.#base.plan(priority));
224
+ const plans = base.map((plan) => finals.get(plan.priority) ?? plan);
225
+ this.#plans = { base, stamp, finals, plans: kept(cached?.plans, plans) };
226
+ return this.#plans;
227
+ }
228
+ plans() {
229
+ return this.#plansState()?.plans ?? this.#base.plans();
230
+ }
231
+ plan(priority) {
232
+ return this.#plansState()?.finals.get(priority) ?? this.#base.plan(priority);
233
+ }
234
+ get profile() {
235
+ if (!this.entries.some((entry) => entry.kind === "profile"))
236
+ return this.#base.profile;
237
+ const finals = this.#overlay("profile", () => this.#base.profile);
238
+ return finals.get("") ?? this.#base.profile;
239
+ }
240
+ /** The confirmed object an entry is about, if there is one. */
241
+ confirmed(entry) {
242
+ if (entry.kind === "item")
243
+ return this.#base.item(entry.id);
244
+ if (entry.kind === "list")
245
+ return this.#base.list(entry.id);
246
+ if (entry.kind === "plan")
247
+ return this.#base.plan(entry.id);
248
+ return this.#base.profile;
249
+ }
250
+ }
251
+ /** A view of the client's cache that shows changes before the hub confirmed them. */
252
+ export function optimistic(client) {
253
+ let view = views.get(client);
254
+ if (!view)
255
+ views.set(client, (view = build(client)));
256
+ return view;
257
+ }
258
+ function build(client) {
259
+ const cache = client.cache;
260
+ const users = new Map();
261
+ const listeners = new Set();
262
+ const resolved = new Map();
263
+ const answered = new Map();
264
+ const drafts = new Set();
265
+ let list;
266
+ const keepsHistory = () => client.intents.includes("history");
267
+ // An item made in or moved to a draft list would otherwise end up in no list once it is real.
268
+ function inRealList(item) {
269
+ const real = resolved.get(item.listId);
270
+ return real === undefined ? item : { ...item, listId: real };
271
+ }
272
+ function userOf(userId) {
273
+ const base = cache.user(userId);
274
+ if (!base)
275
+ return undefined;
276
+ let user = users.get(base.userId);
277
+ if (!user)
278
+ users.set(base.userId, (user = new ViewUser(base, keepsHistory)));
279
+ return user;
280
+ }
281
+ function notify(change) {
282
+ for (const listener of [...listeners]) {
283
+ try {
284
+ listener(change);
285
+ }
286
+ catch (error) {
287
+ console.error("plsremind: a view listener threw", error);
288
+ }
289
+ }
290
+ }
291
+ function remove(entry, kinds) {
292
+ const batch = entry.batch;
293
+ if (!batch.entries.delete(entry))
294
+ return;
295
+ if (batch.entries.size === 0)
296
+ clearTimeout(batch.timer);
297
+ const user = users.get(batch.userId);
298
+ if (user) {
299
+ user.entries.splice(user.entries.indexOf(entry), 1);
300
+ user.touch(entry.kind, entry.id);
301
+ }
302
+ if (entry.create) {
303
+ drafts.delete(entry.id);
304
+ const realId = answered.get(entry.id);
305
+ answered.delete(entry.id);
306
+ // Found while the list is still a draft; once it is resolved they already read as moved.
307
+ const inDraft = realId !== undefined && entry.kind === "list" && user
308
+ ? user.entries.filter((other) => other.kind === "item" &&
309
+ (other.create ?? user.item(other.id))?.listId === entry.id)
310
+ : [];
311
+ if (realId !== undefined)
312
+ resolved.set(entry.id, realId);
313
+ // Changes made to the draft now belong to the object that took its place.
314
+ for (const other of (realId !== undefined && user?.entries) || []) {
315
+ if (other.id === entry.id && other.kind === entry.kind) {
316
+ other.id = realId;
317
+ user.touch(other.kind, realId);
318
+ }
319
+ }
320
+ for (const other of inDraft) {
321
+ if (other.create)
322
+ other.create = inRealList(other.create);
323
+ user.touch(other.kind, other.id);
324
+ for (const kind of shown.item)
325
+ kinds.add(kind);
326
+ }
327
+ }
328
+ if (user && !user.entries.some((other) => other.kind === entry.kind && other.id === entry.id)) {
329
+ user.forget(entry.kind, entry.id);
330
+ }
331
+ for (const kind of shown[entry.kind])
332
+ kinds.add(kind);
333
+ }
334
+ /** True if an older change to the same object is still pending. */
335
+ function behind(user, entry) {
336
+ for (const other of user.entries) {
337
+ if (other === entry)
338
+ return false;
339
+ if (other.kind === entry.kind && other.id === entry.id)
340
+ return true;
341
+ }
342
+ return false;
343
+ }
344
+ /** True once the confirmed state shows what the entry wanted. */
345
+ function arrived(user, entry) {
346
+ if (entry.create) {
347
+ const realId = answered.get(entry.id);
348
+ return realId !== undefined && user.confirmed({ ...entry, id: realId }) !== undefined;
349
+ }
350
+ if (behind(user, entry))
351
+ return false;
352
+ const confirmed = user.confirmed(entry);
353
+ if (!entry.update)
354
+ return confirmed === undefined;
355
+ if (confirmed === undefined)
356
+ return false;
357
+ try {
358
+ return same(entry.update(confirmed), confirmed);
359
+ }
360
+ catch {
361
+ return true;
362
+ }
363
+ }
364
+ /** The draft of this request that the newly created object most likely came from. */
365
+ function draftOf(user, kind, nonce, born) {
366
+ let best;
367
+ let most = -1;
368
+ for (const entry of user.entries) {
369
+ if (!entry.create || entry.kind !== kind)
370
+ continue;
371
+ if (entry.nonce === nonce)
372
+ return entry;
373
+ if (entry.batch.nonce !== nonce)
374
+ continue;
375
+ const known = answered.get(entry.id);
376
+ if (known === born)
377
+ return entry;
378
+ if (known !== undefined)
379
+ continue;
380
+ const real = user.confirmed({ ...entry, id: born });
381
+ const draft = entry.create;
382
+ const score = Object.keys(draft).filter((key) => key !== "id" && same(draft[key], real?.[key])).length;
383
+ if (score > most)
384
+ [best, most] = [entry, score];
385
+ }
386
+ return best;
387
+ }
388
+ function vanished(user, entry) {
389
+ if (entry.create || entry.kind === "plan" || entry.kind === "profile")
390
+ return false;
391
+ return user.confirmed(entry) === undefined && !drafts.has(entry.id);
392
+ }
393
+ cache.subscribe((change) => {
394
+ const kinds = new Set(change.kinds);
395
+ const user = users.get(change.userId);
396
+ if (user && !cache.user(change.userId)) {
397
+ for (const entry of [...user.entries])
398
+ remove(entry, kinds);
399
+ users.delete(change.userId);
400
+ }
401
+ else if (user) {
402
+ const cause = change.cause;
403
+ const kind = cause ? eventKind(cause.name) : undefined;
404
+ const born = cause?.name.endsWith(".created") ? cause.id : undefined;
405
+ const draft = cause && kind && born !== undefined && typeof cause.nonce === "string"
406
+ ? draftOf(user, kind, cause.nonce, born)
407
+ : undefined;
408
+ for (const entry of [...user.entries]) {
409
+ if (entry === draft) {
410
+ answered.set(entry.id, born);
411
+ remove(entry, kinds);
412
+ continue;
413
+ }
414
+ if (cause && kind === entry.kind && cause.nonce === entry.batch.nonce) {
415
+ const changed = born === undefined && (kind === "profile" || cause.id === entry.id);
416
+ if (!entry.create && changed) {
417
+ remove(entry, kinds);
418
+ continue;
419
+ }
420
+ }
421
+ if (vanished(user, entry) || (entry.batch.answered && arrived(user, entry))) {
422
+ remove(entry, kinds);
423
+ }
424
+ }
425
+ }
426
+ notify({ userId: change.userId, kinds: [...kinds], cause: change.cause });
427
+ });
428
+ async function apply(changes, call, options = {}) {
429
+ const principal = client.principal;
430
+ const own = principal && "userId" in principal ? principal.userId : undefined;
431
+ const userId = options.user === undefined || options.user === "@me" ? own : options.user;
432
+ if (userId === undefined) {
433
+ throw new TypeError("Say which user the changes are for: pass { user }.");
434
+ }
435
+ const batch = {
436
+ nonce: randomText(16),
437
+ userId,
438
+ entries: new Set(),
439
+ answered: false,
440
+ timer: undefined,
441
+ };
442
+ const perDraft = new Map();
443
+ for (const change of changes) {
444
+ if ("create" in change)
445
+ perDraft.set(change.create.id, randomText(16));
446
+ }
447
+ const nonceFor = (tempId) => {
448
+ const nonce = perDraft.get(tempId);
449
+ if (nonce === undefined)
450
+ throw new TypeError(`No draft in this call has the id ${tempId}.`);
451
+ return nonce;
452
+ };
453
+ const user = userOf(userId);
454
+ const kinds = new Set();
455
+ const created = [];
456
+ if (user) {
457
+ for (const change of changes) {
458
+ const entry = {
459
+ kind: change.kind,
460
+ id: "create" in change
461
+ ? change.create.id
462
+ : change.kind === "plan"
463
+ ? change.priority
464
+ : change.kind === "profile"
465
+ ? ""
466
+ : change.id,
467
+ create: "create" in change ? change.create : undefined,
468
+ update: "update" in change ? change.update : undefined,
469
+ nonce: "create" in change ? nonceFor(change.create.id) : undefined,
470
+ batch,
471
+ };
472
+ if (entry.kind === "item" && entry.create)
473
+ entry.create = inRealList(entry.create);
474
+ if (entry.kind === "item" && entry.update) {
475
+ const update = entry.update;
476
+ entry.update = ((value) => inRealList(update(value)));
477
+ }
478
+ if (entry.create) {
479
+ drafts.add(entry.id);
480
+ created.push(entry);
481
+ }
482
+ batch.entries.add(entry);
483
+ user.entries.push(entry);
484
+ user.touch(entry.kind, entry.id);
485
+ for (const kind of shown[entry.kind])
486
+ kinds.add(kind);
487
+ }
488
+ if (kinds.size > 0)
489
+ notify({ userId, kinds: [...kinds], cause: undefined });
490
+ }
491
+ const withdraw = (entries) => {
492
+ const gone = new Set();
493
+ for (const entry of [...entries])
494
+ remove(entry, gone);
495
+ if (gone.size > 0)
496
+ notify({ userId, kinds: [...gone], cause: undefined });
497
+ };
498
+ let result;
499
+ try {
500
+ result = await call(batch.nonce, nonceFor);
501
+ }
502
+ catch (error) {
503
+ withdraw(batch.entries);
504
+ throw error;
505
+ }
506
+ batch.answered = true;
507
+ const only = created.length === 1 ? created[0] : undefined;
508
+ const answeredId = result?.id;
509
+ if (only && batch.entries.has(only) && typeof answeredId === "string") {
510
+ answered.set(only.id, answeredId);
511
+ }
512
+ const current = users.get(userId);
513
+ withdraw([...batch.entries].filter((entry) => !current || arrived(current, entry)));
514
+ if (batch.entries.size > 0) {
515
+ batch.timer = setTimeout(() => withdraw(batch.entries), settleAfter);
516
+ }
517
+ return result;
518
+ }
519
+ return {
520
+ user: (userId) => userOf(userId),
521
+ users: () => {
522
+ const base = cache.users();
523
+ if (list?.base !== base) {
524
+ list = { base, users: Object.freeze(base.map((user) => userOf(user.userId))) };
525
+ }
526
+ return list.users;
527
+ },
528
+ subscribe: (listener) => {
529
+ const own = (change) => listener(change);
530
+ listeners.add(own);
531
+ return () => {
532
+ listeners.delete(own);
533
+ };
534
+ },
535
+ apply,
536
+ tempId: () => `tmp_${randomText(16)}`,
537
+ resolveId: (tempId) => resolved.get(tempId),
538
+ isPending: (tempId) => drafts.has(tempId),
539
+ };
540
+ }