@dimassetoid/openapi-mcp 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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/dist/engine/budget.d.ts +40 -0
  4. package/dist/engine/budget.js +96 -0
  5. package/dist/engine/example-generator.d.ts +47 -0
  6. package/dist/engine/example-generator.js +283 -0
  7. package/dist/engine/index-builder.d.ts +50 -0
  8. package/dist/engine/index-builder.js +179 -0
  9. package/dist/engine/index.d.ts +10 -0
  10. package/dist/engine/index.js +10 -0
  11. package/dist/engine/json.d.ts +1 -0
  12. package/dist/engine/json.js +3 -0
  13. package/dist/engine/query-sandbox.d.ts +21 -0
  14. package/dist/engine/query-sandbox.js +343 -0
  15. package/dist/engine/schema-index.d.ts +42 -0
  16. package/dist/engine/schema-index.js +151 -0
  17. package/dist/engine/source-map.d.ts +15 -0
  18. package/dist/engine/source-map.js +50 -0
  19. package/dist/engine/spec-catalog.d.ts +14 -0
  20. package/dist/engine/spec-catalog.js +99 -0
  21. package/dist/engine/spec-diagnostics.d.ts +28 -0
  22. package/dist/engine/spec-diagnostics.js +352 -0
  23. package/dist/engine/spec-diff.d.ts +31 -0
  24. package/dist/engine/spec-diff.js +408 -0
  25. package/dist/engine/spec-loader.d.ts +59 -0
  26. package/dist/engine/spec-loader.js +484 -0
  27. package/dist/index.d.ts +37 -0
  28. package/dist/index.js +293 -0
  29. package/dist/mcp/prompts.d.ts +51 -0
  30. package/dist/mcp/prompts.js +161 -0
  31. package/dist/mcp/resources.d.ts +30 -0
  32. package/dist/mcp/resources.js +187 -0
  33. package/dist/mcp/server.d.ts +43 -0
  34. package/dist/mcp/server.js +201 -0
  35. package/docs/feature/README.md +65 -0
  36. package/docs/feature/getting-started.md +131 -0
  37. package/docs/feature/index-and-prompts.md +50 -0
  38. package/docs/feature/openapi-query.md +48 -0
  39. package/docs/feature/spec-loader.md +33 -0
  40. package/package.json +77 -4
  41. package/skills/use-openapi-mcp/SKILL.md +42 -0
