@dimassetoid/openapi-mcp 0.0.0-stage → 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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -2
  3. package/dist/cli/update.d.ts +38 -0
  4. package/dist/cli/update.js +235 -0
  5. package/dist/engine/budget.d.ts +40 -0
  6. package/dist/engine/budget.js +96 -0
  7. package/dist/engine/example-generator.d.ts +47 -0
  8. package/dist/engine/example-generator.js +273 -0
  9. package/dist/engine/index-builder.d.ts +50 -0
  10. package/dist/engine/index-builder.js +155 -0
  11. package/dist/engine/index.d.ts +12 -0
  12. package/dist/engine/index.js +12 -0
  13. package/dist/engine/json.d.ts +1 -0
  14. package/dist/engine/json.js +3 -0
  15. package/dist/engine/lazy-expander.d.ts +37 -0
  16. package/dist/engine/lazy-expander.js +235 -0
  17. package/dist/engine/openapi-utils.d.ts +13 -0
  18. package/dist/engine/openapi-utils.js +48 -0
  19. package/dist/engine/query-sandbox.d.ts +29 -0
  20. package/dist/engine/query-sandbox.js +345 -0
  21. package/dist/engine/schema-index.d.ts +42 -0
  22. package/dist/engine/schema-index.js +145 -0
  23. package/dist/engine/source-map.d.ts +15 -0
  24. package/dist/engine/source-map.js +50 -0
  25. package/dist/engine/spec-catalog.d.ts +14 -0
  26. package/dist/engine/spec-catalog.js +99 -0
  27. package/dist/engine/spec-diagnostics.d.ts +28 -0
  28. package/dist/engine/spec-diagnostics.js +393 -0
  29. package/dist/engine/spec-diff.d.ts +32 -0
  30. package/dist/engine/spec-diff.js +406 -0
  31. package/dist/engine/spec-loader.d.ts +100 -0
  32. package/dist/engine/spec-loader.js +528 -0
  33. package/dist/index.d.ts +49 -0
  34. package/dist/index.js +371 -0
  35. package/dist/mcp/prompts.d.ts +51 -0
  36. package/dist/mcp/prompts.js +161 -0
  37. package/dist/mcp/resources.d.ts +33 -0
  38. package/dist/mcp/resources.js +207 -0
  39. package/dist/mcp/server.d.ts +88 -0
  40. package/dist/mcp/server.js +588 -0
  41. package/dist/telemetry/telemetry.d.ts +90 -0
  42. package/dist/telemetry/telemetry.js +299 -0
  43. package/docs/feature/README.md +53 -0
  44. package/docs/feature/getting-started.md +167 -0
  45. package/docs/feature/index-and-prompts.md +53 -0
  46. package/docs/feature/openapi-query.md +53 -0
  47. package/docs/feature/spec-loader.md +34 -0
  48. package/package.json +77 -4
  49. package/skills/use-openapi-mcp/SKILL.md +43 -0
