@amritk/nish-aarch64-linux 0.39.0 → 0.40.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 (54) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +112 -33
  4. package/package.json +1 -1
  5. package/runtime/nish.d.ts +21 -17
  6. package/runtime/nish.h +10 -0
  7. package/runtime/page-frame.d.ts +123 -0
  8. package/runtime/page-frame.mjs +736 -0
  9. package/runtime/page-game.d.ts +132 -0
  10. package/runtime/page-game.mjs +738 -0
  11. package/runtime/runtime-aes.c +85 -8
  12. package/runtime/runtime-bytes.c +88 -4
  13. package/runtime/runtime-net.c +32 -0
  14. package/runtime/runtime-sandbox.c +55 -28
  15. package/runtime/runtime-wasm.c +422 -0
  16. package/runtime/vite.mjs +1 -1
  17. package/scripts/build.sh +15 -0
  18. package/std/README.md +73 -87
  19. package/std/array.ts +36 -3
  20. package/std/collections.ts +51 -0
  21. package/std/crypto/hmac.ts +37 -10
  22. package/std/crypto/p256.ts +1388 -2664
  23. package/std/crypto/pki.ts +116 -4
  24. package/std/crypto/sha256.ts +34 -6
  25. package/std/crypto/x509.ts +7 -0
  26. package/std/host/game.ts +273 -0
  27. package/std/input.ts +56 -0
  28. package/std/json-tokenizer.ts +325 -112
  29. package/std/json-typed.ts +43 -8
  30. package/std/json-value.ts +144 -3
  31. package/std/json.ts +63 -8
  32. package/std/net/fetch.ts +22 -4
  33. package/std/net/http-server.ts +3382 -0
  34. package/std/net/http1-client-codec.ts +6 -2
  35. package/std/net/http1-codec.ts +137 -12
  36. package/std/net/http1-server.ts +83 -29
  37. package/std/net/http2.ts +47 -14
  38. package/std/net/http3-server.ts +29 -3
  39. package/std/net/http3.ts +180 -7
  40. package/std/net/quic-recovery.ts +240 -9
  41. package/std/net/quic-stream.ts +21 -1
  42. package/std/net/quic.ts +98 -4
  43. package/std/net/router.ts +378 -31
  44. package/std/net/serve.ts +873 -65
  45. package/std/net/tls/verify.ts +19 -1
  46. package/std/net/url.ts +83 -35
  47. package/std/net/websocket.ts +74 -1
  48. package/std/net/webtransport.ts +7 -1
  49. package/std/raster.ts +837 -0
  50. package/std/release.ts +593 -0
  51. package/std/synth.ts +143 -0
  52. package/std/threads.ts +298 -0
  53. package/std/yaml-json.ts +368 -28
  54. package/std/yaml.ts +122 -27
package/std/crypto/pki.ts CHANGED
@@ -144,6 +144,11 @@ export const PKI_ERR_UNSUPPORTED_ALGORITHM: i32 = 14
144
144
  export const PKI_ERR_CHAIN_TOO_LONG: i32 = 15
145
145
  /** The chain asks for more work than one call does: signatures, names or subtrees. */
146
146
  export const PKI_ERR_BUDGET: i32 = 16
147
+ /**
148
+ * A certificate on the path has a key the caller distrusts: the SHA-256 of
149
+ * its subjectPublicKeyInfo is one `pkiDistrustSpki` added to the store.
150
+ */
151
+ export const PKI_ERR_DISTRUSTED: i32 = 17
147
152
 
148
153
  /** The most certificates a chain may hold, the leaf among them. */
149
154
  export const PKI_MAX_CHAIN_CERTS: i32 = 128
@@ -171,11 +176,14 @@ export class PkiTrustStore {
171
176
  roots: X509Certificate[]
172
177
  /** @internal The roots under each subject, keyed by the subject's DER in hex. */
173
178
  bySubject: Map<string, X509Certificate[]>
179
+ /** @internal The SHA-256 of each distrusted subjectPublicKeyInfo, in hex; empty unless `pkiDistrustSpki` filled it. */
180
+ distrusted: Map<string, boolean>
174
181
 
175
182
  /** An empty store; `pkiTrustStore` builds a filled one. */
176
183
  constructor() {
177
184
  this.roots = []
178
185
  this.bySubject = new Map<string, X509Certificate[]>()
186
+ this.distrusted = new Map<string, boolean>()
179
187
  }
180
188
  }
181
189
 
@@ -740,7 +748,70 @@ const pkiIpWithin = (ip: u8[], t: X509GeneralSubtree): boolean => {
740
748
  return true
741
749
  }
742
750
 
