@cloudflare/codemode 0.1.3 → 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.
package/README.md CHANGED
@@ -9,9 +9,15 @@ Code Mode generates TypeScript type definitions from your tools for LLM context,
9
9
  ## Installation
10
10
 
11
11
  ```sh
12
+ # Full AI SDK integration
12
13
  npm install @cloudflare/codemode agents ai zod
14
+
15
+ # Utilities only (no ai/zod peer deps needed)
16
+ npm install @cloudflare/codemode
13
17
  ```
14
18
 
19
+ The main entry point (`@cloudflare/codemode`) has **no peer dependency on `ai` or `zod`**. The `ai` and `zod` packages are only required when importing from `@cloudflare/codemode/ai`.
20
+
15
21
  ## Quick Start
16
22
 
17
23
  `createCodeTool` takes your tools and an executor, and returns a single AI SDK tool that lets the LLM write code instead of making individual tool calls.
@@ -223,31 +229,70 @@ const codemode = createCodeTool({
223
229
 
224
230
  ## Utilities
225
231
 
226
- ### `generateTypes(tools)`
232
+ ### `sanitizeToolName(name)`
227
233
 
228
- Generates TypeScript type definitions from your tools. Used internally by `createCodeTool` but exported for custom use (e.g. displaying types in a frontend).
234
+ Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words.
229
235
 
230
236
  ```ts
231
- import { generateTypes } from "@cloudflare/codemode";
237
+ import { sanitizeToolName } from "@cloudflare/codemode";
238
+
239
+ sanitizeToolName("my-tool"); // "my_tool"
240
+ sanitizeToolName("3d-render"); // "_3d_render"
241
+ sanitizeToolName("delete"); // "delete_"
242
+ ```
243
+
244
+ ### `normalizeCode(code)`
245
+
246
+ Normalizes LLM-generated code into a valid async arrow function. Strips markdown code fences, handles various function formats.
247
+
248
+ ````ts
249
+ import { normalizeCode } from "@cloudflare/codemode";
250
+
251
+ normalizeCode("```js\nconst x = 1;\nx\n```");
252
+ // "async () => {\nconst x = 1;\nreturn (x)\n}"
253
+ ````
232
254
 
233
- const types = generateTypes(myTools);
255
+ ### `generateTypesFromJsonSchema(tools)`
256
+
257
+ Generates TypeScript type definitions from tool descriptors with plain JSON Schema. No AI SDK or Zod dependency required.
258
+
259
+ ```ts
260
+ import { generateTypesFromJsonSchema } from "@cloudflare/codemode";
261
+
262
+ const types = generateTypesFromJsonSchema({
263
+ getWeather: {
264
+ description: "Get weather for a city",
265
+ inputSchema: {
266
+ type: "object",
267
+ properties: {
268
+ city: { type: "string", description: "City name" }
269
+ },
270
+ required: ["city"]
271
+ }
272
+ }
273
+ });
234
274
  // Returns TypeScript declarations like:
235
- // type CreateProjectInput = { name: string; description?: string }
236
- // declare const codemode: { createProject: (input: CreateProjectInput) => Promise<...>; }
275
+ // type GetWeatherInput = { city: string }
276
+ // declare const codemode: { getWeather: (input: GetWeatherInput) => Promise<...>; }
237
277
  ```
238
278
 
239
- ### `sanitizeToolName(name)`
279
+ ### `generateTypes(tools)` (AI SDK)
240
280
 
241
- Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words.
281
+ Generates TypeScript type definitions from AI SDK tools or Zod-based tool descriptors. Requires `ai` and `zod` peer dependencies.
242
282
 
243
283
  ```ts
244
- import { sanitizeToolName } from "@cloudflare/codemode";
284
+ import { generateTypes } from "@cloudflare/codemode/ai";
245
285
 
246
- sanitizeToolName("my-tool"); // "my_tool"
247
- sanitizeToolName("3d-render"); // "_3d_render"
248
- sanitizeToolName("delete"); // "delete_"
286
+ const types = generateTypes(myAiSdkTools);
249
287
  ```
250
288
 
289
+ ## Module Structure
290
+
291
+ | Module | Requires `ai`/`zod` | Exports |
292
+ | ------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
293
+ | `@cloudflare/codemode` | No | `sanitizeToolName`, `normalizeCode`, `generateTypesFromJsonSchema`, `jsonSchemaToType`, `DynamicWorkerExecutor`, `ToolDispatcher` |
294
+ | `@cloudflare/codemode/ai` | Yes | `createCodeTool`, `generateTypes`, `ToolDescriptor`, `ToolDescriptors` |
295
+
251
296
  ## Limitations
252
297
 
253
298
  - **Tool approval (`needsApproval`) is not supported yet.** Tools with `needsApproval: true` execute immediately inside the sandbox without pausing for approval. Support for approval flows within codemode is planned. For now, do not pass approval-required tools to `createCodeTool` — use them through standard AI SDK tool calling instead.
package/dist/ai.d.ts CHANGED
@@ -1,7 +1,24 @@
1
- import { i as Executor, s as ToolDescriptors } from "./executor-BYZZhAgd.js";
1
+ import { i as Executor } from "./executor-BjlGw-Dd.js";
2
2
  import { Tool, ToolSet } from "ai";
3
- import { z } from "zod";
3
+ import { ZodType, z } from "zod";
4
4
 
5
+ //#region src/tool-types.d.ts
6
+ interface ToolDescriptor {
7
+ description?: string;
8
+ inputSchema: ZodType;
9
+ outputSchema?: ZodType;
10
+ execute?: (args: unknown) => Promise<unknown>;
11
+ }
12
+ type ToolDescriptors = Record<string, ToolDescriptor>;
13
+ /**
14
+ * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
15
+ * These types can be included in tool descriptions to help LLMs write correct code.
16
+ *
17
+ * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
18
+ * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
19
+ */
20
+ declare function generateTypes(tools: ToolDescriptors | ToolSet): string;
21
+ //#endregion
5
22
  //#region src/tool.d.ts
6
23
  interface CreateCodeToolOptions {
7
24
  tools: ToolDescriptors | ToolSet;
@@ -27,5 +44,11 @@ declare function createCodeTool(
27
44
  options: CreateCodeToolOptions
28
45
  ): Tool<CodeInput, CodeOutput>;
29
46
  //#endregion
30
- export { type CreateCodeToolOptions, createCodeTool };
47
+ export {
48
+ type CreateCodeToolOptions,
49
+ type ToolDescriptor,
50
+ type ToolDescriptors,
51
+ createCodeTool,
52
+ generateTypes
53
+ };
31
54
  //# sourceMappingURL=ai.d.ts.map
package/dist/ai.js CHANGED
@@ -1,6 +1,157 @@
1
- import { n as generateTypes, r as sanitizeToolName, t as normalizeCode } from "./normalize-Dy5d7PfI.js";
1
+ import { a as escapeJsDoc, i as jsonSchemaToTypeString, o as sanitizeToolName, s as toPascalCase, t as normalizeCode } from "./normalize-xNh5CsfI.js";
2
2
  import { asSchema, tool } from "ai";
3
3
  import { z } from "zod";
4
+ //#region src/tool-types.ts
5
+ /**
6
+ * Check if a value is a Zod schema (has _zod property).
7
+ */
8
+ function isZodSchema(value) {
9
+ return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
10
+ }
11
+ /**
12
+ * Check if a value conforms to the Standard Schema protocol (~standard).
13
+ * This catches Zod v3 schemas (which expose ~standard but not _zod).
14
+ */
15
+ function isStandardSchema(value) {
16
+ return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
17
+ }
18
+ /**
19
+ * Check if a value is an AI SDK jsonSchema wrapper.
20
+ * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
21
+ */
22
+ function isJsonSchemaWrapper(value) {
23
+ if (value === null || typeof value !== "object") return false;
24
+ if ("jsonSchema" in value) return true;
25
+ const symbols = Object.getOwnPropertySymbols(value);
26
+ for (const sym of symbols) {
27
+ const symValue = value[sym];
28
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
29
+ }
30
+ return false;
31
+ }
32
+ /**
33
+ * Extract JSON schema from an AI SDK jsonSchema wrapper.
34
+ */
35
+ function extractJsonSchema(wrapper) {
36
+ if (wrapper === null || typeof wrapper !== "object") return null;
37
+ if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
38
+ const symbols = Object.getOwnPropertySymbols(wrapper);
39
+ for (const sym of symbols) {
40
+ const symValue = wrapper[sym];
41
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
42
+ }
43
+ return null;
44
+ }
45
+ /**
46
+ * Extract field descriptions from a schema.
47
+ * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
48
+ */
49
+ function extractDescriptions(schema) {
50
+ const descriptions = {};
51
+ const shape = schema.shape;
52
+ if (shape && typeof shape === "object") {
53
+ for (const [fieldName, fieldSchema] of Object.entries(shape)) {
54
+ let s = fieldSchema;
55
+ while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
56
+ if (s.description) descriptions[fieldName] = s.description;
57
+ }
58
+ return descriptions;
59
+ }
60
+ if (isJsonSchemaWrapper(schema)) {
61
+ const jsonSchema = extractJsonSchema(schema);
62
+ if (jsonSchema?.properties) {
63
+ for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
64
+ }
65
+ }
66
+ return descriptions;
67
+ }
68
+ /**
69
+ * Extract field descriptions from a schema and format as @param lines.
70
+ */
71
+ function extractParamDescriptions(schema) {
72
+ const descriptions = extractDescriptions(schema);
73
+ return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
74
+ }
75
+ /**
76
+ * Safely convert a schema to TypeScript type string.
77
+ * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
78
+ */
79
+ function safeSchemaToTs(schema, typeName) {
80
+ try {
81
+ if (isZodSchema(schema) || isStandardSchema(schema)) {
82
+ const jsonSchema = asSchema(schema).jsonSchema;
83
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
84
+ root: jsonSchema,
85
+ depth: 0,
86
+ seen: /* @__PURE__ */ new Set(),
87
+ maxDepth: 20
88
+ })}`;
89
+ }
90
+ if (isJsonSchemaWrapper(schema)) {
91
+ const jsonSchema = extractJsonSchema(schema);
92
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
93
+ root: jsonSchema,
94
+ depth: 0,
95
+ seen: /* @__PURE__ */ new Set(),
96
+ maxDepth: 20
97
+ })}`;
98
+ }
99
+ return `type ${typeName} = unknown`;
100
+ } catch {
101
+ return `type ${typeName} = unknown`;
102
+ }
103
+ }
104
+ /**
105
+ * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
106
+ * These types can be included in tool descriptions to help LLMs write correct code.
107
+ *
108
+ * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
109
+ * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
110
+ */
111
+ function generateTypes(tools) {
112
+ let availableTools = "";
113
+ let availableTypes = "";
114
+ for (const [toolName, tool] of Object.entries(tools)) {
115
+ const safeName = sanitizeToolName(toolName);
116
+ const typeName = toPascalCase(safeName);
117
+ try {
118
+ const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
119
+ const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
120
+ const description = tool.description;
121
+ const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
122
+ const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
123
+ availableTypes += `\n${inputType.trim()}`;
124
+ availableTypes += `\n${outputType.trim()}`;
125
+ const paramDescs = (() => {
126
+ try {
127
+ return inputSchema ? extractParamDescriptions(inputSchema) : [];
128
+ } catch {
129
+ return [];
130
+ }
131
+ })();
132
+ const jsdocLines = [];
133
+ if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
134
+ else jsdocLines.push(escapeJsDoc(toolName));
135
+ for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
136
+ const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
137
+ availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
138
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
139
+ availableTools += "\n";
140
+ } catch {
141
+ availableTypes += `\ntype ${typeName}Input = unknown`;
142
+ availableTypes += `\ntype ${typeName}Output = unknown`;
143
+ availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
144
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
145
+ availableTools += "\n";
146
+ }
147
+ }
148
+ availableTools = `\ndeclare const codemode: {${availableTools}}`;
149
+ return `
150
+ ${availableTypes}
151
+ ${availableTools}
152
+ `.trim();
153
+ }
154
+ //#endregion
4
155
  //#region src/tool.ts
