@ultimat3/testing 31.21.0 → 31.22.1

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/CLAUDE.md CHANGED
@@ -43,6 +43,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
43
43
  | A port is swappable or says why not | `swap-adapter.ts`: `BINDINGS` + `UNSWAPPED` cover `ADAPTER_PORTS` as a `Record` — a new core row is a compile error here |
44
44
  | `toHaveBeenCalledWith` is bun's name | on a `stub()` it parses the expected input by the primitive's schema (`X_TEST_EXPECTED_INPUT_INVALID`); any other receiver goes to bun's own matcher, captured once (`matcher-stub.ts`) |
45
45
  | Per-test state is `per-test-reset.ts` | the app preload's `beforeEach`; `installPerTestReset` installs the test-double scope † |
46
+ | A file reruns in one process | `rerun-declarations.ts`: what the file declared (body, hooks, tests) is forgotten as it loads again; a new registry joins `rerun-registries.ts` with its package's lister + exact restore, never a `reset*` |
46
47
  | A `mock.module` ends with its file | `module-mock-boundary.ts` restores the real namespace at the boundary (`X_TEST_MODULE_MOCK_UNRESTORABLE`) † |
47
48
  | **The frozen clock is reset at every file boundary** | `preload.ts`, `clock-file-boundary.test.ts`: `advanceClock` / `setFrozenClock` move one process-wide instant, and a file that left it moved handed the next file on its worker a different `Date.now()` |
48
49
  | An island test is `describeIslandState` | one block per declared state: mounted in `beforeAll` (60 s), disposed in `afterAll`, one build per file. `mountIslandState` + `using` for one test's own mount; an undeclared id is `X_TEST_ISLAND_STATE_UNKNOWN` |
package/README.md CHANGED
@@ -89,7 +89,9 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
89
89
  | `island-states-resolve.ts` | a name a reader typed → the manifest it meant; a manifest → the island file it claims |
90
90
  | `framework-fixtures.ts` | registers both sets; the app registers only what it owns |
91
91
  | `registry-leak-guard.ts` | fails the run naming the FILE that left a process-global registry dirty, and restores the ones that can be restored at the same boundary |
