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/std/term.ts CHANGED
@@ -79,33 +79,40 @@
79
79
  * sends no releases, so while `releasesAreSynthetic` is set (until the first
80
80
  * real release) a key counts as let go when its repeats stop: `firstRepeatMs`
81
81
  * (700 ms) after a press that has not repeated and `releaseGapMs` (100 ms)
82
- * after its last repeat. Silence is measured in stream time when the caller has
83
- * one: term-io sends an in-order query after each frame and calls `delivered`
84
- * with the send time of each one answered, since by then everything the
85
- * terminal generated before it has arrived. Measured that way a stall, a burst
86
- * or jittery reads delay the watermark as much as the keys, so a held key never
87
- * flickers and a tap comes up 700 ms plus one round trip after its press. With
88
- * no watermark yet, silence is wall-clock time between `apply`s, which a link
89
- * that reads in bursts more than `releaseGapMs` apart can mistake for a key let
90
- * go. While acks stop, nothing is released: there is no wall-clock backstop,
91
- * and a caller that stops getting answers clears `watermarked` to fall back to
92
- * the wall clock. term-io does so once 1000 ms pass with no query answered,
93
- * frames sent or not, which no working link reaches while it draws.
94
- * Within one read the caller `apply`s its events before calling `delivered` for
95
- * the answer it carries: a `tick` between the two would judge keys against a
96
- * watermark that already covers repeats not yet applied, and report a release
97
- * and then a press. A non-finite time is ignored. Under X11 and Windows only
98
- * the last key pressed auto-repeats, so holding W and then pressing D lets W go
99
- * `releaseGapMs` after its last repeat. A real release of a key not down is
100
- * dropped, so one arriving after its key was made up as released is not
101
- * reported twice. Under kitty a real release that is lost leaves its key down
102
- * until focus is lost, and for good without focus reporting. A key the batch
103
- * `apply` takes names stays down. A made-up release carries the code and
104
- * modifiers the key last came with. Losing focus lets every key go, and Ctrl-C
105
- * becomes `EVENT_QUIT` while `quitOnCtrlC` is set. Under the kitty protocol a
106
- * non-Latin layout sends Ctrl-C as its own letter (`ESC [ 1089 ; 5 u` for
107
- * Russian С), which is not read as a quit: the base-layout key that flag 4
108
- * (report alternate keys) adds is not read yet.
82
+ * after its last repeat.
83
+ *
84
+ * Silence is measured in stream time when the caller has one: term-io sends an
85
+ * in-order query after each frame and calls `delivered` with the send time of
86
+ * each one answered, since by then everything the terminal generated before it
87
+ * has arrived. Measured that way a stall, a burst or jittery reads delay the
88
+ * watermark as much as the keys, so a held key never flickers and a tap comes
89
+ * up 700 ms plus one round trip after its press.
90
+ *
91
+ * With no watermark yet, silence is wall-clock time between `apply`s, which a
92
+ * link that reads in bursts more than `releaseGapMs` apart can mistake for a
93
+ * key let go. While acks stop, nothing is released: there is no wall-clock
94
+ * backstop, and a caller that stops getting answers clears `watermarked` to
95
+ * fall back to the wall clock. term-io does so once 1000 ms pass with no query
96
+ * answered, frames sent or not, which no working link reaches while it draws.
97
+ *
98
+ * Within one read the caller `apply`s its events before calling `delivered` for
99
+ * the answer it carries: a `tick` between the two would judge keys against a
100
+ * watermark that already covers repeats not yet applied, and report a release
101
+ * and then a press. A non-finite time is ignored. Under X11 and Windows only
102
+ * the last key pressed auto-repeats, so holding W and then pressing D lets W go
103
+ * `releaseGapMs` after its last repeat.
104
+ *
105
+ * A real release of a key not down is dropped, so one arriving after its key
106
+ * was made up as released is not reported twice. Under kitty a real release
107
+ * that is lost leaves its key down until focus is lost, and for good without
108
+ * focus reporting. A key the batch `apply` takes names stays down. A made-up
109
+ * release carries the code and modifiers the key last came with. Losing focus
110
+ * lets every key go, and Ctrl-C becomes `EVENT_QUIT` while `quitOnCtrlC` is
111
+ * set.
112
+ *
113
+ * Under the kitty protocol a non-Latin layout sends Ctrl-C as its own letter
114
+ * (`ESC [ 1089 ; 5 u` for Russian С), which is not read as a quit: the
115
+ * base-layout key that flag 4 (report alternate keys) adds is not read yet.
109
116
  *
110
117
  * **The same bytes under Node.** Natively a string is UTF-8 bytes, and `flush`
