All files / src/mcp/imf sdmx.ts

77.31% Statements 75/97
57% Branches 61/107
90% Functions 18/20
80% Lines 64/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251                                              1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x                             1x 1x           1x                           4x 1x 4x 1x 1x 1x 4x 4x 4x                   23x 138x 23x 4x 4x 2x 2x 3x 2x     2x                   26x                           9x 25x   9x   27x 53x 27x                       8x         8x                                                                                   17x 17x 17x 4x   17x             13x       1x         2x   1x                                 12x 12x 23x 23x 3x 3x     20x       12x   9x 9x   12x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/imf/sdmx
 * @description SDMX 3.0 URL and structure utilities for the IMF SDMX client.
 */
 
import type { SDMXDimension, SDMXConceptScheme, SDMXDataStructureResponse } from './types.js';
import { IMF_DATAFLOW_AGENCY, DEFAULT_IMF_AGENCY } from './config.js';
 
/**
 * Parse an SDMX URN into its three salient parts:
 * agency (optional), id, and concept-id (only present for Concept URNs).
 * @param urn - SDMX URN string (e.g. `urn:sdmx:org.sdmx.infomodel.codelist.Codelist=IMF:CL_AREA(1.0)`).
 * @returns Object with `agency`, `id`, and `conceptId` (may be empty strings).
 * @internal
 */
export function parseSDMXUrn(urn: string): {
  agency: string;
  id: string;
  conceptId: string;
} {
  const eqIdx = urn.indexOf('=');
  const body = eqIdx >= 0 ? urn.slice(eqIdx + 1) : urn;
  const parenIdx = body.indexOf('(');
  const head = parenIdx >= 0 ? body.slice(0, parenIdx) : body;
  let tail = '';
  Eif (parenIdx >= 0) {
    const closeIdx = body.indexOf(')', parenIdx);
    Eif (closeIdx >= 0) tail = body.slice(closeIdx + 1);
  }
  const conceptId = tail.startsWith('.') ? tail.slice(1) : '';
  const colonIdx = head.indexOf(':');
  const agency = colonIdx >= 0 ? head.slice(0, colonIdx) : '';
  const id = colonIdx >= 0 ? head.slice(colonIdx + 1) : head;
  return { agency, id, conceptId };
}
 
/**
 * Resolve the codelist URN for a single dimension by walking the SDMX
 * 3.0 dimension → concept → codelist binding chain.
 * @param dim - SDMX dimension descriptor from the data-structure response.
 * @param conceptSchemes - Concept scheme array from the same response.
 * @returns Codelist URN string, or `undefined` when not found.
 * @internal
 */
export function resolveCodelistUrn(
  dim: SDMXDimension,
  conceptSchemes: readonly SDMXConceptScheme[]
): string | undefined {
  const direct = dim.localRepresentation?.enumeration;
  Eif (direct) return direct;
  if (!dim.conceptIdentity) return undefined;
  const { agency, id, conceptId } = parseSDMXUrn(dim.conceptIdentity);
  if (!conceptId) return undefined;
  const cs = conceptSchemes.find((s) => s.id === id && (agency === '' || s.agencyID === agency));
  const concept = cs?.concepts?.find((c) => c.id === conceptId);
  return concept?.coreRepresentation?.enumeration;
}
 
/**
 * Resolve the actual list of codes for a single dimension.
 * @param dim - SDMX dimension descriptor.
 * @param payload - The `data` section of the SDMX data-structure response.
 * @returns Array of code objects with `id` and optional `name`.
 * @internal
 */
export function resolveCodelistCodes(
  dim: SDMXDimension,
  payload: NonNullable<SDMXDataStructureResponse['data']>
): readonly { id: string; name?: string | Record<string, string> }[] {
  if (dim.values && dim.values.length > 0) return dim.values;
  const urn = resolveCodelistUrn(dim, payload.conceptSchemes ?? []);
  Iif (!urn) return [];
  const { agency, id } = parseSDMXUrn(urn);
  Iif (!id) return [];
  const cls = payload.codelists ?? [];
  const exact = cls.find((c) => c.id === id && (!agency || c.agencyID === agency));
  const cl = exact ?? cls.find((c) => c.id === id);
  return cl?.codes ?? [];
}
 
/**
 * Resolve the SDMX agency for a dataflow.
 * @param databaseId - IMF dataflow identifier (e.g. `"WEO"`, `"IFS"`).
 * @returns SDMX agency string (e.g. `"IMF"`, `"OECD.SDD.STES"`).
 * @internal
 */
export function resolveAgency(databaseId: string): string {
  const upper = databaseId.toUpperCase();
  const direct = Object.entries(IMF_DATAFLOW_AGENCY).find(([k]) => k === upper)?.[1];
  if (direct) return direct;
  const vintageIdx = upper.indexOf('_VINTAGE');
  if (vintageIdx > 0) {
    const baseId = upper.slice(0, vintageIdx);
    Eif (baseId) {
      const fromBase = Object.entries(IMF_DATAFLOW_AGENCY).find(([k]) => k === baseId)?.[1];
      Eif (fromBase) return fromBase;
    }
  }
  return DEFAULT_IMF_AGENCY;
}
 
/**
 * Simple value-encoder for SDMX URL dimension components.
 * @param codes - Array of dimension code strings to encode.
 * @returns URL-encoded codes joined with `+`.
 * @internal
 */
export function encodeSDMXDimension(codes: readonly string[]): string {
  return codes.map((c) => encodeURIComponent(c)).join('+');
}
 
