nish 0.34.1 → 0.36.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 (127) hide show
  1. package/README.md +7 -6
  2. package/docs/AI.md +86 -16
  3. package/docs/INSTALL.md +22 -13
  4. package/llms.txt +5 -2
  5. package/package.json +15 -5
  6. package/runtime/async.d.mts +49 -0
  7. package/runtime/async.mjs +27 -0
  8. package/runtime/nish.d.ts +4681 -427
  9. package/runtime/nish.h +6 -2
  10. package/runtime/nish.mjs +4 -0
  11. package/runtime/runtime-net.c +22 -0
  12. package/runtime/runtime-shm.c +93 -2
  13. package/runtime/vite.d.ts +30 -0
  14. package/runtime/vite.mjs +150 -0
  15. package/scripts/build.sh +108 -13
  16. package/std/README.md +131 -131
  17. package/std/base64.ts +34 -5
  18. package/std/bytes.ts +258 -42
  19. package/std/cli-args.ts +296 -70
  20. package/std/cli-flags.ts +184 -19
  21. package/std/cli.ts +475 -54
  22. package/std/collections.ts +121 -23
  23. package/std/compress/checksum.ts +44 -14
  24. package/std/compress/deflate.ts +224 -111
  25. package/std/compress/gzip.ts +217 -53
  26. package/std/compress/zlib.ts +63 -7
  27. package/std/crypto/aes.ts +80 -9
  28. package/std/crypto/base64url.ts +22 -0
  29. package/std/crypto/bcrypt-batch.ts +88 -21
  30. package/std/crypto/bcrypt.ts +60 -0
  31. package/std/crypto/chacha20poly1305.ts +53 -0
  32. package/std/crypto/ct.ts +32 -13
  33. package/std/crypto/ed25519.ts +47 -0
  34. package/std/crypto/hkdf.ts +198 -13
  35. package/std/crypto/hmac.ts +235 -31
  36. package/std/crypto/jwt.ts +192 -63
  37. package/std/crypto/p256.ts +159 -16
  38. package/std/crypto/p384.ts +28 -3
  39. package/std/crypto/pki-roots.ts +32 -2
  40. package/std/crypto/pki.ts +81 -15
  41. package/std/crypto/rsa.ts +33 -3
  42. package/std/crypto/sha1.ts +3 -0
  43. package/std/crypto/sha256.ts +24 -1
  44. package/std/crypto/sha512.ts +99 -14
  45. package/std/crypto/x25519.ts +152 -14
  46. package/std/crypto/x509-random.ts +10 -0
  47. package/std/crypto/x509.ts +67 -7
  48. package/std/json-equal.ts +19 -0
  49. package/std/json-format.ts +112 -13
  50. package/std/json-number.ts +64 -14
  51. package/std/json-pointer.ts +23 -1
  52. package/std/json-tokenizer.ts +100 -29
  53. package/std/json-typed.ts +713 -66
  54. package/std/json-value.ts +400 -124
  55. package/std/json.ts +138 -10
  56. package/std/map.ts +25 -7
  57. package/std/math.ts +36 -4
  58. package/std/net/buffer-pool.ts +42 -11
  59. package/std/net/dns-config.ts +109 -23
  60. package/std/net/dns-message.ts +62 -7
  61. package/std/net/dns-resolver.ts +247 -53
  62. package/std/net/dns.ts +203 -35
  63. package/std/net/fetch.ts +151 -61
  64. package/std/net/handler.ts +278 -80
  65. package/std/net/hpack.ts +262 -52
  66. package/std/net/http-compress.ts +125 -15
  67. package/std/net/http-fields.ts +85 -9
  68. package/std/net/http1-client-codec.ts +100 -19
  69. package/std/net/http1-codec.ts +297 -77
  70. package/std/net/http1-server.ts +430 -94
  71. package/std/net/http2-frame.ts +272 -35
  72. package/std/net/http2-tls.ts +135 -34
  73. package/std/net/http2.ts +247 -106
  74. package/std/net/http3-frame.ts +154 -17
  75. package/std/net/http3-server.ts +275 -101
  76. package/std/net/http3.ts +307 -115
  77. package/std/net/outbound.ts +37 -3
  78. package/std/net/postgres-carrier.ts +144 -8
  79. package/std/net/postgres.ts +801 -112
  80. package/std/net/prefork.ts +164 -31
  81. package/std/net/qpack.ts +105 -18
  82. package/std/net/quic-conn-ack.ts +59 -12
  83. package/std/net/quic-conn-cid.ts +124 -27
  84. package/std/net/quic-conn-params.ts +70 -10
  85. package/std/net/quic-datagram.ts +43 -3
  86. package/std/net/quic-frame.ts +286 -12
  87. package/std/net/quic-listener.ts +101 -32
  88. package/std/net/quic-packet.ts +302 -21
  89. package/std/net/quic-recovery.ts +264 -52
  90. package/std/net/quic-stream.ts +353 -91
  91. package/std/net/quic.ts +1124 -201
  92. package/std/net/router.ts +87 -40
  93. package/std/net/tls/client.ts +166 -51
  94. package/std/net/tls/codec.ts +413 -56
  95. package/std/net/tls/record-client.ts +110 -55
  96. package/std/net/tls/record-server.ts +159 -59
  97. package/std/net/tls/record.ts +109 -12
  98. package/std/net/tls/schedule.ts +235 -26
  99. package/std/net/tls/ticket.ts +159 -40
  100. package/std/net/tls/verify.ts +49 -3
  101. package/std/net/tls-tcp.ts +250 -45
  102. package/std/net/tls.ts +221 -59
  103. package/std/net/upstream.ts +81 -45
  104. package/std/net/url.ts +97 -13
  105. package/std/net/websocket.ts +122 -12
  106. package/std/net/webtransport.ts +220 -89
  107. package/std/pair.ts +10 -2
  108. package/std/random.ts +34 -9
  109. package/std/regex.ts +352 -198
  110. package/std/region.ts +70 -15
  111. package/std/secret.ts +52 -11
  112. package/std/sort.ts +17 -2
  113. package/std/sqlite.ts +256 -35
  114. package/std/sync/ring.ts +430 -40
  115. package/std/sync/shm.ts +222 -15
  116. package/std/term-io.ts +137 -64
  117. package/std/term-pixels.ts +144 -19
  118. package/std/term-probe.ts +66 -25
  119. package/std/term-rate.ts +128 -57
  120. package/std/term.ts +332 -121
  121. package/std/testing.ts +130 -32
  122. package/std/text.ts +73 -7
  123. package/std/threads.ts +229 -41
  124. package/std/yaml-json.ts +94 -82
  125. package/std/yaml-lines.ts +47 -15
  126. package/std/yaml-write.ts +24 -16
  127. package/std/yaml.ts +764 -384
