@bastani/atomic-codemode 0.0.0-placeholder.0 → 0.9.88-alpha.1
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/LICENSE +22 -0
- package/NOTICE.md +13 -0
- package/README.md +71 -0
- package/dist/cloudflare.d.ts +53 -0
- package/dist/cloudflare.d.ts.map +1 -0
- package/dist/cloudflare.js +64 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/declarations.d.ts +48 -0
- package/dist/declarations.d.ts.map +1 -0
- package/dist/declarations.js +332 -0
- package/dist/declarations.js.map +1 -0
- package/dist/identifier.d.ts +6 -0
- package/dist/identifier.d.ts.map +1 -0
- package/dist/identifier.js +13 -0
- package/dist/identifier.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/portable.d.ts +15 -0
- package/dist/portable.d.ts.map +1 -0
- package/dist/portable.js +12 -0
- package/dist/portable.js.map +1 -0
- package/dist/runtime/execution.d.ts +66 -0
- package/dist/runtime/execution.d.ts.map +1 -0
- package/dist/runtime/execution.js +494 -0
- package/dist/runtime/execution.js.map +1 -0
- package/dist/runtime/host.d.ts +13 -0
- package/dist/runtime/host.d.ts.map +1 -0
- package/dist/runtime/host.js +86 -0
- package/dist/runtime/host.js.map +1 -0
- package/dist/runtime/inline.d.ts +63 -0
- package/dist/runtime/inline.d.ts.map +1 -0
- package/dist/runtime/inline.js +80 -0
- package/dist/runtime/inline.js.map +1 -0
- package/dist/runtime/prelude-source.d.ts +45 -0
- package/dist/runtime/prelude-source.d.ts.map +1 -0
- package/dist/runtime/prelude-source.js +522 -0
- package/dist/runtime/prelude-source.js.map +1 -0
- package/dist/runtime/protocol.d.ts +110 -0
- package/dist/runtime/protocol.d.ts.map +1 -0
- package/dist/runtime/protocol.js +15 -0
- package/dist/runtime/protocol.js.map +1 -0
- package/dist/runtime/remote.d.ts +102 -0
- package/dist/runtime/remote.d.ts.map +1 -0
- package/dist/runtime/remote.js +175 -0
- package/dist/runtime/remote.js.map +1 -0
- package/dist/runtime/vm.d.ts +24 -0
- package/dist/runtime/vm.d.ts.map +1 -0
- package/dist/runtime/vm.js +293 -0
- package/dist/runtime/vm.js.map +1 -0
- package/dist/runtime/worker.d.ts +2 -0
- package/dist/runtime/worker.d.ts.map +1 -0
- package/dist/runtime/worker.js +38 -0
- package/dist/runtime/worker.js.map +1 -0
- package/dist/source.d.ts +36 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +98 -0
- package/dist/source.js.map +1 -0
- package/dist/types.d.ts +246 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm.d.ts +12 -0
- package/dist/wasm.d.ts.map +1 -0
- package/dist/wasm.js +24 -0
- package/dist/wasm.js.map +1 -0
- package/package.json +82 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mario Zechner
|
|
4
|
+
Copyright (c) 2026 Bastani, Inc.
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/NOTICE.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Notice
|
|
2
|
+
|
|
3
|
+
`@bastani/atomic-codemode` is a hard fork of the `packages/codemode` package from
|
|
4
|
+
[earendil-works/pi](https://github.com/earendil-works/pi). It lives in this
|
|
5
|
+
monorepo at `packages/codemode` and publishes at the same version as `@bastani/atomic`.
|
|
6
|
+
|
|
7
|
+
- Upstream package: [`@earendil-works/pi-codemode`](https://www.npmjs.com/package/@earendil-works/pi-codemode)
|
|
8
|
+
- Fork point: `v1.5.2` (`earendil-works/pi@b4afdddf44e059c67ccf5097e5317d913521b470`). Atomic does not sync further upstream changes.
|
|
9
|
+
|
|
10
|
+
Original work is Copyright (c) 2025 Mario Zechner and is licensed under the MIT License.
|
|
11
|
+
Bastani modifications are Copyright (c) 2026 Bastani, Inc. and are also licensed under the MIT License.
|
|
12
|
+
|
|
13
|
+
Import from `@bastani/atomic-codemode` instead of `@earendil-works/pi-codemode`.
|
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/bastani-inc/atomic">
|
|
3
|
+
<img alt="Atomic" src="https://raw.githubusercontent.com/bastani-inc/atomic/main/packages/coding-agent/docs/logo.svg" width="324">
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<b>@bastani/atomic-codemode</b><br>
|
|
9
|
+
Sandboxed JavaScript whose only capability is calling the tools you inject.
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://docs.bastani.ai/libraries/codemode"><img alt="Docs" src="https://img.shields.io/badge/docs-atomic-blue?style=flat-square" /></a>
|
|
14
|
+
<a href="https://www.npmjs.com/package/@bastani/atomic-codemode"><img alt="npm" src="https://img.shields.io/npm/v/@bastani/atomic-codemode?style=flat-square" /></a>
|
|
15
|
+
<a href="https://github.com/bastani-inc/atomic"><img alt="GitHub" src="https://img.shields.io/badge/github-bastani--inc%2Fatomic-181717?style=flat-square&logo=github" /></a>
|
|
16
|
+
</p>
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
Runs model-written JavaScript in a QuickJS VM compiled to WebAssembly. Scripts call your tools; nested tool calls never enter the model's context, only the script's output and return value do. Atomic uses it for its built-in `codemode` tool, and it runs on Node, Bun and Cloudflare Workers.
|
|
21
|
+
|
|
22
|
+
[Atomic](https://github.com/bastani-inc/atomic), the verifiable coding agent runtime, is built on it, and it is published with every Atomic release at Atomic's version.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install @bastani/atomic-codemode
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Inside an Atomic extension, import it without installing it: the running Atomic provides it. See [Libraries](https://docs.bastani.ai/libraries).
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { CodemodeSandbox } from "@bastani/atomic-codemode";
|
|
36
|
+
|
|
37
|
+
const sandbox = new CodemodeSandbox({
|
|
38
|
+
timeoutMs: 60_000,
|
|
39
|
+
tools: [
|
|
40
|
+
{
|
|
41
|
+
name: "read",
|
|
42
|
+
execute: async (args, { signal }) => {
|
|
43
|
+
const { path } = args as { path: string };
|
|
44
|
+
return await readFile(path, "utf8");
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const result = await sandbox.execute(`
|
|
51
|
+
const source = await tools.read({ path: "package.json" });
|
|
52
|
+
text("bytes " + source.length);
|
|
53
|
+
return JSON.parse(source).name;
|
|
54
|
+
`);
|
|
55
|
+
|
|
56
|
+
console.log(result.output); // [{ type: "text", text: "bytes 1234" }]
|
|
57
|
+
if (result.ok) console.log(result.value); // "@bastani/atomic-codemode"
|
|
58
|
+
else console.error(result.error.kind, result.error.message);
|
|
59
|
+
|
|
60
|
+
await sandbox.close();
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Documentation
|
|
64
|
+
|
|
65
|
+
The full guide and API reference are in Atomic's docs: **[@bastani/atomic-codemode](https://docs.bastani.ai/libraries/codemode)**.
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT. See [LICENSE](LICENSE).
|
|
70
|
+
|
|
71
|
+
Derived from pi by Mario Zechner and Earendil Works; see [NOTICE.md](NOTICE.md).
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Workers entry, for Workers built with Wrangler.
|
|
3
|
+
*
|
|
4
|
+
* Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a
|
|
5
|
+
* `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers
|
|
6
|
+
* do not support the import: use `@bastani/atomic-codemode/portable` with your own module there.
|
|
7
|
+
*
|
|
8
|
+
* Two ways to run codemode on Cloudflare:
|
|
9
|
+
* - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own
|
|
10
|
+
* Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable
|
|
11
|
+
* Object that serves a session.
|
|
12
|
+
* - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script
|
|
13
|
+
* that computes blocks the caller until it awaits a tool or uses up its interrupt budget.
|
|
14
|
+
*/
|
|
15
|
+
import { DurableObject } from "cloudflare:workers";
|
|
16
|
+
import { InlineCodemodeSandbox, type InlineCodemodeSandboxOptions } from "./runtime/inline.ts";
|
|
17
|
+
import { type CodemodeRemoteExchange, type CodemodeRemoteRequest } from "./runtime/remote.ts";
|
|
18
|
+
import type { CodemodeWasmModule } from "./wasm.ts";
|
|
19
|
+
export * from "./portable.ts";
|
|
20
|
+
/** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */
|
|
21
|
+
export declare const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES: number;
|
|
22
|
+
/** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */
|
|
23
|
+
export declare const cloudflareQuickJSWasm: CodemodeWasmModule;
|
|
24
|
+
/** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */
|
|
25
|
+
export declare function createInlineCodemodeSandbox(options?: Omit<InlineCodemodeSandboxOptions, "wasm">): InlineCodemodeSandbox;
|
|
26
|
+
/**
|
|
27
|
+
* The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's
|
|
28
|
+
* VM and calls back into the client for every tool call.
|
|
29
|
+
*
|
|
30
|
+
* Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.
|
|
31
|
+
* A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can
|
|
32
|
+
* share an isolate, and therefore a thread, with the objects that call it.
|
|
33
|
+
*
|
|
34
|
+
* The object keeps no state between executions and never touches storage. Executions that reach
|
|
35
|
+
* the same instance share its thread: they interleave while they wait on tools, and a script that
|
|
36
|
+
* computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one
|
|
37
|
+
* session's scripts together, or per execution for full independence.
|
|
38
|
+
*
|
|
39
|
+
* Limits apply to every request, whatever the client asks for. Override the fields in a subclass:
|
|
40
|
+
*
|
|
41
|
+
* export class CodemodeSandbox extends CodemodeSandboxDurableObject {
|
|
42
|
+
* protected maxInterruptBudget = 200_000;
|
|
43
|
+
* }
|
|
44
|
+
*/
|
|
45
|
+
export declare class CodemodeSandboxDurableObject<Env = unknown> extends DurableObject<Env> {
|
|
46
|
+
/** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */
|
|
47
|
+
protected maxInterruptBudget: number;
|
|
48
|
+
/** VM memory per execution; the client may only ask for less. */
|
|
49
|
+
protected maxMemoryLimitBytes: number;
|
|
50
|
+
/** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */
|
|
51
|
+
execute(request: CodemodeRemoteRequest, exchange: CodemodeRemoteExchange): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=cloudflare.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../src/cloudflare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAEN,qBAAqB,EACrB,KAAK,4BAA4B,EACjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,sBAAsB,EAAE,KAAK,qBAAqB,EAAuB,MAAM,qBAAqB,CAAC;AACnH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD,cAAc,eAAe,CAAC;AAM9B,sGAAsG;AACtG,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAElE,yDAAyD;AACzD,eAAO,MAAM,qBAAqB,EAAE,kBAAgC,CAAC;AAErE,wEAAwE;AACxE,wBAAgB,2BAA2B,CAAC,OAAO,GAAE,IAAI,CAAC,4BAA4B,EAAE,MAAM,CAAM,yBAEnG;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,4BAA4B,CAAC,GAAG,GAAG,OAAO,CAAE,SAAQ,aAAa,CAAC,GAAG,CAAC;IAClF,2GAA2G;IAC3G,SAAS,CAAC,kBAAkB,EAAE,MAAM,CAA4B;IAChE,iEAAiE;IACjE,SAAS,CAAC,mBAAmB,EAAE,MAAM,CAAqC;IAE1E,uGAAuG;IACvG,OAAO,CAAC,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMvF;CACD"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Workers entry, for Workers built with Wrangler.
|
|
3
|
+
*
|
|
4
|
+
* Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a
|
|
5
|
+
* `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers
|
|
6
|
+
* do not support the import: use `@bastani/atomic-codemode/portable` with your own module there.
|
|
7
|
+
*
|
|
8
|
+
* Two ways to run codemode on Cloudflare:
|
|
9
|
+
* - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own
|
|
10
|
+
* Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable
|
|
11
|
+
* Object that serves a session.
|
|
12
|
+
* - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script
|
|
13
|
+
* that computes blocks the caller until it awaits a tool or uses up its interrupt budget.
|
|
14
|
+
*/
|
|
15
|
+
import { DurableObject } from "cloudflare:workers";
|
|
16
|
+
import quickjsWasmImport from "quickjs-wasi/quickjs.wasm";
|
|
17
|
+
import { DEFAULT_INTERRUPT_BUDGET, InlineCodemodeSandbox, } from "./runtime/inline.js";
|
|
18
|
+
import { serveCodemodeRemote } from "./runtime/remote.js";
|
|
19
|
+
export * from "./portable.js";
|
|
20
|
+
// Wrangler's `CompiledWasm` rule makes this a compiled module; the declaration cannot say so (see
|
|
21
|
+
// cloudflare-modules.d.ts).
|
|
22
|
+
const quickjsWasm = quickjsWasmImport;
|
|
23
|
+
/** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */
|
|
24
|
+
export const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES = 32 * 1024 * 1024;
|
|
25
|
+
/** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */
|
|
26
|
+
export const cloudflareQuickJSWasm = quickjsWasm;
|
|
27
|
+
/** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */
|
|
28
|
+
export function createInlineCodemodeSandbox(options = {}) {
|
|
29
|
+
return new InlineCodemodeSandbox({ ...options, wasm: quickjsWasm });
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's
|
|
33
|
+
* VM and calls back into the client for every tool call.
|
|
34
|
+
*
|
|
35
|
+
* Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.
|
|
36
|
+
* A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can
|
|
37
|
+
* share an isolate, and therefore a thread, with the objects that call it.
|
|
38
|
+
*
|
|
39
|
+
* The object keeps no state between executions and never touches storage. Executions that reach
|
|
40
|
+
* the same instance share its thread: they interleave while they wait on tools, and a script that
|
|
41
|
+
* computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one
|
|
42
|
+
* session's scripts together, or per execution for full independence.
|
|
43
|
+
*
|
|
44
|
+
* Limits apply to every request, whatever the client asks for. Override the fields in a subclass:
|
|
45
|
+
*
|
|
46
|
+
* export class CodemodeSandbox extends CodemodeSandboxDurableObject {
|
|
47
|
+
* protected maxInterruptBudget = 200_000;
|
|
48
|
+
* }
|
|
49
|
+
*/
|
|
50
|
+
export class CodemodeSandboxDurableObject extends DurableObject {
|
|
51
|
+
/** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */
|
|
52
|
+
maxInterruptBudget = DEFAULT_INTERRUPT_BUDGET;
|
|
53
|
+
/** VM memory per execution; the client may only ask for less. */
|
|
54
|
+
maxMemoryLimitBytes = DEFAULT_REMOTE_MEMORY_LIMIT_BYTES;
|
|
55
|
+
/** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */
|
|
56
|
+
execute(request, exchange) {
|
|
57
|
+
return serveCodemodeRemote(request, exchange, {
|
|
58
|
+
wasm: quickjsWasm,
|
|
59
|
+
maxInterruptBudget: this.maxInterruptBudget,
|
|
60
|
+
maxMemoryLimitBytes: this.maxMemoryLimitBytes,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=cloudflare.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare.js","sourceRoot":"","sources":["../src/cloudflare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,iBAAiB,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EACN,wBAAwB,EACxB,qBAAqB,GAErB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAA2D,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAGnH,cAAc,eAAe,CAAC;AAE9B,kGAAkG;AAClG,4BAA4B;AAC5B,MAAM,WAAW,GAAG,iBAAkD,CAAC;AAEvE,sGAAsG;AACtG,MAAM,CAAC,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAElE,yDAAyD;AACzD,MAAM,CAAC,MAAM,qBAAqB,GAAuB,WAAW,CAAC;AAErE,wEAAwE;AACxE,MAAM,UAAU,2BAA2B,CAAC,OAAO,GAA+C,EAAE;IACnG,OAAO,IAAI,qBAAqB,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;AACrE,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,4BAA4C,SAAQ,aAAkB;IAClF,2GAA2G;IACjG,kBAAkB,GAAW,wBAAwB,CAAC;IAChE,iEAAiE;IACvD,mBAAmB,GAAW,iCAAiC,CAAC;IAE1E,uGAAuG;IACvG,OAAO,CAAC,OAA8B,EAAE,QAAgC;QACvE,OAAO,mBAAmB,CAAC,OAAO,EAAE,QAAQ,EAAE;YAC7C,IAAI,EAAE,WAAW;YACjB,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;YAC3C,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC7C,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["/**\n * Cloudflare Workers entry, for Workers built with Wrangler.\n *\n * Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a\n * `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers\n * do not support the import: use `@bastani/atomic-codemode/portable` with your own module there.\n *\n * Two ways to run codemode on Cloudflare:\n * - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own\n * Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable\n * Object that serves a session.\n * - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script\n * that computes blocks the caller until it awaits a tool or uses up its interrupt budget.\n */\nimport { DurableObject } from \"cloudflare:workers\";\nimport quickjsWasmImport from \"quickjs-wasi/quickjs.wasm\";\nimport {\n\tDEFAULT_INTERRUPT_BUDGET,\n\tInlineCodemodeSandbox,\n\ttype InlineCodemodeSandboxOptions,\n} from \"./runtime/inline.ts\";\nimport { type CodemodeRemoteExchange, type CodemodeRemoteRequest, serveCodemodeRemote } from \"./runtime/remote.ts\";\nimport type { CodemodeWasmModule } from \"./wasm.ts\";\n\nexport * from \"./portable.ts\";\n\n// Wrangler's `CompiledWasm` rule makes this a compiled module; the declaration cannot say so (see\n// cloudflare-modules.d.ts).\nconst quickjsWasm = quickjsWasmImport as unknown as CodemodeWasmModule;\n\n/** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */\nexport const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES = 32 * 1024 * 1024;\n\n/** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */\nexport const cloudflareQuickJSWasm: CodemodeWasmModule = quickjsWasm;\n\n/** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */\nexport function createInlineCodemodeSandbox(options: Omit<InlineCodemodeSandboxOptions, \"wasm\"> = {}) {\n\treturn new InlineCodemodeSandbox({ ...options, wasm: quickjsWasm });\n}\n\n/**\n * The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's\n * VM and calls back into the client for every tool call.\n *\n * Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.\n * A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can\n * share an isolate, and therefore a thread, with the objects that call it.\n *\n * The object keeps no state between executions and never touches storage. Executions that reach\n * the same instance share its thread: they interleave while they wait on tools, and a script that\n * computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one\n * session's scripts together, or per execution for full independence.\n *\n * Limits apply to every request, whatever the client asks for. Override the fields in a subclass:\n *\n * export class CodemodeSandbox extends CodemodeSandboxDurableObject {\n * protected maxInterruptBudget = 200_000;\n * }\n */\nexport class CodemodeSandboxDurableObject<Env = unknown> extends DurableObject<Env> {\n\t/** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */\n\tprotected maxInterruptBudget: number = DEFAULT_INTERRUPT_BUDGET;\n\t/** VM memory per execution; the client may only ask for less. */\n\tprotected maxMemoryLimitBytes: number = DEFAULT_REMOTE_MEMORY_LIMIT_BYTES;\n\n\t/** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */\n\texecute(request: CodemodeRemoteRequest, exchange: CodemodeRemoteExchange): Promise<void> {\n\t\treturn serveCodemodeRemote(request, exchange, {\n\t\t\twasm: quickjsWasm,\n\t\t\tmaxInterruptBudget: this.maxInterruptBudget,\n\t\t\tmaxMemoryLimitBytes: this.maxMemoryLimitBytes,\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { toCodemodeIdentifier } from "./identifier.ts";
|
|
2
|
+
export { toCodemodeIdentifier };
|
|
3
|
+
import type { CodemodeJsonSchema, CodemodeTool } from "./types.ts";
|
|
4
|
+
/** Largest rendered input type, in characters, before it becomes `unknown`. */
|
|
5
|
+
export declare const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16000;
|
|
6
|
+
export interface RenderDeclarationsOptions {
|
|
7
|
+
tools?: readonly CodemodeTool[];
|
|
8
|
+
globals?: readonly CodemodeTool[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Render TypeScript declarations for the script-visible API. Tools become members of
|
|
12
|
+
* `declare const tools`, globals become `declare function` statements, and `ns.member` globals
|
|
13
|
+
* members of `declare const ns`. Descriptions become doc comments; schemas become types.
|
|
14
|
+
*/
|
|
15
|
+
export declare function renderDeclarations(options: RenderDeclarationsOptions): string;
|
|
16
|
+
/**
|
|
17
|
+
* One tool as a member of the `tools` object: `name(args: T): Promise<R>;` with the
|
|
18
|
+
* name as the identifier scripts use. Input types longer than `inputMaxChars` render as `unknown`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function renderToolSignature(tool: Pick<CodemodeTool, "name" | "inputSchema" | "outputSchema">, options?: {
|
|
21
|
+
inputMaxChars?: number;
|
|
22
|
+
}): string;
|
|
23
|
+
/**
|
|
24
|
+
* A tool's sample: the description followed by the tool's declaration. Used for tool
|
|
25
|
+
* listings and `ALL_TOOLS` entries.
|
|
26
|
+
*/
|
|
27
|
+
export declare function renderToolSample(tool: Pick<CodemodeTool, "name" | "description" | "inputSchema" | "outputSchema">, options?: {
|
|
28
|
+
inputMaxChars?: number;
|
|
29
|
+
}): string;
|
|
30
|
+
/** The type a tool call resolves to: the output schema's type, and `unknown` without a schema. */
|
|
31
|
+
export declare function renderToolOutputType(schema: CodemodeJsonSchema | undefined): string;
|
|
32
|
+
/**
|
|
33
|
+
* Convert a JSON Schema to a TypeScript type expression: objects on one line (`{ a: string; b?: number; }`) with properties sorted by name,
|
|
34
|
+
* or one property per line with `//` comments when a property has a description or constraints the
|
|
35
|
+
* type cannot express (`// @integer @minimum 1 @default 20`); `Array<T>` for arrays. Local references
|
|
36
|
+
* (`#/$defs/...`, `#/definitions/...`) resolve against `schema`; recursive and remote references
|
|
37
|
+
* render as `unknown`. A result longer than `maxChars` is rendered again without the constraint tags,
|
|
38
|
+
* and renders as `unknown` if it is still too long.
|
|
39
|
+
*/
|
|
40
|
+
export declare function schemaToType(schema: CodemodeJsonSchema, options?: {
|
|
41
|
+
maxChars?: number;
|
|
42
|
+
}): string;
|
|
43
|
+
/**
|
|
44
|
+
* The subschema a local `$ref` (`#`, `#/$defs/Item`) names in `root`, or undefined for remote references and
|
|
45
|
+
* references that name nothing. Pointer segments are URI-decoded and JSON Pointer unescaped (`~1` is `/`, `~0` is `~`).
|
|
46
|
+
*/
|
|
47
|
+
export declare function resolveSchemaRef(ref: string, root: unknown): CodemodeJsonSchema | undefined;
|
|
48
|
+
//# sourceMappingURL=declarations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"declarations.d.ts","sourceRoot":"","sources":["../src/declarations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAEhC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAInE,+EAA+E;AAC/E,eAAO,MAAM,8BAA8B,QAAS,CAAC;AAyBrD,MAAM,WAAW,yBAAyB;IACzC,KAAK,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;CAClC;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,MAAM,CAyB7E;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAClC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,cAAc,CAAC,EACjE,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAMR;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,aAAa,GAAG,cAAc,CAAC,EACjF,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAGR;AAED,kGAAkG;AAClG,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,kBAAkB,GAAG,SAAS,GAAG,MAAM,CAEnF;AA6BD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,kBAAkB,EAAE,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,CAMpG;AAWD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,kBAAkB,GAAG,SAAS,CAqB3F"}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { toCodemodeIdentifier } from "./identifier.js";
|
|
2
|
+
export { toCodemodeIdentifier };
|
|
3
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
4
|
+
const INDENT = " ";
|
|
5
|
+
/** Largest rendered input type, in characters, before it becomes `unknown`. */
|
|
6
|
+
export const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16_000;
|
|
7
|
+
/** Local `$ref` expansions per rendered schema, so shared definitions cannot blow up the output. */
|
|
8
|
+
const MAX_REF_EXPANSIONS = 32;
|
|
9
|
+
/** JSON Schema keywords with a number or string value shown as `@keyword value` property tags. */
|
|
10
|
+
const TAG_KEYWORDS = [
|
|
11
|
+
"minimum",
|
|
12
|
+
"exclusiveMinimum",
|
|
13
|
+
"maximum",
|
|
14
|
+
"exclusiveMaximum",
|
|
15
|
+
"multipleOf",
|
|
16
|
+
"minLength",
|
|
17
|
+
"maxLength",
|
|
18
|
+
"pattern",
|
|
19
|
+
"format",
|
|
20
|
+
"minItems",
|
|
21
|
+
"maxItems",
|
|
22
|
+
];
|
|
23
|
+
/** Tag keywords whose values all hold at once, so only the largest (lower) or smallest (upper) matters. */
|
|
24
|
+
const LOWER_BOUNDS = new Set(["minimum", "exclusiveMinimum", "minLength", "minItems"]);
|
|
25
|
+
const UPPER_BOUNDS = new Set(["maximum", "exclusiveMaximum", "maxLength", "maxItems"]);
|
|
26
|
+
/** Longest property tag; longer ones (large defaults, long patterns) are left out. */
|
|
27
|
+
const MAX_TAG_CHARS = 80;
|
|
28
|
+
/** Characters that end a `//` comment. */
|
|
29
|
+
const LINE_TERMINATORS = /[\r\n\u2028\u2029]/g;
|
|
30
|
+
/**
|
|
31
|
+
* Render TypeScript declarations for the script-visible API. Tools become members of
|
|
32
|
+
* `declare const tools`, globals become `declare function` statements, and `ns.member` globals
|
|
33
|
+
* members of `declare const ns`. Descriptions become doc comments; schemas become types.
|
|
34
|
+
*/
|
|
35
|
+
export function renderDeclarations(options) {
|
|
36
|
+
const sections = [];
|
|
37
|
+
const tools = options.tools ?? [];
|
|
38
|
+
if (tools.length > 0) {
|
|
39
|
+
const members = tools.map((tool) => `${docComment(tool.description, INDENT)}${INDENT}${renderToolSignature(tool)}`);
|
|
40
|
+
sections.push(`declare const tools: {\n${members.join("\n")}\n};`);
|
|
41
|
+
}
|
|
42
|
+
const namespaces = new Map();
|
|
43
|
+
for (const global of options.globals ?? []) {
|
|
44
|
+
const dot = global.name.indexOf(".");
|
|
45
|
+
if (dot === -1) {
|
|
46
|
+
sections.push(renderGlobal(`declare function ${global.name}`, global, ""));
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const namespace = global.name.slice(0, dot);
|
|
50
|
+
const members = namespaces.get(namespace) ?? [];
|
|
51
|
+
if (members.length === 0)
|
|
52
|
+
namespaces.set(namespace, members);
|
|
53
|
+
members.push(renderGlobal(global.name.slice(dot + 1), global, INDENT));
|
|
54
|
+
}
|
|
55
|
+
for (const [namespace, members] of namespaces) {
|
|
56
|
+
sections.push(`declare const ${namespace}: {\n${members.join("\n")}\n};`);
|
|
57
|
+
}
|
|
58
|
+
return sections.join("\n\n");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* One tool as a member of the `tools` object: `name(args: T): Promise<R>;` with the
|
|
62
|
+
* name as the identifier scripts use. Input types longer than `inputMaxChars` render as `unknown`.
|
|
63
|
+
*/
|
|
64
|
+
export function renderToolSignature(tool, options = {}) {
|
|
65
|
+
const input = tool.inputSchema === undefined
|
|
66
|
+
? "unknown"
|
|
67
|
+
: schemaToType(tool.inputSchema, { maxChars: options.inputMaxChars ?? DEFAULT_INPUT_SCHEMA_MAX_CHARS });
|
|
68
|
+
return `${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A tool's sample: the description followed by the tool's declaration. Used for tool
|
|
72
|
+
* listings and `ALL_TOOLS` entries.
|
|
73
|
+
*/
|
|
74
|
+
export function renderToolSample(tool, options = {}) {
|
|
75
|
+
const declaration = `declare const tools: { ${renderToolSignature(tool, options)} };`;
|
|
76
|
+
return `${tool.description?.trim() ?? ""}\n\ncodemode tool declaration:\n\`\`\`ts\n${declaration}\n\`\`\``;
|
|
77
|
+
}
|
|
78
|
+
/** The type a tool call resolves to: the output schema's type, and `unknown` without a schema. */
|
|
79
|
+
export function renderToolOutputType(schema) {
|
|
80
|
+
return schema === undefined ? "unknown" : schemaToType(schema);
|
|
81
|
+
}
|
|
82
|
+
function renderGlobal(head, global, indent) {
|
|
83
|
+
if (global.signature !== undefined) {
|
|
84
|
+
return `${docComment(global.description, indent)}${indent}${head}${global.signature};`;
|
|
85
|
+
}
|
|
86
|
+
const input = global.inputSchema === undefined ? "unknown" : schemaToType(global.inputSchema);
|
|
87
|
+
const output = global.outputSchema === undefined ? "unknown" : schemaToType(global.outputSchema);
|
|
88
|
+
return `${docComment(global.description, indent)}${indent}${head}(args: ${input}): Promise<${output}>;`;
|
|
89
|
+
}
|
|
90
|
+
function docComment(description, indent) {
|
|
91
|
+
const text = description?.trim();
|
|
92
|
+
if (!text)
|
|
93
|
+
return "";
|
|
94
|
+
const lines = text.replaceAll("*/", "*\\/").split(/\r?\n/);
|
|
95
|
+
if (lines.length === 1)
|
|
96
|
+
return `${indent}/** ${lines[0]} */\n`;
|
|
97
|
+
return `${indent}/**\n${lines.map((line) => `${indent} *${line ? ` ${line}` : ""}`).join("\n")}\n${indent} */\n`;
|
|
98
|
+
}
|
|
99
|
+
function propertyKey(name) {
|
|
100
|
+
return IDENTIFIER.test(name) ? name : JSON.stringify(name);
|
|
101
|
+
}
|
|
102
|
+
function union(types) {
|
|
103
|
+
const unique = [...new Set(types)];
|
|
104
|
+
if (unique.includes("unknown"))
|
|
105
|
+
return "unknown";
|
|
106
|
+
return unique.length === 0 ? "never" : unique.join(" | ");
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Convert a JSON Schema to a TypeScript type expression: objects on one line (`{ a: string; b?: number; }`) with properties sorted by name,
|
|
110
|
+
* or one property per line with `//` comments when a property has a description or constraints the
|
|
111
|
+
* type cannot express (`// @integer @minimum 1 @default 20`); `Array<T>` for arrays. Local references
|
|
112
|
+
* (`#/$defs/...`, `#/definitions/...`) resolve against `schema`; recursive and remote references
|
|
113
|
+
* render as `unknown`. A result longer than `maxChars` is rendered again without the constraint tags,
|
|
114
|
+
* and renders as `unknown` if it is still too long.
|
|
115
|
+
*/
|
|
116
|
+
export function schemaToType(schema, options = {}) {
|
|
117
|
+
const render = (tags) => toType(schema, { root: schema, resolving: new Set(), expansions: 0, tags });
|
|
118
|
+
const type = render(true);
|
|
119
|
+
if (options.maxChars === undefined || type.length <= options.maxChars)
|
|
120
|
+
return type;
|
|
121
|
+
const untagged = render(false);
|
|
122
|
+
return untagged.length <= options.maxChars ? untagged : "unknown";
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The subschema a local `$ref` (`#`, `#/$defs/Item`) names in `root`, or undefined for remote references and
|
|
126
|
+
* references that name nothing. Pointer segments are URI-decoded and JSON Pointer unescaped (`~1` is `/`, `~0` is `~`).
|
|
127
|
+
*/
|
|
128
|
+
export function resolveSchemaRef(ref, root) {
|
|
129
|
+
if (ref !== "#" && !ref.startsWith("#/"))
|
|
130
|
+
return undefined;
|
|
131
|
+
let current = root;
|
|
132
|
+
for (const segment of ref.slice(2).split("/").filter(Boolean)) {
|
|
133
|
+
let decoded;
|
|
134
|
+
try {
|
|
135
|
+
decoded = decodeURIComponent(segment);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Schemas come from tools and MCP servers: a malformed escape names nothing instead of failing the caller.
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
const key = decoded.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
142
|
+
if (typeof current !== "object" || current === null || Array.isArray(current) || !(key in current)) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
current = current[key];
|
|
146
|
+
}
|
|
147
|
+
if (typeof current === "boolean")
|
|
148
|
+
return current;
|
|
149
|
+
return typeof current === "object" && current !== null && !Array.isArray(current)
|
|
150
|
+
? current
|
|
151
|
+
: undefined;
|
|
152
|
+
}
|
|
153
|
+
function toType(schema, context) {
|
|
154
|
+
if (schema === true)
|
|
155
|
+
return "unknown";
|
|
156
|
+
if (schema === false)
|
|
157
|
+
return "never";
|
|
158
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema))
|
|
159
|
+
return "unknown";
|
|
160
|
+
if (typeof schema.$ref === "string") {
|
|
161
|
+
const ref = schema.$ref;
|
|
162
|
+
if (context.resolving.has(ref) || context.expansions >= MAX_REF_EXPANSIONS)
|
|
163
|
+
return "unknown";
|
|
164
|
+
const target = resolveSchemaRef(ref, context.root);
|
|
165
|
+
if (target === undefined)
|
|
166
|
+
return "unknown";
|
|
167
|
+
context.expansions++;
|
|
168
|
+
context.resolving.add(ref);
|
|
169
|
+
try {
|
|
170
|
+
return toType(target, context);
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
context.resolving.delete(ref);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if ("const" in schema)
|
|
177
|
+
return JSON.stringify(schema.const) ?? "unknown";
|
|
178
|
+
if (Array.isArray(schema.enum))
|
|
179
|
+
return union(schema.enum.map((value) => JSON.stringify(value) ?? "unknown"));
|
|
180
|
+
const variants = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;
|
|
181
|
+
if (variants)
|
|
182
|
+
return union(variants.map((variant) => toType(variant, context)));
|
|
183
|
+
if (Array.isArray(schema.allOf)) {
|
|
184
|
+
const parts = schema.allOf
|
|
185
|
+
.map((part) => toType(part, context))
|
|
186
|
+
.filter((part) => part !== "unknown");
|
|
187
|
+
return parts.length === 0
|
|
188
|
+
? "unknown"
|
|
189
|
+
: parts.map((part) => (part.includes(" | ") ? `(${part})` : part)).join(" & ");
|
|
190
|
+
}
|
|
191
|
+
const type = schema.type;
|
|
192
|
+
if (Array.isArray(type))
|
|
193
|
+
return union(type.map((entry) => toType({ ...schema, type: entry }, context)));
|
|
194
|
+
switch (type) {
|
|
195
|
+
case "string":
|
|
196
|
+
return "string";
|
|
197
|
+
case "number":
|
|
198
|
+
case "integer":
|
|
199
|
+
return "number";
|
|
200
|
+
case "boolean":
|
|
201
|
+
return "boolean";
|
|
202
|
+
case "null":
|
|
203
|
+
return "null";
|
|
204
|
+
case "array":
|
|
205
|
+
return arrayType(schema, context);
|
|
206
|
+
case "object":
|
|
207
|
+
return objectType(schema, context);
|
|
208
|
+
case undefined:
|
|
209
|
+
if ("properties" in schema || "additionalProperties" in schema || "required" in schema) {
|
|
210
|
+
return objectType(schema, context);
|
|
211
|
+
}
|
|
212
|
+
if ("items" in schema || "prefixItems" in schema)
|
|
213
|
+
return arrayType(schema, context);
|
|
214
|
+
return "unknown";
|
|
215
|
+
default:
|
|
216
|
+
return "unknown";
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function arrayType(schema, context) {
|
|
220
|
+
if (schema.items !== undefined && !Array.isArray(schema.items)) {
|
|
221
|
+
return `Array<${toType(schema.items, context)}>`;
|
|
222
|
+
}
|
|
223
|
+
const tuple = Array.isArray(schema.prefixItems)
|
|
224
|
+
? schema.prefixItems
|
|
225
|
+
: Array.isArray(schema.items)
|
|
226
|
+
? schema.items
|
|
227
|
+
: [];
|
|
228
|
+
if (tuple.length > 0)
|
|
229
|
+
return `[${tuple.map((item) => toType(item, context)).join(", ")}]`;
|
|
230
|
+
return "unknown[]";
|
|
231
|
+
}
|
|
232
|
+
function descriptionOf(property) {
|
|
233
|
+
const description = property?.description;
|
|
234
|
+
return typeof description === "string" ? description.trim() : "";
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Constraints of a property that its TypeScript type cannot express, as JSDoc-style tags:
|
|
238
|
+
* `@integer @minimum 1 @maximum 100 @default 20`. Empty when there are none.
|
|
239
|
+
*/
|
|
240
|
+
function constraintTags(schema) {
|
|
241
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema))
|
|
242
|
+
return "";
|
|
243
|
+
const property = schema;
|
|
244
|
+
// Optional fields such as Pydantic's `int | None` keep their constraints in the non-null branch.
|
|
245
|
+
// The branch's constraints apply together with the property's, so both are read.
|
|
246
|
+
const variants = Array.isArray(property.anyOf) ? property.anyOf : property.oneOf;
|
|
247
|
+
const nonNull = Array.isArray(variants)
|
|
248
|
+
? variants.filter((variant) => variant?.type !== "null")
|
|
249
|
+
: [];
|
|
250
|
+
const branch = nonNull.length === 1 ? nonNull[0] : undefined;
|
|
251
|
+
const branches = typeof branch === "object" && branch !== null && !Array.isArray(branch)
|
|
252
|
+
? [property, branch]
|
|
253
|
+
: [property];
|
|
254
|
+
// Draft-04 and OpenAPI 3.0 make `minimum`/`maximum` exclusive with a boolean `exclusiveMinimum`/`exclusiveMaximum`.
|
|
255
|
+
const schemas = branches.map((schema) => ({
|
|
256
|
+
...schema,
|
|
257
|
+
...(schema.exclusiveMinimum === true ? { minimum: undefined, exclusiveMinimum: schema.minimum } : {}),
|
|
258
|
+
...(schema.exclusiveMaximum === true ? { maximum: undefined, exclusiveMaximum: schema.maximum } : {}),
|
|
259
|
+
}));
|
|
260
|
+
const tags = [];
|
|
261
|
+
const isInteger = (type) => type === "integer" || (Array.isArray(type) && type.includes("integer"));
|
|
262
|
+
if (schemas.some((schema) => isInteger(schema.type)))
|
|
263
|
+
tags.push("@integer");
|
|
264
|
+
for (const keyword of TAG_KEYWORDS) {
|
|
265
|
+
const values = schemas.map((schema) => schema[keyword]);
|
|
266
|
+
if (LOWER_BOUNDS.has(keyword) || UPPER_BOUNDS.has(keyword)) {
|
|
267
|
+
const numbers = values.filter((value) => typeof value === "number");
|
|
268
|
+
if (numbers.length === 0)
|
|
269
|
+
continue;
|
|
270
|
+
tags.push(`@${keyword} ${LOWER_BOUNDS.has(keyword) ? Math.max(...numbers) : Math.min(...numbers)}`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
for (const value of new Set(values)) {
|
|
274
|
+
if (typeof value === "number" || typeof value === "string")
|
|
275
|
+
tags.push(`@${keyword} ${value}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (schemas.some((schema) => schema.uniqueItems === true))
|
|
279
|
+
tags.push("@uniqueItems");
|
|
280
|
+
// Annotations, unlike constraints, come from the property itself.
|
|
281
|
+
if (property.default !== undefined && property.default !== null) {
|
|
282
|
+
tags.push(`@default ${JSON.stringify(property.default)}`);
|
|
283
|
+
}
|
|
284
|
+
if (property.deprecated === true)
|
|
285
|
+
tags.push("@deprecated");
|
|
286
|
+
return tags
|
|
287
|
+
.filter((tag) => tag.length <= MAX_TAG_CHARS)
|
|
288
|
+
.map((tag) => tag.replace(LINE_TERMINATORS, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`))
|
|
289
|
+
.join(" ");
|
|
290
|
+
}
|
|
291
|
+
function objectType(schema, context) {
|
|
292
|
+
const properties = typeof schema.properties === "object" && schema.properties !== null && !Array.isArray(schema.properties)
|
|
293
|
+
? schema.properties
|
|
294
|
+
: {};
|
|
295
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
296
|
+
const names = Object.keys(properties).sort();
|
|
297
|
+
const members = names.map((name) => {
|
|
298
|
+
const optional = required.has(name) ? "" : "?";
|
|
299
|
+
return `${propertyKey(name)}${optional}: ${toType(properties[name], context)};`;
|
|
300
|
+
});
|
|
301
|
+
const additional = schema.additionalProperties;
|
|
302
|
+
if (additional !== undefined && additional !== false) {
|
|
303
|
+
const type = additional === true ? "unknown" : toType(additional, context);
|
|
304
|
+
members.push(`[key: string]: ${type};`);
|
|
305
|
+
}
|
|
306
|
+
else if (additional === undefined && names.length === 0) {
|
|
307
|
+
members.push("[key: string]: unknown;");
|
|
308
|
+
}
|
|
309
|
+
if (members.length === 0)
|
|
310
|
+
return "{}";
|
|
311
|
+
const comments = names.map((name) => {
|
|
312
|
+
const lines = descriptionOf(properties[name])
|
|
313
|
+
.split(LINE_TERMINATORS)
|
|
314
|
+
.map((line) => line.trim())
|
|
315
|
+
.filter(Boolean);
|
|
316
|
+
const tags = context.tags ? constraintTags(properties[name]) : "";
|
|
317
|
+
return tags ? [...lines, tags] : lines;
|
|
318
|
+
});
|
|
319
|
+
if (!comments.some((comment) => comment.length > 0))
|
|
320
|
+
return `{ ${members.join(" ")} }`;
|
|
321
|
+
const lines = ["{"];
|
|
322
|
+
comments.forEach((comment, index) => {
|
|
323
|
+
for (const line of comment)
|
|
324
|
+
lines.push(`${INDENT}// ${line}`);
|
|
325
|
+
lines.push(`${INDENT}${members[index].replaceAll("\n", `\n${INDENT}`)}`);
|
|
326
|
+
});
|
|
327
|
+
for (const member of members.slice(names.length))
|
|
328
|
+
lines.push(`${INDENT}${member}`);
|
|
329
|
+
lines.push("}");
|
|
330
|
+
return lines.join("\n");
|
|
331
|
+
}
|
|
332
|
+
//# sourceMappingURL=declarations.js.map
|