/**
 * Build an SDMX key from a filters map + declared dimension order.
 * @param dimensions - Ordered list of dimension names for the dataflow.
 * @param filters - Map from dimension name to array of filter codes.
 * @returns SDMX key string (dot-separated, `*` for unfiltered dimensions).
 * @internal
 */
export function buildSDMXKey(
  dimensions: readonly string[],
  filters: Readonly<Record<string, readonly string[]>>
): string {
  const lowercasedFilters = Object.entries(filters).map(
    ([key, value]) => [key.toLowerCase(), value] as const
  );
  return dimensions
    .map((dim) => {
      const dimLc = dim.toLowerCase();
      const codes = lowercasedFilters.find(([key]) => key === dimLc)?.[1];
      return Array.isArray(codes) && codes.length > 0 ? encodeSDMXDimension(codes) : '*';
    })
    .join('.');
}
 
/**
 * Infer the dimension order for a given dataflow.
 * @param databaseId - IMF dataflow identifier (e.g. `"WEO"`, `"CPI"`).
 * @returns Ordered array of dimension name strings.
 * @internal
 */
export function defaultDimensionOrder(databaseId: string): readonly string[] {
  switch (databaseId.toUpperCase()) {
    case 'WEO':
    case 'FM':
    case 'IFS':
    case 'BOP_AGG':
      return ['COUNTRY', 'INDICATOR', 'FREQUENCY'];
    case 'CPI':
    case 'CPI_WCA':
      return ['COUNTRY', 'INDEX_TYPE', 'COICOP_1999', 'TYPE_OF_TRANSFORMATION', 'FREQUENCY'];
    case 'BOP':
      return ['COUNTRY', 'BOP_ACCOUNTING_ENTRY', 'INDICATOR', 'UNIT', 'FREQUENCY'];
    case 'ER':
      return ['COUNTRY', 'INDICATOR', 'TYPE_OF_TRANSFORMATION', 'FREQUENCY'];
    case 'PCPS':
      return ['COUNTRY', 'INDICATOR', 'DATA_TRANSFORMATION', 'FREQUENCY'];
    case 'DOT':
      return ['COUNTRY', 'COUNTERPART_AREA', 'INDICATOR', 'FREQUENCY'];
    case 'CDIS':
      return ['COUNTRY', 'COUNTERPART_AREA', 'SECTOR', 'INDICATOR', 'FREQUENCY'];
    case 'CPIS':
      return ['COUNTRY', 'COUNTERPART_AREA', 'INSTRUMENT', 'INDICATOR', 'FREQUENCY'];
    case 'FSI':
      return ['COUNTRY', 'INDICATOR', 'SECTOR', 'FREQUENCY'];
    case 'GFSR':
      return ['COUNTRY', 'INDICATOR', 'SECTOR', 'FREQUENCY'];
    case 'GFS':
    case 'GFS_SOO':
    case 'GFS_BS':
    case 'GFS_COFOG':
    case 'GFS_SSUC':
    case 'GFS_SOEF':
    case 'GFS_SFCP':
      return ['COUNTRY', 'SECTOR', 'UNIT', 'INDICATOR', 'FREQUENCY'];
    default:
      return ['COUNTRY', 'INDICATOR', 'FREQUENCY'];
  }
}
 
/**
 * Infer the natural frequency for IMF dataflows whose editorial use is stable.
 * @param databaseId - IMF dataflow identifier.
 * @returns SDMX frequency code (`"A"`, `"Q"`, `"M"`) or `undefined` when dataflow-specific default is unknown.
 * @internal
 */
export function defaultFrequency(databaseId: string): string | undefined {
  // Normalize vintage dataflows (e.g. WEO_VINTAGE_2026_04 → WEO) so they
  // inherit the same default frequency as their base dataflow.
  let normalized = databaseId.toUpperCase();
  const vintageIdx = normalized.indexOf('_VINTAGE');
  if (vintageIdx > 0) {
    normalized = normalized.slice(0, vintageIdx);
  }
  switch (normalized) {
    case 'WEO':
    case 'FM':
    case 'DOT':
    case 'CDIS':
    case 'CPIS':
    case 'GFSR':
      return 'A';
    case 'BOP_AGG':
    case 'FSI':
    case 'GFS':
      return 'Q';
    case 'IFS':
    case 'CPI':
    case 'ER':
    case 'PCPS':
      return 'M';
    default:
      return undefined;
  }
}
 
/**
 * Add a dataflow-specific default frequency when the caller omitted one,
 * and normalise the legacy `freq` alias to the SDMX 3.0 `FREQUENCY` dimension name.
 * @param databaseId - IMF dataflow identifier used to look up the default frequency.
 * @param filters - Caller-supplied dimension filter map (may include `freq` or `FREQUENCY`).
 * @returns Normalised filter map with `FREQUENCY` populated if it was absent.
 * @internal
 */
export function withDefaultFrequency(
  databaseId: string,
  filters: Readonly<Record<string, readonly string[]>>
): Readonly<Record<string, readonly string[]>> {
  let freqCodes: readonly string[] | undefined;
  const passthrough: Record<string, readonly string[]> = {};
  for (const [key, value] of Object.entries(filters)) {
    const k = key.toLowerCase();
    if (k === 'frequency' || k === 'freq') {
      Eif (Array.isArray(value) && value.length > 0 && freqCodes === undefined) {
        freqCodes = value;
      }
    } else {
      passthrough[key] = value;
    }
  }
  const fallback =
    freqCodes ??
    (() => {
      const f = defaultFrequency(databaseId);
      return f ? [f] : undefined;
    })();
  return fallback ? { ...passthrough, FREQUENCY: fallback } : filters;
}