@htilabs/platform-common-models 0.8.13 → 0.8.15

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.
Files changed (75) hide show
  1. package/README.md +44 -0
  2. package/dist/config/index.cjs +4 -0
  3. package/dist/config/index.cjs.map +1 -1
  4. package/dist/config/index.d.cts +16 -1
  5. package/dist/config/index.d.ts +16 -1
  6. package/dist/config/index.js +2 -0
  7. package/dist/config/index.js.map +1 -1
  8. package/dist/constants/index.cjs +10 -0
  9. package/dist/constants/index.cjs.map +1 -1
  10. package/dist/constants/index.d.cts +1 -1
  11. package/dist/constants/index.d.ts +1 -1
  12. package/dist/constants/index.js +10 -0
  13. package/dist/constants/index.js.map +1 -1
  14. package/dist/cvcs/index.cjs +601 -2
  15. package/dist/cvcs/index.cjs.map +1 -1
  16. package/dist/cvcs/index.d.cts +2754 -2084
  17. package/dist/cvcs/index.d.ts +2754 -2084
  18. package/dist/cvcs/index.js +594 -2
  19. package/dist/cvcs/index.js.map +1 -1
  20. package/dist/{index-I-DiX9eQ.d.ts → index-CDoqrfc1.d.ts} +1 -1
  21. package/dist/{index-CoVr1jIV.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  22. package/dist/index.cjs +709 -4
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +154 -7
  25. package/dist/index.d.ts +154 -7
  26. package/dist/index.js +693 -4
  27. package/dist/index.js.map +1 -1
  28. package/dist/models/index.d.cts +2 -2
  29. package/dist/models/index.d.ts +2 -2
  30. package/dist/mongo/index.cjs +383 -0
  31. package/dist/mongo/index.cjs.map +1 -0
  32. package/dist/mongo/index.d.cts +221 -0
  33. package/dist/mongo/index.d.ts +221 -0
  34. package/dist/mongo/index.js +351 -0
  35. package/dist/mongo/index.js.map +1 -0
  36. package/dist/{platform-auth-BfCMuAlC.d.cts → platform-auth-AsfnIXfK.d.cts} +2 -2
  37. package/dist/{platform-auth-BfCMuAlC.d.ts → platform-auth-AsfnIXfK.d.ts} +2 -2
  38. package/dist/schemas/index.cjs +5 -1
  39. package/dist/schemas/index.cjs.map +1 -1
  40. package/dist/schemas/index.d.cts +29 -25
  41. package/dist/schemas/index.d.ts +29 -25
  42. package/dist/schemas/index.js +5 -1
  43. package/dist/schemas/index.js.map +1 -1
  44. package/dist/types/index.d.cts +2 -2
  45. package/dist/types/index.d.ts +2 -2
  46. package/package.json +10 -1
  47. package/src/__sot__/coreIndicators.pin.json +6 -1
  48. package/src/__tests__/__snapshots__/cvc-sot.snap +18 -2
  49. package/src/__tests__/cvc-136-scoring-invariant.test.ts +6 -3
  50. package/src/__tests__/cvc-drift-gate.test.ts +14 -3
  51. package/src/__tests__/cvc-sot-snapshot.test.ts +13 -1
  52. package/src/__tests__/cvc-structural.test.ts +6 -0
  53. package/src/__tests__/mongo-verifier.test.ts +502 -0
  54. package/src/config/index.ts +8 -2
  55. package/src/constants/ic.ts +31 -2
  56. package/src/cvcs/assertionStatus.v1.0.0.json +80 -0
  57. package/src/cvcs/caseShareState.v1.0.0.json +62 -0
  58. package/src/cvcs/coreIndicators.v1.0.0.json +67 -2
  59. package/src/cvcs/createdBySystem.v1.0.0.json +89 -0
  60. package/src/cvcs/criminalOrgCategory.v1.0.0.json +116 -0
  61. package/src/cvcs/hmisSex.v1.0.0.json +89 -0
  62. package/src/cvcs/index.ts +22 -0
  63. package/src/cvcs/minorAdultStatus.v1.0.0.json +80 -0
  64. package/src/cvcs/referralOrigin.v1.0.0.json +26 -0
  65. package/src/cvcs/subjectType.v1.0.0.json +80 -0
  66. package/src/generated/cvc-enums.ts +125 -2
  67. package/src/index.ts +20 -0
  68. package/src/mongo/catalog.ts +65 -0
  69. package/src/mongo/contract.ts +157 -0
  70. package/src/mongo/index.ts +343 -0
  71. package/src/mongo/similarity.ts +133 -0
  72. package/src/mongo/uri.ts +53 -0
  73. package/src/schemas/common.ts +4 -0
  74. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-0BIB9sen.d.cts} +8 -8
  75. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-0BIB9sen.d.ts} +8 -8
