@ultimat3/testing 30.7.0 → 30.8.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.
@@ -1,6 +1,7 @@
1
1
  // `defineExercise(…, { setup })`, run: the app's hook inside the pass's sealed room, before the
2
2
  // first row is seeded, disposed before the room restores the network. What it installs — a
3
3
  // `mockFetch` route, a `cassette()` — answers a vendor call; `allowHost` would send one for real.
4
+ // Several hooks (one per feature group) run in order and are undone in reverse.
4
5
 
5
6
  import { renderCauseValue, UltimateError } from '@ultimat3/core';
6
7
  import type { ExerciseRoom } from './exercise-report';
@@ -35,30 +36,46 @@ async function release(handle: unknown): Promise<void> {
35
36
  }
36
37
 
37
38
  /**
38
- * `room` with `setup` run inside it. Its dispose releases what setup returned FIRST — a cassette's
39
- * own check reads the routes the pass used — then the room. A setup that throws, or lets a host
40
- * through, disposes both before the pass refuses.
39
+ * Every handle released, last first, and then the room — each whatever the one before it threw;
40
+ * the first throw is what the caller sees, once nothing is left installed.
41
+ */
42
+ async function releaseAll(handles: readonly unknown[], room: ExerciseRoom): Promise<void> {
43
+ let failed = false;
44
+ let first: unknown;
45
+ for (const handle of [...handles].reverse()) {
46
+ try {
47
+ await release(handle);
48
+ } catch (error) {
49
+ if (!failed) first = error;
50
+ failed = true;
51
+ }
52
+ }
53
+ await room[Symbol.asyncDispose]();
54
+ if (failed) throw first;
55
+ }
56
+
57
+ /**
58
+ * `room` with each setup run inside it, in order. Its dispose releases what they returned FIRST,
59
+ * in reverse — a cassette's own check reads the routes the pass used — then the room. A setup that
60
+ * throws disposes those that already ran and the room; one that lets a host through, all of them.
41
61
  */
42
62
  export async function withExerciseSetup(
43
63
  room: ExerciseRoom,
44
- setup: ExerciseSetup | undefined,
64
+ setup: ExerciseSetup | readonly ExerciseSetup[] | undefined,
45
65
  ): Promise<ExerciseRoom> {
46
- if (setup === undefined) return room;
66
+ const setups = setup === undefined ? [] : typeof setup === 'function' ? [setup] : setup;
67
+ if (setups.length === 0) return room;
47
68
  const before = new Set(captureNetwork().allowed);
48
- let handle: unknown;
49
- try {
50
- handle = await setup();
51
- } catch (error) {
52
- await room[Symbol.asyncDispose]();
53
- throw error;
54
- }
55
- const dispose = async (): Promise<void> => {
69
+ const handles: unknown[] = [];
70
+ for (const one of setups) {
56
71
  try {
57
- await release(handle);
58
- } finally {
59
- await room[Symbol.asyncDispose]();
72
+ handles.push(await one());
73
+ } catch (error) {
74
+ await releaseAll(handles, room);
75
+ throw error;
60
76
  }
61
- };
77
+ }
78
+ const dispose = (): Promise<void> => releaseAll(handles, room);
62
79
  const opened = captureNetwork().allowed.filter((host) => !before.has(host));
63
80
  if (opened.length > 0) {
64
81
  await dispose();
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Actor } from '@ultimat3/core';
7
7
  import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
8
+ import type { ExerciseRequestOption } from '@ultimat3/http';
8
9
  import type { AnyJobHandle, JobExecution } from '@ultimat3/jobs';
9
10
  import { registeredJobs } from '@ultimat3/jobs';
10
11
  import type { Policy } from '@ultimat3/policy';
@@ -97,7 +98,15 @@ const jobSubject = (handle: AnyJobHandle): Subject => ({
97
98
  },
98
99
  });
99
100
 
