@quad-education/sdk 0.8.0 → 0.9.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 (57) hide show
  1. package/README.md +1 -0
  2. package/dist/contract-tests/apps.d.ts +430 -0
  3. package/dist/contract-tests/apps.js +143 -1
  4. package/dist/contract-tests/harness.d.ts +1 -1
  5. package/dist/contract-tests/harness.js +4 -0
  6. package/dist/contract-tests/lists-and-files.d.ts +19 -0
  7. package/dist/contract-tests/lists-and-files.js +279 -0
  8. package/dist/contract-tests/live.d.ts +3 -0
  9. package/dist/contract-tests/live.js +156 -0
  10. package/dist/contract-tests/notifications.d.ts +3 -0
  11. package/dist/contract-tests/notifications.js +218 -0
  12. package/dist/contract-tests/search-and-totals.d.ts +13 -0
  13. package/dist/contract-tests/search-and-totals.js +226 -0
  14. package/dist/contract-tests/suite.d.ts +5 -0
  15. package/dist/contract-tests/suite.js +27 -1
  16. package/dist/contract-tests/writes.d.ts +3 -0
  17. package/dist/contract-tests/writes.js +265 -0
  18. package/dist/src/base64.d.ts +3 -0
  19. package/dist/src/base64.js +52 -0
  20. package/dist/src/client/connect.d.ts +1 -0
  21. package/dist/src/client/connect.js +1 -0
  22. package/dist/src/client/create-client.js +39 -5
  23. package/dist/src/client/save-file.d.ts +16 -0
  24. package/dist/src/client/save-file.js +28 -0
  25. package/dist/src/client/watch.d.ts +20 -0
  26. package/dist/src/client/watch.js +175 -0
  27. package/dist/src/contract/errors.d.ts +1 -1
  28. package/dist/src/contract/types.d.ts +214 -10
  29. package/dist/src/contract/types.js +4 -1
  30. package/dist/src/engine/engine.d.ts +68 -1
  31. package/dist/src/engine/engine.js +508 -57
  32. package/dist/src/engine/files.d.ts +25 -0
  33. package/dist/src/engine/files.js +88 -0
  34. package/dist/src/engine/index.d.ts +1 -1
  35. package/dist/src/engine/memory-store.d.ts +33 -3
  36. package/dist/src/engine/memory-store.js +116 -8
  37. package/dist/src/engine/notify-content.d.ts +9 -0
  38. package/dist/src/engine/notify-content.js +88 -0
  39. package/dist/src/engine/query.d.ts +14 -2
  40. package/dist/src/engine/query.js +45 -13
  41. package/dist/src/engine/search.d.ts +8 -0
  42. package/dist/src/engine/search.js +32 -0
  43. package/dist/src/engine/storage.d.ts +46 -1
  44. package/dist/src/engine/storage.js +46 -3
  45. package/dist/src/engine/store.d.ts +39 -2
  46. package/dist/src/engine/summary.d.ts +25 -0
  47. package/dist/src/engine/summary.js +107 -0
  48. package/dist/src/engine/validate-input.d.ts +7 -1
  49. package/dist/src/engine/validate-input.js +28 -1
  50. package/dist/src/engine/working-copy.d.ts +30 -0
  51. package/dist/src/engine/working-copy.js +91 -0
  52. package/dist/src/platform-types.d.ts +11 -1
  53. package/dist/src/protocol.d.ts +1 -1
  54. package/dist/src/protocol.js +9 -0
  55. package/dist/src/testing/index.d.ts +2 -0
  56. package/dist/src/testing/index.js +9 -1
  57. package/package.json +4 -4