@@ -0,0 +1,343 @@
1
+ /**
2
+ * @htilabs/platform-common-models — MongoDB connection/collection verifier
3
+ *
4
+ * Sibling to `./config`. Where `validateAgainstContract` proves the env vars
5
+ * are present and well-typed, `verifyMongo` proves they point somewhere real.
6
+ *
7
+ * ## What this catches
8
+ * - a database name that does not exist and looks like a typo of one that does
9
+ * - a collection name that does not exist and looks like a typo of one that does
10
+ * - a database name that does not belong to the current environment
11
+ * (env-affinity; needs no connection — generalizes thread's `assertTestDb`)
12
+ * - collections present in MongoDB but undeclared by the service (reported)
13
+ *
14
+ * ## What this CANNOT catch
15
+ * A plausible-but-wrong POPULATED database. `leads-platform-prod-test` exists
16
+ * and carries the same collection names as `leads-platform-test`; every
17
+ * name-existence check passes. Detecting that needs an identity marker
18
+ * written inside the database, which is outside this utility's read-only
19
+ * remit. Do not claim otherwise in adoption docs.
20
+ *
21
+ * ## Read-only
22
+ * Reaches MongoDB solely through {@link MongoCatalog}: listDatabases and
23
+ * listCollections. It never creates, writes, or drops anything.
24
+ *
25
+ * ## Severity
26
+ * MongoDB creates namespaces lazily, so ABSENCE IS AMBIGUOUS (typo vs
27
+ * unseeded environment). Absence alone warns; absence with a plausible
28
+ * near-neighbour is fatal. See `similarity.ts`.
29
+ *
30
+ * FACT (verified 2026-07-10, read-only): thread registers the Mongoose model
31
+ * `AgencyInfo` (collection `agencyinfos`), and that collection exists in
32
+ * neither `platform-test` (15 collections) nor `platform-dev` (41). A
33
+ * registered model with zero documents has no collection. The warn-on-absence
34
+ * rule exists because of this; do not "tighten" it to fatal.
35
+ */
36
+
37
+ import {
38
+ loadContract,
39
+ resolveDefault,
40
+ type ServiceContract,
41
+ } from "../config/index.js";
42
+ import {
43
+ parseMongoBlock,
44
+ checkEnvAffinity,
45
+ type MongoContractBlock,
46
+ type MongoDbSpec,
47
+ } from "./contract.js";
48
+ import { nearestNames, formatSuggestions } from "./similarity.js";
49
+ import { parseDbName } from "./uri.js";
50
+ import type { MongoCatalog } from "./catalog.js";
51
+
52
+ export type { MongoCatalog, MongoClientLike, MongooseConnectionLike } from "./catalog.js";
53
+ export { catalogFromClient, catalogFromMongoose } from "./catalog.js";
54
+ export type { MongoContractBlock, MongoDbSpec, EnvAffinity } from "./contract.js";
55
+ export { parseDbName, isTestDb, TEST_DB_SUFFIX } from "./uri.js";
56
+
57
+ const TAG = "[platform-common/mongo]";
58
+
59
+ export type Severity = "fatal" | "warn";
60
+
61
+ export type FindingKind =
62
+ | "env_var_missing"
63
+ | "db_shape_violation"
64
+ | "db_absent_typo"
65
+ | "db_absent_unseeded"
66
+ | "collection_absent_typo"
67
+ | "collection_absent_unseeded"
68
+ | "collection_undeclared";
69
+
70
+ export interface Finding {
71
+ severity: Severity;
72
+ kind: FindingKind;
73
+ message: string;
74
+ dbVar?: string;
75
+ database?: string;
76
+ collection?: string;
77
+ /**
78
+ * Existing names this looks like a typo of. More than one means the evidence
79
+ * is ambiguous — the message lists them all rather than guessing.
80
+ */
81
+ suggestions?: string[];
82
+ }
83
+
84
+ export interface MongoVerifyReport {
85
+ /** True when no fatal finding was produced. Warnings do not clear `ok`. */
86
+ ok: boolean;
87
+ findings: Finding[];
88
+ }
89
+
90
+ export interface VerifyMongoOptions {
91
+ /** Read-only catalogue. Required — this package takes no driver dependency. */
92
+ catalog: MongoCatalog;
93
+ /** Environment name for affinity checks. Defaults to NODE_ENV, then "local". */
94
+ env?: string;
95
+ /** Env source. Defaults to `process.env`. */
96
+ processEnv?: NodeJS.ProcessEnv;
97
+ /** If true, throw instead of `exit(1)`. Defaults to false (production exits). */
98
+ throwOnFailure?: boolean;
99
+ /** Injected for tests. Defaults to `process.exit`. */
100
+ exit?: (code: number) => never;
101
+ /** Injected for tests. Defaults to `console`. */
102
+ logger?: Pick<Console, "error" | "warn">;
103
+ }
104
+
105
+ /**
106
+ * Resolve the database name for a spec, applying the same per-environment
107
+ * defaults that `validateAgainstContract` applies. Reading `process.env` alone
108
+ * would miss a value the contract supplies as a default (thread declares
109
+ * `PLATFORM_DB.default.prod: platform-prod`) and report a false fatal.
110
+ *
111
+ * When `db_var` and `uri_var` name the same variable, the database is embedded
112
+ * in the connection string (auth does this for `LEADS_MONGODB_URI` and
113
+ * friends) and must be parsed out of it.
114
+ *
115
+ * A variable the contract marks `required: false` and that carries no value is
116
+ * SKIPPED, not failed: thread's `PAVE_DB` is optional and its absence simply
117
+ * means the read-only pave connection is not configured. Required-ness comes
118
+ * from the contract so there is no second place to declare it.
119
+ */
120
+ function resolveDbName(
121
+ spec: MongoDbSpec,
122
+ contract: ServiceContract,
123
+ env: string,
124
+ processEnv: NodeJS.ProcessEnv,
125
+ ): { name?: string; error?: string; skip?: boolean } {
126
+ const varSpec = contract.variables[spec.db_var];
127
+ const raw =
128
+ processEnv[spec.db_var] ??
129
+ (varSpec ? resolveDefault(varSpec, env) : undefined);
130
+
131
+ if (raw === undefined || raw === "") {
132
+ // A variable absent from `variables` is treated as required: the mongo
133
+ // block references something the contract never declared.
134
+ if (varSpec && varSpec.required === false) return { skip: true };
135
+ return { error: `${spec.db_var}: required by mongo contract but not set` };
136
+ }
137
+
138
+ if (spec.db_var !== spec.uri_var) return { name: raw };
139
+
140
+ const parsed = parseDbName(raw);
141
+ if (parsed === null) {
142
+ return {
143
+ error:
144
+ `${spec.db_var}: connection string carries no database name. ` +
145
+ `Either embed one (mongodb://host/<db>) or declare a separate db_var.`,
146
+ };
147
+ }
148
+ return { name: parsed };
149
+ }
150
+
151
+ async function verifyDatabase(
152
+ spec: MongoDbSpec,
153
+ dbName: string,
154
+ block: MongoContractBlock,
155
+ env: string,
156
+ catalog: MongoCatalog,
157
+ existingDatabases: readonly string[],
158
+ ): Promise<Finding[]> {
159
+ const findings: Finding[] = [];
160
+
161
+ // 1. Env affinity — no connection required, and the only check that catches
162
+ // a test run pointed at production.
163
+ const violation = checkEnvAffinity(dbName, spec.db_var, env, block.env_affinity);
164
+ if (violation) {
165
+ findings.push({
166
+ severity: "fatal",
167
+ kind: "db_shape_violation",
168
+ message: violation,
169
+ dbVar: spec.db_var,
170
+ database: dbName,
171
+ });
172
+ // A database in the wrong environment must not be probed further.
173
+ return findings;
174
+ }
175
+
176
+ // 2. Existence.
177
+ if (!existingDatabases.includes(dbName)) {
178
+ const suggestions = nearestNames(dbName, existingDatabases);
179
+ if (suggestions.length > 0) {
180
+ findings.push({
181
+ severity: "fatal",
182
+ kind: "db_absent_typo",
183
+ message:
184
+ `${spec.db_var}="${dbName}" does not exist. ` +
185
+ `Did you mean ${formatSuggestions(suggestions)}?`,
186
+ dbVar: spec.db_var,
187
+ database: dbName,
188
+ suggestions,
189
+ });
190
+ } else {
191
+ findings.push({
192
+ severity: "warn",
193
+ kind: "db_absent_unseeded",
194
+ message:
195
+ `${spec.db_var}="${dbName}" does not exist yet. Treating as an ` +
196
+ `unseeded environment; MongoDB will create it on first write.`,
197
+ dbVar: spec.db_var,
198
+ database: dbName,
199
+ });
200
+ }
201
+ // Nothing to compare collections against.
202
+ return findings;
203
+ }
204
+
205
+ // 3. An empty `collections` list opts out of collection checking: verify the
206
+ // database NAME only. This lets a service adopt incrementally — expansion
207
+ // reaches the leads databases but enumerating their collections is not
208
+ // tractable, and sweeping a 467MB database would emit a warning per
209
+ // collection. Declaring even one collection opts back in.
210
+ if (spec.collections.length === 0) return findings;
211
+
212
+ // 4. Collections, both directions.
213
+ const actual = await catalog.listCollections(dbName);
214
+
215
+ for (const declared of spec.collections) {
216
+ if (actual.includes(declared)) continue;
217
+
218
+ const suggestions = nearestNames(declared, actual);
219
+ if (suggestions.length > 0) {
220
+ findings.push({
221
+ severity: "fatal",
222
+ kind: "collection_absent_typo",
223
+ message:
224
+ `${dbName}: declared collection "${declared}" does not exist. ` +
225
+ `Did you mean ${formatSuggestions(suggestions)}?`,
226
+ dbVar: spec.db_var,
227
+ database: dbName,
228
+ collection: declared,
229
+ suggestions,
230
+ });
231
+ } else {
232
+ findings.push({
233
+ severity: "warn",
234
+ kind: "collection_absent_unseeded",
235
+ message:
236
+ `${dbName}: declared collection "${declared}" does not exist yet ` +
237
+ `(no documents written). MongoDB creates collections lazily.`,
238
+ dbVar: spec.db_var,
239
+ database: dbName,
240
+ collection: declared,
241
+ });
242
+ }
243
+ }
244
+
245
+ const declaredSet = new Set(spec.collections);
246
+ for (const present of actual) {
247
+ if (declaredSet.has(present)) continue;
248
+ findings.push({
249
+ severity: "warn",
250
+ kind: "collection_undeclared",
251
+ message:
252
+ `${dbName}: collection "${present}" exists but is not declared in the ` +
253
+ `mongo contract.`,
254
+ dbVar: spec.db_var,
255
+ database: dbName,
256
+ collection: present,
257
+ });
258
+ }
259
+
260
+ return findings;
261
+ }
262
+
263
+ /**
264
+ * Verify every database and collection declared in `runtimeYamlPath` against a
265
+ * live MongoDB catalogue.
266
+ *
267
+ * Collects ALL findings before deciding, exactly as `validateAgainstContract`
268
+ * does — an operator fixing a misconfiguration should see every problem at
269
+ * once, not one per restart.
270
+ *
271
+ * Resolves to the report when no fatal finding is produced. On a fatal finding
272
+ * it prints every finding and calls `exit(1)`, or throws when
273
+ * `throwOnFailure` is set.
274
+ *
275
+ * A contract with no `mongo:` block is a no-op success.
276
+ */
277
+ export async function verifyMongo(
278
+ runtimeYamlPath: string,
279
+ opts: VerifyMongoOptions,
280
+ ): Promise<MongoVerifyReport> {
281
+ const processEnv = opts.processEnv ?? process.env;
282
+ const logger = opts.logger ?? console;
283
+ const exit = opts.exit ?? ((code: number) => process.exit(code));
284
+ const env = opts.env ?? processEnv.NODE_ENV ?? "local";
285
+
286
+ const contract = loadContract(runtimeYamlPath);
287
+ const block = parseMongoBlock(contract.mongo, runtimeYamlPath);
288
+ if (block === null) return { ok: true, findings: [] };
289
+
290
+ const findings: Finding[] = [];
291
+ const resolved: Array<{ spec: MongoDbSpec; name: string }> = [];
292
+
293
+ for (const spec of block.databases) {
294
+ const { name, error, skip } = resolveDbName(spec, contract, env, processEnv);
295
+ if (skip) continue; // optional database, not configured in this environment
296
+ if (error !== undefined || name === undefined) {
297
+ findings.push({
298
+ severity: "fatal",
299
+ kind: "env_var_missing",
300
+ message: error ?? `${spec.db_var}: unresolved`,
301
+ dbVar: spec.db_var,
302
+ });
303
+ continue;
304
+ }
305
+ resolved.push({ spec, name });
306
+ }
307
+
308
+ // One catalogue read shared across every database in the contract.
309
+ const existingDatabases =
310
+ resolved.length > 0 ? await opts.catalog.listDatabases() : [];
311
+
312
+ for (const { spec, name } of resolved) {
313
+ findings.push(
314
+ ...(await verifyDatabase(
315
+ spec,
316
+ name,
317
+ block,
318
+ env,
319
+ opts.catalog,
320
+ existingDatabases,
321
+ )),
322
+ );
323
+ }
324
+
325
+ const fatals = findings.filter((f) => f.severity === "fatal");
326
+ const warns = findings.filter((f) => f.severity === "warn");
327
+
328
+ for (const w of warns) logger.warn(`${TAG} ${w.message}`);
329
+
330
+ if (fatals.length > 0) {
331
+ const message = [
332
+ `${TAG} verifyMongo failed for ${runtimeYamlPath} (env "${env}")`,
333
+ `${fatals.length} fatal finding(s):`,
334
+ ...fatals.map((f) => ` - ${f.message}`),
335
+ ].join("\n");
336
+
337
+ if (opts.throwOnFailure) throw new Error(message);
338
+ logger.error(message);
339
+ exit(1);
340
+ }
341
+
342
+ return { ok: fatals.length === 0, findings };
343
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @htilabs/platform-common-models — name-similarity heuristic
3
+ *
4
+ * A missing database or collection is AMBIGUOUS. MongoDB creates namespaces
5
+ * lazily, on first write, so "absent" means either:
6
+ *
7
+ * (a) a typo — the name is wrong and the real one exists nearby, or
8
+ * (b) unseeded — the environment is new and nothing has been written yet.
9
+ *
10
+ * Guessing wrong in direction (b) is expensive: a fatal check would ground
11
+ * every cold-start ephemeral deploy. So absence alone is never fatal. Only
12
+ * absence WITH a plausible near-neighbour is treated as a typo.
13
+ */
14
+
15
+ /** Maximum edit distance at which a neighbouring name is considered a typo. */
16
+ export const TYPO_DISTANCE_THRESHOLD = 2;
17
+
18
+ /**
19
+ * Optimal String Alignment distance (Damerau-Levenshtein restricted to
20
+ * adjacent transpositions), bounded: returns `max + 1` as soon as the true
21
+ * distance is known to exceed `max`. Bounding keeps this cheap across the
22
+ * ~90-database catalogue scanned on each lookup.
23
+ *
24
+ * A transposition MUST cost 1, not 2. `platform-dve` is a transposition of
25
+ * `platform-dev`, but plain Levenshtein scores it 2 -- tying it with the
26
+ * unrelated PRODUCTION name `platform-db` and letting iteration order pick.
27
+ * Steering an operator toward a production database because they typo'd a dev
28
+ * one is a worse failure than suggesting nothing at all.
29
+ */
30
+ export function editDistance(a: string, b: string, max = Infinity): number {
31
+ if (a === b) return 0;
32
+ if (Math.abs(a.length - b.length) > max) return max + 1;
33
+
34
+ // Three rows: prev2 carries i-2 so an adjacent transposition costs 1.
35
+ let prev2 = new Array<number>(b.length + 1).fill(0);
36
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
37
+ let curr = new Array<number>(b.length + 1);
38
+
39
+ for (let i = 1; i <= a.length; i++) {
40
+ curr[0] = i;
41
+ let rowMin = curr[0];
42
+ for (let j = 1; j <= b.length; j++) {
43
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
44
+ let d = Math.min(
45
+ prev[j] + 1, // deletion
46
+ curr[j - 1] + 1, // insertion
47
+ prev[j - 1] + cost, // substitution
48
+ );
49
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
50
+ d = Math.min(d, prev2[j - 2] + 1); // adjacent transposition
51
+ }
52
+ curr[j] = d;
53
+ if (d < rowMin) rowMin = d;
54
+ }
55
+ // Every remaining row can only grow: bail out early.
56
+ if (rowMin > max) return max + 1;
57
+ [prev2, prev, curr] = [prev, curr, prev2];
58
+ }
59
+
60
+ return prev[b.length];
61
+ }
62
+
63
+ /** Strip a trailing ordinal token: `demo2` -> `demo`, `cypress-tests-3` -> `cypress-tests`. */
64
+ function stripOrdinal(name: string): string {
65
+ return name.replace(/[-_]?\d+$/, "");
66
+ }
67
+
68
+ /**
69
+ * True when two names look like sibling environments rather than a typo of
70
+ * each other — that is, they differ ONLY in a trailing ordinal.
71
+ *
72
+ * This guard is mandatory, not cosmetic. The live cluster contains
73
+ * `leads-platform-demo` beside `leads-platform-demo2` (edit distance 1) and
74
+ * `cypress-tests-1/2/3`. Without it, provisioning `leads-platform-demo3` would
75
+ * find `demo2` one edit away, be branded a typo, and hard-fail a healthy new
76
+ * environment — reintroducing exactly the cold-start breakage the severity
77
+ * model exists to prevent.
78
+ *
79
+ * The guard is deliberately biased toward WARN: a genuine typo that happens to
80
+ * differ only in a trailing digit is downgraded to a warning rather than
81
+ * risking a false fatal.
82
+ */
83
+ export function isOrdinalSibling(a: string, b: string): boolean {
84
+ if (a === b) return false;
85
+ const baseA = stripOrdinal(a);
86
+ const baseB = stripOrdinal(b);
87
+ // Both must reduce to the same base, and at least one must have carried an
88
+ // ordinal (otherwise stripping changed nothing and this is a real edit).
89
+ return baseA === baseB && (baseA !== a || baseB !== b);
90
+ }
91
+
92
+ /**
93
+ * Find the existing names most likely to be what `name` was meant to be.
94
+ *
95
+ * Returns EVERY candidate at the minimal distance, not one arbitrary winner.
96
+ * `thread-dv` is one edit from both `thread-dev` and `thread-db`; picking
97
+ * between them by iteration order could point an operator at production. When
98
+ * the evidence is ambiguous, say so.
99
+ *
100
+ * Returns an empty array when nothing is close enough, or when the only close
101
+ * matches are sibling environments (see {@link isOrdinalSibling}). Empty means
102
+ * "absent, but no evidence of a typo" — the caller warns rather than fails.
103
+ *
104
+ * Results are sorted for deterministic messages.
105
+ */
106
+ export function nearestNames(name: string, candidates: readonly string[]): string[] {
107
+ let best: string[] = [];
108
+ let bestDistance = TYPO_DISTANCE_THRESHOLD + 1;
109
+
110
+ for (const candidate of candidates) {
111
+ if (candidate === name) return []; // exact match: not missing at all
112
+ if (isOrdinalSibling(name, candidate)) continue;
113
+
114
+ const d = editDistance(name, candidate, TYPO_DISTANCE_THRESHOLD);
115
+ if (d > TYPO_DISTANCE_THRESHOLD) continue;
116
+
117
+ if (d < bestDistance) {
118
+ bestDistance = d;
119
+ best = [candidate];
120
+ } else if (d === bestDistance) {
121
+ best.push(candidate);
122
+ }
123
+ }
124
+
125
+ return best.sort();
126
+ }
127
+
128
+ /** Render one or more suggestions as `"a"`, or `"a" or "b"`, or `"a", "b" or "c"`. */
129
+ export function formatSuggestions(names: readonly string[]): string {
130
+ const quoted = names.map((n) => `"${n}"`);
131
+ if (quoted.length <= 1) return quoted[0] ?? "";
132
+ return `${quoted.slice(0, -1).join(", ")} or ${quoted[quoted.length - 1]}`;
133
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @htilabs/platform-common-models — MongoDB URI parsing
3
+ *
4
+ * Home of the connection-string parsing shared by the seed guard
5
+ * (`scripts/lib/confirmTargetDb.ts`) and the runtime verifier
6
+ * (`src/mongo/index.ts`). It lives in `src/` so both can import one
7
+ * implementation; `scripts/` cannot be imported from `src/` at build time.
8
+ */
9
+
10
+ /** Suffix that marks a database as a non-production scratch/test database. */
11
+ export const TEST_DB_SUFFIX = "-test";
12
+
13
+ /**
14
+ * Parse the target database name out of a MongoDB connection URI.
15
+ *
16
+ * The database name is the path segment after the host(s), before any query
17
+ * string (`?...`). Handles both `mongodb://` and `mongodb+srv://` URIs and any
18
+ * userinfo / multi-host / option components. Returns `null` when the URI
19
+ * carries no database name (e.g. `mongodb://localhost:27017` or a trailing
20
+ * slash with nothing after it) — callers must treat a `null` name as
21
+ * prod-shaped and never silently default to a production database.
22
+ *
23
+ * Implemented as manual string parsing rather than `new URL()` because Node's
24
+ * URL parser rejects multi-host `mongodb+srv` authorities and mishandles the
25
+ * comma-separated seed-list form that real connection strings use.
26
+ */
27
+ export function parseDbName(uri: string): string | null {
28
+ // Strip the scheme.
29
+ const schemeMatch = /^mongodb(\+srv)?:\/\//i.exec(uri);
30
+ if (!schemeMatch) return null;
31
+ let rest = uri.slice(schemeMatch[0].length);
32
+
33
+ // Drop query string and fragment — the DB name precedes both.
34
+ const qIdx = rest.search(/[?#]/);
35
+ if (qIdx !== -1) rest = rest.slice(0, qIdx);
36
+
37
+ // The path begins at the first '/' after the authority. Everything before
38
+ // that first slash is userinfo + host(s); everything after is the DB name.
39
+ const slashIdx = rest.indexOf("/");
40
+ if (slashIdx === -1) return null;
41
+
42
+ const dbName = rest.slice(slashIdx + 1).trim();
43
+ return dbName.length > 0 ? dbName : null;
44
+ }
45
+
46
+ /**
47
+ * Classify a database name. A name is a "test" database (no confirmation
48
+ * required) only when it is non-null and ends in {@link TEST_DB_SUFFIX}.
49
+ * Everything else — including a `null` name — is prod-shaped.
50
+ */
51
+ export function isTestDb(dbName: string | null): boolean {
52
+ return dbName !== null && dbName.endsWith(TEST_DB_SUFFIX);
53
+ }
@@ -42,6 +42,10 @@ export const personNameSchema = new Schema(
42
42
  alias: Boolean,
43
43
  isUnknown: Boolean,
44
44
  isAnonymous: Boolean,
45
+ // Shape flag: this person has only one name (e.g., Madonna). A mononym
46
+ // can itself be legal, a nickname, a trade name, etc. — it's orthogonal
47
+ // to nameType, not a value of it.
48
+ isMononym: Boolean,
45
49
  },
46
50
  { _id: false },
47
51
  );
@@ -233,18 +233,18 @@ type SectionQuestionRef = InferRawDocType<typeof sectionQuestionRefSchema>;
233
233
  declare const guidanceSchema: Schema<any, mongoose.Model<any, any, any, any, any, any, any>, {}, {}, {}, {}, {
234
234
  _id: false;
235
235
  }, {
236
- text: string;
237
236
  type: "tip" | "warning" | "prompt";
238
- }, mongoose.Document<unknown, {}, {
239
237
  text: string;
238
+ }, mongoose.Document<unknown, {}, {
240
239
  type: "tip" | "warning" | "prompt";
240
+ text: string;
241
241
  }, {
242
242
  id: string;
243
243
  }, Omit<mongoose.DefaultSchemaOptions, "_id"> & {
244
244
  _id: false;
245
245
  }> & Omit<{
246
- text: string;
247
246
  type: "tip" | "warning" | "prompt";
247
+ text: string;
248
248
  } & {
249
249
  _id: mongoose.Types.ObjectId;
250
250
  } & {
@@ -252,8 +252,8 @@ declare const guidanceSchema: Schema<any, mongoose.Model<any, any, any, any, any
252
252
  }, "id"> & {
253
253
  id: string;
254
254
  }, unknown, {
255
- text: string;
256
255
  type: "tip" | "warning" | "prompt";
256
+ text: string;
257
257
  } & {
258
258
  _id: mongoose.Types.ObjectId;
259
259
  } & {
@@ -294,18 +294,18 @@ declare const sectionSchemaDefinition: {
294
294
  type: Schema<any, mongoose.Model<any, any, any, any, any, any, any>, {}, {}, {}, {}, {
295
295
  _id: false;
296
296
  }, {
297
- text: string;
298
297
  type: "tip" | "warning" | "prompt";
299
- }, mongoose.Document<unknown, {}, {
300
298
  text: string;
299
+ }, mongoose.Document<unknown, {}, {
301
300
  type: "tip" | "warning" | "prompt";
301
+ text: string;
302
302
  }, {
303
303
  id: string;
304
304
  }, Omit<mongoose.DefaultSchemaOptions, "_id"> & {
305
305
  _id: false;
306
306
  }> & Omit<{
307
- text: string;
308
307
  type: "tip" | "warning" | "prompt";
308
+ text: string;
309
309
  } & {
310
310
  _id: mongoose.Types.ObjectId;
311
311
  } & {
@@ -313,8 +313,8 @@ declare const sectionSchemaDefinition: {
313
313
  }, "id"> & {
314
314
  id: string;
315
315
  }, unknown, {
316
- text: string;
317
316
  type: "tip" | "warning" | "prompt";
317
+ text: string;
318
318
  } & {
319
319
  _id: mongoose.Types.ObjectId;
320
320
  } & {
@@ -233,18 +233,18 @@ type SectionQuestionRef = InferRawDocType<typeof sectionQuestionRefSchema>;
233
233
  declare const guidanceSchema: Schema<any, mongoose.Model<any, any, any, any, any, any, any>, {}, {}, {}, {}, {
234
234
  _id: false;
235
235
  }, {
236
- text: string;
237
236
  type: "tip" | "warning" | "prompt";
238
- }, mongoose.Document<unknown, {}, {
239
237
  text: string;
238
+ }, mongoose.Document<unknown, {}, {
240
239
  type: "tip" | "warning" | "prompt";
240
+ text: string;
241
241
  }, {
242
242
  id: string;
243
243
  }, Omit<mongoose.DefaultSchemaOptions, "_id"> & {
244
244
  _id: false;
245
245
  }> & Omit<{
246
- text: string;
247
246
  type: "tip" | "warning" | "prompt";
247
+ text: string;
248
248
  } & {
249
249
  _id: mongoose.Types.ObjectId;
250
250
  } & {
@@ -252,8 +252,8 @@ declare const guidanceSchema: Schema<any, mongoose.Model<any, any, any, any, any
252
252
  }, "id"> & {
253
253
  id: string;
254
254
  }, unknown, {
255
- text: string;
256
255
  type: "tip" | "warning" | "prompt";
256
+ text: string;
257
257
  } & {
258
258
  _id: mongoose.Types.ObjectId;
259
259
  } & {
@@ -294,18 +294,18 @@ declare const sectionSchemaDefinition: {
294
294
  type: Schema<any, mongoose.Model<any, any, any, any, any, any, any>, {}, {}, {}, {}, {
295
295
  _id: false;
296
296
  }, {
297
- text: string;
298
297
  type: "tip" | "warning" | "prompt";
299
- }, mongoose.Document<unknown, {}, {
300
298
  text: string;
299
+ }, mongoose.Document<unknown, {}, {
301
300
  type: "tip" | "warning" | "prompt";
301
+ text: string;
302
302
  }, {
303
303
  id: string;
304
304
  }, Omit<mongoose.DefaultSchemaOptions, "_id"> & {
305
305
  _id: false;
306
306
  }> & Omit<{
307
- text: string;
308
307
  type: "tip" | "warning" | "prompt";
308
+ text: string;
309
309
  } & {
310
310
  _id: mongoose.Types.ObjectId;
311
311
  } & {
@@ -313,8 +313,8 @@ declare const sectionSchemaDefinition: {
313
313
  }, "id"> & {
314
314
  id: string;
315
315
  }, unknown, {
316
- text: string;
317
316
  type: "tip" | "warning" | "prompt";
317
+ text: string;
318
318
  } & {
319
319
  _id: mongoose.Types.ObjectId;
320
320
  } & {