@amritk/nish-x86_64-linux 0.42.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +287 -129
  3. package/package.json +1 -1
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +24 -0
  7. package/runtime/core.mjs +21 -0
  8. package/runtime/nish.d.ts +167 -24
  9. package/runtime/nish.mjs +7 -1
  10. package/runtime/runtime-cross.c +9 -0
  11. package/runtime/runtime-net.c +51 -13
  12. package/runtime/runtime-region.c +13 -0
  13. package/runtime/runtime-text.c +11 -0
  14. package/runtime/runtime-uring.c +83 -25
  15. package/runtime/runtime-wasm.c +3 -0
  16. package/runtime/runtime.c +329 -6
  17. package/runtime/sqlite/README.md +16 -3
  18. package/runtime/sqlite/nish-sqlite.c +940 -29
  19. package/scripts/build.sh +111 -29
  20. package/std/README.md +6 -6
  21. package/std/array.ts +10 -2
  22. package/std/bytes.ts +239 -26
  23. package/std/cli-args.ts +1072 -606
  24. package/std/cli-flags.ts +180 -98
  25. package/std/cli.ts +21 -13
  26. package/std/collections.ts +245 -127
  27. package/std/compress/checksum.ts +32 -37
  28. package/std/compress/deflate.ts +1102 -542
  29. package/std/compress/gzip.ts +290 -145
  30. package/std/compress/zlib.ts +57 -21
  31. package/std/crypto/aes.ts +153 -75
  32. package/std/crypto/base64url.ts +163 -39
  33. package/std/crypto/bcrypt-batch.ts +164 -90
  34. package/std/crypto/bcrypt.ts +185 -107
  35. package/std/crypto/chacha20poly1305.ts +84 -68
  36. package/std/crypto/ct.ts +9 -7
  37. package/std/crypto/ed25519.ts +64 -27
  38. package/std/crypto/hkdf.ts +105 -63
  39. package/std/crypto/hmac.ts +95 -89
  40. package/std/crypto/jwt.ts +248 -126
  41. package/std/crypto/p256.ts +758 -444
  42. package/std/crypto/p384.ts +20 -13
  43. package/std/crypto/pki-roots.ts +95 -38
  44. package/std/crypto/pki.ts +164 -60
  45. package/std/crypto/rsa.ts +266 -223
  46. package/std/crypto/scram.ts +141 -0
  47. package/std/crypto/sha1.ts +157 -57
  48. package/std/crypto/sha256.ts +502 -422
  49. package/std/crypto/sha512.ts +204 -135
  50. package/std/crypto/x509-random.ts +9 -3
  51. package/std/crypto/x509.ts +331 -171
  52. package/std/host/ring.ts +1 -1
  53. package/std/host/text.ts +1 -1
  54. package/std/json-equal.ts +35 -19
  55. package/std/json-format.ts +215 -108
  56. package/std/json-number.ts +126 -72
  57. package/std/json-pointer.ts +42 -13
  58. package/std/json-tokenizer.ts +498 -307
  59. package/std/json-typed.ts +115 -36
  60. package/std/json-value.ts +341 -152
  61. package/std/json.ts +300 -158
  62. package/std/net/buffer-pool.ts +17 -7
  63. package/std/net/dns-config.ts +427 -236
  64. package/std/net/dns-message.ts +114 -47
  65. package/std/net/dns-resolver.ts +736 -237
  66. package/std/net/dns.ts +205 -52
  67. package/std/net/fetch.ts +320 -184
  68. package/std/net/grpc.ts +948 -0
  69. package/std/net/handler.ts +1276 -218
  70. package/std/net/hpack.ts +395 -180
  71. package/std/net/http-compress.ts +502 -65
  72. package/std/net/http-fields.ts +85 -49
  73. package/std/net/http-server.ts +1764 -603
  74. package/std/net/http1-client-codec.ts +372 -161
  75. package/std/net/http1-codec.ts +665 -331
  76. package/std/net/http1-server.ts +881 -269
  77. package/std/net/http2-cleartext.ts +165 -95
  78. package/std/net/http2-frame.ts +232 -89
  79. package/std/net/http2-tls.ts +42 -12
  80. package/std/net/http2.ts +327 -101
  81. package/std/net/http3-frame.ts +68 -33
  82. package/std/net/http3-server.ts +672 -206
  83. package/std/net/http3.ts +669 -191
  84. package/std/net/oidc.ts +63 -24
  85. package/std/net/outbound.ts +207 -142
  86. package/std/net/postgres-async.ts +1223 -470
  87. package/std/net/postgres-carrier.ts +575 -372
  88. package/std/net/postgres.ts +1521 -632
  89. package/std/net/prefork.ts +254 -98
  90. package/std/net/protobuf.ts +1017 -0
  91. package/std/net/qpack.ts +143 -92
  92. package/std/net/quic-conn-ack.ts +104 -22
  93. package/std/net/quic-conn-cid.ts +66 -26
  94. package/std/net/quic-conn-params.ts +13 -7
  95. package/std/net/quic-datagram.ts +90 -27
  96. package/std/net/quic-frame.ts +324 -121
  97. package/std/net/quic-listener.ts +206 -91
  98. package/std/net/quic-packet.ts +289 -163
  99. package/std/net/quic-recovery.ts +279 -128
  100. package/std/net/quic-stream.ts +466 -167
  101. package/std/net/quic.ts +584 -258
  102. package/std/net/router.ts +450 -99
  103. package/std/net/serve.ts +661 -240
  104. package/std/net/static.ts +1458 -0
  105. package/std/net/tls/client.ts +140 -45
  106. package/std/net/tls/codec.ts +510 -260
  107. package/std/net/tls/record-client.ts +268 -76
  108. package/std/net/tls/record-server.ts +236 -79
  109. package/std/net/tls/record.ts +173 -47
  110. package/std/net/tls/schedule.ts +58 -39
  111. package/std/net/tls/ticket.ts +295 -103
  112. package/std/net/tls/verify.ts +1 -1
  113. package/std/net/tls-tcp.ts +218 -75
  114. package/std/net/tls.ts +260 -152
  115. package/std/net/upstream.ts +283 -86
  116. package/std/net/url.ts +277 -102
  117. package/std/net/websocket.ts +532 -209
  118. package/std/net/webtransport.ts +755 -436
  119. package/std/regex.ts +1659 -829
  120. package/std/sqlite.ts +325 -0
  121. package/std/sync/ring.ts +320 -156
  122. package/std/sync/shm.ts +53 -6
  123. package/std/text.ts +285 -135
  124. package/std/threads.ts +22 -2