@@ -0,0 +1,265 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
+ import { describe, expect, it } from 'vitest';
3
+ import { WRITES_APP } from "./apps.js";
4
+ import { expectError } from "./helpers.js";
5
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4];
6
+ const png = () => new Blob([new Uint8Array(PNG)], { type: 'image/png' });
7
+ /** Unique rules (D149), all-or-nothing writes and conditional writes (D150): what ADR 0040 adds. */
8
+ export function writes({ env, useApp, staff, student, otherStudent }) {
9
+ const count = async (sdk, entity) => (await sdk.db.entity(entity).list({ limit: 200 })).items.length;
10
+ describe('db unique rules (D149)', () => {
11
+ useApp(WRITES_APP);
12
+ it('refuses a second record with the same value, on create and on update', async () => {
13
+ const slots = (await env().connect(staff)).db.entity('slot');
14
+ const nine = await slots.create({ label: '9:00', status: 'free' });
15
+ const e = await expectError(slots.create({ label: '9:00', status: 'free' }), 'CONFLICT');
16
+ expect(e.details).toMatchObject({ entity: 'slot', fields: ['label'] });
17
+ expect(e.message).toContain('label');
18
+ const ten = await slots.create({ label: '10:00', status: 'free' });
19
+ await expectError(slots.update(ten.id, { label: '9:00' }), 'CONFLICT');
20
+ // A record never clashes with itself.
21
+ expect((await slots.update(nine.id, { label: '9:00', status: 'taken' })).status).toBe('taken');
22
+ // Once the value is given up, it can be taken.
23
+ await slots.delete(nine.id);
24
+ expect((await slots.update(ten.id, { label: '9:00' })).label).toBe('9:00');
25
+ });
26
+ it('compares a combination together, and text exactly', async () => {
27
+ const bookings = (await env().connect(staff)).db.entity('booking');
28
+ await bookings.create({ slotLabel: 'a', who: 'sam', term: 't1' });
29
+ expect((await bookings.create({ slotLabel: 'b', who: 'sam', term: 't2' })).term).toBe('t2');
30
+ expect((await bookings.create({ slotLabel: 'c', who: 'Sam', term: 't1' })).who).toBe('Sam');
31
+ const e = await expectError(bookings.create({ slotLabel: 'd', who: 'sam', term: 't1' }), 'CONFLICT');
32
+ expect(e.details.fields).toEqual(['who', 'term']);
33
+ });
34
+ it('does not bind a record that leaves one of the fields empty', async () => {
35
+ const bookings = (await env().connect(staff)).db.entity('booking');
36
+ await bookings.create({ slotLabel: 'a', who: 'sam' });
37
+ await bookings.create({ slotLabel: 'b', who: 'sam' });
38
+ const c = await bookings.create({ slotLabel: 'c', who: 'sam', term: 't1' });
39
+ const d = await bookings.create({ slotLabel: 'd', who: 'sam' });
40
+ // Filling the field in brings the rule to bear; clearing it again lets go.
41
+ await expectError(bookings.update(d.id, { term: 't1' }), 'CONFLICT');
42
+ await bookings.update(c.id, { term: null });
43
+ expect((await bookings.update(d.id, { term: 't1' })).term).toBe('t1');
44
+ });
45
+ it('covers a record the writer cannot read, and never says whose it is', async () => {
46
+ const first = await (await env().connect(student)).db
47
+ .entity('booking')
48
+ .create({ slotLabel: 'last-slot' });
49
+ const another = (await env().connect(otherStudent)).db.entity('booking');
50
+ await expectError(another.get(first.id), 'NOT_FOUND');
51
+ const e = await expectError(another.create({ slotLabel: 'last-slot' }), 'CONFLICT');
52
+ expect(JSON.stringify([e.message, e.details])).not.toContain(first.id);
53
+ expect(JSON.stringify([e.message, e.details])).not.toContain(student.personId);
54
+ });
55
+ it('lets exactly one of two writes started together take a value', async () => {
56
+ const a = (await env().connect(student)).db.entity('booking');
57
+ const b = (await env().connect(otherStudent)).db.entity('booking');
58
+ const results = await Promise.allSettled([
59
+ a.create({ slotLabel: 'contested' }),
60
+ b.create({ slotLabel: 'contested' }),
61
+ a.create({ slotLabel: 'contested' }),
62
+ ]);
63
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
64
+ for (const r of results)
65
+ if (r.status === 'rejected')
66
+ expect(r.reason.code).toBe('CONFLICT');
67
+ expect(await count(await env().connect(staff), 'booking')).toBe(1);
68
+ });
69
+ it('returns the first record again for a repeated idempotency key, before any rule is checked', async () => {
70
+ const slots = (await env().connect(staff)).db.entity('slot');
71
+ const made = await slots.create({ label: 'k', status: 'free' }, { idempotencyKey: 'k1' });
72
+ expect((await slots.create({ label: 'k', status: 'free' }, { idempotencyKey: 'k1' })).id).toBe(made.id);
73
+ });
74
+ it('limits the text a rule compares', async () => {
75
+ const slots = (await env().connect(staff)).db.entity('slot');
76
+ await expectError(slots.create({ label: 'x'.repeat(256), status: 'free' }), 'VALIDATION');
77
+ expect((await slots.create({ label: 'x'.repeat(255), status: 'free' })).id).toBeTruthy();
78
+ });
79
+ });
80
+ describe('db writes only if the record is unchanged (D150)', () => {
81
+ useApp(WRITES_APP);
82
+ it('updates when the record still holds the values, and refuses when it does not', async () => {
83
+ const slots = (await env().connect(staff)).db.entity('slot');
84
+ const slot = await slots.create({ label: '9:00', status: 'free', seats: 2 });
85
+ const taken = await slots.update(slot.id, { status: 'taken' }, { if: { status: 'free' } });
86
+ expect(taken.status).toBe('taken');
87
+ const e = await expectError(slots.update(slot.id, { status: 'taken' }, { if: { status: 'free' } }), 'CONFLICT');
88
+ expect(e.details).toMatchObject({ entity: 'slot', id: slot.id, fields: ['status'] });
89
+ // Several fields must all hold, and null means "is empty".
90
+ await expectError(slots.update(slot.id, { seats: 1 }, { if: { status: 'taken', seats: 3 } }), 'CONFLICT');
91
+ expect((await slots.update(slot.id, { seats: 1 }, { if: { status: 'taken', seats: 2 } })).seats).toBe(1);
92
+ await expectError(slots.update(slot.id, { seats: 5 }, { if: { secret: 'x' } }), 'CONFLICT');
93
+ expect((await slots.update(slot.id, { seats: 5 }, { if: { secret: null } })).seats).toBe(5);
94
+ });
95
+ it('deletes on the same condition', async () => {
96
+ const slots = (await env().connect(staff)).db.entity('slot');
97
+ const slot = await slots.create({ label: '9:00', status: 'taken' });
98
+ await expectError(slots.delete(slot.id, { if: { status: 'free' } }), 'CONFLICT');
99
+ expect((await slots.get(slot.id)).status).toBe('taken');
100
+ await slots.delete(slot.id, { if: { status: 'taken' } });
101
+ await expectError(slots.get(slot.id), 'NOT_FOUND');
102
+ });
103
+ it('takes only single values of fields the writer is shown', async () => {
104
+ const sdk = await env().connect(staff);
105
+ const slot = await sdk.db.entity('slot').create({ label: '9:00', status: 'free' });
106
+ const slots = sdk.db.entity('slot');
107
+ await expectError(slots.update(slot.id, { seats: 1 }, { if: 'free' }), 'VALIDATION');
108
+ await expectError(slots.update(slot.id, { seats: 1 }, { if: { nope: 1 } }), 'VALIDATION');
109
+ await expectError(slots.update(slot.id, { seats: 1 }, { if: { status: { ne: 'free' } } }), 'VALIDATION');
110
+ expect((await slots.get(slot.id)).seats).toBeUndefined();
111
+ });
112
+ it('lets exactly one of two people take the last seat', async () => {
113
+ const sdk = await env().connect(staff);
114
+ const slots = sdk.db.entity('slot');
115
+ const slot = await slots.create({ label: '9:00', status: 'free' });
116
+ const take = () => slots.update(slot.id, { status: 'taken' }, { if: { status: 'free' } });
117
+ const results = await Promise.allSettled([take(), take(), take()]);
118
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
119
+ });
120
+ });
121
+ describe('db.batch: all or nothing (D150)', () => {
122
+ useApp(WRITES_APP);
123
+ it('writes every operation and returns the results in order', async () => {
124
+ await env().control.setClock('2026-03-04T03:00:00.000Z');
125
+ const sdk = await env().connect(staff);
126
+ const slot = await sdk.db.entity('slot').create({ label: '9:00', status: 'free' });
127
+ const old = await sdk.db.entity('booking').create({ slotLabel: 'old' });
128
+ const results = await sdk.db.batch([
129
+ { create: 'booking', input: { slotLabel: '9:00', who: 'sam' } },
130
+ { update: 'slot', id: slot.id, patch: { status: 'taken' }, if: { status: 'free' } },
131
+ { delete: 'booking', id: old.id },
132
+ ]);
133
+ expect(results).toHaveLength(3);
134
+ expect(results[0]).toMatchObject({ slotLabel: '9:00', createdBy: staff.personId });
135
+ expect(results[1]).toMatchObject({ id: slot.id, status: 'taken' });
136
+ expect(results[2]).toBeNull();
137
+ expect(await sdk.db.entity('booking').get(results[0].id)).toEqual(results[0]);
138
+ await expectError(sdk.db.entity('booking').get(old.id), 'NOT_FOUND');
139
+ });
140
+ it('writes nothing when any operation fails, and says which one', async () => {
141
+ const sdk = await env().connect(staff);
142
+ const slot = await sdk.db.entity('slot').create({ label: '9:00', status: 'taken' });
143
+ const kept = await sdk.db.entity('booking').create({ slotLabel: 'kept' });
144
+ const proof = await sdk.files.upload(png());
145
+ const e = await expectError(sdk.db.batch([
146
+ { create: 'booking', input: { slotLabel: 'new', proof: proof.id } },
147
+ { delete: 'booking', id: kept.id },
148
+ { update: 'slot', id: slot.id, patch: { status: 'taken' }, if: { status: 'free' } },
149
+ ]), 'CONFLICT');
150
+ expect(e.details).toMatchObject({ index: 2, entity: 'slot' });
151
+ expect(e.message).toMatch(/^operation 3: /);
152
+ // Neither the create nor the delete happened, and the file is still unattached and usable.
153
+ expect(await count(sdk, 'booking')).toBe(1);
154
+ expect((await sdk.db.entity('booking').get(kept.id)).id).toBe(kept.id);
155
+ const attached = await sdk.db.entity('booking').create({ slotLabel: 'new', proof: proof.id });
156
+ expect(attached.proof).toBe(proof.id);
157
+ });
158
+ it('checks each operation as it is on its own', async () => {
159
+ const sdk = await env().connect(staff);
160
+ const fail = async (ops, code, index) => {
161
+ const e = await expectError(sdk.db.batch(ops), code);
162
+ expect(e.details.index).toBe(index);
163
+ };
164
+ await fail([{ create: 'booking', input: { slotLabel: 1 } }], 'VALIDATION', 0);
165
+ await fail([
166
+ { create: 'booking', input: { slotLabel: 'a' } },
167
+ { update: 'booking', id: 'booking_nothing', patch: { who: 'x' } },
168
+ ], 'NOT_FOUND', 1);
169
+ await fail([{ create: 'nope', input: {} }], 'VALIDATION', 0);
170
+ const asStudent = await env().connect(student);
171
+ const e = await expectError(asStudent.db.batch([{ create: 'slot', input: { label: 'x', status: 'free' } }]), 'NOT_PERMITTED');
172
+ expect(e.details.index).toBe(0);
173
+ expect(await count(sdk, 'booking')).toBe(0);
174
+ });
175
+ it('lets a later operation see the earlier ones', async () => {
176
+ const sdk = await env().connect(staff);
177
+ // Two creates that would clash with each other.
178
+ const e = await expectError(sdk.db.batch([
179
+ { create: 'slot', input: { label: 'same', status: 'free' } },
180
+ { create: 'slot', input: { label: 'same', status: 'free' } },
181
+ ]), 'CONFLICT');
182
+ expect(e.details.index).toBe(1);
183
+ expect(await count(sdk, 'slot')).toBe(0);
184
+ // Giving a value up and taking it in one batch works, in that order.
185
+ const held = await sdk.db.entity('slot').create({ label: 'held', status: 'free' });
186
+ const [, made] = await sdk.db.batch([
187
+ { delete: 'slot', id: held.id },
188
+ { create: 'slot', input: { label: 'held', status: 'taken' } },
189
+ ]);
190
+ expect(made.status).toBe('taken');
191
+ // Two updates of one record apply in order.
192
+ const [, second] = await sdk.db.batch([
193
+ { update: 'slot', id: made.id, patch: { seats: 1 } },
194
+ { update: 'slot', id: made.id, patch: { seats: 2 }, if: { seats: 1 } },
195
+ ]);
196
+ expect(second.seats).toBe(2);
197
+ });
198
+ it('attaches and removes files with the batch', async () => {
199
+ const sdk = await env().connect(staff);
200
+ const [a, b] = [await sdk.files.upload(png()), await sdk.files.upload(png())];
201
+ const [first] = await sdk.db.batch([
202
+ { create: 'booking', input: { slotLabel: 'a', proof: a.id } },
203
+ ]);
204
+ expect((await sdk.files.info(a.id)).id).toBe(a.id);
205
+ await sdk.db.batch([
206
+ { update: 'booking', id: first.id, patch: { proof: b.id } },
207
+ { create: 'booking', input: { slotLabel: 'b' } },
208
+ ]);
209
+ await expectError(sdk.files.info(a.id), 'NOT_FOUND');
210
+ await sdk.db.batch([{ delete: 'booking', id: first.id }]);
211
+ await expectError(sdk.files.info(b.id), 'NOT_FOUND');
212
+ // One file can't be attached twice in one batch.
213
+ const c = await sdk.files.upload(png());
214
+ await expectError(sdk.db.batch([
215
+ { create: 'booking', input: { slotLabel: 'c1', proof: c.id } },
216
+ { create: 'booking', input: { slotLabel: 'c2', proof: c.id } },
217
+ ]), 'VALIDATION');
218
+ expect((await sdk.files.info(c.id)).id).toBe(c.id);
219
+ });
220
+ it('writes once for a repeated key, for the batch and for each create in it', async () => {
221
+ const sdk = await env().connect(staff);
222
+ const ops = [
223
+ { create: 'booking', input: { slotLabel: 'a' } },
224
+ { create: 'booking', input: { slotLabel: 'b' } },
225
+ ];
226
+ const first = await sdk.db.batch(ops, { idempotencyKey: 'import-1' });
227
+ const again = await sdk.db.batch(ops, { idempotencyKey: 'import-1' });
228
+ expect(again.map((r) => r.id)).toEqual(first.map((r) => r.id));
229
+ expect(await count(sdk, 'booking')).toBe(2);
230
+ // A failed batch remembers nothing: the same keys work afterwards.
231
+ const rows = [
232
+ { create: 'booking', input: { slotLabel: 'c' }, idempotencyKey: 'row-c' },
233
+ { create: 'booking', input: { slotLabel: 'a' }, idempotencyKey: 'row-a' },
234
+ ];
235
+ await expectError(sdk.db.batch(rows), 'CONFLICT');
236
+ expect(await count(sdk, 'booking')).toBe(2);
237
+ const [c] = await sdk.db.batch([rows[0]]);
238
+ const [cAgain] = await sdk.db.batch([rows[0]]);
239
+ expect(cAgain.id).toBe(c.id);
240
+ expect(await count(sdk, 'booking')).toBe(3);
241
+ });
242
+ it('takes 1 to 25 well-formed operations', async () => {
243
+ const sdk = await env().connect(staff);
244
+ await expectError(sdk.db.batch([]), 'VALIDATION');
245
+ await expectError(sdk.db.batch('nope'), 'VALIDATION');
246
+ await expectError(sdk.db.batch([{ upsert: 'slot' }]), 'VALIDATION');
247
+ await expectError(sdk.db.batch([{ create: 'slot', delete: 'slot', input: {}, id: 'x' }]), 'VALIDATION');
248
+ const many = (n) => Array.from({ length: n }, (_, i) => ({ create: 'booking', input: { slotLabel: `s${i}` } }));
249
+ await expectError(sdk.db.batch(many(26)), 'VALIDATION');
250
+ expect(await sdk.db.batch(many(25))).toHaveLength(25);
251
+ expect(await count(sdk, 'booking')).toBe(25);
252
+ });
253
+ it('survives a reload whole', async () => {
254
+ const sdk = await env().connect(staff);
255
+ await sdk.db.batch([
256
+ { create: 'slot', input: { label: 'a', status: 'free' } },
257
+ { create: 'slot', input: { label: 'b', status: 'free' } },
258
+ ]);
259
+ await env().control.restart();
260
+ const again = await env().connect(staff);
261
+ expect(await count(again, 'slot')).toBe(2);
262
+ await expectError(again.db.entity('slot').create({ label: 'a', status: 'free' }), 'CONFLICT');
263
+ });
264
+ });
265
+ }
@@ -0,0 +1,3 @@
1
+ export declare function toBase64(bytes: Uint8Array): string;
2
+ /** The bytes a base64 string holds, or null when it is not base64. */
3
+ export declare function fromBase64(text: string): Uint8Array | null;
@@ -0,0 +1,52 @@
1
+ // Base64 for a file's contents (D148). The protocol stays JSON on every transport (D15), so the two calls that move
2
+ // a file carry its bytes as text. Written out here because the SDK's core uses no DOM or Node globals.
3
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4
+ const LOOKUP = new Uint8Array(128).fill(255);
5
+ for (let i = 0; i < ALPHABET.length; i++)
6
+ LOOKUP[ALPHABET.charCodeAt(i)] = i;
7
+ export function toBase64(bytes) {
8
+ const parts = [];
9
+ // In chunks, so a large file never becomes one enormous argument list or string concatenation.
10
+ const CHUNK = 3 * 8192;
11
+ for (let start = 0; start < bytes.length; start += CHUNK) {
12
+ const end = Math.min(start + CHUNK, bytes.length);
13
+ let out = '';
14
+ for (let i = start; i < end; i += 3) {
15
+ const a = bytes[i];
16
+ const b = i + 1 < end ? bytes[i + 1] : 0;
17
+ const c = i + 2 < end ? bytes[i + 2] : 0;
18
+ out += ALPHABET[a >> 2] + ALPHABET[((a & 3) << 4) | (b >> 4)];
19
+ out += i + 1 < end ? ALPHABET[((b & 15) << 2) | (c >> 6)] : '=';
20
+ out += i + 2 < end ? ALPHABET[c & 63] : '=';
21
+ }
22
+ parts.push(out);
23
+ }
24
+ return parts.join('');
25
+ }
26
+ /** The bytes a base64 string holds, or null when it is not base64. */
27
+ export function fromBase64(text) {
28
+ if (text.length % 4 !== 0)
29
+ return null;
30
+ const padding = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0;
31
+ const bytes = new Uint8Array((text.length / 4) * 3 - padding);
32
+ let at = 0;
33
+ for (let i = 0; i < text.length; i += 4) {
34
+ const last = i + 4 === text.length;
35
+ const v = [0, 1, 2, 3].map((k) => {
36
+ const code = text.charCodeAt(i + k);
37
+ if (last && k >= 4 - padding)
38
+ return code === 61 ? 0 : 255;
39
+ return code < 128 ? LOOKUP[code] : 255;
40
+ });
41
+ if (v.includes(255))
42
+ return null;
43
+ const n = (v[0] << 18) | (v[1] << 12) | (v[2] << 6) | v[3];
44
+ if (at < bytes.length)
45
+ bytes[at++] = n >> 16;
46
+ if (at < bytes.length)
47
+ bytes[at++] = (n >> 8) & 255;
48
+ if (at < bytes.length)
49
+ bytes[at++] = n & 255;
50
+ }
51
+ return bytes;
52
+ }
@@ -8,3 +8,4 @@ export type ConnectOptions = HandshakeOptions;
8
8
  */
