@ultimat3/testing 31.42.1 → 31.44.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.42.1",
3
+ "version": "31.44.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,27 +47,27 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.42.1",
51
- "@ultimat3/ai": "31.42.1",
52
- "@ultimat3/auth": "31.42.1",
53
- "@ultimat3/cache": "31.42.1",
54
- "@ultimat3/core": "31.42.1",
55
- "@ultimat3/db": "31.42.1",
56
- "@ultimat3/entity": "31.42.1",
57
- "@ultimat3/http": "31.42.1",
58
- "@ultimat3/i18n": "31.42.1",
59
- "@ultimat3/jobs": "31.42.1",
60
- "@ultimat3/mail": "31.42.1",
61
- "@ultimat3/notify": "31.42.1",
62
- "@ultimat3/policy": "31.42.1",
63
- "@ultimat3/pwa": "31.42.1",
64
- "@ultimat3/query": "31.42.1",
65
- "@ultimat3/realtime": "31.42.1",
66
- "@ultimat3/render": "31.42.1",
67
- "@ultimat3/schema": "31.42.1",
68
- "@ultimat3/scraping": "31.42.1",
69
- "@ultimat3/seo": "31.42.1",
70
- "@ultimat3/time": "31.42.1"
50
+ "@ultimat3/action": "31.44.0",
51
+ "@ultimat3/ai": "31.44.0",
52
+ "@ultimat3/auth": "31.44.0",
53
+ "@ultimat3/cache": "31.44.0",
54
+ "@ultimat3/core": "31.44.0",
55
+ "@ultimat3/db": "31.44.0",
56
+ "@ultimat3/entity": "31.44.0",
57
+ "@ultimat3/http": "31.44.0",
58
+ "@ultimat3/i18n": "31.44.0",
59
+ "@ultimat3/jobs": "31.44.0",
60
+ "@ultimat3/mail": "31.44.0",
61
+ "@ultimat3/notify": "31.44.0",
62
+ "@ultimat3/policy": "31.44.0",
63
+ "@ultimat3/pwa": "31.44.0",
64
+ "@ultimat3/query": "31.44.0",
65
+ "@ultimat3/realtime": "31.44.0",
66
+ "@ultimat3/render": "31.44.0",
67
+ "@ultimat3/schema": "31.44.0",
68
+ "@ultimat3/scraping": "31.44.0",
69
+ "@ultimat3/seo": "31.44.0",
70
+ "@ultimat3/time": "31.44.0"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "solid-js": "^1.9.18"
@@ -53,7 +53,7 @@ export function seededUuid(seed: number): () => string {
53
53
  return () => `${hex(8)}-${hex(4)}-4${hex(3)}-a${hex(3)}-${hex(12)}`;
54
54
  }
55
55
 