5
156
  const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
6
157
 
@@ -60,6 +211,6 @@ function createCodeTool(options) {
60
211
  });
61
212
  }
62
213
  //#endregion
63
- export { createCodeTool };
214
+ export { createCodeTool, generateTypes };
64
215
 
65
216
  //# sourceMappingURL=ai.js.map
package/dist/ai.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.js","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, sanitizeToolName, type ToolDescriptors } from \"./types\";\nimport type { Executor } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst DEFAULT_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\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\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(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;AAOA,MAAM,sBAAsB;;;;;;;;;;AAoB5B,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE,CAAC;;;;;;;AAWF,SAAS,iBAAiB,GAAqC;AAC7D,QAAO,mBAAmB,KAAK,EAAE,iB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],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): 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 inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\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","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst DEFAULT_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\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\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(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,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KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,MACD;EAIC,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAI3B,MAAM,MAAgE,EAAE;AAExE,QAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;IAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;AACN,QAAI,SAAS;KACX,MAAM,YACJ,iBAAiB,IACb,EAAE,cACF,gBAAgB,IACb,EAA8B,aAC/B,KAAA;KAKR,MAAM,SAAS,aAAa,OAAO,SAAS,UAAU,GAAG,KAAA;AAEzD,SAAI,iBAAiB,KAAK,IAAI,QAAQ,WAClC,OAAO,SAAkB;MACvB,MAAM,SAAS,MAAM,OAAO,SAAU,KAAK;AAC3C,UAAI,CAAC,OAAO,QAAS,OAAM,OAAO;AAClC,aAAO,QAAQ,OAAO,MAAM;SAE9B;;;GAIR,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QAAQ,gBAAgB,IAAI;AAEjE,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
@@ -1,27 +1,5 @@
1
1
  import { RpcTarget } from "cloudflare:workers";