111
118
  * builds its answer as bytes and makes one string of them. Under Node a string
@@ -114,10 +121,11 @@
114
121
  * way, which `tests/run.js` checks ("nish/term prints the same bytes under
115
122
  * runtime/nish.mjs"). `text` reads a string's code points as UTF-8 natively and
116
123
  * as UTF-16 under Node, so a string literal draws the same cells both ways.
117
- * A `TermEvent`'s `text` is made from bytes the terminal sent: natively it
118
- * holds them as they came, and under Node they are decoded as UTF-8 without
119
- * checking, so malformed UTF-8 in a paste or reply can differ between the two.
120
- * Integer division is spelled `(a / b) | 0`, which truncates in both.
124
+ *
125
+ * A `TermEvent`'s `text` is made from bytes the terminal sent: natively it
126
+ * holds them as they came, and under Node they are decoded as UTF-8 without
127
+ * checking, so malformed UTF-8 in a paste or reply can differ between the two.
128
+ * Integer division is spelled `(a / b) | 0`, which truncates in both.
121
129
  */
122
130
 
123
131
  /** The terminal's own colour, foreground or background: SGR 39 and 49. */
@@ -902,11 +910,12 @@ export class Screen {
902
910
  * otherwise — and a gap of up to three unchanged ASCII cells in the current
903
911
  * style is rewritten instead, which is shorter than the move. A style is sent
904
912
  * only when it differs from the previous cell's, and only the parts that
905
- * differ, from a reset when an attribute has to be turned off. A flush that
906
- * leaves the terminal in a style other than the default ends with `ESC [ 0
907
- * m`, so what the caller writes next starts plain. With `sync` set, a flush
908
- * that changes anything is wrapped in `beginSync` and `endSync`, in the same
909
- * string, so the terminal paints the frame whole.
913
+ * differ, from a reset when an attribute has to be turned off.
914
+ *
915
+ * A flush that leaves the terminal in a style other than the default ends
916
+ * with `ESC [ 0 m`, so what the caller writes next starts plain. With `sync`
917
+ * set, a flush that changes anything is wrapped in `beginSync` and `endSync`,
918
+ * in the same string, so the terminal paints the frame whole.
910
919
  *
911
920
  * @returns The escapes and glyphs, to `write`; `""` when nothing changed.
912
921
  */
@@ -1361,16 +1370,18 @@ export class TermEvent {
1361
1370
  }
1362
1371
 
1363
1372
  /**
1364
- * Bytes from a terminal in raw mode, turned into key events. A read can end
1365
- * in the middle of an escape sequence or a UTF-8 character; the decoder keeps
1366
- * the start and finishes it with the next `feed`. An ESC on its own is both the
1373
+ * Bytes from a terminal in raw mode, turned into key events. A read can end in
1374
+ * the middle of an escape sequence or a UTF-8 character; the decoder keeps the
1375
+ * start and finishes it with the next `feed`. An ESC on its own is both the
1367
1376
  * escape key and the start of every arrow, so it is held until either more
1368
1377
  * bytes complete a sequence or `escapeTimeoutMs` passes with none, and then it
1369
- * is `KEY_ESCAPE`. Whatever is held past the timeout is given up the same way:
1370
- * the ESC as `KEY_ESCAPE`, the bytes after it as keys of their own, and an
1371
- * unfinished UTF-8 character as U+FFFD. The clock is the caller's: each call
1372
- * takes the time now in milliseconds, from any origin, so long as it does not
1373
- * go backwards.
1378
+ * is `KEY_ESCAPE`.
1379
+ *
1380
+ * Whatever is held past the timeout is given up the same way: the ESC as
1381
+ * `KEY_ESCAPE`, the bytes after it as keys of their own, and an unfinished
1382
+ * UTF-8 character as U+FFFD. The clock is the caller's: each call takes the
1383
+ * time now in milliseconds, from any origin, so long as it does not go
1384
+ * backwards.
1374
1385
  *
1375
1386
  * `feedEvents` and `pollEvents` decode the same bytes into `TermEvent`s
1376
1387
  * instead: keys with their modifiers and press, repeat or release, the mouse,
@@ -1551,21 +1562,24 @@ export class KeyDecoder {
1551
1562
  /**
1552
1563
  * Which keys are down, from the events a `KeyDecoder` made — what a game asks
1553
1564
  * each frame. Under the kitty protocol with event types (flag 2) a terminal
1554
- * sends real releases. Without it a terminal sends nothing when a key comes
1555
- * up, only the press again as it auto-repeats, so a key is let go once its
1556
- * repeats stop: `releaseGapMs` after its last repeat, and `firstRepeatMs` after
1557
- * a press that has not repeated. The system waits before its first repeat —
1558
- * 660 ms under X11 by default, 500 under Windows, shorter under macOS — and
1559
- * repeats every 30–40 ms; a longer delay needs `firstRepeatMs` raised, and a
1560
- * slower rate `releaseGapMs`. Input arrives late and in bursts (over SSH, reads
1561
- * 150–250 ms apart are usual), so when the reads alone are known the silence
1562
- * is not: a caller that sends in-order queries calls `delivered(sentAtMs)` as
1563
- * each is answered, and silence is then measured against that watermark rather
1564
- * than the clock. A key last seen in a read at `A` is let go once the watermark
1565
- * reaches `A + gap`: had it still been down, the terminal would have generated
1566
- * a repeat before then, and it would have arrived ahead of the answer. Until
1567
- * the first `delivered`, and after the caller clears `watermarked`, the gap is
1568
- * measured against `nowMs`. Pure, with the caller's clock, as `KeyDecoder` is.
1565
+ * sends real releases. Without it a terminal sends nothing when a key comes up,
1566
+ * only the press again as it auto-repeats, so a key is let go once its repeats
1567
+ * stop: `releaseGapMs` after its last repeat, and `firstRepeatMs` after a press
1568
+ * that has not repeated.
1569
+ *
1570
+ * The system waits before its first repeat — 660 ms under X11 by default, 500
1571
+ * under Windows, shorter under macOS — and repeats every 30–40 ms; a longer
1572
+ * delay needs `firstRepeatMs` raised, and a slower rate `releaseGapMs`. Input
1573
+ * arrives late and in bursts (over SSH, reads 150–250 ms apart are usual), so
1574
+ * when the reads alone are known the silence is not: a caller that sends
1575
+ * in-order queries calls `delivered(sentAtMs)` as each is answered, and silence
1576
+ * is then measured against that watermark rather than the clock.
1577
+ *
1578
+ * A key last seen in a read at `A` is let go once the watermark reaches `A +
1579
+ * gap`: had it still been down, the terminal would have generated a repeat
1580
+ * before then, and it would have arrived ahead of the answer. Until the first
1581
+ * `delivered`, and after the caller clears `watermarked`, the gap is measured
1582
+ * against `nowMs`. Pure, with the caller's clock, as `KeyDecoder` is.
1569
1583
  */
1570
1584
  export class KeyState {
1571
1585
  /** How long after its last repeat a key is let go, in milliseconds (100 by default). */
package/std/text.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  /**
2
2
  * `std/text` — the string operations a program has to write itself.
3
3
  *
4
- * import { replaceAll, splitLines, splitWhitespace, trim } from "nish/text";
4
+ * import { asciiUpper, padStart, replaceAll, split, splitLines, splitWhitespace, trim } from "nish/text";
5
5
  *
6
6
  * export const main = (): i32 => {
7
7
  * const lines: string[] = splitLines("a b\n c \n"); // ["a b", " c "]
8
8
  * const words: string[] = splitWhitespace(lines[0]); // ["a", "b"]
9
9
  * const c: string = trim(lines[1]); // "c"
10
10
  * const dashed: string = replaceAll("a b", " ", "-"); // "a-b"
11
+ * const fields: string[] = split("a,,b", ","); // ["a", "", "b"]
12
+ * const loud: string = asciiUpper("get_id"); // "GET_ID"
13
+ * const code: string = padStart("7", 3, "0"); // "007"
11
14
  * return toI32(words.length);
12
15
  * };
13
16
  *
@@ -21,10 +24,13 @@
21
24
  * **So a program that reads a file and wants its lines writes the loop.** This
22
25
  * module is that loop, written once. Every offset here is a **byte** offset,
23
26
  * like `s.length` itself, and every function but one is ASCII-only where it
24
- * inspects characters at all — a UTF-8 string passes through `splitLines` and
25
- * `split` untouched, because a newline and a space cannot appear inside a
26
- * multi-byte sequence. The one is `codePointLength`, which counts code points
27
- * rather than bytes and answers the same natively and under Node; it says how.
27
+ * inspects characters at all — a UTF-8 string passes through `splitLines`,
28
+ * `splitWhitespace`, `asciiUpper` and `asciiLower` untouched, because an ASCII
29
+ * byte cannot appear inside a multi-byte sequence. The one is
30
+ * `codePointLength`, which counts code points rather than bytes and answers the
31
+ * same natively and under Node; it says how. `padStart` and `padEnd` count a
32
+ * width in `s.length`'s units, so they are the two whose answers differ under
33
+ * Node on text that is not ASCII; each says by how much.
28
34
  *
29
35
  * **Every width this module declares is spelled** (`i32`, never `number`) *and*
30
36
  * every value a builtin hands it is converted at the read: `s.length`,
@@ -181,6 +187,62 @@ export const trim = (text: string): string => trimEnd(trimStart(text))
181
187
  */
182
188
  export const contains = (haystack: string, needle: string): boolean => toI32(haystack.indexOf(needle)) >= 0
183
189
 
190
+ /**
191
+ * The pieces of `text` between the occurrences of `sep`: JavaScript's
192
+ * `text.split(sep)` for a separator that is not empty. A separator at the
193
+ * start, at the end or next to another gives an empty piece, so
194
+ * `split(",a,,b,", ",")` is `["", "a", "", "b", ""]`; `split("", ",")` is
195
+ * `[""]`; and a separator that never occurs gives `[text]`. Compare
196
+ * `splitWhitespace`, which drops the empty pieces.
197
+ *
198
+ * The pieces are the same natively and under Node for any text and any
199
+ * separator, multi-byte ones included: a match is a whole UTF-8 sequence
200
+ * natively and a whole run of UTF-16 units under Node, and a well-formed
201
+ * string holds a code point's encoding only where that code point is. So
202
+ * there is nothing for NL8001 (`--warn-portability`) to warn about, and it
203
+ * does not; the pieces' own `.length`s are still counted in each platform's
204
+ * units, and NL8001 reads those where the program does.
205
+ *
206
+ * **An empty separator panics.** JavaScript splits a string on `""` into its
207
+ * UTF-16 units, which natively would be its bytes, and the two answers differ
208
+ * on any text that is not ASCII. A separator is almost always a literal the
209
+ * caller chose, so an empty one is a mistake in the program, like an index out
210
+ * of range, and not a condition a caller could recover from.
211
+ *
212
+ * @param text The text to split.
213
+ * @param sep The separator, compared byte for byte; it must not be empty.
214
+ * Occurrences are found left to right and do not overlap.
215
+ * @returns A fresh array of the pieces, in order; never empty.
216
+ */
217
+ export const split = (text: string, sep: string): string[] => {
218
+ const sepLength: i32 = toI32(sep.length)
219
+ if (sepLength === 0) {
220
+ panic("split: an empty separator")
221
+ }
222
+ const length: i32 = toI32(text.length)
223
+ const parts: string[] = []
224
+ let start: i32 = 0
225
+ while (true) {
226
+ // Searching from `start` rather than cutting `text` down after each match
227
+ // copies nothing until the piece is taken.
228
+ const at: i32 = toI32(text.indexOf(sep, start))
229
+ // `start` is 0 or one past a match, so it is never negative and never
230
+ // past `length`, and a hit starts at or after `start` and a whole
231
+ // separator before `length`. The tests around the `substring`s therefore
232
+ // always hold, but for the empty tail after a final separator; they are
233
+ // written because they are what proves both bounds within `text`, as in
234
+ // `splitLines`.
235
+ if (at < 0) {
236
+ parts.push(start >= 0 && start < length ? text.substring(start, length) : "")
237
+ return parts
238
+ }
239
+ if (start >= 0 && start < length && at >= 0 && at < length) {
240
+ parts.push(text.substring(start, at))
241
+ }
242
+ start = at + sepLength
243
+ }
244
+ }
245
+
184
246
  /**
185
247
  * `text` with every occurrence of `needle` replaced by `replacement`.
186
248
  *
@@ -373,16 +435,17 @@ const textUnitsAreBytes = (): boolean => toI32("\u00e9".length) === 2
373
435
  * rule would miscount: `"©®±"` is three units in `0x80`–`0xBF`, which are
374
436
  * continuation bytes in UTF-8 but whole characters here. So the function asks
375
437
  * which host it is on (`textUnitsAreBytes`) and, under Node, counts every unit
376
- * except the low half of a surrogate pair. Both walks answer the same for any
377
- * string literal, a lone surrogate escape included: it is three WTF-8 bytes
378
- * with one leading byte natively, and one unit under Node. They differ for
379
- * text built from bytes: `String.fromBytes` and `String.fromCharCode` give one
380
- * unit per byte under Node, so a string decoded that way, as `nish/json`
381
- * decodes a `\u` escape, counts its UTF-8 bytes there. They also differ for text
382
- * that is not well-formed — bytes that are not UTF-8 natively, where each
383
- * stray continuation byte counts nothing, or the two halves of a pair joined
384
- * at run time, which are one string under Node and two lone surrogates
385
- * natively.
438
+ * except the low half of a surrogate pair.
439
+ *
440
+ * Both walks answer the same for any string literal, a lone surrogate escape
441
+ * included: it is three WTF-8 bytes with one leading byte natively, and one
442
+ * unit under Node. They differ for text built from bytes: `String.fromBytes`
443
+ * and `String.fromCharCode` give one unit per byte under Node, so a string
444
+ * decoded that way, as `nish/json` decodes a `\u` escape, counts its UTF-8
445
+ * bytes there. They also differ for text that is not well-formed — bytes that
446
+ * are not UTF-8 natively, where each stray continuation byte counts nothing, or
447
+ * the two halves of a pair joined at run time, which are one string under Node
448
+ * and two lone surrogates natively.
386
449
  *
387
450
  * @param text The text whose code points are counted.
388
451
  * @returns How many code points `text` holds, counted as above.
@@ -417,3 +480,167 @@ export const codePointLength = (text: string): i32 => {
417
480
  }
418
481
  return toI32(count)
419
482
  }
483
+
484
+ /** The first and last lower-case ASCII letters, `a` and `z`. */
485
+ const ASCII_LOWER_A: i32 = 97
486
+ const ASCII_LOWER_Z: i32 = 122
487
+
488
+ /** The first and last upper-case ASCII letters, `A` and `Z`. */
489
+ const ASCII_UPPER_A: i32 = 65
490
+ const ASCII_UPPER_Z: i32 = 90
491
+
492
+ /** How far apart an ASCII letter's two cases are: `a` is `A` plus this. */
493
+ const ASCII_CASE_DISTANCE: i32 = 32
494
+
495
+ /**
496
+ * `text` with every unit from `low` to `high` moved by `delta`, and every other
497
+ * unit as it was: `asciiUpper` and `asciiLower`'s one walk.
498
+ *
499
+ * Natively the units are bytes, so the answer is built as bytes, one array and
500
+ * one `String.fromBytes`. Under Node a unit can be wider than a byte, so the
501
+ * unchanged runs are cut out of `text` whole and only the changed letters are
502
+ * made one at a time. The name is long for the reason `isTextBlankByte`'s is.
503
+ */
504
+ const shiftTextAsciiRange = (text: string, low: i32, high: i32, delta: i32): string => {
505
+ const length: i32 = toI32(text.length)
506
+ let i: i32 = 0
507
+ if (textUnitsAreBytes()) {
508
+ const bytes: u8[] = []
509
+ while (i < length) {
510
+ const code: i32 = toI32(text.charCodeAt(i))
511
+ bytes.push(toU8(code >= low && code <= high ? code + delta : code))
512
+ i += 1
513
+ }
514
+ return String.fromBytes(bytes, 0, length)
515
+ }
516
+ const parts: string[] = []
517
+ let start: i32 = 0
518
+ while (i < length) {
519
+ const code: i32 = toI32(text.charCodeAt(i))
520
+ if (code >= low && code <= high) {
521
+ // `start` never passes `i`, which is below `length`, so this always
522
+ // holds; it is what proves `start` within `text`, as in `splitLines`.
523
+ if (start >= 0 && start < length) {
524
+ parts.push(text.substring(start, i))
525
+ }
526
+ parts.push(String.fromCharCode(code + delta))
527
+ start = i + 1
528
+ }
529
+ i += 1
530
+ }
531
+ if (start < length) {
532
+ parts.push(text.substring(start, length))
533
+ }
534
+ return parts.join("")
535
+ }
536
+
537
+ /**
538
+ * `text` with its ASCII letters `a` to `z` made `A` to `Z`, and nothing else
539
+ * changed: every other byte, a UTF-8 sequence's included, passes through.
540
+ *
541
+ * This is not JavaScript's `toUpperCase`, which knows Unicode's case table:
542
+ * that gives `"SS"` for `"ß"` and `"É"` for `"é"`, where this gives `"ß"` and
543
+ * `"é"`. That table is more than this runtime has room for, and the text this
544
+ * is for, identifiers, keywords and protocol tokens, is ASCII. On ASCII text
545
+ * the two agree, and this answers the same natively and under Node for any
546
+ * text, since a byte or unit from 97 to 122 is always the letter itself, so
547
+ * NL8001 (`--warn-portability`) has nothing to warn about, and does not.
548
+ *
549
+ * @param text The text whose ASCII letters are upper-cased.
550
+ * @returns A fresh string as long as `text`.
551
+ */
552
+ export const asciiUpper = (text: string): string =>
553
+ shiftTextAsciiRange(text, ASCII_LOWER_A, ASCII_LOWER_Z, -ASCII_CASE_DISTANCE)
554
+
555
+ /**
556
+ * `text` with its ASCII letters `A` to `Z` made `a` to `z`, and nothing else
557
+ * changed: every other byte, a UTF-8 sequence's included, passes through.
558
+ *
559
+ * This is not JavaScript's `toLowerCase`, for the reason `asciiUpper` gives:
560
+ * `"É"` stays `"É"` here. On ASCII text the two agree, and this answers the
561
+ * same natively and under Node for any text.
562
+ *
563
+ * @param text The text whose ASCII letters are lower-cased.
564
+ * @returns A fresh string as long as `text`.
565
+ */
566
+ export const asciiLower = (text: string): string =>
567
+ shiftTextAsciiRange(text, ASCII_UPPER_A, ASCII_UPPER_Z, ASCII_CASE_DISTANCE)
568
+
569
+ /**
570
+ * The padding `padStart` and `padEnd` put beside `text`: `fill` repeated and
571
+ * cut so that `text` and the padding together are `width` units long, or `""`
572
+ * when `text` is that long already or `fill` is empty.
573
+ *
574
+ * `fill` must be ASCII, and `caller` names the function in the panic when it
575
+ * is not. A multi-byte fill cut at a byte width could end in half a UTF-8
576
+ * sequence natively, which is text that is not well-formed, and padding is
577
+ * done with spaces and zeros. The fill is checked before the width, so a bad
578
+ * fill panics whether or not any padding was needed. The name is long for the
579
+ * reason `isTextBlankByte`'s is.
580
+ */
581
+ const textPadding = (text: string, width: i32, fill: string, caller: string): string => {
582
+ const fillLength: i32 = toI32(fill.length)
583
+ let j: i32 = 0
584
+ while (j < fillLength) {
585
+ if (toI32(fill.charCodeAt(j)) >= NON_ASCII) {
586
+ panic(`${caller}: every byte of the fill must be ASCII`)
587
+ }
588
+ j += 1
589
+ }
590
+ const needed: i32 = width - toI32(text.length)
591
+ if (needed <= 0 || fillLength === 0) {
592
+ return ""
593
+ }
594
+ const parts: string[] = []
595
+ let left: i32 = needed
596
+ while (left >= fillLength) {
597
+ parts.push(fill)
598
+ left -= fillLength
599
+ }
600
+ parts.push(fill.substring(0, left))
601
+ return parts.join("")
602
+ }
603
+
604
+ /**
605
+ * `text` with `fill` repeated in front of it until it is `width` units long:
606
+ * JavaScript's `text.padStart(width, fill)` for ASCII text. A `width` no
607
+ * longer than `text`, or an empty `fill`, gives `text` unchanged, and a fill of
608
+ * several characters repeats and is cut at the width, so
609
+ * `padStart("7", 4, "ab")` is `"aba7"`.
610
+ *
611
+ * **`width` counts the units `text.length` counts**: bytes natively and UTF-16
612
+ * units under Node. So on text that is not ASCII the two answers differ:
613
+ * `padStart("é", 3, " ")` is `" é"` natively, where `é` is two bytes, and
614
+ * `" é"` under Node, where it is one unit. NL8001 (`--warn-portability`)
615
+ * does not warn about it: the warning reads offsets in the program it is given,
616
+ * the library's own `text.length` is not walked, and what reaches the caller is
617
+ * a string rather than a number. Pad ASCII text, or count the width with
618
+ * `codePointLength` yourself, when the answer must be the same on both.
619
+ *
620
+ * **A fill that is not ASCII panics**, for the reason `indexOfAny`'s set must
621
+ * be ASCII: natively it would be cut in the middle of a UTF-8 sequence.
622
+ *
623
+ * @param text The text to pad.
624
+ * @param width The length the answer is padded to, in `text.length`'s units.
625
+ * @param fill The ASCII text repeated as the padding; `" "` and `"0"` are
626
+ * the usual ones.
627
+ * @returns `text` with the padding in front; `text` unchanged when no
628
+ * padding is needed.
629
+ */
630
+ export const padStart = (text: string, width: i32, fill: string): string =>
631
+ textPadding(text, width, fill, "padStart") + text
632
+
633
+ /**
634
+ * `text` with `fill` repeated after it until it is `width` units long:
635
+ * JavaScript's `text.padEnd(width, fill)` for ASCII text, with `padStart`'s
636
+ * rules. `padEnd("7", 4, "ab")` is `"7aba"`, and `padEnd("é", 3, " ")` is
637
+ * `"é "` natively and `"é "` under Node.
638
+ *
639
+ * @param text The text to pad.
640
+ * @param width The length the answer is padded to, in `text.length`'s units.
641
+ * @param fill The ASCII text repeated as the padding.
642
+ * @returns `text` with the padding after it; `text` unchanged when no
643
+ * padding is needed.
644
+ */
645
+ export const padEnd = (text: string, width: i32, fill: string): string =>
646
+ text + textPadding(text, width, fill, "padEnd")
package/std/threads.ts CHANGED
@@ -34,17 +34,18 @@
34
34
  * };
35
35
  *
36
36
  * **What is written here is the meaning, not the implementation.** Each body
37
- * below is the sequential program, and it is what runs under Node, what
38
- * `npm run check` type-checks, and what the compiler checks the call against.
39
- * The compiler then recognises the exported templates by module and name
40
- * and lowers an instance of `parallelMapInto`, `parallelFrom` or
41
- * `parallelReduce` onto `nish_parallel_range` (runtime/runtime-parallel.c): it
42
- * replaces the one call that walks the whole range — `mapRange` for a map,
43
- * `fromRange` for a `parallelFrom`, `reduceBlocks` for a reduce — with a region
44
- * that hands each thread a contiguous piece of it, and emits the rest of the
45
- * body as written. `parallelMap` is `parallelMapInto` into an array it
46
- * allocates first. So the length check, its message and the order a reduce combines in
47
- * are this file's, whichever way the program is compiled.
37
+ * below is the sequential program, and it is what runs under Node, what `npm
38
+ * run check` type-checks, and what the compiler checks the call against.
39
+ *
40
+ * The compiler then recognises the exported templates by module and name and
41
+ * lowers an instance of `parallelMapInto`, `parallelFrom` or `parallelReduce`
42
+ * onto `nish_parallel_range` (runtime/runtime-parallel.c): it replaces the one
43
+ * call that walks the whole range — `mapRange` for a map, `fromRange` for a
44
+ * `parallelFrom`, `reduceBlocks` for a reduce — with a region that hands each
45
+ * thread a contiguous piece of it, and emits the rest of the body as written.
46
+ * `parallelMap` is `parallelMapInto` into an array it allocates first. So the
47
+ * length check, its message and the order a reduce combines in are this file's,
48
+ * whichever way the program is compiled.
48
49
  *
49
50
  * **What makes the region safe is checked at the call, not trusted**
50
51
  * (docs/LANGUAGE.md, "Data parallelism"): the function passed as `f` may write
@@ -52,10 +53,13 @@
52
53
  * before it returns — they are given back after every element — `dst` may not
53
54
  * be reachable from an element of `src`, and the result type is a number, a
54
55
  * `boolean` or an enum — or, for a map, a `string` or an array of those
55
- * scalars, which the join copies out of the worker's arena. An arrow written at the call may read the `const` locals and
56
- * the parameters of the function it is written in: each one is handed to the
57
- * body as a parameter of its own, which no body may write through. Importing this module compiles the program with `--threads`,
58
- * because every worker needs an arena of its own.
56
+ * scalars, which the join copies out of the worker's arena.
57
+ *
58
+ * An arrow written at the call may read the `const` locals and the parameters
59
+ * of the function it is written in: each one is handed to the body as a
60
+ * parameter of its own, which no body may write through. Importing this module
61
+ * compiles the program with `--threads`, because every worker needs an arena of
62
+ * its own.
59
63
  *
60
64
  * **A reduce is deterministic.** `src` is split into `min(64, ceil(n / BLOCK))`
61
65
  * blocks, each block is folded from `identity`, and the block results are
package/std/yaml-json.ts CHANGED
@@ -43,21 +43,23 @@
43
43
  * the alias's range, where it is used.
44
44
  *
45
45
  * **An alias bomb is refused before anything is built.** The values the
46
- * document expands to are counted first, from the nodes, with each node's
47
- * count kept, so the count costs one step per node however far the aliases
48
- * multiply it. Past the document's `maxValues` the load is
49
- * `YAML_JSON_ERR_EXPANSION`, at the first alias whose copy is the largest
50
- * (the first whose copy alone is past the limit, in a bomb), or
51
- * `JSON_VALUE_ERR_VALUES` when the document has no alias. A merged map counts
52
- * all its keys, also those the merging map overrides, so a document within a
53
- * few values of the limit can be refused for merges that would have fit.
54
- * The loader's merging is linear too: a map is merged into a given map at
55
- * most once, however many paths through the merge keys reach it, and the
56
- * pairs every merge visits and the items of every merge sequence it walks are
57
- * charged to a budget of `maxValues` plus the stream's node count, past which
58
- * the load is `YAML_JSON_ERR_EXPANSION` at the merge key. `parseYaml`'s own
59
- * merge check is not bounded this way: it walks a shared merge sequence once
60
- * for each merge key that names it.
46
+ * document expands to are counted first, from the nodes, with each node's count
47
+ * kept, so the count costs one step per node however far the aliases multiply
48
+ * it. Past the document's `maxValues` the load is `YAML_JSON_ERR_EXPANSION`, at
49
+ * the first alias whose copy is the largest (the first whose copy alone is past
50
+ * the limit, in a bomb), or `JSON_VALUE_ERR_VALUES` when the document has no
51
+ * alias.
52
+ *
53
+ * A merged map counts all its keys, also those the merging map overrides, so a
54
+ * document within a few values of the limit can be refused for merges that
55
+ * would have fit. The loader's merging is linear too: a map is merged into a
56
+ * given map at most once, however many paths through the merge keys reach it,
57
+ * and the pairs every merge visits and the items of every merge sequence it
58
+ * walks are charged to a budget of `maxValues` plus the stream's node count,
59
+ * past which the load is `YAML_JSON_ERR_EXPANSION` at the merge key.
60
+ *
61
+ * `parseYaml`'s own merge check is not bounded this way: it walks a shared
62
+ * merge sequence once for each merge key that names it.
61
63
  *
62
64
  * **A merge key's value** is a mapping, an alias to one, or a sequence of
63
65
  * those; anything else is refused at the value, by the parser as
package/std/yaml-write.ts CHANGED
@@ -23,20 +23,27 @@
23
23
  * as its text, which the core schema reads as an integer or a float. The text
24
24
  * ends with a line break.
25
25
  *
26
- * **A string is plain unless it could read as something else.** It is written
27
- * double-quoted when it is empty; when it reads as null, a boolean or a number
28
- * under YAML 1.2 or YAML 1.1 (`~`, `null`, `yes`, `on`, `y`, `true` in any
29
- * case; anything starting with a digit, or a sign or `.` and then a digit;
30
- * `.inf` and `.nan`, signed or not); when it starts with an indicator (`@`, `` ` ``, `\`, `*`,
31
- * `&`, `!`, `|`, `>`, `%`, `'`, `"`, `#`, `,`, `[`, `]`, `{`, `}`, or `-`, `?`
32
- * or `:` before a space or the end) or with `---` or `...`; when it holds
33
- * `: ` or ` #` or ends in `:`; when it starts or ends with a space; when it
34
- * holds a control character, a line break, U+2028, U+2029, U+FEFF, U+FFFE or
35
- * U+FFFF; and, as a key, when it is `<<`, which YAML reads as a merge key.
36
- * Keys and values follow the same rule. A quoted string escapes `"`, `\` and
37
- * every character just listed, so it stays on one line. A key whose written
38
- * form runs past the 1024 bytes YAML allows an implicit key is written as an
39
- * explicit one, `? key` and then `: value`.
26
+ * **A string is plain unless it could read as something else.**
27
+ *
28
+ * It is written double-quoted
29
+ * - when it is empty;
30
+ * - when it reads as null, a boolean or a number under YAML 1.2 or YAML 1.1
31
+ * (`~`, `null`, `yes`, `on`, `y`, `true` in any case; anything starting with
32
+ * a digit, or a sign or `.` and then a digit; `.inf` and `.nan`, signed or
33
+ * not);
34
+ * - when it starts with an indicator (`@`, `` ` ``, `\`, `*`, `&`, `!`, `|`,
35
+ * `>`, `%`, `'`, `"`, `#`, `,`, `[`, `]`, `{`, `}`, or `-`, `?` or `:` before
36
+ * a space or the end) or with `---` or `...`;
37
+ * - when it holds `: ` or ` #` or ends in `:`;
38
+ * - when it starts or ends with a space;
39
+ * - when it holds a control character, a line break, U+2028, U+2029, U+FEFF,
40
+ * U+FFFE or U+FFFF;
41
+ * - and, as a key, when it is `<<`, which YAML reads as a merge key.
42
+ *
43
+ * Keys and values follow the same rule. A quoted string escapes `"`, `\` and
44
+ * every character just listed, so it stays on one line. A key whose written
45
+ * form runs past the 1024 bytes YAML allows an implicit key is written as an
46
+ * explicit one, `? key` and then `: value`.
40
47
  *
41
48
  * **What it answers.** The YAML text, or `""` when `v` names no value or the
42
49
  * tree nests deeper than `JSON_WRITER_MAX_DEPTH` collections, the limit