9
9
  export declare function connect(options?: ConnectOptions): Promise<QuadSdk>;
10
10
  export type { QuadSdk };
11
+ export { saveFile, type SavedFile } from './save-file.ts';
@@ -10,3 +10,4 @@ export async function connect(options = {}) {
10
10
  const { port, session } = await handshake(options);
11
11
  return createSdkClient(portTransport(port, session.clock), session);
12
12
  }
13
+ export { saveFile } from "./save-file.js";
@@ -1,5 +1,8 @@
1
1
  import { ENTITY_NAMES } from '@quad-education/canonical';
2
- import { SDK_VERSION } from "../contract/types.js";
2
+ import { fromBase64, toBase64 } from "../base64.js";
3
+ import { QuadError } from "../contract/errors.js";
4
+ import { MAX_FILE_BYTES, SDK_VERSION } from "../contract/types.js";
5
+ import { createWatcher } from "./watch.js";
3
6
  const dateInZone = (instant, timeZone) => new Intl.DateTimeFormat('en-CA', {
4
7
  timeZone,
5
8
  year: 'numeric',
@@ -10,6 +13,13 @@ const dateInZone = (instant, timeZone) => new Intl.DateTimeFormat('en-CA', {
10
13
  export function createSdkClient(transport, session, context) {
11
14
  const call = (method, params = {}) => transport.call(method, params, context);
12
15
  const nowMs = () => transport.nowMs();
16
+ const watcher = createWatcher((entities) => call('db.changes', { entities }));
17
+ /** A write through this client is followed by a check of its watches (D157). */
18
+ const write = async (method, params) => {
19
+ const result = await call(method, params);
20
+ watcher.wrote();
21
+ return result;
22
+ };
13
23
  const school = {
14
24
  info: () => call('school.info'),
15
25
  };
@@ -37,14 +47,18 @@ export function createSdkClient(transport, session, context) {
37
47
  school: Object.freeze(school),
38
48
  db: {
39
49
  entity: (name) => Object.freeze({
40
- create: (input, options = {}) => call('db.create', { entity: name, input, options }),
41
- update: (id, patch) => call('db.update', { entity: name, id, patch }),
50
+ create: (input, options = {}) => write('db.create', { entity: name, input, options }),
51
+ update: (id, patch, options = {}) => write('db.update', { entity: name, id, patch, options }),
42
52
  get: (id) => call('db.get', { entity: name, id }),
43
53
  list: (options = {}) => call('db.list', { entity: name, options }),
44
- delete: async (id) => {
45
- await call('db.delete', { entity: name, id });
54
+ count: (options = {}) => call('db.count', { entity: name, options }),
55
+ summarise: (options = {}) => call('db.summarise', { entity: name, options }),
56
+ delete: async (id, options = {}) => {
57
+ await write('db.delete', { entity: name, id, options });
46
58
  },
47
59
  }),
60
+ batch: (ops, options = {}) => write('db.batch', { ops, options }),
61
+ watch: watcher.watch,
48
62
  },
49
63
  notify: { send: (input) => call('notify.send', input) },
50
64
  tasks: {
@@ -64,6 +78,26 @@ export function createSdkClient(transport, session, context) {
64
78
  record: (input) => call('audit.record', input),
65
79
  list: (options = {}) => call('audit.list', options),
66
80
  },
81
+ files: {
82
+ upload: async (file, options = {}) => {
83
+ if (file === null || typeof file !== 'object' || typeof file.arrayBuffer !== 'function')
84
+ throw new QuadError('VALIDATION', 'files.upload takes a File or a Blob');
85
+ const bytes = new Uint8Array(await file.arrayBuffer());
86
+ // Checked here too, so a file that is too large is never encoded and sent.
87
+ if (bytes.length > MAX_FILE_BYTES)
88
+ throw new QuadError('VALIDATION', `a file can be at most ${MAX_FILE_BYTES / (1024 * 1024)} MB`);
89
+ return call('files.upload', {
90
+ name: options.name ?? file.name,
91
+ type: file.type,
92
+ data: toBase64(bytes),
93
+ });
94
+ },
95
+ info: (id) => call('files.info', { id }),
96
+ read: async (id) => {
97
+ const { info, data } = (await call('files.read', { id }));
98
+ return { info, bytes: fromBase64(data) ?? new Uint8Array() };
99
+ },
100
+ },
67
101
  clock: {
68
102
  now: () => new Date(nowMs()).toISOString(),
69
103
  today: () => dateInZone(new Date(nowMs()), session.timezone),
@@ -0,0 +1,16 @@
1
+ /** A file an app has made, to hand to the person (D156). */
2
+ export type SavedFile = {
3
+ /** The name it is saved under, e.g. `notes.csv`. Any folders in it are dropped. */
4
+ readonly name: string;
5
+ /** The media type, e.g. `text/csv` or `application/pdf`. */
6
+ readonly type: string;
7
+ /** The contents: text, or bytes such as a PDF library returns. */
8
+ readonly data: string | Uint8Array | ArrayBuffer | Blob;
9
+ };
10
+ /**
11
+ * Gives the person a file the app has made: a spreadsheet, a PDF, a list. The browser saves it as a download;
12
+ * nothing is sent anywhere. To keep a file with the app's records instead, use `sdk.files.upload`.
13
+ *
14
+ * saveFile({ name: 'class-list.csv', type: 'text/csv', data: csv })
15
+ */
16
+ export declare function saveFile(file: SavedFile): void;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Gives the person a file the app has made: a spreadsheet, a PDF, a list. The browser saves it as a download;
3
+ * nothing is sent anywhere. To keep a file with the app's records instead, use `sdk.files.upload`.
4
+ *
5
+ * saveFile({ name: 'class-list.csv', type: 'text/csv', data: csv })
6
+ */
7
+ export function saveFile(file) {
8
+ const name = file.name.split(/[\\/]/).pop()?.trim();
9
+ if (!name)
10
+ throw new Error('saveFile: give the file a name');
11
+ if (typeof file.type !== 'string' || file.type === '')
12
+ throw new Error('saveFile: give the file a type, such as text/csv');
13
+ // A text file opens correctly in a spreadsheet only when it says it is UTF-8.
14
+ const type = /^text\//.test(file.type) && !/charset=/i.test(file.type)
15
+ ? `${file.type};charset=utf-8`
16
+ : file.type;
17
+ const blob = file.data instanceof Blob ? file.data : new Blob([file.data], { type });
18
+ const url = URL.createObjectURL(blob);
19
+ const link = document.createElement('a');
20
+ link.href = url;
21
+ link.download = name;
22
+ link.style.display = 'none';
23
+ document.body.append(link);
24
+ link.click();
25
+ link.remove();
26
+ // The download has started by now; the address is no longer needed.
27
+ setTimeout(() => URL.revokeObjectURL(url), 0);
28
+ }
@@ -0,0 +1,20 @@
1
+ import type { DbWatch } from '../contract/types.ts';
2
+ /** How often a watch asks when the app doesn't say (D157). */
3
+ export declare const WATCH_INTERVAL_MS = 5000;
4
+ /** The fastest a watch may ask. */
5
+ export declare const MIN_WATCH_INTERVAL_MS = 2000;
6
+ type Options = {
7
+ readonly intervalMs?: number;
8
+ readonly onError?: (error: Error) => void;
9
+ };
10
+ /**
11
+ * The watches of one SDK client (D157). They share one timer and one request: each round asks Quad for the
12
+ * stamps of every watched entity, and runs the callbacks whose entities changed. The timer stops while the page
13
+ * is hidden, and slows after errors until a round works again.
14
+ */
15
+ export declare function createWatcher(changes: (entities: readonly string[]) => Promise<Record<string, string>>): {
16
+ watch(entities: unknown, callback: unknown, options?: Options): DbWatch;
17
+ /** The app wrote through this client: ask straight away, so the person sees their own change at once. */
18
+ wrote(): void;
19
+ };
20
+ export {};
@@ -0,0 +1,175 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ /** How often a watch asks when the app doesn't say (D157). */
3
+ export const WATCH_INTERVAL_MS = 5000;
4
+ /** The fastest a watch may ask. */
5
+ export const MIN_WATCH_INTERVAL_MS = 2000;
6
+ /** The slowest it asks after errors. */
7
+ const MAX_BACKOFF_MS = 60_000;
8
+ /** Timers as every runtime has them. The SDK's core is built with neither the browser's types nor Node's. */
9
+ const timers = globalThis;
10
+ const asError = (e) => (e instanceof Error ? e : new Error(String(e)));
11
+ /** An error nobody asked to be told about is the app's to see, not ours to swallow. */
12
+ const surface = (e) => void timers.setTimeout(() => {
13
+ throw e;
14
+ }, 0);
15
+ /** Quad's answer is about the watch itself, so asking again will not help. */
16
+ const final = (e) => e instanceof QuadError && (e.code === 'VALIDATION' || e.code === 'NOT_PERMITTED');
17
+ /**
18
+ * The watches of one SDK client (D157). They share one timer and one request: each round asks Quad for the
19
+ * stamps of every watched entity, and runs the callbacks whose entities changed. The timer stops while the page
20
+ * is hidden, and slows after errors until a round works again.
21
+ */
22
+ export function createWatcher(changes) {
23
+ const watches = new Set();
24
+ let timer;
25
+ let soon;
26
+ let rounds = Promise.resolve();
27
+ let failures = 0;
28
+ let listening = false;
29
+ const page = () => globalThis.document;
30
+ const hidden = () => page()?.visibilityState === 'hidden';
31
+ const stop = () => {
32
+ if (timer !== undefined)
33
+ timers.clearTimeout(timer);
34
+ timer = undefined;
35
+ };
36
+ const schedule = () => {
37
+ stop();
38
+ if (watches.size === 0 || hidden())
39
+ return;
40
+ const every = Math.min(...[...watches].map((w) => w.intervalMs));
41
+ timer = timers.setTimeout(() => {
42
+ timer = undefined;
43
+ void round().catch(() => undefined);
44
+ }, Math.min(every * 2 ** failures, Math.max(every, MAX_BACKOFF_MS)));
45
+ timer.unref?.();
46
+ };
47
+ const onVisibility = () => {
48
+ if (hidden())
49
+ stop();
50
+ else
51
+ void round().catch(() => undefined);
52
+ };
53
+ const listen = () => {
54
+ const doc = page();
55
+ if (watches.size > 0 && !listening && doc) {
56
+ doc.addEventListener('visibilitychange', onVisibility);
57
+ listening = true;
58
+ }
59
+ else if (watches.size === 0 && listening) {
60
+ doc?.removeEventListener('visibilitychange', onVisibility);
61
+ listening = false;
62
+ }
63
+ };
64
+ const report = (w, e) => (w.onError ? w.onError(e) : surface(e));
65
+ const apply = async (group, stamps) => {
66
+ for (const w of group) {
67
+ if (!watches.has(w))
68
+ continue;
69
+ const next = Object.fromEntries(w.entities.map((e) => [e, stamps[e] ?? '']));
70
+ const before = w.stamps;
71
+ if (before && w.entities.every((e) => before[e] === next[e]))
72
+ continue;
73
+ w.stamps = next;
74
+ try {
75
+ await w.callback();
76
+ }
77
+ catch (e) {
78
+ report(w, asError(e));
79
+ }
80
+ }
81
+ };
82
+ const ask = async () => {
83
+ const group = [...watches];
84
+ if (group.length === 0)
85
+ return;
86
+ try {
87
+ await apply(group, await changes([...new Set(group.flatMap((w) => w.entities))]));
88
+ }
89
+ catch (e) {
90
+ if (!final(e))
91
+ throw e;
92
+ // One watch names something Quad refuses: ask for each alone, so the others carry on.
93
+ for (const w of group) {
94
+ try {
95
+ await apply([w], await changes(w.entities));
96
+ }
97
+ catch (own) {
98
+ if (!final(own))
99
+ throw own;
100
+ w.refused = asError(own);
101
+ watches.delete(w);
102
+ report(w, w.refused);
103
+ }
104
+ }
105
+ listen();
106
+ }
107
+ };
108
+ /** One round, after any already under way. Rejects when Quad could not be asked. */
109
+ function round() {
110
+ const run = rounds.then(async () => {
111
+ try {
112
+ await ask();
113
+ failures = 0;
114
+ }
115
+ catch (e) {
116
+ failures += 1;
117
+ for (const w of watches)
118
+ w.onError?.(asError(e));
119
+ throw e;
120
+ }
121
+ finally {
122
+ schedule();
123
+ }
124
+ });
125
+ rounds = run.catch(() => undefined);
126
+ return run;
127
+ }
128
+ return {
129
+ watch(entities, callback, options = {}) {
130
+ if (!Array.isArray(entities) ||
131
+ entities.length === 0 ||
132
+ !entities.every((e) => typeof e === 'string' && e.length > 0))
133
+ throw new QuadError('VALIDATION', "db.watch takes a list of the app's entities to watch");
134
+ if (typeof callback !== 'function')
135
+ throw new QuadError('VALIDATION', 'db.watch takes a function to call when they change');
136
+ const asked = options.intervalMs;
137
+ if (asked !== undefined && (typeof asked !== 'number' || !Number.isFinite(asked)))
138
+ throw new QuadError('VALIDATION', 'intervalMs must be a number of milliseconds');
139
+ const w = {
140
+ entities: [...new Set(entities)],
141
+ callback: callback,
142
+ intervalMs: Math.max(MIN_WATCH_INTERVAL_MS, asked ?? WATCH_INTERVAL_MS),
143
+ onError: options.onError,
144
+ stamps: undefined,
145
+ refused: undefined,
146
+ };
147
+ watches.add(w);
148
+ listen();
149
+ void round().catch(() => undefined);
150
+ return Object.freeze({
151
+ check: async () => {
152
+ await round();
153
+ if (w.refused)
154
+ throw w.refused;
155
+ },
156
+ stop: () => {
157
+ watches.delete(w);
158
+ listen();
159
+ if (watches.size === 0)
160
+ stop();
161
+ },
162
+ });
163
+ },
164
+ /** The app wrote through this client: ask straight away, so the person sees their own change at once. */
165
+ wrote() {
166
+ if (watches.size === 0 || soon !== undefined)
167
+ return;
168
+ soon = timers.setTimeout(() => {
169
+ soon = undefined;
170
+ void round().catch(() => undefined);
171
+ }, 0);
172
+ soon.unref?.();
173
+ },
174
+ };
175
+ }