@cloudflare/codemode 0.5.6 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai.js +3 -3
- package/dist/{base-BqhlNCSH.js → base-B_Zc64P1.js} +2 -2
- package/dist/{base-BqhlNCSH.js.map → base-B_Zc64P1.js.map} +1 -1
- package/dist/browser.js +2 -2
- package/dist/index.d.ts +8 -4
- package/dist/index.js +12 -8
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-D_m9tVnI.js → json-schema-types-CtFHxrML.js} +110 -63
- package/dist/json-schema-types-CtFHxrML.js.map +1 -0
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +1 -1
- package/dist/{run-code-Q3Jh6Dcu.js → run-code-DUD_uzEK.js} +2 -2
- package/dist/{run-code-Q3Jh6Dcu.js.map → run-code-DUD_uzEK.js.map} +1 -1
- package/dist/tanstack-ai.js +2 -2
- package/package.json +1 -1
- package/dist/json-schema-types-D_m9tVnI.js.map +0 -1
|
@@ -201,6 +201,91 @@ function applyNullable(result, schema) {
|
|
|
201
201
|
return result;
|
|
202
202
|
}
|
|
203
203
|
/**
|
|
204
|
+
* Report whether a generated type has a `|` outside brackets, strings and
|
|
205
|
+
* comments. Such a type needs parentheses inside an intersection.
|
|
206
|
+
*/
|
|
207
|
+
function hasTopLevelUnion(type) {
|
|
208
|
+
let depth = 0;
|
|
209
|
+
for (let i = 0; i < type.length; i++) {
|
|
210
|
+
const ch = type[i];
|
|
211
|
+
if (ch === "\"") {
|
|
212
|
+
for (i++; i < type.length && type[i] !== "\""; i++) if (type[i] === "\\") i++;
|
|
213
|
+
} else if (ch === "/" && type[i + 1] === "*") {
|
|
214
|
+
const end = type.indexOf("*/", i + 2);
|
|
215
|
+
if (end === -1) return false;
|
|
216
|
+
i = end + 1;
|
|
217
|
+
} else if (ch === "{" || ch === "[" || ch === "(" || ch === "<") depth++;
|
|
218
|
+
else if (ch === "}" || ch === "]" || ch === ")" || ch === ">") depth--;
|
|
219
|
+
else if (ch === "|" && depth === 0) return true;
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Convert the array keywords of a schema. Does not apply `nullable`.
|
|
225
|
+
*/
|
|
226
|
+
function arrayTypeString(schema, indent, ctx) {
|
|
227
|
+
const prefixItems = schema.prefixItems;
|
|
228
|
+
if (Array.isArray(prefixItems)) return `[${prefixItems.map((s) => jsonSchemaToTypeString(s, indent, ctx)).join(", ")}]`;
|
|
229
|
+
if (Array.isArray(schema.items)) return `[${schema.items.map((s) => jsonSchemaToTypeString(s, indent, ctx)).join(", ")}]`;
|
|
230
|
+
if (schema.items) return `Array<${jsonSchemaToTypeString(schema.items, indent, ctx)}>`;
|
|
231
|
+
return "unknown[]";
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Convert the object keywords of a schema. Does not apply `nullable`.
|
|
235
|
+
*/
|
|
236
|
+
function objectTypeString(schema, indent, nextCtx) {
|
|
237
|
+
const props = schema.properties || {};
|
|
238
|
+
const required = new Set(schema.required || []);
|
|
239
|
+
const lines = [];
|
|
240
|
+
for (const [propName, propSchema] of Object.entries(props)) {
|
|
241
|
+
if (typeof propSchema === "boolean") {
|
|
242
|
+
const boolType = propSchema ? "unknown" : "never";
|
|
243
|
+
const optionalMark = required.has(propName) ? "" : "?";
|
|
244
|
+
lines.push(`${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const isRequired = required.has(propName);
|
|
248
|
+
const propType = jsonSchemaToTypeString(propSchema, indent + " ", nextCtx);
|
|
249
|
+
const desc = propSchema.description;
|
|
250
|
+
const format = propSchema.format;
|
|
251
|
+
if (desc || format) {
|
|
252
|
+
const descText = desc ? escapeJsDoc(desc.replace(/\r?\n/g, " ")) : void 0;
|
|
253
|
+
const formatTag = format ? `@format ${escapeJsDoc(format)}` : void 0;
|
|
254
|
+
if (descText && formatTag) {
|
|
255
|
+
lines.push(`${indent} /**`);
|
|
256
|
+
lines.push(`${indent} * ${descText}`);
|
|
257
|
+
lines.push(`${indent} * ${formatTag}`);
|
|
258
|
+
lines.push(`${indent} */`);
|
|
259
|
+
} else lines.push(`${indent} /** ${descText ?? formatTag} */`);
|
|
260
|
+
}
|
|
261
|
+
const quotedName = quoteProp(propName);
|
|
262
|
+
const optionalMark = isRequired ? "" : "?";
|
|
263
|
+
lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);
|
|
264
|
+
}
|
|
265
|
+
if (schema.additionalProperties) {
|
|
266
|
+
const valueType = schema.additionalProperties === true ? "unknown" : jsonSchemaToTypeString(schema.additionalProperties, indent + " ", nextCtx);
|
|
267
|
+
lines.push(`${indent} [key: string]: ${valueType};`);
|
|
268
|
+
}
|
|
269
|
+
if (lines.length === 0) {
|
|
270
|
+
if (schema.additionalProperties === false) return "{}";
|
|
271
|
+
return "Record<string, unknown>";
|
|
272
|
+
}
|
|
273
|
+
return `{\n${lines.join("\n")}\n${indent}}`;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Convert a schema as if its `type` were the single type `type`.
|
|
277
|
+
* Does not apply `nullable`.
|
|
278
|
+
*/
|
|
279
|
+
function singleTypeString(type, schema, indent, ctx) {
|
|
280
|
+
if (type === "string") return "string";
|
|
281
|
+
if (type === "number" || type === "integer") return "number";
|
|
282
|
+
if (type === "boolean") return "boolean";
|
|
283
|
+
if (type === "null") return "null";
|
|
284
|
+
if (type === "array") return arrayTypeString(schema, indent, ctx);
|
|
285
|
+
if (type === "object" || schema.properties) return objectTypeString(schema, indent, ctx);
|
|
286
|
+
return "unknown";
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
204
289
|
* Convert a JSON Schema to a TypeScript type string.
|
|
205
290
|
* This is a direct conversion without going through Zod.
|
|
206
291
|
*/
|
|
@@ -219,9 +304,24 @@ function jsonSchemaToTypeString(schema, indent, ctx) {
|
|
|
219
304
|
if (!resolved) return "unknown";
|
|
220
305
|
return applyNullable(jsonSchemaToTypeString(resolved, indent, nextCtx), schema);
|
|
221
306
|
}
|
|
222
|
-
if (schema.anyOf)
|
|
223
|
-
|
|
224
|
-
|
|
307
|
+
if (schema.anyOf) {
|
|
308
|
+
const types = schema.anyOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx));
|
|
309
|
+
if (types.length === 0) return "never";
|
|
310
|
+
return applyNullable(types.join(" | "), schema);
|
|
311
|
+
}
|
|
312
|
+
if (schema.oneOf) {
|
|
313
|
+
const types = schema.oneOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx));
|
|
314
|
+
if (types.length === 0) return "never";
|
|
315
|
+
return applyNullable(types.join(" | "), schema);
|
|
316
|
+
}
|
|
317
|
+
if (schema.allOf) {
|
|
318
|
+
const types = schema.allOf.map((s) => {
|
|
319
|
+
const member = jsonSchemaToTypeString(s, indent, nextCtx);
|
|
320
|
+
return hasTopLevelUnion(member) ? `(${member})` : member;
|
|
321
|
+
});
|
|
322
|
+
if (types.length === 0) return "unknown";
|
|
323
|
+
return applyNullable(types.join(" & "), schema);
|
|
324
|
+
}
|
|
225
325
|
if (schema.enum) {
|
|
226
326
|
if (schema.enum.length === 0) return "never";
|
|
227
327
|
return applyNullable(schema.enum.map((v) => {
|
|
@@ -233,66 +333,13 @@ function jsonSchemaToTypeString(schema, indent, ctx) {
|
|
|
233
333
|
}
|
|
234
334
|
if (schema.const !== void 0) return applyNullable(schema.const === null ? "null" : typeof schema.const === "string" ? "\"" + escapeStringLiteral(schema.const) + "\"" : typeof schema.const === "object" ? JSON.stringify(schema.const) ?? "unknown" : String(schema.const), schema);
|
|
235
335
|
const type = schema.type;
|
|
236
|
-
if (type
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
if (type === "array") {
|
|
241
|
-
const prefixItems = schema.prefixItems;
|
|
242
|
-
if (Array.isArray(prefixItems)) return applyNullable(`[${prefixItems.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
|
|
243
|
-
if (Array.isArray(schema.items)) return applyNullable(`[${schema.items.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
|
|
244
|
-
if (schema.items) return applyNullable(`${jsonSchemaToTypeString(schema.items, indent, nextCtx)}[]`, schema);
|
|
245
|
-
return applyNullable("unknown[]", schema);
|
|
246
|
-
}
|
|
247
|
-
if (type === "object" || schema.properties) {
|
|
248
|
-
const props = schema.properties || {};
|
|
249
|
-
const required = new Set(schema.required || []);
|
|
250
|
-
const lines = [];
|
|
251
|
-
for (const [propName, propSchema] of Object.entries(props)) {
|
|
252
|
-
if (typeof propSchema === "boolean") {
|
|
253
|
-
const boolType = propSchema ? "unknown" : "never";
|
|
254
|
-
const optionalMark = required.has(propName) ? "" : "?";
|
|
255
|
-
lines.push(`${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`);
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
const isRequired = required.has(propName);
|
|
259
|
-
const propType = jsonSchemaToTypeString(propSchema, indent + " ", nextCtx);
|
|
260
|
-
const desc = propSchema.description;
|
|
261
|
-
const format = propSchema.format;
|
|
262
|
-
if (desc || format) {
|
|
263
|
-
const descText = desc ? escapeJsDoc(desc.replace(/\r?\n/g, " ")) : void 0;
|
|
264
|
-
const formatTag = format ? `@format ${escapeJsDoc(format)}` : void 0;
|
|
265
|
-
if (descText && formatTag) {
|
|
266
|
-
lines.push(`${indent} /**`);
|
|
267
|
-
lines.push(`${indent} * ${descText}`);
|
|
268
|
-
lines.push(`${indent} * ${formatTag}`);
|
|
269
|
-
lines.push(`${indent} */`);
|
|
270
|
-
} else lines.push(`${indent} /** ${descText ?? formatTag} */`);
|
|
271
|
-
}
|
|
272
|
-
const quotedName = quoteProp(propName);
|
|
273
|
-
const optionalMark = isRequired ? "" : "?";
|
|
274
|
-
lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);
|
|
275
|
-
}
|
|
276
|
-
if (schema.additionalProperties) {
|
|
277
|
-
const valueType = schema.additionalProperties === true ? "unknown" : jsonSchemaToTypeString(schema.additionalProperties, indent + " ", nextCtx);
|
|
278
|
-
lines.push(`${indent} [key: string]: ${valueType};`);
|
|
279
|
-
}
|
|
280
|
-
if (lines.length === 0) {
|
|
281
|
-
if (schema.additionalProperties === false) return applyNullable("{}", schema);
|
|
282
|
-
return applyNullable("Record<string, unknown>", schema);
|
|
283
|
-
}
|
|
284
|
-
return applyNullable(`{\n${lines.join("\n")}\n${indent}}`, schema);
|
|
336
|
+
if (Array.isArray(type)) {
|
|
337
|
+
const types = new Set(type.map((t) => singleTypeString(t, schema, indent, nextCtx)));
|
|
338
|
+
if (types.size === 0 || types.has("unknown")) return "unknown";
|
|
339
|
+
return applyNullable([...types].join(" | "), schema);
|
|
285
340
|
}
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
if (t === "number" || t === "integer") return "number";
|
|
289
|
-
if (t === "boolean") return "boolean";
|
|
290
|
-
if (t === "null") return "null";
|
|
291
|
-
if (t === "array") return "unknown[]";
|
|
292
|
-
if (t === "object") return "Record<string, unknown>";
|
|
293
|
-
return "unknown";
|
|
294
|
-
}).join(" | "), schema);
|
|
295
|
-
return "unknown";
|
|
341
|
+
if (type === "null") return "null";
|
|
342
|
+
return applyNullable(singleTypeString(type, schema, indent, nextCtx), schema);
|
|
296
343
|
} finally {
|
|
297
344
|
ctx.seen.delete(schema);
|
|
298
345
|
}
|
|
@@ -370,4 +417,4 @@ ${availableTools}
|
|
|
370
417
|
//#endregion
|
|
371
418
|
export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, normalizeCode as s, generateTypesFromJsonSchema as t };
|
|
372
419
|
|
|
373
|
-
//# sourceMappingURL=json-schema-types-
|
|
420
|
+
//# sourceMappingURL=json-schema-types-CtFHxrML.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema-types-CtFHxrML.js","names":[],"sources":["../src/normalize.ts","../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Report whether a generated type has a `|` outside brackets, strings and\n * comments. Such a type needs parentheses inside an intersection.\n */\nfunction hasTopLevelUnion(type: string): boolean {\n let depth = 0;\n for (let i = 0; i < type.length; i++) {\n const ch = type[i];\n if (ch === '\"') {\n for (i++; i < type.length && type[i] !== '\"'; i++) {\n if (type[i] === \"\\\\\") i++;\n }\n } else if (ch === \"/\" && type[i + 1] === \"*\") {\n const end = type.indexOf(\"*/\", i + 2);\n if (end === -1) return false;\n i = end + 1;\n } else if (ch === \"{\" || ch === \"[\" || ch === \"(\" || ch === \"<\") {\n depth++;\n } else if (ch === \"}\" || ch === \"]\" || ch === \")\" || ch === \">\") {\n depth--;\n } else if (ch === \"|\" && depth === 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Convert the array keywords of a schema. Does not apply `nullable`.\n */\nfunction arrayTypeString(\n schema: JSONSchema7,\n indent: string,\n ctx: ConversionContext\n): string {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, ctx)\n );\n return `[${types.join(\", \")}]`;\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, ctx)\n );\n return `[${types.join(\", \")}]`;\n }\n\n if (schema.items) {\n // Array<T>, not T[]: `[]` binds tighter than `|` and `&`, so a union or\n // intersection item type would otherwise leak out of the array.\n return `Array<${jsonSchemaToTypeString(schema.items, indent, ctx)}>`;\n }\n return \"unknown[]\";\n}\n\n/**\n * Convert the object keywords of a schema. Does not apply `nullable`.\n */\nfunction objectTypeString(\n schema: JSONSchema7,\n indent: string,\n nextCtx: ConversionContext\n): string {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format ? `@format ${escapeJsDoc(format)}` : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return \"{}\";\n }\n return \"Record<string, unknown>\";\n }\n\n return `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n}\n\n/**\n * Convert a schema as if its `type` were the single type `type`.\n * Does not apply `nullable`.\n */\nfunction singleTypeString(\n type: string | undefined,\n schema: JSONSchema7,\n indent: string,\n ctx: ConversionContext\n): string {\n if (type === \"string\") return \"string\";\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"boolean\";\n if (type === \"null\") return \"null\";\n if (type === \"array\") return arrayTypeString(schema, indent, ctx);\n if (type === \"object\" || schema.properties) {\n return objectTypeString(schema, indent, ctx);\n }\n return \"unknown\";\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n if (types.length === 0) return \"never\";\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n if (types.length === 0) return \"never\";\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n // `&` binds tighter than `|`, so a union member needs parentheses.\n const types = schema.allOf.map((s) => {\n const member = jsonSchemaToTypeString(s, indent, nextCtx);\n return hasTopLevelUnion(member) ? `(${member})` : member;\n });\n if (types.length === 0) return \"unknown\";\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n // Array of types (e.g., [\"string\", \"null\"]). Each member reads the\n // schema's own keywords, so [\"array\", \"null\"] keeps `items` and\n // [\"object\", \"null\"] keeps `properties`.\n if (Array.isArray(type)) {\n const types = new Set(\n type.map((t) => singleTypeString(t, schema, indent, nextCtx))\n );\n if (types.size === 0 || types.has(\"unknown\")) return \"unknown\";\n return applyNullable([...types].join(\" | \"), schema);\n }\n\n if (type === \"null\") return \"null\";\n return applyNullable(\n singleTypeString(type, schema, indent, nextCtx),\n schema\n );\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MAAM,oEAAM;CAC/B,OAAO,QAAQ,MAAM,KAAK;AAC5B;AAEA,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,KAAK,CAAC;CAC3C,IAAI,CAAC,QAAQ,KAAK,GAAG,OAAO;CAE5B,MAAM,SAAS,Q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,EAAE;GACzD,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;GACpF,kBAAkB;EACpB;CACF;CAEA,iBAAiB,8BAA8B,eAAe;CAE9D,OAAO;EACP,eAAe;EACf,eAAe;IACb,KAAK;AACT"}
|
package/dist/mcp.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-
|
|
1
|
+
import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CtFHxrML.js";
|
|
2
2
|
import { n as truncateResult } from "./truncate-Dd-VZZYQ.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -69,7 +69,7 @@ async function codeMcpServer(options) {
|
|
|
69
69
|
const client = new Client({
|
|
70
70
|
name: "codemode-proxy",
|
|
71
71
|
version: "1.0.0"
|
|
72
|
-
});
|
|
72
|
+
}, { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() });
|
|
73
73
|
await client.connect(clientTransport);
|
|
74
74
|
const { tools } = await client.listTools();
|
|
75
75
|
const toolDescriptors = {};
|
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ServerNotification,\n ServerRequest\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { truncateResult } from \"./truncate\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\n/** Character budget for a tool response (~6,000 tokens). */\nconst MAX_RESPONSE_CHARS = 24_000;\n\n/**\n * Model-facing text for a sandbox or executor result. Strings are clipped to\n * the budget; structured values are truncated structurally (largest values\n * first) so the text stays valid JSON. The budget applies to the emitted text:\n * pretty-printed when that still fits, compact otherwise.\n */\nfunction responseText(content: unknown): string {\n const shaped = truncateResult(content, { maxChars: MAX_RESPONSE_CHARS });\n if (typeof shaped === \"string\") return shaped;\n const pretty = JSON.stringify(shaped, null, 2) ?? \"undefined\";\n return pretty.length <= MAX_RESPONSE_CHARS\n ? pretty\n : (JSON.stringify(shaped) ?? \"undefined\");\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n/**\n * MCP context for the outer `execute` tool call.\n *\n * This remains in trusted host code and is never exposed to the sandbox.\n * Use it only while the outer tool call is active.\n */\nexport type OpenApiMcpRequestContext = RequestHandlerExtra<\n ServerRequest,\n ServerNotification\n>;\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n /**\n * Handle an API request from sandbox code on the trusted host.\n *\n * The context belongs to the outer MCP `execute` tool call. It can be used\n * to associate elicitation, sampling, roots, and notifications with that\n * call's response stream.\n *\n * This callback runs while the sandbox is still suspended on its\n * `codemode.request()` call, so the executor timeout covers the whole wait.\n * The default executor timeout (60s) matches the elicitation timeout, so the\n * default config already lets an elicitation finish. If you lower the\n * executor timeout below the elicitation timeout, the sandbox aborts the\n * call before the user can respond.\n */\n request: (\n options: RequestOptions,\n context: OpenApiMcpRequestContext\n ) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn await (${normalized})();\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer(\n { name, version },\n { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }\n );\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }, context) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) =>\n requestFn(args as RequestOptions, context)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAM,qBAAqB;;;;;;;AAQ3B,SAAS,aAAa,SAA0B;CAC9C,MAAM,SAAS,eAAe,SAAS,EAAE,UAAU,mBAAmB,CAAC;CACvE,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,KAAK;CAClD,OAAO,OAAO,UAAU,qBACpB,SACC,KAAK,UAAU,MAAM,KAAK;AACjC;AAEA,SAAS,YAAY,OAAwB;CAC3C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;;;;;;;AAgBA,SAAS,gBAAgB,QAAiC;CACxD,IAAI,gBAAgB,QAClB,OAAO,OAAO;CAGhB,IAAI,OAAO,SAAS;EAClB,MAAM,MACJ,OAAO,QACJ,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,CAChC,KAAK,MAAO,UAAU,IAAI,EAAE,OAAO,EAAG,CAAC,CACvC,KAAK,IAAI,KAAK;EACnB,MAAM,IAAI,MAAM,GAAG;CACrB;CAEA,IAAI,OAAO,qBAAqB,MAC9B,OAAO,OAAO;CAKhB,IADE,OAAO,QAAQ,SAAS,KAAK,OAAO,QAAQ,OAAO,MAAM,EAAE,SAAS,MAAM,GAC/D;EACX,MAAM,OAAO,OAAO,QACjB,K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C7C;GACF,CACF,CACF;GACA,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;IAAQ,CAC1D;IACA,SAAS;GACX;GAEF,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,aAAa,OAAO,MAAM;GAAE,CAC7D,EACF;EACF,SAAS,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ServerNotification,\n ServerRequest\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { truncateResult } from \"./truncate\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\n/** Character budget for a tool response (~6,000 tokens). */\nconst MAX_RESPONSE_CHARS = 24_000;\n\n/**\n * Model-facing text for a sandbox or executor result. Strings are clipped to\n * the budget; structured values are truncated structurally (largest values\n * first) so the text stays valid JSON. The budget applies to the emitted text:\n * pretty-printed when that still fits, compact otherwise.\n */\nfunction responseText(content: unknown): string {\n const shaped = truncateResult(content, { maxChars: MAX_RESPONSE_CHARS });\n if (typeof shaped === \"string\") return shaped;\n const pretty = JSON.stringify(shaped, null, 2) ?? \"undefined\";\n return pretty.length <= MAX_RESPONSE_CHARS\n ? pretty\n : (JSON.stringify(shaped) ?? \"undefined\");\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client(\n { name: \"codemode-proxy\", version: \"1.0.0\" },\n { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }\n );\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n/**\n * MCP context for the outer `execute` tool call.\n *\n * This remains in trusted host code and is never exposed to the sandbox.\n * Use it only while the outer tool call is active.\n */\nexport type OpenApiMcpRequestContext = RequestHandlerExtra<\n ServerRequest,\n ServerNotification\n>;\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n /**\n * Handle an API request from sandbox code on the trusted host.\n *\n * The context belongs to the outer MCP `execute` tool call. It can be used\n * to associate elicitation, sampling, roots, and notifications with that\n * call's response stream.\n *\n * This callback runs while the sandbox is still suspended on its\n * `codemode.request()` call, so the executor timeout covers the whole wait.\n * The default executor timeout (60s) matches the elicitation timeout, so the\n * default config already lets an elicitation finish. If you lower the\n * executor timeout below the elicitation timeout, the sandbox aborts the\n * call before the user can respond.\n */\n request: (\n options: RequestOptions,\n context: OpenApiMcpRequestContext\n ) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn await (${normalized})();\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer(\n { name, version },\n { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }\n );\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }, context) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) =>\n requestFn(args as RequestOptions, context)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n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AEA,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as normalizeCode } from "./json-schema-types-
|
|
1
|
+
import { s as normalizeCode } from "./json-schema-types-CtFHxrML.js";
|
|
2
2
|
//#region src/run-code.ts
|
|
3
3
|
async function runCode({ code, executor, providers, connectors }) {
|
|
4
4
|
const executeResult = await executor.execute(normalizeCode(code), providers, connectors?.length ? { connectors } : void 0);
|
|
@@ -14,4 +14,4 @@ async function runCode({ code, executor, providers, connectors }) {
|
|
|
14
14
|
//#endregion
|
|
15
15
|
export { runCode as t };
|
|
16
16
|
|
|
17
|
-
//# sourceMappingURL=run-code-
|
|
17
|
+
//# sourceMappingURL=run-code-DUD_uzEK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-code-
|
|
1
|
+
{"version":3,"file":"run-code-DUD_uzEK.js","names":[],"sources":["../src/run-code.ts"],"sourcesContent":["import type { CodeOutput } from \"./shared\";\nimport type { Executor, ResolvedProvider, ConnectorBinding } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nexport async function runCode({\n code,\n executor,\n providers,\n connectors\n}: {\n code: string;\n executor: Executor;\n providers: ResolvedProvider[];\n connectors?: ConnectorBinding[];\n}): Promise<CodeOutput> {\n const executeResult = await executor.execute(\n normalizeCode(code),\n providers,\n connectors?.length ? { connectors } : undefined\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n return executeResult.logs?.length\n ? { result: executeResult.result, logs: executeResult.logs }\n : { result: executeResult.result };\n}\n"],"mappings":";;AAIA,eAAsB,QAAQ,EAC5B,MACA,UACA,WACA,cAMsB;CACtB,MAAM,gBAAgB,MAAM,SAAS,QACnC,cAAc,IAAI,GAClB,WACA,YAAY,SAAS,EAAE,WAAW,IAAI,KAAA,CACxC;CAEA,IAAI,cAAc,OAAO;EACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,IAAI,MACpD;EACJ,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,QAAQ;CAC1E;CAEA,OAAO,cAAc,MAAM,SACvB;EAAE,QAAQ,cAAc;EAAQ,MAAM,cAAc;CAAK,IACzD,EAAE,QAAQ,cAAc,OAAO;AACrC"}
|
package/dist/tanstack-ai.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-
|
|
2
|
-
import { t as runCode } from "./run-code-
|
|
1
|
+
import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-CtFHxrML.js";
|
|
2
|
+
import { t as runCode } from "./run-code-DUD_uzEK.js";
|
|
3
3
|
import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-34dC47Il.js";
|
|
4
4
|
import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-SMjV5yN4.js";
|
|
5
5
|
import { z } from "zod";
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"json-schema-types-D_m9tVnI.js","names":[],"sources":["../src/normalize.ts","../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MAAM,oEAAM;CAC/B,OAAO,QAAQ,MAAM,KAAK;AAC5B;AAEA,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,KAAK,CAAC;CAC3C,IAAI,CAAC,QAAQ,KAAK,GAAG,OAAO;CAE5B,MAAM,SAAS,QAAQ,KAAK;CAE5B,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;EACd,CAAC;EAGD,IAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,EAAE,CAAC,SAAS;OAClC,IA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