@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,218 @@
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 { parentsOf } from "../src/index.js";
4
+ import { NOTIFY_APP } from "./apps.js";
5
+ import { expectError } from "./helpers.js";
6
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4];
7
+ const PDF = [0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34];
8
+ const blob = (bytes, type) => new Blob([new Uint8Array(bytes)], { type });
9
+ /** Formatted notifications (D151) and attachments (D152): what ADR 0041 adds. */
10
+ export function notifications({ env, useApp, staff, otherStaff, student, parent, childId, }) {
11
+ const staffId = otherStaff.personId;
12
+ const base = { type: 'notice.sent', subject: 'Zoo excursion', to: { person: staffId } };
13
+ const content = [
14
+ { heading: 'Year 9 zoo excursion' },
15
+ { text: 'Please give your consent by Friday.' },
16
+ {
17
+ details: [
18
+ ['Date', 'Thursday 12 March'],
19
+ ['Cost', '$18'],
20
+ ],
21
+ },
22
+ { list: ['Bus leaves at 8:45 am', 'Back by 3:00 pm'] },
23
+ { button: { label: 'Give consent', link: '/consent/1' } },
24
+ ];
25
+ describe('notify: formatted messages (D151)', () => {
26
+ useApp(NOTIFY_APP);
27
+ it('keeps the blocks, and makes the plain text from them', async () => {
28
+ const sdk = await env().connect(staff);
29
+ await sdk.notify.send({ ...base, content });
30
+ const [entry] = (await env().control.outbox());
31
+ expect(entry.content).toEqual(content);
32
+ expect(entry.body).toBe([
33
+ 'Year 9 zoo excursion',
34
+ '',
35
+ 'Please give your consent by Friday.',
36
+ '',
37
+ 'Date: Thursday 12 March',
38
+ 'Cost: $18',
39
+ '',
40
+ '- Bus leaves at 8:45 am',
41
+ '- Back by 3:00 pm',
42
+ '',
43
+ 'Give consent: /consent/1',
44
+ ].join('\n'));
45
+ });
46
+ it('uses the body an app gives beside the blocks, and still takes a body alone', async () => {
47
+ const sdk = await env().connect(staff);
48
+ await sdk.notify.send({ ...base, body: 'Short version', content });
49
+ await sdk.notify.send({ ...base, body: 'Just text' });
50
+ const outbox = (await env().control.outbox());
51
+ expect(outbox.map((e) => e.body).sort()).toEqual(['Just text', 'Short version']);
52
+ expect(outbox.find((e) => e.body === 'Just text').content).toBeUndefined();
53
+ await expectError(sdk.notify.send({ ...base }), 'VALIDATION');
54
+ });
55
+ it('keeps HTML as text: an app never writes markup', async () => {
56
+ const sdk = await env().connect(staff);
57
+ const html = '<img src=x onerror=alert(1)><a href="https://evil.example">x</a>';
58
+ await sdk.notify.send({ ...base, content: [{ heading: html }, { text: html }] });
59
+ const [entry] = (await env().control.outbox());
60
+ expect(entry.content).toEqual([{ heading: html }, { text: html }]);
61
+ expect(entry.body).toContain(html);
62
+ });
63
+ it('refuses anything that is not one of the blocks, and a link out of the app', async () => {
64
+ const sdk = await env().connect(staff);
65
+ const bad = (blocks) => expectError(sdk.notify.send({ ...base, content: blocks }), 'VALIDATION');
66
+ await bad('hello');
67
+ await bad([]);
68
+ await bad([{ html: '<p>x</p>' }]);
69
+ await bad([{ heading: 'a', text: 'b' }]);
70
+ await bad([{ heading: '' }]);
71
+ await bad([{ heading: 'x'.repeat(201) }]);
72
+ await bad([{ text: 'x'.repeat(2001) }]);
73
+ await bad([{ list: [] }]);
74
+ await bad([{ list: ['a', 2] }]);
75
+ await bad([{ details: [['Date']] }]);
76
+ await bad([{ details: [['Date', 'x', 'y']] }]);
77
+ await bad([{ button: { label: 'Go', link: 'https://evil.example' } }]);
78
+ await bad([{ button: { label: 'Go', link: '//evil.example' } }]);
79
+ await bad([{ button: { label: 'Go' } }]);
80
+ await bad([
81
+ { button: { label: 'One', link: '/a' } },
82
+ { button: { label: 'Two', link: '/b' } },
83
+ ]);
84
+ await bad(Array.from({ length: 31 }, () => ({ text: 'x' })));
85
+ await bad(Array.from({ length: 6 }, () => ({ text: 'x'.repeat(2000) })));
86
+ expect(await env().control.outbox()).toEqual([]);
87
+ });
88
+ });
89
+ describe('notify: attachments (D152)', () => {
90
+ useApp(NOTIFY_APP);
91
+ it('carries a copy of each file to every recipient', async () => {
92
+ const sdk = await env().connect(staff);
93
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
94
+ const photo = await sdk.files.upload(blob(PNG, 'image/png'), { name: 'zoo.png' });
95
+ await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
96
+ const { recipients } = await sdk.notify.send({
97
+ ...base,
98
+ to: parentsOf(childId),
99
+ regarding: { studentId: childId },
100
+ content,
101
+ attachments: [slip.id, photo.id],
102
+ });
103
+ expect(recipients.some((r) => r.personId === parent.personId)).toBe(true);
104
+ const outbox = (await env().control.outbox());
105
+ expect(outbox).toHaveLength(recipients.length);
106
+ for (const entry of outbox)
107
+ expect(entry.attachments.map((a) => [a.name, a.type, a.size])).toEqual([
108
+ ['slip.pdf', 'application/pdf', PDF.length],
109
+ ['zoo.png', 'image/png', PNG.length],
110
+ ]);
111
+ const [first, second] = outbox[0].attachments;
112
+ // The copy is its own file: not the one the record holds.
113
+ expect(first.id).not.toBe(slip.id);
114
+ expect((await env().control.outboxAttachment(first.id)).bytes).toEqual(PDF);
115
+ expect((await env().control.outboxAttachment(second.id)).name).toBe('zoo.png');
116
+ // What was sent is not a file an app can read.
117
+ await expectError(sdk.files.info(first.id), 'NOT_FOUND');
118
+ await expectError((await env().connect(parent)).files.read(first.id), 'NOT_FOUND');
119
+ expect(await env().control.outboxAttachment(slip.id)).toBeUndefined();
120
+ });
121
+ it('keeps what was sent after the record is gone and a day has passed', async () => {
122
+ await env().control.setClock('2026-03-04T03:00:00.000Z');
123
+ const sdk = await env().connect(staff);
124
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
125
+ const notice = await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
126
+ await sdk.notify.send({ ...base, body: 'See attached', attachments: [slip.id] });
127
+ await sdk.db.entity('notice').delete(notice.id);
128
+ await env().control.advanceClock(48 * 60 * 60 * 1000);
129
+ // An upload sweeps files nobody attached; a sent copy is not one of them.
130
+ await sdk.files.upload(blob(PNG, 'image/png'));
131
+ const [entry] = (await env().control.outbox());
132
+ expect((await env().control.outboxAttachment(entry.attachments[0].id)).bytes).toEqual(PDF);
133
+ await env().control.restart();
134
+ expect((await env().control.outboxAttachment(entry.attachments[0].id)).bytes).toEqual(PDF);
135
+ });
136
+ it('sends only files the sender can read', async () => {
137
+ const mine = await env().connect(student);
138
+ const theirs = await (await env().connect(staff)).files.upload(blob(PNG, 'image/png'));
139
+ const send = (attachments) => mine.notify.send({ ...base, body: 'x', attachments });
140
+ await expectError(send([theirs.id]), 'NOT_FOUND');
141
+ await expectError(send(['file_nothing']), 'NOT_FOUND');
142
+ await expectError(send('one'), 'VALIDATION');
143
+ await expectError(send([1]), 'VALIDATION');
144
+ const own = await mine.files.upload(blob(PNG, 'image/png'));
145
+ await expectError(send([own.id, own.id]), 'VALIDATION');
146
+ expect(await env().control.outbox()).toEqual([]);
147
+ expect((await send([own.id])).recipients).toHaveLength(1);
148
+ });
149
+ // Two 6 MB uploads: slow on a busy machine, so it is given more time than the default.
150
+ it('takes at most five files and 10 MB in all', async () => {
151
+ const sdk = await env().connect(staff);
152
+ const small = [];
153
+ for (let i = 0; i < 6; i++)
154
+ small.push((await sdk.files.upload(blob(PNG, 'image/png'))).id);
155
+ await expectError(sdk.notify.send({ ...base, body: 'x', attachments: small }), 'VALIDATION');
156
+ const big = [];
157
+ for (let i = 0; i < 2; i++)
158
+ big.push((await sdk.files.upload(new Blob([new Uint8Array(6 * 1024 * 1024)], { type: 'text/plain' }))).id);
159
+ const e = await expectError(sdk.notify.send({ ...base, body: 'x', attachments: big }), 'VALIDATION');
160
+ expect(e.message).toContain('10 MB');
161
+ expect(await env().control.outbox()).toEqual([]);
162
+ }, 30_000);
163
+ it('never sends a file to a role its field is hidden from, or a staff-only level beyond staff', async () => {
164
+ const sdk = await env().connect(staff);
165
+ const note = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'note.pdf' });
166
+ const review = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'review.pdf' });
167
+ await sdk.db.entity('notice').create({ title: 'x', staffNote: note.id, review: review.id });
168
+ const toParents = { to: parentsOf(childId), regarding: { studentId: childId } };
169
+ for (const [id, field] of [
170
+ [note.id, 'staffNote'],
171
+ [review.id, 'review'],
172
+ ]) {
173
+ const e = await expectError(sdk.notify.send({ ...base, ...toParents, body: 'x', attachments: [id] }), 'NOT_PERMITTED');
174
+ expect(e.message).toContain(`notice.${field}`);
175
+ }
176
+ expect(await env().control.outbox()).toEqual([]);
177
+ // To staff, both go.
178
+ const sent = await sdk.notify.send({ ...base, body: 'x', attachments: [note.id, review.id] });
179
+ expect(sent.recipients).toEqual([{ personId: staffId, role: 'staff' }]);
180
+ });
181
+ it('sends and copies once for a repeated key', async () => {
182
+ const sdk = await env().connect(staff);
183
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'));
184
+ const send = () => sdk.notify.send({ ...base, body: 'x', attachments: [slip.id], idempotencyKey: 'once' });
185
+ await send();
186
+ await send();
187
+ const outbox = (await env().control.outbox());
188
+ expect(outbox).toHaveLength(1);
189
+ });
190
+ it('records for the school who sent which files to whom, and tells the app nothing more', async () => {
191
+ const sdk = await env().connect(staff);
192
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
193
+ const notice = await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
194
+ await sdk.notify.send({ ...base, body: 'x', attachments: [slip.id] });
195
+ const log = await env().control.auditLog();
196
+ const entry = log.find((e) => e.action === 'notification.attachments');
197
+ expect(entry).toMatchObject({
198
+ source: 'platform',
199
+ visibility: 'cio',
200
+ actor: staff.personId,
201
+ });
202
+ expect(entry.data).toMatchObject({
203
+ type: 'notice.sent',
204
+ recipients: [staffId],
205
+ files: [{ name: 'slip.pdf', entity: 'notice', recordId: notice.id, field: 'slip' }],
206
+ });
207
+ expect((await sdk.audit.list()).items).toEqual([]);
208
+ });
209
+ it('clears what was sent with the app’s data', async () => {
210
+ const sdk = await env().connect(staff);
211
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'));
212
+ await sdk.notify.send({ ...base, body: 'x', attachments: [slip.id] });
213
+ const [entry] = (await env().control.outbox());
214
+ await env().control.reset();
215
+ expect(await env().control.outboxAttachment(entry.attachments[0].id)).toBeUndefined();
216
+ });
217
+ });
218
+ }
@@ -0,0 +1,13 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ type Person = {
3
+ id: string;
4
+ givenName: string;
5
+ familyName: string;
6
+ email?: string;
7
+ };
8
+ /** Search by words (D153) and counts and totals (D154): what ADR 0042 adds. */
9
+ export declare function searchAndTotals({ env, useApp, staff, student, students, }: Setup & {
10
+ students: readonly Person[];
11
+ staffRecords: readonly Person[];
12
+ }): void;
13
+ export {};
@@ -0,0 +1,226 @@
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 { SEARCH_APP } from "./apps.js";
4
+ import { expectError, listAll } from "./helpers.js";
5
+ /** Search by words (D153) and counts and totals (D154): what ADR 0042 adds. */
6
+ export function searchAndTotals({ env, useApp, staff, student, students, }) {
7
+ const titles = async (sdk, options) => (await sdk.db.entity('request').list({ orderBy: { field: 'title' }, ...options })).items.map((r) => r.title);
8
+ describe('db search (D153)', () => {
9
+ useApp(SEARCH_APP);
10
+ const seed = async () => {
11
+ const sdk = await env().connect(staff);
12
+ const requests = sdk.db.entity('request');
13
+ await requests.create({ title: 'Zoo excursion', body: 'Bus to the zoo', status: 'open' });
14
+ await requests.create({ title: 'Zoë’s camp', body: 'Three nights', status: 'open' });
15
+ await requests.create({
16
+ title: 'Swimming carnival',
17
+ tags: ['bus', 'Pool'],
18
+ status: 'closed',
19
+ secret: 'budget overrun',
20
+ });
21
+ await requests.create({ title: 'Museum visit', status: 'open' });
22
+ return sdk;
23
+ };
24
+ it('matches records where every word appears somewhere in the searchable fields', async () => {
25
+ const sdk = await seed();
26
+ expect(await titles(sdk, { search: 'zoo' })).toEqual(['Zoo excursion']);
27
+ // Across fields, and in a list of text.
28
+ expect(await titles(sdk, { search: 'bus' })).toEqual(['Swimming carnival', 'Zoo excursion']);
29
+ expect(await titles(sdk, { search: 'bus zoo' })).toEqual(['Zoo excursion']);
30
+ expect(await titles(sdk, { search: 'bus pool' })).toEqual(['Swimming carnival']);
31
+ expect(await titles(sdk, { search: 'bus museum' })).toEqual([]);
32
+ expect(await titles(sdk, { search: 'nothing' })).toEqual([]);
33
+ });
34
+ it('ignores case and accents, and matches part of a word', async () => {
35
+ const sdk = await seed();
36
+ expect(await titles(sdk, { search: 'ZOO' })).toEqual(['Zoo excursion']);
37
+ expect(await titles(sdk, { search: 'zoe' })).toEqual(['Zoë’s camp']);
38
+ expect(await titles(sdk, { search: 'Zoë' })).toEqual(['Zoë’s camp']);
39
+ expect(await titles(sdk, { search: 'exc' })).toEqual(['Zoo excursion']);
40
+ expect(await titles(sdk, { search: ' carnival swim ' })).toEqual(['Swimming carnival']);
41
+ });
42
+ it('works with where, an order and pages', async () => {
43
+ const sdk = await seed();
44
+ expect(await titles(sdk, { search: 'bus', where: { status: 'open' } })).toEqual([
45
+ 'Zoo excursion',
46
+ ]);
47
+ const requests = sdk.db.entity('request');
48
+ const first = await requests.list({ search: 'bus', orderBy: { field: 'title' }, limit: 1 });
49
+ expect(first.items.map((r) => r.title)).toEqual(['Swimming carnival']);
50
+ const second = await requests.list({
51
+ search: 'bus',
52
+ orderBy: { field: 'title' },
53
+ limit: 1,
54
+ cursor: first.nextCursor,
55
+ });
56
+ expect(second.items.map((r) => r.title)).toEqual(['Zoo excursion']);
57
+ expect(second.nextCursor).toBeNull();
58
+ // A cursor belongs to its search.
59
+ await expectError(requests.list({
60
+ search: 'zoo',
61
+ orderBy: { field: 'title' },
62
+ limit: 1,
63
+ cursor: first.nextCursor,
64
+ }), 'VALIDATION');
65
+ });
66
+ it('never looks in a field hidden from the reader, or in records they cannot read', async () => {
67
+ await seed();
68
+ const asStaff = await env().connect(staff);
69
+ expect(await titles(asStaff, { search: 'overrun' })).toEqual(['Swimming carnival']);
70
+ const mine = await env().connect(student);
71
+ await mine.db.entity('request').create({ title: 'My excursion idea', status: 'open' });
72
+ // The student reads only their own row: staff's rows are not found, whatever they hold.
73
+ expect(await titles(mine, { search: 'excursion' })).toEqual(['My excursion idea']);
74
+ expect(await titles(mine, { search: 'overrun' })).toEqual([]);
75
+ // Staff write a secret onto the student's own row; the student's search still can't see it.
76
+ const row = (await asStaff.db.entity('request').list({ search: 'idea' })).items[0];
77
+ await asStaff.db.entity('request').update(row.id, { secret: 'flagged for review' });
78
+ expect(await titles(mine, { search: 'flagged' })).toEqual([]);
79
+ expect(await titles(asStaff, { search: 'flagged' })).toEqual(['My excursion idea']);
80
+ });
81
+ it('takes 1 to 5 words, and refuses an entity that names no searchable fields', async () => {
82
+ const sdk = await seed();
83
+ const requests = sdk.db.entity('request');
84
+ await expectError(requests.list({ search: '' }), 'VALIDATION');
85
+ await expectError(requests.list({ search: ' ' }), 'VALIDATION');
86
+ await expectError(requests.list({ search: 5 }), 'VALIDATION');
87
+ await expectError(requests.list({ search: 'a b c d e f' }), 'VALIDATION');
88
+ await expectError(requests.list({ search: 'x'.repeat(101) }), 'VALIDATION');
89
+ const e = await expectError(sdk.db.entity('plain').list({ search: 'x' }), 'VALIDATION');
90
+ expect(e.message).toContain('search: [');
91
+ });
92
+ });
93
+ describe('school search (D153)', () => {
94
+ useApp(SEARCH_APP);
95
+ it('finds people by name, in any order of words, among those the person may see', async () => {
96
+ const sdk = await env().connect(staff);
97
+ const target = students[40];
98
+ const found = await listAll(sdk.school.students, {
99
+ search: `${target.familyName} ${target.givenName}`.toLowerCase(),
100
+ });
101
+ expect(found.map((s) => s.id)).toContain(target.id);
102
+ for (const s of found) {
103
+ const text = `${s.givenName} ${s.familyName}`.toLowerCase();
104
+ expect(text).toContain(target.givenName.toLowerCase());
105
+ }
106
+ // A student sees themselves and nobody else, searched or not.
107
+ const mine = await env().connect(student);
108
+ expect(await listAll(mine.school.students, { search: target.familyName })).toEqual(target.id === student.personId ? found : []);
109
+ });
110
+ it('looks only in the text the app has been granted', async () => {
111
+ const sdk = await env().connect(staff);
112
+ // This app holds the basic level only, so an email address, a contact detail, is not searched.
113
+ const withEmail = students.find((s) => typeof s.email === 'string');
114
+ if (withEmail)
115
+ expect(await listAll(sdk.school.students, { search: withEmail.email })).toEqual([]);
116
+ await expectError(sdk.school.students.list({ search: '' }), 'VALIDATION');
117
+ });
118
+ });
119
+ describe('db counts and totals (D154)', () => {
120
+ useApp(SEARCH_APP);
121
+ const seed = async () => {
122
+ const sdk = await env().connect(staff);
123
+ const requests = sdk.db.entity('request');
124
+ await requests.create({ title: 'a', status: 'open', term: 'T1', cost: 10, margin: 1 });
125
+ await requests.create({ title: 'b', status: 'open', term: 'T1', cost: 20.5, margin: 2 });
126
+ await requests.create({ title: 'c', status: 'closed', term: 'T2', cost: 5 });
127
+ await requests.create({ title: 'd bus', status: 'closed' });
128
+ return sdk;
129
+ };
130
+ it('counts the records that match', async () => {
131
+ const sdk = await seed();
132
+ const requests = sdk.db.entity('request');
133
+ expect(await requests.count()).toBe(4);
134
+ expect(await requests.count({ where: { status: 'open' } })).toBe(2);
135
+ expect(await requests.count({ search: 'bus' })).toBe(1);
136
+ expect(await requests.count({ where: { cost: { gte: 10 } } })).toBe(2);
137
+ expect(await requests.count({ where: { status: 'open', term: 'T2' } })).toBe(0);
138
+ await expectError(requests.count({ limit: 5 }), 'VALIDATION');
139
+ await expectError(requests.count({ where: { nope: 1 } }), 'VALIDATION');
140
+ });
141
+ it('adds up, and finds the least, the greatest and the average of number fields', async () => {
142
+ const sdk = await seed();
143
+ const summary = await sdk.db
144
+ .entity('request')
145
+ .summarise({ sum: ['cost'], min: ['cost'], max: ['cost'], avg: ['cost', 'margin'] });
146
+ expect(summary).toEqual({
147
+ count: 4,
148
+ sum: { cost: 35.5 },
149
+ min: { cost: 5 },
150
+ max: { cost: 20.5 },
151
+ // An average is over the records that have the field.
152
+ avg: { cost: 11.8333333333, margin: 1.5 },
153
+ });
154
+ expect(await sdk.db.entity('request').summarise()).toEqual({ count: 4 });
155
+ // With nothing to work on, a sum is zero and the others are empty.
156
+ expect(await sdk.db
157
+ .entity('request')
158
+ .summarise({ where: { term: 'T9' }, sum: ['cost'], min: ['cost'], avg: ['cost'] })).toEqual({ count: 0, sum: { cost: 0 }, min: { cost: null }, avg: { cost: null } });
159
+ });
160
+ it('gives the same for each value of one field, with a group for the empty ones', async () => {
161
+ const sdk = await seed();
162
+ const byTerm = await sdk.db
163
+ .entity('request')
164
+ .summarise({ groupBy: 'term', sum: ['cost'], where: { cost: { gte: 0 } } });
165
+ expect(byTerm).toEqual({
166
+ count: 3,
167
+ sum: { cost: 35.5 },
168
+ groups: [
169
+ { value: 'T1', count: 2, sum: { cost: 30.5 } },
170
+ { value: 'T2', count: 1, sum: { cost: 5 } },
171
+ ],
172
+ });
173
+ const byStatus = await sdk.db.entity('request').summarise({ groupBy: 'term' });
174
+ expect(byStatus.groups).toEqual([
175
+ { value: 'T1', count: 2 },
176
+ { value: 'T2', count: 1 },
177
+ { value: null, count: 1 },
178
+ ]);
179
+ const byWho = await sdk.db.entity('request').summarise({ groupBy: 'createdBy' });
180
+ expect(byWho.groups).toEqual([{ value: staff.personId, count: 4 }]);
181
+ });
182
+ it('covers only what the person may read, and only fields they can see', async () => {
183
+ await seed();
184
+ const mine = await env().connect(student);
185
+ const requests = mine.db.entity('request');
186
+ await requests.create({ title: 'mine', status: 'open', cost: 3 });
187
+ expect(await requests.count()).toBe(1);
188
+ expect(await requests.summarise({ sum: ['cost'], groupBy: 'status' })).toEqual({
189
+ count: 1,
190
+ sum: { cost: 3 },
191
+ groups: [{ value: 'open', count: 1, sum: { cost: 3 } }],
192
+ });
193
+ await expectError(requests.summarise({ sum: ['margin'] }), 'VALIDATION');
194
+ await expectError(requests.summarise({ groupBy: 'secret' }), 'VALIDATION');
195
+ await expectError(requests.count({ where: { secret: 'x' } }), 'VALIDATION');
196
+ // An entity the role may not read at all refuses a count as it refuses a list.
197
+ await expectError(mine.db.entity('plain').count(), 'NOT_PERMITTED');
198
+ });
199
+ it('takes number fields to total and a single-valued field to group by', async () => {
200
+ const sdk = await seed();
201
+ const requests = sdk.db.entity('request');
202
+ await expectError(requests.summarise({ sum: ['title'] }), 'VALIDATION');
203
+ await expectError(requests.summarise({ sum: 'cost' }), 'VALIDATION');
204
+ await expectError(requests.summarise({ sum: [] }), 'VALIDATION');
205
+ await expectError(requests.summarise({ sum: ['cost', 'cost'] }), 'VALIDATION');
206
+ await expectError(requests.summarise({ groupBy: 'tags' }), 'VALIDATION');
207
+ await expectError(requests.summarise({ groupBy: 'proof' }), 'VALIDATION');
208
+ await expectError(requests.summarise({ groupBy: 'nope' }), 'VALIDATION');
209
+ await expectError(requests.summarise({ median: ['cost'] }), 'VALIDATION');
210
+ });
211
+ it('refuses more than 200 groups, in words, and never returns a wrong answer', async () => {
212
+ const sdk = await env().connect(staff);
213
+ for (let start = 0; start < 225; start += 25)
214
+ await sdk.db.batch(Array.from({ length: 25 }, (_, i) => ({
215
+ create: 'request',
216
+ input: { title: `r${start + i}`, status: 'open', term: `t${start + i}` },
217
+ })));
218
+ const e = await expectError(sdk.db.entity('request').summarise({ groupBy: 'term' }), 'VALIDATION');
219
+ expect(e.message).toContain('more than 200');
220
+ expect(await sdk.db.entity('request').count()).toBe(225);
221
+ expect((await sdk.db.entity('request').summarise({ groupBy: 'status' })).groups).toEqual([
222
+ { value: 'open', count: 225 },
223
+ ]);
224
+ });
225
+ });
226
+ }
@@ -46,6 +46,11 @@ export type ContractEnv = {
46
46
  type: string;
47
47
  title: string;
48
48
  }[]>;
49
+ /** A file a sent notification carries (D152), by the id its outbox entry gives; undefined when there is none. */
50
+ outboxAttachment(id: string): Promise<{
51
+ name: string;
52
+ bytes: number[];
53
+ } | undefined>;
49
54
  /** Every audit entry, including CIO-only ones (D19). */
50
55
  auditLog(): Promise<readonly (Record<string, any> & {
51
56
  visibility: 'app' | 'cio';
@@ -6,6 +6,11 @@ import stored from '@quad-education/fictional-school/dataset' with { type: 'json
6
6
  import { parentsOf, staffOf, studentsOf } from "../src/index.js";
7
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);
@@ -64,7 +69,7 @@ export function defineContractSuite(name, factory) {
64
69
  },
65
70
  });
66
71
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
67
- expect(sdk.version).toBe('0.8.0');
72
+ expect(sdk.version).toBe('0.9.0');
68
73
  });
69
74
  it('knows parents and students', async () => {
70
75
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
@@ -1629,6 +1634,27 @@ export function defineContractSuite(name, factory) {
1629
1634
  expect(same).toEqual(entry);
1630
1635
  });
1631
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);
1632
1658
  describe('clock controls (D14)', () => {
1633
1659
  useApp(TEST_APP);
1634
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;