package/runtime/nish.h CHANGED
@@ -714,8 +714,10 @@ bool nish_is_executable(const nish_str *path);
714
714
  * `nish_tcp_accept(fd, peer)`: a new descriptor and the peer's address.
715
715
  * `nish_net_read` / `nish_net_write(fd, buf, off, len)`: bytes `[off, off +
716
716
  * len)` of `buf`, which the compiled call has range-checked; a write to a
717
- * gone peer is -32, never SIGPIPE. `nish_net_shutdown(fd, how)`: 0 read, 1
718
- * write, 2 both. `nish_net_close(fd)`.
717
+ * gone peer is -32, never SIGPIPE. `nish_net_write2(fd, a, aoff, alen, b,
718
+ * boff, blen)`: both ranges in one `sendmsg`, `a`'s bytes first, answering the
719
+ * count written (short when the socket buffer fills) or the same errors.
720
+ * `nish_net_shutdown(fd, how)`: 0 read, 1 write, 2 both. `nish_net_close(fd)`.
719
721
  * `nish_net_set_option(fd, option, value)`: one socket option from a
720
722
  * whitelist, by the runtime's own id (1 `TCP_NODELAY`, 2 `TCP_QUICKACK`, 3
721
723
  * `SO_KEEPALIVE`, 4 `SO_SNDBUF`, 5 `SO_RCVBUF`); any other id is -22, and
