@ultimat3/testing 31.25.0 → 31.27.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.
@@ -5,16 +5,22 @@
5
5
 
6
6
  import type { ExerciseActorOptions, ExerciseOffOptions } from '@ultimat3/action';
7
7
  import { finiteCount, renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
8
+ import type { RouteExerciseOverride } from './define-exercise-routes';
9
+ import { checkEmptyWhy, routeEntries } from './define-exercise-routes';
8
10
  import type { ExerciseSetup } from './exercise-setup';
9
11
  import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
10
12
  import type { SeedFactory } from './seed-graph-plan';
11
13
 
12
14
  /**
13
15
  * 39's option type — `{ actor, input?, runs? }` or `{ off: '<reason>' }` — and the pass's own
14
- * `statements: { max, why }`: the ceiling one call is held to, `STATEMENTS_MAX` when omitted.
16
+ * `statements: { max, why }`: the ceiling one call is held to, `STATEMENTS_MAX` when omitted; and
17
+ * `empty: '<why>'`: why a reach with no statement and no effect is right (`X_EXERCISE_EMPTY_REACH`).
15
18
  */
16
19
  export type ExerciseOverride =
17
- | (ExerciseActorOptions & { readonly statements?: ExerciseStatementCeiling })
20
+ | (ExerciseActorOptions & {
21
+ readonly statements?: ExerciseStatementCeiling;
22
+ readonly empty?: string;
23
+ })
18
24
  | ExerciseOffOptions;
19
25
 
20
26
  /**
@@ -32,6 +38,8 @@ export interface ExerciseOverrides {
32
38
  readonly factories?: Readonly<Record<string, SeedFactory>>;
33
39
  /** The app's hooks, run once each, in order, inside the pass's sealed room (`exercise-setup.ts`). */
34
40
  readonly setup?: ExerciseSetup | readonly ExerciseSetup[];
41
+ /** Each route load's entry, by URL pattern (`define-exercise-routes.ts`). */
42
+ readonly routes?: ReadonlyMap<string, RouteExerciseOverride>;
35
43
  }
36
44
 
37
45
  /** The three kinds an entry may be qualified by. */
@@ -77,6 +85,11 @@ export interface ExerciseAppOptions {
77
85
  * disposed in reverse; one that throws disposes those that already ran.
78
86
  */
79
87
  readonly setup?: ExerciseSetup | readonly ExerciseSetup[];
88
+ /**
89
+ * By URL pattern (`x routes`), what a route's `load` runs with: `params`, `actor`, `statements`,
90
+ * `empty` or `off` (`define-exercise-routes.ts`). An unknown pattern is refused when the pass runs.
91
+ */
92
+ readonly routes?: Readonly<Record<string, RouteExerciseOverride>>;
80
93
  }
81
94
 
82
95
  /** `X_CONTRACT_EXERCISE_UNDECLARED`, 39's code for the same silence: an `off` with no reason. */
@@ -113,6 +126,14 @@ export function defineExercise(
113
126
  for (const [name, override] of Object.entries(overrides)) {
114
127
  if ('off' in override && override.off.trim().length === 0) throw blankReason(name);
115
128
  checkCeiling(name, override);
129
+ if (!('off' in override)) {
130
+ const at = renderFixLiteral(name, '<name>');
131
+ checkEmptyWhy(
132
+ name,
133
+ override.empty,
134
+ `defineExercise({ ${at}: { empty: '<why it reads nothing>' } })`,
135
+ );
136
+ }
116
137
  entries.set(name, override);
117
138
  }
118
139
  return Object.freeze({
@@ -125,6 +146,7 @@ export function defineExercise(
125
146
  : { actorEntity: app.actor.$name }),
126
147
  ...(app.factories === undefined ? {} : { factories: app.factories }),
127
148
  ...(app.setup === undefined ? {} : { setup: app.setup }),
149
+ ...(app.routes === undefined ? {} : { routes: routeEntries(app.routes) }),
128
150
  });
129
151
  }
