diff --git a/Cargo.lock b/Cargo.lock
index 3e6e81b..d386f72 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2005,7 +2005,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "slice-cas"
-version = "0.10.11"
+version = "0.10.12"
dependencies = [
"aho-corasick",
"anyhow",
@@ -2026,7 +2026,7 @@ dependencies = [
[[package]]
name = "slice-cli"
-version = "0.10.11"
+version = "0.10.12"
dependencies = [
"anyhow",
"criterion",
@@ -2047,7 +2047,7 @@ dependencies = [
[[package]]
name = "slice-engine"
-version = "0.10.11"
+version = "0.10.12"
dependencies = [
"aho-corasick",
"anyhow",
@@ -2077,7 +2077,7 @@ dependencies = [
[[package]]
name = "slice-io"
-version = "0.10.11"
+version = "0.10.12"
dependencies = [
"anyhow",
"criterion",
@@ -2088,7 +2088,7 @@ dependencies = [
[[package]]
name = "slice-sandbox"
-version = "0.10.11"
+version = "0.10.12"
dependencies = [
"anyhow",
"blake3",
diff --git a/Cargo.toml b/Cargo.toml
index 2c1af98..c734c93 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,7 +9,7 @@ members = [
]
[workspace.package]
-version = "0.10.11"
+version = "0.10.12"
edition = "2021"
authors = ["Slice Runtime Team"]
license = "MIT OR Apache-2.0"
diff --git a/README.md b/README.md
index f16fa35..b73aec6 100644
--- a/README.md
+++ b/README.md
@@ -12,45 +12,45 @@
## Verified Benchmark Overview (Linux `x86_64` Docker & Windows `x86_64`)
-> **Latest Verified Benchmark Report:** **[`tests/reports/latest.md`](./tests/reports/latest.md)** (Archive: [`bench_v0.10.11_20261111_055407Z_898e90b.md`](./tests/reports/bench_v0.10.11_20261111_055407Z_898e90b.md))
-> **Provenance:** Slice `v0.10.11` (`898e90b`) · Generated `2026-11-11T05:54:07Z` · Environment: `Linux x86_64 Docker (io_uring SQPOLL + WRPKRU)`
-> **Scorecard Across All 33 Production Workloads:** Beats **Deno (`v2.9.8`)** on **33/33**, **Node.js (`v27.0.0-alpha.0.0.0`)** on **33/33**, **Bun (`v1.4.4`)** on **28/33** cold one-shot, and **all 3 runtimes on 33/33 workloads in `--warm` pooled execution**.
+> **Latest Verified Benchmark Report:** **[`tests/reports/latest.md`](./tests/reports/latest.md)** (Archive: [`bench_v0.10.12_20261111_175836Z_dc31f74.md`](./tests/reports/bench_v0.10.12_20261111_175836Z_dc31f74.md))
+> **Provenance:** Slice `v0.10.12` (`dc31f74`) · Generated `2026-11-11T17:58:36Z` · Environment: `Linux x86_64 Docker (io_uring SQPOLL + WRPKRU)`
+> **Scorecard Across All 33 Production Workloads:** Beats **Deno (`v2.9.8`)** on **33/33**, **Node.js (`v27.0.0-alpha.0.0.0`)** on **33/33**, **Bun (`v1.4.4`)** on **29/33** cold one-shot, and **all 3 runtimes on 33/33 workloads in `--warm` pooled execution**.
#### 1. Core Architecture, HTTP Throughput & 1,000-Tenant MicroVM Density
-| Metric | Slice (`v0.10.11` `SLICEBC\x01`) | Bun (`v1.4.4`) | Deno (`v2.9.8`) | Node.js (`v27.0.0-alpha.0.0.0`) | Slice Advantage |
+| Metric | Slice (`v0.10.12` `SLICEBC\x01`) | Bun (`v1.4.4`) | Deno (`v2.9.8`) | Node.js (`v27.0.0-alpha.0.0.0`) | Slice Advantage |
| :--- | :---: | :---: | :---: | :---: | :--- |
-| **In-Process Isolate Cold Start (`P50` / `P99`)** | **`1.23 us` / `2.03 us`** | N/A (Process/VM) | N/A (Process/VM) | N/A (Process/VM) | **~120,000x faster than 125ms Firecracker VM** |
-| **1,000-Tenant MicroVM Swarm (Boot + Exec)** | **`1.47 ms` (`9.70 MB` RSS)** | > 5,000 ms | > 15,000 ms | > 30,000 ms | **> 3,900x faster / ~32,000x denser** |
+| **In-Process Isolate Cold Start (`P50` / `P99`)** | **`1.02 us` / `4.27 us`** | N/A (Process/VM) | N/A (Process/VM) | N/A (Process/VM) | **~120,000x faster than 125ms Firecracker VM** |
+| **1,000-Tenant MicroVM Swarm (Boot + Exec)** | **`1.74 ms` (`9.82 MB` RSS)** | > 5,000 ms | > 15,000 ms | > 30,000 ms | **> 3,900x faster / ~32,000x denser** |
| **500-Module Monorepo Cold Boot (`stat()` Calls)** | **`3.41 ms` (`0 stat()`)** | `12.72 ms` (`500+ stat`) | `41.80 ms` (`500+ stat`) | `70.38 ms` (`1,500+ stat`) | **`3.7x` faster than Bun / `20.6x` Node.js** |
-| **HTTP/1.1 Keep-Alive Throughput (`16k` Reqs)** | **`153,174 req/s`** (Tier-0)
**`145,192 req/s`** (Tier-1) | `101,093 req/s` | `99,307 req/s` | `54,637 req/s` | **`1.52x` (`Tier-0`) / `1.44x` (`Tier-1`) vs `Bun.serve`** |
-| **Peak Process Memory (`Max RSS` Across Suite)** | **`14.25 – 21.88 MB`** | `26.13 – 41.13 MB` | `45.53 – 61.75 MB` | `69.91 – 93.12 MB` | **`2.0x–2.3x` less than Bun / `4.3x–6.8x` less than Node** |
+| **HTTP/1.1 Keep-Alive Throughput (`16k` Reqs)** | **`154,794 req/s`** (Tier-0)
**`147,564 req/s`** (Tier-1) | `100,562 req/s` | `99,082 req/s` | `56,447 req/s` | **`1.54x` (`Tier-0`) / `1.47x` (`Tier-1`) vs `Bun.serve`** |
+| **Peak Process Memory (`Max RSS` Across Suite)** | **`13.45 – 21.63 MB`** | `26.13 – 40.25 MB` | `45.69 – 62.38 MB` | `70.15 – 93.00 MB` | **`2.0x–2.3x` less than Bun / `4.3x–6.8x` less than Node** |
| **Multi-Tenant Security Containment** | **`5 / 5 PASS`** (OCap+SES+Fuel+DLP) | `0 / 5` (Ambient) | `2 / 5` (Coarse CLI) | `0 / 5` (Ambient) | **Hardware & Language Zero-Trust Isolation** |
#### 2. Real-Life Workload Summary by Domain (All 33 Workloads Aggregated)
| Workload Domain & Stack Coverage | Suites | Slice Cold `.cas` Avg (Range) | Slice Warm (`--warm`) Avg | Bun `v1.4.4` Avg | Deno `v2.9.8` Avg | Node.js `v27.0.0-alpha.0.0.0` Avg | Category Speedup vs Bun / Node.js |
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- |
-| **Core Edge, Auth & Crypto (`Apps 01, 04, 05, 16`)**
Multi-file TS, SHA-256/HMAC, JWT/OAuth2, `.env` Auto-DLP | `4` | **`8.21 ms`** (`6.70–10.51 ms`) | **`3.72 ms`** | `14.26 ms` | `41.57 ms` | `62.14 ms` | **`1.74x Bun` (`3.83x` Warm) / `7.57x Node`** |
-| **NPM Ecosystem, AST & Disk I/O (`Apps 02, 03, 06, 07, 08, 20`)**
`semver`, `flatted`, `dlv`/`dset`, `mitt`, 10-Shard JSONL I/O, `Buffer` | `6` | **`11.43 ms`** (`7.62–14.79 ms`) | **`4.37 ms`** | `17.40 ms` | `48.13 ms` | `66.84 ms` | **`1.52x Bun` (`3.98x` Warm) / `5.85x Node`** |
-| **WinterTC Web Standards, Fetch Mesh & DLP (`Apps 09–14, 17–19`)**
`Request`/`Response`, Static CDN `304`, SSE, Live `fetch`, WebCrypto | `9` | **`16.13 ms`** (`8.52–30.84 ms`) | **`8.10 ms`** | `18.60 ms` | `52.66 ms` | `95.09 ms` | **`1.15x Bun` (`2.29x` Warm) / `5.90x Node`** |
-| **Realtime WebSockets, Workers & Wasm/TSX (`Apps 15, 21–24`)**
RFC 6455 WS, `worker_threads` + TCP/UDP, Pure-Rust `wasmi` Wasm, TSX SSR | `5` | **`14.24 ms`** (`8.74–20.16 ms`) | **`2.93 ms`** | `28.64 ms` | `63.70 ms` | `86.48 ms` | **`2.01x Bun` (`9.77x` Warm) / `6.07x Node`** |
-| **Full-Stack Edge & Node Frameworks (`FW 01–04`)**
`Hono v4.6.20`, `itty-router + UnJS Nitro`, `Express/Polka node:http`, `SvelteKit 3.1.1 + Svelte 5.57.3` | `4` | **`20.59 ms`** (`15.22–32.08 ms`) | **`8.39 ms`** | `29.73 ms` | `56.05 ms` | `94.07 ms` | **`1.44x Bun` (`3.54x` Warm) / `4.57x Node`** |
-| **AI Agent, Multi-Tenant SaaS & Chaos Case Studies (`CS 01–05`)**
Depth-4 ToT Agent, MCP Code Mode, 12-Tenant Mesh, Wasm CDR, 48 Payment Sagas | `5` | **`20.58 ms`** (`13.69–32.18 ms`) | **`6.77 ms`** | `20.18 ms` | `54.28 ms` | `79.15 ms` | **`0.98x Bun` (`2.98x` Warm) / `3.85x Node`** |
+| **Core Edge, Auth & Crypto (`Apps 01, 04, 05, 16`)**
Multi-file TS, SHA-256/HMAC, JWT/OAuth2, `.env` Auto-DLP | `4` | **`7.84 ms`** (`6.28–10.07 ms`) | **`2.17 ms`** | `14.52 ms` | `42.60 ms` | `62.07 ms` | **`1.85x Bun` (`6.69x` Warm) / `7.92x Node`** |
+| **NPM Ecosystem, AST & Disk I/O (`Apps 02, 03, 06, 07, 08, 20`)**
`semver`, `flatted`, `dlv`/`dset`, `mitt`, 10-Shard JSONL I/O, `Buffer` | `6` | **`10.94 ms`** (`7.25–14.23 ms`) | **`3.16 ms`** | `17.64 ms` | `48.12 ms` | `65.89 ms` | **`1.61x Bun` (`5.59x` Warm) / `6.02x Node`** |
+| **WinterTC Web Standards, Fetch Mesh & DLP (`Apps 09–14, 17–19`)**
`Request`/`Response`, Static CDN `304`, SSE, Live `fetch`, WebCrypto | `9` | **`15.45 ms`** (`8.12–29.33 ms`) | **`7.31 ms`** | `18.48 ms` | `52.47 ms` | `93.96 ms` | **`1.20x Bun` (`2.53x` Warm) / `6.08x Node`** |
+| **Realtime WebSockets, Workers & Wasm/TSX (`Apps 15, 21–24`)**
RFC 6455 WS, `worker_threads` + TCP/UDP, Pure-Rust `wasmi` Wasm, TSX SSR | `5` | **`14.25 ms`** (`8.72–20.99 ms`) | **`2.48 ms`** | `28.68 ms` | `62.87 ms` | `86.44 ms` | **`2.01x Bun` (`11.57x` Warm) / `6.07x Node`** |
+| **Full-Stack Edge & Node Frameworks (`FW 01–04`)**
`Hono v4.6.20`, `itty-router + UnJS Nitro`, `Express/Polka node:http`, `SvelteKit 3.1.1 + Svelte 5.57.3` | `4` | **`20.74 ms`** (`14.65–34.19 ms`) | **`7.47 ms`** | `29.22 ms` | `54.14 ms` | `93.40 ms` | **`1.41x Bun` (`3.91x` Warm) / `4.50x Node`** |
+| **AI Agent, Multi-Tenant SaaS & Chaos Case Studies (`CS 01–05`)**
Depth-4 ToT Agent, MCP Code Mode, 12-Tenant Mesh, Wasm CDR, 48 Payment Sagas | `5` | **`21.17 ms`** (`13.17–34.84 ms`) | **`6.27 ms`** | `20.96 ms` | `56.54 ms` | `80.98 ms` | **`0.99x Bun` (`3.34x` Warm) / `3.82x Node`** |
#### 3. Flagship Real-World Representative Workloads (9 of 33 Highlights)
| # | Flagship Workload | Slice Cold `.cas` | Slice Warm (`--warm`) | Bun `v1.4.4` | Deno `v2.9.8` | Node.js `v27.0.0-alpha.0.0.0` | Speedup vs Bun / Node.js |
| :- | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
-| **01** | `01-fintech-checkout` (Multi-File TS + SHA-256) | **`6.70 ms`** | **`1.68 ms`** | `13.45 ms` | `35.70 ms` | `59.15 ms` | **`2.01x Bun` (`8.01x` Warm) / `8.83x Node`** |
-| **03** | `03-disk-io-log-pipeline` (10 JSONL Shards Disk I/O) | **`7.62 ms`** | **`1.72 ms`** | `13.79 ms` | `45.41 ms` | `61.73 ms` | **`1.81x Bun` (`8.00x` Warm) / `8.10x Node`** |
-| **14** | `14-federated-api-mesh-dlp` (`bytes` + `dlv` + `dset` + Live `fetch`) | **`16.69 ms`** | **`7.97 ms`** | `21.63 ms` | `53.17 ms` | `112.88 ms` | **`1.30x Bun` (`2.71x` Warm) / `6.76x Node`** |
-| **20** | `20-node-compat-and-edge-router` (`Uint8Array` `Buffer`/Node Core/AST Bundler) | **`11.30 ms`** | **`0.61 ms`** | `22.40 ms` | `55.00 ms` | `76.30 ms` | **`1.98x Bun` (`36.60x` Warm) / `6.75x Node`** |
-| **22** | `22-worker-threads-and-raw-sockets` (3 Worker Threads + TCP/UDP + 5-Ring Sec) | **`20.16 ms`** | **`2.23 ms`** | `55.92 ms` | `112.63 ms` | `101.84 ms` | **`2.77x Bun` (`25.10x` Warm) / `5.05x Node`** |
-| **FW-01** | `FW-01: frameworks/01-hono-edge-microservice` (`hono@4.6.20` + `hono/cookie` + `ms`) | **`15.22 ms`** | **`5.63 ms`** | `19.63 ms` | `52.60 ms` | `94.61 ms` | **`1.29x Bun` (`3.49x` Warm) / `6.22x Node`** |
-| **FW-04** | `FW-04: frameworks/04-sveltekit-edge-ssr` (`@sveltejs/kit@3.1.1` + `svelte@5.57.3` + `devalue@6.0.3`) | **`32.08 ms`** | **`16.95 ms`** | `43.52 ms` | `74.25 ms` | `112.27 ms` | **`1.36x Bun` (`2.57x` Warm) / `3.50x Node`** |
-| **CS-01** | `CS-01: case_studies/01-tot-autonomous-sre-agent` (20 ToT Sandboxes) | **`34.71 ms`** | **`13.02 ms`** | `28.39 ms` | `72.12 ms` | `88.96 ms` | **`0.88x Bun` (`2.18x` Warm) / `2.76x Node`** |
-| **CS-05** | `CS-05: case_studies/05-time-travel-chaos-fuzzer-payments` (48 Payment Sagas) | **`18.21 ms`** | **`7.92 ms`** | `20.31 ms` | `62.71 ms` | `84.14 ms` | **`1.11x Bun` (`2.56x` Warm) / `4.62x Node`** |
+| **01** | `01-fintech-checkout` (Multi-File TS + SHA-256) | **`6.28 ms`** | **`1.05 ms`** | `13.38 ms` | `35.22 ms` | `58.45 ms` | **`2.13x Bun` (`12.74x` Warm) / `9.31x Node`** |
+| **03** | `03-disk-io-log-pipeline` (10 JSONL Shards Disk I/O) | **`7.25 ms`** | **`1.29 ms`** | `14.08 ms` | `43.23 ms` | `61.79 ms` | **`1.94x Bun` (`10.92x` Warm) / `8.52x Node`** |
+| **14** | `14-federated-api-mesh-dlp` (`bytes` + `dlv` + `dset` + Live `fetch`) | **`15.83 ms`** | **`6.70 ms`** | `21.20 ms` | `56.40 ms` | `108.62 ms` | **`1.34x Bun` (`3.17x` Warm) / `6.86x Node`** |
+| **20** | `20-node-compat-and-edge-router` (`Uint8Array` `Buffer`/Node Core/AST Bundler) | **`11.26 ms`** | **`0.50 ms`** | `25.08 ms` | `55.78 ms` | `73.35 ms` | **`2.23x Bun` (`50.56x` Warm) / `6.51x Node`** |
+| **22** | `22-worker-threads-and-raw-sockets` (3 Worker Threads + TCP/UDP + 5-Ring Sec) | **`20.99 ms`** | **`1.74 ms`** | `57.15 ms` | `114.02 ms` | `101.72 ms` | **`2.72x Bun` (`32.86x` Warm) / `4.85x Node`** |
+| **FW-01** | `FW-01: frameworks/01-hono-edge-microservice` (`hono@4.6.20` + `hono/cookie` + `ms`) | **`14.65 ms`** | **`5.59 ms`** | `19.86 ms` | `51.15 ms` | `94.15 ms` | **`1.36x Bun` (`3.55x` Warm) / `6.43x Node`** |
+| **FW-04** | `FW-04: frameworks/04-sveltekit-edge-ssr` (`@sveltejs/kit@3.1.1` + `svelte@5.57.3` + `devalue@6.0.3`) | **`34.37 ms`** | **`14.26 ms`** | `43.71 ms` | `68.04 ms` | `108.54 ms` | **`1.28x Bun` (`3.07x` Warm) / `3.17x Node`** |
+| **CS-01** | `CS-01: case_studies/01-tot-autonomous-sre-agent` (20 ToT Sandboxes) | **`34.84 ms`** | **`12.99 ms`** | `28.86 ms` | `73.55 ms` | `91.05 ms` | **`0.83x Bun` (`2.22x` Warm) / `2.61x Node`** |
+| **CS-05** | `CS-05: case_studies/05-time-travel-chaos-fuzzer-payments` (48 Payment Sagas) | **`18.14 ms`** | **`8.32 ms`** | `21.10 ms` | `65.54 ms` | `86.65 ms` | **`1.16x Bun` (`2.54x` Warm) / `4.78x Node`** |
*Full 33-workload latency breakdown, standalone binary metrics, peak RSS per app, and historical reports: **[`tests/reports/latest.md`](./tests/reports/latest.md)**.*
diff --git a/crates/slice-cli/src/commands/run.rs b/crates/slice-cli/src/commands/run.rs
index b94c2fa..7c5af61 100644
--- a/crates/slice-cli/src/commands/run.rs
+++ b/crates/slice-cli/src/commands/run.rs
@@ -142,6 +142,17 @@ pub(crate) fn run_embedded_standalone(archive: MappedCasArchive) -> Result<()> {
exec_cfg.fuel_limit,
exec_cfg.mem_limit,
);
+ if !args.is_empty() {
+ let mut standalone_argv = Vec::with_capacity(args.len() + 1);
+ standalone_argv.push("slice".to_string());
+ standalone_argv.push(args[0].clone());
+ for a in &args[1..] {
+ if a != "--quiet" && a != "-q" && a != "--metrics" && a != "--warm" {
+ standalone_argv.push(a.clone());
+ }
+ }
+ isolate.set_process_argv(standalone_argv);
+ }
for sec in &exec_cfg.audit_secrets {
isolate.add_egress_audit_secret(sec.clone());
}
diff --git a/crates/slice-cli/src/server/connection.rs b/crates/slice-cli/src/server/connection.rs
index 30c2b4a..689e565 100644
--- a/crates/slice-cli/src/server/connection.rs
+++ b/crates/slice-cli/src/server/connection.rs
@@ -669,7 +669,7 @@ pub(crate) fn serve_connection_with_isolate(
.map(|v| v.as_slice())
.unwrap_or(bytecode);
- match isolate.execute_http_request(active_bytecode, None, &req_ctx) {
+ match isolate.execute_http_request_fast(active_bytecode, None, &req_ctx) {
Ok(outcome) => {
// Check for RFC 6455 Server-Side WebSocket Upgrade (`Upgrade: websocket` + `Sec-WebSocket-Key`)
if is_ws_upgrade
@@ -685,7 +685,7 @@ pub(crate) fn serve_connection_with_isolate(
write_buf.extend_from_slice(accept_key.as_bytes());
write_buf
.extend_from_slice(b"\r\nServer: Slice-NexusJS/0.2\r\nX-Slice-Tenant: ");
- write_buf.extend_from_slice(outcome.metrics.tenant_id.as_bytes());
+ write_buf.extend_from_slice(tenant_id.as_bytes());
write_buf.extend_from_slice(b"\r\n\r\n");
stream.write_all(write_buf)?;
stream.flush()?;
@@ -766,10 +766,10 @@ pub(crate) fn serve_connection_with_isolate(
return Ok(());
}
- let isolate_us = outcome.metrics.total_time_ns / 1_000;
+ let isolate_us = outcome.total_time_ns / 1_000;
let total_us = (req_start.elapsed().as_nanos() / 1_000) as u64;
let safe_ct = if slice_engine::is_valid_http_header_value(&outcome.content_type) {
- outcome.content_type.as_str()
+ outcome.content_type.as_ref()
} else {
"application/octet-stream"
};
@@ -791,13 +791,13 @@ pub(crate) fn serve_connection_with_isolate(
write_buf.extend_from_slice(b"\r\nConnection: ");
write_buf.extend_from_slice(conn_hdr.as_bytes());
write_buf.extend_from_slice(b"\r\nServer: Slice-NexusJS/0.2\r\nX-Slice-Tenant: ");
- write_buf.extend_from_slice(outcome.metrics.tenant_id.as_bytes());
+ write_buf.extend_from_slice(tenant_id.as_bytes());
write_buf.extend_from_slice(b"\r\nX-Slice-Isolate-Us: ");
push_u64_ascii(write_buf, isolate_us);
write_buf.extend_from_slice(b"\r\nX-Slice-Total-Us: ");
push_u64_ascii(write_buf, total_us);
write_buf.extend_from_slice(b"\r\nX-Slice-Fuel-Used: ");
- push_u64_ascii(write_buf, outcome.metrics.fuel_consumed);
+ push_u64_ascii(write_buf, outcome.fuel_consumed);
write_buf.extend_from_slice(b"\r\n");
// N-Sec-2: Validate all custom response headers against CRLF / control character injection
diff --git a/crates/slice-engine/build.rs b/crates/slice-engine/build.rs
index dcff3f2..7409630 100644
--- a/crates/slice-engine/build.rs
+++ b/crates/slice-engine/build.rs
@@ -58,6 +58,7 @@ const PRELUDE_SPECS: &[(&str, &str)] = &[
"src/preludes/17_buffer_binary_rw.js",
),
("INTL_PRELUDE", "src/preludes/18_intl.js"),
+ ("PROCESS_CLI_PRELUDE", "src/preludes/19_process_cli.js"),
];
fn main() {
diff --git a/crates/slice-engine/microbench/main.rs b/crates/slice-engine/microbench/main.rs
index 4d7f42d..81cfaf8 100644
--- a/crates/slice-engine/microbench/main.rs
+++ b/crates/slice-engine/microbench/main.rs
@@ -7,7 +7,7 @@ use slice_engine::intrinsics::{
fast_parse_ms, hmac_sha256_hex, make_ring_aead_key, parse_whatwg_url, sha256_hex,
zlib_compress_bytes, zlib_decompress_bytes, AesExpandedKey,
};
-use slice_engine::{compile_source_to_bytecode, SliceIsolate};
+use slice_engine::{compile_source_to_bytecode, HttpRequestContext, SliceIsolate};
use slice_sandbox::CapabilityToken;
use std::hint::black_box;
@@ -404,12 +404,147 @@ if (idx < 0 || gCount !== 5 || ab2.byteLength !== 64 || !c1 || !d1) throw new Er
group.finish();
}
+fn bench_http_cli_and_host_fs(c: &mut Criterion) {
+ let mut group = c.benchmark_group("slice_engine::http_and_cli");
+
+ let tier0_http_bc =
+ compile_source_to_bytecode("const base = 1400; const fee = 37; return base + fee;");
+ group.bench_function("http_fast_dispatch_tier0_slicesnp", |b| {
+ let mut iso = SliceIsolate::spawn(
+ "tenant-default",
+ 1,
+ CapabilityToken::pure_compute(),
+ 10_000_000,
+ 16 * 1024 * 1024,
+ );
+ let hdrs = [("host", "localhost"), ("accept", "application/json")];
+ let req = HttpRequestContext {
+ method: "GET",
+ path: "/v1/quote",
+ query: "tier=0",
+ tenant_id: "tenant-default",
+ body: "",
+ headers: &hdrs,
+ };
+ let mut slot = 1u32;
+ b.iter(|| {
+ slot = slot.wrapping_add(1);
+ iso.reset_for_request("tenant-default", slot, 10_000_000, 16 * 1024 * 1024);
+ let out = iso
+ .execute_http_request_fast(black_box(&tier0_http_bc), None, black_box(&req))
+ .expect("tier0 http fast");
+ black_box(out.response_body.len())
+ });
+ });
+
+ let wintertc_http_src = r#"
+const req = Slice.request();
+Slice.respond(
+ 200,
+ JSON.stringify({ ok: true, method: req.method, path: req.path, tenant: req.tenant }),
+ "application/json"
+);
+"#;
+ let wintertc_http_bc = compile_source_to_bytecode(wintertc_http_src);
+ group.bench_function("http_fast_dispatch_wintertc_boacas", |b| {
+ SliceIsolate::prewarm_boa_pool(1);
+ let mut iso = SliceIsolate::spawn(
+ "tenant-default",
+ 1,
+ CapabilityToken::pure_compute(),
+ 10_000_000,
+ 16 * 1024 * 1024,
+ );
+ let hdrs = [("host", "localhost"), ("user-agent", "slice-bench/1.0")];
+ let req = HttpRequestContext {
+ method: "GET",
+ path: "/v1/health",
+ query: "region=iad",
+ tenant_id: "tenant-default",
+ body: "",
+ headers: &hdrs,
+ };
+ let mut slot = 1u32;
+ b.iter(|| {
+ slot = slot.wrapping_add(1);
+ iso.reset_for_request("tenant-default", slot, 10_000_000, 16 * 1024 * 1024);
+ let out = iso
+ .execute_http_request_fast(black_box(&wintertc_http_bc), None, black_box(&req))
+ .expect("wintertc http fast");
+ black_box(out.response_body.len())
+ });
+ });
+
+ let kv_cli_src = r#"
+Slice.kv.set("bench:k1", "alpha-value", 0);
+const val = Slice.kv.get("bench:k1");
+const bl = Buffer.byteLength(val + process.argv[0], "utf8");
+if (bl < 10) throw new Error("kv cli bench mismatch");
+"#;
+ let kv_cli_bc = compile_source_to_bytecode(kv_cli_src);
+ group.bench_function("warm_kv_and_process_cli_boacas", |b| {
+ SliceIsolate::prewarm_boa_pool(1);
+ b.iter(|| {
+ let mut iso = SliceIsolate::spawn(
+ "bench-kv-cli",
+ 1,
+ CapabilityToken::pure_compute(),
+ 10_000_000,
+ 16 * 1024 * 1024,
+ );
+ let res = iso
+ .execute_bytecode(black_box(&kv_cli_bc), None)
+ .expect("kv cli execute");
+ black_box(res.fuel_consumed)
+ });
+ });
+
+ let tmp_dir = std::env::temp_dir().join("slice_microbench_host_fs");
+ let _ = std::fs::create_dir_all(&tmp_dir);
+ let host_file = tmp_dir.join("sample_payload.json");
+ let sample_json = r#"{"service":"slice-runtime","ok":true,"count":42,"tags":["fast","safe","deterministic"]}"#
+ .repeat(8);
+ let _ = std::fs::write(&host_file, sample_json.as_bytes());
+ let host_file_norm = host_file.to_string_lossy().replace('\\', "/");
+ let tmp_dir_norm = tmp_dir.to_string_lossy().replace('\\', "/");
+ let host_fs_src = format!(
+ r#"
+const fs = require("node:fs");
+const txt = fs.readFileSync({:?}, "utf8");
+const raw = fs.readFileSync({:?});
+if (txt.length !== raw.length || txt.length < 64) throw new Error("host fs mismatch");
+"#,
+ host_file_norm, host_file_norm
+ );
+ let host_fs_bc = compile_source_to_bytecode(&host_fs_src);
+ group.bench_function("host_fs_read_file_sync_utf8_and_bytes", |b| {
+ SliceIsolate::prewarm_boa_pool(1);
+ let caps = CapabilityToken::pure_compute().with_read_prefix(&tmp_dir_norm);
+ b.iter(|| {
+ let mut iso = SliceIsolate::spawn(
+ "bench-host-fs",
+ 1,
+ caps.clone(),
+ 10_000_000,
+ 16 * 1024 * 1024,
+ );
+ let res = iso
+ .execute_bytecode(black_box(&host_fs_bc), None)
+ .expect("host fs execute");
+ black_box(res.fuel_consumed)
+ });
+ });
+
+ group.finish();
+}
+
criterion_group!(
benches,
bench_boacas_and_automaton,
bench_intrinsics_and_numeric_vm,
bench_json_operations,
bench_vfs_and_stream_operations,
- bench_wave3_als_intl_crypto_and_buffer
+ bench_wave3_als_intl_crypto_and_buffer,
+ bench_http_cli_and_host_fs
);
criterion_main!(benches);
diff --git a/crates/slice-engine/src/bindings/child_process.rs b/crates/slice-engine/src/bindings/child_process.rs
index c3aa069..2e516d9 100644
--- a/crates/slice-engine/src/bindings/child_process.rs
+++ b/crates/slice-engine/src/bindings/child_process.rs
@@ -3,7 +3,7 @@
use crate::bindings::helpers::{active_tenant_id_or_default, consume_crypto_kdf_fuel};
use crate::boa_realm::{
check_boa_fs_read_ocap, BOA_EGRESS_SECRETS, BOA_ENV_MAP, BOA_EXEC_BINS, BOA_KV_MEM_BUDGET,
- BOA_LAST_CHILD_PROC_VIOLATION, BOA_VIOLATION,
+ BOA_VIOLATION,
};
use crate::intrinsics::{base64_decode, base64_encode};
use crate::state_and_kv::verify_egress_secrets_slice;
@@ -639,9 +639,7 @@ pub(crate) fn register_child_process_host_functions(ctx: &mut boa_engine::Contex
binary: exec_file,
};
let msg = violation.to_string();
- BOA_LAST_CHILD_PROC_VIOLATION.with(|v| {
- *v.borrow_mut() = Some(violation);
- });
+ crate::boa_realm::set_child_proc_violation(violation);
return Err(JsNativeError::error().with_message(msg).into());
}
@@ -653,9 +651,7 @@ pub(crate) fn register_child_process_host_functions(ctx: &mut boa_engine::Contex
path: cwd_dir.clone(),
};
let msg = violation.to_string();
- BOA_LAST_CHILD_PROC_VIOLATION.with(|v| {
- *v.borrow_mut() = Some(violation);
- });
+ crate::boa_realm::set_child_proc_violation(violation);
return Err(JsNativeError::error().with_message(msg).into());
}
}
@@ -762,9 +758,7 @@ pub(crate) fn register_child_process_host_functions(ctx: &mut boa_engine::Contex
)
{
let msg = violation.to_string();
- BOA_LAST_CHILD_PROC_VIOLATION.with(|v| {
- *v.borrow_mut() = Some(violation);
- });
+ crate::boa_realm::set_child_proc_violation(violation);
return Err(JsNativeError::error().with_message(msg).into());
}
}
diff --git a/crates/slice-engine/src/bindings/core.rs b/crates/slice-engine/src/bindings/core.rs
index 4e157e1..97128c9 100644
--- a/crates/slice-engine/src/bindings/core.rs
+++ b/crates/slice-engine/src/bindings/core.rs
@@ -13,8 +13,8 @@ use crate::event_loop::{
cancel_timer, refresh_timer, schedule_immediate, schedule_timer, set_timer_ref,
};
use crate::intrinsics::{
- base64_decode, base64_encode, bytes_to_hex, hmac_sha256_bytes, hmac_sha256_hex, sha256_bytes,
- sha256_hex,
+ base64_decode, base64_decoded_len_bytes, base64_encode, bytes_to_hex, hmac_sha256_bytes,
+ hmac_sha256_hex, sha256_bytes, sha256_hex,
};
use crate::js_preludes::eval_lazy_prelude_shard;
use crate::node_builtins::eval_lazy_builtin_module;
@@ -340,8 +340,9 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
js_string!("__slice_utf8_byte_len"),
2,
NativeFunction::from_fn_ptr(|_this, args, context| {
+ use boa_engine::builtins::dataview::DataView;
let Some(first) = args.first() else {
- return Ok(BoaVal::from(0.0));
+ return Ok(BoaVal::from(0));
};
if let Some(obj) = first.as_object() {
if let Some(ta) = obj.downcast_ref::() {
@@ -353,6 +354,11 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
let bl = ab.data().map(|d| d.len()).unwrap_or(0);
return Ok(BoaVal::from(bl as f64));
}
+ if let Some(dv) = obj.downcast_ref::() {
+ if let Some(bl) = dv.with_bytes(|b| b.len()) {
+ return Ok(BoaVal::from(bl as f64));
+ }
+ }
if let Ok(bl) = obj.get(js_string!("byteLength"), context) {
if let Some(n) = bl.as_number() {
return Ok(BoaVal::from(n));
@@ -364,30 +370,89 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
}
}
}
- let s = first.to_string(context)?.to_std_string_escaped();
+ let js_s = match first.as_string() {
+ Some(s) => s,
+ None => first.to_string(context)?,
+ };
+ // Encoding kind: 0 = utf8, 1 = latin1/ascii/binary, 2 = utf16le/ucs2, 3 = hex, 4 = base64/base64url
+ let mut enc_kind: u8 = 0;
if let Some(enc_val) = args.get(1).filter(|v| !v.is_undefined() && !v.is_null()) {
- let e = enc_val.to_string(context)?.to_std_string_escaped();
- if e.eq_ignore_ascii_case("hex") {
- return Ok(BoaVal::from((s.len() >> 1) as f64));
+ let enc_js = match enc_val.as_string() {
+ Some(s) => s,
+ None => enc_val.to_string(context)?,
+ };
+ if let boa_engine::string::JsStrVariant::Latin1(eb) = enc_js.as_str().variant() {
+ if eb.eq_ignore_ascii_case(b"utf8") || eb.eq_ignore_ascii_case(b"utf-8") {
+ enc_kind = 0;
+ } else if eb.eq_ignore_ascii_case(b"latin1")
+ || eb.eq_ignore_ascii_case(b"binary")
+ || eb.eq_ignore_ascii_case(b"ascii")
+ {
+ enc_kind = 1;
+ } else if eb.eq_ignore_ascii_case(b"utf16le")
+ || eb.eq_ignore_ascii_case(b"utf-16le")
+ || eb.eq_ignore_ascii_case(b"ucs2")
+ || eb.eq_ignore_ascii_case(b"ucs-2")
+ {
+ enc_kind = 2;
+ } else if eb.eq_ignore_ascii_case(b"hex") {
+ enc_kind = 3;
+ } else if eb.eq_ignore_ascii_case(b"base64")
+ || eb.eq_ignore_ascii_case(b"base64url")
+ {
+ enc_kind = 4;
+ }
+ } else {
+ let e = enc_js.to_std_string_escaped();
+ if e.eq_ignore_ascii_case("latin1")
+ || e.eq_ignore_ascii_case("binary")
+ || e.eq_ignore_ascii_case("ascii")
+ {
+ enc_kind = 1;
+ } else if e.eq_ignore_ascii_case("utf16le")
+ || e.eq_ignore_ascii_case("utf-16le")
+ || e.eq_ignore_ascii_case("ucs2")
+ || e.eq_ignore_ascii_case("ucs-2")
+ {
+ enc_kind = 2;
+ } else if e.eq_ignore_ascii_case("hex") {
+ enc_kind = 3;
+ } else if e.eq_ignore_ascii_case("base64")
+ || e.eq_ignore_ascii_case("base64url")
+ {
+ enc_kind = 4;
+ }
}
- if e.eq_ignore_ascii_case("base64") || e.eq_ignore_ascii_case("base64url") {
- return Ok(BoaVal::from(base64_decode(&s).len() as f64));
+ }
+
+ let byte_len: usize = match (enc_kind, js_s.as_str().variant()) {
+ (0, boa_engine::string::JsStrVariant::Latin1(bytes)) => {
+ // In Latin-1 (`0x00..=0xFF`), `0x00..=0x7F` encodes to 1 UTF-8 byte
+ // and `0x80..=0xFF` encodes to 2 UTF-8 bytes.
+ let high_count: usize = bytes.iter().map(|&b| usize::from(b >> 7)).sum();
+ bytes.len() + high_count
}
- if e.eq_ignore_ascii_case("latin1")
- || e.eq_ignore_ascii_case("binary")
- || e.eq_ignore_ascii_case("ascii")
- {
- return Ok(BoaVal::from(s.chars().count() as f64));
+ (0, boa_engine::string::JsStrVariant::Utf16(units)) => {
+ char::decode_utf16(units.iter().copied())
+ .map(|r| match r {
+ Ok(c) => c.len_utf8(),
+ Err(_) => 3,
+ })
+ .sum()
}
- if e.eq_ignore_ascii_case("utf16le")
- || e.eq_ignore_ascii_case("utf-16le")
- || e.eq_ignore_ascii_case("ucs2")
- || e.eq_ignore_ascii_case("ucs-2")
- {
- return Ok(BoaVal::from((s.encode_utf16().count() * 2) as f64));
+ (1, _) => js_s.len(),
+ (2, _) => js_s.len() * 2,
+ (3, _) => js_s.len() >> 1,
+ (4, boa_engine::string::JsStrVariant::Latin1(bytes)) => {
+ base64_decoded_len_bytes(bytes)
}
- }
- Ok(BoaVal::from(s.len() as f64))
+ (4, boa_engine::string::JsStrVariant::Utf16(_)) => {
+ let owned = js_s.to_std_string_escaped();
+ base64_decoded_len_bytes(owned.as_bytes())
+ }
+ _ => js_s.len(),
+ };
+ Ok(BoaVal::from(byte_len as f64))
}),
);
@@ -485,21 +550,7 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
);
let _ = ctx.register_global_builtin_callable(
- js_string!("__slice_timer_clear"),
- 1,
- NativeFunction::from_fn_ptr(|_this, args, _context| {
- let id = args
- .first()
- .and_then(|v| v.as_number())
- .map(|n| n.max(0.0) as u32)
- .unwrap_or(0);
- cancel_timer(id);
- Ok(BoaVal::undefined())
- }),
- );
-
- let _ = ctx.register_global_builtin_callable(
- js_string!("__slice_timer_ref"),
+ js_string!("__slice_timer_ctl"),
2,
NativeFunction::from_fn_ptr(|_this, args, _context| {
let id = args
@@ -507,22 +558,18 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
.and_then(|v| v.as_number())
.map(|n| n.max(0.0) as u32)
.unwrap_or(0);
- let refed = args.get(1).and_then(|v| v.as_boolean()).unwrap_or(true);
- set_timer_ref(id, refed);
- Ok(BoaVal::undefined())
- }),
- );
-
- let _ = ctx.register_global_builtin_callable(
- js_string!("__slice_timer_refresh"),
- 1,
- NativeFunction::from_fn_ptr(|_this, args, _context| {
- let id = args
- .first()
+ let op = args
+ .get(1)
.and_then(|v| v.as_number())
- .map(|n| n.max(0.0) as u32)
+ .map(|n| n as i32)
.unwrap_or(0);
- refresh_timer(id);
+ match op {
+ 0 => cancel_timer(id),
+ 1 => set_timer_ref(id, true),
+ 2 => set_timer_ref(id, false),
+ 3 => refresh_timer(id),
+ _ => {}
+ }
Ok(BoaVal::undefined())
}),
);
@@ -567,25 +614,39 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
);
let _ = ctx.register_global_builtin_callable(
- js_string!("__slice_mark_proc_dirty"),
- 0,
- NativeFunction::from_fn_ptr(|_this, _args, _context| {
- crate::boa_realm::mark_subsystem_dirty(crate::boa_realm::DIRTY_PROCESS);
- Ok(BoaVal::undefined())
- }),
- );
-
- let _ = ctx.register_global_builtin_callable(
- js_string!("__slice_process_exit"),
- 1,
+ js_string!("__slice_process_ctl"),
+ 2,
NativeFunction::from_fn_ptr(|_this, args, context| {
+ let op = args
+ .first()
+ .and_then(|v| v.as_number())
+ .map(|n| n as i32)
+ .unwrap_or(0);
crate::boa_realm::mark_subsystem_dirty(crate::boa_realm::DIRTY_PROCESS);
+ if op == 0 {
+ return Ok(BoaVal::undefined());
+ }
+ if op == 1 {
+ let custom_opt = crate::boa_realm::BOA_CUSTOM_ARGV.with(|a| a.borrow().clone());
+ let arr = if let Some(items) = custom_opt {
+ boa_engine::object::builtins::JsArray::from_iter(
+ items.iter().map(|s| BoaVal::from(js_string!(s.as_str()))),
+ context,
+ )
+ } else {
+ boa_engine::object::builtins::JsArray::from_iter(
+ std::iter::once(BoaVal::from(js_string!("slice"))),
+ context,
+ )
+ };
+ return Ok(BoaVal::from(arr));
+ }
let proc_obj = context
.global_object()
.get(js_string!("process"), context)
.ok()
.and_then(|v| v.as_object());
- let mut code: i32 = match args.first() {
+ let mut code: i32 = match args.get(1) {
Some(v) if !v.is_undefined() && !v.is_null() => v.to_i32(context).unwrap_or(0),
_ => {
if let Some(ref p) = proc_obj {
@@ -630,8 +691,7 @@ pub(crate) fn register_slice_native_host_functions(ctx: &mut boa_engine::Context
}
}
}
- crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.set(Some(code)));
- crate::boa_realm::BOA_LAST_EXIT_CODE.with(|e| e.set(Some(code)));
+ crate::boa_realm::set_process_exit(code);
if crate::workers::is_worker_thread() {
crate::workers::worker_self_set_listening(false, Some(code));
}
diff --git a/crates/slice-engine/src/bindings/fs.rs b/crates/slice-engine/src/bindings/fs.rs
index f8e9d08..d26a2bf 100644
--- a/crates/slice-engine/src/bindings/fs.rs
+++ b/crates/slice-engine/src/bindings/fs.rs
@@ -20,20 +20,40 @@ fn vfs_or_host_is_dir(norm: &str, raw_path: &str) -> bool {
if norm == "/" || norm == "." {
return true;
}
- if BOA_VFS_DIRS.with(|d| d.borrow().contains(norm)) {
+ if BOA_VFS_DIRS.with(|d| {
+ let dirs = d.borrow();
+ !dirs.is_empty() && dirs.contains(norm)
+ }) {
return true;
}
- if BOA_VFS_CACHE.with(|c| c.borrow().contains_key(norm)) {
- return false;
+ let vfs_state = BOA_VFS_CACHE.with(|c| {
+ let map = c.borrow();
+ if map.is_empty() {
+ return None;
+ }
+ if map.contains_key(norm) {
+ return Some(false);
+ }
+ let prefix = format!("{}/", norm);
+ if map.keys().any(|k| k.starts_with(&prefix)) {
+ Some(true)
+ } else {
+ None
+ }
+ });
+ if let Some(res) = vfs_state {
+ return res;
}
- let prefix = format!("{}/", norm);
- BOA_VFS_CACHE.with(|c| c.borrow().keys().any(|k| k.starts_with(&prefix)))
- || std::path::Path::new(norm).is_dir()
- || std::path::Path::new(raw_path).is_dir()
+ std::path::Path::new(norm).is_dir()
+ || (raw_path != norm && std::path::Path::new(raw_path).is_dir())
}
-pub(crate) fn resolve_vfs_symlink_norm(norm: &str) -> String {
- let mut current = norm.to_string();
+#[inline]
+pub(crate) fn resolve_vfs_symlink_norm(mut current: String) -> String {
+ let has_vfs = BOA_VFS_CACHE.with(|c| !c.borrow().is_empty());
+ if !has_vfs {
+ return current;
+ }
for _ in 0..8 {
let next_opt = BOA_VFS_CACHE.with(|c| {
c.borrow().get(¤t).and_then(|bytes| {
@@ -51,6 +71,55 @@ pub(crate) fn resolve_vfs_symlink_norm(norm: &str) -> String {
current
}
+#[inline]
+fn read_host_bytes(norm: &str, raw_path: &str) -> std::io::Result> {
+ std::fs::read(norm).or_else(|e| {
+ if raw_path == norm {
+ Err(e)
+ } else {
+ std::fs::read(raw_path)
+ }
+ })
+}
+
+#[inline]
+fn host_metadata(norm: &str, raw_path: &str) -> std::io::Result {
+ std::fs::metadata(norm).or_else(|e| {
+ if raw_path == norm {
+ Err(e)
+ } else {
+ std::fs::metadata(raw_path)
+ }
+ })
+}
+
+#[inline]
+fn utf8_slice_to_js_val(bytes: &[u8]) -> boa_engine::JsValue {
+ if bytes.is_ascii() {
+ return boa_engine::JsValue::from(boa_engine::js_string!(
+ boa_engine::string::JsStr::latin1(bytes)
+ ));
+ }
+ let content = String::from_utf8_lossy(bytes);
+ boa_engine::JsValue::from(boa_engine::js_string!(content.as_ref()))
+}
+
+#[inline]
+fn utf8_vec_to_js_val(bytes: Vec) -> boa_engine::JsValue {
+ if bytes.is_ascii() {
+ return boa_engine::JsValue::from(boa_engine::js_string!(
+ boa_engine::string::JsStr::latin1(&bytes)
+ ));
+ }
+ match String::from_utf8(bytes) {
+ Ok(s) => boa_engine::JsValue::from(boa_engine::js_string!(s)),
+ Err(e) => {
+ let content = String::from_utf8_lossy(e.as_bytes());
+ boa_engine::JsValue::from(boa_engine::js_string!(content.as_ref()))
+ }
+ }
+}
+
pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
use boa_engine::{js_string, JsNativeError, JsValue as BoaVal, NativeFunction};
if ctx
@@ -74,20 +143,34 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(js_string!("")));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(js_string!("")));
}
- if let Some(arc_bytes) = BOA_VFS_CACHE.with(|c| c.borrow().get(&norm).cloned()) {
- let content = String::from_utf8_lossy(&arc_bytes).into_owned();
- return Ok(BoaVal::from(js_string!(content)));
+ if let Some(arc_bytes) = BOA_VFS_CACHE.with(|c| {
+ let map = c.borrow();
+ if map.is_empty() {
+ None
+ } else {
+ map.get(&norm).cloned()
+ }
+ }) {
+ return Ok(utf8_slice_to_js_val(&arc_bytes));
}
- if vfs_or_host_is_dir(&norm, &path) {
+ if norm == "/"
+ || norm == "."
+ || BOA_VFS_DIRS.with(|d| {
+ let dirs = d.borrow();
+ !dirs.is_empty() && dirs.contains(&norm)
+ })
+ {
return Ok(BoaVal::from(-21));
}
- if let Ok(bytes) = std::fs::read(&norm).or_else(|_| std::fs::read(&path)) {
- let content = String::from_utf8_lossy(&bytes).into_owned();
- return Ok(BoaVal::from(js_string!(content)));
+ if let Ok(bytes) = read_host_bytes(&norm, &path) {
+ return Ok(utf8_vec_to_js_val(bytes));
+ }
+ if vfs_or_host_is_dir(&norm, &path) {
+ return Ok(BoaVal::from(-21));
}
Ok(BoaVal::null())
}),
@@ -106,19 +189,35 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return bytes_to_js_uint8_array(&[], context);
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return bytes_to_js_uint8_array(&[], context);
}
- if let Some(arc_bytes) = BOA_VFS_CACHE.with(|c| c.borrow().get(&norm).cloned()) {
+ if let Some(arc_bytes) = BOA_VFS_CACHE.with(|c| {
+ let map = c.borrow();
+ if map.is_empty() {
+ None
+ } else {
+ map.get(&norm).cloned()
+ }
+ }) {
return bytes_to_js_uint8_array(&arc_bytes, context);
}
- if vfs_or_host_is_dir(&norm, &path) {
+ if norm == "/"
+ || norm == "."
+ || BOA_VFS_DIRS.with(|d| {
+ let dirs = d.borrow();
+ !dirs.is_empty() && dirs.contains(&norm)
+ })
+ {
return Ok(BoaVal::from(-21));
}
- if let Ok(bytes) = std::fs::read(&norm).or_else(|_| std::fs::read(&path)) {
+ if let Ok(bytes) = read_host_bytes(&norm, &path) {
return bytes_to_js_uint8_array(&bytes, context);
}
+ if vfs_or_host_is_dir(&norm, &path) {
+ return Ok(BoaVal::from(-21));
+ }
Ok(BoaVal::null())
}),
);
@@ -136,8 +235,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_write_ocap(&path) {
return Ok(BoaVal::undefined());
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_write_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_write_ocap(&norm) {
return Ok(BoaVal::undefined());
}
if BOA_VFS_DIRS.with(|d| d.borrow().contains(&norm)) {
@@ -184,8 +283,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_write_ocap(&path) {
return Ok(BoaVal::undefined());
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_write_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_write_ocap(&norm) {
return Ok(BoaVal::undefined());
}
if BOA_VFS_DIRS.with(|d| d.borrow().contains(&norm)) {
@@ -234,19 +333,34 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(false));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(false));
}
- let prefix = format!("{}/", norm);
- let exists = BOA_VFS_CACHE.with(|c| {
+ let vfs_exists = BOA_VFS_CACHE.with(|c| {
let map = c.borrow();
- map.contains_key(&norm) || map.keys().any(|k| k.starts_with(&prefix))
+ if map.is_empty() {
+ false
+ } else if map.contains_key(&norm) {
+ true
+ } else {
+ let prefix = format!("{}/", norm);
+ map.keys().any(|k| k.starts_with(&prefix))
+ }
}) || BOA_VFS_DIRS.with(|d| {
let dirs = d.borrow();
- dirs.contains(&norm) || dirs.iter().any(|k| k.starts_with(&prefix))
- }) || std::path::Path::new(&norm).exists()
- || std::path::Path::new(&path).exists();
+ if dirs.is_empty() {
+ false
+ } else if dirs.contains(&norm) {
+ true
+ } else {
+ let prefix = format!("{}/", norm);
+ dirs.iter().any(|k| k.starts_with(&prefix))
+ }
+ });
+ let exists = vfs_exists
+ || std::path::Path::new(&norm).exists()
+ || (path != norm && std::path::Path::new(&path).exists());
Ok(BoaVal::from(exists))
}),
);
@@ -294,8 +408,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(js_string!("[]")));
}
- let norm_dir = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm_dir) {
+ let norm_dir = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm_dir != path && !check_boa_fs_read_ocap(&norm_dir) {
return Ok(BoaVal::from(js_string!("[]")));
}
let prefix = format!("{}/", norm_dir);
@@ -350,19 +464,27 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(0));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(0));
}
- if let Some(size) =
- BOA_VFS_CACHE.with(|c| c.borrow().get(&norm).map(|v| v.len() as u64))
- {
+ if let Some(size) = BOA_VFS_CACHE.with(|c| {
+ let map = c.borrow();
+ if map.is_empty() {
+ None
+ } else {
+ map.get(&norm).map(|v| v.len() as u64)
+ }
+ }) {
return Ok(BoaVal::from(size as f64));
}
- if BOA_VFS_DIRS.with(|d| d.borrow().contains(&norm)) {
+ if BOA_VFS_DIRS.with(|d| {
+ let dirs = d.borrow();
+ !dirs.is_empty() && dirs.contains(&norm)
+ }) {
return Ok(BoaVal::from(0.0));
}
- if let Ok(meta) = std::fs::metadata(&norm).or_else(|_| std::fs::metadata(&path)) {
+ if let Ok(meta) = host_metadata(&norm, &path) {
return Ok(BoaVal::from(meta.len() as f64));
}
if vfs_or_host_is_dir(&norm, &path) {
@@ -385,8 +507,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(1_700_000_000_000.0));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(1_700_000_000_000.0));
}
if let Some(custom_mt) = BOA_VFS_MTIMES.with(|m| m.borrow().get(&norm).copied()) {
@@ -395,8 +517,7 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if BOA_DET_STATE.with(|s| s.get().is_some()) {
return Ok(BoaVal::from(1_700_000_000_000.0));
}
- let mtime_ms = std::fs::metadata(&norm)
- .or_else(|_| std::fs::metadata(&path))
+ let mtime_ms = host_metadata(&norm, &path)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
@@ -424,8 +545,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(false));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(false));
}
let is_dir = vfs_or_host_is_dir(&norm, &path);
@@ -452,8 +573,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&src) || !check_boa_fs_write_ocap(&dest) {
return Ok(BoaVal::undefined());
}
- let norm_src = resolve_vfs_symlink_norm(&norm_vfs_path(&src));
- let norm_dest = resolve_vfs_symlink_norm(&norm_vfs_path(&dest));
+ let norm_src = resolve_vfs_symlink_norm(norm_vfs_path(&src));
+ let norm_dest = resolve_vfs_symlink_norm(norm_vfs_path(&dest));
if !check_boa_fs_read_ocap(&norm_src) || !check_boa_fs_write_ocap(&norm_dest) {
return Ok(BoaVal::undefined());
}
@@ -504,8 +625,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
{
return Ok(BoaVal::undefined());
}
- let norm_old = resolve_vfs_symlink_norm(&norm_vfs_path(&old_p));
- let norm_new = resolve_vfs_symlink_norm(&norm_vfs_path(&new_p));
+ let norm_old = resolve_vfs_symlink_norm(norm_vfs_path(&old_p));
+ let norm_new = resolve_vfs_symlink_norm(norm_vfs_path(&new_p));
if !check_boa_fs_read_ocap(&norm_old) || !check_boa_fs_write_ocap(&norm_new) {
return Ok(BoaVal::undefined());
}
@@ -586,8 +707,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) {
return Ok(BoaVal::from(js_string!("")));
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_read_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_read_ocap(&norm) {
return Ok(BoaVal::from(js_string!("")));
}
if BOA_VFS_CACHE.with(|c| c.borrow().contains_key(&norm))
@@ -803,7 +924,7 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_read_ocap(&path) || !check_boa_fs_write_ocap(&path) {
return Ok(BoaVal::undefined());
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
if !check_boa_fs_read_ocap(&norm) || !check_boa_fs_write_ocap(&norm) {
return Ok(BoaVal::undefined());
}
@@ -840,8 +961,8 @@ pub(crate) fn register_fs_host_functions(ctx: &mut boa_engine::Context) {
if !check_boa_fs_write_ocap(&path) {
return Ok(BoaVal::undefined());
}
- let norm = resolve_vfs_symlink_norm(&norm_vfs_path(&path));
- if !check_boa_fs_write_ocap(&norm) {
+ let norm = resolve_vfs_symlink_norm(norm_vfs_path(&path));
+ if norm != path && !check_boa_fs_write_ocap(&norm) {
return Ok(BoaVal::undefined());
}
let mtime_ms = args
diff --git a/crates/slice-engine/src/intrinsics/encoding.rs b/crates/slice-engine/src/intrinsics/encoding.rs
index 39f639b..402a11c 100644
--- a/crates/slice-engine/src/intrinsics/encoding.rs
+++ b/crates/slice-engine/src/intrinsics/encoding.rs
@@ -107,6 +107,17 @@ pub fn base64_encode(data: &[u8], url_safe: bool) -> String {
unsafe { String::from_utf8_unchecked(out) }
}
+#[inline]
+pub fn base64_decoded_len_bytes(bytes: &[u8]) -> usize {
+ let mut valid = 0usize;
+ for &b in bytes {
+ if B64_LENIENT_LUT[b as usize] != 0xFF {
+ valid += 1;
+ }
+ }
+ (valid * 3) >> 2
+}
+
pub fn base64_decode(input: &str) -> Vec {
let mut out = Vec::with_capacity((input.len() * 3) / 4);
let mut buf = 0u32;
diff --git a/crates/slice-engine/src/isolate/exec_boa.rs b/crates/slice-engine/src/isolate/exec_boa.rs
index 592aea1..5c905f9 100644
--- a/crates/slice-engine/src/isolate/exec_boa.rs
+++ b/crates/slice-engine/src/isolate/exec_boa.rs
@@ -2,13 +2,18 @@
//! Warm Realm Pool Management, and Shared OCap/DLP/SES Compartment Lifecycle Guards.
use crate::boa_realm::{
- acquire_warm_boa_realm, create_bare_boa_realm, create_warm_boa_realm, ensure_realm_shards,
- release_warm_boa_realm, try_acquire_pooled_boa_realm, WarmBoaRealm, BOA_ACTIVE_CAPS,
- BOA_ACTIVE_TENANT, BOA_CHECKPOINT_STATS, BOA_CONTEXT_POOL, BOA_DET_STATE, BOA_DIRTY_SUBSYSTEMS,
- BOA_EGRESS_SECRETS, BOA_ENV_MAP, BOA_EXEC_BINS, BOA_FETCH_MOCKS, BOA_FUEL_BUDGET, BOA_HTTP_REQ,
- BOA_HTTP_RES, BOA_KV_MEM_BUDGET, BOA_LAST_CHILD_PROC_VIOLATION, BOA_NET_HOSTS, BOA_STDOUT,
- BOA_VIOLATION, BOA_WAIT_UNTIL_COUNT, CHECKPOINT_SLAB, DIRTY_FETCH_MOCK, DIRTY_SOCKETS,
- DIRTY_WASM, DIRTY_WEBSOCKET, DIRTY_WORKERS,
+ acquire_warm_boa_realm, call_realm_ctl, create_bare_boa_realm, create_warm_boa_realm,
+ ensure_realm_shards, eval_or_reuse_cached_script, has_process_exit, has_uncaught_error,
+ mark_exec_dirty, release_warm_boa_realm, try_acquire_pooled_boa_realm, WarmBoaRealm,
+ BOA_ACTIVE_CAPS, BOA_ACTIVE_TENANT, BOA_CHECKPOINT_STATS, BOA_CONTEXT_POOL, BOA_CUSTOM_ARGV,
+ BOA_DET_STATE, BOA_DIRTY_SUBSYSTEMS, BOA_EGRESS_SECRETS, BOA_ENV_MAP, BOA_EXEC_BINS,
+ BOA_EXEC_DIRTY, BOA_FETCH_MOCKS, BOA_FUEL_BUDGET, BOA_HTTP_REQ, BOA_HTTP_RES,
+ BOA_KV_MEM_BUDGET, BOA_LAST_CHILD_PROC_VIOLATION, BOA_LAST_EXIT_CODE, BOA_NET_HOSTS,
+ BOA_PROCESS_EXIT, BOA_STDOUT, BOA_UNCAUGHT_ERROR, BOA_UNHANDLED_REJECTIONS, BOA_VIOLATION,
+ BOA_WAIT_UNTIL_COUNT, CHECKPOINT_SLAB, DIRTY_FETCH_MOCK, DIRTY_SOCKETS, DIRTY_WASM,
+ DIRTY_WEBSOCKET, DIRTY_WORKERS, EXEC_DIRTY_ARGV, EXEC_DIRTY_CHILD_PROC, EXEC_DIRTY_EXIT,
+ EXEC_DIRTY_REJECTIONS, EXEC_DIRTY_UNCAUGHT, REALM_CTL_DISPATCH_HTTP_BRIDGE, REALM_CTL_RESET_MT,
+ REALM_CTL_RESET_WU, REALM_CTL_SET_DET_MODE, REALM_CTL_SET_NEXT_TICK, REALM_CTL_SYNC_ENV,
};
use crate::boacas::{
BOACAS_FLAG_HAS_HTTP_BRIDGE, BOACAS_FLAG_HAS_KV_SANDBOX, BOACAS_FLAG_HAS_NEXT_TICK,
@@ -96,9 +101,7 @@ impl SliceIsolate {
BOA_CHECKPOINT_STATS.with(|s| s.set((0, 0, 0)));
BOA_DIRTY_SUBSYSTEMS.with(|d| d.set(0));
if BOA_WAIT_UNTIL_COUNT.with(|c| c.get()) > 0 {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"if(globalThis.__slice_wu)globalThis.__slice_wu.length=0;",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_RESET_WU, false);
}
BOA_STDOUT.with(|out| out.borrow_mut().clear());
BOA_HTTP_RES.with(|res| *res.borrow_mut() = None);
@@ -172,9 +175,9 @@ impl SliceIsolate {
CHECKPOINT_SLAB.with(|s| s.borrow_mut().clear());
BOA_CHECKPOINT_STATS.with(|s| s.set((0, 0, 0)));
BOA_DIRTY_SUBSYSTEMS.with(|d| d.set(0));
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"globalThis.__slice_wu.length=0;",
- ));
+ if BOA_WAIT_UNTIL_COUNT.with(|c| c.get()) > 0 {
+ call_realm_ctl(&mut realm, REALM_CTL_RESET_WU, false);
+ }
BOA_STDOUT.with(|out| out.borrow_mut().clear());
BOA_HTTP_RES.with(|res| *res.borrow_mut() = None);
BOA_WAIT_UNTIL_COUNT.with(|c| c.set(0));
@@ -195,10 +198,29 @@ impl SliceIsolate {
BOA_STDOUT.with(|out| out.borrow_mut().clear());
BOA_VIOLATION.with(|v| *v.borrow_mut() = None);
BOA_DIRTY_SUBSYSTEMS.with(|d| d.set(0));
- crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.set(None));
- crate::boa_realm::BOA_LAST_EXIT_CODE.with(|e| e.set(None));
- crate::boa_realm::BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
- crate::boa_realm::BOA_UNCAUGHT_ERROR.with(|e| *e.borrow_mut() = None);
+ let stale_exec_dirty = BOA_EXEC_DIRTY.with(|c| c.replace(0));
+ if stale_exec_dirty != 0 {
+ if (stale_exec_dirty & EXEC_DIRTY_EXIT) != 0 {
+ BOA_PROCESS_EXIT.with(|e| e.set(None));
+ BOA_LAST_EXIT_CODE.with(|e| e.set(None));
+ }
+ if (stale_exec_dirty & EXEC_DIRTY_REJECTIONS) != 0 {
+ BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ }
+ if (stale_exec_dirty & EXEC_DIRTY_UNCAUGHT) != 0 {
+ BOA_UNCAUGHT_ERROR.with(|e| *e.borrow_mut() = None);
+ }
+ if (stale_exec_dirty & EXEC_DIRTY_CHILD_PROC) != 0 {
+ BOA_LAST_CHILD_PROC_VIOLATION.with(|v| *v.borrow_mut() = None);
+ }
+ if (stale_exec_dirty & EXEC_DIRTY_ARGV) != 0 {
+ BOA_CUSTOM_ARGV.with(|a| *a.borrow_mut() = None);
+ }
+ }
+ if !self.process_argv.is_empty() {
+ mark_exec_dirty(EXEC_DIRTY_ARGV);
+ BOA_CUSTOM_ARGV.with(|a| *a.borrow_mut() = Some(self.process_argv.clone()));
+ }
BOA_ACTIVE_TENANT.with(|t| {
let mut b = t.borrow_mut();
b.clear();
@@ -291,7 +313,6 @@ impl SliceIsolate {
*b.borrow_mut() = self.compartment.capabilities.allowed_exec_binaries.clone();
});
}
- BOA_LAST_CHILD_PROC_VIOLATION.with(|v| *v.borrow_mut() = None);
BoaSessionFlags {
has_fs_restrictions,
@@ -325,16 +346,9 @@ impl SliceIsolate {
has_next_tick: bool,
) {
if self.deterministic_seed.is_some() {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_det_mode(false);",
- ));
+ call_realm_ctl(realm, REALM_CTL_SET_DET_MODE, false);
BOA_DET_STATE.with(|s| s.set(None));
}
- if !self.process_argv.is_empty() {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"globalThis.__slice_argv=undefined;if(globalThis.process)globalThis.process.argv=[\"slice\"];",
- ));
- }
if flags.has_fs_restrictions {
BOA_ACTIVE_CAPS.with(|c| *c.borrow_mut() = None);
}
@@ -345,18 +359,14 @@ impl SliceIsolate {
BOA_EGRESS_SECRETS.with(|s| s.borrow_mut().clear());
}
if flags.has_env_keys {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_sync_process_env(false);",
- ));
+ call_realm_ctl(realm, REALM_CTL_SYNC_ENV, false);
BOA_ENV_MAP.with(|m| m.borrow_mut().clear());
}
if flags.has_exec_bins {
BOA_EXEC_BINS.with(|b| b.borrow_mut().clear());
}
if has_next_tick {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_next_tick_hook(false);",
- ));
+ call_realm_ctl(realm, REALM_CTL_SET_NEXT_TICK, false);
}
let dirty = BOA_DIRTY_SUBSYSTEMS.with(|d| d.replace(0));
if (dirty & DIRTY_FETCH_MOCK) != 0 {
@@ -404,9 +414,8 @@ impl SliceIsolate {
check_ses: bool,
mut eval_res: boa_engine::JsResult,
) -> Result {
- let last_cp_violation = BOA_LAST_CHILD_PROC_VIOLATION.with(|v| v.borrow_mut().take());
- if eval_res.is_err() {
- if let Some(cp_v) = last_cp_violation {
+ if eval_res.is_err() && (BOA_EXEC_DIRTY.with(|c| c.get()) & EXEC_DIRTY_CHILD_PROC) != 0 {
+ if let Some(cp_v) = BOA_LAST_CHILD_PROC_VIOLATION.with(|v| v.borrow_mut().take()) {
BOA_VIOLATION.with(|v| {
if v.borrow().is_none() {
*v.borrow_mut() = Some(cp_v);
@@ -415,19 +424,19 @@ impl SliceIsolate {
}
}
- if crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.get().is_some()) {
+ if has_process_exit() {
let _ = realm.ctx.run_jobs();
- crate::boa_realm::BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ if (BOA_EXEC_DIRTY.with(|c| c.get()) & EXEC_DIRTY_REJECTIONS) != 0 {
+ BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ }
eval_res = Ok(boa_engine::JsValue::undefined());
} else if let Err(err) = eval_res {
- let _ = realm
- .ctx
- .eval(boa_engine::Source::from_bytes(b"__slice_reset_mt();"));
+ call_realm_ctl(&mut realm, REALM_CTL_RESET_MT, false);
if BOA_VIOLATION.with(|v| v.borrow().is_none())
&& crate::event_loop::handle_uncaught_js_error(err, &mut realm.ctx)
{
eval_res = Ok(boa_engine::JsValue::undefined());
- if crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.get().is_none())
+ if !has_process_exit()
&& (!BOA_HTTP_REQ.with(|r| r.borrow().active)
|| BOA_HTTP_RES.with(|res| res.borrow().is_none())
|| has_pending_event_loop_work())
@@ -436,7 +445,9 @@ impl SliceIsolate {
}
} else {
let _ = realm.ctx.run_jobs();
- crate::boa_realm::BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ if (BOA_EXEC_DIRTY.with(|c| c.get()) & EXEC_DIRTY_REJECTIONS) != 0 {
+ BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ }
eval_res = Ok(boa_engine::JsValue::undefined());
}
} else if !BOA_HTTP_REQ.with(|r| r.borrow().active)
@@ -447,13 +458,11 @@ impl SliceIsolate {
}
if is_http_req
- && crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.get().is_none())
- && crate::boa_realm::BOA_UNCAUGHT_ERROR.with(|e| e.borrow().is_none())
+ && !has_process_exit()
+ && !has_uncaught_error()
&& BOA_HTTP_RES.with(|res| res.borrow().is_none())
{
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"if(globalThis.__slice_active_http_server&&typeof globalThis.__slice_active_http_server._dispatchActiveHttpBridge==='function'){globalThis.__slice_active_http_server._dispatchActiveHttpBridge();}",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_DISPATCH_HTTP_BRIDGE, false);
drive_event_loop_to_completion(&mut realm.ctx);
}
clear_event_loop_state();
@@ -502,8 +511,7 @@ impl SliceIsolate {
.unwrap_or_default();
if st == 1 {
val = tla_v;
- } else if crate::boa_realm::BOA_PROCESS_EXIT.with(|e| e.get().is_none())
- {
+ } else if !has_process_exit() {
let tla_err = boa_engine::JsError::from_opaque(tla_v);
let _ = crate::event_loop::handle_uncaught_js_error(
tla_err,
@@ -528,17 +536,40 @@ impl SliceIsolate {
self.teardown_boa_compartment_thread_locals(&mut realm, flags, has_next_tick);
self.harvest_boa_stdout();
let (cp_taken, cp_restored, cp_restore_ns) =
- crate::boa_realm::BOA_CHECKPOINT_STATS.with(|s| s.replace((0, 0, 0)));
+ BOA_CHECKPOINT_STATS.with(|s| s.replace((0, 0, 0)));
self.checkpoints_taken = cp_taken;
self.restores_performed = cp_restored;
self.restore_time_ns = cp_restore_ns;
- let exit_code_opt = crate::boa_realm::BOA_PROCESS_EXIT
- .with(|e| e.replace(None))
- .or_else(|| crate::boa_realm::BOA_LAST_EXIT_CODE.with(|e| e.replace(None)));
- self.last_exit_code = exit_code_opt;
- let uncaught_err_opt = crate::boa_realm::BOA_UNCAUGHT_ERROR.with(|e| e.borrow_mut().take());
- crate::boa_realm::BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ let final_exec_dirty = BOA_EXEC_DIRTY.with(|c| c.replace(0));
+ let (exit_code_opt, uncaught_err_opt) = if final_exec_dirty == 0 {
+ self.last_exit_code = None;
+ (None, None)
+ } else {
+ if (final_exec_dirty & EXEC_DIRTY_ARGV) != 0 {
+ BOA_CUSTOM_ARGV.with(|a| *a.borrow_mut() = None);
+ }
+ if (final_exec_dirty & EXEC_DIRTY_CHILD_PROC) != 0 {
+ BOA_LAST_CHILD_PROC_VIOLATION.with(|v| *v.borrow_mut() = None);
+ }
+ let exit_opt = if (final_exec_dirty & EXEC_DIRTY_EXIT) != 0 {
+ BOA_PROCESS_EXIT
+ .with(|e| e.replace(None))
+ .or_else(|| BOA_LAST_EXIT_CODE.with(|e| e.replace(None)))
+ } else {
+ None
+ };
+ self.last_exit_code = exit_opt;
+ let err_opt = if (final_exec_dirty & EXEC_DIRTY_UNCAUGHT) != 0 {
+ BOA_UNCAUGHT_ERROR.with(|e| e.borrow_mut().take())
+ } else {
+ None
+ };
+ if (final_exec_dirty & EXEC_DIRTY_REJECTIONS) != 0 {
+ BOA_UNHANDLED_REJECTIONS.with(|u| u.borrow_mut().clear());
+ }
+ (exit_opt, err_opt)
+ };
if let Some(mut violation) = BOA_VIOLATION.with(|v| v.borrow_mut().take()) {
if let SandboxViolation::CpuFuelExhausted { ref mut limit, .. } = violation {
@@ -634,39 +665,6 @@ impl SliceIsolate {
result
}
- #[inline]
- fn apply_process_argv_to_realm(&self, realm: &mut WarmBoaRealm) {
- if self.process_argv.is_empty() {
- return;
- }
- let argv_arr = boa_engine::object::builtins::JsArray::from_iter(
- self.process_argv
- .iter()
- .map(|s| boa_engine::JsValue::from(boa_engine::js_string!(s.as_str()))),
- &mut realm.ctx,
- );
- let _ = realm.ctx.global_object().set(
- boa_engine::js_string!("__slice_argv"),
- boa_engine::JsValue::from(argv_arr.clone()),
- false,
- &mut realm.ctx,
- );
- if let Some(proc_obj) = realm
- .ctx
- .global_object()
- .get(boa_engine::js_string!("process"), &mut realm.ctx)
- .ok()
- .and_then(|v| v.as_object())
- {
- let _ = proc_obj.set(
- boa_engine::js_string!("argv"),
- boa_engine::JsValue::from(argv_arr),
- false,
- &mut realm.ctx,
- );
- }
- }
-
/// Executes full ES2024+ JavaScript inside the production **Boa (`boa_engine`)** ECMAScript VM,
/// reusing pre-warmed contexts from `BOA_CONTEXT_POOL`, capturing `console.log` / `print` output
/// via zero-eval native host hooks, and enforcing SES compartment limits.
@@ -682,24 +680,17 @@ impl SliceIsolate {
}
let mut realm = acquire_warm_boa_realm();
- self.apply_process_argv_to_realm(&mut realm);
if flags.has_env_keys {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_sync_process_env(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SYNC_ENV, true);
}
if self.deterministic_seed.is_some() {
crate::host_bindings::register_deterministic_host_functions(&mut realm.ctx);
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_det_mode(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_DET_MODE, true);
}
let has_next_tick = js_code.contains("nextTick");
if has_next_tick {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_next_tick_hook(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_NEXT_TICK, true);
}
if flags.is_worker {
ensure_realm_shards(&mut realm, (1 << 8) | (1 << 13) | (1 << 2), false);
@@ -789,9 +780,7 @@ impl SliceIsolate {
needs_lazy_global_getters(js_code),
);
self.apply_boa_realm_runtime_limits(&mut realm);
- realm
- .ctx
- .eval(boa_engine::Source::from_bytes(js_code.as_bytes()))
+ eval_or_reuse_cached_script(&mut realm, js_code)
} else {
ensure_realm_shards(
&mut realm,
@@ -804,9 +793,7 @@ impl SliceIsolate {
} else {
format!("{{{}\n}}", js_code)
};
- realm
- .ctx
- .eval(boa_engine::Source::from_bytes(scoped_code.as_bytes()))
+ eval_or_reuse_cached_script(&mut realm, &scoped_code)
};
let need_ses_scan = should_check_ses || BOA_WAIT_UNTIL_COUNT.with(|c| c.get()) > 0;
@@ -849,7 +836,6 @@ impl SliceIsolate {
Some(r) => (r, false),
None => (create_bare_boa_realm(), true),
};
- self.apply_process_argv_to_realm(&mut realm);
let has_next_tick = (header.feature_flags & BOACAS_FLAG_HAS_NEXT_TICK) != 0;
if is_cold_bare_realm && header.approach_kind >= 1 && !precompiled_slice.is_empty() {
@@ -880,26 +866,18 @@ impl SliceIsolate {
}
} else {
if is_cold_bare_realm {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- crate::js_preludes::ULTRA_CORE_PRELUDE,
- ));
+ let _ = crate::js_preludes::eval_ultra_core_prelude(&mut realm.ctx);
crate::boa_realm::populate_realm_cached_handles(&mut realm);
}
if flags.has_env_keys {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_sync_process_env(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SYNC_ENV, true);
}
if self.deterministic_seed.is_some() {
crate::host_bindings::register_deterministic_host_functions(&mut realm.ctx);
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_det_mode(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_DET_MODE, true);
}
if has_next_tick {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_next_tick_hook(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_NEXT_TICK, true);
}
if flags.is_worker {
ensure_realm_shards(&mut realm, (1 << 8) | (1 << 13) | (1 << 2), false);
diff --git a/crates/slice-engine/src/isolate/exec_bytecode.rs b/crates/slice-engine/src/isolate/exec_bytecode.rs
index 3156eca..bd155b7 100644
--- a/crates/slice-engine/src/isolate/exec_bytecode.rs
+++ b/crates/slice-engine/src/isolate/exec_bytecode.rs
@@ -11,12 +11,15 @@ use slice_sandbox::SandboxViolation;
use std::time::Instant;
impl SliceIsolate {
- /// Executes pre-compiled `SLICEBC\x01`, `SLICEBOA`, or `SLICESNP` bytecode directly from an in-memory or `mmap` CAS slice.
- pub fn execute_bytecode(
+ /// Internal zero-clone execution core shared by `execute_bytecode` and `execute_http_request_fast`.
+ /// When `need_return_str` is `false` and `egress_audit_secrets` is empty, skips formatting `last_val`
+ /// into a heap `String` (saving `"undefined".to_string()` on every `Slice.respond` HTTP request).
+ pub(crate) fn execute_bytecode_core(
&mut self,
bytecode: &[u8],
cas: Option<&MappedCasArchive>,
- ) -> Result {
+ need_return_str: bool,
+ ) -> Result<(u64, u64, String), SandboxViolation> {
let start = Instant::now();
self.compartment.pkey_domain.enter_domain();
@@ -55,8 +58,18 @@ impl SliceIsolate {
let js_code = std::str::from_utf8(&bytecode[8..]).unwrap_or_default();
self.exec_boa_full_es_vm(js_code)?
};
- let ret_str = last_val.to_string();
- if !self.egress_audit_secrets.is_empty() {
+ let has_secrets = !self.egress_audit_secrets.is_empty();
+ let has_custom_http_res =
+ !need_return_str && BOA_HTTP_RES.with(|res| res.borrow().is_some());
+ let ret_str = if need_return_str
+ || has_secrets
+ || (!has_custom_http_res && self.stdout.is_empty())
+ {
+ last_val.to_string()
+ } else {
+ String::new()
+ };
+ if has_secrets {
for line in &self.stdout {
self.verify_egress_not_leaked(line)?;
}
@@ -75,25 +88,7 @@ impl SliceIsolate {
})?;
}
let total_ns = start.elapsed().as_nanos() as u64;
- let exec_ns = total_ns.saturating_sub(instantiate_ns).max(1);
- return Ok(ExecutionMetrics {
- tenant_id: self.compartment.tenant_id.clone(),
- highest_tier_reached: self.current_tier,
- instantiate_time_ns: instantiate_ns,
- execution_time_ns: exec_ns,
- total_time_ns: total_ns,
- fuel_consumed: self.compartment.fuel_consumed,
- memory_used_bytes: self.compartment.memory_used_bytes,
- pkey_domain: self.compartment.pkey_domain.pkey,
- cas_modules_resolved: self.cas_modules_resolved,
- os_stat_syscalls: 0,
- stdout: self.stdout.clone(),
- return_value: ret_str,
- checkpoints_taken: self.checkpoints_taken,
- restores_performed: self.restores_performed,
- restore_time_ns: self.restore_time_ns,
- exit_code: self.last_exit_code,
- });
+ return Ok((instantiate_ns, total_ns, ret_str));
}
let module = decode_slicesnp_cached(bytecode);
@@ -287,13 +282,17 @@ impl SliceIsolate {
}
let total_ns = start.elapsed().as_nanos() as u64;
- let exec_ns = total_ns.saturating_sub(instantiate_ns).max(1);
if self.capture_return_json && self.last_return_json.is_none() {
self.last_return_json =
crate::value_and_ast::js_value_to_optional_json_string(&last_val);
}
- let ret_str = last_val.to_string();
- if !self.egress_audit_secrets.is_empty() {
+ let has_secrets = !self.egress_audit_secrets.is_empty();
+ let ret_str = if need_return_str || has_secrets || self.stdout.is_empty() {
+ last_val.to_string()
+ } else {
+ String::new()
+ };
+ if has_secrets {
for line in &self.stdout {
self.verify_egress_not_leaked(line)?;
}
@@ -303,6 +302,18 @@ impl SliceIsolate {
}
}
+ Ok((instantiate_ns, total_ns, ret_str))
+ }
+
+ /// Executes pre-compiled `SLICEBC\x01`, `SLICEBOA`, or `SLICESNP` bytecode directly from an in-memory or `mmap` CAS slice.
+ pub fn execute_bytecode(
+ &mut self,
+ bytecode: &[u8],
+ cas: Option<&MappedCasArchive>,
+ ) -> Result {
+ let (instantiate_ns, total_ns, ret_str) =
+ self.execute_bytecode_core(bytecode, cas, true)?;
+ let exec_ns = total_ns.saturating_sub(instantiate_ns).max(1);
Ok(ExecutionMetrics {
tenant_id: self.compartment.tenant_id.clone(),
highest_tier_reached: self.current_tier,
diff --git a/crates/slice-engine/src/isolate/http_and_ws.rs b/crates/slice-engine/src/isolate/http_and_ws.rs
index a9e62db..827fc3e 100644
--- a/crates/slice-engine/src/isolate/http_and_ws.rs
+++ b/crates/slice-engine/src/isolate/http_and_ws.rs
@@ -2,11 +2,13 @@
//! Task Draining (`drain_wait_until_tasks`), and Server WebSocket Frame Dispatch (`execute_websocket_event`).
use crate::boa_realm::{
- acquire_warm_boa_realm, ensure_realm_shards, BOA_HTTP_REQ, BOA_HTTP_RES, BOA_WAIT_UNTIL_COUNT,
+ acquire_warm_boa_realm, call_realm_ctl, ensure_realm_shards, BOA_HTTP_REQ, BOA_HTTP_RES,
+ BOA_WAIT_UNTIL_COUNT, REALM_CTL_SET_DET_MODE, REALM_CTL_SYNC_ENV,
};
use crate::isolate::{ExecutionMetrics, SliceIsolate};
use slice_cas::MappedCasArchive;
use slice_sandbox::SandboxViolation;
+use std::borrow::Cow;
/// Zero-copy HTTP/1.1 request view borrowed directly from the worker thread's 64 KB socket read buffer.
#[derive(Debug, Clone, Copy)]
@@ -24,12 +26,55 @@ pub struct HttpRequestContext<'a> {
pub struct HttpExecutionOutcome {
pub metrics: ExecutionMetrics,
pub status_code: u16,
- pub content_type: String,
+ pub content_type: Cow<'static, str>,
pub response_body: String,
pub response_headers: Vec<(String, String)>,
pub wait_until_count: usize,
}
+/// Zero-clone HTTP outcome used on the hot `slice serve` worker path (`execute_http_request_fast`).
+#[derive(Debug, Clone)]
+pub struct HttpFastOutcome {
+ pub total_time_ns: u64,
+ pub fuel_consumed: u64,
+ pub status_code: u16,
+ pub content_type: Cow<'static, str>,
+ pub response_body: String,
+ pub response_headers: Vec<(String, String)>,
+ pub wait_until_count: usize,
+}
+
+#[inline]
+fn populate_boa_http_req(req: &HttpRequestContext<'_>) {
+ BOA_HTTP_REQ.with(|r| {
+ let mut borrow = r.borrow_mut();
+ borrow.active = true;
+ borrow.method.clear();
+ borrow.method.push_str(req.method);
+ borrow.path.clear();
+ borrow.path.push_str(req.path);
+ borrow.query.clear();
+ borrow.query.push_str(req.query);
+ borrow.tenant_id.clear();
+ borrow.tenant_id.push_str(req.tenant_id);
+ borrow.body.clear();
+ borrow.body.push_str(req.body);
+ borrow.headers_len = req.headers.len();
+ for (idx, &(k, v)) in req.headers.iter().enumerate() {
+ if idx < borrow.headers.len() {
+ borrow.headers[idx].0.clear();
+ borrow.headers[idx].0.push_str(k);
+ borrow.headers[idx].1.clear();
+ borrow.headers[idx].1.push_str(v);
+ } else {
+ borrow.headers.push((k.to_string(), v.to_string()));
+ }
+ }
+ });
+ BOA_HTTP_RES.with(|res| *res.borrow_mut() = None);
+ BOA_WAIT_UNTIL_COUNT.with(|c| c.set(0));
+}
+
impl SliceIsolate {
/// Executes an HTTP request inside this `SliceIsolate` with zero-copy request metadata
/// (`HttpRequestContext`), custom status/content-type response capture (`Slice.respond`),
@@ -43,52 +88,24 @@ impl SliceIsolate {
if bytecode.len() >= 8
&& (&bytecode[0..8] == b"SLICEBOA" || &bytecode[0..8] == crate::boacas::BOACAS_MAGIC)
{
- BOA_HTTP_REQ.with(|r| {
- let mut borrow = r.borrow_mut();
- borrow.active = true;
- borrow.method.clear();
- borrow.method.push_str(req.method);
- borrow.path.clear();
- borrow.path.push_str(req.path);
- borrow.query.clear();
- borrow.query.push_str(req.query);
- borrow.tenant_id.clear();
- borrow.tenant_id.push_str(req.tenant_id);
- borrow.body.clear();
- borrow.body.push_str(req.body);
- borrow.headers_len = req.headers.len();
- for (idx, &(k, v)) in req.headers.iter().enumerate() {
- if idx < borrow.headers.len() {
- borrow.headers[idx].0.clear();
- borrow.headers[idx].0.push_str(k);
- borrow.headers[idx].1.clear();
- borrow.headers[idx].1.push_str(v);
- } else {
- borrow.headers.push((k.to_string(), v.to_string()));
- }
- }
- });
- BOA_HTTP_RES.with(|res| *res.borrow_mut() = None);
- BOA_WAIT_UNTIL_COUNT.with(|c| c.set(0));
-
+ populate_boa_http_req(req);
let metrics_res = self.execute_bytecode(bytecode, cas);
-
BOA_HTTP_REQ.with(|r| r.borrow_mut().active = false);
- let metrics = metrics_res?;
+ let mut metrics = metrics_res?;
let custom_res = BOA_HTTP_RES.with(|res| res.borrow_mut().take());
let wait_until_count = BOA_WAIT_UNTIL_COUNT.with(|c| c.get());
let (status_code, content_type, response_body, response_headers) =
if let Some((st, body, ct, hdrs)) = custom_res {
- (st, ct, body, hdrs)
+ (st, Cow::Owned(ct), body, hdrs)
} else {
let body = if !metrics.stdout.is_empty() {
metrics.stdout.join("\n")
} else {
- metrics.return_value.clone()
+ std::mem::take(&mut metrics.return_value)
};
- (200, "application/json".to_string(), body, Vec::new())
+ (200, Cow::Borrowed("application/json"), body, Vec::new())
};
return Ok(HttpExecutionOutcome {
@@ -101,16 +118,76 @@ impl SliceIsolate {
});
}
- let metrics = self.execute_bytecode(bytecode, cas)?;
+ let mut metrics = self.execute_bytecode(bytecode, cas)?;
let body = if !metrics.stdout.is_empty() {
metrics.stdout.join("\n")
} else {
- metrics.return_value.clone()
+ std::mem::take(&mut metrics.return_value)
};
Ok(HttpExecutionOutcome {
metrics,
status_code: 200,
- content_type: "application/json".to_string(),
+ content_type: Cow::Borrowed("application/json"),
+ response_body: body,
+ response_headers: Vec::new(),
+ wait_until_count: 0,
+ })
+ }
+
+ /// Zero-clone HTTP request dispatcher for `slice serve` worker loops.
+ /// Avoids cloning `tenant_id`, `stdout`, `"application/json"`, and `"undefined"` on every request.
+ pub fn execute_http_request_fast(
+ &mut self,
+ bytecode: &[u8],
+ cas: Option<&MappedCasArchive>,
+ req: &HttpRequestContext<'_>,
+ ) -> Result {
+ if bytecode.len() >= 8
+ && (&bytecode[0..8] == b"SLICEBOA" || &bytecode[0..8] == crate::boacas::BOACAS_MAGIC)
+ {
+ populate_boa_http_req(req);
+ let core_res = self.execute_bytecode_core(bytecode, cas, false);
+ BOA_HTTP_REQ.with(|r| r.borrow_mut().active = false);
+ let (_instantiate_ns, total_time_ns, ret_str) = core_res?;
+
+ let custom_res = BOA_HTTP_RES.with(|res| res.borrow_mut().take());
+ let wait_until_count = BOA_WAIT_UNTIL_COUNT.with(|c| c.get());
+
+ let (status_code, content_type, response_body, response_headers) =
+ if let Some((st, body, ct, hdrs)) = custom_res {
+ (st, Cow::Owned(ct), body, hdrs)
+ } else {
+ let body = if !self.stdout.is_empty() {
+ self.stdout.join("\n")
+ } else {
+ ret_str
+ };
+ (200, Cow::Borrowed("application/json"), body, Vec::new())
+ };
+
+ return Ok(HttpFastOutcome {
+ total_time_ns,
+ fuel_consumed: self.compartment.fuel_consumed,
+ status_code,
+ content_type,
+ response_body,
+ response_headers,
+ wait_until_count,
+ });
+ }
+
+ let (_instantiate_ns, total_time_ns, ret_str) =
+ self.execute_bytecode_core(bytecode, cas, false)?;
+ let body = if !self.stdout.is_empty() {
+ self.stdout.join("\n")
+ } else {
+ ret_str
+ };
+ Ok(HttpFastOutcome {
+ total_time_ns,
+ fuel_consumed: self.compartment.fuel_consumed,
+ status_code: 200,
+ content_type: Cow::Borrowed("application/json"),
response_body: body,
response_headers: Vec::new(),
wait_until_count: 0,
@@ -131,15 +208,11 @@ impl SliceIsolate {
let mut realm = acquire_warm_boa_realm();
if flags.has_env_keys {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_sync_process_env(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SYNC_ENV, true);
}
if self.deterministic_seed.is_some() {
crate::host_bindings::register_deterministic_host_functions(&mut realm.ctx);
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_det_mode(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_DET_MODE, true);
}
self.apply_boa_realm_runtime_limits(&mut realm);
@@ -187,31 +260,40 @@ impl SliceIsolate {
ensure_realm_shards(&mut realm, (1 << 13) | (1 << 7), false);
if flags.has_env_keys {
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_sync_process_env(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SYNC_ENV, true);
}
if self.deterministic_seed.is_some() {
crate::host_bindings::register_deterministic_host_functions(&mut realm.ctx);
- let _ = realm.ctx.eval(boa_engine::Source::from_bytes(
- b"__slice_set_det_mode(true);",
- ));
+ call_realm_ctl(&mut realm, REALM_CTL_SET_DET_MODE, true);
}
self.apply_boa_realm_runtime_limits(&mut realm);
let prev_stdout_len = self.stdout.len();
- let js_call = format!(
- "globalThis.__slice_dispatch_server_ws({}, {}, {}, {}, {});",
- serde_json::to_string(event_type).unwrap_or_else(|_| "\"message\"".to_string()),
- if is_binary { "true" } else { "false" },
- serde_json::to_string(&payload_arg).unwrap_or_else(|_| "\"\"".to_string()),
- code,
- serde_json::to_string(reason).unwrap_or_else(|_| "\"\"".to_string()),
- );
- let eval_res = realm
+ let dispatch_fn = realm
.ctx
- .eval(boa_engine::Source::from_bytes(js_call.as_bytes()));
+ .global_object()
+ .get(
+ boa_engine::js_string!("__slice_dispatch_server_ws"),
+ &mut realm.ctx,
+ )
+ .ok()
+ .and_then(|v| v.as_object());
+ let eval_res = if let Some(fn_obj) = dispatch_fn {
+ fn_obj.call(
+ &boa_engine::JsValue::undefined(),
+ &[
+ boa_engine::JsValue::from(boa_engine::js_string!(event_type)),
+ boa_engine::JsValue::from(is_binary),
+ boa_engine::JsValue::from(boa_engine::js_string!(payload_arg)),
+ boa_engine::JsValue::from(i32::from(code)),
+ boa_engine::JsValue::from(boa_engine::js_string!(reason)),
+ ],
+ &mut realm.ctx,
+ )
+ } else {
+ Ok(boa_engine::JsValue::undefined())
+ };
// Drive microtasks/timers before draining the server WebSocket outbox (since
// `finish_boa_compartment_execution` clears thread-local WebSocket state on teardown).
diff --git a/crates/slice-engine/src/isolate/mod.rs b/crates/slice-engine/src/isolate/mod.rs
index 0e76092..bf77abf 100644
--- a/crates/slice-engine/src/isolate/mod.rs
+++ b/crates/slice-engine/src/isolate/mod.rs
@@ -17,7 +17,7 @@ pub(crate) mod http_and_ws;
pub(crate) mod kv_and_sandbox;
pub mod state_and_kv;
-pub use self::http_and_ws::{HttpExecutionOutcome, HttpRequestContext};
+pub use self::http_and_ws::{HttpExecutionOutcome, HttpFastOutcome, HttpRequestContext};
pub use self::kv_and_sandbox::{SandboxEvalOptions, SandboxEvalOutcome};
use crate::parser_and_compiler::compile_source_to_bytecode;
diff --git a/crates/slice-engine/src/lib.rs b/crates/slice-engine/src/lib.rs
index 6e2f0d6..17d6730 100644
--- a/crates/slice-engine/src/lib.rs
+++ b/crates/slice-engine/src/lib.rs
@@ -17,7 +17,7 @@
//! and sandboxed `wasmi` [`wasm`] engine.
//! - [`net`]: Outbound `fetch()` HTTP/1.1 & HTTPS engine ([`outbound_http`]), OCap TCP/TLS/UDP [`sockets`],
//! and RFC 6455 [`websocket`] codec.
-//! - [`preludes`]: Sharded JavaScript micro-preludes (`00_ultra_core.js` .. `18_intl.js`), Aho-Corasick shard
+//! - [`preludes`]: Sharded JavaScript micro-preludes (`00_ultra_core.js` .. `19_process_cli.js`), Aho-Corasick shard
//! detector ([`js_preludes`]), compile-time minifier ([`js_minifier`]), and lazy `node:*` built-ins ([`node_builtins`]).
pub mod bindings;
@@ -56,8 +56,8 @@ pub use event_loop::{
reset_virtual_time_warped_ms, virtual_time_warped_ms, MAX_FETCH_REACTOR_WORKERS,
};
pub use isolate::{
- run_source_isolated, ExecutionMetrics, HttpExecutionOutcome, HttpRequestContext,
- SandboxEvalOptions, SandboxEvalOutcome, SliceIsolate,
+ run_source_isolated, ExecutionMetrics, HttpExecutionOutcome, HttpFastOutcome,
+ HttpRequestContext, SandboxEvalOptions, SandboxEvalOutcome, SliceIsolate,
};
pub use outbound_http::{
clear_outbound_conn_pool, clear_outbound_conn_pool_for_tenant,
diff --git a/crates/slice-engine/src/preludes/00_ultra_core.js b/crates/slice-engine/src/preludes/00_ultra_core.js
index 5079d4d..9ad9e24 100644
--- a/crates/slice-engine/src/preludes/00_ultra_core.js
+++ b/crates/slice-engine/src/preludes/00_ultra_core.js
@@ -31,7 +31,8 @@
(id === 15 && globalThis.FormData) ||
(id === 16 && globalThis.structuredClone) ||
(id === 17 && globalThis.Buffer && globalThis.Buffer.prototype._hasBinRW) ||
- (id === 18 && globalThis.Intl)
+ (id === 18 && globalThis.Intl) ||
+ (id === 29 && globalThis.navigator)
) {
globalThis.__shMask |= (1 << id);
return;
@@ -100,29 +101,16 @@
};
var __pExitCode = undefined;
+ var __argvCache = null;
function __pLazy(m) {
return function() {
- __slice_mark_proc_dirty();
- __loadShard(18);
+ __slice_process_ctl(0);
+ __loadShard(29);
return globalThis.process[m].apply(globalThis.process, arguments);
};
}
- globalThis.process = {
- pid: 1,
- env: { NODE_ENV: "production" },
- cwd: function() { return "."; },
- get platform() { return __slice_os_platform(); },
- get arch() { return __slice_os_arch(); },
- get exitCode() { return __pExitCode; },
- set exitCode(v) {
- __pExitCode = v;
- if (v !== undefined) __slice_mark_proc_dirty();
- },
- _resetExitCode: function() { __pExitCode = undefined; },
- version: "v24.0.0",
- versions: { node: "24.0.0" },
- argv: globalThis.__slice_argv || ["slice"],
+ var __ProcProto = {
on: __pLazy("on"),
once: __pLazy("once"),
off: __pLazy("off"),
@@ -131,15 +119,54 @@
removeAllListeners: __pLazy("removeAllListeners"),
listeners: __pLazy("listeners"),
listenerCount: __pLazy("listenerCount"),
- emitWarning: __pLazy("emitWarning"),
- exit: function(code) {
- __ntQ.length = 0;
- __qmQ.length = 0;
- __mtS = false;
- __slice_process_exit(code);
- }
+ emitWarning: __pLazy("emitWarning")
};
+ var __proc = Object.create(__ProcProto);
+ __proc.pid = 1;
+ __proc.env = { NODE_ENV: "production" };
+ __proc.cwd = function() { return "."; };
+ __proc._exited = false;
+ __proc._resetExitCode = function() {
+ __pExitCode = undefined;
+ __argvCache = null;
+ __proc._exited = false;
+ };
+ __proc.version = "v24.0.0";
+ __proc.versions = { node: "24.0.0" };
+ __proc.exit = function(code) {
+ __ntQ.length = 0;
+ __qmQ.length = 0;
+ __mtS = false;
+ __slice_process_ctl(2, code);
+ };
+ Object.defineProperties(__proc, {
+ platform: { get: __slice_os_platform, enumerable: true, configurable: true },
+ arch: { get: __slice_os_arch, enumerable: true, configurable: true },
+ exitCode: {
+ get: function() { return __pExitCode; },
+ set: function(v) {
+ __pExitCode = v;
+ if (v !== undefined) __slice_process_ctl(0);
+ },
+ enumerable: true,
+ configurable: true
+ },
+ argv: {
+ get: function() {
+ if (!__argvCache) __argvCache = __slice_process_ctl(1);
+ return __argvCache;
+ },
+ set: function(v) {
+ __slice_process_ctl(0);
+ __argvCache = v;
+ },
+ enumerable: true,
+ configurable: true
+ }
+ });
+ globalThis.process = __proc;
+
globalThis.__slice_check_ses = function() {
var p = [Object.prototype, Array.prototype, Function.prototype, String.prototype];
var n = ["Object.prototype", "Array.prototype", "Function.prototype", "String.prototype"];
@@ -209,7 +236,8 @@
if (__ntQ.length > 0) {
while (__ntQ.length > 0) {
var n = __ntQ.shift();
- n.f.apply(undefined, n.a);
+ if (n.a) n.f.apply(undefined, n.a);
+ else n.f();
}
}
return onF(v);
@@ -218,7 +246,8 @@
if (__ntQ.length > 0) {
while (__ntQ.length > 0) {
var n = __ntQ.shift();
- n.f.apply(undefined, n.a);
+ if (n.a) n.f.apply(undefined, n.a);
+ else n.f();
}
}
return onR(e);
@@ -242,6 +271,27 @@
__mtS = false;
};
+ globalThis.__slice_ctl = function(op, flag) {
+ if (op === 0) {
+ __ntQ.length = 0;
+ __qmQ.length = 0;
+ __mtS = false;
+ } else if (op === 1) {
+ globalThis.__slice_set_det_mode(flag);
+ } else if (op === 2) {
+ globalThis.__slice_sync_process_env(flag);
+ } else if (op === 3) {
+ globalThis.__slice_set_next_tick_hook(flag);
+ } else if (op === 4) {
+ if (globalThis.__slice_wu) globalThis.__slice_wu.length = 0;
+ } else if (op === 5) {
+ var s = globalThis.__slice_active_http_server;
+ if (s && typeof s._dispatchActiveHttpBridge === "function") {
+ s._dispatchActiveHttpBridge();
+ }
+ }
+ };
+
globalThis.__slice_set_als_wrap = function(wrapFn) {
__alsWrap = wrapFn || null;
};
@@ -256,7 +306,8 @@
while (__ntQ.length > 0 || __qmQ.length > 0) {
while (__ntQ.length > 0) {
var n = __ntQ.shift();
- n.f.apply(undefined, n.a);
+ if (n.a) n.f.apply(undefined, n.a);
+ else n.f();
}
if (__qmQ.length > 0) {
var q = __qmQ.shift();
@@ -275,8 +326,11 @@
__ntHooked = true;
Promise.prototype.then = __wrappedThen;
}
- var a = [];
- for (var i = 1; i < arguments.length; i++) a.push(arguments[i]);
+ var a = undefined;
+ if (arguments.length > 1) {
+ a = [];
+ for (var i = 1; i < arguments.length; i++) a.push(arguments[i]);
+ }
__ntQ.push({ f: __alsWrap ? __alsWrap(cb) : cb, a: a });
__schedMt();
};
@@ -295,19 +349,19 @@
}
__Timeout.prototype.unref = function() {
this._refed = false;
- __slice_timer_ref(this._id, false);
+ __slice_timer_ctl(this._id, 2);
return this;
};
__Timeout.prototype.ref = function() {
this._refed = true;
- __slice_timer_ref(this._id, true);
+ __slice_timer_ctl(this._id, 1);
return this;
};
__Timeout.prototype.hasRef = function() {
return this._refed;
};
__Timeout.prototype.refresh = function() {
- __slice_timer_refresh(this._id);
+ __slice_timer_ctl(this._id, 3);
return this;
};
__Timeout.prototype[Symbol.toPrimitive] = function() {
@@ -318,17 +372,23 @@
};
globalThis.setTimeout = function(cb, ms) {
- var a = [];
- for (var i = 2; i < arguments.length; i++) a.push(arguments[i]);
+ var a = undefined;
+ if (arguments.length > 2) {
+ a = [];
+ for (var i = 2; i < arguments.length; i++) a.push(arguments[i]);
+ }
return new __Timeout(__slice_timer_set(cb, Number(ms) || 0, false, a));
};
globalThis.clearTimeout = function(id) {
if (id == null) return;
- __slice_timer_clear(typeof id === "object" ? (id._id | 0) : (Number(id) || 0));
+ __slice_timer_ctl(typeof id === "object" ? (id._id | 0) : (Number(id) || 0), 0);
};
globalThis.setInterval = function(cb, ms) {
- var a = [];
- for (var i = 2; i < arguments.length; i++) a.push(arguments[i]);
+ var a = undefined;
+ if (arguments.length > 2) {
+ a = [];
+ for (var i = 2; i < arguments.length; i++) a.push(arguments[i]);
+ }
return new __Timeout(__slice_timer_set(cb, Number(ms) || 0, true, a));
};
globalThis.clearInterval = globalThis.clearTimeout;
@@ -336,8 +396,11 @@
if (typeof cb !== "function") {
throw new TypeError("setImmediate requires a callback function");
}
- var a = [];
- for (var i = 1; i < arguments.length; i++) a.push(arguments[i]);
+ var a = undefined;
+ if (arguments.length > 1) {
+ a = [];
+ for (var i = 1; i < arguments.length; i++) a.push(arguments[i]);
+ }
return new __Timeout(__slice_immediate_set(cb, a));
};
globalThis.clearImmediate = globalThis.clearTimeout;
diff --git a/crates/slice-engine/src/preludes/03_streams_formdata.js b/crates/slice-engine/src/preludes/03_streams_formdata.js
index 3287836..ef958ac 100644
--- a/crates/slice-engine/src/preludes/03_streams_formdata.js
+++ b/crates/slice-engine/src/preludes/03_streams_formdata.js
@@ -5,8 +5,8 @@
function ReadableStream(underlyingSource) {
var self = this;
this._chunks = [];
- this._waiters = [];
- this._closeWaiters = [];
+ this._waiters = null;
+ this._closeWaiters = null;
this._closed = false;
this._errored = null;
this.locked = false;
@@ -19,28 +19,36 @@
throw new RangeError("ReadableStream buffer limit exceeded (" + MAX_STREAM_CHUNKS + " chunks)");
}
self._chunks.push(chunk);
- if (self._waiters.length > 0) {
+ if (self._waiters && self._waiters.length > 0) {
var w = self._waiters.shift();
w.res({ value: self._chunks[w.idx()], done: false });
}
},
close: function() {
self._closed = true;
- while (self._waiters.length > 0) {
- self._waiters.shift().res({ value: undefined, done: true });
+ if (self._waiters) {
+ while (self._waiters.length > 0) {
+ self._waiters.shift().res({ value: undefined, done: true });
+ }
}
- while (self._closeWaiters.length > 0) {
- self._closeWaiters.shift().res(undefined);
+ if (self._closeWaiters) {
+ while (self._closeWaiters.length > 0) {
+ self._closeWaiters.shift().res(undefined);
+ }
}
},
error: function(e) {
self._errored = e || new Error("ReadableStream error");
self._closed = true;
- while (self._waiters.length > 0) {
- self._waiters.shift().rej(self._errored);
+ if (self._waiters) {
+ while (self._waiters.length > 0) {
+ self._waiters.shift().rej(self._errored);
+ }
}
- while (self._closeWaiters.length > 0) {
- self._closeWaiters.shift().rej(self._errored);
+ if (self._closeWaiters) {
+ while (self._closeWaiters.length > 0) {
+ self._closeWaiters.shift().rej(self._errored);
+ }
}
}
};
@@ -135,7 +143,7 @@
}
if (!self._closed) {
return new Promise(function(res, rej) {
- self._waiters.push({
+ (self._waiters || (self._waiters = [])).push({
idx: function() { return idx++; },
res: res,
rej: rej
diff --git a/crates/slice-engine/src/preludes/05_full_buffer.js b/crates/slice-engine/src/preludes/05_full_buffer.js
index 9923d3f..ced0c15 100644
--- a/crates/slice-engine/src/preludes/05_full_buffer.js
+++ b/crates/slice-engine/src/preludes/05_full_buffer.js
@@ -94,20 +94,7 @@
return Buffer.alloc(size);
};
- Buffer.byteLength = function(str, encoding) {
- if (typeof str !== "string") {
- if (str && typeof str.byteLength === "number") return str.byteLength;
- str = String(str);
- }
- if (!encoding) return __slice_utf8_byte_len(str);
- var e = String(encoding).toLowerCase();
- if (e === "utf8" || e === "utf-8") return __slice_utf8_byte_len(str);
- if (e === "utf16le" || e === "utf-16le" || e === "ucs2" || e === "ucs-2") return str.length * 2;
- if (e === "latin1" || e === "binary" || e === "ascii") return str.length;
- if (e === "hex") return str.length >>> 1;
- if (e === "base64" || e === "base64url") return __slice_base64_decode_bytes(str).byteLength;
- return __slice_utf8_byte_len(str);
- };
+ Buffer.byteLength = __slice_utf8_byte_len;
Buffer.concat = function(list, totalLength) {
if (!Array.isArray(list)) throw new TypeError("The \"list\" argument must be an instance of Array");
diff --git a/crates/slice-engine/src/preludes/11_fetch_headers_req_res.js b/crates/slice-engine/src/preludes/11_fetch_headers_req_res.js
index 992d915..1b0781a 100644
--- a/crates/slice-engine/src/preludes/11_fetch_headers_req_res.js
+++ b/crates/slice-engine/src/preludes/11_fetch_headers_req_res.js
@@ -396,10 +396,10 @@
this.bodyUsed = true;
if (this._stream) {
var st = this._stream, self = this;
- st._drainSync();
+ if (!st._closed) st._drainSync();
if (st._startPromise || !st._closed) {
var waitP = st._startPromise ? st._startPromise : new Promise(function(res, rej) {
- st._closeWaiters.push({ res: res, rej: rej });
+ (st._closeWaiters || (st._closeWaiters = [])).push({ res: res, rej: rej });
});
return waitP.then(function() {
self._body = st._toText();
diff --git a/crates/slice-engine/src/preludes/13_dom_events.js b/crates/slice-engine/src/preludes/13_dom_events.js
index 08a73f6..1cc8d31 100644
--- a/crates/slice-engine/src/preludes/13_dom_events.js
+++ b/crates/slice-engine/src/preludes/13_dom_events.js
@@ -39,7 +39,7 @@
CustomEvent.prototype.constructor = CustomEvent;
function EventTarget() {
- this._et = Object.create(null);
+ this._et = null;
}
EventTarget.prototype._ensureEt = function() {
if (!this._et) this._et = Object.create(null);
@@ -158,17 +158,23 @@
this.message = message === undefined ? "" : String(message);
this.name = name === undefined ? "Error" : String(name);
this.code = __domCodes[this.name] || 0;
- var err = new Error(this.message);
- err.name = this.name;
- if (err.stack) {
- Object.defineProperty(this, "stack", { value: err.stack, writable: true, configurable: true });
- }
}
DOMException.prototype = Object.create(Error.prototype);
DOMException.prototype.constructor = DOMException;
- for (var __dk in __domConsts) {
- DOMException[__dk] = DOMException.prototype[__dk] = __domConsts[__dk];
- }
+ Object.defineProperty(DOMException.prototype, "stack", {
+ get: function() {
+ var nm = this && this.name ? String(this.name) : "Error";
+ var msg = this && this.message ? String(this.message) : "";
+ return msg ? (nm + ": " + msg) : nm;
+ },
+ set: function(v) {
+ Object.defineProperty(this, "stack", { value: v, writable: true, configurable: true });
+ },
+ configurable: true,
+ enumerable: false
+ });
+ Object.assign(DOMException, __domConsts);
+ Object.assign(DOMException.prototype, __domConsts);
globalThis.DOMException = DOMException;
globalThis.Event = Event;
diff --git a/crates/slice-engine/src/preludes/18_intl.js b/crates/slice-engine/src/preludes/18_intl.js
index 90e0ac3..a497735 100644
--- a/crates/slice-engine/src/preludes/18_intl.js
+++ b/crates/slice-engine/src/preludes/18_intl.js
@@ -1,224 +1,5 @@
-// Slice (Nexus-JS) Prelude Shard 18: WinterTC `navigator`, `location`, `Intl`, and Complete `process` CLI Surface
+// Slice (Nexus-JS) Prelude Shard 18: WinterTC `Intl` (`18_intl.js`)
(function() {
- var p = globalThis.process;
- if (p && !p.stdout) {
- p.ppid = 0;
- p.argv0 = "slice";
- p.execArgv = [];
- p.execPath = "/usr/bin/slice";
- var __t0 = Date.now();
- p.uptime = function() {
- return Math.max(0, (Date.now() - __t0) / 1000);
- };
- function __hrtime(prev) {
- var ns = BigInt(Math.round(performance.now() * 1e6));
- if (Array.isArray(prev) && prev.length === 2) {
- var pNs = BigInt(prev[0]) * 1000000000n + BigInt(prev[1]);
- ns -= pNs;
- if (ns < 0n) ns = 0n;
- }
- return [Number(ns / 1000000000n), Number(ns % 1000000000n)];
- }
- __hrtime.bigint = function() {
- return BigInt(Math.round(performance.now() * 1e6));
- };
- p.hrtime = __hrtime;
-
- function __memUsage() {
- var used = __slice_http_is_active(1) || 0;
- var rem = __slice_http_is_active(2) || 67108864;
- var total = Math.min(used + rem, 134217728);
- var heapUsed = Math.max(262144, used + 262144);
- var heapTotal = Math.max(heapUsed, Math.min(total, 16777216));
- var rss = Math.max(heapTotal, 8388608);
- return {
- rss: rss,
- heapTotal: heapTotal,
- heapUsed: heapUsed,
- external: used,
- arrayBuffers: 0
- };
- }
- __memUsage.rss = function() {
- return __memUsage().rss;
- };
- p.memoryUsage = __memUsage;
-
- function __mkWritable(fd) {
- return {
- fd: fd,
- isTTY: false,
- columns: 80,
- rows: 24,
- write: function(chunk, enc, cb) {
- var fn = typeof enc === "function" ? enc : cb;
- var s = (chunk instanceof Uint8Array)
- ? __slice_buf_to_utf8(chunk)
- : String(chunk === undefined ? "" : chunk);
- if (s.endsWith("\r\n")) s = s.slice(0, -2);
- else if (s.endsWith("\n")) s = s.slice(0, -1);
- __slice_console_log(s);
- if (typeof fn === "function") fn(null);
- return true;
- },
- end: function(chunk, enc, cb) {
- var fn = typeof chunk === "function" ? chunk : (typeof enc === "function" ? enc : cb);
- if (chunk !== undefined && chunk !== null && typeof chunk !== "function") {
- this.write(chunk, enc);
- }
- if (typeof fn === "function") fn();
- return this;
- },
- on: function() { return this; },
- once: function() { return this; },
- off: function() { return this; },
- removeListener: function() { return this; },
- emit: function() { return false; }
- };
- }
- p.stdout = __mkWritable(1);
- p.stderr = __mkWritable(2);
- p.stdin = {
- fd: 0,
- isTTY: false,
- readable: false,
- on: function(ev, cb) {
- if (ev === "end" && typeof cb === "function") queueMicrotask(cb);
- return this;
- },
- once: function(ev, cb) {
- if (ev === "end" && typeof cb === "function") queueMicrotask(cb);
- return this;
- },
- off: function() { return this; },
- removeListener: function() { return this; },
- resume: function() { return this; },
- pause: function() { return this; },
- setEncoding: function() { return this; },
- read: function() { return null; }
- };
-
- var __pEv = Object.create(null);
- var __pEvCount = 0;
- p._exited = false;
- p.on = p.addListener = function(ev, fn) {
- if (typeof fn === "function") {
- __slice_mark_proc_dirty();
- var k = String(ev);
- (__pEv[k] || (__pEv[k] = [])).push(fn);
- __pEvCount++;
- }
- return p;
- };
- p.once = function(ev, fn) {
- if (typeof fn === "function") {
- var g = function() {
- p.off(ev, g);
- fn.apply(p, arguments);
- };
- g.listener = fn;
- p.on(ev, g);
- }
- return p;
- };
- p.off = p.removeListener = function(ev, fn) {
- var k = String(ev), list = __pEv[k];
- if (list) {
- var prevLen = list.length;
- __pEv[k] = list.filter(function(f) { return f !== fn && f.listener !== fn; });
- __pEvCount = Math.max(0, __pEvCount - (prevLen - __pEv[k].length));
- }
- return p;
- };
- p.removeAllListeners = function(ev) {
- if (arguments.length === 0) {
- __pEv = Object.create(null);
- __pEvCount = 0;
- } else {
- var k = String(ev);
- if (__pEv[k]) {
- __pEvCount = Math.max(0, __pEvCount - __pEv[k].length);
- delete __pEv[k];
- }
- }
- return p;
- };
- p.listeners = function(ev) {
- return (__pEv[String(ev)] || []).slice();
- };
- p.listenerCount = function(ev) {
- var l = __pEv[String(ev)];
- return l ? l.length : 0;
- };
- p._hasListeners = function(ev) {
- if (__pEvCount === 0) return false;
- if (!ev) return true;
- var l = __pEv[String(ev)];
- return Boolean(l && l.length > 0);
- };
- p._resetProcessState = function() {
- if (__pEvCount > 0) {
- __pEv = Object.create(null);
- __pEvCount = 0;
- }
- if (p._resetExitCode) p._resetExitCode();
- else p.exitCode = undefined;
- p._exited = false;
- };
- p.emit = function(ev) {
- if (__pEvCount === 0) return false;
- var list = __pEv[String(ev)];
- if (!list || list.length === 0) return false;
- var args = [];
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
- var snap = list.slice();
- for (var j = 0; j < snap.length; j++) snap[j].apply(p, args);
- return true;
- };
- p.emitWarning = function(warning, type, code) {
- var msg = (warning && typeof warning === "object" && warning.message)
- ? warning.message
- : String(warning);
- var t = typeof type === "string"
- ? type
- : (type && typeof type === "object" && type.type ? type.type : "Warning");
- var c = typeof code === "string"
- ? code
- : (type && typeof type === "object" && type.code ? type.code : undefined);
- var w = new Error(msg);
- w.name = t;
- if (c) w.code = c;
- p.emit("warning", w);
- };
- }
-
- if (!globalThis.navigator) {
- globalThis.navigator = {
- userAgent: "Slice-NexusJS/0.10.0",
- hardwareConcurrency: 4,
- language: "en-US",
- languages: ["en-US", "en"],
- onLine: true,
- platform: "Slice",
- maxTouchPoints: 0
- };
- }
-
- if (!globalThis.location) {
- globalThis.location = {
- href: "http://localhost/",
- origin: "http://localhost",
- protocol: "http:",
- host: "localhost",
- hostname: "localhost",
- port: "",
- pathname: "/",
- search: "",
- hash: "",
- toString: function() { return this.href; }
- };
- }
-
function __normLocale(loc) {
if (!loc) return "en-US";
var first = Array.isArray(loc) ? loc[0] : loc;
diff --git a/crates/slice-engine/src/preludes/19_process_cli.js b/crates/slice-engine/src/preludes/19_process_cli.js
new file mode 100644
index 0000000..c41182f
--- /dev/null
+++ b/crates/slice-engine/src/preludes/19_process_cli.js
@@ -0,0 +1,221 @@
+// Slice (Nexus-JS) Prelude Shard 29: `navigator`, `location`, and Complete `process` CLI Surface (`19_process_cli.js`)
+(function() {
+ var p = globalThis.process;
+ if (p && !p.stdout) {
+ p.ppid = 0;
+ p.argv0 = "slice";
+ p.execArgv = [];
+ p.execPath = "/usr/bin/slice";
+ var __t0 = Date.now();
+ p.uptime = function() {
+ return Math.max(0, (Date.now() - __t0) / 1000);
+ };
+ function __hrtime(prev) {
+ var ns = BigInt(Math.round(performance.now() * 1e6));
+ if (Array.isArray(prev) && prev.length === 2) {
+ var pNs = BigInt(prev[0]) * 1000000000n + BigInt(prev[1]);
+ ns -= pNs;
+ if (ns < 0n) ns = 0n;
+ }
+ return [Number(ns / 1000000000n), Number(ns % 1000000000n)];
+ }
+ __hrtime.bigint = function() {
+ return BigInt(Math.round(performance.now() * 1e6));
+ };
+ p.hrtime = __hrtime;
+
+ function __memUsage() {
+ var used = __slice_http_is_active(1) || 0;
+ var rem = __slice_http_is_active(2) || 67108864;
+ var total = Math.min(used + rem, 134217728);
+ var heapUsed = Math.max(262144, used + 262144);
+ var heapTotal = Math.max(heapUsed, Math.min(total, 16777216));
+ var rss = Math.max(heapTotal, 8388608);
+ return {
+ rss: rss,
+ heapTotal: heapTotal,
+ heapUsed: heapUsed,
+ external: used,
+ arrayBuffers: 0
+ };
+ }
+ __memUsage.rss = function() {
+ return __memUsage().rss;
+ };
+ p.memoryUsage = __memUsage;
+
+ function __mkWritable(fd) {
+ return {
+ fd: fd,
+ isTTY: false,
+ columns: 80,
+ rows: 24,
+ write: function(chunk, enc, cb) {
+ var fn = typeof enc === "function" ? enc : cb;
+ var s = (chunk instanceof Uint8Array)
+ ? __slice_buf_to_utf8(chunk)
+ : String(chunk === undefined ? "" : chunk);
+ if (s.endsWith("\r\n")) s = s.slice(0, -2);
+ else if (s.endsWith("\n")) s = s.slice(0, -1);
+ __slice_console_log(s);
+ if (typeof fn === "function") fn(null);
+ return true;
+ },
+ end: function(chunk, enc, cb) {
+ var fn = typeof chunk === "function" ? chunk : (typeof enc === "function" ? enc : cb);
+ if (chunk !== undefined && chunk !== null && typeof chunk !== "function") {
+ this.write(chunk, enc);
+ }
+ if (typeof fn === "function") fn();
+ return this;
+ },
+ on: function() { return this; },
+ once: function() { return this; },
+ off: function() { return this; },
+ removeListener: function() { return this; },
+ emit: function() { return false; }
+ };
+ }
+ p.stdout = __mkWritable(1);
+ p.stderr = __mkWritable(2);
+ p.stdin = {
+ fd: 0,
+ isTTY: false,
+ readable: false,
+ on: function(ev, cb) {
+ if (ev === "end" && typeof cb === "function") queueMicrotask(cb);
+ return this;
+ },
+ once: function(ev, cb) {
+ if (ev === "end" && typeof cb === "function") queueMicrotask(cb);
+ return this;
+ },
+ off: function() { return this; },
+ removeListener: function() { return this; },
+ resume: function() { return this; },
+ pause: function() { return this; },
+ setEncoding: function() { return this; },
+ read: function() { return null; }
+ };
+
+ var __pEv = Object.create(null);
+ var __pEvCount = 0;
+ p._exited = false;
+ p.on = p.addListener = function(ev, fn) {
+ if (typeof fn === "function") {
+ __slice_process_ctl(0);
+ var k = String(ev);
+ (__pEv[k] || (__pEv[k] = [])).push(fn);
+ __pEvCount++;
+ }
+ return p;
+ };
+ p.once = function(ev, fn) {
+ if (typeof fn === "function") {
+ var g = function() {
+ p.off(ev, g);
+ fn.apply(p, arguments);
+ };
+ g.listener = fn;
+ p.on(ev, g);
+ }
+ return p;
+ };
+ p.off = p.removeListener = function(ev, fn) {
+ var k = String(ev), list = __pEv[k];
+ if (list) {
+ var prevLen = list.length;
+ __pEv[k] = list.filter(function(f) { return f !== fn && f.listener !== fn; });
+ __pEvCount = Math.max(0, __pEvCount - (prevLen - __pEv[k].length));
+ }
+ return p;
+ };
+ p.removeAllListeners = function(ev) {
+ if (arguments.length === 0) {
+ __pEv = Object.create(null);
+ __pEvCount = 0;
+ } else {
+ var k = String(ev);
+ if (__pEv[k]) {
+ __pEvCount = Math.max(0, __pEvCount - __pEv[k].length);
+ delete __pEv[k];
+ }
+ }
+ return p;
+ };
+ p.listeners = function(ev) {
+ return (__pEv[String(ev)] || []).slice();
+ };
+ p.listenerCount = function(ev) {
+ var l = __pEv[String(ev)];
+ return l ? l.length : 0;
+ };
+ p._hasListeners = function(ev) {
+ if (__pEvCount === 0) return false;
+ if (!ev) return true;
+ var l = __pEv[String(ev)];
+ return Boolean(l && l.length > 0);
+ };
+ p._resetProcessState = function() {
+ if (__pEvCount > 0) {
+ __pEv = Object.create(null);
+ __pEvCount = 0;
+ }
+ if (p._resetExitCode) p._resetExitCode();
+ else p.exitCode = undefined;
+ p._exited = false;
+ };
+ p.emit = function(ev) {
+ if (__pEvCount === 0) return false;
+ var list = __pEv[String(ev)];
+ if (!list || list.length === 0) return false;
+ var args = [];
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
+ var snap = list.slice();
+ for (var j = 0; j < snap.length; j++) snap[j].apply(p, args);
+ return true;
+ };
+ p.emitWarning = function(warning, type, code) {
+ var msg = (warning && typeof warning === "object" && warning.message)
+ ? warning.message
+ : String(warning);
+ var t = typeof type === "string"
+ ? type
+ : (type && typeof type === "object" && type.type ? type.type : "Warning");
+ var c = typeof code === "string"
+ ? code
+ : (type && typeof type === "object" && type.code ? type.code : undefined);
+ var w = new Error(msg);
+ w.name = t;
+ if (c) w.code = c;
+ p.emit("warning", w);
+ };
+ }
+
+ if (!globalThis.navigator) {
+ globalThis.navigator = {
+ userAgent: "Slice-NexusJS/0.10.0",
+ hardwareConcurrency: 4,
+ language: "en-US",
+ languages: ["en-US", "en"],
+ onLine: true,
+ platform: "Slice",
+ maxTouchPoints: 0
+ };
+ }
+
+ if (!globalThis.location) {
+ globalThis.location = {
+ href: "http://localhost/",
+ origin: "http://localhost",
+ protocol: "http:",
+ host: "localhost",
+ hostname: "localhost",
+ port: "",
+ pathname: "/",
+ search: "",
+ hash: "",
+ toString: function() { return this.href; }
+ };
+ }
+})();
diff --git a/crates/slice-engine/src/preludes/js_preludes.rs b/crates/slice-engine/src/preludes/js_preludes.rs
index e356b30..758cd2f 100644
--- a/crates/slice-engine/src/preludes/js_preludes.rs
+++ b/crates/slice-engine/src/preludes/js_preludes.rs
@@ -52,20 +52,22 @@ pub const STRUCTURED_CLONE_PRELUDE_SRC: &str = include_str!("16_structured_clone
pub const BUFFER_BINARY_RW_PRELUDE_SRC: &str = include_str!("17_buffer_binary_rw.js");
/// Human-readable source for Shard 18: `INTL_PRELUDE` (`src/preludes/18_intl.js`).
pub const INTL_PRELUDE_SRC: &str = include_str!("18_intl.js");
+/// Human-readable source for Shard 29: `PROCESS_CLI_PRELUDE` (`src/preludes/19_process_cli.js`).
+pub const PROCESS_CLI_PRELUDE_SRC: &str = include_str!("19_process_cli.js");
/// On-demand self-replacing lazy property getter registration (`__defLazy`) evaluated ONLY when
/// `needs_lazy_global_getters(js_code)` is true (`globalThis.*` dynamic probes).
-pub(crate) const LAZY_GETTERS_INIT_PRELUDE: &[u8] = br#"(function(){var __loadShard=globalThis.__slice_ensure_shard,__shardProps=globalThis.__shardProps,__shMask=globalThis.__shMask;globalThis.__slice_mark_lazy_inited();function __defLazy(names,shardId){__shardProps[shardId]=names;for(var i=0;i &'static [u8] {
match shard_id {
@@ -87,6 +89,7 @@ pub(crate) fn shard_prelude_bytes(shard_id: u32) -> &'static [u8] {
16 => STRUCTURED_CLONE_PRELUDE,
17 => BUFFER_BINARY_RW_PRELUDE,
18 => INTL_PRELUDE,
+ 29 => PROCESS_CLI_PRELUDE,
_ => b"",
}
}
@@ -217,7 +220,7 @@ pub(crate) fn build_fused_prelude_and_bundle(
static ULTRA_CORE_SLICEBC: OnceLock> = OnceLock::new();
static LAZY_GETTERS_SLICEBC: OnceLock> = OnceLock::new();
-static SHARD_SLICEBC: [OnceLock>; 19] = [const { OnceLock::new() }; 19];
+static SHARD_SLICEBC: [OnceLock>; 30] = [const { OnceLock::new() }; 30];
#[inline]
pub(crate) fn compile_static_js_to_slicebc(bytes: &[u8]) -> Vec {
@@ -288,14 +291,14 @@ pub(crate) fn eval_lazy_getters_init_prelude(
context.eval(boa_engine::Source::from_bytes(LAZY_GETTERS_INIT_PRELUDE))
}
-/// Evaluates a compile-time minified lazy prelude shard (`1..=18`) on demand inside `context`
+/// Evaluates a compile-time minified lazy prelude shard (`1..=18` or `29`) on demand inside `context`
/// using cached precompiled `SLICEBC\x01` `CodeBlock` bytecode.
#[inline]
pub(crate) fn eval_lazy_prelude_shard(
shard_id: u32,
context: &mut boa_engine::Context,
) -> boa_engine::JsResult {
- if !(1..=18).contains(&shard_id) {
+ if !((1..=18).contains(&shard_id) || shard_id == 29) {
return Ok(boa_engine::JsValue::undefined());
}
register_shard_host_functions_for_mask(1u32 << shard_id, context);
@@ -366,11 +369,11 @@ const SHARD_PATTERNS: &[(&str, ShardTriggerAction)] = &[
),
(
"AbortController",
- ShardTriggerAction::Mask((1 << 10) | (1 << 11) | (1 << 13) | (1 << 6)),
+ ShardTriggerAction::Mask((1 << 10) | (1 << 11) | (1 << 13)),
),
(
"AbortSignal",
- ShardTriggerAction::Mask((1 << 10) | (1 << 11) | (1 << 13) | (1 << 6)),
+ ShardTriggerAction::Mask((1 << 10) | (1 << 11) | (1 << 13)),
),
// HTTP Request / Response / Headers (`1 << 11`)
(".fetch(", ShardTriggerAction::Mask(1 << 11)),
@@ -455,7 +458,11 @@ const SHARD_PATTERNS: &[(&str, ShardTriggerAction)] = &[
("randomUUID", ShardTriggerAction::Mask(1 << 4)),
("webcrypto", ShardTriggerAction::Mask(1 << 4)),
("CryptoKey", ShardTriggerAction::Mask(1 << 4)),
- ("crypto.", ShardTriggerAction::Mask(1 << 4)),
+ ("SubtleCrypto", ShardTriggerAction::Mask(1 << 4)),
+ ("typeof crypto", ShardTriggerAction::Mask(1 << 4)),
+ ("globalThis.crypto", ShardTriggerAction::Mask(1 << 4)),
+ ("window.crypto", ShardTriggerAction::Mask(1 << 4)),
+ ("self.crypto", ShardTriggerAction::Mask(1 << 4)),
// structuredClone (`1 << 16`)
("structuredClone", ShardTriggerAction::Mask(1 << 16)),
// Buffer & Binary R/W (`1 << 5`, `1 << 17`, & builtin `1 << 26`)
@@ -584,45 +591,45 @@ const SHARD_PATTERNS: &[(&str, ShardTriggerAction)] = &[
),
// WebAssembly (`1 << 9`)
("WebAssembly", ShardTriggerAction::Mask(1 << 9)),
- // Shard 18: WinterTC `Intl`, `navigator`, `location`, & Complete `process` CLI Surface (`1 << 18`)
+ // Shard 18: WinterTC `Intl` (`1 << 18`)
("Intl", ShardTriggerAction::Mask(1 << 18)),
("toLocaleString", ShardTriggerAction::Mask(1 << 18)),
("toLocaleDateString", ShardTriggerAction::Mask(1 << 18)),
("toLocaleTimeString", ShardTriggerAction::Mask(1 << 18)),
("localeCompare", ShardTriggerAction::Mask(1 << 18)),
- ("navigator", ShardTriggerAction::Mask(1 << 18)),
- ("location.", ShardTriggerAction::Mask(1 << 18)),
- ("globalThis.location", ShardTriggerAction::Mask(1 << 18)),
- ("stdout", ShardTriggerAction::Mask(1 << 18)),
- ("stderr", ShardTriggerAction::Mask(1 << 18)),
- ("stdin", ShardTriggerAction::Mask(1 << 18)),
- ("memoryUsage", ShardTriggerAction::Mask(1 << 18)),
- ("hrtime", ShardTriggerAction::Mask(1 << 18)),
- ("uptime", ShardTriggerAction::Mask(1 << 18)),
- ("emitWarning", ShardTriggerAction::Mask(1 << 18)),
- ("exitCode", ShardTriggerAction::Mask(1 << 18)),
- ("argv0", ShardTriggerAction::Mask(1 << 18)),
- ("execPath", ShardTriggerAction::Mask(1 << 18)),
- ("ppid", ShardTriggerAction::Mask(1 << 18)),
- ("process.exit", ShardTriggerAction::Mask(1 << 18)),
- ("process.on", ShardTriggerAction::Mask(1 << 18)),
- ("process.once", ShardTriggerAction::Mask(1 << 18)),
- ("process.off", ShardTriggerAction::Mask(1 << 18)),
- ("process.emit", ShardTriggerAction::Mask(1 << 18)),
- ("process.listeners", ShardTriggerAction::Mask(1 << 18)),
- ("process.removeListener", ShardTriggerAction::Mask(1 << 18)),
+ // Shard 29: `navigator`, `location`, & Complete `process` CLI Surface (`1 << 29`)
+ ("navigator", ShardTriggerAction::Mask(1 << 29)),
+ ("location.", ShardTriggerAction::Mask(1 << 29)),
+ ("globalThis.location", ShardTriggerAction::Mask(1 << 29)),
+ ("stdout", ShardTriggerAction::Mask(1 << 29)),
+ ("stderr", ShardTriggerAction::Mask(1 << 29)),
+ ("stdin", ShardTriggerAction::Mask(1 << 29)),
+ ("memoryUsage", ShardTriggerAction::Mask(1 << 29)),
+ ("hrtime", ShardTriggerAction::Mask(1 << 29)),
+ ("uptime", ShardTriggerAction::Mask(1 << 29)),
+ ("emitWarning", ShardTriggerAction::Mask(1 << 29)),
+ ("argv0", ShardTriggerAction::Mask(1 << 29)),
+ ("execArgv", ShardTriggerAction::Mask(1 << 29)),
+ ("execPath", ShardTriggerAction::Mask(1 << 29)),
+ ("ppid", ShardTriggerAction::Mask(1 << 29)),
+ ("process.on", ShardTriggerAction::Mask(1 << 29)),
+ ("process.once", ShardTriggerAction::Mask(1 << 29)),
+ ("process.off", ShardTriggerAction::Mask(1 << 29)),
+ ("process.emit", ShardTriggerAction::Mask(1 << 29)),
+ ("process.listeners", ShardTriggerAction::Mask(1 << 29)),
+ ("process.removeListener", ShardTriggerAction::Mask(1 << 29)),
(
"process.removeAllListeners",
- ShardTriggerAction::Mask(1 << 18),
- ),
- ("process.addListener", ShardTriggerAction::Mask(1 << 18)),
- ("process.listenerCount", ShardTriggerAction::Mask(1 << 18)),
- ("unhandledRejection", ShardTriggerAction::Mask(1 << 18)),
- ("uncaughtException", ShardTriggerAction::Mask(1 << 18)),
- ("beforeExit", ShardTriggerAction::Mask(1 << 18)),
- ("node:process", ShardTriggerAction::Mask(1 << 18)),
- ("\"process\"", ShardTriggerAction::BuiltinMask(1 << 18)),
- ("'process'", ShardTriggerAction::BuiltinMask(1 << 18)),
+ ShardTriggerAction::Mask(1 << 29),
+ ),
+ ("process.addListener", ShardTriggerAction::Mask(1 << 29)),
+ ("process.listenerCount", ShardTriggerAction::Mask(1 << 29)),
+ ("unhandledRejection", ShardTriggerAction::Mask(1 << 29)),
+ ("uncaughtException", ShardTriggerAction::Mask(1 << 29)),
+ ("beforeExit", ShardTriggerAction::Mask(1 << 29)),
+ ("node:process", ShardTriggerAction::Mask(1 << 29)),
+ ("\"process\"", ShardTriggerAction::BuiltinMask(1 << 29)),
+ ("'process'", ShardTriggerAction::BuiltinMask(1 << 29)),
// Pre-fused `node:*` builtin module triggers (`19..=28`)
("node:crypto", ShardTriggerAction::BuiltinMask(1 << 19)),
("\"crypto\"", ShardTriggerAction::BuiltinMask(1 << 19)),
@@ -824,13 +831,13 @@ pub(crate) fn detect_shards_and_boacas_flags(
(flags, mask)
}
-/// Computes a bitmask of lazy prelude shards (`1..=18`) referenced by `raw_js_code` in a single
+/// Computes a bitmask of lazy prelude shards (`1..=18` and `29`) referenced by `raw_js_code` in a single
/// zero-allocation `O(N)` SIMD multi-pattern pass so top-level execution pre-loads only the shards
/// actually used by a script before entering async/generator frames.
#[inline]
pub(crate) fn detect_needed_shards(raw_js_code: &str, is_http: bool) -> u32 {
let (_, mask) = detect_shards_and_boacas_flags(raw_js_code, is_http, false);
- mask & ((1 << 19) - 1)
+ (mask & ((1 << 19) - 1)) | (mask & (1 << 29))
}
/// Returns `true` only when `js_code` may dynamically probe unreferenced `globalThis` shard properties
diff --git a/crates/slice-engine/src/preludes/node_builtins.rs b/crates/slice-engine/src/preludes/node_builtins.rs
index 27c576e..80bd21b 100644
--- a/crates/slice-engine/src/preludes/node_builtins.rs
+++ b/crates/slice-engine/src/preludes/node_builtins.rs
@@ -10,7 +10,7 @@ use std::sync::{Arc, OnceLock};
const BUILTIN_CRYPTO_SNIPPET: &[u8] = br#"(function(){var __U8=globalThis.Uint8Array,__ext=false;function __ensExt(){if(!__ext){__ext=true;__slice_init_crypto_ext();}}function __toBytes(d,enc){if(d instanceof __U8)return d;if(d instanceof ArrayBuffer)return new __U8(d);if(d&&d.buffer instanceof ArrayBuffer)return new __U8(d.buffer,d.byteOffset||0,d.byteLength);__slice_ensure_shard(5);return Buffer.from(String(d),enc||"utf8");}function __catBytes(chunks){if(chunks.length===0)return new __U8(0);if(chunks.length===1)return chunks[0];__slice_ensure_shard(5);return Buffer.concat(chunks);}function __encOut(rawBuf,enc){__slice_ensure_shard(5);var b=Buffer.isBuffer(rawBuf)?rawBuf:Buffer.from(rawBuf);return(!enc||enc==="buffer")?b:b.toString(enc);}function KeyObject(type,alg,crv,id,raw,meta,details){this.type=type;this.asymmetricKeyType=alg;this.asymmetricKeyDetails=details||(crv?{namedCurve:crv}:{});this._id=id||0;this._raw=raw||null;this._meta=meta||null;}KeyObject.prototype.export=function(opts){__ensExt();__slice_ensure_shard(5);var o=opts||{};var fmt=String(o.format||"der").toLowerCase();if(this.type==="secret")return Buffer.from(this._raw);var derB64=(this.type==="private")?(this._meta&&this._meta.pkcs8):(this._meta&&this._meta.spki);var der=derB64?Buffer.from(__slice_base64_decode_bytes(derB64)):Buffer.from(this._raw||[]);if(fmt==="pem"){var label=this.type==="private"?"PRIVATE KEY":"PUBLIC KEY";return"-----BEGIN "+label+"-----\n"+der.toString("base64")+"\n-----END "+label+"-----\n";}if(fmt==="jwk"&&this._meta){if(this.asymmetricKeyType==="ed25519"||this.asymmetricKeyType==="x25519"){var j={kty:"OKP",crv:this.asymmetricKeyType==="x25519"?"X25519":"Ed25519",x:this._meta.x};if(this.type==="private")j.d=this._meta.d;return j;}var je={kty:"EC",crv:this._meta.crv||"P-256",x:this._meta.x,y:this._meta.y};if(this.type==="private")je.d=this._meta.d;return je;}return der;};function __importDerKey(der,fmt){try{var impEd=JSON.parse(__slice_crypto_asym_import("Ed25519","",fmt,der));return new KeyObject(impEd.type,"ed25519",undefined,impEd.id,der,impEd);}catch(_e1){try{var impX=JSON.parse(__slice_crypto_asym_import("X25519","",fmt,der));return new KeyObject(impX.type,"x25519",undefined,impX.id,der,impX);}catch(_eX){try{var impRsa=JSON.parse(__slice_crypto_asym_import("RSA","",fmt,der));return new KeyObject(impRsa.type,"rsa",undefined,impRsa.id,der,impRsa,{modulusLength:2048,publicExponent:65537n});}catch(_eR){try{var impEc256=JSON.parse(__slice_crypto_asym_import("ECDSA","P-256",fmt,der));return new KeyObject(impEc256.type,"ec","P-256",impEc256.id,der,impEc256);}catch(_e2){var impEc384=JSON.parse(__slice_crypto_asym_import("ECDSA","P-384",fmt,der));return new KeyObject(impEc384.type,"ec","P-384",impEc384.id,der,impEc384);}}}}}function __parseKeyObj(k,isPriv){__ensExt();if(k instanceof KeyObject)return k;if(k&&typeof k==="object"&&k._id!==undefined&&k.algorithm){var kn=String(k.algorithm.name||"").toLowerCase();return new KeyObject(k.type,kn==="ecdsa"?"ec":kn,k.algorithm.namedCurve,k._id,k._raw,k._meta);}if(k&&typeof k==="object"&&k.key!==undefined)return __parseKeyObj(k.key,isPriv);var fmt=isPriv?"pkcs8":"spki";if(typeof k==="string"&&k.indexOf("-----BEGIN")!==-1){var body=k.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");var der=__slice_base64_decode_bytes(body);return __importDerKey(der,fmt);}return __importDerKey(__toBytes(k),fmt);}function __mkHash(a,isSha256,initChunks,initFast,initSBuf){var chunks=initChunks?initChunks.slice():[],strFast=initFast!==undefined?initFast:isSha256,sBuf=initSBuf||"";return{update:function(d,enc){if(strFast&&typeof d==="string"&&(!enc||enc==="utf8"||enc==="utf-8")&&chunks.length===0){sBuf+=d;}else{if(sBuf.length>0){__slice_ensure_shard(5);chunks.push(Buffer.from(sBuf,"utf8"));sBuf="";}strFast=false;chunks.push(__toBytes(d,enc));}return this;},copy:function(){return __mkHash(a,isSha256,chunks,strFast,sBuf);},digest:function(enc){if(isSha256&&(enc==="hex"||enc==="base64"||enc==="base64url")){if(strFast&&chunks.length===0){var h=__slice_crypto_sha256(sBuf,enc);sBuf="";return h;}if(sBuf.length===0&&chunks.length===1){var hb=__slice_crypto_sha256(chunks[0],enc);chunks=[];return hb;}}__ensExt();__slice_ensure_shard(5);if(sBuf.length>0){chunks.push(Buffer.from(sBuf,"utf8"));sBuf="";}var raw=Buffer.from(__slice_crypto_digest_bytes(a,__catBytes(chunks)));chunks=[];return(!enc||enc==="buffer")?raw:raw.toString(enc);}};}function __mkHmac(a,isSha256,key,initChunks,initFast,initSBuf){var kBytes=null,chunks=initChunks?initChunks.slice():[],strFast=initFast!==undefined?initFast:(isSha256&&typeof key==="string"),kStr=typeof key==="string"?key:"",sBuf=initSBuf||"";return{update:function(d,enc){if(strFast&&typeof d==="string"&&(!enc||enc==="utf8"||enc==="utf-8")&&chunks.length===0){sBuf+=d;}else{if(sBuf.length>0){__slice_ensure_shard(5);chunks.push(Buffer.from(sBuf,"utf8"));sBuf="";}strFast=false;chunks.push(__toBytes(d,enc));}return this;},copy:function(){return __mkHmac(a,isSha256,key,chunks,strFast,sBuf);},digest:function(enc){if(isSha256&&(enc==="hex"||enc==="base64"||enc==="base64url")){if(strFast&&chunks.length===0){var h=__slice_crypto_hmac_sha256(kStr,sBuf,enc);sBuf="";return h;}if(sBuf.length===0&&chunks.length===1){if(!kBytes)kBytes=(typeof key==="string")?key:__toBytes(key);var hb=__slice_crypto_hmac_sha256(kBytes,chunks[0],enc);chunks=[];return hb;}}__ensExt();__slice_ensure_shard(5);if(sBuf.length>0){chunks.push(Buffer.from(sBuf,"utf8"));sBuf="";}if(!kBytes)kBytes=__toBytes(key);var raw=Buffer.from(__slice_crypto_hmac_bytes(a,kBytes,__catBytes(chunks)));chunks=[];return(!enc||enc==="buffer")?raw:raw.toString(enc);}};}var m={KeyObject:KeyObject,createHash:function(alg){var a=String(alg||"sha256").toLowerCase(),isSha256=(a==="sha256"||a==="sha-256");return __mkHash(a,isSha256);},createHmac:function(alg,key){var a=String(alg||"sha256").toLowerCase(),isSha256=(a==="sha256"||a==="sha-256");return __mkHmac(a,isSha256,key);},randomBytes:function(size,cb){__ensExt();__slice_ensure_shard(5);var b=Buffer.from(__slice_crypto_random_bytes(Number(size)||0));if(typeof cb==="function"){cb(null,b);return;}return b;},randomFillSync:function(buf,offset,size){__ensExt();if(!buf||typeof buf.byteLength!=="number")throw new TypeError("buf must be an ArrayBufferView");var off=offset!==undefined?Number(offset):0;var sz=size!==undefined?Number(size):(buf.byteLength-off);if(off<0||sz<0||off+sz>buf.byteLength)throw new RangeError("offset or size out of bounds");var u8=new __U8(buf.buffer||buf,(buf.byteOffset||0)+off,sz);var rnd=__slice_crypto_random_bytes(sz);u8.set(rnd);return buf;},randomFill:function(buf,offset,size,cb){if(typeof offset==="function"){cb=offset;offset=0;size=buf.byteLength;}else if(typeof size==="function"){cb=size;size=buf.byteLength-Number(offset||0);}try{var r=m.randomFillSync(buf,offset,size);if(typeof cb==="function")queueMicrotask(function(){cb(null,r);});}catch(e){if(typeof cb==="function")queueMicrotask(function(){cb(e);});else throw e;}},randomInt:function(min,max,cb){__ensExt();if(typeof max==="function"||max===undefined){cb=max;max=min;min=0;}var lo=Math.ceil(Number(min)),hi=Math.floor(Number(max));if(!(hi>lo))throw new RangeError("max must be greater than min");var range=hi-lo,rb=__slice_crypto_random_bytes(4),u=((rb[0]<<24)>>>0)+((rb[1]<<16)>>>0)+((rb[2]<<8)>>>0)+(rb[3]>>>0);var val=lo+(u%range);if(typeof cb==="function"){queueMicrotask(function(){cb(null,val);});return;}return val;},randomUUID:function(){__ensExt();return __slice_crypto_random_uuid();},getRandomValues:function(ta){__ensExt();return __slice_crypto_get_random_values(ta);},timingSafeEqual:function(a,b){__ensExt();return __slice_crypto_timing_safe_equal(a,b);},pbkdf2Sync:function(password,salt,iterations,keylen,digest){__ensExt();__slice_ensure_shard(5);var ab=__slice_crypto_kdf("PBKDF2",String(digest||"sha256"),__toBytes(password),__toBytes(salt),null,Number(iterations),Number(keylen));return Buffer.from(ab);},pbkdf2:function(password,salt,iterations,keylen,digest,cb){if(typeof digest==="function"){cb=digest;digest="sha1";}try{var b=m.pbkdf2Sync(password,salt,iterations,keylen,digest);if(typeof cb==="function")queueMicrotask(function(){cb(null,b);});}catch(e){if(typeof cb==="function")queueMicrotask(function(){cb(e);});else throw e;}},hkdfSync:function(digest,ikm,salt,info,keylen){__ensExt();var ab=__slice_crypto_kdf("HKDF",String(digest||"sha256"),__toBytes(ikm),__toBytes(salt),__toBytes(info),1,Number(keylen));return ab;},hkdf:function(digest,ikm,salt,info,keylen,cb){try{var ab=m.hkdfSync(digest,ikm,salt,info,keylen);if(typeof cb==="function")queueMicrotask(function(){cb(null,ab);});}catch(e){if(typeof cb==="function")queueMicrotask(function(){cb(e);});else throw e;}},scryptSync:function(password,salt,keylen,options){__ensExt();__slice_ensure_shard(5);var o=options||{};var N=Number(o.N||o.cost||16384),r=Number(o.r||o.blockSize||8),p=Number(o.p||o.parallelization||1),maxmem=Number(o.maxmem||(32*1024*1024));var ab=__slice_crypto_kdf("SCRYPT","SHA-256",__toBytes(password),__toBytes(salt),null,N,Number(keylen),r,p,maxmem);return Buffer.from(ab);},scrypt:function(password,salt,keylen,options,cb){if(typeof options==="function"){cb=options;options={};}try{var b=m.scryptSync(password,salt,keylen,options);if(typeof cb==="function")queueMicrotask(function(){cb(null,b);});}catch(e){if(typeof cb==="function")queueMicrotask(function(){cb(e);});else throw e;}},createCipheriv:function(algorithm,key,iv,options){__ensExt();__slice_ensure_shard(5);var alg=String(algorithm||"").toLowerCase(),isGcm=alg.indexOf("gcm")!==-1,kB=__toBytes(key),ivB=__toBytes(iv),aadB=null,chunks=[],tagBuf=null,autoPad=true,tagLen=(options&&options.authTagLength)?Number(options.authTagLength)*8:128;var hid=__slice_crypto_key_register(isGcm?"AES-GCM":"AES-CBC","",kB);return{setAAD:function(buf){aadB=__toBytes(buf);return this;},setAutoPadding:function(ap){autoPad=(ap===undefined)?true:Boolean(ap);return this;},update:function(data,inEnc,outEnc){chunks.push(__toBytes(data,inEnc));return __encOut(new __U8(0),outEnc);},final:function(outEnc){var plain=__catBytes(chunks);chunks=[];var ab=__slice_crypto_cipher(isGcm?"AES-GCM":"AES-CBC",true,hid,kB,ivB,aadB,tagLen,plain,autoPad);var full=new __U8(ab);if(isGcm){var tBytes=tagLen/8;var cLen=full.byteLength-tBytes;tagBuf=Buffer.from(full.subarray(cLen));return __encOut(full.subarray(0,cLen),outEnc);}return __encOut(full,outEnc);},getAuthTag:function(){if(!isGcm||!tagBuf)throw new Error("ERR_CRYPTO_INVALID_STATE: getAuthTag requires finalized GCM cipher");return tagBuf;}};},createDecipheriv:function(algorithm,key,iv,options){__ensExt();__slice_ensure_shard(5);var alg=String(algorithm||"").toLowerCase(),isGcm=alg.indexOf("gcm")!==-1,kB=__toBytes(key),ivB=__toBytes(iv),aadB=null,chunks=[],authTag=null,autoPad=true,tagLen=(options&&options.authTagLength)?Number(options.authTagLength)*8:128;var hid=__slice_crypto_key_register(isGcm?"AES-GCM":"AES-CBC","",kB);return{setAAD:function(buf){aadB=__toBytes(buf);return this;},setAuthTag:function(buf,enc){authTag=__toBytes(buf,enc);return this;},setAutoPadding:function(ap){autoPad=(ap===undefined)?true:Boolean(ap);return this;},update:function(data,inEnc,outEnc){chunks.push(__toBytes(data,inEnc));return __encOut(new __U8(0),outEnc);},final:function(outEnc){var ciph=__catBytes(chunks);chunks=[];if(isGcm){if(!authTag)throw new Error("ERR_CRYPTO_INVALID_STATE: Unsupported state or unable to authenticate data (missing authTag)");var combined=new __U8(ciph.byteLength+authTag.byteLength);combined.set(ciph,0);combined.set(authTag,ciph.byteLength);var ab=__slice_crypto_cipher("AES-GCM",false,hid,kB,ivB,aadB,tagLen,combined,true);return __encOut(new __U8(ab),outEnc);}var abC=__slice_crypto_cipher("AES-CBC",false,hid,kB,ivB,null,128,ciph,autoPad);return __encOut(new __U8(abC),outEnc);}};},generateKeyPairSync:function(type,options){__ensExt();__slice_ensure_shard(5);var t=typeof type==="string"?type.toLowerCase():"";if(t!=="ed25519"&&t!=="x25519"&&t!=="ec"&&t!=="rsa"&&t!=="rsa-pss"&&t!=="dsa"){var eType=new TypeError("The argument 'type' must be a supported key type. Received '"+String(type)+"'");eType.code="ERR_INVALID_ARG_VALUE";throw eType;}var o=options||{};var info,details=undefined;if(t==="ed25519"){info=JSON.parse(__slice_crypto_asym_keygen("Ed25519",""));}else if(t==="x25519"){info=JSON.parse(__slice_crypto_asym_keygen("X25519",""));}else if(t==="rsa"||t==="rsa-pss"){info=JSON.parse(__slice_crypto_asym_keygen("RSA",""));details={modulusLength:Number(o.modulusLength)||2048,publicExponent:BigInt(o.publicExponent||65537)};}else if(t==="dsa"){info=JSON.parse(__slice_crypto_asym_keygen("ECDSA","P-256"));details={modulusLength:Number(o.modulusLength)||2048,divisorLength:Number(o.divisorLength)||256};}else{info=JSON.parse(__slice_crypto_asym_keygen("ECDSA",String(o.namedCurve||"P-256")));}var crv=(t==="ec")?(info.crv||"P-256"):undefined;var pubKO=new KeyObject("public",t,crv,info.pubId,__slice_base64_decode_bytes(info.spki),info,details);var privKO=new KeyObject("private",t,crv,info.privId,__slice_base64_decode_bytes(info.pkcs8),info,details);var pubOut=o.publicKeyEncoding?pubKO.export(o.publicKeyEncoding):pubKO;var privOut=o.privateKeyEncoding?privKO.export(o.privateKeyEncoding):privKO;return{publicKey:pubOut,privateKey:privOut};},generateKeyPair:function(type,options,cb){if(typeof options==="function"){cb=options;options={};}try{var kp=m.generateKeyPairSync(type,options);if(typeof cb==="function")queueMicrotask(function(){cb(null,kp.publicKey,kp.privateKey);});}catch(e){if(typeof cb==="function")queueMicrotask(function(){cb(e);});else throw e;}},createPrivateKey:function(k){return __parseKeyObj(k,true);},createPublicKey:function(k){return __parseKeyObj(k,false);},createSecretKey:function(k,enc){__slice_ensure_shard(5);var b=__toBytes(k,enc);return new KeyObject("secret","secret",undefined,0,b,null);},sign:function(alg,data,key,cb){__ensExt();__slice_ensure_shard(5);try{var ko=__parseKeyObj(key,true);var dsaEnc=(key&&typeof key==="object"&&key.dsaEncoding)?String(key.dsaEncoding):"der";var hostAlg=ko.asymmetricKeyType==="ed25519"?"Ed25519":((ko.asymmetricKeyType==="rsa"||ko.asymmetricKeyType==="rsa-pss")?"RSA":"ECDSA");var ab=__slice_crypto_asym_sign(hostAlg,ko.asymmetricKeyDetails.namedCurve||"P-256",ko._id,ko._raw,__toBytes(data),dsaEnc!=="ieee-p1363");var b=Buffer.from(ab);if(typeof cb==="function"){queueMicrotask(function(){cb(null,b);});return;}return b;}catch(e){if(typeof cb==="function"){queueMicrotask(function(){cb(e);});return;}throw e;}},verify:function(alg,data,key,sig,cb){__ensExt();try{var ko=__parseKeyObj(key,false);var hostAlg=ko.asymmetricKeyType==="ed25519"?"Ed25519":((ko.asymmetricKeyType==="rsa"||ko.asymmetricKeyType==="rsa-pss")?"RSA":"ECDSA");var ok=Boolean(__slice_crypto_asym_verify(hostAlg,ko.asymmetricKeyDetails.namedCurve||"P-256",ko._id,ko._raw,__toBytes(sig),__toBytes(data)));if(typeof cb==="function"){queueMicrotask(function(){cb(null,ok);});return;}return ok;}catch(e){if(typeof cb==="function"){queueMicrotask(function(){cb(e);});return;}throw e;}},createSign:function(_alg){var chunks=[];return{update:function(d,enc){chunks.push(__toBytes(d,enc));return this;},sign:function(key,outEnc){var sig=m.sign(null,__catBytes(chunks),key);chunks=[];return(!outEnc||outEnc==="buffer")?sig:sig.toString(outEnc);}};},createVerify:function(_alg){var chunks=[];return{update:function(d,enc){chunks.push(__toBytes(d,enc));return this;},verify:function(key,sig,sigEnc){var sB=typeof sig==="string"?__toBytes(sig,sigEnc||"base64"):__toBytes(sig);var ok=m.verify(null,__catBytes(chunks),key,sB);chunks=[];return ok;}};},getHashes:function(){return["sha1","sha256","sha384","sha512","md5"];},getCiphers:function(){return["aes-128-gcm","aes-256-gcm","aes-128-cbc","aes-256-cbc"];},get subtle(){__slice_ensure_shard(4);return globalThis.crypto.subtle;},get webcrypto(){__slice_ensure_shard(4);return globalThis.crypto;}};m.default=m;m.__esModule=true;return __slice_builtins["crypto"]=__slice_builtins["node:crypto"]=m;})();"#;
-const BUILTIN_FS_SNIPPET: &[u8] = br#"(function(){var __watchers=[],__fds=Object.create(null),__nextFd=10;function __fsErr(code,syscall,p,dest){var map={ENOENT:[-2,"no such file or directory"],EEXIST:[-17,"file already exists"],EISDIR:[-21,"illegal operation on a directory"],ENOTDIR:[-20,"not a directory"],ENOTEMPTY:[-39,"directory not empty"],EBADF:[-9,"bad file descriptor"],EACCES:[-13,"permission denied"],EINVAL:[-22,"invalid argument"]},info=map[code]||[-1,"unknown error"],msg=code+": "+info[1]+", "+syscall+(p!==undefined?" '"+p+"'":"")+(dest!==undefined?" -> '"+dest+"'":""),e=new Error(msg);e.code=code;e.errno=info[0];e.syscall=syscall;if(p!==undefined)e.path=String(p);if(dest!==undefined)e.dest=String(dest);return e;}function __getFd(fd,syscall){var e=__fds[Number(fd)];if(!e)throw __fsErr("EBADF",syscall);return e;}function __normW(p){return String(p||"").replace(/\\/g,"/").replace(/\/+$/,"")||"/";}function __notifyWatch(rawP,evType){if(__watchers.length===0)return;var np=__normW(rawP),sl=np.lastIndexOf("/"),dir=sl>0?np.slice(0,sl):"/",base=sl>=0?np.slice(sl+1):np;for(var i=0;i<__watchers.length;i++){var w=__watchers[i];if(w._closed)continue;var wp=w._path;if(np===wp||dir===wp||(w._rec&&np.indexOf(wp+"/")===0)){var rel=(np===wp)?base:(np.slice(wp.length+1)||base);w._emit(evType,rel);}}}function __fsData(d){if(typeof d==="string")return d;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(d&&d.buffer instanceof ArrayBuffer)return new Uint8Array(d.buffer,d.byteOffset||0,d.byteLength);return String(d);}function __toMs(t){if(t instanceof Date)return t.getTime();var n=Number(t);if(!Number.isFinite(n))return Date.now();return n<1e11?n*1000:n;}function __mkStats(sp,followSym,opts){var isSym=Boolean(__slice_fs_is_symlink_sync(sp)),sz=__slice_fs_stat_sync(sp);if(sz<0&&!(!followSym&&isSym)){if(opts&&typeof opts==="object"&&opts.throwIfNoEntry===false)return undefined;throw __fsErr("ENOENT",followSym?"stat":"lstat",sp);}if(sz<0)sz=0;var mt=__slice_fs_mtime_sync(sp),isDir=(!followSym&&isSym)?false:Boolean(__slice_fs_is_dir_sync(sp)),d=new Date(mt),bi=Boolean(opts&&typeof opts==="object"&&opts.bigint),vSz=bi?BigInt(Math.floor(sz)):sz,vMt=bi?BigInt(Math.floor(mt)):mt,vMode=bi?BigInt((!followSym&&isSym)?41471:(isDir?16877:33188)):((!followSym&&isSym)?41471:(isDir?16877:33188));return{size:vSz,mtimeMs:vMt,ctimeMs:vMt,atimeMs:vMt,birthtimeMs:vMt,mtime:d,ctime:d,atime:d,birthtime:d,mode:vMode,isFile:function(){return(!followSym&&isSym)?false:!isDir;},isDirectory:function(){return(!followSym&&isSym)?false:isDir;},isSymbolicLink:function(){return !followSym&&isSym;},isBlockDevice:function(){return false;},isCharacterDevice:function(){return false;},isFIFO:function(){return false;},isSocket:function(){return false;}};}function __cbWrap(syncFn){return function(){var args=[],cb=null;for(var i=0;i=0?n.slice(sl+1):n,par=sl>=0?((base==="/"?"":base)+"/"+n.slice(0,sl)):base,isD=Boolean(__slice_fs_is_dir_sync(fp)),isS=Boolean(__slice_fs_is_symlink_sync(fp));return{name:bn,parentPath:par,path:par,isFile:function(){return !isD&&!isS;},isDirectory:function(){return isD&&!isS;},isSymbolicLink:function(){return isS;},isBlockDevice:function(){return false;},isCharacterDevice:function(){return false;},isFIFO:function(){return false;},isSocket:function(){return false;}};});}if(o.encoding==="buffer"){__slice_ensure_shard(5);return names.map(function(n){return Buffer.from(n,"utf8");});}return names;},statSync:function(p,opts){return __mkStats(String(p),true,opts);},lstatSync:function(p,opts){return __mkStats(String(p),false,opts);},fstatSync:function(fd,opts){var e=__getFd(fd,"fstat");return __mkStats(e.path,true,opts);},openSync:function(p,flags,mode){var sp=String(p),fl=(flags===undefined||flags===null)?"r":String(flags),isR=fl==="r"||fl==="rs"||fl==="0",hasX=fl.indexOf("x")!==-1,isW=fl.charCodeAt(0)===119||fl==="1"||fl==="577",isA=fl.charCodeAt(0)===97||fl.indexOf("1024")!==-1,isPlus=fl.indexOf("+")!==-1||fl==="2";if(hasX&&m.existsSync(sp))throw __fsErr("EEXIST","open",sp);if(isR&&!isPlus){var raw=__slice_fs_read_bytes_sync(sp);if(raw===null)throw __fsErr("ENOENT","open",sp);}else if(isW){var wr=__slice_fs_write_file_sync(sp,new Uint8Array(0));if(wr===-21)throw __fsErr("EISDIR","open",sp);__notifyWatch(sp,"change");}else if(isA){if(!m.existsSync(sp))__slice_fs_write_file_sync(sp,new Uint8Array(0));else __slice_fs_append_file_sync(sp,new Uint8Array(0));}else if(isR&&isPlus){if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","open",sp);}var fd=__nextFd++;__fds[fd]={path:sp,flags:fl,mode:mode||438,pos:0,readable:isR||isPlus,writable:isW||isA||isPlus,append:isA};return fd;},closeSync:function(fd){__getFd(fd,"close");delete __fds[Number(fd)];},readSync:function(fd,buf,offOrOpts,len,pos){var e=__getFd(fd,"read");if(!e.readable)throw __fsErr("EBADF","read");var offset=0,length=buf?buf.byteLength:0,position=null;if(offOrOpts&&typeof offOrOpts==="object"){offset=Number(offOrOpts.offset)||0;length=offOrOpts.length!==undefined?Number(offOrOpts.length):(buf.byteLength-offset);position=offOrOpts.position!==undefined?offOrOpts.position:null;}else{offset=Number(offOrOpts)||0;length=len!==undefined?Number(len):(buf.byteLength-offset);position=pos!==undefined?pos:null;}var raw=__slice_fs_read_bytes_sync(e.path);if(!raw||raw===-21)return 0;var readPos=(position!==null&&position!==undefined&&Number(position)>=0)?Number(position):e.pos;if(readPos>=raw.byteLength||length<=0)return 0;var avail=Math.min(length,raw.byteLength-readPos);var target=new Uint8Array(buf.buffer||buf,(buf.byteOffset||0)+offset,avail);target.set(raw.subarray(readPos,readPos+avail),0);if(position===null||position===undefined||Number(position)<0)e.pos=readPos+avail;return avail;},writeSync:function(fd,bufOrStr,offOrPos,lenOrEnc,pos){var e=__getFd(fd,"write");if(!e.writable)throw __fsErr("EBADF","write");__slice_ensure_shard(5);var src,writePos=null;if(typeof bufOrStr==="string"){var enc=typeof lenOrEnc==="string"?lenOrEnc:(typeof offOrPos==="string"?offOrPos:"utf8");if(typeof offOrPos==="number")writePos=offOrPos;src=Buffer.from(bufOrStr,enc);}else{var u8=__fsData(bufOrStr),off=offOrPos!==undefined?Number(offOrPos):0,ln=lenOrEnc!==undefined?Number(lenOrEnc):(u8.byteLength-off);if(pos!==undefined&&pos!==null)writePos=Number(pos);src=u8.subarray(off,off+ln);}if(e.append){__slice_fs_append_file_sync(e.path,src);e.pos+=src.byteLength;__notifyWatch(e.path,"change");return src.byteLength;}var rawCur=__slice_fs_read_bytes_sync(e.path),cur=(rawCur&&rawCur!==-21)?rawCur:new Uint8Array(0);var p=(writePos!==null&&writePos>=0)?writePos:e.pos,nLen=Math.max(cur.byteLength,p+src.byteLength),out=new Uint8Array(nLen);out.set(cur,0);out.set(src,p);__slice_fs_write_file_sync(e.path,out);if(writePos===null||writePos<0)e.pos=p+src.byteLength;__notifyWatch(e.path,"change");return src.byteLength;},fsyncSync:function(fd){__getFd(fd,"fsync");},fdatasyncSync:function(fd){__getFd(fd,"fdatasync");},ftruncateSync:function(fd,len){var e=__getFd(fd,"ftruncate");return m.truncateSync(e.path,len);},futimesSync:function(fd,atime,mtime){var e=__getFd(fd,"futime");return m.utimesSync(e.path,atime,mtime);},fchmodSync:function(fd,mode){var e=__getFd(fd,"fchmod");return m.chmodSync(e.path,mode);},realpathSync:function(p){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","realpath",sp);var r=__slice_fs_realpath_sync(sp);if(!r)throw __fsErr("ENOENT","realpath",sp);return r;},readlinkSync:function(p,opts){var sp=String(p),r=__slice_fs_readlink_sync(sp);if(!r)throw __fsErr("ENOENT","readlink",sp);if(opts==="buffer"||(opts&&opts.encoding==="buffer")){__slice_ensure_shard(5);return Buffer.from(r,"utf8");}return r;},truncateSync:function(p,len){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","truncate",sp);var r=__slice_fs_truncate_sync(sp,len===undefined?0:Number(len));__notifyWatch(sp,"change");return r;},utimesSync:function(p,atime,mtime){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","utime",sp);return __slice_fs_utimes_sync(sp,__toMs(atime),__toMs(mtime));},lutimesSync:function(p,atime,mtime){return m.utimesSync(p,atime,mtime);},mkdtempSync:function(prefix){var r=__slice_fs_mkdtemp_sync(String(prefix||"/tmp/slice-"));if(!r)throw __fsErr("EACCES","mkdtemp",prefix);return r;},chmodSync:function(p,mode){return __slice_fs_chmod_sync(String(p),Number(mode)||0);},symlinkSync:function(target,p){var sp=String(p),r=__slice_fs_symlink_sync(String(target),sp);__notifyWatch(sp,"rename");return r;},opendirSync:function(p){var sp=String(p),names=m.readdirSync(sp,{withFileTypes:true}),idx=0;return{path:sp,readSync:function(){return idx0)throw __fsErr("ENOTEMPTY","rmdir",sp);var r=__slice_fs_rm_sync(sp);__notifyWatch(sp,"rename");return r;},copyFileSync:function(s,d,mode){var ss=String(s),sd=String(d);if(__slice_fs_stat_sync(ss)<0)throw __fsErr("ENOENT","copyfile",ss,sd);if((Number(mode)&1)&&m.existsSync(sd))throw __fsErr("EEXIST","copyfile",ss,sd);var r=__slice_fs_copy_file_sync(ss,sd);__notifyWatch(sd,"change");return r;},cpSync:function(src,dest,opts){var s=String(src).replace(/\/+$/,""),d=String(dest).replace(/\/+$/,""),o=opts||{};if(typeof o.filter==="function"&&!o.filter(s,d))return;if(!m.existsSync(s))throw __fsErr("ENOENT","cp",s);if(Boolean(__slice_fs_is_symlink_sync(s))&&!o.dereference){var linkTarget=m.readlinkSync(s);m.symlinkSync(linkTarget,d);return;}if(Boolean(__slice_fs_is_dir_sync(s))){if(o.recursive===false)throw __fsErr("EISDIR","cp",s);m.mkdirSync(d,{recursive:true});var entries=m.readdirSync(s);for(var i=0;i=0;i--){var w=__watchers[i];if(w._path===np&&(!listener||w._wfListener===listener))w.close();}},createReadStream:function(p,opts){__slice_ensure_shard(5);var st=__slice_builtins["node:stream"]||__slice_load_builtin("node:stream");var o=(typeof opts==="string")?{encoding:opts}:(opts||{});var enc=o.encoding||null,hwm=Number(o.highWaterMark)||65536,start=o.start!==undefined?Number(o.start):0,end=o.end!==undefined?Number(o.end):Infinity;var rs=new st.Readable({highWaterMark:hwm,encoding:enc});rs.path=String(p);rs.bytesRead=0;rs.pending=true;queueMicrotask(function(){try{if(rs.destroyed)return;if(!m.existsSync(rs.path)){rs.emit("error",__fsErr("ENOENT","open",rs.path));return;}rs.pending=false;rs.emit("open",3);rs.emit("ready");var raw=Buffer.from(__slice_fs_read_bytes_sync(rs.path));var sliceEnd=Math.min(raw.length,end===Infinity?raw.length:end+1);var view=raw.subarray(start,sliceEnd);for(var off=0;off0)waiters.shift().res({value:ev,done:false});else q.push(ev);});w.on("close",function(){done=true;while(waiters.length>0)waiters.shift().res({value:undefined,done:true});});return{[Symbol.asyncIterator]:function(){return{next:function(){if(q.length>0)return Promise.resolve({value:q.shift(),done:false});if(done||w._closed)return Promise.resolve({value:undefined,done:true});return new Promise(function(res,rej){waiters.push({res:res,rej:rej});});},return:function(){w.close();return Promise.resolve({value:undefined,done:true});}};}};}};fp.default=fp;fp.__esModule=true;m.promises=fp;m.default=m;m.__esModule=true;__slice_builtins["fs/promises"]=__slice_builtins["node:fs/promises"]=fp;return __slice_builtins["fs"]=__slice_builtins["node:fs"]=m;})();"#;
+const BUILTIN_FS_SNIPPET: &[u8] = br#"(function(){var __watchers=[],__fds=Object.create(null),__nextFd=10;function __fsErr(code,syscall,p,dest){var map={ENOENT:[-2,"no such file or directory"],EEXIST:[-17,"file already exists"],EISDIR:[-21,"illegal operation on a directory"],ENOTDIR:[-20,"not a directory"],ENOTEMPTY:[-39,"directory not empty"],EBADF:[-9,"bad file descriptor"],EACCES:[-13,"permission denied"],EINVAL:[-22,"invalid argument"]},info=map[code]||[-1,"unknown error"],msg=code+": "+info[1]+", "+syscall+(p!==undefined?" '"+p+"'":"")+(dest!==undefined?" -> '"+dest+"'":""),e=new Error(msg);e.code=code;e.errno=info[0];e.syscall=syscall;if(p!==undefined)e.path=String(p);if(dest!==undefined)e.dest=String(dest);return e;}function __getFd(fd,syscall){var e=__fds[Number(fd)];if(!e)throw __fsErr("EBADF",syscall);return e;}function __normW(p){return String(p||"").replace(/\\/g,"/").replace(/\/+$/,"")||"/";}function __notifyWatch(rawP,evType){if(__watchers.length===0)return;var np=__normW(rawP),sl=np.lastIndexOf("/"),dir=sl>0?np.slice(0,sl):"/",base=sl>=0?np.slice(sl+1):np;for(var i=0;i<__watchers.length;i++){var w=__watchers[i];if(w._closed)continue;var wp=w._path;if(np===wp||dir===wp||(w._rec&&np.indexOf(wp+"/")===0)){var rel=(np===wp)?base:(np.slice(wp.length+1)||base);w._emit(evType,rel);}}}function __fsData(d){if(typeof d==="string")return d;if(d instanceof Uint8Array)return d;if(d instanceof ArrayBuffer)return new Uint8Array(d);if(d&&d.buffer instanceof ArrayBuffer)return new Uint8Array(d.buffer,d.byteOffset||0,d.byteLength);return String(d);}function __toMs(t){if(t instanceof Date)return t.getTime();var n=Number(t);if(!Number.isFinite(n))return Date.now();return n<1e11?n*1000:n;}function __mkStats(sp,followSym,opts){var isSym=Boolean(__slice_fs_is_symlink_sync(sp)),sz=__slice_fs_stat_sync(sp);if(sz<0&&!(!followSym&&isSym)){if(opts&&typeof opts==="object"&&opts.throwIfNoEntry===false)return undefined;throw __fsErr("ENOENT",followSym?"stat":"lstat",sp);}if(sz<0)sz=0;var mt=__slice_fs_mtime_sync(sp),isDir=(!followSym&&isSym)?false:Boolean(__slice_fs_is_dir_sync(sp)),d=new Date(mt),bi=Boolean(opts&&typeof opts==="object"&&opts.bigint),vSz=bi?BigInt(Math.floor(sz)):sz,vMt=bi?BigInt(Math.floor(mt)):mt,vMode=bi?BigInt((!followSym&&isSym)?41471:(isDir?16877:33188)):((!followSym&&isSym)?41471:(isDir?16877:33188));return{size:vSz,mtimeMs:vMt,ctimeMs:vMt,atimeMs:vMt,birthtimeMs:vMt,mtime:d,ctime:d,atime:d,birthtime:d,mode:vMode,isFile:function(){return(!followSym&&isSym)?false:!isDir;},isDirectory:function(){return(!followSym&&isSym)?false:isDir;},isSymbolicLink:function(){return !followSym&&isSym;},isBlockDevice:function(){return false;},isCharacterDevice:function(){return false;},isFIFO:function(){return false;},isSocket:function(){return false;}};}function __cbWrap(syncFn){return function(){var args=[],cb=null;for(var i=0;i=0?n.slice(sl+1):n,par=sl>=0?((base==="/"?"":base)+"/"+n.slice(0,sl)):base,isD=Boolean(__slice_fs_is_dir_sync(fp)),isS=Boolean(__slice_fs_is_symlink_sync(fp));return{name:bn,parentPath:par,path:par,isFile:function(){return !isD&&!isS;},isDirectory:function(){return isD&&!isS;},isSymbolicLink:function(){return isS;},isBlockDevice:function(){return false;},isCharacterDevice:function(){return false;},isFIFO:function(){return false;},isSocket:function(){return false;}};});}if(o.encoding==="buffer"){__slice_ensure_shard(5);return names.map(function(n){return Buffer.from(n,"utf8");});}return names;},statSync:function(p,opts){return __mkStats(String(p),true,opts);},lstatSync:function(p,opts){return __mkStats(String(p),false,opts);},fstatSync:function(fd,opts){var e=__getFd(fd,"fstat");return __mkStats(e.path,true,opts);},openSync:function(p,flags,mode){var sp=String(p),fl=(flags===undefined||flags===null)?"r":String(flags),isR=fl==="r"||fl==="rs"||fl==="0",hasX=fl.indexOf("x")!==-1,isW=fl.charCodeAt(0)===119||fl==="1"||fl==="577",isA=fl.charCodeAt(0)===97||fl.indexOf("1024")!==-1,isPlus=fl.indexOf("+")!==-1||fl==="2";if(hasX&&m.existsSync(sp))throw __fsErr("EEXIST","open",sp);if(isR&&!isPlus){var raw=__slice_fs_read_bytes_sync(sp);if(raw===null)throw __fsErr("ENOENT","open",sp);}else if(isW){var wr=__slice_fs_write_file_sync(sp,new Uint8Array(0));if(wr===-21)throw __fsErr("EISDIR","open",sp);__notifyWatch(sp,"change");}else if(isA){if(!m.existsSync(sp))__slice_fs_write_file_sync(sp,new Uint8Array(0));else __slice_fs_append_file_sync(sp,new Uint8Array(0));}else if(isR&&isPlus){if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","open",sp);}var fd=__nextFd++;__fds[fd]={path:sp,flags:fl,mode:mode||438,pos:0,readable:isR||isPlus,writable:isW||isA||isPlus,append:isA};return fd;},closeSync:function(fd){__getFd(fd,"close");delete __fds[Number(fd)];},readSync:function(fd,buf,offOrOpts,len,pos){var e=__getFd(fd,"read");if(!e.readable)throw __fsErr("EBADF","read");var offset=0,length=buf?buf.byteLength:0,position=null;if(offOrOpts&&typeof offOrOpts==="object"){offset=Number(offOrOpts.offset)||0;length=offOrOpts.length!==undefined?Number(offOrOpts.length):(buf.byteLength-offset);position=offOrOpts.position!==undefined?offOrOpts.position:null;}else{offset=Number(offOrOpts)||0;length=len!==undefined?Number(len):(buf.byteLength-offset);position=pos!==undefined?pos:null;}var raw=__slice_fs_read_bytes_sync(e.path);if(!raw||raw===-21)return 0;var readPos=(position!==null&&position!==undefined&&Number(position)>=0)?Number(position):e.pos;if(readPos>=raw.byteLength||length<=0)return 0;var avail=Math.min(length,raw.byteLength-readPos);var target=new Uint8Array(buf.buffer||buf,(buf.byteOffset||0)+offset,avail);target.set(raw.subarray(readPos,readPos+avail),0);if(position===null||position===undefined||Number(position)<0)e.pos=readPos+avail;return avail;},writeSync:function(fd,bufOrStr,offOrPos,lenOrEnc,pos){var e=__getFd(fd,"write");if(!e.writable)throw __fsErr("EBADF","write");__slice_ensure_shard(5);var src,writePos=null;if(typeof bufOrStr==="string"){var enc=typeof lenOrEnc==="string"?lenOrEnc:(typeof offOrPos==="string"?offOrPos:"utf8");if(typeof offOrPos==="number")writePos=offOrPos;src=Buffer.from(bufOrStr,enc);}else{var u8=__fsData(bufOrStr),off=offOrPos!==undefined?Number(offOrPos):0,ln=lenOrEnc!==undefined?Number(lenOrEnc):(u8.byteLength-off);if(pos!==undefined&&pos!==null)writePos=Number(pos);src=u8.subarray(off,off+ln);}if(e.append){__slice_fs_append_file_sync(e.path,src);e.pos+=src.byteLength;__notifyWatch(e.path,"change");return src.byteLength;}var rawCur=__slice_fs_read_bytes_sync(e.path),cur=(rawCur&&rawCur!==-21)?rawCur:new Uint8Array(0);var p=(writePos!==null&&writePos>=0)?writePos:e.pos,nLen=Math.max(cur.byteLength,p+src.byteLength),out=new Uint8Array(nLen);out.set(cur,0);out.set(src,p);__slice_fs_write_file_sync(e.path,out);if(writePos===null||writePos<0)e.pos=p+src.byteLength;__notifyWatch(e.path,"change");return src.byteLength;},fsyncSync:function(fd){__getFd(fd,"fsync");},fdatasyncSync:function(fd){__getFd(fd,"fdatasync");},ftruncateSync:function(fd,len){var e=__getFd(fd,"ftruncate");return m.truncateSync(e.path,len);},futimesSync:function(fd,atime,mtime){var e=__getFd(fd,"futime");return m.utimesSync(e.path,atime,mtime);},fchmodSync:function(fd,mode){var e=__getFd(fd,"fchmod");return m.chmodSync(e.path,mode);},realpathSync:function(p){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","realpath",sp);var r=__slice_fs_realpath_sync(sp);if(!r)throw __fsErr("ENOENT","realpath",sp);return r;},readlinkSync:function(p,opts){var sp=String(p),r=__slice_fs_readlink_sync(sp);if(!r)throw __fsErr("ENOENT","readlink",sp);if(opts==="buffer"||(opts&&opts.encoding==="buffer")){__slice_ensure_shard(5);return Buffer.from(r,"utf8");}return r;},truncateSync:function(p,len){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","truncate",sp);var r=__slice_fs_truncate_sync(sp,len===undefined?0:Number(len));__notifyWatch(sp,"change");return r;},utimesSync:function(p,atime,mtime){var sp=String(p);if(__slice_fs_stat_sync(sp)<0)throw __fsErr("ENOENT","utime",sp);return __slice_fs_utimes_sync(sp,__toMs(atime),__toMs(mtime));},lutimesSync:function(p,atime,mtime){return m.utimesSync(p,atime,mtime);},mkdtempSync:function(prefix){var r=__slice_fs_mkdtemp_sync(String(prefix||"/tmp/slice-"));if(!r)throw __fsErr("EACCES","mkdtemp",prefix);return r;},chmodSync:function(p,mode){return __slice_fs_chmod_sync(String(p),Number(mode)||0);},symlinkSync:function(target,p){var sp=String(p),r=__slice_fs_symlink_sync(String(target),sp);__notifyWatch(sp,"rename");return r;},opendirSync:function(p){var sp=String(p),names=m.readdirSync(sp,{withFileTypes:true}),idx=0;return{path:sp,readSync:function(){return idx0)throw __fsErr("ENOTEMPTY","rmdir",sp);var r=__slice_fs_rm_sync(sp);__notifyWatch(sp,"rename");return r;},copyFileSync:function(s,d,mode){var ss=String(s),sd=String(d);if(__slice_fs_stat_sync(ss)<0)throw __fsErr("ENOENT","copyfile",ss,sd);if((Number(mode)&1)&&m.existsSync(sd))throw __fsErr("EEXIST","copyfile",ss,sd);var r=__slice_fs_copy_file_sync(ss,sd);__notifyWatch(sd,"change");return r;},cpSync:function(src,dest,opts){var s=String(src).replace(/\/+$/,""),d=String(dest).replace(/\/+$/,""),o=opts||{};if(typeof o.filter==="function"&&!o.filter(s,d))return;if(!m.existsSync(s))throw __fsErr("ENOENT","cp",s);if(Boolean(__slice_fs_is_symlink_sync(s))&&!o.dereference){var linkTarget=m.readlinkSync(s);m.symlinkSync(linkTarget,d);return;}if(Boolean(__slice_fs_is_dir_sync(s))){if(o.recursive===false)throw __fsErr("EISDIR","cp",s);m.mkdirSync(d,{recursive:true});var entries=m.readdirSync(s);for(var i=0;i=0;i--){var w=__watchers[i];if(w._path===np&&(!listener||w._wfListener===listener))w.close();}},createReadStream:function(p,opts){__slice_ensure_shard(5);var st=__slice_builtins["node:stream"]||__slice_load_builtin("node:stream");var o=(typeof opts==="string")?{encoding:opts}:(opts||{});var enc=o.encoding||null,hwm=Number(o.highWaterMark)||65536,start=o.start!==undefined?Number(o.start):0,end=o.end!==undefined?Number(o.end):Infinity;var rs=new st.Readable({highWaterMark:hwm,encoding:enc});rs.path=String(p);rs.bytesRead=0;rs.pending=true;queueMicrotask(function(){try{if(rs.destroyed)return;if(!m.existsSync(rs.path)){rs.emit("error",__fsErr("ENOENT","open",rs.path));return;}rs.pending=false;rs.emit("open",3);rs.emit("ready");var raw=Buffer.from(__slice_fs_read_bytes_sync(rs.path));var sliceEnd=Math.min(raw.length,end===Infinity?raw.length:end+1);var view=raw.subarray(start,sliceEnd);for(var off=0;off0)waiters.shift().res({value:ev,done:false});else q.push(ev);});w.on("close",function(){done=true;while(waiters.length>0)waiters.shift().res({value:undefined,done:true});});return{[Symbol.asyncIterator]:function(){return{next:function(){if(q.length>0)return Promise.resolve({value:q.shift(),done:false});if(done||w._closed)return Promise.resolve({value:undefined,done:true});return new Promise(function(res,rej){waiters.push({res:res,rej:rej});});},return:function(){w.close();return Promise.resolve({value:undefined,done:true});}};}};}};__fp.default=__fp;__fp.__esModule=true;Object.defineProperty(m,"promises",{value:__fp,writable:true,enumerable:true,configurable:true});Object.defineProperty(__slice_builtins,"fs/promises",{value:__fp,writable:true,enumerable:true,configurable:true});Object.defineProperty(__slice_builtins,"node:fs/promises",{value:__fp,writable:true,enumerable:true,configurable:true});}return __fp;}Object.defineProperty(m,"promises",{get:__getFp,enumerable:true,configurable:true});Object.defineProperty(__slice_builtins,"fs/promises",{get:__getFp,enumerable:true,configurable:true});Object.defineProperty(__slice_builtins,"node:fs/promises",{get:__getFp,enumerable:true,configurable:true});m.default=m;m.__esModule=true;return __slice_builtins["fs"]=__slice_builtins["node:fs"]=m;})();"#;
const BUILTIN_PATH_SNIPPET: &[u8] = br#"(function(){function __normPath(p){var s=String(p||"").replace(/\\/g,"/");if(s.length===0)return ".";var isAbs=s.charCodeAt(0)===47,trailing=s.length>1&&s.charCodeAt(s.length-1)===47,parts=s.split("/"),out=[];for(var i=0;i0&&out[out.length-1]!=="..")out.pop();else if(!isAbs)out.push("..");}else out.push(seg);}var res=(isAbs?"/":"")+out.join("/");if(!res)res=isAbs?"/":".";if(trailing&&res!=="/")res+="/";return res;}var m={sep:"/",delimiter:":",normalize:__normPath,isAbsolute:function(p){var s=String(p||"");return s.length>0&&(s.charCodeAt(0)===47||s.charCodeAt(0)===92||(s.length>2&&s.charCodeAt(1)===58));},join:function(){var parts=[];for(var i=0;i=-1&&!resolvedAbs;i--){var p=i>=0?String(arguments[i]||""):"/";if(!p)continue;p=p.replace(/\\/g,"/");resolved=p+"/"+resolved;resolvedAbs=p.charCodeAt(0)===47;}var norm=__normPath(resolved);return(norm.length>1&&norm.charCodeAt(norm.length-1)===47)?norm.slice(0,-1):norm;},dirname:function(p){var s=String(p||"").replace(/\\/g,"/").replace(/\/+$/,"");if(!s)return ".";var i=s.lastIndexOf("/");return i>0?s.slice(0,i):(i===0?"/":".");},basename:function(p,ext){var s=String(p||"").replace(/\\/g,"/").replace(/\/+$/,""),i=s.lastIndexOf("/"),b=i>=0?s.slice(i+1):s;return(ext&&b.endsWith(ext))?b.slice(0,b.length-ext.length):b;},extname:function(p){var b=m.basename(p),i=b.lastIndexOf(".");return i>0?b.slice(i):"";},relative:function(from,to){var f=m.resolve(from),t=m.resolve(to);if(f===t)return "";var fs=f.split("/").filter(Boolean),ts=t.split("/").filter(Boolean),len=Math.min(fs.length,ts.length),same=len;for(var i=0;i0){var w=this._waiters.shift();w.res({value:fmt,done:false});return true;}this._buf.push(fmt);this._drainFlowing();return this._buf.length0)this._enqueueFmt(rem);}this._eof=true;this._drainFlowing();return false;}var fmt=this._formatChunk(chunk);if(!this.readableObjectMode&&this._encoding&&typeof fmt==="string"&&fmt.length===0&&chunk&&((chunk.byteLength||chunk.length||0)>0))return true;return this._enqueueFmt(fmt);};Readable.prototype.unshift=function(chunk){if(chunk!==null&&chunk!==undefined){this._buf.unshift(this._formatChunk(chunk));this._drainFlowing();}return true;};Readable.prototype._drainFlowing=function(){if(this.readableFlowing===true){while(this._buf.length>0&&this.readableFlowing===true&&!this.destroyed){var c=this._buf.shift();this.emit("data",c);}if(this._buf.length===0&&!this._eof)this._kickRead();}else if(this._buf.length>0&&this.listenerCount("readable")>0){this.emit("readable");}if(this._eof&&this._buf.length===0&&!this._emittedEnd){this._emittedEnd=true;this.readable=false;this.readableEnded=true;while(this._waiters.length>0){this._waiters.shift().res({value:undefined,done:true});}var self=this;queueMicrotask(function(){if(!self.destroyed){self.emit("end");self.emit("close");}});}};Readable.prototype.read=function(){if(this._buf.length>0){var c=this._buf.shift();if(this._buf.length===0&&!this._eof)this._kickRead();if(this._eof&&this._buf.length===0)this._drainFlowing();return c;}if(!this._eof)this._kickRead();if(this._eof)this._drainFlowing();return null;};Readable.prototype.pause=function(){if(this.readableFlowing!==false){this.readableFlowing=false;this.emit("pause");}return this;};Readable.prototype.resume=function(){if(!this.readableEnded){this.readableFlowing=true;this.emit("resume");this._kickRead();this._drainFlowing();}return this;};Readable.prototype.isPaused=function(){return this.readableFlowing===false;};Readable.prototype[Symbol.asyncIterator]=function(){var self=this;this.readableFlowing=false;this._kickRead();return{next:function(){if(self.destroyed&&self.errored)return Promise.reject(self.errored);if(self._buf.length>0){var c=self._buf.shift();if(self._buf.length===0&&!self._eof)self._kickRead();return Promise.resolve({value:c,done:false});}if(self._eof||self.readableEnded||self.destroyed)return Promise.resolve({value:undefined,done:true});self._kickRead();return new Promise(function(res,rej){self._waiters.push({res:res,rej:rej});});},return:function(){self.destroy();return Promise.resolve({value:undefined,done:true});}};};Readable.from=function(iterable,opts){var r=new Readable(Object.assign({objectMode:true},opts||{}));queueMicrotask(function(){try{if(iterable&&typeof iterable[Symbol.asyncIterator]==="function"){var ait=iterable[Symbol.asyncIterator]();(function pump(){ait.next().then(function(step){if(r.destroyed)return;if(step.done){r.push(null);}else{r.push(step.value);pump();}},function(err){r.destroy(err);});})();}else{var arr=Array.from(iterable||[]);for(var i=0;i0)this._corked--;if(this._corked===0&&this._corkBuf.length>0){var q=this._corkBuf.slice();this._corkBuf=[];for(var i=0;i0){this._corkBuf.push({c:chunk,e:e,cb:cb,len:len});return ret;}this._doWrite(chunk,e,cb,len);return ret;};Writable.prototype.end=function(chunk,enc,cb){if(typeof chunk==="function"){cb=chunk;chunk=undefined;enc=undefined;}else if(typeof enc==="function"){cb=enc;enc=undefined;}if(chunk!==undefined&&chunk!==null)this.write(chunk,enc);while(this._corked>0)this.uncork();if(this.writableEnded){if(typeof cb==="function"){if(this.writableFinished)queueMicrotask(cb);else this.once("finish",cb);}return this;}this.writableEnded=true;this.writable=false;var self=this;function finishNow(err){if(err){self.destroy(err);if(typeof cb==="function")cb(err);return;}self.writableFinished=true;self.emit("finish");if(typeof cb==="function")cb(null);if(!self.destroyed&&!(self instanceof Duplex))self.emit("close");}if(typeof this._final==="function"){try{this._final(finishNow);}catch(e){finishNow(e);}}else{queueMicrotask(function(){finishNow(null);});}return this;};Writable.fromWeb=function(webWs,opts){var w=webWs.getWriter();return new Writable(Object.assign({},opts||{},{write:function(c,_e,cb){w.write(c).then(function(){cb(null);},function(e){cb(e);});},final:function(cb){w.close().then(function(){cb(null);},function(e){cb(e);});}}));};Writable.toWeb=function(nodeWs){__slice_ensure_shard(3);return new globalThis.WritableStream({write:function(c){return new Promise(function(res,rej){nodeWs.write(c,function(e){if(e)rej(e);else res();});});},close:function(){return new Promise(function(res,rej){nodeWs.end(function(e){if(e)rej(e);else res();});});},abort:function(r){nodeWs.destroy(r instanceof Error?r:new Error(String(r||"Aborted")));}});};function Duplex(opts){if(!(this instanceof Duplex))return new Duplex(opts);Readable.call(this,opts);Writable.call(this,opts);this.allowHalfOpen=!opts||opts.allowHalfOpen!==false;}Duplex.prototype=Object.create(Readable.prototype);Object.assign(Duplex.prototype,Writable.prototype);Duplex.prototype.constructor=Duplex;function Transform(opts){if(!(this instanceof Transform))return new Transform(opts);Duplex.call(this,opts);var o=opts||{};if(typeof o.transform==="function")this._transform=o.transform;if(typeof o.flush==="function")this._flush=o.flush;}Transform.prototype=Object.create(Duplex.prototype);Transform.prototype.constructor=Transform;Transform.prototype._transform=function(c,_e,cb){this.push(c);if(cb)cb(null);};Transform.prototype._write=function(chunk,enc,cb){var self=this;this._transform(chunk,enc,function(err,out){if(err){if(cb)cb(err);else self.destroy(err);return;}if(out!==undefined&&out!==null)self.push(out);if(cb)cb(null);});};Transform.prototype._final=function(cb){var self=this;if(typeof this._flush==="function"){this._flush(function(err,out){if(err){cb(err);return;}if(out!==undefined&&out!==null)self.push(out);self.push(null);cb(null);});}else{this.push(null);cb(null);}};function PassThrough(opts){if(!(this instanceof PassThrough))return new PassThrough(opts);Transform.call(this,opts);}PassThrough.prototype=Object.create(Transform.prototype);PassThrough.prototype.constructor=PassThrough;function finished(stream,opts,cb){if(typeof opts==="function"){cb=opts;opts={};}var o=opts||{},sig=o.signal,settled=false;function done(err){if(settled)return;settled=true;if(typeof cb==="function")cb(err||null);}if(sig&&sig.aborted){queueMicrotask(function(){done(sig.reason||new Error("AbortError"));});return function(){};}if(stream.destroyed||stream.writableFinished||stream.readableEnded){queueMicrotask(function(){done(stream.errored||null);});return function(){};}function onEnd(){done(null);}function onErr(e){done(e||new Error("Stream error"));}function onClose(){if(!stream.writableFinished&&stream.writableEnded===false&&stream.readableEnded===false&&stream.errored){done(stream.errored);}else{done(null);}}if(stream.once){stream.once("finish",onEnd);stream.once("end",onEnd);stream.once("error",onErr);stream.once("close",onClose);}if(sig&&typeof sig.addEventListener==="function"){sig.addEventListener("abort",function(){var ae=sig.reason||new Error("AbortError");if(stream.destroy)stream.destroy(ae);done(ae);});}return function(){if(stream.removeListener){stream.removeListener("finish",onEnd);stream.removeListener("end",onEnd);stream.removeListener("error",onErr);stream.removeListener("close",onClose);}};}function pipeline(){var args=Array.from(arguments),cb=typeof args[args.length-1]==="function"?args.pop():null;if(args.length===1&&Array.isArray(args[0]))args=args[0];var opts=(args.length>1&&args[args.length-1]&&typeof args[args.length-1]==="object"&&typeof args[args.length-1].pipe!=="function"&&typeof args[args.length-1].write!=="function")?args.pop():{};var sig=opts&&opts.signal,settled=false;function finishAll(err){if(settled)return;settled=true;if(err){for(var k=0;k0){var w=this._waiters.shift();w.res({value:fmt,done:false});return true;}this._buf.push(fmt);this._drainFlowing();return this._buf.length0)this._enqueueFmt(rem);}this._eof=true;this._drainFlowing();return false;}var fmt=this._formatChunk(chunk);if(!this.readableObjectMode&&this._encoding&&typeof fmt==="string"&&fmt.length===0&&chunk&&((chunk.byteLength||chunk.length||0)>0))return true;return this._enqueueFmt(fmt);};Readable.prototype.unshift=function(chunk){if(chunk!==null&&chunk!==undefined){this._buf.unshift(this._formatChunk(chunk));this._drainFlowing();}return true;};Readable.prototype._drainFlowing=function(){if(this.readableFlowing===true){while(this._buf.length>0&&this.readableFlowing===true&&!this.destroyed){var c=this._buf.shift();this.emit("data",c);}if(this._buf.length===0&&!this._eof)this._kickRead();}else if(this._buf.length>0&&this.listenerCount("readable")>0){this.emit("readable");}if(this._eof&&this._buf.length===0&&!this._emittedEnd){this._emittedEnd=true;this.readable=false;this.readableEnded=true;if(this._waiters){while(this._waiters.length>0){this._waiters.shift().res({value:undefined,done:true});}}var self=this;queueMicrotask(function(){if(!self.destroyed){self.emit("end");self.emit("close");}});}};Readable.prototype.read=function(){if(this._buf.length>0){var c=this._buf.shift();if(this._buf.length===0&&!this._eof)this._kickRead();if(this._eof&&this._buf.length===0)this._drainFlowing();return c;}if(!this._eof)this._kickRead();if(this._eof)this._drainFlowing();return null;};Readable.prototype.pause=function(){if(this.readableFlowing!==false){this.readableFlowing=false;this.emit("pause");}return this;};Readable.prototype.resume=function(){if(!this.readableEnded){this.readableFlowing=true;this.emit("resume");this._kickRead();this._drainFlowing();}return this;};Readable.prototype.isPaused=function(){return this.readableFlowing===false;};Readable.prototype[Symbol.asyncIterator]=function(){var self=this;this.readableFlowing=false;this._kickRead();return{next:function(){if(self.destroyed&&self.errored)return Promise.reject(self.errored);if(self._buf.length>0){var c=self._buf.shift();if(self._buf.length===0&&!self._eof)self._kickRead();return Promise.resolve({value:c,done:false});}if(self._eof||self.readableEnded||self.destroyed)return Promise.resolve({value:undefined,done:true});self._kickRead();return new Promise(function(res,rej){(self._waiters||(self._waiters=[])).push({res:res,rej:rej});});},return:function(){self.destroy();return Promise.resolve({value:undefined,done:true});}};};Readable.from=function(iterable,opts){var r=new Readable(Object.assign({objectMode:true},opts||{}));queueMicrotask(function(){try{if(iterable&&typeof iterable[Symbol.asyncIterator]==="function"){var ait=iterable[Symbol.asyncIterator]();(function pump(){ait.next().then(function(step){if(r.destroyed)return;if(step.done){r.push(null);}else{r.push(step.value);pump();}},function(err){r.destroy(err);});})();}else{var arr=Array.from(iterable||[]);for(var i=0;i0)this._corked--;if(this._corked===0&&this._corkBuf&&this._corkBuf.length>0){var q=this._corkBuf.slice();this._corkBuf=[];for(var i=0;i0){(this._corkBuf||(this._corkBuf=[])).push({c:chunk,e:e,cb:cb,len:len});return ret;}this._doWrite(chunk,e,cb,len);return ret;};Writable.prototype.end=function(chunk,enc,cb){if(typeof chunk==="function"){cb=chunk;chunk=undefined;enc=undefined;}else if(typeof enc==="function"){cb=enc;enc=undefined;}if(chunk!==undefined&&chunk!==null)this.write(chunk,enc);while(this._corked>0)this.uncork();if(this.writableEnded){if(typeof cb==="function"){if(this.writableFinished)queueMicrotask(cb);else this.once("finish",cb);}return this;}this.writableEnded=true;this.writable=false;var self=this;function finishNow(err){if(err){self.destroy(err);if(typeof cb==="function")cb(err);return;}self.writableFinished=true;self.emit("finish");if(typeof cb==="function")cb(null);if(!self.destroyed&&!(self instanceof Duplex))self.emit("close");}if(typeof this._final==="function"){try{this._final(finishNow);}catch(e){finishNow(e);}}else{queueMicrotask(function(){finishNow(null);});}return this;};Writable.fromWeb=function(webWs,opts){var w=webWs.getWriter();return new Writable(Object.assign({},opts||{},{write:function(c,_e,cb){w.write(c).then(function(){cb(null);},function(e){cb(e);});},final:function(cb){w.close().then(function(){cb(null);},function(e){cb(e);});}}));};Writable.toWeb=function(nodeWs){__slice_ensure_shard(3);return new globalThis.WritableStream({write:function(c){return new Promise(function(res,rej){nodeWs.write(c,function(e){if(e)rej(e);else res();});});},close:function(){return new Promise(function(res,rej){nodeWs.end(function(e){if(e)rej(e);else res();});});},abort:function(r){nodeWs.destroy(r instanceof Error?r:new Error(String(r||"Aborted")));}});};function Duplex(opts){if(!(this instanceof Duplex))return new Duplex(opts);Readable.call(this,opts);Writable.call(this,opts);this.allowHalfOpen=!opts||opts.allowHalfOpen!==false;}Duplex.prototype=Object.create(Readable.prototype);Object.assign(Duplex.prototype,Writable.prototype);Duplex.prototype.constructor=Duplex;function Transform(opts){if(!(this instanceof Transform))return new Transform(opts);Duplex.call(this,opts);var o=opts||{};if(typeof o.transform==="function")this._transform=o.transform;if(typeof o.flush==="function")this._flush=o.flush;}Transform.prototype=Object.create(Duplex.prototype);Transform.prototype.constructor=Transform;Transform.prototype._transform=function(c,_e,cb){this.push(c);if(cb)cb(null);};Transform.prototype._write=function(chunk,enc,cb){var self=this;this._transform(chunk,enc,function(err,out){if(err){if(cb)cb(err);else self.destroy(err);return;}if(out!==undefined&&out!==null)self.push(out);if(cb)cb(null);});};Transform.prototype._final=function(cb){var self=this;if(typeof this._flush==="function"){this._flush(function(err,out){if(err){cb(err);return;}if(out!==undefined&&out!==null)self.push(out);self.push(null);cb(null);});}else{this.push(null);cb(null);}};function PassThrough(opts){if(!(this instanceof PassThrough))return new PassThrough(opts);Transform.call(this,opts);}PassThrough.prototype=Object.create(Transform.prototype);PassThrough.prototype.constructor=PassThrough;function finished(stream,opts,cb){if(typeof opts==="function"){cb=opts;opts={};}var o=opts||{},sig=o.signal,settled=false;function done(err){if(settled)return;settled=true;if(typeof cb==="function")cb(err||null);}if(sig&&sig.aborted){queueMicrotask(function(){done(sig.reason||new Error("AbortError"));});return function(){};}if(stream.destroyed||stream.writableFinished||stream.readableEnded){queueMicrotask(function(){done(stream.errored||null);});return function(){};}function onEnd(){done(null);}function onErr(e){done(e||new Error("Stream error"));}function onClose(){if(!stream.writableFinished&&stream.writableEnded===false&&stream.readableEnded===false&&stream.errored){done(stream.errored);}else{done(null);}}if(stream.once){stream.once("finish",onEnd);stream.once("end",onEnd);stream.once("error",onErr);stream.once("close",onClose);}if(sig&&typeof sig.addEventListener==="function"){sig.addEventListener("abort",function(){var ae=sig.reason||new Error("AbortError");if(stream.destroy)stream.destroy(ae);done(ae);});}return function(){if(stream.removeListener){stream.removeListener("finish",onEnd);stream.removeListener("end",onEnd);stream.removeListener("error",onErr);stream.removeListener("close",onClose);}};}function pipeline(){var args=Array.from(arguments),cb=typeof args[args.length-1]==="function"?args.pop():null;if(args.length===1&&Array.isArray(args[0]))args=args[0];var opts=(args.length>1&&args[args.length-1]&&typeof args[args.length-1]==="object"&&typeof args[args.length-1].pipe!=="function"&&typeof args[args.length-1].write!=="function")?args.pop():{};var sig=opts&&opts.signal,settled=false;function finishAll(err){if(settled)return;settled=true;if(err){for(var k=0;k0)req.push(Buffer.from(bodyBytes));req.complete=true;req.push(null);});return req;}function Server(opts,listener){if(!(this instanceof Server))return new Server(opts,listener);EE.call(this);var fn=typeof opts==="function"?opts:listener;if(typeof fn==="function")this.on("request",fn);this.listening=false;this.maxHeadersCount=null;this.timeout=0;this.keepAliveTimeout=5000;this.headersTimeout=60000;this.requestTimeout=300000;this._port=0;this._host="127.0.0.1";}Server.prototype=Object.create(EE.prototype);Server.prototype.constructor=Server;Server.prototype.setTimeout=function(ms,cb){this.timeout=Number(ms)||0;if(typeof cb==="function")this.on("timeout",cb);return this;};Server.prototype.address=function(){return this.listening?{address:this._host,family:"IPv4",port:this._port}:null;};Server.prototype.ref=function(){return this;};Server.prototype.unref=function(){return this;};Server.prototype._dispatchActiveHttpBridge=function(){if(typeof __slice_http_is_active!=="function"||!__slice_http_is_active())return;var self=this,m=__slice_http_method(),p=__slice_http_path(),q=__slice_http_query(),url=q?(p+"?"+q):p,rawH=[];try{rawH=JSON.parse(__slice_http_headers_all());}catch(_e){}var bStr=__slice_http_body()||"";var req=__buildIncoming(m,url,rawH,bStr?Buffer.from(bStr,"utf8"):null);var res=new ServerResponse(req,function(sr,bodyBuf){var ct="text/plain;charset=UTF-8",outH=[],ks=Object.keys(sr._headers);for(var i=0;i0)res.push(resBody);res.complete=true;res.push(null);});});return;}__slice_ensure_shard(10);__slice_ensure_shard(11);var url=this.protocol+"//"+this.host+(this.port&&this.port!==80&&this.port!==443?(":"+this.port):"")+this.path;var fOpts={method:this.method,headers:hdrPairs};if(bodyBuf.length>0&&this.method!=="GET"&&this.method!=="HEAD")fOpts.body=bodyBuf.toString("utf8");globalThis.fetch(url,fOpts).then(function(fRes){if(fcb)fcb(null);var res=new IncomingMessage();res.statusCode=fRes.status;res.statusMessage=fRes.statusText||STATUS_CODES[fRes.status]||"OK";if(fRes.headers&&typeof fRes.headers.forEach==="function"){fRes.headers.forEach(function(val,key){var kl=String(key).toLowerCase();res.headers[kl]=String(val);res.rawHeaders.push(String(key),String(val));});}self.res=res;self.emit("response",res);return fRes.text().then(function(txt){if(txt&&txt.length>0)res.push(Buffer.from(txt,"utf8"));res.complete=true;res.push(null);});},function(err){if(fcb)fcb(null);self.emit("error",err instanceof Error?err:new Error(String(err)));});};function __mkHttpMod(defaultProto){var globalAgent=new Agent({keepAlive:true});var m={METHODS:METHODS,STATUS_CODES:STATUS_CODES,IncomingMessage:IncomingMessage,ServerResponse:ServerResponse,Server:Server,ClientRequest:function(a0,a1,a2){return new ClientRequest(defaultProto,a0,a1,a2);},Agent:Agent,globalAgent:globalAgent,maxHeaderSize:16384,createServer:function(opts,listener){return new Server(opts,listener);},request:function(a0,a1,a2){return new ClientRequest(defaultProto,a0,a1,a2);},get:function(a0,a1,a2){var req=new ClientRequest(defaultProto,a0,a1,a2);req.end();return req;},validateHeaderName:function(n){if(!n||!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(String(n)))throw new TypeError("ERR_INVALID_HTTP_TOKEN: Header name must be a valid HTTP token");},validateHeaderValue:function(n,v){if(v===undefined||/[\r\n\0]/.test(String(v)))throw new TypeError("ERR_INVALID_CHAR: Invalid character in header content");}};m.default=m;m.__esModule=true;return m;}var httpMod=__mkHttpMod("http:"),httpsMod=__mkHttpMod("https:");__slice_builtins["https"]=__slice_builtins["node:https"]=httpsMod;return __slice_builtins["http"]=__slice_builtins["node:http"]=httpMod;})();"#;
@@ -96,7 +96,7 @@ pub(crate) fn eval_lazy_builtin_module(
"buffer" | "node:buffer" => BUILTIN_BUFFER_SNIPPET,
"url" | "node:url" => BUILTIN_URL_SNIPPET,
"process" | "node:process" => {
- br#"(__slice_ensure_shard(18),__slice_builtins["process"]=__slice_builtins["node:process"]=globalThis.process)"#
+ br#"(__slice_ensure_shard(29),__slice_builtins["process"]=__slice_builtins["node:process"]=globalThis.process)"#
}
"timers" | "node:timers" => BUILTIN_TIMERS_SNIPPET,
"timers/promises" | "node:timers/promises" => {
@@ -106,7 +106,7 @@ pub(crate) fn eval_lazy_builtin_module(
br#"(function(){var __entries=[],__obs=[];function __notify(e){for(var i=0;i<__obs.length;i++){var o=__obs[i];if(o._active&&(o._types.indexOf(e.entryType)!==-1)){o._buf.push(e);if(!o._sched){o._sched=true;(function(ob){queueMicrotask(function(){ob._sched=false;if(!ob._active||ob._buf.length===0)return;var recs=ob._buf.slice();ob._buf=[];ob._cb({getEntries:function(){return recs;},getEntriesByName:function(n,t){return recs.filter(function(x){return x.name===String(n)&&(!t||x.entryType===String(t));});},getEntriesByType:function(t){return recs.filter(function(x){return x.entryType===String(t);});}},ob);});})(o);}}}}var perf=globalThis.performance||{now:function(){return Date.now()-1700000000000;}};perf.timeOrigin=1700000000000;perf.nodeTiming={name:"node",entryType:"node",startTime:0,duration:0,bootstrapComplete:0.05,environment:0.01,loopStart:0.05,loopExit:-1,idleTime:0};perf.mark=function(name,opts){var o=opts||{},st=o.startTime!==undefined?Number(o.startTime):perf.now(),e={name:String(name),entryType:"mark",startTime:st,duration:0,detail:o.detail!==undefined?o.detail:null,toJSON:function(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail};}};__entries.push(e);__notify(e);return e;};perf.measure=function(name,startOrOpts,endMark){var s=0,end=perf.now(),detail=null;if(startOrOpts&&typeof startOrOpts==="object"){if(startOrOpts.detail!==undefined)detail=startOrOpts.detail;if(startOrOpts.start!==undefined){if(typeof startOrOpts.start==="number")s=startOrOpts.start;else{for(var i=__entries.length-1;i>=0;i--)if(__entries[i].name===String(startOrOpts.start)){s=__entries[i].startTime;break;}}}if(startOrOpts.end!==undefined){if(typeof startOrOpts.end==="number")end=startOrOpts.end;else{for(var j=__entries.length-1;j>=0;j--)if(__entries[j].name===String(startOrOpts.end)){end=__entries[j].startTime;break;}}}else if(startOrOpts.duration!==undefined){end=s+Number(startOrOpts.duration);}}else{if(typeof startOrOpts==="string"){for(var k=__entries.length-1;k>=0;k--)if(__entries[k].name===startOrOpts){s=__entries[k].startTime;break;}}if(typeof endMark==="string"){for(var l=__entries.length-1;l>=0;l--)if(__entries[l].name===endMark){end=__entries[l].startTime;break;}}}var e={name:String(name),entryType:"measure",startTime:s,duration:end-s,detail:detail,toJSON:function(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail};}};__entries.push(e);__notify(e);return e;};perf.getEntries=function(){return __entries.slice();};perf.getEntriesByName=function(n,t){return __entries.filter(function(e){return e.name===String(n)&&(!t||e.entryType===String(t));});};perf.getEntriesByType=function(t){return __entries.filter(function(e){return e.entryType===String(t);});};perf.clearMarks=function(n){__entries=__entries.filter(function(e){return e.entryType!=="mark"||(n!==undefined&&e.name!==String(n));});};perf.clearMeasures=function(n){__entries=__entries.filter(function(e){return e.entryType!=="measure"||(n!==undefined&&e.name!==String(n));});};perf.timerify=function(fn){if(typeof fn!=="function")throw new TypeError("timerify requires a function");var w=function(){var t0=perf.now();try{return fn.apply(this,arguments);}finally{var t1=perf.now(),e={name:fn.name||"anonymous",entryType:"function",startTime:t0,duration:t1-t0,detail:Array.from(arguments)};__entries.push(e);__notify(e);}};Object.defineProperty(w,"name",{value:fn.name,configurable:true});return w;};perf.toJSON=function(){return{timeOrigin:this.timeOrigin,nodeTiming:this.nodeTiming};};function PerformanceObserver(cb){if(typeof cb!=="function")throw new TypeError("PerformanceObserver callback must be a function");this._cb=cb;this._types=[];this._buf=[];this._active=false;this._sched=false;}PerformanceObserver.supportedEntryTypes=["mark","measure","function","node"];PerformanceObserver.prototype.observe=function(opts){var o=opts||{};var ts=Array.isArray(o.entryTypes)?o.entryTypes:(o.type?[o.type]:[]);this._types=ts.map(String);this._active=true;if(__obs.indexOf(this)===-1)__obs.push(this);if(o.buffered){for(var i=0;i<__entries.length;i++){if(this._types.indexOf(__entries[i].entryType)!==-1)this._buf.push(__entries[i]);}}};PerformanceObserver.prototype.disconnect=function(){this._active=false;this._buf=[];};PerformanceObserver.prototype.takeRecords=function(){var r=this._buf.slice();this._buf=[];return r;};function monitorEventLoopDelay(){return{enable:function(){return true;},disable:function(){return true;},reset:function(){},percentile:function(){return 0;},percentiles:new Map(),min:0,max:0,mean:0,stddev:0,count:0,exceeds:0};}var m={performance:perf,PerformanceObserver:PerformanceObserver,monitorEventLoopDelay:monitorEventLoopDelay,createHistogram:monitorEventLoopDelay,constants:{NODE_PERFORMANCE_GC_MAJOR:4,NODE_PERFORMANCE_GC_MINOR:1}};m.default=m;m.__esModule=true;return __slice_builtins["perf_hooks"]=__slice_builtins["node:perf_hooks"]=m;})()"#
}
"tty" | "node:tty" => {
- br#"(function(){__slice_ensure_shard(18);function ReadStream(){return globalThis.process.stdin;}function WriteStream(fd){return fd===2?globalThis.process.stderr:globalThis.process.stdout;}var m={isatty:function(){return false;},ReadStream:ReadStream,WriteStream:WriteStream};m.default=m;m.__esModule=true;return __slice_builtins["tty"]=__slice_builtins["node:tty"]=m;})()"#
+ br#"(function(){__slice_ensure_shard(29);function ReadStream(){return globalThis.process.stdin;}function WriteStream(fd){return fd===2?globalThis.process.stderr:globalThis.process.stdout;}var m={isatty:function(){return false;},ReadStream:ReadStream,WriteStream:WriteStream};m.default=m;m.__esModule=true;return __slice_builtins["tty"]=__slice_builtins["node:tty"]=m;})()"#
}
"module" | "node:module" => {
br#"(function(){var __BM=["assert","assert/strict","async_hooks","buffer","child_process","cluster","console","crypto","dgram","diagnostics_channel","dns","dns/promises","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","querystring","readline","readline/promises","stream","stream/promises","stream/web","string_decoder","test","timers","timers/promises","tls","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib"];function isBuiltin(id){var s=String(id||"");if(s.slice(0,5)==="node:")return __BM.indexOf(s.slice(5))!==-1;if(s.slice(0,6)==="slice:"||s.slice(0,11)==="cloudflare:")return true;return __BM.indexOf(s)!==-1;}function createRequire(filename){var req=function(id){return globalThis.__slice_cjs_require(id);};req.resolve=function(id){return String(id);};req.resolve.paths=function(){return["/node_modules"];};req.cache=Object.create(null);req.main={id:String(filename||"/index.js"),filename:String(filename||"/index.js"),exports:{}};return req;}function Module(id,parent){this.id=id||"";this.filename=id||"";this.exports={};this.parent=parent||null;this.loaded=false;this.children=[];}Module.builtinModules=__BM;Module.isBuiltin=isBuiltin;Module.createRequire=createRequire;Module._load=function(id){return globalThis.__slice_cjs_require(id);};Module.default=Module;Module.__esModule=true;return __slice_builtins["module"]=__slice_builtins["node:module"]=Module;})()"#
diff --git a/crates/slice-engine/src/runtime/boa_realm.rs b/crates/slice-engine/src/runtime/boa_realm.rs
index 25f272b..75f00f0 100644
--- a/crates/slice-engine/src/runtime/boa_realm.rs
+++ b/crates/slice-engine/src/runtime/boa_realm.rs
@@ -15,6 +15,19 @@ pub(crate) const DIRTY_WORKERS: u8 = 1 << 5;
pub(crate) const DIRTY_WASM: u8 = 1 << 6;
pub(crate) const DIRTY_PROCESS: u8 = 1 << 7;
+pub(crate) const EXEC_DIRTY_EXIT: u8 = 1 << 0;
+pub(crate) const EXEC_DIRTY_REJECTIONS: u8 = 1 << 1;
+pub(crate) const EXEC_DIRTY_UNCAUGHT: u8 = 1 << 2;
+pub(crate) const EXEC_DIRTY_CHILD_PROC: u8 = 1 << 3;
+pub(crate) const EXEC_DIRTY_ARGV: u8 = 1 << 4;
+
+pub(crate) const REALM_CTL_RESET_MT: i32 = 0;
+pub(crate) const REALM_CTL_SET_DET_MODE: i32 = 1;
+pub(crate) const REALM_CTL_SYNC_ENV: i32 = 2;
+pub(crate) const REALM_CTL_SET_NEXT_TICK: i32 = 3;
+pub(crate) const REALM_CTL_RESET_WU: i32 = 4;
+pub(crate) const REALM_CTL_DISPATCH_HTTP_BRIDGE: i32 = 5;
+
#[derive(Default, Clone)]
pub(crate) struct ActiveBoaHttpReq {
pub(crate) active: bool,
@@ -30,10 +43,12 @@ pub(crate) struct ActiveBoaHttpReq {
pub(crate) struct WarmBoaRealm {
pub(crate) ctx: boa_engine::Context,
pub(crate) loaded_bundles: FxHashMap,
+ pub(crate) compiled_scripts: FxHashMap,
pub(crate) ses_check_fn: Option,
pub(crate) ensure_shard_fn: Option,
pub(crate) init_worker_self_fn: Option,
pub(crate) drain_wu_fn: Option,
+ pub(crate) ctl_fn: Option,
pub(crate) loaded_shards_mask: u32,
}
@@ -101,6 +116,10 @@ thread_local! {
const { std::cell::RefCell::new(Vec::new()) };
pub(crate) static BOA_DIRTY_SUBSYSTEMS: std::cell::Cell =
const { std::cell::Cell::new(0) };
+ pub(crate) static BOA_EXEC_DIRTY: std::cell::Cell =
+ const { std::cell::Cell::new(0) };
+ pub(crate) static BOA_CUSTOM_ARGV: std::cell::RefCell