100
- export async function subjectsOf(): Promise<readonly Subject[]> {
101
+ /** The `request` an action's or a query's entry declares, by kind: a job's call has none. */
102
+ export type RequestOf = (
103
+ kind: 'action' | 'query',
104
+ name: string,
105
+ ) => ExerciseRequestOption | undefined;
106
+
107
+ export async function subjectsOf(
108
+ requestOf: RequestOf = () => undefined,
109
+ ): Promise<readonly Subject[]> {
101
110
  // On demand, as every fixture here loads them: the barrel stays off `action` and `query`.
102
111
  const { invoke, listActions } = await import('@ultimat3/action');
103
112
  const { listQueries, runQuery } = await import('@ultimat3/query');
@@ -110,8 +119,11 @@ export async function subjectsOf(): Promise<readonly Subject[]> {
110
119
  policy: target.policy,
111
120
  permissions: target.describe().permissions,
112
121
  call: async (input, actor) => ({
113
- output: await withExerciseRequest(target.name, actor, () =>
114
- invoke(target, input, { surface: 'http' }),
122
+ output: await withExerciseRequest(
123
+ target.name,
124
+ actor,
125
+ () => invoke(target, input, { surface: 'http' }),
126
+ requestOf('action', target.name),
115
127
  ),
116
128
  }),
117
129
  }),
@@ -124,8 +136,11 @@ export async function subjectsOf(): Promise<readonly Subject[]> {
124
136
  policy: target.policy,
125
137
  permissions: target.describe().permissions,
126
138
  call: async (input, actor) => ({
127
- output: await withExerciseRequest(target.name, actor, () =>
128
- runQuery(target, input, { surface: 'http' }),
139
+ output: await withExerciseRequest(
140
+ target.name,
141
+ actor,
142
+ () => runQuery(target, input, { surface: 'http' }),
143
+ requestOf('query', target.name),
129
144
  ),
130
145
  }),
131
146
  }),
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Actor } from '@ultimat3/core';
7
7
  import type { ExerciseOverrides } from './define-exercise';
8
+ import { overrideFor } from './define-exercise';
8
9
  import type { ActorRows, RoleGrants } from './exercise-actor';
9
10
  import { asSeededRow, chooseActor } from './exercise-actor';
10
11
  import type { Sampler } from './exercise-input';
@@ -44,7 +45,7 @@ export const seated = (actor: Actor | null, tenant: string, rows: ActorRows | un
44
45
  rows === undefined ? actor : asSeededRow(actor, tenant, rows);
45
46
 
46
47
  /** A primitive as a sized call needs it: its schema, its policy, and a job's seat. */
47
- type Callable = Pick<Subject, 'name' | 'input' | 'policy' | 'permissions' | 'seat'>;
48
+ type Callable = Pick<Subject, 'kind' | 'name' | 'input' | 'policy' | 'permissions' | 'seat'>;
48
49
 
49
50
  /** One call of `subject` in `tenant` of a sized graph: the control's actor and first input. */
50
51
  export async function sizedCall(
@@ -54,7 +55,7 @@ export async function sizedCall(
54
55
  at: { readonly graph: SeedGraph; readonly tenant: string; readonly self: boolean },
55
56
  ): Promise<{ readonly actor: Actor | null; readonly input: unknown } | undefined> {
56
57
  const { graph, tenant, self } = at;
57
- const override = options.overrides?.entries.get(subject.name);
58
+ const override = overrideFor(options.overrides, subject.kind, subject.name);
58
59
  const chosen = chooseActor(subject.policy, subject.permissions, options.roles, tenant, override);
59
60
  if (chosen.kind === 'refused') return undefined;
60
61
  const rows = actorRowsOf(options, graph);
@@ -93,10 +94,12 @@ const timed = (subject: ScaleSubject, spent: Map<string, number>): ScaleSubject
93
94
 
94
95
  /**
95
96
  * The scale sweep inside the room, the room closed, then the plan sweep — on the installed client
96
- * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read.
97
+ * only: with none, the pass ran on a driver that sends no SQL and there is no plan to read. Each
98
+ * proof is found under `label(record)`, the name its primitive ran under in the room.
97
99
  */
98
100
  export async function attachSweeps(
99
101
  records: readonly ExerciseRecord[],
102
+ label: (record: ExerciseRecord) => string,
100
103
  options: ScaleSweepOptions,
101
104
  ): Promise<Swept> {
102
105
  const spent = new Map<string, number>();
@@ -120,9 +123,9 @@ export async function attachSweeps(
120
123
  plans: Math.round(performance.now() - plansStarted),
121
124
  };
122
125
  const swept = records.map((record) => {
123
- const proof = plans.get(record.name);
124
- const sized = scale.get(record.name);
125
- const scaleMs = spent.get(record.name);
126
+ const proof = plans.get(label(record));
127
+ const sized = scale.get(label(record));
128
+ const scaleMs = spent.get(label(record));
126
129
  const proofMs = {
127
130
  ...record.proofMs,
128
131
  ...(scaleMs === undefined ? {} : { scale: Math.round(scaleMs) }),
package/src/exercise.ts CHANGED
@@ -5,30 +5,27 @@
5
5
  // Committed, never rolled back. Around that call the tenant proof runs: the pair's other tenant
6
6
  // calls with the first one's ids before and after it (`tenant-proof.ts`, plan 101, 40). A reached
7
7
  // job is then killed at every step boundary (`exercise-crash.ts`).
8
+ //
9
+ // Each record is its primitive's alone: an entry's input that throws is that primitive unreached,
10
+ // what the input sent is never the call's, and a name two kinds share has an entry per kind.
8
11
 
9
12
  import type { Actor, ExerciseAttempt, ExerciseVerdict } from '@ultimat3/core';
10
- import { isUltimateError, renderThrowable, runExercise } from '@ultimat3/core';
13
+ import { runExercise } from '@ultimat3/core';
11
14
  import { registeredJobs } from '@ultimat3/jobs';
12
15
  import type { ExerciseOverride, ExerciseOverrides } from './define-exercise';
13
- import { assertOverridesKnown, unknownDeclaration } from './define-exercise';
16
+ import { assertOverridesKnown, overrideFor, unknownDeclaration } from './define-exercise';
14
17
  import type { RoleGrants } from './exercise-actor';
15
18
  import { chooseActor } from './exercise-actor';
16
19
  import { seatActorUsers } from './exercise-actor-user';
17
20
  import { proveCrash } from './exercise-crash';
18
21
  import { defectDetail } from './exercise-defect';
19
- import { driftOverrideLine } from './exercise-drift-hint';
20
22
  import type { IdLookup, Sampler } from './exercise-input';
21
- import {
22
- bindIds,
23
- drawInput,
24
- idStem,
25
- loadSampler,
26
- namesActorEntity,
27
- seededIds,
28
- } from './exercise-input';
23
+ import { bindIds, drawInput, loadSampler, namesActorEntity, seededIds } from './exercise-input';
29
24
  import { ambientJobRows } from './exercise-job-run';
25
+ import { judged, labelFor } from './exercise-judge';
26
+ import { mergeObserved } from './exercise-observed';
30
27
  import type { OverrideInput } from './exercise-override-input';
31
- import { overrideInput } from './exercise-override-input';
28
+ import { inputThrew, overrideInput } from './exercise-override-input';
32
29
  import type {
33
30
  EffectPayload,
34
31
  ExerciseEffect,
@@ -37,7 +34,7 @@ import type {
37
34
  ExerciseRoom,
38
35
  Observed,
39
36
  } from './exercise-report';
40
- import { openExerciseRoom, overrideLine } from './exercise-report';
37
+ import { openExerciseRoom } from './exercise-report';
41
38
  import { withExerciseSetup } from './exercise-setup';
42
39
  import type { Subject } from './exercise-subjects';
43
40
  import { fixedTenant, seatIn, subjectsOf } from './exercise-subjects';
@@ -68,19 +65,11 @@ export interface ExercisePassOptions {
68
65
  readonly onPhases?: (ms: ExercisePhaseMs) => void;
69
66
  }
70
67
 
71
- const isOff = (overrides: ExerciseOverrides | undefined, name: string): boolean => {
72
- const override = overrides?.entries.get(name);
68
+ const isOff = (overrides: ExerciseOverrides | undefined, subject: Subject): boolean => {
69
+ const override = overrideFor(overrides, subject.kind, subject.name);
73
70
  return override !== undefined && 'off' in override;
74
71
  };
75
72
 
76
- const codeOf = (error: unknown): string | undefined => {
77
- if (isUltimateError(error)) return error.code;
78
- return typeof error === 'string' ? /^(X_[A-Z0-9_]+)/.exec(error)?.[1] : undefined;
79
- };
80
-
81
- const reasonOf = (error: unknown): string =>
82
- isUltimateError(error) ? error.cause : typeof error === 'string' ? error : renderThrowable(error);
83
-
84
73
  /**
85
74
  * Jobs the primitive queued, its own job excepted. Never run: a job's children are left queued as
86
75
  * an action's are (`exercise-job-run.ts`), so their statements are theirs, never this record's.
@@ -108,47 +97,11 @@ async function queuedPayloads(subject: Subject): Promise<readonly EffectPayload[
108
97
  }));
109
98
  }
110
99
 
111
- interface Run {
112
- readonly verdict: ExerciseVerdict;
113
- readonly answered: boolean;
114
- readonly lastError: unknown;
115
- readonly lastInput: unknown;
116
- }
117
-
118
- function judged(subject: Subject, run: Run, observed: Observed, sampler: Sampler) {
119
- const idFields = (input: unknown): readonly string[] =>
120
- typeof input === 'object' && input !== null
121
- ? Object.keys(input).filter((key) => idStem(key) !== undefined)
122
- : [];
123
- const unreached = (code: string | undefined, reason: string) => ({
124
- outcome: 'unreached' as const,
125
- ...(code === undefined ? {} : { code }),
126
- reason,
127
- override: overrideLine(subject.name, idFields(run.lastInput)),
128
- });
129
- if (observed.refusedHosts.length > 0) {
130
- // A call out is a refusal whatever the handler made of it: sealed, so never sent.
131
- const hosts = [...new Set(observed.refusedHosts)].join(', ');
132
- return unreached('X_TEST_NETWORK_SEALED', `called out to ${hosts}: sealed, never sent`);
133
- }
134
- if (run.verdict.kind === 'pass' && run.answered) return { outcome: 'reached' as const };
135
- if (run.verdict.kind === 'drift') {
136
- // The field no draw can fill, named: `...drawn` alone told the author nothing to write.
137
- const fields = idFields(run.lastInput);
138
- return {
139
- ...unreached('X_CONTRACT_DRIFT', 'its input schema refused every generated value'),
140
- override: driftOverrideLine(subject.name, subject.input, sampler, fields),
141
- };
142
- }
143
- if (run.verdict.kind === 'defect') {
144
- return unreached(codeOf(run.verdict.error) ?? 'X_CONTRACT_DEFECT', run.verdict.defect);
145
- }
146
- return unreached(codeOf(run.lastError), reasonOf(run.lastError));
147
- }
148
-
149
100
  /** Everything one primitive's calls share: who acts in each tenant, and how ids are bound. */
150
101
  interface Prepared {
151
102
  readonly subject: Subject;
103
+ /** The entry key and room label: `labelFor`'s. */
104
+ readonly key: string;
152
105
  readonly options: ExercisePassOptions;
153
106
  readonly tenant: string;
154
107
  readonly actor: Actor | null;
@@ -158,13 +111,21 @@ interface Prepared {
158
111
  readonly bindInput: OverrideInput | undefined;
159
112
  }
160
113
 
161
- /** A's positive control: 39's loop, as the pass has always run it. */
114
+ /** Thrown out of 39's loop by a bind that failed: the record is the entry's, never the loop's. */
115
+ class BindThrew {
116
+ constructor(readonly error: unknown) {}
117
+ }
118
+
119
+ /**
120
+ * A's positive control: 39's loop, as the pass has always run it. The room records each CALL
121
+ * alone: an override's input runs between calls, and what it sends is never this primitive's.
122
+ */
162
123
  async function control(
163
124
  run: Prepared,
164
125
  room: ExerciseRoom,
165
126
  sampler: Sampler,
166
127
  ): Promise<{ readonly record: ExerciseRecord; readonly output: unknown; readonly input: unknown }> {
167
- const { subject, actor, tenant, declaredRuns, lookups, bindInput } = run;
128
+ const { subject, key, actor, tenant, declaredRuns, lookups, bindInput } = run;
168
129
  const { kind, name } = subject;
169
130
  let binds = 0;
170
131
  await using jobs = await testJobs();
@@ -172,43 +133,66 @@ async function control(
172
133
  let lastError: unknown;
173
134
  let lastInput: unknown;
174
135
  let output: unknown;
175
- room.begin(name);
136
+ const segments: Observed[] = [];
176
137
  const started = performance.now();
177
- const verdict = await runExercise({
178
- name,
179
- runs: run.runs,
180
- stoppedLabel: 'stopped before the call answered',
181
- // The minimal draw on every run the pass adds; 39's seeded draw only on runs an override asks.
182
- draw: (at, n) => drawInput(sampler, subject.input, at, declaredRuns === undefined ? 0 : n),
183
- bind: async (drawn) => {
184
- const bound = bindIds(drawn, lookups[binds++ === 0 ? 0 : 1]);
185
- const given = bindInput === undefined ? bound : await bindInput(bound, actor);
186
- lastInput = seatIn(subject, given, tenant);
187
- return lastInput;
188
- },
189
- accepts: async (input) =>
190
- (await subject.input['~standard'].validate(input)).issues === undefined,
191
- attempt: async (input): Promise<ExerciseAttempt> => {
192
- try {
193
- const answer = await subject.call(input, actor, tenant, jobs);
194
- if ('failure' in answer) {
195
- lastError = answer.failure;
196
- return { ok: false, reached: true, error: answer.failure };
138
+ let verdict: ExerciseVerdict;
139
+ try {
140
+ verdict = await runExercise({
141
+ name,
142
+ runs: run.runs,
143
+ stoppedLabel: 'stopped before the call answered',
144
+ // The minimal draw on every run the pass adds; 39's seeded draw only on runs an override asks.
145
+ draw: (at, n) => drawInput(sampler, subject.input, at, declaredRuns === undefined ? 0 : n),
146
+ bind: async (drawn) => {
147
+ const bound = bindIds(drawn, lookups[binds++ === 0 ? 0 : 1]);
148
+ try {
149
+ const given = bindInput === undefined ? bound : await bindInput(bound, actor);
150
+ lastInput = seatIn(subject, given, tenant);
151
+ } catch (error) {
152
+ throw new BindThrew(error);
197
153
  }
198
- answered = true;
199
- output = answer.output;
200
- return { ok: true, reached: true };
201
- } catch (error) {
202
- lastError = error;
203
- return { ok: false, reached: false, error };
204
- }
205
- },
206
- statusOf: (await import('@ultimat3/http')).statusFor,
207
- });
154
+ return lastInput;
155
+ },
156
+ accepts: async (input) =>
157
+ (await subject.input['~standard'].validate(input)).issues === undefined,
158
+ attempt: async (input): Promise<ExerciseAttempt> => {
159
+ room.begin(key);
160
+ try {
161
+ const answer = await subject.call(input, actor, tenant, jobs);
162
+ if ('failure' in answer) {
163
+ lastError = answer.failure;
164
+ return { ok: false, reached: true, error: answer.failure };
165
+ }
166
+ answered = true;
167
+ output = answer.output;
168
+ return { ok: true, reached: true };
169
+ } catch (error) {
170
+ lastError = error;
171
+ return { ok: false, reached: false, error };
172
+ } finally {
173
+ segments.push(room.end());
174
+ }
175
+ },
176
+ statusOf: (await import('@ultimat3/http')).statusFor,
177
+ });
178
+ } catch (error) {
179
+ if (!(error instanceof BindThrew)) throw error;
180
+ const observed = mergeObserved(segments);
181
+ const record = {
182
+ kind,
183
+ name,
184
+ statements: observed.statements,
185
+ effects: observed.effects,
186
+ ms: Math.round(performance.now() - started),
187
+ ...inputThrew(name, key, error.error),
188
+ };
189
+ return { record, output, input: lastInput };
190
+ }
208
191
  const ms = Math.round(performance.now() - started);
209
- const observed = room.end();
192
+ const observed = mergeObserved(segments);
210
193
  const effects = [...observed.effects, ...(await enqueued(subject, jobs))];
211
- const verdictOf = judged(subject, { verdict, answered, lastError, lastInput }, observed, sampler);
194
+ const outcome = { verdict, answered, lastError, lastInput };
195
+ const verdictOf = judged(subject, key, outcome, observed, sampler);
212
196
  // A 5xx's cause, statement and fields: the code alone sent the author to reproduce it by hand.
213
197
  const defect =
214
198
  verdict.kind === 'defect' && verdictOf.outcome === 'unreached'
@@ -229,13 +213,14 @@ async function control(
229
213
  /** One B leg: B's actor, A's ids, a queue of its own. What it answered and every effect it had. */
230
214
  async function attack(
231
215
  subject: Subject,
216
+ key: string,
232
217
  input: unknown,
233
218
  actor: Actor | null,
234
219
  tenant: string,
235
220
  room: ExerciseRoom,
236
221
  ): Promise<LegAnswer> {
237
222
  await using jobs = await testJobs();
238
- room.begin(subject.name);
223
+ room.begin(key);
239
224
  let output: unknown;
240
225
  // A job's org is re-seated in B's: B cannot enqueue a payload naming A (refused at the enqueue,
241
226
  // which proves nothing), so the attack that matters is a job of B's carrying A's ids.
@@ -261,6 +246,7 @@ async function attack(
261
246
 
262
247
  async function exerciseOne(
263
248
  subject: Subject,
249
+ key: string,
264
250
  options: ExercisePassOptions,
265
251
  [tenant, other]: readonly [string, string],
266
252
  graph: SeedGraph,
@@ -268,7 +254,7 @@ async function exerciseOne(
268
254
  sampler: Sampler,
269
255
  ): Promise<ExerciseRecord> {
270
256
  const { kind, name } = subject;
271
- const override: ExerciseOverride | undefined = options.overrides?.entries.get(name);
257
+ const override: ExerciseOverride | undefined = overrideFor(options.overrides, kind, name);
272
258
  const none = { kind, name, statements: 0, effects: [], ms: 0 };
273
259
  if (override !== undefined && 'off' in override) {
274
260
  return { ...none, outcome: 'off', reason: override.off.trim() };
@@ -301,6 +287,7 @@ async function exerciseOne(
301
287
  ] as const;
302
288
  const run: Prepared = {
303
289
  subject,
290
+ key,
304
291
  options,
305
292
  tenant,
306
293
  actor,
@@ -311,7 +298,13 @@ async function exerciseOne(
311
298
  };
312
299
  // A's own first input, A's ids in it: B sends exactly what A legitimately would.
313
300
  const drawn = bindIds(drawInput(sampler, subject.input, 0, 0), lookups[0]);
314
- const given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
301
+ let given: unknown;
302
+ try {
303
+ given = bindInput === undefined ? drawn : await bindInput(drawn, actor);
304
+ } catch (error) {
305
+ const threw = inputThrew(name, key, error);
306
+ return { ...none, ...threw, tenant: { verdict: 'unproven', reason: threw.reason } };
307
+ }
315
308
  const seat = subject.seat?.(given, tenant);
316
309
  if (seat?.kind === 'fixed') {
317
310
  const fixed = fixedTenant(name, seat.declared);
@@ -332,7 +325,7 @@ async function exerciseOne(
332
325
  read: kind === 'query',
333
326
  sweep: kind === 'job',
334
327
  tenantless: seat?.kind === 'none',
335
- attack: () => attack(subject, input, intruder, other, room),
328
+ attack: () => attack(subject, key, input, intruder, other, room),
336
329
  control: async () => {
337
330
  const done = await control(run, room, sampler);
338
331
  reachedWith = done.input;
@@ -355,9 +348,14 @@ async function exerciseOne(
355
348
  export async function runExercisePass(
356
349
  options: ExercisePassOptions,
357
350
  ): Promise<readonly ExerciseRecord[]> {
358
- const subjects = await subjectsOf();
351
+ // Each call's request is its entry's, read by kind: an action's cookies are never its job twin's.
352
+ const subjects = await subjectsOf((kind, name) => {
353
+ const entry = overrideFor(options.overrides, kind, name);
354
+ return entry === undefined || 'off' in entry ? undefined : entry.request;
355
+ });
359
356
  const known = new Set(subjects.map((subject) => subject.name));
360
- assertOverridesKnown(options.overrides, known);
357
+ assertOverridesKnown(options.overrides, subjects);
358
+ const label = labelFor(subjects);
361
359
  if (options.only !== undefined && !known.has(options.only)) {
362
360
  throw unknownDeclaration([options.only], known, 'x exercise');
363
361
  }
@@ -367,7 +365,7 @@ export async function runExercisePass(
367
365
  const passSeed = options.seed ?? (crypto.getRandomValues(new Uint32Array(1))[0] as number);
368
366
  // The app's setup runs inside the seal, before the first row: its routes answer every call.
369
367
  const room = await withExerciseSetup(await openExerciseRoom(), options.overrides?.setup);
370
- const live = chosen.filter((subject) => !isOff(options.overrides, subject.name));
368
+ const live = chosen.filter((subject) => !isOff(options.overrides, subject));
371
369
  const records: ExerciseRecord[] = [];
372
370
  let graph: SeedGraph;
373
371
  const seedStarted = performance.now();
@@ -387,7 +385,8 @@ export async function runExercisePass(
387
385
  const index = live.indexOf(subject);
388
386
  const at = Math.max(0, index);
389
387
  const view = pairGraph(graph, at);
390
- records.push(await exerciseOne(subject, options, tenantPair(graph, at), view, room, sampler));
388
+ const pair = tenantPair(graph, at);
389
+ records.push(await exerciseOne(subject, label(subject), options, pair, view, room, sampler));
391
390
  }
392
391
  } catch (error) {
393
392
  await room[Symbol.asyncDispose]();
@@ -396,9 +395,12 @@ export async function runExercisePass(
396
395
  const seed = Math.round(primitivesStarted - seedStarted);
397
396
  const primitives = Math.round(performance.now() - primitivesStarted);
398
397
  // The sweeps: every reached primitive again at two sizes, then every statement planned.
399
- const reached = new Set(records.filter((r) => r.outcome === 'reached').map((r) => r.name));
400
- const swept = await attachSweeps(records, {
401
- subjects: chosen.filter((subject) => reached.has(subject.name)),
398
+ const reached = new Set(records.filter((r) => r.outcome === 'reached').map(label));
399
+ const swept = await attachSweeps(records, label, {
400
+ // Named by label: the sweeps key their proofs by name, and a shared name is two primitives.
401
+ subjects: chosen
402
+ .filter((subject) => reached.has(label(subject)))
403
+ .map((subject) => ({ ...subject, name: label(subject) })),
402
404
  entities: options.entities,
403
405
  // The sized graphs close their cycles as the pass's did: a refused deferred key stays null.
404
406
  writer: deferredMayStayNull(options.writer),
@@ -407,7 +409,7 @@ export async function runExercisePass(
407
409
  room,
408
410
  factories: options.overrides?.factories,
409
411
  setup: async (subject, sized, tenant, self) => {
410
- const full = chosen.find((one) => one.name === subject.name);
412
+ const full = chosen.find((one) => label(one) === subject.name);
411
413
  if (full === undefined) return undefined;
412
414
  const call = await sizedCall(full, options, sampler, { graph: sized, tenant, self });
413
415
  // Before the sweep's room opens: the sized tenant's actor is a user too.
@@ -4,9 +4,9 @@
4
4
  // edge. A structural seam keeps the direction honest and survives the bundler changing underneath.
5
5
 
6
6
  import { basename, join } from 'node:path';
7
- import { islandMountMissing, islandNotBuilt } from './errors';
8
7
  import { onFileBoundary } from './file-boundary';
9
8
  import { createIslandDocument, FakeElement, handlerFor, parseHtml } from './island-dom';
9
+ import { islandMountMissing, islandNotBuilt } from './island-errors';
10
10
  import { installGlobals } from './island-globals';
11
11
  import type { ResizeInput } from './island-observers';
12
12
  import { deliverResize } from './island-observers';
@@ -0,0 +1,82 @@
1
+ // The two refusals `mountIsland` gives before any island code runs: the file the test named was
2
+ // not built, or its chunk exports no `mount`. Codes registered with the rest in `errors.ts`.
3
+
4
+ import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
5
+
6
+ /** Neither path is controlled by the framework: both arrive from the test's own call. */
7
+ const ISLAND_PLACEHOLDER = '<the island path the cause names>';
8
+
9
+ /**
10
+ * The builder produced no chunk for the file the test named. Listing what it DID build is the
11
+ * whole value: a path relative to the test file instead of to the app root, a typo, and an island
12
+ * outside the discovery glob are one symptom and three different edits, and only the list tells
13
+ * them apart. An empty list is its own answer — the glob found nothing at all under this root.
14
+ */
15
+ export class IslandNotBuiltError extends UltimateError {
16
+ constructor(input: { file: string; root: string; built: readonly string[] }) {
17
+ const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
18
+ super({
19
+ code: 'X_TEST_ISLAND_NOT_BUILT',
20
+ cause:
21
+ input.built.length === 0
22
+ ? `no island was built under ${renderCauseValue(input.root)}, so ${renderCauseValue(input.file)} cannot be mounted`
23
+ : `${renderCauseValue(input.file)} is not in the bundle built from ${renderCauseValue(input.root)}; it built ${input.built.join(', ')}`,
24
+ fix:
25
+ input.built.length === 0
26
+ ? 'x g island <name> --at apps/web/site — then set root to the directory holding apps/'
27
+ : `mountIsland({ build, root, file: ${renderFixLiteral(input.built[0], ISLAND_PLACEHOLDER)} }) — the path is app-root-relative, not relative to the test, and ${file} is not one of them`,
28
+ });
29
+ }
30
+ }
31
+
32
+ export const islandNotBuilt = (
33
+ file: string,
34
+ root: string,
35
+ built: readonly string[],
36
+ ): UltimateError => new IslandNotBuiltError({ file, root, built });
37
+
38
+ /** A name that can be written as a JSX tag. `export default` and `export { x as 'a b' }` are both
39
+ * legal ES and neither can — a paste emitting one is a syntax error in the reader's own file. */
40
+ const JSX_NAME = /^[A-Za-z_$][\w$]*$/;
41
+
42
+ /**
43
+ * The export the paste renders. A component first — an initial capital that is not the whole name,
44
+ * which is what separates `Counter` from a `PROPS` constant — and any other usable identifier
45
+ * after it, because a lowercase component still compiles and beats a name the reader must invent.
46
+ */
47
+ const componentOf = (exported: readonly string[]): string | undefined => {
48
+ const usable = exported.filter((name) => JSX_NAME.test(name) && name !== 'default');
49
+ return usable.find((name) => /^[A-Z]/.test(name) && name !== name.toUpperCase()) ?? usable[0];
50
+ };
51
+
52
+ /**
53
+ * The chunk built and imported, and exports no `mount`. Distinct from a build failure: the island
54
+ * compiles, ships and is served — the hydration runtime calls `m.mount(el, props)` and the browser
55
+ * throws on a page that passed every gate. Naming the exports it DOES have is what separates a
56
+ * renamed export from a file that exports only its component.
57
+ *
58
+ * The paste is built from THOSE exports rather than from a sketch. It read
59
+ * `render(() => <Island {...props} />, el)` with `props: Props` until 2026-08-21, and none of
60
+ * `Island`, `Props` or `render` exists in the file the reader was told to paste it into — three
61
+ * compile errors handed out as the remedy for one. Two of them the error already knew the answer
62
+ * to, from its own cause; the third is an import, so the import is in the line.
63
+ */
64
+ export class IslandMountMissingError extends UltimateError {
65
+ constructor(input: { file: string; exported: readonly string[] }) {
66
+ const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
67
+ const component = componentOf(input.exported);
68
+ super({
69
+ code: 'X_TEST_ISLAND_NO_MOUNT',
70
+ cause: `the chunk built from ${renderCauseValue(input.file)} exports ${
71
+ input.exported.length === 0 ? 'nothing' : input.exported.join(', ')
72
+ } — the hydration runtime calls m.mount(el, props)`,
73
+ fix:
74
+ component === undefined
75
+ ? `${file} exports nothing a mount could render — x g island <name> --at apps/web/site writes an island whose mount() is already there, and its shape is the one to copy`
76
+ : `in ${file} add: import { render } from 'solid-js/web'; export function mount(el: HTMLElement, props: Parameters<typeof ${component}>[0]): () => void { el.textContent = ''; return render(() => <${component} {...props} />, el); }`,
77
+ });
78
+ }
79
+ }
80
+
81
+ export const islandMountMissing = (file: string, exported: readonly string[]): UltimateError =>
82
+ new IslandMountMissingError({ file, exported });
@@ -21,7 +21,7 @@ const EQUALITY = /(?<![<>!])=(?!>)/;
21
21
  const IS_NULL = /\bIS\s+NULL\b/i;
22
22
 
23
23
  /** The parts of `text` between `word`s that stand outside every parenthesis and literal. */
24
- function splitTop(text: string, word: 'AND' | 'OR'): string[] {
24
+ export function splitTop(text: string, word: 'AND' | 'OR'): string[] {
25
25
  const parts: string[] = [];
26
26
  let depth = 0;
27
27
  let quoted = false;
@@ -43,7 +43,7 @@ function splitTop(text: string, word: 'AND' | 'OR'): string[] {
43
43
  }
44
44
 
45
45
  /** `((a = $1))` → `a = $1`: parentheses that wrap the whole text, and only those. */
46
- function unwrap(text: string): string {
46
+ export function unwrap(text: string): string {
47
47
  let rest = text.trim();
48
48
  for (;;) {
49
49
  if (!rest.startsWith('(') || !rest.endsWith(')')) return rest;