@htilabs/platform-common-models 0.12.0 → 0.12.2

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 (99) hide show
  1. package/dist/config/index.cjs +0 -81
  2. package/dist/config/index.cjs.map +1 -1
  3. package/dist/config/index.d.cts +4 -79
  4. package/dist/config/index.d.ts +4 -79
  5. package/dist/config/index.js +1 -79
  6. package/dist/config/index.js.map +1 -1
  7. package/dist/constants/index.cjs +18 -2
  8. package/dist/constants/index.cjs.map +1 -1
  9. package/dist/constants/index.d.cts +1 -1
  10. package/dist/constants/index.d.ts +1 -1
  11. package/dist/constants/index.js +18 -2
  12. package/dist/constants/index.js.map +1 -1
  13. package/dist/cvc-Cp4uWnAa.d.cts +298 -0
  14. package/dist/cvc-Cp4uWnAa.d.ts +298 -0
  15. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-ctHTp2df.d.cts} +44 -44
  16. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-ctHTp2df.d.ts} +44 -44
  17. package/dist/cvcs/index.cjs +8065 -1384
  18. package/dist/cvcs/index.cjs.map +1 -1
  19. package/dist/cvcs/index.d.cts +15287 -8079
  20. package/dist/cvcs/index.d.ts +15287 -8079
  21. package/dist/cvcs/index.js +8052 -1384
  22. package/dist/cvcs/index.js.map +1 -1
  23. package/dist/enums/index.cjs +4573 -0
  24. package/dist/enums/index.cjs.map +1 -0
  25. package/dist/enums/index.d.cts +5277 -0
  26. package/dist/enums/index.d.ts +5277 -0
  27. package/dist/enums/index.js +4369 -0
  28. package/dist/enums/index.js.map +1 -0
  29. package/dist/{index-I-DiX9eQ.d.ts → index-4DiJrn7y.d.ts} +1 -1
  30. package/dist/{index-CoVr1jIV.d.cts → index-qreOzXYS.d.cts} +1 -1
  31. package/dist/index.cjs +8616 -1389
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +7 -4700
  34. package/dist/index.d.ts +7 -4700
  35. package/dist/index.js +8590 -1389
  36. package/dist/index.js.map +1 -1
  37. package/dist/models/index.d.cts +2 -2
  38. package/dist/models/index.d.ts +2 -2
  39. package/dist/mongo/index.cjs +0 -1
  40. package/dist/mongo/index.cjs.map +1 -1
  41. package/dist/mongo/index.js +1 -2
  42. package/dist/mongo/index.js.map +1 -1
  43. package/dist/{platform-auth-v53r3BhN.d.cts → platform-auth-Dv5fu0Fh.d.cts} +5 -4
  44. package/dist/{platform-auth-v53r3BhN.d.ts → platform-auth-Dv5fu0Fh.d.ts} +5 -4
  45. package/dist/schemas/index.cjs +5 -1
  46. package/dist/schemas/index.cjs.map +1 -1
  47. package/dist/schemas/index.d.cts +35 -35
  48. package/dist/schemas/index.d.ts +35 -35
  49. package/dist/schemas/index.js +5 -1
  50. package/dist/schemas/index.js.map +1 -1
  51. package/dist/types/index.d.cts +2 -2
  52. package/dist/types/index.d.ts +2 -2
  53. package/dist/validation/index.cjs +58 -0
  54. package/dist/validation/index.cjs.map +1 -1
  55. package/dist/validation/index.d.cts +82 -283
  56. package/dist/validation/index.d.ts +82 -283
  57. package/dist/validation/index.js +57 -0
  58. package/dist/validation/index.js.map +1 -1
  59. package/package.json +32 -22
  60. package/src/__sot__/README.md +36 -1
  61. package/src/__sot__/coreIndicatorFields.ts +331 -0
  62. package/src/__sot__/coreIndicators.pin.json +1936 -2
  63. package/src/__sot__/cvcIndex.pin.json +8 -4
  64. package/src/__tests__/__snapshots__/cvc-sot.snap +45 -13
  65. package/src/__tests__/core-information-scope-invariant.test.ts +134 -0
  66. package/src/__tests__/cvc-136-scoring-invariant.test.ts +8 -3
  67. package/src/__tests__/cvc-181-182-country-parity.test.ts +163 -0
  68. package/src/__tests__/cvc-drift-gate.test.ts +463 -12
  69. package/src/__tests__/cvc-sot-snapshot.test.ts +81 -11
  70. package/src/__tests__/cvc-status-parser.test.ts +150 -0
  71. package/src/__tests__/cvc-structural.test.ts +16 -0
  72. package/src/__tests__/runtime-contract-validator.test.ts +1 -325
  73. package/src/__tests__/share-response-reason-invariant.test.ts +167 -0
  74. package/src/config/index.ts +4 -189
  75. package/src/constants/ic.ts +120 -3
  76. package/src/cvcs/assertionDomain.v1.1.0.json +19 -1
  77. package/src/cvcs/assertionStatus.v1.0.0.json +80 -0
  78. package/src/cvcs/carCorrectionReason.v1.0.0.json +89 -0
  79. package/src/cvcs/caseShareState.v1.0.0.json +62 -0
  80. package/src/cvcs/coreIndicators.v1.0.0.json +83 -5
  81. package/src/cvcs/coreInformationScope.v1.0.0.json +1165 -0
  82. package/src/cvcs/countries.v1.0.0.json +3077 -0
  83. package/src/cvcs/createdBySystem.v1.0.0.json +89 -0
  84. package/src/cvcs/criminalOrgCategory.v1.0.0.json +116 -0
  85. package/src/cvcs/determinationHelperCategories.v1.0.0.json +1166 -0
  86. package/src/cvcs/incidentParticipationRoles.v1.0.0.json +11 -1
  87. package/src/cvcs/index.ts +36 -0
  88. package/src/cvcs/minorAdultStatus.v1.0.0.json +80 -0
  89. package/src/cvcs/personRelationships.v1.0.0.json +67 -2
  90. package/src/cvcs/referralOrigin.v1.0.0.json +26 -0
  91. package/src/cvcs/relationshipConcern.v1.0.0.json +28 -19
  92. package/src/cvcs/riskIdentificationMilestone.v1.0.0.json +109 -0
  93. package/src/cvcs/sessionTemplate.v1.0.0.json +22 -0
  94. package/src/cvcs/sharePurpose.v1.0.0.json +80 -12
  95. package/src/cvcs/shareResponseReason.v1.0.0.json +220 -0
  96. package/src/cvcs/subjectType.v1.0.0.json +80 -0
  97. package/src/generated/cvc-enums.ts +628 -20
  98. package/src/validation/cvcStatus.ts +209 -0
  99. package/src/validation/index.ts +1 -0