2
- import { ToolSet } from "ai";
3
- import { ZodType } from "zod";
4
2
 
5
- //#region src/types.d.ts
6
- /**
7
- * Sanitize a tool name into a valid JavaScript identifier.
8
- * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,
9
- * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.
10
- */
11
- declare function sanitizeToolName(name: string): string;
12
- interface ToolDescriptor {
13
- description?: string;
14
- inputSchema: ZodType;
15
- outputSchema?: ZodType;
16
- execute?: (args: unknown) => Promise<unknown>;
17
- }
18
- type ToolDescriptors = Record<string, ToolDescriptor>;
19
- /**
20
- * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
21
- * These types can be included in tool descriptions to help LLMs write correct code.
22
- */
23
- declare function generateTypes(tools: ToolDescriptors | ToolSet): string;
24
- //#endregion
25
3
  //#region src/executor.d.ts
26
4
  interface ExecuteResult {
27
5
  result: unknown;
@@ -84,13 +62,9 @@ declare class DynamicWorkerExecutor implements Executor {
84
62
  //#endregion
85
63
  export {
86
64
  ToolDispatcher as a,
87
- generateTypes as c,
88
65
  Executor as i,
89
- sanitizeToolName as l,
90
66
  DynamicWorkerExecutorOptions as n,
91
- ToolDescriptor as o,
92
67
  ExecuteResult as r,
93
- ToolDescriptors as s,
94
68
  DynamicWorkerExecutor as t
95
69
  };
96
- //# sourceMappingURL=executor-BYZZhAgd.d.ts.map
70
+ //# sourceMappingURL=executor-BjlGw-Dd.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,15 +1,49 @@
1
1
  import {
2
2
  a as ToolDispatcher,
3
- c as generateTypes,
4
3
  i as Executor,
5
- l as sanitizeToolName,
6
4
  n as DynamicWorkerExecutorOptions,
7
- o as ToolDescriptor,
8
5
  r as ExecuteResult,
9
- s as ToolDescriptors,
10
6
  t as DynamicWorkerExecutor
11
- } from "./executor-BYZZhAgd.js";
7
+ } from "./executor-BjlGw-Dd.js";
8
+ import { JSONSchema7 } from "json-schema";
12
9
 
10
+ //#region src/utils.d.ts
11
+ /**
12
+ * Sanitize a tool name into a valid JavaScript identifier.
13
+ * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,
14
+ * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.
15
+ */
16
+ declare function sanitizeToolName(name: string): string;
17
+ //#endregion
18
+ //#region src/json-schema-types.d.ts
19
+ /**
20
+ * Convert a JSON Schema to a TypeScript type declaration.
21
+ */
22
+ declare function jsonSchemaToType(
23
+ schema: JSONSchema7,
24
+ typeName: string
25
+ ): string;
26
+ /**
27
+ * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).
28
+ */
29
+ interface JsonSchemaToolDescriptor {
30
+ description?: string;
31
+ inputSchema: JSONSchema7;
32
+ outputSchema?: JSONSchema7;
33
+ }
34
+ type JsonSchemaToolDescriptors = Record<string, JsonSchemaToolDescriptor>;
35
+ /**
36
+ * Generate TypeScript type definitions from tool descriptors with JSON Schema.
37
+ * This function has NO dependency on the AI SDK or Zod — it works purely with
38
+ * JSON Schema objects.
39
+ *
40
+ * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool
41
+ * definitions, etc.) and don't need the AI SDK.
42
+ */
43
+ declare function generateTypesFromJsonSchema(
44
+ tools: JsonSchemaToolDescriptors
45
+ ): string;
46
+ //#endregion
13
47
  //#region src/normalize.d.ts
14
48
  declare function normalizeCode(code: string): string;
15
49
  //#endregion
@@ -18,10 +52,11 @@ export {
18
52
  type DynamicWorkerExecutorOptions,
19
53
  type ExecuteResult,
20
54
  type Executor,
21
- type ToolDescriptor,
22
- type ToolDescriptors,
55
+ type JsonSchemaToolDescriptor,
56
+ type JsonSchemaToolDescriptors,
23
57
  ToolDispatcher,
24
- generateTypes,
58
+ generateTypesFromJsonSchema,
59
+ jsonSchemaToType,
25
60
  normalizeCode,
26
61
  sanitizeToolName
27
62
  };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as generateTypes, r as sanitizeToolName, t as normalizeCode } from "./normalize-Dy5d7PfI.js";