92
- | `rerun-declarations.ts` | a test file loaded again in the same process (`bun test --rerun-each`) has what its module BODY declared — `entity()`, `job()` — forgotten first, so it declares afresh instead of `X_ENTITY_DUPLICATE` / `X_JOB_DUPLICATE`. What a test or hook registers is the file's own to undo |
92
+ | `rerun-declarations.ts` | a test file loaded again in the same process (`bun test --rerun-each`, CI's `flaky` job) has what IT declared — its body, its hooks, its tests — forgotten first, so it declares afresh instead of `X_*_DUPLICATE`. A name a module first evaluated meanwhile exports (`sendMailJob`) is that module's and stays. Automatic, through the preload |
93
+ | `rerun-registries.ts` | the registries it forgets in, each over its package's own lister + restore: jobs, services, entities, actions, queries, mails, mail layouts, OAuth providers — each only once its package is loaded |
94
+ | `rerun-modules.ts` | which modules evaluated since the body ended, and what they export |
93
95
  | `registry-snapshot.ts` | `captureProcessRegistries()` / `restoreProcessRegistries()` — the locale config, the catalogs, the permission set, the role map, the tasks and the declared measurement actor, put back as a file inherited them. A module-scope declaration evaluates once per process (`bun test` without `--isolate`, `As of 2026-08`), so a neighbour's `clearPermissions()` is otherwise permanent |
94
96
  | `registry-isolation.ts` | `isolateEntityRegistry()` — an empty entity registry, and the process's back after. Its own entry point (`@ultimat3/testing/registry-isolation`), never the barrel: it value-imports `@ultimat3/entity`, and the barrel is what a tier-0 test imports for `expect` |
95
97
  | `quiet-logs.ts` | a green run prints the reporter and nothing else: the framework's log lines go to a sink that drops them. `LOG_LEVEL=info bun test <file>` shows them — naming `LOG_LEVEL` is the one escape hatch, and a level above `info` filters what the TERMINAL shows, never what the logger emits (below). A test asserting on log output hands `structuredLogger({ level, writer })` its own writer, or installs its own with `installLogSink` and calls the release it returns |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.21.0",
3
+ "version": "31.22.1",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.21.0",
51
- "@ultimat3/ai": "31.21.0",
52
- "@ultimat3/auth": "31.21.0",
53
- "@ultimat3/cache": "31.21.0",
54
- "@ultimat3/core": "31.21.0",
55
- "@ultimat3/db": "31.21.0",
56
- "@ultimat3/entity": "31.21.0",
57
- "@ultimat3/http": "31.21.0",
58
- "@ultimat3/i18n": "31.21.0",
59
- "@ultimat3/jobs": "31.21.0",
60
- "@ultimat3/mail": "31.21.0",
61
- "@ultimat3/notify": "31.21.0",
62
- "@ultimat3/policy": "31.21.0",
63
- "@ultimat3/pwa": "31.21.0",
64
- "@ultimat3/query": "31.21.0",
65
- "@ultimat3/realtime": "31.21.0",
66
- "@ultimat3/render": "31.21.0",
67
- "@ultimat3/schema": "31.21.0",
68
- "@ultimat3/scraping": "31.21.0",
69
- "@ultimat3/seo": "31.21.0",
70
- "@ultimat3/time": "31.21.0"
50
+ "@ultimat3/action": "31.22.1",
51
+ "@ultimat3/ai": "31.22.1",
52
+ "@ultimat3/auth": "31.22.1",
53
+ "@ultimat3/cache": "31.22.1",
54
+ "@ultimat3/core": "31.22.1",
55
+ "@ultimat3/db": "31.22.1",
56
+ "@ultimat3/entity": "31.22.1",
57
+ "@ultimat3/http": "31.22.1",
58
+ "@ultimat3/i18n": "31.22.1",
59
+ "@ultimat3/jobs": "31.22.1",
60
+ "@ultimat3/mail": "31.22.1",
61
+ "@ultimat3/notify": "31.22.1",
62
+ "@ultimat3/policy": "31.22.1",
63
+ "@ultimat3/pwa": "31.22.1",
64
+ "@ultimat3/query": "31.22.1",
65
+ "@ultimat3/realtime": "31.22.1",
66
+ "@ultimat3/render": "31.22.1",
67
+ "@ultimat3/schema": "31.22.1",
68
+ "@ultimat3/scraping": "31.22.1",
69
+ "@ultimat3/seo": "31.22.1",
70
+ "@ultimat3/time": "31.22.1"
71
71
  }
72
72
  }
@@ -14,7 +14,8 @@ import {
14
14
  mergeSnapshots,
15
15
  restoreProcessRegistries,
16
16
  } from './registry-snapshot';
17
- import { frameworkDeclarationRegistries, rerunDeclarations } from './rerun-declarations';
17
+ import { rerunDeclarations } from './rerun-declarations';
18
+ import { frameworkDeclarationRegistries } from './rerun-registries';
18
19
 
19
20
  /**
20
21
  * What is REPORTED, and why only these two. Both are BOOT installs — `declareTags` takes the
@@ -51,9 +52,10 @@ import { frameworkDeclarationRegistries, rerunDeclarations } from './rerun-decla
51
52
  *
52
53
  * Every "no" needs the SAME two halves the two "yes" rows have: a reader and a writer in the owning
53
54
  * package (`restorePermissions` was added to `@ultimat3/policy` for exactly this), and one line
54
- * here. `@ultimat3/action`, `@ultimat3/query` and `@ultimat3/mail` publish a
55
- * lister and a reset but no restore, so the change is theirs first and this file's second — and it
56
- * has to land as ONE change, because the cost of the rest is a second edit of this same shape.
55
+ * here. `@ultimat3/action` (`restoreActions`, on `./loader`) and `@ultimat3/mail` (`restoreMails`,
56
+ * `restoreLayouts`) now publish both halves, for the rerun seam (`rerun-registries.ts`);
57
+ * `@ultimat3/query` still publishes a lister and a reset but no restore. Adding a row to the
58
+ * snapshot is a separate decision from having the writer: it changes what every later file sees.
57
59
  */
