@quad-education/sdk 0.7.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 (58) hide show
  1. package/README.md +5 -2
  2. package/dist/contract-tests/apps.d.ts +617 -0
  3. package/dist/contract-tests/apps.js +215 -1
  4. package/dist/contract-tests/harness.d.ts +1 -1
  5. package/dist/contract-tests/harness.js +7 -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 +7 -0
  15. package/dist/contract-tests/suite.js +180 -2
  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 +220 -10
  29. package/dist/src/contract/types.js +4 -1
  30. package/dist/src/engine/engine.d.ts +91 -2
  31. package/dist/src/engine/engine.js +604 -67
  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/state.d.ts +5 -0
  44. package/dist/src/engine/storage.d.ts +46 -1
  45. package/dist/src/engine/storage.js +46 -3
  46. package/dist/src/engine/store.d.ts +39 -2
  47. package/dist/src/engine/summary.d.ts +25 -0
  48. package/dist/src/engine/summary.js +107 -0
  49. package/dist/src/engine/validate-input.d.ts +7 -1
  50. package/dist/src/engine/validate-input.js +28 -1
  51. package/dist/src/engine/working-copy.d.ts +30 -0
  52. package/dist/src/engine/working-copy.js +91 -0
  53. package/dist/src/platform-types.d.ts +11 -1
  54. package/dist/src/protocol.d.ts +1 -1
  55. package/dist/src/protocol.js +9 -0
  56. package/dist/src/testing/index.d.ts +9 -0
  57. package/dist/src/testing/index.js +16 -1
  58. package/package.json +4 -4
@@ -4,8 +4,13 @@ import { eligibleParents } from '@quad-education/canonical';
4
4
  import { suggestedPeople, withDerived } from '@quad-education/fictional-school';
5
5
  import stored from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
6
  import { parentsOf, staffOf, studentsOf } from "../src/index.js";
7
- import { ACCESS_APP, BASIC_APP, JOBS_APP, ROLES_APP, TEST_APP, MEDICAL_APP, slowGate, } from "./apps.js";
7
+ import { ACCESS_APP, APP_ROLES_APP, LISTED_APP, BASIC_APP, JOBS_APP, ROLES_APP, TEST_APP, MEDICAL_APP, slowGate, } from "./apps.js";
8
8
  import { expectError, ids, listAll } from "./helpers.js";
9
+ import { files, listsAndFiles } from "./lists-and-files.js";
10
+ import { writes } from "./writes.js";
11
+ import { notifications } from "./notifications.js";
12
+ import { searchAndTotals } from "./search-and-totals.js";
13
+ import { live } from "./live.js";
9
14
  // The fictional school is the oracle: tests compare what the SDK returns with what the
10
15
  // dataset says should be visible. They never read an implementation's storage.
11
16
  const ds = withDerived(stored);
@@ -55,6 +60,7 @@ export function defineContractSuite(name, factory) {
55
60
  kind: 'user',
56
61
  role: 'staff',
57
62
  appAdmin: false,
63
+ appRoles: [],
58
64
  person: {
59
65
  id: record.id,
60
66
  givenName: record.givenName,
@@ -63,7 +69,7 @@ export function defineContractSuite(name, factory) {
63
69
  },
64
70
  });
65
71
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
66
- expect(sdk.version).toBe('0.6.0');
72
+ expect(sdk.version).toBe('0.9.0');
67
73
  });
68
74
  it('knows parents and students', async () => {
69
75
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
@@ -122,6 +128,154 @@ export function defineContractSuite(name, factory) {
122
128
  });
123
129
  });
124
130
  });
