@htilabs/platform-common-models 0.8.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +44 -0
  2. package/dist/config/index.cjs +191 -0
  3. package/dist/config/index.cjs.map +1 -0
  4. package/dist/config/index.d.cts +101 -0
  5. package/dist/config/index.d.ts +101 -0
  6. package/dist/config/index.js +165 -0
  7. package/dist/config/index.js.map +1 -0
  8. package/dist/constants/index.cjs +5 -432
  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 +5 -429
  13. package/dist/constants/index.js.map +1 -1
  14. package/dist/{cvcEntry-DaDrEuTa.d.cts → cvcEntry-0BIB9sen.d.cts} +44 -44
  15. package/dist/{cvcEntry-DaDrEuTa.d.ts → cvcEntry-0BIB9sen.d.ts} +44 -44
  16. package/dist/cvcs/index.cjs +5863 -7181
  17. package/dist/cvcs/index.cjs.map +1 -1
  18. package/dist/cvcs/index.d.cts +3127 -4581
  19. package/dist/cvcs/index.d.ts +3127 -4581
  20. package/dist/cvcs/index.js +5863 -7173
  21. package/dist/cvcs/index.js.map +1 -1
  22. package/dist/{index-C0J3f169.d.ts → index-CDoqrfc1.d.ts} +1 -1
  23. package/dist/{index-EPjPjR0z.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  24. package/dist/index.cjs +1780 -3613
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +191 -544
  27. package/dist/index.d.ts +191 -544
  28. package/dist/index.js +5967 -7775
  29. package/dist/index.js.map +1 -1
  30. package/dist/models/index.d.cts +2 -2
  31. package/dist/models/index.d.ts +2 -2
  32. package/dist/{platform-auth-BSKYSDKe.d.cts → platform-auth-XVB9aHqR.d.cts} +3 -19
  33. package/dist/{platform-auth-BSKYSDKe.d.ts → platform-auth-XVB9aHqR.d.ts} +3 -19
  34. package/dist/schemas/index.cjs +9 -26
  35. package/dist/schemas/index.cjs.map +1 -1
  36. package/dist/schemas/index.d.cts +39 -35
  37. package/dist/schemas/index.d.ts +39 -35
  38. package/dist/schemas/index.js +9 -26
  39. package/dist/schemas/index.js.map +1 -1
  40. package/dist/types/index.d.cts +2 -2
  41. package/dist/types/index.d.ts +2 -2
  42. package/package.json +25 -19
  43. package/src/__tests__/__snapshots__/cvc-sot.snap +13 -77
  44. package/src/__tests__/cvc-sot-snapshot.test.ts +11 -62
  45. package/src/__tests__/cvc-structural.test.ts +2 -11
  46. package/src/__tests__/runtime-contract-validator.test.ts +556 -0
  47. package/src/config/fixtures/valid.yaml +90 -0
  48. package/src/config/index.ts +352 -0
  49. package/src/constants/ic.ts +3 -445
  50. package/src/cvcs/highestEducationLevelCompleted.v1.0.0.json +0 -9
  51. package/src/cvcs/hmisSex.v1.0.0.json +89 -0
  52. package/src/cvcs/identificationStatus.v1.0.0.json +0 -18
  53. package/src/cvcs/incomeBenefitsSources.v1.0.0.json +2 -31
  54. package/src/cvcs/index.ts +1 -17
  55. package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +96 -0
  56. package/src/cvcs/recencyBand.v1.0.0.json +57 -38
  57. package/src/cvcs/{serviceCategories.v1.1.0.json → serviceCategories.v1.0.0.json} +1091 -1091
  58. package/src/cvcs/serviceStates.v1.0.0.json +1 -23
  59. package/src/cvcs/sourceSubtype.v1.1.0.json +0 -36
  60. package/src/cvcs/verificationMethod.v1.0.0.json +0 -18
  61. package/src/generated/cvc-enums.ts +149 -572
  62. package/src/index.ts +20 -0
  63. package/src/schemas/common.ts +4 -0
  64. package/src/cvcs/activityType.v1.0.0.json +0 -143
  65. package/src/cvcs/assertionDomain.v1.0.0.json +0 -629
  66. package/src/cvcs/contactLinkType.v1.0.0.json +0 -89
  67. package/src/cvcs/hmisRelationshipToHoh.v1.0.0.json +0 -104
  68. package/src/cvcs/housingSubsidyTypes.v1.0.0.json +0 -159
  69. package/src/cvcs/htType.v1.0.0.json +0 -87
  70. package/src/cvcs/livingSituation.v1.0.0.json +0 -213
  71. package/src/cvcs/provenanceSourceId.v1.0.0.json +0 -134
  72. package/src/cvcs/radiusBucket.v1.0.0.json +0 -98
  73. package/src/cvcs/relationshipConcern.v1.0.0.json +0 -114
  74. package/src/cvcs/roiMethod.v1.0.0.json +0 -107
  75. package/src/cvcs/serviceAudience.v1.0.0.json +0 -96
  76. package/src/cvcs/sessionNoteVisibility.v1.0.0.json +0 -80
  77. package/src/cvcs/suggestionSource.v1.0.0.json +0 -71
  78. package/src/cvcs/victimAbuseTypes.v1.0.0.json +0 -276
@@ -0,0 +1,352 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Runtime Config Contract Validator
3
+ *
4
+ * Implements contract R12.1 (platform-common home):
5
+ * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)
6
+ * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)
7
+ *
8
+ * Consumers MUST call validateAgainstContract once at process startup, before
9
+ * any other initialization that reads env vars. Build-phase variables
10
+ * (phase: build) are NOT checked at runtime per R3.4.
11
+ *
12
+ * No secret VALUES are read, stored, or returned here. Secret env vars are
13
+ * validated for presence but their values are never logged or exposed.
14
+ *
15
+ * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():
16
+ * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');
17
+ */
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { parse } from "yaml";
21
+
22
+ // ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────
23
+
24
+ export interface VariableSpec {
25
+ type: "string" | "boolean" | "number" | "enum" | "url" | "json";
26
+ required: boolean;
27
+ secret: boolean;
28
+ description: string;
29
+ phase?: "runtime" | "build";
30
+ values?: string[];
31
+ default?: Record<string, unknown>;
32
+ provider?: string;
33
+ name?: string;
34
+ client_visible?: boolean;
35
+ deprecated?: { since: string; remove_after?: string; replacement?: string };
36
+ }
37
+
38
+ export interface ServiceContract {
39
+ service: string;
40
+ version: number;
41
+ environments: string[];
42
+ // Thread extensions (tolerated, not required — R1.1 note)
43
+ port?: number;
44
+ build_secrets?: string[];
45
+ variables: Record<string, VariableSpec>;
46
+ }
47
+
48
+ /** Typed config accessor returned by validateAgainstContract. */
49
+ export type TypedConfig = Record<string, string | boolean | number | unknown>;
50
+
51
+ export interface ValidateOptions {
52
+ /**
53
+ * Environment name used to select per-env defaults (e.g. "local", "test").
54
+ * Defaults to process.env.NODE_ENV, then "local".
55
+ */
56
+ env?: string;
57
+ /**
58
+ * If true, do not call process.exit(1) on failure; throw instead.
59
+ * Useful for tests. Defaults to false (production mode exits).
60
+ */
61
+ throwOnFailure?: boolean;
62
+ }
63
+
64
+ export interface EndpointOptions {
65
+ /** Cache-Control header value. Defaults to "private, no-store". */
66
+ cacheControl?: string;
67
+ }
68
+
69
+ /**
70
+ * A framework-agnostic route handler that returns a JSON response.
71
+ * Compatible with:
72
+ * - Next.js App Router: export const GET = createConfigEndpoint(...)
73
+ * - Fastify: instance.get('/api/config', createConfigEndpoint(...))
74
+ * - Express: app.get('/api/config', createConfigEndpoint(...))
75
+ */
76
+ export type RouteHandler = (
77
+ req?: unknown,
78
+ res?: unknown,
79
+ ) => Promise<Response | void> | Response | void;
80
+
81
+ // ─── YAML parser ──────────────────────────────────────────────────────────────
82
+
83
+ function loadContract(runtimeYamlPath: string): ServiceContract {
84
+ let raw: string;
85
+ try {
86
+ raw = readFileSync(runtimeYamlPath, "utf8");
87
+ } catch (err) {
88
+ const msg =
89
+ err instanceof Error ? err.message : String(err);
90
+ throw new Error(
91
+ `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,
92
+ );
93
+ }
94
+ const parsed = parse(raw) as ServiceContract | null;
95
+ if (!parsed || typeof parsed !== "object") {
96
+ throw new Error(
97
+ `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,
98
+ );
99
+ }
100
+ if (parsed.version !== 1) {
101
+ throw new Error(
102
+ `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,
103
+ );
104
+ }
105
+ if (!parsed.variables || typeof parsed.variables !== "object") {
106
+ throw new Error(
107
+ `[platform-common/config] ${runtimeYamlPath}: missing "variables" map`,
108
+ );
109
+ }
110
+ return parsed;
111
+ }
112
+
113
+ // ─── Coercion ────────────────────────────────────────────────────────────────
114
+
115
+ /**
116
+ * Coerce a raw environment string value to the declared type.
117
+ * Returns [ok, coerced] or [false, errorMessage].
118
+ */
119
+ function coerce(
120
+ key: string,
121
+ raw: string,
122
+ spec: VariableSpec,
123
+ ): [true, unknown] | [false, string] {
124
+ switch (spec.type) {
125
+ case "boolean": {
126
+ if (raw === "true" || raw === "1") return [true, true];
127
+ if (raw === "false" || raw === "0") return [true, false];
128
+ return [false, `${key}: expected boolean ("true"/"false"/"1"/"0"), got "${raw}"`];
129
+ }
130
+ case "number": {
131
+ const n = Number(raw);
132
+ if (!Number.isFinite(n)) {
133
+ return [false, `${key}: expected number, got "${raw}"`];
134
+ }
135
+ return [true, n];
136
+ }
137
+ case "enum": {
138
+ const vals = spec.values ?? [];
139
+ if (!vals.includes(raw)) {
140
+ return [false, `${key}: expected one of [${vals.join(", ")}], got "${raw}"`];
141
+ }
142
+ return [true, raw];
143
+ }
144
+ case "url": {
145
+ try {
146
+ new URL(raw);
147
+ return [true, raw];
148
+ } catch {
149
+ return [false, `${key}: expected a valid URL, got "${raw}"`];
150
+ }
151
+ }
152
+ case "json": {
153
+ try {
154
+ const parsed = JSON.parse(raw) as unknown;
155
+ return [true, parsed];
156
+ } catch {
157
+ return [false, `${key}: expected valid JSON, got "${raw}"`];
158
+ }
159
+ }
160
+ default:
161
+ // string
162
+ return [true, raw];
163
+ }
164
+ }
165
+
166
+ // ─── Default application ─────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * Returns the default value for a variable in the given environment,
170
+ * or undefined if no default applies.
171
+ *
172
+ * Exact env match only — defaults are per-environment and MUST NOT bleed
173
+ * across envs. (A local default stays local; it does not fall back into prod.)
174
+ */
175
+ function resolveDefault(
176
+ spec: VariableSpec,
177
+ env: string,
178
+ ): string | undefined {
179
+ if (!spec.default) return undefined;
180
+ const v = spec.default[env];
181
+ if (v === undefined) return undefined;
182
+ return String(v);
183
+ }
184
+
185
+ // ─── validateAgainstContract ─────────────────────────────────────────────────
186
+
187
+ /**
188
+ * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
189
+ * `process.env` (with per-env defaults applied), and fail fast on any
190
+ * missing or invalid required variable (R3.2).
191
+ *
192
+ * Build-phase variables (phase: build) are skipped per R3.4.
193
+ *
194
+ * Returns a typed config object keyed by variable name.
195
+ */
196
+ export function validateAgainstContract(
197
+ runtimeYamlPath: string,
198
+ opts: ValidateOptions = {},
199
+ ): TypedConfig {
200
+ const contract = loadContract(runtimeYamlPath);
201
+ const env =
202
+ opts.env ??
203
+ (process.env.NODE_ENV as string | undefined) ??
204
+ "local";
205
+
206
+ const errors: string[] = [];
207
+ const result: TypedConfig = {};
208
+
209
+ for (const [key, spec] of Object.entries(contract.variables)) {
210
+ // R3.4: skip build-phase variables entirely at runtime.
211
+ if (spec.phase === "build") continue;
212
+
213
+ const rawFromEnv = process.env[key];
214
+ const defaultValue = resolveDefault(spec, env);
215
+ const effective = rawFromEnv ?? defaultValue;
216
+
217
+ if (effective === undefined || effective === "") {
218
+ if (spec.required) {
219
+ errors.push(
220
+ `${key}: required but not set (no value in process.env and no default for env "${env}")`,
221
+ );
222
+ }
223
+ // Not required and not set — omit from result.
224
+ continue;
225
+ }
226
+
227
+ const [ok, coerced] = coerce(key, effective, spec);
228
+ if (!ok) {
229
+ errors.push(coerced as string);
230
+ continue;
231
+ }
232
+ result[key] = coerced;
233
+ }
234
+
235
+ if (errors.length > 0) {
236
+ const message = [
237
+ `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,
238
+ `${errors.length} variable(s) missing or invalid:`,
239
+ ...errors.map((e) => ` - ${e}`),
240
+ ].join("\n");
241
+
242
+ if (opts.throwOnFailure) {
243
+ throw new Error(message);
244
+ }
245
+ console.error(message);
246
+ process.exit(1);
247
+ }
248
+
249
+ return result;
250
+ }
251
+
252
+ // ─── createConfigEndpoint ────────────────────────────────────────────────────
253
+
254
+ /**
255
+ * Build a static JSON payload containing only variables that are
256
+ * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env
257
+ * once at factory call time.
258
+ */
259
+ function buildClientPayload(
260
+ contract: ServiceContract,
261
+ env: string,
262
+ ): Record<string, unknown> {
263
+ const payload: Record<string, unknown> = {};
264
+
265
+ for (const [key, spec] of Object.entries(contract.variables)) {
266
+ // R7.3: never expose secrets.
267
+ if (spec.secret) continue;
268
+ // R7.2: only expose client_visible vars.
269
+ if (!spec.client_visible) continue;
270
+ // R3.4: build-phase vars are not available at runtime.
271
+ if (spec.phase === "build") continue;
272
+
273
+ const raw = process.env[key] ?? resolveDefault(spec, env);
274
+ if (raw === undefined) continue;
275
+
276
+ const [ok, coerced] = coerce(key, raw, spec);
277
+ payload[key] = ok ? coerced : raw;
278
+ }
279
+
280
+ return payload;
281
+ }
282
+
283
+ /**
284
+ * Route-handler factory for GET /api/config (R7.1).
285
+ *
286
+ * Reads the contract and process.env once at factory-call time and caches
287
+ * the JSON payload. The returned handler is compatible with:
288
+ *
289
+ * Next.js App Router:
290
+ * export const GET = createConfigEndpoint(path);
291
+ *
292
+ * Fastify:
293
+ * instance.get('/api/config', createConfigEndpoint(path));
294
+ *
295
+ * Express:
296
+ * app.get('/api/config', createConfigEndpoint(path));
297
+ *
298
+ * The handler detects the calling convention at runtime:
299
+ * - Next.js / fetch-native: called with no arguments; returns a Response.
300
+ * - Express: called with (req, res); calls res.json() and returns void.
301
+ * - Fastify: called with (req, reply); calls reply.send() and returns void.
302
+ */
303
+ export function createConfigEndpoint(
304
+ runtimeYamlPath: string,
305
+ opts: EndpointOptions = {},
306
+ ): RouteHandler {
307
+ const contract = loadContract(runtimeYamlPath);
308
+ const env =
309
+ (process.env.NODE_ENV as string | undefined) ?? "local";
310
+ const payload = buildClientPayload(contract, env);
311
+ const cacheControl = opts.cacheControl ?? "private, no-store";
312
+ const body = JSON.stringify(payload);
313
+
314
+ return function configHandler(
315
+ _req?: unknown,
316
+ res?: unknown,
317
+ ): Promise<Response | void> | Response | void {
318
+ // Express-shaped: res has .json()
319
+ if (res && typeof (res as Record<string, unknown>)["json"] === "function") {
320
+ const r = res as {
321
+ setHeader: (k: string, v: string) => void;
322
+ json: (data: unknown) => void;
323
+ };
324
+ r.setHeader("Cache-Control", cacheControl);
325
+ r.setHeader("Content-Type", "application/json");
326
+ r.json(payload);
327
+ return;
328
+ }
329
+
330
+ // Fastify-shaped: res has .send()
331
+ if (res && typeof (res as Record<string, unknown>)["send"] === "function") {
332
+ const r = res as {
333
+ header: (k: string, v: string) => void;
334
+ type: (ct: string) => void;
335
+ send: (data: string) => void;
336
+ };
337
+ r.header("Cache-Control", cacheControl);
338
+ r.type("application/json");
339
+ r.send(body);
340
+ return;
341
+ }
342
+
343
+ // Next.js / fetch-native (no res argument, or unrecognised res)
344
+ return new Response(body, {
345
+ status: 200,
346
+ headers: {
347
+ "Content-Type": "application/json",
348
+ "Cache-Control": cacheControl,
349
+ },
350
+ });
351
+ };
352
+ }