zapcode 1.0.1__cp310-cp310-win_amd64.whl

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.
zapcode/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .zapcode import *
2
+
3
+ __doc__ = zapcode.__doc__
4
+ if hasattr(zapcode, "__all__"):
5
+ __all__ = zapcode.__all__
Binary file
@@ -0,0 +1,621 @@
1
+ Metadata-Version: 2.4
2
+ Name: zapcode
3
+ Version: 1.0.1
4
+ Classifier: Development Status :: 4 - Beta
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: License :: OSI Approved :: MIT License
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Rust
9
+ Classifier: Topic :: Software Development :: Interpreters
10
+ Summary: A minimal, secure TypeScript interpreter for AI agents — Python bindings
11
+ Keywords: typescript,interpreter,sandbox,ai,mcp,snapshot,secure
12
+ Author: Uncharted
13
+ License-Expression: MIT
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
16
+ Project-URL: Documentation, https://github.com/TheUncharted/zapcode#readme
17
+ Project-URL: Homepage, https://github.com/TheUncharted/zapcode
18
+ Project-URL: Issues, https://github.com/TheUncharted/zapcode/issues
19
+ Project-URL: Repository, https://github.com/TheUncharted/zapcode
20
+
21
+ <p align="center">
22
+ <img src="assets/logo.png" alt="Zapcode" width="160" />
23
+ </p>
24
+ <h1 align="center">Zapcode</h1>
25
+ <p align="center"><strong>Run AI code. Safely. Instantly.</strong></p>
26
+ <p align="center">A minimal, secure TypeScript interpreter written in Rust for use by AI agents</p>
27
+
28
+ <p align="center">
29
+ <a href="https://github.com/TheUncharted/zapcode/actions"><img src="https://img.shields.io/github/actions/workflow/status/TheUncharted/zapcode/ci.yml?branch=master&label=CI" alt="CI"></a>
30
+ <a href="https://crates.io/crates/zapcode-core"><img src="https://img.shields.io/crates/v/zapcode-core" alt="crates.io"></a>
31
+ <a href="https://www.npmjs.com/package/@unchartedfr/zapcode"><img src="https://img.shields.io/npm/v/@unchartedfr/zapcode" alt="npm"></a>
32
+ <a href="https://pypi.org/project/zapcode/"><img src="https://img.shields.io/pypi/v/zapcode" alt="PyPI"></a>
33
+ <a href="https://github.com/TheUncharted/zapcode/blob/master/LICENSE"><img src="https://img.shields.io/github/license/TheUncharted/zapcode" alt="License"></a>
34
+ </p>
35
+
36
+ ---
37
+
38
+ > **Experimental** — Zapcode is under active development. APIs may change.
39
+
40
+ ## Why agents should write code
41
+
42
+ AI agents are more capable when they **write code** instead of chaining tool calls. Code gives agents loops, conditionals, variables, and composition — things that tool chains simulate poorly.
43
+
44
+ - [CodeMode](https://blog.cloudflare.com/codemode-ai-agent-coding) — Cloudflare on why agents should write code
45
+ - [Programmatic Tool Calling](https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-use-examples#programmatic-tool-calling) — Anthropic's approach
46
+ - [Code Execution with MCP](https://www.anthropic.com/engineering/code-execution-mcp) — Anthropic engineering
47
+ - [Smol Agents](https://huggingface.co/docs/smolagents/en/index) — Hugging Face's code-first agents
48
+
49
+ **But running AI-generated code is dangerous and slow.**
50
+
51
+ Docker adds 200-500ms of cold-start latency and requires a container runtime. V8 isolates bring ~20MB of binary and millisecond startup. Neither supports snapshotting execution mid-function.
52
+
53
+ Zapcode takes a different approach: a purpose-built TypeScript interpreter that starts in **2 microseconds**, enforces a security sandbox at the language level, and can snapshot execution state to bytes for later resumption — all in a single, embeddable library with zero dependencies on Node.js or V8.
54
+
55
+ Inspired by [Monty](https://github.com/pydantic/monty), Pydantic's Python subset interpreter that takes the same approach for Python.
56
+
57
+ ## Alternatives
58
+
59
+ | | Language completeness | Security | Startup | Snapshots | Setup |
60
+ |---|---|---|---|---|---|
61
+ | **Zapcode** | TypeScript subset | Language-level sandbox | **~2 µs** | Built-in, < 2 KB | `npm install` / `pip install` |
62
+ | Docker + Node.js | Full Node.js | Container isolation | ~200-500 ms | No | Container runtime |
63
+ | V8 Isolates | Full JS/TS | Isolate boundary | ~5-50 ms | No | V8 (~20 MB) |
64
+ | Deno Deploy | Full TS | Isolate + permissions | ~10-50 ms | No | Cloud service |
65
+ | QuickJS | Full ES2023 | Process isolation | ~1-5 ms | No | C library |
66
+ | WASI/Wasmer | Depends on guest | Wasm sandbox | ~1-10 ms | Possible | Wasm runtime |
67
+
68
+ ### Why not Docker?
69
+
70
+ Docker provides strong isolation but adds hundreds of milliseconds of cold-start latency, requires a container runtime, and doesn't support snapshotting execution state mid-function. For AI agent loops that execute thousands of small code snippets, the overhead dominates.
71
+
72
+ ### Why not V8?
73
+
74
+ V8 is the gold standard for JavaScript execution. But it brings ~20 MB of binary size, millisecond startup times, and a vast API surface that must be carefully restricted for sandboxing. If you need full ECMAScript compliance, use V8. If you need microsecond startup, byte-sized snapshots, and a security model where "blocked by default" is the foundation rather than an afterthought, use Zapcode.
75
+
76
+ ## Benchmarks
77
+
78
+ All benchmarks run the full pipeline: parse → compile → execute. No caching, no warm-up.
79
+
80
+ | Benchmark | Zapcode | Docker + Node.js | V8 Isolate |
81
+ |---|---|---|---|
82
+ | Simple expression (`1 + 2 * 3`) | **2.1 µs** | ~200-500 ms | ~5-50 ms |
83
+ | Variable arithmetic | **2.8 µs** | — | — |
84
+ | String concatenation | **2.6 µs** | — | — |
85
+ | Template literal | **2.9 µs** | — | — |
86
+ | Array creation | **2.4 µs** | — | — |
87
+ | Object creation | **5.2 µs** | — | — |
88
+ | Function call | **4.6 µs** | — | — |
89
+ | Loop (100 iterations) | **77.8 µs** | — | — |
90
+ | Fibonacci (n=10, 177 calls) | **138.4 µs** | — | — |
91
+ | Snapshot size (typical agent) | **< 2 KB** | N/A | N/A |
92
+ | Memory per execution | **~10 KB** | ~50+ MB | ~20+ MB |
93
+ | Cold start | **~2 µs** | ~200-500 ms | ~5-50 ms |
94
+
95
+ No background thread, no GC, no runtime — CPU usage is exactly proportional to the instructions executed.
96
+
97
+ ```bash
98
+ cargo bench # run benchmarks yourself
99
+ ```
100
+
101
+ ## Installation
102
+
103
+ **TypeScript / JavaScript**
104
+ ```bash
105
+ npm install @unchartedfr/zapcode # npm / yarn / pnpm / bun
106
+ ```
107
+
108
+ **Python**
109
+ ```bash
110
+ pip install zapcode # pip / uv
111
+ ```
112
+
113
+ **Rust**
114
+ ```toml
115
+ # Cargo.toml
116
+ [dependencies]
117
+ zapcode-core = "1.0.0"
118
+ ```
119
+
120
+ **WebAssembly**
121
+ ```bash
122
+ wasm-pack build crates/zapcode-wasm --target web
123
+ ```
124
+
125
+ ## Basic Usage
126
+
127
+ ### TypeScript / JavaScript
128
+
129
+ ```typescript
130
+ import { Zapcode, ZapcodeSnapshotHandle } from '@unchartedfr/zapcode';
131
+
132
+ // Simple expression
133
+ const b = new Zapcode('1 + 2 * 3');
134
+ console.log(b.run().output); // 7
135
+
136
+ // With inputs
137
+ const greeter = new Zapcode(
138
+ '`Hello, ${name}! You are ${age} years old.`',
139
+ { inputs: ['name', 'age'] },
140
+ );
141
+ console.log(greeter.run({ name: 'Zapcode', age: 30 }).output);
142
+
143
+ // Data processing
144
+ const processor = new Zapcode(`
145
+ const items = [
146
+ { name: "Widget", price: 25.99, qty: 3 },
147
+ { name: "Gadget", price: 49.99, qty: 1 },
148
+ ];
149
+ const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
150
+ ({ total, names: items.map(i => i.name) })
151
+ `);
152
+ console.log(processor.run().output);
153
+ // { total: 127.96, names: ["Widget", "Gadget"] }
154
+
155
+ // External function (snapshot/resume)
156
+ const app = new Zapcode(`const data = await fetch(url); data`, {
157
+ inputs: ['url'],
158
+ externalFunctions: ['fetch'],
159
+ });
160
+ const state = app.start({ url: 'https://api.example.com' });
161
+ if (!state.completed) {
162
+ console.log(state.functionName); // "fetch"
163
+ const snapshot = ZapcodeSnapshotHandle.load(state.snapshot);
164
+ const final_ = snapshot.resume({ status: 'ok' });
165
+ console.log(final_.output); // { status: "ok" }
166
+ }
167
+ ```
168
+
169
+ See [`examples/typescript/basic.ts`](examples/typescript/basic.ts) for more.
170
+
171
+ ### Python
172
+
173
+ ```python
174
+ from zapcode import Zapcode, ZapcodeSnapshot
175
+
176
+ # Simple expression
177
+ b = Zapcode("1 + 2 * 3")
178
+ print(b.run()["output"]) # 7
179
+
180
+ # With inputs
181
+ b = Zapcode(
182
+ '`Hello, ${name}!`',
183
+ inputs=["name"],
184
+ )
185
+ print(b.run({"name": "Zapcode"})["output"]) # "Hello, Zapcode!"
186
+
187
+ # External function (snapshot/resume)
188
+ b = Zapcode(
189
+ "const w = await getWeather(city); `${city}: ${w.temp}°C`",
190
+ inputs=["city"],
191
+ external_functions=["getWeather"],
192
+ )
193
+ state = b.start({"city": "London"})
194
+ if state.get("suspended"):
195
+ result = state["snapshot"].resume({"condition": "Cloudy", "temp": 12})
196
+ print(result["output"]) # "London: 12°C"
197
+
198
+ # Snapshot persistence
199
+ state = b.start({"city": "Tokyo"})
200
+ if state.get("suspended"):
201
+ bytes_ = state["snapshot"].dump() # serialize to bytes
202
+ restored = ZapcodeSnapshot.load(bytes_) # load from bytes
203
+ result = restored.resume({"condition": "Clear", "temp": 26})
204
+ ```
205
+
206
+ See [`examples/python/basic.py`](examples/python/basic.py) for more.
207
+
208
+ <details>
209
+ <summary><strong>Rust</strong></summary>
210
+
211
+ ```rust
212
+ use zapcode_core::{ZapcodeRun, Value, ResourceLimits, VmState};
213
+
214
+ // Simple expression
215
+ let runner = ZapcodeRun::new(
216
+ "1 + 2 * 3".to_string(), vec![], vec![],
217
+ ResourceLimits::default(),
218
+ )?;
219
+ assert_eq!(runner.run_simple()?, Value::Int(7));
220
+
221
+ // With inputs and external functions (snapshot/resume)
222
+ let runner = ZapcodeRun::new(
223
+ r#"const weather = await getWeather(city);
224
+ `${city}: ${weather.condition}, ${weather.temp}°C`"#.to_string(),
225
+ vec!["city".to_string()],
226
+ vec!["getWeather".to_string()],
227
+ ResourceLimits::default(),
228
+ )?;
229
+
230
+ let state = runner.start(vec![
231
+ ("city".to_string(), Value::String("London".into())),
232
+ ])?;
233
+
234
+ if let VmState::Suspended { snapshot, .. } = state {
235
+ let weather = Value::Object(indexmap::indexmap! {
236
+ "condition".into() => Value::String("Cloudy".into()),
237
+ "temp".into() => Value::Int(12),
238
+ });
239
+ let final_state = snapshot.resume(weather)?;
240
+ // VmState::Complete("London: Cloudy, 12°C")
241
+ }
242
+ ```
243
+
244
+ See [`examples/rust/basic.rs`](examples/rust/basic.rs) for more.
245
+ </details>
246
+
247
+ <details>
248
+ <summary><strong>WebAssembly (browser)</strong></summary>
249
+
250
+ ```html
251
+ <script type="module">
252
+ import init, { Zapcode } from './zapcode-wasm/zapcode_wasm.js';
253
+
254
+ await init();
255
+
256
+ const b = new Zapcode(`
257
+ const items = [10, 20, 30];
258
+ items.map(x => x * 2).reduce((a, b) => a + b, 0)
259
+ `);
260
+ const result = b.run();
261
+ console.log(result.output); // 120
262
+ </script>
263
+ ```
264
+
265
+ See [`examples/wasm/index.html`](examples/wasm/index.html) for a full playground.
266
+ </details>
267
+
268
+ ## AI Agent Usage
269
+
270
+ ### Vercel AI SDK (@unchartedfr/zapcode-ai)
271
+
272
+ ```bash
273
+ npm install @unchartedfr/zapcode-ai ai @ai-sdk/anthropic # or @ai-sdk/amazon-bedrock, @ai-sdk/openai
274
+ ```
275
+
276
+ The recommended way — one call gives you `{ system, tools }` that plug directly into `generateText` / `streamText`:
277
+
278
+ ```typescript
279
+ import { zapcode } from "@unchartedfr/zapcode-ai";
280
+ import { generateText } from "ai";
281
+ import { anthropic } from "@ai-sdk/anthropic";
282
+
283
+ const { system, tools } = zapcode({
284
+ system: "You are a helpful travel assistant.",
285
+ tools: {
286
+ getWeather: {
287
+ description: "Get current weather for a city",
288
+ parameters: { city: { type: "string", description: "City name" } },
289
+ execute: async ({ city }) => {
290
+ const res = await fetch(`https://api.weather.com/${city}`);
291
+ return res.json();
292
+ },
293
+ },
294
+ searchFlights: {
295
+ description: "Search flights between two cities",
296
+ parameters: {
297
+ from: { type: "string" },
298
+ to: { type: "string" },
299
+ date: { type: "string" },
300
+ },
301
+ execute: async ({ from, to, date }) => {
302
+ return flightAPI.search(from, to, date);
303
+ },
304
+ },
305
+ },
306
+ });
307
+
308
+ // Works with any AI SDK model — Anthropic, OpenAI, Google, etc.
309
+ const { text } = await generateText({
310
+ model: anthropic("claude-sonnet-4-20250514"),
311
+ system,
312
+ tools,
313
+ messages: [{ role: "user", content: "Weather in Tokyo and cheapest flight from London?" }],
314
+ });
315
+ ```
316
+
317
+ Under the hood: the LLM writes TypeScript code that calls your tools → Zapcode executes it in a sandbox → tool calls suspend the VM → your `execute` functions run on the host → results flow back in. All in ~2µs startup + tool execution time.
318
+
319
+ See [`examples/typescript/ai-agent-zapcode-ai.ts`](examples/typescript/ai-agent-zapcode-ai.ts) for the full working example.
320
+
321
+ <details>
322
+ <summary><strong>Anthropic SDK</strong></summary>
323
+
324
+ **TypeScript:**
325
+
326
+ ```typescript
327
+ import Anthropic from "@anthropic-ai/sdk";
328
+ import { Zapcode, ZapcodeSnapshotHandle } from "@unchartedfr/zapcode";
329
+
330
+ const tools = {
331
+ getWeather: async (city: string) => {
332
+ const res = await fetch(`https://api.weather.com/${city}`);
333
+ return res.json();
334
+ },
335
+ };
336
+
337
+ const client = new Anthropic();
338
+ const response = await client.messages.create({
339
+ model: "claude-sonnet-4-20250514",
340
+ max_tokens: 1024,
341
+ system: `Write TypeScript to answer the user's question.
342
+ Available functions (use await): getWeather(city: string) → { condition, temp }
343
+ Last expression = output. No markdown fences.`,
344
+ messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
345
+ });
346
+
347
+ const code = response.content[0].type === "text" ? response.content[0].text : "";
348
+
349
+ // Execute + resolve tool calls via snapshot/resume
350
+ const sandbox = new Zapcode(code, { externalFunctions: ["getWeather"] });
351
+ let state = sandbox.start();
352
+ while (!state.completed) {
353
+ const result = await tools[state.functionName](...state.args);
354
+ state = ZapcodeSnapshotHandle.load(state.snapshot).resume(result);
355
+ }
356
+ console.log(state.output);
357
+ ```
358
+
359
+ **Python:**
360
+
361
+ ```python
362
+ import anthropic
363
+ from zapcode import Zapcode
364
+
365
+ client = anthropic.Anthropic()
366
+ response = client.messages.create(
367
+ model="claude-sonnet-4-20250514",
368
+ max_tokens=1024,
369
+ system="""Write TypeScript to answer the user's question.
370
+ Available functions (use await): getWeather(city: string) → { condition, temp }
371
+ Last expression = output. No markdown fences.""",
372
+ messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
373
+ )
374
+ code = response.content[0].text
375
+
376
+ sandbox = Zapcode(code, external_functions=["getWeather"])
377
+ state = sandbox.start()
378
+ while state.get("suspended"):
379
+ result = get_weather(*state["args"])
380
+ state = state["snapshot"].resume(result)
381
+ print(state["output"])
382
+ ```
383
+
384
+ See [`examples/typescript/ai-agent-anthropic.ts`](examples/typescript/ai-agent-anthropic.ts) and [`examples/python/ai_agent_anthropic.py`](examples/python/ai_agent_anthropic.py).
385
+ </details>
386
+
387
+ <details>
388
+ <summary><strong>Multi-SDK support</strong></summary>
389
+
390
+ `zapcode()` returns adapters for all major AI SDKs from a single call:
391
+
392
+ ```typescript
393
+ const { system, tools, openaiTools, anthropicTools, handleToolCall } = zapcode({
394
+ tools: { getWeather: { ... } },
395
+ });
396
+
397
+ // Vercel AI SDK
398
+ await generateText({ model: anthropic("claude-sonnet-4-20250514"), system, tools, messages });
399
+
400
+ // OpenAI SDK
401
+ await openai.chat.completions.create({
402
+ messages: [{ role: "system", content: system }, ...userMessages],
403
+ tools: openaiTools,
404
+ });
405
+
406
+ // Anthropic SDK
407
+ await anthropic.messages.create({ system, tools: anthropicTools, messages });
408
+
409
+ // Any SDK — just extract the code from the tool call and pass it to handleToolCall
410
+ const result = await handleToolCall(codeFromToolCall);
411
+ ```
412
+
413
+ ```python
414
+ b = zapcode(tools={...})
415
+ b.anthropic_tools # → Anthropic SDK format
416
+ b.openai_tools # → OpenAI SDK format
417
+ b.handle_tool_call(code) # → Universal handler
418
+ ```
419
+ </details>
420
+
421
+ <details>
422
+ <summary><strong>Custom adapters</strong></summary>
423
+
424
+ Build a custom adapter for any AI SDK without forking Zapcode:
425
+
426
+ ```typescript
427
+ import { zapcode, createAdapter } from "@unchartedfr/zapcode-ai";
428
+
429
+ const myAdapter = createAdapter("my-sdk", (ctx) => {
430
+ return {
431
+ systemMessage: ctx.system,
432
+ actions: [{
433
+ id: ctx.toolName,
434
+ schema: ctx.toolSchema,
435
+ run: async (input: { code: string }) => {
436
+ return ctx.handleToolCall(input.code);
437
+ },
438
+ }],
439
+ };
440
+ });
441
+
442
+ const { custom } = zapcode({
443
+ tools: { ... },
444
+ adapters: [myAdapter],
445
+ });
446
+
447
+ const myConfig = custom["my-sdk"];
448
+ ```
449
+
450
+ ```python
451
+ from zapcode_ai import zapcode, Adapter, AdapterContext
452
+
453
+ class LangChainAdapter(Adapter):
454
+ name = "langchain"
455
+
456
+ def adapt(self, ctx: AdapterContext):
457
+ from langchain_core.tools import StructuredTool
458
+ return StructuredTool.from_function(
459
+ func=lambda code: ctx.handle_tool_call(code),
460
+ name=ctx.tool_name,
461
+ description=ctx.tool_description,
462
+ )
463
+
464
+ b = zapcode(tools={...}, adapters=[LangChainAdapter()])
465
+ langchain_tool = b.custom["langchain"]
466
+ ```
467
+
468
+ The adapter receives an `AdapterContext` with everything needed: system prompt, tool name, tool JSON schema, and a `handleToolCall` function. Return whatever shape your SDK expects.
469
+ </details>
470
+
471
+ ## What Zapcode Can and Cannot Do
472
+
473
+ **Can do:**
474
+
475
+ - Execute a useful subset of TypeScript — variables, functions, classes, generators, async/await, closures, destructuring, spread/rest, optional chaining, nullish coalescing, template literals, try/catch
476
+ - Strip TypeScript types at parse time via [oxc](https://oxc.rs) — no `tsc` needed
477
+ - Snapshot execution to bytes and resume later, even in a different process or machine
478
+ - Call from Rust, Node.js, Python, or WebAssembly
479
+ - Track and limit resources — memory, allocations, stack depth, and wall-clock time
480
+ - 30+ string methods, 25+ array methods, plus Math, JSON, Object, and Promise builtins
481
+
482
+ **Cannot do:**
483
+
484
+ - Run arbitrary npm packages or the full Node.js standard library
485
+ - Execute regular expressions (parsing supported, execution is a no-op)
486
+ - Provide full `Promise` semantics (`.then()` chains, `Promise.race`, etc.)
487
+ - Run code that requires `this` in non-class contexts
488
+
489
+ These are intentional constraints, not bugs. Zapcode targets one use case: **running code written by AI agents** inside a secure, embeddable sandbox.
490
+
491
+ ## Supported Syntax
492
+
493
+ | Feature | Status |
494
+ |---|---|
495
+ | Variables (`const`, `let`) | Supported |
496
+ | Functions (declarations, arrows, expressions) | Supported |
497
+ | Classes (`constructor`, methods, `extends`, `super`, `static`) | Supported |
498
+ | Generators (`function*`, `yield`, `.next()`) | Supported |
499
+ | Async/await | Supported |
500
+ | Control flow (`if`, `for`, `while`, `do-while`, `switch`, `for-of`) | Supported |
501
+ | Try/catch/finally, `throw` | Supported |
502
+ | Closures with mutable capture | Supported |
503
+ | Destructuring (object and array) | Supported |
504
+ | Spread/rest operators | Supported |
505
+ | Optional chaining (`?.`) | Supported |
506
+ | Nullish coalescing (`??`) | Supported |
507
+ | Template literals | Supported |
508
+ | Type annotations, interfaces, type aliases | Stripped at parse time |
509
+ | String methods (30+) | Supported |
510
+ | Array methods (25+, including `map`, `filter`, `reduce`) | Supported |
511
+ | Math, JSON, Object, Promise | Supported |
512
+ | `import` / `require` / `eval` | Blocked (sandbox) |
513
+ | Regular expressions | Parsed, not executed |
514
+ | `var` declarations | Not supported (use `let`/`const`) |
515
+ | Decorators | Not supported |
516
+ | `Symbol`, `WeakMap`, `WeakSet` | Not supported |
517
+
518
+ ## Security
519
+
520
+ Running AI-generated code is inherently dangerous. Unlike Docker, which isolates at the OS level, Zapcode isolates at the **language level** — no container, no process boundary, no syscall filter. The sandbox must be correct by construction, not by configuration.
521
+
522
+ ### Deny-by-default sandbox
523
+
524
+ Guest code runs inside a bytecode VM with no access to the host:
525
+
526
+ | Blocked | How |
527
+ |---|---|
528
+ | Filesystem (`fs`, `path`) | No `std::fs` in the core crate |
529
+ | Network (`net`, `http`, `fetch`) | No `std::net` in the core crate |
530
+ | Environment (`process.env`, `os`) | No `std::env` in the core crate |
531
+ | `eval`, `Function()`, dynamic import | Blocked at parse time |
532
+ | `import`, `require` | Blocked at parse time |
533
+ | `globalThis`, `global` | Blocked at parse time |
534
+ | Prototype pollution | Not applicable — objects are plain `IndexMap` values |
535
+
536
+ The **only** escape hatch is external functions that you explicitly register. When guest code calls one, the VM suspends and returns a snapshot — your code resolves the call, not the guest.
537
+
538
+ ### Resource limits
539
+
540
+ | Limit | Default | Configurable |
541
+ |---|---|---|
542
+ | Memory | 32 MB | `memory_limit_bytes` |
543
+ | Execution time | 5 seconds | `time_limit_ms` |
544
+ | Call stack depth | 512 frames | `max_stack_depth` |
545
+ | Heap allocations | 100,000 | `max_allocations` |
546
+
547
+ ### Zero `unsafe` code
548
+
549
+ The `zapcode-core` crate contains **zero `unsafe` blocks**. Memory safety is guaranteed by the Rust compiler.
550
+
551
+ <details>
552
+ <summary><strong>Adversarial test suite — 65 tests across 19 attack categories</strong></summary>
553
+
554
+ | Attack category | Tests | Result |
555
+ |---|---|---|
556
+ | Prototype pollution (`Object.prototype`, `__proto__`) | 4 | Blocked |
557
+ | Constructor chain escapes (`({}).constructor.constructor(...)`) | 3 | Blocked |
558
+ | `eval`, `Function()`, indirect eval, dynamic import | 5 | Blocked at parse time |
559
+ | `globalThis`, `process`, `require`, `import` | 6 | Blocked at parse time |
560
+ | Stack overflow (direct + mutual recursion) | 2 | Caught by stack depth limit |
561
+ | Memory exhaustion (huge arrays, string doubling) | 4 | Caught by allocation limit |
562
+ | Infinite loops (`while(true)`, `for(;;)`) | 2 | Caught by time/allocation limit |
563
+ | JSON bombs (deep nesting, huge payloads) | 2 | Depth-limited (max 64) |
564
+ | Sparse array attacks (`arr[1e9]`, `arr[MAX_SAFE_INTEGER]`) | 3 | Capped growth (max +1024) |
565
+ | toString/valueOf hijacking during coercion | 3 | Not invoked (by design) |
566
+ | Unicode escapes for blocked keywords | 2 | Blocked |
567
+ | Computed property access tricks | 2 | Returns undefined |
568
+ | Timing side channels (`performance.now`) | 1 | Blocked |
569
+ | Error message information leakage | 3 | No host paths/env exposed |
570
+ | Type confusion attacks | 4 | Proper TypeError |
571
+ | Promise/Generator internal abuse | 4 | No escape |
572
+ | Negative array indices | 2 | Returns undefined |
573
+ | `setTimeout`, `setInterval`, `Proxy`, `Reflect` | 6 | Blocked |
574
+ | `with` statement, `arguments.callee` | 3 | Blocked |
575
+
576
+ ```bash
577
+ cargo test -p zapcode-core --test security # run the security tests
578
+ ```
579
+
580
+ **Known limitations:**
581
+ - `Object.freeze()` is not yet implemented — frozen objects can still be mutated (correctness gap, not a sandbox escape)
582
+ - User-defined `toString()`/`valueOf()` are not called during implicit type coercion (intentional — prevents injection)
583
+ </details>
584
+
585
+ ## Architecture
586
+
587
+ ```
588
+ TypeScript source
589
+
590
+
591
+ ┌─────────┐ oxc_parser (fastest TS parser in Rust)
592
+ │ Parse │──────────────────────────────────────────► Strip types
593
+ └────┬────┘
594
+
595
+ ┌─────────┐
596
+ │ IR │ ZapcodeIR (statements, expressions, operators)
597
+ └────┬────┘
598
+
599
+ ┌─────────┐
600
+ │ Compile │ Stack-based bytecode (~50 instructions)
601
+ └────┬────┘
602
+
603
+ ┌─────────┐
604
+ │ VM │ Execute, snapshot at external calls, resume later
605
+ └────┬────┘
606
+
607
+ Result / Suspended { snapshot }
608
+ ```
609
+
610
+ ## Contributing
611
+
612
+ ```bash
613
+ git clone https://github.com/TheUncharted/zapcode.git
614
+ cd zapcode
615
+ ./scripts/dev-setup.sh # installs toolchain, builds, runs tests
616
+ ```
617
+
618
+ ## License
619
+
620
+ MIT
621
+
@@ -0,0 +1,6 @@
1
+ zapcode/__init__.py,sha256=flLqHm1WEX1VG1td7YXPqWpuF5eJR90NYFg_UhN_PuI,111
2
+ zapcode/zapcode.cp310-win_amd64.pyd,sha256=766Kq7F3flhkGW75jayLL0Ln7eukhvcVxUswSAZROP4,1916416
3
+ zapcode-1.0.1.dist-info/METADATA,sha256=MJDefMQstt7Zr__A9ZNnogK_6tjRQxK5x-c2fjTPI_g,23414
4
+ zapcode-1.0.1.dist-info/WHEEL,sha256=ZOk5ap3wnNasTVHPFf0pDFBHDBpcBLfTSOHYmY6LHzo,97
5
+ zapcode-1.0.1.dist-info/sboms/zapcode-py.cyclonedx.json,sha256=dV9xAGSsvg88ehar0yUClwLPIjBr48RXIeJRqNGR-DQ,102695
6
+ zapcode-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.12.6)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-win_amd64