@@ -784,6 +786,8 @@ int32_t nish_tcp_listen_flags(const nish_str *host, int32_t port, int32_t backlo
784
786
  int32_t nish_tcp_accept(int32_t fd, nish_array *peer);
785
787
  int32_t nish_net_read(int32_t fd, nish_array *buf, int64_t off, int64_t len);
786
788
  int32_t nish_net_write(int32_t fd, const nish_array *buf, int64_t off, int64_t len);
789
+ int32_t nish_net_write2(int32_t fd, const nish_array *a, int64_t aoff, int64_t alen, const nish_array *b,
790
+ int64_t boff, int64_t blen);
787
791
  int32_t nish_net_shutdown(int32_t fd, int32_t how);
788
792
  int32_t nish_net_close(int32_t fd);
789
793
  int32_t nish_net_set_option(int32_t fd, int32_t option, int32_t value);
package/runtime/nish.mjs CHANGED
@@ -139,6 +139,7 @@ for (const name of [
139
139
  "tcpAccept",
140
140
  "netRead",
141
141
  "netWrite",
142
+ "netWrite2",
142
143
  "netShutdown",
143
144
  "netClose",
144
145
  "tcpConnect",
@@ -379,6 +380,9 @@ registerHooks({
379
380
  if (specifier === "nish:simd") {
380
381
  return next(new URL("./core.mjs", import.meta.url).href, context);
381
382
  }
383
+ if (specifier === "nish:async") {
384
+ return next(new URL("./async.mjs", import.meta.url).href, context);
385
+ }
382
386
  if (specifier === "nish:region") {
383
387
  return { url: `data:text/javascript,${encodeURIComponent(regionSource)}`, shortCircuit: true };
384
388
  }
@@ -417,6 +417,28 @@ int32_t nish_net_write(int32_t fd, const nish_array *buf, int64_t off, int64_t l
417
417
  return n < 0 ? nish_net_fail() : (int32_t)n;
418
418
  }
419
419
 
420
+ /* `netWrite2(fd, a, aoff, alen, b, boff, blen)`: `netWrite` of two ranges in
421
+ one `sendmsg`, so a response head and its body leave in one system call
422
+ without being copied together first. Both ranges are checked by the
423
+ compiled call. The count is at most `alen + blen`; a sum past `INT32_MAX`
424
+ is offered only up to it, so the answer always fits, and a short write is a
425
+ count, as `netWrite`'s is. */
426
+ int32_t nish_net_write2(int32_t fd, const nish_array *a, int64_t aoff, int64_t alen, const nish_array *b,
427
+ int64_t boff, int64_t blen) {
428
+ struct iovec iov[2];
429
+ struct msghdr msg;
430
+ if (blen > (int64_t)INT32_MAX - alen) blen = (int64_t)INT32_MAX - alen;
431
+ iov[0].iov_base = a->data + aoff;
432
+ iov[0].iov_len = (size_t)alen;
433
+ iov[1].iov_base = b->data + boff;
434
+ iov[1].iov_len = (size_t)blen;
435
+ memset(&msg, 0, sizeof msg);
436
+ msg.msg_iov = iov;
437
+ msg.msg_iovlen = 2;
438
+ ssize_t n = sendmsg(fd, &msg, NISH_NOSIGNAL);
439
+ return n < 0 ? nish_net_fail() : (int32_t)n;
440
+ }
441
+
420
442
  /* `netShutdown(fd, how)`: 0 the read side, 1 the write side, 2 both, which
421
443
  are `SHUT_RD`, `SHUT_WR` and `SHUT_RDWR` on both platforms. */
422
444
  int32_t nish_net_shutdown(int32_t fd, int32_t how) {
@@ -52,12 +52,24 @@
52
52
  * answer -95, as `setIdlePriority` does on Darwin, and on wasi creating or
53
53
  * opening a region answers -95 too.
54
54
  *
55
- * Results are 0 or a count on success and a negated errno on failure. Nothing
56
- * here allocates: the table is a fixed array, and a mapping is the kernel's. */
55
+ * **A window** (`nishshm_lend`) is a `u8[]` whose data is a range of the
56
+ * mapping, so a program writes the region with `copyBytes` and index stores
57
+ * and no copy. Its header is a record of this file's, malloc'd (never the
58
+ * arena: a `region()` would free it under the program) and never freed: the
59
+ * program may keep the array past `nishshm_give_back` and `nishshm_close`,
60
+ * and both leave it a header of length 0 and no data, so an index after them
61
+ * is a bounds panic, not a read of an unmapped page. A loop lends again with
62
+ * the window it gave back as `reuse`, which re-points that header and takes
63
+ * no memory.
64
+ *
65
+ * Results are 0 or a count on success and a negated errno on failure. The
66
+ * table is a fixed array, a mapping is the kernel's, and a window's header is
67
+ * the one allocation. */
57
68
 
58
69
  #define _GNU_SOURCE /* `syscall`, for the futex */
59
70
  #include <errno.h>
60
71
  #include <stdint.h>
72
+ #include <stdlib.h>
61
73
  #include <string.h>
62
74
 
63
75
  #include "nish.h"
@@ -90,10 +102,20 @@
90
102
  /* The longest name. Darwin's shm_open takes 31 bytes with its leading '/'. */
91
103
  #define NISHSHM_NAME_MAX 30
92
104
 
105
+ /* A window `lend` made: a `u8[]` header whose data is the mapping. The header
106
+ comes first, so the program's array pointer is the record's. */
107
+ typedef struct nishshm_window {
108
+ nish_array hdr;
109
+ uint8_t *lent; /* `hdr.data` as lent; NULL once given back */
110
+ uint64_t lent_len; /* the length lent */
111
+ struct nishshm_window *next; /* the region's next window */
112
+ } nishshm_window;
113
+
93
114
  typedef struct nishshm_region {
94
115
  uint8_t *base; /* the mapping, NULL while the slot is free */
95
116
  uint64_t size; /* its length in bytes */
96
117
  int32_t gen; /* the high bits of the slot's handle: 0 never used, 32767 retired */
118
+ nishshm_window *windows; /* every window this mapping lent, given back or not */
97
119
  } nishshm_region;
98
120
 
99
121
  /* NULL until this thread first maps a region. Slot 0 is never used, so no
@@ -312,6 +334,65 @@ void nishshm_write(int32_t h, int32_t at, const uint8_t *src, uint64_t n, uint64
312
334
  memcpy(dst, src + off, len);
313
335
  }
314
336
 
337
+ /* -- windows ----------------------------------------------------------------- */
338
+
339
+ /* The record of `a` among the region's windows, or NULL. A pointer walk, so a
340
+ header no window has is never read as one. */
341
+ static nishshm_window *window_of(nishshm_region *r, const nish_array *a) {
342
+ nishshm_window *w = r->windows;
343
+ while (w != NULL && &w->hdr != a) w = w->next;
344
+ return w;
345
+ }
346
+
347
+ /* A `u8[]` of `len` bytes whose data is the region's bytes at `at`, checked as
348
+ a byte copy's window is. `reuse` NULL takes a new header, which is malloc'd
349
+ and never freed: the program may hold it after any giveBack or close, so it
350
+ must stay a header, one that reads as empty. Otherwise `reuse` must be a
351
+ window this region lent and was given back, and is re-pointed. */
352
+ nish_array *nishshm_lend(int32_t h, int32_t at, int32_t len, nish_array *reuse) {
353
+ nishshm_region *r = region_checked(h);
354
+ uint8_t *p = window(h, at, (uint64_t)(int64_t)len, 0, (uint64_t)(int64_t)len);
355
+ nishshm_window *w;
356
+ if (reuse != NULL) {
357
+ w = window_of(r, reuse);
358
+ if (__builtin_expect(w == NULL || w->lent != NULL, 0))
359
+ shm_fail("reuse of length ", (int64_t)reuse->len,
360
+ " is not a window this region lent and was given back", 0, NULL);
361
+ } else {
362
+ w = (nishshm_window *)malloc(sizeof *w);
363
+ if (__builtin_expect(w == NULL, 0))
364
+ shm_fail("lend of ", len, " bytes found no memory for the window's header", 0, NULL);
365
+ w->next = r->windows;
366
+ r->windows = w;
367
+ }
368
+ w->hdr.len = w->hdr.cap = (uint64_t)len;
369
+ w->hdr.data = (char *)p;
370
+ w->lent = p;
371
+ w->lent_len = (uint64_t)len;
372
+ return &w->hdr;
373
+ }
374
+
375
+ /* Empties a lent window and answers its length. A pop or a shorter `length`
376
+ keeps the window; a push that moved its data took it out of the region, and
377
+ that, a second giveBack, or another region's window, panics. */
378
+ int32_t nishshm_give_back(int32_t h, nish_array *a) {
379
+ nishshm_region *r = region_checked(h);
380
+ nishshm_window *w = window_of(r, a);
381
+ if (__builtin_expect(w == NULL || w->lent == NULL, 0))
382
+ shm_fail("window of length ", (int64_t)a->len,
383
+ " is not lent by this region: it was given back, or another region lent it", 0,
384
+ NULL);
385
+ if (__builtin_expect((uint8_t *)a->data != w->lent || a->len > w->lent_len, 0))
386
+ shm_fail("window of length ", (int64_t)a->len,
387
+ " is no longer the region's bytes: a push moved it, so it cannot be given back", 0,
388
+ NULL);
389
+ int32_t n = (int32_t)a->len;
390
+ a->len = a->cap = 0;
391
+ a->data = NULL;
392
+ w->lent = NULL;
393
+ return n;
394
+ }
395
+
315
396
  /* -- regions ----------------------------------------------------------------- */
316
397
 
317
398
  int32_t nishshm_size(int32_t h) { return (int32_t)region_checked(h)->size; }
@@ -486,6 +567,16 @@ int32_t nishshm_unlink(const char *name) {
486
567
  int32_t nishshm_close(int32_t h) {
487
568
  nishshm_region *r = region_of(h);
488
569
  if (r == NULL) return -9;
570
+ /* Every window still on the mapping reads as empty before the pages go: one
571
+ a push moved off it is the program's array now, and is left alone. */
572
+ for (nishshm_window *w = r->windows; w != NULL; w = w->next) {
573
+ if (w->lent != NULL && (uint8_t *)w->hdr.data == w->lent) {
574
+ w->hdr.len = w->hdr.cap = 0;
575
+ w->hdr.data = NULL;
576
+ }
577
+ w->lent = NULL;
578
+ }
579
+ r->windows = NULL;
489
580
  munmap(r->base, (size_t)r->size);
490
581
  r->base = NULL;
491
582
  r->size = 0;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `nish/vite`: the Vite plugin that builds a Nish module imported by a page
3
+ * into wasm, inlined and loaded without a fetch (docs/guide/using-nish/interop.md).
4
+ */
5
+
6
+ export interface NishViteOptions {
7
+ /** Modules to build to wasm, paths from the root. Default: none. */
8
+ entries?: string[];
9
+ /**
10
+ * Host modules, paths from the root, each passed to the compiler as
11
+ * `--host`; a root `package.json` `"nish": { "host": [...] }` also names
12
+ * them. The ones an entry imports are passed to its loader. Default: none.
13
+ */
14
+ host?: string[];
15
+ /** The `nish` command. Default: this package's `bin/nish`. */
16
+ compiler?: string;
17
+ /** `scripts/build.sh`. Default: this package's. */
18
+ buildScript?: string;
19
+ }
20
+
21
+ /** The hooks the plugin uses, which Vite and Rollup share. */
22
+ export interface NishVitePlugin {
23
+ name: "nish";
24
+ enforce: "pre";
25
+ configResolved(config: { root?: string; command?: "build" | "serve"; cacheDir?: string }): void;
26
+ resolveId(source: string, importer?: string): Promise<string | null>;
27
+ load(id: string): Promise<string | null>;
28
+ }
29
+
30
+ export default function nish(options?: NishViteOptions): NishVitePlugin;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * `nish/vite` (WP50 stage 1): a Vite plugin that lets a page import a Nish
3
+ * module as the TypeScript it is and get, in a build, the wasm build of it.
4
+ *
5
+ * The entries are the modules compiled to wasm, `nish({ entries })`, paths
6
+ * from the root. (The root package.json's `nish` field cannot name them yet:
7
+ * the compiler refuses a key there other than `noPanic`, `capabilities` and
8
+ * `host`.) In
9
+ * `vite build` an import that resolves to one is answered with a generated
10
+ * module. The plugin compiles the entry with `nish --target wasm32 --emit-dts`,
11
+ * links the IR with `scripts/build.sh --profile wasm-host --inline`, and the
12
+ * generated module calls the loader's `loadSync` on the inlined bytes and
13
+ * re-exports each export by name. The page fetches nothing and awaits nothing.
14
+ * In `vite serve` the import is left to Vite, which serves the TypeScript.
15
+ *
16
+ * An entry that imports host modules (WP50 stage 2) is instantiated with
17
+ * them: the generated module imports each one the `.d.ts` names in `Imports`
18
+ * and passes them as `host`, so the page passes nothing. One seam is left for
19
+ * a later stage of docs/wp50-wasm-host.md: the `.nish` client specifier in
20
+ * `resolveId`.
21
+ *
22
+ * The plugin drives only the hooks Vite and Rollup share (`configResolved`,
23
+ * `resolveId`, `load`), so `tests/run.js` calls them directly, with no Vite.
24
+ */
25
+ import { execFile } from "node:child_process";
26
+ import { mkdirSync, readFileSync } from "node:fs";
27
+ import path from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+ import { promisify } from "node:util";
30
+
31
+ const run = promisify(execFile);
32
+ const packageDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
33
+ const PREFIX = "\0nish-entry:";
34
+
35
+ /**
36
+ * The host modules an entry imports, as absolute paths: the
37
+ * `typeof import("...")` members of the `.d.ts`'s `Imports` type, each a
38
+ * specifier from the `.d.ts`'s directory written without its `.ts`, which is
39
+ * put back so the import names the file. None when there is no `Imports`.
40
+ */
41
+ function hostModules(dts, dir) {
42
+ const line = dts.split("\n").find((l) => l.startsWith("export type Imports = "));
43
+ if (line === undefined) return [];
44
+ return [...line.matchAll(/typeof import\("([^"]+)"\)/g)].map((m) => `${path.resolve(dir, m[1])}.ts`);
45
+ }
46
+
47
+ /**
48
+ * The import lines and the import object an entry is instantiated with: each
49
+ * host module imported whole and passed under `host`, or `{}` with none.
50
+ */
51
+ function importsFor(hosts) {
52
+ const lines = hosts.map((h, i) => `import * as __nishHost${i} from ${JSON.stringify(h)};`);
53
+ if (hosts.length === 0) return { lines, object: "{}" };
54
+ const host = hosts.length === 1 ? "__nishHost0" : `{ ${hosts.map((_, i) => `...__nishHost${i}`).join(", ")} }`;
55
+ return { lines, object: `{ host: ${host} }` };
56
+ }
57
+
58
+ /**
59
+ * The names the loader returns, read from the `Exports` interface of the
60
+ * `.d.ts` the same compile wrote: one member a line, `memory` included.
61
+ */
62
+ function exportNames(dts) {
63
+ const body = dts.slice(dts.indexOf("export interface Exports {"));
64
+ const names = [];
65
+ for (const m of body.slice(0, body.indexOf("\n}")).matchAll(/^ {2}(?:readonly )?([A-Za-z_$][\w$]*)[(:]/gm)) {
66
+ names.push(m[1]);
67
+ }
68
+ return names;
69
+ }
70
+
71
+ /** The plugin. `compiler` and `buildScript` default to the ones in this package. */
72
+ export default function nish(options = {}) {
73
+ const compiler = options.compiler ?? path.join(packageDir, "bin", "nish");
74
+ const buildScript = options.buildScript ?? path.join(packageDir, "scripts", "build.sh");
75
+ const runtimeWasm = path.join(packageDir, "runtime", "runtime-wasm.c");
76
+ let root = process.cwd();
77
+ let building = false;
78
+ let cacheDir = path.join(root, "node_modules", ".vite");
79
+ let entries = new Set();
80
+
81
+ const configure = (config) => {
82
+ root = config.root ?? root;
83
+ building = config.command === "build";
84
+ cacheDir = config.cacheDir ?? path.join(root, "node_modules", ".vite");
85
+ entries = new Set((options.entries ?? []).map((e) => path.resolve(root, e)));
86
+ };
87
+ configure({ root });
88
+
89
+ /** Compile and link one entry; resolves to the paths the generated module imports. */
90
+ const buildEntry = async (entry) => {
91
+ const stem = path.basename(entry, path.extname(entry));
92
+ const dir = path.join(cacheDir, "nish", path.relative(root, entry).replace(/[\\/]/g, "_"));
93
+ mkdirSync(dir, { recursive: true });
94
+ const ll = path.join(dir, `${stem}.ll`);
95
+ const dts = path.join(dir, `${stem}.d.ts`);
96
+ const host = (options.host ?? []).flatMap((h) => ["--host", path.resolve(root, h)]);
97
+ await run(compiler, [entry, "--target", "wasm32", ...host, "--emit-dts", dts, "-o", ll], { cwd: root });
98
+ const loader = path.join(dir, `${stem}.mjs`);
99
+ const ir = readFileSync(ll, "utf8");
100
+ // runtime-wasm.c is linked when the IR needs a runtime function (a weak
101
+ // `extern_weak` one, a panic stub wasm-ld writes itself, does not count)
102
+ // or the loader calls the arena.
103
+ const needsRuntime =
104
+ /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) ||
105
+ readFileSync(loader, "utf8").includes("raw.nish_arena_mark(");
106
+ const inline = path.join(dir, `${stem}.bytes.mjs`);
107
+ const inputs = needsRuntime ? [ll, runtimeWasm] : [ll];
108
+ await run("bash", [buildScript, ...inputs, "-o", path.join(dir, `${stem}.wasm`), "--profile", "wasm-host", "--inline", inline], {
109
+ cwd: root,
110
+ });
111
+ const types = readFileSync(dts, "utf8");
112
+ return { loader, inline, names: exportNames(types), hosts: hostModules(types, dir) };
113
+ };
114
+
115
+ return {
116
+ name: "nish",
117
+ enforce: "pre",
118
+ configResolved: configure,
119
+ async resolveId(source, importer) {
120
+ if (!building) return null;
121
+ // The seam for a `./client.nish` specifier (the page's client module of a
122
+ // later stage) is here; stage 1 resolves only the entries.
123
+ const base = importer ? path.dirname(importer) : root;
124
+ const candidates = source.startsWith(".")
125
+ ? [path.resolve(base, source)]
126
+ : path.isAbsolute(source)
127
+ ? [source, path.join(root, source)]
128
+ : [];
129
+ const hit = candidates.find((c) => entries.has(c));
130
+ return hit === undefined ? null : PREFIX + hit;
131
+ },
132
+ async load(id) {
133
+ if (!id.startsWith(PREFIX)) return null;
134
+ const entry = id.slice(PREFIX.length);
135
+ const { loader, inline, names, hosts } = await buildEntry(entry);
136
+ const imports = importsFor(hosts);
137
+ // The module's own bindings are prefixed, so an export named `bytes`,
138
+ // `loadSync` or `exports` does not redeclare one of them.
139
+ const lines = [
140
+ `import { loadSync as __nishLoadSync } from ${JSON.stringify(loader)};`,
141
+ `import { bytes as __nishBytes } from ${JSON.stringify(inline)};`,
142
+ ...imports.lines,
143
+ `const __nishExports = __nishLoadSync(__nishBytes, ${imports.object});`,
144
+ "export default __nishExports;",
145
+ ];
146
+ if (names.length > 0) lines.push(`export const { ${names.join(", ")} } = __nishExports;`);
147
+ return `${lines.join("\n")}\n`;
148
+ },
149
+ };
150
+ }
package/scripts/build.sh CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bash
2
2
  # Build an Nish .ll module (plus optional C sources) into a native binary.
3
3
  #
4
- # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasi|napi]
4
+ # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasm-host|wasi|napi]
5
5
  #
6
6
  # The C runtime is sixteen translation units and is named as one: an input
7
7
  # <dir>/runtime.c also compiles <dir>/runtime-os.c, the half that wraps the
@@ -33,6 +33,28 @@
33
33
  # load it from Node. Add runtime/runtime-wasm.c to the inputs when a
34
34
  # function uses arrays (the arena and the array cold paths, no libc);
35
35
  # strings and I/O still need a WASI runtime and are not available.
36
+ # wasm-host the wasm profile's module for a page (WP50 stage 1): the same
37
+ # inputs, linked with an explicit export list instead of exporting
38
+ # everything -- the program's exported functions, `memory`, and,
39
+ # when runtime-wasm.c is linked, the arena entry points the
40
+ # `--emit-dts` loader calls (nish_arena_mark, nish_arena_release,
41
+ # nish_alloc_array, nish_reset_arena, nish_free_arena). The stack is
42
+ # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz` on the
43
+ # module when wasm-opt (binaryen) is on PATH; the build line says
44
+ # whether it ran. Two flags take this profile alone, and any other
45
+ # refuses them with exit 2:
46
+ # --memory <MiB> memory fixed at <MiB> MiB (1 to 4096), the
47
+ # initial size and the maximum both, so it
48
+ # never grows and `memory.buffer` is one
49
+ # ArrayBuffer for the module's life; an arena
50
+ # that runs out traps. Without it (the
51
+ # default) the memory starts at what the
52
+ # module needs and grows on demand, as under
53
+ # the wasm profile.
54
+ # --inline <file.mjs> also write <file.mjs>, an ES module whose
55
+ # `export const bytes = new Uint8Array([...])`
56
+ # holds the .wasm's bytes, so a page loads the
57
+ # module with `loadSync(bytes)` and no fetch.
36
58
  # wasi wasm32-wasi command module: runtime.c linked against wasi-libc, so
37
59
  # string programs run under any WASI host (`_start` runs `main`;
38
60
  # `node examples/wasi-host.mjs app.wasm args...`). Needs a WASI
@@ -138,6 +160,9 @@ cpu="" # --cpu x86-64-v3: the one CPU level abov
138
160
  sqlite_to="" # --sqlite-objects <dir>: compile runtime/sqlite/ alone, into <dir>
139
161
  sqlite_from="" # --sqlite-from <dir>: link runtime/sqlite/ compiled there
140
162
  modules_at="" # --module-objects <dir>: each X.ll's object is <dir>/X.o
163
+ memory_mib="" # --memory <MiB>: wasm-host's fixed memory (WP50 stage 1)
164
+ wasm_opt="" # what the build line says of wasm-opt; set only by wasm-host
165
+ inline_to="" # --inline <file.mjs>: wasm-host's bytes as an ES module
141
166
  while [ $# -gt 0 ]; do
142
167
  case "$1" in
143
168
  -o) out="$2"; shift 2 ;;
@@ -152,6 +177,12 @@ while [ $# -gt 0 ]; do
152
177
  --sqlite-objects) sqlite_to="$2"; shift 2 ;;
153
178
  --sqlite-from) sqlite_from="$2"; shift 2 ;;
154
179
  --module-objects) modules_at="$2"; shift 2 ;;
180
+ --memory)
181
+ [ -n "${2-}" ] || { echo "error: --memory needs a size in MiB" >&2; exit 2; }
182
+ memory_mib="$2"; shift 2 ;;
183
+ --inline)
184
+ [ -n "${2-}" ] || { echo "error: --inline needs a file to write" >&2; exit 2; }
185
+ inline_to="$2"; shift 2 ;;
155
186
  --pgo-generate) pgo=(-fprofile-generate); shift ;;
156
187
  --pgo-use)
157
188
  [ -f "$2" ] || { echo "error: --pgo-use: profile '$2' not found (run the instrumented binary, then llvm-profdata merge)" >&2; exit 2; }
@@ -164,9 +195,19 @@ done
164
195
  if [ -n "$cpu" ]; then
165
196
  [ "$cpu" = x86-64-v3 ] || { echo "error: --cpu takes x86-64-v3, not '$cpu'" >&2; exit 2; }
166
197
  case "$profile" in
167
- wasm|wasi) echo "error: --cpu x86-64-v3 is an x86-64 level, so the $profile profile does not take it" >&2; exit 2 ;;
198
+ 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 ;;
168
199
  esac
169
200
  fi
201
+ if [ -n "$memory_mib" ] || [ -n "$inline_to" ]; then
202
+ [ "$profile" = wasm-host ] || { echo "error: --memory and --inline take the wasm-host profile, not '$profile'" >&2; exit 2; }
203
+ fi
204
+ if [ -n "$memory_mib" ]; then
205
+ case "$memory_mib" in
206
+ *[!0-9]*|0*) memory_ok=0 ;;
207
+ *) if [ "${#memory_mib}" -le 4 ] && [ "$memory_mib" -le 4096 ]; then memory_ok=1; else memory_ok=0; fi ;;
208
+ esac
209
+ [ "$memory_ok" = 1 ] || { echo "error: --memory takes a whole number of MiB from 1 to 4096, not '$memory_mib'" >&2; exit 2; }
210
+ fi
170
211
  # wasm-ld exports a wasm module's linear memory as `memory`, so under the wasm