@@ -20,17 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/config/index.ts
21
21
  var config_exports = {};
22
22
  __export(config_exports, {
23
- applyContractDefaults: () => applyContractDefaults,
24
- applyEnvLocal: () => applyEnvLocal,
25
23
  createConfigEndpoint: () => createConfigEndpoint,
26
24
  loadContract: () => loadContract,
27
- parseDotenv: () => parseDotenv,
28
25
  resolveDefault: () => resolveDefault,
29
26
  validateAgainstContract: () => validateAgainstContract
30
27
  });
31
28
  module.exports = __toCommonJS(config_exports);
32
29
  var import_node_fs = require("fs");
33
- var import_node_path = require("path");
34
30
  var import_yaml = require("yaml");
35
31
  function loadContract(runtimeYamlPath) {
36
32
  let raw;
@@ -107,83 +103,9 @@ function resolveDefault(spec, env) {
107
103
  if (v === void 0) return void 0;
108
104
  return String(v);
109
105
  }
110
- function applyContractDefaults(contract, env) {
111
- const applied = [];
112
- for (const [key, spec] of Object.entries(contract.variables)) {
113
- if (spec.phase === "build") continue;
114
- if (process.env[key] !== void 0) continue;
115
- const value = resolveDefault(spec, env);
116
- if (value === void 0) continue;
117
- process.env[key] = value;
118
- applied.push(key);
119
- }
120
- return applied;
121
- }
122
- var DOTENV_LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
123
- function indexOfUnescaped(s, quote) {
124
- for (let i = 0; i < s.length; i += 1) {
125
- if (s[i] === "\\") {
126
- i += 1;
127
- continue;
128
- }
129
- if (s[i] === quote) return i;
130
- }
131
- return -1;
132
- }
133
- function parseDotenv(content) {
134
- const out = {};
135
- const lines = content.split(/\r?\n/);
136
- for (let i = 0; i < lines.length; i += 1) {
137
- const trimmed = lines[i].trim();
138
- if (trimmed === "" || trimmed.startsWith("#")) continue;
139
- const match = DOTENV_LINE.exec(trimmed);
140
- if (!match) continue;
141
- const key = match[1];
142
- const rest = match[2].trim();
143
- const quote = rest.charAt(0);
144
- if (quote === '"' || quote === "'" || quote === "`") {
145
- let body = rest.slice(1);
146
- let end = indexOfUnescaped(body, quote);
147
- while (end === -1 && i + 1 < lines.length) {
148
- i += 1;
149
- body += `
150
- ${lines[i]}`;
151
- end = indexOfUnescaped(body, quote);
152
- }
153
- if (end === -1) continue;
154
- const value = body.slice(0, end);
155
- out[key] = quote === '"' ? value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\") : value;
156
- continue;
157
- }
158
- out[key] = rest.split(/\s+#/)[0].trimEnd();
159
- }
160
- return out;
161
- }
162
- function applyEnvLocal(path) {
163
- const file = path ?? (0, import_node_path.join)(process.cwd(), ".env.local");
164
- if (!(0, import_node_fs.existsSync)(file)) return [];
165
- let raw;
166
- try {
167
- raw = (0, import_node_fs.readFileSync)(file, "utf8");
168
- } catch (err) {
169
- const msg = err instanceof Error ? err.message : String(err);
170
- throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);
171
- }
172
- const parsed = parseDotenv(raw);
173
- for (const [key, value] of Object.entries(parsed)) {
174
- process.env[key] = value;
175
- }
176
- return Object.keys(parsed);
177
- }
178
106
  function validateAgainstContract(runtimeYamlPath, opts = {}) {
179
107
  const contract = loadContract(runtimeYamlPath);
180
- if (opts.applyEnvLocal !== false) {
181
- applyEnvLocal(opts.envLocalPath);
182
- }
183
108
  const env = opts.env ?? process.env.NODE_ENV ?? "local";
184
- if (opts.applyDefaults !== false) {
185
- applyContractDefaults(contract, env);
186
- }
187
109
  const errors = [];
188
110
  const result = {};
189
111
  for (const [key, spec] of Object.entries(contract.variables)) {
@@ -265,11 +187,8 @@ function createConfigEndpoint(runtimeYamlPath, opts = {}) {
265
187
  }
266
188
  // Annotate the CommonJS export names for ESM import in node:
267
189
  0 && (module.exports = {
268
- applyContractDefaults,
269
- applyEnvLocal,
270
190
  createConfigEndpoint,
271
191
  loadContract,
272
- parseDotenv,
273
192
  resolveDefault,
274
193
  validateAgainstContract
275
194
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * validateAgainstContract also LOADS config, not just validates it: it applies\n * the contract's per-tier defaults into process.env so that code reading\n * process.env.FOO directly sees the same value the validator resolved. This is\n * what removes the need for a materialized `.env.generated` file in local dev.\n *\n * Precedence, highest first:\n * 1. .env.local — local developer overrides; beat everything\n * 2. process.env — real deployed / materialized task-def values\n * 3. contract default — spec.default[<tier>]\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n /**\n * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.\n * Left untyped here to keep `config` free of a dependency on `mongo`; the\n * verifier validates its shape via `parseMongoBlock`.\n */\n mongo?: unknown;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n /**\n * Apply the contract's defaults for the resolved env into process.env for\n * every runtime variable that is not already set. Defaults to true.\n * An existing process.env value is never overwritten.\n */\n applyDefaults?: boolean;\n /**\n * Load `.env.local` and apply it over process.env before anything else.\n * Defaults to true; the file is optional, so a missing file is a no-op.\n */\n applyEnvLocal?: boolean;\n /**\n * Explicit path to the `.env.local` override file.\n * Defaults to `<process.cwd()>/.env.local`.\n */\n envLocalPath?: string;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nexport function loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nexport function resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n/**\n * Write the contract's defaults for `env` into process.env for every\n * runtime-phase variable that is not already set.\n *\n * A value already present in process.env — a real deployed env var, or one\n * materialized into a task definition — always wins and is left untouched.\n * An explicitly empty value (\"\") counts as present: it is a deliberate\n * choice by whoever set it, and the required-variable check still rejects it.\n *\n * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,\n * so process.env agrees with the value the validator itself resolved. Secret\n * values are never logged.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyContractDefaults(\n contract: ServiceContract,\n env: string,\n): string[] {\n const applied: string[] = [];\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n if (spec.phase === \"build\") continue;\n if (process.env[key] !== undefined) continue;\n\n const value = resolveDefault(spec, env);\n if (value === undefined) continue;\n\n process.env[key] = value;\n applied.push(key);\n }\n\n return applied;\n}\n\n// ─── .env.local overrides ────────────────────────────────────────────────────\n\n/** `KEY=`, `export KEY=`; everything after the first `=` is the raw value. */\nconst DOTENV_LINE = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=(.*)$/;\n\n/** Index of the next `quote` not preceded by a backslash, or -1. */\nfunction indexOfUnescaped(s: string, quote: string): number {\n for (let i = 0; i < s.length; i += 1) {\n if (s[i] === \"\\\\\") {\n i += 1;\n continue;\n }\n if (s[i] === quote) return i;\n }\n return -1;\n}\n\n/**\n * Parse `.env` file content into a plain object.\n *\n * Supported: blank lines, `#` comments, an optional `export ` prefix,\n * single-quoted / double-quoted / backtick-quoted values (which may span\n * multiple lines), and `\\n` `\\r` `\\t` `\\\\` escapes inside double quotes.\n * An unquoted value ends at a ` #` inline comment, so `#` may still be used\n * freely inside a quoted value or in the middle of a bare word.\n *\n * Malformed lines are skipped rather than thrown on: a typo in a developer's\n * local override file should not take down the whole process.\n */\nexport function parseDotenv(content: string): Record<string, string> {\n const out: Record<string, string> = {};\n const lines = content.split(/\\r?\\n/);\n\n for (let i = 0; i < lines.length; i += 1) {\n const trimmed = lines[i].trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n\n const match = DOTENV_LINE.exec(trimmed);\n if (!match) continue;\n\n const key = match[1];\n const rest = match[2].trim();\n const quote = rest.charAt(0);\n\n if (quote === '\"' || quote === \"'\" || quote === \"`\") {\n // Quoted value — keep consuming lines until the closing quote.\n let body = rest.slice(1);\n let end = indexOfUnescaped(body, quote);\n while (end === -1 && i + 1 < lines.length) {\n i += 1;\n body += `\\n${lines[i]}`;\n end = indexOfUnescaped(body, quote);\n }\n if (end === -1) continue; // unterminated quote — skip the entry\n\n const value = body.slice(0, end);\n out[key] =\n quote === '\"'\n ? value\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\r\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, \"\\\\\")\n : value;\n continue;\n }\n\n out[key] = rest.split(/\\s+#/)[0].trimEnd();\n }\n\n return out;\n}\n\n/**\n * Apply `.env.local` over process.env.\n *\n * `.env.local` has the last word in local development: it overwrites values\n * already present in process.env, and it runs before defaults are applied, so\n * it also beats every contract default. It may declare variables the contract\n * does not know about — a developer can add config without editing the\n * contract. The file is optional; a missing file is a no-op.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyEnvLocal(path?: string): string[] {\n const file = path ?? join(process.cwd(), \".env.local\");\n if (!existsSync(file)) return [];\n\n let raw: string;\n try {\n raw = readFileSync(file, \"utf8\");\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);\n }\n\n const parsed = parseDotenv(raw);\n for (const [key, value] of Object.entries(parsed)) {\n process.env[key] = value;\n }\n\n return Object.keys(parsed);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, load config into `process.env`, coerce every\n * runtime-phase variable, and fail fast on any missing or invalid required\n * variable (R3.2).\n *\n * Loading happens before validation, in precedence order:\n * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)\n * 2. contract defaults for the resolved env fill anything still unset\n * (opts.applyDefaults)\n *\n * `.env.local` is applied first so a developer can set NODE_ENV there and\n * have it select the tier whose defaults are applied.\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n\n if (opts.applyEnvLocal !== false) {\n applyEnvLocal(opts.envLocalPath);\n }\n\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n if (opts.applyDefaults !== false) {\n applyContractDefaults(contract, env);\n }\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,qBAAyC;AACzC,uBAAqB;AAErB,kBAAsB;AAqFf,SAAS,aAAa,iBAA0C;AACr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YAAM,IAAI;AAKV,QAAE,OAAO,iBAAiB,YAAY;AACtC,QAAE,KAAK,kBAAkB;AACzB,QAAE,KAAK,IAAI;AACX;AAAA,IACF;AAGA,WAAO,IAAI,SAAS,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n /**\n * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.\n * Left untyped here to keep `config` free of a dependency on `mongo`; the\n * verifier validates its shape via `parseMongoBlock`.\n */\n mongo?: unknown;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nexport function loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nexport function resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, coerce every runtime-phase variable from\n * `process.env` (with per-env defaults applied), and fail fast on any\n * missing or invalid required variable (R3.2).\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,qBAA6B;AAC7B,kBAAsB;AAqEf,SAAS,aAAa,iBAA0C;AACrE,MAAI;AACJ,MAAI;AACF,cAAM,6BAAa,iBAAiB,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,MACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,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GA,QAAI,OAAO,OAAQ,IAAgC,MAAM,MAAM,YAAY;AACzE,YAAM,IAAI;AAKV,QAAE,OAAO,iBAAiB,YAAY;AACtC,QAAE,KAAK,kBAAkB;AACzB,QAAE,KAAK,IAAI;AACX;AAAA,IACF;AAGA,WAAO,IAAI,SAAS,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -9,16 +9,6 @@
9
9
  * any other initialization that reads env vars. Build-phase variables
10
10
  * (phase: build) are NOT checked at runtime per R3.4.
11
11
  *
12
- * validateAgainstContract also LOADS config, not just validates it: it applies
13
- * the contract's per-tier defaults into process.env so that code reading
14
- * process.env.FOO directly sees the same value the validator resolved. This is
15
- * what removes the need for a materialized `.env.generated` file in local dev.
16
- *
17
- * Precedence, highest first:
18
- * 1. .env.local — local developer overrides; beat everything
19
- * 2. process.env — real deployed / materialized task-def values
20
- * 3. contract default — spec.default[<tier>]
21
- *
22
12
  * No secret VALUES are read, stored, or returned here. Secret env vars are
23
13
  * validated for presence but their values are never logged or exposed.
24
14
  *
@@ -69,22 +59,6 @@ interface ValidateOptions {
69
59
  * Useful for tests. Defaults to false (production mode exits).
70
60
  */
71
61
  throwOnFailure?: boolean;
72
- /**
73
- * Apply the contract's defaults for the resolved env into process.env for
74
- * every runtime variable that is not already set. Defaults to true.
75
- * An existing process.env value is never overwritten.
76
- */
77
- applyDefaults?: boolean;
78
- /**
79
- * Load `.env.local` and apply it over process.env before anything else.
80
- * Defaults to true; the file is optional, so a missing file is a no-op.
81
- */
82
- applyEnvLocal?: boolean;
83
- /**
84
- * Explicit path to the `.env.local` override file.
85
- * Defaults to `<process.cwd()>/.env.local`.
86
- */
87
- envLocalPath?: string;
88
62
  }
89
63
  interface EndpointOptions {
90
64
  /** Cache-Control header value. Defaults to "private, no-store". */
@@ -108,58 +82,9 @@ declare function loadContract(runtimeYamlPath: string): ServiceContract;
108
82
  */
109
83
  declare function resolveDefault(spec: VariableSpec, env: string): string | undefined;
110
84
  /**
111
- * Write the contract's defaults for `env` into process.env for every
112
- * runtime-phase variable that is not already set.
113
- *
114
- * A value already present in process.env — a real deployed env var, or one
115
- * materialized into a task definition — always wins and is left untouched.
116
- * An explicitly empty value ("") counts as present: it is a deliberate
117
- * choice by whoever set it, and the required-variable check still rejects it.
118
- *
119
- * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,
120
- * so process.env agrees with the value the validator itself resolved. Secret
121
- * values are never logged.
122
- *
123
- * Returns the names of the variables that were applied.
124
- */
125
- declare function applyContractDefaults(contract: ServiceContract, env: string): string[];
126
- /**
127
- * Parse `.env` file content into a plain object.
128
- *
129
- * Supported: blank lines, `#` comments, an optional `export ` prefix,
130
- * single-quoted / double-quoted / backtick-quoted values (which may span
131
- * multiple lines), and `\n` `\r` `\t` `\\` escapes inside double quotes.
132
- * An unquoted value ends at a ` #` inline comment, so `#` may still be used
133
- * freely inside a quoted value or in the middle of a bare word.
134
- *
135
- * Malformed lines are skipped rather than thrown on: a typo in a developer's
136
- * local override file should not take down the whole process.
137
- */
138
- declare function parseDotenv(content: string): Record<string, string>;
139
- /**
140
- * Apply `.env.local` over process.env.
141
- *
142
- * `.env.local` has the last word in local development: it overwrites values
143
- * already present in process.env, and it runs before defaults are applied, so
144
- * it also beats every contract default. It may declare variables the contract
145
- * does not know about — a developer can add config without editing the
146
- * contract. The file is optional; a missing file is a no-op.
147
- *
148
- * Returns the names of the variables that were applied.
149
- */
150
- declare function applyEnvLocal(path?: string): string[];
151
- /**
152
- * Parse `runtimeYamlPath`, load config into `process.env`, coerce every
153
- * runtime-phase variable, and fail fast on any missing or invalid required
154
- * variable (R3.2).
155
- *
156
- * Loading happens before validation, in precedence order:
157
- * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)
158
- * 2. contract defaults for the resolved env fill anything still unset
159
- * (opts.applyDefaults)
160
- *
161
- * `.env.local` is applied first so a developer can set NODE_ENV there and
162
- * have it select the tier whose defaults are applied.
85
+ * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
86
+ * `process.env` (with per-env defaults applied), and fail fast on any
87
+ * missing or invalid required variable (R3.2).
163
88
  *
164
89
  * Build-phase variables (phase: build) are skipped per R3.4.
165
90
  *
@@ -188,4 +113,4 @@ declare function validateAgainstContract(runtimeYamlPath: string, opts?: Validat
188
113
  */
189
114
  declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
190
115
 
191
- export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, applyContractDefaults, applyEnvLocal, createConfigEndpoint, loadContract, parseDotenv, resolveDefault, validateAgainstContract };
116
+ export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, loadContract, resolveDefault, validateAgainstContract };
@@ -9,16 +9,6 @@
9
9
  * any other initialization that reads env vars. Build-phase variables
10
10
  * (phase: build) are NOT checked at runtime per R3.4.
11
11
  *
12
- * validateAgainstContract also LOADS config, not just validates it: it applies
13
- * the contract's per-tier defaults into process.env so that code reading
14
- * process.env.FOO directly sees the same value the validator resolved. This is
15
- * what removes the need for a materialized `.env.generated` file in local dev.
16
- *
17
- * Precedence, highest first:
18
- * 1. .env.local — local developer overrides; beat everything
19
- * 2. process.env — real deployed / materialized task-def values
20
- * 3. contract default — spec.default[<tier>]
21
- *
22
12
  * No secret VALUES are read, stored, or returned here. Secret env vars are
23
13
  * validated for presence but their values are never logged or exposed.
24
14
  *
@@ -69,22 +59,6 @@ interface ValidateOptions {
69
59
  * Useful for tests. Defaults to false (production mode exits).
70
60
  */
71
61
  throwOnFailure?: boolean;
72
- /**
73
- * Apply the contract's defaults for the resolved env into process.env for
74
- * every runtime variable that is not already set. Defaults to true.
75
- * An existing process.env value is never overwritten.
76
- */
77
- applyDefaults?: boolean;
78
- /**
79
- * Load `.env.local` and apply it over process.env before anything else.
80
- * Defaults to true; the file is optional, so a missing file is a no-op.
81
- */
82
- applyEnvLocal?: boolean;
83
- /**
84
- * Explicit path to the `.env.local` override file.
85
- * Defaults to `<process.cwd()>/.env.local`.
86
- */
87
- envLocalPath?: string;
88
62
  }
89
63
  interface EndpointOptions {
90
64
  /** Cache-Control header value. Defaults to "private, no-store". */
@@ -108,58 +82,9 @@ declare function loadContract(runtimeYamlPath: string): ServiceContract;
108
82
  */
109
83
  declare function resolveDefault(spec: VariableSpec, env: string): string | undefined;
110
84
  /**
111
- * Write the contract's defaults for `env` into process.env for every
112
- * runtime-phase variable that is not already set.
113
- *
114
- * A value already present in process.env — a real deployed env var, or one
115
- * materialized into a task definition — always wins and is left untouched.
116
- * An explicitly empty value ("") counts as present: it is a deliberate
117
- * choice by whoever set it, and the required-variable check still rejects it.
118
- *
119
- * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,
120
- * so process.env agrees with the value the validator itself resolved. Secret
121
- * values are never logged.
122
- *
123
- * Returns the names of the variables that were applied.
124
- */
125
- declare function applyContractDefaults(contract: ServiceContract, env: string): string[];
126
- /**
127
- * Parse `.env` file content into a plain object.
128
- *
129
- * Supported: blank lines, `#` comments, an optional `export ` prefix,
130
- * single-quoted / double-quoted / backtick-quoted values (which may span
131
- * multiple lines), and `\n` `\r` `\t` `\\` escapes inside double quotes.
132
- * An unquoted value ends at a ` #` inline comment, so `#` may still be used
133
- * freely inside a quoted value or in the middle of a bare word.
134
- *
135
- * Malformed lines are skipped rather than thrown on: a typo in a developer's
136
- * local override file should not take down the whole process.
137
- */
138
- declare function parseDotenv(content: string): Record<string, string>;
139
- /**
140
- * Apply `.env.local` over process.env.
141
- *
142
- * `.env.local` has the last word in local development: it overwrites values
143
- * already present in process.env, and it runs before defaults are applied, so
144
- * it also beats every contract default. It may declare variables the contract
145
- * does not know about — a developer can add config without editing the
146
- * contract. The file is optional; a missing file is a no-op.
147
- *
148
- * Returns the names of the variables that were applied.
149
- */
150
- declare function applyEnvLocal(path?: string): string[];
151
- /**
152
- * Parse `runtimeYamlPath`, load config into `process.env`, coerce every
153
- * runtime-phase variable, and fail fast on any missing or invalid required
154
- * variable (R3.2).
155
- *
156
- * Loading happens before validation, in precedence order:
157
- * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)
158
- * 2. contract defaults for the resolved env fill anything still unset
159
- * (opts.applyDefaults)
160
- *
161
- * `.env.local` is applied first so a developer can set NODE_ENV there and
162
- * have it select the tier whose defaults are applied.
85
+ * Parse `runtimeYamlPath`, coerce every runtime-phase variable from
86
+ * `process.env` (with per-env defaults applied), and fail fast on any
87
+ * missing or invalid required variable (R3.2).
163
88
  *
164
89
  * Build-phase variables (phase: build) are skipped per R3.4.
165
90
  *
@@ -188,4 +113,4 @@ declare function validateAgainstContract(runtimeYamlPath: string, opts?: Validat
188
113
  */
189
114
  declare function createConfigEndpoint(runtimeYamlPath: string, opts?: EndpointOptions): RouteHandler;
190
115
 
191
- export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, applyContractDefaults, applyEnvLocal, createConfigEndpoint, loadContract, parseDotenv, resolveDefault, validateAgainstContract };
116
+ export { type EndpointOptions, type RouteHandler, type ServiceContract, type TypedConfig, type ValidateOptions, type VariableSpec, createConfigEndpoint, loadContract, resolveDefault, validateAgainstContract };
@@ -1,6 +1,5 @@
1
1
  // src/config/index.ts
2
- import { existsSync, readFileSync } from "fs";
3
- import { join } from "path";
2
+ import { readFileSync } from "fs";
4
3
  import { parse } from "yaml";
5
4
  function loadContract(runtimeYamlPath) {
6
5
  let raw;
@@ -77,83 +76,9 @@ function resolveDefault(spec, env) {
77
76
  if (v === void 0) return void 0;
78
77
  return String(v);
79
78
  }
80
- function applyContractDefaults(contract, env) {
81
- const applied = [];
82
- for (const [key, spec] of Object.entries(contract.variables)) {
83
- if (spec.phase === "build") continue;
84
- if (process.env[key] !== void 0) continue;
85
- const value = resolveDefault(spec, env);
86
- if (value === void 0) continue;
87
- process.env[key] = value;
88
- applied.push(key);
89
- }
90
- return applied;
91
- }
92
- var DOTENV_LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
93
- function indexOfUnescaped(s, quote) {
94
- for (let i = 0; i < s.length; i += 1) {
95
- if (s[i] === "\\") {
96
- i += 1;
97
- continue;
98
- }
99
- if (s[i] === quote) return i;
100
- }
101
- return -1;
102
- }
103
- function parseDotenv(content) {
104
- const out = {};
105
- const lines = content.split(/\r?\n/);
106
- for (let i = 0; i < lines.length; i += 1) {
107
- const trimmed = lines[i].trim();
108
- if (trimmed === "" || trimmed.startsWith("#")) continue;
109
- const match = DOTENV_LINE.exec(trimmed);
110
- if (!match) continue;
111
- const key = match[1];
112
- const rest = match[2].trim();
113
- const quote = rest.charAt(0);
114
- if (quote === '"' || quote === "'" || quote === "`") {
115
- let body = rest.slice(1);
116
- let end = indexOfUnescaped(body, quote);
117
- while (end === -1 && i + 1 < lines.length) {
118
- i += 1;
119
- body += `
120
- ${lines[i]}`;
121
- end = indexOfUnescaped(body, quote);
122
- }
123
- if (end === -1) continue;
124
- const value = body.slice(0, end);
125
- out[key] = quote === '"' ? value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\") : value;
126
- continue;
127
- }
128
- out[key] = rest.split(/\s+#/)[0].trimEnd();
129
- }
130
- return out;
131
- }
132
- function applyEnvLocal(path) {
133
- const file = path ?? join(process.cwd(), ".env.local");
134
- if (!existsSync(file)) return [];
135
- let raw;
136
- try {
137
- raw = readFileSync(file, "utf8");
138
- } catch (err) {
139
- const msg = err instanceof Error ? err.message : String(err);
140
- throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);
141
- }
142
- const parsed = parseDotenv(raw);
143
- for (const [key, value] of Object.entries(parsed)) {
144
- process.env[key] = value;
145
- }
146
- return Object.keys(parsed);
147
- }
148
79
  function validateAgainstContract(runtimeYamlPath, opts = {}) {
149
80
  const contract = loadContract(runtimeYamlPath);
150
- if (opts.applyEnvLocal !== false) {
151
- applyEnvLocal(opts.envLocalPath);
152
- }
153
81
  const env = opts.env ?? process.env.NODE_ENV ?? "local";
154
- if (opts.applyDefaults !== false) {
155
- applyContractDefaults(contract, env);
156
- }
157
82
  const errors = [];
158
83
  const result = {};
159
84
  for (const [key, spec] of Object.entries(contract.variables)) {
@@ -234,11 +159,8 @@ function createConfigEndpoint(runtimeYamlPath, opts = {}) {
234
159
  };
235
160
  }
236
161
  export {
237
- applyContractDefaults,
238
- applyEnvLocal,
239
162
  createConfigEndpoint,
240
163
  loadContract,
241
- parseDotenv,
242
164
  resolveDefault,
243
165
  validateAgainstContract
244
166
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * validateAgainstContract also LOADS config, not just validates it: it applies\n * the contract's per-tier defaults into process.env so that code reading\n * process.env.FOO directly sees the same value the validator resolved. This is\n * what removes the need for a materialized `.env.generated` file in local dev.\n *\n * Precedence, highest first:\n * 1. .env.local — local developer overrides; beat everything\n * 2. process.env — real deployed / materialized task-def values\n * 3. contract default — spec.default[<tier>]\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n /**\n * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.\n * Left untyped here to keep `config` free of a dependency on `mongo`; the\n * verifier validates its shape via `parseMongoBlock`.\n */\n mongo?: unknown;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n /**\n * Apply the contract's defaults for the resolved env into process.env for\n * every runtime variable that is not already set. Defaults to true.\n * An existing process.env value is never overwritten.\n */\n applyDefaults?: boolean;\n /**\n * Load `.env.local` and apply it over process.env before anything else.\n * Defaults to true; the file is optional, so a missing file is a no-op.\n */\n applyEnvLocal?: boolean;\n /**\n * Explicit path to the `.env.local` override file.\n * Defaults to `<process.cwd()>/.env.local`.\n */\n envLocalPath?: string;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nexport function loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nexport function resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n/**\n * Write the contract's defaults for `env` into process.env for every\n * runtime-phase variable that is not already set.\n *\n * A value already present in process.env — a real deployed env var, or one\n * materialized into a task definition — always wins and is left untouched.\n * An explicitly empty value (\"\") counts as present: it is a deliberate\n * choice by whoever set it, and the required-variable check still rejects it.\n *\n * Build-phase variables are skipped (R3.4); secret variables are NOT skipped,\n * so process.env agrees with the value the validator itself resolved. Secret\n * values are never logged.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyContractDefaults(\n contract: ServiceContract,\n env: string,\n): string[] {\n const applied: string[] = [];\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n if (spec.phase === \"build\") continue;\n if (process.env[key] !== undefined) continue;\n\n const value = resolveDefault(spec, env);\n if (value === undefined) continue;\n\n process.env[key] = value;\n applied.push(key);\n }\n\n return applied;\n}\n\n// ─── .env.local overrides ────────────────────────────────────────────────────\n\n/** `KEY=`, `export KEY=`; everything after the first `=` is the raw value. */\nconst DOTENV_LINE = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=(.*)$/;\n\n/** Index of the next `quote` not preceded by a backslash, or -1. */\nfunction indexOfUnescaped(s: string, quote: string): number {\n for (let i = 0; i < s.length; i += 1) {\n if (s[i] === \"\\\\\") {\n i += 1;\n continue;\n }\n if (s[i] === quote) return i;\n }\n return -1;\n}\n\n/**\n * Parse `.env` file content into a plain object.\n *\n * Supported: blank lines, `#` comments, an optional `export ` prefix,\n * single-quoted / double-quoted / backtick-quoted values (which may span\n * multiple lines), and `\\n` `\\r` `\\t` `\\\\` escapes inside double quotes.\n * An unquoted value ends at a ` #` inline comment, so `#` may still be used\n * freely inside a quoted value or in the middle of a bare word.\n *\n * Malformed lines are skipped rather than thrown on: a typo in a developer's\n * local override file should not take down the whole process.\n */\nexport function parseDotenv(content: string): Record<string, string> {\n const out: Record<string, string> = {};\n const lines = content.split(/\\r?\\n/);\n\n for (let i = 0; i < lines.length; i += 1) {\n const trimmed = lines[i].trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n\n const match = DOTENV_LINE.exec(trimmed);\n if (!match) continue;\n\n const key = match[1];\n const rest = match[2].trim();\n const quote = rest.charAt(0);\n\n if (quote === '\"' || quote === \"'\" || quote === \"`\") {\n // Quoted value — keep consuming lines until the closing quote.\n let body = rest.slice(1);\n let end = indexOfUnescaped(body, quote);\n while (end === -1 && i + 1 < lines.length) {\n i += 1;\n body += `\\n${lines[i]}`;\n end = indexOfUnescaped(body, quote);\n }\n if (end === -1) continue; // unterminated quote — skip the entry\n\n const value = body.slice(0, end);\n out[key] =\n quote === '\"'\n ? value\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\r/g, \"\\r\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, \"\\\\\")\n : value;\n continue;\n }\n\n out[key] = rest.split(/\\s+#/)[0].trimEnd();\n }\n\n return out;\n}\n\n/**\n * Apply `.env.local` over process.env.\n *\n * `.env.local` has the last word in local development: it overwrites values\n * already present in process.env, and it runs before defaults are applied, so\n * it also beats every contract default. It may declare variables the contract\n * does not know about — a developer can add config without editing the\n * contract. The file is optional; a missing file is a no-op.\n *\n * Returns the names of the variables that were applied.\n */\nexport function applyEnvLocal(path?: string): string[] {\n const file = path ?? join(process.cwd(), \".env.local\");\n if (!existsSync(file)) return [];\n\n let raw: string;\n try {\n raw = readFileSync(file, \"utf8\");\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[platform-common/config] Cannot read ${file}: ${msg}`);\n }\n\n const parsed = parseDotenv(raw);\n for (const [key, value] of Object.entries(parsed)) {\n process.env[key] = value;\n }\n\n return Object.keys(parsed);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, load config into `process.env`, coerce every\n * runtime-phase variable, and fail fast on any missing or invalid required\n * variable (R3.2).\n *\n * Loading happens before validation, in precedence order:\n * 1. `.env.local` is applied over process.env (opts.applyEnvLocal)\n * 2. contract defaults for the resolved env fill anything still unset\n * (opts.applyDefaults)\n *\n * `.env.local` is applied first so a developer can set NODE_ENV there and\n * have it select the tier whose defaults are applied.\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n\n if (opts.applyEnvLocal !== false) {\n applyEnvLocal(opts.envLocalPath);\n }\n\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n if (opts.applyDefaults !== false) {\n applyContractDefaults(contract, env);\n }\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":";AA4BA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AAErB,SAAS,aAAa;AAqFf,SAAS,aAAa,iBAA0C;AACrE,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,iBAAiB,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,MACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,wCAAwC,eAAe,KAAK,GAAG;AAAA,IACjE;AAAA,EACF;AACA,QAAM,SAAS,MAAM,GAAG;AACxB,MAAI,CAAC,UAAU,OAAO,WAAW,UAAU;AACzC,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,OAAO,YAAY,GAAG;AACxB,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe,kCAAkC,OAAO,OAAO;AAAA,IAC7F;AAAA,EACF;AACA,MAAI,CAAC,OAAO,aAAa,OAAO,OAAO,cAAc,UAAU;AAC7D,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AA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W;AAEvB,UAAM,CAAC,IAAI,OAAO,IAAI,OAAO,KAAK,KAAK,IAAI;AAC3C,YAAQ,GAAG,IAAI,KAAK,UAAU;AAAA,EAChC;AAEA,SAAO;AACT;AAsBO,SAAS,qBACd,iBACA,OAAwB,CAAC,GACX;AACd,QAAM,WAAW,aAAa,eAAe;AAC7C,QAAM,MACH,QAAQ,IAAI,YAAmC;AAClD,QAAM,UAAU,mBAAmB,UAAU,GAAG;AAChD,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,OAAO,KAAK,UAAU,OAAO;AAEnC,SAAO,SAAS,cACd,MACA,KAC4C;AAE5C,QAAI,OAAO,OAAQ,IAAgC,MAAM,MAAM,YAAY;AACzE,YAAM,IAAI;AAIV,QAAE,UAAU,iBAAiB,YAAY;AACzC,QAAE,UAAU,gBAAgB,kBAAkB;AAC9C,QAAE,KAAK,OAAO;AACd;AAAA,IACF;AAGA,QAAI,OAAO,OAAQ,IAAgC,MAAM,MAAM,YAAY;AACzE,YAAM,IAAI;AAKV,QAAE,OAAO,iBAAiB,YAAY;AACtC,QAAE,KAAK,kBAAkB;AACzB,QAAE,KAAK,IAAI;AACX;AAAA,IACF;AAGA,WAAO,IAAI,SAAS,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Runtime Config Contract Validator\n *\n * Implements contract R12.1 (platform-common home):\n * - validateAgainstContract(runtimeYamlPath, opts?) — startup validator (R3.2)\n * - createConfigEndpoint(runtimeYamlPath, opts?) — /api/config factory (R7)\n *\n * Consumers MUST call validateAgainstContract once at process startup, before\n * any other initialization that reads env vars. Build-phase variables\n * (phase: build) are NOT checked at runtime per R3.4.\n *\n * No secret VALUES are read, stored, or returned here. Secret env vars are\n * validated for presence but their values are never logged or exposed.\n *\n * Dual ESM + CJS via tsup. Plain JS consumers (pave, leads) use require():\n * const { validateAgainstContract } = require('@htilabs/platform-common-models/config');\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parse } from \"yaml\";\n\n// ─── Schema types (mirrors thread's runtime-config-lib.ts VariableSpec) ──────\n\nexport interface VariableSpec {\n type: \"string\" | \"boolean\" | \"number\" | \"enum\" | \"url\" | \"json\";\n required: boolean;\n secret: boolean;\n description: string;\n phase?: \"runtime\" | \"build\";\n values?: string[];\n default?: Record<string, unknown>;\n provider?: string;\n name?: string;\n client_visible?: boolean;\n deprecated?: { since: string; remove_after?: string; replacement?: string };\n}\n\nexport interface ServiceContract {\n service: string;\n version: number;\n environments: string[];\n // Thread extensions (tolerated, not required — R1.1 note)\n port?: number;\n build_secrets?: string[];\n variables: Record<string, VariableSpec>;\n /**\n * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.\n * Left untyped here to keep `config` free of a dependency on `mongo`; the\n * verifier validates its shape via `parseMongoBlock`.\n */\n mongo?: unknown;\n}\n\n/** Typed config accessor returned by validateAgainstContract. */\nexport type TypedConfig = Record<string, string | boolean | number | unknown>;\n\nexport interface ValidateOptions {\n /**\n * Environment name used to select per-env defaults (e.g. \"local\", \"test\").\n * Defaults to process.env.NODE_ENV, then \"local\".\n */\n env?: string;\n /**\n * If true, do not call process.exit(1) on failure; throw instead.\n * Useful for tests. Defaults to false (production mode exits).\n */\n throwOnFailure?: boolean;\n}\n\nexport interface EndpointOptions {\n /** Cache-Control header value. Defaults to \"private, no-store\". */\n cacheControl?: string;\n}\n\n/**\n * A framework-agnostic route handler that returns a JSON response.\n * Compatible with:\n * - Next.js App Router: export const GET = createConfigEndpoint(...)\n * - Fastify: instance.get('/api/config', createConfigEndpoint(...))\n * - Express: app.get('/api/config', createConfigEndpoint(...))\n */\nexport type RouteHandler = (\n req?: unknown,\n res?: unknown,\n) => Promise<Response | void> | Response | void;\n\n// ─── YAML parser ──────────────────────────────────────────────────────────────\n\nexport function loadContract(runtimeYamlPath: string): ServiceContract {\n let raw: string;\n try {\n raw = readFileSync(runtimeYamlPath, \"utf8\");\n } catch (err) {\n const msg =\n err instanceof Error ? err.message : String(err);\n throw new Error(\n `[platform-common/config] Cannot read ${runtimeYamlPath}: ${msg}`,\n );\n }\n const parsed = parse(raw) as ServiceContract | null;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: not a YAML mapping`,\n );\n }\n if (parsed.version !== 1) {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: unsupported contract version ${parsed.version} (expected 1)`,\n );\n }\n if (!parsed.variables || typeof parsed.variables !== \"object\") {\n throw new Error(\n `[platform-common/config] ${runtimeYamlPath}: missing \"variables\" map`,\n );\n }\n return parsed;\n}\n\n// ─── Coercion ────────────────────────────────────────────────────────────────\n\n/**\n * Coerce a raw environment string value to the declared type.\n * Returns [ok, coerced] or [false, errorMessage].\n */\nfunction coerce(\n key: string,\n raw: string,\n spec: VariableSpec,\n): [true, unknown] | [false, string] {\n switch (spec.type) {\n case \"boolean\": {\n if (raw === \"true\" || raw === \"1\") return [true, true];\n if (raw === \"false\" || raw === \"0\") return [true, false];\n return [false, `${key}: expected boolean (\"true\"/\"false\"/\"1\"/\"0\"), got \"${raw}\"`];\n }\n case \"number\": {\n const n = Number(raw);\n if (!Number.isFinite(n)) {\n return [false, `${key}: expected number, got \"${raw}\"`];\n }\n return [true, n];\n }\n case \"enum\": {\n const vals = spec.values ?? [];\n if (!vals.includes(raw)) {\n return [false, `${key}: expected one of [${vals.join(\", \")}], got \"${raw}\"`];\n }\n return [true, raw];\n }\n case \"url\": {\n try {\n new URL(raw);\n return [true, raw];\n } catch {\n return [false, `${key}: expected a valid URL, got \"${raw}\"`];\n }\n }\n case \"json\": {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return [true, parsed];\n } catch {\n return [false, `${key}: expected valid JSON, got \"${raw}\"`];\n }\n }\n default:\n // string\n return [true, raw];\n }\n}\n\n// ─── Default application ─────────────────────────────────────────────────────\n\n/**\n * Returns the default value for a variable in the given environment,\n * or undefined if no default applies.\n *\n * Exact env match only — defaults are per-environment and MUST NOT bleed\n * across envs. (A local default stays local; it does not fall back into prod.)\n */\nexport function resolveDefault(\n spec: VariableSpec,\n env: string,\n): string | undefined {\n if (!spec.default) return undefined;\n const v = spec.default[env];\n if (v === undefined) return undefined;\n return String(v);\n}\n\n// ─── validateAgainstContract ─────────────────────────────────────────────────\n\n/**\n * Parse `runtimeYamlPath`, coerce every runtime-phase variable from\n * `process.env` (with per-env defaults applied), and fail fast on any\n * missing or invalid required variable (R3.2).\n *\n * Build-phase variables (phase: build) are skipped per R3.4.\n *\n * Returns a typed config object keyed by variable name.\n */\nexport function validateAgainstContract(\n runtimeYamlPath: string,\n opts: ValidateOptions = {},\n): TypedConfig {\n const contract = loadContract(runtimeYamlPath);\n const env =\n opts.env ??\n (process.env.NODE_ENV as string | undefined) ??\n \"local\";\n\n const errors: string[] = [];\n const result: TypedConfig = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R3.4: skip build-phase variables entirely at runtime.\n if (spec.phase === \"build\") continue;\n\n const rawFromEnv = process.env[key];\n const defaultValue = resolveDefault(spec, env);\n const effective = rawFromEnv ?? defaultValue;\n\n if (effective === undefined || effective === \"\") {\n if (spec.required) {\n errors.push(\n `${key}: required but not set (no value in process.env and no default for env \"${env}\")`,\n );\n }\n // Not required and not set — omit from result.\n continue;\n }\n\n const [ok, coerced] = coerce(key, effective, spec);\n if (!ok) {\n errors.push(coerced as string);\n continue;\n }\n result[key] = coerced;\n }\n\n if (errors.length > 0) {\n const message = [\n `[platform-common/config] validateAgainstContract failed for ${runtimeYamlPath}`,\n `${errors.length} variable(s) missing or invalid:`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n if (opts.throwOnFailure) {\n throw new Error(message);\n }\n console.error(message);\n process.exit(1);\n }\n\n return result;\n}\n\n// ─── createConfigEndpoint ────────────────────────────────────────────────────\n\n/**\n * Build a static JSON payload containing only variables that are\n * client_visible: true AND secret: false (R7.2, R7.3). Reads process.env\n * once at factory call time.\n */\nfunction buildClientPayload(\n contract: ServiceContract,\n env: string,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n\n for (const [key, spec] of Object.entries(contract.variables)) {\n // R7.3: never expose secrets.\n if (spec.secret) continue;\n // R7.2: only expose client_visible vars.\n if (!spec.client_visible) continue;\n // R3.4: build-phase vars are not available at runtime.\n if (spec.phase === \"build\") continue;\n\n const raw = process.env[key] ?? resolveDefault(spec, env);\n if (raw === undefined) continue;\n\n const [ok, coerced] = coerce(key, raw, spec);\n payload[key] = ok ? coerced : raw;\n }\n\n return payload;\n}\n\n/**\n * Route-handler factory for GET /api/config (R7.1).\n *\n * Reads the contract and process.env once at factory-call time and caches\n * the JSON payload. The returned handler is compatible with:\n *\n * Next.js App Router:\n * export const GET = createConfigEndpoint(path);\n *\n * Fastify:\n * instance.get('/api/config', createConfigEndpoint(path));\n *\n * Express:\n * app.get('/api/config', createConfigEndpoint(path));\n *\n * The handler detects the calling convention at runtime:\n * - Next.js / fetch-native: called with no arguments; returns a Response.\n * - Express: called with (req, res); calls res.json() and returns void.\n * - Fastify: called with (req, reply); calls reply.send() and returns void.\n */\nexport function createConfigEndpoint(\n runtimeYamlPath: string,\n opts: EndpointOptions = {},\n): RouteHandler {\n const contract = loadContract(runtimeYamlPath);\n const env =\n (process.env.NODE_ENV as string | undefined) ?? \"local\";\n const payload = buildClientPayload(contract, env);\n const cacheControl = opts.cacheControl ?? \"private, no-store\";\n const body = JSON.stringify(payload);\n\n return function configHandler(\n _req?: unknown,\n res?: unknown,\n ): Promise<Response | void> | Response | void {\n // Express-shaped: res has .json()\n if (res && typeof (res as Record<string, unknown>)[\"json\"] === \"function\") {\n const r = res as {\n setHeader: (k: string, v: string) => void;\n json: (data: unknown) => void;\n };\n r.setHeader(\"Cache-Control\", cacheControl);\n r.setHeader(\"Content-Type\", \"application/json\");\n r.json(payload);\n return;\n }\n\n // Fastify-shaped: res has .send()\n if (res && typeof (res as Record<string, unknown>)[\"send\"] === \"function\") {\n const r = res as {\n header: (k: string, v: string) => void;\n type: (ct: string) => void;\n send: (data: string) => void;\n };\n r.header(\"Cache-Control\", cacheControl);\n r.type(\"application/json\");\n r.send(body);\n return;\n }\n\n // Next.js / fetch-native (no res argument, or unrecognised res)\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": cacheControl,\n },\n });\n };\n}\n"],"mappings":";AAkBA,SAAS,oBAAoB;AAC7B,SAAS,aAAa;AAqEf,SAAS,aAAa,iBAA0C;AACrE,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,iBAAiB,MAAM;AAAA,EAC5C,SAAS,KAAK;AACZ,UAAM,MACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,wCAAwC,eAAe,KAAK,GAAG;AAAA,IACjE;AAAA,EACF;AACA,QAAM,SAAS,MAAM,GAAG;AACxB,MAAI,CAAC,UAAU,OAAO,WAAW,UAAU;AACzC,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,OAAO,YAAY,GAAG;AACxB,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe,kCAAkC,OAAO,OAAO;AAAA,IAC7F;AAAA,EACF;AACA,MAAI,CAAC,OAAO,aAAa,OAAO,OAAO,cAAc,UAAU;AAC7D,UAAM,IAAI;AAAA,MACR,4BAA4B,eAAe;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AAQA,SAAS,OACP,KACA,KACA,MACmC;AACnC,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK,WAAW;AACd,UAAI,QAAQ,UAAU,QAAQ,IAAK,QAAO,CAAC,MAAM,IAAI;AACrD,UAAI,QAAQ,WAAW,QAAQ,IAAK,QAAO,CAAC,MAA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