@@ -0,0 +1,179 @@
1
+ import { isRecord } from './json.js';
2
+ import { escapeJsonPointer } from './source-map.js';
3
+ export const HTTP_METHODS = [
4
+ 'get',
5
+ 'post',
6
+ 'put',
7
+ 'patch',
8
+ 'delete',
9
+ 'options',
10
+ 'head',
11
+ 'trace',
12
+ ];
13
+ function sortStatusCodes(codes) {
14
+ return [...codes].sort((a, b) => {
15
+ const aNum = /^\d+$/.test(a) ? Number(a) : Number.POSITIVE_INFINITY;
16
+ const bNum = /^\d+$/.test(b) ? Number(b) : Number.POSITIVE_INFINITY;
17
+ if (aNum !== bNum)
18
+ return aNum - bNum;
19
+ if (a === 'default')
20
+ return 1;
21
+ if (b === 'default')
22
+ return -1;
23
+ return a.localeCompare(b);
24
+ });
25
+ }
26
+ export function searchEndpoints(entries, filters) {
27
+ const query = filters.q?.toLowerCase();
28
+ const tag = filters.tag?.toLowerCase();
29
+ const method = filters.method?.toUpperCase();
30
+ const pathPrefix = filters.pathPrefix;
31
+ const operationId = filters.operationId?.toLowerCase();
32
+ const endpoints = [];
33
+ let totalMatches = 0;
34
+ for (const entry of entries) {
35
+ const tags = entry.tags ?? [];
36
+ if (method && entry.method !== method)
37
+ continue;
38
+ if (pathPrefix && !entry.path.startsWith(pathPrefix))
39
+ continue;
40
+ if (tag && !tags.some(value => value.toLowerCase() === tag))
41
+ continue;
42
+ if (operationId && entry.operationId?.toLowerCase() !== operationId)
43
+ continue;
44
+ if (filters.missingErrorContracts === true && entry.errorStatusCodes.length > 0)
45
+ continue;
46
+ if (filters.missingErrorContracts === false && entry.errorStatusCodes.length === 0)
47
+ continue;
48
+ if (query && ![entry.method, entry.path, entry.summary, entry.operationId ?? '', ...tags]
49
+ .some(value => value.toLowerCase().includes(query)))
50
+ continue;
51
+ if (totalMatches >= filters.offset && endpoints.length < filters.limit)
52
+ endpoints.push(entry);
53
+ totalMatches++;
54
+ }
55
+ return { endpoints, totalMatches };
56
+ }
57
+ function extractSecuritySchemes(securityField) {
58
+ if (!Array.isArray(securityField))
59
+ return undefined;
60
+ const schemes = new Set();
61
+ for (const requirement of securityField) {
62
+ if (!isRecord(requirement))
63
+ continue;
64
+ for (const schemeName of Object.keys(requirement)) {
65
+ if (schemeName.trim())
66
+ schemes.add(schemeName);
67
+ }
68
+ }
69
+ return [...schemes].sort();
70
+ }
71
+ function isErrorStatusCode(code) {
72
+ const normalized = code.trim().toLowerCase();
73
+ return /^[45](?:\d{2}|xx)$/.test(normalized);
74
+ }
75
+ function extractSummary(operation) {
76
+ if (typeof operation.summary === 'string' && operation.summary.trim()) {
77
+ return operation.summary.trim().replace(/\s+/g, ' ');
78
+ }
79
+ if (typeof operation.description === 'string' && operation.description.trim()) {
80
+ const firstLine = operation.description.trim().split(/\r?\n/)[0] ?? '';
81
+ if (firstLine.trim()) {
82
+ return firstLine.trim().slice(0, 120);
83
+ }
84
+ }
85
+ if (typeof operation.operationId === 'string' && operation.operationId.trim()) {
86
+ return operation.operationId.trim();
87
+ }
88
+ return 'No summary';
89
+ }
90
+ /**
91
+ * Builds a compact, token-lean index of all endpoints and their defined HTTP status codes
92
+ * (including all 4xx/5xx error responses) from a resolved OpenAPI specification.
93
+ */
94
+ export function buildEndpointIndex(spec, specPath, sourceLocations) {
95
+ const info = isRecord(spec.info) ? spec.info : {};
96
+ const title = typeof info.title === 'string' && info.title.trim() ? info.title.trim() : 'Untitled API';
97
+ const version = typeof info.version === 'string' && info.version.trim() ? info.version.trim() : 'unknown';
98
+ const openapiVersion = typeof spec.openapi === 'string'
99
+ ? spec.openapi
100
+ : typeof spec.swagger === 'string'
101
+ ? spec.swagger
102
+ : 'unknown';
103
+ const pathsObj = isRecord(spec.paths) ? spec.paths : {};
104
+ const globalSecurity = extractSecuritySchemes(spec.security);
105
+ const endpoints = [];
106
+ const endpointsMissingErrorContracts = [];
107
+ const allTags = new Set();
108
+ for (const pathKey of Object.keys(pathsObj)) {
109
+ const pathItem = pathsObj[pathKey];
110
+ if (!isRecord(pathItem))
111
+ continue;
112
+ for (const httpMethod of HTTP_METHODS) {
113
+ const operation = pathItem[httpMethod];
114
+ if (!isRecord(operation))
115
+ continue;
116
+ const method = httpMethod.toUpperCase();
117
+ const summary = extractSummary(operation);
118
+ const responses = isRecord(operation.responses) ? operation.responses : {};
119
+ const statusCodes = sortStatusCodes(Object.keys(responses));
120
+ const errorStatusCodes = statusCodes.filter(isErrorStatusCode);
121
+ const errorBodies = Object.fromEntries(errorStatusCodes.map(code => {
122
+ const response = responses[code];
123
+ const content = isRecord(response) && isRecord(response.content) ? response.content : {};
124
+ const schemaMediaTypes = Object.keys(content).filter(type => {
125
+ const media = content[type];
126
+ return isRecord(media) && (isRecord(media.schema) || typeof media.schema === 'boolean');
127
+ });
128
+ const hasSwaggerSchema = spec.swagger === '2.0' && isRecord(response) && isRecord(response.schema);
129
+ return [code, { schemaMediaTypes, ...(hasSwaggerSchema ? { hasSwaggerSchema } : {}) }];
130
+ }));
131
+ if (errorStatusCodes.length === 0) {
132
+ endpointsMissingErrorContracts.push(`${method} ${pathKey}`);
133
+ }
134
+ const tags = Array.isArray(operation.tags)
135
+ ? operation.tags.filter((t) => typeof t === 'string' && t.trim().length > 0)
136
+ : undefined;
137
+ if (tags) {
138
+ for (const t of tags)
139
+ allTags.add(t);
140
+ }
141
+ const operationId = typeof operation.operationId === 'string' && operation.operationId.trim()
142
+ ? operation.operationId.trim()
143
+ : undefined;
144
+ const deprecated = operation.deprecated === true;
145
+ const opSecurity = extractSecuritySchemes(operation.security);
146
+ const effectiveSecurity = opSecurity !== undefined ? opSecurity : globalSecurity;
147
+ const includeSecurity = effectiveSecurity !== undefined && (effectiveSecurity.length > 0 || (opSecurity !== undefined && (globalSecurity?.length ?? 0) > 0));
148
+ const sourceLocation = sourceLocations?.[`/paths/${escapeJsonPointer(pathKey)}/${httpMethod}`];
149
+ const statusList = statusCodes.length > 0 ? statusCodes.join(', ') : 'none';
150
+ const line = `${method} ${pathKey} — ${summary} — [${statusList}]`;
151
+ endpoints.push({
152
+ method,
153
+ path: pathKey,
154
+ ...(operationId ? { operationId } : {}),
155
+ summary,
156
+ ...(tags && tags.length > 0 ? { tags } : {}),
157
+ ...(deprecated ? { deprecated: true } : {}),
158
+ ...(includeSecurity ? { security: effectiveSecurity } : {}),
159
+ statusCodes,
160
+ errorStatusCodes,
161
+ errorBodies,
162
+ ...(sourceLocation ? { sourceLocation } : {}),
163
+ line,
164
+ });
165
+ }
166
+ }
167
+ return {
168
+ title,
169
+ version,
170
+ openapiVersion,
171
+ ...(specPath ? { specPath } : {}),
172
+ totalEndpoints: endpoints.length,
173
+ tags: [...allTags].sort(),
174
+ endpointsWithErrorContracts: endpoints.length - endpointsMissingErrorContracts.length,
175
+ endpointsMissingErrorContracts,
176
+ lines: endpoints.map((e) => e.line),
177
+ endpoints,
178
+ };
179
+ }
@@ -0,0 +1,10 @@
1
+ export { DEFAULT_SPEC_CANDIDATES, clearSpecCache, deepFreeze, findOpenApiSpecFile, getSpecCacheStats, loadOpenApiSpec, resolveSafeSpecPath, type FileFingerprint, type LoadOpenApiSpecOptions, type LoadedOpenApiSpec, } from './spec-loader.js';
2
+ export { HTTP_METHODS, buildEndpointIndex, searchEndpoints, type EndpointIndex, type EndpointSearchFilters, type EndpointSummaryItem, } from './index-builder.js';
3
+ export { DEFAULT_IGNORED_DIRS, listWorkspaceSpecs, scanWorkspaceSpecs, type WorkspaceSpecCatalog, } from './spec-catalog.js';
4
+ export { escapeJsonPointer, parseDocumentWithLocations, type ParsedDocumentWithLocations, type SourceLocation, } from './source-map.js';
5
+ export { buildSchemaIndex, searchSchemas, type SchemaIndex, type SchemaSearchFilters, type SchemaSummaryItem, type SchemaUsageRef, } from './schema-index.js';
6
+ export { DEFAULT_SANDBOX_TIMEOUT_MS, runSandboxQuery, validateSandboxCode, type SandboxMetadata, type SandboxQueryOptions, type SandboxQueryResult, } from './query-sandbox.js';
7
+ export { generateOperationExamples, generateSchemaExample, getMergedOperation, type ExampleGeneratorOptions, type MergedOperationContract, } from './example-generator.js';
8
+ export { diagnoseOpenApiSpec, type DiagnosticSeverity, type SpecDiagnosticIssue, type SpecDiagnosticsReport, } from './spec-diagnostics.js';
9
+ export { diffOpenApiSpecs, type DiffClassification, type SpecDiffChange, type SpecDiffReport, } from './spec-diff.js';
10
+ export { DEFAULT_MAX_BYTES, enforceByteBudget, type BudgetCheckResult, type BudgetExceededPayload, type BudgetExceededResult, type BudgetOkResult, } from './budget.js';
@@ -0,0 +1,10 @@
1
+ export { DEFAULT_SPEC_CANDIDATES, clearSpecCache, deepFreeze, findOpenApiSpecFile, getSpecCacheStats, loadOpenApiSpec, resolveSafeSpecPath, } from './spec-loader.js';
2
+ export { HTTP_METHODS, buildEndpointIndex, searchEndpoints, } from './index-builder.js';
3
+ export { DEFAULT_IGNORED_DIRS, listWorkspaceSpecs, scanWorkspaceSpecs, } from './spec-catalog.js';
4
+ export { escapeJsonPointer, parseDocumentWithLocations, } from './source-map.js';
5
+ export { buildSchemaIndex, searchSchemas, } from './schema-index.js';
6
+ export { DEFAULT_SANDBOX_TIMEOUT_MS, runSandboxQuery, validateSandboxCode, } from './query-sandbox.js';
7
+ export { generateOperationExamples, generateSchemaExample, getMergedOperation, } from './example-generator.js';
8
+ export { diagnoseOpenApiSpec, } from './spec-diagnostics.js';
9
+ export { diffOpenApiSpecs, } from './spec-diff.js';
10
+ export { DEFAULT_MAX_BYTES, enforceByteBudget, } from './budget.js';
@@ -0,0 +1 @@
1
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,3 @@
1
+ export function isRecord(value) {
2
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
3
+ }
@@ -0,0 +1,21 @@
1
+ export declare const DEFAULT_SANDBOX_TIMEOUT_MS = 150;
2
+ export declare const MAX_QUERY_CODE_LENGTH: number;
3
+ export interface SandboxMetadata {
4
+ sourceLocations?: Readonly<Record<string, unknown>>;
5
+ schemaUsages?: Readonly<Record<string, unknown>>;
6
+ }
7
+ export interface SandboxQueryOptions {
8
+ timeoutMs?: number;
9
+ metadata?: SandboxMetadata;
10
+ }
11
+ export interface SandboxQueryResult {
12
+ value: unknown;
13
+ durationMs: number;
14
+ }
15
+ export declare function validateSandboxCode(code: string): void;
16
+ /** Runs and serializes the query within one bounded guest runtime. */
17
+ export declare function evaluateSandboxQuery(spec: unknown, code: string, options?: SandboxQueryOptions): {
18
+ text: string | undefined;
19
+ durationMs: number;
20
+ };
21
+ export declare function runSandboxQuery(spec: unknown, code: string, options?: SandboxQueryOptions): SandboxQueryResult;
@@ -0,0 +1,343 @@
1
+ import { parse } from 'acorn';
2
+ import { newQuickJSWASMModuleFromVariant, Scope } from 'quickjs-emscripten-core';
3
+ import { MAX_RESULT_BYTES } from './budget.js';
4
+ import { serializeSpec } from './spec-loader.js';
5
+ export const DEFAULT_SANDBOX_TIMEOUT_MS = 150;
6
+ export const MAX_QUERY_CODE_LENGTH = 16 * 1024;
7
+ const BOOTSTRAP_TIMEOUT_MS = 2_000;
8
+ const GUEST_MEMORY_BYTES = 64 * 1024 * 1024;
9
+ const GUEST_STACK_BYTES = 512 * 1024;
10
+ const QuickJS = await newQuickJSWASMModuleFromVariant(import('@jitl/quickjs-singlefile-cjs-release-sync'));
11
+ const GUEST_HELPERS_SOURCE = `
12
+ const isRec = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
13
+ const escPtr = (s) => String(s).replace(/~/g, "~0").replace(/\\//g, "~1");
14
+ const pickType = (t) => typeof t === "string" ? t : Array.isArray(t) ? (t.find((x) => typeof x === "string" && x !== "null") ?? t.find((x) => typeof x === "string")) : undefined;
15
+ const synthStr = (s) => {
16
+ const f = typeof s.format === "string" ? s.format.toLowerCase() : "";
17
+ if (f === "uuid") return "00000000-0000-4000-8000-000000000000";
18
+ if (f === "email" || f === "idn-email") return "user@example.com";
19
+ if (f === "date-time") return "2026-01-01T00:00:00Z";
20
+ if (f === "date") return "2026-01-01";
21
+ if (f === "time") return "00:00:00Z";
22
+ if (f === "uri" || f === "url" || f === "iri") return "https://example.com/resource";
23
+ if (f === "ipv4") return "192.0.2.1";
24
+ if (f === "ipv6") return "2001:db8::1";
25
+ if (f === "hostname" || f === "idn-hostname") return "example.com";
26
+ if (f === "byte") return "ZXhhbXBsZQ==";
27
+ const minL = typeof s.minLength === "number" && s.minLength > 0 ? Math.min(64, Math.floor(s.minLength)) : 0;
28
+ return minL > 6 ? "string".padEnd(minL, "x") : "string";
29
+ };
30
+ const synthNum = (s, isInt) => {
31
+ let v = isInt ? 1 : 0;
32
+ if (typeof s.exclusiveMinimum === "number") v = isInt ? Math.floor(s.exclusiveMinimum) + 1 : s.exclusiveMinimum + 0.5;
33
+ else if (typeof s.minimum === "number" && v < s.minimum) v = isInt ? Math.ceil(s.minimum) : s.minimum;
34
+ if (typeof s.maximum === "number" && v > s.maximum) v = isInt ? Math.floor(s.maximum) : s.maximum;
35
+ return v;
36
+ };
37
+ const genExample = (schema, opts = {}) => {
38
+ const maxD = opts.maxDepth ?? 8;
39
+ const maxN = opts.maxNodes ?? 256;
40
+ const incRO = opts.includeReadOnly ?? true;
41
+ const incWO = opts.includeWriteOnly ?? true;
42
+ let nodes = 0;
43
+ const visit = (n, d) => {
44
+ if (++nodes > maxN || d > maxD) return null;
45
+ if (typeof n === "string" && n.startsWith("[Circular:")) return null;
46
+ if (typeof n === "boolean") return n ? {} : null;
47
+ if (!isRec(n)) return null;
48
+ if (n.example !== undefined) return n.example;
49
+ if (Array.isArray(n.examples) && n.examples.length > 0) return n.examples[0];
50
+ if (n.const !== undefined) return n.const;
51
+ if (n.default !== undefined) return n.default;
52
+ if (Array.isArray(n.enum) && n.enum.length > 0) return n.enum[0];
53
+ if (Array.isArray(n.allOf) && n.allOf.length > 0) {
54
+ const merged = {};
55
+ let anyObj = false;
56
+ for (const b of n.allOf) {
57
+ const s = visit(b, d + 1);
58
+ if (isRec(s)) { Object.assign(merged, s); anyObj = true; }
59
+ }
60
+ return anyObj ? merged : visit(n.allOf[0], d + 1);
61
+ }
62
+ const union = Array.isArray(n.oneOf) ? n.oneOf : Array.isArray(n.anyOf) ? n.anyOf : null;
63
+ if (union && union.length > 0) {
64
+ const pick = union.find((b) => isRec(b) && b.type !== "null") ?? union[0];
65
+ return visit(pick, d + 1);
66
+ }
67
+ const t = pickType(n.type) ?? (isRec(n.properties) ? "object" : n.items !== undefined ? "array" : undefined);
68
+ if (t === "object") {
69
+ const out = {};
70
+ if (isRec(n.properties)) {
71
+ for (const [k, ps] of Object.entries(n.properties)) {
72
+ if (isRec(ps) && ((!incRO && ps.readOnly === true) || (!incWO && ps.writeOnly === true))) continue;
73
+ out[k] = visit(ps, d + 1);
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+ if (t === "array") {
79
+ if (Array.isArray(n.prefixItems) && n.prefixItems.length > 0) return n.prefixItems.map((x) => visit(x, d + 1));
80
+ if (n.items === undefined) return [];
81
+ const cnt = typeof n.minItems === "number" && n.minItems > 0 ? Math.min(2, Math.floor(n.minItems)) : 1;
82
+ const arr = [];
83
+ for (let i = 0; i < cnt; i++) arr.push(visit(n.items, d + 1));
84
+ return arr;
85
+ }
86
+ if (t === "string") return synthStr(n);
87
+ if (t === "integer") return synthNum(n, true);
88
+ if (t === "number") return synthNum(n, false);
89
+ if (t === "boolean") return true;
90
+ return null;
91
+ };
92
+ return visit(schema, 0);
93
+ };
94
+ const pickMedia = (content) => {
95
+ if (isRec(content["application/json"])) return { mediaType: "application/json", media: content["application/json"] };
96
+ const jKey = Object.keys(content).find((k) => k.includes("json") && isRec(content[k]));
97
+ if (jKey) return { mediaType: jKey, media: content[jKey] };
98
+ const fKey = Object.keys(content).find((k) => isRec(content[k]));
99
+ return fKey ? { mediaType: fKey, media: content[fKey] } : null;
100
+ };
101
+ const extractMediaEx = (media, opts) => {
102
+ if (media.example !== undefined) return media.example;
103
+ if (isRec(media.examples)) {
104
+ for (const ex of Object.values(media.examples)) {
105
+ if (isRec(ex) && ex.value !== undefined) return ex.value;
106
+ }
107
+ }
108
+ return media.schema !== undefined ? genExample(media.schema, opts) : null;
109
+ };
110
+ const getOp = (method, path) => {
111
+ const specObj = globalThis.spec;
112
+ const paths = isRec(specObj?.paths) ? specObj.paths : null;
113
+ const item = paths && isRec(paths[path]) ? paths[path] : null;
114
+ const m = String(method ?? "").trim().toLowerCase();
115
+ const op = item && isRec(item[m]) ? item[m] : null;
116
+ if (!item || !op) return null;
117
+ const paramMap = new Map();
118
+ const addP = (list) => {
119
+ if (!Array.isArray(list)) return;
120
+ for (const p of list) {
121
+ if (isRec(p) && typeof p.name === "string" && typeof p.in === "string") paramMap.set(p.in + ":" + p.name, p);
122
+ }
123
+ };
124
+ addP(item.parameters);
125
+ addP(op.parameters);
126
+ const sec = Array.isArray(op.security) ? op.security : Array.isArray(specObj.security) ? specObj.security : undefined;
127
+ const loc = __meta?.sourceLocations?.["/paths/" + escPtr(path) + "/" + m];
128
+ const res = { method: m.toUpperCase(), path, parameters: [...paramMap.values()] };
129
+ if (typeof op.operationId === "string") res.operationId = op.operationId;
130
+ if (typeof op.summary === "string") res.summary = op.summary;
131
+ if (typeof op.description === "string") res.description = op.description;
132
+ if (Array.isArray(op.tags)) res.tags = op.tags;
133
+ if (op.deprecated === true) res.deprecated = true;
134
+ if (sec !== undefined) res.security = sec;
135
+ if (op.requestBody !== undefined) res.requestBody = op.requestBody;
136
+ if (op.responses !== undefined) res.responses = op.responses;
137
+ if (loc) res.sourceLocation = loc;
138
+ return res;
139
+ };
140
+ const exampleHelper = (first, second, third) => {
141
+ if (typeof first === "string" && typeof second === "string") {
142
+ const op = getOp(first, second);
143
+ if (!op) return null;
144
+ const out = { method: op.method, path: op.path, responses: {} };
145
+ if (isRec(op.requestBody) && isRec(op.requestBody.content)) {
146
+ const picked = pickMedia(op.requestBody.content);
147
+ if (picked) out.requestBody = { mediaType: picked.mediaType, example: extractMediaEx(picked.media, { includeReadOnly: false, includeWriteOnly: true }) };
148
+ }
149
+ if (isRec(op.responses)) {
150
+ const codes = third !== undefined ? [String(third)] : Object.keys(op.responses);
151
+ for (const c of codes) {
152
+ const r = op.responses[c];
153
+ if (!isRec(r)) continue;
154
+ if (isRec(r.content)) {
155
+ const picked = pickMedia(r.content);
156
+ if (picked) { out.responses[c] = { mediaType: picked.mediaType, example: extractMediaEx(picked.media, { includeReadOnly: true, includeWriteOnly: false }) }; continue; }
157
+ }
158
+ if (r.schema !== undefined) out.responses[c] = { example: genExample(r.schema, { includeReadOnly: true, includeWriteOnly: false }) };
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ return genExample(first, isRec(second) ? second : {});
164
+ };
165
+ const schemaRefsHelper = (name) => {
166
+ const usages = __meta?.schemaUsages ?? {};
167
+ if (name === undefined) return usages;
168
+ return usages[String(name)] ?? [];
169
+ };
170
+ Object.defineProperty(globalThis, "helpers", {
171
+ value: Object.freeze({
172
+ op: Object.freeze(getOp),
173
+ example: Object.freeze(exampleHelper),
174
+ schemaRefs: Object.freeze(schemaRefsHelper),
175
+ }),
176
+ enumerable: true,
177
+ });
178
+ `;
179
+ const hostIdentifiers = new Set([
180
+ 'process', 'Bun', 'require', 'fetch', 'XMLHttpRequest', 'WebSocket',
181
+ 'Worker', 'SharedArrayBuffer', 'Atomics', 'eval', 'Function', 'fs', 'net',
182
+ 'child_process', 'dgram', 'dns', 'tls', 'cluster', 'v8', 'vm', '__dirname', '__filename',
183
+ ]);
184
+ const metaProperties = new Set(['constructor', '__proto__', 'prototype']);
185
+ function isNode(value) {
186
+ return value !== null && typeof value === 'object' && 'type' in value;
187
+ }
188
+ function prepareQuery(code) {
189
+ if (!code.trim() || code.length > MAX_QUERY_CODE_LENGTH) {
190
+ throw new Error(`SANDBOX_SYNTAX_ERROR: Query code must contain 1 to ${MAX_QUERY_CODE_LENGTH} characters.`);
191
+ }
192
+ // Parse exactly the source the guest will execute. An expression is tried first
193
+ // so object literals, arrow functions and optional chaining work without a return.
194
+ for (const body of [false, true]) {
195
+ const source = body ? `"use strict";\n(() => {\n${code}\n})` : `"use strict";\n(\n${code}\n)`;
196
+ let program;
197
+ try {
198
+ program = parse(source, { ecmaVersion: 'latest' });
199
+ }
200
+ catch {
201
+ continue;
202
+ }
203
+ const statement = program.body[1];
204
+ if (program.body.length !== 2 || statement?.type !== 'ExpressionStatement' ||
205
+ (body && statement.expression.type !== 'ArrowFunctionExpression')) {
206
+ continue;
207
+ }
208
+ // This check provides actionable errors for unsupported APIs. The guest
209
+ // runtime owns isolation and receives no host objects or callbacks.
210
+ const stack = [
211
+ { node: statement.expression },
212
+ ];
213
+ while (stack.length > 0) {
214
+ const { node, parent, key } = stack.pop();
215
+ const staticMember = parent?.type === 'MemberExpression' && key === 'property';
216
+ const globalMember = staticMember && isNode(parent?.object) &&
217
+ parent.object.type === 'Identifier' && parent.object.name === 'globalThis';
218
+ const objectKey = parent?.type === 'Property' && key === 'key' && !parent.computed;
219
+ if (node.type === 'ImportExpression' ||
220
+ (node.type === 'Identifier' && typeof node.name === 'string' && !objectKey &&
221
+ (staticMember && !parent?.computed
222
+ ? metaProperties.has(node.name) || (globalMember && hostIdentifiers.has(node.name))
223
+ : hostIdentifiers.has(node.name))) ||
224
+ (node.type === 'Literal' && staticMember && typeof node.value === 'string' &&
225
+ metaProperties.has(node.value))) {
226
+ throw new Error('SANDBOX_FORBIDDEN_API: Use standard synchronous JavaScript against spec.');
227
+ }
228
+ for (const [childKey, value] of Object.entries(node)) {
229
+ if (isNode(value))
230
+ stack.push({ node: value, parent: node, key: childKey });
231
+ if (Array.isArray(value)) {
232
+ for (const child of value) {
233
+ if (isNode(child))
234
+ stack.push({ node: child, parent: node, key: childKey });
235
+ }
236
+ }
237
+ }
238
+ }
239
+ return source;
240
+ }
241
+ throw new Error('SANDBOX_SYNTAX_ERROR: Use a JavaScript expression or a statement body with return.');
242
+ }
243
+ const metaJsonCache = new WeakMap();
244
+ function serializeMetadata(metadata) {
245
+ if (!metadata)
246
+ return '{}';
247
+ const cached = metaJsonCache.get(metadata);
248
+ if (cached !== undefined)
249
+ return cached;
250
+ const text = JSON.stringify(metadata);
251
+ metaJsonCache.set(metadata, text);
252
+ return text;
253
+ }
254
+ export function validateSandboxCode(code) {
255
+ prepareQuery(code);
256
+ }
257
+ /** Runs and serializes the query within one bounded guest runtime. */
258
+ export function evaluateSandboxQuery(spec, code, options = {}) {
259
+ const source = prepareQuery(code);
260
+ const specJson = serializeSpec(spec);
261
+ const configuredTimeout = options.timeoutMs;
262
+ const timeoutMs = configuredTimeout !== undefined && Number.isFinite(configuredTimeout) && configuredTimeout > 0
263
+ ? configuredTimeout
264
+ : DEFAULT_SANDBOX_TIMEOUT_MS;
265
+ let deadline = performance.now() + Math.max(BOOTSTRAP_TIMEOUT_MS, timeoutMs);
266
+ let interrupted = false;
267
+ let phase = 'bootstrap';
268
+ return Scope.withScope((scope) => {
269
+ const runtime = scope.manage(QuickJS.newRuntime());
270
+ runtime.setMemoryLimit(GUEST_MEMORY_BYTES);
271
+ runtime.setMaxStackSize(GUEST_STACK_BYTES);
272
+ runtime.setInterruptHandler(() => {
273
+ interrupted ||= performance.now() >= deadline;
274
+ return interrupted;
275
+ });
276
+ const context = scope.manage(runtime.newContext());
277
+ function unwrap(result, errorCode) {
278
+ if (result.error) {
279
+ result.error.dispose();
280
+ if (interrupted) {
281
+ if (phase === 'bootstrap') {
282
+ throw new Error('SANDBOX_LIMIT: Spec bootstrap exceeded time limit.');
283
+ }
284
+ throw new Error(`SANDBOX_TIMEOUT: Query exceeded ${timeoutMs}ms. Narrow the query.`);
285
+ }
286
+ throw new Error(`${errorCode}: Guest evaluation failed. Check the query, JSON output, and resource limits.`);
287
+ }
288
+ return scope.manage(result.value);
289
+ }
290
+ const metaJson = serializeMetadata(options.metadata);
291
+ const serialize = unwrap(context.evalCode(`
292
+ "use strict";
293
+ (() => {
294
+ const stringify = JSON.stringify;
295
+ const freeze = (value) => {
296
+ if (value !== null && typeof value === "object") {
297
+ for (const child of Object.values(value)) freeze(child);
298
+ Object.freeze(value);
299
+ }
300
+ return value;
301
+ };
302
+ const __meta = freeze(JSON.parse(${JSON.stringify(metaJson)}));
303
+ Object.defineProperty(globalThis, "spec", {
304
+ value: freeze(JSON.parse(${JSON.stringify(specJson)})), enumerable: true
305
+ });
306
+ ${GUEST_HELPERS_SOURCE}
307
+ Object.freeze(Object.prototype);
308
+ Object.freeze(Array.prototype);
309
+ return (value) => {
310
+ if (value != null && typeof value.then === "function") return false;
311
+ const text = stringify(value, null, 2);
312
+ return text?.length > ${MAX_RESULT_BYTES} ? 0 : text;
313
+ };
314
+ })()
315
+ `), 'SANDBOX_LIMIT');
316
+ // Measure query execution timeout independently of guest spec parse/freeze bootstrap.
317
+ phase = 'query';
318
+ const queryStartedAt = performance.now();
319
+ deadline = queryStartedAt + timeoutMs;
320
+ interrupted = false;
321
+ let result = unwrap(context.evalCode(source, 'openapi-query.js', { type: 'global' }), 'SANDBOX_RUNTIME_ERROR');
322
+ if (context.typeof(result) === 'function') {
323
+ const specHandle = scope.manage(context.getProp(context.global, 'spec'));
324
+ result = unwrap(context.callFunction(result, context.undefined, specHandle), 'SANDBOX_RUNTIME_ERROR');
325
+ }
326
+ const json = unwrap(context.callFunction(serialize, context.undefined, result), 'SANDBOX_RESULT_ERROR');
327
+ if (performance.now() >= deadline)
328
+ throw new Error(`SANDBOX_TIMEOUT: Query exceeded ${timeoutMs}ms.`);
329
+ const resultType = context.typeof(json);
330
+ if (resultType === 'boolean') {
331
+ throw new Error('SANDBOX_ASYNC_FORBIDDEN: Return a synchronous JSON value.');
332
+ }
333
+ const text = resultType === 'string' ? context.getString(json) : undefined;
334
+ if (resultType === 'number' || (text !== undefined && Buffer.byteLength(text) > MAX_RESULT_BYTES)) {
335
+ throw new Error(`SANDBOX_LIMIT: Serialized result exceeds ${MAX_RESULT_BYTES} bytes. Narrow the query.`);
336
+ }
337
+ return { text, durationMs: Math.round(performance.now() - queryStartedAt) };
338
+ });
339
+ }
340
+ export function runSandboxQuery(spec, code, options = {}) {
341
+ const { text, durationMs } = evaluateSandboxQuery(spec, code, options);
342
+ return { value: text === undefined ? undefined : JSON.parse(text), durationMs };
343
+ }
@@ -0,0 +1,42 @@
1
+ import { type SourceLocation } from './source-map.js';
2
+ export interface SchemaUsageRef {
3
+ method: string;
4
+ path: string;
5
+ section: string;
6
+ }
7
+ export interface SchemaSummaryItem {
8
+ name: string;
9
+ type: string;
10
+ description?: string;
11
+ required?: string[];
12
+ properties?: string[];
13
+ totalProperties?: number;
14
+ enumValues?: unknown[];
15
+ usedBy: string[];
16
+ sourceLocation?: SourceLocation;
17
+ }
18
+ export interface SchemaIndex {
19
+ title: string;
20
+ version: string;
21
+ openapiVersion: string;
22
+ specPath?: string;
23
+ totalSchemas: number;
24
+ unusedSchemas: string[];
25
+ schemas: SchemaSummaryItem[];
26
+ }
27
+ export interface SchemaSearchFilters {
28
+ q?: string;
29
+ usedByPath?: string;
30
+ unusedOnly?: boolean;
31
+ offset: number;
32
+ limit: number;
33
+ }
34
+ /**
35
+ * Builds a compact index of `components.schemas` (OpenAPI 3.x) or `definitions` (Swagger 2.0),
36
+ * enriched with reverse references (`usedBy`) and YAML/JSON `sourceLocation`.
37
+ */
38
+ export declare function buildSchemaIndex(spec: Record<string, unknown>, specPath?: string, sourceLocations?: Readonly<Record<string, SourceLocation>>, schemaUsages?: Readonly<Record<string, readonly SchemaUsageRef[]>>): SchemaIndex;
39
+ export declare function searchSchemas(entries: SchemaSummaryItem[], filters: SchemaSearchFilters): {
40
+ schemas: SchemaSummaryItem[];
41
+ totalMatches: number;
42
+ };