@draht/durable 2026.11.27 → 2026.12.3-2

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 (119) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/codemode/codemode.d.ts.map +1 -1
  3. package/dist/codemode/codemode.js +39 -0
  4. package/dist/codemode/codemode.js.map +1 -1
  5. package/dist/documents.d.ts.map +1 -1
  6. package/dist/documents.js +7 -2
  7. package/dist/documents.js.map +1 -1
  8. package/dist/env/index.d.ts +11 -0
  9. package/dist/env/index.d.ts.map +1 -1
  10. package/dist/env/index.js.map +1 -1
  11. package/dist/env/node.d.ts +1 -0
  12. package/dist/env/node.d.ts.map +1 -1
  13. package/dist/env/node.js +114 -34
  14. package/dist/env/node.js.map +1 -1
  15. package/dist/harness/task-graph.d.ts.map +1 -1
  16. package/dist/harness/task-graph.js +26 -13
  17. package/dist/harness/task-graph.js.map +1 -1
  18. package/dist/harness/usage.d.ts.map +1 -1
  19. package/dist/harness/usage.js +2 -0
  20. package/dist/harness/usage.js.map +1 -1
  21. package/dist/harness/view.d.ts +5 -1
  22. package/dist/harness/view.d.ts.map +1 -1
  23. package/dist/harness/view.js +36 -24
  24. package/dist/harness/view.js.map +1 -1
  25. package/dist/ids.d.ts +10 -0
  26. package/dist/ids.d.ts.map +1 -1
  27. package/dist/ids.js +21 -0
  28. package/dist/ids.js.map +1 -1
  29. package/dist/images/encode.d.ts +33 -0
  30. package/dist/images/encode.d.ts.map +1 -0
  31. package/dist/images/encode.js +69 -0
  32. package/dist/images/encode.js.map +1 -0
  33. package/dist/images/index.d.ts +4 -4
  34. package/dist/images/index.d.ts.map +1 -1
  35. package/dist/images/index.js +41 -58
  36. package/dist/images/index.js.map +1 -1
  37. package/dist/images/node-worker.d.ts +1 -18
  38. package/dist/images/node-worker.d.ts.map +1 -1
  39. package/dist/images/node-worker.js +2 -12
  40. package/dist/images/node-worker.js.map +1 -1
  41. package/dist/images/node.d.ts.map +1 -1
  42. package/dist/images/node.js +4 -103
  43. package/dist/images/node.js.map +1 -1
  44. package/dist/images/pi-images/cloudflare.d.ts +8 -0
  45. package/dist/images/pi-images/cloudflare.d.ts.map +1 -0
  46. package/dist/images/pi-images/cloudflare.js +14 -0
  47. package/dist/images/pi-images/cloudflare.js.map +1 -0
  48. package/dist/images/pi-images/index.d.ts +37 -0
  49. package/dist/images/pi-images/index.d.ts.map +1 -0
  50. package/dist/images/pi-images/index.js +22 -0
  51. package/dist/images/pi-images/index.js.map +1 -0
  52. package/dist/images/pi-images/installed.d.ts +8 -0
  53. package/dist/images/pi-images/installed.d.ts.map +1 -0
  54. package/dist/images/pi-images/installed.js +24 -0
  55. package/dist/images/pi-images/installed.js.map +1 -0
  56. package/dist/images/pi-images/node-worker.d.ts +2 -0
  57. package/dist/images/pi-images/node-worker.d.ts.map +1 -0
  58. package/dist/images/pi-images/node-worker.js +7 -0
  59. package/dist/images/pi-images/node-worker.js.map +1 -0
  60. package/dist/images/pi-images/node.d.ts +24 -0
  61. package/dist/images/pi-images/node.d.ts.map +1 -0
  62. package/dist/images/pi-images/node.js +18 -0
  63. package/dist/images/pi-images/node.js.map +1 -0
  64. package/dist/images/pi-images/processor.d.ts +21 -0
  65. package/dist/images/pi-images/processor.d.ts.map +1 -0
  66. package/dist/images/pi-images/processor.js +117 -0
  67. package/dist/images/pi-images/processor.js.map +1 -0
  68. package/dist/images/thread.d.ts +27 -0
  69. package/dist/images/thread.d.ts.map +1 -0
  70. package/dist/images/thread.js +131 -0
  71. package/dist/images/thread.js.map +1 -0
  72. package/dist/session/session.js +32 -6
  73. package/dist/session/session.js.map +1 -1
  74. package/dist/session/transaction.d.ts.map +1 -1
  75. package/dist/session/transaction.js +3 -0
  76. package/dist/session/transaction.js.map +1 -1
  77. package/dist/storage/jsonl/storage.d.ts +6 -0
  78. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  79. package/dist/storage/jsonl/storage.js +65 -0
  80. package/dist/storage/jsonl/storage.js.map +1 -1
  81. package/dist/storage/sqlite/commit.d.ts.map +1 -1
  82. package/dist/storage/sqlite/commit.js +3 -3
  83. package/dist/storage/sqlite/commit.js.map +1 -1
  84. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  85. package/dist/storage/sqlite/migrations.js +20 -0
  86. package/dist/storage/sqlite/migrations.js.map +1 -1
  87. package/dist/storage/sqlite/rows.d.ts +0 -2
  88. package/dist/storage/sqlite/rows.d.ts.map +1 -1
  89. package/dist/storage/sqlite/rows.js +3 -5
  90. package/dist/storage/sqlite/rows.js.map +1 -1
  91. package/dist/storage/sqlite/storage.d.ts +1 -1
  92. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  93. package/dist/storage/sqlite/storage.js +11 -10
  94. package/dist/storage/sqlite/storage.js.map +1 -1
  95. package/dist/storage/store/documents.d.ts.map +1 -1
  96. package/dist/storage/store/documents.js +4 -6
  97. package/dist/storage/store/documents.js.map +1 -1
  98. package/dist/storage/store/migrations.d.ts +10 -0
  99. package/dist/storage/store/migrations.d.ts.map +1 -0
  100. package/dist/storage/store/migrations.js +44 -0
  101. package/dist/storage/store/migrations.js.map +1 -0
  102. package/dist/storage/store/storage.d.ts +3 -2
  103. package/dist/storage/store/storage.d.ts.map +1 -1
  104. package/dist/storage/store/storage.js +9 -6
  105. package/dist/storage/store/storage.js.map +1 -1
  106. package/dist/storage/store/tables.d.ts +21 -3
  107. package/dist/storage/store/tables.d.ts.map +1 -1
  108. package/dist/storage/store/tables.js +14 -10
  109. package/dist/storage/store/tables.js.map +1 -1
  110. package/dist/tasks.d.ts.map +1 -1
  111. package/dist/tasks.js +2 -0
  112. package/dist/tasks.js.map +1 -1
  113. package/dist/testing/storage-conformance.d.ts.map +1 -1
  114. package/dist/testing/storage-conformance.js +0 -74
  115. package/dist/testing/storage-conformance.js.map +1 -1
  116. package/dist/types.d.ts +4 -1
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/package.json +26 -6
@@ -0,0 +1,22 @@
1
+ import { DEFAULT_IDLE_MS, PiImages } from "./processor.js";
2
+ /**
3
+ * An `ImageProcessor` on pi-images, for `createCodingTools({ images })` and `/images/fit`. `module` is
4
+ * `@earendil-works/pi-images/pi-images.wasm` compiled, or a promise of it: `/images/pi-images/node` reads and compiles
5
+ * it, `/images/pi-images/cloudflare` imports it as a Workers module; a browser passes
6
+ * `WebAssembly.compileStreaming(fetch(url))`.
7
+ *
8
+ * It prepares as Photon's processor does (`encode.ts` holds the policy both follow): an image already upright, in a
9
+ * format providers take inline that its bytes are, and within the limits is returned as it is once it decodes;
10
+ * otherwise it is decoded into the maximum width and height turned upright by its EXIF orientation, and encoded as PNG
11
+ * or JPEG at falling qualities (JPEG first for JPEG sources), then 3/4 smaller at a time, until the base64 fits. The
12
+ * format is read from the bytes; one providers do not take inline (BMP) becomes PNG. Scaling averages the area each
13
+ * pixel covers.
14
+ *
15
+ * The work runs on the calling thread: about 0.2 s for a 12-megapixel JPEG, 0.3 s for a 6-megapixel PNG. A trap (the
16
+ * library's 512 MiB memory ceiling, a panic) answers `undefined`, any other error rejects, and either loses only that
17
+ * instance.
18
+ */
19
+ export function createPiImages(module, options = {}) {
20
+ return new PiImages(module, { kind: "idle", ms: options.idleMs ?? DEFAULT_IDLE_MS }, options.onDropped);
21
+ }
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/images/pi-images/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAoB3D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,cAAc,CAC7B,MAAwD,EACxD,OAAO,GAAoB,EAAE;IAE7B,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,CAAC,MAAM,IAAI,eAAe,EAAE,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;AACzG,CAAC","sourcesContent":["// `@draht/durable/images/pi-images`: an `ImageProcessor` on `@earendil-works/pi-images`, a small\n// WebAssembly image library that streams PNG rows and decodes JPEG at a reduced size into an area filter, so a\n// 12-megapixel photo fits into 2000x2000 with an 18 MiB peak; its memory goes with the instance, which is kept for a\n// burst of images and dropped after it.\nimport type { ImageProcessor } from \"../../tools/image-processor.ts\";\nimport { DEFAULT_IDLE_MS, PiImages } from \"./processor.ts\";\n\n/** How `createPiImages` keeps its instance. */\nexport type PiImagesOptions = {\n\t/**\n\t * How long the instance (and its memory) stays after its last image, so a burst of images shares one; the next\n\t * image after that opens a fresh one, and the dropped one's memory goes at the engine's next garbage collection.\n\t * 0 drops it at the next macrotask: images prepared one after another without waiting on I/O still share it.\n\t * Default 1 s, an unreferenced timer, which never keeps a Node process alive.\n\t */\n\treadonly idleMs?: number;\n\t/**\n\t * Called once each time the processor drops an instance (after its idle time; after an image failed on it, in a task\n\t * of its own once the failure unwound), once nothing of the processor's holds it any more: for a host that wants the\n\t * memory back at once rather than at the engine's next collection, which an idle process may not run for a long\n\t * time. Node's `gc()` (with `--expose-gc`) returns it then.\n\t */\n\treadonly onDropped?: () => void;\n};\n\n/**\n * An `ImageProcessor` on pi-images, for `createCodingTools({ images })` and `/images/fit`. `module` is\n * `@earendil-works/pi-images/pi-images.wasm` compiled, or a promise of it: `/images/pi-images/node` reads and compiles\n * it, `/images/pi-images/cloudflare` imports it as a Workers module; a browser passes\n * `WebAssembly.compileStreaming(fetch(url))`.\n *\n * It prepares as Photon's processor does (`encode.ts` holds the policy both follow): an image already upright, in a\n * format providers take inline that its bytes are, and within the limits is returned as it is once it decodes;\n * otherwise it is decoded into the maximum width and height turned upright by its EXIF orientation, and encoded as PNG\n * or JPEG at falling qualities (JPEG first for JPEG sources), then 3/4 smaller at a time, until the base64 fits. The\n * format is read from the bytes; one providers do not take inline (BMP) becomes PNG. Scaling averages the area each\n * pixel covers.\n *\n * The work runs on the calling thread: about 0.2 s for a 12-megapixel JPEG, 0.3 s for a 6-megapixel PNG. A trap (the\n * library's 512 MiB memory ceiling, a panic) answers `undefined`, any other error rejects, and either loses only that\n * instance.\n */\nexport function createPiImages(\n\tmodule: WebAssembly.Module | Promise<WebAssembly.Module>,\n\toptions: PiImagesOptions = {},\n): ImageProcessor {\n\treturn new PiImages(module, { kind: \"idle\", ms: options.idleMs ?? DEFAULT_IDLE_MS }, options.onDropped);\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { ImageProcessor } from "../../tools/image-processor.ts";
2
+ import { type InstanceLifetime } from "./processor.ts";
3
+ /**
4
+ * A processor on the installed package's wasm, keeping its instance for `lifetime` (`onDropped` as `createPiImages`
5
+ * takes it), loaded on its first image.
6
+ */
7
+ export declare function installedPiImages(lifetime: InstanceLifetime, onDropped?: () => void): ImageProcessor;
8
+ //# sourceMappingURL=installed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installed.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/installed.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,KAAK,gBAAgB,EAAY,MAAM,gBAAgB,CAAC;AAEjE;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,SAAS,CAAC,EAAE,MAAM,IAAI,GAAG,cAAc,CAepG"}
@@ -0,0 +1,24 @@
1
+ // The pi-images processor on the installed `@earendil-works/pi-images`' WebAssembly, for the Node entry and its worker
2
+ // thread: nothing of the library loads before the first image; then its wasm is read and compiled, and the compiled
3
+ // module is kept for the next bursts.
4
+ import { readFile } from "node:fs/promises";
5
+ import { createRequire } from "node:module";
6
+ import { compileImages } from "@earendil-works/pi-images";
7
+ import { PiImages } from "./processor.js";
8
+ /**
9
+ * A processor on the installed package's wasm, keeping its instance for `lifetime` (`onDropped` as `createPiImages`
10
+ * takes it), loaded on its first image.
11
+ */
12
+ export function installedPiImages(lifetime, onDropped) {
13
+ let images;
14
+ return {
15
+ prepare(bytes, mimeType, limits) {
16
+ if (images === undefined) {
17
+ const path = createRequire(import.meta.url).resolve("@earendil-works/pi-images/pi-images.wasm");
18
+ images = new PiImages(readFile(path).then((wasm) => compileImages(wasm)), lifetime, onDropped);
19
+ }
20
+ return images.prepare(bytes, mimeType, limits);
21
+ },
22
+ };
23
+ }
24
+ //# sourceMappingURL=installed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installed.js","sourceRoot":"","sources":["../../../src/images/pi-images/installed.ts"],"names":[],"mappings":"AAAA,uHAAuH;AACvH,oHAAoH;AACpH,sCAAsC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE1D,OAAO,EAAyB,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAEjE;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,QAA0B,EAAE,SAAsB;IACnF,IAAI,MAAkC,CAAC;IACvC,OAAO;QACN,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM;YAC9B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;gBAC1B,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,0CAA0C,CAAC,CAAC;gBAChG,MAAM,GAAG,IAAI,QAAQ,CACpB,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,EAClD,QAAQ,EACR,SAAS,CACT,CAAC;YACH,CAAC;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["// The pi-images processor on the installed `@earendil-works/pi-images`' WebAssembly, for the Node entry and its worker\n// thread: nothing of the library loads before the first image; then its wasm is read and compiled, and the compiled\n// module is kept for the next bursts.\nimport { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { compileImages } from \"@earendil-works/pi-images\";\nimport type { ImageProcessor } from \"../../tools/image-processor.ts\";\nimport { type InstanceLifetime, PiImages } from \"./processor.ts\";\n\n/**\n * A processor on the installed package's wasm, keeping its instance for `lifetime` (`onDropped` as `createPiImages`\n * takes it), loaded on its first image.\n */\nexport function installedPiImages(lifetime: InstanceLifetime, onDropped?: () => void): ImageProcessor {\n\tlet images: ImageProcessor | undefined;\n\treturn {\n\t\tprepare(bytes, mimeType, limits) {\n\t\t\tif (images === undefined) {\n\t\t\t\tconst path = createRequire(import.meta.url).resolve(\"@earendil-works/pi-images/pi-images.wasm\");\n\t\t\t\timages = new PiImages(\n\t\t\t\t\treadFile(path).then((wasm) => compileImages(wasm)),\n\t\t\t\t\tlifetime,\n\t\t\t\t\tonDropped,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn images.prepare(bytes, mimeType, limits);\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=node-worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-worker.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/node-worker.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ // The worker thread of `createNodePiImages()`: pi-images prepares images here, off the caller's event loop. The
2
+ // instance stays as long as the thread: the host's idle exit is the one clock, so no timer of the thread's own drops
3
+ // it between images the host still sends.
4
+ import { serveImages } from "../thread.js";
5
+ import { installedPiImages } from "./installed.js";
6
+ serveImages(installedPiImages({ kind: "thread" }));
7
+ //# sourceMappingURL=node-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-worker.js","sourceRoot":"","sources":["../../../src/images/pi-images/node-worker.ts"],"names":[],"mappings":"AAAA,gHAAgH;AAChH,qHAAqH;AACrH,0CAA0C;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,WAAW,CAAC,iBAAiB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC","sourcesContent":["// The worker thread of `createNodePiImages()`: pi-images prepares images here, off the caller's event loop. The\n// instance stays as long as the thread: the host's idle exit is the one clock, so no timer of the thread's own drops\n// it between images the host still sends.\nimport { serveImages } from \"../thread.ts\";\nimport { installedPiImages } from \"./installed.ts\";\n\nserveImages(installedPiImages({ kind: \"thread\" }));\n"]}
@@ -0,0 +1,24 @@
1
+ import type { ImageProcessor } from "../../tools/image-processor.ts";
2
+ /**
3
+ * Where `createNodePiImages` prepares images, and how long it keeps what it holds for them. `worker` (default `true`)
4
+ * prepares them in a worker thread, so a large photo does not block the event loop for the 0.2 to 0.8 s it takes; the
5
+ * thread exits `idleMs` after its last image (default 30 s) and holds the library's instance until then. `worker:
6
+ * false` prepares them on the calling thread, with no thread to start or keep: the instance goes `idleMs` after the
7
+ * last image (default 1 s), and `onDropped` is called each time it does (`PiImagesOptions.onDropped`).
8
+ */
9
+ export type NodePiImagesOptions = {
10
+ readonly worker?: true;
11
+ readonly idleMs?: number;
12
+ } | {
13
+ readonly worker: false;
14
+ readonly idleMs?: number;
15
+ readonly onDropped?: () => void;
16
+ };
17
+ /**
18
+ * `createPiImages()` for Node and Bun, by default in a worker thread that keeps the process alive only while it
19
+ * prepares an image; a worker that cannot start falls back to the calling thread. A single-file binary cannot resolve
20
+ * the package: compile its own copy of `pi-images.wasm` and call `createPiImages()`. In a worker, the thread holds the
21
+ * library's instance until it exits.
22
+ */
23
+ export declare function createNodePiImages(options?: NodePiImagesOptions): Promise<ImageProcessor>;
24
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/node.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAKrE;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB,GAC5B;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GACpD;IAAE,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,CAAC;AAEzF;;;;;GAKG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,cAAc,CAAC,CASnG"}
@@ -0,0 +1,18 @@
1
+ import { threadedImages } from "../thread.js";
2
+ import { installedPiImages } from "./installed.js";
3
+ import { DEFAULT_IDLE_MS } from "./processor.js";
4
+ /**
5
+ * `createPiImages()` for Node and Bun, by default in a worker thread that keeps the process alive only while it
6
+ * prepares an image; a worker that cannot start falls back to the calling thread. A single-file binary cannot resolve
7
+ * the package: compile its own copy of `pi-images.wasm` and call `createPiImages()`. In a worker, the thread holds the
8
+ * library's instance until it exits.
9
+ */
10
+ export async function createNodePiImages(options = {}) {
11
+ if (options.worker === false) {
12
+ return installedPiImages({ kind: "idle", ms: options.idleMs ?? DEFAULT_IDLE_MS }, options.onDropped);
13
+ }
14
+ // Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.
15
+ const file = new URL(import.meta.url.endsWith(".ts") ? "./node-worker.ts" : "./node-worker.js", import.meta.url);
16
+ return threadedImages(file, options.idleMs ?? 30_000, async () => installedPiImages({ kind: "idle", ms: DEFAULT_IDLE_MS }));
17
+ }
18
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../../../src/images/pi-images/node.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAajD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,OAAO,GAAwB,EAAE;IACzE,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;QAC9B,OAAO,iBAAiB,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,CAAC,MAAM,IAAI,eAAe,EAAE,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IACtG,CAAC;IACD,2GAA2G;IAC3G,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,kBAAkB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACjH,OAAO,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,IAAI,MAAM,EAAE,KAAK,IAAI,EAAE,CAChE,iBAAiB,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,eAAe,EAAE,CAAC,CACxD,CAAC;AACH,CAAC","sourcesContent":["// `@draht/durable/images/pi-images/node`: `createPiImages()` for Node and Bun, with the library's\n// WebAssembly read from the installed `@earendil-works/pi-images`, on the calling thread or in a worker thread.\nimport type { ImageProcessor } from \"../../tools/image-processor.ts\";\nimport { threadedImages } from \"../thread.ts\";\nimport { installedPiImages } from \"./installed.ts\";\nimport { DEFAULT_IDLE_MS } from \"./processor.ts\";\n\n/**\n * Where `createNodePiImages` prepares images, and how long it keeps what it holds for them. `worker` (default `true`)\n * prepares them in a worker thread, so a large photo does not block the event loop for the 0.2 to 0.8 s it takes; the\n * thread exits `idleMs` after its last image (default 30 s) and holds the library's instance until then. `worker:\n * false` prepares them on the calling thread, with no thread to start or keep: the instance goes `idleMs` after the\n * last image (default 1 s), and `onDropped` is called each time it does (`PiImagesOptions.onDropped`).\n */\nexport type NodePiImagesOptions =\n\t| { readonly worker?: true; readonly idleMs?: number }\n\t| { readonly worker: false; readonly idleMs?: number; readonly onDropped?: () => void };\n\n/**\n * `createPiImages()` for Node and Bun, by default in a worker thread that keeps the process alive only while it\n * prepares an image; a worker that cannot start falls back to the calling thread. A single-file binary cannot resolve\n * the package: compile its own copy of `pi-images.wasm` and call `createPiImages()`. In a worker, the thread holds the\n * library's instance until it exits.\n */\nexport async function createNodePiImages(options: NodePiImagesOptions = {}): Promise<ImageProcessor> {\n\tif (options.worker === false) {\n\t\treturn installedPiImages({ kind: \"idle\", ms: options.idleMs ?? DEFAULT_IDLE_MS }, options.onDropped);\n\t}\n\t// Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.\n\tconst file = new URL(import.meta.url.endsWith(\".ts\") ? \"./node-worker.ts\" : \"./node-worker.js\", import.meta.url);\n\treturn threadedImages(file, options.idleMs ?? 30_000, async () =>\n\t\tinstalledPiImages({ kind: \"idle\", ms: DEFAULT_IDLE_MS }),\n\t);\n}\n"]}
@@ -0,0 +1,21 @@
1
+ import { type ImageLimits, type ImageProcessor, type PreparedImage } from "../../tools/image-processor.ts";
2
+ /**
3
+ * How long a processor keeps its instance after the last image: `idle`, `ms` after it (the next image opens a new
4
+ * one); `thread`, as long as the worker thread it runs in lives, whose host's idle exit is then the one clock. Either
5
+ * way a failed image drops it.
6
+ */
7
+ export type InstanceLifetime = {
8
+ readonly kind: "idle";
9
+ readonly ms: number;
10
+ } | {
11
+ readonly kind: "thread";
12
+ };
13
+ /** How long an idle lifetime keeps the instance after the last image unless told otherwise: a burst's gaps. */
14
+ export declare const DEFAULT_IDLE_MS = 1000;
15
+ /** The pi-images processor: one job (instance) per burst of images, as `createPiImages` describes. */
16
+ export declare class PiImages implements ImageProcessor {
17
+ #private;
18
+ constructor(module: WebAssembly.Module | Promise<WebAssembly.Module>, lifetime: InstanceLifetime, onDropped?: () => void);
19
+ prepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined>;
20
+ }
21
+ //# sourceMappingURL=processor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/processor.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,aAAa,EAAY,MAAM,gCAAgC,CAAC;AAIrH;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC;AAE5G,+GAA+G;AAC/G,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,sGAAsG;AACtG,qBAAa,QAAS,YAAW,cAAc;;IAY9C,YACC,MAAM,EAAE,WAAW,CAAC,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,EACxD,QAAQ,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,IAAI,EAKtB;IAEK,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CA8B1G;CA8BD"}
@@ -0,0 +1,117 @@
1
+ // The pi-images processor behind `createPiImages` and the Node entries: one library instance per burst of images, and
2
+ // the policy every processor shares (`encode.ts`) on top of the library's job.
3
+ import { openImageJob } from "@earendil-works/pi-images";
4
+ import { imageDimensions } from "../../tools/image.js";
5
+ import { toBase64 } from "../../tools/image-processor.js";
6
+ import { encodeToFit, mayReturnAsIs, withinLimits } from "../encode.js";
7
+ import { exifOrientation } from "../exif.js";
8
+ /** How long an idle lifetime keeps the instance after the last image unless told otherwise: a burst's gaps. */
9
+ export const DEFAULT_IDLE_MS = 1000;
10
+ /** The pi-images processor: one job (instance) per burst of images, as `createPiImages` describes. */
11
+ export class PiImages {
12
+ #module;
13
+ #lifetime;
14
+ /** The burst's job, while images are prepared and as long as its lifetime says after the last one. */
15
+ #job;
16
+ /** Images in progress. */
17
+ #active = 0;
18
+ /** The timer that drops the job after the last image. */
19
+ #drop;
20
+ /** Called once each time an instance is dropped, as `PiImagesOptions.onDropped` says. */
21
+ #onDropped;
22
+ constructor(module, lifetime, onDropped) {
23
+ this.#module = module;
24
+ this.#lifetime = lifetime;
25
+ this.#onDropped = onDropped;
26
+ }
27
+ async prepare(bytes, mimeType, limits) {
28
+ this.#active++;
29
+ clearTimeout(this.#drop);
30
+ try {
31
+ let job;
32
+ for (;;) {
33
+ this.#job ??= Promise.resolve(this.#module).then(openImageJob);
34
+ const opening = this.#job;
35
+ job = await this.#opened(opening);
36
+ // Another image's trap dropped this job while it opened: take the next one.
37
+ if (this.#job === opening)
38
+ break;
39
+ }
40
+ try {
41
+ return prepare(job, bytes, mimeType, limits);
42
+ }
43
+ catch (error) {
44
+ // The job is dropped: the next image, also one waiting, opens a new one. A failure in the library closed it
45
+ // already, one in the policy's code did not. A trap (out of memory, a panic) is the image's: it cannot be
46
+ // prepared. Anything else is a bug, not an image.
47
+ this.#job = undefined;
48
+ job.close();
49
+ // Told in a task of its own: until the failure unwinds, its frames still reach the instance's memory, so a
50
+ // collection the hook started here would not free it (measured).
51
+ if (this.#onDropped !== undefined)
52
+ setTimeout(this.#onDropped, 0);
53
+ if (error instanceof WebAssembly.RuntimeError)
54
+ return undefined;
55
+ throw error;
56
+ }
57
+ }
58
+ finally {
59
+ this.#active--;
60
+ if (this.#active === 0)
61
+ this.#scheduleDrop();
62
+ }
63
+ }
64
+ /** The job `opening` gives; a failed open is forgotten, so the next image tries again. */
65
+ async #opened(opening) {
66
+ try {
67
+ return await opening;
68
+ }
69
+ catch (error) {
70
+ if (this.#job === opening)
71
+ this.#job = undefined;
72
+ throw error;
73
+ }
74
+ }
75
+ /**
76
+ * Drops the job its idle time from now (in a thread, never: the thread's exit does); the next image clears the
77
+ * timer first, so a job in use is never dropped.
78
+ */
79
+ #scheduleDrop() {
80
+ const job = this.#job;
81
+ if (job === undefined || this.#lifetime.kind === "thread")
82
+ return;
83
+ this.#drop = setTimeout(() => {
84
+ this.#job = undefined;
85
+ void job.then((dropped) => {
86
+ // Closed first: the instance is then unreachable, so a collection the hook starts frees its memory.
87
+ dropped.close();
88
+ this.#onDropped?.();
89
+ });
90
+ }, this.#lifetime.ms);
91
+ // It only frees memory, so it never keeps a Node process alive. Feature detection: browsers' timers are numbers.
92
+ this.#drop.unref?.();
93
+ }
94
+ }
95
+ /** `bytes` prepared with `job`, as `createPiImages` describes. */
96
+ function prepare(job, bytes, mimeType, limits) {
97
+ const orientation = exifOrientation(bytes);
98
+ if (mayReturnAsIs(bytes, mimeType, orientation, limits)) {
99
+ // The header's size, read without decoding: an image it puts past the limits needs fitting, so it decodes once,
100
+ // in `fit`, instead of a check first.
101
+ const declared = imageDimensions(bytes, mimeType);
102
+ if (declared === undefined || withinLimits(declared, limits)) {
103
+ // Decoded even when it is returned as it is: a damaged file is an error, not an image the provider rejects.
104
+ const stored = job.check(bytes);
105
+ if (stored === undefined)
106
+ return undefined;
107
+ if (withinLimits(stored, limits))
108
+ return { data: toBase64(bytes), mimeType };
109
+ }
110
+ }
111
+ const fitted = job.fit(bytes, limits.maxWidth, limits.maxHeight, orientation);
112
+ if (fitted === undefined)
113
+ return undefined;
114
+ const size = { width: fitted.width, height: fitted.height };
115
+ return encodeToFit(job, fitted.from, size, mimeType, limits.maxBytes);
116
+ }
117
+ //# sourceMappingURL=processor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processor.js","sourceRoot":"","sources":["../../../src/images/pi-images/processor.ts"],"names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I,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC3C,MAAM,IAAI,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;IAC5D,OAAO,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;AACvE,CAAC","sourcesContent":["// The pi-images processor behind `createPiImages` and the Node entries: one library instance per burst of images, and\n// the policy every processor shares (`encode.ts`) on top of the library's job.\nimport { type ImageJob, openImageJob } from \"@earendil-works/pi-images\";\nimport { imageDimensions } from \"../../tools/image.ts\";\nimport { type ImageLimits, type ImageProcessor, type PreparedImage, toBase64 } from \"../../tools/image-processor.ts\";\nimport { encodeToFit, mayReturnAsIs, withinLimits } from \"../encode.ts\";\nimport { exifOrientation } from \"../exif.ts\";\n\n/**\n * How long a processor keeps its instance after the last image: `idle`, `ms` after it (the next image opens a new\n * one); `thread`, as long as the worker thread it runs in lives, whose host's idle exit is then the one clock. Either\n * way a failed image drops it.\n */\nexport type InstanceLifetime = { readonly kind: \"idle\"; readonly ms: number } | { readonly kind: \"thread\" };\n\n/** How long an idle lifetime keeps the instance after the last image unless told otherwise: a burst's gaps. */\nexport const DEFAULT_IDLE_MS = 1000;\n\n/** The pi-images processor: one job (instance) per burst of images, as `createPiImages` describes. */\nexport class PiImages implements ImageProcessor {\n\treadonly #module: WebAssembly.Module | Promise<WebAssembly.Module>;\n\treadonly #lifetime: InstanceLifetime;\n\t/** The burst's job, while images are prepared and as long as its lifetime says after the last one. */\n\t#job: Promise<ImageJob> | undefined;\n\t/** Images in progress. */\n\t#active = 0;\n\t/** The timer that drops the job after the last image. */\n\t#drop: ReturnType<typeof setTimeout> | undefined;\n\t/** Called once each time an instance is dropped, as `PiImagesOptions.onDropped` says. */\n\treadonly #onDropped: (() => void) | undefined;\n\n\tconstructor(\n\t\tmodule: WebAssembly.Module | Promise<WebAssembly.Module>,\n\t\tlifetime: InstanceLifetime,\n\t\tonDropped?: () => void,\n\t) {\n\t\tthis.#module = module;\n\t\tthis.#lifetime = lifetime;\n\t\tthis.#onDropped = onDropped;\n\t}\n\n\tasync prepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined> {\n\t\tthis.#active++;\n\t\tclearTimeout(this.#drop);\n\t\ttry {\n\t\t\tlet job: ImageJob;\n\t\t\tfor (;;) {\n\t\t\t\tthis.#job ??= Promise.resolve(this.#module).then(openImageJob);\n\t\t\t\tconst opening = this.#job;\n\t\t\t\tjob = await this.#opened(opening);\n\t\t\t\t// Another image's trap dropped this job while it opened: take the next one.\n\t\t\t\tif (this.#job === opening) break;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn prepare(job, bytes, mimeType, limits);\n\t\t\t} catch (error) {\n\t\t\t\t// The job is dropped: the next image, also one waiting, opens a new one. A failure in the library closed it\n\t\t\t\t// already, one in the policy's code did not. A trap (out of memory, a panic) is the image's: it cannot be\n\t\t\t\t// prepared. Anything else is a bug, not an image.\n\t\t\t\tthis.#job = undefined;\n\t\t\t\tjob.close();\n\t\t\t\t// Told in a task of its own: until the failure unwinds, its frames still reach the instance's memory, so a\n\t\t\t\t// collection the hook started here would not free it (measured).\n\t\t\t\tif (this.#onDropped !== undefined) setTimeout(this.#onDropped, 0);\n\t\t\t\tif (error instanceof WebAssembly.RuntimeError) return undefined;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#active--;\n\t\t\tif (this.#active === 0) this.#scheduleDrop();\n\t\t}\n\t}\n\n\t/** The job `opening` gives; a failed open is forgotten, so the next image tries again. */\n\tasync #opened(opening: Promise<ImageJob>): Promise<ImageJob> {\n\t\ttry {\n\t\t\treturn await opening;\n\t\t} catch (error) {\n\t\t\tif (this.#job === opening) this.#job = undefined;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Drops the job its idle time from now (in a thread, never: the thread's exit does); the next image clears the\n\t * timer first, so a job in use is never dropped.\n\t */\n\t#scheduleDrop(): void {\n\t\tconst job = this.#job;\n\t\tif (job === undefined || this.#lifetime.kind === \"thread\") return;\n\t\tthis.#drop = setTimeout(() => {\n\t\t\tthis.#job = undefined;\n\t\t\tvoid job.then((dropped) => {\n\t\t\t\t// Closed first: the instance is then unreachable, so a collection the hook starts frees its memory.\n\t\t\t\tdropped.close();\n\t\t\t\tthis.#onDropped?.();\n\t\t\t});\n\t\t}, this.#lifetime.ms);\n\t\t// It only frees memory, so it never keeps a Node process alive. Feature detection: browsers' timers are numbers.\n\t\t(this.#drop as { unref?: () => void }).unref?.();\n\t}\n}\n\n/** `bytes` prepared with `job`, as `createPiImages` describes. */\nfunction prepare(job: ImageJob, bytes: Uint8Array, mimeType: string, limits: ImageLimits): PreparedImage | undefined {\n\tconst orientation = exifOrientation(bytes);\n\tif (mayReturnAsIs(bytes, mimeType, orientation, limits)) {\n\t\t// The header's size, read without decoding: an image it puts past the limits needs fitting, so it decodes once,\n\t\t// in `fit`, instead of a check first.\n\t\tconst declared = imageDimensions(bytes, mimeType);\n\t\tif (declared === undefined || withinLimits(declared, limits)) {\n\t\t\t// Decoded even when it is returned as it is: a damaged file is an error, not an image the provider rejects.\n\t\t\tconst stored = job.check(bytes);\n\t\t\tif (stored === undefined) return undefined;\n\t\t\tif (withinLimits(stored, limits)) return { data: toBase64(bytes), mimeType };\n\t\t}\n\t}\n\tconst fitted = job.fit(bytes, limits.maxWidth, limits.maxHeight, orientation);\n\tif (fitted === undefined) return undefined;\n\tconst size = { width: fitted.width, height: fitted.height };\n\treturn encodeToFit(job, fitted.from, size, mimeType, limits.maxBytes);\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import type { ImageLimits, ImageProcessor, PreparedImage } from "../tools/image-processor.ts";
2
+ /** One request: the image to prepare, and its ID for the reply. */
3
+ export type PrepareRequest = {
4
+ readonly id: number;
5
+ readonly bytes: Uint8Array;
6
+ readonly mimeType: string;
7
+ readonly limits: ImageLimits;
8
+ };
9
+ /** The reply to a request: its result, or why it failed. */
10
+ export type PrepareReply = {
11
+ readonly kind: "prepared";
12
+ readonly id: number;
13
+ readonly result: PreparedImage | undefined;
14
+ } | {
15
+ readonly kind: "failed";
16
+ readonly id: number;
17
+ readonly error: string;
18
+ };
19
+ /**
20
+ * A processor that prepares images in a worker thread running `file` (which calls `serveImages`), started on the first
21
+ * image and kept alive only while it prepares one; it exits `idleMs` after its last image, and the next starts a new
22
+ * one. Where no thread can start, it prepares them with `inProcess()` on the calling thread from then on.
23
+ */
24
+ export declare function threadedImages(file: URL, idleMs: number, inProcess: () => Promise<ImageProcessor>): ImageProcessor;
25
+ /** Answers the requests of the thread's parent with `images`: the body of a worker file `threadedImages` starts. */
26
+ export declare function serveImages(images: ImageProcessor): void;
27
+ //# sourceMappingURL=thread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thread.d.ts","sourceRoot":"","sources":["../../src/images/thread.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE9F,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;CAC7B,CAAC;AAEF,4DAA4D;AAC5D,MAAM,MAAM,YAAY,GACrB;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,CAAA;CAAE,GAC9F;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5E;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CAqBlH;AAED,oHAAoH;AACpH,wBAAgB,WAAW,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAcxD"}
@@ -0,0 +1,131 @@
1
+ // The Node thread host every image processor's `/node` entry shares: images prepared in a worker thread, off the
2
+ // caller's event loop, which exits after a while without images, freeing what it holds; both sides of it, the
3
+ // caller's (`threadedImages`) and the thread's (`serveImages`).
4
+ import { parentPort, Worker } from "node:worker_threads";
5
+ /**
6
+ * A processor that prepares images in a worker thread running `file` (which calls `serveImages`), started on the first
7
+ * image and kept alive only while it prepares one; it exits `idleMs` after its last image, and the next starts a new
8
+ * one. Where no thread can start, it prepares them with `inProcess()` on the calling thread from then on.
9
+ */
10
+ export function threadedImages(file, idleMs, inProcess) {
11
+ let thread;
12
+ let fallback;
13
+ return {
14
+ async prepare(bytes, mimeType, limits) {
15
+ if (fallback !== undefined)
16
+ return (await fallback).prepare(bytes, mimeType, limits);
17
+ try {
18
+ thread ??= new ImageThread(file, idleMs, (exited) => {
19
+ // An exiting thread forgets itself only: a new one may have started while it terminated.
20
+ if (thread === exited)
21
+ thread = undefined;
22
+ });
23
+ return await thread.prepare(bytes, mimeType, limits);
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof WorkerUnavailable))
27
+ throw error;
28
+ // No worker on this platform or build: prepare here from now on, with one processor however many images
29
+ // were waiting for the worker.
30
+ fallback ??= inProcess();
31
+ return (await fallback).prepare(bytes, mimeType, limits);
32
+ }
33
+ },
34
+ };
35
+ }
36
+ /** Answers the requests of the thread's parent with `images`: the body of a worker file `threadedImages` starts. */
37
+ export function serveImages(images) {
38
+ const port = parentPort;
39
+ if (port === null)
40
+ throw new Error("The image worker needs a parent thread");
41
+ port.on("message", (request) => {
42
+ void images.prepare(request.bytes, request.mimeType, request.limits).then((result) => port.postMessage({ kind: "prepared", id: request.id, result }), (error) => port.postMessage({
43
+ kind: "failed",
44
+ id: request.id,
45
+ error: error instanceof Error ? error.message : String(error),
46
+ }));
47
+ });
48
+ }
49
+ /** The worker could not start, as opposed to failing on one image. */
50
+ class WorkerUnavailable extends Error {
51
+ }
52
+ /** One worker thread and the requests it has not answered; it exits after `idleMs` without requests. */
53
+ class ImageThread {
54
+ #worker;
55
+ #pending = new Map();
56
+ #idleMs;
57
+ #onExit;
58
+ #nextId = 0;
59
+ #idle;
60
+ /** Whether the worker answered once: a failure before that means it is unavailable. */
61
+ #started = false;
62
+ constructor(file, idleMs, onExit) {
63
+ this.#idleMs = idleMs;
64
+ this.#onExit = onExit;
65
+ try {
66
+ this.#worker = new Worker(file);
67
+ }
68
+ catch (error) {
69
+ throw new WorkerUnavailable("The image worker cannot start", { cause: error });
70
+ }
71
+ this.#worker.on("message", (reply) => {
72
+ this.#started = true;
73
+ const request = this.#pending.get(reply.id);
74
+ if (request === undefined)
75
+ return;
76
+ this.#pending.delete(reply.id);
77
+ if (reply.kind === "failed")
78
+ request.reject(new Error(reply.error));
79
+ else
80
+ request.resolve(reply.result);
81
+ this.#settled();
82
+ });
83
+ const fail = (error) => {
84
+ const failure = this.#started
85
+ ? error
86
+ : new WorkerUnavailable("The image worker cannot start", { cause: error });
87
+ for (const request of this.#pending.values())
88
+ request.reject(failure);
89
+ this.#pending.clear();
90
+ this.#exit();
91
+ };
92
+ this.#worker.on("error", fail);
93
+ this.#worker.on("exit", (code) => fail(new Error(`The image worker exited with code ${code}`)));
94
+ // A new thread starts idle: its first image cancels the deadline, so one that cannot be sent leaves a thread
95
+ // that still exits.
96
+ this.#settled();
97
+ }
98
+ prepare(bytes, mimeType, limits) {
99
+ const id = this.#nextId++;
100
+ // A copy into a buffer of its own, transferred: the caller keeps its bytes. `slice()` would not do: a Node
101
+ // Buffer's slice is a view of the caller's (often pooled) memory, which the transfer would detach.
102
+ const copy = new Uint8Array(bytes);
103
+ // Posted before anything is recorded, so a message that cannot be sent leaves no request behind.
104
+ this.#worker.postMessage({ id, bytes: copy, mimeType, limits }, [copy.buffer]);
105
+ const request = Promise.withResolvers();
106
+ this.#pending.set(id, request);
107
+ if (this.#idle !== undefined)
108
+ clearTimeout(this.#idle);
109
+ this.#idle = undefined;
110
+ // A pending image keeps the process alive, as one prepared on the calling thread would.
111
+ this.#worker.ref();
112
+ return request.promise;
113
+ }
114
+ #settled() {
115
+ if (this.#pending.size > 0)
116
+ return;
117
+ this.#worker.unref();
118
+ this.#idle = setTimeout(() => {
119
+ this.#exit();
120
+ void this.#worker.terminate();
121
+ }, this.#idleMs);
122
+ this.#idle.unref();
123
+ }
124
+ #exit() {
125
+ if (this.#idle !== undefined)
126
+ clearTimeout(this.#idle);
127
+ this.#idle = undefined;
128
+ this.#onExit(this);
129
+ }
130
+ }
131
+ //# sourceMappingURL=thread.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thread.js","sourceRoot":"","sources":["../../src/images/thread.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,8GAA8G;AAC9G,gEAAgE;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAgBzD;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,IAAS,EAAE,MAAc,EAAE,SAAwC;IACjG,IAAI,MAA+B,CAAC;IACpC,IAAI,QAA6C,CAAC;IAClD,OAAO;QACN,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM;YACpC,IAAI,QAAQ,KAAK,SAAS;gBAAE,OAAO,CAAC,MAAM,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;YACrF,IAAI,CAAC;gBACJ,MAAM,KAAK,IAAI,WAAW,CAAC,IAAI,EAAE,M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QACxG,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAA6B,CAAC;QACnE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAC/B,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACvD,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,wFAAwF;QACxF,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACnB,OAAO,OAAO,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,QAAQ;QACP,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC;YAAE,OAAO;QACnC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,KAAK,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QAC/B,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACjB,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED,KAAK;QACJ,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACvD,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;CACD","sourcesContent":["// The Node thread host every image processor's `/node` entry shares: images prepared in a worker thread, off the\n// caller's event loop, which exits after a while without images, freeing what it holds; both sides of it, the\n// caller's (`threadedImages`) and the thread's (`serveImages`).\nimport { parentPort, Worker } from \"node:worker_threads\";\nimport type { ImageLimits, ImageProcessor, PreparedImage } from \"../tools/image-processor.ts\";\n\n/** One request: the image to prepare, and its ID for the reply. */\nexport type PrepareRequest = {\n\treadonly id: number;\n\treadonly bytes: Uint8Array;\n\treadonly mimeType: string;\n\treadonly limits: ImageLimits;\n};\n\n/** The reply to a request: its result, or why it failed. */\nexport type PrepareReply =\n\t| { readonly kind: \"prepared\"; readonly id: number; readonly result: PreparedImage | undefined }\n\t| { readonly kind: \"failed\"; readonly id: number; readonly error: string };\n\n/**\n * A processor that prepares images in a worker thread running `file` (which calls `serveImages`), started on the first\n * image and kept alive only while it prepares one; it exits `idleMs` after its last image, and the next starts a new\n * one. Where no thread can start, it prepares them with `inProcess()` on the calling thread from then on.\n */\nexport function threadedImages(file: URL, idleMs: number, inProcess: () => Promise<ImageProcessor>): ImageProcessor {\n\tlet thread: ImageThread | undefined;\n\tlet fallback: Promise<ImageProcessor> | undefined;\n\treturn {\n\t\tasync prepare(bytes, mimeType, limits) {\n\t\t\tif (fallback !== undefined) return (await fallback).prepare(bytes, mimeType, limits);\n\t\t\ttry {\n\t\t\t\tthread ??= new ImageThread(file, idleMs, (exited) => {\n\t\t\t\t\t// An exiting thread forgets itself only: a new one may have started while it terminated.\n\t\t\t\t\tif (thread === exited) thread = undefined;\n\t\t\t\t});\n\t\t\t\treturn await thread.prepare(bytes, mimeType, limits);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof WorkerUnavailable)) throw error;\n\t\t\t\t// No worker on this platform or build: prepare here from now on, with one processor however many images\n\t\t\t\t// were waiting for the worker.\n\t\t\t\tfallback ??= inProcess();\n\t\t\t\treturn (await fallback).prepare(bytes, mimeType, limits);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** Answers the requests of the thread's parent with `images`: the body of a worker file `threadedImages` starts. */\nexport function serveImages(images: ImageProcessor): void {\n\tconst port = parentPort;\n\tif (port === null) throw new Error(\"The image worker needs a parent thread\");\n\tport.on(\"message\", (request: PrepareRequest) => {\n\t\tvoid images.prepare(request.bytes, request.mimeType, request.limits).then(\n\t\t\t(result) => port.postMessage({ kind: \"prepared\", id: request.id, result } satisfies PrepareReply),\n\t\t\t(error: unknown) =>\n\t\t\t\tport.postMessage({\n\t\t\t\t\tkind: \"failed\",\n\t\t\t\t\tid: request.id,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t} satisfies PrepareReply),\n\t\t);\n\t});\n}\n\n/** The worker could not start, as opposed to failing on one image. */\nclass WorkerUnavailable extends Error {}\n\n/** One worker thread and the requests it has not answered; it exits after `idleMs` without requests. */\nclass ImageThread {\n\treadonly #worker: Worker;\n\treadonly #pending = new Map<number, PromiseWithResolvers<PreparedImage | undefined>>();\n\treadonly #idleMs: number;\n\treadonly #onExit: (exited: ImageThread) => void;\n\t#nextId = 0;\n\t#idle: ReturnType<typeof setTimeout> | undefined;\n\t/** Whether the worker answered once: a failure before that means it is unavailable. */\n\t#started = false;\n\n\tconstructor(file: URL, idleMs: number, onExit: (exited: ImageThread) => void) {\n\t\tthis.#idleMs = idleMs;\n\t\tthis.#onExit = onExit;\n\t\ttry {\n\t\t\tthis.#worker = new Worker(file);\n\t\t} catch (error) {\n\t\t\tthrow new WorkerUnavailable(\"The image worker cannot start\", { cause: error });\n\t\t}\n\t\tthis.#worker.on(\"message\", (reply: PrepareReply) => {\n\t\t\tthis.#started = true;\n\t\t\tconst request = this.#pending.get(reply.id);\n\t\t\tif (request === undefined) return;\n\t\t\tthis.#pending.delete(reply.id);\n\t\t\tif (reply.kind === \"failed\") request.reject(new Error(reply.error));\n\t\t\telse request.resolve(reply.result);\n\t\t\tthis.#settled();\n\t\t});\n\t\tconst fail = (error: unknown): void => {\n\t\t\tconst failure = this.#started\n\t\t\t\t? error\n\t\t\t\t: new WorkerUnavailable(\"The image worker cannot start\", { cause: error });\n\t\t\tfor (const request of this.#pending.values()) request.reject(failure);\n\t\t\tthis.#pending.clear();\n\t\t\tthis.#exit();\n\t\t};\n\t\tthis.#worker.on(\"error\", fail);\n\t\tthis.#worker.on(\"exit\", (code) => fail(new Error(`The image worker exited with code ${code}`)));\n\t\t// A new thread starts idle: its first image cancels the deadline, so one that cannot be sent leaves a thread\n\t\t// that still exits.\n\t\tthis.#settled();\n\t}\n\n\tprepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined> {\n\t\tconst id = this.#nextId++;\n\t\t// A copy into a buffer of its own, transferred: the caller keeps its bytes. `slice()` would not do: a Node\n\t\t// Buffer's slice is a view of the caller's (often pooled) memory, which the transfer would detach.\n\t\tconst copy = new Uint8Array(bytes);\n\t\t// Posted before anything is recorded, so a message that cannot be sent leaves no request behind.\n\t\tthis.#worker.postMessage({ id, bytes: copy, mimeType, limits } satisfies PrepareRequest, [copy.buffer]);\n\t\tconst request = Promise.withResolvers<PreparedImage | undefined>();\n\t\tthis.#pending.set(id, request);\n\t\tif (this.#idle !== undefined) clearTimeout(this.#idle);\n\t\tthis.#idle = undefined;\n\t\t// A pending image keeps the process alive, as one prepared on the calling thread would.\n\t\tthis.#worker.ref();\n\t\treturn request.promise;\n\t}\n\n\t#settled(): void {\n\t\tif (this.#pending.size > 0) return;\n\t\tthis.#worker.unref();\n\t\tthis.#idle = setTimeout(() => {\n\t\t\tthis.#exit();\n\t\t\tvoid this.#worker.terminate();\n\t\t}, this.#idleMs);\n\t\tthis.#idle.unref();\n\t}\n\n\t#exit(): void {\n\t\tif (this.#idle !== undefined) clearTimeout(this.#idle);\n\t\tthis.#idle = undefined;\n\t\tthis.#onExit(this);\n\t}\n}\n"]}
@@ -3,7 +3,7 @@ import { PendingOps, track } from "@draht/chord/delta";
3
3
  import { Watch } from "@draht/chord/watch";
4
4
  import { addressId, checkRecordScope, checkRecordVersion, materializeDocument, resolveAddress, } from "../documents.js";
5
5
  import { ReadOnlySession, SessionFailed, StorageRequestError } from "../errors.js";
6
- import { idFromNumber } from "../ids.js";
6
+ import { identityProblem, idFromNumber } from "../ids.js";
7
7
  import { hostTimers } from "../timers.js";
8
8
  import { CachedStorage, scopeOf } from "./cached-storage.js";
9
9
  import { ConversationTails } from "./conversation-tails.js";
@@ -1573,7 +1573,8 @@ function cancellationError(signal) {
1573
1573
  * The Session's Storage behind its failure guard; every component of the Session reads and writes through it. Before a
1574
1574
  * call, a failed Session gets `SessionFailed` without reaching the backend. A call that throws fails the Session and
1575
1575
  * rethrows the backend's error, unless it is a `StorageRequestError` or a read whose caller's context was aborted:
1576
- * neither says the Storage is broken.
1576
+ * neither says the Storage is broken. A read of an identity no backend can keep is refused as such before the backend,
1577
+ * where it could match another record or fail the Session; a document key is made well-formed first, as stored.
1577
1578
  * `close()` always reaches the backend, so a failed Session still closes it.
1578
1579
  */
1579
1580
  class GuardedStorage {
@@ -1633,7 +1634,10 @@ class GuardedStorage {
1633
1634
  return this.#call(context, () => this.#storage.task(id, context));
1634
1635
  }
1635
1636
  scanTasks(query, limit, cursor, context) {
1636
- return this.#call(context, () => this.#storage.scanTasks(query, limit, cursor, context));
1637
+ return this.#call(context, () => {
1638
+ checkReadIdentity("Task kind", query.kind);
1639
+ return this.#storage.scanTasks(query, limit, cursor, context);
1640
+ });
1637
1641
  }
1638
1642
  submission(id, context) {
1639
1643
  return this.#call(context, () => this.#storage.submission(id, context));
@@ -1642,16 +1646,30 @@ class GuardedStorage {
1642
1646
  return this.#call(context, () => this.#storage.scanSubmissions(query, limit, cursor, context));
1643
1647
  }
1644
1648
  submissionByRequest(conversationId, requestId, context) {
1645
- return this.#call(context, () => this.#storage.submissionByRequest(conversationId, requestId, context));
1649
+ return this.#call(context, () => {
1650
+ checkReadIdentity("Request ID", requestId);
1651
+ return this.#storage.submissionByRequest(conversationId, requestId, context);
1652
+ });
1646
1653
  }
1647
1654
  findDocument(address, at, context) {
1648
- return this.#call(context, () => this.#storage.findDocument(address, at, context));
1655
+ return this.#call(context, () => {
1656
+ checkReadIdentity("Document kind", address.kind);
1657
+ if (address.key === undefined)
1658
+ return this.#storage.findDocument(address, at, context);
1659
+ // The key as `resolveAddress` stores it.
1660
+ const key = address.key.toWellFormed();
1661
+ checkReadIdentity("Document key", key);
1662
+ return this.#storage.findDocument(key === address.key ? address : { ...address, key }, at, context);
1663
+ });
1649
1664
  }
1650
1665
  document(id, at, context) {
1651
1666
  return this.#call(context, () => this.#storage.document(id, at, context));
1652
1667
  }
1653
1668
  scanDocuments(query, limit, cursor, context) {
1654
- return this.#call(context, () => this.#storage.scanDocuments(query, limit, cursor, context));
1669
+ return this.#call(context, () => {
1670
+ checkReadIdentity("Document kind", query.kind);
1671
+ return this.#storage.scanDocuments(query, limit, cursor, context);
1672
+ });
1655
1673
  }
1656
1674
  /**
1657
1675
  * Close the backend once every call underway has settled, so none outlives it or fails after `closed` settles. New
@@ -1698,4 +1716,12 @@ class GuardedStorage {
1698
1716
  throw new SessionFailed(failure.error);
1699
1717
  }
1700
1718
  }
1719
+ /** Refuses a read of an identity no backend can keep (`identityProblem`): an invalid request, failing that read only. */
1720
+ function checkReadIdentity(what, value) {
1721
+ if (value === undefined)
1722
+ return;
1723
+ const problem = identityProblem(what, value);
1724
+ if (problem !== undefined)
1725
+ throw new StorageRequestError(problem);
1726
+ }
1701
1727
  //# sourceMappingURL=session.js.map