package/scripts/build.sh CHANGED
@@ -100,6 +100,12 @@
100
100
  # runtime names it (docs/security/runtime.md, "The debug arena"). The IR is the
101
101
  # same either way; `nish --debug-arena` passes it through. Native profiles only.
102
102
  #
103
+ # Compact-class range (WP48 stage 1): `--arena-range` compiles the runtime with
104
+ # -DNISH_ARENA_RANGE, which carves arena chunks of 2 MiB or less from one
105
+ # 15 GiB reservation (at [1 GiB, 16 GiB) on Linux) so a compact class's 32-bit
106
+ # reference can name them. There is no user flag: nish passes it when the
107
+ # program has a compact class (docs/wp48-ref32-classes.md). Native profiles only.
108
+ #
103
109
  # Debug info (WP10): `-g` compiles every input with -g and skips the strip
104
110
  # step of the speed/size/napi profiles, so the DWARF that `nish -g`
105
111
  # put in the .ll (line table, variables) reaches the binary. `nish
@@ -119,11 +125,13 @@
119
125
  # passes it through.
120
126
  #
121
127
  # SQLite: an input .ll that declares an `sqlite3_*` or `nishsqlite_*` function
122
- # also compiles and links every runtime/sqlite/*.c, the vendored amalgamation
123
- # (runtime/sqlite/README.md). Any other program compiles none of it. sqlite3.c
124
- # is compiled to native code at the profile's level, even where the profile
125
- # compiles to LTO bitcode. The options are most of SQLite's recommended set
126
- # (see the defaults below), with THREADSAFE=0 (=2 under --threads).
128
+ # also compiles and links runtime/sqlite/nish-sqlite.c, the adapter, which
129
+ # includes sqlite3.c, the vendored amalgamation (runtime/sqlite/README.md), so
130
+ # it can call SQLite's internal B-tree functions (docs/sqlite-cursor.md): every
131
+ # *.c there but sqlite3.c is a unit. Any other program compiles none of it.
132
+ # The unit is compiled to native code at the profile's level, even where the
133
+ # profile compiles to LTO bitcode. The options are most of SQLite's recommended
134
+ # set (see the defaults below), with THREADSAFE=0 (=2 under --threads).
127
135
  # NISH_SQLITE_CFLAGS is appended to them: its first line, split on whitespace
128
136
  # with no quoting, and a relative -I in it names a directory below
129
137
  # runtime/sqlite/, where each unit is compiled. A -D or -U in it for one of
@@ -144,7 +152,7 @@
144
152
  # runtime.c input, after compiling every other input
145
153
  # with its own $CC -c, all at once. The link line is
146
154
  # the one the profile always uses.
147
- # --sqlite-objects <dir> compile runtime/sqlite/*.c alone, into
155
+ # --sqlite-objects <dir> compile runtime/sqlite/'s units alone, into
148
156
  # <dir>/<unit>.o, as a link of a program that calls
149
157
  # SQLite would, and link nothing. Takes no inputs and
150
158
  # no -o, and prints nothing on success.
@@ -157,6 +165,19 @@
157
165
  # not, so the caller keeps every object it compiled
158
166
  # (`nish run`'s module cache, src/build-cache.ts).
159
167
  # The inputs' file names must differ.
168
+ # --link-lib <name> debug, speed and size only: link the C library
169
+ # <name> (-l<name>, after the inputs and before -lm);
170
+ # <name> is [A-Za-z0-9_][A-Za-z0-9_.+-]*, so it is
171
+ # never a flag. A package's `nish.link.libraries`
172
+ # (WP66 S7, docs/security/package-link.md).
173
+ # --link-source <file.c> debug, speed and size only: compile the C file, an
174
+ # absolute path, with the profile's flags and link
175
+ # it with the program. A package's `nish.link.sources`.
176
+ # --link-depends <file.c> debug, speed and size only: print, as a make rule
177
+ # (clang -M), the files it lists for the compile of
178
+ # that source with this profile's flags, and link
179
+ # nothing.
180
+ # `nish run` keys its cache on them.
160
181
  #
161
182
  # Works on Linux (clang + lld preferred, GNU ld tolerated) and macOS (Apple ld64
162
183
  # or Homebrew llvm). Set CC to pick a compiler (default: clang on PATH).
@@ -169,6 +190,7 @@ pgo=() # -fprofile-generate / -fprofile-use=<fil
169
190
  debug=0 # -g: keep DWARF (nish -g emits it in the IR; runtime.c gets it here)
170
191
  threads=0 # --threads: -DNISH_THREADS, the thread-local arena (WP20 T0)
171
192
  debug_arena=0 # --debug-arena: -DNISH_ARENA_DEBUG, the arena that traps a stale reference
193
+ arena_range=0 # --arena-range: -DNISH_ARENA_RANGE, the compact-class range (WP48)
172
194
  objects_to="" # --runtime-objects <dir>: compile the runtime alone, into <dir>
173
195
  objects_from="" # --runtime-from <dir>: link against the runtime compiled there
174
196
  cpu="" # --cpu x86-64-v3: the one CPU level above the baseline (WP38 S2)
@@ -178,6 +200,9 @@ modules_at="" # --module-objects <dir>: each X.ll's obj
178
200
  memory_mib="" # --memory <MiB>: wasm-host's fixed memory (WP50 stage 1)
179
201
  wasm_opt="" # what the build line says of wasm-opt; set only by wasm-host
180
202
  inline_to="" # --inline <file.mjs>: wasm-host's bytes as an ES module
203
+ link_libs=() # --link-lib <name>: -l<name> on the link line (WP66 S7)
204
+ link_sources=() # --link-source <file.c>: a package's own C, compiled into the link
205
+ link_depends="" # --link-depends <file.c>: print what its compile reads, then stop
181
206
  while [ $# -gt 0 ]; do
182
207
  case "$1" in
183
208
  -o) out="$2"; shift 2 ;;
@@ -185,6 +210,7 @@ while [ $# -gt 0 ]; do
185
210
  -g) debug=1; shift ;;
186
211
  --threads) threads=1; shift ;;
187
212
  --debug-arena) debug_arena=1; shift ;;
213
+ --arena-range) arena_range=1; shift ;;
188
214
  --cpu)
189
215
  [ -n "${2-}" ] || { echo "error: --cpu needs a level; the one taken is x86-64-v3" >&2; exit 2; }
190
216
  cpu="$2"; shift 2 ;;
@@ -199,6 +225,21 @@ while [ $# -gt 0 ]; do
199
225
  --inline)
200
226
  [ -n "${2-}" ] || { echo "error: --inline needs a file to write" >&2; exit 2; }
