@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
@@ -1,4 +1,4 @@
1
- import { boolean, defineSchema, entity, enumOf, listedIn, number, ref, text, } from '@quad-education/schema';
1
+ import { boolean, defineSchema, entity, enumOf, file, listedIn, listOf, number, ref, text, } from '@quad-education/schema';
2
2
  import { staffOf } from "../src/contract/recipients.js";
3
3
  import { defineJob } from "../src/jobs/index.js";
4
4
  /** The schema the contract suite's test apps use. */
@@ -372,3 +372,145 @@ export const JOBS_APP = {
372
372
  schema: JOBS_SCHEMA,
373
373
  jobs: TEST_JOBS,
374
374
  };
375
+ /**
376
+ * Lists and files (D147, D148). Staff reach every incident; a student reaches the ones they wrote, so one student
377
+ * can't read another's files. `staffNotes` is hidden from students by `visibleTo`.
378
+ */
379
+ export const FILES_SCHEMA = defineSchema({
380
+ incident: entity({
381
+ fields: {
382
+ summary: text(),
383
+ students: listOf(ref('school.students'), { optional: true }),
384
+ tags: listOf(text(), { optional: true }),
385
+ days: listOf(enumOf(['mon', 'tue', 'wed']), { optional: true }),
386
+ scores: listOf(number(), { optional: true }),
387
+ related: listOf(ref('incident'), { optional: true }),
388
+ photo: file({ accept: ['image'], optional: true }),
389
+ evidence: listOf(file(), { optional: true }),
390
+ staffNotes: listOf(file(), { optional: true, visibleTo: ['staff'] }),
391
+ },
392
+ indexes: [['summary']],
393
+ access: {
394
+ staff: { read: 'all', create: 'all', update: 'all', delete: 'all' },
395
+ student: { read: 'own', create: 'own', update: 'own', delete: 'own' },
396
+ },
397
+ }),
398
+ });
399
+ export const FILES_APP = {
400
+ manifest: {
401
+ ...TEST_APP.manifest,
402
+ id: 'contract-files',
403
+ name: 'Lists and files app',
404
+ roles: ['staff', 'student'],
405
+ scopes: ['students.basic:read', 'staff.basic:read'],
406
+ notifications: [],
407
+ },
408
+ schema: FILES_SCHEMA,
409
+ };
410
+ /**
411
+ * Unique rules, batches and conditional writes (D149, D150). A student reaches only the bookings they made, so a
412
+ * unique rule is seen refusing a value held by a record the writer cannot read.
413
+ */
414
+ export const WRITES_SCHEMA = defineSchema({
415
+ slot: entity({
416
+ fields: {
417
+ label: text(),
418
+ status: enumOf(['free', 'taken']),
419
+ seats: number({ optional: true }),
420
+ secret: text({ optional: true, visibleTo: ['staff'] }),
421
+ },
422
+ unique: [['label']],
423
+ access: {
424
+ staff: { read: 'all', create: 'all', update: 'all', delete: 'all' },
425
+ },
426
+ }),
427
+ booking: entity({
428
+ fields: {
429
+ slotLabel: text(),
430
+ who: text({ optional: true }),
431
+ term: text({ optional: true }),
432
+ proof: file({ optional: true }),
433
+ },
434
+ unique: [['slotLabel'], ['who', 'term']],
435
+ access: {
436
+ staff: { read: 'all', create: 'all', update: 'all', delete: 'all' },
437
+ student: { read: 'own', create: 'own', update: 'own', delete: 'own' },
438
+ },
439
+ }),
440
+ });
441
+ export const WRITES_APP = {
442
+ manifest: {
443
+ ...TEST_APP.manifest,
444
+ id: 'contract-writes',
445
+ name: 'Unique rules and batches app',
446
+ roles: ['staff', 'student'],
447
+ scopes: ['students.basic:read', 'staff.basic:read'],
448
+ notifications: [],
449
+ },
450
+ schema: WRITES_SCHEMA,
451
+ };
452
+ /**
453
+ * Formatted notifications and attachments (D151, D152). `staffNote` is hidden from students and parents, and
454
+ * `review` is at a staff-only level, so neither may be sent to them.
455
+ */
456
+ export const NOTIFY_SCHEMA = defineSchema({
457
+ notice: entity({
458
+ fields: {
459
+ title: text(),
460
+ slip: file({ optional: true }),
461
+ pages: listOf(file(), { optional: true }),
462
+ staffNote: file({ optional: true, visibleTo: ['staff'] }),
463
+ review: file({ optional: true, tier: 'hr' }),
464
+ },
465
+ access: {
466
+ staff: { read: 'all', create: 'all', update: 'all', delete: 'all' },
467
+ student: { read: 'own', create: 'own' },
468
+ },
469
+ }),
470
+ });
471
+ export const NOTIFY_APP = {
472
+ manifest: {
473
+ ...TEST_APP.manifest,
474
+ id: 'contract-notify',
475
+ name: 'Formatted notifications app',
476
+ notifications: ['notice.sent'],
477
+ },
478
+ schema: NOTIFY_SCHEMA,
479
+ };
480
+ /**
481
+ * Search and totals (D153, D154). `secret` and `margin` are hidden from students, so neither a search nor a
482
+ * total may tell a student anything about them. `plain` names no searchable fields.
483
+ */
484
+ export const SEARCH_SCHEMA = defineSchema({
485
+ request: entity({
486
+ fields: {
487
+ title: text(),
488
+ body: text({ optional: true }),
489
+ tags: listOf(text(), { optional: true }),
490
+ secret: text({ optional: true, visibleTo: ['staff'] }),
491
+ status: enumOf(['open', 'closed']),
492
+ term: text({ optional: true }),
493
+ cost: number({ optional: true }),
494
+ margin: number({ optional: true, visibleTo: ['staff'] }),
495
+ proof: file({ optional: true }),
496
+ },
497
+ search: ['title', 'body', 'tags', 'secret'],
498
+ indexes: [['title'], ['cost']],
499
+ access: {
500
+ staff: { read: 'all', create: 'all', update: 'all', delete: 'all' },
501
+ student: { read: 'own', create: 'own' },
502
+ },
503
+ }),
504
+ plain: entity({ fields: { label: text() } }),
505
+ });
506
+ export const SEARCH_APP = {
507
+ manifest: {
508
+ ...TEST_APP.manifest,
509
+ id: 'contract-search',
510
+ name: 'Search and totals app',
511
+ roles: ['staff', 'student'],
512
+ scopes: ['students.basic:read', 'staff.basic:read'],
513
+ notifications: [],
514
+ },
515
+ schema: SEARCH_SCHEMA,
516
+ };
@@ -2,7 +2,7 @@ import type { Principal } from '@quad-education/canonical';
2
2
  import type { ContractEnv, TestApp } from './suite.ts';