171
212
  # profile's `--export-all` a function of that name makes a module Node refuses
172
213
  # to compile ("Duplicate export name 'memory'", #643). The wasi module exports
@@ -175,7 +216,7 @@ fi
175
216
  # when it knows the build is wasm, but IR compiled for the host with `-o` alone
176
217
  # reaches these profiles without telling it, so the IR is read here too.
177
218
  case "$profile" in
178
- wasm|wasi)
219
+ wasm|wasm-host|wasi)
179
220
  for i in ${inputs[@]+"${inputs[@]}"}; do
180
221
  case "$i" in
181
222
  *.ll)
@@ -298,8 +339,8 @@ if [ "$sqlite_wanted" = 1 ] && [ -z "$sqlite_dir" ]; then
298
339
  echo "error: the module calls SQLite, and $(dirname "$0")/../runtime/sqlite/ is not there" >&2
299
340
  exit 2
300
341
  fi
301
- if [ "$sqlite_wanted" = 1 ] && [ "$profile" = wasm ]; then
302
- echo "error: the module calls SQLite, which the wasm profile cannot link: it has no libc for runtime/sqlite/sqlite3.c to build on; use --profile wasi" >&2
342
+ if [ "$sqlite_wanted" = 1 ] && { [ "$profile" = wasm ] || [ "$profile" = wasm-host ]; }; then
343
+ echo "error: the module calls SQLite, which the $profile profile cannot link: it has no libc for runtime/sqlite/sqlite3.c to build on; use --profile wasi" >&2
303
344
  exit 2