201
227
  inline_to="$2"; shift 2 ;;
228
+ --link-lib)
229
+ [[ "${2-}" =~ ^[A-Za-z0-9_][A-Za-z0-9_.+-]*$ ]] || { echo "error: --link-lib takes a library name of letters, digits, _ . + and -, not '${2-}'" >&2; exit 2; }
230
+ link_libs+=("-l$2"); shift 2 ;;
231
+ --link-source)
232
+ case "${2-}" in
233
+ /*.c) [ -f "$2" ] || { echo "error: --link-source: $2 is not a file" >&2; exit 2; } ;;
234
+ *) echo "error: --link-source takes the absolute path of a .c file, not '${2-}'" >&2; exit 2 ;;
235
+ esac
236
+ link_sources+=("$2"); shift 2 ;;
237
+ --link-depends)
238
+ case "${2-}" in
239
+ /*.c) [ -f "$2" ] || { echo "error: --link-depends: $2 is not a file" >&2; exit 2; } ;;
240
+ *) echo "error: --link-depends takes the absolute path of a .c file, not '${2-}'" >&2; exit 2 ;;
241
+ esac
242
+ link_depends="$2"; shift 2 ;;
202
243
  --pgo-generate) pgo=(-fprofile-generate); shift ;;
203
244
  --pgo-use)
204
245
  [ -f "$2" ] || { echo "error: --pgo-use: profile '$2' not found (run the instrumented binary, then llvm-profdata merge)" >&2; exit 2; }
@@ -207,8 +248,9 @@ while [ $# -gt 0 ]; do
207
248
  *) inputs+=("$1"); shift ;;
208
249
  esac
209
250
  done
210
- [ ${#inputs[@]} -gt 0 ] || [ -n "$sqlite_to" ] || { echo "error: no input files" >&2; exit 2; }
251
+ [ ${#inputs[@]} -gt 0 ] || [ -n "$sqlite_to" ] || [ -n "$link_depends" ] || { echo "error: no input files" >&2; exit 2; }
211
252
  if [ -n "$cpu" ]; then
253
+ [ "$cpu" != native ] || { echo "error: --cpu native is refused: under clang 18 the constant-time check (CT-16) refuses the assembly made for some CPUs native names (znver2 to znver4, sapphirerapids); --cpu takes x86-64-v3" >&2; exit 2; }
212
254
  [ "$cpu" = x86-64-v3 ] || { echo "error: --cpu takes x86-64-v3, not '$cpu'" >&2; exit 2; }
213
255
  case "$profile" in
214
256
  wasm|wasm-host|wasi) echo "error: --cpu x86-64-v3 is an x86-64 level, so the $profile profile does not take it" >&2; exit 2 ;;
@@ -219,6 +261,11 @@ if [ "$debug_arena" = 1 ]; then
219
261
  wasm|wasm-host|wasi|napi) echo "error: --debug-arena maps pages and catches SIGSEGV, so the $profile profile does not take it" >&2; exit 2 ;;
220
262
  esac
221
263
  fi
264
+ if [ "$arena_range" = 1 ]; then
265
+ case "$profile" in
266
+ wasm|wasm-host|wasi|napi) echo "error: --arena-range reserves a fixed address range, so the $profile profile does not take it" >&2; exit 2 ;;
267
+ esac
268
+ fi
222
269
  if [ -n "$memory_mib" ] || [ -n "$inline_to" ]; then
223
270
  [ "$profile" = wasm-host ] || { echo "error: --memory and --inline take the wasm-host profile, not '$profile'" >&2; exit 2; }
224
271
  fi
@@ -284,7 +331,7 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
284
331
  [ -z "$sqlite_to" ] || [ -z "$sqlite_from" ] || { echo "error: --sqlite-objects and --sqlite-from are two different builds" >&2; exit 2; }
285
332
  [ -z "$sqlite_to" ] || [ -z "$objects_to$objects_from" ] || { echo "error: --sqlite-objects compiles runtime/sqlite/ alone, without --runtime-objects or --runtime-from" >&2; exit 2; }
286
333
  fi
287
- [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
334
+ [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || [ -n "$link_depends" ] || { echo "error: -o <out> is required" >&2; exit 2; }
288
335
 
289
336
  # The runtime is eighteen translation units, and a caller names one: whoever passes
290
337
  # <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
@@ -324,8 +371,8 @@ done
324
371
 
325
372
  # SQLite (runtime/sqlite/) is an optional unit, and the IR selects it. A module
326
373
  # that declares a function of SQLite's C API (`sqlite3_*`) or of the adapter
327
- # beside it (`nishsqlite_*`) gets every runtime/sqlite/*.c compiled and
328
- # linked. Any other program compiles none of it, so its link line and binary
374
+ # beside it (`nishsqlite_*`) gets runtime/sqlite/'s units (`sqlite_units`)
375
+ # compiled and linked. Any other program compiles none of it, so its link line and binary
329
376
  # stay as they were. The test reads `declare` lines, and only before the first
330
377
  # `"` on one, rather than any `@sqlite3_` in the file, because a string
331
378
  # constant or a quoted name may hold one. It is one rule with `callsSqlite` in
@@ -533,6 +580,7 @@ if [ "$threads" = 1 ]; then
533
580
  tls=(-DNISH_THREADS=1 -ftls-model=initial-exec)
534
581
  fi
535
582
  if [ "$debug_arena" = 1 ]; then common+=(-DNISH_ARENA_DEBUG=1); fi
583
+ if [ "$arena_range" = 1 ]; then common+=(-DNISH_ARENA_RANGE=1); fi
536
584
 
537
585
  # What the speed and size profiles compile every input with, beside `common`.
538
586
  # One list per profile, because the runtime cache below compiles with exactly
@@ -554,6 +602,20 @@ case "$profile" in
554
602
  -fno-asynchronous-unwind-tables -fno-unwind-tables ${elf[@]+"${elf[@]}"}) ;;
555
603
  esac
556
604
 
605
+ # --link-depends: the files clang -M lists for a package source's compile,
606
+ # every header and every #included file of any name, with the flags the link
607
+ # line compiles that source with (`common` and the profile's `optimise`), so
608
+ # `nish run` keys those rather than guessing at them by name. clang -M does
609
+ # not list a file an assembler `.incbin` reads, nor a header that would shadow
610
+ # a listed one if it appeared later (docs/security/package-link.md, PL-6, PL-10).
611
+ if [ -n "$link_depends" ]; then
612
+ case "$profile" in
613
+ debug) exec "$CC" "${common[@]}" -Wno-unused-command-line-argument -M "$link_depends" ;;
614
+ speed|size) exec "$CC" "${common[@]}" "${optimise[@]}" -Wno-unused-command-line-argument -M "$link_depends" ;;
615
+ *) echo "error: --link-depends takes the debug, speed and size profiles, not '$profile'" >&2; exit 2 ;;
616
+ esac
617
+ fi
618
+
557
619
  # The speed link splits full LTO's code generation into one partition per core,
558
620
  # run in parallel: lld's --lto-partitions, after the whole program is optimised
559
621
  # as one module, so inlining does not change. But a partition boundary promotes
@@ -660,29 +722,40 @@ for d in -DSQLITE_DQS=0 -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_DEFAULT_WAL_SYNCHR
660
722
  done
661
723
  sqlite_defs+=(${sqlite_extra[@]+"${sqlite_extra[@]}"})
662
724
 
663
- # Compiles every runtime/sqlite/*.c with the flags given, all at once, into
664
- # $1/<unit>.o. Each unit is compiled from inside runtime/sqlite/ by its bare
665
- # name, as the runtime is, so -g's DWARF names no directory the link was
666
- # started in. sqlite3.c, the 9.6 MB amalgamation, is compiled to native code
667
- # even where the profile compiles to LTO bitcode. As bitcode, every link of a
668
- # program that uses it would generate its code again: measured on a program
669
- # that opens a database and runs a query, that is 10.6 s a link at -O3,
670
- # against 0.04 s for the native object. The adapter beside it stays LTO, and
671
- # it is what inlines into the program. So `-flto` comes off for that one unit
672
- # alone.
725
+ # The units of runtime/sqlite/: every *.c but sqlite3.c, the amalgamation,
726
+ # which nish-sqlite.c compiles by including it. SQLite's B-tree and record
727
+ # functions are static there, and the cursor adapter calls them, so the two
728
+ # must be one translation unit (docs/sqlite-cursor.md, "The build decision").
729
+ # One name a line; callers read them with `while read`, so a name is never
730
+ # split on spaces.
731
+ sqlite_unit_names() {
732
+ local unit
733
+ for unit in "$sqlite_dir"/*.c; do
734
+ unit=${unit##*/}
735
+ [ "$unit" = sqlite3.c ] || printf '%s\n' "$unit"
736
+ done
737
+ }
738
+ # Compiles every unit of runtime/sqlite/ with the flags given, all at once,
739
+ # into $1/<unit>.o. Each unit is compiled from inside runtime/sqlite/ by its
740
+ # bare name, as the runtime is, so -g's DWARF names no directory the link was
741
+ # started in. Each is compiled to native code even where the profile compiles
742
+ # to LTO bitcode, because nish-sqlite.c holds the 9.6 MB amalgamation. As
743
+ # bitcode, every link of a program that uses it would generate its code
744
+ # again: measured on a program that opens a database and runs a query, that
745
+ # is 10.6 s a link at -O3, against 0.04 s for the native object. So `-flto`
746
+ # comes off.
673
747
  sqlite_units() {
674
748
  local to=$1 unit flag
675
749
  local -a flags
676
750
  shift
677
- for unit in "$sqlite_dir"/*.c; do
678
- unit=${unit##*/}
751
+ while IFS= read -r unit; do
679
752
  flags=()