743
- /** Whether `issuer`'s iPAddress constraints allow `ip`; a subtree of the other family never holds it. */
751
+ /** Whether the first 12 octets of `a` are `::ffff:`, the prefix of an IPv4-mapped IPv6 address. */
752
+ const pkiIpMappedPrefix = (a: u8[]): boolean => {
753
+ if (toI32(a.length) < 12) {
754
+ return false
755
+ }
756
+ for (let k: i32 = 0; k < 12 && k < toI32(a.length); k++) {
757
+ if (toI32(a[k]) !== (k < 10 ? 0 : 0xff)) {
758
+ return false
759
+ }
760
+ }
761
+ return true
762
+ }
763
+
764
+ /** Whether `ip`'s four octets from `at` equal `t`'s from `from` under `t`'s mask. */
765
+ const pkiIpV4Within = (ip: u8[], at: i32, t: X509GeneralSubtree, from: i32): boolean => {
766
+ for (let k: i32 = 0; k < 4; k++) {
767
+ const a: i32 = at + k
768
+ const b: i32 = from + k
769
+ if (a < 0 || a >= toI32(ip.length) || b < 0 || b >= toI32(t.ip.length) || b >= toI32(t.mask.length)) {
770
+ return false
771
+ }
772
+ if ((toI32(ip[a]) & toI32(t.mask[b])) !== (toI32(t.ip[b]) & toI32(t.mask[b]))) {
773
+ return false
774
+ }
775
+ }
776
+ return true
777
+ }
778
+
779
+ /**
780
+ * Whether the excluded iPAddress subtree `t` holds `ip`: as `pkiIpWithin`,
781
+ * and across the families for an IPv4 address and its IPv4-mapped IPv6 form
782
+ * (`::ffff:a.b.c.d`), which name the same host. An IPv4 subtree holds the
783
+ * mapped form of every address it holds; an IPv6 subtree whose mask covers
784
+ * the whole `::ffff:0:0/96` prefix holds the IPv4 addresses it maps. A
785
+ * wider IPv6 subtree, such as `::/0`, holds no IPv4 address (PKI-33).
786
+ */
787
+ const pkiIpExcludedBy = (ip: u8[], t: X509GeneralSubtree): boolean => {
788
+ if (pkiIpWithin(ip, t)) {
789
+ return true
790
+ }
791
+ const n: i32 = toI32(ip.length)
792
+ const tn: i32 = toI32(t.ip.length)
793
+ if (tn !== toI32(t.mask.length)) {
794
+ return false
795
+ }
796
+ if (n === 16 && tn === 4) {
797
+ return pkiIpMappedPrefix(ip) && pkiIpV4Within(ip, 12, t, 0)
798
+ }
799
+ if (n === 4 && tn === 16) {
800
+ for (let k: i32 = 0; k < 12 && k < toI32(t.mask.length); k++) {
801
+ if (toI32(t.mask[k]) !== 0xff) {
802
+ return false
803
+ }
804
+ }
805
+ return pkiIpMappedPrefix(t.ip) && pkiIpV4Within(ip, 0, t, 12)
806
+ }
807
+ return false
808
+ }
809
+
810
+ /**
811
+ * Whether `issuer`'s iPAddress constraints allow `ip`. A permitted subtree
812
+ * of the other family never holds it; an excluded one holds an address's
813
+ * IPv4-mapped twin as `pkiIpExcludedBy` says, so the exclusion fails closed.
814
+ */
744
815
  const pkiIpAllowed = (issuer: X509Certificate, ip: u8[]): boolean => {
745
816
  let listed: boolean = false
746
817
  let inside: boolean = false
@@ -756,7 +827,7 @@ const pkiIpAllowed = (issuer: X509Certificate, ip: u8[]): boolean => {
756
827
  return false
757
828
  }
758
829
  for (const e of issuer.ncExcluded) {
759
- if (e.kind === X509_GN_IP && pkiIpWithin(ip, e)) {
830
+ if (e.kind === X509_GN_IP && pkiIpExcludedBy(ip, e)) {
760
831
  return false
761
832
  }
762
833
  }
@@ -882,7 +953,8 @@ const pkiCriticalitySound = (c: X509Certificate): boolean => !c.akiCritical && (
882
953
 
883
954
  /**
884
955
  * The checks of the issuer `cand` added above the path, a root of the store
885
- * when `root` holds and an intermediate otherwise: its validity, its critical
956
+ * when `root` holds and an intermediate otherwise: that the store does not
957
+ * distrust its key (`pkiDistrustSpki`), its validity, its critical
886
958
  * extensions and the criticality RFC 5280 fixes, among them a critical
887
959
  * basicConstraints (§4.2.1.9), that it is a CA, its extKeyUsage, its name constraints, its
888
960
  * signature over `child` — the only check that costs — and, once that
@@ -897,6 +969,9 @@ const pkiIssuerCode = (s: PkiSearch, child: X509Certificate, cand: X509Certifica
897
969
  if (!root && toI32(s.path.length) + 2 > PKI_MAX_PATH) {
898
970
  return PKI_ERR_CHAIN_TOO_LONG
899
971
  }
972
+ if (pkiIsDistrusted(s.store, cand)) {
973
+ return PKI_ERR_DISTRUSTED
974
+ }
900
975
  const time: i32 = pkiTimeCode(cand, s.nowMs)
901
976
  if (time !== PKI_OK) {
902
977
  return time
@@ -938,6 +1013,14 @@ const pkiIssuerCode = (s: PkiSearch, child: X509Certificate, cand: X509Certifica
938
1013
  return signature !== PKI_OK ? signature : pkiKeyIdsCode(cand, root)
939
1014
  }
940
1015
 
1016
+ /** Whether `cert`'s subjectPublicKeyInfo hashes to one `store` distrusts; no hash is taken while it distrusts none. */
1017
+ const pkiIsDistrusted = (store: PkiTrustStore, cert: X509Certificate): boolean => {
1018
+ if (store.distrusted.size === 0) {
1019
+ return false
1020
+ }
1021
+ return store.distrusted.has(pkiHex(sha256(cert.spki)))
1022
+ }
1023
+
941
1024
  /** Keeps `code` as the answer when its attempt, `score` long, got nearer a root than any before it. */
942
1025
  const pkiNote = (s: PkiSearch, code: i32, score: i32): void => {
943
1026
  if (score > s.bestScore) {
@@ -1157,6 +1240,28 @@ export const pkiTrustStore = (roots: X509Certificate[]): PkiTrustStore => {
1157
1240
  return store
1158
1241
  }
1159
1242
 
1243
+ /**
1244
+ * Distrusts a key in `store`: from now on, `pkiVerifyServer` refuses with
1245
+ * `PKI_ERR_DISTRUSTED` a path that holds any certificate, the leaf, an
1246
+ * intermediate or a root, whose subjectPublicKeyInfo DER hashes to
1247
+ * `spkiSha256` under SHA-256. A certificate's DER is `X509Certificate.spki`;
1248
+ * `sha256` of `nish/crypto/sha256` hashes it. The key is refused whatever
1249
+ * name or certificate carries it, so one entry covers a CA's cross-signs and
1250
+ * reissues. A store distrusts nothing until this is called.
1251
+ *
1252
+ * @param store The store to add the hash to.
1253
+ * @param spkiSha256 The SHA-256 of the subjectPublicKeyInfo DER, 32 bytes.
1254
+ * @returns Whether the hash was added: false, and nothing added, unless it is
1255
+ * 32 bytes long.
1256
+ */
1257
+ export const pkiDistrustSpki = (store: PkiTrustStore, spkiSha256: u8[]): boolean => {
1258
+ if (toI32(spkiSha256.length) !== 32) {
1259
+ return false
1260
+ }
1261
+ store.distrusted.set(pkiHex(spkiSha256), true)
1262
+ return true
1263
+ }
1264
+
1160
1265
  /**
1161
1266
  * Verifies a TLS server's chain: `chain` holds each certificate's DER as the
1162
1267
  * server sent it, the leaf first; `hostname` is the name or address dialled,
@@ -1172,7 +1277,8 @@ export const pkiTrustStore = (roots: X509Certificate[]): PkiTrustStore => {
1172
1277
  * `PKI_ERR_MALFORMED` and one with more than `PKI_MAX_NAMES` names or
1173
1278
  * `PKI_MAX_SUBTREES` subtrees is `PKI_ERR_BUDGET`; then the leaf's own checks,
1174
1279
  * in turn its validity, an unknown critical extension, being a CA, its key
1175
- * usage, its extended key usage and the host name; then the path search,
1280
+ * usage, its extended key usage and the host name; then whether its key is
1281
+ * distrusted (`pkiDistrustSpki`); then the path search,
1176
1282
  * whose reason the module's header ranks, or `PKI_ERR_BUDGET` when it ran out
1177
1283
  * of signatures or name comparisons; and last, once a path is found, the
1178
1284
  * leaf's profile.
@@ -1225,6 +1331,9 @@ export const pkiVerifyServer = (
1225
1331
  if (leafCode !== PKI_OK) {
1226
1332
  return new PkiResult(leafCode, none)
1227
1333
  }
1334
+ if (pkiIsDistrusted(store, leaf)) {
1335
+ return new PkiResult(PKI_ERR_DISTRUSTED, none)
1336
+ }
1228
1337
  const pool: X509Certificate[] = []
1229
1338
  for (let i: i32 = 1; i < toI32(certs.length); i++) {
1230
1339
  pool.push(certs[i])
@@ -1298,5 +1407,8 @@ export const pkiReason = (code: i32): string => {
1298
1407
  if (code === PKI_ERR_BUDGET) {
1299
1408
  return "the chain asks for more work than one verification does"
1300
1409
  }
1410
+ if (code === PKI_ERR_DISTRUSTED) {
1411
+ return "a certificate's key is distrusted"
1412
+ }
1301
1413
  return "unknown reason"
1302
1414
  }
@@ -561,9 +561,31 @@ export class Sha256 {
561
561
  * @returns A fresh 32-byte digest, which the caller owns.
562
562
  */
563
563
  digest(): u8[] {
564
+ const out: u8[] = new Array<u8>(SHA256_SIZE)
565
+ const from: i32 = 0
566
+ this.digestInto(out, from)
567
+ return out
568
+ }
569
+
570
+ /**
571
+ * Writes the 32-byte message digest (FIPS 180-4 §6.2.2, the final H^(N) in
572
+ * big-endian order) at `out[at .. at + 32)` and ends the computation, with
573
+ * nothing allocated. A window outside `out` panics before anything is
574
+ * written or the hasher is finished, rather than writing the part of the
575
+ * digest that fits. A second `digest` or `digestInto` panics, and so does an
576
+ * `update` after it.
577
+ *
578
+ * @param out The caller's array the digest is written into.
579
+ * @param at Where the 32 digest bytes start in `out`.
580
+ */
581
+ digestInto(out: u8[], at: i32): void {
564
582
  if (this.finished) {
565
583
  panic("Sha256: digest called twice")
566
584
  }
585
+ const size: i32 = toI32(out.length)
586
+ if (at < 0 || at > size - SHA256_SIZE) {
587
+ panic("Sha256: the digest window is outside its array")
588
+ }
567
589
  this.finished = true
568
590
  // §5.1.1: a single 1 bit, then zeros up to 56 bytes into a block, then the
569
591
  // message length in bits as a big-endian 64-bit number. When fewer than
@@ -588,17 +610,23 @@ export class Sha256 {
588
610
  block[SHA256_BLOCK - 1 - i] = toU8(bits >>> toU64(8 * i))
589
611
  }
590
612
  sha256Compress(this.state, this.schedule, block, 0)
591
- const out: u8[] = new Array<u8>(SHA256_SIZE)
592
613
  const state: u32[] = this.state
593
614
  const words: i32 = toI32(state.length)
594
615
  for (let i: i32 = 0; i < words; i += 1) {
595
616
  const word: u32 = state[i]
596
- out[4 * i] = toU8(word >>> 24)
597
- out[4 * i + 1] = toU8(word >>> 16)
598
- out[4 * i + 2] = toU8(word >>> 8)
599
- out[4 * i + 3] = toU8(word)
617
+ const p: i32 = at + 4 * i
618
+ // Always true once the window check above passed; written out so the
619
+ // prover sees each byte's index is inside `out`, and a panic rather
620
+ // than a skipped write if an edit ever makes it false.
621
+ if (p >= 0 && p + 3 < toI32(out.length)) {
622
+ out[p] = toU8(word >>> 24)
623
+ out[p + 1] = toU8(word >>> 16)
624
+ out[p + 2] = toU8(word >>> 8)
625
+ out[p + 3] = toU8(word)
626
+ } else {
627
+ panic("Sha256: a digest word fell outside its window")
628
+ }
600
629
  }
601
- return out
602
630
  }
603
631
  }
604
632
 
@@ -248,6 +248,11 @@ export class X509Certificate {
248
248
  subject: u8[]
249
249
  /** The subjectPublicKey BIT STRING's octets: for a P-256 key, the 65-byte uncompressed point. */
250
250
  publicKey: u8[]
251
+ /**
252
+ * The subjectPublicKeyInfo's DER, whole: the key and its algorithm, as a
253
+ * key pin or `nish/crypto/pki`'s `pkiDistrustSpki` hashes it.
254
+ */
255
+ spki: u8[]
251
256
  /** The signatureValue BIT STRING's octets: for ECDSA, the DER `SEQUENCE { r, s }`. */
252
257
  signature: u8[]
253
258
  /** The first instant the certificate is valid, inclusive (RFC 5280 §4.1.2.5). */
@@ -347,6 +352,7 @@ export class X509Certificate {
347
352
  this.issuer = []
348
353
  this.subject = []
349
354
  this.publicKey = []
355
+ this.spki = []
350
356
  this.signature = []
351
357
  this.sanDns = []
352
358
  this.sanIp = []
@@ -2275,6 +2281,7 @@ export const x509ParseCertificate = (der: u8[]): X509Certificate | null => {
2275
2281
  out.issuer = x509DerWhole(der, issuer)
2276
2282
  out.subject = x509DerWhole(der, subject)
2277
2283
  out.publicKey = publicKey
2284
+ out.spki = x509DerWhole(der, spki)
2278
2285
  out.p256 = out.keyType === X509_KEY_P256
2279
2286
  out.notBefore = before
2280
2287
  out.notAfter = after
@@ -0,0 +1,273 @@
1
+ /**
2
+ * `nish/host/game` — the memory a game built for `wasm32` shares with the page
3
+ * that runs it: the frame it draws, the input the page feeds it, the sounds it
4
+ * asks for and the samples the page plays them from. Every piece is module
5
+ * storage, so the page reaches it in place through the loader's
6
+ * `views().storage` (the keys below are the storage's names) and nothing is
7
+ * copied across the boundary in either direction.
8
+ *
9
+ * | Storage | Words | Written by | Holds |
10
+ * | --- | --- | --- | --- |
11
+ * | `GAME_FRAME` | `Int32Array(960 × 540)` | the game | the frame, `0xRRGGBB`, row-major, `width` words a row |
12
+ * | `GAME_INFO` | `Int32Array(4)` | the game | `[width, height, samples, sampleRate]` |
13
+ * | `GAME_INPUT` | `Int32Array(2 + 7 × 64)` | the page | a `nish/host/ring` of input events, 7 words each |
14
+ * | `GAME_SOUNDS` | `Int32Array(2 + 32)` | the game | a `nish/host/ring` of sound ids to start |
15
+ * | `GAME_SAMPLES` | `Float32Array(96000)` | the game | one sound's samples, `-1..1` |
16
+ *
17
+ * **The frame.** The game picks its size with `gameSetSize` (at most
18
+ * `GAME_MAX_WIDTH × GAME_MAX_HEIGHT`) and draws into `GAME_FRAME`, for
19
+ * instance by lending it to `nish/raster` with `gameWidth()` and
20
+ * `gameHeight()`. The page reads `GAME_INFO[0]` and `[1]` and copies the first
21
+ * `width × height` words into its canvas, setting each pixel's alpha to 255
22
+ * as it does. Storage cannot be returned or aliased, so a program names
23
+ * `GAME_FRAME` itself rather than asking a function for it.
24
+ *
25
+ * **Input.** The page pushes one record of `GAME_EVENT_WORDS` words per event
26
+ * onto `GAME_INPUT`, and pushes a record only when the ring has room for all
27
+ * of it. The words are:
28
+ *
29
+ * | Word | Key event | Pointer event | Focus event |
30
+ * | --- | --- | --- | --- |
31
+ * | 0 | `EVENT_KEY` | `EVENT_MOUSE` | `EVENT_FOCUS` |
32
+ * | 1 | the `KEY_` kind | the `MOUSE_` button, `MOUSE_NONE` for a move | 1 gained, 0 lost |
33
+ * | 2 | the code point, for `KEY_CHAR` | 0 | 0 |
34
+ * | 3 | the `MOD_` bits | the `MOD_` bits | 0 |
35
+ * | 4 | `ACTION_PRESS`, `ACTION_REPEAT` or `ACTION_RELEASE` | `ACTION_PRESS`, `ACTION_RELEASE` or `ACTION_MOVE` | 0 |
36
+ * | 5 | 0 | x, in frame pixels | 0 |
37
+ * | 6 | 0 | y, in frame pixels | 0 |
38
+ *
39
+ * The constants are `nish/term`'s, so a step reads the page's keys exactly as
40
+ * it reads a terminal's. Each step the game calls `gameReadInput`, which
41
+ * drains the ring into a `nish/input` `StepInput`: its `events` become this
42
+ * step's events and its `keys` (a `KeyState`) keep which keys are held, for
43
+ * `isDown`. A page sees every key go up, so it sends a release for every press
44
+ * (`keyup`) and a lost focus on `blur`, which releases every held key; the
45
+ * reader turns `KeyState`'s synthetic releases off. A page has no terminal to
46
+ * quit, so Ctrl-C arrives as an ordinary key press, never `EVENT_QUIT`. Nor
47
+ * does the reader make up auto-repeat: a page that wants it sends
48
+ * `ACTION_REPEAT` records itself (a `keydown` with `repeat` set, say). A
49
+ * pointer event's x and y are set as both the event's cell (`x`, `y`) and its
50
+ * pixel (`px`, `py`).
51
+ * A record with an unknown kind is dropped, and so is a trailing part-record
52
+ * a page pushed out of protocol.
53
+ *
54
+ * **Sound.** The game names its sounds by small ids and asks for one with
55
+ * `gamePlaySound`, which queues the id on `GAME_SOUNDS`; the page shifts the
56
+ * ring after each step and starts each id's buffer. To build those buffers,
57
+ * the page calls an export of the game's once per id at start, which
58
+ * synthesizes the sound (with `nish/synth`, say) and hands it to
59
+ * `gameWriteSamples`; the page then reads `GAME_INFO[2]` samples of
60
+ * `GAME_SAMPLES` at `GAME_INFO[3]` Hz into an `AudioBuffer`.
61
+ *
62
+ * import { GAME_FRAME, gameHeight, gamePlaySound, gameReadInput, gameSetSize, gameWidth, gameWriteSamples } from "nish/host/game";
63
+ * import { KeyState } from "nish/term";
64
+ * import { StepInput } from "nish/input";
65
+ * import { rasterRect } from "nish/raster";
66
+ * import { SYNTH_SQUARE, synthSilence, synthTone } from "nish/synth";
67
+ *
68
+ * const input = new StepInput(new KeyState());
69
+ *
70
+ * export const start = (): void => gameSetSize(320, 180);
71
+ *
72
+ * export const sound = (id: i32): i32 => {
73
+ * const out = synthSilence(0.1, 22050);
74
+ * synthTone(out, 22050, 0.0, 0.1, 440.0 + toF64(id) * 110.0, 220.0, SYNTH_SQUARE, 0.3, 20.0);
75
+ * return gameWriteSamples(out, 22050);
76
+ * };
77
+ *
78
+ * export const step = (nowMs: f64): void => {
79
+ * gameReadInput(input, nowMs);
80
+ * if (input.events.length > 0) gamePlaySound(0);
81
+ * rasterRect(GAME_FRAME, gameWidth(), gameHeight(), 0, 0, 320, 180, 0x101830, 256);
82
+ * };
83
+ *
84
+ * **Building it.** A page's game is compiled with `--target wasm32` and
85
+ * linked by `scripts/build.sh` with `--profile wasm-host`, which exports the
86
+ * storage above for the loader's `views()`, and `--memory <MiB>`, which pins
87
+ * the memory so those views never go stale. The
88
+ * storage alone is about 2.5 MB (`GAME_FRAME` 2 MB, `GAME_SAMPLES` 384 KB,
89
+ * the rings 2 KB), so pin at least 4 MiB, more for what the game itself
90
+ * allocates. The `GAME_*` names are the page's keys and are reserved: when
91
+ * two modules declare storage of one name, the later module's is keyed by its
92
+ * symbol instead, so a program's own `GAME_FRAME` could move this module's
93
+ * off the key the page reads.
94
+ *
95
+ * The module is ordinary Nish everywhere: a native build has the same
96
+ * storage, so a test can push records onto `GAME_INPUT` and read the frame
97
+ * back without a page. It needs no capability and does no I/O.
98
+ */
99
+ import { ringClear, ringPush, ringShift, ringSize } from "nish/host/ring"
100
+ import { StepInput } from "nish/input"
101
+ import { EVENT_FOCUS, EVENT_KEY, EVENT_MOUSE, TermEvent } from "nish/term"
102
+
103
+ /** The widest frame `GAME_FRAME` holds, in pixels. */
104
+ export const GAME_MAX_WIDTH: i32 = 960
105
+
106
+ /** The tallest frame `GAME_FRAME` holds, in pixels. */
107
+ export const GAME_MAX_HEIGHT: i32 = 540
108
+
109
+ /** The words of one input record on `GAME_INPUT`. */
110
+ export const GAME_EVENT_WORDS: i32 = 7
111
+
112
+ /** The input records `GAME_INPUT` holds at once. */
113
+ export const GAME_INPUT_EVENTS: i32 = 64
114
+
115
+ /** The sound ids `GAME_SOUNDS` holds at once. */
116
+ export const GAME_SOUND_SLOTS: i32 = 32
117
+
118
+ /** The samples `GAME_SAMPLES` holds: two seconds at 48000 Hz. */
119
+ export const GAME_SAMPLE_LIMIT: i32 = 96000
120
+
121
+ /** `GAME_INFO`'s word for the frame's width in pixels. */
122
+ export const GAME_INFO_WIDTH: i32 = 0
123
+
124
+ /** `GAME_INFO`'s word for the frame's height in pixels. */
125
+ export const GAME_INFO_HEIGHT: i32 = 1
126
+
127
+ /** `GAME_INFO`'s word for how many samples `gameWriteSamples` last wrote. */
128
+ export const GAME_INFO_SAMPLES: i32 = 2
129
+
130
+ /** `GAME_INFO`'s word for the sample rate of those samples, in Hz. */
131
+ export const GAME_INFO_RATE: i32 = 3
132
+
133
+ /** The frame: `0xRRGGBB` pixels, row-major, `GAME_INFO[GAME_INFO_WIDTH]` words a row. */
134
+ export const GAME_FRAME = new Int32Array(960 * 540)
135
+
136
+ /** The frame's size and the last sound's sample count and rate; see `GAME_INFO_WIDTH` and the rest. */
137
+ export const GAME_INFO = new Int32Array(4)
138
+
139
+ /** The page's input events: a `nish/host/ring` of `GAME_EVENT_WORDS`-word records. */
140
+ export const GAME_INPUT = new Int32Array(2 + 7 * 64)
141
+
142
+ /** The sound ids the game asked for since the page last looked: a `nish/host/ring`. */
143
+ export const GAME_SOUNDS = new Int32Array(2 + 32)
144
+
145
+ /** One sound's samples, written by `gameWriteSamples` for the page to copy. */
146
+ export const GAME_SAMPLES = new Float32Array(96000)
147
+
148
+ /** `v` held to `0..most`. */
149
+ const gameClamp = (v: i32, most: i32): i32 => Math.min(Math.max(v, 0), most)
150
+
151
+ /**
152
+ * Set the frame's size, which the page reads to know how much of `GAME_FRAME`
153
+ * to show. Each side is held to `0..GAME_MAX_WIDTH` and `0..GAME_MAX_HEIGHT`.
154
+ * The pixels are not touched: the next frame draws over them.
155
+ *
156
+ * @param width - the frame's width in pixels
157
+ * @param height - the frame's height in pixels
158
+ */
159
+ export const gameSetSize = (width: i32, height: i32): void => {
160
+ GAME_INFO[GAME_INFO_WIDTH] = gameClamp(width, GAME_MAX_WIDTH)
161
+ GAME_INFO[GAME_INFO_HEIGHT] = gameClamp(height, GAME_MAX_HEIGHT)
162
+ }
163
+
164
+ /**
165
+ * The frame's width, as `gameSetSize` set it.
166
+ *
167
+ * @returns the width in pixels, held to `0..GAME_MAX_WIDTH` even if the page wrote the word
168
+ */
169
+ export const gameWidth = (): i32 => gameClamp(GAME_INFO[GAME_INFO_WIDTH], GAME_MAX_WIDTH)
170
+
171
+ /**
172
+ * The frame's height, as `gameSetSize` set it.
173
+ *
174
+ * @returns the height in pixels, held to `0..GAME_MAX_HEIGHT` even if the page wrote the word
175
+ */
176
+ export const gameHeight = (): i32 => gameClamp(GAME_INFO[GAME_INFO_HEIGHT], GAME_MAX_HEIGHT)
177
+
178
+ /** The next record on `GAME_INPUT` as a `TermEvent`, or null for a kind the reader does not know. */
179
+ const gameEventOf = (): TermEvent | null => {
180
+ const type: i32 = ringShift(GAME_INPUT)
181
+ const what: i32 = ringShift(GAME_INPUT)
182
+ const code: i32 = ringShift(GAME_INPUT)
183
+ const modifiers: i32 = ringShift(GAME_INPUT)
184
+ const action: i32 = ringShift(GAME_INPUT)
185
+ const x: i32 = ringShift(GAME_INPUT)
186
+ const y: i32 = ringShift(GAME_INPUT)
187
+ if (type !== EVENT_KEY && type !== EVENT_MOUSE && type !== EVENT_FOCUS) {
188
+ return null
189
+ }
190
+ const e = new TermEvent(type)
191
+ if (type === EVENT_FOCUS) {
192
+ e.gained = what !== 0
193
+ return e
194
+ }
195
+ e.modifiers = modifiers
196
+ e.action = action
197
+ if (type === EVENT_KEY) {
198
+ e.key = what
199
+ e.code = code
200
+ return e
201
+ }
202
+ e.button = what
203
+ e.x = x
204
+ e.y = y
205
+ e.px = x
206
+ e.py = y
207
+ return e
208
+ }
209
+
210
+ /**
211
+ * Drain the page's input into `input`: every whole record on `GAME_INPUT`
212
+ * becomes a `TermEvent`, and `input.events` becomes what `input.keys.apply`
213
+ * makes of them at `nowMs`, so `input.isDown` answers for the keys still held.
214
+ * The page sends real key releases, so the key state's synthetic releases are
215
+ * turned off, and Ctrl-C is an ordinary key (a page's copy), not a quit. A
216
+ * trailing part-record is dropped.
217
+ *
218
+ * @param input - the step's input, kept by the game from step to step
219
+ * @param nowMs - the step's clock in milliseconds, for the key state
220
+ */
221
+ export const gameReadInput = (input: StepInput, nowMs: f64): void => {
222
+ input.keys.releasesAreSynthetic = false
223
+ input.keys.quitOnCtrlC = false
224
+ const read: TermEvent[] = []
225
+ while (ringSize(GAME_INPUT) >= GAME_EVENT_WORDS) {
226
+ const e = gameEventOf()
227
+ if (e !== null) {
228
+ read.push(e)
229
+ }
230
+ }
231
+ if (ringSize(GAME_INPUT) > 0) {
232
+ ringClear(GAME_INPUT)
233
+ }
234
+ input.events = input.keys.apply(read, nowMs)
235
+ }
236
+
237
+ /**
238
+ * Ask the page to start a sound: `id` goes on `GAME_SOUNDS`, which the page
239
+ * drains after the step. A full queue drops the id, since a sound late by a
240
+ * frame is worse than one missed.
241
+ *
242
+ * @param id - the sound's id, the one the page fetched its samples by
243
+ * @returns whether the id was queued
244
+ */
245
+ export const gamePlaySound = (id: i32): boolean => ringPush(GAME_SOUNDS, id)
246
+
247
+ /**
248
+ * Hand one sound's samples to the page: each is clipped to `-1..1` (NaN is
249
+ * 0) and written to `GAME_SAMPLES` as an `f32`, and `GAME_INFO` records how
250
+ * many and at what rate. Samples past `GAME_SAMPLE_LIMIT` are cut off.
251
+ *
252
+ * @param samples - the sound, at `sampleRate` samples a second
253
+ * @param sampleRate - the samples' rate in Hz
254
+ * @returns how many samples were written
255
+ */
256
+ export const gameWriteSamples = (samples: f64[], sampleRate: i32): i32 => {
257
+ const n: i32 = Math.min(toI32(samples.length), GAME_SAMPLE_LIMIT)
258
+ for (let i: i32 = 0; i < n && i < toI32(samples.length); i++) {
259
+ const s: f64 = samples[i]
260
+ let x: f64 = 0.0
261
+ if (s > 1.0) {
262
+ x = 1.0
263
+ } else if (s < -1.0) {
264
+ x = -1.0
265
+ } else if (s >= -1.0) {
266
+ x = s
267
+ }
268
+ GAME_SAMPLES[i] = toF32(x)
269
+ }
270
+ GAME_INFO[GAME_INFO_SAMPLES] = n
271
+ GAME_INFO[GAME_INFO_RATE] = sampleRate
272
+ return n
273
+ }
package/std/input.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `nish/input` — what one fixed step of a program reads from its player: the
3
+ * key and mouse events since the last step, and which keys are held down.
4
+ *
5
+ * The module is pure: no capability, no I/O and no clock. Code that steps a
6
+ * scene takes a `StepInput`, so it compiles for a terminal, for `wasm32`
7
+ * behind a page, or for a test that scripts the keys, and runs the same way
8
+ * under each. The host owns one `StepInput` and points it at what it read
9
+ * each step; nothing is copied.
10
+ *
11
+ * import { KEY_CHAR, KeyState } from "nish/term"
12
+ * import { StepInput } from "nish/input"
13
+ *
14
+ * const quits = (input: StepInput): boolean => input.isDown(KEY_CHAR, 113)
15
+ *
16
+ * const input = new StepInput(new KeyState())
17
+ * // each step, with the events the host read and its clock in ms:
18
+ * input.events = input.keys.apply(read, nowMs)
19
+ * if (quits(input)) { ... }
20
+ *
21
+ * A terminal program sets `events` and `keys` from the `TermInput` that
22
+ * `nish/term-io`'s `runTerminal` hands it. The events and key state themselves
23
+ * (`TermEvent`, `KeyState` and the `KEY_`, `EVENT_` and `ACTION_` constants)
24
+ * are `nish/term`'s, which is pure too.
25
+ */
26
+ import { KeyState, TermEvent } from "nish/term"
27
+
28
+ /** The input of one step: the events since the last step and which keys are down. */
29
+ export class StepInput {
30
+ /** The events since the last step, in the order they arrived; the step may filter them in place. */
31
+ events: TermEvent[]
32
+ /** Which keys are down, for `isDown`. */
33
+ keys: KeyState
34
+
35
+ /**
36
+ * An input with no events yet.
37
+ *
38
+ * @param keys The key state the host keeps current, which `isDown` reads.
39
+ */
40
+ constructor(keys: KeyState) {
41
+ this.events = []
42
+ this.keys = keys
43
+ }
44
+
45
+ /**
46
+ * Whether a key is down.
47
+ *
48
+ * @param key The key's `KEY_` kind.
49
+ * @param code The code point for `KEY_CHAR`; it tells `KEY_CONTROL` and `KEY_UNKNOWN` keys apart
50
+ * too, and is ignored for the other kinds.
51
+ * @returns True from the key's press until its release, real or synthetic, or a loss of focus.
52
+ */
53
+ isDown(key: i32, code: i32): boolean {
54
+ return this.keys.isDown(key, code)
55
+ }
56
+ }