nish 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +8 -7
  2. package/docs/AI.md +75 -14
  3. package/docs/INSTALL.md +92 -71
  4. package/package.json +12 -7
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/core/arrays.d.ts +4 -0
  8. package/runtime/core/arrays.mjs +33 -0
  9. package/runtime/nish.d.ts +1045 -512
  10. package/runtime/nish.h +53 -6
  11. package/runtime/page.d.ts +53 -0
  12. package/runtime/page.mjs +146 -0
  13. package/runtime/runtime-async.c +740 -0
  14. package/runtime/runtime-cross.c +2 -1
  15. package/runtime/runtime-region.c +85 -7
  16. package/runtime/runtime-text.c +1068 -0
  17. package/runtime/runtime-wasm.c +65 -9
  18. package/runtime/runtime.c +50 -961
  19. package/runtime/vite.mjs +48 -11
  20. package/scripts/build.sh +231 -31
  21. package/scripts/fuzz.sh +59 -8
  22. package/scripts/gen-pow10-table.py +1 -1
  23. package/scripts/postinstall.mjs +8 -7
  24. package/scripts/size-report.sh +2 -2
  25. package/scripts/undocumented.txt +14 -0
  26. package/std/LICENSE-fdlibm +8 -0
  27. package/std/README.md +109 -82
  28. package/std/array.ts +266 -0
  29. package/std/bytes.ts +23 -19
  30. package/std/compress/checksum.ts +1 -1
  31. package/std/crypto/aes.ts +48 -43
  32. package/std/crypto/base64url.ts +7 -5
  33. package/std/crypto/bcrypt-batch.ts +13 -13
  34. package/std/crypto/bcrypt.ts +33 -27
  35. package/std/crypto/chacha20poly1305.ts +16 -14
  36. package/std/crypto/ed25519.ts +19 -16
  37. package/std/crypto/hmac.ts +7 -6
  38. package/std/crypto/jwt.ts +23 -20
  39. package/std/crypto/p256.ts +63 -56
  40. package/std/crypto/p384.ts +23 -20
  41. package/std/crypto/pki.ts +18 -15
  42. package/std/crypto/rsa.ts +23 -19
  43. package/std/crypto/x25519.ts +11 -10
  44. package/std/crypto/x509.ts +69 -62
  45. package/std/host/ring.ts +124 -0
  46. package/std/host/text.ts +86 -0
  47. package/std/json-equal.ts +12 -11
  48. package/std/json-number.ts +12 -12
  49. package/std/json-tokenizer.ts +26 -22
  50. package/std/json-typed.ts +92 -78
  51. package/std/json-value.ts +38 -33
  52. package/std/json.ts +32 -28
  53. package/std/math.ts +743 -41
  54. package/std/net/dns-resolver.ts +46 -6
  55. package/std/net/dns.ts +50 -13
  56. package/std/net/fetch.ts +1744 -295
  57. package/std/net/handler.ts +30 -0
  58. package/std/net/hpack.ts +29 -26
  59. package/std/net/http-compress.ts +42 -28
  60. package/std/net/http-fields.ts +19 -4
  61. package/std/net/http1-client-codec.ts +29 -25
  62. package/std/net/http1-codec.ts +62 -91
  63. package/std/net/http1-server.ts +79 -57
  64. package/std/net/http2-frame.ts +17 -16
  65. package/std/net/http2-tls.ts +17 -15
  66. package/std/net/http2.ts +67 -54
  67. package/std/net/http3-frame.ts +11 -10
  68. package/std/net/http3-server.ts +36 -35
  69. package/std/net/http3.ts +70 -58
  70. package/std/net/postgres-async.ts +1005 -0
  71. package/std/net/postgres.ts +185 -164
  72. package/std/net/prefork.ts +38 -34
  73. package/std/net/qpack.ts +15 -14
  74. package/std/net/quic-conn-ack.ts +1 -0
  75. package/std/net/quic-conn-cid.ts +11 -0
  76. package/std/net/quic-conn-params.ts +41 -14
  77. package/std/net/quic-datagram.ts +7 -0
  78. package/std/net/quic-frame.ts +48 -12
  79. package/std/net/quic-listener.ts +61 -44
  80. package/std/net/quic-packet.ts +71 -52
  81. package/std/net/quic-recovery.ts +59 -21
  82. package/std/net/quic-stream.ts +83 -55
  83. package/std/net/quic.ts +204 -152
  84. package/std/net/serve.ts +763 -0
  85. package/std/net/tls/client.ts +1 -0
  86. package/std/net/tls/codec.ts +81 -12
  87. package/std/net/tls/record-client.ts +30 -18
  88. package/std/net/tls/record-server.ts +74 -46
  89. package/std/net/tls/record.ts +33 -24
  90. package/std/net/tls/ticket.ts +2 -0
  91. package/std/net/tls/verify.ts +8 -7
  92. package/std/net/tls-tcp.ts +58 -50
  93. package/std/net/tls.ts +55 -43
  94. package/std/net/url.ts +12 -9
  95. package/std/net/websocket.ts +23 -19
  96. package/std/net/webtransport.ts +24 -18
  97. package/std/random.ts +8 -6
  98. package/std/regex.ts +70 -59
  99. package/std/sync/ring.ts +24 -21
  100. package/std/sync/shm.ts +9 -7
  101. package/std/term-io.ts +17 -14
  102. package/std/term-probe.ts +11 -10
  103. package/std/term-rate.ts +71 -61
  104. package/std/term.ts +73 -59
  105. package/std/text.ts +242 -15
  106. package/std/threads.ts +19 -15
  107. package/std/yaml-json.ts +17 -15
  108. package/std/yaml-write.ts +21 -14