680
753
  for flag in "$@"; do
681
- case "$unit:$flag" in sqlite3.c:-flto) ;; *) flags+=("$flag") ;; esac
754
+ case "$flag" in -flto) ;; *) flags+=("$flag") ;; esac
682
755
  done
683
756
  (cd -- "$sqlite_dir" && exec "$CC" "${flags[@]}" "${sqlite_defs[@]}" -I. -c "$unit" -o "$to/${unit%.c}.o") &
684
757
  pids+=("$!")
685
- done
758
+ done < <(sqlite_unit_names)
686
759
  join_jobs || { echo "error: runtime/sqlite/ did not compile" >&2; exit 1; }
687
760
  }
688
761
  # Adds the objects of runtime/sqlite/ to this link, in the order of the units.
@@ -698,11 +771,10 @@ sqlite_objects() {
698
771
  mkdir -p -- "$from"
699
772
  sqlite_units "$from" "$@"
700
773
  fi
701
- for unit in "$sqlite_dir"/*.c; do
702
- unit=${unit##*/}
774
+ while IFS= read -r unit; do
703
775
  [ -f "$from/${unit%.c}.o" ] || { echo "error: --sqlite-from: $from/${unit%.c}.o is missing" >&2; exit 2; }
704
776
  inputs+=("$from/${unit%.c}.o")
705
- done
777
+ done < <(sqlite_unit_names)
706
778
  }
707
779
 
708
780
  if [ -n "$sqlite_to" ]; then
@@ -784,12 +856,22 @@ fi
784
856
  # why Linux never noticed. `pgo`, `elf`, `strip_flag` and `libs` are all empty on
785
857
  # ordinary builds, so please do not simplify these back.
786
858
  case "$profile" in debug|speed|size) sqlite_objects "${compile[@]}" ;; esac
859
+ # A package's own C sources join the inputs here, after the runtime's halves
860
+ # and SQLite were decided from the IR alone, so a source can neither stand in
861
+ # for runtime.c nor be taken for one of its siblings. clang compiles each by
862
+ # its .c name on the one link line, with the profile's flags.
863
+ if [ ${#link_libs[@]} -gt 0 ] || [ ${#link_sources[@]} -gt 0 ]; then
864
+ case "$profile" in
865
+ debug|speed|size) inputs+=(${link_sources[@]+"${link_sources[@]}"}) ;;
866
+ *) echo "error: --link-lib and --link-source take the debug, speed and size profiles, not '$profile'" >&2; exit 2 ;;
867
+ esac
868
+ fi
787
869
  case "$profile" in
788
870
  debug)
789
- "$CC" "${common[@]}" "${inputs[@]}" -lm -o "$out" ;;
871
+ "$CC" "${common[@]}" "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
790
872
  speed|size)
791
873
  "$CC" "${common[@]}" "${optimise[@]}" ${lto_parts[@]+"${lto_parts[@]}"} \
792
- "${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" -lm -o "$out" ;;
874
+ "${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
793
875
  wasm|wasm-host)
794
876
  # A region's chunks come from malloc, and the freestanding wasm runtime
795
877
  # (runtime-wasm.c) has none, so IR that makes or enters one is refused here
package/std/README.md CHANGED
@@ -13,7 +13,7 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
13
13
  | Module | What it is |
14
14
  | --- | --- |