304
345
  fi
305
346
 
@@ -672,7 +713,7 @@ case "$profile" in
672
713
  speed|size)
673
714
  "$CC" "${common[@]}" "${optimise[@]}" ${lto_parts[@]+"${lto_parts[@]}"} \
674
715
  "${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" -lm -o "$out" ;;
675
- wasm)
716
+ wasm|wasm-host)
676
717
  # A region's chunks come from malloc, and the freestanding wasm runtime
677
718
  # (runtime-wasm.c) has none, so IR that makes or enters one is refused here
678
719
  # rather than failing at the link on an undefined `nish_region_*`. The wasi
@@ -680,7 +721,7 @@ case "$profile" in
680
721
  for i in ${inputs[@]+"${inputs[@]}"}; do
681
722
  case "$i" in
682
723
  *.ll) if grep -q "@nish_region_" "$i"; then
683
- echo "error: $i uses regions, which the wasm profile cannot link (it has no malloc); build it with --profile wasi" >&2
724
+ echo "error: $i uses regions, which the $profile profile cannot link (it has no malloc); build it with --profile wasi" >&2
684
725
  exit 2
685
726
  fi ;;
686
727
  esac
@@ -689,7 +730,7 @@ case "$profile" in
689
730
  # rather than probing PATH so a Homebrew llvm without a PATH entry still works.
