@dimassetoid/openapi-mcp 0.1.0 → 0.2.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.
@@ -0,0 +1,235 @@
1
+ import { statSync } from 'node:fs';
2
+ import { dirname, relative } from 'node:path';
3
+ import { buildEndpointIndex } from './index-builder.js';
4
+ import { isRecord } from './json.js';
5
+ import { parseDocumentWithLocations } from './source-map.js';
6
+ import { MissingReferenceError, assertWorkspaceRoot, createSpecNodeExpander, deepFreeze, discoverSpec, inferPointerPosition, isSpecFileMissingError, readBoundedFileSnapshot, resolveJsonPointerSafe, resolveLocalSpecFile, resolvePointer, resolveSpecLimits, } from './spec-loader.js';
7
+ const MAX_RAW_DOCS = 8;
8
+ const MAX_SUBTREE_CACHE_ENTRIES = 64;
9
+ const rawDocCache = new Map();
10
+ const subtreeCache = new Map();
11
+ export function clearLazySpecCache() {
12
+ rawDocCache.clear();
13
+ subtreeCache.clear();
14
+ }
15
+ /**
16
+ * Loads only the entry OpenAPI file without eagerly expanding nested or sibling $refs.
17
+ * External $ref files are parsed lazily on demand only when touched by a targeted subtree.
18
+ */
19
+ export function loadRawOpenApiDocument(options = {}) {
20
+ const limits = resolveSpecLimits();
21
+ const rootInput = options.rootDir?.trim() || process.cwd();
22
+ const root = assertWorkspaceRoot(rootInput, options.allowedRootDir);
23
+ const entry = discoverSpec(root, rootInput, options.specPath);
24
+ const cacheId = `${root}\0${entry}`;
25
+ const existing = rawDocCache.get(cacheId);
26
+ if (existing?.rootDir === root) {
27
+ let fresh = false;
28
+ try {
29
+ const st = statSync(entry);
30
+ const depMatch = st.mtimeMs === existing.entryFingerprint.mtimeMs &&
31
+ st.ctimeMs === existing.entryFingerprint.ctimeMs &&
32
+ st.size === existing.entryFingerprint.size;
33
+ if (depMatch) {
34
+ fresh = [...existing.locations].every(([alias, canonical]) => resolveLocalSpecFile(alias, root, root)?.canonical === canonical);
35
+ }
36
+ else {
37
+ const snap = readBoundedFileSnapshot(entry, limits.maxSpecBytes, limits.maxSpecBytes);
38
+ fresh = snap.fingerprint.sha256 === existing.entryFingerprint.sha256;
39
+ }
40
+ }
41
+ catch (error) {
42
+ if (!isSpecFileMissingError(error) && !(error instanceof Error && error.message.startsWith('SPEC_CHANGED:'))) {
43
+ throw error;
44
+ }
45
+ fresh = false;
46
+ }
47
+ rawDocCache.delete(cacheId);
48
+ if (fresh) {
49
+ rawDocCache.set(cacheId, existing);
50
+ return toHandle(existing, root, limits, true);
51
+ }
52
+ }
53
+ const state = {
54
+ rootDir: root,
55
+ entryPath: entry,
56
+ schema31: false,
57
+ entryFingerprint: readBoundedFileSnapshot(entry, limits.maxSpecBytes, limits.maxSpecBytes).fingerprint,
58
+ parsedFiles: new Map(),
59
+ fileSourceLocations: new Map(),
60
+ snapshots: new Map(),
61
+ locations: new Map(),
62
+ };
63
+ let remainingBytes = limits.maxSpecBytes;
64
+ const loadFile = (path) => {
65
+ if (state.parsedFiles.has(path))
66
+ return state.parsedFiles.get(path);
67
+ if (state.snapshots.size >= limits.maxSpecFiles) {
68
+ throw new Error(`SPEC_LIMIT: At most ${limits.maxSpecFiles} source files are supported.`);
69
+ }
70
+ const snap = readBoundedFileSnapshot(path, remainingBytes, limits.maxSpecBytes);
71
+ remainingBytes -= snap.size;
72
+ state.snapshots.set(path, snap);
73
+ try {
74
+ const relFile = relative(root, path).replace(/\\/g, '/');
75
+ const parsed = parseDocumentWithLocations(snap.content, relFile);
76
+ state.parsedFiles.set(path, parsed.value);
77
+ state.fileSourceLocations.set(path, parsed.locations);
78
+ return parsed.value;
79
+ }
80
+ catch (error) {
81
+ const message = error instanceof Error ? error.message : String(error);
82
+ throw new Error(`SPEC_PARSE_ERROR: Failed to parse '${path}': ${message.slice(0, 400)}`);
83
+ }
84
+ };
85
+ const entryDoc = loadFile(entry);
86
+ if (!isRecord(entryDoc)) {
87
+ throw new Error(`SPEC_PARSE_ERROR: Entry specification '${entry}' must be an object.`);
88
+ }
89
+ state.entryFingerprint = state.snapshots.get(entry).fingerprint;
90
+ state.schema31 = typeof entryDoc.openapi === 'string' && /^3\.(?:[1-9]|\d{2,})\./.test(entryDoc.openapi);
91
+ rawDocCache.set(cacheId, state);
92
+ if (rawDocCache.size > MAX_RAW_DOCS) {
93
+ rawDocCache.delete(rawDocCache.keys().next().value);
94
+ }
95
+ return toHandle(state, root, limits, false);
96
+ }
97
+ function toHandle(state, root, limits, fromCache) {
98
+ let usedBytes = [...state.snapshots.values()].reduce((acc, s) => acc + s.size, 0);
99
+ const parseFile = (canonicalPath) => {
100
+ if (state.parsedFiles.has(canonicalPath))
101
+ return state.parsedFiles.get(canonicalPath);
102
+ if (state.snapshots.size >= limits.maxSpecFiles) {
103
+ throw new Error(`SPEC_LIMIT: At most ${limits.maxSpecFiles} source files are supported.`);
104
+ }
105
+ const snap = readBoundedFileSnapshot(canonicalPath, limits.maxSpecBytes - usedBytes, limits.maxSpecBytes);
106
+ usedBytes += snap.size;
107
+ state.snapshots.set(canonicalPath, snap);
108
+ try {
109
+ const relFile = relative(root, canonicalPath).replace(/\\/g, '/');
110
+ const parsed = parseDocumentWithLocations(snap.content, relFile);
111
+ state.parsedFiles.set(canonicalPath, parsed.value);
112
+ state.fileSourceLocations.set(canonicalPath, parsed.locations);
113
+ return parsed.value;
114
+ }
115
+ catch (error) {
116
+ const message = error instanceof Error ? error.message : String(error);
117
+ throw new Error(`SPEC_PARSE_ERROR: Failed to parse '${canonicalPath}': ${message.slice(0, 400)}`);
118
+ }
119
+ };
120
+ const entryLocations = state.fileSourceLocations.get(state.entryPath);
121
+ const sourceLocations = entryLocations
122
+ ? Object.fromEntries(entryLocations.entries())
123
+ : {};
124
+ return {
125
+ entryPath: state.entryPath,
126
+ rootDir: state.rootDir,
127
+ entryDoc: state.parsedFiles.get(state.entryPath),
128
+ schema31: state.schema31,
129
+ entryFingerprint: state.entryFingerprint,
130
+ sourceLocations,
131
+ parseFile,
132
+ locations: state.locations,
133
+ fromCache,
134
+ };
135
+ }
136
+ function resolveShallowRefNode(node, rawDoc, currentFile = rawDoc.entryPath, maxHops = 8) {
137
+ let cursor = node;
138
+ let file = currentFile;
139
+ for (let hop = 0; hop < maxHops; hop++) {
140
+ if (!isRecord(cursor) || typeof cursor.$ref !== 'string')
141
+ return cursor;
142
+ const ref = cursor.$ref.trim();
143
+ const hash = ref.indexOf('#');
144
+ const path = hash < 0 ? ref : ref.slice(0, hash);
145
+ const fragment = hash < 0 ? '' : ref.slice(hash + 1);
146
+ let targetFile = file;
147
+ if (path) {
148
+ const location = resolveLocalSpecFile(path, rawDoc.rootDir, dirname(file));
149
+ if (!location)
150
+ throw new MissingReferenceError(path, file);
151
+ rawDoc.locations.set(location.candidate, location.canonical);
152
+ targetFile = location.canonical;
153
+ }
154
+ cursor = resolvePointer(rawDoc.parseFile(targetFile), fragment, ref);
155
+ file = targetFile;
156
+ }
157
+ return cursor;
158
+ }
159
+ /**
160
+ * Builds the endpoint summary index from a raw OpenAPI document in O(endpoints) without
161
+ * expanding deep nested schemas on unrelated endpoints.
162
+ */
163
+ export function buildRawEndpointSummary(rawDoc) {
164
+ const entry = rawDoc.entryDoc;
165
+ const rawPaths = isRecord(entry.paths) ? entry.paths : {};
166
+ const shallowPaths = {};
167
+ for (const [pathKey, rawPathItem] of Object.entries(rawPaths)) {
168
+ const resolvedPathItem = resolveShallowRefNode(rawPathItem, rawDoc);
169
+ if (!isRecord(resolvedPathItem)) {
170
+ shallowPaths[pathKey] = resolvedPathItem;
171
+ continue;
172
+ }
173
+ const shallowItem = { ...resolvedPathItem };
174
+ for (const [key, value] of Object.entries(resolvedPathItem)) {
175
+ if (!isRecord(value))
176
+ continue;
177
+ if (typeof value.$ref === 'string') {
178
+ const resolvedOp = resolveShallowRefNode(value, rawDoc);
179
+ shallowItem[key] = resolvedOp;
180
+ }
181
+ const opObj = shallowItem[key];
182
+ if (isRecord(opObj) && isRecord(opObj.responses)) {
183
+ const nextResponses = { ...opObj.responses };
184
+ for (const [code, resp] of Object.entries(opObj.responses)) {
185
+ if (isRecord(resp) && typeof resp.$ref === 'string') {
186
+ nextResponses[code] = resolveShallowRefNode(resp, rawDoc);
187
+ }
188
+ }
189
+ shallowItem[key] = { ...opObj, responses: nextResponses };
190
+ }
191
+ }
192
+ shallowPaths[pathKey] = shallowItem;
193
+ }
194
+ return buildEndpointIndex({ ...entry, paths: shallowPaths }, rawDoc.entryPath, rawDoc.sourceLocations);
195
+ }
196
+ /**
197
+ * Lazily resolves and expands only the $refs reachable from the given JSON Pointer
198
+ * (e.g. `/paths/~1users/get` or `/components/schemas/Order`).
199
+ */
200
+ export function expandPointerSubtree(rawDoc, pointer, limits = resolveSpecLimits()) {
201
+ const normalizedPointer = pointer === '/' ? '' : pointer.startsWith('#') ? pointer.slice(1) : pointer;
202
+ const cacheKey = `${rawDoc.entryPath}\0${rawDoc.entryFingerprint.sha256}\0${normalizedPointer}`;
203
+ const cached = subtreeCache.get(cacheKey);
204
+ if (cached) {
205
+ subtreeCache.delete(cacheKey);
206
+ subtreeCache.set(cacheKey, cached);
207
+ return { pointer: normalizedPointer, ...cached, fromCache: true };
208
+ }
209
+ const resolvedTarget = resolveJsonPointerSafe(rawDoc.entryDoc, normalizedPointer);
210
+ if (!resolvedTarget.ok) {
211
+ throw new Error(`INVALID_POINTER: '${pointer}': ${resolvedTarget.reason}`);
212
+ }
213
+ const expander = createSpecNodeExpander({
214
+ root: rawDoc.rootDir,
215
+ entry: rawDoc.entryPath,
216
+ schema31: rawDoc.schema31,
217
+ limits,
218
+ parseFile: rawDoc.parseFile,
219
+ locations: rawDoc.locations,
220
+ });
221
+ const value = deepFreeze(expander.expand(resolvedTarget.value, rawDoc.entryPath, normalizedPointer, 0, inferPointerPosition(normalizedPointer)));
222
+ const stats = expander.getStats();
223
+ const entry = { value, nodeVisits: stats.nodeVisits, expandedBytes: stats.expandedBytes };
224
+ subtreeCache.set(cacheKey, entry);
225
+ if (subtreeCache.size > MAX_SUBTREE_CACHE_ENTRIES) {
226
+ subtreeCache.delete(subtreeCache.keys().next().value);
227
+ }
228
+ return {
229
+ pointer: normalizedPointer,
230
+ value,
231
+ nodeVisits: stats.nodeVisits,
232
+ expandedBytes: stats.expandedBytes,
233
+ fromCache: false,
234
+ };
235
+ }
@@ -0,0 +1,13 @@
1
+ export interface SpecMetadataSummary {
2
+ title: string;
3
+ version: string;
4
+ openapiVersion: string;
5
+ }
6
+ /** Extracts normalized title, version, and OpenAPI/Swagger specification version. */
7
+ export declare function extractSpecMetadata(spec: Record<string, unknown>): SpecMetadataSummary;
8
+ /** Merges path-level and operation-level parameters keyed by `in:name` (operation overrides path). */
9
+ export declare function mergeOperationParameters(pathItem: Record<string, unknown>, operation: Record<string, unknown>): Map<string, Record<string, unknown>>;
10
+ /** Extracts sorted security scheme names from an OpenAPI `security` requirement array. */
11
+ export declare function extractSecuritySchemeNames(securityField: unknown): string[] | undefined;
12
+ /** Returns true when a response key denotes a 4xx/5xx error status code. */
13
+ export declare function isErrorStatusCode(code: string): boolean;
@@ -0,0 +1,48 @@
1
+ import { isRecord } from './json.js';
2
+ /** Extracts normalized title, version, and OpenAPI/Swagger specification version. */
3
+ export function extractSpecMetadata(spec) {
4
+ const info = isRecord(spec.info) ? spec.info : {};
5
+ const title = typeof info.title === 'string' && info.title.trim() ? info.title.trim() : 'Untitled API';
6
+ const version = typeof info.version === 'string' && info.version.trim() ? info.version.trim() : 'unknown';
7
+ const openapiVersion = typeof spec.openapi === 'string'
8
+ ? spec.openapi
9
+ : typeof spec.swagger === 'string'
10
+ ? spec.swagger
11
+ : 'unknown';
12
+ return { title, version, openapiVersion };
13
+ }
14
+ /** Merges path-level and operation-level parameters keyed by `in:name` (operation overrides path). */
15
+ export function mergeOperationParameters(pathItem, operation) {
16
+ const merged = new Map();
17
+ const add = (list) => {
18
+ if (!Array.isArray(list))
19
+ return;
20
+ for (const item of list) {
21
+ if (isRecord(item) && typeof item.name === 'string' && typeof item.in === 'string') {
22
+ merged.set(`${item.in}:${item.name}`, item);
23
+ }
24
+ }
25
+ };
26
+ add(pathItem.parameters);
27
+ add(operation.parameters);
28
+ return merged;
29
+ }
30
+ /** Extracts sorted security scheme names from an OpenAPI `security` requirement array. */
31
+ export function extractSecuritySchemeNames(securityField) {
32
+ if (!Array.isArray(securityField))
33
+ return undefined;
34
+ const schemes = new Set();
35
+ for (const requirement of securityField) {
36
+ if (!isRecord(requirement))
37
+ continue;
38
+ for (const schemeName of Object.keys(requirement)) {
39
+ if (schemeName.trim())
40
+ schemes.add(schemeName);
41
+ }
42
+ }
43
+ return [...schemes].sort();
44
+ }
45
+ /** Returns true when a response key denotes a 4xx/5xx error status code. */
46
+ export function isErrorStatusCode(code) {
47
+ return /^[45](?:\d{2}|xx)$/i.test(code.trim());
48
+ }
@@ -1,8 +1,16 @@
1
1
  export declare const DEFAULT_SANDBOX_TIMEOUT_MS = 150;