15
15
  | [`testing.ts`](https://github.com/amritk/nish/blob/main/std/testing.ts) | a test runner: a `Suite` a program drives with straight-line assertions, printing the `PASS` / `FAIL` / `SKIP` lines the repository's own harness prints, and answering the exit code |
16
- | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of 1 to 16 ASCII `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
16
+ | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
17
17
  | [`math.ts`](https://github.com/amritk/nish/blob/main/std/math.ts) | `Math.tan`, `Math.atan2` and `Math.hypot` on `f64`, ported from fdlibm (`LICENSE-fdlibm`) so that every target, wasm included, answers alike without libm. A program never imports it: a call to one of the three loads it, and the compiler copies the functions the call reaches into the calling module as `internal` ones. JavaScript's answer for every NaN, signed zero and infinity, and within one ulp elsewhere (0.83, 0.84 and 0.93 ulp measured against mpmath). `tests/cases/math_std_edges` pins the special values |
18
18
  | [`sort.ts`](https://github.com/amritk/nish/blob/main/std/sort.ts) | `xs.sort(cmp)` on any array: `sortWith`, a stable merge sort over runs of 32 sorted by insertion — one scratch array released before it returns, a pair of runs already in order copied without merging, no bounds check left in it — so its order is element for element Node's `Array.prototype.sort`. Like `math.ts` it is one the compiler knows about: a program never imports it, a `.sort(cmp)` call loads it, the checker rewrites the call to `sortWith`, and each comparator's instantiation — the comparator called directly, no function pointer — is copied into the module that sorts. Under Node the call stays the platform's own. `tests/cases/arr_sort_cmp*` are its programs, a 10,000-element sort with ties among them |
19
19
  | [`array.ts`](https://github.com/amritk/nish/blob/main/std/array.ts) | the array methods that take a callback, and `slice`: `xs.map(f)`, `filter`, `some`, `every`, `findIndex` and `slice`, each a plain loop compiled once per callback, with no function pointer. A program never imports it: a call to one of those methods on an array loads it, and the compiler routes `xs.map(f)` to `map` or `mapIndexed` by how many parameters `f` takes. Each walks the array in order up to the length it had when the call began, as `Array.prototype` does, and `some`, `every` and `findIndex` stop at the element that decides the answer; a callback that shrinks the array ends the walk at the new length, where JavaScript goes on. Under Node the methods are the platform's own (`tests/cases/arr_map`, `arr_filter` and their kin) |
@@ -113,10 +113,10 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
113
113
  | [`crypto/ct.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ct.ts) | `timingSafeEqual(a, b)`, which reads every byte whatever it holds, and `timingSafeEqualAt(a, aOff, b, bOff, len)` over two windows, which answers `false` for a window outside its array. Two lengths that differ answer `false` at once, because a length is public, and so does an array longer than 2^31 − 1 bytes | — |
114
114
  | [`crypto/bcrypt.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt.ts) | `bcryptHash(password, salt, cost)`, the 60-character `$2b$` hash of a `Secret<u8[]>` password under a 16-byte salt and a cost of 4 to 31, and `bcryptVerify(password, hash)`, which reads `$2a$`, `$2b$` and `$2y$` hashes, refuses `$2x$`, and compares in constant time. The first 72 bytes of a password count, up to its first NUL, as under libxcrypt's `crypt_r` (where other implementations differ: [the interoperability table](../docs/security/crypto-bcrypt.md#interoperability)); the Blowfish state is wiped before either returns. `bcryptHash4(p0, p1, p2, p3, salts, cost)` and `bcryptVerify4(p0, p1, p2, p3, hashes)` do up to four at once, interleaved (four in the time of about 1.2 single hashes on one core), each lane the single path's answer; verify groups lanes by cost, and a malformed lane makes the whole call an `Err` naming it. `BCRYPT_MAX_PASSWORD`, `BCRYPT_HASH_LENGTH`, `BCRYPT_SALT_SIZE`, `BCRYPT_MIN_COST`, `BCRYPT_MAX_COST`. A `std/threads` task may call all four ([BCRYPT-9](../docs/security/crypto-bcrypt.md#findings)) | OpenBSD `bcrypt(3)`; crypt_blowfish 1.3 for `$2a$` and `$2y$` |
115
115
  | [`crypto/bcrypt-batch.ts`](https://github.com/amritk/nish/blob/main/std/crypto/bcrypt-batch.ts) | `bcryptBatcher({ width, holdNanos, cores, cost })`, a login batcher: `verify(password, hash, now)` and `hash(password, salt, now)` queue a request and answer its ticket, `waitNanos(now)` says when a run is due (a full batch, or the oldest request held `holdNanos`), and `run(now)` sends up to `width × cores` requests as `bcryptVerifyN` / `bcryptHashN` batches on one `std/threads` task per core and answers a `BcryptAnswer` (`ticket`, `ok`, `hash`, `error`) for each. It keeps and wipes its own copy of each password; a damaged stored hash answers its `Err` on its own row ([the record](../docs/security/crypto-bcrypt.md#the-login-batcher)) | — |
116
- | [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
117
- | [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
116
+ | [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, with the buffer forms `base64StdPadEncodeInto(data, start, length, out, at)` and `base64StdPadDecodedLength(text, start, length)` that allocate nothing, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
117
+ | [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, `Sha1`, whose `digestInto(data, start, length, out, at)` hashes a slice into a caller's buffer and allocates nothing after it is built, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only, not streaming; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
118
118
  | [`crypto/x25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x25519.ts) | `x25519(scalar, u)`, the shared secret as a `Secret<u8[]>`, and `x25519Base(scalar)`, the public key, each from a `Secret<u8[]>` scalar, on ten 25.5-bit limbs in `i64`. Either answers `null` unless its arguments are `X25519_SIZE` (32) bytes; the scalar is clamped on a copy, which is wiped | RFC 7748 §5.2, §6.1, Wycheproof `x25519_test` |