58
60
  export interface RegistrySample {
59
61
  readonly tags: readonly string[];
@@ -223,6 +225,7 @@ export function installRegistryLeakGuard(): void {
223
225
  runFileBoundary();
224
226
  close();
225
227
  pending = repoRelative(args.path);
228
+ // `loading` closes the previous file's window first (`fileEnd`).
226
229
  reruns.loading(args.path);
227
230
  return {
228
231
  contents: `${SAMPLE_BODY_START}${await Bun.file(args.path).text()}${SAMPLE_BASELINE}`,
@@ -235,6 +238,7 @@ export function installRegistryLeakGuard(): void {
235
238
  afterAll(() => {
236
239
  // The run's LAST file has no boundary after it: its undisposed island mounts end here.
237
240
  runBoundaryHooks();
241
+ reruns.fileEnd();
238
242
  close();
239
243
  if (leaks.length > 0) throw new RegistryLeakError({ leaks });
240
244
  });
@@ -1,12 +1,10 @@
1
1
  // One test file loaded AGAIN in the same process — `bun test --rerun-each`, CI's `flaky` job —
2
- // re-evaluates its own module body and nothing it imports. What that BODY declared last run is
3
- // forgotten as the file reloads, so `entity()` / `job()` at module scope declare afresh instead of
4
- // throwing X_ENTITY_DUPLICATE / X_JOB_DUPLICATE. `registry-leak-guard.ts` owns WHEN.
2
+ // re-evaluates its own module body and nothing it imports. What that FILE declared last run — its
3
+ // body, its hooks, its tests — is forgotten as it reloads, so it declares afresh instead of throwing
4
+ // X_*_DUPLICATE. `registry-leak-guard.ts` owns WHEN; `rerun-registries.ts` lists the registries.
5
5
 
6
- import type { RegistryEntry } from '@ultimat3/entity';
7
- import type { AnyJobHandle } from '@ultimat3/jobs';
8
- import { registeredJobs, restoreJobs } from '@ultimat3/jobs';
9
- import { loaded } from './per-test-reset';
6
+ import type { ModuleLedger } from './rerun-modules';
7
+ import { processModules } from './rerun-modules';
10
8
 
11
9
  /** A name-keyed process registry this module can read, prune and refill. */
12
10
  export interface DeclarationRegistry {
@@ -14,114 +12,146 @@ export interface DeclarationRegistry {
14
12
  names(): readonly string[];
15
13
  /** Removes `names`; answers what it removed, to hand back to `putBack`. */
16
14
  forget(names: ReadonlySet<string>): readonly unknown[];
17
- /** Re-registers each entry whose name is absent now; one the body declared again stays. */
15
+ /** Re-registers each entry whose name is absent now; one the file declared again stays. */
18
16
  putBack(entries: readonly unknown[]): void;
17
+ /** Whether one of `values` — a module's exports — is what `name` registered. */
18
+ exported(name: string, values: readonly unknown[]): boolean;
19
19
  }
20
20
 
21
21
  export interface RerunDeclarations {
22
- /** The file at `path` is about to evaluate: forget what its body declared on its last run. */
22
+ /** The file at `path` is about to evaluate: forget what it declared on its last run. */
23
23
  loading(path: string): void;
24
24
  /** Its imports have evaluated and its body is about to: the baseline its body adds to. */
25
25
  bodyStart(): void;
26
26
  /** Its body has evaluated: record what it declared; refill what this run did not redo. */
27
27
  bodyEnd(): void;
28
+ /** The file is over: refill what its hooks and tests did not redo, and remember the rest. */
29
+ fileEnd(): void;
28
30
  }
29
31
 
32
+ type KindNames = ReadonlyMap<string, ReadonlySet<string>>;
33
+
34
+ interface Mark {
35
+ readonly names: KindNames;
36
+ /** The modules evaluated when its body ended. */
37
+ readonly modules: ReadonlySet<string>;
38
+ }
39
+
40
+ const sample = (registries: readonly DeclarationRegistry[]): KindNames =>
41
+ new Map(registries.map((registry) => [registry.kind, new Set(registry.names())]));
42
+
43
+ const forgetAll = (
44
+ registries: readonly DeclarationRegistry[],
45
+ last: KindNames | undefined,
46
+ ): Map<string, readonly unknown[]> => {
47
+ const stash = new Map<string, readonly unknown[]>();
48
+ if (last === undefined) return stash;
49
+ for (const registry of registries) {
50
+ const names = last.get(registry.kind);
51
+ if (names !== undefined && names.size > 0) stash.set(registry.kind, registry.forget(names));
52
+ }
53
+ return stash;
54
+ };
55
+
56
+ const union = (a: KindNames, b: KindNames | undefined): KindNames => {
57
+ if (b === undefined) return a;
58
+ const merged = new Map<string, ReadonlySet<string>>(b);
59
+ for (const [kind, names] of a) merged.set(kind, new Set([...(b.get(kind) ?? []), ...names]));
60
+ return merged;
61
+ };
62
+
63
+ const putBackAll = (
64
+ registries: readonly DeclarationRegistry[],
65
+ stash: ReadonlyMap<string, readonly unknown[]>,
66
+ ): void => {
67
+ for (const registry of registries) {
68
+ const entries = stash.get(registry.kind);
69
+ if (entries !== undefined) registry.putBack(entries);
70
+ }
71
+ };
72
+
30
73
  /**
31
- * Only the BODY's window — after its imports, before its first hook — and never what a test or
32
- * hook registers: that is the file's own to undo, and a test's import inside a body would then be
33
- * forgotten for a module that will not evaluate again. A name forgotten and not declared again
34
- * (a top-level `await import()` that was a cache hit this time) is put back at `bodyEnd`.
74
+ * Two windows, two rules. The BODY — after its imports, before its first hook — is the file's own
75
+ * by construction. AFTER it, a hook or a test can also `await import()` a module that declares,
76
+ * and a module evaluates once per process: forgetting its names would leave the rerun without
77
+ * them. So a name added after the body is the file's unless a module first evaluated since then
78
+ * EXPORTS what it registered (`sendMailJob`, `baseLayout`). One such module that declares without
79
+ * exporting is the case this cannot see: its rerun goes without that name, and says so by failing.
80
+ * A forgotten name the rerun does not declare again goes back: the body's at `bodyEnd`, the rest
81
+ * at `fileEnd`. Nothing runs per test: one read at the body's end, one at the file's.
35
82
  */
36
83
  export function rerunDeclarations(
37
84
  registries: () => readonly DeclarationRegistry[],
85
+ modules: ModuleLedger = processModules,
38
86
  ): RerunDeclarations {
39
- const declaredBy = new Map<string, ReadonlyMap<string, ReadonlySet<string>>>();
87
+ const declaredBy = new Map<string, { readonly body: KindNames; readonly later: KindNames }>();
40
88
  let current: string | undefined;
41
- let baseline = new Map<string, ReadonlySet<string>>();
42
- let forgotten = new Map<string, readonly unknown[]>();
89
+ let baseline: KindNames = new Map();
90
+ let body: KindNames | undefined;
91
+ let mark: Mark | undefined;
92
+ let forgottenBody = new Map<string, readonly unknown[]>();
93
+ let forgottenLater = new Map<string, readonly unknown[]>();
94
+ /** What the file added after its body: not what a module it evaluated meanwhile exports. */
95
+ const addedSinceBody = (live: readonly DeclarationRegistry[]): KindNames => {
96
+ const added = new Map<string, ReadonlySet<string>>();
97
+ if (mark === undefined || current === undefined) return added;
98
+ let exports: readonly unknown[] | undefined;
99
+ for (const registry of live) {
100
+ const before = mark.names.get(registry.kind) ?? new Set<string>();
101
+ const gained = registry.names().filter((name) => !before.has(name));
102
+ if (gained.length === 0) continue;
103
+ // Read once, and only when something was gained: ~1 ms over a large module cache.
104
+ exports ??= modules.exportsSince(mark.modules, current);
105
+ const own = exports;
106
+ added.set(registry.kind, new Set(gained.filter((name) => !registry.exported(name, own))));
107
+ }
108
+ return added;
109
+ };
110
+ const fileEnd = (): void => {
111
+ if (current === undefined) return;
112
+ const live = registries();
113
+ const last = declaredBy.get(current);
114
+ const later = addedSinceBody(live);
115
+ // A body that threw never reached `bodyEnd`: what was forgotten for it goes back here, and its
116
+ // last complete record stands in for the names it did not get to report.
117
+ putBackAll(live, forgottenBody);
118
+ putBackAll(live, forgottenLater);
119
+ declaredBy.set(current, {
120
+ body: body ?? last?.body ?? new Map(),
121
+ // Kept from the last run too: a test this run skipped (`-t`) declares again on the next.
122
+ later: union(later, last?.later),
123
+ });
124
+ current = undefined;
125
+ body = undefined;
126
+ mark = undefined;
127
+ forgottenBody = new Map();
128
+ forgottenLater = new Map();
129
+ };
43
130
  return {
44
131
  loading(path) {
132
+ fileEnd();
45
133
  current = path;
46
- forgotten = new Map();
47
134
  const last = declaredBy.get(path);
48
- if (last === undefined) return;
49
- for (const registry of registries()) {
50
- const names = last.get(registry.kind);
51
- if (names !== undefined && names.size > 0) {
52
- forgotten.set(registry.kind, registry.forget(names));
53
- }
54
- }
135
+ forgottenBody = forgetAll(registries(), last?.body);
136
+ forgottenLater = forgetAll(registries(), last?.later);
55
137
  },
56
138
  bodyStart() {
57
- baseline = new Map(
58
- registries().map((registry) => [registry.kind, new Set(registry.names())]),
59
- );
139
+ baseline = sample(registries());
60
140
  },
61
141
  bodyEnd() {
62
142
  if (current === undefined) return;
143
+ const live = registries();
144
+ const now = sample(live);
63
145
  const declared = new Map<string, ReadonlySet<string>>();
64
- for (const registry of registries()) {
65
- const before = baseline.get(registry.kind) ?? new Set<string>();
66
- declared.set(registry.kind, new Set(registry.names().filter((name) => !before.has(name))));
67
- const stash = forgotten.get(registry.kind);
68
- if (stash !== undefined) registry.putBack(stash);
146
+ for (const [kind, names] of now) {
147
+ const before = baseline.get(kind) ?? new Set<string>();
148
+ declared.set(kind, new Set([...names].filter((name) => !before.has(name))));
69
149
  }
70
- declaredBy.set(current, declared);
71
- current = undefined;
72
- forgotten = new Map();
150
+ body = declared;
151
+ putBackAll(live, forgottenBody);
152
+ forgottenBody = new Map();
153
+ mark = { names: sample(live), modules: modules.snapshot() };
73
154
  },
155
+ fileEnd,
74
156
  };
75
157
  }
76
-
77
- /** Jobs: `@ultimat3/jobs` is already in every test's graph (`registry-snapshot.ts` imports it). */
78
- const jobRegistry: DeclarationRegistry = {
79
- kind: 'job',
80
- names: () => registeredJobs().map((handle) => handle.name),
81
- forget(names) {
82
- const all = registeredJobs();
83
- restoreJobs(all.filter((handle) => !names.has(handle.name)));
84
- return all.filter((handle) => names.has(handle.name));
85
- },
86
- putBack(entries) {
87
- const live = registeredJobs();
88
- const present = new Set(live.map((handle) => handle.name));
89
- const missing = (entries as readonly AnyJobHandle[]).filter((h) => !present.has(h.name));
90
- if (missing.length > 0) restoreJobs([...live, ...missing]);
91
- },
92
- };
93
-
94
- interface EntityRegistryModule {
95
- readonly registeredEntities: () => readonly RegistryEntry[];
96
- readonly registerEntity: (entry: RegistryEntry) => RegistryEntry;
97
- readonly getEntity: (name: string) => RegistryEntry | undefined;
98
- readonly clearRegistry: () => void;
99
- }
100
-
101
- /**
102
- * Entities, only once something in this process loaded `@ultimat3/entity`: importing it here would
103
- * put the entity registry into every `packages/core` test (`registry-isolation.ts`'s reason).
104
- */
105
- const entityRegistry = (module: EntityRegistryModule): DeclarationRegistry => ({
106
- kind: 'entity',
107
- names: () => module.registeredEntities().map((entry) => entry.name),
108
- forget(names) {
109
- const all = module.registeredEntities();
110
- module.clearRegistry();
111
- for (const entry of all) if (!names.has(entry.name)) module.registerEntity(entry);
112
- return all.filter((entry) => names.has(entry.name));
113
- },
114
- putBack(entries) {
115
- for (const entry of entries as readonly RegistryEntry[]) {
116
- if (module.getEntity(entry.name) === undefined) module.registerEntity(entry);
117
- }
118
- },
119
- });
120
-
121
- /** The registries a framework test file declares into at module scope, as loaded right now. */
122
- export function frameworkDeclarationRegistries(): readonly DeclarationRegistry[] {
123
- const path = loaded('@ultimat3/entity', 'registry.ts');
124
- if (path === undefined) return [jobRegistry];
125
- // why: synchronous, as the body hooks are; the module is in the cache, so this evaluates nothing.
126
- return [jobRegistry, entityRegistry(require(path) as EntityRegistryModule)];
127
- }
@@ -0,0 +1,49 @@
1
+ // Which modules evaluated between two points of one test file, and what they export: how the
2
+ // rerun seam tells a declaration a test made from one a module it imported made, since a module
3
+ // evaluates once per process and a rerun's `await import()` of it declares nothing.
4
+
5
+ /** The process's evaluated modules at one instant, and what the ones after it export. */
6
+ export interface ModuleLedger {
7
+ /** Every module evaluated so far, ESM included. ~1 ms at 2,700: read once per file, then on a gain. */
8
+ snapshot(): ReadonlySet<string>;
9
+ /** Every value the modules evaluated since `before` export — arrays one level deep. */
10
+ exportsSince(before: ReadonlySet<string>, self: string): readonly unknown[];
11
+ }
12
+
13
+ /**
14
+ * The namespace the cache already holds for `key`. Never `require(key)`: on a `?x-reload=` entry a
15
+ * loader plugin made, that goes back through the plugin, whose async read of a fixture app since
16
+ * deleted was an unhandled ENOENT at the file's end (`serve-web.test.ts`).
17
+ */
18
+ const namespaceOf = (key: string): unknown => {
19
+ try {
20
+ return require.cache[key]?.exports;
21
+ } catch {
22
+ // An entry whose namespace cannot be read (one still evaluating) exports nothing this seam
23
+ // could match a declaration to.
24
+ return undefined;
25
+ }
26
+ };
27
+
28
+ const valuesOf = (namespace: unknown): readonly unknown[] => {
29
+ if (namespace === null || typeof namespace !== 'object') return [];
30
+ const values: unknown[] = [];
31
+ for (const value of Object.values(namespace)) {
32
+ values.push(value);
33
+ if (Array.isArray(value)) values.push(...value);
34
+ }
35
+ return values;
36
+ };
37
+
38
+ export const processModules: ModuleLedger = {
39
+ snapshot: () => new Set(Object.keys(require.cache)),
40
+ exportsSince(before, self) {
41
+ const values: unknown[] = [];
42
+ for (const key of Object.keys(require.cache)) {
43
+ // The test file enters the cache once its body is done: its exports are its own.
44
+ if (before.has(key) || key === self) continue;
45
+ values.push(...valuesOf(namespaceOf(key)));
46
+ }
47
+ return values;
48
+ },
49
+ };
@@ -0,0 +1,213 @@
1
+ // The process registries a framework test file declares into, each as `rerun-declarations.ts`
2
+ // reads one: a lister and an exact restore from the package that owns it. Only those loaded by
3
+ // now — importing a package to forget its names would put its graph into every `packages/core`
4
+ // test (`registry-isolation.ts`'s reason) — and each one read through the `require` cache.
5
+
6
+ import type { AnyAction, listActions } from '@ultimat3/action';
7
+ import type { restoreActions } from '@ultimat3/action/loader';
8
+ import type {
9
+ OAuthProvider,
10
+ registeredOAuthProviders,
11
+ restoreOAuthProviders,
12
+ } from '@ultimat3/auth';
13
+ import type { ServiceRegistration } from '@ultimat3/core';
14
+ import { registeredServices, restoreServices } from '@ultimat3/core';
15
+ import type {
16
+ clearRegistry,
17
+ RegistryEntry,
18
+ registerEntity,
19
+ registeredEntities,
20
+ } from '@ultimat3/entity';
21
+ import type { AnyJobHandle } from '@ultimat3/jobs';
22
+ import { registeredJobs, restoreJobs } from '@ultimat3/jobs';
23
+ import type {
24
+ AnyMailDefinition,
25
+ LayoutRegistration,
26
+ layoutFor,
27
+ registeredLayouts,
28
+ registeredMails,
29
+ restoreLayouts,
30
+ restoreMails,
31
+ } from '@ultimat3/mail';
32
+ import type { AnyQuery, listQueries, resetQueries } from '@ultimat3/query';
33
+ import type { registerQuery } from '@ultimat3/query/loader';
34
+ import { loaded } from './per-test-reset';
35
+ import type { DeclarationRegistry } from './rerun-declarations';
36
+
37
+ /**
38
+ * One registry over its package's own `registeredX()` / `restoreX(entries)` pair. `exportedAs` is
39
+ * what a module that declared `entry` exports for it: the entry itself unless the registry wraps.
40
+ */
41
+ export function listedRegistry<E>(
42
+ kind: string,
43
+ read: () => readonly E[],
44
+ nameOf: (entry: E) => string,
45
+ restore: (entries: readonly E[]) => void,
46
+ exportedAs: (entry: E, value: unknown) => boolean = (entry, value) => value === entry,
47
+ ): DeclarationRegistry {
48
+ return {
49
+ kind,
50
+ names: () => read().map(nameOf),
51
+ forget(names) {
52
+ const all = read();
53
+ restore(all.filter((entry) => !names.has(nameOf(entry))));
54
+ return all.filter((entry) => names.has(nameOf(entry)));
55
+ },
56
+ putBack(entries) {
57
+ const live = read();
58
+ const present = new Set(live.map(nameOf));
59
+ const missing = (entries as readonly E[]).filter((entry) => !present.has(nameOf(entry)));
60
+ if (missing.length > 0) restore([...live, ...missing]);
61
+ },
62
+ exported(name, values) {
63
+ const entry = read().find((candidate) => nameOf(candidate) === name);
64
+ return entry !== undefined && values.some((value) => exportedAs(entry, value));
65
+ },
66
+ };
67
+ }
68
+
69
+ /** Jobs: `@ultimat3/jobs` is already in every test's graph (`registry-snapshot.ts` imports it). */
70
+ const jobRegistry = listedRegistry<AnyJobHandle>(
71
+ 'job',
72
+ registeredJobs,
73
+ (handle) => handle.name,
74
+ restoreJobs,
75
+ );
76
+
77
+ /** Services: `@ultimat3/core` is in every graph. */
78
+ const serviceRegistry = listedRegistry<ServiceRegistration>(
79
+ 'service',
80
+ registeredServices,
81
+ (entry) => entry.name,
82
+ restoreServices,
83
+ (entry, value) => value === entry.factory,
84
+ );
85
+
86
+ const isProvider = (
87
+ value: unknown,
88
+ ): value is { readonly id: unknown; readonly tokenUrl: unknown } =>
89
+ typeof value === 'object' && value !== null && 'id' in value && 'tokenUrl' in value;
90
+
91
+ interface EntityModule {
92
+ readonly registeredEntities: typeof registeredEntities;
93
+ readonly registerEntity: typeof registerEntity;
94
+ readonly clearRegistry: typeof clearRegistry;
95
+ }
96
+ interface ActionModule {
97
+ readonly listActions: typeof listActions;
98
+ readonly restoreActions: typeof restoreActions;
99
+ }
100
+ interface QueryModule {
101
+ readonly listQueries: typeof listQueries;
102
+ readonly resetQueries: typeof resetQueries;
103
+ readonly registerQuery: typeof registerQuery;
104
+ }
105
+ interface MailModule {
106
+ readonly registeredMails: typeof registeredMails;
107
+ readonly restoreMails: typeof restoreMails;
108
+ }
109
+ interface LayoutModule {
110
+ readonly registeredLayouts: typeof registeredLayouts;
111
+ readonly layoutFor: typeof layoutFor;
112
+ readonly restoreLayouts: typeof restoreLayouts;
113
+ }
114
+ interface OAuthModule {
115
+ readonly registeredOAuthProviders: typeof registeredOAuthProviders;
116
+ readonly restoreOAuthProviders: typeof restoreOAuthProviders;
117
+ }
118
+
119
+ /**
120
+ * `file` of `pkg` when this process already loaded it. Synchronous, as the body hooks are: the
121
+ * module is in the cache, so `require` evaluates nothing.
122
+ */
123
+ function moduleOf<M>(pkg: string, file: string): M | undefined {
124
+ const path = loaded(pkg, file);
125
+ return path === undefined ? undefined : (require(path) as M);
126
+ }
127
+
128
+ /** The entity registry has no exact restore of its own; clear-and-register is one. */
129
+ const entityRegistry = (module: EntityModule): DeclarationRegistry =>
130
+ listedRegistry<RegistryEntry>(
131
+ 'entity',
132
+ module.registeredEntities,
133
+ (entry) => entry.name,
134
+ (entries) => {
135
+ module.clearRegistry();
136
+ for (const entry of entries) module.registerEntity(entry);
137
+ },
138
+ // A module exports the entity, which the registry entry carries as `core`.
139
+ (entry, value) => value === entry || (entry.core !== undefined && value === entry.core),
140
+ );
141
+
142
+ /** Nor has the query registry; a reset that clears only the map, and each one back by name. */
143
+ const queryRegistry = (module: QueryModule): DeclarationRegistry =>
144
+ listedRegistry<AnyQuery>(
145
+ 'query',
146
+ module.listQueries,
147
+ (entry) => entry.name,
148
+ (entries) => {
149
+ module.resetQueries();
150
+ for (const entry of entries) module.registerQuery(entry.name, entry);
151
+ },
152
+ );
153
+
154
+ /** Layouts are listed by name; the entry handed back is the name with what it resolves to. */
155
+ const layoutRegistry = (module: LayoutModule): DeclarationRegistry =>
156
+ listedRegistry<LayoutRegistration>(
157
+ 'mail-layout',
158
+ () =>
159
+ module.registeredLayouts().flatMap((name) => {
160
+ const layout = module.layoutFor(name);
161
+ return layout === undefined ? [] : [{ name, layout }];
162
+ }),
163
+ (entry) => entry.name,
164
+ module.restoreLayouts,
165
+ (entry, value) => value === entry.layout,
166
+ );
167
+
168
+ /** The registries a framework test file declares into, as loaded right now. */
169
+ export function frameworkDeclarationRegistries(): readonly DeclarationRegistry[] {
170
+ const registries = [jobRegistry, serviceRegistry];
171
+ const entities = moduleOf<EntityModule>('@ultimat3/entity', 'registry.ts');
172
+ if (entities !== undefined) registries.push(entityRegistry(entities));
173
+ const actions = moduleOf<ActionModule>('@ultimat3/action', 'registry.ts');
174
+ if (actions !== undefined) {
175
+ registries.push(
176
+ listedRegistry<AnyAction>(
177
+ 'action',
178
+ actions.listActions,
179
+ (entry) => entry.name,
180
+ actions.restoreActions,
181
+ ),
182
+ );
183
+ }
184
+ const queries = moduleOf<QueryModule>('@ultimat3/query', 'registry.ts');
185
+ if (queries !== undefined) registries.push(queryRegistry(queries));
186
+ const mails = moduleOf<MailModule>('@ultimat3/mail', 'mail.ts');
187
+ if (mails !== undefined) {
188
+ registries.push(
189
+ listedRegistry<AnyMailDefinition>(
190
+ 'mail',
191
+ mails.registeredMails,
192
+ (entry) => entry.id,
193
+ mails.restoreMails,
194
+ ),
195
+ );
196
+ }
197
+ const layouts = moduleOf<LayoutModule>('@ultimat3/mail', 'layout.ts');
198
+ if (layouts !== undefined) registries.push(layoutRegistry(layouts));
199
+ const oauth = moduleOf<OAuthModule>('@ultimat3/auth', 'oauth-registry.ts');
200
+ if (oauth !== undefined) {
201
+ registries.push(
202
+ listedRegistry<OAuthProvider>(
203
+ 'oauth-provider',
204
+ oauth.registeredOAuthProviders,
205
+ (entry) => entry.id,
206
+ oauth.restoreOAuthProviders,
207
+ // Sealed on the way in, so the registry holds a copy of what the module exports.
208
+ (entry, value) => isProvider(value) && value.id === entry.id,
209
+ ),
210
+ );
211
+ }
212
+ return registries;
213
+ }