@myvitalrx/metadata-runtime 1.2.0 → 1.4.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 CHANGED
@@ -53,6 +53,10 @@ var RUNTIME_METADATA_EVENTS = {
53
53
  CACHE_HIT: "metadata_cache_hit",
54
54
  CACHE_MISS: "metadata_cache_miss",
55
55
  BATCH_LOOKUP: "metadata_batch_lookup",
56
+ TYPE_ENUMERATION: "runtimeMetadata.typeEnumeration",
57
+ TYPE_BATCH_ENUMERATION: "runtimeMetadata.typeBatchEnumeration",
58
+ RELATIONSHIP_QUERY: "runtimeMetadata.relationshipQuery",
59
+ FRESHNESS_REJECTED: "runtimeMetadata.freshness.rejected",
56
60
  PROVIDER_SELECTED: "runtimeMetadata.provider.selected",
57
61
  PROVIDER_FALLBACK: "runtimeMetadata.provider.fallback",
58
62
  PROVIDER_RECOVERED: "runtimeMetadata.provider.recovered"
@@ -1309,6 +1313,435 @@ function parseTypedRelationshipFile(parsed, expected) {
1309
1313
  return relations;
1310
1314
  }
1311
1315
  createLogger({ serviceName: "metadata-projection" });
1316
+
1317
+ // ../../libs/metadata-projection/src/lib/runtime-query/publishedValueListing.ts
1318
+ var PUBLISHED_VALUE_LIST_LIMITS = {
1319
+ MAX_PAGE_SIZE: 500,
1320
+ MAX_COMPLETE_SIZE: 2e3};
1321
+ var PUBLISHED_VALUE_SORT = {
1322
+ SORT_ORDER: "sortOrder",
1323
+ VALUE_CODE: "valueCode",
1324
+ DISPLAY_NAME: "displayName"
1325
+ };
1326
+ var PUBLISHED_VALUE_SORT_DIRECTION = {
1327
+ ASC: "ASC",
1328
+ DESC: "DESC"
1329
+ };
1330
+ var PUBLISHED_VALUE_ATTRIBUTE_FILTER_KEY = {
1331
+ ROLE_TYPE_CODE: "roleTypeCode",
1332
+ CATEGORY_CODE: "categoryCode",
1333
+ MODULE_CODE: "moduleCode",
1334
+ FEATURE_CODE: "featureCode",
1335
+ DEVICE_CATEGORY_CODE: "deviceCategoryCode"
1336
+ };
1337
+ var ATTRIBUTE_FILTER_KEYS = new Set(
1338
+ Object.values(PUBLISHED_VALUE_ATTRIBUTE_FILTER_KEY)
1339
+ );
1340
+ var PUBLISHED_VALUE_LIST_CODE = {
1341
+ INVALID: "METADATA_DISCOVERY_INVALID",
1342
+ INCOMPLETE: "METADATA_TYPE_INCOMPLETE"
1343
+ };
1344
+ function entriesFromProjectionFile(file) {
1345
+ const entries = [];
1346
+ const seen = /* @__PURE__ */ new Set();
1347
+ const active = collectRecords(file.records, seen);
1348
+ if (!active.ok) {
1349
+ return active;
1350
+ }
1351
+ entries.push(...active.entries);
1352
+ const inactive = collectRecords(file.inactiveRecords ?? {}, seen);
1353
+ if (!inactive.ok) {
1354
+ return inactive;
1355
+ }
1356
+ entries.push(...inactive.entries);
1357
+ return { ok: true, entries };
1358
+ }
1359
+ function listPublishedValues(entries, query) {
1360
+ const normalized = normalizeQuery(query);
1361
+ if (isListFailure(normalized)) {
1362
+ return normalized;
1363
+ }
1364
+ const matched = [];
1365
+ for (const entry of entries) {
1366
+ if (!isUsableEntry(entry)) {
1367
+ return incomplete("Metadata type contains a value that cannot be listed");
1368
+ }
1369
+ if (!matches(entry, normalized)) {
1370
+ continue;
1371
+ }
1372
+ matched.push(entry);
1373
+ }
1374
+ matched.sort(
1375
+ (left, right) => compareEntries(left, right, normalized.sortBy, normalized.sortDirection)
1376
+ );
1377
+ const { offset, limit } = normalized;
1378
+ if (limit === void 0 && matched.length > PUBLISHED_VALUE_LIST_LIMITS.MAX_COMPLETE_SIZE) {
1379
+ return invalid(
1380
+ `Metadata type listing exceeds ${PUBLISHED_VALUE_LIST_LIMITS.MAX_COMPLETE_SIZE} values; pass limit to page`
1381
+ );
1382
+ }
1383
+ const page = limit === void 0 ? matched : matched.slice(offset, offset + limit);
1384
+ const nextOffset = limit === void 0 ? matched.length : offset + page.length;
1385
+ const result = {
1386
+ ok: true,
1387
+ items: page.map(copyEntry)
1388
+ };
1389
+ if (limit !== void 0 && nextOffset < matched.length) {
1390
+ result.nextCursor = encodeCursor({
1391
+ v: 1,
1392
+ offset: nextOffset,
1393
+ releaseId: query.releaseId,
1394
+ fingerprint: normalized.fingerprint
1395
+ });
1396
+ }
1397
+ return result;
1398
+ }
1399
+ function collectRecords(records, seen) {
1400
+ const entries = [];
1401
+ for (const [valueCode, record] of Object.entries(records)) {
1402
+ if (seen.has(valueCode)) {
1403
+ continue;
1404
+ }
1405
+ const entry = record?.versions?.[String(record.latestVersion)];
1406
+ if (!isUsableEntry(entry) || entry.code !== valueCode) {
1407
+ return incomplete("Metadata type contains a value that cannot be listed");
1408
+ }
1409
+ seen.add(valueCode);
1410
+ entries.push(entry);
1411
+ }
1412
+ return { ok: true, entries };
1413
+ }
1414
+ function normalizeQuery(query) {
1415
+ if (!query.releaseId) {
1416
+ return invalid("releaseId is required to list metadata values");
1417
+ }
1418
+ const sortBy = query.sortBy ?? PUBLISHED_VALUE_SORT.SORT_ORDER;
1419
+ if (!isSort(sortBy)) {
1420
+ return invalid("sortBy must be sortOrder, valueCode, or displayName");
1421
+ }
1422
+ const sortDirection = query.sortDirection ?? PUBLISHED_VALUE_SORT_DIRECTION.ASC;
1423
+ if (sortDirection !== PUBLISHED_VALUE_SORT_DIRECTION.ASC && sortDirection !== PUBLISHED_VALUE_SORT_DIRECTION.DESC) {
1424
+ return invalid("sortDirection must be ASC or DESC");
1425
+ }
1426
+ let limit;
1427
+ if (query.limit !== void 0) {
1428
+ if (!Number.isInteger(query.limit) || query.limit < 1) {
1429
+ return invalid("limit must be a positive integer");
1430
+ }
1431
+ if (query.limit > PUBLISHED_VALUE_LIST_LIMITS.MAX_PAGE_SIZE) {
1432
+ return invalid(
1433
+ `limit must be at most ${PUBLISHED_VALUE_LIST_LIMITS.MAX_PAGE_SIZE}`
1434
+ );
1435
+ }
1436
+ limit = query.limit;
1437
+ }
1438
+ const statuses = normalizeStatuses(query.status);
1439
+ if (!statuses.ok) {
1440
+ return statuses;
1441
+ }
1442
+ const attributes = normalizeAttributes(query.attributes);
1443
+ if (!attributes.ok) {
1444
+ return attributes;
1445
+ }
1446
+ const valueCode = normalizeOptionalCode(query.valueCode, "valueCode");
1447
+ if (!valueCode.ok) {
1448
+ return valueCode;
1449
+ }
1450
+ const valueCodePrefix = normalizeOptionalCode(
1451
+ query.valueCodePrefix,
1452
+ "valueCodePrefix"
1453
+ );
1454
+ if (!valueCodePrefix.ok) {
1455
+ return valueCodePrefix;
1456
+ }
1457
+ const fingerprint = fingerprintOf({
1458
+ sortBy,
1459
+ sortDirection,
1460
+ statuses: statuses.statuses,
1461
+ valueCode: valueCode.value,
1462
+ valueCodePrefix: valueCodePrefix.value,
1463
+ attributes: attributes.attributes
1464
+ });
1465
+ let offset = 0;
1466
+ if (query.cursor) {
1467
+ const decoded = decodeCursor(query.cursor);
1468
+ if (!decoded.ok) {
1469
+ return decoded;
1470
+ }
1471
+ if (decoded.cursor.releaseId !== query.releaseId) {
1472
+ return invalid("cursor does not match the requested projection release");
1473
+ }
1474
+ if (decoded.cursor.fingerprint !== fingerprint) {
1475
+ return invalid("cursor does not match the requested filters");
1476
+ }
1477
+ offset = decoded.cursor.offset;
1478
+ }
1479
+ return {
1480
+ statuses: statuses.statuses,
1481
+ limit,
1482
+ offset,
1483
+ sortBy,
1484
+ sortDirection,
1485
+ valueCode: valueCode.value,
1486
+ valueCodePrefix: valueCodePrefix.value,
1487
+ attributes: attributes.attributes,
1488
+ fingerprint
1489
+ };
1490
+ }
1491
+ function matches(entry, query) {
1492
+ if (query.statuses && !query.statuses.includes(entry.status)) {
1493
+ return false;
1494
+ }
1495
+ if (query.valueCode && entry.code !== query.valueCode) {
1496
+ return false;
1497
+ }
1498
+ if (query.valueCodePrefix && !entry.code.startsWith(query.valueCodePrefix)) {
1499
+ return false;
1500
+ }
1501
+ for (const [key, expected] of Object.entries(query.attributes)) {
1502
+ if (entry.attributes[key] !== expected) {
1503
+ return false;
1504
+ }
1505
+ }
1506
+ return true;
1507
+ }
1508
+ function compareEntries(left, right, sortBy, direction) {
1509
+ const primary = comparePrimary(left, right, sortBy);
1510
+ const code = left.code.localeCompare(right.code);
1511
+ const compared = primary !== 0 ? primary : code;
1512
+ return direction === PUBLISHED_VALUE_SORT_DIRECTION.DESC ? -compared : compared;
1513
+ }
1514
+ function comparePrimary(left, right, sortBy) {
1515
+ if (sortBy === PUBLISHED_VALUE_SORT.VALUE_CODE) {
1516
+ return left.code.localeCompare(right.code);
1517
+ }
1518
+ if (sortBy === PUBLISHED_VALUE_SORT.DISPLAY_NAME) {
1519
+ return left.displayName.localeCompare(right.displayName);
1520
+ }
1521
+ return left.sortOrder - right.sortOrder;
1522
+ }
1523
+ function isUsableEntry(entry) {
1524
+ return Boolean(
1525
+ entry && typeof entry.code === "string" && entry.code.trim() && typeof entry.status === "string" && entry.status.trim() && typeof entry.displayName === "string" && typeof entry.sortOrder === "number" && Number.isFinite(entry.sortOrder) && entry.attributes && typeof entry.attributes === "object" && !Array.isArray(entry.attributes)
1526
+ );
1527
+ }
1528
+ function copyEntry(entry) {
1529
+ const applicability = entry.applicability;
1530
+ return {
1531
+ ...entry,
1532
+ attributes: { ...entry.attributes },
1533
+ applicability: {
1534
+ ...applicability,
1535
+ module: [...applicability?.module ?? []],
1536
+ category: [...applicability?.category ?? []],
1537
+ condition: [...applicability?.condition ?? []],
1538
+ country: [...applicability?.country ?? []],
1539
+ ...applicability?.language ? { language: [...applicability.language] } : {}
1540
+ },
1541
+ ...entry.localizedLabels ? { localizedLabels: { ...entry.localizedLabels } } : {},
1542
+ ...entry.relationships ? { relationships: entry.relationships.map((row) => ({ ...row })) } : {}
1543
+ };
1544
+ }
1545
+ function normalizeStatuses(status) {
1546
+ if (status === void 0) {
1547
+ return { ok: true, statuses: void 0 };
1548
+ }
1549
+ const raw = Array.isArray(status) ? status : [status];
1550
+ const statuses = [...new Set(raw.map((value) => value.trim()).filter(Boolean))].sort();
1551
+ if (statuses.length === 0) {
1552
+ return invalid("status filter must contain at least one status");
1553
+ }
1554
+ return { ok: true, statuses };
1555
+ }
1556
+ function normalizeAttributes(attributes) {
1557
+ if (!attributes) {
1558
+ return { ok: true, attributes: {} };
1559
+ }
1560
+ const normalized = {};
1561
+ for (const [key, value] of Object.entries(attributes)) {
1562
+ if (!ATTRIBUTE_FILTER_KEYS.has(key)) {
1563
+ return invalid(`Attribute filter ${key} is not supported`);
1564
+ }
1565
+ if (typeof value !== "string" || !value.trim()) {
1566
+ return invalid(`Attribute filter ${key} must be a non-empty string`);
1567
+ }
1568
+ normalized[key] = value;
1569
+ }
1570
+ return { ok: true, attributes: normalized };
1571
+ }
1572
+ function normalizeOptionalCode(value, field) {
1573
+ if (value === void 0) {
1574
+ return { ok: true, value: void 0 };
1575
+ }
1576
+ const trimmed = value.trim();
1577
+ if (!trimmed) {
1578
+ return invalid(`${field} must be a non-empty string`);
1579
+ }
1580
+ return { ok: true, value: trimmed };
1581
+ }
1582
+ function fingerprintOf(input) {
1583
+ const attributeKey = Object.keys(input.attributes).sort().map((key) => `${key}=${input.attributes[key]}`).join("&");
1584
+ return [
1585
+ input.sortBy,
1586
+ input.sortDirection,
1587
+ input.statuses?.join(",") ?? "*",
1588
+ input.valueCode ?? "",
1589
+ input.valueCodePrefix ?? "",
1590
+ attributeKey
1591
+ ].join("|");
1592
+ }
1593
+ function encodeCursor(payload) {
1594
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
1595
+ }
1596
+ function decodeCursor(cursor) {
1597
+ try {
1598
+ const parsed = JSON.parse(
1599
+ Buffer.from(cursor, "base64url").toString("utf8")
1600
+ );
1601
+ if (parsed?.v !== 1 || typeof parsed.offset !== "number" || !Number.isInteger(parsed.offset) || parsed.offset < 0 || typeof parsed.releaseId !== "string" || typeof parsed.fingerprint !== "string") {
1602
+ return invalid("cursor is invalid");
1603
+ }
1604
+ return {
1605
+ ok: true,
1606
+ cursor: {
1607
+ v: 1,
1608
+ offset: parsed.offset,
1609
+ releaseId: parsed.releaseId,
1610
+ fingerprint: parsed.fingerprint
1611
+ }
1612
+ };
1613
+ } catch {
1614
+ return invalid("cursor is invalid");
1615
+ }
1616
+ }
1617
+ function isListFailure(value) {
1618
+ return "message" in value;
1619
+ }
1620
+ function isSort(value) {
1621
+ return value === PUBLISHED_VALUE_SORT.SORT_ORDER || value === PUBLISHED_VALUE_SORT.VALUE_CODE || value === PUBLISHED_VALUE_SORT.DISPLAY_NAME;
1622
+ }
1623
+ function invalid(message) {
1624
+ return { ok: false, code: PUBLISHED_VALUE_LIST_CODE.INVALID, message };
1625
+ }
1626
+ function incomplete(message) {
1627
+ return { ok: false, code: PUBLISHED_VALUE_LIST_CODE.INCOMPLETE, message };
1628
+ }
1629
+
1630
+ // ../../libs/metadata-projection/src/lib/runtime-query/publishedRelationshipQuery.ts
1631
+ var PUBLISHED_RELATION_DIRECTION = {
1632
+ OUTGOING: "OUTGOING",
1633
+ INCOMING: "INCOMING"
1634
+ };
1635
+ function queryPublishedRelationships(query) {
1636
+ const sourceTypeCode = query.sourceTypeCode.trim();
1637
+ const sourceValueCode = query.sourceValueCode.trim();
1638
+ if (!sourceTypeCode || !sourceValueCode) {
1639
+ return {
1640
+ ok: false,
1641
+ code: "METADATA_DISCOVERY_INVALID",
1642
+ message: "sourceTypeCode and sourceValueCode are required"
1643
+ };
1644
+ }
1645
+ const direction = query.direction ?? PUBLISHED_RELATION_DIRECTION.OUTGOING;
1646
+ if (direction !== PUBLISHED_RELATION_DIRECTION.OUTGOING && direction !== PUBLISHED_RELATION_DIRECTION.INCOMING) {
1647
+ return {
1648
+ ok: false,
1649
+ code: "METADATA_DISCOVERY_INVALID",
1650
+ message: "direction must be OUTGOING or INCOMING"
1651
+ };
1652
+ }
1653
+ const targetTypeCode = optionalCode(query.targetTypeCode);
1654
+ const relationType = optionalCode(query.relationType);
1655
+ if (targetTypeCode === "" || relationType === "") {
1656
+ return {
1657
+ ok: false,
1658
+ code: "METADATA_DISCOVERY_INVALID",
1659
+ message: "relationship filters must be non-empty strings"
1660
+ };
1661
+ }
1662
+ if (!query.supported) {
1663
+ return { ok: true, supported: false, relationships: [] };
1664
+ }
1665
+ const seen = /* @__PURE__ */ new Set();
1666
+ const relationships = [];
1667
+ for (const relation of query.relations) {
1668
+ if (!isCompleteRelation(relation)) {
1669
+ return {
1670
+ ok: false,
1671
+ code: "METADATA_TYPE_INCOMPLETE",
1672
+ message: "Typed relationship catalog contains a row that cannot be queried"
1673
+ };
1674
+ }
1675
+ const matchesSource = direction === PUBLISHED_RELATION_DIRECTION.OUTGOING ? relation.fromMetadataTypeCode === sourceTypeCode && relation.fromMetadataValueCode === sourceValueCode : relation.toMetadataTypeCode === sourceTypeCode && relation.toMetadataValueCode === sourceValueCode;
1676
+ if (!matchesSource) {
1677
+ continue;
1678
+ }
1679
+ if (relationType && relation.relationType !== relationType) {
1680
+ continue;
1681
+ }
1682
+ if (targetTypeCode) {
1683
+ const otherType = direction === PUBLISHED_RELATION_DIRECTION.OUTGOING ? relation.toMetadataTypeCode : relation.fromMetadataTypeCode;
1684
+ if (otherType !== targetTypeCode) {
1685
+ continue;
1686
+ }
1687
+ }
1688
+ const view = toView(relation, direction);
1689
+ const key = relationshipKey(view);
1690
+ if (seen.has(key)) {
1691
+ continue;
1692
+ }
1693
+ seen.add(key);
1694
+ relationships.push(view);
1695
+ }
1696
+ relationships.sort((left, right) => relationshipKey(left).localeCompare(relationshipKey(right)));
1697
+ return { ok: true, supported: true, relationships };
1698
+ }
1699
+ function toView(relation, direction) {
1700
+ const view = {
1701
+ relationType: relation.relationType,
1702
+ status: relation.status,
1703
+ direction,
1704
+ fromMetadataTypeCode: relation.fromMetadataTypeCode,
1705
+ fromMetadataValueCode: relation.fromMetadataValueCode,
1706
+ toMetadataTypeCode: relation.toMetadataTypeCode,
1707
+ toMetadataValueCode: relation.toMetadataValueCode
1708
+ };
1709
+ if (typeof relation.moduleCode === "string") {
1710
+ view.moduleCode = relation.moduleCode;
1711
+ }
1712
+ if (typeof relation.featureCode === "string") {
1713
+ view.featureCode = relation.featureCode;
1714
+ }
1715
+ if (typeof relation.permissionActionCode === "string") {
1716
+ view.permissionActionCode = relation.permissionActionCode;
1717
+ }
1718
+ return view;
1719
+ }
1720
+ function relationshipKey(relation) {
1721
+ return [
1722
+ relation.relationType,
1723
+ relation.status,
1724
+ relation.direction,
1725
+ relation.fromMetadataTypeCode,
1726
+ relation.fromMetadataValueCode,
1727
+ relation.toMetadataTypeCode,
1728
+ relation.toMetadataValueCode,
1729
+ relation.moduleCode ?? "",
1730
+ relation.featureCode ?? "",
1731
+ relation.permissionActionCode ?? ""
1732
+ ].join("\0");
1733
+ }
1734
+ function isCompleteRelation(relation) {
1735
+ return Boolean(
1736
+ relation && typeof relation.relationType === "string" && relation.relationType.trim() && typeof relation.status === "string" && relation.status.trim() && typeof relation.fromMetadataTypeCode === "string" && relation.fromMetadataTypeCode.trim() && typeof relation.fromMetadataValueCode === "string" && relation.fromMetadataValueCode.trim() && typeof relation.toMetadataTypeCode === "string" && relation.toMetadataTypeCode.trim() && typeof relation.toMetadataValueCode === "string" && relation.toMetadataValueCode.trim()
1737
+ );
1738
+ }
1739
+ function optionalCode(value) {
1740
+ if (value === void 0) {
1741
+ return void 0;
1742
+ }
1743
+ return value.trim();
1744
+ }
1312
1745
  var metadataPublishedPayloadSchema = z.object({
1313
1746
  changeRequestId: z.string().min(1),
1314
1747
  changeRevision: z.string().min(1).optional(),
@@ -1471,6 +1904,41 @@ var MetadataProjectionUnavailableError = class extends RuntimeMetadataError {
1471
1904
  this.name = "MetadataProjectionUnavailableError";
1472
1905
  }
1473
1906
  };
1907
+ var MetadataDiscoveryError = class extends RuntimeMetadataError {
1908
+ constructor(message, code = "METADATA_DISCOVERY_INVALID") {
1909
+ super(message, code === "METADATA_TYPE_INCOMPLETE" ? 503 : 400, code, void 0, {
1910
+ retryable: code === "METADATA_TYPE_INCOMPLETE"
1911
+ });
1912
+ this.name = "MetadataDiscoveryError";
1913
+ }
1914
+ };
1915
+ var MetadataFreshnessError = class extends RuntimeMetadataError {
1916
+ constructor(state, releaseId) {
1917
+ super(
1918
+ "Metadata projection does not meet the requested freshness policy",
1919
+ 409,
1920
+ "METADATA_FRESHNESS_NOT_SATISFIED",
1921
+ void 0,
1922
+ { retryable: true, metadata: { state, releaseId } }
1923
+ );
1924
+ this.name = "MetadataFreshnessError";
1925
+ }
1926
+ };
1927
+ var MetadataReleaseMismatchError = class extends RuntimeMetadataError {
1928
+ constructor(requestedReleaseId, actualReleaseId) {
1929
+ super(
1930
+ "Metadata projection release changed during the read",
1931
+ 409,
1932
+ "METADATA_RELEASE_MISMATCH",
1933
+ void 0,
1934
+ {
1935
+ retryable: true,
1936
+ metadata: { requestedReleaseId, actualReleaseId }
1937
+ }
1938
+ );
1939
+ this.name = "MetadataReleaseMismatchError";
1940
+ }
1941
+ };
1474
1942
  var InvalidMetadataReferenceError = class extends RuntimeMetadataError {
1475
1943
  constructor(reference, options) {
1476
1944
  super(
@@ -3427,6 +3895,41 @@ var MetadataHealthService = class {
3427
3895
  }
3428
3896
  };
3429
3897
 
3898
+ // ../../libs/runtime-metadata/src/lib/provider/MetadataDiscovery.ts
3899
+ var METADATA_READ_POLICY = {
3900
+ ALLOW_STALE: "ALLOW_STALE",
3901
+ REQUIRE_FRESH: "REQUIRE_FRESH"
3902
+ };
3903
+ var METADATA_RELATION_DIRECTION = {
3904
+ OUTGOING: "OUTGOING",
3905
+ INCOMING: "INCOMING"
3906
+ };
3907
+ var METADATA_ATTRIBUTE_FILTER_KEY = PUBLISHED_VALUE_ATTRIBUTE_FILTER_KEY;
3908
+ function supportsMetadataDiscovery(provider) {
3909
+ const candidate = provider;
3910
+ return typeof candidate.listValuesByType === "function" && typeof candidate.getRelationships === "function" && typeof candidate.listValuesByTypes === "function";
3911
+ }
3912
+ function isFreshProjectionState(state) {
3913
+ return state?.trim().toLowerCase() === "ready";
3914
+ }
3915
+ function assertMetadataReadPolicy(policy, state, releaseId) {
3916
+ const resolved = policy ?? METADATA_READ_POLICY.ALLOW_STALE;
3917
+ if (resolved !== METADATA_READ_POLICY.ALLOW_STALE && resolved !== METADATA_READ_POLICY.REQUIRE_FRESH) {
3918
+ throw new MetadataDiscoveryError("Unsupported metadata read policy");
3919
+ }
3920
+ if (resolved === METADATA_READ_POLICY.REQUIRE_FRESH && !isFreshProjectionState(state)) {
3921
+ throw new MetadataFreshnessError(state, releaseId);
3922
+ }
3923
+ }
3924
+ function assertReleasePin(requestedReleaseId, actualReleaseId) {
3925
+ if (requestedReleaseId && requestedReleaseId !== actualReleaseId) {
3926
+ throw new MetadataReleaseMismatchError(requestedReleaseId, actualReleaseId);
3927
+ }
3928
+ }
3929
+ function throwPublishedListFailure(failure) {
3930
+ throw new MetadataDiscoveryError(failure.message, failure.code);
3931
+ }
3932
+
3430
3933
  // ../../libs/runtime-metadata/src/lib/provider/MetadataProvider.ts
3431
3934
  function projectionEntryToMetadataValue(typeCode, valueCode, entry, locale) {
3432
3935
  return {
@@ -3460,6 +3963,7 @@ function metadataValueToReference(value) {
3460
3963
  // ../../libs/runtime-metadata/src/lib/provider/ExtensionMetadataProvider.ts
3461
3964
  var DEFAULT_READY_TIMEOUT_MS = 5e3;
3462
3965
  var DEFAULT_REQUEST_TIMEOUT_MS = 2e3;
3966
+ var RELATED_BATCH_LIMIT = 200;
3463
3967
  var ExtensionMetadataProvider = class {
3464
3968
  baseUrl;
3465
3969
  readyTimeoutMs;
@@ -3651,6 +4155,43 @@ var ExtensionMetadataProvider = class {
3651
4155
  throw err;
3652
4156
  }
3653
4157
  }
4158
+ async listValuesByType(typeCode, options) {
4159
+ await this.assertDiscoveryPolicy(options?.readPolicy);
4160
+ const body = await this.requestJson("GET", `/v1/metadata/types/${encodeURIComponent(typeCode)}/values${discoveryQuery(options)}`);
4161
+ return {
4162
+ releaseId: body.releaseId ?? null,
4163
+ items: Array.isArray(body.items) ? body.items : [],
4164
+ ...body.nextCursor ? { nextCursor: body.nextCursor } : {}
4165
+ };
4166
+ }
4167
+ async listValuesByTypes(typeCodes, options) {
4168
+ await this.assertDiscoveryPolicy(options?.readPolicy);
4169
+ const body = await this.requestJson(
4170
+ "POST",
4171
+ "/v1/metadata/types/values",
4172
+ {
4173
+ typeCodes,
4174
+ ...discoveryBody(options)
4175
+ }
4176
+ );
4177
+ return {
4178
+ releaseId: body.releaseId ?? null,
4179
+ types: Array.isArray(body.types) ? body.types : []
4180
+ };
4181
+ }
4182
+ async getRelationships(query) {
4183
+ await this.assertDiscoveryPolicy(query.readPolicy);
4184
+ const body = await this.requestJson(
4185
+ "POST",
4186
+ "/v1/metadata/relationships/query",
4187
+ query
4188
+ );
4189
+ return {
4190
+ releaseId: body.releaseId ?? null,
4191
+ supported: body.supported === true,
4192
+ relationships: Array.isArray(body.relationships) ? body.relationships : []
4193
+ };
4194
+ }
3654
4195
  async listRelations(query) {
3655
4196
  const params = new URLSearchParams();
3656
4197
  params.set("fromType", query.fromType);
@@ -3691,6 +4232,38 @@ var ExtensionMetadataProvider = class {
3691
4232
  throw err;
3692
4233
  }
3693
4234
  }
4235
+ async getRelatedValueGroups(sourceTypeCode, sourceValueCodes, targetTypeCode, options) {
4236
+ if (sourceValueCodes.length === 0) {
4237
+ return [];
4238
+ }
4239
+ const groups = [];
4240
+ try {
4241
+ for (let offset = 0; offset < sourceValueCodes.length; offset += RELATED_BATCH_LIMIT) {
4242
+ const sourceValues = sourceValueCodes.slice(offset, offset + RELATED_BATCH_LIMIT);
4243
+ const body = await this.requestJson("POST", "/v1/related/batch", {
4244
+ sourceType: sourceTypeCode,
4245
+ sourceValues,
4246
+ targetType: targetTypeCode,
4247
+ ...options?.locale ? { locale: options.locale } : {}
4248
+ });
4249
+ for (const group of body.groups ?? []) {
4250
+ groups.push({
4251
+ sourceValueCode: group.sourceValueCode ?? "",
4252
+ values: (group.items ?? []).map((item) => this.toMetadataValue(item, options?.locale)).filter((item) => item != null)
4253
+ });
4254
+ }
4255
+ }
4256
+ return groups;
4257
+ } catch (err) {
4258
+ if (isNotFound(err)) {
4259
+ throw new MetadataProjectionUnavailableError(
4260
+ "Extension related batch route is unavailable",
4261
+ { retryable: true, metadata: { path: "/v1/related/batch" } }
4262
+ );
4263
+ }
4264
+ throw err;
4265
+ }
4266
+ }
3694
4267
  async getLocalizationValue(keyOrTypeCode, valueCodeOrLocale, maybeLocale) {
3695
4268
  let key;
3696
4269
  let locale;
@@ -3765,6 +4338,13 @@ var ExtensionMetadataProvider = class {
3765
4338
  }
3766
4339
  };
3767
4340
  }
4341
+ async assertDiscoveryPolicy(readPolicy) {
4342
+ if (readPolicy !== "REQUIRE_FRESH") {
4343
+ return;
4344
+ }
4345
+ const status = await this.getStatus();
4346
+ assertMetadataReadPolicy(readPolicy, status.state, status.releaseId);
4347
+ }
3768
4348
  async requestJson(method, path, payload) {
3769
4349
  const started = Date.now();
3770
4350
  const controller = new AbortController();
@@ -3792,6 +4372,29 @@ var ExtensionMetadataProvider = class {
3792
4372
  if (!response.ok) {
3793
4373
  const errorBody = parsed;
3794
4374
  const code = errorBody.code ?? `HTTP_${response.status}`;
4375
+ if (code === "METADATA_UNKNOWN_TYPE") {
4376
+ throw new UnknownMetadataTypeError(
4377
+ errorBody.metadataType ?? "unknown"
4378
+ );
4379
+ }
4380
+ if (code === "METADATA_FRESHNESS_NOT_SATISFIED") {
4381
+ throw new MetadataFreshnessError(
4382
+ errorBody.state ?? "UNKNOWN",
4383
+ errorBody.releaseId ?? null
4384
+ );
4385
+ }
4386
+ if (code === "METADATA_RELEASE_MISMATCH") {
4387
+ throw new MetadataReleaseMismatchError(
4388
+ errorBody.requestedReleaseId ?? "",
4389
+ errorBody.actualReleaseId ?? errorBody.releaseId ?? null
4390
+ );
4391
+ }
4392
+ if (code === "METADATA_DISCOVERY_INVALID" || code === "METADATA_TYPE_INCOMPLETE") {
4393
+ throw new MetadataDiscoveryError(
4394
+ errorBody.message ?? "Metadata discovery request was rejected",
4395
+ code
4396
+ );
4397
+ }
3795
4398
  if (response.status === 404) {
3796
4399
  const err = new Error(errorBody.message ?? "not found");
3797
4400
  err.code = "RUNTIME_METADATA_NOT_FOUND";
@@ -3810,7 +4413,7 @@ var ExtensionMetadataProvider = class {
3810
4413
  }
3811
4414
  return parsed;
3812
4415
  } catch (err) {
3813
- if (err instanceof MetadataProjectionUnavailableError) {
4416
+ if (err instanceof MetadataProjectionUnavailableError || err instanceof UnknownMetadataTypeError || err instanceof MetadataFreshnessError || err instanceof MetadataReleaseMismatchError || err instanceof MetadataDiscoveryError) {
3814
4417
  throw err;
3815
4418
  }
3816
4419
  if (err.code === "RUNTIME_METADATA_NOT_FOUND") {
@@ -3872,6 +4475,66 @@ function correlationHeaders() {
3872
4475
  }
3873
4476
  return { "x-correlation-id": correlationId };
3874
4477
  }
4478
+ function discoveryQuery(options) {
4479
+ const params = new URLSearchParams();
4480
+ appendDiscoveryParams(params, options);
4481
+ const query = params.toString();
4482
+ return query ? `?${query}` : "";
4483
+ }
4484
+ function discoveryBody(options) {
4485
+ if (!options) {
4486
+ return {};
4487
+ }
4488
+ return {
4489
+ ...options.status !== void 0 ? { status: options.status } : {},
4490
+ ...options.limit !== void 0 ? { limit: options.limit } : {},
4491
+ ...options.sortBy ? { sortBy: options.sortBy } : {},
4492
+ ...options.sortDirection ? { sortDirection: options.sortDirection } : {},
4493
+ ...options.valueCode ? { valueCode: options.valueCode } : {},
4494
+ ...options.valueCodePrefix ? { valueCodePrefix: options.valueCodePrefix } : {},
4495
+ ...options.attributes ? { attributes: options.attributes } : {},
4496
+ ...options.releaseId ? { releaseId: options.releaseId } : {},
4497
+ ...options.readPolicy ? { readPolicy: options.readPolicy } : {}
4498
+ };
4499
+ }
4500
+ function appendDiscoveryParams(params, options) {
4501
+ if (!options) {
4502
+ return;
4503
+ }
4504
+ const statuses = options.status === void 0 ? [] : Array.isArray(options.status) ? options.status : [options.status];
4505
+ for (const status of statuses) {
4506
+ params.append("status", status);
4507
+ }
4508
+ if (options.limit !== void 0) {
4509
+ params.set("limit", String(options.limit));
4510
+ }
4511
+ if (options.cursor) {
4512
+ params.set("cursor", options.cursor);
4513
+ }
4514
+ if (options.sortBy) {
4515
+ params.set("sortBy", options.sortBy);
4516
+ }
4517
+ if (options.sortDirection) {
4518
+ params.set("sortDirection", options.sortDirection);
4519
+ }
4520
+ if (options.valueCode) {
4521
+ params.set("valueCode", options.valueCode);
4522
+ }
4523
+ if (options.valueCodePrefix) {
4524
+ params.set("valueCodePrefix", options.valueCodePrefix);
4525
+ }
4526
+ if (options.releaseId) {
4527
+ params.set("releaseId", options.releaseId);
4528
+ }
4529
+ if (options.readPolicy) {
4530
+ params.set("readPolicy", options.readPolicy);
4531
+ }
4532
+ for (const [key, value] of Object.entries(options.attributes ?? {})) {
4533
+ if (value) {
4534
+ params.set(`attribute.${key}`, value);
4535
+ }
4536
+ }
4537
+ }
3875
4538
  function sleep(ms) {
3876
4539
  return new Promise((resolve) => setTimeout(resolve, ms));
3877
4540
  }
@@ -4194,38 +4857,63 @@ var S3MetadataProvider = class {
4194
4857
  };
4195
4858
  }
4196
4859
  async getRelatedValues(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
4197
- await this.ensureTypesLoaded([sourceTypeCode, targetTypeCode]);
4198
- const index = this.cache.getRelationshipIndex();
4199
- const codes = relatedValueCodes(
4200
- index,
4860
+ const groups = await this.getRelatedValueGroups(
4201
4861
  sourceTypeCode,
4202
- sourceValueCode,
4203
- targetTypeCode
4862
+ [sourceValueCode],
4863
+ targetTypeCode,
4864
+ options
4204
4865
  );
4205
- if (codes.length === 0) {
4206
- const fallback = relatedValueCodesFromEntry(
4207
- this.resolver,
4866
+ const values = groups[0]?.values ?? [];
4867
+ this.logger.info({
4868
+ event: "runtimeMetadata.related.lookup",
4869
+ sourceTypeCode,
4870
+ sourceValueCode,
4871
+ targetTypeCode,
4872
+ count: values.length
4873
+ });
4874
+ return values;
4875
+ }
4876
+ async getRelatedValueGroups(sourceTypeCode, sourceValueCodes, targetTypeCode, options) {
4877
+ if (sourceValueCodes.length === 0) {
4878
+ return [];
4879
+ }
4880
+ await this.ensureTypesLoaded([sourceTypeCode, targetTypeCode]);
4881
+ const index = this.cache.getRelationshipIndex();
4882
+ const groups = [];
4883
+ for (const sourceValueCode of sourceValueCodes) {
4884
+ const codes = relatedValueCodes(
4885
+ index,
4208
4886
  sourceTypeCode,
4209
4887
  sourceValueCode,
4210
4888
  targetTypeCode
4211
4889
  );
4212
- codes.push(...fallback);
4213
- }
4214
- const values = [];
4215
- for (const valueCode of codes) {
4216
- const value = await this.getValue(targetTypeCode, valueCode, options);
4217
- if (value) {
4218
- values.push(value);
4890
+ if (codes.length === 0) {
4891
+ codes.push(
4892
+ ...relatedValueCodesFromEntry(
4893
+ this.resolver,
4894
+ sourceTypeCode,
4895
+ sourceValueCode,
4896
+ targetTypeCode
4897
+ )
4898
+ );
4219
4899
  }
4900
+ const values = [];
4901
+ for (const valueCode of codes) {
4902
+ const value = await this.getValue(targetTypeCode, valueCode, options);
4903
+ if (value) {
4904
+ values.push(value);
4905
+ }
4906
+ }
4907
+ groups.push({ sourceValueCode, values });
4220
4908
  }
4221
4909
  this.logger.info({
4222
- event: "runtimeMetadata.related.lookup",
4910
+ event: "runtimeMetadata.related.batch",
4223
4911
  sourceTypeCode,
4224
- sourceValueCode,
4225
4912
  targetTypeCode,
4226
- count: values.length
4913
+ sources: sourceValueCodes.length,
4914
+ count: groups.reduce((sum, group) => sum + group.values.length, 0)
4227
4915
  });
4228
- return values;
4916
+ return groups;
4229
4917
  }
4230
4918
  async listTypeValues(typeCode, options) {
4231
4919
  await this.ensureTypesLoaded([typeCode]);
@@ -4257,6 +4945,143 @@ var S3MetadataProvider = class {
4257
4945
  type: typeCatalogFromProjection(typeCode, file, this.cache.getCommon())
4258
4946
  };
4259
4947
  }
4948
+ async listValuesByType(typeCode, options) {
4949
+ const releaseId = await this.prepareDiscoveryRead(
4950
+ options?.readPolicy,
4951
+ options?.releaseId,
4952
+ [typeCode]
4953
+ );
4954
+ return this.listLoadedType(typeCode, releaseId, options);
4955
+ }
4956
+ async listValuesByTypes(typeCodes, options) {
4957
+ if (typeCodes.length === 0 || typeCodes.length > 25) {
4958
+ throw new MetadataDiscoveryError(
4959
+ "typeCodes must contain between 1 and 25 metadata types"
4960
+ );
4961
+ }
4962
+ const normalized = typeCodes.map((typeCode) => typeCode.trim());
4963
+ if (normalized.some((typeCode) => !typeCode) || new Set(normalized).size !== normalized.length) {
4964
+ throw new MetadataDiscoveryError("typeCodes must be unique non-empty strings");
4965
+ }
4966
+ const releaseId = await this.prepareDiscoveryRead(
4967
+ options?.readPolicy,
4968
+ options?.releaseId,
4969
+ normalized
4970
+ );
4971
+ const types = [];
4972
+ for (const typeCode of normalized) {
4973
+ if (!this.isKnownType(typeCode)) {
4974
+ types.push({ typeCode, found: false, items: [] });
4975
+ continue;
4976
+ }
4977
+ try {
4978
+ const listed = this.listLoadedType(typeCode, releaseId, options);
4979
+ types.push({
4980
+ typeCode,
4981
+ found: true,
4982
+ items: listed.items,
4983
+ ...listed.nextCursor ? { nextCursor: listed.nextCursor } : {}
4984
+ });
4985
+ } catch (err) {
4986
+ const code = err.code;
4987
+ if (code === "METADATA_TYPE_INCOMPLETE" || code === "METADATA_DISCOVERY_INVALID") {
4988
+ types.push({ typeCode, found: true, items: [], errorCode: code });
4989
+ continue;
4990
+ }
4991
+ throw err;
4992
+ }
4993
+ }
4994
+ return { releaseId, types };
4995
+ }
4996
+ async getRelationships(query) {
4997
+ const releaseId = await this.prepareDiscoveryRead(query.readPolicy, query.releaseId);
4998
+ const relations = this.cache.getTypedRelations();
4999
+ const listed = queryPublishedRelationships({
5000
+ supported: relations !== void 0,
5001
+ relations: relations ?? [],
5002
+ sourceTypeCode: query.sourceTypeCode,
5003
+ sourceValueCode: query.sourceValueCode,
5004
+ targetTypeCode: query.targetTypeCode,
5005
+ relationType: query.relationType,
5006
+ direction: query.direction
5007
+ });
5008
+ if (!listed.ok) {
5009
+ throwPublishedListFailure(listed);
5010
+ }
5011
+ return {
5012
+ releaseId,
5013
+ supported: listed.supported,
5014
+ relationships: listed.relationships
5015
+ };
5016
+ }
5017
+ async prepareDiscoveryRead(readPolicy, requestedReleaseId, typeCodes = []) {
5018
+ const status = await this.getStatus();
5019
+ assertMetadataReadPolicy(readPolicy, status.state, status.releaseId);
5020
+ assertReleasePin(requestedReleaseId, status.releaseId);
5021
+ const releaseBefore = this.cache.getReleaseId();
5022
+ if (typeCodes.length > 0) {
5023
+ await this.ensureTypesLoaded(typeCodes);
5024
+ }
5025
+ const releaseAfter = this.cache.getReleaseId();
5026
+ if (releaseBefore && releaseAfter && releaseBefore !== releaseAfter) {
5027
+ throw new MetadataReleaseMismatchError(releaseBefore, releaseAfter);
5028
+ }
5029
+ assertReleasePin(requestedReleaseId, releaseAfter);
5030
+ assertMetadataReadPolicy(readPolicy, this.cache.getStatus(), releaseAfter);
5031
+ return releaseAfter;
5032
+ }
5033
+ listLoadedType(typeCode, releaseId, options) {
5034
+ if (!this.isKnownType(typeCode)) {
5035
+ throw new UnknownMetadataTypeError(typeCode);
5036
+ }
5037
+ const file = this.cache.getDomainFile(typeCode);
5038
+ if (!file) {
5039
+ throw new MetadataDiscoveryError(
5040
+ `Metadata type ${typeCode} is not fully loaded`,
5041
+ "METADATA_TYPE_INCOMPLETE"
5042
+ );
5043
+ }
5044
+ if (!releaseId) {
5045
+ throw new MetadataDiscoveryError(
5046
+ "Metadata type listing requires a projection release",
5047
+ "METADATA_TYPE_INCOMPLETE"
5048
+ );
5049
+ }
5050
+ const extracted = entriesFromProjectionFile(file);
5051
+ if (!extracted.ok) {
5052
+ throwPublishedListFailure(extracted);
5053
+ }
5054
+ const listed = listPublishedValues(extracted.entries, {
5055
+ releaseId,
5056
+ status: options?.status,
5057
+ limit: options?.limit,
5058
+ cursor: options?.cursor,
5059
+ sortBy: options?.sortBy,
5060
+ sortDirection: options?.sortDirection,
5061
+ valueCode: options?.valueCode,
5062
+ valueCodePrefix: options?.valueCodePrefix,
5063
+ attributes: options?.attributes
5064
+ });
5065
+ if (!listed.ok) {
5066
+ throwPublishedListFailure(listed);
5067
+ }
5068
+ return {
5069
+ releaseId,
5070
+ items: listed.items,
5071
+ ...listed.nextCursor ? { nextCursor: listed.nextCursor } : {}
5072
+ };
5073
+ }
5074
+ isKnownType(typeCode) {
5075
+ if (this.cache.getDomainFile(typeCode)) {
5076
+ return true;
5077
+ }
5078
+ if (this.cache.getManifest()?.metadataTypes[typeCode]) {
5079
+ return true;
5080
+ }
5081
+ return Boolean(
5082
+ this.cache.getCommon()?.types.some((type) => type.metadataTypeCode === typeCode)
5083
+ );
5084
+ }
4260
5085
  };
4261
5086
  function relatedValueCodes(index, sourceTypeCode, sourceValueCode, targetTypeCode) {
4262
5087
  if (!index) {
@@ -4886,6 +5711,36 @@ var RuntimeMetadataService = class {
4886
5711
  throw err;
4887
5712
  }
4888
5713
  }
5714
+ async getRelatedValueGroups(sourceTypeCode, sourceValueCodes, targetTypeCode, options) {
5715
+ try {
5716
+ const provider = await this.activeProvider();
5717
+ const guard = this.currentWriteGuard();
5718
+ const groups = await provider.getRelatedValueGroups(
5719
+ sourceTypeCode,
5720
+ sourceValueCodes,
5721
+ targetTypeCode,
5722
+ options
5723
+ );
5724
+ this.hydrateProviderValues(
5725
+ groups.flatMap((group) => group.values),
5726
+ guard
5727
+ );
5728
+ return groups;
5729
+ } catch (err) {
5730
+ if (await this.tryActivateFallbackFromError(err, "extension-related")) {
5731
+ const fallback = this.metadataProviderFallback;
5732
+ if (fallback) {
5733
+ return fallback.getRelatedValueGroups(
5734
+ sourceTypeCode,
5735
+ sourceValueCodes,
5736
+ targetTypeCode,
5737
+ options
5738
+ );
5739
+ }
5740
+ }
5741
+ throw err;
5742
+ }
5743
+ }
4889
5744
  async listRelations(query) {
4890
5745
  try {
4891
5746
  const provider = await this.activeProvider();
@@ -4921,6 +5776,82 @@ var RuntimeMetadataService = class {
4921
5776
  throw err;
4922
5777
  }
4923
5778
  }
5779
+ /**
5780
+ * Capture one projection release for a catalogue built from several discovery calls.
5781
+ * Pass `releaseId` and `readPolicy` back on each call. A later call fails if the
5782
+ * extension has activated a different release. The extension keeps a single
5783
+ * snapshot, so a mismatched pin must be retried as a new session.
5784
+ */
5785
+ async beginMetadataRead(options) {
5786
+ const provider = await this.activeProvider();
5787
+ const status = await provider.getStatus();
5788
+ const readPolicy = options?.readPolicy ?? METADATA_READ_POLICY.ALLOW_STALE;
5789
+ try {
5790
+ assertMetadataReadPolicy(readPolicy, status.state, status.releaseId);
5791
+ } catch (err) {
5792
+ this.logFreshnessRejection(err);
5793
+ throw err;
5794
+ }
5795
+ if (!status.releaseId) {
5796
+ throw new MetadataProjectionUnavailableError(
5797
+ "Metadata projection release is unavailable"
5798
+ );
5799
+ }
5800
+ return { releaseId: status.releaseId, readPolicy };
5801
+ }
5802
+ async listValuesByType(typeCode, options) {
5803
+ const started = Date.now();
5804
+ const result = await this.withDiscoveryProvider(
5805
+ options?.readPolicy,
5806
+ (provider) => provider.listValuesByType(typeCode, options)
5807
+ );
5808
+ this.logger.info({
5809
+ event: RUNTIME_METADATA_EVENTS.TYPE_ENUMERATION,
5810
+ typeCode,
5811
+ releaseId: result.releaseId,
5812
+ itemCount: result.items.length,
5813
+ paged: Boolean(options?.limit),
5814
+ durationMs: Date.now() - started,
5815
+ transport: this.providerCoordinator.getActiveKind()
5816
+ });
5817
+ return result;
5818
+ }
5819
+ async listValuesByTypes(typeCodes, options) {
5820
+ const started = Date.now();
5821
+ const result = await this.withDiscoveryProvider(
5822
+ options?.readPolicy,
5823
+ (provider) => provider.listValuesByTypes(typeCodes, options)
5824
+ );
5825
+ this.logger.info({
5826
+ event: RUNTIME_METADATA_EVENTS.TYPE_BATCH_ENUMERATION,
5827
+ typeCount: typeCodes.length,
5828
+ releaseId: result.releaseId,
5829
+ failed: result.types.filter((type) => type.errorCode).length,
5830
+ unknown: result.types.filter((type) => !type.found).length,
5831
+ durationMs: Date.now() - started,
5832
+ transport: this.providerCoordinator.getActiveKind()
5833
+ });
5834
+ return result;
5835
+ }
5836
+ async getRelationships(query) {
5837
+ const started = Date.now();
5838
+ const result = await this.withDiscoveryProvider(
5839
+ query.readPolicy,
5840
+ (provider) => provider.getRelationships(query)
5841
+ );
5842
+ this.logger.info({
5843
+ event: RUNTIME_METADATA_EVENTS.RELATIONSHIP_QUERY,
5844
+ sourceTypeCode: query.sourceTypeCode,
5845
+ relationType: query.relationType,
5846
+ direction: query.direction ?? "OUTGOING",
5847
+ releaseId: result.releaseId,
5848
+ supported: result.supported,
5849
+ count: result.relationships.length,
5850
+ durationMs: Date.now() - started,
5851
+ transport: this.providerCoordinator.getActiveKind()
5852
+ });
5853
+ return result;
5854
+ }
4924
5855
  getActiveProviderKind() {
4925
5856
  return this.providerCoordinator.getActiveKind();
4926
5857
  }
@@ -5084,6 +6015,36 @@ var RuntimeMetadataService = class {
5084
6015
  { forceReset: true }
5085
6016
  );
5086
6017
  }
6018
+ async withDiscoveryProvider(readPolicy, run) {
6019
+ try {
6020
+ const provider = await this.activeProvider();
6021
+ if (!supportsMetadataDiscovery(provider)) {
6022
+ throw new MetadataDiscoveryError(
6023
+ "Active metadata provider does not support discovery"
6024
+ );
6025
+ }
6026
+ return await run(provider);
6027
+ } catch (err) {
6028
+ this.logFreshnessRejection(err);
6029
+ if (readPolicy !== METADATA_READ_POLICY.REQUIRE_FRESH && await this.tryActivateFallbackFromError(err, "extension-discovery")) {
6030
+ const fallback = this.metadataProviderFallback;
6031
+ if (fallback && supportsMetadataDiscovery(fallback)) {
6032
+ return run(fallback);
6033
+ }
6034
+ }
6035
+ throw err;
6036
+ }
6037
+ }
6038
+ logFreshnessRejection(err) {
6039
+ if (!(err instanceof MetadataFreshnessError)) {
6040
+ return;
6041
+ }
6042
+ this.logger.info({
6043
+ event: RUNTIME_METADATA_EVENTS.FRESHNESS_REJECTED,
6044
+ state: err.metadata?.state,
6045
+ releaseId: err.metadata?.releaseId
6046
+ });
6047
+ }
5087
6048
  async tryActivateFallbackFromError(err, reason) {
5088
6049
  if (!(err instanceof MetadataProjectionUnavailableError) || !this.metadataProviderFallback || !this.usesExtensionTransport()) {
5089
6050
  return false;
@@ -5209,10 +6170,16 @@ var InMemoryMetadataProvider = class {
5209
6170
  byKey = /* @__PURE__ */ new Map();
5210
6171
  related = /* @__PURE__ */ new Map();
5211
6172
  relations;
6173
+ knownTypeCodes = /* @__PURE__ */ new Set();
5212
6174
  constructor(options = {}) {
5213
6175
  this.releaseId = options.releaseId ?? "memory";
5214
6176
  this.unavailable = options.unavailable === true;
5215
6177
  this.relations = options.relations;
6178
+ for (const typeCode of options.knownTypeCodes ?? []) {
6179
+ if (typeCode.trim()) {
6180
+ this.knownTypeCodes.add(typeCode.trim());
6181
+ }
6182
+ }
5216
6183
  for (const record of options.records ?? []) {
5217
6184
  const key = formatMetadataReference(record.typeCode, record.valueCode);
5218
6185
  this.byKey.set(key, record);
@@ -5357,6 +6324,33 @@ var InMemoryMetadataProvider = class {
5357
6324
  { retryable: true }
5358
6325
  );
5359
6326
  }
6327
+ return this.relatedValuesFor(sourceTypeCode, sourceValueCode, targetTypeCode, options);
6328
+ }
6329
+ async getRelatedValueGroups(sourceTypeCode, sourceValueCodes, targetTypeCode, options) {
6330
+ if (this.unavailable) {
6331
+ throw new MetadataProjectionUnavailableError(
6332
+ "In-memory metadata provider is unavailable",
6333
+ { retryable: true }
6334
+ );
6335
+ }
6336
+ if (sourceValueCodes.length === 0) {
6337
+ return [];
6338
+ }
6339
+ const groups = [];
6340
+ for (const sourceValueCode of sourceValueCodes) {
6341
+ groups.push({
6342
+ sourceValueCode,
6343
+ values: await this.relatedValuesFor(
6344
+ sourceTypeCode,
6345
+ sourceValueCode,
6346
+ targetTypeCode,
6347
+ options
6348
+ )
6349
+ });
6350
+ }
6351
+ return groups;
6352
+ }
6353
+ async relatedValuesFor(sourceTypeCode, sourceValueCode, targetTypeCode, options) {
5360
6354
  const sourceKey = formatMetadataReference(sourceTypeCode, sourceValueCode);
5361
6355
  const targets = this.related.get(sourceKey)?.get(targetTypeCode) ?? [];
5362
6356
  const values = [];
@@ -5394,8 +6388,126 @@ var InMemoryMetadataProvider = class {
5394
6388
  type: null
5395
6389
  };
5396
6390
  }
6391
+ async listValuesByType(typeCode, options) {
6392
+ this.assertReadable(options?.readPolicy, options?.releaseId);
6393
+ return this.listOneType(typeCode, options);
6394
+ }
6395
+ async listValuesByTypes(typeCodes, options) {
6396
+ this.assertReadable(options?.readPolicy, options?.releaseId);
6397
+ if (typeCodes.length === 0 || typeCodes.length > 25) {
6398
+ throwPublishedListFailure({
6399
+ code: "METADATA_DISCOVERY_INVALID",
6400
+ message: "typeCodes must contain between 1 and 25 metadata types"
6401
+ });
6402
+ }
6403
+ const seen = /* @__PURE__ */ new Set();
6404
+ const types = [];
6405
+ for (const typeCode of typeCodes) {
6406
+ const normalized = typeCode.trim();
6407
+ if (!normalized || seen.has(normalized)) {
6408
+ throwPublishedListFailure({
6409
+ code: "METADATA_DISCOVERY_INVALID",
6410
+ message: "typeCodes must be unique non-empty strings"
6411
+ });
6412
+ }
6413
+ seen.add(normalized);
6414
+ if (!this.hasType(normalized)) {
6415
+ types.push({ typeCode: normalized, found: false, items: [] });
6416
+ continue;
6417
+ }
6418
+ try {
6419
+ const listed = this.listOneType(normalized, options);
6420
+ types.push({
6421
+ typeCode: normalized,
6422
+ found: true,
6423
+ items: listed.items,
6424
+ ...listed.nextCursor ? { nextCursor: listed.nextCursor } : {}
6425
+ });
6426
+ } catch (err) {
6427
+ const code = err.code;
6428
+ if (code === "METADATA_TYPE_INCOMPLETE" || code === "METADATA_DISCOVERY_INVALID") {
6429
+ types.push({
6430
+ typeCode: normalized,
6431
+ found: true,
6432
+ items: [],
6433
+ errorCode: code
6434
+ });
6435
+ continue;
6436
+ }
6437
+ throw err;
6438
+ }
6439
+ }
6440
+ return { releaseId: this.releaseId, types };
6441
+ }
6442
+ async getRelationships(query) {
6443
+ this.assertReadable(query.readPolicy, query.releaseId);
6444
+ const listed = queryPublishedRelationships({
6445
+ supported: this.relations !== void 0,
6446
+ relations: this.relations ?? [],
6447
+ sourceTypeCode: query.sourceTypeCode,
6448
+ sourceValueCode: query.sourceValueCode,
6449
+ targetTypeCode: query.targetTypeCode,
6450
+ relationType: query.relationType,
6451
+ direction: query.direction
6452
+ });
6453
+ if (!listed.ok) {
6454
+ throwPublishedListFailure(listed);
6455
+ }
6456
+ return {
6457
+ releaseId: this.releaseId,
6458
+ supported: listed.supported,
6459
+ relationships: listed.relationships
6460
+ };
6461
+ }
6462
+ listOneType(typeCode, options) {
6463
+ if (!this.hasType(typeCode)) {
6464
+ throw new UnknownMetadataTypeError(typeCode);
6465
+ }
6466
+ const entries = [...this.byKey.values()].filter((record) => record.typeCode === typeCode).map((record) => record.entry);
6467
+ const listed = listPublishedValues(entries, {
6468
+ releaseId: this.releaseId,
6469
+ status: options?.status,
6470
+ limit: options?.limit,
6471
+ cursor: options?.cursor,
6472
+ sortBy: options?.sortBy,
6473
+ sortDirection: options?.sortDirection,
6474
+ valueCode: options?.valueCode,
6475
+ valueCodePrefix: options?.valueCodePrefix,
6476
+ attributes: options?.attributes
6477
+ });
6478
+ if (!listed.ok) {
6479
+ throwPublishedListFailure(listed);
6480
+ }
6481
+ return {
6482
+ releaseId: this.releaseId,
6483
+ items: listed.items,
6484
+ ...listed.nextCursor ? { nextCursor: listed.nextCursor } : {}
6485
+ };
6486
+ }
6487
+ hasType(typeCode) {
6488
+ if (this.knownTypeCodes.has(typeCode)) {
6489
+ return true;
6490
+ }
6491
+ for (const record of this.byKey.values()) {
6492
+ if (record.typeCode === typeCode) {
6493
+ return true;
6494
+ }
6495
+ }
6496
+ return false;
6497
+ }
6498
+ assertReadable(readPolicy, releaseId) {
6499
+ if (this.unavailable) {
6500
+ throw new MetadataProjectionUnavailableError(
6501
+ "In-memory metadata provider is unavailable",
6502
+ { retryable: true }
6503
+ );
6504
+ }
6505
+ const state = this.forcedState ?? "READY";
6506
+ assertMetadataReadPolicy(readPolicy, state, this.releaseId);
6507
+ assertReleasePin(releaseId, this.releaseId);
6508
+ }
5397
6509
  };
5398
6510
 
5399
- 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 };
6511
+ export { CACHE_STATUS, DEFAULT_EXCLUDED_CODE_FIELDS, DEFAULT_PROVIDER_RECOVERY_COOLDOWN_MS, ExtensionMetadataProvider, InMemoryMetadataProvider, InvalidMetadataReferenceError, METADATA_ATTRIBUTE_FILTER_KEY, METADATA_PROJECTIONS_BUCKET_ENV, METADATA_PROVIDER_KIND, METADATA_READ_POLICY, METADATA_RELATION_DIRECTION, ManifestValidationError, MetadataCache, MetadataDiscoveryError, MetadataDownloader, MetadataFreshnessError, MetadataHealthService, MetadataLoader, MetadataLookupError, MetadataNotReadyError, MetadataProjectionUnavailableError, MetadataRefreshService, MetadataReleaseMismatchError, 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, assertMetadataReadPolicy, assertReleasePin, canonicalMetadataProjectionsBucketName, collectResponseReferences, collectResponseTypeCodes, createCodeFieldExclusionSet, createRuntimeMetadataFromEnv, defaultExtensionBaseUrl, ensureRuntimeMetadataLoaded, formatMetadataReference, getCandidateTypeCodesForKey, getRuntimeMetadataHealth, getRuntimeMetadataService, hasPotentialMetadata, isCompactMetadataReference, isExtensionEnabled, isExtensionServing, isFreshProjectionState, isMetadataProjectionConfigured, isMetadataProjectionsBucketConfigured, isMetadataReference, isMetadataValueObject, isMetadataValueObjectArray, isWorkflowStepRecord, isWorkflowStepRuleField, localizedLabelFromEntry, manifestLocalizationSchema, metadataGroupFromManifest, metadataValueToReference, normalizeRuntimeMetadataTypeCode, onMetadataProjectionCompleted, parseMetadataReference, projectionEntryToMetadataValue, projectionManifestSchema, readMetadataProjectionsBucket, readModelGroupsFromManifest, relatedValueCodes, resetRuntimeMetadataBootstrapState, resolveMetadataProjectionsBucket, resolveRuntimeMetadataConfig, runtimeMetadataConfigSchema, selectMetadataProvider, supportsMetadataDiscovery, throwPublishedListFailure, tryGetRuntimeMetadataService, tryParseMetadataReference, typeCodeFromCodeFieldName };
5400
6512
  //# sourceMappingURL=index.js.map
5401
6513
  //# sourceMappingURL=index.js.map