130
152
 
@@ -6,13 +6,13 @@ import { DrillServiceMissingError } from './drill-errors';
6
6
  import type { DrillServiceUrls } from './drill-fleet';
7
7
  import type { Drill } from './drills';
8
8
  import { drillService } from './drills';
9
+ import { TEST_SERVICE_ENV } from './test-types-services';
9
10
 
10
- /** The variables the test services are published under (`docker/test-services.env`). */
11
- export const DRILL_SERVICE_ENV = {
12
- postgres: 'TEST_DATABASE_URL',
13
- redis: 'TEST_REDIS_URL',
14
- nats: 'TEST_NATS_URL',
15
- } as const;
11
+ /**
12
+ * The variables the test services are published under (`docker/test-services.env`): the same map a
13
+ * typed test's `{ needs }` reads, never a second copy of it.
14
+ */
15
+ export const DRILL_SERVICE_ENV = TEST_SERVICE_ENV;
16
16
 
17
17
  /** What the app's config says it uses, beyond the Postgres every drill needs. */
18
18
  export interface DrillDeclarations {
package/src/e2e-driver.ts CHANGED
@@ -35,19 +35,15 @@ const refuse =
35
35
  Promise.reject(new FixtureUnavailableError({ name, needs }));
36
36
 
37
37
  /**
38
- * `offline()`/`online()` FORWARD, `As of 2026-08-27`. They refused until then on a reason the tree
39
- * contradicted on the day it was written: this file said `CdpPageLike`
40
- * (`packages/scraping/src/cdp-port.ts`) "declares twelve methods and none of them is
41
- * `setOfflineMode`". It declares it at line 71 — optional, guarded, with a coded
42
- * `X_NOT_IMPLEMENTED` in `cdp-target.ts` for a launcher that lacks it — and `page-over-target.ts`
43
- * exposes it as `ScrapePage.offline()`. All of that landed in **the same commit as the comment**
44
- * (#351), so the refusal was never true, and it is the reason issue #390 records a real browser
45
- * check as out of reach.
38
+ * `offline()`/`online()` FORWARD, `As of 2026-08-27`, to `ScrapePage.offline()`
39
+ * (`page-over-target.ts`), which reaches `CdpPageLike.setOfflineMode` — checked when the session
40
+ * opens (scraping's `cdp-complete.ts`), so a driver that lacks it is refused there, never at the
41
+ * first `offline()`. Issue #390 recorded a real browser check as out of reach on a refusal that
42
+ * was never true (#351).
46
43
  *
47
- * Optional on `E2eBrowserPage` rather than required, for the reason `CdpPageLike` gives about the
48
- * same method: this port is the shape of somebody ELSE's object, and a six-line test double must
49
- * still satisfy it. Absent, the refusal stands — and now it names the method the double is missing
50
- * rather than a capability the framework does not have.
44
+ * Optional on `E2eBrowserPage` all the same: this port is the shape of somebody ELSE's object, and
45
+ * a six-line test double must still satisfy it. Absent, the fixture refuses by name — naming the
46
+ * method the double is missing rather than a capability the framework does not have.
51
47
  */
52
48
  const networkFixtures = (browser: E2eBrowserPage): Pick<E2eFixtures, 'offline' | 'online'> => {
53
49
  const setOffline = browser.offline?.bind(browser);
package/src/e2e-page.ts CHANGED
@@ -22,14 +22,14 @@ export interface E2eBrowserPage {
22
22
  click(selector: string): Promise<void>;
23
23
  /**
24
24
  * The browser's own network condition, which `E2eFixtures.offline()`/`online()` forward to.
25
- * `ScrapePage` has it (`page-over-target.ts`), reaching `CdpPageLike.setOfflineMode` through
26
- * `cdp-target.ts`'s guard.
25
+ * `ScrapePage` has it (`page-over-target.ts`), over `CdpPageLike.setOfflineMode` — checked when
26
+ * the session opens (scraping's `cdp-complete.ts`).
27
27
  *
28
- * OPTIONAL for the reason the four above are structural: this port is the shape of somebody
28
+ * OPTIONAL here for the reason the four above are structural: this port is the shape of somebody
29
29
  * ELSE's object, and requiring it would cost every six-line double a type error for a capability
30
- * a test that never goes offline does not need. Absent, `e2e-driver.ts` keeps refusing by name —
31
- * a coded refusal, never a silent no-op, because an `offline()` that did nothing would let the
32
- * app's ONLINE page pass an offline test.
30
+ * a test that never goes offline does not need. Absent, `e2e-driver.ts` refuses by name — a coded
31
+ * refusal, never a silent no-op, because an `offline()` that did nothing would let the app's
32
+ * ONLINE page pass an offline test.
33
33
  */
34
34
  offline?(enabled: boolean): Promise<void>;
35
35
  /**
@@ -4,12 +4,13 @@
4
4
 
5
5
  import type { ExerciseVerdict } from '@ultimat3/core';
6
6
  import { isUltimateError, renderThrowable } from '@ultimat3/core';
7
- import { exerciseEntryKey } from './define-exercise';
7
+ import type { ExerciseOverrides } from './define-exercise';
8
+ import { exerciseEntryKey, overrideFor } from './define-exercise';
8
9
  import { driftOverrideLine } from './exercise-drift-hint';
9
10
  import type { Sampler } from './exercise-input';
10
11
  import { idStem } from './exercise-input';
11
12
  import { type OverrideHint, overrideLine } from './exercise-override-line';
12
- import type { Observed } from './exercise-report';
13
+ import type { ExerciseRecord, Observed } from './exercise-report';
13
14
  import type { Subject } from './exercise-subjects';
14
15
 
15
16
  /**
@@ -78,3 +79,13 @@ export function judged(
78
79
  }
79
80
  return unreached(codeOf(run.lastError), reasonOf(run.lastError));
80
81
  }
82
+
83
+ /** A reach with nothing to prove carries its entry's `empty` reason, when the entry gives one. */
84
+ export function withEmptyWhy(record: ExerciseRecord, overrides: ExerciseOverrides | undefined) {
85
+ if (record.outcome !== 'reached' || record.statements > 0 || record.effects.length > 0) {
86
+ return record;
87
+ }
88
+ const entry = overrideFor(overrides, record.kind, record.name);
89
+ const why = entry === undefined || 'off' in entry ? undefined : entry.empty;
90
+ return why === undefined ? record : { ...record, empty: why.trim() };
91
+ }
@@ -11,6 +11,7 @@ const countKey = (effect: ExerciseEffect): string | undefined => {
11
11
  if (effect.kind === 'row') return `row\u0000${effect.entity}\u0000${effect.op}`;
12
12
  if (effect.kind === 'mail') return `mail\u0000${effect.mail}`;
13
13
  if (effect.kind === 'enqueue') return `enqueue\u0000${effect.job}`;
14
+ if (effect.kind === 'push') return `push\u0000${effect.host}`;
14
15
  return undefined;
15
16
  };
16
17
 
@@ -21,6 +22,8 @@ const added = (one: ExerciseEffect, other: ExerciseEffect): ExerciseEffect => {
21
22
  if (one.kind === 'enqueue' && other.kind === 'enqueue') {
22
23
  return { ...one, count: one.count + other.count };
23
24
  }
25
+ if (one.kind === 'push' && other.kind === 'push')
26
+ return { ...one, count: one.count + other.count };
24
27
  return one;
25
28
  };
26
29
 
@@ -0,0 +1,43 @@
1
+ // What a primitive's call left on its queue, read off the call's own ambient queue: the jobs it
2
+ // enqueued (its effects) and, for a tenant proof's B leg, every queued job's input (its payloads).
3
+
4
+ import { LIVE_STATES, registeredJobs } from '@ultimat3/jobs';
5
+ import { ambientJobRows } from './exercise-job-run';
6
+ import type { EffectPayload, ExerciseEffect } from './exercise-report';
7
+ import type { Subject } from './exercise-subjects';
8
+
9
+ /** The ids of every row the call's queue holds now: what an attempt adds is the call's. */
10
+ export const queuedIds = async (): Promise<ReadonlySet<string>> =>
11
+ new Set((await ambientJobRows()).map((record) => record.id));
12
+
13
+ /**
14
+ * Jobs the primitive queued — rows an ATTEMPT added (`mine`), still live — its own job excepted.
15
+ * Never run: a job's children are left queued as an action's are (`exercise-job-run.ts`). A row
16
+ * the override's input added between calls is on the same queue, so the call can find it, and is
17
+ * not in `mine`: the input's enqueue is never the primitive's.
18
+ */
19
+ export async function enqueued(subject: Subject, mine: ReadonlySet<string>) {
20
+ const counts = new Map<string, number>();
21
+ for (const record of await ambientJobRows()) {
22
+ if (!mine.has(record.id) || !LIVE_STATES.has(record.state)) continue;
23
+ if (subject.kind === 'job' && record.name === subject.name) continue;
24
+ counts.set(record.name, (counts.get(record.name) ?? 0) + 1);
25
+ }
26
+ const order = registeredJobs().map((handle) => handle.name);
27
+ return [...counts]
28
+ .sort(([a], [b]) => order.indexOf(a) - order.indexOf(b))
29
+ .map(([job, count]): ExerciseEffect => ({ kind: 'enqueue', job, count }));
30
+ }
31
+
32
+ /**
33
+ * Every job a B leg's queue holds or ran, with its input — the subject's own job excepted, whose
34
+ * input is what B was handed. Read off the leg's own queue, page by page.
35
+ */
36
+ export async function queuedPayloads(subject: Subject): Promise<readonly EffectPayload[]> {
37
+ return (await ambientJobRows())
38
+ .filter((record) => !(subject.kind === 'job' && record.name === subject.name))
39
+ .map((record, i) => ({
40
+ path: `effect.enqueue[${i}]`,
41
+ value: { job: record.name, input: record.input },
42
+ }));
43
+ }
@@ -34,7 +34,9 @@ export type ExerciseEffect =
34
34
  readonly host: string;
35
35
  readonly refused: boolean;
36
36
  }
37
- | { readonly kind: 'enqueue'; readonly job: string; readonly count: number };
37
+ | { readonly kind: 'enqueue'; readonly job: string; readonly count: number }
38
+ /** Web Push messages sent to `host`'s push service: a notifier that pushes nothing has none. */
39
+ | { readonly kind: 'push'; readonly host: string; readonly count: number };
38
40
 
39
41
  export type ExerciseOutcome = 'reached' | 'refused' | 'unreached' | 'off';
40
42
 
@@ -123,6 +125,11 @@ export interface ExerciseRecord {
123
125
  * whose `tenant(input)` names one fixed org (`exercise-subjects.ts`'s `fixedTenant`).
124
126
  */
125
127
  readonly fix?: string;
128
+ /**
129
+ * On a reached one with no statement and no effect: the entry's `empty` reason, why that reach
130
+ * is right. Absent, the reach is `X_EXERCISE_EMPTY_REACH` — its proofs prove nothing.
131
+ */
132
+ readonly empty?: string;
126
133
  /** On every record that ran — absent only on `off` and `refused`. The fields above are A's. */
127
134
  readonly tenant?: TenantProof;
128
135
  /** On a reached job only: its control's input, killed at every step boundary. */
@@ -286,6 +293,12 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
286
293
  const offDials = onDial((call) => {
287
294
  if (owns()) calls.push(call);
288
295
  });
296
+ // A push travels through an injected fetch (the pass's push stand-in), never a dial: what tells
297
+ // of it is `outbound()`'s own event, vendor `push`, which every send emits whatever answers it.
298
+ const pushes: string[] = [];
299
+ const offPushes = subscribe('outbound.request', (event) => {
300
+ if (owns() && event.payload.vendor === 'push') pushes.push(event.payload.host);
301
+ });
289
302
 
290
303
  const begin = (name: string | undefined): object => {
291
304
  subject = name;
@@ -295,6 +308,7 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
295
308
  unattributed = false;
296
309
  rows.length = 0;
297
310
  calls.length = 0;
311
+ pushes.length = 0;
298
312
  mail.clear();
299
313
  marker = {};
300
314
  return marker;
@@ -321,6 +335,7 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
321
335
  refused: refused(call),
322
336
  }),
323
337
  ),
338
+ ...[...tally(pushes)].map(([host, count]): ExerciseEffect => ({ kind: 'push', host, count })),
324
339
  ];
325
340
  const refusedHosts = calls.filter(refused).map((c) => hostOf(c.url));
326
341
  const payloads: EffectPayload[] = [
@@ -366,6 +381,7 @@ export async function openExerciseRoom(): Promise<ExerciseRoom> {
366
381
  try {
367
382
  mail[Symbol.dispose]();
368
383
  } finally {
384
+ offPushes();
369
385
  offDials();
370
386
  offRows();
371
387
  offStatements();
@@ -16,8 +16,16 @@ import type {
16
16
  ProofMs,
17
17
  } from './exercise-report';
18
18
  import { withExerciseRequest } from './exercise-request';
19
+ import {
20
+ entryActor,
21
+ entryActorChoice,
22
+ entryParams,
23
+ entrySearch,
24
+ liveEntry,
25
+ routeEntryFor,
26
+ } from './exercise-route-override';
19
27
  import type { RouteLoadSubject, RouteParamsValue } from './exercise-route-subjects';
20
- import { chooseRouteActor, routeParams, routeUrl } from './exercise-route-subjects';
28
+ import { routeParams, routeUrl } from './exercise-route-subjects';
21
29
  import type { StatementCeilingProof } from './exercise-statement-ceiling';
22
30
  import { judgeStatementCeiling } from './exercise-statement-ceiling';
23
31
  import { actorRowsOf, seated } from './exercise-sweeps';
@@ -32,13 +40,15 @@ export interface RouteLoadRecord {
32
40
  readonly kind: 'route';
33
41
  readonly name: string;
34
42
  readonly file: string;
35
- readonly outcome: 'reached' | 'refused' | 'unreached';
43
+ readonly outcome: 'reached' | 'refused' | 'unreached' | 'off';
36
44
  readonly code?: string;
37
45
  readonly reason?: string;
38
46
  readonly statements: number;
39
47
  readonly effects: readonly ExerciseEffect[];
40
48
  readonly ms: number;
41
49
  readonly statementCeiling?: StatementCeilingProof;
50
+ /** Reached with no statement and no effect, and the entry says why that is right. */
51
+ readonly empty?: string;
42
52
  readonly plans?: PlanProof;
43
53
  readonly scale?: ScaleProof;
44
54
  readonly proofMs?: ProofMs;
@@ -57,31 +67,51 @@ export interface RouteCallOptions {
57
67
  /** The page's data, resolved as a render resolves it, in a request as `actor`. */
58
68
  export const callRoute = (
59
69
  route: RouteLoadSubject,
60
- params: RouteParamsValue,
70
+ call: RouteCallInput,
61
71
  actor: Actor | null,
62
72
  ): Promise<unknown> =>
63
73
  withExerciseRequest(routeLabel(route.path), actor, () =>
64
- route.load({ params, url: routeUrl(route.path, params) }),
74
+ route.load({ params: call.params, url: `${routeUrl(route.path, call.params)}${call.search}` }),
65
75
  );
66
76
 
67
- /** Who loads `route` in `tenant` of `graph`, and with which params — or none. */
77
+ /** What one load is handed: its params and the query string its URL carries (`''`, or `?…`). */
78
+ export interface RouteCallInput {
79
+ readonly params: RouteParamsValue;
80
+ readonly search: string;
81
+ }
82
+
83
+ /**
84
+ * Who loads `route` in `tenant` of `graph`, and with which params — or none. The route's
85
+ * `defineExercise` entry speaks first (`exercise-route-override.ts`); the pass picks the rest.
86
+ */
68
87
  export async function routeCall(
69
88
  route: RouteLoadSubject,
70
89
  options: RouteCallOptions,
71
90
  graph: SeedGraph,
72
91
  tenant: string,
73
92
  ): Promise<
74
- | { readonly actor: Actor | null; readonly params: RouteParamsValue }
93
+ | ({ readonly actor: Actor | null } & RouteCallInput)
75
94
  | { readonly refused?: true; readonly reason: string }
76
95
  > {
77
- const chosen = chooseRouteActor(route.permission, options.roles, tenant);
96
+ const entry = liveEntry(routeEntryFor(options.overrides, route.path));
97
+ const label = routeLabel(route.path);
98
+ const chosen = entryActorChoice(entry, route.permission, options.roles, tenant);
78
99
  if (chosen.kind === 'refused') return { refused: true, reason: chosen.reason };
79
- const actor = seated(chosen.actor, tenant, actorRowsOf(options, graph));
100
+ const base = seated(chosen.actor, tenant, actorRowsOf(options, graph));
101
+ // A user, as a request's actor always is: its `x_users` row before any call.
102
+ await seatActorUsers([base]);
103
+ const resolved = await entryActor(label, entry, base);
104
+ if (resolved.kind === 'threw') return { reason: resolved.reason };
105
+ const actor = resolved.value;
106
+ if (actor !== base) await seatActorUsers([actor]);
107
+ const search = await entrySearch(label, entry, actor);
108
+ if (search.kind === 'threw') return { reason: search.reason };
109
+ const declared = await entryParams(label, entry, actor);
110
+ if (declared?.kind === 'threw') return { reason: declared.reason };
111
+ if (declared !== undefined) return { actor, params: declared.value, search: search.value };
80
112
  const params = await routeParams(route, graph, options.entities, { tenant, actorId: actor?.id });
81
113
  if (params.kind === 'none') return { reason: params.reason };
82
- // A user, as a request's actor always is: its `x_users` row before the call.
83
- await seatActorUsers([actor]);
84
- return { actor, params: params.params };
114
+ return { actor, params: params.params, search: search.value };
85
115
  }
86
116
 
87
117
  const unreachedBy = (seen: Observation<unknown>) => {
@@ -107,6 +137,10 @@ export async function exerciseRouteLoad(
107
137
  ): Promise<RouteLoadRecord> {
108
138
  const none = { kind: 'route' as const, name: route.path, file: route.file };
109
139
  const empty = { ...none, statements: 0, effects: [], ms: 0 };
140
+ const entry = routeEntryFor(options.overrides, route.path);
141
+ if (entry !== undefined && 'off' in entry) {
142
+ return { ...empty, outcome: 'off', reason: entry.off.trim() };
143
+ }
110
144
  const call = await routeCall(route, options, at.graph, at.tenant);
111
145
  if ('reason' in call) {
112
146
  return {
@@ -117,25 +151,28 @@ export async function exerciseRouteLoad(
117
151
  }
118
152
  const started = performance.now();
119
153
  const seen = await at.room.observe(routeLabel(route.path), () =>
120
- callRoute(route, call.params, call.actor),
154
+ callRoute(route, call, call.actor),
121
155
  );
122
156
  const ms = Math.round(performance.now() - started);
123
157
  const { observed } = seen;
124
158
  const ran = { ...none, statements: observed.statements, effects: observed.effects, ms };
125
- const statementCeiling = judgeStatementCeiling([observed]);
159
+ const statementCeiling = judgeStatementCeiling([observed], liveEntry(entry).statements);
126
160
  const failed = unreachedBy(seen);
161
+ const why = liveEntry(entry).empty;
162
+ const vacuous = failed === undefined && ran.statements === 0 && ran.effects.length === 0;
127
163
  return {
128
164
  ...ran,
129
165
  ...(failed ?? { outcome: 'reached' as const }),
166
+ ...(vacuous && why !== undefined ? { empty: why.trim() } : {}),
130
167
  ...(statementCeiling === undefined ? {} : { statementCeiling }),
131
168
  };
132
169
  }
133
170
 
134
- /** The route as the scale sweep calls it: `input` is the params `routeCall` bound at each size. */
171
+ /** The route as the scale sweep calls it: `input` is what `routeCall` bound at each size. */
135
172
  export const routeScaleSubject = (route: RouteLoadSubject): ScaleSubject => ({
136
173
  name: routeLabel(route.path),
137
174
  call: async (input, actor) => {
138
- await callRoute(route, input as RouteParamsValue, actor);
175
+ await callRoute(route, input as RouteCallInput, actor);
139
176
  return {};
140
177
  },
141
178
  });
@@ -172,7 +209,9 @@ export async function routeSizedCall(
172
209
  const route = routes.find((one) => routeLabel(one.path) === at.label);
173
210
  if (route === undefined) return undefined;
174
211
  const call = await routeCall(route, options, at.graph, at.tenant);
175
- return 'reason' in call ? undefined : { actor: call.actor, input: call.params };
212
+ return 'reason' in call
213
+ ? undefined
214
+ : { actor: call.actor, input: { params: call.params, search: call.search } };
176
215
  }
177
216
 
178
217
  /** The sweeps' key for a record of either kind: a route's label, else the primitive's own. */
@@ -0,0 +1,105 @@
1
+ // What a route's `defineExercise(…, { routes })` entry changes about its call: the actor (declared,
2
+ // or the app's resolution of the one the pass seated) and the params (declared, or computed in the
3
+ // load's own request). Each function the app wrote runs in that request, so its reads see the
4
+ // route's tenant — and before the observed call, so its statements are never the load's.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { renderThrowable } from '@ultimat3/core';
8
+ import type { ExerciseOverrides } from './define-exercise';
9
+ import type { RouteExerciseEntry, RouteExerciseOverride } from './define-exercise-routes';
10
+ import type { RoleGrants } from './exercise-actor';
11
+ import { inTenant } from './exercise-actor';
12
+ import { withExerciseRequest } from './exercise-request';
13
+ import type { RouteActorChoice, RouteParamsValue } from './exercise-route-subjects';
14
+ import { chooseRouteActor } from './exercise-route-subjects';
15
+
16
+ /** The route's entry, by its URL pattern, or none. */
17
+ export const routeEntryFor = (
18
+ overrides: ExerciseOverrides | undefined,
19
+ path: string,
20
+ ): RouteExerciseOverride | undefined => overrides?.routes?.get(path);
21
+
22
+ /** The entry as a call reads it: an `off` entry never reaches a call. */
23
+ export const liveEntry = (entry: RouteExerciseOverride | undefined): RouteExerciseEntry =>
24
+ entry === undefined || 'off' in entry ? {} : entry;
25
+
26
+ /**
27
+ * Who the pass seats before the entry speaks: a declared actor, moved into `tenant`; else the role
28
+ * the guard admits — and for an actor FUNCTION whose guard no role holds, the first signed-in one,
29
+ * which the function is there to complete.
30
+ */
31
+ export function entryActorChoice(
32
+ entry: RouteExerciseEntry,
33
+ permission: string | undefined,
34
+ grants: RoleGrants,
35
+ tenant: string,
36
+ ): RouteActorChoice {
37
+ const { actor } = entry;
38
+ if (actor !== undefined && typeof actor !== 'function') {
39
+ return { kind: 'actor', actor: inTenant(actor, tenant) };
40
+ }
41
+ const chosen = chooseRouteActor(permission, grants, tenant);
42
+ if (chosen.kind === 'actor' || actor === undefined) return chosen;
43
+ return chooseRouteActor(undefined, grants, tenant);
44
+ }
45
+
46
+ export type EntryOutcome<T> =
47
+ | { readonly kind: 'value'; readonly value: T }
48
+ | { readonly kind: 'threw'; readonly reason: string };
49
+
50
+ const threw = (field: string, error: unknown) => ({
51
+ kind: 'threw' as const,
52
+ reason: `its exercise.ts ${field} threw: ${renderThrowable(error)}`,
53
+ });
54
+
55
+ /** The actor the load runs as: the seated one, or what the entry's function made of it. */
56
+ export async function entryActor(
57
+ label: string,
58
+ entry: RouteExerciseEntry,
59
+ seated: Actor | null,
60
+ ): Promise<EntryOutcome<Actor | null>> {
61
+ const resolve = entry.actor;
62
+ if (typeof resolve !== 'function') return { kind: 'value', value: seated };
63
+ try {
64
+ const value = await withExerciseRequest(label, seated, async () => resolve(seated));
65
+ return { kind: 'value', value };
66
+ } catch (error) {
67
+ return threw('actor', error);
68
+ }
69
+ }
70
+
71
+ /** The entry's params, computed in the load's request when a function; `undefined`: the pass's. */
72
+ export async function entryParams(
73
+ label: string,
74
+ entry: RouteExerciseEntry,
75
+ actor: Actor | null,
76
+ ): Promise<EntryOutcome<RouteParamsValue> | undefined> {
77
+ const { params } = entry;
78
+ if (params === undefined) return undefined;
79
+ if (typeof params !== 'function') return { kind: 'value', value: params };
80
+ try {
81
+ return { kind: 'value', value: await withExerciseRequest(label, actor, async () => params()) };
82
+ } catch (error) {
83
+ return threw('params', error);
84
+ }
85
+ }
86
+
87
+ /** The query string the load's URL carries: the entry's (`?` added), computed in its request. */
88
+ export async function entrySearch(
89
+ label: string,
90
+ entry: RouteExerciseEntry,
91
+ actor: Actor | null,
92
+ ): Promise<EntryOutcome<string>> {
93
+ const { search } = entry;
94
+ if (search === undefined) return { kind: 'value', value: '' };
95
+ try {
96
+ const value =
97
+ typeof search === 'function'
98
+ ? await withExerciseRequest(label, actor, async () => search())
99
+ : search;
100
+ const bare = value.startsWith('?') ? value.slice(1) : value;
101
+ return { kind: 'value', value: bare.length === 0 ? '' : `?${bare}` };
102
+ } catch (error) {
103
+ return threw('search', error);
104
+ }
105
+ }
@@ -0,0 +1,13 @@
1
+ // `x exercise --shard i/n`: which primitives and route loads one of n processes runs. A pure
2
+ // function of the position in the registry's own order, so shard 3 of 8 is the same slice on every
3
+ // machine — and each subject's tenant pair is its own, so the slices share no row.
4
+
5
+ /** 1-based, as a CI matrix counts: `{ index: 2, total: 4 }` is the second of four. */
6
+ export interface ExerciseShard {
7
+ readonly index: number;
8
+ readonly total: number;
9
+ }
10
+
11
+ /** Whether the subject at `position` (primitives first, then routes) is this shard's. */
12
+ export const inShard = (position: number, shard: ExerciseShard | undefined): boolean =>
13
+ shard === undefined || position % shard.total === shard.index - 1;