690
731
  wasm_ld=$("$CC" -print-prog-name=wasm-ld)
691
732
  if [ ! -x "$wasm_ld" ]; then
692
- echo "error: the wasm profile needs wasm-ld (install lld; on macOS: brew install llvm@18)" >&2
733
+ echo "error: the $profile profile needs wasm-ld (install lld; on macOS: brew install llvm@18)" >&2
693
734
  exit 2
694
735
  fi
695
736
  # IR compiled for the host rather than with `--target wasm32` calls std/crypto/aes.ts's
@@ -749,10 +790,64 @@ case "$profile" in
749
790
  fi
750
791
  # -mbulk-memory lowers llvm.memset/memcpy (`new Array<T>(n)`, `push` growth) to the
751
792
  # memory.fill/memory.copy instructions instead of libc calls the freestanding link lacks.
752
- "$CC" -Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory \
753
- ${tls[@]+"${tls[@]}"} \
754
- -Wl,--no-entry -Wl,--export-all -Wl,--strip-all -Wl,--gc-sections \
755
- "${inputs[@]}" -o "$out" ;;
793
+ wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory)
794
+ if [ "$profile" = wasm ]; then
795
+ "$CC" "${wasm_compile[@]}" \
796
+ ${tls[@]+"${tls[@]}"} \
797
+ -Wl,--no-entry -Wl,--export-all -Wl,--strip-all -Wl,--gc-sections \
798
+ "${inputs[@]}" -o "$out"
799
+ else
800
+ # The export list. A module's exported functions are its `define` lines
801
+ # with external linkage and default visibility: the compiler gives
802
+ # everything else `internal` or `private`, and the other linkages are
803
+ # listed for IR it did not write. wasm-ld exports `memory` itself.
804
+ exports=()
805
+ runtime_linked=0
806
+ for i in "${inputs[@]}"; do
807
+ case "$i" in
808
+ */runtime-wasm.c|runtime-wasm.c) runtime_linked=1 ;;
809
+ *.ll)
810
+ while IFS= read -r name; do
811
+ exports+=("-Wl,--export=$name")
812
+ done < <(grep -E '^define ' "$i" \
813
+ | grep -Ev '^define (internal|private|linkonce|linkonce_odr|weak|weak_odr|available_externally|extern_weak|common|hidden|protected) ' \
814
+ | sed -nE 's/^[^@]*@"?([^"(]+)"?\(.*/\1/p') ;;
815
+ esac
816
+ done
817
+ if [ "$runtime_linked" = 1 ]; then
818
+ for name in nish_arena_mark nish_arena_release nish_alloc_array nish_reset_arena nish_free_arena; do
819
+ exports+=("-Wl,--export=$name")
820
+ done
821
+ fi
822
+ # shellcheck disable=SC2054 # -Wl,<flag> is one argument: the comma is the linker's
823
+ memory=(-Wl,-z,stack-size=65536)
824
+ if [ -n "$memory_mib" ]; then
825
+ bytes=$((memory_mib * 1048576))
826
+ memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
827
+ fi
828
+ "$CC" "${wasm_compile[@]}" \
829
+ ${tls[@]+"${tls[@]}"} \
830
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
831
+ "${inputs[@]}" -o "$out"
832
+ # binaryen's size pass is optional: the module is complete without it.
833
+ if command -v wasm-opt >/dev/null 2>&1; then
834
+ wasm-opt -Oz --enable-bulk-memory "$out" -o "$out"
835
+ wasm_opt="wasm-opt -Oz"
836
+ else
837
+ wasm_opt="no wasm-opt"
838
+ fi
839
+ if [ -n "$inline_to" ]; then
840
+ # Decimal, one array literal: of the inline forms the smallest after
841
+ # compression (docs/wp50-wasm-host.md, Q10). od prints each byte as an
842
+ # unsigned decimal, and tr and sed join them with commas.
843
+ {
844
+ printf '// The bytes of %s, from scripts/build.sh --profile wasm-host --inline.\n' "${out##*/}"
845
+ printf 'export const bytes = new Uint8Array(['
846
+ od -An -v -tu1 "$out" | tr -s ' \n' ' ' | sed -E 's/^ //; s/ $//; s/ /,/g' | tr -d '\n'
847
+ printf ']);\n'
848
+ } > "$inline_to"
849
+ fi
850
+ fi ;;
756
851
  wasi)
757
852
  sysroot=${WASI_SYSROOT:-}
758
853
  for d in /usr/lib/wasi-sysroot /opt/wasi-sdk/share/wasi-sysroot /usr/share/wasi-sysroot; do
@@ -830,4 +925,4 @@ esac
830
925
  if [ "${dsym:-0}" = 1 ]; then "$("$CC" -print-prog-name=dsymutil)" "$out"; fi
831
926
 
832
927
  # `wc -c` pads with spaces on macOS; strip them so the number is clean.
833
- printf '%s: %s bytes (%s)\n' "$out" "$(wc -c < "$out" | tr -d ' ')" "$profile"
928
+ printf '%s: %s bytes (%s%s)\n' "$out" "$(wc -c < "$out" | tr -d ' ')" "$profile" "${wasm_opt:+, $wasm_opt}"