@amritk/nish-x86_64-linux 0.38.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 (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -0,0 +1,736 @@
1
+ // nish/page/frame: puts a framebuffer a wasm module draws into on a canvas,
2
+ // and drives the module with a fixed-step loop that renders on every
3
+ // animation frame. The framebuffer is the module's own memory: an Int32Array
4
+ // of 0xRRGGBB words, row-major, the shape `std/term-pixels.ts` draws. Plain
5
+ // ECMAScript with no imports, so a browser loads it as it is.
6
+ //
7
+ // Both halves read their browser objects (`navigator`, `requestAnimationFrame`,
8
+ // `performance`) from `globalThis` when they are called, never when the module
9
+ // loads, so tests/page-frame runs them under Node against fakes.
10
+
11
+ /** The tiers, best first. A fallback only ever moves down this list. */
12
+ const TIERS = ["webgpu", "webgl2", "canvas2d"];
13
+
14
+ // The WebGPU flag values are fixed by the specification; spelling them here
15
+ // rather than reading `GPUTextureUsage` keeps the module free of a global that
16
+ // exists only where WebGPU does.
17
+ const TEXTURE_BINDING = 0x04;
18
+ const COPY_DST = 0x02;
19
+
20
+ /**
21
+ * One full-screen triangle, its texture coordinates running 0..1 across the
22
+ * viewport with row 0 at the top. The viewport is the letterbox, so the
23
+ * shader never sees the canvas size. The texture is `bgra8unorm`, so a
24
+ * little-endian 0x00RRGGBB word samples as the colour it names; the alpha
25
+ * byte is 0 and is replaced by 1.
26
+ */
27
+ const WGSL = `
28
+ struct Out {
29
+ @builtin(position) position: vec4f,
30
+ @location(0) uv: vec2f,
31
+ }
32
+
33
+ @vertex fn vs(@builtin(vertex_index) i: u32) -> Out {
34
+ let p = vec2f(f32((i << 1u) & 2u), f32(i & 2u));
35
+ var out: Out;
36
+ out.position = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
37
+ out.uv = vec2f(p.x, 1.0 - p.y);
38
+ return out;
39
+ }
40
+
41
+ @group(0) @binding(0) var frame: texture_2d<f32>;
42
+ @group(0) @binding(1) var nearest: sampler;
43
+
44
+ @fragment fn fs(in: Out) -> @location(0) vec4f {
45
+ return vec4f(textureSample(frame, nearest, in.uv).rgb, 1.0);
46
+ }
47
+ `;
48
+
49
+ /** The same triangle for WebGL 2, from `gl_VertexID` alone: no buffer is bound. */
50
+ const GLSL_VERTEX = `#version 300 es
51
+ out vec2 uv;
52
+ void main() {
53
+ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
54
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
55
+ uv = vec2(p.x, 1.0 - p.y);
56
+ }
57
+ `;
58
+
59
+ /**
60
+ * The bytes are uploaded as RGBA, so a 0x00RRGGBB word arrives as
61
+ * (BB, GG, RR, 00): `.bgr` puts the channels back, and alpha is forced to 1.
62
+ */
63
+ const GLSL_FRAGMENT = `#version 300 es
64
+ precision highp float;
65
+ uniform sampler2D frame;
66
+ in vec2 uv;
67
+ out vec4 color;
68
+ void main() {
69
+ color = vec4(texture(frame, uv).bgr, 1.0);
70
+ }
71
+ `;
72
+
73
+ /** A tier's refusal: the message is the reason `attempts` records. */
74
+ const refuse = (reason) => {
75
+ throw new Error(reason);
76
+ };
77
+
78
+ /** Passes an error the presenter catches but cannot act on to the page's error reporting. */
79
+ const report = (error) => {
80
+ if (typeof globalThis.reportError === "function") {
81
+ globalThis.reportError(error);
82
+ } else {
83
+ console.error(error);
84
+ }
85
+ };
86
+
87
+ /** The message of anything a browser API threw or rejected with. */
88
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
89
+
90
+ /**
91
+ * Writes into `box` the largest rectangle of the framebuffer's aspect that
92
+ * fits the canvas, centred, in whole device pixels. `box` is the caller's and
93
+ * reused, so a frame allocates nothing for it.
94
+ */
95
+ const letterbox = (box, canvasWidth, canvasHeight, width, height) => {
96
+ const scale = Math.min(canvasWidth / width, canvasHeight / height);
97
+ const w = Math.max(1, Math.round(width * scale));
98
+ const h = Math.max(1, Math.round(height * scale));
99
+ box.x = Math.floor((canvasWidth - w) / 2);
100
+ box.y = Math.floor((canvasHeight - h) / 2);
101
+ box.w = w;
102
+ box.h = h;
103
+ };
104
+
105
+ /**
106
+ * The WebGPU tier. Each step that can refuse is a recorded reason: no
107
+ * `navigator.gpu`, no adapter, a device that will not come, a canvas that
108
+ * will not give a "webgpu" context, a pipeline that will not build. The
109
+ * context is asked for after the device, so a refusal before it leaves the
110
+ * canvas free for the next tier.
111
+ */
112
+ const buildWebGpu = async (state) => {
113
+ const nav = globalThis.navigator;
114
+ const gpu = nav === undefined || nav === null ? undefined : nav.gpu;
115
+ if (gpu === undefined || gpu === null) {
116
+ refuse("navigator.gpu is missing");
117
+ }
118
+ let adapter = null;
119
+ try {
120
+ adapter = await gpu.requestAdapter();
121
+ } catch (error) {
122
+ refuse(`requestAdapter rejected: ${messageOf(error)}`);
123
+ }
124
+ if (adapter === null || adapter === undefined) {
125
+ refuse("requestAdapter answered null");
126
+ }
127
+ let device = null;
128
+ try {
129
+ device = await adapter.requestDevice();
130
+ } catch (error) {
131
+ refuse(`requestDevice rejected: ${messageOf(error)}`);
132
+ }
133
+ // A lost device or an error nothing captured ends the tier. Both are
134
+ // listened for from the moment the device exists: until the presenter has
135
+ // taken the tier, the first is kept in `ended` and the presenter reads it
136
+ // (`tier.ended`) before it does; after, the presenter drops the tier for the
137
+ // next one. A loss this tier caused itself (`release`, or a refusal below)
138
+ // arrives once the presenter has moved on, and `lose` ignores a tier that
139
+ // is no longer current.
140
+ let ended = null;
141
+ let tier = null;
142
+ const end = (reason) => {
143
+ if (ended === null) {
144
+ ended = reason;
145
+ }
146
+ if (tier !== null) {
147
+ state.lose(tier, reason);
148
+ }
149
+ };
150
+ const onError = (event) => {
151
+ end(`uncaptured WebGPU error: ${messageOf(event.error)}`);
152
+ };
153
+ device.addEventListener("uncapturederror", onError);
154
+ device.lost.then((info) => {
155
+ end(`WebGPU device lost (${info.reason}): ${info.message}`);
156
+ });
157
+ let context = null;
158
+ // A refusal gives back what was made: the context's configuration, then the device.
159
+ const drop = () => {
160
+ device.removeEventListener("uncapturederror", onError);
161
+ if (context !== null) {
162
+ try {
163
+ context.unconfigure();
164
+ } catch (error) {
165
+ report(error);
166
+ }
167
+ }
168
+ device.destroy();
169
+ };
170
+ context = state.canvas.getContext("webgpu");
171
+ if (context === null) {
172
+ drop();
173
+ refuse('getContext("webgpu") answered null');
174
+ }
175
+ state.touched = true;
176
+ const format = gpu.getPreferredCanvasFormat();
177
+ let pipeline = null;
178
+ try {
179
+ context.configure({ device, format, alphaMode: "opaque" });
180
+ const module = device.createShaderModule({ code: WGSL });
181
+ pipeline = await device.createRenderPipelineAsync({
182
+ layout: "auto",
183
+ vertex: { module, entryPoint: "vs" },
184
+ fragment: { module, entryPoint: "fs", targets: [{ format }] },
185
+ primitive: { topology: "triangle-list" },
186
+ });
187
+ } catch (error) {
188
+ drop();
189
+ refuse(`the WebGPU pipeline did not build: ${messageOf(error)}`);
190
+ }
191
+ const sampler = device.createSampler({ magFilter: "nearest", minFilter: "nearest" });
192
+
193
+ // Everything a frame passes to the API is made here, or when the
194
+ // framebuffer's size changes, and only its fields are written per frame.
195
+ let texture = null;
196
+ let group = null;
197
+ const destination = { texture: null };
198
+ const dataLayout = { offset: 0, bytesPerRow: 0, rowsPerImage: 0 };
199
+ const size = { width: 0, height: 0 };
200
+ const textureDescriptor = { size, format: "bgra8unorm", usage: TEXTURE_BINDING | COPY_DST };
201
+ const groupEntries = [
202
+ { binding: 0, resource: null },
203
+ { binding: 1, resource: sampler },
204
+ ];
205
+ const groupDescriptor = { layout: pipeline.getBindGroupLayout(0), entries: groupEntries };
206
+ const attachment = { view: null, clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: "clear", storeOp: "store" };
207
+ const pass = { colorAttachments: [attachment] };
208
+ const submitted = [null];
209
+ const box = { x: 0, y: 0, w: 0, h: 0 };
210
+
211
+ tier = {
212
+ backend: "webgpu",
213
+ ended: () => ended,
214
+ present: (pixels, width, height) => {
215
+ if (width !== size.width || height !== size.height) {
216
+ if (texture !== null) {
217
+ texture.destroy();
218
+ }
219
+ size.width = width;
220
+ size.height = height;
221
+ texture = device.createTexture(textureDescriptor);
222
+ destination.texture = texture;
223
+ dataLayout.bytesPerRow = width * 4;
224
+ dataLayout.rowsPerImage = height;
225
+ groupEntries[0].resource = texture.createView();
226
+ group = device.createBindGroup(groupDescriptor);
227
+ }
228
+ device.queue.writeTexture(destination, pixels, dataLayout, size);
229
+ attachment.view = context.getCurrentTexture().createView();
230
+ letterbox(box, state.canvas.width, state.canvas.height, width, height);
231
+ const encoder = device.createCommandEncoder();
232
+ const render = encoder.beginRenderPass(pass);
233
+ render.setPipeline(pipeline);
234
+ render.setBindGroup(0, group);
235
+ render.setViewport(box.x, box.y, box.w, box.h, 0, 1);
236
+ render.draw(3);
237
+ render.end();
238
+ submitted[0] = encoder.finish();
239
+ device.queue.submit(submitted);
240
+ },
241
+ release: () => {
242
+ device.removeEventListener("uncapturederror", onError);
243
+ if (texture !== null) {
244
+ texture.destroy();
245
+ }
246
+ context.unconfigure();
247
+ device.destroy();
248
+ },
249
+ };
250
+ return tier;
251
+ };
252
+
253
+ /** The WebGL 2 tier: a texture upload of the same bytes and the same triangle. */
254
+ const buildWebGl2 = (state) => {
255
+ const canvas = state.canvas;
256
+ const gl = canvas.getContext("webgl2", {
257
+ alpha: false,
258
+ antialias: false,
259
+ depth: false,
260
+ stencil: false,
261
+ premultipliedAlpha: false,
262
+ });
263
+ if (gl === null) {
264
+ refuse('getContext("webgl2") answered null');
265
+ }
266
+ state.touched = true;
267
+ // Browsers cap the live WebGL contexts a page holds, so a context this tier
268
+ // gives up is lost on purpose rather than left on the abandoned canvas.
269
+ const loseContext = () => {
270
+ const extension = gl.getExtension("WEBGL_lose_context");
271
+ if (extension !== null && !gl.isContextLost()) {
272
+ extension.loseContext();
273
+ }
274
+ };
275
+ if (gl.isContextLost()) {
276
+ refuse("the WebGL 2 context was lost before it was used");
277
+ }
278
+ const shaders = [];
279
+ const program = gl.createProgram();
280
+ const compile = (kind, source) => {
281
+ const shader = gl.createShader(kind);
282
+ shaders.push(shader);
283
+ gl.shaderSource(shader, source);
284
+ gl.compileShader(shader);
285
+ if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) !== true) {
286
+ refuse(`a WebGL 2 shader did not compile: ${gl.getShaderInfoLog(shader)}`);
287
+ }
288
+ return shader;
289
+ };
290
+ try {
291
+ gl.attachShader(program, compile(gl.VERTEX_SHADER, GLSL_VERTEX));
292
+ gl.attachShader(program, compile(gl.FRAGMENT_SHADER, GLSL_FRAGMENT));
293
+ gl.linkProgram(program);
294
+ if (gl.getProgramParameter(program, gl.LINK_STATUS) !== true) {
295
+ refuse(`the WebGL 2 program did not link: ${gl.getProgramInfoLog(program)}`);
296
+ }
297
+ } catch (error) {
298
+ for (const shader of shaders) {
299
+ gl.deleteShader(shader);
300
+ }
301
+ gl.deleteProgram(program);
302
+ loseContext();
303
+ throw error;
304
+ }
305
+ // A linked program keeps what it needs: the shaders can go now.
306
+ for (const shader of shaders) {
307
+ gl.deleteShader(shader);
308
+ }
309
+ const texture = gl.createTexture();
310
+ gl.bindTexture(gl.TEXTURE_2D, texture);
311
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
312
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
313
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
314
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
315
+ gl.useProgram(program);
316
+ gl.uniform1i(gl.getUniformLocation(program, "frame"), 0);
317
+ gl.clearColor(0, 0, 0, 1);
318
+
319
+ // `texSubImage2D` wants a Uint8Array for UNSIGNED_BYTE, so the Int32Array is
320
+ // viewed as bytes. The view is made again only when the caller's array
321
+ // moves: a new buffer after `memory.grow`, or a different span of it.
322
+ let bytes = null;
323
+ let width = 0;
324
+ let height = 0;
325
+ const box = { x: 0, y: 0, w: 0, h: 0 };
326
+ const tier = {
327
+ backend: "webgl2",
328
+ present: (pixels, w, h) => {
329
+ const length = w * h * 4;
330
+ if (
331
+ bytes === null ||
332
+ bytes.buffer !== pixels.buffer ||
333
+ bytes.byteOffset !== pixels.byteOffset ||
334
+ bytes.length !== length
335
+ ) {
336
+ bytes = new Uint8Array(pixels.buffer, pixels.byteOffset, length);
337
+ }
338
+ if (w !== width || h !== height) {
339
+ width = w;
340
+ height = h;
341
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, bytes);
342
+ } else {
343
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, bytes);
344
+ }
345
+ letterbox(box, gl.drawingBufferWidth, gl.drawingBufferHeight, w, h);
346
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
347
+ gl.clear(gl.COLOR_BUFFER_BIT);
348
+ gl.viewport(box.x, box.y, box.w, box.h);
349
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
350
+ },
351
+ release: () => {
352
+ canvas.removeEventListener("webglcontextlost", onLost);
353
+ if (!gl.isContextLost()) {
354
+ gl.deleteTexture(texture);
355
+ gl.deleteProgram(program);
356
+ loseContext();
357
+ }
358
+ },
359
+ };
360
+ // `preventDefault` tells the browser the page handles the loss; the
361
+ // presenter does, by moving to the next tier rather than waiting for a
362
+ // restore that may never come.
363
+ const onLost = (event) => {
364
+ event.preventDefault();
365
+ state.lose(tier, "the WebGL 2 context was lost");
366
+ };
367
+ canvas.addEventListener("webglcontextlost", onLost);
368
+ return tier;
369
+ };
370
+
371
+ /**
372
+ * The Canvas 2D tier, which needs no GPU: the words are swizzled into an
373
+ * ImageData on a canvas the framebuffer's size, which is then drawn scaled
374
+ * with smoothing off. The ImageData and its word view are kept until the
375
+ * framebuffer's size changes.
376
+ */
377
+ const buildCanvas2d = (state) => {
378
+ const canvas = state.canvas;
379
+ const ctx = canvas.getContext("2d", { alpha: false });
380
+ if (ctx === null) {
381
+ refuse('getContext("2d") answered null');
382
+ }
383
+ state.touched = true;
384
+ const source = canvas.ownerDocument.createElement("canvas");
385
+ const sourceCtx = source.getContext("2d");
386
+ if (sourceCtx === null) {
387
+ refuse('the framebuffer-sized canvas answered null to getContext("2d")');
388
+ }
389
+ let image = null;
390
+ let words = null;
391
+ const box = { x: 0, y: 0, w: 0, h: 0 };
392
+ return {
393
+ backend: "canvas2d",
394
+ present: (pixels, width, height) => {
395
+ if (image === null || image.width !== width || image.height !== height) {
396
+ source.width = width;
397
+ source.height = height;
398
+ image = sourceCtx.createImageData(width, height);
399
+ words = new Uint32Array(image.data.buffer, image.data.byteOffset, width * height);
400
+ }
401
+ // ImageData is R, G, B, A in memory, which is the little-endian word
402
+ // 0xAABBGGRR: swap the red and blue bytes and make it opaque.
403
+ const n = width * height;
404
+ for (let i = 0; i < n; i++) {
405
+ const p = pixels[i];
406
+ words[i] = 0xff000000 | ((p & 0xff) << 16) | (p & 0xff00) | ((p >> 16) & 0xff);
407
+ }
408
+ sourceCtx.putImageData(image, 0, 0);
409
+ letterbox(box, canvas.width, canvas.height, width, height);
410
+ ctx.fillStyle = "#000";
411
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
412
+ // Resizing a canvas resets its context's state, so this is set every frame.
413
+ ctx.imageSmoothingEnabled = false;
414
+ ctx.drawImage(source, box.x, box.y, box.w, box.h);
415
+ },
416
+ release: () => undefined,
417
+ };
418
+ };
419
+
420
+ const BUILDERS = { webgpu: buildWebGpu, webgl2: buildWebGl2, canvas2d: buildCanvas2d };
421
+
422
+ /**
423
+ * Makes a presenter on `canvas`, trying WebGPU, then WebGL 2, then Canvas 2D,
424
+ * and keeping the first that builds. Each tier that refuses is recorded in
425
+ * `attempts` with its reason and reported to `onFallback`.
426
+ *
427
+ * A canvas keeps the first context type it was given, so once a tier has taken
428
+ * a context and is then refused or lost, the next tier is built on a fresh
429
+ * canvas: `canvas.cloneNode(false)`, put in the old one's place in the
430
+ * document. The clone keeps the element's attributes (id, classes, style,
431
+ * size) but not its event listeners; `onFallback` is passed it, and
432
+ * `presenter.canvas` reads it after. A canvas outside the document has no
433
+ * place to take, so its fresh canvas is outside the document too: put
434
+ * `presenter.canvas` where it is wanted.
435
+ *
436
+ * @param canvas - the canvas to present on
437
+ * @param options - `prefer`, the tier to start from (the tiers above it are
438
+ * not tried), and `onFallback`, called each time a tier is given up for the
439
+ * next one, at creation or later on a lost device or context
440
+ * @returns the presenter, once a tier has built; it rejects, naming every
441
+ * tier's reason, when none does
442
+ */
443
+ export const createPresenter = async (canvas, options) => {
444
+ const prefer = options === undefined || options.prefer === undefined ? "webgpu" : options.prefer;
445
+ const onFallback = options === undefined ? undefined : options.onFallback;
446
+ const first = TIERS.indexOf(prefer);
447
+ if (first < 0) {
448
+ throw new RangeError(`nish/page/frame: prefer is one of ${TIERS.join(", ")}, not ${prefer}`);
449
+ }
450
+ const attempts = [];
451
+ let current = null;
452
+ // The tier presenting now, or the last one tried once every tier is gone.
453
+ let shown = prefer;
454
+ let destroyed = false;
455
+ let cssSize = null;
456
+
457
+ const state = {
458
+ canvas,
459
+ // Whether the canvas has handed out a context: the next tier then needs a fresh one.
460
+ touched: false,
461
+ lose: (tier, reason) => {
462
+ if (tier !== current || destroyed) {
463
+ return;
464
+ }
465
+ current = null;
466
+ attempts.push({ backend: tier.backend, reason });
467
+ // A release that throws must not keep the next tier from building.
468
+ try {
469
+ tier.release();
470
+ } catch (error) {
471
+ report(error);
472
+ }
473
+ // Every tier below WebGPU builds synchronously, so a fallback is over
474
+ // before the next frame is presented.
475
+ buildFrom(TIERS.indexOf(tier.backend) + 1, tier.backend, reason);
476
+ },
477
+ };
478
+
479
+ const freshCanvas = () => {
480
+ const fresh = state.canvas.cloneNode(false);
481
+ state.canvas.replaceWith(fresh);
482
+ state.canvas = fresh;
483
+ state.touched = false;
484
+ if (cssSize !== null) {
485
+ fresh.width = cssSize.width;
486
+ fresh.height = cssSize.height;
487
+ }
488
+ };
489
+
490
+ // A callback that throws is reported, not let through: the fallback it
491
+ // was told about still has to happen. It gets the canvas the next tier
492
+ // builds on, since at creation `presenter` does not exist yet.
493
+ const fellBack = (from, to, reason) => {
494
+ if (onFallback === undefined) {
495
+ return;
496
+ }
497
+ try {
498
+ onFallback(from, to, reason, state.canvas);
499
+ } catch (error) {
500
+ report(error);
501
+ }
502
+ };
503
+
504
+ // Builds the first tier from `at` down that will, calling `onFallback`
505
+ // for the hand-over from `from` and for each refusal after it. Answers
506
+ // either the tier or a promise of it: WebGPU is the only asynchronous one.
507
+ const buildFrom = (at, from, reason) => {
508
+ if (at >= TIERS.length || destroyed) {
509
+ return null;
510
+ }
511
+ // The fresh canvas goes in first, so `onFallback` can reach it through
512
+ // `presenter.canvas` to add its listeners again.
513
+ if (state.touched) {
514
+ freshCanvas();
515
+ }
516
+ if (from !== null) {
517
+ fellBack(from, TIERS[at], reason);
518
+ }
519
+ const backend = TIERS[at];
520
+ const accept = (tier) => {
521
+ // Destroyed while this tier built (inside `onFallback`, say): it is
522
+ // given back at once rather than installed.
523
+ if (destroyed) {
524
+ tier.release();
525
+ return null;
526
+ }
527
+ // A device lost or erring while its pipeline built (or in the moment
528
+ // before this ran) has already ended the tier.
529
+ const ended = tier.ended === undefined ? null : tier.ended();
530
+ if (ended !== null) {
531
+ tier.release();
532
+ return decline(new Error(ended));
533
+ }
534
+ current = tier;
535
+ shown = backend;
536
+ return tier;
537
+ };
538
+ const decline = (error) => {
539
+ const why = messageOf(error);
540
+ shown = backend;
541
+ attempts.push({ backend, reason: why });
542
+ return buildFrom(at + 1, backend, why);
543
+ };
544
+ try {
545
+ const built = BUILDERS[backend](state);
546
+ return built instanceof Promise ? built.then(accept, decline) : accept(built);
547
+ } catch (error) {
548
+ return decline(error);
549
+ }
550
+ };
551
+
552
+ await buildFrom(first, null, "");
553
+ if (current === null) {
554
+ throw new Error(
555
+ `nish/page/frame: no backend could present: ${attempts.map((a) => `${a.backend}: ${a.reason}`).join("; ")}`
556
+ );
557
+ }
558
+
559
+ return {
560
+ get backend() {
561
+ return shown;
562
+ },
563
+ get attempts() {
564
+ return attempts;
565
+ },
566
+ get canvas() {
567
+ return state.canvas;
568
+ },
569
+ present(pixels, width, height) {
570
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) {
571
+ throw new RangeError(`nish/page/frame: a framebuffer is at least 1x1 whole pixels, not ${width}x${height}`);
572
+ }
573
+ if (pixels.length < width * height) {
574
+ throw new RangeError(`nish/page/frame: ${width}x${height} pixels need ${width * height} words, not ${pixels.length}`);
575
+ }
576
+ if (current !== null) {
577
+ current.present(pixels, width, height);
578
+ }
579
+ },
580
+ resize(cssWidth, cssHeight, devicePixelRatio) {
581
+ if (
582
+ !Number.isFinite(cssWidth) ||
583
+ !Number.isFinite(cssHeight) ||
584
+ !Number.isFinite(devicePixelRatio) ||
585
+ cssWidth < 0 ||
586
+ cssHeight < 0 ||
587
+ devicePixelRatio <= 0
588
+ ) {
589
+ throw new RangeError(
590
+ `nish/page/frame: resize takes finite sizes of at least 0 and a ratio above 0, not ${cssWidth}x${cssHeight} at ${devicePixelRatio}`
591
+ );
592
+ }
593
+ const width = Math.max(1, Math.round(cssWidth * devicePixelRatio));
594
+ const height = Math.max(1, Math.round(cssHeight * devicePixelRatio));
595
+ cssSize = { width, height };
596
+ if (state.canvas.width !== width) {
597
+ state.canvas.width = width;
598
+ }
599
+ if (state.canvas.height !== height) {
600
+ state.canvas.height = height;
601
+ }
602
+ },
603
+ destroy() {
604
+ if (current !== null && !destroyed) {
605
+ destroyed = true;
606
+ current.release();
607
+ current = null;
608
+ }
609
+ destroyed = true;
610
+ },
611
+ };
612
+ };
613
+
614
+ /** How many recent frame intervals the refresh-rate estimate reads. */
615
+ const INTERVALS = 64;
616
+ /** The longest frame the loop accounts for, in milliseconds: a hidden tab's gap is cut to this. */
617
+ const LONGEST_FRAME_MS = 250;
618
+ /** How often the frame-rate counter is brought up to date, in milliseconds. */
619
+ const FPS_WINDOW_MS = 500;
620
+
621
+ /**
622
+ * Runs `step` at a fixed `stepsPerSecond` and `render` on every animation
623
+ * frame, at whatever rate the display runs: a 240 Hz display gets 240 renders
624
+ * a second, each with the `alpha` between the last step and the next to
625
+ * interpolate with. A frame longer than a quarter second (a hidden tab, a
626
+ * debugger pause) is counted as a quarter second, and at most
627
+ * `maxStepsPerFrame` steps run per frame; the backlog past that is dropped
628
+ * rather than carried, so a slow machine slows the game down instead of
629
+ * falling ever further behind. A `step` or `render` that throws ends the
630
+ * loop.
631
+ *
632
+ * @param options - `stepsPerSecond`, `maxStepsPerFrame` (8 by default), and
633
+ * the `step` and `render` callbacks; `render` gets the alpha in [0, 1) and
634
+ * the frame's length in milliseconds, after the clamp (0 on the first frame
635
+ * and on a clock that ran backwards)
636
+ * @returns the running loop: `stop()` cancels its next frame, `refreshHz` is
637
+ * the display's rate as read from the fastest recent frame intervals (0
638
+ * until a frame has passed), and `fps` the renders per second over the last
639
+ * half second or so (0 until one has passed)
640
+ */
641
+ export const runFixedStep = (options) => {
642
+ const stepsPerSecond = options.stepsPerSecond;
643
+ if (!(stepsPerSecond > 0) || !Number.isFinite(stepsPerSecond)) {
644
+ throw new RangeError(`nish/page/frame: stepsPerSecond is a positive number, not ${stepsPerSecond}`);
645
+ }
646
+ const maxSteps = options.maxStepsPerFrame === undefined ? 8 : options.maxStepsPerFrame;
647
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
648
+ throw new RangeError(`nish/page/frame: maxStepsPerFrame is a whole number of at least 1, not ${maxSteps}`);
649
+ }
650
+ const step = options.step;
651
+ const render = options.render;
652
+ const interval = 1000 / stepsPerSecond;
653
+ const requestFrame = globalThis.requestAnimationFrame;
654
+ const cancelFrame = globalThis.cancelAnimationFrame;
655
+
656
+ const intervals = new Float64Array(INTERVALS);
657
+ const sorted = new Float64Array(INTERVALS);
658
+ let recorded = 0;
659
+ let last = -1;
660
+ let accumulator = 0;
661
+ let handle = 0;
662
+ let stopped = false;
663
+ let windowStart = -1;
664
+ let windowFrames = 0;
665
+ let fps = 0;
666
+
667
+ const frame = (now) => {
668
+ if (stopped) {
669
+ return;
670
+ }
671
+ let frameMs = 0;
672
+ if (last >= 0) {
673
+ const elapsed = now - last;
674
+ if (elapsed > 0) {
675
+ intervals[recorded % INTERVALS] = elapsed;
676
+ recorded++;
677
+ }
678
+ // A clock that ran backwards (a faked one) counts as no time at all.
679
+ frameMs = elapsed <= 0 ? 0 : elapsed > LONGEST_FRAME_MS ? LONGEST_FRAME_MS : elapsed;
680
+ accumulator += frameMs;
681
+ let steps = 0;
682
+ while (!stopped && accumulator >= interval && steps < maxSteps) {
683
+ step();
684
+ accumulator -= interval;
685
+ steps++;
686
+ }
687
+ if (accumulator >= interval) {
688
+ accumulator %= interval;
689
+ }
690
+ }
691
+ last = now;
692
+ // A step may have stopped the loop: the frame then renders nothing.
693
+ if (stopped) {
694
+ return;
695
+ }
696
+ if (windowStart < 0) {
697
+ windowStart = now;
698
+ } else {
699
+ windowFrames++;
700
+ if (now - windowStart >= FPS_WINDOW_MS) {
701
+ fps = (windowFrames * 1000) / (now - windowStart);
702
+ windowStart = now;
703
+ windowFrames = 0;
704
+ }
705
+ }
706
+ render(accumulator / interval, frameMs);
707
+ if (!stopped) {
708
+ handle = requestFrame(frame);
709
+ }
710
+ };
711
+ handle = requestFrame(frame);
712
+
713
+ return {
714
+ stop() {
715
+ stopped = true;
716
+ cancelFrame(handle);
717
+ },
718
+ get refreshHz() {
719
+ const n = recorded < INTERVALS ? recorded : INTERVALS;
720
+ if (n === 0) {
721
+ return 0;
722
+ }
723
+ // The eighth-fastest of the last 64 intervals: animation frames land on
724
+ // the display's refresh, so the fast ones are its period, and taking
725
+ // one an eighth of the way in rather than the fastest steps over a
726
+ // single early frame that jitter brought in short.
727
+ sorted.set(intervals);
728
+ const kept = sorted.subarray(0, n);
729
+ kept.sort();
730
+ return 1000 / kept[Math.floor(n / 8)];
731
+ },
732
+ get fps() {
733
+ return fps;
734
+ },
735
+ };
736
+ };