@quad-education/sdk 0.0.0-stage → 0.1.2
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.
- package/LICENSE.md +15 -0
- package/README.md +105 -2
- package/dist/contract-tests/apps.d.ts +332 -0
- package/dist/contract-tests/apps.js +261 -0
- package/dist/contract-tests/index.d.ts +3 -0
- package/dist/contract-tests/index.js +2 -0
- package/dist/contract-tests/suite.d.ts +57 -0
- package/dist/contract-tests/suite.js +1286 -0
- package/dist/src/client/connect.d.ts +10 -0
- package/dist/src/client/connect.js +12 -0
- package/dist/src/client/create-client.d.ts +14 -0
- package/dist/src/client/create-client.js +76 -0
- package/dist/src/client/handshake-client.d.ts +16 -0
- package/dist/src/client/handshake-client.js +37 -0
- package/dist/src/contract/errors.d.ts +8 -0
- package/dist/src/contract/errors.js +13 -0
- package/dist/src/contract/recipients.d.ts +28 -0
- package/dist/src/contract/recipients.js +12 -0
- package/dist/src/contract/types.d.ts +421 -0
- package/dist/src/contract/types.js +1 -0
- package/dist/src/engine/audit.d.ts +27 -0
- package/dist/src/engine/audit.js +105 -0
- package/dist/src/engine/cron.d.ts +17 -0
- package/dist/src/engine/cron.js +143 -0
- package/dist/src/engine/db-indexes.d.ts +11 -0
- package/dist/src/engine/db-indexes.js +82 -0
- package/dist/src/engine/engine.d.ts +153 -0
- package/dist/src/engine/engine.js +922 -0
- package/dist/src/engine/host.d.ts +39 -0
- package/dist/src/engine/host.js +70 -0
- package/dist/src/engine/in-process.d.ts +5 -0
- package/dist/src/engine/in-process.js +18 -0
- package/dist/src/engine/index.d.ts +10 -0
- package/dist/src/engine/index.js +8 -0
- package/dist/src/engine/query.d.ts +16 -0
- package/dist/src/engine/query.js +106 -0
- package/dist/src/engine/runner.d.ts +26 -0
- package/dist/src/engine/runner.js +260 -0
- package/dist/src/engine/state.d.ts +107 -0
- package/dist/src/engine/state.js +16 -0
- package/dist/src/engine/storage.d.ts +46 -0
- package/dist/src/engine/storage.js +86 -0
- package/dist/src/engine/tasks.d.ts +17 -0
- package/dist/src/engine/tasks.js +245 -0
- package/dist/src/engine/validate-input.d.ts +9 -0
- package/dist/src/engine/validate-input.js +76 -0
- package/dist/src/engine/values.d.ts +10 -0
- package/dist/src/engine/values.js +58 -0
- package/dist/src/handshake.d.ts +16 -0
- package/dist/src/handshake.js +9 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +4 -0
- package/dist/src/jobs/define.d.ts +41 -0
- package/dist/src/jobs/define.js +28 -0
- package/dist/src/jobs/host.d.ts +13 -0
- package/dist/src/jobs/host.js +22 -0
- package/dist/src/jobs/index.d.ts +1 -0
- package/dist/src/jobs/index.js +2 -0
- package/dist/src/jobs/worker.d.ts +17 -0
- package/dist/src/jobs/worker.js +25 -0
- package/dist/src/platform-types.d.ts +19 -0
- package/dist/src/platform-types.js +1 -0
- package/dist/src/port-rpc.d.ts +42 -0
- package/dist/src/port-rpc.js +85 -0
- package/dist/src/protocol.d.ts +41 -0
- package/dist/src/protocol.js +45 -0
- package/dist/src/testing/index.d.ts +78 -0
- package/dist/src/testing/index.js +118 -0
- package/package.json +71 -3
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
|
|
2
|
+
/** Define a job. Its name must match a `cron` entry or a `scheduled` name in app.manifest.json. */
|
|
3
|
+
export function defineJob(job) {
|
|
4
|
+
if (!NAME_RE.test(job.name))
|
|
5
|
+
throw new Error(`job names are lowercase kebab-case: '${job.name}'`);
|
|
6
|
+
if (typeof job.run !== 'function')
|
|
7
|
+
throw new Error(`job '${job.name}' needs a run function`);
|
|
8
|
+
return job;
|
|
9
|
+
}
|
|
10
|
+
/** Runs one job for a run request. Used by the jobs worker, the test kit and contract tests. */
|
|
11
|
+
export async function executeRun(jobs, run, sdk) {
|
|
12
|
+
const job = jobs.find((j) => j.name === run.jobName);
|
|
13
|
+
if (!job)
|
|
14
|
+
return { ok: false, error: `no job named '${run.jobName}' in jobs/index.ts` };
|
|
15
|
+
try {
|
|
16
|
+
await job.run({
|
|
17
|
+
sdk,
|
|
18
|
+
runId: run.runId,
|
|
19
|
+
jobName: run.jobName,
|
|
20
|
+
scheduledFor: run.scheduledFor,
|
|
21
|
+
payload: run.payload,
|
|
22
|
+
});
|
|
23
|
+
return { ok: true };
|
|
24
|
+
}
|
|
25
|
+
catch (e) {
|
|
26
|
+
return { ok: false, error: e instanceof Error ? `${e.name}: ${e.message}` : String(e) };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type HandshakeOptions } from '../client/handshake-client.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The jobs host (D20): a hidden page on the app's origin, loaded by the demo shell. It does
|
|
4
|
+
* the same handshake as the UI (as the system principal, chosen by the shell), then hands
|
|
5
|
+
* the session port to the Web Worker that runs the app's `jobs/` with no DOM.
|
|
6
|
+
*
|
|
7
|
+
* `quad gen` writes the app's `jobs.html`, which creates the worker from its generated
|
|
8
|
+
* `jobs-worker.ts`, so Vite bundles the jobs for dev and for production builds:
|
|
9
|
+
* hostJobs({ worker: new Worker(new URL('./jobs-worker.ts', import.meta.url), { type: 'module' }) })
|
|
10
|
+
*/
|
|
11
|
+
export declare function hostJobs(options: HandshakeOptions & {
|
|
12
|
+
worker: Worker;
|
|
13
|
+
}): Promise<Worker>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { handshake } from "../client/handshake-client.js";
|
|
2
|
+
/**
|
|
3
|
+
* The jobs host (D20): a hidden page on the app's origin, loaded by the demo shell. It does
|
|
4
|
+
* the same handshake as the UI (as the system principal, chosen by the shell), then hands
|
|
5
|
+
* the session port to the Web Worker that runs the app's `jobs/` with no DOM.
|
|
6
|
+
*
|
|
7
|
+
* `quad gen` writes the app's `jobs.html`, which creates the worker from its generated
|
|
8
|
+
* `jobs-worker.ts`, so Vite bundles the jobs for dev and for production builds:
|
|
9
|
+
* hostJobs({ worker: new Worker(new URL('./jobs-worker.ts', import.meta.url), { type: 'module' }) })
|
|
10
|
+
*/
|
|
11
|
+
export async function hostJobs(options) {
|
|
12
|
+
const { worker, ...handshakeOptions } = options;
|
|
13
|
+
const { port, session } = await handshake(handshakeOptions);
|
|
14
|
+
worker.addEventListener('message', (e) => {
|
|
15
|
+
if (e.data?.type === 'quad:jobs-error')
|
|
16
|
+
console.error(`[quad] jobs worker: ${e.data.error}`);
|
|
17
|
+
if (e.data?.type === 'quad:jobs-ready')
|
|
18
|
+
console.info(`[quad] jobs ready: ${e.data.jobs?.join(', ')}`);
|
|
19
|
+
});
|
|
20
|
+
worker.postMessage({ type: 'quad:jobs-session', session }, [port]);
|
|
21
|
+
return worker;
|
|
22
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineJob, type Job, type JobContext } from './define.ts';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AppConfig } from '../contract/types.ts';
|
|
2
|
+
import type { SessionInfo } from '../protocol.ts';
|
|
3
|
+
import { type Job } from './define.ts';
|
|
4
|
+
export type JobsSessionMessage = {
|
|
5
|
+
type: 'quad:jobs-session';
|
|
6
|
+
session: SessionInfo;
|
|
7
|
+
};
|
|
8
|
+
/** The parts of a worker's global scope the jobs worker uses. */
|
|
9
|
+
export type WorkerScope = {
|
|
10
|
+
addEventListener(type: 'message', listener: (e: MessageEvent) => void): void;
|
|
11
|
+
postMessage(message: unknown): void;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Runs `jobs` in this worker. Waits for the jobs host to hand over the session port, then
|
|
15
|
+
* runs each job the shell sends and reports the result, as the principal the shell chose.
|
|
16
|
+
*/
|
|
17
|
+
export declare function runJobsWorker(jobs: readonly Job<AppConfig>[], scope?: WorkerScope): void;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createSdkClient } from "../client/create-client.js";
|
|
2
|
+
import { portTransport } from "../port-rpc.js";
|
|
3
|
+
import { executeRun } from "./define.js";
|
|
4
|
+
/**
|
|
5
|
+
* Runs `jobs` in this worker. Waits for the jobs host to hand over the session port, then
|
|
6
|
+
* runs each job the shell sends and reports the result, as the principal the shell chose.
|
|
7
|
+
*/
|
|
8
|
+
export function runJobsWorker(jobs, scope = globalThis) {
|
|
9
|
+
scope.addEventListener('message', (e) => {
|
|
10
|
+
if (e.data?.type !== 'quad:jobs-session' || !e.ports[0])
|
|
11
|
+
return;
|
|
12
|
+
const session = e.data.session;
|
|
13
|
+
const transport = portTransport(e.ports[0], session.clock, {
|
|
14
|
+
onRun: (run) => {
|
|
15
|
+
// One SDK per run, tagging every call with its runId; the shell decides who the run
|
|
16
|
+
// acts as from its own record of the run, never from anything the job says (D7).
|
|
17
|
+
const sdk = createSdkClient(transport, session, {
|
|
18
|
+
runId: run.runId,
|
|
19
|
+
});
|
|
20
|
+
void executeRun(jobs, run, sdk).then((result) => transport.reportRun(run.runId, result));
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
scope.postMessage({ type: 'quad:jobs-ready', jobs: jobs.map((j) => j.name) });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Role } from '@quad-education/canonical';
|
|
2
|
+
import type { Channel } from './contract/types.ts';
|
|
3
|
+
/** A simulated outbox entry (D10). Visible to the demo shell and tests, never to apps. */
|
|
4
|
+
export type OutboxEntry = {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly appId: string;
|
|
7
|
+
readonly type: string;
|
|
8
|
+
readonly channel: Channel;
|
|
9
|
+
readonly recipientId: string;
|
|
10
|
+
readonly recipientRole: Role;
|
|
11
|
+
readonly subject: string;
|
|
12
|
+
readonly body: string;
|
|
13
|
+
readonly link?: string;
|
|
14
|
+
readonly regardingStudentId?: string;
|
|
15
|
+
readonly sentAt: string;
|
|
16
|
+
readonly sentBy: string;
|
|
17
|
+
/** Always true in V1: nothing leaves the browser. */
|
|
18
|
+
readonly simulated: true;
|
|
19
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { RunRequest, RunResult } from './jobs/define.ts';
|
|
2
|
+
import { type ClockState, type Method, type RpcResponse } from './protocol.ts';
|
|
3
|
+
import type { Transport } from './client/create-client.ts';
|
|
4
|
+
type PortLike = Pick<MessagePort, 'postMessage' | 'start' | 'close'> & {
|
|
5
|
+
addEventListener(type: 'message', listener: (e: MessageEvent) => void): void;
|
|
6
|
+
};
|
|
7
|
+
/** Host → client. */
|
|
8
|
+
export type ServerMessage = RpcResponse | {
|
|
9
|
+
kind: 'clock';
|
|
10
|
+
clock: ClockState;
|
|
11
|
+
} | {
|
|
12
|
+
kind: 'run';
|
|
13
|
+
run: RunRequest;
|
|
14
|
+
};
|
|
15
|
+
/** Client → host, besides RPC requests. */
|
|
16
|
+
export type RunDoneMessage = {
|
|
17
|
+
kind: 'runDone';
|
|
18
|
+
runId: string;
|
|
19
|
+
result: RunResult;
|
|
20
|
+
};
|
|
21
|
+
export type PortTransport = Transport & {
|
|
22
|
+
close(): void;
|
|
23
|
+
/** Report a job run's result to the host (jobs host only). */
|
|
24
|
+
reportRun(runId: string, result: RunResult): void;
|
|
25
|
+
};
|
|
26
|
+
/** Client side: a Transport over a port, tracking clock updates and receiving job runs. */
|
|
27
|
+
export declare function portTransport(port: PortLike, initialClock: ClockState, options?: {
|
|
28
|
+
onRun?: (run: RunRequest) => void;
|
|
29
|
+
}): PortTransport;
|
|
30
|
+
export type PortServer = {
|
|
31
|
+
pushClock(clock: ClockState): void;
|
|
32
|
+
/** Send a job run to the client (the jobs host). */
|
|
33
|
+
dispatchRun(run: RunRequest): void;
|
|
34
|
+
close(): void;
|
|
35
|
+
};
|
|
36
|
+
/** Host side: answers RPC requests on a port with `handle`, and relays job results. */
|
|
37
|
+
export declare function servePort(port: PortLike, handle: (method: Method, params: unknown, meta: {
|
|
38
|
+
runId?: string;
|
|
39
|
+
}) => Promise<unknown>, options?: {
|
|
40
|
+
onRunDone?: (runId: string, result: RunResult) => void;
|
|
41
|
+
}): PortServer;
|
|
42
|
+
export {};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { QuadError } from "./contract/errors.js";
|
|
2
|
+
import { METHODS, clockNow, deserializeError, serializeError, } from "./protocol.js";
|
|
3
|
+
/** Client side: a Transport over a port, tracking clock updates and receiving job runs. */
|
|
4
|
+
export function portTransport(port, initialClock, options = {}) {
|
|
5
|
+
let clock = initialClock;
|
|
6
|
+
let nextId = 1;
|
|
7
|
+
const pending = new Map();
|
|
8
|
+
port.addEventListener('message', (e) => {
|
|
9
|
+
const msg = e.data;
|
|
10
|
+
if (msg && 'kind' in msg) {
|
|
11
|
+
if (msg.kind === 'clock')
|
|
12
|
+
clock = msg.clock;
|
|
13
|
+
else if (msg.kind === 'run')
|
|
14
|
+
options.onRun?.(msg.run);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
if (!msg || typeof msg.id !== 'number')
|
|
18
|
+
return;
|
|
19
|
+
const res = msg;
|
|
20
|
+
const waiter = pending.get(res.id);
|
|
21
|
+
if (!waiter)
|
|
22
|
+
return;
|
|
23
|
+
pending.delete(res.id);
|
|
24
|
+
if (res.ok)
|
|
25
|
+
waiter.resolve(res.result);
|
|
26
|
+
else
|
|
27
|
+
waiter.reject(deserializeError(res.error));
|
|
28
|
+
});
|
|
29
|
+
port.start();
|
|
30
|
+
return {
|
|
31
|
+
call(method, params, context) {
|
|
32
|
+
const id = nextId++;
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
pending.set(id, { resolve, reject });
|
|
35
|
+
try {
|
|
36
|
+
const request = {
|
|
37
|
+
id,
|
|
38
|
+
method,
|
|
39
|
+
params,
|
|
40
|
+
...(context?.runId ? { runId: context.runId } : {}),
|
|
41
|
+
};
|
|
42
|
+
port.postMessage(request);
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
pending.delete(id);
|
|
46
|
+
reject(new QuadError('TRANSPORT', `couldn't send ${method}: ${e.message}`));
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
},
|
|
50
|
+
// The client reads its own wall clock and applies the host's offset (D14).
|
|
51
|
+
nowMs: () => clockNow(clock, Date.now()),
|
|
52
|
+
close: () => port.close(),
|
|
53
|
+
reportRun: (runId, result) => port.postMessage({ kind: 'runDone', runId, result }),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Host side: answers RPC requests on a port with `handle`, and relays job results. */
|
|
57
|
+
export function servePort(port, handle, options = {}) {
|
|
58
|
+
port.addEventListener('message', (e) => {
|
|
59
|
+
const msg = e.data;
|
|
60
|
+
if (msg && 'kind' in msg) {
|
|
61
|
+
if (msg.kind === 'runDone' && typeof msg.runId === 'string')
|
|
62
|
+
options.onRunDone?.(msg.runId, msg.result);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const req = msg;
|
|
66
|
+
if (!req || typeof req.id !== 'number')
|
|
67
|
+
return;
|
|
68
|
+
const reply = (res) => port.postMessage(res);
|
|
69
|
+
if (!METHODS.includes(req.method)) {
|
|
70
|
+
reply({
|
|
71
|
+
id: req.id,
|
|
72
|
+
ok: false,
|
|
73
|
+
error: { code: 'VALIDATION', message: `unknown method ${String(req.method)}` },
|
|
74
|
+
});
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
handle(req.method, req.params, typeof req.runId === 'string' ? { runId: req.runId } : {}).then((result) => reply({ id: req.id, ok: true, result: result ?? null }), (error) => reply({ id: req.id, ok: false, error: serializeError(error) }));
|
|
78
|
+
});
|
|
79
|
+
port.start();
|
|
80
|
+
return {
|
|
81
|
+
pushClock: (clock) => port.postMessage({ kind: 'clock', clock }),
|
|
82
|
+
dispatchRun: (run) => port.postMessage({ kind: 'run', run }),
|
|
83
|
+
close: () => port.close(),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { QuadError, type QuadErrorCode } from './contract/errors.ts';
|
|
2
|
+
export declare const METHODS: readonly ["auth.me", "school.info", "school.get", "school.list", "school.cohortByCode", "school.cohortMembers", "school.studentParents", "school.parentChildren", "school.calendar", "db.create", "db.update", "db.get", "db.list", "db.delete", "notify.send", "tasks.assign", "tasks.get", "tasks.list", "tasks.complete", "tasks.cancel", "schedule.at", "schedule.cancel", "schedule.list", "cron.list", "audit.record", "audit.list"];
|
|
3
|
+
export type Method = (typeof METHODS)[number];
|
|
4
|
+
export type SerializedError = {
|
|
5
|
+
code: QuadErrorCode;
|
|
6
|
+
message: string;
|
|
7
|
+
details?: unknown;
|
|
8
|
+
};
|
|
9
|
+
/** `runId` ties a call from the jobs host to the run it belongs to; the host decides the principal (D7). */
|
|
10
|
+
export type RpcRequest = {
|
|
11
|
+
id: number;
|
|
12
|
+
method: Method;
|
|
13
|
+
params: unknown;
|
|
14
|
+
runId?: string;
|
|
15
|
+
};
|
|
16
|
+
export type RpcResponse = {
|
|
17
|
+
id: number;
|
|
18
|
+
ok: true;
|
|
19
|
+
result: unknown;
|
|
20
|
+
} | {
|
|
21
|
+
id: number;
|
|
22
|
+
ok: false;
|
|
23
|
+
error: SerializedError;
|
|
24
|
+
};
|
|
25
|
+
/** The engine clock (D14): frozen at an instant, or running at an offset from real time. */
|
|
26
|
+
export type ClockState = {
|
|
27
|
+
kind: 'fixed';
|
|
28
|
+
at: number;
|
|
29
|
+
} | {
|
|
30
|
+
kind: 'offset';
|
|
31
|
+
offsetMs: number;
|
|
32
|
+
};
|
|
33
|
+
export declare function clockNow(state: ClockState, wallClockMs: number): number;
|
|
34
|
+
/** What a client needs to know about its session, sent in the handshake. */
|
|
35
|
+
export type SessionInfo = {
|
|
36
|
+
appId: string;
|
|
37
|
+
timezone: string;
|
|
38
|
+
clock: ClockState;
|
|
39
|
+
};
|
|
40
|
+
export declare function serializeError(e: unknown): SerializedError;
|
|
41
|
+
export declare function deserializeError(e: SerializedError): QuadError;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { QuadError } from "./contract/errors.js";
|
|
2
|
+
// The RPC protocol between an SDK client and the engine. Every SDK call becomes one
|
|
3
|
+
// method call with JSON-serialisable params, whatever the transport (D15).
|
|
4
|
+
export const METHODS = [
|
|
5
|
+
'auth.me',
|
|
6
|
+
'school.info',
|
|
7
|
+
'school.get',
|
|
8
|
+
'school.list',
|
|
9
|
+
'school.cohortByCode',
|
|
10
|
+
'school.cohortMembers',
|
|
11
|
+
'school.studentParents',
|
|
12
|
+
'school.parentChildren',
|
|
13
|
+
'school.calendar',
|
|
14
|
+
'db.create',
|
|
15
|
+
'db.update',
|
|
16
|
+
'db.get',
|
|
17
|
+
'db.list',
|
|
18
|
+
'db.delete',
|
|
19
|
+
'notify.send',
|
|
20
|
+
'tasks.assign',
|
|
21
|
+
'tasks.get',
|
|
22
|
+
'tasks.list',
|
|
23
|
+
'tasks.complete',
|
|
24
|
+
'tasks.cancel',
|
|
25
|
+
'schedule.at',
|
|
26
|
+
'schedule.cancel',
|
|
27
|
+
'schedule.list',
|
|
28
|
+
'cron.list',
|
|
29
|
+
'audit.record',
|
|
30
|
+
'audit.list',
|
|
31
|
+
];
|
|
32
|
+
export function clockNow(state, wallClockMs) {
|
|
33
|
+
return state.kind === 'fixed' ? state.at : wallClockMs + state.offsetMs;
|
|
34
|
+
}
|
|
35
|
+
export function serializeError(e) {
|
|
36
|
+
if (e instanceof QuadError) {
|
|
37
|
+
return e.details === undefined
|
|
38
|
+
? { code: e.code, message: e.message }
|
|
39
|
+
: { code: e.code, message: e.message, details: e.details };
|
|
40
|
+
}
|
|
41
|
+
return { code: 'INTERNAL', message: e instanceof Error ? e.message : String(e) };
|
|
42
|
+
}
|
|
43
|
+
export function deserializeError(e) {
|
|
44
|
+
return new QuadError(e.code, e.message, e.details);
|
|
45
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import 'fake-indexeddb/auto';
|
|
2
|
+
import type { Dataset, Principal } from '@quad-education/canonical';
|
|
3
|
+
import { type PersonaKey } from '@quad-education/fictional-school';
|
|
4
|
+
import type { AppSchema } from '@quad-education/schema';
|
|
5
|
+
import type { AppConfig, CurrentApp, JsonValue, QuadSdk } from '../contract/types.ts';
|
|
6
|
+
import { Engine } from '../engine/engine.ts';
|
|
7
|
+
import { type Job, type RunResult } from '../jobs/define.ts';
|
|
8
|
+
export type TestPlatform = {
|
|
9
|
+
readonly engine: Engine;
|
|
10
|
+
readonly appId: string;
|
|
11
|
+
readonly dataset: Dataset;
|
|
12
|
+
/** An SDK for a persona (e.g. 'parent-of-siblings') or any principal. */
|
|
13
|
+
as(who: PersonaKey | Principal): QuadSdk;
|
|
14
|
+
/** An SDK acting as the system principal, as jobs run. */
|
|
15
|
+
system(): QuadSdk;
|
|
16
|
+
setClock(iso: string | null): Promise<void>;
|
|
17
|
+
close(): void;
|
|
18
|
+
};
|
|
19
|
+
/** A fresh in-memory platform with your app installed. */
|
|
20
|
+
export declare function createTestPlatform(app: {
|
|
21
|
+
manifest: unknown;
|
|
22
|
+
schema: AppSchema;
|
|
23
|
+
now?: string;
|
|
24
|
+
}): Promise<TestPlatform>;
|
|
25
|
+
/** What one run changed. Records count creates and updates by entity. */
|
|
26
|
+
export type Effects = {
|
|
27
|
+
outbox: number;
|
|
28
|
+
tasksCreated: number;
|
|
29
|
+
tasksChanged: number;
|
|
30
|
+
schedulesCreated: number;
|
|
31
|
+
schedulesChanged: number;
|
|
32
|
+
audit: number;
|
|
33
|
+
records: Record<string, {
|
|
34
|
+
created: number;
|
|
35
|
+
updated: number;
|
|
36
|
+
deleted: number;
|
|
37
|
+
}>;
|
|
38
|
+
};
|
|
39
|
+
/** True if a run changed anything at all. */
|
|
40
|
+
export declare function hasEffects(e: Effects): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Runs a job twice with the same runId, as at-least-once delivery may (D20), and reports
|
|
43
|
+
* what each run changed. A safe job's second run has no effects:
|
|
44
|
+
*
|
|
45
|
+
* const { first, second } = await runJobTwice(dailySummary, { app, setup })
|
|
46
|
+
* expect(hasEffects(first)).toBe(true)
|
|
47
|
+
* expect(second).toEqual(NO_EFFECTS)
|
|
48
|
+
*/
|
|
49
|
+
export declare function runJobTwice<A extends AppConfig = CurrentApp>(job: Job<A>, options: {
|
|
50
|
+
app: {
|
|
51
|
+
manifest: unknown;
|
|
52
|
+
schema: AppSchema;
|
|
53
|
+
};
|
|
54
|
+
/** Demo clock for the run (defaults to scheduledFor). */
|
|
55
|
+
now?: string;
|
|
56
|
+
/**
|
|
57
|
+
* Who the run acts as (D7): the system principal (default, as for cron jobs), or the
|
|
58
|
+
* persona or principal who scheduled it.
|
|
59
|
+
*/
|
|
60
|
+
runAs?: PersonaKey | Principal;
|
|
61
|
+
scheduledFor?: string;
|
|
62
|
+
payload?: JsonValue;
|
|
63
|
+
runId?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Prepare data first, e.g. create records the job will summarise. It may return the
|
|
66
|
+
* payload to run with, when the payload depends on what it created.
|
|
67
|
+
*/
|
|
68
|
+
setup?: (platform: TestPlatform) => Promise<void | {
|
|
69
|
+
payload: JsonValue;
|
|
70
|
+
}>;
|
|
71
|
+
}): Promise<{
|
|
72
|
+
first: Effects;
|
|
73
|
+
second: Effects;
|
|
74
|
+
results: [RunResult, RunResult];
|
|
75
|
+
platform: TestPlatform;
|
|
76
|
+
}>;
|
|
77
|
+
/** What a safe second run should report. */
|
|
78
|
+
export declare const NO_EFFECTS: Effects;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// @quad-education/sdk/testing: a test kit for app code. It runs the in-browser engine in memory
|
|
2
|
+
// (fake IndexedDB) with the fictional school, so app tests need no browser or shell.
|
|
3
|
+
import 'fake-indexeddb/auto';
|
|
4
|
+
import { personasFor } from '@quad-education/fictional-school';
|
|
5
|
+
import fictionalSchool from '@quad-education/fictional-school/dataset' with { type: 'json' };
|
|
6
|
+
import { connectInProcess } from "../engine/in-process.js";
|
|
7
|
+
import { Engine } from "../engine/engine.js";
|
|
8
|
+
import { executeRun } from "../jobs/define.js";
|
|
9
|
+
let instance = 0;
|
|
10
|
+
/** A fresh in-memory platform with your app installed. */
|
|
11
|
+
export async function createTestPlatform(app) {
|
|
12
|
+
const dataset = fictionalSchool;
|
|
13
|
+
const engine = await Engine.create({ dataset, indexedDB, dbName: `quad-test-${++instance}` });
|
|
14
|
+
if (app.now)
|
|
15
|
+
await engine.setClock(app.now);
|
|
16
|
+
await engine.installApp(app);
|
|
17
|
+
const appId = app.manifest.id;
|
|
18
|
+
const personas = personasFor(dataset);
|
|
19
|
+
return {
|
|
20
|
+
engine,
|
|
21
|
+
appId,
|
|
22
|
+
dataset,
|
|
23
|
+
as(who) {
|
|
24
|
+
if (typeof who !== 'string')
|
|
25
|
+
return connectInProcess(engine, appId, who);
|
|
26
|
+
const p = personas.find((x) => x.key === who);
|
|
27
|
+
if (!p)
|
|
28
|
+
throw new Error(`unknown persona '${who}'`);
|
|
29
|
+
return connectInProcess(engine, appId, { kind: 'user', role: p.role, personId: p.personId });
|
|
30
|
+
},
|
|
31
|
+
system: () => connectInProcess(engine, appId, { kind: 'system', appId }),
|
|
32
|
+
setClock: (iso) => engine.setClock(iso),
|
|
33
|
+
close: () => engine.close(),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function resolvePrincipal(platform, who) {
|
|
37
|
+
if (who === undefined)
|
|
38
|
+
return { kind: 'system', appId: platform.appId };
|
|
39
|
+
if (typeof who !== 'string')
|
|
40
|
+
return who;
|
|
41
|
+
const p = personasFor(platform.dataset).find((x) => x.key === who);
|
|
42
|
+
if (!p)
|
|
43
|
+
throw new Error(`unknown persona '${who}'`);
|
|
44
|
+
return { kind: 'user', role: p.role, personId: p.personId };
|
|
45
|
+
}
|
|
46
|
+
function diff(before, after) {
|
|
47
|
+
const records = {};
|
|
48
|
+
for (const entity of new Set([...Object.keys(before.records), ...Object.keys(after.records)])) {
|
|
49
|
+
const a = before.records[entity] ?? {};
|
|
50
|
+
const b = after.records[entity] ?? {};
|
|
51
|
+
const created = Object.keys(b).filter((id) => !(id in a)).length;
|
|
52
|
+
const deleted = Object.keys(a).filter((id) => !(id in b)).length;
|
|
53
|
+
const updated = Object.keys(b).filter((id) => id in a && a[id] !== b[id]).length;
|
|
54
|
+
if (created || updated || deleted)
|
|
55
|
+
records[entity] = { created, updated, deleted };
|
|
56
|
+
}
|
|
57
|
+
const changed = (x, y) => ({
|
|
58
|
+
created: Object.keys(y).filter((id) => !(id in x)).length,
|
|
59
|
+
changed: Object.keys(y).filter((id) => id in x && x[id] !== y[id]).length,
|
|
60
|
+
});
|
|
61
|
+
const tasks = changed(before.tasks, after.tasks);
|
|
62
|
+
const schedules = changed(before.schedules, after.schedules);
|
|
63
|
+
return {
|
|
64
|
+
outbox: after.outbox - before.outbox,
|
|
65
|
+
tasksCreated: tasks.created,
|
|
66
|
+
tasksChanged: tasks.changed,
|
|
67
|
+
schedulesCreated: schedules.created,
|
|
68
|
+
schedulesChanged: schedules.changed,
|
|
69
|
+
audit: after.audit - before.audit,
|
|
70
|
+
records,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** True if a run changed anything at all. */
|
|
74
|
+
export function hasEffects(e) {
|
|
75
|
+
return (e.outbox + e.tasksCreated + e.tasksChanged + e.schedulesCreated + e.schedulesChanged + e.audit >
|
|
76
|
+
0 || Object.keys(e.records).length > 0);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Runs a job twice with the same runId, as at-least-once delivery may (D20), and reports
|
|
80
|
+
* what each run changed. A safe job's second run has no effects:
|
|
81
|
+
*
|
|
82
|
+
* const { first, second } = await runJobTwice(dailySummary, { app, setup })
|
|
83
|
+
* expect(hasEffects(first)).toBe(true)
|
|
84
|
+
* expect(second).toEqual(NO_EFFECTS)
|
|
85
|
+
*/
|
|
86
|
+
export async function runJobTwice(job, options) {
|
|
87
|
+
const scheduledFor = options.scheduledFor ?? '2026-03-09T20:00:00.000Z';
|
|
88
|
+
const platform = await createTestPlatform({ ...options.app, now: options.now ?? scheduledFor });
|
|
89
|
+
const prepared = await options.setup?.(platform);
|
|
90
|
+
const run = {
|
|
91
|
+
runId: options.runId ?? `test:${job.name}:${scheduledFor}`,
|
|
92
|
+
jobName: job.name,
|
|
93
|
+
scheduledFor,
|
|
94
|
+
payload: (prepared ? prepared.payload : options.payload) ?? null,
|
|
95
|
+
attempt: 1,
|
|
96
|
+
runAs: resolvePrincipal(platform, options.runAs),
|
|
97
|
+
};
|
|
98
|
+
const sdk = (options.runAs === undefined
|
|
99
|
+
? platform.system()
|
|
100
|
+
: platform.as(options.runAs));
|
|
101
|
+
const jobs = [job];
|
|
102
|
+
const s0 = await platform.engine.effectsSnapshot(platform.appId);
|
|
103
|
+
const r1 = await executeRun(jobs, run, sdk);
|
|
104
|
+
const s1 = await platform.engine.effectsSnapshot(platform.appId);
|
|
105
|
+
const r2 = await executeRun(jobs, { ...run, attempt: 2 }, sdk);
|
|
106
|
+
const s2 = await platform.engine.effectsSnapshot(platform.appId);
|
|
107
|
+
return { first: diff(s0, s1), second: diff(s1, s2), results: [r1, r2], platform };
|
|
108
|
+
}
|
|
109
|
+
/** What a safe second run should report. */
|
|
110
|
+
export const NO_EFFECTS = {
|
|
111
|
+
outbox: 0,
|
|
112
|
+
tasksCreated: 0,
|
|
113
|
+
tasksChanged: 0,
|
|
114
|
+
schedulesCreated: 0,
|
|
115
|
+
schedulesChanged: 0,
|
|
116
|
+
audit: 0,
|
|
117
|
+
records: {},
|
|
118
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quad-education/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "The @quad-education/sdk contract, its in-browser engine, transports and contract tests",
|
|
6
|
+
"license": "SEE LICENSE IN LICENSE.md",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/src/index.d.ts",
|
|
10
|
+
"default": "./dist/src/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./client": {
|
|
13
|
+
"types": "./dist/src/client/connect.d.ts",
|
|
14
|
+
"default": "./dist/src/client/connect.js"
|
|
15
|
+
},
|
|
16
|
+
"./engine": {
|
|
17
|
+
"types": "./dist/src/engine/index.d.ts",
|
|
18
|
+
"default": "./dist/src/engine/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./contract-tests": {
|
|
21
|
+
"types": "./dist/contract-tests/index.d.ts",
|
|
22
|
+
"default": "./dist/contract-tests/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./jobs": {
|
|
25
|
+
"types": "./dist/src/jobs/index.d.ts",
|
|
26
|
+
"default": "./dist/src/jobs/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./jobs-host": {
|
|
29
|
+
"types": "./dist/src/jobs/host.d.ts",
|
|
30
|
+
"default": "./dist/src/jobs/host.js"
|
|
31
|
+
},
|
|
32
|
+
"./jobs-worker": {
|
|
33
|
+
"types": "./dist/src/jobs/worker.d.ts",
|
|
34
|
+
"default": "./dist/src/jobs/worker.js"
|
|
35
|
+
},
|
|
36
|
+
"./testing": {
|
|
37
|
+
"types": "./dist/src/testing/index.d.ts",
|
|
38
|
+
"default": "./dist/src/testing/index.js"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"LICENSE.md"
|
|
44
|
+
],
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"fake-indexeddb": "^6.2.5",
|
|
50
|
+
"@quad-education/canonical": "^0.1.2",
|
|
51
|
+
"@quad-education/fictional-school": "^0.1.2",
|
|
52
|
+
"@quad-education/schema": "^0.1.2"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"vitest": "^5.0.3"
|
|
56
|
+
},
|
|
57
|
+
"peerDependenciesMeta": {
|
|
58
|
+
"vitest": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@microsoft/api-extractor": "^7.59.3",
|
|
64
|
+
"@types/node": "^24.19.1",
|
|
65
|
+
"typescript": "6.0.3",
|
|
66
|
+
"vitest": "^5.0.3"
|
|
67
|
+
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp ../../LICENSE.md .",
|
|
70
|
+
"typecheck": "tsc -p . && tsc -p tsconfig.core.json",
|
|
71
|
+
"api": "tsc -p tsconfig.api.json && api-extractor run --local",
|
|
72
|
+
"api:check": "tsc -p tsconfig.api.json && api-extractor run"
|
|
73
|
+
}
|
|
6
74
|
}
|