56
- class FrozenDate extends RealDate {
56
+ class FrozenClassDate extends RealDate {
57
57
  constructor(...args: readonly unknown[]) {
58
58
  if (args.length === 0) {
59
59
  super(frozenAt);
@@ -95,6 +95,17 @@ class FrozenDate extends RealDate {
95
95
  }
96
96
  }
97
97
 
98
+ /**
99
+ * What `globalThis.Date` is while installed. A `class` cannot be called without `new`, so
100
+ * `Date()` — the real one answers the current time's string — threw a TypeError under every test
101
+ * preload. The `apply` trap answers the frozen instant's string, ignoring arguments as the real
102
+ * call does; `new`, the statics, `instanceof` and `extends Date` all fall through to the class.
103
+ * One Proxy for the process, so a snapshot's `date` compares by identity.
104
+ */
105
+ const FrozenDate = new Proxy(FrozenClassDate, {
106
+ apply: (): string => new RealDate(frozenAt).toString(),
107
+ });
108
+
98
109
  export interface DeterminismOptions {
99
110
  readonly seed?: number;
100
111
  readonly now?: string | number;
@@ -63,22 +63,21 @@ export function entityForStem(
63
63
  * that references the actor when there is one (`authorId` = the actor), since ownership is the
64
64
  * rule a handler most often checks; else one that is not the actor's own row.
65
65
  */
66
- export type IdLookup = (
67
- key: string,
68
- ) => { readonly found: true; readonly value: unknown } | undefined;
66
+ export type IdLookup = (key: string) =>
67
+ | {
68
+ readonly found: true;
69
+ readonly value: unknown;
70
+ /** A tenant column's field: the run's own tenant, a fresh one every pass. */
71
+ readonly tenant?: true;
72
+ }
73
+ | undefined;
69
74
 
70
75
  const singularOf = (name: string): string =>
71
76
  name.endsWith('ies') ? `${name.slice(0, -3)}y` : name.endsWith('s') ? name.slice(0, -1) : name;
72
77
 
73
- /**
74
- * A bare `id` names the entity the PRIMITIVE is named after (`movePostStatus` -> `posts`): the
75
- * longest singular entity name inside the primitive's own name. A tie is no binding.
76
- */
77
- export function entityForSubject(
78
- subject: string,
79
- entities: readonly SeedEntity[],
80
- ): SeedEntity | undefined {
81
- const name = folded(subject);
78
+ /** The longest singular entity name inside `text`; a tie is none. */
79
+ function entityInside(text: string, entities: readonly SeedEntity[]): SeedEntity | undefined {
80
+ const name = folded(text);
82
81
  const named = entities
83
82
  .map((entity) => [entity, singularOf(folded(entity.$name))] as const)
84
83
  .filter(([, singular]) => singular.length > 0 && name.includes(singular))
@@ -87,12 +86,34 @@ export function entityForSubject(
87
86
  return first === undefined || second?.[1].length === first[1].length ? undefined : first[0];
88
87
  }
89
88
 
89
+ /**
90
+ * A bare `id` names the entity the PRIMITIVE is named after (`movePostStatus` -> `posts`), else
91
+ * the one entity its policy's grants name (`sendReminder` holding `invoice:write` -> `invoices`):
92
+ * `x g action <verb> --feature <slice>` takes any verb, and only the grant spells the slice. Two
93
+ * grants naming two entities name none — a guess between two tables is not a binding.
94
+ */
95
+ export function entityForSubject(
96
+ subject: string,
97
+ entities: readonly SeedEntity[],
98
+ permissions: readonly string[] = [],
99
+ ): SeedEntity | undefined {
100
+ const byName = entityInside(subject, entities);
101
+ if (byName !== undefined) return byName;
102
+ const granted = new Set(
103
+ permissions.map((permission) => entityInside(permission.split(':')[0] ?? '', entities)),
104
+ );
105
+ granted.delete(undefined);
106
+ return granted.size === 1 ? [...granted][0] : undefined;
107
+ }
108
+
90
109
  export interface IdScope {
91
110
  readonly tenant: string;
92
111
  /** The acting row's id: a row referencing it is preferred. */
93
112
  readonly actorId?: string | undefined;
94
113
  /** The primitive's name, for a bare `id`. */
95
114
  readonly subject: string;
115
+ /** Every permission its policy references: a bare `id`'s entity when the name names none. */
116
+ readonly permissions?: readonly string[] | undefined;
96
117
  /** The entity whose rows are the actors (`defineExercise(…, { actor })`). */
97
118
  readonly actorEntity?: string | undefined;
98
119
  /**
@@ -106,9 +127,9 @@ export interface IdScope {
106
127
  const entityForField = (
107
128
  key: string,
108
129
  entities: readonly SeedEntity[],
109
- subject: string,
130
+ scope: Pick<IdScope, 'subject' | 'permissions'>,
110
131
  ): SeedEntity | undefined => {
111
- if (key === 'id') return entityForSubject(subject, entities);
132
+ if (key === 'id') return entityForSubject(scope.subject, entities, scope.permissions);
112
133
  const stem = idStem(key);
113
134
  return stem === undefined ? undefined : entityForStem(stem, entities);
114
135
  };
@@ -117,12 +138,12 @@ const entityForField = (
117
138
  export function namesActorEntity(
118
139
  drawn: unknown,
119
140
  entities: readonly SeedEntity[],
120
- scope: Pick<IdScope, 'subject' | 'actorEntity'>,
141
+ scope: Pick<IdScope, 'subject' | 'permissions' | 'actorEntity'>,
121
142
  ): boolean {
122
143
  if (scope.actorEntity === undefined || !isPlainObject(drawn)) return false;
123
144
  return Object.keys(drawn).some((key) =>
124
145
  typeof drawn[key] === 'string'
125
- ? entityForField(key, entities, scope.subject)?.$name === scope.actorEntity
146
+ ? entityForField(key, entities, scope)?.$name === scope.actorEntity
126
147
  : namesActorEntity(drawn[key], entities, scope),
127
148
  );
128
149
  }
@@ -137,8 +158,8 @@ export function seededIds(
137
158
  // happens to name: a policy comparing it with `actor.orgId` refuses any other id.
138
159
  const tenantKeys = new Set(entities.map((entity) => entity.$tenantColumn));
139
160
  return (key) => {
140
- if (tenantKeys.has(key)) return { found: true, value: tenant };
141
- const entity = entityForField(key, entities, scope.subject);
161
+ if (tenantKeys.has(key)) return { found: true, value: tenant, tenant: true };
162
+ const entity = entityForField(key, entities, scope);
142
163
  if (entity === undefined || entity.$primaryKey.length !== 1) return undefined;
143
164
  const property = entity.$primaryKey[0] as string;
144
165
  const seen = graph.inserts.filter(
@@ -50,9 +50,12 @@ export function judged(
50
50
  observed: Observed,
51
51
  sampler: Sampler,
52
52
  ) {
53
+ // A field the pass binds every run (`hint.perRun`, the tenant) is no field to paste a value into.
53
54
  const idFields = (input: unknown): readonly string[] =>
54
55
  typeof input === 'object' && input !== null
55
- ? Object.keys(input).filter((key) => idStem(key) !== undefined)
56
+ ? Object.keys(input).filter(
57
+ (key) => idStem(key) !== undefined && run.hint?.perRun?.includes(key) !== true,
58
+ )
56
59
  : [];
57
60
  const unreached = (code: string | undefined, reason: string) => ({
58
61
  outcome: 'unreached' as const,
@@ -1,6 +1,6 @@
1
1
  // The entry an unreached primitive's record says to paste into `exercise.ts`: valid TS, naming
2
- // exactly what the pass ran with — the actor's grants and each id field's seeded row — so pasting
3
- // it compiles, and the author edits a working line instead of filling `<…>` holes in a broken one.
2
+ // exactly what the pass ran with — the actor (its grants, or the one the entry declared) and each
3
+ // id field's seeded row — so pasting it compiles and holds no value that changes from run to run.
4
4
 
5
5
  import type { Actor } from '@ultimat3/core';
6
6
  import { renderExerciseKey } from '@ultimat3/core';
@@ -16,13 +16,23 @@ export interface OverrideActor {
16
16
 
17
17
  export interface OverrideHint {
18
18
  /**
19
- * `null`: the pass ran signed out (or as a job's worker) — `actor: null`. Absent: the entry
20
- * already declares its actor, or the pass's pick cannot be spelled; the line leaves `actor` out
21
- * and the pass picks as it did.
19
+ * `null`: the pass ran signed out (or as a job's worker) — `actor: null`. Absent (and no
20
+ * `declared`): the entry declares an actor no builder call spells (`onBehalfOf`, facts JSON
21
+ * cannot carry); the line leaves `actor` out, so the author keeps theirs.
22
22
  */
23
23
  readonly actor?: OverrideActor | null | undefined;
24
+ /**
25
+ * The actor the entry DECLARED, spelled back as the builder that minted it (`userActor({ … })`):
26
+ * pasting the line over the entry keeps it. Wins over `actor`.
27
+ */
28
+ readonly declared?: Actor | undefined;
24
29
  /** Each id field's value where the pass bound it to a seeded row: the line binds that row. */
25
30
  readonly ids?: Readonly<Record<string, string>> | undefined;
31
+ /**
32
+ * Fields the pass binds itself on every run (a tenant column, to the run's fresh tenant): the
33
+ * line leaves them to `...drawn`, since any literal it printed is the wrong tenant next run.
34
+ */
35
+ readonly perRun?: readonly string[] | undefined;
26
36
  }
27
37
 
28
38
  /** What an id field the pass could not bind is left as: a string, so the line still compiles. */
@@ -41,6 +51,37 @@ function actorSource(actor: OverrideActor): string {
41
51
  return `testActor(${quoted(actor.name)}${second}).actor`;
42
52
  }
43
53
 
54
+ /** `userActor({ id: "member", orgId: "…", permissions: ["invoice:write"] })`: the declared one. */
55
+ function declaredSource(actor: Actor): string {
56
+ if (actor.kind === 'anonymous') return 'anonymousActor()';
57
+ const init = [
58
+ `id: ${quoted(actor.id)}`,
59
+ ...(actor.orgId === undefined ? [] : [`orgId: ${quoted(actor.orgId)}`]),
60
+ ...(actor.roles.length === 0 ? [] : [`roles: ${list(actor.roles)}`]),
61
+ ...(actor.scopes.length === 0 ? [] : [`scopes: ${list(actor.scopes)}`]),
62
+ ...(actor.permissions.length === 0 ? [] : [`permissions: ${list(actor.permissions)}`]),
63
+ ...(isEmpty(actor.facts) ? [] : [`facts: ${JSON.stringify(actor.facts)}`]),
64
+ ...(actor.locale === undefined ? [] : [`locale: ${quoted(actor.locale)}`]),
65
+ ...(actor.tz === undefined ? [] : [`tz: ${quoted(actor.tz)}`]),
66
+ ];
67
+ return `${actor.kind}Actor({ ${init.join(', ')} })`;
68
+ }
69
+
70
+ const isEmpty = (facts: object | undefined): boolean =>
71
+ facts === undefined || Object.keys(facts).length === 0;
72
+
73
+ /** What the line's actor slot reads, and the one import that needs (`undefined`: none). */
74
+ function actorSlot(hint: OverrideHint): { source: string; from?: string } | undefined {
75
+ const { actor, declared } = hint;
76
+ if (declared !== undefined) {
77
+ const builder = declared.kind === 'anonymous' ? 'anonymousActor' : `${declared.kind}Actor`;
78
+ return { source: declaredSource(declared), from: `${builder}: @ultimat3/core` };
79
+ }
80
+ if (actor === undefined) return undefined;
81
+ if (actor === null) return { source: 'null' };
82
+ return { source: actorSource(actor), from: 'testActor: @ultimat3/policy' };
83
+ }
84
+
44
85
  /**
45
86
  * `publishPost: { actor: testActor("editor", { roles: ["editor"] }).actor, input: (drawn) => ({
46
87
  * ...drawn, postId: "<seeded id>" }) }, // testActor: @ultimat3/policy` — the trailing comment is
@@ -52,29 +93,31 @@ export function overrideLine(
52
93
  hint: OverrideHint = {},
53
94
  ): string {
54
95
  const bound = idFields
96
+ .filter((field) => hint.perRun?.includes(field) !== true)
55
97
  .map((field) => `, ${renderExerciseKey(field)}: ${quoted(hint.ids?.[field] ?? UNBOUND_ID)}`)
56
98
  .join('');
57
- const actor =
58
- hint.actor === undefined
59
- ? ''
60
- : `actor: ${hint.actor === null ? 'null' : actorSource(hint.actor)}, `;
99
+ const slot = actorSlot(hint);
100
+ const actor = slot === undefined ? '' : `actor: ${slot.source}, `;
61
101
  const line = `${renderExerciseKey(name)}: { ${actor}input: (drawn) => ({ ...drawn${bound} }) },`;
62
- return hint.actor === undefined || hint.actor === null
63
- ? line
64
- : `${line} // testActor: @ultimat3/policy`;
102
+ return slot?.from === undefined ? line : `${line} // ${slot.from}`;
65
103
  }
66
104
 
105
+ /** Who the pass ran as, for the line: the pick by its grants, or the entry's declared actor. */
106
+ export type HintActor = OverrideHint['actor'] | { readonly declared: Actor };
107
+
67
108
  /**
68
- * The pick, spelled: absent when the entry declares its actor (the author's line already has it);
69
- * `null` for a signed-out run or a job's worker; else the grants the picked actor was minted with.
109
+ * The pick, spelled: the entry's own actor when it declares one (pasting the line over the entry
110
+ * must not drop it — the pass's pick would be refused where the declared member is not), `null`
111
+ * for a signed-out run or a job's worker, else the grants the picked actor was minted with.
112
+ * `undefined` only for a declared actor no builder call reproduces.
70
113
  */
71
114
  export function actorHintOf(
72
115
  chosen: { readonly actor: Actor | null; readonly name: string },
73
116
  override: ExerciseOverride | undefined,
74
- ): OverrideHint['actor'] {
75
- if (override !== undefined && !('off' in override) && override.actor !== undefined) {
76
- return undefined;
77
- }
117
+ ): HintActor {
118
+ const declared = override === undefined || 'off' in override ? undefined : override.actor;
119
+ if (declared === null) return null;
120
+ if (declared !== undefined) return spellable(declared) ? { declared } : undefined;
78
121
  if (chosen.actor === null) return null;
79
122
  return {
80
123
  name: chosen.name,
@@ -83,16 +126,41 @@ export function actorHintOf(
83
126
  };
84
127
  }
85
128
 
86
- /** Each top-level id field of `input` holding the seeded row either lookup bound it to. */
87
- export function seededIn(
129
+ /** A builder call mints the same actor: no impersonation, and facts JSON carries unchanged. */
130
+ function spellable(actor: Actor): boolean {
131
+ if (actor.onBehalfOf !== undefined) return false;
132
+ if (isEmpty(actor.facts)) return true;
133
+ try {
134
+ return Bun.deepEquals(JSON.parse(JSON.stringify(actor.facts)), actor.facts, true);
135
+ } catch {
136
+ // A cycle or a BigInt: JSON cannot carry it, so no line can.
137
+ return false;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * What the line binds, from the input the pass last sent: each id field holding a seeded row, and
143
+ * each tenant field — that one as the declared actor's org (the pass re-homes it, as it does the
144
+ * generated entry's literal), or left to the pass when the actor declares none.
145
+ */
146
+ export function hintFor(
147
+ actor: HintActor,
88
148
  input: unknown,
89
149
  lookups: readonly IdLookup[],
90
- ): Readonly<Record<string, string>> {
91
- if (typeof input !== 'object' || input === null) return {};
150
+ ): OverrideHint {
151
+ const who = actor !== undefined && actor !== null && 'declared' in actor ? actor : { actor };
152
+ if (typeof input !== 'object' || input === null) return who;
153
+ const org = 'declared' in who ? who.declared.orgId : undefined;
92
154
  const ids: Record<string, string> = {};
155
+ const perRun: string[] = [];
93
156
  for (const [field, value] of Object.entries(input)) {
94
157
  if (typeof value !== 'string') continue;
95
- if (lookups.some((lookup) => lookup(field)?.value === value)) ids[field] = value;
158
+ const hits = lookups.map((lookup) => lookup(field)).filter((hit) => hit?.value === value);
159
+ if (hits.length === 0) continue;
160
+ if (hits.some((hit) => hit?.tenant === true)) {
161
+ if (org === undefined) perRun.push(field);
162
+ else ids[field] = org;
163
+ } else ids[field] = value;
96
164
  }
97
- return ids;
165
+ return { ...who, ids, perRun };
98
166
  }
@@ -64,6 +64,7 @@ export async function sizedCall(
64
64
  tenant,
65
65
  actorId: actor?.id,
66
66
  subject: subject.name,
67
+ permissions: subject.permissions,
67
68
  actorEntity: rows?.entity.$name,
68
69
  };
69
70
  const lookup = seededIds(graph, options.entities, { ...scope, self });
package/src/exercise.ts CHANGED
@@ -26,7 +26,7 @@ import { judged, labelFor, withEmptyWhy } from './exercise-judge';
26
26
  import { mergeObserved } from './exercise-observed';
27
27
  import type { OverrideInput } from './exercise-override-input';
28
28
  import { inputThrew, overrideInput } from './exercise-override-input';
29
- import { actorHintOf, type OverrideHint, seededIn } from './exercise-override-line';
29
+ import { actorHintOf, type HintActor, hintFor } from './exercise-override-line';
30
30
  import { enqueued, queuedIds, queuedPayloads } from './exercise-queued';
31
31
  import type { ExercisePhaseMs, ExerciseRecord, ExerciseRoom, Observed } from './exercise-report';
32
32
  import { openExerciseRoom } from './exercise-report';
@@ -105,7 +105,7 @@ interface Prepared {
105
105
  readonly lookups: readonly [IdLookup, IdLookup];
106
106
  readonly bindInput: OverrideInput | undefined;
107
107
  /** The actor the pass picked, as the paste line spells it (`exercise-override-line.ts`). */
108
- readonly actorHint: OverrideHint['actor'];
108
+ readonly actorHint: HintActor;
109
109
  /** The entry's `statements: { max, why }`: the ceiling each call is held to. */
110
110
  readonly ceiling: ExerciseStatementCeiling | undefined;
111
111
  }
@@ -192,7 +192,7 @@ async function control(run: Prepared, room: ExerciseRoom, sampler: Sampler): Pro
192
192
  const ms = Math.round(performance.now() - started);
193
193
  const observed = mergeObserved(segments);
194
194
  const effects = [...observed.effects, ...(await enqueued(subject, mine))];
195
- const hint = { actor: run.actorHint, ids: seededIn(lastInput, lookups) };
195
+ const hint = hintFor(run.actorHint, lastInput, lookups);
196
196
  const outcome = { verdict, answered, lastError, lastInput, hint };
197
197
  const verdictOf = judged(subject, key, outcome, observed, sampler);
198
198
  // A 5xx's cause, statement and fields: the code alone sent the author to reproduce it by hand.
@@ -277,7 +277,13 @@ async function exerciseOne(
277
277
  // Both are users, as a request's actor always is: their `x_users` rows, before any call.
278
278
  await seatActorUsers([actor, intruder]);
279
279
 
280
- const scope = { tenant, actorId: actor?.id, subject: name, actorEntity: rows?.entity.$name };
280
+ const scope = {
281
+ tenant,
282
+ actorId: actor?.id,
283
+ subject: name,
284
+ permissions: subject.permissions,
285
+ actorEntity: rows?.entity.$name,
286
+ };
281
287
  const bindInput = overrideInput(name, override);
282
288
  // `off` returned above: any other entry's `runs` is declared, with or without an `actor`.
283
289
  const declaredRuns = override === undefined || 'off' in override ? undefined : override.runs;