@math.gl/tasks 0.0.0-stage → 5.0.0-beta.6

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 (212) hide show
  1. package/LICENSE +147 -0
  2. package/LOADERS-GL-LICENSE.txt +52 -0
  3. package/README.md +26 -2
  4. package/THIRD-PARTY-NOTICES.md +5 -0
  5. package/dist/index.cjs +3454 -0
  6. package/dist/index.cjs.map +6 -0
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +5 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/tasks/index.d.ts +9 -0
  12. package/dist/tasks/index.d.ts.map +1 -0
  13. package/dist/tasks/index.js +9 -0
  14. package/dist/tasks/index.js.map +1 -0
  15. package/dist/tasks/task-channel.d.ts +48 -0
  16. package/dist/tasks/task-channel.d.ts.map +1 -0
  17. package/dist/tasks/task-channel.js +166 -0
  18. package/dist/tasks/task-channel.js.map +1 -0
  19. package/dist/tasks/task-operation-queue.d.ts +26 -0
  20. package/dist/tasks/task-operation-queue.d.ts.map +1 -0
  21. package/dist/tasks/task-operation-queue.js +106 -0
  22. package/dist/tasks/task-operation-queue.js.map +1 -0
  23. package/dist/tasks/task-preload.d.ts +13 -0
  24. package/dist/tasks/task-preload.d.ts.map +1 -0
  25. package/dist/tasks/task-preload.js +96 -0
  26. package/dist/tasks/task-preload.js.map +1 -0
  27. package/dist/tasks/task-runner.d.ts +74 -0
  28. package/dist/tasks/task-runner.d.ts.map +1 -0
  29. package/dist/tasks/task-runner.js +811 -0
  30. package/dist/tasks/task-runner.js.map +1 -0
  31. package/dist/tasks/task-runtime.d.ts +27 -0
  32. package/dist/tasks/task-runtime.d.ts.map +1 -0
  33. package/dist/tasks/task-runtime.js +216 -0
  34. package/dist/tasks/task-runtime.js.map +1 -0
  35. package/dist/tasks/task-sync.d.ts +4 -0
  36. package/dist/tasks/task-sync.d.ts.map +1 -0
  37. package/dist/tasks/task-sync.js +95 -0
  38. package/dist/tasks/task-sync.js.map +1 -0
  39. package/dist/tasks/task-worker-channel.d.ts +11 -0
  40. package/dist/tasks/task-worker-channel.d.ts.map +1 -0
  41. package/dist/tasks/task-worker-channel.js +34 -0
  42. package/dist/tasks/task-worker-channel.js.map +1 -0
  43. package/dist/tasks/task.d.ts +132 -0
  44. package/dist/tasks/task.d.ts.map +1 -0
  45. package/dist/tasks/task.js +5 -0
  46. package/dist/tasks/task.js.map +1 -0
  47. package/dist/tasks/typed-task-dispatch.d.ts +30 -0
  48. package/dist/tasks/typed-task-dispatch.d.ts.map +1 -0
  49. package/dist/tasks/typed-task-dispatch.js +12 -0
  50. package/dist/tasks/typed-task-dispatch.js.map +1 -0
  51. package/dist/worker-utils/index.d.ts +25 -0
  52. package/dist/worker-utils/index.d.ts.map +1 -0
  53. package/dist/worker-utils/index.js +46 -0
  54. package/dist/worker-utils/index.js.map +1 -0
  55. package/dist/worker-utils/lib/async-queue/async-queue.d.ts +32 -0
  56. package/dist/worker-utils/lib/async-queue/async-queue.d.ts.map +1 -0
  57. package/dist/worker-utils/lib/async-queue/async-queue.js +88 -0
  58. package/dist/worker-utils/lib/async-queue/async-queue.js.map +1 -0
  59. package/dist/worker-utils/lib/env-utils/assert.d.ts +3 -0
  60. package/dist/worker-utils/lib/env-utils/assert.d.ts.map +1 -0
  61. package/dist/worker-utils/lib/env-utils/assert.js +13 -0
  62. package/dist/worker-utils/lib/env-utils/assert.js.map +1 -0
  63. package/dist/worker-utils/lib/env-utils/globals.d.ts +22 -0
  64. package/dist/worker-utils/lib/env-utils/globals.d.ts.map +1 -0
  65. package/dist/worker-utils/lib/env-utils/globals.js +30 -0
  66. package/dist/worker-utils/lib/env-utils/globals.js.map +1 -0
  67. package/dist/worker-utils/lib/env-utils/version.d.ts +3 -0
  68. package/dist/worker-utils/lib/env-utils/version.d.ts.map +1 -0
  69. package/dist/worker-utils/lib/env-utils/version.js +11 -0
  70. package/dist/worker-utils/lib/env-utils/version.js.map +1 -0
  71. package/dist/worker-utils/lib/library-utils/library-utils.d.ts +42 -0
  72. package/dist/worker-utils/lib/library-utils/library-utils.d.ts.map +1 -0
  73. package/dist/worker-utils/lib/library-utils/library-utils.js +251 -0
  74. package/dist/worker-utils/lib/library-utils/library-utils.js.map +1 -0
  75. package/dist/worker-utils/lib/node/worker_threads-browser.d.ts +15 -0
  76. package/dist/worker-utils/lib/node/worker_threads-browser.d.ts.map +1 -0
  77. package/dist/worker-utils/lib/node/worker_threads-browser.js +23 -0
  78. package/dist/worker-utils/lib/node/worker_threads-browser.js.map +1 -0
  79. package/dist/worker-utils/lib/node/worker_threads.d.ts +16 -0
  80. package/dist/worker-utils/lib/node/worker_threads.d.ts.map +1 -0
  81. package/dist/worker-utils/lib/node/worker_threads.js +7 -0
  82. package/dist/worker-utils/lib/node/worker_threads.js.map +1 -0
  83. package/dist/worker-utils/lib/npm-tag.d.ts +2 -0
  84. package/dist/worker-utils/lib/npm-tag.d.ts.map +1 -0
  85. package/dist/worker-utils/lib/npm-tag.js +5 -0
  86. package/dist/worker-utils/lib/npm-tag.js.map +1 -0
  87. package/dist/worker-utils/lib/process-utils/child-process-proxy.browser.d.ts +8 -0
  88. package/dist/worker-utils/lib/process-utils/child-process-proxy.browser.d.ts.map +1 -0
  89. package/dist/worker-utils/lib/process-utils/child-process-proxy.browser.js +18 -0
  90. package/dist/worker-utils/lib/process-utils/child-process-proxy.browser.js.map +1 -0
  91. package/dist/worker-utils/lib/process-utils/child-process-proxy.d.ts +45 -0
  92. package/dist/worker-utils/lib/process-utils/child-process-proxy.d.ts.map +1 -0
  93. package/dist/worker-utils/lib/process-utils/child-process-proxy.js +128 -0
  94. package/dist/worker-utils/lib/process-utils/child-process-proxy.js.map +1 -0
  95. package/dist/worker-utils/lib/process-utils/process-utils.d.ts +2 -0
  96. package/dist/worker-utils/lib/process-utils/process-utils.d.ts.map +1 -0
  97. package/dist/worker-utils/lib/process-utils/process-utils.js +32 -0
  98. package/dist/worker-utils/lib/process-utils/process-utils.js.map +1 -0
  99. package/dist/worker-utils/lib/worker-api/create-worker.d.ts +9 -0
  100. package/dist/worker-utils/lib/worker-api/create-worker.d.ts.map +1 -0
  101. package/dist/worker-utils/lib/worker-api/create-worker.js +229 -0
  102. package/dist/worker-utils/lib/worker-api/create-worker.js.map +1 -0
  103. package/dist/worker-utils/lib/worker-api/get-worker-url.d.ts +29 -0
  104. package/dist/worker-utils/lib/worker-api/get-worker-url.d.ts.map +1 -0
  105. package/dist/worker-utils/lib/worker-api/get-worker-url.js +101 -0
  106. package/dist/worker-utils/lib/worker-api/get-worker-url.js.map +1 -0
  107. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts +67 -0
  108. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts.map +1 -0
  109. package/dist/worker-utils/lib/worker-api/process-on-worker.js +429 -0
  110. package/dist/worker-utils/lib/worker-api/process-on-worker.js.map +1 -0
  111. package/dist/worker-utils/lib/worker-api/shared-state.d.ts +34 -0
  112. package/dist/worker-utils/lib/worker-api/shared-state.d.ts.map +1 -0
  113. package/dist/worker-utils/lib/worker-api/shared-state.js +105 -0
  114. package/dist/worker-utils/lib/worker-api/shared-state.js.map +1 -0
  115. package/dist/worker-utils/lib/worker-api/validate-output-ownership.d.ts +3 -0
  116. package/dist/worker-utils/lib/worker-api/validate-output-ownership.d.ts.map +1 -0
  117. package/dist/worker-utils/lib/worker-api/validate-output-ownership.js +10 -0
  118. package/dist/worker-utils/lib/worker-api/validate-output-ownership.js.map +1 -0
  119. package/dist/worker-utils/lib/worker-api/validate-worker-version.d.ts +9 -0
  120. package/dist/worker-utils/lib/worker-api/validate-worker-version.d.ts.map +1 -0
  121. package/dist/worker-utils/lib/worker-api/validate-worker-version.js +35 -0
  122. package/dist/worker-utils/lib/worker-api/validate-worker-version.js.map +1 -0
  123. package/dist/worker-utils/lib/worker-api/worker-resource.d.ts +33 -0
  124. package/dist/worker-utils/lib/worker-api/worker-resource.d.ts.map +1 -0
  125. package/dist/worker-utils/lib/worker-api/worker-resource.js +156 -0
  126. package/dist/worker-utils/lib/worker-api/worker-resource.js.map +1 -0
  127. package/dist/worker-utils/lib/worker-farm/worker-body.d.ts +20 -0
  128. package/dist/worker-utils/lib/worker-farm/worker-body.d.ts.map +1 -0
  129. package/dist/worker-utils/lib/worker-farm/worker-body.js +134 -0
  130. package/dist/worker-utils/lib/worker-farm/worker-body.js.map +1 -0
  131. package/dist/worker-utils/lib/worker-farm/worker-farm.d.ts +73 -0
  132. package/dist/worker-utils/lib/worker-farm/worker-farm.d.ts.map +1 -0
  133. package/dist/worker-utils/lib/worker-farm/worker-farm.js +135 -0
  134. package/dist/worker-utils/lib/worker-farm/worker-farm.js.map +1 -0
  135. package/dist/worker-utils/lib/worker-farm/worker-job.d.ts +47 -0
  136. package/dist/worker-utils/lib/worker-farm/worker-job.d.ts.map +1 -0
  137. package/dist/worker-utils/lib/worker-farm/worker-job.js +124 -0
  138. package/dist/worker-utils/lib/worker-farm/worker-job.js.map +1 -0
  139. package/dist/worker-utils/lib/worker-farm/worker-pool.d.ts +152 -0
  140. package/dist/worker-utils/lib/worker-farm/worker-pool.d.ts.map +1 -0
  141. package/dist/worker-utils/lib/worker-farm/worker-pool.js +584 -0
  142. package/dist/worker-utils/lib/worker-farm/worker-pool.js.map +1 -0
  143. package/dist/worker-utils/lib/worker-farm/worker-thread.d.ts +77 -0
  144. package/dist/worker-utils/lib/worker-farm/worker-thread.d.ts.map +1 -0
  145. package/dist/worker-utils/lib/worker-farm/worker-thread.js +215 -0
  146. package/dist/worker-utils/lib/worker-farm/worker-thread.js.map +1 -0
  147. package/dist/worker-utils/lib/worker-utils/get-input-byte-length.d.ts +5 -0
  148. package/dist/worker-utils/lib/worker-utils/get-input-byte-length.d.ts.map +1 -0
  149. package/dist/worker-utils/lib/worker-utils/get-input-byte-length.js +39 -0
  150. package/dist/worker-utils/lib/worker-utils/get-input-byte-length.js.map +1 -0
  151. package/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.d.ts +15 -0
  152. package/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.d.ts.map +1 -0
  153. package/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js +84 -0
  154. package/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js.map +1 -0
  155. package/dist/worker-utils/lib/worker-utils/get-transfer-list.d.ts +16 -0
  156. package/dist/worker-utils/lib/worker-utils/get-transfer-list.d.ts.map +1 -0
  157. package/dist/worker-utils/lib/worker-utils/get-transfer-list.js +127 -0
  158. package/dist/worker-utils/lib/worker-utils/get-transfer-list.js.map +1 -0
  159. package/dist/worker-utils/lib/worker-utils/remove-nontransferable-options.d.ts +6 -0
  160. package/dist/worker-utils/lib/worker-utils/remove-nontransferable-options.d.ts.map +1 -0
  161. package/dist/worker-utils/lib/worker-utils/remove-nontransferable-options.js +27 -0
  162. package/dist/worker-utils/lib/worker-utils/remove-nontransferable-options.js.map +1 -0
  163. package/dist/worker-utils/types.d.ts +165 -0
  164. package/dist/worker-utils/types.d.ts.map +1 -0
  165. package/dist/worker-utils/types.js +5 -0
  166. package/dist/worker-utils/types.js.map +1 -0
  167. package/dist/worker-utils/workers/null-worker.d.ts +2 -0
  168. package/dist/worker-utils/workers/null-worker.d.ts.map +1 -0
  169. package/dist/worker-utils/workers/null-worker.js +17 -0
  170. package/dist/worker-utils/workers/null-worker.js.map +1 -0
  171. package/package.json +43 -4
  172. package/src/index.ts +5 -0
  173. package/src/tasks/index.ts +33 -0
  174. package/src/tasks/task-channel.ts +191 -0
  175. package/src/tasks/task-operation-queue.ts +109 -0
  176. package/src/tasks/task-preload.ts +107 -0
  177. package/src/tasks/task-runner.ts +933 -0
  178. package/src/tasks/task-runtime.ts +244 -0
  179. package/src/tasks/task-sync.ts +100 -0
  180. package/src/tasks/task-worker-channel.ts +44 -0
  181. package/src/tasks/task.ts +168 -0
  182. package/src/tasks/typed-task-dispatch.ts +44 -0
  183. package/src/worker-utils/index.ts +105 -0
  184. package/src/worker-utils/lib/async-queue/async-queue.ts +100 -0
  185. package/src/worker-utils/lib/env-utils/assert.ts +14 -0
  186. package/src/worker-utils/lib/env-utils/globals.ts +40 -0
  187. package/src/worker-utils/lib/env-utils/version.ts +15 -0
  188. package/src/worker-utils/lib/library-utils/library-utils.ts +305 -0
  189. package/src/worker-utils/lib/node/worker_threads-browser.ts +44 -0
  190. package/src/worker-utils/lib/node/worker_threads.ts +21 -0
  191. package/src/worker-utils/lib/npm-tag.ts +5 -0
  192. package/src/worker-utils/lib/process-utils/child-process-proxy.browser.ts +23 -0
  193. package/src/worker-utils/lib/process-utils/child-process-proxy.ts +172 -0
  194. package/src/worker-utils/lib/process-utils/process-utils.ts +34 -0
  195. package/src/worker-utils/lib/worker-api/create-worker.ts +271 -0
  196. package/src/worker-utils/lib/worker-api/get-worker-url.ts +130 -0
  197. package/src/worker-utils/lib/worker-api/process-on-worker.ts +596 -0
  198. package/src/worker-utils/lib/worker-api/shared-state.ts +135 -0
  199. package/src/worker-utils/lib/worker-api/validate-output-ownership.ts +10 -0
  200. package/src/worker-utils/lib/worker-api/validate-worker-version.ts +44 -0
  201. package/src/worker-utils/lib/worker-api/worker-resource.ts +203 -0
  202. package/src/worker-utils/lib/worker-farm/worker-body.ts +154 -0
  203. package/src/worker-utils/lib/worker-farm/worker-farm.ts +172 -0
  204. package/src/worker-utils/lib/worker-farm/worker-job.ts +148 -0
  205. package/src/worker-utils/lib/worker-farm/worker-pool.ts +719 -0
  206. package/src/worker-utils/lib/worker-farm/worker-thread.ts +260 -0
  207. package/src/worker-utils/lib/worker-utils/get-input-byte-length.ts +34 -0
  208. package/src/worker-utils/lib/worker-utils/get-loadable-worker-url.ts +96 -0
  209. package/src/worker-utils/lib/worker-utils/get-transfer-list.ts +125 -0
  210. package/src/worker-utils/lib/worker-utils/remove-nontransferable-options.ts +27 -0
  211. package/src/worker-utils/types.ts +224 -0
  212. package/src/worker-utils/workers/null-worker.ts +20 -0