1
+ import { n as generateTypesFromJsonSchema, o as sanitizeToolName, r as jsonSchemaToType, t as normalizeCode } from "./normalize-xNh5CsfI.js";
2
2
  import { RpcTarget } from "cloudflare:workers";
3
3
  //#region src/executor.ts
4
4
  /**
@@ -103,6 +103,6 @@ var DynamicWorkerExecutor = class {
103
103
  }
104
104
  };
105
105
  //#endregion
106
- export { DynamicWorkerExecutor, ToolDispatcher, generateTypes, normalizeCode, sanitizeToolName };
106
+ export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, sanitizeToolName };
107
107
 
108
108
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,5 @@
1
- import { asSchema } from "ai";
2
1
  import * as acorn from "acorn";
3
- //#region src/types.ts
2
+ //#region src/utils.ts
4
3
  const JS_RESERVED = new Set([
5
4
  "abstract",
6
5
  "arguments",
@@ -82,64 +81,10 @@ function sanitizeToolName(name) {
82
81
  if (JS_RESERVED.has(sanitized)) sanitized = sanitized + "_";
83
82
  return sanitized;
84
83
  }
85
- function toCamelCase(str) {
84
+ function toPascalCase(str) {
86
85
  return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
87
86
  }
88
87
  /**
89
- * Extract field descriptions from a schema and format as @param lines.
90
- * Returns an array of `@param input.fieldName - description` lines.
91
- */
92
- function extractParamDescriptions(schema) {
93
- const descriptions = extractDescriptions(schema);
94
- return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
95
- }
96
- /**
97
- * Check if a value is a Zod schema (has _zod property).
98
- */
99
- function isZodSchema(value) {
100
- return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
101
- }
102
- /**
103
- * Check if a value conforms to the Standard Schema protocol (~standard).
104
- * This catches Zod v3 schemas (which expose ~standard but not _zod).
105
- */
106
- function isStandardSchema(value) {
107
- return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
108
- }
109
- /**
110
- * Check if a value is an AI SDK jsonSchema wrapper.
111
- * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
112
- */
113
- function isJsonSchemaWrapper(value) {
114
- if (value === null || typeof value !== "object") return false;
115
- if ("jsonSchema" in value) return true;
116
- const symbols = Object.getOwnPropertySymbols(value);
117
- for (const sym of symbols) {
118
- const symValue = value[sym];
119
- if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
120
- }
121
- return false;
122
- }
123
- /**
124
- * Extract JSON schema from an AI SDK jsonSchema wrapper.
125
- */
126
- function extractJsonSchema(wrapper) {
127
- if (wrapper === null || typeof wrapper !== "object") return null;
128
- if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
129
- const symbols = Object.getOwnPropertySymbols(wrapper);
130
- for (const sym of symbols) {
131
- const symValue = wrapper[sym];
132
- if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
133
- }
134
- return null;
135
- }
136
- /**
137
- * Check if a property name needs quoting in TypeScript.
138
- */
139
- function needsQuotes(name) {
140
- return !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
141
- }
142
- /**
143
88
  * Escape a character as a unicode escape sequence if it is a control character.
144
89
  */