119
- | [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public. Sign and verify panic on a message longer than 2^31 − 1 bytes. It reuses `crypto/x25519.ts`'s field arithmetic | RFC 8032 §5.1, §7.1 |
119
+ | [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public. A message longer than 2^31 − 1 bytes makes sign answer `null` and verify answer `false`. It reuses `crypto/x25519.ts`'s field arithmetic | RFC 8032 §5.1, §7.1 |
120
120
  | [`crypto/chacha20poly1305.ts`](https://github.com/amritk/nish/blob/main/std/crypto/chacha20poly1305.ts) | `chacha20Poly1305Seal(key, nonce, aad, plaintext)`, which answers the ciphertext followed by the 16-byte tag, and `chacha20Poly1305Open`, which checks the whole tag before it decrypts anything and answers `null` for a message that does not authenticate. Beneath them `chacha20Block`, `chacha20`, `chacha20QuarterRound`, `poly1305` and `poly1305KeyGen`, and `chacha20HeaderMask`, QUIC's 5-byte header-protection mask. Every input of the wrong length answers `null`. What a call derives from the key — the ChaCha20 state, the keystream, the Poly1305 key, `r` and accumulator, and on open the tag it compared — is wiped with `wipe`'s volatile stores before the call returns, the refusal path included. Natively, on x86-64 with AVX2 or on AArch64, the compiler sends the keystream of a message of 256 bytes or more to the runtime's kernel instead (`runtime/runtime-chacha20.c`), and `NISH_CHACHA20=soft` pins the Nish code | RFC 8439 §2, RFC 9001 §5.4.4, Wycheproof `chacha20_poly1305` (all 325 cases) |
121
121
  | [`crypto/aes.ts`](https://github.com/amritk/nish/blob/main/std/crypto/aes.ts) | AES-128 and AES-256, bitsliced four blocks at a time with the Boyar–Peralta S-box circuit, so no table is read; natively, on a CPU with AES-NI and PCLMULQDQ or the ARMv8 AES and PMULL instructions, the compiler sends the key schedule, the block, GCTR and GHASH to the runtime's kernels instead (`runtime/runtime-aes.c`), and `NISH_AES=soft` pins the bitsliced code: `aesKey(key)` expands a 16- or 32-byte key into an `AesKey` (or `aesKeyInto(key, out)` into one the caller holds, allocating nothing that outlives the call), then `aesEncryptBlock`, `aesGcmSeal` / `aesGcmOpen` (tag last, checked in full before anything is decrypted; any non-empty IV) and `aesHeaderMask`. AES-192 is out of scope, and a wrong length answers `null`, as does an `AesKey` not made by `aesKey`; one whose H is zero opens nothing. An `AesKey` holds its round keys in `roundKeys` and H in `h`, two `u64` words (high, low); `aesKeyWipe(key)` zeroes both with `wipe`'s volatile stores, the kernels' powers of H after the schedule included, and is how a holder drops a key. The bitsliced schedule's, block's and GCTR's working copies, the tag's E(K, J0) block, the tag open compared and J0 itself are wiped the same way before they are released | FIPS 197, SP 800-38D, RFC 9001 §5.4.3, Wycheproof `aes_gcm` (all 316 cases; the 103 AES-192 ones check that the key is refused) |
122
122
  | [`crypto/p256.ts`](https://github.com/amritk/nish/blob/main/std/crypto/p256.ts) | ECDSA over P-256 with RFC 6979's deterministic nonces: `p256PublicKey(priv)` (65-byte uncompressed SEC1) from a `Secret<u8[]>` private key, `p256Sign` / `p256Verify` over a digest and `p256SignSha256` / `p256VerifySha256` over a message, and `p256SignSha256Into(scratch, priv, msg, off, len, out, at)`, the same signature written into the caller's window in a `P256SignScratch` made once, keeping nothing in the arena; a signature is `r` and `s`, 32 big-endian bytes each, not DER (`crypto/x509.ts`'s `x509DerSignatureRS` converts one). A malformed key, a point off the curve or an `r` or `s` out of range answers `null` or `false`, never a panic. ECDSA is malleable, and `p256Verify` accepts a high `s`: when `(r, s)` verifies, so does `(r, n − s)` | RFC 6979 A.2.5, Wycheproof `ecdsa_secp256r1_sha256`, `_sha256_p1363`, `_sha512` and `_sha512_p1363` |
@@ -212,7 +212,7 @@ libdeflate: `bench/gzip/`; against Go, Rust, Java, Node, Bun and Python:
212
212
  | Module | What it is | Reproduces |
213
213
  | --- | --- | --- |
214
214
  | [`compress/deflate.ts`](https://github.com/amritk/nish/blob/main/std/compress/deflate.ts) | `Deflater(level)` and `Inflater`, raw DEFLATE. Levels 0 (stored), 1 to 3 (greedy on a four-byte hash, `DEFLATE_FAST` = 1) and 4 to 9 (lazy, `DEFLATE_DEFAULT` = 6); each block is the smallest of dynamic, fixed and stored by its exact size. `compress(src, off, len, out, at)` answers the end or `DEFLATE_NO_ROOM` (-1); `deflateBound(n)` / `compressBound(n)` are the most any level writes. `decompress(src, off, len, out, at, limit)` answers the end or a `DEFLATE_ERR_*` code (truncated, block type, stored length, Huffman, symbol, distance, output limit, trailing) and never panics on a stream; `inflate` is the resumable step under it (`INFLATE_DONE`, `INFLATE_NEED_INPUT`, `INFLATE_NEED_OUTPUT`). `FixedDeflater` is the small-body encoder: one fixed-Huffman block, a 16 KB window, nothing kept between calls, two to four times faster than `DEFLATE_FAST` at about 1.35 times its size; `fixedDeflateBound(n)` is the most it writes | RFC 1951: every level against Node's zlib both ways (`tests/link/std_compress_node`), round trips of empty to 1 MB inputs, a 1,500-input fuzz, every prefix and random corruption refused (`tests/link/std_compress`) |
215
- | [`compress/gzip.ts`](https://github.com/amritk/nish/blob/main/std/compress/gzip.ts) | `GzipCompressor(level)` / `GzipDecompressor` one-shot (the decompressor reads concatenated members, refuses trailing bytes, checks the header CRC, CRC-32 and length: `GZIP_ERR_HEADER`, `GZIP_ERR_CRC`, `GZIP_ERR_SIZE`), `gzipCompress` / `gzipDecompress`; `GzipFixedCompressor`, the same framing round `FixedDeflater` (`gzipFixedBound(n)`); `GzipWriter` (`write`, `flush`, `finish`, `bound`) and `GzipReader` (`feed` or `inputBuffer` / `commit`, `endInput`, `read` answering bytes, `GZIP_NEED_INPUT`, `GZIP_END` or an error, with a total `limit`) for bodies that arrive in pieces | RFC 1952: Node's gzip at every level, strategy and window, through both readers; the writer's output through Node's gunzip (`std_compress_node`, `std_compress`) |
215
+ | [`compress/gzip.ts`](https://github.com/amritk/nish/blob/main/std/compress/gzip.ts) | `GzipCompressor(level)` / `GzipDecompressor` one-shot (the decompressor reads concatenated members, refuses trailing bytes, checks the header CRC, CRC-32 and length: `GZIP_ERR_HEADER`, `GZIP_ERR_CRC`, `GZIP_ERR_SIZE`), `gzipCompress` / `gzipDecompress`; `GzipFixedCompressor`, the same framing round `FixedDeflater` (`gzipFixedBound(n)`); `GzipWriter` (`write`, `flush`, `finish`, `bound`, `start`; `GZIP_ERR_FINISHED` after `finish`) and `GzipReader` (`feed` or `inputBuffer` / `commit`, `endInput`, `read` answering bytes, `GZIP_NEED_INPUT`, `GZIP_END` or an error, with a total `limit`) for bodies that arrive in pieces | RFC 1952: Node's gzip at every level, strategy and window, through both readers; the writer's output through Node's gunzip (`std_compress_node`, `std_compress`) |
216
216
  | [`compress/zlib.ts`](https://github.com/amritk/nish/blob/main/std/compress/zlib.ts) | `ZlibCompressor(level)` / `ZlibDecompressor`, `zlibCompress` / `zlibDecompress`: the two-byte header and Adler-32 trailer (`ZLIB_ERR_HEADER`, `ZLIB_ERR_ADLER`, `ZLIB_ERR_DICTIONARY` for `FDICT`) | RFC 1950, against Node's `deflateSync` / `inflateSync` (`std_compress_node`) |
217
217
  | [`compress/checksum.ts`](https://github.com/amritk/nish/blob/main/std/compress/checksum.ts) | `Crc32` (slicing-by-8 tables built once; `update(crc, buf, off, len)`), `crc32` for a one-off, `adler32`, `adler32Update`. Natively the compiler sends `update`'s walk to `runtime/runtime-checksum.c` where the CPU has PCLMULQDQ or the ARMv8 CRC32 instructions, chosen once per process; `NISH_CRC32=soft` pins the tables | The check values of "123456789", pieces against the whole, Adler-32's deferred reduction against its definition (`std_compress`); every kernel against a bit-at-a-time reference (`tests/simd/crc32.c`); both paths on the same programs (`tests/link/std_compress_crc_paths`, `std_compress_crc_diff`) |
218
218
 
@@ -257,7 +257,7 @@ reads one, and it still takes its randomness as an argument.
257
257
  | [`net/fetch.ts`](https://github.com/amritk/nish/blob/main/std/net/fetch.ts) | A blocking HTTP/1.1 client for command-line programs: `fetchSync(request, options)` looks the host up, connects, sends an `HttpRequest` (`method`, `url`, `header(name, value)`, `body`) and answers an `HttpResponse` (`status`, `reason`, `url`, `header(name)`) once its head is in, its body read through `body.read` or `body.readAll(limit)`; null on a failure. `FetchSyncClient(options)` does the same and keeps one connection alive between fetches, sending an idempotent request once more when a kept connection turns out to be gone, and says why a fetch failed in `error` (an `HTTP_E_*` code, `httpErrorName`) and `errorText`. `HttpOptions` bounds every wait (`connectTimeoutMs`, `readTimeoutMs`, `totalTimeoutMs`) and every body (`maxBodyBytes`), follows redirects only when asked (`followRedirects`, `maxRedirects`, `crossOriginRedirects`, never https to http, credentials dropped across origins), and reads `http_proxy`, `https_proxy` and `no_proxy` when `useEnvProxy` is set (`HTTP_PROXY` ignored under CGI; https through `CONNECT`). Every byte goes through `nish/net/http1-client-codec`. Native only. Record: [`docs/security/fetch.md`](../docs/security/fetch.md) | RFC 9110 §9.2.2 and §15.4, RFC 9112; a loopback server and proxy in the test itself: keep-alive, retries, redirects, proxies, timeouts and body caps (`tests/link/net_http_fetch`) |
258
258
  | [`net/outbound.ts`](https://github.com/amritk/nish/blob/main/std/net/outbound.ts) | The policy for fetching URLs your program did not choose, set as `HttpOptions.outbound`: `OutboundPolicy` reaches only public addresses (no loopback, private, link-local, CGNAT, metadata or other special-purpose range, IPv4-mapped, NAT64 and 6to4 forms judged as the IPv4 address they carry), checked on the resolved address the client then connects to, so DNS rebinding cannot move it; every redirect hop is checked again, the proxy is not used, and redirects, total time and body size are capped. `permit(cidr)` lets a trusted prefix through, `allowHost(name)` limits the names a URL or hop may carry (`HTTP_E_BLOCKED` before the lookup). Native only. Record: [`docs/security/outbound.md`](../docs/security/outbound.md) | RFC 6890, RFC 4291, RFC 6052, RFC 3056 and the IANA special-purpose address registries; every range at its edges and a loopback server fetched with and without a policy (`tests/link/net_outbound`) |
259
259
  | [`net/tls/ticket.ts`](https://github.com/amritk/nish/blob/main/std/net/tls/ticket.ts) | Session tickets a server seals for itself (RFC 8446 §4.6.1): `tlsTicketSeal` and `tlsTicketOpen` seal a `TlsTicketState` (suite, issue time, lifetime, chain start, server name, resumption PSK) under ChaCha20-Poly1305 with a borrowed `Secret<u8[]>` key, as key id ‖ nonce ‖ ciphertext ‖ tag, and wipe the plaintext on every path. `TlsTicketKeyInfo`, `tlsTicketKeyDraw` and `tlsTicketKeyDue` are a key's public record, its draw and when to replace it: a key seals for 12 h of awake time and 2^30 tickets, and opens for 14 h. `TlsTicketStrikes` is the bounded strike register (§8.1) that makes a ticket single-use, failing closed when full | `tests/link/net_tls_ticket`: every bound at its instant and 1 ns past it, a flipped bit in each region, three key rotations, replay and a full register |
260
- | [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
260
+ | [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101; `WsAcceptKey`, `websocketRequestKeyField` and `websocketWriteUpgradeResponse`, the same accept written into storage a server keeps, so a connection's later handshakes allocate nothing. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
261
261
  | [`net/http1-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-server.ts) | The server side of HTTP/1.1: `Http1Connection`, sans-IO, drives an `Http1Parser` — `feed`, then `next()` answers `H1_REQUEST` (the parser's head), `H1_BODY` (at most `chunkSize` bytes, either framing), `H1_END`, `H1_WRITE` (a held-back write may go again), `H1_WS_MESSAGE`, `H1_WS_CLOSE` or the final `H1_ERROR`; the program answers with `respond(status, names, values, bodyLength)`, `write` and `end`, or `acceptWebSocket(protocol)` and then `sendFrame` and `closeWebSocket`. Keep-alive and pipelining one exchange at a time, a response with a length or chunked (unframed to an HTTP/1.0 client), `Connection` and the framing decided by the server, every parser refusal answered with its status and a close, pings and closes answered on a WebSocket. Two slot pools for a program that owns its loop: `Http1Server` on plain TCP and `Http1TlsServer` on `nish/net/tls-tcp` with ALPN `http/1.1` or none (`accept`, `readable` / `writable`, `next(slot)`, `flush(slot)`, `close`, `expire(now)` for the idle timeout and the deadline for a whole head, `headTimeout`, against a client that trickles its head). Both build a slot's connection on the first accept into it rather than at start-up. `Http1Server` reads a socket until a short read rather than until it would block, takes a free slot off a stack of released slots or the next never-used one rather than scanning for one, and answers `rearm(slot, wants)`, whether the interest changed and needs a `pollModify` at all: a keep-alive request is one `recv` and one `send`. The slots borrow their output from one `Http1OutputPool` while they write and give it back once sent, so a pool's memory follows the connections the socket is holding back, not its size: an idle slot holds no output buffer. Every final response carries a `Date` from `HttpDate`, which reads `Date.now()` and formats at most once a second, shared by a pool's slots; `pin(unixMs)` fixes it for a test, and a program's own `date` field replaces it. Every cap is an `Http1Config` number fixed at start-up, and a warmed slot allocates nothing per request (`docs/security/http1-codec.md`). Native only, as `nish:net` is | RFC 9112 §6, §7, §9; RFC 9110 §9.3.2, §15; RFC 6455 §4.2, §5.5. Nish clients over loopback against both carriers, requests cut at every byte, 2 MiB bodies each way, pipelining, a WebSocket echo, the arena flat over two hundred requests, the date formatted once a second, and every refusal (`tests/link/net_http1_server`); `curl` against its `serve` mode |
262
262
  | [`net/url.ts`](https://github.com/amritk/nish/blob/main/std/net/url.ts) | The request target's path and query, read in place: `urlQueryStart` finds the `?`, `UrlPathSegments` splits a path on the raw `/` and `UrlQuery` yields a query's pairs as offsets, both reusable by `reset`; `percentDecode` and `percentDecodePathSegment` decode a window into the caller's array and answer the length or a `URL_DECODE_ERR_*` code, `percentDecodeErrorAt` answers the offset an error is at, and `urlQueryFind` finds a key. Decoding is strict by default (a malformed escape and `%00` are refused); `URL_DECODE_FORM`, `URL_DECODE_LENIENT` and `URL_DECODE_ALLOW_NUL` together decode valid UTF-8 as `URLSearchParams` does. A query yields at most `UrlQueryLimits.maxPairs` pairs (100 by default) and then answers `URL_QUERY_ERR_PAIRS`. The byte API allocates nothing; `urlDecode` and `urlQueryGet` answer strings and refuse what is not UTF-8. Whole URLs: `urlParse` splits an absolute URL into a `Url` (`scheme`, `hasAuthority`, `username`, `password`, `host`, `port`, `path`, `query`, `fragment`, each still percent-encoded, the scheme and host lower-cased), `urlResolve(base, ref)` resolves a reference against one, `urlSerialize` writes one back, and `urlDefaultPort` and `urlOrigin` answer the port and the origin a client connects to. Both refuse with null what two readers could take for different hosts: a byte outside printable ASCII, a backslash, a malformed `%`, a second `@`, a non-unreserved host byte, a numeric host that is not strict dotted-decimal IPv4, an IPv6 zone, a port past 65535. Records: [`docs/security/url.md`](../docs/security/url.md) | RFC 3986 §2.1 and §3.3, the WHATWG URL Standard's percent-decode and `application/x-www-form-urlencoded` parser; `decodeURIComponent` and `URLSearchParams` on 3,000 seeded inputs; RFC 3986 §3 and §5.2, every §5.4 example, 57 refusals and 4,000 seeded round trips in both number modes (`tests/link/net_url_parse`) |
263
263
  | [`net/http-fields.ts`](https://github.com/amritk/nish/blob/main/std/net/http-fields.ts) | The header model HTTP/2 and HTTP/3 share, version-neutral: `HttpFields` reads a decoded section with `readRequest(names, values, extendedConnect)`, `readResponse` or `readTrailers` into `method`, `scheme`, `authority`, `path`, `protocol`, `status`, the regular fields in order (`get(name)`) and `contentLength`, answering `HTTP_FIELDS_OK` or the first refusal: a name that is empty, not a token or not lowercase; a value with NUL, CR or LF or whitespace at an end; a connection-specific field (`te` but `trailers` included); a pseudo-header unknown, repeated, after a regular field, forbidden by the shape or missing; a pseudo-header value of the wrong syntax; a `host` that disagrees with `:authority`; a bad or disagreeing `content-length`. `:protocol` (RFC 8441) is read only where the caller enabled extended CONNECT. `httpFieldNameValid`, `httpFieldValueValid`, `httpFieldConnectionSpecific` and `httpFieldsCheckOutgoing` check one name, one value or a section a program sends. `httpDateWrite(out, at, seconds)` writes a second since 1970 as the IMF-fixdate a `Date` field holds (`HTTP_DATE_SIZE` bytes, to 9999), reading no clock, so it compiles for wasm32 | RFC 9110 §5, RFC 9113 §8.2–§8.5, RFC 9114 §4.2–§4.3, RFC 8441 §4; every refusal in `tests/link/net_http_fields`; RFC 9110 §5.6.7, every day from 1970 to 2399 (`tests/link/net_http_date`) |
package/std/array.ts CHANGED
@@ -291,9 +291,17 @@ export const slice = <T>(xs: readonly T[], start: number, end: number): T[] => {
291
291
  export const sliceFrom = <T>(xs: readonly T[], start: number): T[] => slice(xs, start, xs.length)
292
292
 
293
293
  /**
294
- * A copy of the whole of `xs`: what `xs.slice()` compiles to.
294
+ * A copy of the whole of `xs`: what `xs.slice()` compiles to. It copies
295
+ * directly rather than through `slice`, whose range check can panic and
296
+ * which a whole copy never needs, so it cannot panic but out of memory.
295
297
  *
296
298
  * @param xs the array copied; it is not changed.
297
299
  * @returns a new array with the same elements.
298
300
  */
299
- export const sliceAll = <T>(xs: readonly T[]): T[] => slice(xs, 0, xs.length)
301
+ export const sliceAll = <T>(xs: readonly T[]): T[] => {
302
+ const out: T[] = []
303
+ for (let i: i32 = 0; i >= 0 && i < toI32(xs.length); i++) {
304
+ out.push(xs[i])
305
+ }
306
+ return out
307
+ }