@htilabs/platform-common-models 0.2.0-beta.4 → 0.3.0-beta.5
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/README.md +38 -0
- package/dist/constants/index.cjs +0 -843
- package/dist/constants/index.cjs.map +1 -1
- package/dist/constants/index.d.cts +146 -5
- package/dist/constants/index.d.ts +146 -5
- package/dist/constants/index.js +0 -786
- package/dist/constants/index.js.map +1 -1
- package/dist/{platform-role-AHv1l5Og.d.cts → cvcEntry-wqktWfzE.d.cts} +231 -37
- package/dist/{platform-role-AHv1l5Og.d.ts → cvcEntry-wqktWfzE.d.ts} +231 -37
- package/dist/cvcs/index.cjs +2184 -0
- package/dist/cvcs/index.cjs.map +1 -0
- package/dist/cvcs/index.d.cts +2384 -0
- package/dist/cvcs/index.d.ts +2384 -0
- package/dist/cvcs/index.js +2154 -0
- package/dist/cvcs/index.js.map +1 -0
- package/dist/index--NCIPluF.d.cts +378 -0
- package/dist/index-CFOrHA8l.d.ts +378 -0
- package/dist/index.cjs +2962 -843
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +217 -3
- package/dist/index.d.ts +217 -3
- package/dist/index.js +2934 -786
- package/dist/index.js.map +1 -1
- package/dist/models/index.cjs +211 -0
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.d.cts +3 -292
- package/dist/models/index.d.ts +3 -292
- package/dist/models/index.js +209 -0
- package/dist/models/index.js.map +1 -1
- package/dist/{platform-auth-BTbQIY3b.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -297
- package/dist/{platform-auth-BTbQIY3b.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -297
- package/dist/schemas/index.cjs +195 -729
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +11 -11
- package/dist/schemas/index.d.ts +11 -11
- package/dist/schemas/index.js +189 -729
- package/dist/schemas/index.js.map +1 -1
- package/dist/services/index.cjs +1442 -0
- package/dist/services/index.cjs.map +1 -0
- package/dist/services/index.d.cts +305 -0
- package/dist/services/index.d.ts +305 -0
- package/dist/services/index.js +1417 -0
- package/dist/services/index.js.map +1 -0
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/validation/index.cjs +261 -0
- package/dist/validation/index.cjs.map +1 -0
- package/dist/validation/index.d.cts +251 -0
- package/dist/validation/index.d.ts +251 -0
- package/dist/validation/index.js +228 -0
- package/dist/validation/index.js.map +1 -0
- package/package.json +36 -12
- package/src/__tests__/__snapshots__/cvc-sot.snap +22 -0
- package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
- package/src/__tests__/cvc-structural.test.ts +130 -0
- package/src/constants/ic.ts +0 -925
- package/src/constants/service-catalog.ts +146 -4
- package/src/cvcs/index.ts +31 -0
- package/src/cvcs/missingness.v1.0.0.json +50 -0
- package/src/cvcs/serviceCategories.v1.0.0.json +1947 -0
- package/src/cvcs/serviceMechanisms.v1.0.0.json +47 -0
- package/src/cvcs/serviceStates.v1.0.0.json +106 -0
- package/src/generated/cvc-enums.ts +215 -0
- package/src/index.ts +61 -1
- package/src/models/cvcEntryModel.ts +32 -0
- package/src/models/cvcRegistryModel.ts +35 -0
- package/src/models/index.ts +8 -0
- package/src/schemas/cvcEntry.ts +158 -0
- package/src/schemas/cvcRegistry.ts +149 -0
- package/src/schemas/index.ts +16 -0
- package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
- package/src/services/cvcRegistryService.ts +729 -0
- package/src/services/index.ts +21 -0
- package/src/validation/cvc.ts +414 -0
- package/src/validation/index.ts +15 -0
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @htilabs/platform-common-models — CvcRegistryService
|
|
3
|
+
*
|
|
4
|
+
* Runtime API for resolving Controlled Vocabulary (CVC) data through a
|
|
5
|
+
* registry. The service is the canonical entry point used by Thread, PAVE,
|
|
6
|
+
* and any other consumer that needs "give me the entries that are live in
|
|
7
|
+
* scope X right now". It hides three concerns from callers:
|
|
8
|
+
*
|
|
9
|
+
* 1. **Scope resolution.** Callers ask in terms of `{application, agencyId}`;
|
|
10
|
+
* the service walks the agency-specific → app-specific → platform-default
|
|
11
|
+
* fallback chain to find the active registry.
|
|
12
|
+
* 2. **Inheritance.** A registry may be `basedOn` another registry. The
|
|
13
|
+
* service merges the parent's pinned `cvcVersions` under the child's,
|
|
14
|
+
* then applies the child's own `excludedEntries` / `includedEntries`
|
|
15
|
+
* overrides on top of the merged entry pool.
|
|
16
|
+
* 3. **Caching.** Resolved entry sets are memoised per active registry, and
|
|
17
|
+
* flushed on `activate()` / `deprecate()` so that the next read picks
|
|
18
|
+
* up the new pin.
|
|
19
|
+
*
|
|
20
|
+
* Locked spec reference:
|
|
21
|
+
* §9.1.1 — Entry resolution logic (default / blacklist / whitelist modes)
|
|
22
|
+
* §9.1.2 — `basedOn` inheritance resolution
|
|
23
|
+
* §9.6 — Service API surface
|
|
24
|
+
* /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md
|
|
25
|
+
*
|
|
26
|
+
* The pure helpers (`cascadeExclusions`, `applyEntryOverrides`,
|
|
27
|
+
* `resolveRegistryWithInheritance`) are exported alongside the class so
|
|
28
|
+
* they can be unit-tested without a Mongoose connection.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { Types } from "mongoose";
|
|
32
|
+
import type { Connection, Model } from "mongoose";
|
|
33
|
+
|
|
34
|
+
import { cvcRegistryModel, cvcEntryModel } from "../models/index.js";
|
|
35
|
+
|
|
36
|
+
// ─── Public types ────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Plain document shape for a `cvc_entries` row. Mirrors the Mongoose schema
|
|
40
|
+
* in `schemas/cvcEntry.ts` (co-am3.2) and the locked spec §9.1.2 interface.
|
|
41
|
+
*
|
|
42
|
+
* Defined locally rather than imported because the schema-derived
|
|
43
|
+
* `InferRawDocType<typeof schema>` types in `schemas/cvcEntry.ts` widen to
|
|
44
|
+
* the Schema instance type — they're not usable as document shapes. This
|
|
45
|
+
* interface is the canonical document contract for the service layer.
|
|
46
|
+
*/
|
|
47
|
+
export interface ICvcEntry {
|
|
48
|
+
domain: string;
|
|
49
|
+
version: string;
|
|
50
|
+
code: string;
|
|
51
|
+
key: string;
|
|
52
|
+
title: string;
|
|
53
|
+
selectable: boolean;
|
|
54
|
+
parentCode: string | null;
|
|
55
|
+
childCodes: string[];
|
|
56
|
+
definition: string | null;
|
|
57
|
+
meta?: Record<string, unknown> | null;
|
|
58
|
+
createdAt?: Date;
|
|
59
|
+
updatedAt?: Date;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Plain document shape for a `cvc_registries` row. Mirrors the Mongoose
|
|
64
|
+
* schema in `schemas/cvcRegistry.ts` (co-am3.2) and the locked spec §9.1.1
|
|
65
|
+
* interface. See {@link ICvcEntry} for why this is defined locally.
|
|
66
|
+
*
|
|
67
|
+
* `cvcVersions` is typed as either a `Map` (raw mongoose hydrated doc) or
|
|
68
|
+
* a plain object (from `.lean()` / `.toObject()`). The pure helpers
|
|
69
|
+
* normalise both forms via {@link cvcVersionsToRecord}.
|
|
70
|
+
*/
|
|
71
|
+
export interface ICvcRegistry {
|
|
72
|
+
_id: Types.ObjectId;
|
|
73
|
+
version: string;
|
|
74
|
+
name: string;
|
|
75
|
+
application: string | null;
|
|
76
|
+
agencyId: Types.ObjectId | null;
|
|
77
|
+
status: "draft" | "active" | "deprecated";
|
|
78
|
+
dateActivated?: Date | null;
|
|
79
|
+
dateDeactivated?: Date | null;
|
|
80
|
+
cvcVersions: Map<string, string> | Record<string, string>;
|
|
81
|
+
excludedEntries: string[];
|
|
82
|
+
includedEntries: string[];
|
|
83
|
+
basedOn: Types.ObjectId | null;
|
|
84
|
+
createdAt?: Date;
|
|
85
|
+
updatedAt?: Date;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Lookup scope for convenience methods. `null`/`undefined` widens the scope:
|
|
90
|
+
* a missing `application` matches the platform-default registry; a missing
|
|
91
|
+
* `agencyId` matches the application-wide registry.
|
|
92
|
+
*
|
|
93
|
+
* Locked spec §9.6 — scope hierarchy.
|
|
94
|
+
*/
|
|
95
|
+
export interface RegistryScope {
|
|
96
|
+
application?: string | null;
|
|
97
|
+
agencyId?: Types.ObjectId | null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Options accepted by the service constructor. Kept as a single object so
|
|
102
|
+
* future toggles (telemetry, custom cache, etc.) can be added without
|
|
103
|
+
* breaking the call site.
|
|
104
|
+
*/
|
|
105
|
+
export interface CvcRegistryServiceOptions {
|
|
106
|
+
/**
|
|
107
|
+
* When `true` (default), `getActiveRegistry` walks the
|
|
108
|
+
* agency → application → platform fallback chain. When `false`, only the
|
|
109
|
+
* exact requested scope is consulted.
|
|
110
|
+
*/
|
|
111
|
+
scopeFallback?: boolean;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
// ─── Pure helpers (exported for unit tests) ──────────────────────────────────
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Convert a Mongoose `Map<string, string>` (or a plain object that came from
|
|
119
|
+
* `.toObject()`) into a `Record<string, string>`. The Mongoose schema stores
|
|
120
|
+
* `cvcVersions` as a `Map`, but the resolution logic in the locked spec is
|
|
121
|
+
* written against `Object.entries(...)` — this normaliser bridges the gap
|
|
122
|
+
* once at the entry to the pure layer.
|
|
123
|
+
*
|
|
124
|
+
* @param versions - Either a Map (raw mongoose doc) or a plain record
|
|
125
|
+
* @returns A plain object whose keys are CVC domains and values are versions
|
|
126
|
+
*/
|
|
127
|
+
export function cvcVersionsToRecord(
|
|
128
|
+
versions: Map<string, string> | Record<string, string> | undefined | null,
|
|
129
|
+
): Record<string, string> {
|
|
130
|
+
if (!versions) return {};
|
|
131
|
+
if (versions instanceof Map) {
|
|
132
|
+
return Object.fromEntries(versions.entries());
|
|
133
|
+
}
|
|
134
|
+
return { ...versions };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Compute the cascading-exclusion set for a CVC entry pool.
|
|
139
|
+
*
|
|
140
|
+
* Cascading exclusion (locked spec §9.1.1) treats the entry tree as a DAG of
|
|
141
|
+
* `parentCode → code` edges. Excluding a node implicitly excludes every
|
|
142
|
+
* descendant reachable from it. The result set always contains the original
|
|
143
|
+
* `excludedCodes` plus every transitively-reachable child.
|
|
144
|
+
*
|
|
145
|
+
* Implemented as breadth-first walk over a parent → children index built
|
|
146
|
+
* from the entry pool. Time/space complexity is `O(N)` in the entry count.
|
|
147
|
+
*
|
|
148
|
+
* @param excludedCodes - Codes the registry explicitly excludes
|
|
149
|
+
* @param entries - The entry pool to cascade through
|
|
150
|
+
* @returns Set containing every excluded code plus every descendant
|
|
151
|
+
*/
|
|
152
|
+
export function cascadeExclusions(
|
|
153
|
+
excludedCodes: ReadonlySet<string>,
|
|
154
|
+
entries: readonly ICvcEntry[],
|
|
155
|
+
): Set<string> {
|
|
156
|
+
const result = new Set<string>(excludedCodes);
|
|
157
|
+
|
|
158
|
+
// Build parent → children adjacency once. Entries with `parentCode === null`
|
|
159
|
+
// are tree roots and contribute no edges.
|
|
160
|
+
const childMap = new Map<string, string[]>();
|
|
161
|
+
for (const entry of entries) {
|
|
162
|
+
if (entry.parentCode) {
|
|
163
|
+
const siblings = childMap.get(entry.parentCode);
|
|
164
|
+
if (siblings) {
|
|
165
|
+
siblings.push(entry.code);
|
|
166
|
+
} else {
|
|
167
|
+
childMap.set(entry.parentCode, [entry.code]);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// BFS from every initially-excluded code. The visited check (`!result.has`)
|
|
173
|
+
// both prevents infinite loops on accidental cycles and ensures O(N) work.
|
|
174
|
+
const queue: string[] = [...excludedCodes];
|
|
175
|
+
while (queue.length > 0) {
|
|
176
|
+
const code = queue.shift() as string;
|
|
177
|
+
const children = childMap.get(code);
|
|
178
|
+
if (!children) continue;
|
|
179
|
+
for (const childCode of children) {
|
|
180
|
+
if (!result.has(childCode)) {
|
|
181
|
+
result.add(childCode);
|
|
182
|
+
queue.push(childCode);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return result;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Apply a registry's `excludedEntries` / `includedEntries` overrides to a
|
|
192
|
+
* pre-loaded entry pool. Implements the four-mode table from locked spec
|
|
193
|
+
* §9.1.1:
|
|
194
|
+
*
|
|
195
|
+
* | excludedEntries | includedEntries | Mode |
|
|
196
|
+
* | --------------- | --------------- | ------------------ |
|
|
197
|
+
* | empty | empty | Default (all) |
|
|
198
|
+
* | has values | empty | Blacklist |
|
|
199
|
+
* | empty | has values | Whitelist |
|
|
200
|
+
* | has values | has values | Blacklist + override |
|
|
201
|
+
*
|
|
202
|
+
* Inclusion always wins over exclusion in the override mode — that's how
|
|
203
|
+
* agencies pull a single descendant back in after excluding its parent.
|
|
204
|
+
*
|
|
205
|
+
* @param excludedEntries - Codes the registry excludes (cascades to children)
|
|
206
|
+
* @param includedEntries - Codes the registry force-includes (override or whitelist)
|
|
207
|
+
* @param entries - The merged entry pool from all pinned domains
|
|
208
|
+
* @returns A new array containing only the entries selected by the overrides
|
|
209
|
+
*/
|
|
210
|
+
export function applyEntryOverrides(
|
|
211
|
+
excludedEntries: readonly string[] | null | undefined,
|
|
212
|
+
includedEntries: readonly string[] | null | undefined,
|
|
213
|
+
entries: readonly ICvcEntry[],
|
|
214
|
+
): ICvcEntry[] {
|
|
215
|
+
const excluded = new Set(excludedEntries ?? []);
|
|
216
|
+
const included = new Set(includedEntries ?? []);
|
|
217
|
+
const hasExclusions = excluded.size > 0;
|
|
218
|
+
const hasInclusions = included.size > 0;
|
|
219
|
+
|
|
220
|
+
// Default mode: no overrides at all → return the pool unchanged.
|
|
221
|
+
if (!hasExclusions && !hasInclusions) {
|
|
222
|
+
return [...entries];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Whitelist mode: start from empty and pull in only the listed codes.
|
|
226
|
+
if (!hasExclusions && hasInclusions) {
|
|
227
|
+
return entries.filter((entry) => included.has(entry.code));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Blacklist mode (with optional override): cascade the exclusion set, then
|
|
231
|
+
// filter the pool, letting any explicitly-included code punch through.
|
|
232
|
+
const cascadedExclusions = cascadeExclusions(excluded, entries);
|
|
233
|
+
return entries.filter((entry) => {
|
|
234
|
+
if (included.has(entry.code)) return true;
|
|
235
|
+
if (cascadedExclusions.has(entry.code)) return false;
|
|
236
|
+
return true;
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Loader signature: fetch a registry document by id. Used by
|
|
242
|
+
* `resolveRegistryWithInheritance` to walk the `basedOn` pointer without
|
|
243
|
+
* needing a live Mongoose connection.
|
|
244
|
+
*/
|
|
245
|
+
export type RegistryLoader = (
|
|
246
|
+
id: Types.ObjectId,
|
|
247
|
+
) => Promise<ICvcRegistry | null>;
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Loader signature: fetch all entries for a `(domain, version)` tuple. Used
|
|
251
|
+
* by `resolveRegistryWithInheritance` so the pure resolution layer can be
|
|
252
|
+
* tested with in-memory fixtures instead of a real `cvc_entries` collection.
|
|
253
|
+
*/
|
|
254
|
+
export type EntryLoader = (
|
|
255
|
+
domain: string,
|
|
256
|
+
version: string,
|
|
257
|
+
) => Promise<ICvcEntry[]>;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Resolve a registry into its effective `(mergedVersions, entries)` pair,
|
|
261
|
+
* walking exactly one level of `basedOn` inheritance per locked spec §9.1.2.
|
|
262
|
+
*
|
|
263
|
+
* The spec constrains `basedOn` chains to two levels (base → child); the
|
|
264
|
+
* implementation enforces that constraint by **only** consulting the
|
|
265
|
+
* immediate parent. Deeper grandparents are ignored even if a misconfigured
|
|
266
|
+
* registry chains further — this matches the contract that downstream
|
|
267
|
+
* callers see at most one merge step.
|
|
268
|
+
*
|
|
269
|
+
* Resolution order (locked spec §9.1.2):
|
|
270
|
+
* 1. Start with the child's own `cvcVersions`
|
|
271
|
+
* 2. If the child has `basedOn`, load the parent and overlay the child's
|
|
272
|
+
* `cvcVersions` on top of the parent's (child wins per-domain)
|
|
273
|
+
* 3. Load entries for every merged `(domain, version)` tuple
|
|
274
|
+
* 4. Apply the child's own `excludedEntries` / `includedEntries` to the
|
|
275
|
+
* merged pool — inheritance does not propagate overrides
|
|
276
|
+
*
|
|
277
|
+
* @param registry - The child registry being resolved
|
|
278
|
+
* @param loadRegistry - Loader for the parent registry (only called if `basedOn` is set)
|
|
279
|
+
* @param loadEntries - Loader for entry pools by (domain, version)
|
|
280
|
+
* @returns The merged version pins and the resolved effective entry list
|
|
281
|
+
*/
|
|
282
|
+
export async function resolveRegistryWithInheritance(
|
|
283
|
+
registry: ICvcRegistry,
|
|
284
|
+
loadRegistry: RegistryLoader,
|
|
285
|
+
loadEntries: EntryLoader,
|
|
286
|
+
): Promise<{
|
|
287
|
+
mergedVersions: Record<string, string>;
|
|
288
|
+
entries: ICvcEntry[];
|
|
289
|
+
}> {
|
|
290
|
+
const childVersions = cvcVersionsToRecord(registry.cvcVersions);
|
|
291
|
+
let mergedVersions: Record<string, string> = { ...childVersions };
|
|
292
|
+
|
|
293
|
+
if (registry.basedOn) {
|
|
294
|
+
const base = await loadRegistry(registry.basedOn);
|
|
295
|
+
if (!base) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
`CvcRegistryService: basedOn registry not found: ${registry.basedOn.toString()}`,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
// Locked spec §9.1.2: base versions first, child overrides on top.
|
|
301
|
+
mergedVersions = {
|
|
302
|
+
...cvcVersionsToRecord(base.cvcVersions),
|
|
303
|
+
...childVersions,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Load entries for every pinned `(domain, version)`. We deliberately load
|
|
308
|
+
// sequentially per domain rather than in parallel because consumer apps
|
|
309
|
+
// typically have ≤5 domains pinned per registry — the parallelism win is
|
|
310
|
+
// negligible and the sequential form keeps test fixtures deterministic.
|
|
311
|
+
const pool: ICvcEntry[] = [];
|
|
312
|
+
for (const [domain, version] of Object.entries(mergedVersions)) {
|
|
313
|
+
const domainEntries = await loadEntries(domain, version);
|
|
314
|
+
pool.push(...domainEntries);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const entries = applyEntryOverrides(
|
|
318
|
+
registry.excludedEntries,
|
|
319
|
+
registry.includedEntries,
|
|
320
|
+
pool,
|
|
321
|
+
);
|
|
322
|
+
return { mergedVersions, entries };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ─── Service class ───────────────────────────────────────────────────────────
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Build a Mongo filter that pins a registry to a specific scope. `null`
|
|
329
|
+
* scope keys translate to `null` in the filter (matching the on-disk default
|
|
330
|
+
* for unscoped rows) — they do **not** become `$exists: false`. The schema
|
|
331
|
+
* defaults `application` and `agencyId` to `null`, so this matches reality.
|
|
332
|
+
*/
|
|
333
|
+
function scopeFilter(scope: RegistryScope): {
|
|
334
|
+
application: string | null;
|
|
335
|
+
agencyId: Types.ObjectId | null;
|
|
336
|
+
} {
|
|
337
|
+
return {
|
|
338
|
+
application: scope.application ?? null,
|
|
339
|
+
agencyId: scope.agencyId ?? null,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Build the cache key for a resolved registry. Cache keys are stringified
|
|
345
|
+
* `_id`s — every registry has a unique `_id`, so two distinct scopes that
|
|
346
|
+
* happen to share an active version still get distinct cache slots.
|
|
347
|
+
*/
|
|
348
|
+
function cacheKeyFor(registryId: Types.ObjectId): string {
|
|
349
|
+
return registryId.toString();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Service class. See module-level docstring for the high-level contract;
|
|
354
|
+
* each method documents its own scope-fallback / cache / lifecycle behavior.
|
|
355
|
+
*/
|
|
356
|
+
export class CvcRegistryService {
|
|
357
|
+
private readonly registryModel: Model<ICvcRegistry>;
|
|
358
|
+
private readonly entryModel: Model<ICvcEntry>;
|
|
359
|
+
private readonly scopeFallback: boolean;
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Cached resolved entry set per registry id. The value is the full
|
|
363
|
+
* post-override entry list — domain filtering is done on read so the
|
|
364
|
+
* cache stays domain-agnostic. Cleared on activate/deprecate of any
|
|
365
|
+
* registry that overlaps the cached scope.
|
|
366
|
+
*/
|
|
367
|
+
private readonly resolvedCache = new Map<string, ICvcEntry[]>();
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* @param connection - Mongoose connection that owns `cvc_registries` and `cvc_entries`
|
|
371
|
+
* @param options - Optional behavior toggles (see {@link CvcRegistryServiceOptions})
|
|
372
|
+
*/
|
|
373
|
+
constructor(connection: Connection, options: CvcRegistryServiceOptions = {}) {
|
|
374
|
+
// The schema-derived `CvcRegistry`/`CvcEntry` types from co-am3.2's
|
|
375
|
+
// `schemas/*.ts` widen to the Schema instance shape (a known limitation
|
|
376
|
+
// of `InferRawDocType<Schema>` without preserved generics). Cast to the
|
|
377
|
+
// canonical `ICvcRegistry`/`ICvcEntry` interfaces defined above —
|
|
378
|
+
// these are the contract every method in this file is written against.
|
|
379
|
+
this.registryModel = cvcRegistryModel.compileModel(
|
|
380
|
+
connection,
|
|
381
|
+
) as unknown as Model<ICvcRegistry>;
|
|
382
|
+
this.entryModel = cvcEntryModel.compileModel(
|
|
383
|
+
connection,
|
|
384
|
+
) as unknown as Model<ICvcEntry>;
|
|
385
|
+
this.scopeFallback = options.scopeFallback ?? true;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
389
|
+
// Registry lifecycle
|
|
390
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Find the active registry for a scope, walking the fallback chain
|
|
394
|
+
* (agency-specific → app-specific → platform-default) when enabled. Returns
|
|
395
|
+
* `null` if no active registry exists at any level of the chain.
|
|
396
|
+
*/
|
|
397
|
+
async getActiveRegistry(
|
|
398
|
+
scope: RegistryScope,
|
|
399
|
+
): Promise<ICvcRegistry | null> {
|
|
400
|
+
const candidates: RegistryScope[] = [scope];
|
|
401
|
+
|
|
402
|
+
// Build the fallback ladder. We only widen scope if it actually narrows
|
|
403
|
+
// something — there's no point asking for `{null, null}` twice.
|
|
404
|
+
if (this.scopeFallback) {
|
|
405
|
+
if (scope.agencyId != null && scope.application != null) {
|
|
406
|
+
candidates.push({ application: scope.application, agencyId: null });
|
|
407
|
+
}
|
|
408
|
+
if (scope.application != null) {
|
|
409
|
+
candidates.push({ application: null, agencyId: null });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
for (const candidate of candidates) {
|
|
414
|
+
const found = await this.registryModel
|
|
415
|
+
.findOne({ ...scopeFilter(candidate), status: "active" })
|
|
416
|
+
.lean<ICvcRegistry>()
|
|
417
|
+
.exec();
|
|
418
|
+
if (found) return found;
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Look up a registry by its `(scope, version)` tuple. The scope must be
|
|
425
|
+
* exact — there is no fallback chain here, since version pins are scope-
|
|
426
|
+
* specific by definition.
|
|
427
|
+
*/
|
|
428
|
+
async getRegistry(
|
|
429
|
+
scope: RegistryScope,
|
|
430
|
+
version: string,
|
|
431
|
+
): Promise<ICvcRegistry | null> {
|
|
432
|
+
return this.registryModel
|
|
433
|
+
.findOne({ ...scopeFilter(scope), version })
|
|
434
|
+
.lean<ICvcRegistry>()
|
|
435
|
+
.exec();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* List every registry version for an exact scope, regardless of status.
|
|
440
|
+
* Sorted by version so callers get a deterministic ordering for change
|
|
441
|
+
* logs / version pickers. The version field is a semver string, so the
|
|
442
|
+
* sort is lexicographic — good enough for the typical 1.0.0 / 1.1.0 case.
|
|
443
|
+
*/
|
|
444
|
+
async listVersions(scope: RegistryScope): Promise<ICvcRegistry[]> {
|
|
445
|
+
return this.registryModel
|
|
446
|
+
.find(scopeFilter(scope))
|
|
447
|
+
.sort({ version: 1 })
|
|
448
|
+
.lean<ICvcRegistry[]>()
|
|
449
|
+
.exec();
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Promote a draft registry to `active`. Atomically demotes the previous
|
|
454
|
+
* active registry in the same scope to `deprecated` so the
|
|
455
|
+
* one-active-per-scope invariant holds even under concurrent activations
|
|
456
|
+
* (the partial unique index on `cvc_registries` enforces this at the DB
|
|
457
|
+
* layer; we mirror it here for clarity).
|
|
458
|
+
*
|
|
459
|
+
* @throws Error if the target registry doesn't exist or isn't in `draft`
|
|
460
|
+
*/
|
|
461
|
+
async activate(registryId: Types.ObjectId): Promise<ICvcRegistry> {
|
|
462
|
+
const target = await this.registryModel
|
|
463
|
+
.findById(registryId)
|
|
464
|
+
.lean<ICvcRegistry>()
|
|
465
|
+
.exec();
|
|
466
|
+
if (!target) {
|
|
467
|
+
throw new Error(
|
|
468
|
+
`CvcRegistryService.activate: registry not found: ${registryId.toString()}`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
if (target.status !== "draft") {
|
|
472
|
+
throw new Error(
|
|
473
|
+
`CvcRegistryService.activate: registry ${registryId.toString()} is '${target.status}', expected 'draft'`,
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const now = new Date();
|
|
478
|
+
|
|
479
|
+
// Demote the existing active registry in this scope (if any). Done
|
|
480
|
+
// before promoting the new one so the partial unique index never sees
|
|
481
|
+
// two active rows in the same scope, even mid-transaction.
|
|
482
|
+
await this.registryModel
|
|
483
|
+
.updateOne(
|
|
484
|
+
{
|
|
485
|
+
application: target.application ?? null,
|
|
486
|
+
agencyId: target.agencyId ?? null,
|
|
487
|
+
status: "active",
|
|
488
|
+
},
|
|
489
|
+
{ $set: { status: "deprecated", dateDeactivated: now } },
|
|
490
|
+
)
|
|
491
|
+
.exec();
|
|
492
|
+
|
|
493
|
+
const activated = await this.registryModel
|
|
494
|
+
.findByIdAndUpdate(
|
|
495
|
+
registryId,
|
|
496
|
+
{ $set: { status: "active", dateActivated: now } },
|
|
497
|
+
{ new: true },
|
|
498
|
+
)
|
|
499
|
+
.lean<ICvcRegistry>()
|
|
500
|
+
.exec();
|
|
501
|
+
if (!activated) {
|
|
502
|
+
throw new Error(
|
|
503
|
+
`CvcRegistryService.activate: registry vanished mid-update: ${registryId.toString()}`,
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// Cache invariants change on every activation: the previously active
|
|
508
|
+
// registry's resolution is still correct for its id, but consumers
|
|
509
|
+
// asking for "active in scope X" will now get a new id. Drop the entire
|
|
510
|
+
// cache rather than reasoning about which entries overlap.
|
|
511
|
+
this.resolvedCache.clear();
|
|
512
|
+
return activated;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Demote an active registry to `deprecated`. Idempotent only in the sense
|
|
517
|
+
* that calling it twice on the same registry will fail the second time —
|
|
518
|
+
* we don't allow re-deprecating something that's already deprecated, so
|
|
519
|
+
* the lifecycle stays a strict state machine.
|
|
520
|
+
*
|
|
521
|
+
* @throws Error if the target registry doesn't exist or isn't `active`
|
|
522
|
+
*/
|
|
523
|
+
async deprecate(registryId: Types.ObjectId): Promise<ICvcRegistry> {
|
|
524
|
+
const target = await this.registryModel
|
|
525
|
+
.findById(registryId)
|
|
526
|
+
.lean<ICvcRegistry>()
|
|
527
|
+
.exec();
|
|
528
|
+
if (!target) {
|
|
529
|
+
throw new Error(
|
|
530
|
+
`CvcRegistryService.deprecate: registry not found: ${registryId.toString()}`,
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
if (target.status !== "active") {
|
|
534
|
+
throw new Error(
|
|
535
|
+
`CvcRegistryService.deprecate: registry ${registryId.toString()} is '${target.status}', expected 'active'`,
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const updated = await this.registryModel
|
|
540
|
+
.findByIdAndUpdate(
|
|
541
|
+
registryId,
|
|
542
|
+
{ $set: { status: "deprecated", dateDeactivated: new Date() } },
|
|
543
|
+
{ new: true },
|
|
544
|
+
)
|
|
545
|
+
.lean<ICvcRegistry>()
|
|
546
|
+
.exec();
|
|
547
|
+
if (!updated) {
|
|
548
|
+
throw new Error(
|
|
549
|
+
`CvcRegistryService.deprecate: registry vanished mid-update: ${registryId.toString()}`,
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
this.resolvedCache.clear();
|
|
554
|
+
return updated;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
558
|
+
// Entry resolution (core — all convenience methods funnel through here)
|
|
559
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Resolve a registry into its effective entry list, applying inheritance
|
|
563
|
+
* and overrides. Results are memoised by registry id; the cache is
|
|
564
|
+
* invalidated on `activate()` / `deprecate()`.
|
|
565
|
+
*/
|
|
566
|
+
async resolveEntries(registryId: Types.ObjectId): Promise<ICvcEntry[]> {
|
|
567
|
+
const cacheKey = cacheKeyFor(registryId);
|
|
568
|
+
const cached = this.resolvedCache.get(cacheKey);
|
|
569
|
+
if (cached) return cached;
|
|
570
|
+
|
|
571
|
+
const registry = await this.registryModel
|
|
572
|
+
.findById(registryId)
|
|
573
|
+
.lean<ICvcRegistry>()
|
|
574
|
+
.exec();
|
|
575
|
+
if (!registry) {
|
|
576
|
+
throw new Error(
|
|
577
|
+
`CvcRegistryService.resolveEntries: registry not found: ${registryId.toString()}`,
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const { entries } = await resolveRegistryWithInheritance(
|
|
582
|
+
registry,
|
|
583
|
+
(id) =>
|
|
584
|
+
this.registryModel
|
|
585
|
+
.findById(id)
|
|
586
|
+
.lean<ICvcRegistry>()
|
|
587
|
+
.exec(),
|
|
588
|
+
(domain, version) =>
|
|
589
|
+
this.entryModel
|
|
590
|
+
.find({ domain, version })
|
|
591
|
+
.lean<ICvcEntry[]>()
|
|
592
|
+
.exec(),
|
|
593
|
+
);
|
|
594
|
+
|
|
595
|
+
this.resolvedCache.set(cacheKey, entries);
|
|
596
|
+
return entries;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Same as {@link resolveEntries} but filtered to a single CVC domain.
|
|
601
|
+
* Filtering is done on the cached set so repeated calls for different
|
|
602
|
+
* domains share the same underlying load.
|
|
603
|
+
*/
|
|
604
|
+
async resolveEntriesForDomain(
|
|
605
|
+
registryId: Types.ObjectId,
|
|
606
|
+
domain: string,
|
|
607
|
+
): Promise<ICvcEntry[]> {
|
|
608
|
+
const all = await this.resolveEntries(registryId);
|
|
609
|
+
return all.filter((entry) => entry.domain === domain);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
613
|
+
// Entry lookups (convenience — resolve through the active registry)
|
|
614
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Find an entry by its 7-segment positional code within the active
|
|
618
|
+
* registry for `scope`. Returns `null` if no active registry exists or
|
|
619
|
+
* the code isn't present in the resolved entry set.
|
|
620
|
+
*/
|
|
621
|
+
async getEntryByCode(
|
|
622
|
+
scope: RegistryScope,
|
|
623
|
+
code: string,
|
|
624
|
+
): Promise<ICvcEntry | null> {
|
|
625
|
+
const registry = await this.getActiveRegistry(scope);
|
|
626
|
+
if (!registry) return null;
|
|
627
|
+
const entries = await this.resolveEntries(registry._id);
|
|
628
|
+
return entries.find((entry) => entry.code === code) ?? null;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Find an entry by its stable machine key within a specific domain in the
|
|
633
|
+
* active registry. Keys are unique per `(domain, version)` so the lookup
|
|
634
|
+
* always returns at most one entry.
|
|
635
|
+
*/
|
|
636
|
+
async getEntryByKey(
|
|
637
|
+
scope: RegistryScope,
|
|
638
|
+
domain: string,
|
|
639
|
+
key: string,
|
|
640
|
+
): Promise<ICvcEntry | null> {
|
|
641
|
+
const registry = await this.getActiveRegistry(scope);
|
|
642
|
+
if (!registry) return null;
|
|
643
|
+
const entries = await this.resolveEntriesForDomain(registry._id, domain);
|
|
644
|
+
return entries.find((entry) => entry.key === key) ?? null;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Get every resolved entry for a given domain in the active registry.
|
|
649
|
+
*/
|
|
650
|
+
async getEntries(
|
|
651
|
+
scope: RegistryScope,
|
|
652
|
+
domain: string,
|
|
653
|
+
): Promise<ICvcEntry[]> {
|
|
654
|
+
const registry = await this.getActiveRegistry(scope);
|
|
655
|
+
if (!registry) return [];
|
|
656
|
+
return this.resolveEntriesForDomain(registry._id, domain);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Get only the selectable (leaf) entries for a domain — useful for form
|
|
661
|
+
* dropdowns where structural grouping rows must be hidden.
|
|
662
|
+
*/
|
|
663
|
+
async getSelectableEntries(
|
|
664
|
+
scope: RegistryScope,
|
|
665
|
+
domain: string,
|
|
666
|
+
): Promise<ICvcEntry[]> {
|
|
667
|
+
const entries = await this.getEntries(scope, domain);
|
|
668
|
+
return entries.filter((entry) => entry.selectable);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Get the direct children of a parent code within the active registry.
|
|
673
|
+
* Returns `[]` for leaves and for codes not present in the resolved set.
|
|
674
|
+
*/
|
|
675
|
+
async getChildren(
|
|
676
|
+
scope: RegistryScope,
|
|
677
|
+
code: string,
|
|
678
|
+
): Promise<ICvcEntry[]> {
|
|
679
|
+
const registry = await this.getActiveRegistry(scope);
|
|
680
|
+
if (!registry) return [];
|
|
681
|
+
const entries = await this.resolveEntries(registry._id);
|
|
682
|
+
return entries.filter((entry) => entry.parentCode === code);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Walk the parent chain from `code` up to the tree root, returning the
|
|
687
|
+
* ancestors in **root → entry** order (the entry itself is not included).
|
|
688
|
+
* Stops early if a parent code references an entry that isn't present in
|
|
689
|
+
* the resolved set — that's a corrupt-tree signal but we'd rather return
|
|
690
|
+
* a partial chain than throw inside a UI breadcrumb call.
|
|
691
|
+
*/
|
|
692
|
+
async getAncestors(
|
|
693
|
+
scope: RegistryScope,
|
|
694
|
+
code: string,
|
|
695
|
+
): Promise<ICvcEntry[]> {
|
|
696
|
+
const registry = await this.getActiveRegistry(scope);
|
|
697
|
+
if (!registry) return [];
|
|
698
|
+
const entries = await this.resolveEntries(registry._id);
|
|
699
|
+
const byCode = new Map(entries.map((entry) => [entry.code, entry]));
|
|
700
|
+
|
|
701
|
+
const chain: ICvcEntry[] = [];
|
|
702
|
+
let current = byCode.get(code);
|
|
703
|
+
// Cycle guard: if a corrupt tree contains a loop, stop after we've seen
|
|
704
|
+
// every entry once. This bounds the walk to O(N) in the worst case.
|
|
705
|
+
const seen = new Set<string>();
|
|
706
|
+
while (current?.parentCode && !seen.has(current.parentCode)) {
|
|
707
|
+
seen.add(current.parentCode);
|
|
708
|
+
const parent = byCode.get(current.parentCode);
|
|
709
|
+
if (!parent) break;
|
|
710
|
+
chain.push(parent);
|
|
711
|
+
current = parent;
|
|
712
|
+
}
|
|
713
|
+
return chain.reverse();
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
717
|
+
// Test seam: cache introspection
|
|
718
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Test-only accessor for the resolved-entry cache. Exposed so service
|
|
722
|
+
* tests can assert that `activate()` / `deprecate()` actually flush the
|
|
723
|
+
* cache, and so consumers diagnosing stale-data bugs can dump the live
|
|
724
|
+
* keyset. Not part of the locked spec API surface — treat as internal.
|
|
725
|
+
*/
|
|
726
|
+
get __cacheKeysForTests(): readonly string[] {
|
|
727
|
+
return [...this.resolvedCache.keys()];
|
|
728
|
+
}
|
|
729
|
+
}
|