131
+ // D143: the school gives people the app's own roles. The app is told which ones the person holds, and the rules
132
+ // of each apply to whoever holds it, beside the rules of their school role.
133
+ describe('auth and db access: school-assigned app roles (D143)', () => {
134
+ useApp(APP_ROLES_APP);
135
+ const OTHER = persona('secondary-teacher');
136
+ it('holds none until the school assigns one, and says so in me()', async () => {
137
+ expect((await (await env.connect(STAFF)).auth.me()).appRoles).toEqual([]);
138
+ expect((await (await env.connect(STUDENT)).auth.me()).appRoles).toEqual([]);
139
+ });
140
+ it("names the roles a person holds, in the manifest's spelling, and no others", async () => {
141
+ await env.control.setAppRoles({
142
+ [STAFF.personId]: ['coach', 'WELLBEING LEAD', 'Principal'],
143
+ [OTHER.personId]: ['Coach'],
144
+ });
145
+ expect((await (await env.connect(STAFF)).auth.me()).appRoles).toEqual([
146
+ 'Wellbeing lead',
147
+ 'Coach',
148
+ ]);
149
+ expect((await (await env.connect(OTHER)).auth.me()).appRoles).toEqual(['Coach']);
150
+ expect((await (await env.connect(STAFF)).auth.me()).role).toBe('staff');
151
+ });
152
+ it('adds the rules of a role held to those of the school role', async () => {
153
+ const staff = await env.connect(STAFF);
154
+ const other = await env.connect(OTHER);
155
+ const mine = await staff.db.entity('note').create({ body: 'mine' });
156
+ const theirs = await other.db.entity('note').create({ body: 'theirs' });
157
+ expect(ids(await listAll(staff.db.entity('note')))).toEqual([mine.id]);
158
+ await env.control.setAppRoles({ [STAFF.personId]: ['Wellbeing lead'] });
159
+ expect(ids(await listAll(staff.db.entity('note')))).toEqual(ids([mine, theirs]));
160
+ // The school role's rules still apply: a lead writes their own notes as staff do.
161
+ await staff.db.entity('note').create({ body: 'another' });
162
+ expect(ids(await listAll(other.db.entity('note')))).toEqual([theirs.id]);
163
+ await env.control.setAppRoles({});
164
+ expect(ids(await listAll(staff.db.entity('note')))).not.toContain(theirs.id);
165
+ });
166
+ it('applies a role to whoever holds it, a student included', async () => {
167
+ const staff = await env.connect(STAFF);
168
+ const note = await staff.db.entity('note').create({ body: 'from staff' });
169
+ const student = await env.connect(STUDENT);
170
+ expect(await listAll(student.db.entity('note'))).toEqual([]);
171
+ await env.control.setAppRoles({ [STUDENT.personId]: ['Wellbeing lead'] });
172
+ expect(ids(await listAll(student.db.entity('note')))).toEqual([note.id]);
173
+ });
174
+ it('serves someone the school gave a role, whatever their school role', async () => {
175
+ await expectError((await env.connect(SIBLINGS_PARENT)).auth.me(), 'FORBIDDEN');
176
+ await env.control.setAppRoles({ [SIBLINGS_PARENT.personId]: ['Coach'] });
177
+ const parent = await env.connect(SIBLINGS_PARENT);
178
+ expect(await parent.auth.me()).toMatchObject({ role: 'parent', appRoles: ['Coach'] });
179
+ const plan = await parent.db.entity('plan').create({ title: 'Saturday' });
180
+ expect(ids(await listAll(parent.db.entity('plan')))).toEqual([plan.id]);
181
+ // Only what the role's rules say: a parent has no rules of their own for notes.
182
+ await expectError(parent.db.entity('note').list(), 'NOT_PERMITTED');
183
+ // Staff without the role have no rules for plans.
184
+ await expectError((await env.connect(STAFF)).db.entity('plan').list(), 'NOT_PERMITTED');
185
+ });
186
+ it('says nothing about roles for the system principal', async () => {
187
+ await env.control.setAppRoles({ [STAFF.personId]: ['Coach'] });
188
+ expect(await (await env.connect({ kind: 'system', appId: APP_ROLES_APP.manifest.id })).auth.me()).toEqual({ kind: 'system', appId: APP_ROLES_APP.manifest.id });
189
+ });
190
+ });
191
+ // D142: an app decides who reaches its rows with two more rules. `appAdmin` follows the school's choice of who
192
+ // looks after the app; `listed:` follows a table of people the app keeps, changed by whoever its own rules allow.
193
+ describe('db access: app admins and listed people (D142)', () => {
194
+ useApp(LISTED_APP);
195
+ const ADMIN = SUPERVISOR;
196
+ const OTHER = persona('secondary-teacher');
197
+ const SYSTEM_HERE = { kind: 'system', appId: LISTED_APP.manifest.id };
198
+ const OTHER_STUDENT = {
199
+ kind: 'user',
200
+ role: 'student',
201
+ personId: ds.students.find((s) => s.id !== STUDENT.personId).id,
202
+ };
203
+ beforeEach(async () => {
204
+ await env.control.setAppAdmins([ADMIN.personId]);
205
+ });
206
+ it("'appAdmin' lets only the app's admins write, while others read", async () => {
207
+ const admin = await env.connect(ADMIN);
208
+ const staff = await env.connect(STAFF);
209
+ const made = await admin.db.entity('setting').create({ label: 'Term 4' });
210
+ expect((await staff.db.entity('setting').get(made.id)).label).toBe('Term 4');
211
+ await expectError(staff.db.entity('setting').create({ label: 'mine' }), 'NOT_PERMITTED');
212
+ await expectError(staff.db.entity('setting').update(made.id, { label: 'changed' }), 'NOT_PERMITTED');
213
+ await expectError(staff.db.entity('setting').delete(made.id), 'NOT_PERMITTED');
214
+ expect((await admin.db.entity('setting').update(made.id, { label: 'Term 1' })).label).toBe('Term 1');
215
+ });
216
+ it('stops following someone the school no longer names as an admin', async () => {
217
+ const staff = await env.connect(STAFF);
218
+ await env.control.setAppAdmins([STAFF.personId]);
219
+ const made = await staff.db.entity('setting').create({ label: 'while admin' });
220
+ await env.control.setAppAdmins([]);
221
+ await expectError(staff.db.entity('setting').delete(made.id), 'NOT_PERMITTED');
222
+ });
223
+ it("'listed' gives the people a table points at every row, and nobody else", async () => {
224
+ const staff = await env.connect(STAFF);
225
+ const other = await env.connect(OTHER);
226
+ const admin = await env.connect(ADMIN);
227
+ const mine = await staff.db.entity('checkin').create({ mood: 'good' });
228
+ await other.db.entity('checkin').create({ mood: 'low' });
229
+ expect(ids(await listAll(other.db.entity('checkin')))).not.toContain(mine.id);
230
+ await expectError(other.db.entity('checkin').get(mine.id), 'NOT_FOUND');
231
+ const listing = await admin.db.entity('leads').create({ staffId: OTHER.personId });
232
+ expect(await listAll(other.db.entity('checkin'))).toHaveLength(2);
233
+ expect((await other.db.entity('checkin').get(mine.id)).mood).toBe('good');
234
+ // Being listed adds reading here, and nothing the rules don't say: deleting is still for the writer.
235
+ await expectError(other.db.entity('checkin').delete(mine.id), 'NOT_PERMITTED');
236
+ // Someone not listed is unchanged.
237
+ expect(await listAll(staff.db.entity('checkin'))).toHaveLength(1);
238
+ await admin.db.entity('leads').delete(listing.id);
239
+ expect(ids(await listAll(other.db.entity('checkin')))).not.toContain(mine.id);
240
+ });
241
+ it("lets only the people the table's own rules allow change who is listed", async () => {
242
+ const other = await env.connect(OTHER);
243
+ await expectError(other.db.entity('leads').create({ staffId: OTHER.personId }), 'NOT_PERMITTED');
244
+ expect(await listAll(other.db.entity('leads'))).toEqual([]);
245
+ });
246
+ it('lists students too, in a table staff keep', async () => {
247
+ const staff = await env.connect(STAFF);
248
+ const student = await env.connect(STUDENT);
249
+ const another = await env.connect(OTHER_STUDENT);
250
+ const theirs = await another.db.entity('loan').create({ title: 'Atlas' });
251
+ await student.db.entity('loan').create({ title: 'Novel' });
252
+ expect(ids(await listAll(student.db.entity('loan')))).not.toContain(theirs.id);
253
+ await staff.db.entity('monitors').create({ studentId: STUDENT.personId });
254
+ expect(ids(await listAll(student.db.entity('loan')))).toContain(theirs.id);
255
+ expect(ids(await listAll(another.db.entity('loan')))).toEqual([theirs.id]);
256
+ // A student is never listed by a field that holds staff.
257
+ await staff.db
258
+ .entity('monitors')
259
+ .create({ studentId: OTHER_STUDENT.personId, addedBy: STAFF.personId });
260
+ expect(await listAll(another.db.entity('loan'))).toHaveLength(2);
261
+ });
262
+ it('allows a list people add themselves to: a sign-up sheet', async () => {
263
+ const staff = await env.connect(STAFF);
264
+ await expectError(staff.db.entity('roster').create({ day: 'Monday' }), 'NOT_PERMITTED');
265
+ expect(await listAll(staff.db.entity('roster'))).toEqual([]);
266
+ await staff.db.entity('signups').create({ staffId: STAFF.personId });
267
+ const made = await staff.db.entity('roster').create({ day: 'Monday' });
268
+ expect(ids(await listAll(staff.db.entity('roster')))).toEqual([made.id]);
269
+ expect(await listAll((await env.connect(OTHER)).db.entity('roster'))).toEqual([]);
270
+ });
271
+ it('leaves jobs as they were: the system principal reaches every row', async () => {
272
+ const staff = await env.connect(STAFF);
273
+ const mine = await staff.db.entity('checkin').create({ mood: 'okay' });
274
+ const system = await env.connect(SYSTEM_HERE);
275
+ expect(ids(await listAll(system.db.entity('checkin')))).toEqual([mine.id]);
276
+ await system.db.entity('setting').create({ label: 'from a job' });
277
+ });
278
+ });
125
279
  describe('school: visibility (D4)', () => {
126
280
  useApp(TEST_APP);
127
281
  it('staff see every student', async () => {
@@ -238,6 +392,9 @@ export function defineContractSuite(name, factory) {
238
392
  const student = await env.connect(STUDENT);
239
393
  expect((await staff.auth.me()).role).toBe('staff');
240
394
  expect((await student.auth.me()).role).toBe('student');
395
+ // Everyone with the school role holds the app role of the same name (D143).
396
+ expect((await staff.auth.me()).appRoles).toEqual(['Staff']);
397
+ expect((await student.auth.me()).appRoles).toEqual(['Student']);
241
398
  await expectError(env.connect(SIBLINGS_PARENT).then((p) => p.auth.me()), 'FORBIDDEN');
242
399
  });
243
400
  it('follows the access rules written for the app role, whatever the case of the key', async () => {
@@ -1477,6 +1634,27 @@ export function defineContractSuite(name, factory) {
1477
1634
  expect(same).toEqual(entry);
1478
1635
  });
1479
1636
  });
1637
+ const setup = {
1638
+ env: () => env,
1639
+ useApp,
1640
+ staff: STAFF,
1641
+ otherStaff: SUPERVISOR,
1642
+ student: STUDENT,
1643
+ otherStudent: {
1644
+ kind: 'user',
1645
+ role: 'student',
1646
+ personId: ds.students.find((s) => s.id !== STUDENT.personId).id,
1647
+ },
1648
+ studentIds: ds.students.slice(0, 3).map((s) => s.id),
1649
+ parent: SIBLINGS_PARENT,
1650
+ childId: childrenOf(SIBLINGS_PARENT.personId)[0],
1651
+ };
1652
+ listsAndFiles(setup);
1653
+ files(setup);
1654
+ writes(setup);
1655
+ notifications(setup);
1656
+ searchAndTotals({ ...setup, students: ds.students, staffRecords: ds.staff });
1657
+ live(setup);
1480
1658
  describe('clock controls (D14)', () => {
1481
1659
  useApp(TEST_APP);
1482
1660
  it('advances a frozen clock', async () => {
@@ -0,0 +1,3 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ /** Unique rules (D149), all-or-nothing writes and conditional writes (D150): what ADR 0040 adds. */
3
+ export declare function writes({ env, useApp, staff, student, otherStudent }: Setup): void;
@@ -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),