package/README.md CHANGED
@@ -175,7 +175,7 @@ ship in the npm package, and [llms.txt](llms.txt) indexes them.
175
175
  | Control flow | `if`/`else`, `while`, `do`, `for`, `for...of` (arrays, `Map` keys and values, `Set`), `switch` (exhaustive over a union's tag, a clause may fall into the next), `break`/`continue`, labelled or not, boolean-only conditions, definite return, unreachable-code errors | [Statements](docs/LANGUAGE.md#statements) |
176
176
  | Expressions | `+ - * / %` (integer `/` and `%` checked: zero divisor or `MIN / -1` panics), shifts and bitwise operators, numeric-only ordering, `=== !==` (strings by content), `&& \|\|`, `?:`, `??` on a `T \| null` and a `?.` chain that ends in `??`, `op=`, `++`/`--`, template literals, contextual numeric literals | [Expressions](docs/LANGUAGE.md#expressions) |
177
177
  | Strings | immutable UTF-8 (`.length` is the byte length), literals as constant data, `+`, `===`, templates, `console.log` | [Builtins](docs/LANGUAGE.md#builtins), [Semantics](docs/LANGUAGE.md#semantics-decisions) |
178
- | Arrays | `T[]` with one element type, literals, `new Array<T>(n)` zero-filled, bounds-checked `a[i]` (panic, or `uncheckedGet` from `nish:unsafe`), `.length`, `push`/`pop`, `set`/`fill`, `for...of`; arrays of records stored contiguously and fixed-length array fields inline | [Arrays](docs/LANGUAGE.md#array-literals) |
178
+ | Arrays | `T[]` with one element type, literals, `new Array<T>(n)` zero-filled, bounds-checked `a[i]` (panic, or `uncheckedGet` from `nish:unsafe`), `.length`, `push`/`pop`, `set`/`fill`, `sort`, `map`/`filter`/`some`/`every`/`findIndex`/`slice`, `for...of`; arrays of records stored contiguously and fixed-length array fields inline | [Arrays](docs/LANGUAGE.md#array-literals) |
179
179
  | `Map` and `Set` | the global `Map<K, V>` and `Set<T>`, insertion-ordered, one probe per `get`/`set`/`has`/`delete`; `get` is `V \| undefined` and narrowed as TypeScript does | [`Map` and `Set`](docs/LANGUAGE.md#map-and-set) |
180
180
  | Classes and interfaces | LLVM structs with clang's layout, constructors, methods, `readonly`, definite assignment, object literals, `implements` by identical layout; no inheritance | [Classes](docs/LANGUAGE.md#classes) |
181
181
  | Generics | generic functions, classes, interfaces and methods by monomorphisation: one specialised `define` per instantiation, type arguments inferred at a call and written after `new` or in an annotation, `<T extends Shape>` constraints, exported instantiations callable from C and JavaScript as `nish_gen_identity_i32` | [Generic functions](docs/LANGUAGE.md#generic-functions) |
@@ -393,7 +393,7 @@ recompile of the runtime. `-o`, `--link`, `--target`, the `--emit-*` sidecars an
393
393
  errors there, and performance warnings are not printed, because stderr belongs
394
394
  to the program.
395
395
 
396
- Without `--link`, build the IR yourself: `clang add.ll examples/main.c runtime/runtime.c runtime/runtime-os.c -o app`
396
+ Without `--link`, build the IR yourself: `clang add.ll examples/main.c runtime/runtime.c runtime/runtime-text.c runtime/runtime-os.c -ffp-contract=off -o app`
397
397
  (a program that uses threads, the host calls or `nish:net` also names
398
398
  `runtime/runtime-parallel.c`, `runtime-host.c` or `runtime-net.c`; the
399
399
  `overriding the module target triple` warning is harmless: the IR is
@@ -424,13 +424,14 @@ dynamically linked (`npm run size-report`):
424
424
  | `wasm` | 279 | Freestanding `wasm32` module, every function exported, stripped. |
425
425
  | `wasi` | 42,228 (`argv.ts`) | `wasm32-wasi` command module: the runtime linked against wasi-libc, `_start` runs `main`; needs a WASI sysroot ([INSTALL.md](docs/INSTALL.md#wasi-optional-for---profile-wasi)). |
426
426
 
427
- `hello.ts` with `--link` is 4,712 bytes. The runtime is sixteen translation units
427
+ `hello.ts` with `--link` is 4,712 bytes. The runtime is seventeen translation units
428
428
  with a measured ceiling each, so that the core does not grow every time the
429
429
  language reaches further into the operating system, and section GC drops
430
- whatever a program does not call: `runtime.c` is the 3,606 bytes every program
431
- touches (one chunked bump arena with O(1) reset and mark/release, strings,
432
- JavaScript-exact number formatting, string parsing, `Math.random`,
433
- `process.argv`, array growth, the panic paths), `runtime-os.c` the 1,530 bytes
430
+ whatever a program does not call: `runtime.c` is the 1,723 bytes every program
431
+ touches (one chunked bump arena with O(1) reset and mark/release, string
432
+ parsing, `Math.random`, `process.argv`, array growth, the panic paths),
433
+ `runtime-text.c` the 1,787 bytes of strings and JavaScript-exact number
434
+ formatting, which a wasm module links too, `runtime-os.c` the 1,530 bytes
434
435
  that wrap a system call (exit, files, directories, subprocesses, the
435
436
  environment, the clock), and `runtime-parallel.c`, `runtime-cross.c`,
436
437
  `runtime-host.c`, `runtime-net.c`, `runtime-simd.c`, `runtime-aes.c`,
package/docs/AI.md CHANGED
@@ -49,7 +49,7 @@ stdout, nothing on stderr, every field 1-based with `endLine`/`endColumn`
49
49
  exclusive:
50
50
 
51
51
  ```json
52
- {"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":20,"severity":"error","code":"NL2249","message":"Unknown method `map` on i32[] (supported: push, pop, indexOf, join, set, fill, sort)"}
52
+ {"file":"p.ts","line":3,"column":17,"endLine":3,"endColumn":23,"severity":"error","code":"NL2249","message":"Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, slice)"}
53
53
  ```
54
54
 
55
55
  - **Key on `code`, never on `message`.** A code is a promise: `NL2249` means
@@ -165,7 +165,8 @@ rejects. This table is the highest-value part of the page.
165
165
  | `x == y` | `Loose equality is forbidden` | `x === y` |
166
166
  | `throw new Error(m)` | `` `throw` is forbidden `` | `return Err(m)`, or `panic(m)` to end the process |
167
167
  | `try { … } catch { … }` | `` `try`/`catch`/`finally` is forbidden `` | `Result<T, E>` and `isErr()` |
168
- | `xs.map(f)`, `.filter`, `.reduce`, `.forEach`, `.slice`, `.shift` | `` Unknown method `map` on i32[] (supported: push, pop, indexOf, join, set, fill, sort) `` | a `for` loop, or a top-level `map(xs, f)` with a [function parameter](#function-parameters) |
168
+ | `xs.reduce(f)`, `.forEach`, `.shift` | `` Unknown method `reduce` on i32[] (supported: push, pop, indexOf, join, set, fill, sort, map, filter, some, every, findIndex, slice) `` | a `for` loop; `map`, `filter`, `some`, `every`, `findIndex` and `slice` work, with a one- or two-parameter callback |
169
+ | `xs.find(f)` | `` `find` is not supported: TypeScript types its answer `T \| undefined` … `` (NL2697) | `const i = xs.findIndex(f); if (i >= 0) { ... xs[i] ... }` |
169
170
  | `s.toUpperCase()`, `s.split()`, `s.trim()`, `s.replace()` | `` Unknown method … on string `` | index bytes with `charCodeAt` / `substring` |
170
171
  | `a?.b`, `a ?? b` | `?.` only in a chain that ends in `??`; `??` only on a `T \| null`, a chain or `m.get(k)` | `a?.b ?? d`, `a ?? d`, or `if (a !== null)` first |
171
172
  | `x as T`, `<T>x`, `x satisfies T` | `Unsupported expression in Phase 1: AsExpression` (to `any` or `unknown`: `` Type assertion to `any` is forbidden ``); `x!` is a syntax error | there are no casts; `implements` is the only widening |
@@ -861,8 +862,9 @@ export const main = (): i32 => {
861
862
  (`` The arrow reads `k`, a `let` of the function it is written in: ... bind the value to a `const` before the call ``),
862
863
  read `this` (bind `const self = this`), or read a function-typed parameter
863
864
  of its function. An arrow inside another arrow, or given to a method, a
864
- constructor, `expose` or `exposeWith`, captures nothing; `xs.sort(cmp)`'s
865
- comparator is the exception, and captures as an arrow argument does.
865
+ constructor, `expose` or `exposeWith`, captures nothing; the callbacks of
866
+ the array methods `sort`, `map`, `filter`, `some`, `every` and `findIndex`
867
+ are the exception, and capture as an arrow argument does.
866
868
  - **The argument's type must match exactly**: `(x: i32) => i64` for a
867
869
  `(x: i32) => i32` parameter is refused. A generic function cannot be passed
868
870
  by name — write `(x) => identity(x)`.
@@ -1484,8 +1486,8 @@ export const main = (): i32 => {
1484
1486
  `--target`** (NL2666; `--target wasm32-wasi` keeps it): there a function the page
1485
1487
  supplies is imported from a host module, the page's own TypeScript file
1486
1488
  named by `--host`, and becomes a wasm import from module `host`. Only
1487
- scalars, enums and `HostHandle<"kind">` (a nominal `i32` for an object the
1488
- page keeps) cross; `import { Canvas, fill } from "./host.ts"`, no `type`
1489
+ scalars, enums, `HostHandle<"kind">` (a nominal `i32` for an object the
1490
+ page keeps) and buffer windows (an array, then `at: u32, n: u32`) cross; `import { Canvas, fill } from "./host.ts"`, no `type`
1489
1491
  modifier.
1490
1492
  - **A class with a `CPtr` field is a handle class: open one with `using`.**
1491
1493
  `using f = new File(p)` closes `f` once at every exit of its block (falling
@@ -1520,12 +1522,51 @@ emitted and no initialiser runs** — every use lowers to the value itself.
1520
1522
  array, class or interface constant would need an allocation, and there is no
1521
1523
  code to run it.
1522
1524
  - The initialiser is literals, other constants (declared anywhere, or
1523
- imported), and arithmetic over them. A call, a `new`, a local — anything else
1524
- — is rejected.
1525
+ imported), and arithmetic over them. A call, a local — anything else — is
1526
+ rejected. The one `new` allowed is module storage, below.
1525
1527
  - Folding uses the language's own arithmetic, so an overflowing fold is an
1526
1528
  error rather than a wrap, and `1 / 0` in a constant is refused at compile
1527
1529
  time.
1528
1530
 
1531
+ ### Module storage
1532
+
1533
+ ```ts nish:ok
1534
+ const SCORES = new Int32Array(4);
1535
+
1536
+ const sum = (xs: Int32Array): i32 => {
1537
+ let total: i32 = 0;
1538
+ for (let i = 0; i < xs.length; i++) {
1539
+ total += xs[i];
1540
+ }
1541
+ return total;
1542
+ };
1543
+
1544
+ export const main = (): i32 => {
1545
+ SCORES[0] = 30;
1546
+ SCORES[3] = 4;
1547
+ console.log(`${sum(SCORES)} ${SCORES[1]}`); // 34 0
1548
+ return 0;
1549
+ };
1550
+ ```
1551
+
1552
+ A top-level `const` holding `new Array<T>(n)` or a typed-array `new` of a
1553
+ constant length is **module storage**: a static, zero-filled array that keeps
1554
+ its values between calls, with no initialiser that runs. It is the only
1555
+ state a module keeps (there is no top-level `let`).
1556
+
1557
+ - The length is a constant from 1 to 16,777,216, at most 256 MiB in all. The element is pointer-free:
1558
+ a number, `boolean`, an enum or range whose zero is a member, a
1559
+ `HostHandle`, or an interface no class implements with fields of those.
1560
+ - **It never grows or moves**: no method call on it (`push`, `pop`, `sort`,
1561
+ NL2688) and no `length =`. Keep a count beside it.
1562
+ - **Its name is a place, not a value**: index it and read `length`; never bind,
1563
+ store or return it. Lend it only to a parameter spelled with a typed-array
1564
+ name (`xs: Int32Array`) or to a host function's buffer window. A record
1565
+ element is a place too: `bodies[i].x = 1` and `bodies[i] = bodies[j]` are
1566
+ fine, `const b = bodies[i]` is refused; pass the index.
1567
+ - Under `--profile wasm-host` the page reads and writes it through `layout`
1568
+ and `views()` in the `.d.ts`. The rules: `LANGUAGE.md` → "Module storage".
1569
+
1529
1570
  ### Classes and interfaces
1530
1571
 
1531
1572
  ```ts nish:ok
@@ -2206,7 +2247,10 @@ answers `a` — the same order Node gives; the comparator is required (`a.sort()
2206
2247
  is refused, since JavaScript would compare strings), a readonly array and
2207
2248
  `process.argv` are refused, `a - b` panics on `i32` values a full range apart
2208
2249
  (compare with `a > b ? 1 : a < b ? -1 : 0` there), and the comparator may read the caller's `const` locals and parameters but not
2209
- a `let`, as any arrow argument may. That is every array method there is. A
2250
+ a `let`, as any arrow argument may. `a.map(f)`, `a.filter(f)`, `a.some(f)`,
2251
+ `a.every(f)`, `a.findIndex(f)` and `a.slice(start, end)` answer as in JavaScript
2252
+ (a callback takes the element, and the index if it names two parameters). That is
2253
+ every array method there is. A
2210
2254
  window into a buffer is `(buf, offset, length)`; there is no view type.
2211
2255
 
2212
2256
  **Strings.** `s.length` (**bytes**), `s.charCodeAt(i)` (the byte, bounds-checked),
@@ -2717,15 +2761,16 @@ the module (NL4015).
2717
2761
 
2718
2762
  ## Recipes for what is missing
2719
2763
 
2720
- **Iterate and transform** — there is no `map`, and no function to pass it:
2764
+ **Iterate and accumulate** — there is no `reduce` or `forEach` (`map`, `filter`, `some`, `every`, `findIndex` and `slice` work); fold in a loop:
2721
2765
 
2722
2766
  ```ts nish:ok-body
2723
2767
  const xs: i32[] = [1, 2, 3];
2724
- const doubled: i32[] = [];
2725
- for (const x of xs) {
2726
- doubled.push(x * 2);
2768
+ const doubled = xs.map((x) => x * 2);
2769
+ let sum = 0;
2770
+ for (const x of doubled) {
2771
+ sum += x;
2727
2772
  }
2728
- console.log(`${doubled.length}`);
2773
+ console.log(`${sum}`);
2729
2774
  ```
2730
2775
 
2731
2776
  **Convert a number to a string** — there is no `toString` and no `String()`:
@@ -2869,6 +2914,22 @@ event waits for `end`. The batcher reads no clock: when to take is the loop's ch
2869
2914
  guide's [PostgreSQL page](guide/using-nish/postgres.md#batching-keyed-reads)
2870
2915
  its walk-through.)
2871
2916
 
2917
+ **Serve HTTP from an `async` program** — there is no `app.get(path, cb)`:
2918
+ `serve(port, router, limits, handle)` from `nish/net/serve` runs the loop and
2919
+ calls your one `async function handle(req: Request): Promise<Response>` in a
2920
+ task of its own per request, so `handle` may `await sleep(ms)` or a socket
2921
+ while others are answered. Add routes with `router.add(method, pattern)` and
2922
+ `switch (req.route)` on the numbers it answered (0, 1, 2 ...); read
2923
+ `req.param(k)` by index, `req.paramNumber(k)`, `req.query(name)`,
2924
+ `req.header(lowercaseName)`, `req.text()`; answer with
2925
+ `new Response(status).text(s)`, `.json(s)` or `.bytes(type, buf, off, len)`,
2926
+ and `refuse(req)` for 404 and 405. `ServeLimits` caps connections, `inFlight`
2927
+ (503 past it), `headerBytes` (431), `bodyBytes` (413) and `responseBytes`
2928
+ (500), and `headTimeout` and `idleTimeout` close a slow or idle connection; pipelined answers keep request order. `--emit-ts` refuses it (NL4017).
2929
+ (No block, as for `nish/text`; `tests/link/net_serve` is its program, and the
2930
+ user guide's [async server page](guide/using-nish/async-server.md) its
2931
+ walk-through.)
2932
+
2872
2933
  **Call another service from a route handler** — there is no `await fetch()`
2873
2934
  in a handler (an `async` task does not wait on a socket yet) and no event-loop
2874
2935
  callback: `nish/net/upstream`'s `Upstream(h,
package/docs/INSTALL.md CHANGED
@@ -56,8 +56,12 @@ the Homebrew LLVM is needed for the `wasm`, `wasm-host` and `wasi` profiles (`wa
56
56
 
57
57
  `wasm-opt` (binaryen: `apt-get install binaryen`, `brew install binaryen`) is
58
58
  optional. When it is on `PATH`, `scripts/build.sh --profile wasm-host` runs
59
- `wasm-opt -Oz` on the module, and the build line says whether it ran. Without
60
- it the module is complete, just not as small.
59
+ `wasm-opt -Oz --strip-target-features` on the module, and the build line says
60
+ whether it ran: `add.wasm` goes from 102 bytes to 74. Without it the module
61
+ is complete and works the same. clang 18 also runs a `wasm-opt` it finds,
62
+ after any optimising wasm link, and keeps a `target_features` section for it
63
+ that build.sh's pass then drops. `NISH_WASM_OPT=0` links with neither pass,
64
+ even with binaryen installed: the bytes a machine without it builds.
61
65
 
62
66
  <a id="wasi-optional-for---profile-wasi" style="scroll-margin-top: 65px"></a>
63
67
 
@@ -155,13 +159,15 @@ tarball's SHA-256 with the release's `SHA256SUMS` (or with the digest pinned
155
159
  for releases that predate it) and refuses a mismatch. For releases after
156
160
  0.21.0 it also checks the release's **build provenance attestation** when a
157
161
  signed-in GitHub CLI is present whose `gh attestation verify` takes the
158
- options below. The attestation
159
- is a Sigstore-signed statement, made by `actions/attest-build-provenance` in
160
- the release workflow, that every file in `SHA256SUMS` was built by
161
- `.github/workflows/release.yml` at the release's tag on a GitHub-hosted
162
- runner. A failed verification refuses the install; with no `gh`, a signed-out
163
- one or one too old for those options, the check is skipped with a note saying so, and the
164
- SHA-256 still applies. The same command by hand, on a tarball you downloaded:
162
+ options below.
163
+
164
+ The attestation is a Sigstore-signed statement, made by
165
+ `actions/attest-build-provenance` in the release workflow, that every file in
166
+ `SHA256SUMS` was built by `.github/workflows/release.yml` at the release's tag
167
+ on a GitHub-hosted runner. A failed verification refuses the install; with no
168
+ `gh`, a signed-out one or one too old for those options, the check is skipped
169
+ with a note saying so, and the SHA-256 still applies. The same command by hand,
170
+ on a tarball you downloaded:
165
171
 
166
172
  ```bash
167
173
  gh attestation verify nish-<version>-<asset>.tar.gz \
@@ -259,11 +265,11 @@ routes are
259
265
  # in the glibc container, where build/nish runs
260
266
  build/nish app.ts -o app.ll
261
267
  # on the musl host, with its own clang and the runtime from this repository
262
- clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
268
+ clang app.ll runtime/runtime.c runtime/runtime-text.c runtime/runtime-os.c runtime/runtime-parallel.c \
263
269
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
264
270
  runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-sha256.c runtime/runtime-chacha20.c \
265
271
  runtime/runtime-term.c runtime/runtime-bytes.c runtime/runtime-checksum.c runtime/runtime-sandbox.c \
266
- runtime/runtime-shm.c runtime/runtime-region.c -lm -o app
272
+ runtime/runtime-shm.c runtime/runtime-region.c -ffp-contract=off -lm -o app
267
273
  ```
268
274
 
269
275
  `--link`ing inside the container is the mistake to avoid: it shells out to the
@@ -372,7 +378,8 @@ release exists, take its version from
372
378
  Unpack it and run `bin/nish` from wherever you like; put that on `PATH` if you
373
379
  want it there. Keep the directory intact rather than moving the binary out of
374
380
  it: `--link` runs `scripts/build.sh` and compiles the C runtime
375
- (`runtime/runtime.c` and `runtime/runtime-os.c`, the system-call half), and the
381
+ (`runtime/runtime.c`, `runtime/runtime-text.c`, the strings and number
382
+ formatting, `runtime/runtime-os.c`, the system-call half, and the rest), and the
376
383
  compiler finds all of them relative to its own location — `bin/nish` alone in a
377
384
  directory can still emit IR with `-o`, but `--link` will tell you it cannot
378
385
  find `scripts/build.sh`.
@@ -399,53 +406,67 @@ it into `build/seed/`; `NISH_BOOTSTRAP=<path>` names one you already have and
399
406
  skips the download. §2a has what the build does with it.
400
407
 
401
408
  The published package ships `bin/` (the `nish` command, which is a launcher),
402
- `runtime/` (the C runtime — sixteen translation units, the wasm subset and their
409
+ `runtime/` (the C runtime — seventeen translation units, the wasm subset and their
403
410
  header — and `runtime/sqlite/`, SQLite's vendored source),
404
411
  `scripts/build.sh` (the link pipeline), `std/` (the standard library) and
405
412
  `docs/AI.md` (the rules card). The
406
413
  compiler itself is not in it: it arrives as one prebuilt
407
414
  `@amritk/nish-<asset>` package per platform, and `bin/nish` hands over to
408
- whichever one npm installed. That package carries its own copy of all of
409
- these, and its `docs/AI.md` is the one an agent's `nish --help` names. `nish` locates the runtime, the script and `std/`
410
- relative to its own install directory, so a global install works from any
411
- working directory — and the binary runs from inside its own platform package
412
- for exactly that reason.
415
+ whichever one npm installed.
416
+
417
+ That package carries its own copy of all of these, and its `docs/AI.md` is the
418
+ one an agent's `nish --help` names. `nish` locates the runtime, the script and
419
+ `std/` relative to its own install directory, so a global install works from
420
+ any working directory — and the binary runs from inside its own platform
421
+ package for exactly that reason.
413
422
 
414
423
  Building the IR yourself rather than through `--link` means naming the runtime
415
- on the `clang` line, and it is sixteen files:
424
+ on the `clang` line, and it is seventeen files:
416
425
 
417
426
  ```bash
418
- clang app.ll runtime/runtime.c runtime/runtime-os.c runtime/runtime-parallel.c \
427
+ clang app.ll runtime/runtime.c runtime/runtime-text.c runtime/runtime-os.c runtime/runtime-parallel.c \
419
428
  runtime/runtime-cross.c runtime/runtime-host.c runtime/runtime-net.c \
420
429
  runtime/runtime-simd.c runtime/runtime-aes.c runtime/runtime-sha256.c runtime/runtime-chacha20.c \
421
430
  runtime/runtime-term.c runtime/runtime-bytes.c runtime/runtime-checksum.c runtime/runtime-sandbox.c \
422
- runtime/runtime-shm.c runtime/runtime-region.c -lm -o app
431
+ runtime/runtime-shm.c runtime/runtime-region.c -ffp-contract=off -lm -o app
423
432
  ```
424
433
 
425
- `runtime.c` is the part every program touches — the arena, strings, arrays,
426
- number formatting, the panics — and `runtime-os.c` wraps the system calls:
427
- files, directories, subprocesses, `getenv`, the monotonic clock.
428
- `runtime-parallel.c` divides work across threads for `nish/threads` (a
429
- program built with `--threads`, as every importer of `nish/threads` is, also
430
- needs `-DNISH_THREADS=1 -pthread` on the line), `runtime-cross.c` copies
431
- the strings and arrays a task answers, a channel sends or a `Mutex` keeps out
432
- of the arena they were made in, `runtime-host.c` holds the wall clock,
433
- entropy, file times and signals, `runtime-net.c` the sockets of `nish:net`,
434
- `runtime-simd.c` and `runtime-aes.c` the vector text search and AES-GCM,
435
- `runtime-sha256.c` the SHA-256 block kernel `nish/crypto/sha256` hands its
436
- blocks to on a CPU with the SHA instructions (`NISH_SHA256=soft` keeps the
437
- portable path), `runtime-chacha20.c` the ChaCha20 keystream `nish/crypto/chacha20poly1305`
438
- hands a message of 256 bytes or more to on a CPU with AVX2 or NEON (`NISH_CHACHA20=soft`
439
- keeps the portable path), `runtime-term.c` the stdin reads and terminal calls of `nish:term`,
440
- `runtime-bytes.c` the byte-class runs of `nish/bytes`, which `nish/json` steps
441
- over, `runtime-checksum.c` the CRC-32 kernels of `nish/compress/checksum`,
442
- `runtime-sandbox.c` the confinement a `--sandbox` build applies, and
443
- `runtime-shm.c` the shared-memory regions of `nish/sync/shm`.
444
- They are separate so that each carries its own measured size ceiling
445
- ([docs/wp7-runtime.md](https://github.com/amritk/nish/blob/main/docs/wp7-runtime.md)); nothing in the core calls into the
446
- others, so a line that names only `runtime.c` and `runtime-os.c` still links a
447
- program that uses none of the other nine. `scripts/build.sh` compiles the other
448
- nine beside any
434
+ `runtime.c` is the part every program touches — the arena, arrays, the
435
+ panics — `runtime-text.c` holds strings and number formatting, and
436
+ `runtime-os.c` wraps the system calls: files, directories, subprocesses,
437
+ `getenv`, the monotonic clock.
438
+
439
+ `-ffp-contract=off` keeps clang from fusing a C `a*b+c` into one rounding
440
+ where the CPU has a fused multiply-add (every arm64, x86-64 at v3): the runtime
441
+ then prints the same float on every target, as `scripts/build.sh` compiles it.
442
+
443
+ `runtime-parallel.c` divides work across threads for `nish/threads` (a program
444
+ built with `--threads`, as every importer of `nish/threads` is, also needs
445
+ `-DNISH_THREADS=1 -pthread` on the line), `runtime-cross.c` copies the strings
446
+ and arrays a task answers, a channel sends or a `Mutex` keeps out of the arena
447
+ they were made in, `runtime-host.c` holds the wall clock, entropy, file times
448
+ and signals, `runtime-net.c` the sockets of `nish:net`, `runtime-simd.c` and
449
+ `runtime-aes.c` the vector text search and AES-GCM, `runtime-sha256.c` the
450
+ SHA-256 block kernel `nish/crypto/sha256` hands its blocks to on a CPU with the
451
+ SHA instructions (`NISH_SHA256=soft` keeps the portable path),
452
+ `runtime-chacha20.c` the ChaCha20 keystream `nish/crypto/chacha20poly1305`
453
+ hands a message of 256 bytes or more to on a CPU with AVX2 or NEON
454
+ (`NISH_CHACHA20=soft` keeps the portable path), `runtime-term.c` the stdin
455
+ reads and terminal calls of `nish:term`, `runtime-bytes.c` the byte-class runs
456
+ of `nish/bytes`, which `nish/json` steps over, `runtime-checksum.c` the CRC-32
457
+ kernels of `nish/compress/checksum`, `runtime-sandbox.c` the confinement a
458
+ `--sandbox` build applies, and `runtime-shm.c` the shared-memory regions of
459
+ `nish/sync/shm`. They are separate so that each carries its own measured size
460
+ ceiling
461
+ ([docs/wp7-runtime.md](https://github.com/amritk/nish/blob/main/docs/wp7-runtime.md));
462
+ the core is three files that call each other — `runtime-os.c` builds strings
463
+ with `runtime-text.c`'s `nish_str_new` — and calls into none of the others, so a
464
+ line that names only `runtime.c`, `runtime-text.c` and `runtime-os.c` links a
465
+ program that uses none of the other fourteen. Leave out `runtime-text.c` and it
466
+ does not link at all: `nish_str_new` is undefined.
467
+
468
+ `scripts/build.sh` compiles the other
469
+ sixteen beside any
449
470
  `runtime.c` it is handed, so a build that goes through it — every `--link`,
450
471
  and every `--profile` recipe in these documents — needs to name only the one.
451
472
 
@@ -473,19 +494,19 @@ The seed builds stage1, stage1 builds stage2, and stage2 is installed as
473
494
  own IR is only reported beside them, because a codegen change since the
474
495
  release is expected to move it. `--stages 1` stops one link sooner.
475
496
 
476
- `build/nish` is then the compiler you run: it takes the same `-o`, `--link`
477
- and `--profile` spellings as an installed `nish`, because it is the same
478
- program, and makes every directory in the way of the IR, a sidecar or the
479
- binary itself. It looks for `scripts/build.sh` and the `runtime/*.c` files
480
- one level up from wherever it was invoked (and one level up from the file a
481
- symbolic link to it names), so it wants a checkout or an installed package
482
- around it the way `nish` does. It falls back to the working directory only
483
- when the compiler itself lies inside that directory, so a checkout you merely
484
- `cd` into cannot hand it a `scripts/build.sh` to run. Keep `bin/nish` beside
485
- `scripts/`, `runtime/` and `std/`, as every install above does, and keep that
486
- directory's parent writable only by you: the package root is the parent of
487
- the compiler's directory, so a compiler at `/tmp/x/nish` would trust
488
- `/tmp/scripts/build.sh` (CLI-9 in [docs/security/cli.md](security/cli.md)).
497
+ `build/nish` is then the compiler you run: it takes the same `-o`, `--link` and
498
+ `--profile` spellings as an installed `nish`, because it is the same program,
499
+ and makes every directory in the way of the IR, a sidecar or the binary itself.
500
+ It looks for `scripts/build.sh` and the `runtime/*.c` files one level up from
501
+ wherever it was invoked (and one level up from the file a symbolic link to it
502
+ names), so it wants a checkout or an installed package around it the way `nish`
503
+ does. It falls back to the working directory only when the compiler itself lies
504
+ inside that directory, so a checkout you merely `cd` into cannot hand it a
505
+ `scripts/build.sh` to run. Keep `bin/nish` beside `scripts/`, `runtime/` and
506
+ `std/`, as every install above does, and keep that directory's parent writable
507
+ only by you: the package root is the parent of the compiler's directory, so a
508
+ compiler at `/tmp/x/nish` would trust `/tmp/scripts/build.sh` (CLI-9 in
509
+ [docs/security/cli.md](security/cli.md)).
489
510
 
490
511
  Because the seed is the last release, `src/` may only *use* in its own
491
512
  source the constructs that release compiles. A new construct is implemented
@@ -537,24 +558,24 @@ nish run hello.ts
537
558
  `nish run [options] <file.ts> [args ...]` compiles the file, links it into
538
559
  `$XDG_CACHE_HOME/nish/run` (or `~/.cache/nish/run`) when that program has not
539
560
  been linked before, and starts it with the arguments after the file. The first
540
- run of a new edit pays for one link, and later runs start the cached binary.
541
- It needs clang only for that link. It needs `HOME` or `XDG_CACHE_HOME` set
542
- to an absolute path (a relative one is ignored, as if it were unset), and
543
- refuses the run without one rather than keep a binary in a shared directory.
544
- The first run that builds into the cache makes its root `0700`, so no other
545
- user can plant a binary in it ([docs/security/cli.md](security/cli.md)).
561
+ run of a new edit pays for one link, and later runs start the cached binary. It
562
+ needs clang only for that link. It needs `HOME` or `XDG_CACHE_HOME` set to an
563
+ absolute path (a relative one is ignored, as if it were unset), and refuses the
564
+ run without one rather than keep a binary in a shared directory. The first run
565
+ that builds into the cache makes its root `0700`, so no other user can plant a
566
+ binary in it ([docs/security/cli.md](security/cli.md)).
546
567
 
547
568
  Every link with the debug, speed or size profile, `nish run`'s and `--link`'s
548
569
  alike, keeps the compiled C runtime in `$XDG_CACHE_HOME/nish/runtime` (or
549
570
  `~/.cache/nish/runtime`), one entry per profile, `-g`, `--threads`, `CC` and
550
571
  the version that compiler reports, made `0700` the same way. The first link
551
- compiles the runtime's six files at once into it, and every later link
552
- compiles only the program's modules, also at once, and links against the
553
- entry: a `hello.ts` debug link goes from about half a second to about a
554
- tenth. `--link` with no absolute `HOME` or `XDG_CACHE_HOME`, or with a root
555
- it cannot make private, compiles the runtime itself as it always did; the
556
- wasi profile and `scripts/build.sh` called directly never use the cache.
557
- Removing the directory is always safe.
572
+ compiles the runtime's six files at once into it, and every later link compiles
573
+ only the program's modules, also at once, and links against the entry: a
574
+ `hello.ts` debug link goes from about half a second to about a tenth. `--link`
575
+ with no absolute `HOME` or `XDG_CACHE_HOME`, or with a root it cannot make
576
+ private, compiles the runtime itself as it always did; the wasi profile and
577
+ `scripts/build.sh` called directly never use the cache. Removing the directory
578
+ is always safe.
558
579
 
559
580
  <a id="4-exit-codes" style="scroll-margin-top: 65px"></a>
560
581
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nish",
3
- "version": "0.36.0",
3
+ "version": "0.38.0",
4
4
  "description": "Nish: an ahead-of-time compiler from a static subset of TypeScript to LLVM IR",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,6 +25,10 @@
25
25
  "types": "./runtime/vite.d.ts",
26
26
  "default": "./runtime/vite.mjs"
27
27
  },
28
+ "./page": {
29
+ "types": "./runtime/page.d.ts",
30
+ "default": "./runtime/page.mjs"
31
+ },
28
32
  "./runtime/*": "./runtime/*",
29
33
  "./scripts/*": "./scripts/*",
30
34
  "./*": "./std/*.ts"
@@ -47,6 +51,7 @@
47
51
  "!scripts/ddc-chain.sh",
48
52
  "!scripts/gen-reference.mjs",
49
53
  "!scripts/typedoc-nish-widths.mjs",
54
+ "!scripts/pin-platform-packages.mjs",
50
55
  "std",
51
56
  "README.md",
52
57
  "LICENSE",
@@ -100,17 +105,17 @@
100
105
  "webassembly",
101
106
  "nish"
102
107
  ],
103
- "optionalDependencies": {
104
- "@amritk/nish-x86_64-linux": "0.36.0",
105
- "@amritk/nish-aarch64-linux": "0.36.0",
106
- "@amritk/nish-aarch64-darwin": "0.36.0",
107
- "@amritk/nish-x86_64-darwin": "0.36.0"
108
- },
109
108
  "devDependencies": {
110
109
  "@biomejs/biome": "2.5.12",
111
110
  "@types/node": "^22.0.0",
112
111
  "knip": "6.38.0",
113
112
  "typedoc": "0.28.20",
114
113
  "typescript": "^5.6.0"
114
+ },
115
+ "optionalDependencies": {
116
+ "@amritk/nish-aarch64-darwin": "0.38.0",
117
+ "@amritk/nish-aarch64-linux": "0.38.0",
118
+ "@amritk/nish-x86_64-darwin": "0.38.0",
119
+ "@amritk/nish-x86_64-linux": "0.38.0"
115
120
  }
116
121
  }
@@ -45,5 +45,7 @@ export declare function awaitAll<A, B, C, D, E, F, G, H>(
45
45
  g: Promise<G>,
46
46
  h: Promise<H>,
47
47
  ): Promise<[A, B, C, D, E, F, G, H]>;
48
+ /** `true` once `ms` milliseconds have passed; `false` at once for a negative `ms`. */
49
+ export declare function sleep(ms: number): Promise<boolean>;
48
50
  /** Waits for every task `spawn` started, the tasks those tasks start included. */
49
51
  export declare function settleTasks(): Promise<void>;
package/runtime/async.mjs CHANGED
@@ -19,6 +19,13 @@ export const spawn = (task) => {
19
19
 
20
20
  export const awaitAll = (...tasks) => Promise.all(tasks);
21
21
 
22
+ // `sleep` is a timer: `true` once `ms` milliseconds have passed, `false` for a
23
+ // negative `ms`, as natively. `readable` and `writable` have no counterpart in
24
+ // Node, whose descriptors are not polled from JavaScript, so `--emit-ts`
25
+ // refuses them (NL4017) and this file does not export them.
26
+ export const sleep = (ms) =>
27
+ ms < 0 ? Promise.resolve(false) : new Promise((resolve) => setTimeout(() => resolve(true), ms));
28
+
22
29
  export const settleTasks = async () => {
23
30
  for (let i = 0; i < pending.length; i++) {
24
31
  await pending[i];
@@ -11,6 +11,10 @@ export declare function storeIdx<T>(a: T[], i: number | bigint, v: T): T;
11
11
  export declare function arraySet<T>(dst: T[], src: readonly T[], offset?: number): void;
12
12
  /** `dst.set(src, offset)` as `--emit-ts` writes it: a 64-bit offset is a bigint, checked exactly. */
13
13
  export declare function arraySetAt<T>(dst: T[], src: readonly T[], offset?: number | bigint): void;
14
+ /** `xs.slice(start, end)` as `--emit-ts` writes it: an out-of-range bound panics, as the native one does. */
15
+ export declare function sliceArray<T>(a: readonly T[], start?: number | bigint, end?: number | bigint): T[];
16
+ /** The answer of `xs.map`, `xs.filter` or `xs.slice` with each record copied, as an array holds it inline. */
17
+ export declare function copyRecords<T>(a: T[]): T[];
14
18
  /** `new Array<T>(n)`: `--emit-ts` writes `T` out, so the zero it fills with is not what `T` is read from. */
15
19
  export declare function newArray<T>(n: number | bigint, zero: unknown): T[];
16
20
  export declare function arenaUsed(): i64;
@@ -66,6 +66,39 @@ export function copyIn(v) {
66
66
  return isRecord(v) ? { ...v } : v;
67
67
  }
68
68
 
69
+ /**
70
+ * `xs.slice(start, end)` as `nish --emit-ts` writes it: the native rule, where
71
+ * the range must satisfy `0 <= start <= end <= xs.length` and anything else
72
+ * panics, not JavaScript's, which counts a negative bound from the end and
73
+ * clamps the rest.
74
+ */
75
+ export function sliceArray(a, start, end) {
76
+ const from = start === undefined ? 0n : sliceBound(start);
77
+ const to = end === undefined ? BigInt(a.length) : sliceBound(end);
78
+ if (!(from >= 0n && from <= to && to <= BigInt(a.length))) panicSlice(from, to, a.length);
79
+ return a.slice(Number(from), Number(to));
80
+ }
81
+
82
+ // A `slice` bound as the native template converts it to `i64`: a `number` is
83
+ // truncated toward zero and saturates, NaN to 0 and an infinity to the i64
84
+ // limit, so a panic prints the same offsets natively and here.
85
+ function sliceBound(i) {
86
+ if (typeof i === "bigint") return i;
87
+ if (Number.isNaN(i)) return 0n;
88
+ if (i >= 2 ** 63) return (1n << 63n) - 1n;
89
+ if (i <= -(2 ** 63)) return -(1n << 63n);
90
+ return BigInt(Math.trunc(i));
91
+ }
92
+
93
+ /**
94
+ * The array `xs.map`, `xs.filter` or `xs.slice` answers, as the native one
95
+ * holds it: each record a fresh copy, as an array holds a record inline.
96
+ */
97
+ export function copyRecords(a) {
98
+ for (let i = 0; i < a.length; i++) a[i] = copyIn(a[i]);
99
+ return a;
100
+ }
101
+
69
102
  /**
70
103
  * `a[i] = v` from a generic body: as `setIdx`, but a record is written field
71
104
  * by field into the record already in the slot, as an inline element is.