2
2
  export declare const MAX_QUERY_CODE_LENGTH: number;
3
+ export interface SandboxSpecMeta {
4
+ specPath: string;
5
+ rootDir: string;
6
+ title: string;
7
+ version: string;
8
+ openapiVersion: string;
9
+ }
3
10
  export interface SandboxMetadata {
4
11
  sourceLocations?: Readonly<Record<string, unknown>>;
5
12
  schemaUsages?: Readonly<Record<string, unknown>>;
13
+ specMeta?: SandboxSpecMeta;
6
14
  }
7
15
  export interface SandboxQueryOptions {
8
16
  timeoutMs?: number;
@@ -167,11 +167,13 @@ const GUEST_HELPERS_SOURCE = `
167
167
  if (name === undefined) return usages;
168
168
  return usages[String(name)] ?? [];
169
169
  };
170
+ const metaHelper = () => __meta?.specMeta ?? null;
170
171
  Object.defineProperty(globalThis, "helpers", {
171
172
  value: Object.freeze({
172
173
  op: Object.freeze(getOp),
173
174
  example: Object.freeze(exampleHelper),
174
175
  schemaRefs: Object.freeze(schemaRefsHelper),
176
+ meta: Object.freeze(metaHelper),
175
177
  }),
176
178
  enumerable: true,
177
179
  });
@@ -1,4 +1,5 @@
1
1
  import { isRecord } from './json.js';
2
+ import { extractSpecMetadata } from './openapi-utils.js';
2
3
  import { escapeJsonPointer } from './source-map.js';
3
4
  const MAX_LISTED_PROPERTIES = 40;
4
5
  const MAX_LISTED_ENUM = 20;
@@ -60,14 +61,7 @@ function formatUsage(usage) {
60
61
  * enriched with reverse references (`usedBy`) and YAML/JSON `sourceLocation`.
61
62
  */
62
63
  export function buildSchemaIndex(spec, specPath, sourceLocations, schemaUsages) {
63
- const info = isRecord(spec.info) ? spec.info : {};
64
- const title = typeof info.title === 'string' && info.title.trim() ? info.title.trim() : 'Untitled API';
65
- const version = typeof info.version === 'string' && info.version.trim() ? info.version.trim() : 'unknown';
66
- const openapiVersion = typeof spec.openapi === 'string'
67
- ? spec.openapi
68
- : typeof spec.swagger === 'string'
69
- ? spec.swagger
70
- : 'unknown';
64
+ const { title, version, openapiVersion } = extractSpecMetadata(spec);
71
65
  const components = isRecord(spec.components) ? spec.components : undefined;
72
66
  const schemasObj = isRecord(components?.schemas)
73
67
  ? components.schemas
@@ -1,6 +1,7 @@
1
1
  import { dirname, relative } from 'node:path';
2
2
  import { HTTP_METHODS } from './index-builder.js';
3
3
  import { isRecord } from './json.js';
4
+ import { extractSecuritySchemeNames, isErrorStatusCode } from './openapi-utils.js';
4
5
  import { escapeJsonPointer, parseDocumentWithLocations } from './source-map.js';
5
6
  import { MAX_SPEC_BYTES, MAX_SPEC_FILES, assertWorkspaceRoot, findOpenApiSpecFile, readBoundedFileSnapshot, resolveJsonPointerSafe, resolveSafeSpecPath, } from './spec-loader.js';
6
7
  const MAX_DIAGNOSTIC_ISSUES = 200;
@@ -202,6 +203,47 @@ export function diagnoseOpenApiSpec(options = {}) {
202
203
  }
203
204
  };
204
205
  checkSecurity(doc.security, '/security', locMap.get('/security'));
206
+ const globalSecurity = extractSecuritySchemeNames(doc.security);
207
+ const resolveRefObject = (candidate) => {
208
+ let current = candidate;
209
+ let currentFile = entryPath;
210
+ let currentDoc = doc;
211
+ const seen = new Set();
212
+ for (let depth = 0; depth < 8; depth++) {
213
+ if (!isRecord(current))
214
+ return undefined;
215
+ if (seen.has(current))
216
+ return undefined;
217
+ seen.add(current);
218
+ if (typeof current.$ref !== 'string')
219
+ return current;
220
+ const ref = current.$ref.trim();
221
+ const hash = ref.indexOf('#');
222
+ const filePart = hash < 0 ? ref : ref.slice(0, hash);
223
+ const fragment = hash < 0 ? '' : ref.slice(hash + 1);
224
+ let nextDoc = currentDoc;
225
+ let nextFile = currentFile;
226
+ if (filePart) {
227
+ try {
228
+ nextFile = resolveSafeSpecPath(filePart, rootReal, dirname(currentFile), rootInput);
229
+ const loadedTarget = loadRawFile(nextFile);
230
+ if ('error' in loadedTarget)
231
+ return undefined;
232
+ nextDoc = loadedTarget.value;
233
+ }
234
+ catch {
235
+ return undefined;
236
+ }
237
+ }
238
+ const resolved = resolveJsonPointerSafe(nextDoc, fragment);
239
+ if (!resolved.ok)
240
+ return undefined;
241
+ current = resolved.value;
242
+ currentFile = nextFile;
243
+ currentDoc = nextDoc;
244
+ }
245
+ return undefined;
246
+ };
205
247
  const seenOperationIds = new Map();
206
248
  const pathsObj = isRecord(doc.paths) ? doc.paths : {};
207
249
  for (const [pathKey, pathItem] of Object.entries(pathsObj)) {
@@ -209,19 +251,10 @@ export function diagnoseOpenApiSpec(options = {}) {
209
251
  continue;
210
252
  const escapedPath = escapeJsonPointer(pathKey);
211
253
  const templateParams = extractPathTemplateParams(pathKey);
212
- const resolveParamObject = (param) => {
213
- if (!isRecord(param))
214
- return undefined;
215
- if (typeof param.$ref === 'string' && param.$ref.startsWith('#')) {
216
- const res = resolveJsonPointerSafe(doc, param.$ref.slice(1));
217
- return res.ok && isRecord(res.value) ? res.value : undefined;
218
- }
219
- return param;
220
- };
221
254
  const pathLevelPathParams = new Set();
222
255
  if (Array.isArray(pathItem.parameters)) {
223
256
  for (const rawParam of pathItem.parameters) {
224
- const param = resolveParamObject(rawParam);
257
+ const param = resolveRefObject(rawParam);
225
258
  if (param && param.in === 'path' && typeof param.name === 'string') {
226
259
  pathLevelPathParams.add(param.name);
227
260
  }
@@ -254,7 +287,7 @@ export function diagnoseOpenApiSpec(options = {}) {
254
287
  const declared = new Set(pathLevelPathParams);
255
288
  if (Array.isArray(op.parameters)) {
256
289
  for (const rawParam of op.parameters) {
257
- const param = resolveParamObject(rawParam);
290
+ const param = resolveRefObject(rawParam);
258
291
  if (param && param.in === 'path' && typeof param.name === 'string') {
259
292
  declared.add(param.name);
260
293
  }
@@ -273,8 +306,21 @@ export function diagnoseOpenApiSpec(options = {}) {
273
306
  }
274
307
  }
275
308
  checkSecurity(op.security, `${opPointer}/security`, opLoc);
309
+ const opSecurity = extractSecuritySchemeNames(op.security);
310
+ const effectiveSecurity = opSecurity !== undefined ? opSecurity : globalSecurity;
311
+ const requiresAuth = effectiveSecurity !== undefined && effectiveSecurity.length > 0;
276
312
  const responses = isRecord(op.responses) ? op.responses : {};
277
- const errorCodes = Object.keys(responses).filter((c) => /^[45](?:\d{2}|xx)$/i.test(c.trim()));
313
+ const responseCodes = Object.keys(responses);
314
+ const errorCodes = responseCodes.filter(isErrorStatusCode);
315
+ if (requiresAuth && !responseCodes.some((c) => /^(?:401|403|4xx)$/i.test(c.trim()))) {
316
+ pushIssue({
317
+ severity: 'info',
318
+ code: 'AUTH_ENDPOINT_MISSING_401_403',
319
+ message: `Protected operation ${opLabel} declares security (${effectiveSecurity.join(', ')}) without a 401/403 response.`,
320
+ pointer: opPointer,
321
+ ...(opLoc ? { location: opLoc } : {}),
322
+ });
323
+ }
278
324
  if (errorCodes.length === 0) {
279
325
  pushIssue({
280
326
  severity: 'warning',
@@ -286,13 +332,8 @@ export function diagnoseOpenApiSpec(options = {}) {
286
332
  }
287
333
  else {
288
334
  for (const code of errorCodes) {
289
- let resp = responses[code];
290
- if (isRecord(resp) && typeof resp.$ref === 'string' && resp.$ref.startsWith('#')) {
291
- const resolvedResp = resolveJsonPointerSafe(doc, resp.$ref.slice(1));
292
- if (resolvedResp.ok)
293
- resp = resolvedResp.value;
294
- }
295
- if (!isRecord(resp))
335
+ const resp = resolveRefObject(responses[code]);
336
+ if (!resp)
296
337
  continue;
297
338
  const content = isRecord(resp.content) ? resp.content : undefined;
298
339
  const hasSchema = (content && Object.values(content).some((m) => isRecord(m) && (isRecord(m.schema) || typeof m.schema === 'boolean'))) ||
@@ -24,6 +24,7 @@ export interface SpecDiffReport {
24
24
  /**
25
25
  * Semantically compares two resolved OpenAPI specifications and classifies changes into
26
26
  * `breaking` vs `nonBreaking` using O(E + P + F) indexed lookups.
27
+ * Caps `breaking` and `nonBreaking` independently so non-breaking volume never starves breaking detections.
27
28
  */
28
29
  export declare function diffOpenApiSpecs(baseSpec: Record<string, unknown>, targetSpec: Record<string, unknown>, labels?: {
29
30
  base?: string;
@@ -1,6 +1,7 @@
1
1
  import { HTTP_METHODS } from './index-builder.js';
2
2
  import { isRecord } from './json.js';
3
- const MAX_DIFF_CHANGES = 250;
3
+ import { mergeOperationParameters } from './openapi-utils.js';
4
+ const MAX_DIFF_CHANGES_PER_BUCKET = 250;
4
5
  const MAX_SCHEMA_DIFF_DEPTH = 6;
5
6
  function normalizeType(schema) {
6
7
  if (typeof schema === 'boolean')
@@ -50,40 +51,37 @@ function mergeObjectShape(schema, depth = 0) {
50
51
  }
51
52
  return { properties, required };
52
53
  }
53
- function collectMergedParams(pathItem, op) {
54
- const map = new Map();
55
- const add = (list) => {
56
- if (!Array.isArray(list))
57
- return;
58
- for (const item of list) {
59
- if (isRecord(item) && typeof item.name === 'string' && typeof item.in === 'string') {
60
- map.set(`${item.in}:${item.name}`, item);
61
- }
62
- }
63
- };
64
- add(pathItem.parameters);
65
- add(op.parameters);
66
- return map;
67
- }
68
54
  /**
69
55
  * Semantically compares two resolved OpenAPI specifications and classifies changes into
70
56
  * `breaking` vs `nonBreaking` using O(E + P + F) indexed lookups.
57
+ * Caps `breaking` and `nonBreaking` independently so non-breaking volume never starves breaking detections.
71
58
  */
72
59
  export function diffOpenApiSpecs(baseSpec, targetSpec, labels) {
73
60
  const breaking = [];
74
61
  const nonBreaking = [];
62
+ let totalBreaking = 0;
63
+ let totalNonBreaking = 0;
75
64
  let addedEndpoints = 0;
76
65
  let removedEndpoints = 0;
77
66
  let truncated = false;
78
67
  const record = (change) => {
79
- if (breaking.length + nonBreaking.length >= MAX_DIFF_CHANGES) {
80
- truncated = true;
68
+ if (change.classification === 'breaking') {
69
+ totalBreaking++;
70
+ if (breaking.length < MAX_DIFF_CHANGES_PER_BUCKET) {
71
+ breaking.push(change);
72
+ }
73
+ else {
74
+ truncated = true;
75
+ }
81
76
  return;
82
77
  }
83
- if (change.classification === 'breaking')
84
- breaking.push(change);
85
- else
78
+ totalNonBreaking++;
79
+ if (nonBreaking.length < MAX_DIFF_CHANGES_PER_BUCKET) {
86
80
  nonBreaking.push(change);
81
+ }
82
+ else {
83
+ truncated = true;
84
+ }
87
85
  };
88
86
  function diffSchemas(baseSchema, targetSchema, direction, endpoint, loc, depth) {
89
87
  if (depth > MAX_SCHEMA_DIFF_DEPTH)
@@ -243,8 +241,8 @@ export function diffOpenApiSpecs(baseSpec, targetSpec, labels) {
243
241
  });
244
242
  }
245
243
  // Parameters
246
- const baseParams = collectMergedParams(baseEntry.pathItem, baseEntry.op);
247
- const targetParams = collectMergedParams(targetEntry.pathItem, targetEntry.op);
244
+ const baseParams = mergeOperationParameters(baseEntry.pathItem, baseEntry.op);
245
+ const targetParams = mergeOperationParameters(targetEntry.pathItem, targetEntry.op);
248
246
  for (const [key, baseParam] of baseParams) {
249
247
  const targetParam = targetParams.get(key);
250
248
  if (!targetParam) {
@@ -393,13 +391,13 @@ export function diffOpenApiSpecs(baseSpec, targetSpec, labels) {
393
391
  return {
394
392
  ...(labels?.base ? { baseSpec: labels.base } : {}),
395
393
  ...(labels?.target ? { targetSpec: labels.target } : {}),
396
- hasBreakingChanges: breaking.length > 0,
394
+ hasBreakingChanges: totalBreaking > 0,
397
395
  summary: {
398
- breakingCount: breaking.length,
399
- nonBreakingCount: nonBreaking.length,
396
+ breakingCount: totalBreaking,
397
+ nonBreakingCount: totalNonBreaking,
400
398
  addedEndpoints,
401
399
  removedEndpoints,
402
- totalChanges: breaking.length + nonBreaking.length,
400
+ totalChanges: totalBreaking + totalNonBreaking,
403
401
  truncated,
404
402
  },
405
403
  breaking,
@@ -3,6 +3,14 @@ import type { SchemaUsageRef } from './schema-index.js';
3
3
  export declare const DEFAULT_SPEC_CANDIDATES: readonly ["openapi.yml", "openapi.yaml", "openapi.json", "api/openapi.yml", "api/openapi.yaml", "api/openapi.json", "docs/openapi.yml", "docs/openapi.yaml", "docs/openapi.json"];
4
4
  export declare const MAX_SPEC_BYTES: number;
5
5
  export declare const MAX_SPEC_FILES = 128;
6
+ export declare const MAX_DEPTH = 128;
7
+ export interface SpecLimits {
8
+ maxSpecBytes: number;
9
+ maxSpecFiles: number;
10
+ maxNodeVisits: number;
11
+ maxCachedSpecs: number;
12
+ }
13
+ export declare function resolveSpecLimits(env?: NodeJS.ProcessEnv): SpecLimits;
6
14
  export declare class MissingReferenceError extends Error {
7
15
  readonly code = "REF_FILE_NOT_FOUND";
8
16
  constructor(target: string, source: string);
@@ -36,10 +44,17 @@ export interface FileSnapshot {
36
44
  }
37
45
  /** Serialize loader-owned snapshots once. Library callers can also supply their own data. */
38
46
  export declare function serializeSpec(spec: unknown): string;
47
+ export declare function isSpecFileMissingError(error: unknown): boolean;
48
+ export declare function resolveSpecWorkspaceRoot(path: string): string;
49
+ export declare function resolveLocalSpecFile(target: string, root: string, base: string, rawRoot?: string): {
50
+ candidate: string;
51
+ canonical: string;
52
+ } | undefined;
39
53
  export declare function resolveSafeSpecPath(targetPath: string, rootRealPath: string, baseDir?: string, rawRootDir?: string): string;
54
+ export declare function discoverSpec(root: string, rawRoot: string, explicitPath?: string): string;
40
55
  export declare function assertWorkspaceRoot(rootInput: string, allowedRootDir?: string): string;
41
56
  export declare function findOpenApiSpecFile(rootDir: string, explicitPath?: string): string;
42
- export declare function readBoundedFileSnapshot(path: string, availableBytes: number): FileSnapshot;
57
+ export declare function readBoundedFileSnapshot(path: string, availableBytes: number, maxSpecBytes?: number): FileSnapshot;
43
58
  export declare function resolveJsonPointerSafe(document: unknown, fragment: string): {
44
59
  ok: true;
45
60
  value: unknown;
@@ -47,7 +62,32 @@ export declare function resolveJsonPointerSafe(document: unknown, fragment: stri
47
62
  ok: false;
48
63
  reason: string;
49
64
  };
65
+ export declare function resolvePointer(document: unknown, fragment: string, ref: string): unknown;
66
+ export type ExpanderPosition = 'document' | 'named-map' | 'example-map' | 'example-object' | 'schema' | 'schema-map' | 'schema-list' | 'literal';
67
+ type Position = ExpanderPosition;
68
+ export interface SubtreeExpanderOptions {
69
+ root: string;
70
+ entry: string;
71
+ schema31: boolean;
72
+ limits: SpecLimits;
73
+ parseFile: (canonicalPath: string) => unknown;
74
+ locations: Map<string, string>;
75
+ schemaUsageMap?: Map<string, Map<string, SchemaUsageRef>>;
76
+ }
77
+ export declare function inferPointerPosition(pointer: string): ExpanderPosition;
50
78
  export declare function deepFreeze<T>(value: T, seen?: WeakSet<object>): T;
79
+ interface OperationContext {
80
+ method: string;
81
+ path: string;
82
+ section?: string;
83
+ }
84
+ export declare function createSpecNodeExpander(options: SubtreeExpanderOptions): {
85
+ expand: (node: unknown, file: string, pointer: string, depth: number, position: Position, opCtx?: OperationContext) => unknown;
86
+ getStats: () => {
87
+ nodeVisits: number;
88
+ expandedBytes: number;
89
+ };
90
+ };
51
91
  /**
52
92
  * Returns a bounded, immutable snapshot shared by library, index, and query consumers.
53
93
  */
@@ -57,3 +97,4 @@ export declare function getSpecCacheStats(): {
57
97
  size: number;
58
98
  entries: string[];
59
99
  };
100
+ export {};