145
90
  function escapeControlChar(ch) {
@@ -152,7 +97,7 @@ function escapeControlChar(ch) {
152
97
  * Escapes backslashes, quotes, and control characters.
153
98
  */
154
99
  function quoteProp(name) {
155
- if (needsQuotes(name)) {
100
+ if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
156
101
  let escaped = "";
157
102
  for (const ch of name) if (ch === "\\") escaped += "\\\\";
158
103
  else if (ch === "\"") escaped += "\\\"";
@@ -168,7 +113,6 @@ function quoteProp(name) {
168
113
  }
169
114
  /**
170
115
  * Escape a string for use inside a double-quoted TypeScript string literal.
171
- * Handles backslashes, quotes, newlines, control characters, and line/paragraph separators.
172
116
  */
173
117
  function escapeStringLiteral(s) {
174
118
  let out = "";
@@ -189,6 +133,8 @@ function escapeStringLiteral(s) {
189
133
  function escapeJsDoc(text) {
190
134
  return text.replace(/\*\//g, "*\\/");
191
135
  }
136
+ //#endregion
137
+ //#region src/json-schema-types.ts
192
138
  /**
193
139
  * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.
194
140
  * Returns null for external URLs or unresolvable paths.
@@ -208,6 +154,13 @@ function resolveRef(ref, root) {
208
154
  return current;
209
155
  }
210
156
  /**
157
+ * Apply OpenAPI 3.0 `nullable: true` to a type result.
158
+ */
159
+ function applyNullable(result, schema) {
160
+ if (result !== "unknown" && result !== "never" && schema?.nullable === true) return `${result} | null`;
161
+ return result;
162
+ }
163
+ /**
211
164
  * Convert a JSON Schema to a TypeScript type string.
212
165
  * This is a direct conversion without going through Zod.
213
166
  */
@@ -305,97 +258,66 @@ function jsonSchemaToTypeString(schema, indent, ctx) {
305
258
  }
306
259
  }
307
260
  /**
308
- * Apply OpenAPI 3.0 `nullable: true` to a type result.
261
+ * Convert a JSON Schema to a TypeScript type declaration.
309
262
  */
310
- function applyNullable(result, schema) {
311
- if (result !== "unknown" && result !== "never" && schema?.nullable === true) return `${result} | null`;
312
- return result;
263
+ function jsonSchemaToType(schema, typeName) {
264
+ return `type ${typeName} = ${jsonSchemaToTypeString(schema, "", {
265
+ root: schema,
266
+ depth: 0,
267
+ seen: /* @__PURE__ */ new Set(),
268
+ maxDepth: 20
269
+ })}`;
313
270
  }
314
271
  /**
315
- * Extract field descriptions from a schema.
316
- * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
272
+ * Extract field descriptions from a JSON Schema's properties.
317
273
  */
318
- function extractDescriptions(schema) {
274
+ function extractJsonSchemaDescriptions(schema) {
319
275
  const descriptions = {};
320
- const shape = schema.shape;
321
- if (shape && typeof shape === "object") {
322
- for (const [fieldName, fieldSchema] of Object.entries(shape)) {
323
- let s = fieldSchema;
324
- while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
325
- if (s.description) descriptions[fieldName] = s.description;
326
- }
327
- return descriptions;
328
- }
329
- if (isJsonSchemaWrapper(schema)) {
330
- const jsonSchema = extractJsonSchema(schema);
331
- if (jsonSchema?.properties) {
332
- for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
333
- }
276
+ if (schema.properties) {
277
+ for (const [fieldName, propSchema] of Object.entries(schema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
334
278
  }
335
279
  return descriptions;
336
280
  }
337
281
  /**
338
- * Safely convert a schema to TypeScript type string.
339
- * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
340
- * Returns "unknown" if the schema cannot be represented in TypeScript.
282
+ * Generate TypeScript type definitions from tool descriptors with JSON Schema.
283
+ * This function has NO dependency on the AI SDK or Zod — it works purely with
284
+ * JSON Schema objects.
285
+ *
286
+ * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool
287
+ * definitions, etc.) and don't need the AI SDK.
341
288
  */
342
- function safeSchemaToTs(schema, typeName) {
343
- try {
344
- if (isZodSchema(schema) || isStandardSchema(schema)) {
345
- const jsonSchema = asSchema(schema).jsonSchema;
346
- if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
347
- root: jsonSchema,
348
- depth: 0,
349
- seen: /* @__PURE__ */ new Set(),
350
- maxDepth: 20
351
- })}`;
352
- }
353
- if (isJsonSchemaWrapper(schema)) {
354
- const jsonSchema = extractJsonSchema(schema);
355
- if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
356
- root: jsonSchema,
357
- depth: 0,
358
- seen: /* @__PURE__ */ new Set(),
359
- maxDepth: 20
360
- })}`;
361
- }
362
- return `type ${typeName} = unknown`;
363
- } catch {
364
- return `type ${typeName} = unknown`;
365
- }
366
- }
367
- /**
368
- * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
369
- * These types can be included in tool descriptions to help LLMs write correct code.
370
- */
371
- function generateTypes(tools) {
289
+ function generateTypesFromJsonSchema(tools) {
372
290
  let availableTools = "";
373
291
  let availableTypes = "";
374
292
  for (const [toolName, tool] of Object.entries(tools)) {
375
293
  const safeName = sanitizeToolName(toolName);
376
- const camelName = toCamelCase(safeName);
294
+ const typeName = toPascalCase(safeName);
377
295
  try {
378
- const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
379
- const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
380
- const description = tool.description;
381
- const inputType = safeSchemaToTs(inputSchema, `${camelName}Input`);
382
- const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${camelName}Output`) : `type ${camelName}Output = unknown`;
296
+ const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);
297
+ const outputType = tool.outputSchema ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
383
298
  availableTypes += `\n${inputType.trim()}`;
384
299
  availableTypes += `\n${outputType.trim()}`;
385
- const paramDescs = inputSchema ? extractParamDescriptions(inputSchema) : [];
300
+ const paramLines = (() => {
301
+ try {
302
+ const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);
303
+ return Object.entries(paramDescs).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
304
+ } catch {
305
+ return [];
306
+ }
307
+ })();
386
308
  const jsdocLines = [];
387
- if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
309
+ if (tool.description?.trim()) jsdocLines.push(escapeJsDoc(tool.description.trim().replace(/\r?\n/g, " ")));
388
310
  else jsdocLines.push(escapeJsDoc(toolName));
389
- for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
311
+ for (const pd of paramLines) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
390
312
  const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
391
313
  availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
392
- availableTools += `\n\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}Output>;`;
314
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
393
315
  availableTools += "\n";
394
316
  } catch {
395
- availableTypes += `\ntype ${camelName}Input = unknown`;
396
- availableTypes += `\ntype ${camelName}Output = unknown`;
317
+ availableTypes += `\ntype ${typeName}Input = unknown`;
318
+ availableTypes += `\ntype ${typeName}Output = unknown`;
397
319
  availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
398
- availableTools += `\n\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}Output>;`;
320
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
399
321
  availableTools += "\n";
400
322
  }
401
323
  }
@@ -446,6 +368,6 @@ function normalizeCode(code) {
446
368
  }
447
369
  }
448
370
  //#endregion
449
- export { generateTypes as n, sanitizeToolName as r, normalizeCode as t };
371
+ export { escapeJsDoc as a, jsonSchemaToTypeString as i, generateTypesFromJsonSchema as n, sanitizeToolName as o, jsonSchemaToType as r, toPascalCase as s, normalizeCode as t };
450
372
 
451
- //# sourceMappingURL=normalize-Dy5d7PfI.js.map
373
+ //# sourceMappingURL=normalize-xNh5CsfI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize-xNh5CsfI.js","names":[],"sources":["../src/utils.ts","../src/json-schema-types.ts","../src/normalize.ts"],"sourcesContent":["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","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"],"mappings":";;AAAA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAgB,iBAAiB,MAAsB;AACrD,KAAI,CAAC,KAAM,QAAO;CAGlB,IAAI,YAAY,KAAK,QAAQ,WAAW,IAAI;AAG5C,aAAY,UAAU,QAAQ,mBAAmB,GAAG;AAEpD,KAAI,CAAC,UAAW,QAAO;AAGvB,KAAI,SAAS,KAAK,UAAU,CAC1B,aAAY,MAAM;AAIpB,KAAI,YAAY,IAAI,UAAU,CAC5B,aAAY,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AE,QAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;AAE7B,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;AAGF,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,0BAA2B,QAAO;;AAItD,MACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ,IAAI,KAAK,GAAsC;GAC7D,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,IAAI;AAIhD,OACE,KAAK,SAAS,yBACd,CAAE,KAAmC,GAErC,QAAO,0BAA0B,MAAM;AAEzC,OACE,KAAK,SAAS,sBACd,CAAE,KAAgC,GAElC,QAAO,0BAA0B,MAAM;AAGzC,UAAO,cAAc,MAAM;;AAI7B,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,sBAGhD,QAAO,kBAAkB,OAAO,WAFrB,IAAI,KAAK,GACJ,IAAI,QAAQ,KACoB;EAIlD,MAAM,OAAO,IAAI,KAAK,IAAI,KAAK,SAAS;AACxC,MAAI,MAAM,SAAS,uBAAuB;GACxC,MAAM,WAAW;AAMjB,UAAO,kBALQ,OAAO,MAAM,GAAG,KAAK,MAAM,CAKV,UAJf,OAAO,MACtB,SAAS,WAAW,OACpB,SAAS,WAAW,IACrB,CACkD;;AAGrD,SAAO,kBAAkB,OAAO;SAC1B;AACN,SAAO,kBAAkB,OAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -11,6 +11,7 @@
11
11
  "url": "https://github.com/cloudflare/agents/issues"
12
12
  },
13
13
  "dependencies": {
14
+ "@types/json-schema": "^7.0.15",
14
15
  "acorn": "^8.16.0"
15
16
  },
16
17
  "devDependencies": {
@@ -23,6 +24,14 @@
23
24
  "ai": "^6.0.0",
24
25
  "zod": "^3.25.0 || ^4.0.0"
25
26
  },
27
+ "peerDependenciesMeta": {
28
+ "ai": {
29
+ "optional": true
30
+ },
31
+ "zod": {
32
+ "optional": true
33
+ }
34
+ },
26
35
  "types": "dist/index.d.ts",
27
36
  "exports": {
28
37
  ".": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"normalize-Dy5d7PfI.js","names":[],"sources":["../src/types.ts","../src/normalize.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\n\ninterface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\nconst 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\nfunction toCamelCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n * Returns an array of `@param input.fieldName - description` lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n // AI SDK jsonSchema wrapper stores data in a symbol property\n // but also exposes jsonSchema directly in some versions\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n // Check for symbol-based storage (AI SDK internal)\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n // Direct property access\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n // Symbol-based storage\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Check if a property name needs quoting in TypeScript.\n */\nfunction needsQuotes(name: string): boolean {\n // Valid JS identifier: starts with letter, $, or _, followed by letters, digits, $, _\n return !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\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 */\nfunction quoteProp(name: string): string {\n if (needsQuotes(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 * Handles backslashes, quotes, newlines, control characters, and line/paragraph separators.\n */\nfunction 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 */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\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 * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nfunction 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 // Multi-line JSDoc when both description and format are present\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 // NOTE: In TypeScript, an index signature [key: string]: T requires all\n // named properties to be assignable to T. If any named property has an\n // incompatible type, the generated type is invalid. We emit it anyway\n // since it's more informative for LLMs consuming these types.\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 // additionalProperties: false means no keys allowed → empty object\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 * 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 * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n // Try Zod schema shape\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n // Unwrap optional/nullable/default wrappers to find .description\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n // Try JSON Schema properties (for jsonSchema wrapper)\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n * Returns \"unknown\" if the schema cannot be represented in TypeScript.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n // For Zod schemas (v4 via _zod, v3 via ~standard), convert to JSON Schema\n // via AI SDK's asSchema() then use jsonSchemaToTypeString()\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n // For JSON Schema wrapper, convert directly to TypeScript\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n // If the schema cannot be represented, fall back to unknown\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const camelName = toCamelCase(safeName);\n\n try {\n // Handle both our ToolDescriptor and AI SDK Tool types\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${camelName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${camelName}Output`)\n : `type ${camelName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n // Build JSDoc comment with description and param descriptions\n const paramDescs = inputSchema\n ? extractParamDescriptions(inputSchema)\n : [];\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\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: ${camelName}Input) => Promise<${camelName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n // One bad tool should not break the others — emit unknown types\n availableTypes += `\\ntype ${camelName}Input = unknown`;\n availableTypes += `\\ntype ${camelName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","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"],"mappings":";;;AAYA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAgB,iBAAiB,MAAsB;AACrD,KAAI,CAAC,KAAM,QAAO;CAGlB,IAAI,YAAY,KAAK,QAAQ,WAAW,IAAI;AAG5C,aAAY,UAAU,QAAQ,mBAAmB,GAAG;AAEpD,KAAI,CAAC,UAAW,QAAO;AAGvB,KAAI,SAAS,KAAK,UAAU,CAC1B,aAAY,MAAM;AAIpB,KAAI,YAAY,IAAI,UAAU,CAC5B,aAAY,YAAY;AAG1B,QAAO;;AAGT,SAAS,YAAY,KAAa;AAChC,QAAO,IACJ,QAAQ,cAAc,GAAG,WAAW,OAAO,aAAa,CAAC,CACzD,QAAQ,WAAW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