@niwa-labs/testing 0.0.0-stage → 0.0.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.
package/src/index.ts ADDED
@@ -0,0 +1,521 @@
1
+ /**
2
+ * Testing helpers for niwa: a real host, a real journal, a real signal.
3
+ *
4
+ * Effects are counted through files in the home, one line per hit, so a count survives the
5
+ * death of the process that wrote it. A gate blocks a stubbed action until the test opens it;
6
+ * that block is the point, so it has no deadline. Everything else has one.
7
+ */
8
+
9
+ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { mkdtemp, rm } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { dirname, join, resolve } from "node:path";
13
+ import net from "node:net";
14
+ import { setTimeout as sleep } from "node:timers/promises";
15
+ import type { z } from "zod";
16
+
17
+ import { action } from "@niwa-labs/core";
18
+ import type { Clock, Action, ActionContext, Effect, Recovery } from "@niwa-labs/core";
19
+ import { socketPath } from "@niwa-labs/client";
20
+
21
+ // What nearly every test needs besides the helpers below: a host to run, a client to speak with,
22
+ // and the helpers shared by the tests.
23
+ export { createNiwa } from "@niwa-labs/host";
24
+ export { connect } from "@niwa-labs/client";
25
+ export { live, loginWeb, opt, pick, webFetch } from "./helpers.ts";
26
+ export { COCKPIT_MODULE, plugin } from "./cli.ts";
27
+ export {
28
+ STATE_TYPE,
29
+ connectAsOwner,
30
+ invocationOf,
31
+ lastState,
32
+ ownerTokenOf,
33
+ runFinishes,
34
+ watch,
35
+ } from "./client.ts";
36
+ export type { InvocationStateData, WaitedRun } from "./client.ts";
37
+ export { claudePrompt, fakeSdkQuery } from "./harness-claude.ts";
38
+ export type { FakeCall } from "./harness-claude.ts";
39
+ export { ZCODE_FAKE } from "./harness-zcode.ts";
40
+ export * from "./messages.ts";
41
+ export * from "./niwa.ts";
42
+ export * from "./requests.ts";
43
+ export { unreadable, unsendable } from "./schema-reads.ts";
44
+ export * from "./sessions.ts";
45
+ export * from "./tasks.ts";
46
+ export * from "./web.ts";
47
+ export * from "./workflow.ts";
48
+
49
+ const READY_TIMEOUT_MS = 10_000; // How long `ready()` waits for the host to accept a connection.
50
+ const STOP_GRACE_MS = 5_000; // How long `stop()` gives SIGTERM before SIGKILL.
51
+ const POLL_INTERVAL_MS = 20; // The interval of every poll in this file.
52
+
53
+ /** The file a counter's hits are appended to, or a gate is opened by. */
54
+ function homeFile(home: string, dir: "counters" | "gates", name: string): string {
55
+ const what = dir === "counters" ? "counter name" : "gate name";
56
+ if (typeof name !== "string" || name.trim().length === 0) {
57
+ throw new TypeError(`${what} must be a non-empty string`);
58
+ }
59
+ if (/[/\\]/.test(name) || name === "." || name === "..") {
60
+ throw new TypeError(`${what} "${name}" must not contain a path separator`);
61
+ }
62
+ return join(home, dir, name);
63
+ }
64
+
65
+ /** Poll until the condition holds; the failure names what was waited for. */
66
+ async function pollUntil(
67
+ fn: () => boolean | Promise<boolean>,
68
+ deadline: number,
69
+ message: () => string,
70
+ ): Promise<void> {
71
+ for (;;) {
72
+ if (await fn()) return;
73
+ if (Date.now() >= deadline) throw new Error(message());
74
+ await sleep(POLL_INTERVAL_MS);
75
+ }
76
+ }
77
+
78
+ const TEMP_PREFIX = "niwa-test-"; // Every directory made here starts with it, then the pid of the run that made it.
79
+ const owned = new Set<string>(); // The directories this process made and has not removed yet.
80
+ let sweeping = false;
81
+
82
+ /** Whether a process is alive; a process of another user counts as alive. */
83
+ function alive(pid: number): boolean {
84
+ try {
85
+ process.kill(pid, 0);
86
+ return true;
87
+ } catch (error) {
88
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
89
+ }
90
+ }
91
+
92
+ function removeQuietly(path: string): void {
93
+ try {
94
+ rmSync(path, { recursive: true, force: true });
95
+ } catch {
96
+ // A directory that cannot be removed must not hide the failure of the test before it.
97
+ }
98
+ }
99
+
100
+ /** Remove the directories this process made and has not removed yet. */
101
+ export function sweepTempDirs(): void {
102
+ for (const path of owned) removeQuietly(path);
103
+ owned.clear();
104
+ }
105
+
106
+ /**
107
+ * The backstop for a directory a test did not remove (it failed, timed out or never reached its
108
+ * cleanup). This run's own directories go when the process exits or is interrupted, and when the
109
+ * test runner calls `sweepTempDirs` (`bun test` does not emit `exit`). The directories of runs
110
+ * whose process is gone (killed, so it could not sweep) go when the next run starts. A directory
111
+ * of a run that is still alive is never touched.
112
+ */
113
+ function startSweeping(): void {
114
+ if (sweeping) return;
115
+ sweeping = true;
116
+ for (const name of readdirSync(tmpdir())) {
117
+ const pid = new RegExp(`^${TEMP_PREFIX}(\\d+)-`).exec(name)?.[1];
118
+ if (pid !== undefined && !alive(Number(pid))) removeQuietly(join(tmpdir(), name));
119
+ }
120
+ process.on("exit", sweepTempDirs);
121
+ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]] as const) {
122
+ process.on(signal, () => {
123
+ sweepTempDirs();
124
+ process.exit(code);
125
+ });
126
+ }
127
+ }
128
+
129
+ /** A fresh, empty directory that is removed when the process ends, whatever became of the test. */
130
+ export async function tempDir(label: string): Promise<string> {
131
+ startSweeping();
132
+ const path = await mkdtemp(join(tmpdir(), `${TEMP_PREFIX}${String(process.pid)}-${label}-`));
133
+ owned.add(path);
134
+ return path;
135
+ }
136
+
137
+ /** `tempDir` for a test that cannot await. */
138
+ export function tempDirSync(label: string): string {
139
+ startSweeping();
140
+ const path = mkdtempSync(join(tmpdir(), `${TEMP_PREFIX}${String(process.pid)}-${label}-`));
141
+ owned.add(path);
142
+ return path;
143
+ }
144
+
145
+ /** A fresh, empty home: where the journal, the socket, the counters and the gates live. */
146
+ export async function tempHome(): Promise<{ path: string; cleanup(): Promise<void> }> {
147
+ const path = await tempDir("home");
148
+ return {
149
+ path,
150
+ // A failing cleanup must not hide the failure of the test before it.
151
+ cleanup: async (): Promise<void> => {
152
+ owned.delete(path);
153
+ await rm(path, { recursive: true, force: true }).catch(() => {});
154
+ },
155
+ };
156
+ }
157
+
158
+ /** A counter: how many times something happened, counted across processes. */
159
+ export interface Counter {
160
+ hit(): void;
161
+ count(): number;
162
+ }
163
+
164
+ /** A counter shared through the file system: one hit appends one line, atomically. */
165
+ export function counter(home: string, name: string): Counter {
166
+ const path = homeFile(home, "counters", name);
167
+ return {
168
+ hit(): void {
169
+ mkdirSync(dirname(path), { recursive: true });
170
+ appendFileSync(path, `${Date.now()}\n`);
171
+ },
172
+ count(): number {
173
+ const text = existsSync(path) ? readFileSync(path, "utf8") : "";
174
+ return text.split("\n").filter((line) => line.trim() !== "").length;
175
+ },
176
+ };
177
+ }
178
+
179
+ /**
180
+ * A gate: a point where an action waits until the test lets it through. The gate is a file:
181
+ * `open()` creates it, `wait()` returns once it exists. A gate that is never opened blocks the
182
+ * action forever — that is how a test parks a host inside a step.
183
+ */
184
+ export interface Gate {
185
+ open(): void;
186
+ isOpen(): boolean;
187
+ /** Resolves once the gate is open; with `timeoutMs` it rejects instead of waiting forever. */
188
+ wait(timeoutMs?: number): Promise<void>;
189
+ }
190
+
191
+ /** A gate shared through the file system. */
192
+ export function gate(home: string, name: string): Gate {
193
+ const path = homeFile(home, "gates", name);
194
+ return {
195
+ open(): void {
196
+ mkdirSync(dirname(path), { recursive: true });
197
+ writeFileSync(path, "");
198
+ },
199
+ isOpen(): boolean {
200
+ return existsSync(path);
201
+ },
202
+ async wait(timeoutMs?: number): Promise<void> {
203
+ await pollUntil(
204
+ () => existsSync(path),
205
+ timeoutMs === undefined ? Infinity : Date.now() + timeoutMs,
206
+ () => `the gate "${name}" was not opened within ${String(timeoutMs)} ms`,
207
+ );
208
+ },
209
+ };
210
+ }
211
+
212
+ /**
213
+ * The operation ids of the calls of one action, in the order they were made.
214
+ *
215
+ * They are appended to a file in the home, one per line, so they survive the death of the
216
+ * process that made them. A test reads them to tell one operation from another across a
217
+ * crash: the same operation id means the other side will dedupe the call.
218
+ */
219
+ export interface Operations {
220
+ hit(operationId: string): void;
221
+ /** The operation ids, in the order they were recorded. */
222
+ ids(): string[];
223
+ }
224
+
225
+ /** The operation ids of the calls of one action, shared through the file system. */
226
+ export function operations(home: string, name: string): Operations {
227
+ const path = homeFile(home, "counters", `operations-${name}`);
228
+ return {
229
+ hit(operationId: string): void {
230
+ mkdirSync(dirname(path), { recursive: true });
231
+ appendFileSync(path, `${operationId}\n`);
232
+ },
233
+ ids(): string[] {
234
+ const text = existsSync(path) ? readFileSync(path, "utf8") : "";
235
+ return text.split("\n").filter((line) => line.trim() !== "");
236
+ },
237
+ };
238
+ }
239
+
240
+ /**
241
+ * A stubbed action: it counts, it may wait on a gate, and it returns a fixed result.
242
+ *
243
+ * It may also record the operation id of every call, so a test can tell one operation from
244
+ * another across a crash: the ids are appended to a file, one per line, in the same order as
245
+ * the calls.
246
+ *
247
+ * The recovery contract is given by the test, like the gate: a stub that counts its calls is
248
+ * not safe to make again by itself, and one that stands for an effect that cannot be
249
+ * repeated says so.
250
+ */
251
+ export function stubAction<I, O, In = I>(
252
+ name: string,
253
+ opts: {
254
+ home: string;
255
+ input: z.ZodType<I, In>;
256
+ output: z.ZodType<O>;
257
+ recovery: Recovery;
258
+ /** What a call changes. Default: "write". */
259
+ effect?: Effect;
260
+ /** The name of the gate this action waits on before it returns. */
261
+ gate?: string;
262
+ /** Record the operation id of every call, under this name. */
263
+ operations?: string;
264
+ result: (input: I) => O;
265
+ },
266
+ ): Action<I, O, In> {
267
+ const { home, input, output, recovery, result } = opts;
268
+ const count = counter(home, name);
269
+ const ids = opts.operations === undefined ? undefined : operations(home, opts.operations);
270
+ return action<I, O, In>(name, {
271
+ description: `A stubbed action "${name}": it counts its calls and returns a fixed result.`,
272
+ input,
273
+ output,
274
+ recovery,
275
+ effect: opts.effect ?? "write",
276
+ async run(value: I, ctx: ActionContext): Promise<O> {
277
+ count.hit();
278
+ ids?.hit(ctx.operationId);
279
+ if (opts.gate !== undefined) await gate(home, opts.gate).wait();
280
+ return result(value);
281
+ },
282
+ });
283
+ }
284
+
285
+ /**
286
+ * A clock a test moves by hand.
287
+ *
288
+ * The clock starts at a moment the test names and only moves when the test says so. The work
289
+ * that was scheduled for a moment that the clock has passed runs then, in the order the moments
290
+ * come, and `advance` waits for it: a test can watch a week of work without waiting a week.
291
+ *
292
+ * The callbacks are run in time order, and one at a time: a callback that schedules more work
293
+ * for a later moment does not jump ahead of the work that was due before it.
294
+ */
295
+ export interface TestClock extends Clock {
296
+ /** The moment now, in milliseconds since the epoch. */
297
+ now(): number;
298
+ /**
299
+ * Move the clock forward by `ms`, and run the work that comes due.
300
+ *
301
+ * The callbacks that come due are awaited, so the work they did is done when `advance`
302
+ * returns. A callback that fails does not stop the others: the failure is reported, and the
303
+ * clock keeps moving.
304
+ */
305
+ advance(ms: number): Promise<void>;
306
+ /** The failures of the callbacks that were run, in the order they failed. */
307
+ failures(): Error[];
308
+ }
309
+
310
+ /** One scheduled piece of work: when it is due, and what it does. */
311
+ interface Scheduled {
312
+ readonly at: number;
313
+ readonly fn: () => void | Promise<void>;
314
+ cancelled: boolean;
315
+ }
316
+
317
+ /**
318
+ * A clock that only moves when the test says so.
319
+ *
320
+ * `start` is the moment it begins at, in milliseconds since the epoch; the default is the moment
321
+ * the clock was made.
322
+ */
323
+ export function testClock(start: number = Date.now()): TestClock {
324
+ let now = start;
325
+ let scheduled: Scheduled[] = [];
326
+ const failures: Error[] = [];
327
+ return {
328
+ now: (): number => now,
329
+ schedule: (at, fn): (() => void) => {
330
+ const entry: Scheduled = { at, fn, cancelled: false };
331
+ scheduled.push(entry);
332
+ return () => {
333
+ entry.cancelled = true;
334
+ };
335
+ },
336
+ async advance(ms: number): Promise<void> {
337
+ if (!Number.isFinite(ms) || ms < 0) {
338
+ throw new TypeError(`the clock advances by a non-negative number of milliseconds, got ${String(ms)}`);
339
+ }
340
+ const target = now + ms;
341
+ for (;;) {
342
+ // The nearest moment that is due, and not cancelled.
343
+ let next: Scheduled | undefined;
344
+ for (const entry of scheduled) {
345
+ if (entry.cancelled || entry.at > target) continue;
346
+ if (next === undefined || entry.at < next.at) next = entry;
347
+ }
348
+ if (next === undefined) break;
349
+ next.cancelled = true;
350
+ scheduled = scheduled.filter((entry) => entry !== next && !entry.cancelled);
351
+ // The clock stands at the moment of the work, so the work sees the time it was due at.
352
+ now = Math.max(now, next.at);
353
+ try {
354
+ await next.fn();
355
+ } catch (error) {
356
+ failures.push(error instanceof Error ? error : new Error(String(error)));
357
+ }
358
+ }
359
+ now = target;
360
+ },
361
+ failures: (): Error[] => [...failures],
362
+ };
363
+ }
364
+
365
+ /** Wait until a condition holds; the message says what was waited for. */
366
+ export async function eventually(
367
+ fn: () => boolean | Promise<boolean>,
368
+ timeoutMs = 10_000,
369
+ message?: string,
370
+ ): Promise<void> {
371
+ await pollUntil(
372
+ fn,
373
+ Date.now() + timeoutMs,
374
+ () => message ?? `the condition was not met within ${String(timeoutMs)} ms`,
375
+ );
376
+ }
377
+
378
+ /** A host process under test. */
379
+ export interface HostProcess {
380
+ readonly pid: number;
381
+ /** Resolves when the host accepts a connection on its socket. */
382
+ ready(): Promise<void>;
383
+ /** Crash the host: SIGKILL, no clean shutdown. */
384
+ kill(): Promise<void>;
385
+ /** Stop the host: SIGTERM, then SIGKILL if it does not exit. */
386
+ stop(): Promise<void>;
387
+ output(): string;
388
+ }
389
+
390
+ /** Host children still running. A test that times out skips its `finally`, so they are also
391
+ * killed when the runner exits. */
392
+ const liveHosts = new Set<ReturnType<typeof Bun.spawn>>();
393
+ process.on("exit", () => {
394
+ for (const child of liveHosts) child.kill("SIGKILL");
395
+ });
396
+
397
+ /**
398
+ * Spawn a host program: `bun <script> <home> [args...]`, with the home as its argument. The
399
+ * script is an absolute path (a test names the program that sits next to it); the child runs in
400
+ * the directory of the script. Its output is collected from the start: a host that died during
401
+ * startup says why only in what it printed.
402
+ */
403
+ export function spawnHost(script: string, home: string, args: string[] = []): HostProcess {
404
+ const path = resolve(script);
405
+ const cwd = dirname(path);
406
+ const child = Bun.spawn([process.execPath, path, home, ...args], {
407
+ cwd,
408
+ stdout: "pipe",
409
+ stderr: "pipe",
410
+ env: process.env,
411
+ });
412
+
413
+ liveHosts.add(child);
414
+ void child.exited.then(() => liveHosts.delete(child));
415
+
416
+ const chunks: string[] = [];
417
+ void collect(chunks, child.stdout);
418
+ void collect(chunks, child.stderr);
419
+
420
+ let gone = false;
421
+ void child.exited.then(() => {
422
+ gone = true;
423
+ });
424
+
425
+ const output = (): string => chunks.join("");
426
+
427
+ /** Wait until the socket accepts a connection: the host deletes a stale socket before it
428
+ * listens, so the file can exist while nobody answers. */
429
+ const waitForSocket = (): Promise<void> =>
430
+ pollUntil(
431
+ async () => {
432
+ if (await connectOnce(socketPath(home))) return true;
433
+ if (gone) {
434
+ throw new Error(`the host process exited before it was ready.\n--- output ---\n${output()}`);
435
+ }
436
+ return false;
437
+ },
438
+ Date.now() + READY_TIMEOUT_MS,
439
+ () =>
440
+ `the host did not accept a connection within ${String(READY_TIMEOUT_MS)} ms.\n` +
441
+ `--- output ---\n${output()}`,
442
+ );
443
+
444
+ let readyPromise: Promise<void> | undefined;
445
+ const ready = (): Promise<void> => {
446
+ readyPromise ??= waitForSocket();
447
+ return readyPromise;
448
+ };
449
+
450
+ return {
451
+ pid: child.pid,
452
+ ready,
453
+ async kill(): Promise<void> {
454
+ if (!gone) child.kill("SIGKILL");
455
+ await child.exited;
456
+ },
457
+ async stop(): Promise<void> {
458
+ if (gone) {
459
+ await child.exited;
460
+ return;
461
+ }
462
+ child.kill("SIGTERM");
463
+ // A host that ignores SIGTERM must not hang the test.
464
+ const exited = await Promise.race([
465
+ child.exited.then(() => true),
466
+ sleep(STOP_GRACE_MS).then(() => false),
467
+ ]);
468
+ if (!exited) child.kill("SIGKILL");
469
+ await child.exited;
470
+ },
471
+ output,
472
+ };
473
+ }
474
+
475
+ /**
476
+ * Append the text of a stream to the shared output. Each stream has its own decoder: a
477
+ * multibyte character split across two chunks must survive, and two streams must not share
478
+ * the state of a split character.
479
+ */
480
+ async function collect(chunks: string[], stream: ReadableStream<Uint8Array> | null): Promise<void> {
481
+ if (stream === null) return;
482
+ const decoder = new TextDecoder();
483
+ try {
484
+ for await (const chunk of stream) chunks.push(decoder.decode(chunk, { stream: true }));
485
+ const tail = decoder.decode();
486
+ if (tail) chunks.push(tail);
487
+ } catch {
488
+ // The stream was closed under us (the process died); what was read is what there is.
489
+ }
490
+ }
491
+
492
+ /** One connection attempt to a unix socket, with a deadline: a refused or silent socket is false. */
493
+ function connectOnce(path: string): Promise<boolean> {
494
+ return new Promise<boolean>((resolveAttempt) => {
495
+ const socket = net.connect({ path });
496
+ socket.setNoDelay(true);
497
+ const timer = setTimeout(() => {
498
+ socket.destroy();
499
+ resolveAttempt(false);
500
+ }, 1_000);
501
+ timer.unref?.();
502
+
503
+ socket.once("connect", () => {
504
+ clearTimeout(timer);
505
+ // Greet the host the way a client does, then leave: this proves the host is serving.
506
+ try {
507
+ socket.write(`${JSON.stringify({ id: 1, op: "hello", client: "niwa-testing" })}\n`);
508
+ } catch {
509
+ // The host may have closed the connection already; the greeting was best-effort.
510
+ }
511
+ socket.end();
512
+ resolveAttempt(true);
513
+ });
514
+
515
+ socket.once("error", () => {
516
+ clearTimeout(timer);
517
+ socket.destroy();
518
+ resolveAttempt(false);
519
+ });
520
+ });
521
+ }
@@ -0,0 +1,25 @@
1
+ // What the tests of the messages package need besides the shared helpers: the factory of the
2
+ // sessions module, which a plugin may reach only through its records, and the harness model a fake
3
+ // control side is written against.
4
+
5
+ export { sessions } from "@niwa-labs/sessions";
6
+ export {
7
+ ToolCallRecordSchema,
8
+ ToolResultRecordSchema,
9
+ harnessId,
10
+ harnessKind,
11
+ machineId,
12
+ manifestVersion,
13
+ sessionId,
14
+ } from "@niwa-labs/harness";
15
+ export type {
16
+ AskAnswer,
17
+ AskOptions,
18
+ DeliveryReceipt,
19
+ Harness,
20
+ LifeEvent,
21
+ SessionControl,
22
+ SessionId,
23
+ SessionState,
24
+ StartOptions,
25
+ } from "@niwa-labs/harness";
package/src/niwa.ts ADDED
@@ -0,0 +1,7 @@
1
+ // What the tests that compose a whole niwa need: the base stack of plugins over a fake harness.
2
+
3
+ export { FAKE_HARNESS, FakeControl, fakeHarness } from "./fake-harness.ts";
4
+ export type { FakeHarness, FakeHarnessOptions } from "./fake-harness.ts";
5
+ export { baseStack } from "./stack.ts";
6
+ export type { BaseStack, BaseStackOptions } from "./stack.ts";
7
+ export { NO_ADVISOR } from "./harness-claude.ts";
package/src/preload.ts ADDED
@@ -0,0 +1,7 @@
1
+ // `bun test` does not emit `exit`, so the temporary directories a test left are removed here, after each file.
2
+
3
+ import { afterAll } from "bun:test";
4
+
5
+ import { sweepTempDirs } from "./index.ts";
6
+
7
+ afterAll(sweepTempDirs);
@@ -0,0 +1,6 @@
1
+ // What the tests of the requests package reach besides the helpers of this package: the error a
2
+ // client call fails with, and the types of the host and of the api a client speaks through.
3
+
4
+ export { HostError } from "@niwa-labs/client";
5
+ export type { NiwaApi } from "@niwa-labs/client";
6
+ export type { Host } from "@niwa-labs/host";
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Whether a schema that only reads a value can read everything another schema allows to be written.
3
+ *
4
+ * A client module cannot import the schemas of the actions it calls, so it keeps a narrower copy of them. This tells a
5
+ * test where the copy has drifted: a field the real output may lack, a type it changed, a value its enum gained.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ type Json = {
11
+ type?: string | string[];
12
+ properties?: Record<string, Json>;
13
+ required?: string[];
14
+ items?: Json;
15
+ enum?: unknown[];
16
+ const?: unknown;
17
+ anyOf?: Json[];
18
+ oneOf?: Json[];
19
+ };
20
+
21
+ const variantsOf = (schema: Json): Json[] | undefined => schema.anyOf ?? schema.oneOf;
22
+
23
+ const typesOf = (schema: Json): string[] | undefined => (schema.type === undefined ? undefined : Array.isArray(schema.type) ? schema.type : [schema.type]);
24
+
25
+ /** The reasons `reader` cannot read what `writer` produces, at the path they were found; none when it can. */
26
+ function problems(reader: Json, writer: Json, path: string, ofVariant = false): string[] {
27
+ const written = variantsOf(writer);
28
+ if (written !== undefined) {
29
+ // A field one variant lacks is read as absent there; it must still be a field of some variant.
30
+ const named = new Set(written.flatMap((variant) => Object.keys(variant.properties ?? {})));
31
+ const lost = Object.keys(reader.properties ?? {})
32
+ .filter((name) => !named.has(name) && written.every((variant) => variant.properties !== undefined))
33
+ .map((name) => `${path}.${name}: no variant of the writer has such a field`);
34
+ return [...lost, ...written.flatMap((variant, index) => problems(reader, variant, `${path}|${String(index)}`, true))];
35
+ }
36
+ const read = variantsOf(reader);
37
+ if (read !== undefined) {
38
+ const attempts = read.map((variant) => problems(variant, writer, path, ofVariant));
39
+ return attempts.some((one) => one.length === 0) ? [] : [`${path}: no variant of the reader takes it`, ...attempts.flat()];
40
+ }
41
+ if (Object.keys(reader).length === 0) return [];
42
+ const known = reader.enum ?? (reader.const === undefined ? undefined : [reader.const]);
43
+ const values = writer.enum ?? (writer.const === undefined ? undefined : [writer.const]);
44
+ if (known !== undefined) {
45
+ if (values === undefined) return [`${path}: the writer allows values the reader does not name`];
46
+ const missing = values.filter((value) => !known.includes(value));
47
+ return missing.length === 0 ? [] : [`${path}: the values ${JSON.stringify(missing)} are not read`];
48
+ }
49
+ const readTypes = typesOf(reader);
50
+ const writeTypes = typesOf(writer);
51
+ if (readTypes !== undefined) {
52
+ if (writeTypes === undefined) return [`${path}: the writer allows any value`];
53
+ const fits = (type: string): boolean => readTypes.includes(type) || (type === "integer" && readTypes.includes("number"));
54
+ const wrong = writeTypes.filter((type) => !fits(type));
55
+ if (wrong.length > 0) return [`${path}: the type ${wrong.join("|")} is not read as ${readTypes.join("|")}`];
56
+ }
57
+ const found: string[] = [];
58
+ if (reader.properties !== undefined) {
59
+ for (const [name, property] of Object.entries(reader.properties)) {
60
+ const there = writer.properties?.[name];
61
+ if (there === undefined) {
62
+ // In a variant, an optional field the variant lacks is read as absent; the union as a whole was checked for it.
63
+ if (ofVariant && !(reader.required ?? []).includes(name)) continue;
64
+ found.push(`${path}.${name}: the writer has no such field`);
65
+ continue;
66
+ }
67
+ if ((reader.required ?? []).includes(name) && !(writer.required ?? []).includes(name)) found.push(`${path}.${name}: the reader needs it, the writer may leave it out`);
68
+ found.push(...problems(property, there, `${path}.${name}`));
69
+ }
70
+ }
71
+ if (reader.items !== undefined && writer.items !== undefined) found.push(...problems(reader.items, writer.items, `${path}[]`));
72
+ return found;
73
+ }
74
+
75
+ const jsonOf = (schema: z.ZodType): Json => z.toJSONSchema(schema, { io: "output", unrepresentable: "any" }) as Json;
76
+
77
+ /** The reasons `reader` cannot read the output of `writer`; empty when it reads all of it. */
78
+ export function unreadable(reader: z.ZodType, writer: z.ZodType): string[] {
79
+ return problems(jsonOf(reader), jsonOf(writer), "$");
80
+ }
81
+
82
+ /**
83
+ * The reasons the input a client module builds is not one the real action takes: a field the action does not have, or one it
84
+ * needs that the module never sends. Only the fields are compared, one level deep.
85
+ */
86
+ export function unsendable(sends: z.ZodType, real: z.ZodType): string[] {
87
+ const mine = z.toJSONSchema(sends, { io: "input", unrepresentable: "any" }) as Json;
88
+ const theirs = z.toJSONSchema(real, { io: "input", unrepresentable: "any" }) as Json;
89
+ const found = Object.keys(mine.properties ?? {})
90
+ .filter((name) => theirs.properties?.[name] === undefined)
91
+ .map((name) => `$.${name}: the action takes no such field`);
92
+ for (const name of theirs.required ?? []) if (mine.properties?.[name] === undefined) found.push(`$.${name}: the action needs it and the module never sends it`);
93
+ return found;
94
+ }