@@ -0,0 +1,27 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ /**
5
+ * Recursively drop non serializable values like functions and regexps.
6
+ * @param object
7
+ */
8
+ export function removeNontransferableOptions(object) {
9
+ if (object === null) {
10
+ return {};
11
+ }
12
+ const clone = Object.assign({}, object);
13
+ Object.keys(clone).forEach(key => {
14
+ // Checking if it is an object and not a typed array.
15
+ if (typeof object[key] === 'object' && !ArrayBuffer.isView(object[key])) {
16
+ clone[key] = removeNontransferableOptions(object[key]);
17
+ }
18
+ else if (typeof clone[key] === 'function' || clone[key] instanceof RegExp) {
19
+ clone[key] = {};
20
+ }
21
+ else {
22
+ clone[key] = object[key];
23
+ }
24
+ });
25
+ return clone;
26
+ }
27
+ //# sourceMappingURL=remove-nontransferable-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remove-nontransferable-options.js","sourceRoot":"","sources":["../../../../src/worker-utils/lib/worker-utils/remove-nontransferable-options.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,+BAA+B;AAC/B,4DAA4D;AAE5D;;;GAGG;AACH,MAAM,UAAU,4BAA4B,CAAC,MAAqB;IAChE,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IAExC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QAC/B,qDAAqD;QACrD,IAAI,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACxE,KAAK,CAAC,GAAG,CAAC,GAAG,4BAA4B,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACzD,CAAC;aAAM,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,UAAU,IAAI,KAAK,CAAC,GAAG,CAAC,YAAY,MAAM,EAAE,CAAC;YAC5E,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QAClB,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,165 @@
1
+ import type { SharedWorkerState } from "./lib/worker-api/shared-state.js";
2
+ /** Progress measured independently within a named phase. */
3
+ export type WorkerProgress = {
4
+ /** Operation being measured. */
5
+ phase: string;
6
+ /** Work completed in this phase. */
7
+ completed: number;
8
+ /** Expected work, when known. */
9
+ total?: number;
10
+ /** Measurement unit, such as bytes, rows, or tasks. */
11
+ unit: string;
12
+ };
13
+ /** One settled worker lease. Times are milliseconds; postMessageMs is synchronous serialization/transfer. */
14
+ export type WorkerJobMetrics = {
15
+ name: string;
16
+ outcome: 'completed' | 'failed' | 'cancelled';
17
+ queueWaitMs: number;
18
+ durationMs: number;
19
+ workerCreationMs: number;
20
+ /** Runtime ready handshake latency; absent for legacy custom workers. */
21
+ workerStartupMs?: number;
22
+ postMessageMs: number;
23
+ /** Processor time reported by createWorker; absent for legacy workers. */
24
+ executionMs?: number;
25
+ inputBytes: number;
26
+ };
27
+ export type WorkerPoolStats = {
28
+ queuedJobs: number;
29
+ activeJobs: number;
30
+ queuedBytes: number;
31
+ inFlightBytes: number;
32
+ peakQueuedBytes: number;
33
+ peakInFlightBytes: number;
34
+ pendingAdmissions: number;
35
+ reservations: number;
36
+ workersCreated: number;
37
+ workerRestarts: number;
38
+ completed: number;
39
+ failed: number;
40
+ cancelled: number;
41
+ };
42
+ /** Shared worker execution options. */
43
+ export type WorkerOptions = {
44
+ /** Copy input or transfer its backing buffers; transfer preserves the loaders.gl default. */
45
+ inputOwnership?: 'copy' | 'transfer' | 'share';
46
+ /** Copy worker output or transfer its backing buffers; transfer is the default. */
47
+ outputOwnership?: 'copy' | 'transfer';
48
+ /** Shared control buffer, or false to disable automatic cooperative shared control. */
49
+ sharedState?: SharedArrayBuffer | false;
50
+ /** Hard termination is the compatibility default. Cooperative mode requires createWorker support. */
51
+ cancellationMode?: 'terminate' | 'cooperative';
52
+ /** Grace period before hard termination; defaults to 1000 ms. */
53
+ cancellationTimeout?: number;
54
+ /** Cancels queued or running work. */
55
+ signal?: AbortSignal;
56
+ /** Receives phase progress. Throwing aborts the job with that error. */
57
+ onProgress?: (progress: WorkerProgress) => void;
58
+ CDN?: string | null;
59
+ worker?: boolean;
60
+ /** Declares batch-protocol support for a custom worker, or disables batch offloading. */
61
+ workerInBatches?: boolean;
62
+ /** Per-pool input byte budgets. Queue overflow rejects before input transfer. */
63
+ maxQueuedJobs?: number;
64
+ maxPendingAdmissions?: number;
65
+ priorityAgingMs?: number;
66
+ onMetrics?: (metrics: WorkerJobMetrics) => void;
67
+ performanceMarks?: boolean;
68
+ maxQueuedBytes?: number;
69
+ maxInFlightBytes?: number;
70
+ /** Larger values start first; equal priorities preserve submission order. */
71
+ priority?: number;
72
+ /** Reserved input bytes for a batch session; bounds each batch's retained buffers. */
73
+ inputBytes?: number;
74
+ maxConcurrency?: number;
75
+ maxMobileConcurrency?: number;
76
+ reuseWorkers?: boolean;
77
+ _workerType?: string;
78
+ workerUrl?: string;
79
+ /** Browser worker script type for URL or source targets. Defaults to classic. */
80
+ workerType?: 'classic' | 'module';
81
+ [key: string]: any;
82
+ };
83
+ /**
84
+ * Creates a fresh browser Worker instance for a worker descriptor.
85
+ *
86
+ * Returning `null` delegates to the existing URL-based worker resolution. This lets packages
87
+ * expose bundler-resolved module workers without removing classic worker or CDN support.
88
+ */
89
+ export type LoadWorker = () => Worker | null;
90
+ export type WorkerContext = {
91
+ /** Worker-side signal; long CPU loops must yield and check it to cooperate. */
92
+ signal?: AbortSignal;
93
+ sharedState?: SharedWorkerState;
94
+ /** Checks the message signal and atomic shared cancellation, including inside synchronous loops. */
95
+ throwIfAborted?: () => void;
96
+ /** Reports progress from the active worker job. */
97
+ reportProgress?: (progress: WorkerProgress) => void;
98
+ process?: Process;
99
+ processInBatches?: ProcessInBatches;
100
+ };
101
+ /** Serializable context sent with a single worker job. */
102
+ export type WorkerJobContext = {
103
+ [key: string]: any;
104
+ };
105
+ export type Process<Input = any, Output = any, Options extends object = {
106
+ [key: string]: any;
107
+ }> = (data: Input, options?: Options, context?: WorkerContext, jobContext?: WorkerJobContext) => Output | Promise<Output>;
108
+ export type ProcessInBatches<Input = any, Output = any, Options extends object = {
109
+ [key: string]: any;
110
+ }> = (iterator: AsyncIterable<Input> | Iterable<Input>, options?: Options, context?: WorkerContext, jobContext?: WorkerJobContext) => AsyncIterable<Output>;
111
+ /**
112
+ * A worker description object
113
+ */
114
+ export type WorkerObject<Input = any, Output = any, Options extends object = {
115
+ [key: string]: any;
116
+ }> = {
117
+ id: string;
118
+ name: string;
119
+ module: string;
120
+ /** npm package containing worker artifacts; omitted preserves the loaders.gl URL convention. */
121
+ packageName?: string;
122
+ version: string;
123
+ worker?: string | boolean;
124
+ /** Whether the built-in worker accepts stateful batch requests. */
125
+ workerInBatches?: boolean;
126
+ /** Browser worker filename when it differs from the worker id. */
127
+ workerFile?: string;
128
+ /** Creates a built-in browser worker, typically using `type: 'module'`. */
129
+ loadWorker?: LoadWorker;
130
+ /** Optional Node.js-specific worker filename (for example a `.cjs` asset). */
131
+ workerNode?: string;
132
+ /** Repository-relative source path for a Node test worker after package grouping. */
133
+ workerSourceNode?: string;
134
+ options: {
135
+ [key: string]: any;
136
+ };
137
+ deprecatedOptions?: object;
138
+ process?: Process<Input, Output, Options>;
139
+ processInBatches?: ProcessInBatches<Input, Output, Options>;
140
+ };
141
+ export type WorkerMessageType = 'ready' | 'cancel' | 'progress' | 'preload' | 'process' | 'done' | 'error' | 'process-in-batches' | 'input-request' | 'input-batch' | 'input-done' | 'output-batch' | 'output-ack';
142
+ export type WorkerMessagePayload = {
143
+ /** Phase progress from the worker. */
144
+ progress?: WorkerProgress;
145
+ executionMs?: number;
146
+ id?: number;
147
+ options?: {
148
+ [key: string]: any;
149
+ };
150
+ context?: WorkerJobContext;
151
+ input?: any;
152
+ result?: any;
153
+ error?: string;
154
+ errorName?: string;
155
+ };
156
+ export type WorkerMessageData = {
157
+ source: 'loaders.gl';
158
+ type: WorkerMessageType;
159
+ payload: WorkerMessagePayload;
160
+ };
161
+ export type WorkerMessage = {
162
+ type: string;
163
+ data: WorkerMessageData;
164
+ };
165
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/worker-utils/types.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAC,iBAAiB,EAAC,yCAAsC;AAErE,4DAA4D;AAC5D,MAAM,MAAM,cAAc,GAAG;IAC3B,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,oCAAoC;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,iCAAiC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,6GAA6G;AAC7G,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,yEAAyE;IACzE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,aAAa,EAAE,MAAM,CAAC;IACtB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAA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"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/worker-utils/types.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,+BAA+B;AAC/B,4DAA4D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=null-worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"null-worker.d.ts","sourceRoot":"","sources":["../../../src/worker-utils/workers/null-worker.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ // loaders.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import { createWorker } from "../lib/worker-api/create-worker.js";
5
+ createWorker(async (data) => {
6
+ // @ts-ignore
7
+ return data;
8
+ },
9
+ /** Echoes batches together with session-local state for worker protocol tests. */
10
+ async function* processInBatches(iterator) {
11
+ let batchIndex = 0;
12
+ for await (const input of iterator) {
13
+ yield { input, batchIndex };
14
+ batchIndex++;
15
+ }
16
+ });
17
+ //# sourceMappingURL=null-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"null-worker.js","sourceRoot":"","sources":["../../../src/worker-utils/workers/null-worker.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,+BAA+B;AAC/B,4DAA4D;AAE5D,OAAO,EAAC,YAAY,EAAC,2CAAwC;AAE7D,YAAY,CACV,KAAK,EAAC,IAAI,EAAC,EAAE;IACX,aAAa;IACb,OAAO,IAAI,CAAC;AACd,CAAC;AACD,kFAAkF;AAClF,KAAK,SAAS,CAAC,CAAC,gBAAgB,CAAC,QAAQ;IACvC,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;QACnC,MAAM,EAAC,KAAK,EAAE,UAAU,EAAC,CAAC;QAC1B,UAAU,EAAE,CAAC;IACf,CAAC;AACH,CAAC,CACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@math.gl/tasks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Typed task scheduling and worker execution",
4
+ "version": "5.0.0-beta.6",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/visgl/math.gl.git"
13
+ },
14
+ "types": "dist/index.d.ts",
15
+ "main": "dist/index.cjs",
16
+ "module": "dist/index.js",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "src",
27
+ "!src/**/README.md",
28
+ "README.md",
29
+ "LICENSE",
30
+ "THIRD-PARTY-NOTICES.md",
31
+ "LOADERS-GL-LICENSE.txt"
32
+ ],
33
+ "sideEffects": false,
34
+ "browser": {
35
+ "./dist/worker-utils/lib/node/worker_threads.js": "./dist/worker-utils/lib/node/worker_threads-browser.js",
36
+ "./dist/worker-utils/lib/process-utils/child-process-proxy.js": "./dist/worker-utils/lib/process-utils/child-process-proxy.browser.js",
37
+ "./src/worker-utils/lib/node/worker_threads.ts": "./src/worker-utils/lib/node/worker_threads-browser.ts",
38
+ "./src/worker-utils/lib/process-utils/child-process-proxy.ts": "./src/worker-utils/lib/process-utils/child-process-proxy.browser.ts",
39
+ "child_process": false,
40
+ "fs": false,
41
+ "module": false,
42
+ "path": false
43
+ },
44
+ "gitHead": "c0b536175257abee1b30f687a3ca8cf5c8ca7bb9"
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ export * from './tasks/index';
@@ -0,0 +1,33 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Public task execution API. Worker transport is an internal implementation detail. */
6
+ export {TaskRunner} from './task-runner';
7
+ export {preloadTasks} from './task-preload';
8
+ export type {InitializedTask} from './task-runner';
9
+ export {initializeTaskWorker} from './task-runtime';
10
+ export type {
11
+ Task,
12
+ TaskTypes,
13
+ TaskContext,
14
+ TaskInitializationContext,
15
+ TaskProgress,
16
+ TaskWorker,
17
+ TaskRunControls,
18
+ TaskInitializeControls,
19
+ TaskInitializationControls,
20
+ TaskRunOptions,
21
+ TaskSyncRunOptions,
22
+ TaskPreloadOptions,
23
+ TaskBatchRunOptions,
24
+ TaskRunsOptions,
25
+ TaskRunnerOptions
26
+ } from './task';
27
+ export {createTypedTaskDispatcher} from './typed-task-dispatch';
28
+ export type {
29
+ TaskOperation,
30
+ TaskOperationRequest,
31
+ TaskOperationResult,
32
+ TypedTaskDispatcher
33
+ } from './typed-task-dispatch';
@@ -0,0 +1,191 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** A peer processor rejected its request without losing the transport. @internal */
6
+ export class TaskRequestError extends Error {}
7
+
8
+ /** Messages on a dedicated, multiplexed task transport. */
9
+ export type TaskChannelMessage = {
10
+ source: 'math.gl/tasks';
11
+ kind: 'request' | 'result' | 'error' | 'cancel' | 'event' | 'failure';
12
+ id: number;
13
+ operation?: string;
14
+ value?: unknown;
15
+ error?: {name: string; message: string};
16
+ };
17
+
18
+ /** Transport-independent services used by each endpoint of a task channel. */
19
+ export type TaskChannelOptions = {
20
+ send(message: TaskChannelMessage, transfer: Transferable[]): void;
21
+ handleRequest(operation: string, value: unknown, signal: AbortSignal): Promise<unknown>;
22
+ handleEvent?(operation: string, value: unknown): void;
23
+ getResultTransferList?(value: unknown, request: unknown): Transferable[];
24
+ onFailure?(reason: unknown): void;
25
+ };
26
+
27
+ /**
28
+ * Bidirectional request correlation and cancellation on one physical transport.
29
+ * Scheduling and state safety belong to the initialized task, not this channel.
30
+ * @internal
31
+ */
32
+ export class TaskChannel {
33
+ private nextId = 1;
34
+ private failure: {reason: unknown} | undefined;
35
+ private readonly pending = new Map<
36
+ number,
37
+ {
38
+ resolve(value: unknown): void;
39
+ reject(reason: unknown): void;
40
+ cleanup(): void;
41
+ }
42
+ >();
43
+ private readonly incoming = new Map<number, AbortController>();
44
+
45
+ constructor(private readonly options: TaskChannelOptions) {}
46
+
47
+ /** Send a request without serializing other in-flight requests. */
48
+ request(
49
+ operation: string,
50
+ value: unknown,
51
+ signal?: AbortSignal,
52
+ transfer: Transferable[] = []
53
+ ): Promise<unknown> {
54
+ if (this.failure) return Promise.reject(this.failure.reason);
55
+ if (signal?.aborted) return Promise.reject(signal.reason);
56
+ const id = this.nextId++;
57
+ return new Promise((resolve, reject) => {
58
+ const abort = () => {
59
+ const pending = this.pending.get(id);
60
+ if (!pending) return;
61
+ this.pending.delete(id);
62
+ pending.cleanup();
63
+ reject(signal?.reason);
64
+ this.send({source: 'math.gl/tasks', kind: 'cancel', id});
65
+ };
66
+ this.pending.set(id, {
67
+ resolve,
68
+ reject,
69
+ cleanup: () => signal?.removeEventListener('abort', abort)
70
+ });
71
+ signal?.addEventListener('abort', abort, {once: true});
72
+ this.send({source: 'math.gl/tasks', kind: 'request', id, operation, value}, transfer);
73
+ });
74
+ }
75
+
76
+ /** Send a one-way notification. */
77
+ emit(operation: string, value: unknown, transfer: Transferable[] = []): void {
78
+ if (this.failure) throw this.failure.reason;
79
+ this.send({source: 'math.gl/tasks', kind: 'event', id: 0, operation, value}, transfer);
80
+ }
81
+
82
+ /** Dispatch a transport message; unrelated protocols are ignored. */
83
+ receive(message: TaskChannelMessage): void {
84
+ if (this.failure || message?.source !== 'math.gl/tasks') return;
85
+ if (message.kind === 'failure') {
86
+ const reason = new Error(message.error?.message ?? 'Task channel failed');
87
+ this.close(reason);
88
+ this.options.onFailure?.(reason);
89
+ } else if (message.kind === 'result' || message.kind === 'error') {
90
+ const pending = this.pending.get(message.id);
91
+ if (!pending) return;
92
+ this.pending.delete(message.id);
93
+ pending.cleanup();
94
+ if (message.kind === 'result') pending.resolve(message.value);
95
+ else {
96
+ const error = new TaskRequestError(message.error?.message ?? 'Task request failed');
97
+ error.name = message.error?.name ?? 'Error';
98
+ pending.reject(error);
99
+ }
100
+ } else if (message.kind === 'cancel') {
101
+ this.incoming
102
+ .get(message.id)
103
+ ?.abort(new DOMException('Task request cancelled', 'AbortError'));
104
+ } else if (message.kind === 'event') {
105
+ try {
106
+ this.options.handleEvent?.(message.operation!, message.value);
107
+ } catch (error) {
108
+ this.fail(error);
109
+ }
110
+ } else if (message.kind === 'request') {
111
+ if (this.incoming.has(message.id)) {
112
+ this.fail(new Error('Duplicate task request identifier'));
113
+ return;
114
+ }
115
+ const controller = new AbortController();
116
+ this.incoming.set(message.id, controller);
117
+ void Promise.resolve()
118
+ .then(() => {
119
+ controller.signal.throwIfAborted();
120
+ return this.options.handleRequest(message.operation!, message.value, controller.signal);
121
+ })
122
+ .then(value => {
123
+ if (!controller.signal.aborted && !this.failure) {
124
+ this.send(
125
+ {source: 'math.gl/tasks', kind: 'result', id: message.id, value},
126
+ this.options.getResultTransferList?.(value, message.value)
127
+ );
128
+ }
129
+ })
130
+ .catch(reason => {
131
+ if (!controller.signal.aborted && !this.failure) {
132
+ this.send({
133
+ source: 'math.gl/tasks',
134
+ kind: 'error',
135
+ id: message.id,
136
+ error: {
137
+ name: reason instanceof Error ? reason.name : 'Error',
138
+ message: reason instanceof Error ? reason.message : String(reason)
139
+ }
140
+ });
141
+ }
142
+ })
143
+ .finally(() => this.incoming.delete(message.id));
144
+ }
145
+ }
146
+
147
+ /** Reject all outstanding calls with a common cause and abort incoming callbacks. */
148
+ close(reason: unknown = new Error('Task channel closed')): void {
149
+ if (this.failure) return;
150
+ this.failure = {reason};
151
+ for (const pending of this.pending.values()) {
152
+ pending.cleanup();
153
+ pending.reject(reason);
154
+ }
155
+ this.pending.clear();
156
+ for (const controller of this.incoming.values()) controller.abort(reason);
157
+ this.incoming.clear();
158
+ }
159
+
160
+ private send(message: TaskChannelMessage, transfer: Transferable[] = []): void {
161
+ if (this.failure) return;
162
+ try {
163
+ this.options.send(message, transfer);
164
+ } catch (error) {
165
+ this.fail(error);
166
+ }
167
+ }
168
+
169
+ /** Invalidate the channel and notify the peer when the transport still works. */
170
+ fail(reason: unknown): void {
171
+ if (this.failure) return;
172
+ this.close(reason);
173
+ try {
174
+ this.options.send(
175
+ {
176
+ source: 'math.gl/tasks',
177
+ kind: 'failure',
178
+ id: 0,
179
+ error: {
180
+ name: reason instanceof Error ? reason.name : 'Error',
181
+ message: reason instanceof Error ? reason.message : String(reason)
182
+ }
183
+ },
184
+ []
185
+ );
186
+ } catch {
187
+ // A dead physical transport must also report its error through onFailure.
188
+ }
189
+ this.options.onFailure?.(reason);
190
+ }
191
+ }
@@ -0,0 +1,109 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Scheduling mode for work sharing a single task instance. */
6
+ export type TaskOperationMode = 'parallel' | 'exclusive';
7
+
8
+ type Entry = {
9
+ mode: TaskOperationMode;
10
+ start: () => void;
11
+ cancel: (reason: unknown) => void;
12
+ };
13
+
14
+ /**
15
+ * FIFO operation scheduler. Exclusive entries form barriers; parallel entries
16
+ * overlap only up to the configured limit. This does not create worker threads.
17
+ * @internal
18
+ */
19
+ export class TaskOperationQueue {
20
+ private readonly pending: Entry[] = [];
21
+ private active = 0;
22
+ private exclusive = false;
23
+ private closed = false;
24
+ private readonly idleWaiters = new Set<() => void>();
25
+
26
+ constructor(private readonly maxConcurrency: number) {
27
+ if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency < 1) {
28
+ throw new RangeError('maxConcurrency must be a positive safe integer');
29
+ }
30
+ }
31
+
32
+ /** Queue an operation; aborting before it starts removes it without running it. */
33
+ run<T>(mode: TaskOperationMode, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
34
+ if (this.closed) return Promise.reject(new Error('Task operation queue is closed'));
35
+ if (mode !== 'parallel' && mode !== 'exclusive')
36
+ return Promise.reject(new TypeError('Invalid operation mode'));
37
+ if (signal?.aborted) return Promise.reject(signal.reason);
38
+ return new Promise<T>((resolve, reject) => {
39
+ const onAbort = () => {
40
+ const index = this.pending.indexOf(entry);
41
+ if (index >= 0) {
42
+ this.pending.splice(index, 1);
43
+ entry.cancel(signal?.reason);
44
+ this.pump();
45
+ }
46
+ };
47
+ const entry: Entry = {
48
+ mode,
49
+ cancel: reason => {
50
+ signal?.removeEventListener('abort', onAbort);
51
+ reject(reason);
52
+ },
53
+ start: () => {
54
+ signal?.removeEventListener('abort', onAbort);
55
+ this.active++;
56
+ if (mode === 'exclusive') this.exclusive = true;
57
+ void Promise.resolve()
58
+ .then(() => {
59
+ signal?.throwIfAborted();
60
+ return operation();
61
+ })
62
+ .then(resolve, reject)
63
+ .finally(() => {
64
+ this.active--;
65
+ if (mode === 'exclusive') this.exclusive = false;
66
+ this.pump();
67
+ });
68
+ }
69
+ };
70
+ this.pending.push(entry);
71
+ signal?.addEventListener('abort', onAbort, {once: true});
72
+ if (signal?.aborted) onAbort();
73
+ else this.pump();
74
+ });
75
+ }
76
+
77
+ /** Reject queued calls with one cause while allowing active operations to settle. */
78
+ cancelPending(reason: unknown): void {
79
+ this.closed = true;
80
+ for (const entry of this.pending.splice(0)) entry.cancel(reason);
81
+ this.pump();
82
+ }
83
+
84
+ /** Stop accepting new work; accepted operations continue to completion. */
85
+ close(): Promise<void> {
86
+ this.closed = true;
87
+ return this.whenIdle();
88
+ }
89
+
90
+ /** Wait until the queue has no running or waiting operations. */
91
+ whenIdle(): Promise<void> {
92
+ if (!this.active && !this.pending.length) return Promise.resolve();
93
+ return new Promise(resolve => this.idleWaiters.add(resolve));
94
+ }
95
+
96
+ private pump(): void {
97
+ while (!this.exclusive && this.pending.length && this.active < this.maxConcurrency) {
98
+ const entry = this.pending[0];
99
+ if (entry.mode === 'exclusive' && this.active) break;
100
+ this.pending.shift();
101
+ entry.start();
102
+ if (entry.mode === 'exclusive') break;
103
+ }
104
+ if (!this.active && !this.pending.length) {
105
+ for (const resolve of this.idleWaiters) resolve();
106
+ this.idleWaiters.clear();
107
+ }
108
+ }
109
+ }