@myvitalrx/metadata-runtime 0.0.0-stage → 1.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,4793 @@
1
+ import { z } from 'zod';
2
+ import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
3
+ import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
4
+ import crypto, { createHash } from 'crypto';
5
+ import { createLogger, createPerformanceTimer } from '@myvitalrx/platform-tools/observability';
6
+ import { AsyncLocalStorage } from 'async_hooks';
7
+ import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
8
+
9
+ // ../../libs/runtime-metadata/src/lib/constants/RuntimeMetadataConstants.ts
10
+ var CACHE_STATUS = {
11
+ EMPTY: "empty",
12
+ READY: "ready",
13
+ REFRESHING: "refreshing",
14
+ DEGRADED: "degraded",
15
+ STALE: "stale"
16
+ };
17
+ var REFRESH_STATUS = {
18
+ IDLE: "idle",
19
+ IN_PROGRESS: "inProgress",
20
+ SUCCEEDED: "succeeded",
21
+ FAILED: "failed"
22
+ };
23
+ var RUNTIME_METADATA_EVENTS = {
24
+ INIT_START: "runtimeMetadata.init.start",
25
+ INIT_COMPLETE: "runtimeMetadata.init.complete",
26
+ INIT_FAILED: "runtimeMetadata.init.failed",
27
+ REFRESH_START: "runtimeMetadata.refresh.start",
28
+ REFRESH_COMPLETE: "runtimeMetadata.refresh.complete",
29
+ REFRESH_FAILED: "runtimeMetadata.refresh.failed",
30
+ REFRESH_SKIPPED: "runtimeMetadata.refresh.skipped",
31
+ DOWNLOAD_START: "runtimeMetadata.download.start",
32
+ DOWNLOAD_COMPLETE: "runtimeMetadata.download.complete",
33
+ DOWNLOAD_FAILED: "runtimeMetadata.download.failed",
34
+ MANIFEST_LOADED: "runtimeMetadata.manifest.loaded",
35
+ /** Authoritative keys after manifest parse (metadataTypes + lookupIndex type prefixes). */
36
+ PROJECTION_MANIFEST_LOADED: "projection.manifest.loaded",
37
+ /** Per-file download begin. */
38
+ PROJECTION_FILE_LOADING: "projection.file.loading",
39
+ /** Per-file download + parse complete. */
40
+ PROJECTION_FILE_LOADED: "projection.file.loaded",
41
+ /** Selective skip: requested type has no integrity entry in this release. */
42
+ PROJECTION_FILE_SKIPPED: "projection.file.skipped",
43
+ /** Domain type registered into the in-memory cache index. */
44
+ PROJECTION_CACHE_REGISTER: "projection.cache.register",
45
+ /** supportsType decision with availableTypes for diagnosis. */
46
+ PROJECTION_PROVIDER_SUPPORTS_TYPE: "projection.provider.supportsType",
47
+ /** getProjection / soft miss diagnosis. */
48
+ PROJECTION_PROVIDER_GET_PROJECTION: "projection.provider.getProjection",
49
+ /** Post-initialize loaded type catalog. */
50
+ RUNTIME_METADATA_INITIALIZED: "runtime.metadata.initialized",
51
+ LOOKUP_MISS: "runtimeMetadata.lookup.miss",
52
+ PERIODIC_CHECK: "runtimeMetadata.periodic.check",
53
+ CACHE_HIT: "metadata_cache_hit",
54
+ CACHE_MISS: "metadata_cache_miss",
55
+ BATCH_LOOKUP: "metadata_batch_lookup",
56
+ PROVIDER_SELECTED: "runtimeMetadata.provider.selected",
57
+ PROVIDER_FALLBACK: "runtimeMetadata.provider.fallback",
58
+ PROVIDER_RECOVERED: "runtimeMetadata.provider.recovered"
59
+ };
60
+
61
+ // ../../libs/metadata-projection/src/lib/constants/ProjectionConstants.ts
62
+ var PROJECTION_SCHEMA_VERSION = 2;
63
+ var PROJECTION_VERSION = "1.0";
64
+ var DEFAULT_STORAGE_PREFIX = "metadata-projections";
65
+ var CURRENT_POINTER_FILE_NAME = "current.json";
66
+ var RELEASES_FOLDER_NAME = "releases";
67
+ var PROJECTION_TYPE = {
68
+ /** @deprecated Legacy — Metadata Type `Condition`. */
69
+ CONDITION: "Condition",
70
+ /** @deprecated Legacy — Metadata Type `MetricCode`. */
71
+ METRIC: "MetricCode",
72
+ /** @deprecated Legacy — Metadata Type `QuestionCode`. */
73
+ QUESTION: "QuestionCode",
74
+ /** @deprecated Legacy — Metadata Type `Category`. */
75
+ CATEGORY: "Category",
76
+ /** @deprecated Legacy — Metadata Type `PackageType`. */
77
+ PACKAGE: "PackageType",
78
+ /** @deprecated Use PACKAGE — kept as alias for gradual migration. */
79
+ PACKAGE_TYPE: "PackageType",
80
+ /** @deprecated Legacy — Metadata Type `Country`. */
81
+ COUNTRY: "Country",
82
+ /** @deprecated Legacy — Metadata Type `Language`. */
83
+ LANGUAGE: "Language",
84
+ COMMON: "common",
85
+ /**
86
+ * Bidirectional relationship lookup artifact (`relationship-index.json`).
87
+ * Platform file — not a domain Metadata Type.
88
+ */
89
+ RELATIONSHIP_INDEX: "relationshipIndex",
90
+ /**
91
+ * @deprecated Removed from publish — capabilities live on manifest.json.
92
+ * Kept so transitional parsers can ignore leftover objects.
93
+ */
94
+ RUNTIME_CONFIG: "runtimeConfig",
95
+ MANIFEST: "manifest",
96
+ LOCALIZATION: "localization"
97
+ };
98
+ var PROJECTION_FILE_NAME = {
99
+ [PROJECTION_TYPE.CONDITION]: "Condition.json",
100
+ [PROJECTION_TYPE.METRIC]: "MetricCode.json",
101
+ [PROJECTION_TYPE.QUESTION]: "QuestionCode.json",
102
+ [PROJECTION_TYPE.CATEGORY]: "Category.json",
103
+ [PROJECTION_TYPE.PACKAGE]: "PackageType.json",
104
+ [PROJECTION_TYPE.COUNTRY]: "Country.json",
105
+ [PROJECTION_TYPE.LANGUAGE]: "Language.json",
106
+ [PROJECTION_TYPE.COMMON]: "common.json",
107
+ [PROJECTION_TYPE.RELATIONSHIP_INDEX]: "relationship-index.json",
108
+ /** @deprecated No longer published. */
109
+ [PROJECTION_TYPE.RUNTIME_CONFIG]: "runtime-config.json",
110
+ [PROJECTION_TYPE.MANIFEST]: "manifest.json"
111
+ };
112
+ var PROJECTION_STATUS = {
113
+ ACTIVE: "active",
114
+ INACTIVE: "inactive",
115
+ DELETED: "deleted"
116
+ };
117
+
118
+ // ../../libs/metadata-projection/src/lib/models/ProjectionManifest.ts
119
+ function lookupIndexKey(typeCode, valueCode) {
120
+ return `${typeCode}:${valueCode}`;
121
+ }
122
+ var STATUS = {
123
+ ACTIVE: "ACTIVE",
124
+ INACTIVE: "INACTIVE",
125
+ DELETED: "DELETED"
126
+ };
127
+ var region = process.env.DEFAULT_REGION || process.env.DP_REGION || "us-east-1";
128
+ var config = {
129
+ region
130
+ };
131
+ var ddbClient = new DynamoDBClient(config);
132
+ DynamoDBDocumentClient.from(ddbClient, {
133
+ marshallOptions: {
134
+ removeUndefinedValues: true,
135
+ convertClassInstanceToMap: true
136
+ },
137
+ unmarshallOptions: {
138
+ wrapNumbers: false
139
+ }
140
+ });
141
+
142
+ // ../../libs/utils/src/helper/object.helpers.ts
143
+ function stableStringify(value) {
144
+ if (value === null) {
145
+ return "null";
146
+ }
147
+ const t = typeof value;
148
+ if (t === "string" || t === "number" || t === "boolean") {
149
+ return JSON.stringify(value);
150
+ }
151
+ if (t === "bigint") {
152
+ const asBig = value;
153
+ return JSON.stringify(asBig.toString());
154
+ }
155
+ if (t === "undefined") {
156
+ return "null";
157
+ }
158
+ if (Array.isArray(value)) {
159
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
160
+ }
161
+ if (value instanceof Date) {
162
+ return JSON.stringify(value.toISOString());
163
+ }
164
+ if (t === "object") {
165
+ const obj = value;
166
+ const keys = Object.keys(obj).sort();
167
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
168
+ }
169
+ throw new TypeError(`stableStringify: unsupported type ${t}`);
170
+ }
171
+ function sha256Hex(data) {
172
+ return createHash("sha256").update(data).digest("hex");
173
+ }
174
+
175
+ // ../../libs/utils/src/errors/base.error.ts
176
+ var BaseError = class extends Error {
177
+ statusCode;
178
+ code;
179
+ details;
180
+ retryable;
181
+ metadata;
182
+ constructor(message, statusCode = 500, code = "INTERNAL_ERROR", details, options) {
183
+ super(message);
184
+ this.name = "BaseError";
185
+ Object.setPrototypeOf(this, new.target.prototype);
186
+ this.statusCode = statusCode;
187
+ this.code = code;
188
+ this.details = details;
189
+ this.retryable = options?.retryable;
190
+ this.metadata = options?.metadata;
191
+ }
192
+ };
193
+ createLogger({
194
+ service: "api-service",
195
+ redactPII: true
196
+ });
197
+ createLogger({
198
+ service: "dynamo-repository",
199
+ redactPII: true
200
+ });
201
+
202
+ // ../../libs/metadata/src/models/relation-types.ts
203
+ var RELATION_TYPES = [
204
+ "PARENT_CHILD",
205
+ "VALID_IN",
206
+ "SUPPORTED_BY",
207
+ "BELONGS_TO_CATEGORY",
208
+ "REQUIRES"
209
+ ];
210
+ var RELATION_STATUS = {
211
+ ACTIVE: "ACTIVE"};
212
+
213
+ // ../../libs/metadata/src/validators/code-patterns.ts
214
+ var METADATA_TYPE_CODE_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
215
+ var METADATA_VALUE_CODE_PATTERN = /^[A-Z0-9]+(_[A-Z0-9]+)*$/;
216
+
217
+ // ../../libs/metadata/src/validators/relation.ts
218
+ new Set(RELATION_TYPES);
219
+
220
+ // ../../libs/metadata/src/domain/lifecycle-filter.ts
221
+ var LIFECYCLE_QUERY_STATUS = {
222
+ ACTIVE: "ACTIVE",
223
+ INACTIVE: "INACTIVE",
224
+ DELETED: "DELETED",
225
+ ALL: "ALL"
226
+ };
227
+ new Set(Object.values(LIFECYCLE_QUERY_STATUS));
228
+ var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
229
+ var ENCODING_LEN = 32;
230
+ var RANDOM_LEN = 16;
231
+ var TIME_LEN = 10;
232
+ var TIME_MAX = 281474976710655;
233
+ var ULIDErrorCode;
234
+ (function(ULIDErrorCode2) {
235
+ ULIDErrorCode2["Base32IncorrectEncoding"] = "B32_ENC_INVALID";
236
+ ULIDErrorCode2["DecodeTimeInvalidCharacter"] = "DEC_TIME_CHAR";
237
+ ULIDErrorCode2["DecodeTimeValueMalformed"] = "DEC_TIME_MALFORMED";
238
+ ULIDErrorCode2["EncodeTimeNegative"] = "ENC_TIME_NEG";
239
+ ULIDErrorCode2["EncodeTimeSizeExceeded"] = "ENC_TIME_SIZE_EXCEED";
240
+ ULIDErrorCode2["EncodeTimeValueMalformed"] = "ENC_TIME_MALFORMED";
241
+ ULIDErrorCode2["PRNGDetectFailure"] = "PRNG_DETECT";
242
+ ULIDErrorCode2["ULIDInvalid"] = "ULID_INVALID";
243
+ ULIDErrorCode2["Unexpected"] = "UNEXPECTED";
244
+ ULIDErrorCode2["UUIDInvalid"] = "UUID_INVALID";
245
+ })(ULIDErrorCode || (ULIDErrorCode = {}));
246
+ var ULIDError = class extends Error {
247
+ constructor(errorCode, message) {
248
+ super(`${message} (${errorCode})`);
249
+ this.name = "ULIDError";
250
+ this.code = errorCode;
251
+ }
252
+ };
253
+ function randomChar(prng) {
254
+ const randomPosition = Math.floor(prng() * ENCODING_LEN) % ENCODING_LEN;
255
+ return ENCODING.charAt(randomPosition);
256
+ }
257
+ function replaceCharAt(str, index, char) {
258
+ if (index > str.length - 1) {
259
+ return str;
260
+ }
261
+ return str.substr(0, index) + char + str.substr(index + 1);
262
+ }
263
+ function incrementBase32(str) {
264
+ let done = void 0, index = str.length, char, charIndex, output = str;
265
+ const maxCharIndex = ENCODING_LEN - 1;
266
+ while (!done && index-- >= 0) {
267
+ char = output[index];
268
+ charIndex = ENCODING.indexOf(char);
269
+ if (charIndex === -1) {
270
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Incorrectly encoded string");
271
+ }
272
+ if (charIndex === maxCharIndex) {
273
+ output = replaceCharAt(output, index, ENCODING[0]);
274
+ continue;
275
+ }
276
+ done = replaceCharAt(output, index, ENCODING[charIndex + 1]);
277
+ }
278
+ if (typeof done === "string") {
279
+ return done;
280
+ }
281
+ throw new ULIDError(ULIDErrorCode.Base32IncorrectEncoding, "Failed incrementing string");
282
+ }
283
+ function detectPRNG(root) {
284
+ const rootLookup = detectRoot();
285
+ const globalCrypto = rootLookup && (rootLookup.crypto || rootLookup.msCrypto) || (typeof crypto !== "undefined" ? crypto : null);
286
+ if (typeof globalCrypto?.getRandomValues === "function") {
287
+ return () => {
288
+ const buffer = new Uint8Array(1);
289
+ globalCrypto.getRandomValues(buffer);
290
+ return buffer[0] / 256;
291
+ };
292
+ } else if (typeof globalCrypto?.randomBytes === "function") {
293
+ return () => globalCrypto.randomBytes(1).readUInt8() / 256;
294
+ } else if (crypto?.randomBytes) {
295
+ return () => crypto.randomBytes(1).readUInt8() / 256;
296
+ }
297
+ throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
298
+ }
299
+ function detectRoot() {
300
+ if (inWebWorker())
301
+ return self;
302
+ if (typeof window !== "undefined") {
303
+ return window;
304
+ }
305
+ if (typeof global !== "undefined") {
306
+ return global;
307
+ }
308
+ if (typeof globalThis !== "undefined") {
309
+ return globalThis;
310
+ }
311
+ return null;
312
+ }
313
+ function encodeRandom(len, prng) {
314
+ let str = "";
315
+ for (; len > 0; len--) {
316
+ str = randomChar(prng) + str;
317
+ }
318
+ return str;
319
+ }
320
+ function encodeTime(now, len = TIME_LEN) {
321
+ if (isNaN(now)) {
322
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be a number: ${now}`);
323
+ } else if (now > TIME_MAX) {
324
+ throw new ULIDError(ULIDErrorCode.EncodeTimeSizeExceeded, `Cannot encode a time larger than ${TIME_MAX}: ${now}`);
325
+ } else if (now < 0) {
326
+ throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
327
+ } else if (Number.isInteger(now) === false) {
328
+ throw new ULIDError(ULIDErrorCode.EncodeTimeValueMalformed, `Time must be an integer: ${now}`);
329
+ }
330
+ let mod, str = "";
331
+ for (let currentLen = len; currentLen > 0; currentLen--) {
332
+ mod = now % ENCODING_LEN;
333
+ str = ENCODING.charAt(mod) + str;
334
+ now = (now - mod) / ENCODING_LEN;
335
+ }
336
+ return str;
337
+ }
338
+ function inWebWorker() {
339
+ return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
340
+ }
341
+ function monotonicFactory(prng) {
342
+ const currentPRNG = detectPRNG();
343
+ let lastTime = 0, lastRandom;
344
+ return function _ulid(seedTime) {
345
+ const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
346
+ if (seed <= lastTime) {
347
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
348
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
349
+ }
350
+ lastTime = seed;
351
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currentPRNG);
352
+ return encodeTime(seed, TIME_LEN) + newRandom;
353
+ };
354
+ }
355
+
356
+ // ../../libs/metadata/src/repositories/dynamodb/metadata.repository.impl.ts
357
+ monotonicFactory();
358
+ monotonicFactory();
359
+ var RELATION_TYPE_ZOD_ENUM = RELATION_TYPES;
360
+ var contextSchema = z.object({
361
+ module: z.string().min(1),
362
+ category: z.string().min(1),
363
+ condition: z.string().min(1),
364
+ country: z.string().min(1)
365
+ });
366
+ z.object({
367
+ metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode"),
368
+ displayName: z.string().min(1).max(100),
369
+ description: z.string().optional(),
370
+ valueDataType: z.enum(["Enum", "Numeric", "Boolean", "Text"]),
371
+ multiSelectAllowed: z.boolean(),
372
+ applicableModules: z.array(z.string()).optional(),
373
+ attributeSchema: z.record(z.string(), z.unknown()).optional(),
374
+ status: z.enum(["ACTIVE", "INACTIVE"]),
375
+ supportsRelations: z.boolean().optional(),
376
+ relationFieldLabel: z.string().max(150).nullable().optional(),
377
+ targetMetadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN).nullable().optional(),
378
+ selectionMode: z.enum(["SINGLE", "MULTI"]).nullable().optional(),
379
+ relationRequired: z.boolean().nullable().optional(),
380
+ relationType: z.enum(RELATION_TYPE_ZOD_ENUM).nullable().optional(),
381
+ createdBy: z.string().optional(),
382
+ lastModifiedBy: z.string().optional()
383
+ });
384
+ z.object({
385
+ status: z.enum(["ACTIVE", "INACTIVE"]),
386
+ lastModifiedBy: z.string().optional()
387
+ });
388
+ var applicabilityObjectSchema = z.object({
389
+ module: z.array(z.string()),
390
+ category: z.array(z.string()),
391
+ condition: z.array(z.string()),
392
+ country: z.array(z.string()),
393
+ language: z.array(z.string()).optional()
394
+ });
395
+ z.object({
396
+ valueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid valueCode").optional(),
397
+ metadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid metadataValueCode").optional(),
398
+ label: z.string().min(1).max(150),
399
+ description: z.string().max(2e3).optional(),
400
+ sortOrder: z.number().int().min(0).optional(),
401
+ status: z.enum(["ACTIVE", "INACTIVE"]),
402
+ isGlobal: z.boolean(),
403
+ attributes: z.record(z.string(), z.unknown()).optional(),
404
+ valueAttributes: z.record(z.string(), z.unknown()).optional(),
405
+ applicability: applicabilityObjectSchema.optional(),
406
+ applicableModules: z.array(z.string()).optional(),
407
+ applicableCategories: z.array(z.string()).optional(),
408
+ applicableConditions: z.array(z.string()).optional(),
409
+ applicableCountries: z.array(z.string()).optional(),
410
+ applicableLanguages: z.array(z.string()).optional(),
411
+ relationships: z.array(
412
+ z.object({
413
+ targetMetadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid targetMetadataValueCode")
414
+ })
415
+ ).optional()
416
+ }).refine((b) => !!(b.valueCode || b.metadataValueCode), { message: "valueCode or metadataValueCode is required" });
417
+ z.object({
418
+ metadataTypeCode: z.string().min(1),
419
+ metadataValueCode: z.string().min(1),
420
+ context: contextSchema
421
+ });
422
+ var paginationSchema = z.object({
423
+ limit: z.coerce.number().int().min(1).max(100).optional().default(50),
424
+ nextToken: z.string().optional()
425
+ });
426
+ paginationSchema.extend({
427
+ module: z.string().optional(),
428
+ category: z.string().optional(),
429
+ condition: z.string().optional(),
430
+ country: z.string().optional(),
431
+ language: z.string().optional()
432
+ });
433
+ z.object({
434
+ dimension: z.enum(["module", "category", "condition", "country", "language"], {
435
+ message: "dimension must be module, category, condition, country, or language"
436
+ })
437
+ });
438
+ z.object({
439
+ limit: z.coerce.number().int().min(1).max(100).optional().default(50),
440
+ nextToken: z.string().optional()
441
+ });
442
+ z.object({
443
+ metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode")
444
+ });
445
+ z.object({
446
+ metadataTypeCode: z.string().regex(METADATA_TYPE_CODE_PATTERN, "Invalid metadataTypeCode"),
447
+ metadataValueCode: z.string().regex(METADATA_VALUE_CODE_PATTERN, "Invalid metadataValueCode")
448
+ });
449
+
450
+ // ../../libs/metadata/src/validators/validate-inputs.ts
451
+ new Set(RELATION_TYPES);
452
+ createLogger({
453
+ service: "metadata-registry-service",
454
+ redactPII: true
455
+ });
456
+
457
+ // ../../libs/metadata/src/change-policy/types/policy-group.codes.ts
458
+ var POLICY_GROUP = {
459
+ IDENTITY_IMMUTABLE: "IDENTITY_IMMUTABLE",
460
+ DISPLAY_ONLY: "DISPLAY_ONLY",
461
+ AVAILABILITY_STATUS: "AVAILABILITY_STATUS",
462
+ APPLICABILITY_SCOPE: "APPLICABILITY_SCOPE",
463
+ STRUCTURED_BEHAVIOR: "STRUCTURED_BEHAVIOR",
464
+ CLINICAL_INTERPRETATION: "CLINICAL_INTERPRETATION",
465
+ EXPANDABLE_OPTION: "EXPANDABLE_OPTION",
466
+ FIXED_TEMPLATE_VALUE: "FIXED_TEMPLATE_VALUE",
467
+ RUNTIME_PINNED: "RUNTIME_PINNED"
468
+ };
469
+ var POLICY_GROUP_CODES = Object.values(POLICY_GROUP);
470
+ var VERSION_IMPACT = {
471
+ DESCRIPTIVE: "Descriptive",
472
+ ADDITIVE: "Additive",
473
+ BREAKING: "Breaking"
474
+ };
475
+ var VERSION_IMPACT_CODES = Object.values(VERSION_IMPACT);
476
+ var RUNTIME_IMPACT = {
477
+ NONE: "None",
478
+ DISPLAY_ONLY: "DisplayOnly",
479
+ REVIEW_REQUIRED: "ReviewRequired",
480
+ MIGRATION_REQUIRED: "MigrationRequired"
481
+ };
482
+ var RUNTIME_IMPACT_CODES = Object.values(RUNTIME_IMPACT);
483
+ var MERGE_BEHAVIOR = {
484
+ SILENT_DISPLAY_REFRESH: "SilentDisplayRefresh",
485
+ ADD_ONLY: "AddOnly",
486
+ PRESERVE_ORG_OVERRIDE: "PreserveOrgOverride",
487
+ MANUAL_REVIEW: "ManualReview",
488
+ BLOCK: "Block"
489
+ };
490
+ var MERGE_BEHAVIOR_CODES = Object.values(MERGE_BEHAVIOR);
491
+ var CHANGE_POLICY_OPERATION = {
492
+ ADD: "Add",
493
+ UPDATE: "Update",
494
+ INACTIVATE: "Inactivate",
495
+ RETIRE: "Retire",
496
+ PUBLISH: "Publish"
497
+ };
498
+ var CHANGE_POLICY_OPERATION_CODES = Object.values(CHANGE_POLICY_OPERATION);
499
+ var APPLICABILITY_CHANGE_KIND = {
500
+ EXPAND: "Expand",
501
+ RESTRICT: "Restrict",
502
+ ANY: "Any"
503
+ };
504
+ var APPLICABILITY_CHANGE_KIND_CODES = Object.values(APPLICABILITY_CHANGE_KIND);
505
+ var changePolicyRuleSchema = z.object({
506
+ ruleId: z.string().min(1),
507
+ objectPath: z.string().min(1),
508
+ operation: z.enum(CHANGE_POLICY_OPERATION_CODES),
509
+ changeKind: z.enum(APPLICABILITY_CHANGE_KIND_CODES).optional(),
510
+ policyGroup: z.enum(POLICY_GROUP_CODES),
511
+ versionImpact: z.enum(VERSION_IMPACT_CODES),
512
+ requiresMetadataVersion: z.boolean(),
513
+ requiresTemplateAdoption: z.boolean(),
514
+ requiresOrgCapabilityReevaluation: z.boolean(),
515
+ runtimeImpact: z.enum(RUNTIME_IMPACT_CODES),
516
+ canAutoApplyToPublishedCarePlan: z.boolean(),
517
+ canAutoApplyToActiveRuntime: z.boolean(),
518
+ mergeBehavior: z.enum(MERGE_BEHAVIOR_CODES),
519
+ uxDiffRequired: z.boolean(),
520
+ notes: z.string().optional()
521
+ });
522
+ z.object({
523
+ version: z.string().min(1),
524
+ rules: z.array(changePolicyRuleSchema).min(1)
525
+ });
526
+
527
+ // ../../libs/metadata/src/services/metadata-value-retire.service.ts
528
+ monotonicFactory();
529
+
530
+ // ../../libs/metadata/src/services/metadata-change-request.service.ts
531
+ monotonicFactory();
532
+ z.object({
533
+ /** When true, inactive values are included; default false (ACTIVE only for latest filter). */
534
+ includeInactive: z.boolean().optional(),
535
+ /**
536
+ * When true, every published version of a value is retained under `versions`.
537
+ * Default false: runtime projection keeps only the latest version.
538
+ * Historical versions remain in the registry/audit model.
539
+ */
540
+ includeAllVersions: z.boolean().optional(),
541
+ /** Numeric schema version stamped for transitional validators. */
542
+ schemaVersion: z.number().int().positive().optional(),
543
+ /** Wire projectionVersion string (e.g. `1.0`). */
544
+ projectionVersion: z.string().min(1).optional(),
545
+ /**
546
+ * Optional storage key prefix hint for adapters (not used by pure build).
547
+ * Callers may also pass prefix directly to {@link S3ProjectionStorage}.
548
+ */
549
+ storagePrefix: z.string().min(1).optional()
550
+ });
551
+
552
+ // ../../libs/metadata-projection/src/lib/errors/ProjectionError.ts
553
+ var ProjectionError = class extends BaseError {
554
+ constructor(message, statusCode = 400, code = "PROJECTION_ERROR", details, options) {
555
+ super(message, statusCode, code, details, options);
556
+ this.name = "ProjectionError";
557
+ }
558
+ };
559
+ new AsyncLocalStorage();
560
+
561
+ // ../../libs/metadata-projection/src/lib/serializer/ProjectionSerializer.ts
562
+ var ProjectionSerializer = class _ProjectionSerializer {
563
+ /**
564
+ * SHA-256 hex digest of a deterministic JSON serialization.
565
+ */
566
+ static contentHash(value) {
567
+ return sha256Hex(stableStringify(value));
568
+ }
569
+ /**
570
+ * Deterministic JSON body for artifact serialization.
571
+ */
572
+ static toStableJson(value) {
573
+ return stableStringify(value);
574
+ }
575
+ /**
576
+ * Derive a short seed from a content hash when the caller omits identifiers.
577
+ */
578
+ static deriveSeed(contentSeed) {
579
+ return _ProjectionSerializer.contentHash(contentSeed).slice(0, 16);
580
+ }
581
+ };
582
+
583
+ // ../../libs/metadata-projection/src/lib/helpers/ProjectionHelper.ts
584
+ var ProjectionHelper = class _ProjectionHelper {
585
+ /**
586
+ * Build relation lookup key for a from-side value.
587
+ */
588
+ static relationFromKey(fromMetadataTypeCode, fromMetadataValueCode) {
589
+ return `${fromMetadataTypeCode}#${fromMetadataValueCode}`;
590
+ }
591
+ /**
592
+ * Map registry STATUS to projection wire status (camelCase).
593
+ */
594
+ static toProjectionStatus(status) {
595
+ switch (status) {
596
+ case STATUS.ACTIVE:
597
+ return PROJECTION_STATUS.ACTIVE;
598
+ case STATUS.INACTIVE:
599
+ return PROJECTION_STATUS.INACTIVE;
600
+ case STATUS.DELETED:
601
+ return PROJECTION_STATUS.DELETED;
602
+ default:
603
+ return status.toLowerCase();
604
+ }
605
+ }
606
+ /**
607
+ * Filter values to those included in the projection.
608
+ * Always excludes DELETED. When includeInactive is false, only ACTIVE.
609
+ */
610
+ static filterValues(values, includeInactive) {
611
+ return values.filter((value) => {
612
+ if (value.status === STATUS.DELETED) {
613
+ return false;
614
+ }
615
+ if (includeInactive) {
616
+ return value.status === STATUS.ACTIVE || value.status === STATUS.INACTIVE;
617
+ }
618
+ return value.status === STATUS.ACTIVE;
619
+ });
620
+ }
621
+ /**
622
+ * Filter relations to ACTIVE only.
623
+ */
624
+ static filterActiveRelations(relations) {
625
+ return relations.filter((rel) => rel.status === RELATION_STATUS.ACTIVE);
626
+ }
627
+ /**
628
+ * Default English locale plus any existing registry locales.
629
+ *
630
+ * Prefers `displayName`, then `label`, for `en-US` when not already present.
631
+ * Explicit locales in `existing` always win. Does not invent test markers.
632
+ */
633
+ static mergeLocalizedLabels(displayName, label, existing) {
634
+ const englishLabel = displayName?.trim() || label?.trim();
635
+ const localizedLabels = {
636
+ ...englishLabel ? { "en-US": englishLabel } : {},
637
+ ...existing ?? {}
638
+ };
639
+ return Object.keys(localizedLabels).length > 0 ? localizedLabels : void 0;
640
+ }
641
+ /**
642
+ * Map a registry value + optional relations to a slim version entry.
643
+ *
644
+ * Every projected value gets `localizedLabels` when an English display string
645
+ * exists: prefer `displayName`, fall back to `label`. Existing registry
646
+ * locales (including `hi-IN`) are preserved and win over the English default.
647
+ */
648
+ static toProjectionEntry(value, relations = []) {
649
+ const relationships = _ProjectionHelper.toRelationships(relations);
650
+ const displayName = value.label;
651
+ const label = displayName;
652
+ const entry = {
653
+ version: value.version,
654
+ status: _ProjectionHelper.toProjectionStatus(value.status),
655
+ code: value.valueCode,
656
+ displayName,
657
+ label,
658
+ sortOrder: value.sortOrder,
659
+ isGlobal: value.isGlobal,
660
+ attributes: { ...value.attributes },
661
+ applicability: {
662
+ module: [...value.applicability.module],
663
+ category: [...value.applicability.category],
664
+ condition: [...value.applicability.condition],
665
+ country: [...value.applicability.country],
666
+ ...value.applicability.language ? { language: [...value.applicability.language] } : {}
667
+ }
668
+ };
669
+ if (value.description !== void 0) {
670
+ entry.description = value.description;
671
+ }
672
+ const existingLocalizedLabels = value.localizedLabels;
673
+ const localizedLabels = _ProjectionHelper.mergeLocalizedLabels(
674
+ displayName,
675
+ label,
676
+ existingLocalizedLabels
677
+ );
678
+ if (localizedLabels !== void 0) {
679
+ entry.localizedLabels = localizedLabels;
680
+ }
681
+ if (relationships.length > 0) {
682
+ entry.relationships = relationships;
683
+ }
684
+ return entry;
685
+ }
686
+ /**
687
+ * Convert ACTIVE relation rows to slim projection relationships.
688
+ */
689
+ static toRelationships(relations) {
690
+ return relations.map((rel) => ({
691
+ targetMetadataTypeCode: rel.toMetadataTypeCode,
692
+ targetValueCode: rel.toMetadataValueCode
693
+ }));
694
+ }
695
+ /**
696
+ * Group version entries by business code into O(1) records map.
697
+ */
698
+ static buildRecordsMap(entries) {
699
+ const byCode = /* @__PURE__ */ new Map();
700
+ for (const entry of entries) {
701
+ const list = byCode.get(entry.code) ?? [];
702
+ list.push(entry);
703
+ byCode.set(entry.code, list);
704
+ }
705
+ const codes = [...byCode.keys()].sort((a, b) => {
706
+ const aSort = Math.min(...(byCode.get(a) ?? []).map((e) => e.sortOrder));
707
+ const bSort = Math.min(...(byCode.get(b) ?? []).map((e) => e.sortOrder));
708
+ if (aSort !== bSort) {
709
+ return aSort - bSort;
710
+ }
711
+ return a.localeCompare(b);
712
+ });
713
+ const records = {};
714
+ for (const code of codes) {
715
+ const versions = byCode.get(code) ?? [];
716
+ versions.sort((a, b) => a.version - b.version);
717
+ const versionsMap = {};
718
+ let latestVersion = 0;
719
+ for (const v of versions) {
720
+ versionsMap[String(v.version)] = v;
721
+ if (v.version > latestVersion) {
722
+ latestVersion = v.version;
723
+ }
724
+ }
725
+ records[code] = {
726
+ latestVersion,
727
+ publishedVersion: latestVersion,
728
+ versions: versionsMap
729
+ };
730
+ }
731
+ return records;
732
+ }
733
+ /**
734
+ * Resolve the latest version entry for a code from a records map.
735
+ */
736
+ static resolveLatest(records, code) {
737
+ const record = records[code];
738
+ if (!record) {
739
+ return void 0;
740
+ }
741
+ return record.versions[String(record.latestVersion)];
742
+ }
743
+ /**
744
+ * @deprecated Prefer {@link buildRecordsMap}. Flat map of latest entry per code.
745
+ */
746
+ static buildByCodeMap(entries) {
747
+ const records = _ProjectionHelper.buildRecordsMap(entries);
748
+ const byCode = {};
749
+ for (const [code, record] of Object.entries(records)) {
750
+ const latest = record.versions[String(record.latestVersion)];
751
+ if (latest) {
752
+ byCode[code] = latest;
753
+ }
754
+ }
755
+ return byCode;
756
+ }
757
+ /**
758
+ * SHA-256 hex digest of a deterministic JSON serialization.
759
+ */
760
+ static contentHash(value) {
761
+ return ProjectionSerializer.contentHash(value);
762
+ }
763
+ /**
764
+ * Deterministic JSON body for artifact serialization.
765
+ */
766
+ static toStableJson(value) {
767
+ return ProjectionSerializer.toStableJson(value);
768
+ }
769
+ /**
770
+ * Derive a short revision from a content hash when the caller omits revision.
771
+ */
772
+ static deriveRevision(contentSeed) {
773
+ return ProjectionSerializer.deriveSeed(contentSeed);
774
+ }
775
+ /** Count total version entries across all records. */
776
+ static countVersions(records) {
777
+ let count = 0;
778
+ for (const record of Object.values(records)) {
779
+ count += Object.keys(record.versions).length;
780
+ }
781
+ return count;
782
+ }
783
+ /**
784
+ * Build domain projection `records` + hashes for one registry metadata type.
785
+ *
786
+ * Shared by {@link GenericReadModelGenerator} — type-agnostic transform.
787
+ */
788
+ static buildDomainProjectionRecords(input) {
789
+ const filtered = _ProjectionHelper.filterValues(
790
+ input.values,
791
+ input.includeInactive
792
+ );
793
+ const entries = filtered.map((value) => {
794
+ const fromKey = _ProjectionHelper.relationFromKey(
795
+ value.metadataTypeCode,
796
+ value.valueCode
797
+ );
798
+ const relations = input.relationsByFrom.get(fromKey) ?? [];
799
+ return _ProjectionHelper.toProjectionEntry(value, relations);
800
+ });
801
+ const records = _ProjectionHelper.buildRecordsMap(entries);
802
+ if (input.includeAllVersions === false) {
803
+ for (const record of Object.values(records)) {
804
+ const latest = record.versions[String(record.latestVersion)];
805
+ record.versions = latest ? { [String(record.latestVersion)]: latest } : {};
806
+ }
807
+ }
808
+ const metadataCount = _ProjectionHelper.countVersions(records);
809
+ const contentHash = _ProjectionHelper.contentHash(records);
810
+ return { records, metadataCount, contentHash };
811
+ }
812
+ };
813
+
814
+ // ../../libs/metadata-projection/src/lib/read-model/ReadModelNaming.ts
815
+ var RESERVED_PROJECTION_NAMES = [
816
+ "common",
817
+ "manifest",
818
+ "runtimeConfig",
819
+ "relationshipIndex"
820
+ ];
821
+ function assertUsableMetadataTypeCode(metadataTypeCode) {
822
+ const trimmed = metadataTypeCode.trim();
823
+ if (!trimmed) {
824
+ throw new ProjectionError(
825
+ "metadataTypeCode is required for projection naming",
826
+ 400,
827
+ "PROJECTION_NAME_REQUIRED",
828
+ void 0,
829
+ { retryable: false }
830
+ );
831
+ }
832
+ if (isReservedProjectionName(trimmed)) {
833
+ throw new ProjectionError(
834
+ `Metadata type "${trimmed}" collides with reserved projection name`,
835
+ 500,
836
+ "PROJECTION_NAME_RESERVED",
837
+ void 0,
838
+ {
839
+ retryable: false,
840
+ metadata: { metadataTypeCode: trimmed }
841
+ }
842
+ );
843
+ }
844
+ return trimmed;
845
+ }
846
+ function projectionFileName(metadataTypeCode) {
847
+ return `${assertUsableMetadataTypeCode(metadataTypeCode)}.json`;
848
+ }
849
+ function isReservedProjectionName(projectionName) {
850
+ const lower = projectionName.trim().toLowerCase();
851
+ return RESERVED_PROJECTION_NAMES.some(
852
+ (name) => name.toLowerCase() === lower
853
+ );
854
+ }
855
+
856
+ // ../../libs/metadata-projection/src/lib/errors/StorageError.ts
857
+ var StorageError = class extends BaseError {
858
+ constructor(message, statusCode = 502, code = "PROJECTION_STORAGE_ERROR", details, options) {
859
+ super(message, statusCode, code, details, options);
860
+ this.name = "StorageError";
861
+ }
862
+ };
863
+ var statusSchema = z.enum([STATUS.ACTIVE, STATUS.INACTIVE, STATUS.DELETED]);
864
+ var applicabilitySchema = z.object({
865
+ module: z.array(z.string()),
866
+ category: z.array(z.string()),
867
+ condition: z.array(z.string()),
868
+ country: z.array(z.string()),
869
+ language: z.array(z.string()).optional()
870
+ });
871
+ var metadataTypeRecordSchema = z.object({
872
+ metadataTypeCode: z.string().min(1),
873
+ version: z.number().int().nonnegative(),
874
+ displayName: z.string().min(1),
875
+ description: z.string().optional(),
876
+ valueDataType: z.string().min(1),
877
+ multiSelectAllowed: z.boolean(),
878
+ applicableModules: z.array(z.string()),
879
+ supportsRelations: z.boolean(),
880
+ relationFieldLabel: z.string().nullable(),
881
+ targetMetadataTypeCode: z.string().nullable(),
882
+ selectionMode: z.enum(["SINGLE", "MULTI"]).nullable(),
883
+ relationRequired: z.boolean().nullable(),
884
+ relationType: z.string().nullable(),
885
+ valueApplicabilityConfig: z.object({
886
+ moduleScoped: z.boolean().optional(),
887
+ categoryDependent: z.boolean().optional(),
888
+ conditionDependent: z.boolean().optional(),
889
+ countryDependent: z.boolean().optional(),
890
+ languageDependent: z.boolean().optional()
891
+ }).optional(),
892
+ attributeSchema: z.record(z.string(), z.unknown()).optional(),
893
+ status: statusSchema,
894
+ createdAt: z.string().min(1),
895
+ lastModifiedAt: z.string().min(1),
896
+ createdBy: z.string().optional(),
897
+ lastModifiedBy: z.string().optional()
898
+ });
899
+ var metadataValueRecordSchema = z.object({
900
+ metadataTypeCode: z.string().min(1),
901
+ valueCode: z.string().min(1),
902
+ version: z.number().int().nonnegative(),
903
+ label: z.string().min(1),
904
+ description: z.string().optional(),
905
+ sortOrder: z.number().int(),
906
+ status: statusSchema,
907
+ isGlobal: z.boolean(),
908
+ attributes: z.record(z.string(), z.unknown()),
909
+ applicability: applicabilitySchema,
910
+ applSkKeys: z.array(z.string()),
911
+ createdAt: z.string().min(1),
912
+ lastModifiedAt: z.string().min(1),
913
+ createdBy: z.string().optional(),
914
+ lastModifiedBy: z.string().optional(),
915
+ deletedAt: z.string().optional(),
916
+ deletedBy: z.string().optional(),
917
+ deleteReason: z.string().optional(),
918
+ previousStatus: statusSchema.optional()
919
+ });
920
+ var metadataRelationRecordSchema = z.object({
921
+ id: z.string().min(1),
922
+ relationType: z.string().min(1),
923
+ fromMetadataTypeCode: z.string().min(1),
924
+ fromMetadataValueCode: z.string().min(1),
925
+ toMetadataTypeCode: z.string().min(1),
926
+ toMetadataValueCode: z.string().min(1),
927
+ status: z.enum(["ACTIVE", "INACTIVE"]),
928
+ createdAt: z.string().min(1),
929
+ createdBy: z.string().optional(),
930
+ updatedAt: z.string().optional(),
931
+ updatedBy: z.string().optional()
932
+ });
933
+ z.object({
934
+ environment: z.string().min(1),
935
+ releaseId: z.string().min(1).optional(),
936
+ revision: z.string().min(1).optional(),
937
+ generatedAt: z.string().min(1).optional(),
938
+ types: z.array(metadataTypeRecordSchema),
939
+ values: z.array(metadataValueRecordSchema),
940
+ relations: z.array(metadataRelationRecordSchema).optional()
941
+ });
942
+ var projectionTypeSchema = z.string().min(1);
943
+ var artifactSchema = z.object({
944
+ fileName: z.string().min(1),
945
+ projectionType: projectionTypeSchema,
946
+ contentType: z.literal("application/json"),
947
+ body: z.string().min(1),
948
+ contentHash: z.string().min(1),
949
+ parsed: z.unknown()
950
+ });
951
+ var metadataTypeEntrySchema = z.object({
952
+ typeCode: z.string().min(1),
953
+ projectionFile: z.string().min(1)
954
+ });
955
+ var lookupIndexEntrySchema = z.object({
956
+ typeCode: z.string().min(1),
957
+ valueCode: z.string().min(1),
958
+ projectionFile: z.string().min(1)
959
+ });
960
+ var manifestSchema = z.object({
961
+ releaseId: z.string().min(1),
962
+ environment: z.string().min(1),
963
+ generatedAt: z.string().min(1),
964
+ projectionVersion: z.string().min(1),
965
+ metadataCount: z.number().int().nonnegative(),
966
+ artifactCount: z.number().int().nonnegative(),
967
+ contentHash: z.string().min(1),
968
+ artifacts: z.array(z.string().min(1)),
969
+ files: z.array(
970
+ z.object({
971
+ fileName: z.string().min(1),
972
+ projectionType: projectionTypeSchema,
973
+ contentHash: z.string().min(1),
974
+ itemCount: z.number().int().nonnegative()
975
+ })
976
+ ),
977
+ metadataTypes: z.record(z.string(), metadataTypeEntrySchema),
978
+ lookupIndex: z.record(z.string(), lookupIndexEntrySchema),
979
+ revision: z.string().min(1),
980
+ schemaVersion: z.number().int().positive()
981
+ });
982
+ z.object({
983
+ releaseId: z.string().min(1),
984
+ environment: z.string().min(1),
985
+ generatedAt: z.string().min(1),
986
+ projectionVersion: z.string().min(1),
987
+ revision: z.string().min(1),
988
+ metadataCount: z.number().int().nonnegative(),
989
+ manifest: manifestSchema,
990
+ artifacts: z.array(artifactSchema).min(1)
991
+ });
992
+
993
+ // ../../libs/metadata-projection/src/lib/validators/RelationshipIndexValidator.ts
994
+ var RELATIONSHIP_KEY_PATTERN = /^[^:\s]+:.+$/;
995
+ function parseAndValidateRelationshipIndex(input) {
996
+ const fileName = input.fileName ?? "relationship-index.json";
997
+ const parsed = input.parsed;
998
+ if (parsed === null || parsed === void 0) {
999
+ throw new Error(`${fileName} is missing`);
1000
+ }
1001
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
1002
+ throw new Error(`${fileName} is not a JSON object`);
1003
+ }
1004
+ const record = parsed;
1005
+ if (typeof record.releaseId === "string" && record.releaseId.trim()) {
1006
+ if (record.releaseId !== input.expectedReleaseId) {
1007
+ throw new Error(
1008
+ `${fileName} releaseId ${record.releaseId} does not match ${input.expectedReleaseId}`
1009
+ );
1010
+ }
1011
+ }
1012
+ const indexCandidate = isRelationshipIndexPayload(record.index) && (record.releaseId !== void 0 || record.contentHash !== void 0) ? record.index : record;
1013
+ const index = assertRelationshipIndexShape(indexCandidate, fileName);
1014
+ const actualHash = ProjectionHelper.contentHash(index);
1015
+ if (actualHash !== input.expectedContentHash) {
1016
+ throw new Error(`Checksum mismatch for ${fileName}`);
1017
+ }
1018
+ return index;
1019
+ }
1020
+ function assertRelationshipIndexShape(value, fileName = "relationship-index.json") {
1021
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1022
+ throw new Error(`${fileName} has an invalid schema: expected object map`);
1023
+ }
1024
+ const index = {};
1025
+ for (const [key, targets] of Object.entries(value)) {
1026
+ if (key === "releaseId" || key === "contentHash" || key === "index") {
1027
+ continue;
1028
+ }
1029
+ if (!RELATIONSHIP_KEY_PATTERN.test(key)) {
1030
+ throw new Error(`${fileName} has invalid relationship key "${key}"`);
1031
+ }
1032
+ if (!targets || typeof targets !== "object" || Array.isArray(targets)) {
1033
+ throw new Error(
1034
+ `${fileName} entry "${key}" must map target type codes to string arrays`
1035
+ );
1036
+ }
1037
+ const mapped = {};
1038
+ for (const [typeCode, codes] of Object.entries(
1039
+ targets
1040
+ )) {
1041
+ if (!typeCode.trim()) {
1042
+ throw new Error(`${fileName} entry "${key}" has an empty target type`);
1043
+ }
1044
+ if (!Array.isArray(codes)) {
1045
+ throw new Error(
1046
+ `${fileName} entry "${key}" \u2192 ${typeCode} must be a string array`
1047
+ );
1048
+ }
1049
+ const valueCodes = [];
1050
+ for (const code of codes) {
1051
+ if (typeof code !== "string" || !code.trim()) {
1052
+ throw new Error(
1053
+ `${fileName} entry "${key}" \u2192 ${typeCode} contains a non-string value`
1054
+ );
1055
+ }
1056
+ valueCodes.push(code);
1057
+ }
1058
+ mapped[typeCode] = valueCodes;
1059
+ }
1060
+ index[key] = mapped;
1061
+ }
1062
+ return index;
1063
+ }
1064
+ function isRelationshipIndexPayload(value) {
1065
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1066
+ }
1067
+
1068
+ // ../../libs/metadata-projection/src/lib/path/ProjectionPathBuilder.ts
1069
+ var ProjectionPathBuilder = class {
1070
+ prefix;
1071
+ environment;
1072
+ constructor(options) {
1073
+ const env = options.environment?.trim() ?? "";
1074
+ if (!env || env.includes("/") || env.includes("..")) {
1075
+ throw new StorageError(
1076
+ "Invalid environment for projection path",
1077
+ 400,
1078
+ "PROJECTION_PATH_INVALID_ENVIRONMENT",
1079
+ void 0,
1080
+ { retryable: false, metadata: { environment: options.environment } }
1081
+ );
1082
+ }
1083
+ this.environment = env;
1084
+ this.prefix = (options.prefix ?? DEFAULT_STORAGE_PREFIX).trim().replace(/^\/+|\/+$/g, "");
1085
+ }
1086
+ /** `{prefix}/{environment}` */
1087
+ environmentRoot() {
1088
+ return `${this.prefix}/${this.environment}`;
1089
+ }
1090
+ /** `{prefix}/{environment}/current.json` */
1091
+ currentPointerKey() {
1092
+ return `${this.environmentRoot()}/${CURRENT_POINTER_FILE_NAME}`;
1093
+ }
1094
+ /** `{prefix}/{environment}/releases` */
1095
+ releasesRoot() {
1096
+ return `${this.environmentRoot()}/${RELEASES_FOLDER_NAME}`;
1097
+ }
1098
+ /** `{prefix}/{environment}/releases/{releaseId}` */
1099
+ releaseRoot(releaseId) {
1100
+ this.assertSafeSegment(releaseId, "releaseId");
1101
+ return `${this.releasesRoot()}/${releaseId.trim()}`;
1102
+ }
1103
+ /** `{prefix}/{environment}/releases/{releaseId}/{fileName}` */
1104
+ releaseArtifactKey(releaseId, fileName) {
1105
+ this.assertSafeSegment(releaseId, "releaseId");
1106
+ this.assertSafeArtifactPath(fileName, "fileName");
1107
+ return `${this.releaseRoot(releaseId)}/${fileName.trim()}`;
1108
+ }
1109
+ assertSafeSegment(value, field) {
1110
+ const trimmed = value?.trim() ?? "";
1111
+ if (!trimmed || trimmed.includes("/") || trimmed.includes("..")) {
1112
+ throw new StorageError(
1113
+ `Invalid ${field} for projection path`,
1114
+ 400,
1115
+ "PROJECTION_PATH_INVALID_SEGMENT",
1116
+ void 0,
1117
+ { retryable: false, metadata: { field, value } }
1118
+ );
1119
+ }
1120
+ }
1121
+ assertSafeArtifactPath(value, field) {
1122
+ const trimmed = value?.trim() ?? "";
1123
+ if (!trimmed || trimmed.startsWith("/") || trimmed.endsWith("/") || trimmed.includes("..") || trimmed.split("/").some((seg) => !seg.trim())) {
1124
+ throw new StorageError(
1125
+ `Invalid ${field} for projection path`,
1126
+ 400,
1127
+ "PROJECTION_PATH_INVALID_SEGMENT",
1128
+ void 0,
1129
+ { retryable: false, metadata: { field, value } }
1130
+ );
1131
+ }
1132
+ }
1133
+ };
1134
+ createLogger({ serviceName: "metadata-projection" });
1135
+ var metadataPublishedPayloadSchema = z.object({
1136
+ changeRequestId: z.string().min(1),
1137
+ changeRevision: z.string().min(1).optional(),
1138
+ metadataTypeCode: z.string().min(1),
1139
+ metadataValueCode: z.string().min(1).optional(),
1140
+ entityType: z.enum(["METADATA_TYPE", "METADATA_VALUE"]),
1141
+ operation: z.enum(["Add", "Update"]),
1142
+ publishStrategy: z.enum(["IN_PLACE", "NEW_VERSION"]),
1143
+ version: z.number().int().positive(),
1144
+ publishedAt: z.string().min(1)
1145
+ });
1146
+ Object.assign(
1147
+ metadataPublishedPayloadSchema,
1148
+ {
1149
+ __meta: {
1150
+ eventType: "MetadataPublished.v1",
1151
+ eventVersion: "1.0.0",
1152
+ source: "metadata-registry"
1153
+ }
1154
+ }
1155
+ );
1156
+
1157
+ // ../../libs/runtime-metadata/src/lib/config/RuntimeMetadataConfig.ts
1158
+ var runtimeMetadataConfigSchema = z.object({
1159
+ /** S3 bucket holding projection artifacts. */
1160
+ bucket: z.string().min(1),
1161
+ /** Key prefix without leading/trailing slashes. */
1162
+ prefix: z.string().min(1).optional(),
1163
+ /** Runtime environment segment (`dev`, `qa`, …). */
1164
+ environment: z.string().min(1),
1165
+ /** Expected numeric schema version; defaults to library constant. */
1166
+ expectedSchemaVersion: z.number().int().positive().optional(),
1167
+ /** Expected wire projectionVersion (e.g. `1.0`). */
1168
+ expectedProjectionVersion: z.string().min(1).optional(),
1169
+ /**
1170
+ * When set, startup loads this release id.
1171
+ * When omitted, resolves via `{prefix}/{environment}/current.json`.
1172
+ */
1173
+ revision: z.string().min(1).optional(),
1174
+ /** Periodic manifest check interval in ms. `0` / omitted disables auto timer. */
1175
+ periodicCheckIntervalMs: z.number().int().nonnegative().optional()
1176
+ });
1177
+ function resolveRuntimeMetadataConfig(input) {
1178
+ const parsed = runtimeMetadataConfigSchema.parse(input);
1179
+ return {
1180
+ bucket: parsed.bucket.trim(),
1181
+ prefix: (parsed.prefix ?? DEFAULT_STORAGE_PREFIX).trim().replace(/^\/+|\/+$/g, ""),
1182
+ environment: parsed.environment.trim(),
1183
+ expectedSchemaVersion: parsed.expectedSchemaVersion ?? PROJECTION_SCHEMA_VERSION,
1184
+ expectedProjectionVersion: parsed.expectedProjectionVersion ?? PROJECTION_VERSION,
1185
+ revision: parsed.revision?.trim() || void 0,
1186
+ periodicCheckIntervalMs: parsed.periodicCheckIntervalMs ?? 0
1187
+ };
1188
+ }
1189
+
1190
+ // ../../libs/runtime-metadata/src/lib/config/resolveMetadataProjectionsBucket.ts
1191
+ var METADATA_PROJECTIONS_BUCKET_ENV = {
1192
+ PRIMARY: "METADATA_PROJECTIONS_BUCKET",
1193
+ ALTERNATE: "METADATA_PROJECTION_BUCKET",
1194
+ LEGACY: "PROJECTION_BUCKET"
1195
+ };
1196
+ function canonicalMetadataProjectionsBucketName(stage) {
1197
+ const normalized = stage.trim().toLowerCase();
1198
+ if (!normalized) {
1199
+ throw new Error("stage is required to resolve the metadata projections bucket");
1200
+ }
1201
+ return `${normalized}-mvx-metadata-projections-bucket`;
1202
+ }
1203
+ function readMetadataProjectionsBucket(env = process.env) {
1204
+ const configured = (env[METADATA_PROJECTIONS_BUCKET_ENV.PRIMARY] ?? env[METADATA_PROJECTIONS_BUCKET_ENV.ALTERNATE] ?? env[METADATA_PROJECTIONS_BUCKET_ENV.LEGACY] ?? "").trim();
1205
+ if (configured) {
1206
+ return configured;
1207
+ }
1208
+ const stage = (env.STAGE ?? env.NODE_ENV)?.trim();
1209
+ if (stage && stage !== "test") {
1210
+ return canonicalMetadataProjectionsBucketName(stage);
1211
+ }
1212
+ return "";
1213
+ }
1214
+ function resolveMetadataProjectionsBucket(env = process.env) {
1215
+ const bucket = readMetadataProjectionsBucket(env);
1216
+ if (!bucket) {
1217
+ throw new Error(
1218
+ "METADATA_PROJECTIONS_BUCKET is required to load metadata projections"
1219
+ );
1220
+ }
1221
+ if (/\s/.test(bucket)) {
1222
+ throw new Error(
1223
+ "METADATA_PROJECTIONS_BUCKET must not contain whitespace"
1224
+ );
1225
+ }
1226
+ return bucket;
1227
+ }
1228
+ function isMetadataProjectionsBucketConfigured(env = process.env) {
1229
+ return readMetadataProjectionsBucket(env).length > 0;
1230
+ }
1231
+
1232
+ // ../../libs/runtime-metadata/src/lib/errors/RuntimeMetadataError.ts
1233
+ var RuntimeMetadataError = class extends BaseError {
1234
+ constructor(message, statusCode = 500, code = "RUNTIME_METADATA_ERROR", details, options) {
1235
+ super(message, statusCode, code, details, options);
1236
+ this.name = "RuntimeMetadataError";
1237
+ }
1238
+ };
1239
+ var ManifestValidationError = class extends RuntimeMetadataError {
1240
+ constructor(message, details) {
1241
+ super(message, 400, "RUNTIME_METADATA_MANIFEST_INVALID", details, {
1242
+ retryable: false
1243
+ });
1244
+ this.name = "ManifestValidationError";
1245
+ }
1246
+ };
1247
+ var ProjectionDownloadError = class extends RuntimeMetadataError {
1248
+ constructor(message, options) {
1249
+ super(message, 502, "RUNTIME_METADATA_DOWNLOAD_FAILED", void 0, {
1250
+ retryable: options?.retryable ?? true,
1251
+ metadata: options?.metadata
1252
+ });
1253
+ this.name = "ProjectionDownloadError";
1254
+ }
1255
+ };
1256
+ var MetadataNotReadyError = class extends RuntimeMetadataError {
1257
+ constructor(message = "Runtime metadata cache is not initialized") {
1258
+ super(message, 503, "RUNTIME_METADATA_NOT_READY", void 0, {
1259
+ retryable: true
1260
+ });
1261
+ this.name = "MetadataNotReadyError";
1262
+ }
1263
+ };
1264
+ var MetadataLookupError = class extends RuntimeMetadataError {
1265
+ constructor(message, options) {
1266
+ super(message, 404, "RUNTIME_METADATA_NOT_FOUND", void 0, {
1267
+ retryable: false,
1268
+ metadata: options?.metadata
1269
+ });
1270
+ this.name = "MetadataLookupError";
1271
+ }
1272
+ };
1273
+ var UnknownMetadataTypeError = class extends RuntimeMetadataError {
1274
+ constructor(metadataType, options) {
1275
+ super(
1276
+ `Unknown metadata type: ${metadataType}`,
1277
+ 404,
1278
+ "RUNTIME_METADATA_UNKNOWN_TYPE",
1279
+ void 0,
1280
+ {
1281
+ retryable: false,
1282
+ metadata: { metadataType, ...options?.metadata }
1283
+ }
1284
+ );
1285
+ this.name = "UnknownMetadataTypeError";
1286
+ }
1287
+ };
1288
+ var MetadataProjectionUnavailableError = class extends RuntimeMetadataError {
1289
+ constructor(message = "Metadata projection is unavailable", options) {
1290
+ super(message, 503, "METADATA_PROJECTION_UNAVAILABLE", void 0, {
1291
+ retryable: options?.retryable ?? true,
1292
+ metadata: options?.metadata
1293
+ });
1294
+ this.name = "MetadataProjectionUnavailableError";
1295
+ }
1296
+ };
1297
+ var InvalidMetadataReferenceError = class extends RuntimeMetadataError {
1298
+ constructor(reference, options) {
1299
+ super(
1300
+ `Invalid metadata reference: ${String(reference ?? "")}`,
1301
+ 400,
1302
+ "INVALID_METADATA_REFERENCE",
1303
+ void 0,
1304
+ {
1305
+ retryable: false,
1306
+ metadata: { reference, ...options?.metadata }
1307
+ }
1308
+ );
1309
+ this.name = "InvalidMetadataReferenceError";
1310
+ }
1311
+ };
1312
+
1313
+ // ../../libs/runtime-metadata/src/lib/utils/isMetadataReference.ts
1314
+ function isMetadataReference(value) {
1315
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1316
+ return false;
1317
+ }
1318
+ const candidate = value;
1319
+ const hasTypeCode = typeof candidate.typeCode === "string" && candidate.typeCode.trim().length > 0;
1320
+ const hasValueCode = typeof candidate.valueCode === "string" && candidate.valueCode.trim().length > 0;
1321
+ return hasTypeCode && hasValueCode;
1322
+ }
1323
+
1324
+ // ../../libs/runtime-metadata/src/lib/utils/isMetadataValueObject.ts
1325
+ function isMetadataValueObject(val) {
1326
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
1327
+ return false;
1328
+ }
1329
+ const obj = val;
1330
+ if (typeof obj["value"] !== "string" || obj["value"].trim().length === 0) {
1331
+ return false;
1332
+ }
1333
+ if ("labelKey" in obj) {
1334
+ const lk = obj["labelKey"];
1335
+ if (lk !== null && lk !== void 0 && typeof lk !== "string") {
1336
+ return false;
1337
+ }
1338
+ }
1339
+ return true;
1340
+ }
1341
+ function isMetadataValueObjectArray(val) {
1342
+ if (!Array.isArray(val) || val.length === 0) {
1343
+ return false;
1344
+ }
1345
+ return val.every(isMetadataValueObject);
1346
+ }
1347
+
1348
+ // ../../libs/runtime-metadata/src/lib/utils/normalizeRuntimeMetadataTypeCode.ts
1349
+ var RUNTIME_METADATA_TYPE_CODE_ALIASES = {
1350
+ Speciality: "Specialty"
1351
+ };
1352
+ function normalizeRuntimeMetadataTypeCode(metadataTypeCode) {
1353
+ const trimmed = metadataTypeCode?.trim() ?? "";
1354
+ if (!trimmed) {
1355
+ return trimmed;
1356
+ }
1357
+ return RUNTIME_METADATA_TYPE_CODE_ALIASES[trimmed] ?? trimmed;
1358
+ }
1359
+
1360
+ // ../../libs/runtime-metadata/src/lib/utils/codeFieldConvention.ts
1361
+ var DEFAULT_EXCLUDED_CODE_FIELDS = [
1362
+ "typeCode",
1363
+ "valueCode",
1364
+ "metadataTypeCode",
1365
+ "metadataValueCode",
1366
+ "targetValueCode",
1367
+ "targetMetadataTypeCode",
1368
+ "fromMetadataTypeCode",
1369
+ "fromMetadataValueCode",
1370
+ "toMetadataTypeCode",
1371
+ "toMetadataValueCode",
1372
+ "postalCode",
1373
+ "zipCode",
1374
+ "areaCode",
1375
+ "countryCallingCode",
1376
+ "phoneCountryCode",
1377
+ "dialCode",
1378
+ "hashCode",
1379
+ "errorCode",
1380
+ "httpStatusCode",
1381
+ "statusCode"
1382
+ ];
1383
+ var NON_METADATA_KEYS = /* @__PURE__ */ new Set([
1384
+ "id",
1385
+ "status",
1386
+ "name",
1387
+ "title",
1388
+ "message",
1389
+ "error",
1390
+ "description",
1391
+ "createdBy",
1392
+ "updatedBy",
1393
+ "createdByName",
1394
+ "updatedByName",
1395
+ "createdAt",
1396
+ "updatedAt",
1397
+ "timestamp",
1398
+ "count",
1399
+ "version",
1400
+ "recordVersion",
1401
+ "stepCount",
1402
+ "checklistItemCount",
1403
+ "page",
1404
+ "limit",
1405
+ "total",
1406
+ "value",
1407
+ "labelKey",
1408
+ "scope",
1409
+ "templateId",
1410
+ "orgTemplateId",
1411
+ "platformTemplateId",
1412
+ "templateName",
1413
+ "monitoringName",
1414
+ "subtitle",
1415
+ "requirement",
1416
+ "instruction",
1417
+ "instructions",
1418
+ "active",
1419
+ "sortOrder",
1420
+ "required",
1421
+ "allowSkip",
1422
+ "allowDefer",
1423
+ "blocksStepCompletion",
1424
+ "linkedAction",
1425
+ "linkedObject",
1426
+ "assigneeOverride",
1427
+ "defaultAssignee",
1428
+ "steps",
1429
+ "checklists",
1430
+ "items",
1431
+ "nextCursor",
1432
+ "organizationId",
1433
+ "orgId",
1434
+ "patientId",
1435
+ "carePlanId",
1436
+ "workflowInstanceId",
1437
+ "contextKey",
1438
+ "reason",
1439
+ "idempotencyKey",
1440
+ "sourceEventId",
1441
+ "eventId",
1442
+ "eventType",
1443
+ "eventVersion",
1444
+ "correlationId",
1445
+ "awsRequestId",
1446
+ "_metadata",
1447
+ "_links"
1448
+ ]);
1449
+ var WORKFLOW_STEP_RULE_KEYS = /* @__PURE__ */ new Set(["condition"]);
1450
+ function isWorkflowStepRecord(node) {
1451
+ if (typeof node["stepId"] === "string" && node["stepId"].trim().length > 0) {
1452
+ return true;
1453
+ }
1454
+ return "allowSkip" in node || "allowDefer" in node || "blocksStepCompletion" in node || Array.isArray(node["checklists"]);
1455
+ }
1456
+ function isWorkflowStepRuleField(key, parent) {
1457
+ return WORKFLOW_STEP_RULE_KEYS.has(key) && isWorkflowStepRecord(parent);
1458
+ }
1459
+ var DEFAULT_EXCLUDED = new Set(DEFAULT_EXCLUDED_CODE_FIELDS);
1460
+ function typeCodeFromCodeFieldName(fieldName, excluded = DEFAULT_EXCLUDED) {
1461
+ if (typeof fieldName !== "string" || fieldName.length <= 4) {
1462
+ return void 0;
1463
+ }
1464
+ if (!fieldName.endsWith("Code")) {
1465
+ return void 0;
1466
+ }
1467
+ if (fieldName.includes("__Code")) {
1468
+ return void 0;
1469
+ }
1470
+ if (excluded.has(fieldName)) {
1471
+ return void 0;
1472
+ }
1473
+ const inferred = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
1474
+ return normalizeRuntimeMetadataTypeCode(inferred) || void 0;
1475
+ }
1476
+ function createCodeFieldExclusionSet(extra) {
1477
+ const excluded = new Set(DEFAULT_EXCLUDED);
1478
+ if (extra) {
1479
+ for (const name of extra) {
1480
+ const trimmed = name.trim();
1481
+ if (trimmed) {
1482
+ excluded.add(trimmed);
1483
+ }
1484
+ }
1485
+ }
1486
+ return excluded;
1487
+ }
1488
+
1489
+ // ../../libs/runtime-metadata/src/lib/utils/collectResponseTypeCodes.ts
1490
+ function collectResponseTypeCodes(value, options) {
1491
+ const collected = /* @__PURE__ */ new Set();
1492
+ const knownSet = options?.knownTypes ? options.knownTypes instanceof Set ? options.knownTypes : new Set(options.knownTypes) : void 0;
1493
+ walk(value, collected, void 0, /* @__PURE__ */ new WeakSet(), exclusionSet(options), knownSet, "", options?.diagnostics);
1494
+ if (options?.diagnostics) {
1495
+ options.diagnostics.totalUniqueTypesDiscovered = collected.size;
1496
+ }
1497
+ return [...collected].sort((a, b) => a.localeCompare(b));
1498
+ }
1499
+ function collectResponseReferences(value, options) {
1500
+ const collected = /* @__PURE__ */ new Map();
1501
+ const knownSet = options?.knownTypes ? options.knownTypes instanceof Set ? options.knownTypes : new Set(options.knownTypes) : void 0;
1502
+ walk(value, void 0, collected, /* @__PURE__ */ new WeakSet(), exclusionSet(options), knownSet, "", options?.diagnostics);
1503
+ if (options?.diagnostics) {
1504
+ options.diagnostics.totalUniqueTypeValuesDiscovered = collected.size;
1505
+ }
1506
+ return [...collected.values()].sort((a, b) => {
1507
+ const type = a.typeCode.localeCompare(b.typeCode);
1508
+ return type !== 0 ? type : a.valueCode.localeCompare(b.valueCode);
1509
+ });
1510
+ }
1511
+ function exclusionSet(options) {
1512
+ return createCodeFieldExclusionSet(options?.excludedCodeFields);
1513
+ }
1514
+ function pushUnique(candidates, value) {
1515
+ const trimmed = value?.trim() ?? "";
1516
+ if (!trimmed || candidates.includes(trimmed)) {
1517
+ return;
1518
+ }
1519
+ candidates.push(trimmed);
1520
+ }
1521
+ function isAllCapsToken(key) {
1522
+ return key.length > 0 && key === key.toUpperCase() && key !== key.toLowerCase();
1523
+ }
1524
+ function pascalCaseToken(token) {
1525
+ const lower = token.toLowerCase();
1526
+ return lower.charAt(0).toUpperCase() + lower.slice(1);
1527
+ }
1528
+ function getCandidateTypeCodesForKey(key) {
1529
+ const candidates = [];
1530
+ const capitalized = key.charAt(0).toUpperCase() + key.slice(1);
1531
+ if (isAllCapsToken(key) && !key.includes("_") && !/code$/i.test(key)) {
1532
+ pushUnique(candidates, pascalCaseToken(key));
1533
+ }
1534
+ pushUnique(candidates, capitalized);
1535
+ pushUnique(candidates, normalizeRuntimeMetadataTypeCode(key));
1536
+ if (/code$/i.test(key) && key.length > 4) {
1537
+ const base = key.slice(0, -4);
1538
+ pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
1539
+ pushUnique(candidates, normalizeRuntimeMetadataTypeCode(base));
1540
+ if (isAllCapsToken(base) && !base.includes("_")) {
1541
+ pushUnique(candidates, pascalCaseToken(base));
1542
+ }
1543
+ }
1544
+ if (capitalized === "AllowedDevice" || capitalized === "AllowedDevices") {
1545
+ pushUnique(candidates, "Device");
1546
+ }
1547
+ if (capitalized === "LinkedEntityCode" || capitalized === "LinkedEntity") {
1548
+ pushUnique(candidates, "MetricCode");
1549
+ pushUnique(candidates, "QuestionCode");
1550
+ }
1551
+ const pluralKey = isAllCapsToken(key) ? key.toLowerCase() : key;
1552
+ if (pluralKey.endsWith("ies") && pluralKey.length > 3) {
1553
+ const base = pluralKey.slice(0, -3) + "y";
1554
+ pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
1555
+ } else if (pluralKey.endsWith("es") && pluralKey.length > 2) {
1556
+ const base = pluralKey.slice(0, -2);
1557
+ pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
1558
+ } else if (pluralKey.endsWith("s") && pluralKey.length > 1) {
1559
+ const base = pluralKey.slice(0, -1);
1560
+ pushUnique(candidates, base.charAt(0).toUpperCase() + base.slice(1));
1561
+ }
1562
+ return candidates;
1563
+ }
1564
+ var getCandidatesForKey = getCandidateTypeCodesForKey;
1565
+ function walk(value, typeCodes, references, visited, excludedCodeFields, knownSet, currentPath = "", diagnostics) {
1566
+ if (value === null || value === void 0) {
1567
+ return;
1568
+ }
1569
+ if (typeof value !== "object") {
1570
+ return;
1571
+ }
1572
+ if (visited.has(value)) {
1573
+ return;
1574
+ }
1575
+ visited.add(value);
1576
+ if (Array.isArray(value)) {
1577
+ for (const item of value) {
1578
+ walk(item, typeCodes, references, visited, excludedCodeFields, knownSet);
1579
+ }
1580
+ return;
1581
+ }
1582
+ if (isMetadataReference(value)) {
1583
+ addReference(value.typeCode, value.valueCode, typeCodes, references);
1584
+ }
1585
+ const record = value;
1586
+ if (record["ref"] === "META" && typeof record["typeCode"] === "string") {
1587
+ const valCode = typeof record["valueCode"] === "string" ? record["valueCode"] : "";
1588
+ addReference(record["typeCode"], valCode, typeCodes, references);
1589
+ }
1590
+ for (const [field, child] of Object.entries(record)) {
1591
+ if (excludedCodeFields.has(field)) {
1592
+ continue;
1593
+ }
1594
+ if (field.includes("__Code")) {
1595
+ continue;
1596
+ }
1597
+ if (NON_METADATA_KEYS.has(field)) {
1598
+ walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
1599
+ continue;
1600
+ }
1601
+ if (isWorkflowStepRuleField(field, record)) {
1602
+ if (typeof child === "object" && child !== null) {
1603
+ walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
1604
+ }
1605
+ continue;
1606
+ }
1607
+ if (isMetadataValueObject(child)) {
1608
+ const candidates = getCandidatesForKey(field);
1609
+ let matchedType;
1610
+ if (knownSet) {
1611
+ matchedType = candidates.find((c) => knownSet.has(c));
1612
+ } else if ("labelKey" in child || field.endsWith("Code")) {
1613
+ matchedType = candidates[0];
1614
+ }
1615
+ if (matchedType) {
1616
+ addReference(matchedType, child.value, typeCodes, references);
1617
+ continue;
1618
+ }
1619
+ }
1620
+ if (isMetadataValueObjectArray(child)) {
1621
+ const candidates = getCandidatesForKey(field);
1622
+ let matchedType;
1623
+ if (knownSet) {
1624
+ matchedType = candidates.find((c) => knownSet.has(c));
1625
+ } else if (child.some((item) => "labelKey" in item) || field.endsWith("Code")) {
1626
+ matchedType = candidates[0];
1627
+ }
1628
+ if (matchedType) {
1629
+ for (const item of child) {
1630
+ addReference(matchedType, item.value, typeCodes, references);
1631
+ }
1632
+ continue;
1633
+ }
1634
+ }
1635
+ collectStringCodeField(
1636
+ field,
1637
+ child,
1638
+ typeCodes,
1639
+ references,
1640
+ excludedCodeFields
1641
+ );
1642
+ if (knownSet) {
1643
+ const candidates = getCandidatesForKey(field);
1644
+ for (const cand of candidates) {
1645
+ if (knownSet.has(cand)) {
1646
+ if (typeof child === "string" && child.trim().length > 0) {
1647
+ addReference(cand, child, typeCodes, references);
1648
+ break;
1649
+ }
1650
+ if (Array.isArray(child) && child.length > 0 && child.every((c) => typeof c === "string")) {
1651
+ for (const item of child) {
1652
+ addReference(cand, item, typeCodes, references);
1653
+ }
1654
+ break;
1655
+ }
1656
+ }
1657
+ }
1658
+ }
1659
+ walk(child, typeCodes, references, visited, excludedCodeFields, knownSet);
1660
+ }
1661
+ }
1662
+ function collectStringCodeField(field, child, typeCodes, references, excludedCodeFields) {
1663
+ const inferredType = typeCodeFromCodeFieldName(field, excludedCodeFields);
1664
+ if (!inferredType) {
1665
+ return;
1666
+ }
1667
+ if (typeof child === "string") {
1668
+ if (child.trim().length > 0) {
1669
+ addReference(inferredType, child, typeCodes, references);
1670
+ }
1671
+ return;
1672
+ }
1673
+ if (Array.isArray(child)) {
1674
+ for (const item of child) {
1675
+ if (typeof item === "string" && item.trim().length > 0) {
1676
+ addReference(inferredType, item, typeCodes, references);
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+ function addReference(rawTypeCode, rawValueCode, typeCodes, references) {
1682
+ const typeCode = normalizeRuntimeMetadataTypeCode(rawTypeCode);
1683
+ const valueCode = rawValueCode.trim();
1684
+ if (!typeCode) {
1685
+ return;
1686
+ }
1687
+ typeCodes?.add(typeCode);
1688
+ if (valueCode) {
1689
+ references?.set(`${typeCode}:${valueCode}`, { typeCode, valueCode });
1690
+ }
1691
+ }
1692
+ var SCREAMING_SNAKE_REGEX = /^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$/;
1693
+ var METADATA_CODE_VALUE_REGEX = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
1694
+ function hasPotentialMetadata(value) {
1695
+ if (value === null || value === void 0 || typeof value !== "object") {
1696
+ return false;
1697
+ }
1698
+ if (Array.isArray(value)) {
1699
+ return value.some((item) => hasPotentialMetadata(item));
1700
+ }
1701
+ if (isMetadataReference(value)) {
1702
+ return true;
1703
+ }
1704
+ if (isMetadataValueObject(value)) {
1705
+ return true;
1706
+ }
1707
+ const obj = value;
1708
+ if (obj["ref"] === "META") {
1709
+ return true;
1710
+ }
1711
+ for (const [key, child] of Object.entries(obj)) {
1712
+ if (NON_METADATA_KEYS.has(key)) {
1713
+ if (typeof child === "object" && child !== null && hasPotentialMetadata(child)) {
1714
+ return true;
1715
+ }
1716
+ continue;
1717
+ }
1718
+ if (isMetadataValueObject(child) || isMetadataValueObjectArray(child)) {
1719
+ return true;
1720
+ }
1721
+ if (key.endsWith("Code") && key.length > 4 && typeof child === "string" && child.trim().length > 0) {
1722
+ return true;
1723
+ }
1724
+ if (typeof child === "string" && (SCREAMING_SNAKE_REGEX.test(child.trim()) || METADATA_CODE_VALUE_REGEX.test(child.trim()))) {
1725
+ return true;
1726
+ }
1727
+ if (Array.isArray(child) && child.length > 0 && child.some(
1728
+ (c) => typeof c === "string" && (SCREAMING_SNAKE_REGEX.test(c.trim()) || METADATA_CODE_VALUE_REGEX.test(c.trim()))
1729
+ )) {
1730
+ return true;
1731
+ }
1732
+ if (typeof child === "object" && child !== null && hasPotentialMetadata(child)) {
1733
+ return true;
1734
+ }
1735
+ }
1736
+ return false;
1737
+ }
1738
+
1739
+ // ../../libs/runtime-metadata/src/lib/utils/parseMetadataReference.ts
1740
+ function parseMetadataReference(reference) {
1741
+ const parsed = tryParseMetadataReference(reference);
1742
+ if (!parsed) {
1743
+ throw new InvalidMetadataReferenceError(reference);
1744
+ }
1745
+ return parsed;
1746
+ }
1747
+ function tryParseMetadataReference(reference) {
1748
+ if (typeof reference !== "string") {
1749
+ return null;
1750
+ }
1751
+ const trimmed = reference.trim();
1752
+ if (!trimmed) {
1753
+ return null;
1754
+ }
1755
+ const separator = trimmed.indexOf(":");
1756
+ if (separator <= 0 || separator === trimmed.length - 1) {
1757
+ return null;
1758
+ }
1759
+ const typeCode = normalizeRuntimeMetadataTypeCode(
1760
+ trimmed.slice(0, separator)
1761
+ );
1762
+ const valueCode = trimmed.slice(separator + 1).trim();
1763
+ if (!typeCode || !valueCode) {
1764
+ return null;
1765
+ }
1766
+ return { typeCode, valueCode };
1767
+ }
1768
+ function formatMetadataReference(typeCode, valueCode) {
1769
+ return `${typeCode}:${valueCode}`;
1770
+ }
1771
+ function isCompactMetadataReference(value) {
1772
+ return tryParseMetadataReference(typeof value === "string" ? value : null) !== null;
1773
+ }
1774
+
1775
+ // ../../libs/runtime-metadata/src/lib/read-model/ReadModelManifestGroups.ts
1776
+ function metadataGroupFromManifest(manifest) {
1777
+ return {
1778
+ metadataTypes: manifest.metadataTypes,
1779
+ lookupIndex: manifest.lookupIndex
1780
+ };
1781
+ }
1782
+ function readModelGroupsFromManifest(manifest) {
1783
+ return {
1784
+ metadata: metadataGroupFromManifest(manifest)
1785
+ };
1786
+ }
1787
+ var projectionTypeSchema2 = z.string().min(1);
1788
+ var manifestLocalizationSchema = z.object({
1789
+ defaultLocale: z.string().min(1),
1790
+ supportedLocales: z.array(z.string().min(1)),
1791
+ files: z.record(z.string(), z.string().min(1))
1792
+ }).optional();
1793
+ var projectionManifestSchema = z.object({
1794
+ releaseId: z.string().min(1),
1795
+ environment: z.string().min(1),
1796
+ generatedAt: z.string().min(1),
1797
+ projectionVersion: z.string().min(1),
1798
+ metadataCount: z.number().int().nonnegative(),
1799
+ artifactCount: z.number().int().nonnegative(),
1800
+ contentHash: z.string().min(1),
1801
+ artifacts: z.array(z.string().min(1)),
1802
+ files: z.array(
1803
+ z.object({
1804
+ fileName: z.string().min(1),
1805
+ projectionType: projectionTypeSchema2,
1806
+ contentHash: z.string().min(1),
1807
+ itemCount: z.number().int().nonnegative()
1808
+ })
1809
+ ).min(1),
1810
+ metadataTypes: z.record(
1811
+ z.string(),
1812
+ z.object({
1813
+ typeCode: z.string().min(1),
1814
+ projectionFile: z.string().min(1),
1815
+ localizedDisplayName: z.record(z.string(), z.string()).optional(),
1816
+ valueDataType: z.string().optional(),
1817
+ multiSelectAllowed: z.boolean().optional()
1818
+ }).passthrough()
1819
+ ).refine((v) => Object.keys(v).length > 0, {
1820
+ message: "metadataTypes must not be empty"
1821
+ }),
1822
+ lookupIndex: z.record(
1823
+ z.string(),
1824
+ z.object({
1825
+ typeCode: z.string().min(1),
1826
+ valueCode: z.string().min(1),
1827
+ projectionFile: z.string().min(1)
1828
+ })
1829
+ ).optional().default({}),
1830
+ localization: manifestLocalizationSchema,
1831
+ revision: z.string().min(1),
1832
+ schemaVersion: z.number().int().positive()
1833
+ });
1834
+ var MetadataLoader = class {
1835
+ expectedSchemaVersion;
1836
+ expectedProjectionVersion;
1837
+ logger;
1838
+ constructor(options) {
1839
+ this.expectedSchemaVersion = options.expectedSchemaVersion;
1840
+ this.expectedProjectionVersion = options.expectedProjectionVersion;
1841
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
1842
+ }
1843
+ /**
1844
+ * Parse + validate raw manifest JSON body.
1845
+ */
1846
+ parseAndValidate(rawBody) {
1847
+ let parsed;
1848
+ try {
1849
+ parsed = JSON.parse(rawBody);
1850
+ } catch {
1851
+ throw new ManifestValidationError("Malformed manifest JSON", [
1852
+ { code: "invalid_json", message: "manifest.json is not valid JSON" }
1853
+ ]);
1854
+ }
1855
+ const result = projectionManifestSchema.safeParse(parsed);
1856
+ if (!result.success) {
1857
+ const details = result.error.issues.map((issue) => ({
1858
+ code: issue.code,
1859
+ field: issue.path.join(".") || void 0,
1860
+ message: issue.message
1861
+ }));
1862
+ throw new ManifestValidationError("Invalid manifest schema", details);
1863
+ }
1864
+ const manifest = result.data;
1865
+ this.validateVersion(manifest);
1866
+ this.validateRequiredFiles(manifest);
1867
+ this.validateManifestContentHash(manifest);
1868
+ const metadataTypes = Object.keys(manifest.metadataTypes);
1869
+ const lookupIndexTypes = [
1870
+ ...new Set(
1871
+ Object.keys(manifest.lookupIndex ?? {}).map(
1872
+ (key) => key.split(":")[0] ?? key
1873
+ )
1874
+ )
1875
+ ].sort();
1876
+ this.logger.info({
1877
+ event: RUNTIME_METADATA_EVENTS.MANIFEST_LOADED,
1878
+ releaseId: manifest.releaseId,
1879
+ revision: manifest.revision,
1880
+ contentHash: manifest.contentHash,
1881
+ fileCount: manifest.files.length,
1882
+ metadataTypeCount: metadataTypes.length,
1883
+ lookupIndexSize: Object.keys(manifest.lookupIndex).length
1884
+ });
1885
+ this.logger.info({
1886
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_MANIFEST_LOADED,
1887
+ releaseId: manifest.releaseId,
1888
+ metadataTypes,
1889
+ lookupIndex: lookupIndexTypes,
1890
+ lookupIndexSize: Object.keys(manifest.lookupIndex).length,
1891
+ files: manifest.files.map((f) => ({
1892
+ fileName: f.fileName,
1893
+ projectionType: f.projectionType
1894
+ })),
1895
+ consistent: metadataTypes.length === lookupIndexTypes.length && metadataTypes.every((t) => lookupIndexTypes.includes(t))
1896
+ });
1897
+ return manifest;
1898
+ }
1899
+ /**
1900
+ * Detect whether a newly loaded manifest differs from the currently cached one.
1901
+ */
1902
+ compare(current, next) {
1903
+ const previousRevision = current?.revision ?? null;
1904
+ const previousContentHash = current?.contentHash ?? null;
1905
+ const changed = previousRevision === null || previousContentHash === null || previousRevision !== next.revision || previousContentHash !== next.contentHash;
1906
+ return {
1907
+ changed,
1908
+ previousRevision,
1909
+ previousContentHash,
1910
+ nextRevision: next.revision,
1911
+ nextContentHash: next.contentHash
1912
+ };
1913
+ }
1914
+ validateVersion(manifest) {
1915
+ if (manifest.schemaVersion !== this.expectedSchemaVersion) {
1916
+ throw new ManifestValidationError(
1917
+ `Incompatible manifest schemaVersion ${manifest.schemaVersion}; expected ${this.expectedSchemaVersion}`,
1918
+ [
1919
+ {
1920
+ code: "incompatible_version",
1921
+ field: "schemaVersion",
1922
+ message: `expected ${this.expectedSchemaVersion}`
1923
+ }
1924
+ ]
1925
+ );
1926
+ }
1927
+ if (this.expectedProjectionVersion && manifest.projectionVersion !== this.expectedProjectionVersion) {
1928
+ throw new ManifestValidationError(
1929
+ `Incompatible projectionVersion ${manifest.projectionVersion}; expected ${this.expectedProjectionVersion}`,
1930
+ [
1931
+ {
1932
+ code: "incompatible_projection_version",
1933
+ field: "projectionVersion",
1934
+ message: `expected ${this.expectedProjectionVersion}`
1935
+ }
1936
+ ]
1937
+ );
1938
+ }
1939
+ }
1940
+ validateRequiredFiles(manifest) {
1941
+ const byName = new Map(manifest.files.map((f) => [f.fileName, f]));
1942
+ const missing = [];
1943
+ for (const [typeCode, entry] of Object.entries(manifest.metadataTypes)) {
1944
+ if (!byName.has(entry.projectionFile)) {
1945
+ missing.push(entry.projectionFile);
1946
+ }
1947
+ if (entry.typeCode !== typeCode) {
1948
+ throw new ManifestValidationError(
1949
+ `metadataTypes key "${typeCode}" does not match typeCode "${entry.typeCode}"`,
1950
+ [
1951
+ {
1952
+ code: "metadata_type_key_mismatch",
1953
+ field: `metadataTypes.${typeCode}`,
1954
+ message: "typeCode must equal the map key"
1955
+ }
1956
+ ]
1957
+ );
1958
+ }
1959
+ }
1960
+ if (!byName.has(PROJECTION_FILE_NAME[PROJECTION_TYPE.COMMON])) {
1961
+ missing.push(PROJECTION_FILE_NAME[PROJECTION_TYPE.COMMON]);
1962
+ }
1963
+ if (missing.length > 0) {
1964
+ throw new ManifestValidationError(
1965
+ `Manifest missing required projection files: ${missing.join(", ")}`,
1966
+ missing.map((fileName) => ({
1967
+ code: "missing_file",
1968
+ field: fileName,
1969
+ message: "required projection file not listed in manifest"
1970
+ }))
1971
+ );
1972
+ }
1973
+ }
1974
+ validateManifestContentHash(manifest) {
1975
+ const expected = ProjectionHelper.contentHash(
1976
+ [...manifest.files].sort((a, b) => a.fileName.localeCompare(b.fileName)).map((f) => ({ fileName: f.fileName, contentHash: f.contentHash }))
1977
+ );
1978
+ if (expected !== manifest.contentHash) {
1979
+ throw new ManifestValidationError(
1980
+ "Manifest contentHash does not match file entries",
1981
+ [
1982
+ {
1983
+ code: "checksum_mismatch",
1984
+ field: "contentHash",
1985
+ message: "manifest contentHash integrity check failed"
1986
+ }
1987
+ ]
1988
+ );
1989
+ }
1990
+ }
1991
+ };
1992
+ async function streamToString(body) {
1993
+ if (body == null) return "";
1994
+ if (typeof body === "string") return body;
1995
+ if (body instanceof Uint8Array) return Buffer.from(body).toString("utf-8");
1996
+ const stream = body;
1997
+ const chunks = [];
1998
+ for await (const chunk of stream) {
1999
+ chunks.push(Buffer.from(chunk));
2000
+ }
2001
+ return Buffer.concat(chunks).toString("utf-8");
2002
+ }
2003
+ var MetadataDownloader = class {
2004
+ client;
2005
+ bucket;
2006
+ pathBuilder;
2007
+ expectedProjectionVersion;
2008
+ logger;
2009
+ loader;
2010
+ constructor(options) {
2011
+ if (!options.client) {
2012
+ throw new RuntimeMetadataError(
2013
+ "MetadataDownloader requires an injected S3Client",
2014
+ 400,
2015
+ "RUNTIME_METADATA_CLIENT_REQUIRED",
2016
+ void 0,
2017
+ { retryable: false }
2018
+ );
2019
+ }
2020
+ const bucket = options.bucket?.trim() ?? "";
2021
+ if (!bucket) {
2022
+ throw new RuntimeMetadataError(
2023
+ "MetadataDownloader requires a non-empty bucket",
2024
+ 400,
2025
+ "RUNTIME_METADATA_BUCKET_REQUIRED",
2026
+ void 0,
2027
+ { retryable: false }
2028
+ );
2029
+ }
2030
+ this.client = options.client;
2031
+ this.bucket = bucket;
2032
+ this.pathBuilder = new ProjectionPathBuilder({
2033
+ prefix: options.prefix,
2034
+ environment: options.environment
2035
+ });
2036
+ this.expectedProjectionVersion = options.expectedProjectionVersion ?? PROJECTION_VERSION;
2037
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
2038
+ this.loader = options.loader ?? new MetadataLoader({
2039
+ expectedSchemaVersion: options.expectedSchemaVersion,
2040
+ expectedProjectionVersion: this.expectedProjectionVersion,
2041
+ logger: this.logger
2042
+ });
2043
+ }
2044
+ buildKey(releaseId, fileName) {
2045
+ return this.pathBuilder.releaseArtifactKey(releaseId, fileName);
2046
+ }
2047
+ /**
2048
+ * Resolve the active release via `current.json`.
2049
+ */
2050
+ async discoverLatestRevision() {
2051
+ const pointer = await this.downloadCurrentPointer();
2052
+ return pointer.currentRelease;
2053
+ }
2054
+ async downloadCurrentPointer() {
2055
+ const key = this.pathBuilder.currentPointerKey();
2056
+ const body = await this.getObjectBody(key);
2057
+ let parsed;
2058
+ try {
2059
+ parsed = JSON.parse(body);
2060
+ } catch {
2061
+ throw new ProjectionDownloadError("Malformed current.json", {
2062
+ retryable: false,
2063
+ metadata: { key }
2064
+ });
2065
+ }
2066
+ if (!parsed.currentRelease?.trim()) {
2067
+ throw new ProjectionDownloadError(
2068
+ "current.json missing currentRelease",
2069
+ { retryable: false, metadata: { key } }
2070
+ );
2071
+ }
2072
+ return parsed;
2073
+ }
2074
+ /**
2075
+ * Download + validate manifest.json for a release (lookupIndex + integrity catalog).
2076
+ */
2077
+ async downloadManifest(releaseId) {
2078
+ const fileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.MANIFEST];
2079
+ const body = await this.getObjectBody(this.buildKey(releaseId, fileName));
2080
+ return this.loader.parseAndValidate(body);
2081
+ }
2082
+ /**
2083
+ * Bootstrap: resolve release → manifest.json only.
2084
+ *
2085
+ * Manifest supplies lookupIndex, metadataTypes, and integrity hashes.
2086
+ * `common.json` is **not** loaded — enrichment resolves from domain projections.
2087
+ * Domain `{typeCode}.json` files are downloaded later via
2088
+ * {@link downloadDomainProjections}.
2089
+ */
2090
+ async loadBootstrap(releaseId) {
2091
+ const target = releaseId?.trim() || await this.discoverLatestRevision();
2092
+ const manifest = await this.downloadManifest(target);
2093
+ this.assertManifestMatchesRelease(manifest, target);
2094
+ return this.downloadBootstrapBundle(manifest);
2095
+ }
2096
+ /**
2097
+ * Installable bootstrap bundle from an already-fetched manifest.
2098
+ * Does not download common.json or domain projection files.
2099
+ */
2100
+ async downloadBootstrapBundle(manifest) {
2101
+ const timer = createPerformanceTimer("runtimeMetadata.downloadBootstrap");
2102
+ const releaseId = manifest.releaseId;
2103
+ const manifestFileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.MANIFEST];
2104
+ this.logger.info({
2105
+ event: RUNTIME_METADATA_EVENTS.DOWNLOAD_START,
2106
+ releaseId,
2107
+ revision: releaseId,
2108
+ fileCount: 0,
2109
+ mode: "bootstrap"
2110
+ });
2111
+ try {
2112
+ const relationshipIndex = await this.downloadRelationshipIndex(manifest);
2113
+ const loadedFiles = relationshipIndex ? [
2114
+ manifestFileName,
2115
+ PROJECTION_FILE_NAME[PROJECTION_TYPE.RELATIONSHIP_INDEX]
2116
+ ] : [manifestFileName];
2117
+ const localization = /* @__PURE__ */ new Map();
2118
+ if (manifest.localization?.files) {
2119
+ const localeEntries = Object.entries(manifest.localization.files);
2120
+ await Promise.all(
2121
+ localeEntries.map(async ([locale, relativePath]) => {
2122
+ try {
2123
+ const body = await this.getObjectBody(
2124
+ this.buildKey(releaseId, relativePath)
2125
+ );
2126
+ const parsed = JSON.parse(body);
2127
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
2128
+ const localeMap = /* @__PURE__ */ new Map();
2129
+ for (const [k, v] of Object.entries(parsed)) {
2130
+ if (typeof v === "string") {
2131
+ localeMap.set(k, v);
2132
+ }
2133
+ }
2134
+ localization.set(locale, localeMap);
2135
+ loadedFiles.push(relativePath);
2136
+ }
2137
+ } catch (locErr) {
2138
+ this.logger.warn({
2139
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED,
2140
+ releaseId,
2141
+ locale,
2142
+ relativePath,
2143
+ reason: "localizationFileDownloadFailed",
2144
+ err: locErr instanceof Error ? locErr.message : String(locErr)
2145
+ });
2146
+ }
2147
+ })
2148
+ );
2149
+ }
2150
+ const bundle = {
2151
+ revision: releaseId,
2152
+ releaseId,
2153
+ manifest,
2154
+ domainFiles: /* @__PURE__ */ new Map(),
2155
+ relationshipIndex,
2156
+ loadedFiles: loadedFiles.sort((a, b) => a.localeCompare(b)),
2157
+ localization: localization.size > 0 ? localization : void 0,
2158
+ downloadedAt: (/* @__PURE__ */ new Date()).toISOString()
2159
+ };
2160
+ this.logger.info({
2161
+ event: RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE,
2162
+ releaseId,
2163
+ loadedFiles: bundle.loadedFiles,
2164
+ mode: "bootstrap"
2165
+ });
2166
+ timer.end();
2167
+ return bundle;
2168
+ } catch (err) {
2169
+ timer.end();
2170
+ this.logger.error({
2171
+ event: RUNTIME_METADATA_EVENTS.DOWNLOAD_FAILED,
2172
+ err: err instanceof Error ? err : void 0,
2173
+ releaseId,
2174
+ mode: "bootstrap"
2175
+ });
2176
+ if (err instanceof ProjectionDownloadError || err instanceof RuntimeMetadataError) {
2177
+ throw err;
2178
+ }
2179
+ const message = err instanceof Error ? err.message : String(err);
2180
+ throw new ProjectionDownloadError(`Projection download failed: ${message}`, {
2181
+ retryable: true,
2182
+ metadata: { releaseId }
2183
+ });
2184
+ }
2185
+ }
2186
+ /**
2187
+ * Download domain projection files for the given MetadataTypeCodes.
2188
+ * Filenames are `{MetadataTypeCode}.json` — never looked up from the manifest.
2189
+ * Manifest `files` entries supply contentHash for integrity only.
2190
+ *
2191
+ * Types without a manifest integrity entry are WARN-skipped
2192
+ * (`manifestIntegrityEntryMissing`) so unsupported/unpublished projections
2193
+ * do not fail the batch. S3/integrity failures for types that *are* in the
2194
+ * manifest still throw. Downloads in parallel.
2195
+ */
2196
+ async downloadDomainProjections(manifest, metadataTypeCodes) {
2197
+ const releaseId = manifest.releaseId;
2198
+ const uniqueTypeCodes = [
2199
+ ...new Set(metadataTypeCodes.map((t) => t.trim()).filter(Boolean))
2200
+ ];
2201
+ if (uniqueTypeCodes.length === 0) {
2202
+ return { domainFiles: /* @__PURE__ */ new Map(), loadedFiles: [] };
2203
+ }
2204
+ const integrityByFileName = new Map(
2205
+ manifest.files.map((f) => [f.fileName, f])
2206
+ );
2207
+ this.logger.info({
2208
+ event: RUNTIME_METADATA_EVENTS.DOWNLOAD_START,
2209
+ releaseId,
2210
+ revision: releaseId,
2211
+ fileCount: uniqueTypeCodes.length,
2212
+ mode: "selective",
2213
+ metadataTypes: uniqueTypeCodes
2214
+ });
2215
+ const results = await Promise.all(
2216
+ uniqueTypeCodes.map(async (metadataTypeCode) => {
2217
+ const fileName = projectionFileName(metadataTypeCode);
2218
+ const entry = integrityByFileName.get(fileName);
2219
+ if (!entry) {
2220
+ this.logger.warn({
2221
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_SKIPPED,
2222
+ metadataTypeCode,
2223
+ projectionFile: fileName,
2224
+ releaseId,
2225
+ reason: "manifestIntegrityEntryMissing",
2226
+ mode: "selective"
2227
+ });
2228
+ return null;
2229
+ }
2230
+ this.logger.info({
2231
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_LOADING,
2232
+ releaseId,
2233
+ metadataType: metadataTypeCode,
2234
+ projectionFile: fileName,
2235
+ projectionType: entry.projectionType,
2236
+ mode: "selective"
2237
+ });
2238
+ const body = await this.getObjectBody(
2239
+ this.buildKey(releaseId, fileName)
2240
+ );
2241
+ return { metadataTypeCode, fileName, entry, body };
2242
+ })
2243
+ );
2244
+ const domainFiles = /* @__PURE__ */ new Map();
2245
+ const loadedFiles = [];
2246
+ for (const result of results) {
2247
+ if (!result) {
2248
+ continue;
2249
+ }
2250
+ const { metadataTypeCode, fileName, entry, body } = result;
2251
+ if (entry.projectionType === PROJECTION_TYPE.COMMON) {
2252
+ throw new ProjectionDownloadError(
2253
+ `Unexpected common projection in selective domain download: ${fileName}`,
2254
+ { retryable: false, metadata: { fileName, releaseId } }
2255
+ );
2256
+ }
2257
+ const file = this.parseAndValidateProjectionBody(
2258
+ fileName,
2259
+ entry.contentHash,
2260
+ body,
2261
+ releaseId
2262
+ );
2263
+ loadedFiles.push(fileName);
2264
+ domainFiles.set(metadataTypeCode, file);
2265
+ const recordCount = typeof file.records === "object" && file.records ? Object.keys(file.records).length : 0;
2266
+ this.logger.info({
2267
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_FILE_LOADED,
2268
+ releaseId,
2269
+ metadataType: metadataTypeCode,
2270
+ projectionFile: fileName,
2271
+ recordCount,
2272
+ fileEnvelopeMetadataType: file.metadataType,
2273
+ mode: "selective"
2274
+ });
2275
+ this.logger.info({
2276
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_CACHE_REGISTER,
2277
+ releaseId,
2278
+ metadataType: metadataTypeCode,
2279
+ cacheSize: domainFiles.size,
2280
+ projectionFile: fileName,
2281
+ mode: "selective"
2282
+ });
2283
+ }
2284
+ const sortedLoadedFiles = loadedFiles.sort((a, b) => a.localeCompare(b));
2285
+ this.logger.info({
2286
+ event: RUNTIME_METADATA_EVENTS.DOWNLOAD_COMPLETE,
2287
+ releaseId,
2288
+ loadedFiles: sortedLoadedFiles,
2289
+ mode: "selective"
2290
+ });
2291
+ return {
2292
+ domainFiles,
2293
+ loadedFiles: sortedLoadedFiles
2294
+ };
2295
+ }
2296
+ /**
2297
+ * Load `relationship-index.json` when listed in the manifest integrity catalog.
2298
+ * Missing/corrupt/mismatched artifacts fail closed — never activate an empty map.
2299
+ */
2300
+ async downloadRelationshipIndex(manifest) {
2301
+ const fileName = PROJECTION_FILE_NAME[PROJECTION_TYPE.RELATIONSHIP_INDEX];
2302
+ const entry = manifest.files.find((f) => f.fileName === fileName);
2303
+ if (!entry) {
2304
+ return void 0;
2305
+ }
2306
+ const body = await this.getObjectBody(
2307
+ this.buildKey(manifest.releaseId, fileName)
2308
+ );
2309
+ let parsed;
2310
+ try {
2311
+ parsed = JSON.parse(body);
2312
+ } catch {
2313
+ throw new ProjectionDownloadError(`Corrupted JSON for ${fileName}`, {
2314
+ retryable: false,
2315
+ metadata: { fileName, releaseId: manifest.releaseId }
2316
+ });
2317
+ }
2318
+ try {
2319
+ return parseAndValidateRelationshipIndex({
2320
+ parsed,
2321
+ expectedContentHash: entry.contentHash,
2322
+ expectedReleaseId: manifest.releaseId,
2323
+ fileName
2324
+ });
2325
+ } catch (err) {
2326
+ throw new ProjectionDownloadError(
2327
+ err instanceof Error ? err.message : `Invalid relationship index for ${fileName}`,
2328
+ {
2329
+ retryable: false,
2330
+ metadata: { fileName, releaseId: manifest.releaseId }
2331
+ }
2332
+ );
2333
+ }
2334
+ }
2335
+ assertManifestMatchesRelease(manifest, target) {
2336
+ if (manifest.releaseId !== target && manifest.revision !== target) {
2337
+ throw new ProjectionDownloadError(
2338
+ `Manifest releaseId ${manifest.releaseId} does not match requested ${target}`,
2339
+ { retryable: false, metadata: { releaseId: target } }
2340
+ );
2341
+ }
2342
+ }
2343
+ parseAndValidateProjectionBody(fileName, contentHash, body, releaseId) {
2344
+ let parsed;
2345
+ try {
2346
+ parsed = JSON.parse(body);
2347
+ } catch {
2348
+ throw new ProjectionDownloadError(`Corrupted JSON for ${fileName}`, {
2349
+ retryable: false,
2350
+ metadata: { fileName, releaseId }
2351
+ });
2352
+ }
2353
+ this.validateDownloadedFile(fileName, contentHash, parsed);
2354
+ return parsed;
2355
+ }
2356
+ async getObjectBody(key) {
2357
+ try {
2358
+ const resp = await this.client.send(
2359
+ new GetObjectCommand({
2360
+ Bucket: this.bucket,
2361
+ Key: key
2362
+ })
2363
+ );
2364
+ return streamToString(resp.Body);
2365
+ } catch (err) {
2366
+ const message = err instanceof Error ? err.message : String(err);
2367
+ const notFound = typeof err === "object" && err !== null && (err.name === "NoSuchKey" || err.$metadata?.httpStatusCode === 404);
2368
+ throw new ProjectionDownloadError(
2369
+ notFound ? `Missing projection object s3://${this.bucket}/${key}` : `S3 get failed for ${key}: ${message}`,
2370
+ {
2371
+ retryable: !notFound,
2372
+ metadata: { key, bucket: this.bucket }
2373
+ }
2374
+ );
2375
+ }
2376
+ }
2377
+ validateDownloadedFile(fileName, expectedHash, parsed) {
2378
+ if (!parsed || typeof parsed !== "object") {
2379
+ throw new ProjectionDownloadError(`Invalid projection payload for ${fileName}`, {
2380
+ retryable: false,
2381
+ metadata: { fileName }
2382
+ });
2383
+ }
2384
+ const record = parsed;
2385
+ const projectionVersion = record.projectionVersion;
2386
+ if (typeof projectionVersion !== "string" || projectionVersion !== this.expectedProjectionVersion) {
2387
+ throw new ProjectionDownloadError(
2388
+ `Incompatible projectionVersion on ${fileName}`,
2389
+ {
2390
+ retryable: false,
2391
+ metadata: { fileName, projectionVersion }
2392
+ }
2393
+ );
2394
+ }
2395
+ const contentHash = record.contentHash;
2396
+ if (typeof contentHash !== "string" || contentHash !== expectedHash) {
2397
+ throw new ProjectionDownloadError(
2398
+ `Checksum mismatch for ${fileName}`,
2399
+ {
2400
+ retryable: false,
2401
+ metadata: { fileName, expectedHash, contentHash }
2402
+ }
2403
+ );
2404
+ }
2405
+ }
2406
+ };
2407
+
2408
+ // ../../libs/runtime-metadata/src/lib/cache/MetadataCache.ts
2409
+ var MetadataCache = class {
2410
+ snapshot = null;
2411
+ status = CACHE_STATUS.EMPTY;
2412
+ /**
2413
+ * Monotonic generation incremented on every replace/clear.
2414
+ * Stale async hydration must not write into a newer generation.
2415
+ */
2416
+ generation = 0;
2417
+ getStatus() {
2418
+ return this.status;
2419
+ }
2420
+ setStatus(status) {
2421
+ this.status = status;
2422
+ }
2423
+ isReady() {
2424
+ return this.snapshot !== null && this.status !== CACHE_STATUS.EMPTY;
2425
+ }
2426
+ getSnapshot() {
2427
+ return this.snapshot;
2428
+ }
2429
+ getManifest() {
2430
+ return this.snapshot?.manifest ?? null;
2431
+ }
2432
+ getRevision() {
2433
+ return this.snapshot?.revision ?? null;
2434
+ }
2435
+ getReleaseId() {
2436
+ return this.snapshot?.releaseId ?? null;
2437
+ }
2438
+ getContentHash() {
2439
+ return this.snapshot?.contentHash ?? null;
2440
+ }
2441
+ getLoadedAt() {
2442
+ return this.snapshot?.loadedAt ?? null;
2443
+ }
2444
+ getLoadedFiles() {
2445
+ return this.snapshot?.loadedFiles ?? [];
2446
+ }
2447
+ getDomainFile(type) {
2448
+ return this.snapshot?.domainFiles.get(type);
2449
+ }
2450
+ getCommon() {
2451
+ return this.snapshot?.common;
2452
+ }
2453
+ getRelationshipIndex() {
2454
+ return this.snapshot?.relationshipIndex;
2455
+ }
2456
+ getLocalization(locale) {
2457
+ return this.snapshot?.localization?.get(locale);
2458
+ }
2459
+ getLocalizationMap(locale) {
2460
+ return this.snapshot?.localization?.get(locale);
2461
+ }
2462
+ getLocalizationValue(key, locale) {
2463
+ if (!this.snapshot?.localization) {
2464
+ return void 0;
2465
+ }
2466
+ if (locale) {
2467
+ const targetMap = this.snapshot.localization.get(locale);
2468
+ if (targetMap?.has(key)) {
2469
+ return targetMap.get(key);
2470
+ }
2471
+ }
2472
+ const defaultLocale = this.snapshot.manifest.localization?.defaultLocale ?? "en-US";
2473
+ return this.snapshot.localization.get(defaultLocale)?.get(key);
2474
+ }
2475
+ getGeneration() {
2476
+ return this.generation;
2477
+ }
2478
+ /**
2479
+ * Atomically replace the entire cache from a downloaded bundle.
2480
+ * Previous snapshot is discarded (not mutated).
2481
+ */
2482
+ replace(bundle) {
2483
+ this.generation += 1;
2484
+ const domainFiles = new Map(bundle.domainFiles);
2485
+ Object.freeze(domainFiles);
2486
+ const snapshot = Object.freeze({
2487
+ revision: bundle.releaseId,
2488
+ releaseId: bundle.releaseId,
2489
+ contentHash: bundle.manifest.contentHash,
2490
+ schemaVersion: bundle.manifest.schemaVersion,
2491
+ projectionVersion: bundle.manifest.projectionVersion,
2492
+ generatedAt: bundle.manifest.generatedAt,
2493
+ loadedAt: bundle.downloadedAt,
2494
+ loadedFiles: Object.freeze([...bundle.loadedFiles]),
2495
+ domainFiles,
2496
+ common: bundle.common ? Object.freeze({ ...bundle.common }) : void 0,
2497
+ relationshipIndex: bundle.relationshipIndex ? Object.freeze({ ...bundle.relationshipIndex }) : void 0,
2498
+ manifest: Object.freeze({
2499
+ ...bundle.manifest,
2500
+ files: Object.freeze(
2501
+ bundle.manifest.files.map((f) => Object.freeze({ ...f }))
2502
+ ),
2503
+ artifacts: Object.freeze([...bundle.manifest.artifacts ?? []]),
2504
+ metadataTypes: Object.freeze({ ...bundle.manifest.metadataTypes }),
2505
+ lookupIndex: Object.freeze({ ...bundle.manifest.lookupIndex })
2506
+ }),
2507
+ localization: bundle.localization ? Object.freeze(
2508
+ new Map(
2509
+ [...bundle.localization.entries()].map(([loc, cat]) => [
2510
+ loc,
2511
+ Object.freeze(new Map(cat))
2512
+ ])
2513
+ )
2514
+ ) : void 0
2515
+ });
2516
+ this.snapshot = snapshot;
2517
+ this.status = CACHE_STATUS.READY;
2518
+ return snapshot;
2519
+ }
2520
+ /**
2521
+ * Merge additional domain projection files into the current snapshot (same revision).
2522
+ * Used by selective on-demand downloads — never mutates the prior snapshot.
2523
+ */
2524
+ mergeDomainFiles(domainFiles, additionalLoadedFiles, guard) {
2525
+ if (!this.snapshot) {
2526
+ throw new Error("Cannot merge domain files into an empty metadata cache");
2527
+ }
2528
+ if (!this.guardAllowsWrite(guard)) {
2529
+ return this.snapshot;
2530
+ }
2531
+ const mergedDomain = new Map(this.snapshot.domainFiles);
2532
+ for (const [typeCode, file] of domainFiles) {
2533
+ if (file.releaseId && file.releaseId !== this.snapshot.releaseId) {
2534
+ continue;
2535
+ }
2536
+ mergedDomain.set(typeCode, file);
2537
+ }
2538
+ Object.freeze(mergedDomain);
2539
+ const loadedFiles = Object.freeze(
2540
+ [
2541
+ .../* @__PURE__ */ new Set([
2542
+ ...this.snapshot.loadedFiles,
2543
+ ...additionalLoadedFiles
2544
+ ])
2545
+ ].sort((a, b) => a.localeCompare(b))
2546
+ );
2547
+ const snapshot = Object.freeze({
2548
+ ...this.snapshot,
2549
+ domainFiles: mergedDomain,
2550
+ loadedFiles,
2551
+ loadedAt: (/* @__PURE__ */ new Date()).toISOString()
2552
+ });
2553
+ this.snapshot = snapshot;
2554
+ this.status = CACHE_STATUS.READY;
2555
+ return snapshot;
2556
+ }
2557
+ /**
2558
+ * Merge individual resolved entries into domain record maps (same release).
2559
+ * Used after an extension batch lookup so {@link MetadataResolver.resolve}
2560
+ * remains synchronous.
2561
+ */
2562
+ hydrateEntries(entries, guard) {
2563
+ if (!this.snapshot) {
2564
+ throw new Error("Cannot hydrate entries into an empty metadata cache");
2565
+ }
2566
+ if (entries.length === 0) {
2567
+ return this.snapshot;
2568
+ }
2569
+ if (!this.guardAllowsWrite(guard)) {
2570
+ return this.snapshot;
2571
+ }
2572
+ const byType = /* @__PURE__ */ new Map();
2573
+ for (const item of entries) {
2574
+ let typeMap = byType.get(item.typeCode);
2575
+ if (!typeMap) {
2576
+ typeMap = /* @__PURE__ */ new Map();
2577
+ byType.set(item.typeCode, typeMap);
2578
+ }
2579
+ typeMap.set(item.valueCode, item.entry);
2580
+ }
2581
+ const mergedDomain = new Map(this.snapshot.domainFiles);
2582
+ const additionalFiles = [];
2583
+ for (const [typeCode, values] of byType) {
2584
+ const existing = mergedDomain.get(typeCode);
2585
+ const records = { ...existing?.records ?? {} };
2586
+ for (const [valueCode, entry] of values) {
2587
+ records[valueCode] = {
2588
+ latestVersion: entry.version,
2589
+ publishedVersion: entry.version,
2590
+ versions: { [String(entry.version)]: entry }
2591
+ };
2592
+ }
2593
+ const fileName = projectionFileName(typeCode);
2594
+ additionalFiles.push(fileName);
2595
+ mergedDomain.set(typeCode, {
2596
+ metadataType: existing?.metadataType ?? typeCode,
2597
+ environment: existing?.environment ?? this.snapshot.manifest.environment,
2598
+ releaseId: existing?.releaseId ?? this.snapshot.releaseId,
2599
+ generatedAt: existing?.generatedAt ?? this.snapshot.generatedAt,
2600
+ projectionVersion: existing?.projectionVersion ?? this.snapshot.projectionVersion,
2601
+ contentHash: existing?.contentHash ?? this.snapshot.contentHash,
2602
+ metadataCount: Object.keys(records).length,
2603
+ records
2604
+ });
2605
+ }
2606
+ Object.freeze(mergedDomain);
2607
+ const loadedFiles = Object.freeze(
2608
+ [
2609
+ .../* @__PURE__ */ new Set([...this.snapshot.loadedFiles, ...additionalFiles])
2610
+ ].sort((a, b) => a.localeCompare(b))
2611
+ );
2612
+ const snapshot = Object.freeze({
2613
+ ...this.snapshot,
2614
+ domainFiles: mergedDomain,
2615
+ loadedFiles
2616
+ });
2617
+ this.snapshot = snapshot;
2618
+ this.status = CACHE_STATUS.READY;
2619
+ return snapshot;
2620
+ }
2621
+ /**
2622
+ * Clear only when explicitly requested (e.g. tests). Refresh failures must NOT call this.
2623
+ */
2624
+ clear() {
2625
+ this.generation += 1;
2626
+ this.snapshot = null;
2627
+ this.status = CACHE_STATUS.EMPTY;
2628
+ }
2629
+ guardAllowsWrite(guard) {
2630
+ if (!guard || !this.snapshot) {
2631
+ return true;
2632
+ }
2633
+ return guard.generation === this.generation && guard.releaseId === this.snapshot.releaseId;
2634
+ }
2635
+ };
2636
+ var MetadataResolver = class {
2637
+ cache;
2638
+ logger;
2639
+ constructor(options) {
2640
+ this.cache = options.cache;
2641
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
2642
+ }
2643
+ resolve(typeCodeOrRef, valueCodeOrVersion, version) {
2644
+ if (isMetadataReference(typeCodeOrRef)) {
2645
+ const refVersion = typeof valueCodeOrVersion === "number" ? valueCodeOrVersion : void 0;
2646
+ return this.resolveByTypeAndCode(
2647
+ typeCodeOrRef.typeCode,
2648
+ typeCodeOrRef.valueCode,
2649
+ refVersion
2650
+ );
2651
+ }
2652
+ return this.resolveByTypeAndCode(
2653
+ typeCodeOrRef,
2654
+ typeof valueCodeOrVersion === "string" ? valueCodeOrVersion : "",
2655
+ version
2656
+ );
2657
+ }
2658
+ resolveByTypeAndCode(typeCode, valueCode, version) {
2659
+ this.assertReady();
2660
+ const metadataTypeCode = this.requireSupportedType(typeCode);
2661
+ const trimmedValueCode = valueCode?.trim() ?? "";
2662
+ return this.requireEntry(metadataTypeCode, trimmedValueCode, version);
2663
+ }
2664
+ /**
2665
+ * O(1) localization lookup using in-memory locale map.
2666
+ * Resolves by key `<typeCode>.<valueCode>`.
2667
+ * Falls back to default locale if requested locale does not have the key.
2668
+ */
2669
+ resolveLocalization(typeCode, valueCode, locale) {
2670
+ if (!this.cache.isReady()) {
2671
+ return void 0;
2672
+ }
2673
+ const targetLocale = locale?.trim() || this.cache.getManifest()?.localization?.defaultLocale || "en-US";
2674
+ const locMap = this.cache.getLocalizationMap(targetLocale);
2675
+ const key = `${typeCode}.${valueCode}`;
2676
+ if (locMap?.has(key)) {
2677
+ return locMap.get(key);
2678
+ }
2679
+ const defaultLocale = this.cache.getManifest()?.localization?.defaultLocale || "en-US";
2680
+ if (targetLocale !== defaultLocale) {
2681
+ const defaultMap = this.cache.getLocalizationMap(defaultLocale);
2682
+ if (defaultMap?.has(key)) {
2683
+ return defaultMap.get(key);
2684
+ }
2685
+ }
2686
+ return void 0;
2687
+ }
2688
+ /**
2689
+ * Look up localized display name for a MetadataType from manifest or domain file.
2690
+ */
2691
+ getTypeLocalizedDisplayName(typeCode, locale) {
2692
+ if (!this.cache.isReady()) {
2693
+ return void 0;
2694
+ }
2695
+ const targetType = this.resolveMetadataTypeCode(typeCode);
2696
+ if (!targetType) {
2697
+ return void 0;
2698
+ }
2699
+ const manifest = this.cache.getManifest();
2700
+ const manifestType = manifest?.metadataTypes[targetType];
2701
+ const file = this.cache.getDomainFile(targetType);
2702
+ const locNames = file?.localizedDisplayName ?? manifestType?.localizedDisplayName;
2703
+ if (locNames && typeof locNames === "object") {
2704
+ const targetLocale = locale?.trim() || manifest?.localization?.defaultLocale || "en-US";
2705
+ if (locNames[targetLocale]) {
2706
+ return locNames[targetLocale];
2707
+ }
2708
+ const defaultLocale = manifest?.localization?.defaultLocale || "en-US";
2709
+ if (locNames[defaultLocale]) {
2710
+ return locNames[defaultLocale];
2711
+ }
2712
+ }
2713
+ return void 0;
2714
+ }
2715
+ /**
2716
+ * Value data type for a MetadataType (e.g. STRING, INTEGER).
2717
+ */
2718
+ getValueDataType(typeCode) {
2719
+ if (!this.cache.isReady()) {
2720
+ return void 0;
2721
+ }
2722
+ const targetType = this.resolveMetadataTypeCode(typeCode);
2723
+ if (!targetType) {
2724
+ return void 0;
2725
+ }
2726
+ const manifest = this.cache.getManifest();
2727
+ const manifestType = manifest?.metadataTypes[targetType];
2728
+ const file = this.cache.getDomainFile(targetType);
2729
+ return manifestType?.valueDataType ?? file?.valueDataType;
2730
+ }
2731
+ /**
2732
+ * Whether the given MetadataTypeCode is listed in the loaded manifest.
2733
+ * Does not require the domain projection file to be cached yet.
2734
+ */
2735
+ supportsType(typeCode) {
2736
+ const requestedType = typeCode?.trim() ?? "";
2737
+ if (!this.cache.isReady()) {
2738
+ this.logger.info({
2739
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_PROVIDER_SUPPORTS_TYPE,
2740
+ requestedType,
2741
+ supported: false,
2742
+ availableTypes: [],
2743
+ reason: "cacheNotReady",
2744
+ cacheStatus: this.cache.getStatus()
2745
+ });
2746
+ return false;
2747
+ }
2748
+ const supported = this.resolveMetadataTypeCode(requestedType) !== void 0;
2749
+ const availableTypes = Object.keys(
2750
+ this.cache.getManifest()?.metadataTypes ?? {}
2751
+ ).sort();
2752
+ this.logger.info({
2753
+ event: RUNTIME_METADATA_EVENTS.PROJECTION_PROVIDER_SUPPORTS_TYPE,
2754
+ requestedType,
2755
+ supported,
2756
+ availableTypes,
2757
+ cacheStatus: this.cache.getStatus(),
2758
+ releaseId: this.cache.getReleaseId()
2759
+ });
2760
+ return supported;
2761
+ }
2762
+ /** MetadataTypeCodes available for resolve (from manifest.metadataTypes). */
2763
+ listMetadataTypes() {
2764
+ this.assertReady();
2765
+ const manifest = this.requireManifest();
2766
+ return Object.freeze(Object.keys(manifest.metadataTypes).sort());
2767
+ }
2768
+ /** Authoritative loaded manifest (integrity catalog + metadataTypes + lookupIndex). */
2769
+ getManifest() {
2770
+ this.assertReady();
2771
+ return this.requireManifest();
2772
+ }
2773
+ /** Published lookup index from the loaded manifest. */
2774
+ getLookupIndex() {
2775
+ this.assertReady();
2776
+ return this.requireManifest().lookupIndex;
2777
+ }
2778
+ exists(type, code, version) {
2779
+ this.assertReady();
2780
+ const metadataTypeCode = this.resolveMetadataTypeCode(type);
2781
+ if (!metadataTypeCode) {
2782
+ return false;
2783
+ }
2784
+ const valueCode = code?.trim() ?? "";
2785
+ return this.lookupEntry(metadataTypeCode, valueCode, version) !== void 0;
2786
+ }
2787
+ /**
2788
+ * Return latest entries for a type, optionally filtered by a simple substring on code/label.
2789
+ * Not a hot path — used by tooling / health, not HTTP enrichment.
2790
+ */
2791
+ search(type, query) {
2792
+ const all = this.getAll(type);
2793
+ if (!query?.trim()) {
2794
+ return all;
2795
+ }
2796
+ const q = query.trim().toLowerCase();
2797
+ return all.filter(
2798
+ (entry) => entry.code.toLowerCase().includes(q) || entry.label.toLowerCase().includes(q) || entry.displayName.toLowerCase().includes(q)
2799
+ );
2800
+ }
2801
+ getAll(type) {
2802
+ this.assertReady();
2803
+ const metadataTypeCode = this.requireSupportedType(type);
2804
+ const file = this.cache.getDomainFile(metadataTypeCode);
2805
+ if (!file) {
2806
+ return [];
2807
+ }
2808
+ const latest = [];
2809
+ for (const record of Object.values(file.records)) {
2810
+ const entry = record.versions[String(record.latestVersion)];
2811
+ if (entry) {
2812
+ latest.push(entry);
2813
+ }
2814
+ }
2815
+ return latest.sort((a, b) => {
2816
+ if (a.sortOrder !== b.sortOrder) {
2817
+ return a.sortOrder - b.sortOrder;
2818
+ }
2819
+ return a.code.localeCompare(b.code);
2820
+ });
2821
+ }
2822
+ requireSupportedType(metadataType) {
2823
+ const metadataTypeCode = this.resolveMetadataTypeCode(metadataType);
2824
+ if (!metadataTypeCode) {
2825
+ const availableTypes = Object.keys(
2826
+ this.cache.getManifest()?.metadataTypes ?? {}
2827
+ ).sort();
2828
+ const trimmed = metadataType?.trim() ?? "";
2829
+ this.logger.warn({
2830
+ event: RUNTIME_METADATA_EVENTS.LOOKUP_MISS,
2831
+ metadataType,
2832
+ metadataTypeCode: trimmed,
2833
+ availableTypes,
2834
+ message: "Unknown metadata type"
2835
+ });
2836
+ throw new UnknownMetadataTypeError(metadataType);
2837
+ }
2838
+ return metadataTypeCode;
2839
+ }
2840
+ /**
2841
+ * Resolve MetadataTypeCode against manifest.metadataTypes.
2842
+ * Applies {@link normalizeRuntimeMetadataTypeCode} (e.g. Speciality → Specialty).
2843
+ * No SCREAMING_SNAKE / case-folding aliases.
2844
+ */
2845
+ resolveMetadataTypeCode(metadataType) {
2846
+ const metadataTypeCode = normalizeRuntimeMetadataTypeCode(metadataType);
2847
+ if (!metadataTypeCode) {
2848
+ return void 0;
2849
+ }
2850
+ const metadataTypes = this.cache.getManifest()?.metadataTypes;
2851
+ return metadataTypes && metadataTypeCode in metadataTypes ? metadataTypeCode : void 0;
2852
+ }
2853
+ requireEntry(metadataTypeCode, code, version) {
2854
+ const entry = this.lookupEntry(metadataTypeCode, code, version);
2855
+ if (!entry) {
2856
+ this.logger.warn({
2857
+ event: RUNTIME_METADATA_EVENTS.LOOKUP_MISS,
2858
+ projectionType: metadataTypeCode,
2859
+ code,
2860
+ version: version ?? null
2861
+ });
2862
+ throw new MetadataLookupError(
2863
+ version !== void 0 ? `Metadata ${metadataTypeCode} code not found: ${code} version ${version}` : `Metadata ${metadataTypeCode} code not found: ${code}`,
2864
+ {
2865
+ metadata: {
2866
+ projectionType: metadataTypeCode,
2867
+ code,
2868
+ version
2869
+ }
2870
+ }
2871
+ );
2872
+ }
2873
+ return entry;
2874
+ }
2875
+ lookupEntry(metadataTypeCode, code, version) {
2876
+ const file = this.cache.getDomainFile(metadataTypeCode);
2877
+ const record = file?.records[code];
2878
+ if (!record) {
2879
+ return void 0;
2880
+ }
2881
+ const targetVersion = version !== void 0 ? version : record.latestVersion;
2882
+ return record.versions[String(targetVersion)];
2883
+ }
2884
+ requireManifest() {
2885
+ const manifest = this.cache.getManifest();
2886
+ if (!manifest) {
2887
+ throw new MetadataNotReadyError();
2888
+ }
2889
+ return manifest;
2890
+ }
2891
+ assertReady() {
2892
+ if (!this.cache.isReady()) {
2893
+ throw new MetadataNotReadyError();
2894
+ }
2895
+ }
2896
+ };
2897
+ var MetadataRefreshService = class {
2898
+ cache;
2899
+ downloader;
2900
+ loader;
2901
+ configuredRevision;
2902
+ logger;
2903
+ reloadDomainFiles;
2904
+ refreshStatus = REFRESH_STATUS.IDLE;
2905
+ lastRefreshError = null;
2906
+ refreshInFlight = null;
2907
+ periodicTimer = null;
2908
+ constructor(options) {
2909
+ this.cache = options.cache;
2910
+ this.downloader = options.downloader;
2911
+ this.loader = options.loader;
2912
+ this.configuredRevision = options.configuredRevision;
2913
+ this.reloadDomainFiles = options.reloadDomainFiles;
2914
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
2915
+ }
2916
+ getRefreshStatus() {
2917
+ return this.refreshStatus;
2918
+ }
2919
+ getLastRefreshError() {
2920
+ return this.lastRefreshError;
2921
+ }
2922
+ /**
2923
+ * Demand-driven bootstrap: current.json → manifest.json → atomic cache replace.
2924
+ * Domain projection files and common.json are not loaded here.
2925
+ */
2926
+ async initialize(revision) {
2927
+ const target = revision?.trim() || this.configuredRevision || await this.downloader.discoverLatestRevision();
2928
+ this.logger.info({
2929
+ event: RUNTIME_METADATA_EVENTS.INIT_START,
2930
+ revision: target
2931
+ });
2932
+ try {
2933
+ const bundle = await this.downloader.loadBootstrap(target);
2934
+ this.cache.replace(bundle);
2935
+ this.refreshStatus = REFRESH_STATUS.SUCCEEDED;
2936
+ this.lastRefreshError = null;
2937
+ const loadedTypes = Object.keys(bundle.manifest.metadataTypes).sort();
2938
+ const domainFileTypes = [...bundle.domainFiles.keys()].sort();
2939
+ this.logger.info({
2940
+ event: RUNTIME_METADATA_EVENTS.INIT_COMPLETE,
2941
+ revision: bundle.releaseId,
2942
+ contentHash: bundle.manifest.contentHash,
2943
+ loadedFiles: bundle.loadedFiles,
2944
+ mode: "bootstrap"
2945
+ });
2946
+ this.logger.info({
2947
+ event: RUNTIME_METADATA_EVENTS.RUNTIME_METADATA_INITIALIZED,
2948
+ releaseId: bundle.releaseId,
2949
+ loadedTypes,
2950
+ domainFileTypes,
2951
+ lookupIndexTypes: [
2952
+ ...new Set(
2953
+ Object.keys(bundle.manifest.lookupIndex).map(
2954
+ (key) => key.split(":")[0] ?? key
2955
+ )
2956
+ )
2957
+ ].sort(),
2958
+ hasMetric: loadedTypes.includes("MetricCode"),
2959
+ metadataTypesMetricEntry: bundle.manifest.metadataTypes["MetricCode"] ?? null
2960
+ });
2961
+ } catch (err) {
2962
+ this.refreshStatus = REFRESH_STATUS.FAILED;
2963
+ this.lastRefreshError = err instanceof Error ? err.message : String(err);
2964
+ this.logger.error({
2965
+ event: RUNTIME_METADATA_EVENTS.INIT_FAILED,
2966
+ err: err instanceof Error ? err : void 0,
2967
+ revision: target,
2968
+ message: this.lastRefreshError
2969
+ });
2970
+ throw err;
2971
+ }
2972
+ }
2973
+ /**
2974
+ * Event strategy: MetadataProjectionCompleted → reload via current.json → atomic swap.
2975
+ * `releaseId` is diagnostic; the pointer is the source of truth.
2976
+ * Returns true when the cache was updated.
2977
+ */
2978
+ async refreshFromEvent(releaseId) {
2979
+ return this.runRefresh(void 0, "event");
2980
+ }
2981
+ /**
2982
+ * Periodic strategy: re-read current.json; reload only if changed.
2983
+ */
2984
+ async checkAndRefresh(preferredRevision) {
2985
+ const current = this.cache.getManifest();
2986
+ const target = preferredRevision?.trim() || this.configuredRevision || await this.downloader.discoverLatestRevision();
2987
+ this.logger.info({
2988
+ event: RUNTIME_METADATA_EVENTS.PERIODIC_CHECK,
2989
+ revision: target,
2990
+ currentRevision: current?.revision ?? null
2991
+ });
2992
+ try {
2993
+ const nextManifest = await this.downloader.downloadManifest(target);
2994
+ const comparison = this.loader.compare(current, nextManifest);
2995
+ if (!comparison.changed) {
2996
+ this.logger.info({
2997
+ event: RUNTIME_METADATA_EVENTS.REFRESH_SKIPPED,
2998
+ reason: "unchanged",
2999
+ revision: target,
3000
+ contentHash: nextManifest.contentHash
3001
+ });
3002
+ return false;
3003
+ }
3004
+ return this.runRefresh(nextManifest.releaseId, "periodic", nextManifest);
3005
+ } catch (err) {
3006
+ this.refreshStatus = REFRESH_STATUS.FAILED;
3007
+ this.lastRefreshError = err instanceof Error ? err.message : String(err);
3008
+ if (this.cache.isReady()) {
3009
+ this.cache.setStatus(CACHE_STATUS.DEGRADED);
3010
+ }
3011
+ this.logger.error({
3012
+ event: RUNTIME_METADATA_EVENTS.REFRESH_FAILED,
3013
+ err: err instanceof Error ? err : void 0,
3014
+ revision: target,
3015
+ message: this.lastRefreshError,
3016
+ retainedCache: this.cache.isReady()
3017
+ });
3018
+ return false;
3019
+ }
3020
+ }
3021
+ startPeriodicCheck(intervalMs) {
3022
+ this.stopPeriodicCheck();
3023
+ if (intervalMs <= 0) {
3024
+ return;
3025
+ }
3026
+ this.periodicTimer = setInterval(() => {
3027
+ void this.checkAndRefresh();
3028
+ }, intervalMs);
3029
+ if (typeof this.periodicTimer.unref === "function") {
3030
+ this.periodicTimer.unref();
3031
+ }
3032
+ }
3033
+ stopPeriodicCheck() {
3034
+ if (this.periodicTimer) {
3035
+ clearInterval(this.periodicTimer);
3036
+ this.periodicTimer = null;
3037
+ }
3038
+ }
3039
+ async runRefresh(revision, reason, preloadedManifest) {
3040
+ if (this.refreshInFlight) {
3041
+ return this.refreshInFlight;
3042
+ }
3043
+ this.refreshInFlight = this.doRefresh(revision, reason, preloadedManifest);
3044
+ try {
3045
+ return await this.refreshInFlight;
3046
+ } finally {
3047
+ this.refreshInFlight = null;
3048
+ }
3049
+ }
3050
+ async doRefresh(revision, reason, preloadedManifest) {
3051
+ const previousStatus = this.cache.getStatus();
3052
+ this.refreshStatus = REFRESH_STATUS.IN_PROGRESS;
3053
+ if (this.cache.isReady()) {
3054
+ this.cache.setStatus(CACHE_STATUS.REFRESHING);
3055
+ }
3056
+ this.logger.info({
3057
+ event: RUNTIME_METADATA_EVENTS.REFRESH_START,
3058
+ revision: revision ?? "current",
3059
+ reason
3060
+ });
3061
+ try {
3062
+ const previousTypes = [
3063
+ ...this.cache.getSnapshot()?.domainFiles.keys() ?? []
3064
+ ];
3065
+ const previousReleaseId = this.cache.getSnapshot()?.releaseId ?? this.cache.getManifest()?.releaseId ?? null;
3066
+ const bundle = preloadedManifest ? await this.downloader.downloadBootstrapBundle(preloadedManifest) : await this.downloader.loadBootstrap(revision);
3067
+ if (this.reloadDomainFiles && previousTypes.length > 0) {
3068
+ const reloaded = await this.reloadDomainFiles(
3069
+ bundle.manifest,
3070
+ previousTypes
3071
+ );
3072
+ for (const [typeCode, file] of reloaded.domainFiles) {
3073
+ bundle.domainFiles.set(typeCode, file);
3074
+ }
3075
+ bundle.loadedFiles = [
3076
+ .../* @__PURE__ */ new Set([...bundle.loadedFiles, ...reloaded.loadedFiles])
3077
+ ].sort((a, b) => a.localeCompare(b));
3078
+ }
3079
+ this.cache.replace(bundle);
3080
+ this.refreshStatus = REFRESH_STATUS.SUCCEEDED;
3081
+ this.lastRefreshError = null;
3082
+ this.logger.info({
3083
+ event: RUNTIME_METADATA_EVENTS.REFRESH_COMPLETE,
3084
+ revision: bundle.releaseId,
3085
+ oldReleaseId: previousReleaseId,
3086
+ newReleaseId: bundle.releaseId,
3087
+ contentHash: bundle.manifest.contentHash,
3088
+ reason,
3089
+ mode: previousTypes.length > 0 ? "snapshot" : "bootstrap",
3090
+ retainedDomainTypes: previousTypes
3091
+ });
3092
+ return true;
3093
+ } catch (err) {
3094
+ this.refreshStatus = REFRESH_STATUS.FAILED;
3095
+ this.lastRefreshError = err instanceof Error ? err.message : String(err);
3096
+ if (this.cache.isReady()) {
3097
+ this.cache.setStatus(CACHE_STATUS.DEGRADED);
3098
+ } else if (previousStatus !== CACHE_STATUS.REFRESHING) {
3099
+ this.cache.setStatus(previousStatus);
3100
+ }
3101
+ this.logger.error({
3102
+ event: RUNTIME_METADATA_EVENTS.REFRESH_FAILED,
3103
+ err: err instanceof Error ? err : void 0,
3104
+ revision: revision ?? "current",
3105
+ reason,
3106
+ message: this.lastRefreshError,
3107
+ retainedCache: this.cache.isReady()
3108
+ });
3109
+ return false;
3110
+ }
3111
+ }
3112
+ };
3113
+
3114
+ // ../../libs/runtime-metadata/src/lib/health/MetadataHealthService.ts
3115
+ var MetadataHealthService = class {
3116
+ cache;
3117
+ getRefreshStatus;
3118
+ getLastRefreshError;
3119
+ constructor(options) {
3120
+ this.cache = options.cache;
3121
+ this.getRefreshStatus = options.getRefreshStatus;
3122
+ this.getLastRefreshError = options.getLastRefreshError;
3123
+ }
3124
+ getHealth() {
3125
+ const snapshot = this.cache.getSnapshot();
3126
+ const loadedAt = snapshot?.loadedAt ?? null;
3127
+ let cacheAgeMs = null;
3128
+ if (loadedAt) {
3129
+ const parsed = Date.parse(loadedAt);
3130
+ cacheAgeMs = Number.isFinite(parsed) ? Math.max(0, Date.now() - parsed) : null;
3131
+ }
3132
+ return {
3133
+ projectionVersion: snapshot?.projectionVersion ?? "unavailable",
3134
+ metadataRevision: snapshot?.releaseId ?? snapshot?.revision ?? "none",
3135
+ contentHash: snapshot?.contentHash ?? null,
3136
+ schemaVersion: snapshot?.schemaVersion ?? null,
3137
+ lastRefreshTime: loadedAt,
3138
+ loadedFiles: snapshot?.loadedFiles ?? [],
3139
+ cacheStatus: this.cache.getStatus(),
3140
+ refreshStatus: this.getRefreshStatus(),
3141
+ lastRefreshError: this.getLastRefreshError(),
3142
+ cacheAgeMs
3143
+ };
3144
+ }
3145
+ isHealthy() {
3146
+ const status = this.cache.getStatus();
3147
+ return this.cache.isReady() && (status === CACHE_STATUS.READY || status === CACHE_STATUS.DEGRADED || status === CACHE_STATUS.STALE || status === CACHE_STATUS.REFRESHING);
3148
+ }
3149
+ };
3150
+
3151
+ // ../../libs/runtime-metadata/src/lib/provider/MetadataProvider.ts
3152
+ function projectionEntryToMetadataValue(typeCode, valueCode, entry, locale) {
3153
+ return {
3154
+ typeCode,
3155
+ valueCode,
3156
+ localizedLabel: localizedLabelFromEntry(entry, locale),
3157
+ status: entry.status,
3158
+ version: entry.version,
3159
+ entry
3160
+ };
3161
+ }
3162
+ function localizedLabelFromEntry(entry, locale) {
3163
+ const labels = entry.localizedLabels ?? {};
3164
+ const requested = locale?.trim();
3165
+ if (requested) {
3166
+ const match = labels[requested]?.trim();
3167
+ if (match) {
3168
+ return match;
3169
+ }
3170
+ }
3171
+ const english = labels["en-US"]?.trim();
3172
+ if (english) {
3173
+ return english;
3174
+ }
3175
+ return entry.displayName || entry.label || entry.code;
3176
+ }
3177
+ function metadataValueToReference(value) {
3178
+ return { typeCode: value.typeCode, valueCode: value.valueCode };
3179
+ }
3180
+
3181
+ // ../../libs/runtime-metadata/src/lib/provider/ExtensionMetadataProvider.ts
3182
+ var DEFAULT_READY_TIMEOUT_MS = 5e3;
3183
+ var DEFAULT_REQUEST_TIMEOUT_MS = 2e3;
3184
+ var ExtensionMetadataProvider = class {
3185
+ baseUrl;
3186
+ readyTimeoutMs;
3187
+ requestTimeoutMs;
3188
+ logger;
3189
+ fetchImpl;
3190
+ constructor(options) {
3191
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
3192
+ this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
3193
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
3194
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
3195
+ this.fetchImpl = options.fetchImpl ?? fetch;
3196
+ }
3197
+ async isAvailable() {
3198
+ try {
3199
+ const status = await this.getStatus();
3200
+ return status.state === "READY" || status.state === "STALE" || status.state === "DEGRADED";
3201
+ } catch {
3202
+ return false;
3203
+ }
3204
+ }
3205
+ async waitUntilReady() {
3206
+ const deadline = Date.now() + this.readyTimeoutMs;
3207
+ let lastError;
3208
+ while (Date.now() < deadline) {
3209
+ try {
3210
+ const status = await this.getStatus();
3211
+ if (isServingState(status.state) && status.releaseId) {
3212
+ return status;
3213
+ }
3214
+ } catch (err) {
3215
+ lastError = err;
3216
+ }
3217
+ await sleep(50);
3218
+ }
3219
+ throw new MetadataProjectionUnavailableError(
3220
+ "Metadata extension did not become ready",
3221
+ {
3222
+ retryable: true,
3223
+ metadata: {
3224
+ lastError: lastError instanceof Error ? lastError.message : String(lastError ?? "")
3225
+ }
3226
+ }
3227
+ );
3228
+ }
3229
+ async getStatus() {
3230
+ const body = await this.requestJson(
3231
+ "GET",
3232
+ "/v1/status"
3233
+ );
3234
+ return {
3235
+ state: body.state ?? "UNKNOWN",
3236
+ releaseId: body.releaseId ?? null,
3237
+ loadedAt: body.loadedAt ?? null,
3238
+ lastRefreshAttemptAt: body.lastRefreshAttemptAt ?? null,
3239
+ lastSuccessfulRefreshAt: body.lastSuccessfulRefreshAt ?? null,
3240
+ cacheAgeMs: typeof body.cacheAgeMs === "number" ? body.cacheAgeMs : null,
3241
+ metadataTypes: body.metadataTypes
3242
+ };
3243
+ }
3244
+ async getValue(typeCode, valueCode, options) {
3245
+ const localeQuery = options?.locale ? `?locale=${encodeURIComponent(options.locale)}` : "";
3246
+ const path = `/v1/metadata/${encodeURIComponent(typeCode)}/${encodeURIComponent(valueCode)}${localeQuery}`;
3247
+ try {
3248
+ const item = await this.requestJson("GET", path);
3249
+ return this.toMetadataValue(item, options?.locale);
3250
+ } catch (err) {
3251
+ if (isNotFound(err)) {
3252
+ return null;
3253
+ }
3254
+ throw err;
3255
+ }
3256
+ }
3257
+ async batchGet(references, options) {
3258
+ const invalidReferences = [];
3259
+ const valid = [];
3260
+ const seen = /* @__PURE__ */ new Set();
3261
+ for (const raw of references) {
3262
+ const parsed = tryParseMetadataReference(raw);
3263
+ if (!parsed) {
3264
+ if (typeof raw === "string" && raw.trim()) {
3265
+ invalidReferences.push(raw);
3266
+ }
3267
+ continue;
3268
+ }
3269
+ const compact = formatMetadataReference(parsed.typeCode, parsed.valueCode);
3270
+ if (seen.has(compact)) {
3271
+ continue;
3272
+ }
3273
+ seen.add(compact);
3274
+ valid.push(compact);
3275
+ }
3276
+ if (valid.length === 0) {
3277
+ return {
3278
+ releaseId: null,
3279
+ items: {},
3280
+ invalidReferences,
3281
+ unavailable: false
3282
+ };
3283
+ }
3284
+ try {
3285
+ const body = await this.requestJson(
3286
+ "POST",
3287
+ "/v1/metadata/batch",
3288
+ {
3289
+ references: valid,
3290
+ locale: options?.locale
3291
+ }
3292
+ );
3293
+ const items = {};
3294
+ for (const [key, item] of Object.entries(body.items ?? {})) {
3295
+ const value = this.toMetadataValue(item, options?.locale);
3296
+ if (value) {
3297
+ items[key] = value;
3298
+ }
3299
+ }
3300
+ return {
3301
+ releaseId: body.releaseId ?? null,
3302
+ items,
3303
+ invalidReferences,
3304
+ unavailable: false
3305
+ };
3306
+ } catch (err) {
3307
+ if (isUnavailable(err)) {
3308
+ return {
3309
+ releaseId: null,
3310
+ items: {},
3311
+ invalidReferences,
3312
+ unavailable: true
3313
+ };
3314
+ }
3315
+ throw err;
3316
+ }
3317
+ }
3318
+ async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
3319
+ const localeQuery = options?.locale ? `?locale=${encodeURIComponent(options.locale)}` : "";
3320
+ const path = `/v1/related/${encodeURIComponent(sourceTypeCode)}/${encodeURIComponent(sourceValueCode)}/${encodeURIComponent(targetTypeCode)}${localeQuery}`;
3321
+ try {
3322
+ const body = await this.requestJson(
3323
+ "GET",
3324
+ path
3325
+ );
3326
+ return (body.items ?? []).map((item) => this.toMetadataValue(item, options?.locale)).filter((item) => item != null);
3327
+ } catch (err) {
3328
+ if (isNotFound(err)) {
3329
+ return [];
3330
+ }
3331
+ throw err;
3332
+ }
3333
+ }
3334
+ async getLocalizationValue(keyOrTypeCode, valueCodeOrLocale, maybeLocale) {
3335
+ let key;
3336
+ let locale;
3337
+ if (keyOrTypeCode.includes(".")) {
3338
+ key = keyOrTypeCode;
3339
+ locale = valueCodeOrLocale;
3340
+ } else if (valueCodeOrLocale) {
3341
+ key = `${keyOrTypeCode}.${valueCodeOrLocale}`;
3342
+ locale = maybeLocale;
3343
+ } else {
3344
+ return void 0;
3345
+ }
3346
+ const query = locale ? `?locale=${encodeURIComponent(locale)}` : "";
3347
+ const path = `/v1/localization/${encodeURIComponent(locale ?? "default")}/${encodeURIComponent(key)}${query}`;
3348
+ try {
3349
+ const body = await this.requestJson("GET", path);
3350
+ return body.value;
3351
+ } catch {
3352
+ return void 0;
3353
+ }
3354
+ }
3355
+ async getLocalizationMap(locale) {
3356
+ const path = `/v1/localization/${encodeURIComponent(locale)}`;
3357
+ try {
3358
+ const body = await this.requestJson("GET", path);
3359
+ return body.items;
3360
+ } catch {
3361
+ return void 0;
3362
+ }
3363
+ }
3364
+ async requestRefresh(releaseId) {
3365
+ const body = await this.requestJson(
3366
+ "POST",
3367
+ "/v1/refresh",
3368
+ { releaseId }
3369
+ );
3370
+ return body.changed === true;
3371
+ }
3372
+ toMetadataValue(item, locale) {
3373
+ if (!item?.typeCode || !item.valueCode) {
3374
+ return null;
3375
+ }
3376
+ if (item.entry) {
3377
+ return projectionEntryToMetadataValue(
3378
+ item.typeCode,
3379
+ item.valueCode,
3380
+ item.entry,
3381
+ locale
3382
+ );
3383
+ }
3384
+ return {
3385
+ typeCode: item.typeCode,
3386
+ valueCode: item.valueCode,
3387
+ localizedLabel: item.localizedLabel,
3388
+ status: item.status,
3389
+ version: item.version,
3390
+ entry: {
3391
+ code: item.valueCode,
3392
+ displayName: item.localizedLabel,
3393
+ label: item.localizedLabel,
3394
+ status: item.status,
3395
+ version: item.version,
3396
+ sortOrder: 0,
3397
+ isGlobal: true,
3398
+ attributes: {},
3399
+ applicability: {
3400
+ module: [],
3401
+ category: [],
3402
+ condition: [],
3403
+ country: []
3404
+ }
3405
+ }
3406
+ };
3407
+ }
3408
+ async requestJson(method, path, payload) {
3409
+ const controller = new AbortController();
3410
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
3411
+ try {
3412
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
3413
+ method,
3414
+ headers: {
3415
+ accept: "application/json",
3416
+ ...payload !== void 0 ? { "content-type": "application/json" } : {}
3417
+ },
3418
+ body: payload !== void 0 ? JSON.stringify(payload) : void 0,
3419
+ signal: controller.signal
3420
+ });
3421
+ const text = await response.text();
3422
+ let parsed = {};
3423
+ if (text) {
3424
+ try {
3425
+ parsed = JSON.parse(text);
3426
+ } catch {
3427
+ parsed = { message: text };
3428
+ }
3429
+ }
3430
+ if (!response.ok) {
3431
+ const errorBody = parsed;
3432
+ const code = errorBody.code ?? `HTTP_${response.status}`;
3433
+ if (response.status === 404) {
3434
+ const err = new Error(errorBody.message ?? "not found");
3435
+ err.code = "RUNTIME_METADATA_NOT_FOUND";
3436
+ throw err;
3437
+ }
3438
+ if (response.status === 503 || code === "METADATA_PROJECTION_UNAVAILABLE") {
3439
+ throw new MetadataProjectionUnavailableError(
3440
+ errorBody.message ?? "Metadata projection is unavailable",
3441
+ { retryable: true, metadata: { code, path } }
3442
+ );
3443
+ }
3444
+ throw new MetadataProjectionUnavailableError(
3445
+ errorBody.message ?? `Extension request failed: ${response.status}`,
3446
+ { retryable: response.status >= 500, metadata: { code, path } }
3447
+ );
3448
+ }
3449
+ return parsed;
3450
+ } catch (err) {
3451
+ if (err instanceof MetadataProjectionUnavailableError) {
3452
+ throw err;
3453
+ }
3454
+ if (err.code === "RUNTIME_METADATA_NOT_FOUND") {
3455
+ throw err;
3456
+ }
3457
+ const aborted = err.name === "AbortError";
3458
+ this.logger.warn({
3459
+ event: "runtimeMetadata.extension.requestFailed",
3460
+ path,
3461
+ aborted,
3462
+ message: err instanceof Error ? err.message : String(err)
3463
+ });
3464
+ throw new MetadataProjectionUnavailableError(
3465
+ aborted ? "Metadata extension request timed out" : "Metadata extension is unavailable",
3466
+ { retryable: true, metadata: { path } }
3467
+ );
3468
+ } finally {
3469
+ clearTimeout(timer);
3470
+ }
3471
+ }
3472
+ };
3473
+ function isNotFound(err) {
3474
+ return err.code === "RUNTIME_METADATA_NOT_FOUND";
3475
+ }
3476
+ function isUnavailable(err) {
3477
+ return err instanceof MetadataProjectionUnavailableError;
3478
+ }
3479
+ function isServingState(state) {
3480
+ return state === "READY" || state === "STALE" || state === "DEGRADED";
3481
+ }
3482
+ function sleep(ms) {
3483
+ return new Promise((resolve) => setTimeout(resolve, ms));
3484
+ }
3485
+ function defaultExtensionBaseUrl(port = 12701) {
3486
+ return `http://127.0.0.1:${port}`;
3487
+ }
3488
+
3489
+ // ../../libs/runtime-metadata/src/lib/provider/selectMetadataProvider.ts
3490
+ var METADATA_PROVIDER_KIND = {
3491
+ EXTENSION: "extension",
3492
+ S3: "s3",
3493
+ MEMORY: "memory"
3494
+ };
3495
+ function selectMetadataProvider(input) {
3496
+ const env = input.env ?? process.env;
3497
+ if (input.extensionProvider) {
3498
+ return {
3499
+ kind: METADATA_PROVIDER_KIND.EXTENSION,
3500
+ provider: input.extensionProvider,
3501
+ fallback: input.s3Provider
3502
+ };
3503
+ }
3504
+ const extensionEnabled = isExtensionEnabled(env);
3505
+ if (extensionEnabled) {
3506
+ const port = Number(env.METADATA_EXTENSION_PORT ?? "12701");
3507
+ const baseUrl = (env.METADATA_EXTENSION_BASE_URL ?? defaultExtensionBaseUrl(port)).trim();
3508
+ const extension = new ExtensionMetadataProvider({
3509
+ baseUrl,
3510
+ logger: input.logger,
3511
+ fetchImpl: input.extensionFetch,
3512
+ readyTimeoutMs: env.METADATA_EXTENSION_READY_TIMEOUT_MS ? Number(env.METADATA_EXTENSION_READY_TIMEOUT_MS) : void 0
3513
+ });
3514
+ const fallbackEnabled = (env.METADATA_EXTENSION_FALLBACK ?? "s3") !== "none";
3515
+ return {
3516
+ kind: METADATA_PROVIDER_KIND.EXTENSION,
3517
+ provider: extension,
3518
+ fallback: fallbackEnabled ? input.s3Provider : void 0
3519
+ };
3520
+ }
3521
+ if (input.s3Provider) {
3522
+ return {
3523
+ kind: METADATA_PROVIDER_KIND.S3,
3524
+ provider: input.s3Provider,
3525
+ fallback: void 0
3526
+ };
3527
+ }
3528
+ return null;
3529
+ }
3530
+ function isExtensionEnabled(env = process.env) {
3531
+ const flag = env.METADATA_EXTENSION_ENABLED?.trim().toLowerCase();
3532
+ if (flag === "false" || flag === "0") {
3533
+ return false;
3534
+ }
3535
+ if (flag === "true" || flag === "1") {
3536
+ return true;
3537
+ }
3538
+ return Boolean(env.METADATA_EXTENSION_BASE_URL?.trim());
3539
+ }
3540
+ function isMetadataProjectionConfigured(env = process.env) {
3541
+ if (isExtensionEnabled(env)) {
3542
+ return true;
3543
+ }
3544
+ return isMetadataProjectionsBucketConfigured(env);
3545
+ }
3546
+
3547
+ // ../../libs/runtime-metadata/src/lib/provider/ProviderFailoverCoordinator.ts
3548
+ var PROVIDER_TRANSPORT_STATE = {
3549
+ EXTENSION_READY: "EXTENSION_READY",
3550
+ EXTENSION_UNAVAILABLE: "EXTENSION_UNAVAILABLE"
3551
+ };
3552
+ var SERVING_STATES = /* @__PURE__ */ new Set(["READY", "STALE", "DEGRADED"]);
3553
+ var DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS = 2e3;
3554
+ var ProviderFailoverCoordinator = class {
3555
+ state;
3556
+ recoveryInFlight = null;
3557
+ fallbackActivateInFlight = null;
3558
+ lastProbeAt = 0;
3559
+ healthCheckCount = 0;
3560
+ extension;
3561
+ fallback;
3562
+ kind;
3563
+ logger;
3564
+ recoveryCooldownMs;
3565
+ now;
3566
+ onFallbackActivated;
3567
+ onRecovered;
3568
+ constructor(options) {
3569
+ this.extension = options.extension;
3570
+ this.fallback = options.fallback;
3571
+ this.kind = options.kind;
3572
+ this.logger = options.logger;
3573
+ this.recoveryCooldownMs = options.recoveryCooldownMs ?? DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS;
3574
+ this.now = options.now ?? Date.now;
3575
+ this.onFallbackActivated = options.onFallbackActivated;
3576
+ this.onRecovered = options.onRecovered;
3577
+ this.state = options.kind === METADATA_PROVIDER_KIND.EXTENSION ? PROVIDER_TRANSPORT_STATE.EXTENSION_READY : PROVIDER_TRANSPORT_STATE.EXTENSION_UNAVAILABLE;
3578
+ }
3579
+ getState() {
3580
+ return this.state;
3581
+ }
3582
+ getActiveKind() {
3583
+ if (this.usesExtension()) {
3584
+ return METADATA_PROVIDER_KIND.EXTENSION;
3585
+ }
3586
+ return this.fallback ? METADATA_PROVIDER_KIND.S3 : this.kind;
3587
+ }
3588
+ usesExtension() {
3589
+ return this.kind === METADATA_PROVIDER_KIND.EXTENSION && this.state === PROVIDER_TRANSPORT_STATE.EXTENSION_READY;
3590
+ }
3591
+ getHealthCheckCount() {
3592
+ return this.healthCheckCount;
3593
+ }
3594
+ /**
3595
+ * Returns the current provider without probing. Warm extension path:
3596
+ * zero localhost health checks.
3597
+ */
3598
+ peekProvider() {
3599
+ if (this.usesExtension()) {
3600
+ return this.extension;
3601
+ }
3602
+ return this.fallback ?? this.extension;
3603
+ }
3604
+ /**
3605
+ * When serving from S3 fallback, opportunistically recover if the cooldown
3606
+ * has elapsed. Concurrent callers share one in-flight probe.
3607
+ */
3608
+ async activeProvider() {
3609
+ if (this.usesExtension()) {
3610
+ return this.extension;
3611
+ }
3612
+ if (this.kind === METADATA_PROVIDER_KIND.EXTENSION && this.fallback) {
3613
+ await this.maybeRecover();
3614
+ if (this.usesExtension()) {
3615
+ return this.extension;
3616
+ }
3617
+ return this.fallback;
3618
+ }
3619
+ return this.fallback ?? this.extension;
3620
+ }
3621
+ async activateFallback(reason) {
3622
+ if (this.kind !== METADATA_PROVIDER_KIND.EXTENSION || !this.fallback) {
3623
+ return;
3624
+ }
3625
+ if (this.state === PROVIDER_TRANSPORT_STATE.EXTENSION_UNAVAILABLE) {
3626
+ return;
3627
+ }
3628
+ if (this.fallbackActivateInFlight) {
3629
+ await this.fallbackActivateInFlight;
3630
+ return;
3631
+ }
3632
+ this.fallbackActivateInFlight = this.doActivateFallback(reason).finally(
3633
+ () => {
3634
+ this.fallbackActivateInFlight = null;
3635
+ }
3636
+ );
3637
+ await this.fallbackActivateInFlight;
3638
+ }
3639
+ async maybeRecover() {
3640
+ if (this.kind !== METADATA_PROVIDER_KIND.EXTENSION || !this.fallback) {
3641
+ return false;
3642
+ }
3643
+ if (this.state === PROVIDER_TRANSPORT_STATE.EXTENSION_READY) {
3644
+ return true;
3645
+ }
3646
+ if (this.recoveryInFlight) {
3647
+ return this.recoveryInFlight;
3648
+ }
3649
+ if (this.now() - this.lastProbeAt < this.recoveryCooldownMs) {
3650
+ return false;
3651
+ }
3652
+ this.recoveryInFlight = this.probeExtension().finally(() => {
3653
+ this.recoveryInFlight = null;
3654
+ });
3655
+ return this.recoveryInFlight;
3656
+ }
3657
+ async doActivateFallback(reason) {
3658
+ if (this.state === PROVIDER_TRANSPORT_STATE.EXTENSION_UNAVAILABLE) {
3659
+ return;
3660
+ }
3661
+ this.state = PROVIDER_TRANSPORT_STATE.EXTENSION_UNAVAILABLE;
3662
+ this.lastProbeAt = this.now();
3663
+ this.logger.warn({
3664
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
3665
+ reason,
3666
+ fallback: METADATA_PROVIDER_KIND.S3,
3667
+ recoverable: true
3668
+ });
3669
+ await this.onFallbackActivated?.(reason);
3670
+ }
3671
+ async probeExtension() {
3672
+ this.lastProbeAt = this.now();
3673
+ this.healthCheckCount += 1;
3674
+ try {
3675
+ const status = await this.extension.getStatus();
3676
+ if (isExtensionServing(status)) {
3677
+ this.state = PROVIDER_TRANSPORT_STATE.EXTENSION_READY;
3678
+ this.logger.info({
3679
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_RECOVERED,
3680
+ releaseId: status.releaseId,
3681
+ extensionState: status.state
3682
+ });
3683
+ await this.onRecovered?.(status);
3684
+ return true;
3685
+ }
3686
+ } catch {
3687
+ }
3688
+ return false;
3689
+ }
3690
+ };
3691
+ function isExtensionServing(status) {
3692
+ return SERVING_STATES.has(status.state) && Boolean(status.releaseId);
3693
+ }
3694
+ var S3MetadataProvider = class {
3695
+ cache;
3696
+ resolver;
3697
+ ensureTypesLoaded;
3698
+ logger;
3699
+ constructor(options) {
3700
+ this.cache = options.cache;
3701
+ this.resolver = options.resolver;
3702
+ this.ensureTypesLoaded = options.ensureTypesLoaded;
3703
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
3704
+ void options.downloader;
3705
+ }
3706
+ async isAvailable() {
3707
+ return this.cache.isReady();
3708
+ }
3709
+ async getStatus() {
3710
+ const snapshot = this.cache.getSnapshot();
3711
+ const loadedAt = snapshot?.loadedAt ?? null;
3712
+ let cacheAgeMs = null;
3713
+ if (loadedAt) {
3714
+ const parsed = Date.parse(loadedAt);
3715
+ cacheAgeMs = Number.isFinite(parsed) ? Math.max(0, Date.now() - parsed) : null;
3716
+ }
3717
+ return {
3718
+ state: this.cache.getStatus(),
3719
+ releaseId: this.cache.getReleaseId(),
3720
+ loadedAt,
3721
+ lastRefreshAttemptAt: null,
3722
+ lastSuccessfulRefreshAt: loadedAt,
3723
+ cacheAgeMs,
3724
+ metadataTypes: snapshot ? Object.keys(snapshot.manifest.metadataTypes).sort() : []
3725
+ };
3726
+ }
3727
+ async getValue(typeCode, valueCode, options) {
3728
+ await this.ensureTypesLoaded([typeCode]);
3729
+ try {
3730
+ const entry = this.resolver.resolve(typeCode, valueCode, options?.version);
3731
+ return projectionEntryToMetadataValue(
3732
+ typeCode,
3733
+ valueCode,
3734
+ entry,
3735
+ options?.locale
3736
+ );
3737
+ } catch (err) {
3738
+ if (err instanceof MetadataLookupError) {
3739
+ return null;
3740
+ }
3741
+ throw err;
3742
+ }
3743
+ }
3744
+ async batchGet(references, options) {
3745
+ const invalidReferences = [];
3746
+ const parsedRefs = [];
3747
+ const seen = /* @__PURE__ */ new Set();
3748
+ const typeCodes = /* @__PURE__ */ new Set();
3749
+ for (const raw of references) {
3750
+ const parsed = tryParseMetadataReference(raw);
3751
+ if (!parsed) {
3752
+ if (typeof raw === "string" && raw.trim()) {
3753
+ invalidReferences.push(raw);
3754
+ }
3755
+ continue;
3756
+ }
3757
+ const key = formatMetadataReference(parsed.typeCode, parsed.valueCode);
3758
+ if (seen.has(key)) {
3759
+ continue;
3760
+ }
3761
+ seen.add(key);
3762
+ parsedRefs.push({ key, ...parsed });
3763
+ typeCodes.add(parsed.typeCode);
3764
+ }
3765
+ if (!this.cache.isReady() && typeCodes.size === 0) {
3766
+ return {
3767
+ releaseId: this.cache.getReleaseId(),
3768
+ items: {},
3769
+ invalidReferences,
3770
+ unavailable: false
3771
+ };
3772
+ }
3773
+ await this.ensureTypesLoaded([...typeCodes]);
3774
+ const items = {};
3775
+ for (const ref of parsedRefs) {
3776
+ const value = await this.getValue(ref.typeCode, ref.valueCode, options);
3777
+ if (value) {
3778
+ items[ref.key] = value;
3779
+ }
3780
+ }
3781
+ return {
3782
+ releaseId: this.cache.getReleaseId(),
3783
+ items,
3784
+ invalidReferences,
3785
+ unavailable: !this.cache.isReady() && parsedRefs.length > 0
3786
+ };
3787
+ }
3788
+ async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
3789
+ await this.ensureTypesLoaded([sourceTypeCode, targetTypeCode]);
3790
+ const index = this.cache.getRelationshipIndex();
3791
+ const codes = relatedValueCodes(
3792
+ index,
3793
+ sourceTypeCode,
3794
+ sourceValueCode,
3795
+ targetTypeCode
3796
+ );
3797
+ if (codes.length === 0) {
3798
+ const fallback = relatedValueCodesFromEntry(
3799
+ this.resolver,
3800
+ sourceTypeCode,
3801
+ sourceValueCode,
3802
+ targetTypeCode
3803
+ );
3804
+ codes.push(...fallback);
3805
+ }
3806
+ const values = [];
3807
+ for (const valueCode of codes) {
3808
+ const value = await this.getValue(targetTypeCode, valueCode, options);
3809
+ if (value) {
3810
+ values.push(value);
3811
+ }
3812
+ }
3813
+ this.logger.info({
3814
+ event: "runtimeMetadata.related.lookup",
3815
+ sourceTypeCode,
3816
+ sourceValueCode,
3817
+ targetTypeCode,
3818
+ count: values.length
3819
+ });
3820
+ return values;
3821
+ }
3822
+ };
3823
+ function relatedValueCodes(index, sourceTypeCode, sourceValueCode, targetTypeCode) {
3824
+ if (!index) {
3825
+ return [];
3826
+ }
3827
+ const key = lookupIndexKey(sourceTypeCode, sourceValueCode);
3828
+ const values = index[key]?.[targetTypeCode];
3829
+ return values ? [...values] : [];
3830
+ }
3831
+ function relatedValueCodesFromEntry(resolver, sourceTypeCode, sourceValueCode, targetTypeCode) {
3832
+ try {
3833
+ const entry = resolver.resolve(sourceTypeCode, sourceValueCode);
3834
+ return (entry.relationships ?? []).filter((rel) => rel.targetMetadataTypeCode === targetTypeCode).map((rel) => rel.targetValueCode);
3835
+ } catch {
3836
+ return [];
3837
+ }
3838
+ }
3839
+
3840
+ // ../../libs/runtime-metadata/src/lib/services/RuntimeMetadataService.ts
3841
+ var RuntimeMetadataService = class {
3842
+ cache;
3843
+ loader;
3844
+ downloader;
3845
+ resolver;
3846
+ refreshService;
3847
+ healthService;
3848
+ config;
3849
+ logger;
3850
+ /** Coalesce concurrent cold bootstrap (current.json + manifest.json). */
3851
+ initializeInFlight = null;
3852
+ /**
3853
+ * In-flight selective downloads keyed by MetadataTypeCode.
3854
+ * Concurrent requests (and overlapping type sets) share one download per type
3855
+ * for the lifetime of the Lambda execution context.
3856
+ */
3857
+ domainLoadInFlight = /* @__PURE__ */ new Map();
3858
+ /**
3859
+ * Types soft-skipped for the current release (no manifest integrity entry).
3860
+ * Prevents ensureProjectionTypesLoaded from retrying unsupported types forever.
3861
+ */
3862
+ unsupportedProjectionTypes = /* @__PURE__ */ new Set();
3863
+ unsupportedProjectionReleaseId = null;
3864
+ metadataProvider;
3865
+ metadataProviderKind;
3866
+ metadataProviderFallback;
3867
+ providerCoordinator;
3868
+ constructor(options) {
3869
+ this.config = resolveRuntimeMetadataConfig(options.config);
3870
+ this.logger = options.logger ?? createLogger({ serviceName: "runtime-metadata" });
3871
+ this.cache = options.cache ?? new MetadataCache();
3872
+ this.loader = options.loader ?? new MetadataLoader({
3873
+ expectedSchemaVersion: this.config.expectedSchemaVersion,
3874
+ expectedProjectionVersion: this.config.expectedProjectionVersion,
3875
+ logger: this.logger
3876
+ });
3877
+ this.downloader = options.downloader ?? new MetadataDownloader({
3878
+ client: options.client,
3879
+ bucket: this.config.bucket,
3880
+ prefix: this.config.prefix,
3881
+ environment: this.config.environment,
3882
+ expectedSchemaVersion: this.config.expectedSchemaVersion,
3883
+ expectedProjectionVersion: this.config.expectedProjectionVersion,
3884
+ logger: this.logger,
3885
+ loader: this.loader
3886
+ });
3887
+ this.resolver = options.resolver ?? new MetadataResolver({ cache: this.cache, logger: this.logger });
3888
+ this.refreshService = options.refreshService ?? new MetadataRefreshService({
3889
+ cache: this.cache,
3890
+ downloader: this.downloader,
3891
+ loader: this.loader,
3892
+ configuredRevision: this.config.revision,
3893
+ logger: this.logger,
3894
+ reloadDomainFiles: (manifest, typeCodes) => this.downloader.downloadDomainProjections(manifest, typeCodes)
3895
+ });
3896
+ this.healthService = options.healthService ?? new MetadataHealthService({
3897
+ cache: this.cache,
3898
+ getRefreshStatus: () => this.refreshService.getRefreshStatus(),
3899
+ getLastRefreshError: () => this.refreshService.getLastRefreshError(),
3900
+ logger: this.logger
3901
+ });
3902
+ const s3Provider = new S3MetadataProvider({
3903
+ cache: this.cache,
3904
+ resolver: this.resolver,
3905
+ downloader: this.downloader,
3906
+ ensureTypesLoaded: (typeCodes) => this.ensureProjectionTypesLoaded(typeCodes),
3907
+ logger: this.logger
3908
+ });
3909
+ const selected = selectMetadataProvider({
3910
+ env: options.env,
3911
+ logger: this.logger,
3912
+ extensionProvider: options.metadataProvider,
3913
+ s3Provider: options.metadataProviderFallback ?? s3Provider
3914
+ });
3915
+ this.metadataProvider = selected?.provider ?? s3Provider;
3916
+ this.metadataProviderKind = selected?.kind ?? METADATA_PROVIDER_KIND.S3;
3917
+ this.metadataProviderFallback = selected?.fallback;
3918
+ this.providerCoordinator = new ProviderFailoverCoordinator({
3919
+ extension: this.metadataProvider,
3920
+ fallback: this.metadataProviderFallback,
3921
+ kind: this.metadataProviderKind,
3922
+ logger: this.logger,
3923
+ recoveryCooldownMs: recoveryCooldownMs(options.env),
3924
+ onFallbackActivated: async () => {
3925
+ this.cache.clear();
3926
+ this.startS3PeriodicCheck();
3927
+ },
3928
+ onRecovered: async (status) => {
3929
+ this.refreshService.stopPeriodicCheck();
3930
+ this.installExtensionManifest(
3931
+ status.releaseId ?? "",
3932
+ status.metadataTypes ?? [],
3933
+ { forceReset: true }
3934
+ );
3935
+ }
3936
+ });
3937
+ this.logger.info({
3938
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_SELECTED,
3939
+ kind: this.metadataProviderKind,
3940
+ hasFallback: Boolean(this.metadataProviderFallback)
3941
+ });
3942
+ }
3943
+ /**
3944
+ * Load current.json + manifest.json into cache (no domain projections, no common.json).
3945
+ * Called on demand when a response needs metadata — not from beforeHandler.
3946
+ * Concurrent callers share one in-flight initialize.
3947
+ */
3948
+ async initialize(revision) {
3949
+ if (this.cache.isReady() && !revision?.trim()) {
3950
+ return;
3951
+ }
3952
+ this.initializeInFlight ??= this.initializeInternal(revision).finally(() => {
3953
+ this.initializeInFlight = null;
3954
+ });
3955
+ await this.initializeInFlight;
3956
+ }
3957
+ async initializeInternal(revision) {
3958
+ if (this.usesExtensionTransport()) {
3959
+ const ready = await this.initializeFromExtension();
3960
+ if (ready) {
3961
+ return;
3962
+ }
3963
+ await this.providerCoordinator.activateFallback("extension-init");
3964
+ }
3965
+ await this.refreshService.initialize(revision ?? this.config.revision);
3966
+ this.startS3PeriodicCheck();
3967
+ }
3968
+ /**
3969
+ * Handle MetadataProjectionCompleted — reload bootstrap via current.json.
3970
+ *
3971
+ * This refreshes the current execution environment only. It cannot fan-out
3972
+ * to every warm Lambda. Warm environments learn about new releases via the
3973
+ * extension INVOKE hook, extension polling, or this method when this
3974
+ * environment is the one that handled the event.
3975
+ */
3976
+ async onProjectionCompleted(releaseId) {
3977
+ if (this.usesExtensionTransport()) {
3978
+ try {
3979
+ const changed = await this.refreshViaExtension(releaseId);
3980
+ return changed;
3981
+ } catch (err) {
3982
+ this.logger.warn({
3983
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
3984
+ reason: "extension-refresh-failed",
3985
+ message: err instanceof Error ? err.message : String(err)
3986
+ });
3987
+ await this.providerCoordinator.activateFallback("extension-refresh");
3988
+ }
3989
+ }
3990
+ return this.refreshService.refreshFromEvent(releaseId);
3991
+ }
3992
+ /** Periodic / manual current.json check + conditional snapshot reload. */
3993
+ async checkForUpdates(revision) {
3994
+ if (this.usesExtensionTransport()) {
3995
+ try {
3996
+ return await this.refreshViaExtension(revision);
3997
+ } catch (err) {
3998
+ this.logger.warn({
3999
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
4000
+ reason: "extension-check-failed",
4001
+ message: err instanceof Error ? err.message : String(err)
4002
+ });
4003
+ await this.providerCoordinator.activateFallback("extension-check");
4004
+ }
4005
+ }
4006
+ return this.refreshService.checkAndRefresh(revision);
4007
+ }
4008
+ stop() {
4009
+ this.refreshService.stopPeriodicCheck();
4010
+ }
4011
+ /**
4012
+ * Demand-driven selective load:
4013
+ * 1. Collect unique typeCodes from the response (zero S3 when none)
4014
+ * 2. Ensure release bootstrap (current + manifest) only if needed
4015
+ * 3. Download missing `{typeCode}.json` in parallel into MetadataCache
4016
+ *
4017
+ * {@link MetadataResolver} resolves valueCodes from cache only.
4018
+ */
4019
+ /**
4020
+ * Demand-driven selective load:
4021
+ * 1. Collect unique typeCodes from the response (zero S3 when none)
4022
+ * 2. Ensure release bootstrap (current + manifest) only if needed
4023
+ * 3. Download missing `{typeCode}.json` in parallel into MetadataCache
4024
+ *
4025
+ * {@link MetadataResolver} resolves valueCodes from cache only.
4026
+ */
4027
+ async ensureProjectionsForResponse(response) {
4028
+ const potential = hasPotentialMetadata(response);
4029
+ if (!potential) {
4030
+ this.logger.info({
4031
+ event: "metadata-enrichment.trace.typeDetection.completed",
4032
+ stage: "ensureProjectionsForResponse",
4033
+ hasPotentialMetadata: false,
4034
+ referencesFound: 0,
4035
+ typeCodesFound: []
4036
+ });
4037
+ return;
4038
+ }
4039
+ if (!this.cache.isReady()) {
4040
+ await this.initialize();
4041
+ }
4042
+ const knownTypes = this.cache.isReady() ? this.listMetadataTypes() : void 0;
4043
+ const diagnostics = {
4044
+ candidateFields: [],
4045
+ totalCandidatesDiscovered: 0,
4046
+ totalUniqueTypesDiscovered: 0,
4047
+ totalUniqueTypeValuesDiscovered: 0
4048
+ };
4049
+ const references = collectResponseReferences(response, { knownTypes, diagnostics });
4050
+ const typeCodes = collectResponseTypeCodes(response, { knownTypes, diagnostics });
4051
+ this.logger.info({
4052
+ event: "metadata-enrichment.trace.typeDetection.completed",
4053
+ stage: "ensureProjectionsForResponse",
4054
+ hasPotentialMetadata: true,
4055
+ totalCandidatesDiscovered: diagnostics.totalCandidatesDiscovered,
4056
+ totalUniqueTypesDiscovered: diagnostics.totalUniqueTypesDiscovered,
4057
+ totalUniqueTypeValuesDiscovered: diagnostics.totalUniqueTypeValuesDiscovered,
4058
+ referencesFound: references.length,
4059
+ typeCodesFound: typeCodes,
4060
+ sampleCandidates: diagnostics.candidateFields.slice(0, 15),
4061
+ knownTypesAvailable: knownTypes ? knownTypes.length : 0
4062
+ });
4063
+ if (references.length === 0) {
4064
+ return;
4065
+ }
4066
+ if (this.usesExtensionTransport()) {
4067
+ const compact = references.map(
4068
+ (ref) => formatMetadataReference(ref.typeCode, ref.valueCode)
4069
+ );
4070
+ const batch = await this.batchGet(compact);
4071
+ if (batch.unavailable) {
4072
+ await this.providerCoordinator.activateFallback("extension-lookup");
4073
+ await this.ensureProjectionTypesLoaded(
4074
+ collectResponseTypeCodes(response, { knownTypes })
4075
+ );
4076
+ return;
4077
+ }
4078
+ return;
4079
+ }
4080
+ await this.ensureProjectionTypesLoaded(typeCodes);
4081
+ }
4082
+ /**
4083
+ * Ensure domain projection files for the given MetadataTypeCodes are present in cache.
4084
+ * Filenames are `{MetadataTypeCode}.json` — not discovered from the manifest.
4085
+ *
4086
+ * Warm path: when every requested type is already in {@link MetadataCache}, this
4087
+ * returns immediately with **zero** S3 calls.
4088
+ */
4089
+ async ensureProjectionTypesLoaded(metadataTypeCodes) {
4090
+ if (metadataTypeCodes.length === 0) {
4091
+ return;
4092
+ }
4093
+ if (!this.cache.isReady()) {
4094
+ await this.initialize();
4095
+ }
4096
+ const startLoadTime = Date.now();
4097
+ const inMemoryBefore = metadataTypeCodes.filter((c) => Boolean(this.cache.getDomainFile(c)));
4098
+ const missingInitial = this.findMissingTypeCodes(metadataTypeCodes);
4099
+ this.logger.info({
4100
+ event: "metadata-enrichment.trace.metadataLoading.start",
4101
+ stage: "ensureProjectionTypesLoaded",
4102
+ requestedTypes: metadataTypeCodes,
4103
+ typesInMemory: inMemoryBefore,
4104
+ typesMissing: missingInitial,
4105
+ totalRequested: metadataTypeCodes.length,
4106
+ totalInMemory: inMemoryBefore.length,
4107
+ totalMissing: missingInitial.length
4108
+ });
4109
+ while (true) {
4110
+ const missing = this.findMissingTypeCodes(metadataTypeCodes);
4111
+ if (missing.length === 0) {
4112
+ this.logger.info({
4113
+ event: "metadata-enrichment.trace.metadataLoading.completed",
4114
+ stage: "ensureProjectionTypesLoaded",
4115
+ requestedTypes: metadataTypeCodes,
4116
+ durationMs: Date.now() - startLoadTime,
4117
+ s3IoAttempted: missingInitial.length > 0,
4118
+ outcome: "all_types_in_cache"
4119
+ });
4120
+ return;
4121
+ }
4122
+ const inFlight = missing.map((code) => this.domainLoadInFlight.get(code)).filter((p) => p != null);
4123
+ if (inFlight.length > 0) {
4124
+ await Promise.all(inFlight);
4125
+ continue;
4126
+ }
4127
+ const toDownload = missing.filter(
4128
+ (code) => !this.domainLoadInFlight.has(code)
4129
+ );
4130
+ if (toDownload.length === 0) {
4131
+ continue;
4132
+ }
4133
+ const generation = this.cache.getGeneration();
4134
+ const releaseId = this.cache.getReleaseId();
4135
+ const batchPromise = this.downloadAndMergeTypes(
4136
+ toDownload,
4137
+ releaseId,
4138
+ generation
4139
+ ).finally(() => {
4140
+ for (const code of toDownload) {
4141
+ this.domainLoadInFlight.delete(code);
4142
+ }
4143
+ });
4144
+ for (const code of toDownload) {
4145
+ this.domainLoadInFlight.set(code, batchPromise);
4146
+ }
4147
+ await batchPromise;
4148
+ }
4149
+ }
4150
+ syncUnsupportedProjectionRelease(releaseId) {
4151
+ const id = releaseId ?? null;
4152
+ if (this.unsupportedProjectionReleaseId !== id) {
4153
+ this.unsupportedProjectionTypes.clear();
4154
+ this.unsupportedProjectionReleaseId = id;
4155
+ }
4156
+ }
4157
+ findMissingTypeCodes(metadataTypeCodes) {
4158
+ this.syncUnsupportedProjectionRelease(this.cache.getManifest()?.releaseId);
4159
+ const missing = /* @__PURE__ */ new Set();
4160
+ for (const raw of metadataTypeCodes) {
4161
+ const metadataTypeCode = normalizeRuntimeMetadataTypeCode(raw);
4162
+ if (!metadataTypeCode) {
4163
+ continue;
4164
+ }
4165
+ if (this.unsupportedProjectionTypes.has(metadataTypeCode)) {
4166
+ continue;
4167
+ }
4168
+ if (!this.cache.getDomainFile(metadataTypeCode)) {
4169
+ missing.add(metadataTypeCode);
4170
+ }
4171
+ }
4172
+ return [...missing].sort((a, b) => a.localeCompare(b));
4173
+ }
4174
+ async downloadAndMergeTypes(metadataTypeCodes, expectedReleaseId, expectedGeneration) {
4175
+ const manifest = this.cache.getManifest();
4176
+ if (!manifest || metadataTypeCodes.length === 0) {
4177
+ return;
4178
+ }
4179
+ if (expectedReleaseId && (manifest.releaseId !== expectedReleaseId || this.cache.getGeneration() !== expectedGeneration)) {
4180
+ return;
4181
+ }
4182
+ this.syncUnsupportedProjectionRelease(manifest.releaseId);
4183
+ const { domainFiles, loadedFiles } = await this.downloader.downloadDomainProjections(
4184
+ manifest,
4185
+ metadataTypeCodes
4186
+ );
4187
+ if (expectedReleaseId && (this.cache.getReleaseId() !== expectedReleaseId || this.cache.getGeneration() !== expectedGeneration)) {
4188
+ return;
4189
+ }
4190
+ for (const code of metadataTypeCodes) {
4191
+ if (!domainFiles.has(code)) {
4192
+ this.unsupportedProjectionTypes.add(code);
4193
+ }
4194
+ }
4195
+ if (domainFiles.size === 0) {
4196
+ return;
4197
+ }
4198
+ this.cache.mergeDomainFiles(domainFiles, loadedFiles, {
4199
+ releaseId: manifest.releaseId,
4200
+ generation: expectedGeneration
4201
+ });
4202
+ }
4203
+ resolve(typeCodeOrRef, valueCodeOrVersion, version) {
4204
+ if (isMetadataReference(typeCodeOrRef)) {
4205
+ const refVersion = typeof valueCodeOrVersion === "number" ? valueCodeOrVersion : void 0;
4206
+ return this.resolver.resolve(typeCodeOrRef, refVersion);
4207
+ }
4208
+ return this.resolver.resolve(
4209
+ typeCodeOrRef,
4210
+ typeof valueCodeOrVersion === "string" ? valueCodeOrVersion : "",
4211
+ version
4212
+ );
4213
+ }
4214
+ supportsType(typeCode) {
4215
+ return this.resolver.supportsType(typeCode);
4216
+ }
4217
+ resolveLocalization(typeCode, valueCode, locale) {
4218
+ return this.resolver.resolveLocalization(typeCode, valueCode, locale);
4219
+ }
4220
+ getLocalizationValue(keyOrTypeCode, valueCodeOrLocale, maybeLocale) {
4221
+ if (keyOrTypeCode.includes(".")) {
4222
+ const dotIndex = keyOrTypeCode.indexOf(".");
4223
+ const typeCode = keyOrTypeCode.slice(0, dotIndex);
4224
+ const valueCode = keyOrTypeCode.slice(dotIndex + 1);
4225
+ return this.resolver.resolveLocalization(
4226
+ typeCode,
4227
+ valueCode,
4228
+ valueCodeOrLocale
4229
+ );
4230
+ }
4231
+ if (valueCodeOrLocale) {
4232
+ return this.resolver.resolveLocalization(
4233
+ keyOrTypeCode,
4234
+ valueCodeOrLocale,
4235
+ maybeLocale
4236
+ );
4237
+ }
4238
+ return void 0;
4239
+ }
4240
+ getDomainFile(typeCode) {
4241
+ return this.cache.getDomainFile(typeCode);
4242
+ }
4243
+ getTypeLocalizedDisplayName(typeCode, locale) {
4244
+ return this.resolver.getTypeLocalizedDisplayName(typeCode, locale);
4245
+ }
4246
+ getValueDataType(typeCode) {
4247
+ return this.resolver.getValueDataType(typeCode);
4248
+ }
4249
+ listMetadataTypes() {
4250
+ return this.resolver.listMetadataTypes();
4251
+ }
4252
+ getManifest() {
4253
+ return this.resolver.getManifest();
4254
+ }
4255
+ getLookupIndex() {
4256
+ return this.resolver.getLookupIndex();
4257
+ }
4258
+ exists(type, code, version) {
4259
+ return this.resolver.exists(type, code, version);
4260
+ }
4261
+ search(type, query) {
4262
+ return this.resolver.search(type, query);
4263
+ }
4264
+ getAll(type) {
4265
+ return this.resolver.getAll(type);
4266
+ }
4267
+ getHealth() {
4268
+ return this.healthService.getHealth();
4269
+ }
4270
+ isHealthy() {
4271
+ return this.healthService.isHealthy();
4272
+ }
4273
+ async getValue(typeCode, valueCode, options) {
4274
+ try {
4275
+ const provider = await this.activeProvider();
4276
+ const guard = this.currentWriteGuard();
4277
+ const value = await provider.getValue(typeCode, valueCode, options);
4278
+ this.hydrateProviderValues(value ? [value] : [], guard);
4279
+ this.logger.info({
4280
+ event: value ? RUNTIME_METADATA_EVENTS.CACHE_HIT : RUNTIME_METADATA_EVENTS.CACHE_MISS,
4281
+ typeCode,
4282
+ valueCode,
4283
+ transport: this.providerCoordinator.getActiveKind()
4284
+ });
4285
+ return value;
4286
+ } catch (err) {
4287
+ if (await this.tryActivateFallbackFromError(err, "extension-lookup")) {
4288
+ const fallback = this.metadataProviderFallback;
4289
+ if (fallback) {
4290
+ return fallback.getValue(typeCode, valueCode, options);
4291
+ }
4292
+ }
4293
+ throw err;
4294
+ }
4295
+ }
4296
+ async batchGet(references, options) {
4297
+ try {
4298
+ const provider = await this.activeProvider();
4299
+ const generationAtStart = this.cache.getGeneration();
4300
+ const result = await provider.batchGet(references, options);
4301
+ this.logger.info({
4302
+ event: RUNTIME_METADATA_EVENTS.BATCH_LOOKUP,
4303
+ requested: references.length,
4304
+ resolved: Object.keys(result.items).length,
4305
+ invalid: result.invalidReferences.length,
4306
+ unavailable: result.unavailable,
4307
+ transport: this.providerCoordinator.getActiveKind(),
4308
+ releaseId: result.releaseId
4309
+ });
4310
+ if (result.unavailable && this.metadataProviderFallback && this.usesExtensionTransport()) {
4311
+ await this.providerCoordinator.activateFallback("batch-unavailable");
4312
+ return this.metadataProviderFallback.batchGet(references, options);
4313
+ }
4314
+ this.installBatchReleaseIfCurrent(result, generationAtStart);
4315
+ this.hydrateProviderValues(
4316
+ Object.values(result.items),
4317
+ {
4318
+ releaseId: result.releaseId ?? this.cache.getReleaseId() ?? "",
4319
+ generation: this.cache.getGeneration()
4320
+ }
4321
+ );
4322
+ return result;
4323
+ } catch (err) {
4324
+ if (await this.tryActivateFallbackFromError(err, "batch-unavailable")) {
4325
+ const fallback = this.metadataProviderFallback;
4326
+ if (fallback) {
4327
+ return fallback.batchGet(references, options);
4328
+ }
4329
+ }
4330
+ throw err;
4331
+ }
4332
+ }
4333
+ async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
4334
+ try {
4335
+ const provider = await this.activeProvider();
4336
+ const guard = this.currentWriteGuard();
4337
+ const values = await provider.getRelatedValues(
4338
+ sourceTypeCode,
4339
+ sourceValueCode,
4340
+ targetTypeCode,
4341
+ options
4342
+ );
4343
+ this.hydrateProviderValues(values, guard);
4344
+ return values;
4345
+ } catch (err) {
4346
+ if (await this.tryActivateFallbackFromError(err, "extension-related")) {
4347
+ const fallback = this.metadataProviderFallback;
4348
+ if (fallback) {
4349
+ return fallback.getRelatedValues(
4350
+ sourceTypeCode,
4351
+ sourceValueCode,
4352
+ targetTypeCode,
4353
+ options
4354
+ );
4355
+ }
4356
+ }
4357
+ throw err;
4358
+ }
4359
+ }
4360
+ getActiveProviderKind() {
4361
+ return this.providerCoordinator.getActiveKind();
4362
+ }
4363
+ getProviderTransportState() {
4364
+ return this.providerCoordinator.getState();
4365
+ }
4366
+ getExtensionHealthCheckCount() {
4367
+ return this.providerCoordinator.getHealthCheckCount();
4368
+ }
4369
+ usesExtensionTransport() {
4370
+ return this.providerCoordinator.usesExtension();
4371
+ }
4372
+ async activeProvider() {
4373
+ return this.providerCoordinator.activeProvider();
4374
+ }
4375
+ startS3PeriodicCheck() {
4376
+ if (this.config.periodicCheckIntervalMs > 0) {
4377
+ this.refreshService.startPeriodicCheck(
4378
+ this.config.periodicCheckIntervalMs
4379
+ );
4380
+ }
4381
+ }
4382
+ async refreshViaExtension(releaseId) {
4383
+ const refresh = this.metadataProvider.requestRefresh;
4384
+ if (!refresh) {
4385
+ return false;
4386
+ }
4387
+ const changed = await refresh.call(this.metadataProvider, releaseId);
4388
+ if (changed) {
4389
+ await this.initializeFromExtension();
4390
+ }
4391
+ return changed;
4392
+ }
4393
+ async initializeFromExtension() {
4394
+ try {
4395
+ const extension = this.metadataProvider;
4396
+ const status = extension.waitUntilReady ? await extension.waitUntilReady() : await extension.getStatus();
4397
+ if (!isExtensionServing(status)) {
4398
+ return false;
4399
+ }
4400
+ this.installExtensionManifest(
4401
+ status.releaseId ?? "",
4402
+ status.metadataTypes ?? [],
4403
+ {
4404
+ forceReset: true
4405
+ }
4406
+ );
4407
+ return true;
4408
+ } catch (err) {
4409
+ this.logger.warn({
4410
+ event: RUNTIME_METADATA_EVENTS.PROVIDER_FALLBACK,
4411
+ reason: "extension-unavailable",
4412
+ recoverable: true,
4413
+ message: err instanceof Error ? err.message : String(err)
4414
+ });
4415
+ return false;
4416
+ }
4417
+ }
4418
+ installExtensionManifest(releaseId, metadataTypes, options) {
4419
+ if (!releaseId) {
4420
+ return;
4421
+ }
4422
+ const uniqueTypes = [...new Set(metadataTypes.filter((code) => code.trim()))].sort(
4423
+ (a, b) => a.localeCompare(b)
4424
+ );
4425
+ if (!options?.forceReset && this.cache.isReady() && this.cache.getReleaseId() === releaseId) {
4426
+ return;
4427
+ }
4428
+ const types = {};
4429
+ for (const typeCode of uniqueTypes) {
4430
+ types[typeCode] = {
4431
+ typeCode,
4432
+ projectionFile: `${typeCode}.json`
4433
+ };
4434
+ }
4435
+ const files = [
4436
+ {
4437
+ fileName: "manifest.json",
4438
+ projectionType: "manifest",
4439
+ contentHash: releaseId,
4440
+ itemCount: uniqueTypes.length
4441
+ }
4442
+ ];
4443
+ const manifest = {
4444
+ releaseId,
4445
+ environment: this.config.environment,
4446
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
4447
+ projectionVersion: this.config.expectedProjectionVersion,
4448
+ metadataCount: uniqueTypes.length,
4449
+ artifactCount: 1,
4450
+ contentHash: releaseId,
4451
+ artifacts: [],
4452
+ files,
4453
+ metadataTypes: types,
4454
+ lookupIndex: {},
4455
+ revision: releaseId,
4456
+ schemaVersion: this.config.expectedSchemaVersion,
4457
+ localization: options?.localization ? {
4458
+ defaultLocale: "en-US",
4459
+ supportedLocales: [...options.localization.keys()].sort(),
4460
+ files: Object.fromEntries(
4461
+ [...options.localization.keys()].map((l) => [
4462
+ l,
4463
+ `localization/${l}.json`
4464
+ ])
4465
+ )
4466
+ } : void 0
4467
+ };
4468
+ const cachedLoc = this.cache.getSnapshot()?.localization;
4469
+ const fallbackLoc = cachedLoc ? new Map([...cachedLoc.entries()].map(([k, v]) => [k, new Map(v)])) : void 0;
4470
+ const bundle = {
4471
+ revision: releaseId,
4472
+ releaseId,
4473
+ manifest,
4474
+ domainFiles: /* @__PURE__ */ new Map(),
4475
+ relationshipIndex: void 0,
4476
+ localization: options?.localization ?? fallbackLoc,
4477
+ loadedFiles: ["manifest.json"],
4478
+ downloadedAt: (/* @__PURE__ */ new Date()).toISOString()
4479
+ };
4480
+ this.cache.replace(bundle);
4481
+ this.syncUnsupportedProjectionRelease(releaseId);
4482
+ }
4483
+ hydrateProviderValues(values, guard) {
4484
+ if (!this.cache.isReady() || values.length === 0 || !guard.releaseId) {
4485
+ return;
4486
+ }
4487
+ this.cache.hydrateEntries(
4488
+ values.map((value) => ({
4489
+ typeCode: value.typeCode,
4490
+ valueCode: value.valueCode,
4491
+ entry: value.entry
4492
+ })),
4493
+ guard
4494
+ );
4495
+ }
4496
+ currentWriteGuard(captured) {
4497
+ return {
4498
+ releaseId: captured?.releaseId ?? this.cache.getReleaseId() ?? "",
4499
+ generation: captured?.generation ?? this.cache.getGeneration()
4500
+ };
4501
+ }
4502
+ installBatchReleaseIfCurrent(result, generationAtStart) {
4503
+ if (!result.releaseId || !this.usesExtensionTransport()) {
4504
+ return;
4505
+ }
4506
+ const currentReleaseId = this.cache.getReleaseId();
4507
+ if (result.releaseId === currentReleaseId) {
4508
+ return;
4509
+ }
4510
+ const staleInFlight = this.cache.getGeneration() !== generationAtStart;
4511
+ if (staleInFlight) {
4512
+ return;
4513
+ }
4514
+ this.installExtensionManifest(
4515
+ result.releaseId,
4516
+ Object.keys(result.items).map((key) => {
4517
+ const sep = key.indexOf(":");
4518
+ return sep > 0 ? key.slice(0, sep) : key;
4519
+ }),
4520
+ { forceReset: true }
4521
+ );
4522
+ }
4523
+ async tryActivateFallbackFromError(err, reason) {
4524
+ if (!(err instanceof MetadataProjectionUnavailableError) || !this.metadataProviderFallback || !this.usesExtensionTransport()) {
4525
+ return false;
4526
+ }
4527
+ await this.providerCoordinator.activateFallback(reason);
4528
+ return true;
4529
+ }
4530
+ };
4531
+ function recoveryCooldownMs(env) {
4532
+ const raw = env?.METADATA_EXTENSION_RECOVERY_INTERVAL_MS;
4533
+ if (!raw) {
4534
+ return void 0;
4535
+ }
4536
+ const parsed = Number(raw);
4537
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
4538
+ }
4539
+ function createRuntimeMetadataFromEnv(options) {
4540
+ const env = options.env ?? process.env;
4541
+ const bucket = resolveMetadataProjectionsBucket(env);
4542
+ const environment = (options.environment ?? env.PROJECTION_ENVIRONMENT ?? env.STAGE ?? env.NODE_ENV ?? "dev").trim().toLowerCase();
4543
+ const config2 = {
4544
+ bucket,
4545
+ prefix: env.PROJECTION_ROOT_PREFIX ?? env.METADATA_PROJECTIONS_PREFIX,
4546
+ environment,
4547
+ revision: options.revision ?? env.METADATA_PROJECTION_REVISION,
4548
+ periodicCheckIntervalMs: options.periodicCheckIntervalMs ?? (env.METADATA_PROJECTION_CHECK_INTERVAL_MS ? Number(env.METADATA_PROJECTION_CHECK_INTERVAL_MS) : void 0)
4549
+ };
4550
+ return new RuntimeMetadataService({
4551
+ client: options.client,
4552
+ config: config2,
4553
+ env,
4554
+ logger: options.logger ?? createLogger({ serviceName: "runtime-metadata" })
4555
+ });
4556
+ }
4557
+ var logger = createLogger({
4558
+ service: process.env.SERVICE_NAME ?? "api-service",
4559
+ redactPII: true
4560
+ });
4561
+ var metadataServiceInstance;
4562
+ var initializePromise;
4563
+ var initialized = false;
4564
+ var lastUpdateCheckAtMs = 0;
4565
+ var UPDATE_CHECK_MIN_INTERVAL_MS = 3e4;
4566
+ function getRuntimeMetadataService() {
4567
+ if (!isMetadataProjectionConfigured()) {
4568
+ throw new Error(
4569
+ "METADATA_PROJECTIONS_BUCKET is required to create RuntimeMetadataService"
4570
+ );
4571
+ }
4572
+ if (!metadataServiceInstance) {
4573
+ metadataServiceInstance = createRuntimeMetadataFromEnv({
4574
+ client: new S3Client({
4575
+ region: process.env.AWS_REGION ?? process.env.REGION
4576
+ }),
4577
+ logger
4578
+ });
4579
+ }
4580
+ return metadataServiceInstance;
4581
+ }
4582
+ function resetRuntimeMetadataBootstrapState() {
4583
+ metadataServiceInstance = void 0;
4584
+ initializePromise = void 0;
4585
+ initialized = false;
4586
+ lastUpdateCheckAtMs = 0;
4587
+ }
4588
+ async function ensureRuntimeMetadataLoaded() {
4589
+ const service = getRuntimeMetadataService();
4590
+ if (!initialized) {
4591
+ initializePromise ??= service.initialize().then(() => {
4592
+ initialized = true;
4593
+ lastUpdateCheckAtMs = Date.now();
4594
+ }).catch((error) => {
4595
+ logger.error({
4596
+ error,
4597
+ message: "Failed to initialize runtime metadata"
4598
+ });
4599
+ initializePromise = void 0;
4600
+ throw error;
4601
+ });
4602
+ await initializePromise;
4603
+ return;
4604
+ }
4605
+ const now = Date.now();
4606
+ if (now - lastUpdateCheckAtMs < UPDATE_CHECK_MIN_INTERVAL_MS) {
4607
+ return;
4608
+ }
4609
+ lastUpdateCheckAtMs = now;
4610
+ await service.checkForUpdates();
4611
+ }
4612
+ function getRuntimeMetadataHealth() {
4613
+ return getRuntimeMetadataService().getHealth();
4614
+ }
4615
+ function tryGetRuntimeMetadataService() {
4616
+ if (!isMetadataProjectionConfigured()) {
4617
+ return null;
4618
+ }
4619
+ try {
4620
+ return getRuntimeMetadataService();
4621
+ } catch {
4622
+ return null;
4623
+ }
4624
+ }
4625
+ async function onMetadataProjectionCompleted(releaseId) {
4626
+ return getRuntimeMetadataService().onProjectionCompleted(releaseId);
4627
+ }
4628
+
4629
+ // ../../libs/runtime-metadata/src/lib/integration/domain-integration.notes.ts
4630
+ var RUNTIME_METADATA_INTEGRATION_TARGETS = [
4631
+ "care-plan-runtime",
4632
+ "monitoring-runtime",
4633
+ "threshold-runtime",
4634
+ "symptom-runtime-service",
4635
+ "task-service",
4636
+ "workflow-service",
4637
+ "alert-service"
4638
+ ];
4639
+
4640
+ // ../../libs/runtime-metadata/src/lib/provider/InMemoryMetadataProvider.ts
4641
+ var InMemoryMetadataProvider = class {
4642
+ releaseId;
4643
+ unavailable;
4644
+ forcedState;
4645
+ byKey = /* @__PURE__ */ new Map();
4646
+ related = /* @__PURE__ */ new Map();
4647
+ constructor(options = {}) {
4648
+ this.releaseId = options.releaseId ?? "memory";
4649
+ this.unavailable = options.unavailable === true;
4650
+ for (const record of options.records ?? []) {
4651
+ const key = formatMetadataReference(record.typeCode, record.valueCode);
4652
+ this.byKey.set(key, record);
4653
+ if (record.related) {
4654
+ const byTarget = /* @__PURE__ */ new Map();
4655
+ for (const [targetType, values] of Object.entries(record.related)) {
4656
+ byTarget.set(targetType, [...values]);
4657
+ }
4658
+ this.related.set(key, byTarget);
4659
+ }
4660
+ }
4661
+ }
4662
+ async isAvailable() {
4663
+ return !this.unavailable;
4664
+ }
4665
+ setUnavailable(unavailable) {
4666
+ this.unavailable = unavailable;
4667
+ }
4668
+ setReleaseId(releaseId) {
4669
+ this.releaseId = releaseId;
4670
+ }
4671
+ setState(state) {
4672
+ this.forcedState = state;
4673
+ }
4674
+ replaceRecords(records, releaseId) {
4675
+ this.byKey.clear();
4676
+ this.related.clear();
4677
+ if (releaseId) {
4678
+ this.releaseId = releaseId;
4679
+ }
4680
+ for (const record of records) {
4681
+ const key = formatMetadataReference(record.typeCode, record.valueCode);
4682
+ this.byKey.set(key, record);
4683
+ if (record.related) {
4684
+ const byTarget = /* @__PURE__ */ new Map();
4685
+ for (const [targetType, values] of Object.entries(record.related)) {
4686
+ byTarget.set(targetType, [...values]);
4687
+ }
4688
+ this.related.set(key, byTarget);
4689
+ }
4690
+ }
4691
+ }
4692
+ async waitUntilReady() {
4693
+ return this.getStatus();
4694
+ }
4695
+ async requestRefresh(_releaseId) {
4696
+ return false;
4697
+ }
4698
+ async getStatus() {
4699
+ const types = [
4700
+ ...new Set([...this.byKey.values()].map((r) => r.typeCode))
4701
+ ].sort();
4702
+ return {
4703
+ state: this.forcedState ?? (this.unavailable ? "FAILED" : "READY"),
4704
+ releaseId: this.unavailable ? null : this.releaseId,
4705
+ loadedAt: this.unavailable ? null : (/* @__PURE__ */ new Date(0)).toISOString(),
4706
+ lastRefreshAttemptAt: null,
4707
+ lastSuccessfulRefreshAt: null,
4708
+ cacheAgeMs: this.unavailable ? null : 0,
4709
+ metadataTypes: types
4710
+ };
4711
+ }
4712
+ async getValue(typeCode, valueCode, options) {
4713
+ if (this.unavailable) {
4714
+ throw new MetadataProjectionUnavailableError(
4715
+ "In-memory metadata provider is unavailable",
4716
+ { retryable: true }
4717
+ );
4718
+ }
4719
+ const record = this.byKey.get(formatMetadataReference(typeCode, valueCode));
4720
+ if (!record) {
4721
+ return null;
4722
+ }
4723
+ return projectionEntryToMetadataValue(
4724
+ record.typeCode,
4725
+ record.valueCode,
4726
+ record.entry,
4727
+ options?.locale
4728
+ );
4729
+ }
4730
+ async batchGet(references, options) {
4731
+ const invalidReferences = [];
4732
+ const items = {};
4733
+ if (this.unavailable) {
4734
+ return {
4735
+ releaseId: null,
4736
+ items: {},
4737
+ invalidReferences: references.filter((r) => r?.trim()),
4738
+ unavailable: true
4739
+ };
4740
+ }
4741
+ const seen = /* @__PURE__ */ new Set();
4742
+ for (const raw of references) {
4743
+ const parsed = tryParseMetadataReference(raw);
4744
+ if (!parsed) {
4745
+ if (typeof raw === "string" && raw.trim()) {
4746
+ invalidReferences.push(raw);
4747
+ }
4748
+ continue;
4749
+ }
4750
+ const key = formatMetadataReference(parsed.typeCode, parsed.valueCode);
4751
+ if (seen.has(key)) {
4752
+ continue;
4753
+ }
4754
+ seen.add(key);
4755
+ const value = await this.getValue(
4756
+ parsed.typeCode,
4757
+ parsed.valueCode,
4758
+ options
4759
+ );
4760
+ if (value) {
4761
+ items[key] = value;
4762
+ }
4763
+ }
4764
+ return {
4765
+ releaseId: this.releaseId,
4766
+ items,
4767
+ invalidReferences,
4768
+ unavailable: false
4769
+ };
4770
+ }
4771
+ async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
4772
+ if (this.unavailable) {
4773
+ throw new MetadataProjectionUnavailableError(
4774
+ "In-memory metadata provider is unavailable",
4775
+ { retryable: true }
4776
+ );
4777
+ }
4778
+ const sourceKey = formatMetadataReference(sourceTypeCode, sourceValueCode);
4779
+ const targets = this.related.get(sourceKey)?.get(targetTypeCode) ?? [];
4780
+ const values = [];
4781
+ for (const valueCode of targets) {
4782
+ const value = await this.getValue(targetTypeCode, valueCode, options);
4783
+ if (value) {
4784
+ values.push(value);
4785
+ }
4786
+ }
4787
+ return values;
4788
+ }
4789
+ };
4790
+
4791
+ export { CACHE_STATUS, DEFAULT_EXCLUDED_CODE_FIELDS, DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS, ExtensionMetadataProvider, InMemoryMetadataProvider, InvalidMetadataReferenceError, METADATA_PROJECTIONS_BUCKET_ENV, METADATA_PROVIDER_KIND, ManifestValidationError, MetadataCache, MetadataDownloader, MetadataHealthService, MetadataLoader, MetadataLookupError, MetadataNotReadyError, MetadataProjectionUnavailableError, MetadataRefreshService, MetadataResolver, NON_METADATA_KEYS, PROVIDER_TRANSPORT_STATE, ProjectionDownloadError, ProviderFailoverCoordinator, REFRESH_STATUS, RUNTIME_METADATA_EVENTS, RUNTIME_METADATA_INTEGRATION_TARGETS, RUNTIME_METADATA_TYPE_CODE_ALIASES, RuntimeMetadataError, RuntimeMetadataService, S3MetadataProvider, UnknownMetadataTypeError, WORKFLOW_STEP_RULE_KEYS, canonicalMetadataProjectionsBucketName, collectResponseReferences, collectResponseTypeCodes, createCodeFieldExclusionSet, createRuntimeMetadataFromEnv, defaultExtensionBaseUrl, ensureRuntimeMetadataLoaded, formatMetadataReference, getCandidateTypeCodesForKey, getRuntimeMetadataHealth, getRuntimeMetadataService, hasPotentialMetadata, isCompactMetadataReference, isExtensionEnabled, isExtensionServing, isMetadataProjectionConfigured, isMetadataProjectionsBucketConfigured, isMetadataReference, isMetadataValueObject, isMetadataValueObjectArray, isWorkflowStepRecord, isWorkflowStepRuleField, localizedLabelFromEntry, manifestLocalizationSchema, metadataGroupFromManifest, metadataValueToReference, normalizeRuntimeMetadataTypeCode, onMetadataProjectionCompleted, parseMetadataReference, projectionEntryToMetadataValue, projectionManifestSchema, readMetadataProjectionsBucket, readModelGroupsFromManifest, relatedValueCodes, resetRuntimeMetadataBootstrapState, resolveMetadataProjectionsBucket, resolveRuntimeMetadataConfig, runtimeMetadataConfigSchema, selectMetadataProvider, tryGetRuntimeMetadataService, tryParseMetadataReference, typeCodeFromCodeFieldName };
4792
+ //# sourceMappingURL=index.js.map
4793
+ //# sourceMappingURL=index.js.map