@@ -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
+ }
@@ -0,0 +1,29 @@
1
+ export declare const DEFAULT_SANDBOX_TIMEOUT_MS = 150;
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
+ }
10
+ export interface SandboxMetadata {
11
+ sourceLocations?: Readonly<Record<string, unknown>>;
12
+ schemaUsages?: Readonly<Record<string, unknown>>;
13
+ specMeta?: SandboxSpecMeta;
14
+ }
15
+ export interface SandboxQueryOptions {
16
+ timeoutMs?: number;
17
+ metadata?: SandboxMetadata;
18
+ }
19
+ export interface SandboxQueryResult {
20
+ value: unknown;
21
+ durationMs: number;
22
+ }
23
+ export declare function validateSandboxCode(code: string): void;
24
+ /** Runs and serializes the query within one bounded guest runtime. */
25
+ export declare function evaluateSandboxQuery(spec: unknown, code: string, options?: SandboxQueryOptions): {
26
+ text: string | undefined;
27
+ durationMs: number;
28
+ };
29
+ export declare function runSandboxQuery(spec: unknown, code: string, options?: SandboxQueryOptions): SandboxQueryResult;
@@ -0,0 +1,345 @@
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
+ const metaHelper = () => __meta?.specMeta ?? null;
171
+ Object.defineProperty(globalThis, "helpers", {
172
+ value: Object.freeze({
173
+ op: Object.freeze(getOp),
174
+ example: Object.freeze(exampleHelper),
175
+ schemaRefs: Object.freeze(schemaRefsHelper),
176
+ meta: Object.freeze(metaHelper),
177
+ }),
178
+ enumerable: true,
179
+ });
180
+ `;
181
+ const hostIdentifiers = new Set([
182
+ 'process', 'Bun', 'require', 'fetch', 'XMLHttpRequest', 'WebSocket',
183
+ 'Worker', 'SharedArrayBuffer', 'Atomics', 'eval', 'Function', 'fs', 'net',
184
+ 'child_process', 'dgram', 'dns', 'tls', 'cluster', 'v8', 'vm', '__dirname', '__filename',
185
+ ]);
186
+ const metaProperties = new Set(['constructor', '__proto__', 'prototype']);
187
+ function isNode(value) {
188
+ return value !== null && typeof value === 'object' && 'type' in value;
189
+ }
190
+ function prepareQuery(code) {
191
+ if (!code.trim() || code.length > MAX_QUERY_CODE_LENGTH) {
192
+ throw new Error(`SANDBOX_SYNTAX_ERROR: Query code must contain 1 to ${MAX_QUERY_CODE_LENGTH} characters.`);
193
+ }
194
+ // Parse exactly the source the guest will execute. An expression is tried first
195
+ // so object literals, arrow functions and optional chaining work without a return.
196
+ for (const body of [false, true]) {
197
+ const source = body ? `"use strict";\n(() => {\n${code}\n})` : `"use strict";\n(\n${code}\n)`;
198
+ let program;
199
+ try {
200
+ program = parse(source, { ecmaVersion: 'latest' });
201
+ }
202
+ catch {
203
+ continue;
204
+ }
205
+ const statement = program.body[1];
206
+ if (program.body.length !== 2 || statement?.type !== 'ExpressionStatement' ||
207
+ (body && statement.expression.type !== 'ArrowFunctionExpression')) {
208
+ continue;
209
+ }
210
+ // This check provides actionable errors for unsupported APIs. The guest
211
+ // runtime owns isolation and receives no host objects or callbacks.
212
+ const stack = [
213
+ { node: statement.expression },
214
+ ];
215
+ while (stack.length > 0) {
216
+ const { node, parent, key } = stack.pop();
217
+ const staticMember = parent?.type === 'MemberExpression' && key === 'property';
218
+ const globalMember = staticMember && isNode(parent?.object) &&
219
+ parent.object.type === 'Identifier' && parent.object.name === 'globalThis';
220
+ const objectKey = parent?.type === 'Property' && key === 'key' && !parent.computed;
221
+ if (node.type === 'ImportExpression' ||
222
+ (node.type === 'Identifier' && typeof node.name === 'string' && !objectKey &&
223
+ (staticMember && !parent?.computed
224
+ ? metaProperties.has(node.name) || (globalMember && hostIdentifiers.has(node.name))
225
+ : hostIdentifiers.has(node.name))) ||
226
+ (node.type === 'Literal' && staticMember && typeof node.value === 'string' &&
227
+ metaProperties.has(node.value))) {
228
+ throw new Error('SANDBOX_FORBIDDEN_API: Use standard synchronous JavaScript against spec.');
229
+ }
230
+ for (const [childKey, value] of Object.entries(node)) {
231
+ if (isNode(value))
232
+ stack.push({ node: value, parent: node, key: childKey });
233
+ if (Array.isArray(value)) {
234
+ for (const child of value) {
235
+ if (isNode(child))
236
+ stack.push({ node: child, parent: node, key: childKey });
237
+ }
238
+ }
239
+ }
240
+ }
241
+ return source;
242
+ }
243
+ throw new Error('SANDBOX_SYNTAX_ERROR: Use a JavaScript expression or a statement body with return.');
244
+ }
245
+ const metaJsonCache = new WeakMap();
246
+ function serializeMetadata(metadata) {
247
+ if (!metadata)
248
+ return '{}';
249
+ const cached = metaJsonCache.get(metadata);
250
+ if (cached !== undefined)
251
+ return cached;
252
+ const text = JSON.stringify(metadata);
253
+ metaJsonCache.set(metadata, text);
254
+ return text;
255
+ }
256
+ export function validateSandboxCode(code) {
257
+ prepareQuery(code);
258
+ }
259
+ /** Runs and serializes the query within one bounded guest runtime. */
260
+ export function evaluateSandboxQuery(spec, code, options = {}) {
261
+ const source = prepareQuery(code);
262
+ const specJson = serializeSpec(spec);
263
+ const configuredTimeout = options.timeoutMs;
264
+ const timeoutMs = configuredTimeout !== undefined && Number.isFinite(configuredTimeout) && configuredTimeout > 0
265
+ ? configuredTimeout
266
+ : DEFAULT_SANDBOX_TIMEOUT_MS;
267
+ let deadline = performance.now() + Math.max(BOOTSTRAP_TIMEOUT_MS, timeoutMs);
268
+ let interrupted = false;
269
+ let phase = 'bootstrap';
270
+ return Scope.withScope((scope) => {
271
+ const runtime = scope.manage(QuickJS.newRuntime());
272
+ runtime.setMemoryLimit(GUEST_MEMORY_BYTES);
273
+ runtime.setMaxStackSize(GUEST_STACK_BYTES);
274
+ runtime.setInterruptHandler(() => {
275
+ interrupted ||= performance.now() >= deadline;
276
+ return interrupted;
277
+ });
278
+ const context = scope.manage(runtime.newContext());
279
+ function unwrap(result, errorCode) {
280
+ if (result.error) {
281
+ result.error.dispose();
282
+ if (interrupted) {
283
+ if (phase === 'bootstrap') {
284
+ throw new Error('SANDBOX_LIMIT: Spec bootstrap exceeded time limit.');
285
+ }
286
+ throw new Error(`SANDBOX_TIMEOUT: Query exceeded ${timeoutMs}ms. Narrow the query.`);
287
+ }
288
+ throw new Error(`${errorCode}: Guest evaluation failed. Check the query, JSON output, and resource limits.`);
289
+ }
290
+ return scope.manage(result.value);
291
+ }
292
+ const metaJson = serializeMetadata(options.metadata);
293
+ const serialize = unwrap(context.evalCode(`
294
+ "use strict";
295
+ (() => {
296
+ const stringify = JSON.stringify;
297
+ const freeze = (value) => {
298
+ if (value !== null && typeof value === "object") {
299
+ for (const child of Object.values(value)) freeze(child);
300
+ Object.freeze(value);
301
+ }
302
+ return value;
303
+ };
304
+ const __meta = freeze(JSON.parse(${JSON.stringify(metaJson)}));
305
+ Object.defineProperty(globalThis, "spec", {
306
+ value: freeze(JSON.parse(${JSON.stringify(specJson)})), enumerable: true
307
+ });
308
+ ${GUEST_HELPERS_SOURCE}
309
+ Object.freeze(Object.prototype);
310
+ Object.freeze(Array.prototype);
311
+ return (value) => {
312
+ if (value != null && typeof value.then === "function") return false;
313
+ const text = stringify(value, null, 2);
314
+ return text?.length > ${MAX_RESULT_BYTES} ? 0 : text;
315
+ };
316
+ })()
317
+ `), 'SANDBOX_LIMIT');
318
+ // Measure query execution timeout independently of guest spec parse/freeze bootstrap.
319
+ phase = 'query';
320
+ const queryStartedAt = performance.now();
321
+ deadline = queryStartedAt + timeoutMs;
322
+ interrupted = false;
323
+ let result = unwrap(context.evalCode(source, 'openapi-query.js', { type: 'global' }), 'SANDBOX_RUNTIME_ERROR');
324
+ if (context.typeof(result) === 'function') {
325
+ const specHandle = scope.manage(context.getProp(context.global, 'spec'));
326
+ result = unwrap(context.callFunction(result, context.undefined, specHandle), 'SANDBOX_RUNTIME_ERROR');
327
+ }
328
+ const json = unwrap(context.callFunction(serialize, context.undefined, result), 'SANDBOX_RESULT_ERROR');
329
+ if (performance.now() >= deadline)
330
+ throw new Error(`SANDBOX_TIMEOUT: Query exceeded ${timeoutMs}ms.`);
331
+ const resultType = context.typeof(json);
332
+ if (resultType === 'boolean') {
333
+ throw new Error('SANDBOX_ASYNC_FORBIDDEN: Return a synchronous JSON value.');
334
+ }
335
+ const text = resultType === 'string' ? context.getString(json) : undefined;
336
+ if (resultType === 'number' || (text !== undefined && Buffer.byteLength(text) > MAX_RESULT_BYTES)) {
337
+ throw new Error(`SANDBOX_LIMIT: Serialized result exceeds ${MAX_RESULT_BYTES} bytes. Narrow the query.`);
338
+ }
339
+ return { text, durationMs: Math.round(performance.now() - queryStartedAt) };
340
+ });
341
+ }
342
+ export function runSandboxQuery(spec, code, options = {}) {
343
+ const { text, durationMs } = evaluateSandboxQuery(spec, code, options);
344
+ return { value: text === undefined ? undefined : JSON.parse(text), durationMs };
345
+ }