3
3
  import type { QuadSdk } from '../src/contract/types.ts';
4
4
  import type { Engine } from '../src/engine/index.ts';
5
- type SliceBControl = Pick<ContractEnv['control'], 'advanceClock' | 'runDueJobs' | 'redeliver' | 'runs' | 'inbox' | 'auditLog' | 'setAppAdmins' | 'setAppRoles'>;
5
+ type SliceBControl = Pick<ContractEnv['control'], 'advanceClock' | 'runDueJobs' | 'redeliver' | 'runs' | 'inbox' | 'auditLog' | 'outboxAttachment' | 'setAppAdmins' | 'setAppRoles'>;
6
6
  /**
7
7
  * The job-running and inspection controls, shared by both contract runners. Each job runs
8
8
  * as its run's principal through whatever transport `connect` uses.
@@ -42,5 +42,9 @@ export function sliceBControls(engine, app, connect, onClock = async () => { })
42
42
  })),
43
43
  inbox: async (personId) => engine().inbox(appId(), personId),
44
44
  auditLog: async () => engine().auditLog(appId()),
45
+ outboxAttachment: async (id) => {
46
+ const sent = await engine().sentFile(appId(), id);
47
+ return sent ? { name: sent.info.name, bytes: [...sent.bytes] } : undefined;
48
+ },
45
49
  };
46
50
  }
@@ -0,0 +1,19 @@
1
+ import type { Principal } from '@quad-education/canonical';
2
+ import type { ContractEnv, TestApp } from './suite.ts';
3
+ export type Setup = {
4
+ env: () => ContractEnv;
5
+ useApp: (app: TestApp) => void;
6
+ staff: Principal;
7
+ otherStaff: Principal;
8
+ student: Principal;
9
+ otherStudent: Principal;
10
+ /** Three students staff can see. */
11
+ studentIds: readonly string[];
12
+ /** A parent who may be contacted about `childId`. */
13
+ parent: Principal;
14
+ childId: string;
15
+ };
16
+ /** Lists (D147) and files (D148): the parts of the contract ADR 0039 adds. */
17
+ export declare function listsAndFiles({ env, useApp, staff, student, studentIds }: Setup): void;
18
+ /** Files (D148): the life of a file, who reads it, and what is refused. */
19
+ export declare function files({ env, useApp, staff, otherStaff, student, otherStudent }: Setup): void;
@@ -0,0 +1,279 @@
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 { FILES_APP, TEST_APP } from "./apps.js";
4
+ import { expectError } from "./helpers.js";
5
+ /** Lists (D147) and files (D148): the parts of the contract ADR 0039 adds. */
6
+ export function listsAndFiles({ env, useApp, staff, student, studentIds }) {
7
+ const [s1, s2, s3] = studentIds;
8
+ describe('db lists (D147)', () => {
9
+ useApp(FILES_APP);
10
+ it('keeps a list in the order written, and an empty list as a value', async () => {
11
+ const incidents = (await env().connect(staff)).db.entity('incident');
12
+ const made = await incidents.create({
13
+ summary: 'Oval',
14
+ students: [s2, s1],
15
+ tags: [],
16
+ days: ['wed', 'mon'],
17
+ scores: [3, 1.5],
18
+ });
19
+ expect(made).toMatchObject({ students: [s2, s1], tags: [], days: ['wed', 'mon'] });
20
+ expect((await incidents.get(made.id)).scores).toEqual([3, 1.5]);
21
+ const changed = await incidents.update(made.id, { students: [s3], tags: null });
22
+ expect(changed.students).toEqual([s3]);
23
+ expect('tags' in changed).toBe(false);
24
+ });
25
+ it('checks every item as a single value of its type is checked', async () => {
26
+ const incidents = (await env().connect(staff)).db.entity('incident');
27
+ const bad = (input) => expectError(incidents.create({ summary: 'x', ...input }), 'VALIDATION');
28
+ await bad({ tags: 'one' });
29
+ await bad({ tags: ['one', 2] });
30
+ await bad({ days: ['mon', 'fri'] });
31
+ await bad({ scores: [1, Number.NaN] });
32
+ await bad({ tags: [['nested']] });
33
+ await bad({ students: [s1, 'student_nobody'] });
34
+ await bad({ related: ['incident_nothing'] });
35
+ await bad({ tags: Array.from({ length: 101 }, (_, i) => `t${i}`) });
36
+ const full = await incidents.create({
37
+ summary: 'full',
38
+ tags: Array.from({ length: 100 }, (_, i) => `t${i}`),
39
+ });
40
+ expect(full.tags).toHaveLength(100);
41
+ });
42
+ it('refuses a link in a list to a record the writer cannot see', async () => {
43
+ const asStudent = (await env().connect(student)).db.entity('incident');
44
+ const other = studentIds.find((id) => id !== student.personId);
45
+ await expectError(asStudent.create({ summary: 'x', students: [other] }), 'VALIDATION');
46
+ const mine = await asStudent.create({
47
+ summary: 'mine',
48
+ students: [student.personId],
49
+ });
50
+ expect(mine.students).toEqual([student.personId]);
51
+ });
52
+ it('finds the records whose list has a value', async () => {
53
+ const incidents = (await env().connect(staff)).db.entity('incident');
54
+ await incidents.create({ summary: 'a', students: [s1, s2], tags: ['oval', 'lunch'] });
55
+ await incidents.create({ summary: 'b', students: [s2], tags: ['lunch'] });
56
+ await incidents.create({ summary: 'c', students: [s3] });
57
+ const summaries = async (where) => (await incidents.list({ where, orderBy: { field: 'summary' } })).items.map((i) => i.summary);
58
+ expect(await summaries({ students: { has: s2 } })).toEqual(['a', 'b']);
59
+ expect(await summaries({ tags: { has: 'oval' } })).toEqual(['a']);
60
+ expect(await summaries({ tags: { has: 'lunch' }, students: { has: s1 } })).toEqual(['a']);
61
+ expect(await summaries({ tags: { has: 'nothing' } })).toEqual([]);
62
+ });
63
+ it('filters a list only with has, and never sorts by one', async () => {
64
+ const incidents = (await env().connect(staff)).db.entity('incident');
65
+ await expectError(incidents.list({ where: { tags: 'oval' } }), 'VALIDATION');
66
+ await expectError(incidents.list({ where: { tags: { in: ['oval'] } } }), 'VALIDATION');
67
+ await expectError(incidents.list({ where: { tags: { has: ['oval'] } } }), 'VALIDATION');
68
+ await expectError(incidents.list({ where: { summary: { has: 'a' } } }), 'VALIDATION');
69
+ await expectError(incidents.list({ orderBy: { field: 'tags' } }), 'VALIDATION');
70
+ });
71
+ it('includes the records a list of links points at, in order', async () => {
72
+ const incidents = (await env().connect(staff)).db.entity('incident');
73
+ const first = await incidents.create({ summary: 'first' });
74
+ const made = await incidents.create({
75
+ summary: 'second',
76
+ students: [s2, s1],
77
+ related: [first.id],
78
+ });
79
+ await incidents.delete(first.id);
80
+ const page = await incidents.list({
81
+ where: { id: made.id },
82
+ include: ['students', 'related'],
83
+ });
84
+ const included = page.items[0].$included;
85
+ expect(included.students.map((s) => s.id)).toEqual([s2, s1]);
86
+ expect(included.related).toEqual([null]);
87
+ const none = await incidents.list({ where: { summary: 'full-none' }, include: ['students'] });
88
+ expect(none.items).toEqual([]);
89
+ const bare = await incidents.create({ summary: 'bare' });
90
+ const barePage = await incidents.list({ where: { id: bare.id }, include: ['students'] });
91
+ expect(barePage.items[0].$included.students).toEqual([]);
92
+ });
93
+ });
94
+ }
95
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4];
96
+ const PDF = [0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34];
97
+ const blob = (bytes, type) => new Blob([new Uint8Array(bytes)], { type });
98
+ const png = () => blob(PNG, 'image/png');
99
+ const pdf = () => blob(PDF, 'application/pdf');
100
+ const HOUR = 60 * 60 * 1000;
101
+ /** Files (D148): the life of a file, who reads it, and what is refused. */
102
+ export function files({ env, useApp, staff, otherStaff, student, otherStudent }) {
103
+ describe('files (D148)', () => {
104
+ useApp(FILES_APP);
105
+ it('keeps an uploaded file for its uploader alone until it is attached', async () => {
106
+ await env().control.setClock('2026-03-04T03:00:00.000Z');
107
+ const sdk = await env().connect(staff);
108
+ const info = await sdk.files.upload(png(), { name: 'oval.png' });
109
+ expect(info).toEqual({
110
+ id: info.id,
111
+ name: 'oval.png',
112
+ type: 'image/png',
113
+ size: PNG.length,
114
+ createdAt: '2026-03-04T03:00:00.000Z',
115
+ createdBy: staff.personId,
116
+ });
117
+ expect(info.id).toMatch(/^file_/);
118
+ expect(await sdk.files.info(info.id)).toEqual(info);
119
+ const read = await sdk.files.read(info.id);
120
+ expect(read.info).toEqual(info);
121
+ expect([...read.bytes]).toEqual(PNG);
122
+ const other = await env().connect(otherStaff);
123
+ await expectError(other.files.info(info.id), 'NOT_FOUND');
124
+ await expectError(other.files.read(info.id), 'NOT_FOUND');
125
+ await expectError(sdk.files.info('file_nothing'), 'NOT_FOUND');
126
+ });
127
+ it('names a file "file" when it has no name, and takes the name a File carries', async () => {
128
+ const sdk = await env().connect(staff);
129
+ expect((await sdk.files.upload(png())).name).toBe('file');
130
+ const carried = Object.assign(png(), { name: 'carried.png' });
131
+ expect((await sdk.files.upload(carried)).name).toBe('carried.png');
132
+ });
133
+ it('lets whoever can read the record read its file, and nobody else', async () => {
134
+ const mine = await env().connect(student);
135
+ const photo = await mine.files.upload(png(), { name: 'me.png' });
136
+ const doc = await mine.files.upload(pdf(), { name: 'note.pdf' });
137
+ const incident = await mine.db
138
+ .entity('incident')
139
+ .create({ summary: 'mine', photo: photo.id, evidence: [doc.id] });
140
+ expect(incident).toMatchObject({ photo: photo.id, evidence: [doc.id] });
141
+ // The writer, and staff, who read every incident.
142
+ expect([...(await mine.files.read(photo.id)).bytes]).toEqual(PNG);
143
+ const asStaff = await env().connect(staff);
144
+ expect((await asStaff.files.info(photo.id)).name).toBe('me.png');
145
+ expect([...(await asStaff.files.read(doc.id)).bytes]).toEqual(PDF);
146
+ // Another student can't read the record, so the file isn't there for them.
147
+ const another = await env().connect(otherStudent);
148
+ await expectError(another.files.info(photo.id), 'NOT_FOUND');
149
+ await expectError(another.files.read(doc.id), 'NOT_FOUND');
150
+ });
151
+ it('hides a file in a field the role is not shown', async () => {
152
+ const mine = await env().connect(student);
153
+ const incident = await mine.db.entity('incident').create({ summary: 'mine' });
154
+ const asStaff = await env().connect(staff);
155
+ const note = await asStaff.files.upload(pdf(), { name: 'staff-only.pdf' });
156
+ await asStaff.db.entity('incident').update(incident.id, { staffNotes: [note.id] });
157
+ expect(await (await env().connect(otherStaff)).files.info(note.id)).toMatchObject({
158
+ name: 'staff-only.pdf',
159
+ });
160
+ expect('staffNotes' in (await mine.db.entity('incident').get(incident.id))).toBe(false);
161
+ await expectError(mine.files.info(note.id), 'NOT_FOUND');
162
+ await expectError(mine.files.read(note.id), 'NOT_FOUND');
163
+ });
164
+ it('attaches a file once, and only for whoever uploaded it', async () => {
165
+ const sdk = await env().connect(staff);
166
+ const incidents = sdk.db.entity('incident');
167
+ const theirs = await (await env().connect(otherStaff)).files.upload(png());
168
+ await expectError(incidents.create({ summary: 'x', photo: theirs.id }), 'VALIDATION');
169
+ await expectError(incidents.create({ summary: 'x', photo: 'file_nothing' }), 'VALIDATION');
170
+ const a = await sdk.files.upload(png());
171
+ const first = await incidents.create({ summary: 'first', photo: a.id });
172
+ await expectError(incidents.create({ summary: 'second', photo: a.id }), 'VALIDATION');
173
+ await expectError(incidents.update(first.id, { evidence: [a.id] }), 'VALIDATION');
174
+ const b = await sdk.files.upload(png());
175
+ await expectError(incidents.create({ summary: 'x', evidence: [b.id, b.id] }), 'VALIDATION');
176
+ // Nothing was attached by the refused writes.
177
+ await expectError((await env().connect(otherStaff)).files.info(b.id), 'NOT_FOUND');
178
+ expect((await incidents.create({ summary: 'ok', evidence: [b.id] })).evidence).toEqual([b.id]);
179
+ });
180
+ it('takes only the kinds of file a field accepts', async () => {
181
+ const sdk = await env().connect(staff);
182
+ const doc = await sdk.files.upload(pdf());
183
+ const e = await expectError(sdk.db.entity('incident').create({ summary: 'x', photo: doc.id }), 'VALIDATION');
184
+ expect(e.message).toContain('image');
185
+ expect((await sdk.db.entity('incident').create({ summary: 'x', evidence: [doc.id] })).id).toBeTruthy();
186
+ });
187
+ it('keeps the files a write leaves in place', async () => {
188
+ const sdk = await env().connect(staff);
189
+ const incidents = sdk.db.entity('incident');
190
+ const [a, b, c] = [
191
+ await sdk.files.upload(png()),
192
+ await sdk.files.upload(png()),
193
+ await sdk.files.upload(pdf()),
194
+ ];
195
+ const made = await incidents.create({ summary: 'x', photo: a.id, evidence: [b.id] });
196
+ await incidents.update(made.id, { summary: 'renamed' });
197
+ const grown = await incidents.update(made.id, { evidence: [c.id, b.id] });
198
+ expect(grown.evidence).toEqual([c.id, b.id]);
199
+ for (const f of [a, b, c])
200
+ expect((await sdk.files.info(f.id)).id).toBe(f.id);
201
+ });
202
+ it('removes a file with its field, its place in a list, or its record', async () => {
203
+ const sdk = await env().connect(staff);
204
+ const incidents = sdk.db.entity('incident');
205
+ const upload = () => sdk.files.upload(png());
206
+ const [a, b, c, d, e] = [
207
+ await upload(),
208
+ await upload(),
209
+ await upload(),
210
+ await upload(),
211
+ await upload(),
212
+ ];
213
+ const made = await incidents.create({ summary: 'x', photo: a.id, evidence: [b.id, c.id] });
214
+ await incidents.update(made.id, { photo: null });
215
+ await expectError(sdk.files.info(a.id), 'NOT_FOUND');
216
+ await incidents.update(made.id, { photo: d.id });
217
+ await incidents.update(made.id, { photo: e.id });
218
+ await expectError(sdk.files.info(d.id), 'NOT_FOUND');
219
+ await incidents.update(made.id, { evidence: [c.id] });
220
+ await expectError(sdk.files.read(b.id), 'NOT_FOUND');
221
+ expect((await sdk.files.info(c.id)).id).toBe(c.id);
222
+ await incidents.delete(made.id);
223
+ await expectError(sdk.files.info(c.id), 'NOT_FOUND');
224
+ await expectError(sdk.files.info(e.id), 'NOT_FOUND');
225
+ });
226
+ it('removes a file still unattached after 24 hours', async () => {
227
+ await env().control.setClock('2026-03-04T03:00:00.000Z');
228
+ const sdk = await env().connect(staff);
229
+ const kept = await sdk.files.upload(png());
230
+ const attached = await sdk.files.upload(png());
231
+ await sdk.db.entity('incident').create({ summary: 'x', photo: attached.id });
232
+ await env().control.advanceClock(23 * HOUR);
233
+ expect((await sdk.files.info(kept.id)).id).toBe(kept.id);
234
+ await env().control.advanceClock(HOUR);
235
+ await expectError(sdk.files.info(kept.id), 'NOT_FOUND');
236
+ await expectError(sdk.db.entity('incident').create({ summary: 'late', photo: kept.id }), 'VALIDATION');
237
+ expect((await sdk.files.info(attached.id)).id).toBe(attached.id);
238
+ });
239
+ it('refuses what Quad does not keep', async () => {
240
+ const sdk = await env().connect(staff);
241
+ const refuse = (file, options) => expectError(sdk.files.upload(file, options), 'VALIDATION');
242
+ await refuse(blob([60, 115, 118, 103, 62], 'image/svg+xml'));
243
+ await refuse(blob([60, 104, 116, 109, 108, 62], 'text/html'));
244
+ await refuse(blob([1, 2, 3], ''));
245
+ // The first bytes of an image or a PDF must be that image's or a PDF's.
246
+ await refuse(blob(PDF, 'image/png'));
247
+ await refuse(blob(PNG, 'application/pdf'));
248
+ await refuse(blob([], 'text/plain'));
249
+ await refuse(png(), { name: '../up.png' });
250
+ await refuse(png(), { name: 'x'.repeat(201) });
251
+ await refuse('not a file');
252
+ expect((await sdk.files.upload(blob([104, 105], 'text/plain'), { name: 'hi.txt' })).size).toBe(2);
253
+ });
254
+ it('refuses a file over 10 MB', async () => {
255
+ const sdk = await env().connect(staff);
256
+ const big = new Blob([new Uint8Array(10 * 1024 * 1024 + 1)], { type: 'text/plain' });
257
+ const e = await expectError(sdk.files.upload(big), 'VALIDATION');
258
+ expect(e.message).toContain('10 MB');
259
+ }, 30_000);
260
+ it('keeps files across a reload, and loses them with the app’s data', async () => {
261
+ const sdk = await env().connect(staff);
262
+ const file = await sdk.files.upload(png(), { name: 'kept.png' });
263
+ await sdk.db.entity('incident').create({ summary: 'x', photo: file.id });
264
+ await env().control.restart();
265
+ const again = await env().connect(otherStaff);
266
+ expect([...(await again.files.read(file.id)).bytes]).toEqual(PNG);
267
+ await env().control.reset();
268
+ await expectError((await env().connect(staff)).files.info(file.id), 'NOT_FOUND');
269
+ });
270
+ });
271
+ describe('files in an app with no file field (D148)', () => {
272
+ useApp(TEST_APP);
273
+ it('has nowhere to attach a file, so keeps none', async () => {
274
+ const sdk = await env().connect(staff);
275
+ const e = await expectError(sdk.files.upload(png()), 'VALIDATION');
276
+ expect(e.message).toContain('file()');
277
+ });
278
+ });
279
+ }
@@ -0,0 +1,3 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ /** Watching the app's records (D157): what ADR 0044 adds. */
3
+ export declare function live({ env, useApp, staff, otherStaff, student }: Setup): void;
@@ -0,0 +1,156 @@
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 { LISTED_APP, WRITES_APP } from "./apps.js";
4
+ import { expectError } from "./helpers.js";
5
+ /** Watching the app's records (D157): what ADR 0044 adds. */
6
+ export function live({ env, useApp, staff, otherStaff, student }) {
7
+ /** A watch, how many times it has called back, and a check that tells how many more that made. */
8
+ const watching = (sdk, entities, options = {}) => {
9
+ let calls = 0;
10
+ const watch = sdk.db.watch(entities, () => void (calls += 1), options);
11
+ return {
12
+ watch,
13
+ calls: () => calls,
14
+ async more() {
15
+ const before = calls;
16
+ await watch.check();
17
+ return calls - before;
18
+ },
19
+ };
20
+ };
21
+ describe('db watch (D157)', () => {
22
+ useApp(WRITES_APP);
23
+ it('calls back once at the start, and not again while nothing changes', async () => {
24
+ const w = watching(await env().connect(staff), ['slot']);
25
+ await w.watch.check();
26
+ expect(w.calls()).toBe(1);
27
+ expect(await w.more()).toBe(0);
28
+ expect(await w.more()).toBe(0);
29
+ w.watch.stop();
30
+ });
31
+ it("calls back after another person's create, update and delete", async () => {
32
+ const w = watching(await env().connect(staff), ['slot']);
33
+ await w.watch.check();
34
+ const slots = (await env().connect(otherStaff)).db.entity('slot');
35
+ const made = await slots.create({ label: 'Mon 9', status: 'free' });
36
+ expect(await w.more()).toBe(1);
37
+ await slots.update(made.id, { status: 'taken' });
38
+ expect(await w.more()).toBe(1);
39
+ await slots.delete(made.id);
40
+ expect(await w.more()).toBe(1);
41
+ expect(await w.more()).toBe(0);
42
+ w.watch.stop();
43
+ });
44
+ it('calls back once for a batch, and for the entities it wrote only', async () => {
45
+ const sdk = await env().connect(staff);
46
+ const slot = watching(sdk, ['slot']);
47
+ const booking = watching(sdk, ['booking']);
48
+ const both = watching(sdk, ['slot', 'booking']);
49
+ await both.watch.check();
50
+ const other = await env().connect(otherStaff);
51
+ await other.db.batch([
52
+ { create: 'slot', input: { label: 'Tue 9', status: 'free' } },
53
+ { create: 'slot', input: { label: 'Tue 10', status: 'free' } },
54
+ ]);
55
+ expect(await slot.more()).toBe(1);
56
+ expect(await booking.more()).toBe(0);
57
+ expect(await both.more()).toBe(0); // it ran in the same round as `slot`
58
+ expect(both.calls()).toBe(2);
59
+ for (const w of [slot, booking, both])
60
+ w.watch.stop();
61
+ });
62
+ it('stays silent after a read, and after a write that was refused', async () => {
63
+ const w = watching(await env().connect(staff), ['slot']);
64
+ const slots = (await env().connect(otherStaff)).db.entity('slot');
65
+ await slots.create({ label: 'Wed 9', status: 'free' });
66
+ await w.watch.check();
67
+ await slots.list();
68
+ await slots.count();
69
+ await expectError(slots.create({ label: 'Wed 9', status: 'free' }), 'CONFLICT');
70
+ await expectError((await env().connect(otherStaff)).db.batch([
71
+ { create: 'slot', input: { label: 'Wed 10', status: 'free' } },
72
+ { create: 'slot', input: { label: 'Wed 9', status: 'free' } },
73
+ ]), 'CONFLICT');
74
+ expect(await w.more()).toBe(0);
75
+ w.watch.stop();
76
+ });
77
+ it("follows a person's own write without being asked", async () => {
78
+ const sdk = await env().connect(staff);
79
+ const w = watching(sdk, ['slot']);
80
+ await w.watch.check();
81
+ await sdk.db.entity('slot').create({ label: 'Thu 9', status: 'free' });
82
+ await expect.poll(() => w.calls(), { timeout: 2000 }).toBe(2);
83
+ w.watch.stop();
84
+ });
85
+ it('tells a person that a table changed, whoever wrote and whatever they may read of it', async () => {
86
+ const w = watching(await env().connect(student), ['booking']);
87
+ await w.watch.check();
88
+ await (await env().connect(staff)).db.entity('booking').create({ slotLabel: 'Fri 9' });
89
+ expect(await w.more()).toBe(1);
90
+ // What they read is still only their own.
91
+ expect((await (await env().connect(student)).db.entity('booking').list()).items).toEqual([]);
92
+ w.watch.stop();
93
+ });
94
+ it('stops when asked', async () => {
95
+ const w = watching(await env().connect(staff), ['slot']);
96
+ await w.watch.check();
97
+ w.watch.stop();
98
+ await (await env().connect(otherStaff)).db
99
+ .entity('slot')
100
+ .create({ label: 'Sat 9', status: 'free' });
101
+ expect(await w.more()).toBe(0);
102
+ });
103
+ it('calls back after the app is reset', async () => {
104
+ const w = watching(await env().connect(staff), ['slot']);
105
+ await w.watch.check();
106
+ await env().control.reset();
107
+ expect(await w.more()).toBe(1);
108
+ w.watch.stop();
109
+ });
110
+ it('refuses a table the person may not read, and one that does not exist', async () => {
111
+ const sdk = await env().connect(student);
112
+ const errors = [];
113
+ const refused = sdk.db.watch(['slot'], () => undefined, {
114
+ onError: (e) => errors.push(e),
115
+ });
116
+ await expectError(refused.check(), 'NOT_PERMITTED');
117
+ expect(errors).toHaveLength(1);
118
+ const unknown = sdk.db.watch(['nothing'], () => undefined, { onError: () => undefined });
119
+ await expectError(unknown.check(), 'VALIDATION');
120
+ // A refused watch does not stop the others.
121
+ const fine = watching(sdk, ['booking']);
122
+ const bad = sdk.db.watch(['slot'], () => undefined, { onError: () => undefined });
123
+ await fine.watch.check();
124
+ expect(fine.calls()).toBe(1);
125
+ await expectError(bad.check(), 'NOT_PERMITTED');
126
+ fine.watch.stop();
127
+ });
128
+ it('says what it takes when called wrongly', async () => {
129
+ const sdk = await env().connect(staff);
130
+ expect(() => sdk.db.watch('slot', () => undefined)).toThrow(/list of the app's entities/);
131
+ expect(() => sdk.db.watch([], () => undefined)).toThrow(/list of the app's entities/);
132
+ expect(() => sdk.db.watch(['slot'])).toThrow(/function to call/);
133
+ expect(() => sdk.db.watch(['slot'], () => undefined, { intervalMs: 'fast' })).toThrow(/number of milliseconds/);
134
+ });
135
+ });
136
+ describe('db watch and listed access (D157, D142)', () => {
137
+ useApp(LISTED_APP);
138
+ it('calls back when a table its rules look people up in changes', async () => {
139
+ const me = staff;
140
+ await env().control.setAppAdmins([me.personId]);
141
+ const sdk = await env().connect(staff);
142
+ const signups = sdk.db.entity('signups');
143
+ const listing = await signups.create({ staffId: me.personId });
144
+ const roster = watching(sdk, ['roster']);
145
+ const setting = watching(sdk, ['setting']);
146
+ await roster.watch.check();
147
+ await setting.watch.check();
148
+ // Who may read the roster has changed, though no roster record has.
149
+ await (await env().connect(otherStaff)).db.entity('signups').delete(listing.id);
150
+ expect(await roster.more()).toBe(1);
151
+ expect(await setting.more()).toBe(0);
152
+ roster.watch.stop();
153
+ setting.watch.stop();
154
+ });
155
+ });
156
+ }
@@ -0,0 +1,3 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ /** Formatted notifications (D151) and attachments (D152): what ADR 0041 adds. */
3
+ export declare function notifications({ env, useApp, staff, otherStaff, student, parent, childId, }: Setup): void;