@jadelclemens/pi-model-map 0.0.0-stage → 0.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/src/log.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { appendFileSync, mkdirSync, statSync, truncateSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { CONFIG_DIR_NAME, LOG_FILE_NAME, LOG_MAX_BYTES } from "./constants.js";
6
+
7
+ const WARN_PREFIX = "[pi-model-map]";
8
+
9
+ /** Always `~/.pi/agent/model-map/pi-model-map.log`, even when config was loaded from a project-local directory. */
10
+ export const logFilePath = (): string =>
11
+ path.join(os.homedir(), ".pi", "agent", CONFIG_DIR_NAME, LOG_FILE_NAME);
12
+
13
+ const appendLog = (message: string): void => {
14
+ const file = logFilePath();
15
+ const line = `${new Date().toISOString()} ${message}\n`;
16
+ try {
17
+ mkdirSync(path.dirname(file), { recursive: true });
18
+ let size = 0;
19
+ try {
20
+ size = statSync(file).size;
21
+ } catch {
22
+ size = 0;
23
+ }
24
+ if (size > LOG_MAX_BYTES) truncateSync(file, 0);
25
+ appendFileSync(file, line);
26
+ } catch {
27
+ /* best-effort — logging must never break startup or a turn */
28
+ }
29
+ };
30
+
31
+ /** Persist a warning to the plugin log and echo it to stderr (TUI startup output is ephemeral). */
32
+ export const pluginWarn = (message: string): void => {
33
+ const line = message.startsWith(WARN_PREFIX) ? message : `${WARN_PREFIX} ${message}`;
34
+ console.warn(line);
35
+ appendLog(line);
36
+ };
package/src/mapping.ts ADDED
@@ -0,0 +1,457 @@
1
+ import type { Api, ThinkingLevel } from "@earendil-works/pi-ai";
2
+
3
+ export interface BackendRef {
4
+ provider: string;
5
+ id: string;
6
+ }
7
+
8
+ /**
9
+ * The four backend variants a single effort level can resolve to, depending on the
10
+ * /pi-model-map-thinking and /pi-model-map-fast toggles.
11
+ *
12
+ * These toggles exist only because some providers (e.g. Cursor) bake extended-thinking
13
+ * mode and a "fast" routing tier into the model ID string instead of exposing them as
14
+ * request parameters. pi-model-map does not add or emulate those parameters itself —
15
+ * it only picks which pre-baked backend model ID to send for a given combination.
16
+ *
17
+ * JSON keys use "default" and "thinking-fast" (hyphenated) to match this project's other
18
+ * naming conventions; they're addressed internally as `default` and `thinkingFast`.
19
+ *
20
+ * - `default` — thinking off, fast off.
21
+ * - `thinking` — thinking on, fast off.
22
+ * - `fast` — thinking off, fast on.
23
+ * - `thinking-fast` — thinking on, fast on.
24
+ *
25
+ * At least one key is required, but `default` is not mandatory: some effort levels have no
26
+ * non-thinking backend at all (e.g. a model whose highest effort tiers only exist in
27
+ * extended-thinking form). When the requested combination isn't configured, pi-model-map falls
28
+ * back to whichever configured variant honors the most of what was actually requested (e.g. if
29
+ * only `thinking`/`thinking-fast` exist and `/pi-model-map-fast` alone was requested,
30
+ * `thinking-fast` is used rather than plain `thinking`, since it also honors the fast request);
31
+ * see `resolveVariant()` in this file for the exact scoring.
32
+ */
33
+ export interface VariantRefs {
34
+ default?: string;
35
+ thinking?: string;
36
+ fast?: string;
37
+ "thinking-fast"?: string;
38
+ }
39
+
40
+ /** One effort level's mapping: either a bare "provider/modelId" (= default only) or full variants. */
41
+ export type LevelMapping = string | VariantRefs;
42
+
43
+ /** Effort level -> LevelMapping. */
44
+ export type EffortMap = Record<string, LevelMapping>;
45
+
46
+ /** Internal variant key (camelCase for JS object/field ergonomics). */
47
+ export type Variant = "default" | "thinking" | "fast" | "thinkingFast";
48
+
49
+ /** Maps internal Variant keys to their JSON representation in VariantRefs. */
50
+ const VARIANT_JSON_KEYS: Record<Variant, keyof VariantRefs> = {
51
+ default: "default",
52
+ thinking: "thinking",
53
+ fast: "fast",
54
+ thinkingFast: "thinking-fast",
55
+ };
56
+
57
+ export interface MappingEntry {
58
+ name?: string;
59
+ reasoning?: boolean;
60
+ /**
61
+ * Whether Pi's "off" thinking level (no reasoning param sent at all) is meaningful for this
62
+ * family. Defaults to an automatic check: if this family's "default" map level's `default`
63
+ * variant resolves to the exact same backend reference as one of its own named effort levels
64
+ * (e.g. "default" is simply aliased to "medium" because the provider has no true no-reasoning
65
+ * variant for this family), pi-model-map infers `false` and hides "off" from Pi's /thinking
66
+ * picker entirely (`thinkingLevelMap.off = null`) rather than implying "no deeper thinking"
67
+ * when the backend actually always reasons at some level. Set explicitly to override the
68
+ * automatic check either way.
69
+ */
70
+ offSupported?: boolean;
71
+ contextWindow?: number;
72
+ maxTokens?: number;
73
+ input?: ("text" | "image")[];
74
+ cost?: {
75
+ input: number;
76
+ output: number;
77
+ cacheRead: number;
78
+ cacheWrite: number;
79
+ };
80
+ /** Effort level -> backend reference(s). Required. */
81
+ map: EffortMap;
82
+ }
83
+
84
+ export interface ModelMapConfig {
85
+ provider?: string;
86
+ /** Display name in Pi's provider UI. Defaults to provider id. */
87
+ name?: string;
88
+ /** Catalog metadata for registered models. */
89
+ api?: Api;
90
+ /** Catalog metadata for registered models. Defaults to empty string. */
91
+ baseUrl?: string;
92
+ /**
93
+ * Path to a JSON file describing the delegate provider's live model catalog (e.g. a cache file
94
+ * the delegate extension itself maintains). When set, pi-model-map warns at config-load time
95
+ * (and via `/pi-model-map-check-source`) about any backend id referenced in `mappings` that is
96
+ * no longer present in this file -- a sign the provider renamed or retired that model.
97
+ *
98
+ * Resolved relative to this config file's own directory if not absolute; a leading "~" expands
99
+ * to the home directory. There is no built-in assumption about *which* provider or file format
100
+ * this points to -- every provider's catalog cache looks different (this started from Cursor's
101
+ * `~/.pi/agent/cache/pi-cursor-agent/models.json`, but nothing here is Cursor-specific). Use
102
+ * `sourceListPath` / `sourceIdField` to describe the shape of whatever file you point this at.
103
+ */
104
+ source?: string;
105
+ /**
106
+ * Dot-path to the array of catalog entries within the parsed `source` JSON (e.g. "models" for
107
+ * Cursor's `{ "models": [...] }` cache shape). Omit if the JSON's root value is already that
108
+ * array.
109
+ */
110
+ sourceListPath?: string;
111
+ /**
112
+ * Field name holding each entry's raw model id, when `source` list entries are objects rather
113
+ * than bare strings. Defaults to "modelId" (Cursor's cache format). Ignored for entries that
114
+ * are already bare strings.
115
+ */
116
+ sourceIdField?: string;
117
+ /** Canonical model id -> mapping entry (metadata + effort-level map). */
118
+ mappings: Record<string, MappingEntry>;
119
+ }
120
+
121
+ /**
122
+ * Every selectable Pi thinking level, excluding "off" (which corresponds to this project's
123
+ * "default" map key, not a ThinkingLevel). Exported so catalog.ts can build a complete
124
+ * `thinkingLevelMap` — Pi treats an *omitted* key differently from an explicit `null` for
125
+ * standard levels (minimal..high default to "supported" when omitted), so every level a
126
+ * family doesn't map must be set to `null` explicitly, not left out. See models.md's
127
+ * "Thinking Level Map" section.
128
+ */
129
+ export const EFFORT_LEVELS = [
130
+ "minimal",
131
+ "low",
132
+ "medium",
133
+ "high",
134
+ "xhigh",
135
+ "max",
136
+ ] as const satisfies readonly ThinkingLevel[];
137
+
138
+ const VARIANT_KEYS: readonly Variant[] = ["default", "thinking", "fast", "thinkingFast"];
139
+
140
+ /** Which of the two independent toggle axes ("thinking", "fast") each Variant corresponds to. */
141
+ const VARIANT_BITS: Record<Variant, { thinking: boolean; fast: boolean }> = {
142
+ default: { thinking: false, fast: false },
143
+ thinking: { thinking: true, fast: false },
144
+ fast: { thinking: false, fast: true },
145
+ thinkingFast: { thinking: true, fast: true },
146
+ };
147
+
148
+ /**
149
+ * Resolve a variant from a level's parsed refs, falling back to whichever *configured* variant
150
+ * best honors the requested thinking/fast toggle state when the exact combination isn't present.
151
+ *
152
+ * Each configured candidate is scored: +1 for each requested toggle it actually satisfies, -1 for
153
+ * each toggle it forces on that wasn't requested. The highest-scoring configured candidate wins.
154
+ * This is deliberately symmetric across both axes -- e.g. if a level only has "thinking" and
155
+ * "thinking-fast" configured (no "default"/"fast" at all, as with some providers' highest effort
156
+ * tiers) and only the "fast" toggle was requested, "thinking-fast" scores higher than "thinking"
157
+ * because it honors the requested fast toggle too, even though both force thinking on regardless.
158
+ * Ties (both toggles' request-satisfaction identical) prefer satisfying "thinking" over "fast",
159
+ * matching this project's other thinking-first conventions; remaining ties fall back to
160
+ * declaration order (default, thinking, fast, thinking-fast) for full determinism.
161
+ *
162
+ * Returns undefined only if the level has no variants at all (should not happen post-parse,
163
+ * since every level requires at least one variant).
164
+ */
165
+ const resolveVariant = (
166
+ refs: Partial<Record<Variant, BackendRef>> | undefined,
167
+ variant: Variant,
168
+ ): BackendRef | undefined => {
169
+ if (!refs) return undefined;
170
+ const requested = VARIANT_BITS[variant];
171
+
172
+ let best: { candidate: Variant; score: number; thinkingMatch: number } | undefined;
173
+ for (const candidate of VARIANT_KEYS) {
174
+ if (!refs[candidate]) continue;
175
+ const bits = VARIANT_BITS[candidate];
176
+ const thinkingMatch = requested.thinking && bits.thinking ? 1 : 0;
177
+ const fastMatch = requested.fast && bits.fast ? 1 : 0;
178
+ const thinkingPenalty = !requested.thinking && bits.thinking ? 1 : 0;
179
+ const fastPenalty = !requested.fast && bits.fast ? 1 : 0;
180
+ const score = thinkingMatch + fastMatch - thinkingPenalty - fastPenalty;
181
+ if (!best || score > best.score || (score === best.score && thinkingMatch > best.thinkingMatch)) {
182
+ best = { candidate, score, thinkingMatch };
183
+ }
184
+ }
185
+ return best ? refs[best.candidate] : undefined;
186
+ };
187
+
188
+ const parseBackendRef = (
189
+ value: string,
190
+ canonicalId: string,
191
+ level: string,
192
+ variant: Variant,
193
+ source: string,
194
+ ): BackendRef => {
195
+ const slashIndex = value.indexOf("/");
196
+ if (slashIndex <= 0 || slashIndex === value.length - 1) {
197
+ const jsonKey = VARIANT_JSON_KEYS[variant];
198
+ const path =
199
+ variant === "default"
200
+ ? `mappings.${canonicalId}.map.${level}`
201
+ : `mappings.${canonicalId}.map.${level}.${jsonKey}`;
202
+ throw new Error(
203
+ `${source}: ${path} = "${value}" must be "provider/modelId" ` +
204
+ `(e.g. "cursor-agent/claude-opus-4-8-thinking-high").`,
205
+ );
206
+ }
207
+ return {
208
+ provider: value.slice(0, slashIndex),
209
+ id: value.slice(slashIndex + 1),
210
+ };
211
+ };
212
+
213
+ const normalizeLevelMapping = (value: LevelMapping): Partial<Record<Variant, string>> => {
214
+ if (typeof value === "string") {
215
+ return { default: value };
216
+ }
217
+ const out: Partial<Record<Variant, string>> = {};
218
+ for (const key of VARIANT_KEYS) {
219
+ const v = value[VARIANT_JSON_KEYS[key]];
220
+ if (v) out[key] = v;
221
+ }
222
+ return out;
223
+ };
224
+
225
+ export class ModelMapper {
226
+ readonly source: string;
227
+ readonly provider: string;
228
+ readonly displayName: string;
229
+ readonly api: Api;
230
+ readonly baseUrl: string;
231
+ /** Raw `source`/`sourceListPath`/`sourceIdField` config, or undefined if `source` was omitted. */
232
+ readonly catalogSource?: { path: string; listPath?: string; idField: string };
233
+ private readonly mappings: Record<string, MappingEntry>;
234
+ /** canonicalId -> effort level -> variant -> BackendRef */
235
+ private readonly parsedMap = new Map<string, Map<string, Partial<Record<Variant, BackendRef>>>>();
236
+ private readonly delegateProviders = new Set<string>();
237
+ /** canonicalId -> distinct delegate providers referenced anywhere in that family's own map. */
238
+ private readonly providersByFamily = new Map<string, Set<string>>();
239
+ /** canonicalId -> whether any level provides a "thinking" variant. */
240
+ private readonly hasThinkingVariant = new Set<string>();
241
+ /** canonicalId -> whether any level provides a "fast" variant. */
242
+ private readonly hasFastVariant = new Set<string>();
243
+ /** raw backend id -> human-readable location(s) it's referenced at, e.g. "claude-opus-5.map.high.thinking". */
244
+ private readonly backendIdLocations = new Map<string, string[]>();
245
+
246
+ constructor(config: ModelMapConfig, source: string, providerDefault?: string) {
247
+ this.source = source;
248
+ this.provider = config.provider ?? providerDefault ?? "model-map";
249
+ this.displayName = config.name ?? this.provider;
250
+ this.api = (config.api ?? "openai-completions") as Api;
251
+ this.baseUrl = config.baseUrl ?? "";
252
+ this.catalogSource = config.source
253
+ ? { path: config.source, listPath: config.sourceListPath, idField: config.sourceIdField ?? "modelId" }
254
+ : undefined;
255
+ this.mappings = config.mappings;
256
+ this.buildIndexes();
257
+ }
258
+
259
+ private buildIndexes(): void {
260
+ for (const [canonicalId, entry] of Object.entries(this.mappings)) {
261
+ if (!entry.map || typeof entry.map !== "object") {
262
+ throw new Error(`${this.source}: mappings.${canonicalId} is missing required "map"`);
263
+ }
264
+ const levelMap = new Map<string, Partial<Record<Variant, BackendRef>>>();
265
+ const familyProviders = new Set<string>();
266
+ for (const [level, rawValue] of Object.entries(entry.map)) {
267
+ const normalized = normalizeLevelMapping(rawValue);
268
+ if (Object.keys(normalized).length === 0) {
269
+ throw new Error(
270
+ `${this.source}: mappings.${canonicalId}.map.${level} must define at least one of ` +
271
+ `"default", "thinking", "fast", "thinking-fast"`,
272
+ );
273
+ }
274
+ const refs: Partial<Record<Variant, BackendRef>> = {};
275
+ for (const variant of VARIANT_KEYS) {
276
+ const value = normalized[variant];
277
+ if (!value) continue;
278
+ const ref = parseBackendRef(value, canonicalId, level, variant, this.source);
279
+ refs[variant] = ref;
280
+ this.delegateProviders.add(ref.provider);
281
+ familyProviders.add(ref.provider);
282
+ const jsonKey = VARIANT_JSON_KEYS[variant];
283
+ const location =
284
+ variant === "default"
285
+ ? `mappings.${canonicalId}.map.${level}`
286
+ : `mappings.${canonicalId}.map.${level}.${jsonKey}`;
287
+ const locations = this.backendIdLocations.get(ref.id);
288
+ if (locations) {
289
+ locations.push(location);
290
+ } else {
291
+ this.backendIdLocations.set(ref.id, [location]);
292
+ }
293
+ if (variant === "thinking" || variant === "thinkingFast") {
294
+ this.hasThinkingVariant.add(canonicalId);
295
+ }
296
+ if (variant === "fast" || variant === "thinkingFast") {
297
+ this.hasFastVariant.add(canonicalId);
298
+ }
299
+ }
300
+ levelMap.set(level, refs);
301
+ }
302
+ this.parsedMap.set(canonicalId, levelMap);
303
+ this.providersByFamily.set(canonicalId, familyProviders);
304
+ }
305
+ }
306
+
307
+ getCanonicalFamilies(): string[] {
308
+ return Object.keys(this.mappings);
309
+ }
310
+
311
+ /** All distinct delegate providers referenced across every mapping/level/variant. */
312
+ getDelegateProviders(): string[] {
313
+ return [...this.delegateProviders];
314
+ }
315
+
316
+ /**
317
+ * Distinct delegate providers referenced within a single canonical family's own map (across
318
+ * all its effort levels and thinking/fast variants). Used to detect a family whose levels or
319
+ * variants are split across more than one real provider — out of scope for pi-model-map
320
+ * (see `warnings.ts`); each mapping is meant to describe one canonical model backed by one
321
+ * delegate provider, with "provider/modelId" syntax used only for explicitness, not fan-out.
322
+ */
323
+ getFamilyDelegateProviders(canonicalId: string): string[] {
324
+ return [...(this.providersByFamily.get(canonicalId) ?? [])];
325
+ }
326
+
327
+ /** Whether any effort level of this family defines a "thinking" or "thinkingFast" variant. */
328
+ supportsThinkingToggle(canonicalId: string): boolean {
329
+ return this.hasThinkingVariant.has(canonicalId);
330
+ }
331
+
332
+ /** Whether any effort level of this family defines a "fast" or "thinkingFast" variant. */
333
+ supportsFastToggle(canonicalId: string): boolean {
334
+ return this.hasFastVariant.has(canonicalId);
335
+ }
336
+
337
+ /**
338
+ * Resolve a canonical id + effort level + thinking/fast toggles to a backend reference.
339
+ *
340
+ * Falls back in this order when the requested variant is not configured:
341
+ * thinking-fast -> thinking or fast (whichever axis is still requested) -> default
342
+ * Falls back to the "default" level's resolved ref when the requested level is absent.
343
+ */
344
+ toBackendRef(
345
+ canonicalId: string,
346
+ reasoning?: ThinkingLevel,
347
+ thinking = false,
348
+ fast = false,
349
+ ): BackendRef | undefined {
350
+ const levelMap = this.parsedMap.get(canonicalId);
351
+ if (!levelMap) {
352
+ return undefined;
353
+ }
354
+ const level = reasoning && levelMap.has(reasoning) ? reasoning : "default";
355
+ const refs = levelMap.get(level) ?? levelMap.get("default");
356
+ if (!refs) {
357
+ return undefined;
358
+ }
359
+
360
+ const variant: Variant = thinking && fast ? "thinkingFast" : thinking ? "thinking" : fast ? "fast" : "default";
361
+
362
+ return resolveVariant(refs, variant);
363
+ }
364
+
365
+ /** The `map` key `toBackendRef` actually resolves to for a given effort level (falls back to "default" the same way `toBackendRef` does). */
366
+ resolvedLevel(canonicalId: string, reasoning?: ThinkingLevel): string {
367
+ const levelMap = this.parsedMap.get(canonicalId);
368
+ if (!levelMap) return "default";
369
+ return reasoning && levelMap.has(reasoning) ? reasoning : "default";
370
+ }
371
+
372
+ /**
373
+ * Whether `canonicalId`'s `level` has no non-thinking variant at all (only "thinking" and/or
374
+ * "thinking-fast" keys) -- meaning `toBackendRef` will always resolve to a thinking backend for
375
+ * this level regardless of the `/pi-model-map-thinking` toggle's actual state, because there's
376
+ * nothing else to fall back to. Used to warn instead of silently overriding the toggle.
377
+ */
378
+ isThinkingOnlyLevel(canonicalId: string, level: string): boolean {
379
+ const refs = this.parsedMap.get(canonicalId)?.get(level);
380
+ if (!refs) return false;
381
+ return !refs.default && !refs.fast && (!!refs.thinking || !!refs.thinkingFast);
382
+ }
383
+
384
+ /**
385
+ * Whether `level` has no entry at all in `canonicalId`'s map -- meaning `toBackendRef` /
386
+ * `resolvedLevel` silently fall through to the "default" map level instead of resolving
387
+ * `level` itself. Used to warn instead of silently substituting a different effort level
388
+ * than the one actually requested (e.g. a caller -- possibly another extension, like a
389
+ * roundrobin wrapper, that doesn't know this family's supported levels -- asking for
390
+ * "minimal" on a family whose map only defines low/medium/high/xhigh/max).
391
+ *
392
+ * Returns false for a family with no map at all (nothing to compare against) and for a level
393
+ * that *is* mapped, obviously. `"default"` itself is never "unmapped" in this sense -- it's
394
+ * this project's own internal fallback key, not a requestable `ThinkingLevel`.
395
+ */
396
+ isUnmappedLevel(canonicalId: string, level: ThinkingLevel): boolean {
397
+ const levelMap = this.parsedMap.get(canonicalId);
398
+ if (!levelMap) return false;
399
+ return !levelMap.has(level);
400
+ }
401
+
402
+ getModelMetadata(canonicalId: string): MappingEntry | undefined {
403
+ return this.mappings[canonicalId];
404
+ }
405
+
406
+ /** All distinct raw backend ids (not "provider/id", just the id half) referenced in `mappings`. */
407
+ getAllBackendIds(): string[] {
408
+ return [...this.backendIdLocations.keys()];
409
+ }
410
+
411
+ /** Where a given raw backend id is referenced, e.g. ["mappings.claude-opus-5.map.high.thinking"]. */
412
+ getBackendIdLocations(id: string): string[] {
413
+ return this.backendIdLocations.get(id) ?? [];
414
+ }
415
+
416
+ /** All distinct backend references available to a canonical family. */
417
+ getFamilyBackendRefs(canonicalId: string): BackendRef[] {
418
+ const refs = new Map<string, BackendRef>();
419
+ for (const level of this.parsedMap.get(canonicalId)?.values() ?? []) {
420
+ for (const ref of Object.values(level)) {
421
+ if (ref) refs.set(`${ref.provider}/${ref.id}`, ref);
422
+ }
423
+ }
424
+ return [...refs.values()];
425
+ }
426
+
427
+ getSupportedThinkingLevels(canonicalId: string): ThinkingLevel[] {
428
+ const levelMap = this.parsedMap.get(canonicalId);
429
+ if (!levelMap) {
430
+ return [];
431
+ }
432
+ return EFFORT_LEVELS.filter((level) => levelMap.has(level));
433
+ }
434
+
435
+ /**
436
+ * Whether this family's "default" map level has a backend distinct from all of its own named
437
+ * effort levels -- i.e. whether Pi's "off" thinking level would mean something real for this
438
+ * family, rather than secretly being some other named effort level under a misleading label.
439
+ * Compares only the "default" variant (no thinking/fast toggle) of each level, since that's
440
+ * what Pi's "off" resolves through. Returns true (supported) when there's nothing to compare
441
+ * against, e.g. a family with only a "default" map level and no other effort levels at all.
442
+ */
443
+ hasDistinctOffLevel(canonicalId: string): boolean {
444
+ const levelMap = this.parsedMap.get(canonicalId);
445
+ if (!levelMap) return true;
446
+ const defaultRef = levelMap.get("default")?.default;
447
+ if (!defaultRef) return true;
448
+ for (const [level, refs] of levelMap) {
449
+ if (level === "default") continue;
450
+ const ref = refs.default;
451
+ if (ref && ref.provider === defaultRef.provider && ref.id === defaultRef.id) {
452
+ return false;
453
+ }
454
+ }
455
+ return true;
456
+ }
457
+ }
@@ -0,0 +1,87 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import type { ModelMapper } from "./mapping.js";
6
+
7
+ const expandHome = (p: string): string => (p.startsWith("~") ? path.join(os.homedir(), p.slice(1)) : p);
8
+
9
+ const resolveSourcePath = (mapper: ModelMapper): string | undefined => {
10
+ if (!mapper.catalogSource) return undefined;
11
+ const expanded = expandHome(mapper.catalogSource.path);
12
+ return path.isAbsolute(expanded) ? expanded : path.resolve(path.dirname(mapper.source), expanded);
13
+ };
14
+
15
+ const getAtPath = (value: unknown, dotPath: string): unknown =>
16
+ dotPath.split(".").reduce<unknown>((acc, key) => {
17
+ if (acc && typeof acc === "object" && key in (acc as Record<string, unknown>)) {
18
+ return (acc as Record<string, unknown>)[key];
19
+ }
20
+ return undefined;
21
+ }, value);
22
+
23
+ export interface SourceCheckResult {
24
+ /** Resolved path that was actually read. */
25
+ resolvedPath: string;
26
+ /** True if the file was read/parsed successfully and every referenced backend id was found. */
27
+ ok: boolean;
28
+ /** Backend ids referenced in `mappings` that are absent from the source catalog. */
29
+ missingIds: string[];
30
+ /** Set instead of checking ids when the source file itself couldn't be read/parsed/shaped as expected. */
31
+ error?: string;
32
+ }
33
+
34
+ /**
35
+ * Compares every raw backend id referenced in `mapper`'s `mappings` against the live catalog
36
+ * file named by its `source` config (if any). Returns undefined when `source` was not configured
37
+ * -- this check is opt-in per config file, since there's no universal catalog cache format or
38
+ * location across providers.
39
+ */
40
+ export const checkAgainstSource = (mapper: ModelMapper): SourceCheckResult | undefined => {
41
+ const catalogSource = mapper.catalogSource;
42
+ if (!catalogSource) return undefined;
43
+
44
+ const resolvedPath = resolveSourcePath(mapper);
45
+ if (!resolvedPath) return undefined;
46
+
47
+ let raw: unknown;
48
+ try {
49
+ raw = JSON.parse(fs.readFileSync(resolvedPath, "utf8"));
50
+ } catch (error) {
51
+ return {
52
+ resolvedPath,
53
+ ok: false,
54
+ missingIds: [],
55
+ error: `could not read/parse: ${error instanceof Error ? error.message : String(error)}`,
56
+ };
57
+ }
58
+
59
+ const listValue = catalogSource.listPath ? getAtPath(raw, catalogSource.listPath) : raw;
60
+ if (!Array.isArray(listValue)) {
61
+ return {
62
+ resolvedPath,
63
+ ok: false,
64
+ missingIds: [],
65
+ error:
66
+ `expected an array at ${catalogSource.listPath ? `"${catalogSource.listPath}"` : "the JSON root"}, ` +
67
+ `got ${Array.isArray(listValue) ? "array" : typeof listValue}`,
68
+ };
69
+ }
70
+
71
+ const sourceIds = new Set<string>();
72
+ for (const entry of listValue) {
73
+ if (typeof entry === "string") {
74
+ sourceIds.add(entry);
75
+ continue;
76
+ }
77
+ if (entry && typeof entry === "object") {
78
+ const value = (entry as Record<string, unknown>)[catalogSource.idField];
79
+ if (typeof value === "string") {
80
+ sourceIds.add(value);
81
+ }
82
+ }
83
+ }
84
+
85
+ const missingIds = mapper.getAllBackendIds().filter((id) => !sourceIds.has(id));
86
+ return { resolvedPath, ok: missingIds.length === 0, missingIds };
87
+ };