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

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 +42 -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
package/dist/index.cjs ADDED
@@ -0,0 +1,3454 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // dist/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ TaskRunner: () => TaskRunner,
23
+ createTypedTaskDispatcher: () => createTypedTaskDispatcher,
24
+ initializeTaskWorker: () => initializeTaskWorker,
25
+ preloadTasks: () => preloadTasks
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // dist/worker-utils/lib/npm-tag.js
30
+ var NPM_TAG = "latest";
31
+
32
+ // dist/worker-utils/lib/env-utils/version.js
33
+ function getVersion() {
34
+ return typeof __VERSION__ === "undefined" ? NPM_TAG : __VERSION__;
35
+ }
36
+ var VERSION = getVersion();
37
+
38
+ // dist/worker-utils/lib/env-utils/assert.js
39
+ function assert(condition, message) {
40
+ if (!condition) {
41
+ throw new Error(message || "loaders.gl assertion failed.");
42
+ }
43
+ }
44
+
45
+ // dist/worker-utils/lib/env-utils/globals.js
46
+ var globals = {
47
+ self: typeof self !== "undefined" && self,
48
+ window: typeof window !== "undefined" && window,
49
+ global: typeof global !== "undefined" && global,
50
+ document: typeof document !== "undefined" && document
51
+ };
52
+ var self_ = globals.self || globals.window || globals.global || {};
53
+ var window_ = globals.window || globals.self || globals.global || {};
54
+ var global_ = globals.global || globals.self || globals.window || {};
55
+ var document_ = globals.document || {};
56
+ var isBrowser = (
57
+ // @ts-ignore process.browser
58
+ typeof process !== "object" || String(process) !== "[object process]" || process.browser
59
+ );
60
+ var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
61
+ var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
62
+ var nodeVersion = matches && parseFloat(matches[1]) || 0;
63
+
64
+ // dist/worker-utils/lib/worker-farm/worker-job.js
65
+ var WorkerJob = class {
66
+ constructor(jobName, workerThread) {
67
+ this.isRunning = true;
68
+ this.isCancelled = false;
69
+ this.failed = false;
70
+ this.postMessageMs = 0;
71
+ this.complete = () => {
72
+ };
73
+ this.processStarted = false;
74
+ this._resolve = () => {
75
+ };
76
+ this._reject = () => {
77
+ };
78
+ this.name = jobName;
79
+ this.workerThread = workerThread;
80
+ this.completion = new Promise((resolve) => {
81
+ this.complete = resolve;
82
+ });
83
+ this.result = new Promise((resolve, reject) => {
84
+ this._resolve = resolve;
85
+ this._reject = reject;
86
+ });
87
+ }
88
+ /**
89
+ * Send a message to the job's worker thread
90
+ * @param data any data structure, ideally consisting mostly of transferrable objects
91
+ */
92
+ postMessage(type, payload, transferList) {
93
+ if (!this.isRunning || this.isCancelled)
94
+ return;
95
+ const startedAt = performance.now();
96
+ if (type === "process" || type === "process-in-batches" || type === "preload")
97
+ this.processStarted = true;
98
+ try {
99
+ this.workerThread.postMessage({
100
+ source: "loaders.gl",
101
+ // Lets worker ignore unrelated messages
102
+ type,
103
+ payload
104
+ }, transferList);
105
+ } finally {
106
+ this.postMessageMs += performance.now() - startedAt;
107
+ }
108
+ }
109
+ /**
110
+ * Call to resolve the `result` Promise with the supplied value
111
+ */
112
+ done(value) {
113
+ if (!this.isRunning) {
114
+ return;
115
+ }
116
+ this.isRunning = false;
117
+ this.executionMs = value == null ? void 0 : value.executionMs;
118
+ clearTimeout(this.cancellationTimer);
119
+ this.complete();
120
+ if (!this.isCancelled)
121
+ this._resolve(value);
122
+ }
123
+ /**
124
+ * Call to reject the `result` Promise with the supplied error
125
+ */
126
+ error(error) {
127
+ var _a2;
128
+ if (!this.isRunning) {
129
+ return;
130
+ }
131
+ this.isRunning = false;
132
+ this.failed = true;
133
+ if ((_a2 = this.sharedState) == null ? void 0 : _a2.snapshot.cancelled)
134
+ this.isCancelled = true;
135
+ clearTimeout(this.cancellationTimer);
136
+ this.complete();
137
+ this._reject(error);
138
+ }
139
+ /** Reject immediately, but keep the lease until acknowledgement or hard-cancel timeout. */
140
+ cancel(reason, timeout = 1e3) {
141
+ var _a2;
142
+ if (!this.isRunning || this.isCancelled)
143
+ return;
144
+ if (!Number.isFinite(timeout) || timeout < 0) {
145
+ this.abort(new RangeError("cancellationTimeout must be finite and nonnegative"));
146
+ return;
147
+ }
148
+ this.isCancelled = true;
149
+ (_a2 = this.sharedState) == null ? void 0 : _a2.cancel();
150
+ const abortReason = arguments.length ? reason : createAbortError(`Worker job "${this.name}" was cancelled`);
151
+ if (!this.processStarted) {
152
+ this.error(abortReason);
153
+ return;
154
+ }
155
+ this._reject(abortReason);
156
+ try {
157
+ this.workerThread.postMessage({ source: "loaders.gl", type: "cancel", payload: {} }, []);
158
+ this.cancellationTimer = setTimeout(() => this.abort(reason), timeout);
159
+ } catch (error) {
160
+ this.abort(error);
161
+ }
162
+ }
163
+ /**
164
+ * Terminates the worker executing this job and rejects its result.
165
+ * @param reason Abort reason supplied by the caller, or a cross-runtime `AbortError`.
166
+ */
167
+ abort(reason) {
168
+ var _a2;
169
+ if (!this.isRunning) {
170
+ return;
171
+ }
172
+ this.isCancelled = true;
173
+ (_a2 = this.sharedState) == null ? void 0 : _a2.cancel();
174
+ this.workerThread.destroy();
175
+ this.error(arguments.length ? reason : createAbortError(`Worker job "${this.name}" was aborted`));
176
+ }
177
+ };
178
+ function createAbortError(message) {
179
+ const error = new Error(message);
180
+ error.name = "AbortError";
181
+ return error;
182
+ }
183
+
184
+ // dist/worker-utils/lib/node/worker_threads-browser.js
185
+ var NodeWorker = class {
186
+ /** Restores the native worker constructor when this browser shim is embedded in a Node bundle. */
187
+ constructor(...arguments_) {
188
+ var _a2;
189
+ const runtimeProcess = globalThis.process;
190
+ const WorkerConstructor = (_a2 = runtimeProcess == null ? void 0 : runtimeProcess.getBuiltinModule) == null ? void 0 : _a2.call(runtimeProcess, "node:worker_threads").Worker;
191
+ if (WorkerConstructor) {
192
+ return new WorkerConstructor(...arguments_);
193
+ }
194
+ }
195
+ /** No-op browser fallback matching the native Worker API. */
196
+ terminate() {
197
+ }
198
+ };
199
+ var _a, _b, _c;
200
+ var parentPort = ((_c = (_b = (_a = globalThis.process) == null ? void 0 : _a.getBuiltinModule) == null ? void 0 : _b.call(_a, "node:worker_threads")) == null ? void 0 : _c.parentPort) ?? null;
201
+
202
+ // dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js
203
+ var workerURLCache = /* @__PURE__ */ new Map();
204
+ function getLoadableWorkerURL(props) {
205
+ var _a2, _b2, _c2;
206
+ assert(props.source && !props.url || !props.source && props.url);
207
+ if (props.url && props.workerType === "module") {
208
+ const baseUrl = ((_a2 = globalThis.document) == null ? void 0 : _a2.baseURI) ?? ((_b2 = globalThis.location) == null ? void 0 : _b2.href);
209
+ if (!baseUrl)
210
+ return props.url;
211
+ const resolved = new URL(props.url, baseUrl);
212
+ const origin = (_c2 = globalThis.location) == null ? void 0 : _c2.origin;
213
+ if (/^https?:$/.test(resolved.protocol) && resolved.origin !== origin) {
214
+ return getLoadableWorkerURLFromSource(`import ${JSON.stringify(resolved.href)};`);
215
+ }
216
+ return props.url;
217
+ }
218
+ let workerURL = workerURLCache.get(props.source || props.url);
219
+ if (!workerURL) {
220
+ if (props.url) {
221
+ workerURL = getLoadableWorkerURLFromURL(props.url);
222
+ workerURLCache.set(props.url, workerURL);
223
+ }
224
+ if (props.source) {
225
+ workerURL = getLoadableWorkerURLFromSource(props.source);
226
+ workerURLCache.set(props.source, workerURL);
227
+ }
228
+ }
229
+ assert(workerURL);
230
+ return workerURL;
231
+ }
232
+ function getLoadableWorkerURLFromURL(url) {
233
+ if (!url.startsWith("http")) {
234
+ return url;
235
+ }
236
+ const workerSource = buildScriptSource(url);
237
+ return getLoadableWorkerURLFromSource(workerSource);
238
+ }
239
+ function getLoadableWorkerURLFromSource(workerSource) {
240
+ const blob = new Blob([workerSource], { type: "application/javascript" });
241
+ return URL.createObjectURL(blob);
242
+ }
243
+ function buildScriptSource(workerUrl) {
244
+ return `try {
245
+ importScripts('${workerUrl}');
246
+ } catch (error) {
247
+ console.error(error);
248
+ throw error;
249
+ }`;
250
+ }
251
+
252
+ // dist/worker-utils/lib/worker-utils/get-transfer-list.js
253
+ function getTransferList(object, recursive = true, transfers) {
254
+ const transfersSet = transfers || /* @__PURE__ */ new Set();
255
+ const seen = /* @__PURE__ */ new Set();
256
+ function visit(value) {
257
+ if (!value || typeof value !== "object" || seen.has(value))
258
+ return;
259
+ seen.add(value);
260
+ if (isTransferable(value))
261
+ transfersSet.add(value);
262
+ else if (ArrayBuffer.isView(value)) {
263
+ if (isTransferable(value.buffer))
264
+ transfersSet.add(value.buffer);
265
+ } else if (recursive && typeof MessageChannel !== "undefined" && value instanceof MessageChannel) {
266
+ visit(value.port1);
267
+ visit(value.port2);
268
+ } else if (recursive && value instanceof Map) {
269
+ for (const [key, item] of value) {
270
+ visit(key);
271
+ visit(item);
272
+ }
273
+ } else if (recursive && value instanceof Set) {
274
+ for (const item of value)
275
+ visit(item);
276
+ } else if (recursive) {
277
+ for (const key of Object.keys(value))
278
+ visit(value[key]);
279
+ }
280
+ }
281
+ visit(object);
282
+ return transfers === void 0 ? Array.from(transfersSet) : [];
283
+ }
284
+ function isTransferable(object) {
285
+ if (!object) {
286
+ return false;
287
+ }
288
+ if (object instanceof ArrayBuffer) {
289
+ return true;
290
+ }
291
+ if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
292
+ return true;
293
+ }
294
+ if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
295
+ return true;
296
+ }
297
+ if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
298
+ return true;
299
+ }
300
+ return false;
301
+ }
302
+ function getTransferListForWriter(object) {
303
+ const seen = /* @__PURE__ */ new Map();
304
+ function clone(value) {
305
+ if (typeof value === "function" || value instanceof RegExp)
306
+ return {};
307
+ if (!value || typeof value !== "object")
308
+ return value;
309
+ if (seen.has(value))
310
+ return seen.get(value);
311
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer || value instanceof Date || typeof WebAssembly !== "undefined" && value instanceof WebAssembly.Module || isTransferable(value))
312
+ return value;
313
+ const result = value instanceof Map ? /* @__PURE__ */ new Map() : value instanceof Set ? /* @__PURE__ */ new Set() : Array.isArray(value) ? [] : {};
314
+ seen.set(value, result);
315
+ if (value instanceof Map) {
316
+ for (const [key, item] of value)
317
+ result.set(clone(key), clone(item));
318
+ } else if (value instanceof Set) {
319
+ for (const item of value)
320
+ result.add(clone(item));
321
+ } else {
322
+ for (const key of Object.keys(value)) {
323
+ Object.defineProperty(result, key, {
324
+ value: clone(value[key]),
325
+ enumerable: true,
326
+ writable: true,
327
+ configurable: true
328
+ });
329
+ }
330
+ }
331
+ return result;
332
+ }
333
+ return object === null ? {} : clone(object);
334
+ }
335
+
336
+ // dist/worker-utils/lib/worker-farm/worker-thread.js
337
+ var NOOP = () => {
338
+ };
339
+ var WorkerThread = class {
340
+ /** Checks if workers are supported on this platform */
341
+ static isSupported() {
342
+ return typeof Worker !== "undefined" && isBrowser || typeof NodeWorker !== "undefined" && !isBrowser;
343
+ }
344
+ constructor(props) {
345
+ this.terminated = false;
346
+ this.createdAt = performance.now();
347
+ this._loadableURL = "";
348
+ const { name, source, url, getUrl, loadWorker } = props;
349
+ assert(source || url || getUrl || loadWorker);
350
+ this.name = name;
351
+ this.source = source;
352
+ this.url = url;
353
+ this.workerType = props.workerType ?? "classic";
354
+ this.getUrl = getUrl;
355
+ this.loadWorker = loadWorker;
356
+ this.onMessage = NOOP;
357
+ this.onError = (error) => console.log(error);
358
+ const startedAt = performance.now();
359
+ this.worker = isBrowser ? this._createBrowserWorker() : this._createNodeWorker();
360
+ this.creationTimeMs = performance.now() - startedAt;
361
+ }
362
+ /**
363
+ * Terminate this worker thread
364
+ * @note Can free up significant memory
365
+ */
366
+ destroy() {
367
+ this.onMessage = NOOP;
368
+ this.onError = NOOP;
369
+ if (this.terminated)
370
+ return this.termination ?? Promise.resolve();
371
+ this.terminated = true;
372
+ this.termination = Promise.resolve(this.worker.terminate()).then(() => void 0).finally(() => this.releaseModuleWorkerURL());
373
+ void this.termination.catch(() => void 0);
374
+ return this.termination;
375
+ }
376
+ /** Keeps this worker from preventing Node.js process exit while idle. */
377
+ unref() {
378
+ if (!isBrowser && typeof this.worker.unref === "function") {
379
+ this.worker.unref();
380
+ }
381
+ }
382
+ /** Keeps this worker alive while it is actively processing a job. */
383
+ ref() {
384
+ if (!isBrowser && typeof this.worker.ref === "function") {
385
+ this.worker.ref();
386
+ }
387
+ }
388
+ get isRunning() {
389
+ return Boolean(this.onMessage);
390
+ }
391
+ /**
392
+ * Send a message to this worker thread
393
+ * @param data any data structure, ideally consisting mostly of transferrable objects
394
+ * @param transferList If not supplied, calculated automatically by traversing data
395
+ */
396
+ postMessage(data, transferList) {
397
+ transferList = transferList || getTransferList(data);
398
+ this.worker.postMessage(data, transferList);
399
+ }
400
+ // PRIVATE
401
+ /**
402
+ * Generate a standard Error from an ErrorEvent
403
+ * @param event
404
+ */
405
+ _getErrorFromErrorEvent(event) {
406
+ let message = "Failed to load ";
407
+ message += `worker ${this.name} from ${this.url || "built-in worker factory"}. `;
408
+ if (event.message) {
409
+ message += `${event.message} in `;
410
+ }
411
+ if (event.lineno) {
412
+ message += `:${event.lineno}:${event.colno}`;
413
+ }
414
+ return new Error(message);
415
+ }
416
+ /**
417
+ * Creates a worker thread on the browser
418
+ */
419
+ _createBrowserWorker() {
420
+ var _a2;
421
+ if (this.loadWorker) {
422
+ try {
423
+ const worker = this.loadWorker();
424
+ if (worker) {
425
+ return this._initializeBrowserWorker(worker);
426
+ }
427
+ } catch (error) {
428
+ if (!this.source && !this.url && !this.getUrl) {
429
+ throw error;
430
+ }
431
+ }
432
+ }
433
+ const url = this.url || ((_a2 = this.getUrl) == null ? void 0 : _a2.call(this));
434
+ this._loadableURL = getLoadableWorkerURL({
435
+ source: this.source,
436
+ url,
437
+ workerType: this.workerType
438
+ });
439
+ if (this.workerType === "module" && url && this._loadableURL !== url && this._loadableURL.startsWith("blob:"))
440
+ this.ownedModuleWorkerURL = this._loadableURL;
441
+ try {
442
+ const worker = new Worker(this._loadableURL, { name: this.name, type: this.workerType });
443
+ return this._initializeBrowserWorker(worker);
444
+ } catch (error) {
445
+ this.releaseModuleWorkerURL();
446
+ throw error;
447
+ }
448
+ }
449
+ /** Releases only the module shim owned by this worker, never caller-owned blob URLs. */
450
+ releaseModuleWorkerURL() {
451
+ if (this.ownedModuleWorkerURL) {
452
+ URL.revokeObjectURL(this.ownedModuleWorkerURL);
453
+ this.ownedModuleWorkerURL = void 0;
454
+ }
455
+ }
456
+ /** Attaches protocol handlers to a browser worker. */
457
+ _initializeBrowserWorker(worker) {
458
+ worker.onmessage = (event) => {
459
+ if (!event.data) {
460
+ this.onError(new Error("No data received"));
461
+ } else if (event.data.type === "ready") {
462
+ this.startupTimeMs = performance.now() - this.createdAt;
463
+ } else {
464
+ this.onMessage(event.data);
465
+ }
466
+ };
467
+ worker.onerror = (error) => {
468
+ const onError = this.onError;
469
+ const reason = this._getErrorFromErrorEvent(error);
470
+ this.destroy();
471
+ onError(reason);
472
+ };
473
+ worker.onmessageerror = () => {
474
+ const onError = this.onError;
475
+ this.destroy();
476
+ onError(new Error("Worker message could not be deserialized"));
477
+ };
478
+ return worker;
479
+ }
480
+ /**
481
+ * Creates a worker thread in node.js
482
+ * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool
483
+ */
484
+ _createNodeWorker() {
485
+ let worker;
486
+ if (this.url) {
487
+ const absolute = this.url.includes(":/") || this.url.startsWith("/");
488
+ const url = absolute ? this.url : `./${this.url}`;
489
+ const workerUrl = url.startsWith("file:") ? new URL(url) : url;
490
+ const type = this.url.endsWith(".ts") || this.url.endsWith(".mjs") ? "module" : "commonjs";
491
+ worker = new NodeWorker(workerUrl, { eval: false, type });
492
+ } else if (this.source) {
493
+ worker = new NodeWorker(this.source, { eval: true });
494
+ } else {
495
+ throw new Error("no worker");
496
+ }
497
+ worker.on("message", (data) => {
498
+ if ((data == null ? void 0 : data.type) === "ready")
499
+ this.startupTimeMs = performance.now() - this.createdAt;
500
+ else
501
+ this.onMessage(data);
502
+ });
503
+ worker.on("error", (error) => {
504
+ this.terminated = true;
505
+ this.onError(error);
506
+ });
507
+ this.termination = new Promise((resolve) => worker.on("exit", () => resolve()));
508
+ worker.on("exit", (code) => {
509
+ if (!this.terminated) {
510
+ this.terminated = true;
511
+ this.onError(new Error(`Worker ${this.name} exited unexpectedly (code ${code})`));
512
+ }
513
+ });
514
+ return worker;
515
+ }
516
+ };
517
+
518
+ // dist/worker-utils/lib/worker-farm/worker-pool.js
519
+ var WorkerPool = class {
520
+ /** Snapshot; byte figures describe input buffers, not total heap memory. */
521
+ get stats() {
522
+ return {
523
+ ...this.totals,
524
+ queuedJobs: this.jobQueue.length,
525
+ activeJobs: this.activeJobs.size,
526
+ queuedBytes: this.queuedBytes + this.reservedBytes,
527
+ inFlightBytes: this.inFlightBytes,
528
+ pendingAdmissions: this.admissions.length,
529
+ reservations: this.reservations.size
530
+ };
531
+ }
532
+ /** Wait for an atomic queue reservation before allocating input. Waiting metadata is bounded. */
533
+ reserve(inputBytes, options = {}) {
534
+ const { signal } = options;
535
+ if (signal == null ? void 0 : signal.aborted)
536
+ return Promise.reject(signal.reason);
537
+ if (this.isDestroyed)
538
+ return Promise.reject(new Error("Worker pool was destroyed"));
539
+ if (this.isClosing)
540
+ return Promise.reject(new Error("Worker pool is closing"));
541
+ if (!Number.isSafeInteger(inputBytes) || inputBytes < 0 || inputBytes > this.maxQueuedBytes || inputBytes > this.maxInFlightBytes) {
542
+ return Promise.reject(new RangeError("Reservation exceeds worker byte budgets"));
543
+ }
544
+ if (this.maxQueuedJobs < 1 || this.admissions.length >= this.maxPendingAdmissions) {
545
+ return Promise.reject(new RangeError("Worker admission queue is full"));
546
+ }
547
+ return new Promise((resolve, reject) => {
548
+ const abort = () => {
549
+ const index = this.admissions.indexOf(waiter);
550
+ if (index >= 0)
551
+ this.admissions.splice(index, 1);
552
+ waiter.cleanup();
553
+ reject(signal == null ? void 0 : signal.reason);
554
+ this._admit();
555
+ };
556
+ const waiter = {
557
+ inputBytes,
558
+ resolve,
559
+ reject,
560
+ cleanup: () => signal == null ? void 0 : signal.removeEventListener("abort", abort)
561
+ };
562
+ this.admissions.push(waiter);
563
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
564
+ this._admit();
565
+ });
566
+ }
567
+ _admit() {
568
+ while (!this.isDestroyed && !this.isClosing && this.admissions.length) {
569
+ const waiter = this.admissions[0];
570
+ if (waiter.inputBytes > this.maxQueuedBytes || waiter.inputBytes > this.maxInFlightBytes) {
571
+ this.admissions.shift();
572
+ waiter.cleanup();
573
+ waiter.reject(new RangeError("Reservation exceeds worker byte budgets"));
574
+ continue;
575
+ }
576
+ if (this.jobQueue.length + this.reservations.size >= this.maxQueuedJobs || waiter.inputBytes > this.maxQueuedBytes - this.queuedBytes - this.reservedBytes)
577
+ return;
578
+ this.admissions.shift();
579
+ waiter.cleanup();
580
+ const admission = {
581
+ inputBytes: waiter.inputBytes,
582
+ release: () => {
583
+ if (this.reservations.delete(admission)) {
584
+ this.reservedBytes -= admission.inputBytes;
585
+ this._admit();
586
+ }
587
+ }
588
+ };
589
+ this.reservations.add(admission);
590
+ this.reservedBytes += admission.inputBytes;
591
+ this.totals.peakQueuedBytes = Math.max(this.totals.peakQueuedBytes, this.queuedBytes + this.reservedBytes);
592
+ waiter.resolve(admission);
593
+ }
594
+ }
595
+ /** Checks if workers are supported on this platform */
596
+ static isSupported() {
597
+ return WorkerThread.isSupported();
598
+ }
599
+ /**
600
+ * @param processor - worker function
601
+ * @param maxConcurrency - max count of workers
602
+ */
603
+ constructor(props) {
604
+ this.name = "unnamed";
605
+ this.maxConcurrency = 1;
606
+ this.maxMobileConcurrency = 1;
607
+ this.onDebug = () => {
608
+ };
609
+ this.reuseWorkers = true;
610
+ this.props = {};
611
+ this.jobQueue = [];
612
+ this.idleQueue = [];
613
+ this.activeJobs = /* @__PURE__ */ new Set();
614
+ this.startingJobs = 0;
615
+ this.count = 0;
616
+ this.workers = /* @__PURE__ */ new Set();
617
+ this.queuedBytes = 0;
618
+ this.inFlightBytes = 0;
619
+ this.maxQueuedBytes = Infinity;
620
+ this.maxInFlightBytes = Infinity;
621
+ this.isDestroyed = false;
622
+ this.isClosing = false;
623
+ this.maxQueuedJobs = Infinity;
624
+ this.maxPendingAdmissions = 128;
625
+ this.priorityAgingMs = 1e3;
626
+ this.reservations = /* @__PURE__ */ new Set();
627
+ this.admissions = [];
628
+ this.reservedBytes = 0;
629
+ this.totals = {
630
+ peakQueuedBytes: 0,
631
+ peakInFlightBytes: 0,
632
+ workersCreated: 0,
633
+ workerRestarts: 0,
634
+ completed: 0,
635
+ failed: 0,
636
+ cancelled: 0
637
+ };
638
+ this.source = props.source;
639
+ this.url = props.url;
640
+ this.workerType = props.workerType;
641
+ this.getUrl = props.getUrl;
642
+ this.loadWorker = props.loadWorker;
643
+ this.setProps(props);
644
+ }
645
+ /** Reject new work, drain submitted jobs, and terminate workers; optionally force termination after a deadline. */
646
+ close(options = {}) {
647
+ if (this.closing)
648
+ return this.closing;
649
+ if (this.isDestroyed)
650
+ return this.destroy();
651
+ if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout < 0 || options.timeout > 2147483647)) {
652
+ return Promise.reject(new RangeError("Close timeout must be between 0 and 2147483647 ms"));
653
+ }
654
+ this.isClosing = true;
655
+ const reason = new Error("Worker pool is closing");
656
+ this.admissions.splice(0).forEach((waiter) => {
657
+ waiter.cleanup();
658
+ waiter.reject(reason);
659
+ });
660
+ this.reservations.clear();
661
+ this.reservedBytes = 0;
662
+ let timer;
663
+ const drained = new Promise((resolve) => {
664
+ this.onDrained = resolve;
665
+ });
666
+ const deadline = options.timeout === void 0 ? drained : Promise.race([
667
+ drained,
668
+ new Promise((resolve) => {
669
+ timer = setTimeout(resolve, options.timeout);
670
+ })
671
+ ]);
672
+ this.closing = deadline.then(async () => {
673
+ clearTimeout(timer);
674
+ await this.destroy();
675
+ });
676
+ this._checkDrained();
677
+ return this.closing;
678
+ }
679
+ _checkDrained() {
680
+ var _a2;
681
+ if (this.isClosing && !this.jobQueue.length && !this.activeJobs.size && !this.startingJobs)
682
+ (_a2 = this.onDrained) == null ? void 0 : _a2.call(this);
683
+ }
684
+ /**
685
+ * Terminates all workers in the pool and aborts active jobs.
686
+ * @param reason Optional error delivered to active jobs.
687
+ * @note Can free up significant memory
688
+ */
689
+ destroy(reason = new Error("Worker pool was destroyed")) {
690
+ var _a2;
691
+ if (this.destruction)
692
+ return this.destruction;
693
+ const workers = [...this.workers];
694
+ this.isDestroyed = true;
695
+ (_a2 = this.onDrained) == null ? void 0 : _a2.call(this);
696
+ this.activeJobs.forEach((job) => job.abort(reason));
697
+ this.admissions.splice(0).forEach((waiter) => {
698
+ waiter.cleanup();
699
+ waiter.reject(reason);
700
+ });
701
+ this.reservations.clear();
702
+ this.reservedBytes = 0;
703
+ const queuedJobs = this.jobQueue.splice(0);
704
+ this.queuedBytes = 0;
705
+ queuedJobs.forEach((queuedJob) => {
706
+ queuedJob.removeAbortListener();
707
+ queuedJob.onReject(reason);
708
+ });
709
+ this.idleQueue.splice(0).forEach((worker) => {
710
+ worker.destroy();
711
+ this.count--;
712
+ });
713
+ this.isDestroyed = true;
714
+ this.destruction = Promise.all(workers.map((worker) => worker.destroy())).then(() => {
715
+ this.workers.clear();
716
+ });
717
+ void this.destruction.catch(() => void 0);
718
+ return this.destruction;
719
+ }
720
+ setProps(props) {
721
+ for (const key of [
722
+ "maxQueuedBytes",
723
+ "maxInFlightBytes",
724
+ "maxQueuedJobs",
725
+ "maxPendingAdmissions"
726
+ ]) {
727
+ const value = props[key];
728
+ if (value !== void 0 && (!(value >= 0) || value !== Infinity && !Number.isSafeInteger(value))) {
729
+ throw new RangeError(`${key} must be a nonnegative safe integer or Infinity`);
730
+ }
731
+ }
732
+ if (props.priorityAgingMs !== void 0 && (!Number.isFinite(props.priorityAgingMs) || props.priorityAgingMs <= 0)) {
733
+ throw new RangeError("priorityAgingMs must be positive and finite");
734
+ }
735
+ this.maxQueuedJobs = props.maxQueuedJobs ?? this.maxQueuedJobs;
736
+ this.maxPendingAdmissions = props.maxPendingAdmissions ?? this.maxPendingAdmissions;
737
+ this.priorityAgingMs = props.priorityAgingMs ?? this.priorityAgingMs;
738
+ this.maxQueuedBytes = props.maxQueuedBytes ?? this.maxQueuedBytes;
739
+ this.maxInFlightBytes = props.maxInFlightBytes ?? this.maxInFlightBytes;
740
+ this.props = { ...this.props, ...props };
741
+ if (props.name !== void 0) {
742
+ this.name = props.name;
743
+ }
744
+ if (props.maxConcurrency !== void 0) {
745
+ this.maxConcurrency = props.maxConcurrency;
746
+ }
747
+ if (props.maxMobileConcurrency !== void 0) {
748
+ this.maxMobileConcurrency = props.maxMobileConcurrency;
749
+ }
750
+ if (props.reuseWorkers !== void 0) {
751
+ this.reuseWorkers = props.reuseWorkers;
752
+ }
753
+ if (props.onDebug !== void 0) {
754
+ this.onDebug = props.onDebug;
755
+ }
756
+ for (const queuedJob of [...this.jobQueue]) {
757
+ if (queuedJob.inputBytes > this.maxInFlightBytes) {
758
+ this.jobQueue.splice(this.jobQueue.indexOf(queuedJob), 1);
759
+ this.queuedBytes -= queuedJob.inputBytes;
760
+ queuedJob.removeAbortListener();
761
+ queuedJob.onReject(new RangeError("Worker job exceeds maxInFlightBytes"));
762
+ }
763
+ }
764
+ this._admit();
765
+ void this._startQueuedJob();
766
+ this._checkDrained();
767
+ }
768
+ /** Whether batch callers must declare a retained-input reservation. */
769
+ get requiresInputBytes() {
770
+ return this.maxQueuedBytes !== Infinity || this.maxInFlightBytes !== Infinity;
771
+ }
772
+ async startJob(name, onMessage2 = (job, type, data) => job.done(data), onError = (job, error) => job.error(error), signal, scheduling = {}) {
773
+ if (scheduling.cancellationMode !== void 0 && !["terminate", "cooperative"].includes(scheduling.cancellationMode)) {
774
+ throw new Error("Invalid worker cancellation mode");
775
+ }
776
+ if (scheduling.cancellationTimeout !== void 0 && (!Number.isFinite(scheduling.cancellationTimeout) || scheduling.cancellationTimeout < 0)) {
777
+ throw new RangeError("cancellationTimeout must be finite and nonnegative");
778
+ }
779
+ if (signal == null ? void 0 : signal.aborted) {
780
+ throw signal.reason;
781
+ }
782
+ if (this.isDestroyed) {
783
+ return Promise.reject(new Error("Worker pool was destroyed"));
784
+ }
785
+ if (this.isClosing)
786
+ return Promise.reject(new Error("Worker pool is closing"));
787
+ const { inputBytes = 0, priority = 0 } = scheduling;
788
+ if (!Number.isSafeInteger(inputBytes) || inputBytes < 0 || !Number.isFinite(priority)) {
789
+ throw new RangeError("Invalid worker scheduling inputBytes or priority");
790
+ }
791
+ if (inputBytes > this.maxInFlightBytes) {
792
+ throw new RangeError("Worker job exceeds maxInFlightBytes");
793
+ }
794
+ const admission = scheduling.admission;
795
+ if (admission && (!this.reservations.has(admission) || admission.inputBytes !== inputBytes)) {
796
+ throw new Error("Invalid or consumed worker admission");
797
+ }
798
+ const canStart = !this.jobQueue.length && this.activeJobs.size < this._getMaxConcurrency() && this.inFlightBytes + inputBytes <= this.maxInFlightBytes;
799
+ if (!admission && !canStart && (this.jobQueue.length + this.reservations.size >= this.maxQueuedJobs || inputBytes > this.maxQueuedBytes - this.queuedBytes - this.reservedBytes)) {
800
+ throw new RangeError("Worker queue exceeds maxQueuedBytes or maxQueuedJobs");
801
+ }
802
+ if (admission) {
803
+ this.reservations.delete(admission);
804
+ this.reservedBytes -= admission.inputBytes;
805
+ }
806
+ const startPromise = new Promise((onStart, onReject) => {
807
+ const abortQueuedJob = () => {
808
+ const index2 = this.jobQueue.indexOf(queuedJob);
809
+ if (index2 >= 0) {
810
+ this.jobQueue.splice(index2, 1);
811
+ this.queuedBytes -= queuedJob.inputBytes;
812
+ this._admit();
813
+ void this._startQueuedJob();
814
+ queuedJob.removeAbortListener();
815
+ onReject(signal == null ? void 0 : signal.reason);
816
+ this._checkDrained();
817
+ }
818
+ };
819
+ const queuedJob = {
820
+ name,
821
+ inputBytes,
822
+ priority,
823
+ queuedAt: performance.now(),
824
+ sharedState: scheduling.sharedState,
825
+ cancellationMode: scheduling.cancellationMode,
826
+ cancellationTimeout: scheduling.cancellationTimeout,
827
+ onMessage: onMessage2,
828
+ onError,
829
+ onStart,
830
+ onReject,
831
+ signal,
832
+ removeAbortListener: () => signal == null ? void 0 : signal.removeEventListener("abort", abortQueuedJob)
833
+ };
834
+ const index = this.jobQueue.findIndex((job) => job.priority < priority);
835
+ this.jobQueue.splice(index < 0 ? this.jobQueue.length : index, 0, queuedJob);
836
+ this.queuedBytes += inputBytes;
837
+ if (!canStart)
838
+ this.totals.peakQueuedBytes = Math.max(this.totals.peakQueuedBytes, this.queuedBytes + this.reservedBytes);
839
+ signal == null ? void 0 : signal.addEventListener("abort", abortQueuedJob, { once: true });
840
+ return this;
841
+ });
842
+ this._startQueuedJob();
843
+ return await startPromise;
844
+ }
845
+ // PRIVATE
846
+ /**
847
+ * Starts first queued job if worker is available or can be created
848
+ * Called when job is started and whenever a worker returns to the idleQueue
849
+ */
850
+ async _startQueuedJob() {
851
+ var _a2, _b2, _c2, _d, _e;
852
+ if (!this.jobQueue.length) {
853
+ return;
854
+ }
855
+ const now = performance.now();
856
+ this.jobQueue.sort((a, b) => b.priority + Math.floor((now - b.queuedAt) / this.priorityAgingMs) - (a.priority + Math.floor((now - a.queuedAt) / this.priorityAgingMs)));
857
+ if (this.jobQueue[0].inputBytes > this.maxInFlightBytes - this.inFlightBytes)
858
+ return;
859
+ let workerThread;
860
+ try {
861
+ workerThread = this._getAvailableWorker();
862
+ } catch (error) {
863
+ const queuedJob2 = this.jobQueue.shift();
864
+ if (queuedJob2)
865
+ this.queuedBytes -= queuedJob2.inputBytes;
866
+ this._admit();
867
+ queuedJob2 == null ? void 0 : queuedJob2.removeAbortListener();
868
+ queuedJob2 == null ? void 0 : queuedJob2.onReject(error);
869
+ void this._startQueuedJob();
870
+ this._checkDrained();
871
+ return;
872
+ }
873
+ if (!workerThread) {
874
+ return;
875
+ }
876
+ const queuedJob = this.jobQueue.shift();
877
+ if (queuedJob) {
878
+ this.startingJobs++;
879
+ this.queuedBytes -= queuedJob.inputBytes;
880
+ this.inFlightBytes += queuedJob.inputBytes;
881
+ this.totals.peakInFlightBytes = Math.max(this.totals.peakInFlightBytes, this.inFlightBytes);
882
+ this._admit();
883
+ const startedAt = performance.now();
884
+ try {
885
+ this.onDebug({
886
+ message: "Starting job",
887
+ name: queuedJob.name,
888
+ workerThread,
889
+ backlog: this.jobQueue.length
890
+ });
891
+ } catch {
892
+ }
893
+ if (this.isDestroyed || workerThread.terminated) {
894
+ this.startingJobs--;
895
+ this.inFlightBytes -= queuedJob.inputBytes;
896
+ queuedJob.removeAbortListener();
897
+ queuedJob.onReject(new Error("Worker pool was destroyed before job start"));
898
+ this.returnWorkerToQueue(workerThread);
899
+ return;
900
+ }
901
+ const job = new WorkerJob(queuedJob.name, workerThread);
902
+ job.sharedState = queuedJob.sharedState;
903
+ queuedJob.removeAbortListener();
904
+ const abortJob = () => {
905
+ var _a3, _b3;
906
+ if (queuedJob.cancellationMode === "cooperative") {
907
+ job.cancel((_a3 = queuedJob.signal) == null ? void 0 : _a3.reason, queuedJob.cancellationTimeout);
908
+ } else
909
+ job.abort((_b3 = queuedJob.signal) == null ? void 0 : _b3.reason);
910
+ };
911
+ (_a2 = queuedJob.signal) == null ? void 0 : _a2.addEventListener("abort", abortJob, { once: true });
912
+ if ((_b2 = queuedJob.signal) == null ? void 0 : _b2.aborted)
913
+ abortJob();
914
+ this.activeJobs.add(job);
915
+ this.startingJobs--;
916
+ workerThread.ref();
917
+ workerThread.onMessage = (data) => {
918
+ try {
919
+ if (job.isRunning)
920
+ queuedJob.onMessage(job, data.type, data.payload);
921
+ } catch (error) {
922
+ job.abort(error);
923
+ }
924
+ };
925
+ workerThread.onError = (error) => {
926
+ try {
927
+ queuedJob.onError(job, error);
928
+ } catch (callbackError) {
929
+ job.abort(callbackError);
930
+ }
931
+ };
932
+ void job.result.catch(() => void 0);
933
+ queuedJob.onStart(job);
934
+ void this._startQueuedJob();
935
+ try {
936
+ await job.completion;
937
+ } catch {
938
+ } finally {
939
+ (_c2 = queuedJob.signal) == null ? void 0 : _c2.removeEventListener("abort", abortJob);
940
+ this.activeJobs.delete(job);
941
+ this.inFlightBytes -= queuedJob.inputBytes;
942
+ const outcome = job.isCancelled ? "cancelled" : job.failed ? "failed" : "completed";
943
+ this.totals[outcome]++;
944
+ const metrics = {
945
+ name: job.name,
946
+ outcome,
947
+ queueWaitMs: startedAt - queuedJob.queuedAt,
948
+ durationMs: performance.now() - startedAt,
949
+ workerCreationMs: workerThread.creationTimeMs,
950
+ workerStartupMs: workerThread.startupTimeMs,
951
+ postMessageMs: job.postMessageMs,
952
+ executionMs: job.executionMs,
953
+ inputBytes: queuedJob.inputBytes
954
+ };
955
+ try {
956
+ (_e = (_d = this.props).onMetrics) == null ? void 0 : _e.call(_d, metrics);
957
+ if (this.props.performanceMarks && typeof performance.measure === "function") {
958
+ performance.measure(`math.gl.worker:${job.name}`, {
959
+ start: queuedJob.queuedAt,
960
+ end: performance.now(),
961
+ detail: metrics
962
+ });
963
+ }
964
+ } catch {
965
+ }
966
+ this._admit();
967
+ this.returnWorkerToQueue(workerThread);
968
+ }
969
+ } else {
970
+ this.returnWorkerToQueue(workerThread);
971
+ }
972
+ }
973
+ /**
974
+ * Returns a worker to the idle queue
975
+ * Destroys the worker if
976
+ * - pool is destroyed
977
+ * - if this pool doesn't reuse workers
978
+ * - if maxConcurrency has been lowered
979
+ * @param worker
980
+ */
981
+ returnWorkerToQueue(worker) {
982
+ const shouldDestroyWorker = (
983
+ // Aborted jobs terminate their worker immediately.
984
+ worker.terminated || // If the pool is destroyed, there is no reason to keep the worker around
985
+ this.isDestroyed || // If the app has disabled worker reuse, any completed workers should be destroyed
986
+ !this.reuseWorkers || // If concurrency has been lowered, this worker might be surplus to requirements
987
+ this.count > this._getMaxConcurrency()
988
+ );
989
+ if (shouldDestroyWorker) {
990
+ if (worker.terminated && !this.isDestroyed)
991
+ this.totals.workerRestarts++;
992
+ if (!worker.terminated) {
993
+ worker.destroy();
994
+ }
995
+ void worker.destroy().then(() => this.workers.delete(worker));
996
+ this.count--;
997
+ } else {
998
+ worker.unref();
999
+ this.idleQueue.push(worker);
1000
+ }
1001
+ if (!this.isDestroyed) {
1002
+ this._startQueuedJob();
1003
+ }
1004
+ this._checkDrained();
1005
+ }
1006
+ /**
1007
+ * Returns idle worker or creates new worker if maxConcurrency has not been reached
1008
+ */
1009
+ _getAvailableWorker() {
1010
+ while (this.idleQueue.length > 0) {
1011
+ const worker = this.idleQueue.shift();
1012
+ if (worker && (worker.terminated || this.count > this._getMaxConcurrency())) {
1013
+ if (worker.terminated)
1014
+ this.totals.workerRestarts++;
1015
+ void worker.destroy().then(() => this.workers.delete(worker));
1016
+ this.count--;
1017
+ } else if (worker) {
1018
+ return worker;
1019
+ }
1020
+ }
1021
+ if (this.count < this._getMaxConcurrency()) {
1022
+ this.count++;
1023
+ const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;
1024
+ try {
1025
+ const worker = new WorkerThread({
1026
+ name,
1027
+ source: this.source,
1028
+ url: this.url,
1029
+ workerType: this.workerType,
1030
+ getUrl: this.getUrl,
1031
+ loadWorker: this.loadWorker
1032
+ });
1033
+ this.totals.workersCreated++;
1034
+ this.workers.add(worker);
1035
+ return worker;
1036
+ } catch (error) {
1037
+ this.count--;
1038
+ throw error;
1039
+ }
1040
+ }
1041
+ return null;
1042
+ }
1043
+ _getMaxConcurrency() {
1044
+ return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
1045
+ }
1046
+ };
1047
+
1048
+ // dist/worker-utils/lib/worker-farm/worker-farm.js
1049
+ var DEFAULT_PROPS = {
1050
+ maxQueuedJobs: Infinity,
1051
+ maxPendingAdmissions: 128,
1052
+ priorityAgingMs: 1e3,
1053
+ onMetrics: () => {
1054
+ },
1055
+ performanceMarks: false,
1056
+ maxQueuedBytes: Infinity,
1057
+ maxInFlightBytes: Infinity,
1058
+ maxConcurrency: 3,
1059
+ maxMobileConcurrency: 1,
1060
+ reuseWorkers: true,
1061
+ onDebug: () => {
1062
+ }
1063
+ };
1064
+ var loadWorkerIds = /* @__PURE__ */ new WeakMap();
1065
+ var nextLoadWorkerId = 1;
1066
+ var WorkerFarm = class _WorkerFarm {
1067
+ /** Checks if workers are supported on this platform */
1068
+ static isSupported() {
1069
+ return WorkerThread.isSupported();
1070
+ }
1071
+ /** Get the singleton instance of the global worker farm */
1072
+ static getWorkerFarm(props = {}) {
1073
+ _WorkerFarm._workerFarm = _WorkerFarm._workerFarm || new _WorkerFarm({});
1074
+ _WorkerFarm._workerFarm.setProps(props);
1075
+ return _WorkerFarm._workerFarm;
1076
+ }
1077
+ /** get global instance with WorkerFarm.getWorkerFarm() */
1078
+ constructor(props) {
1079
+ this.workerPools = /* @__PURE__ */ new Map();
1080
+ this.props = { ...DEFAULT_PROPS };
1081
+ this.setProps(props);
1082
+ this.workerPools = /* @__PURE__ */ new Map();
1083
+ }
1084
+ /**
1085
+ * Terminate all workers in the farm and abort active jobs.
1086
+ * @param reason Optional error delivered to active jobs.
1087
+ * @note Can free up significant memory
1088
+ */
1089
+ destroy(reason) {
1090
+ const pools = [...this.workerPools.values()];
1091
+ this.workerPools.clear();
1092
+ return Promise.all(pools.map((pool) => pool.destroy(reason))).then(() => void 0);
1093
+ }
1094
+ /**
1095
+ * Set props used when initializing worker pools
1096
+ * @param props
1097
+ */
1098
+ setProps(props) {
1099
+ const configuration = {};
1100
+ for (const key of Object.keys(DEFAULT_PROPS)) {
1101
+ if (props[key] !== void 0)
1102
+ configuration[key] = props[key];
1103
+ }
1104
+ this.props = { ...this.props, ...configuration };
1105
+ for (const workerPool of this.workerPools.values()) {
1106
+ workerPool.setProps(this._getWorkerPoolProps());
1107
+ }
1108
+ }
1109
+ /**
1110
+ * Returns a worker pool for the specified worker
1111
+ * @param options Worker target used to identify and initialize the pool.
1112
+ * @param options.name Worker name used as the base pool identity.
1113
+ * @param options.url Worker script URL.
1114
+ * @param options.source Inline worker source.
1115
+ * @param options.loadWorker Built-in browser worker factory.
1116
+ * @example
1117
+ * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);
1118
+ */
1119
+ getWorkerPool(options) {
1120
+ const { name, source, url, getUrl, loadWorker, workerType } = options;
1121
+ const workerPoolKey = getWorkerPoolKey(options);
1122
+ let workerPool = this.workerPools.get(workerPoolKey);
1123
+ if (!workerPool) {
1124
+ workerPool = new WorkerPool({
1125
+ name,
1126
+ source,
1127
+ url,
1128
+ getUrl,
1129
+ loadWorker,
1130
+ workerType
1131
+ });
1132
+ workerPool.setProps(this._getWorkerPoolProps());
1133
+ this.workerPools.set(workerPoolKey, workerPool);
1134
+ }
1135
+ return workerPool;
1136
+ }
1137
+ _getWorkerPoolProps() {
1138
+ return {
1139
+ maxQueuedJobs: this.props.maxQueuedJobs,
1140
+ maxPendingAdmissions: this.props.maxPendingAdmissions,
1141
+ priorityAgingMs: this.props.priorityAgingMs,
1142
+ onMetrics: this.props.onMetrics,
1143
+ performanceMarks: this.props.performanceMarks,
1144
+ maxQueuedBytes: this.props.maxQueuedBytes,
1145
+ maxInFlightBytes: this.props.maxInFlightBytes,
1146
+ maxConcurrency: this.props.maxConcurrency,
1147
+ maxMobileConcurrency: this.props.maxMobileConcurrency,
1148
+ reuseWorkers: this.props.reuseWorkers,
1149
+ onDebug: this.props.onDebug
1150
+ };
1151
+ }
1152
+ };
1153
+ function getWorkerPoolKey(options) {
1154
+ const { name, source, url, urlKey, loadWorker, workerType } = options;
1155
+ const sourceKey = source ? `source:${source}` : "";
1156
+ const urlKeyPart = url || urlKey ? `url:${url || urlKey}` : "";
1157
+ const loadWorkerKey = loadWorker ? `loadWorker:${getLoadWorkerId(loadWorker)}` : "";
1158
+ return [name, sourceKey, urlKeyPart, loadWorkerKey, `type:${workerType || "classic"}`].filter(Boolean).join("|");
1159
+ }
1160
+ function getLoadWorkerId(loadWorker) {
1161
+ let loadWorkerId = loadWorkerIds.get(loadWorker);
1162
+ if (!loadWorkerId) {
1163
+ loadWorkerId = nextLoadWorkerId++;
1164
+ loadWorkerIds.set(loadWorker, loadWorkerId);
1165
+ }
1166
+ return loadWorkerId;
1167
+ }
1168
+
1169
+ // dist/worker-utils/lib/worker-farm/worker-body.js
1170
+ async function getParentPort() {
1171
+ return parentPort;
1172
+ }
1173
+ var onMessageWrapperMap = /* @__PURE__ */ new Map();
1174
+ var WorkerBody = class {
1175
+ /** Check that we are actually in a worker thread */
1176
+ static async inWorkerThread() {
1177
+ const workerGlobalScope = globalThis.WorkerGlobalScope;
1178
+ return typeof workerGlobalScope === "function" && globalThis instanceof workerGlobalScope || Boolean(await getParentPort());
1179
+ }
1180
+ /*
1181
+ * (type: WorkerMessageType, payload: WorkerMessagePayload) => any
1182
+ */
1183
+ static set onmessage(onMessage2) {
1184
+ async function handleMessage(message) {
1185
+ const parentPort2 = await getParentPort();
1186
+ const { type, payload } = parentPort2 ? message : message.data;
1187
+ onMessage2(type, payload);
1188
+ }
1189
+ getParentPort().then((parentPort2) => {
1190
+ if (parentPort2) {
1191
+ parentPort2.on("message", (message) => {
1192
+ handleMessage(message);
1193
+ });
1194
+ parentPort2.on("exit", () => console.debug("Node worker closing"));
1195
+ } else {
1196
+ globalThis.onmessage = handleMessage;
1197
+ }
1198
+ });
1199
+ }
1200
+ static async addEventListener(onMessage2) {
1201
+ let onMessageWrapper = onMessageWrapperMap.get(onMessage2);
1202
+ if (!onMessageWrapper) {
1203
+ onMessageWrapper = (message) => {
1204
+ const messageData = getWorkerMessageData(message);
1205
+ if (!messageData) {
1206
+ return;
1207
+ }
1208
+ onMessage2(messageData.type, messageData.payload);
1209
+ };
1210
+ onMessageWrapperMap.set(onMessage2, onMessageWrapper);
1211
+ }
1212
+ const parentPort2 = await getParentPort();
1213
+ if (parentPort2) {
1214
+ parentPort2.on("message", onMessageWrapper);
1215
+ } else {
1216
+ globalThis.addEventListener("message", onMessageWrapper);
1217
+ }
1218
+ }
1219
+ static async removeEventListener(onMessage2) {
1220
+ const onMessageWrapper = onMessageWrapperMap.get(onMessage2);
1221
+ onMessageWrapperMap.delete(onMessage2);
1222
+ if (!onMessageWrapper) {
1223
+ return;
1224
+ }
1225
+ const parentPort2 = await getParentPort();
1226
+ if (parentPort2) {
1227
+ parentPort2.off("message", onMessageWrapper);
1228
+ } else {
1229
+ globalThis.removeEventListener("message", onMessageWrapper);
1230
+ }
1231
+ }
1232
+ /**
1233
+ * Send a message from a worker to creating thread (main thread)
1234
+ * @param type
1235
+ * @param payload
1236
+ */
1237
+ static async postMessage(type, payload, copy = false) {
1238
+ const data = { source: "loaders.gl", type, payload };
1239
+ const transferList = copy ? [] : getTransferList(payload);
1240
+ const parentPort2 = await getParentPort();
1241
+ if (parentPort2) {
1242
+ parentPort2.postMessage(data, transferList);
1243
+ } else {
1244
+ globalThis.postMessage(data, transferList);
1245
+ }
1246
+ }
1247
+ };
1248
+ function getWorkerMessageData(message) {
1249
+ if (!message || typeof message !== "object") {
1250
+ return null;
1251
+ }
1252
+ const messageData = "data" in message && message.type === "message" ? message.data : message;
1253
+ return messageData && typeof messageData.source === "string" && messageData.source.startsWith("loaders.gl") ? messageData : null;
1254
+ }
1255
+
1256
+ // dist/worker-utils/lib/async-queue/async-queue.js
1257
+ var AsyncQueue = class {
1258
+ constructor() {
1259
+ this._values = [];
1260
+ this._settlers = [];
1261
+ this._closed = false;
1262
+ }
1263
+ /** Return an async iterator for this queue */
1264
+ [Symbol.asyncIterator]() {
1265
+ return this;
1266
+ }
1267
+ /** Push a new value - the async iterator will yield a promise resolved to this value */
1268
+ push(value) {
1269
+ return this.enqueue(value);
1270
+ }
1271
+ /**
1272
+ * Push a new value - the async iterator will yield a promise resolved to this value
1273
+ * Add an error - the async iterator will yield a promise rejected with this value
1274
+ */
1275
+ enqueue(value) {
1276
+ if (this._closed) {
1277
+ throw new Error("Closed");
1278
+ }
1279
+ if (this._settlers.length > 0) {
1280
+ if (this._values.length > 0) {
1281
+ throw new Error("Illegal internal state");
1282
+ }
1283
+ const settler = this._settlers.shift();
1284
+ if (value instanceof Error) {
1285
+ settler.reject(value);
1286
+ } else {
1287
+ settler.resolve({ value });
1288
+ }
1289
+ } else {
1290
+ this._values.push(value);
1291
+ }
1292
+ }
1293
+ /** Indicate that we not waiting for more values - The async iterator will be done */
1294
+ close() {
1295
+ while (this._settlers.length > 0) {
1296
+ const settler = this._settlers.shift();
1297
+ settler.resolve({ done: true });
1298
+ }
1299
+ this._closed = true;
1300
+ }
1301
+ // ITERATOR IMPLEMENTATION
1302
+ /** @returns a Promise for an IteratorResult */
1303
+ next() {
1304
+ if (this._values.length > 0) {
1305
+ const value = this._values.shift();
1306
+ if (value instanceof Error) {
1307
+ return Promise.reject(value);
1308
+ }
1309
+ return Promise.resolve({ done: false, value });
1310
+ }
1311
+ if (this._closed) {
1312
+ if (this._settlers.length > 0) {
1313
+ throw new Error("Illegal internal state");
1314
+ }
1315
+ return Promise.resolve({ done: true, value: void 0 });
1316
+ }
1317
+ return new Promise((resolve, reject) => {
1318
+ this._settlers.push({ resolve, reject });
1319
+ });
1320
+ }
1321
+ };
1322
+
1323
+ // dist/worker-utils/lib/worker-api/get-worker-url.js
1324
+ var warnedWorkerVersionFallbacks = /* @__PURE__ */ new Set();
1325
+ function getWorkerName(worker) {
1326
+ const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : "";
1327
+ return `${worker.name}@${worker.version}${warning}`;
1328
+ }
1329
+ function getCustomWorkerURL(worker, options = {}) {
1330
+ var _a2, _b2;
1331
+ const workerFile = isBrowser ? worker.workerFile || `${worker.id}-worker.js` : worker.workerNode || `${worker.id}-worker-node.js`;
1332
+ let url = getConfiguredWorkerURL(worker, options);
1333
+ const workerType = options._workerType || ((_a2 = options == null ? void 0 : options.core) == null ? void 0 : _a2._workerType);
1334
+ if (!url && workerType === "test") {
1335
+ if (isBrowser) {
1336
+ url = `modules/${worker.module}/dist/${workerFile}`;
1337
+ } else {
1338
+ const workerSourceDirectory = worker.module === "tasks" && ((_b2 = worker.workerNode) == null ? void 0 : _b2.startsWith("worker-utils/")) ? "worker-utils/workers" : "workers";
1339
+ const workerSourceNode = worker.workerSourceNode || `${workerSourceDirectory}/${worker.id}-worker-node.ts`;
1340
+ url = `modules/${worker.module}/src/${workerSourceNode}`;
1341
+ }
1342
+ }
1343
+ return url || null;
1344
+ }
1345
+ function getConfiguredWorkerURL(worker, options = {}) {
1346
+ const workerOptions = options[worker.id] || {};
1347
+ return workerOptions.workerUrl || (worker.id === "compression" ? options.workerUrl : null) || null;
1348
+ }
1349
+ function getWorkerURL(worker, options = {}) {
1350
+ const customWorkerUrl = getCustomWorkerURL(worker, options);
1351
+ const descriptorWorkerUrl = typeof worker.worker === "string" ? worker.worker : null;
1352
+ const url = customWorkerUrl || descriptorWorkerUrl || getDefaultWorkerURL(worker, true);
1353
+ assert(url);
1354
+ return url;
1355
+ }
1356
+ function getDefaultWorkerURL(worker, warn = false) {
1357
+ const workerFile = isBrowser ? worker.workerFile || `${worker.id}-worker.js` : worker.workerNode || `${worker.id}-worker-node.js`;
1358
+ let version = worker.version;
1359
+ if (version === "latest") {
1360
+ version = NPM_TAG;
1361
+ }
1362
+ const versionTag = version ? `@${version}` : "";
1363
+ const packageName = worker.packageName || `@loaders.gl/${worker.module}`;
1364
+ const url = `https://unpkg.com/${packageName}${versionTag}/dist/${workerFile}`;
1365
+ if (warn) {
1366
+ warnIfUsingNpmTagFallback(worker, url);
1367
+ }
1368
+ return url;
1369
+ }
1370
+ function warnIfUsingNpmTagFallback(worker, url) {
1371
+ if (worker.version !== "latest") {
1372
+ return;
1373
+ }
1374
+ const workerId = `${worker.module}:${worker.id}`;
1375
+ if (warnedWorkerVersionFallbacks.has(workerId)) {
1376
+ return;
1377
+ }
1378
+ warnedWorkerVersionFallbacks.add(workerId);
1379
+ console.warn(`loaders.gl: ${worker.name} loader worker version is "latest" because __VERSION__ was not injected. Fetching ${url} from CDN.`);
1380
+ }
1381
+
1382
+ // dist/worker-utils/lib/worker-api/shared-state.js
1383
+ function getWorkerCapabilities() {
1384
+ const isolated = typeof globalThis.crossOriginIsolated === "boolean" ? globalThis.crossOriginIsolated : void 0;
1385
+ const capabilities = {
1386
+ workers: WorkerThread.isSupported(),
1387
+ sharedMemory: false,
1388
+ crossOriginIsolated: isolated
1389
+ };
1390
+ if (isBrowser && isolated !== true) {
1391
+ capabilities.sharedMemoryUnavailableReason = "cross-origin-isolation";
1392
+ } else if (typeof SharedArrayBuffer === "undefined" || typeof Atomics === "undefined" || typeof structuredClone !== "function") {
1393
+ capabilities.sharedMemoryUnavailableReason = "unsupported";
1394
+ } else {
1395
+ try {
1396
+ const buffer = new SharedArrayBuffer(4);
1397
+ const cloned = structuredClone(buffer);
1398
+ Atomics.store(new Int32Array(buffer), 0, 17);
1399
+ capabilities.sharedMemory = Atomics.load(new Int32Array(cloned), 0) === 17;
1400
+ if (!capabilities.sharedMemory)
1401
+ capabilities.sharedMemoryUnavailableReason = "blocked";
1402
+ } catch {
1403
+ capabilities.sharedMemoryUnavailableReason = "blocked";
1404
+ }
1405
+ }
1406
+ return capabilities;
1407
+ }
1408
+ var SharedWorkerState = class {
1409
+ constructor(buffer) {
1410
+ if (typeof SharedArrayBuffer === "undefined" || !(buffer instanceof SharedArrayBuffer) || buffer.byteLength !== 16)
1411
+ throw new Error("Expected a 16-byte shared worker control buffer");
1412
+ this.buffer = buffer;
1413
+ this.values = new Int32Array(buffer);
1414
+ }
1415
+ get snapshot() {
1416
+ return {
1417
+ cancelled: Atomics.load(this.values, 0) !== 0,
1418
+ completed: Atomics.load(this.values, 1),
1419
+ total: Atomics.load(this.values, 2),
1420
+ revision: Atomics.load(this.values, 3)
1421
+ };
1422
+ }
1423
+ cancel() {
1424
+ Atomics.store(this.values, 0, 1);
1425
+ Atomics.add(this.values, 3, 1);
1426
+ Atomics.notify(this.values, 0);
1427
+ }
1428
+ throwIfCancelled() {
1429
+ if (Atomics.load(this.values, 0) !== 0) {
1430
+ const error = new Error("Shared worker task was cancelled");
1431
+ error.name = "AbortError";
1432
+ throw error;
1433
+ }
1434
+ }
1435
+ /** Integer counters for application-defined work; messages still carry phase names and units. */
1436
+ setProgress(completed, total = -1) {
1437
+ if (!Number.isInteger(completed) || completed < 0 || completed > 2147483647 || !Number.isInteger(total) || total < -1 || total > 2147483647) {
1438
+ throw new RangeError("Shared progress requires nonnegative int32 counts (or total -1)");
1439
+ }
1440
+ Atomics.store(this.values, 1, completed);
1441
+ Atomics.store(this.values, 2, total);
1442
+ Atomics.add(this.values, 3, 1);
1443
+ }
1444
+ };
1445
+ function createSharedWorkerState() {
1446
+ if (!getWorkerCapabilities().sharedMemory)
1447
+ return null;
1448
+ const state = new SharedWorkerState(new SharedArrayBuffer(16));
1449
+ state.setProgress(0);
1450
+ return state;
1451
+ }
1452
+ function prepareSharedState(options) {
1453
+ if (options.sharedState === void 0 && options.cancellationMode === "cooperative") {
1454
+ const state = createSharedWorkerState();
1455
+ return state ? { ...options, sharedState: state.buffer } : options;
1456
+ }
1457
+ if (options.sharedState) {
1458
+ if (!getWorkerCapabilities().sharedMemory)
1459
+ throw new Error("Shared worker memory is unavailable");
1460
+ new SharedWorkerState(options.sharedState).throwIfCancelled();
1461
+ }
1462
+ return options;
1463
+ }
1464
+
1465
+ // dist/worker-utils/lib/worker-utils/get-input-byte-length.js
1466
+ function getInputByteLength(input) {
1467
+ const seen = /* @__PURE__ */ new Set();
1468
+ let bytes = 0;
1469
+ function visit(value) {
1470
+ if (!value || typeof value !== "object" || seen.has(value))
1471
+ return;
1472
+ seen.add(value);
1473
+ if (ArrayBuffer.isView(value)) {
1474
+ visit(value.buffer);
1475
+ } else if (value instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
1476
+ bytes += value.byteLength;
1477
+ } else if (value instanceof Map) {
1478
+ for (const [key, item] of value) {
1479
+ visit(key);
1480
+ visit(item);
1481
+ }
1482
+ } else if (value instanceof Set) {
1483
+ for (const item of value)
1484
+ visit(item);
1485
+ } else {
1486
+ for (const key of Object.keys(value))
1487
+ visit(value[key]);
1488
+ }
1489
+ }
1490
+ visit(input);
1491
+ return bytes;
1492
+ }
1493
+
1494
+ // dist/worker-utils/lib/worker-api/validate-output-ownership.js
1495
+ function validateOutputOwnership(ownership) {
1496
+ if (ownership !== void 0 && ownership !== "copy" && ownership !== "transfer") {
1497
+ throw new Error("Invalid worker output ownership");
1498
+ }
1499
+ }
1500
+
1501
+ // dist/worker-utils/lib/worker-api/process-on-worker.js
1502
+ async function processOnWorker(worker, data, options = {}, context = {}, jobContext = {}) {
1503
+ var _a2;
1504
+ validateOutputOwnership(options.outputOwnership);
1505
+ if (options.inputOwnership !== void 0 && !["copy", "transfer", "share"].includes(options.inputOwnership))
1506
+ throw new Error("Invalid worker input ownership");
1507
+ options = prepareSharedState(options);
1508
+ throwIfAborted(options.signal);
1509
+ validateSharedInput(options, [data, serializableOptions(options), jobContext]);
1510
+ const name = getWorkerName(worker);
1511
+ const workerPool = options.workerPool ?? WorkerFarm.getWorkerFarm(options).getWorkerPool(getWorkerPoolTarget(worker, options, name));
1512
+ const jobName = options.jobName || worker.name;
1513
+ const job = await workerPool.startJob(
1514
+ jobName,
1515
+ // eslint-disable-next-line
1516
+ onMessage.bind(null, context, options),
1517
+ void 0,
1518
+ options.signal,
1519
+ {
1520
+ inputBytes: getInputByteLength([data, budgetOptions(options), jobContext]),
1521
+ priority: options.priority,
1522
+ admission: options.admission,
1523
+ sharedState: options.sharedState ? new SharedWorkerState(options.sharedState) : void 0,
1524
+ cancellationMode: options.cancellationMode,
1525
+ cancellationTimeout: options.cancellationTimeout
1526
+ }
1527
+ );
1528
+ try {
1529
+ if (((_a2 = options.signal) == null ? void 0 : _a2.aborted) && !job.isCancelled)
1530
+ job.abort(getAbortReason(options.signal));
1531
+ const workerOptions = serializableOptions(options);
1532
+ const transferableOptions = getTransferListForWriter(workerOptions);
1533
+ const transferableContext = getTransferListForWriter(jobContext);
1534
+ if (job.isRunning) {
1535
+ job.postMessage("process", {
1536
+ input: data,
1537
+ options: transferableOptions,
1538
+ context: transferableContext
1539
+ }, options.inputOwnership === "copy" || options.inputOwnership === "share" ? [] : void 0);
1540
+ }
1541
+ const result = await job.result;
1542
+ return result.result;
1543
+ } catch (error) {
1544
+ if (!job.isCancelled)
1545
+ job.abort(error);
1546
+ throw error;
1547
+ }
1548
+ }
1549
+ function processOnWorkerInBatches(worker, input, options = {}, context = {}, jobContext = {}) {
1550
+ validateOutputOwnership(options.outputOwnership);
1551
+ if (options.inputOwnership !== void 0 && !["copy", "transfer", "share"].includes(options.inputOwnership))
1552
+ throw new Error("Invalid worker input ownership");
1553
+ return processOnWorkerInBatchesIterator(worker, input, options, context, jobContext);
1554
+ }
1555
+ async function* processOnWorkerInBatchesIterator(worker, input, options, context, jobContext) {
1556
+ options = prepareSharedState(options);
1557
+ throwIfAborted(options.signal);
1558
+ const name = getWorkerName(worker);
1559
+ const workerPool = options.workerPool ?? WorkerFarm.getWorkerFarm(options).getWorkerPool(getWorkerPoolTarget(worker, options, name));
1560
+ validateSharedInput(options, [serializableOptions(options), jobContext]);
1561
+ const contextBytes = getInputByteLength([budgetOptions(options), jobContext]);
1562
+ const inputBytes = options.inputBytes ?? contextBytes;
1563
+ if (workerPool.requiresInputBytes && options.inputBytes === void 0) {
1564
+ throw new Error("Byte-bounded batch sessions require inputBytes");
1565
+ }
1566
+ if (!Number.isSafeInteger(inputBytes) || inputBytes < contextBytes) {
1567
+ throw new RangeError("Batch inputBytes must cover options and context buffers");
1568
+ }
1569
+ const outputBatches = new AsyncQueue();
1570
+ const inputIterator = getAsyncIterator(input);
1571
+ let outputFinished = false;
1572
+ let inputFinished = false;
1573
+ let inputCleanupRequested = false;
1574
+ let inputRequest = Promise.resolve();
1575
+ const batchJobFailed = new Error("Worker batch job failed");
1576
+ const closeJobInput = () => {
1577
+ if (!inputFinished && !inputCleanupRequested) {
1578
+ inputCleanupRequested = true;
1579
+ closeInputIterator(inputIterator);
1580
+ }
1581
+ };
1582
+ const finishOutput = () => {
1583
+ if (!outputFinished) {
1584
+ outputFinished = true;
1585
+ outputBatches.close();
1586
+ }
1587
+ };
1588
+ const failOutput = (_error) => {
1589
+ if (!outputFinished) {
1590
+ outputFinished = true;
1591
+ outputBatches.enqueue(batchJobFailed);
1592
+ outputBatches.close();
1593
+ }
1594
+ };
1595
+ const job = await workerPool.startJob(options.jobName || worker.name, (activeJob, type, payload) => {
1596
+ if (activeJob.isCancelled && type !== "done" && type !== "error")
1597
+ return;
1598
+ switch (type) {
1599
+ case "progress":
1600
+ reportProgress(activeJob, options, payload);
1601
+ break;
1602
+ case "input-request":
1603
+ inputRequest = inputRequest.then(async () => {
1604
+ if (!activeJob.isRunning)
1605
+ return;
1606
+ const nextBatch = await inputIterator.next();
1607
+ if (!activeJob.isRunning) {
1608
+ return;
1609
+ }
1610
+ if (nextBatch.done) {
1611
+ inputFinished = true;
1612
+ activeJob.postMessage("input-done", {});
1613
+ } else {
1614
+ validateSharedInput(options, nextBatch.value);
1615
+ if (options.inputBytes !== void 0 && getInputByteLength(nextBatch.value) + contextBytes > inputBytes) {
1616
+ throw new RangeError("Worker batch exceeds reserved inputBytes");
1617
+ }
1618
+ activeJob.postMessage("input-batch", { input: nextBatch.value }, options.inputOwnership === "copy" || options.inputOwnership === "share" ? [] : void 0);
1619
+ }
1620
+ }).catch((error) => {
1621
+ if (!activeJob.isCancelled)
1622
+ activeJob.abort(error);
1623
+ });
1624
+ break;
1625
+ case "output-batch":
1626
+ outputBatches.push(payload.result);
1627
+ break;
1628
+ case "done":
1629
+ activeJob.done(payload);
1630
+ finishOutput();
1631
+ break;
1632
+ case "error": {
1633
+ const error = new Error(payload.error || "Worker batch processing failed");
1634
+ error.name = payload.errorName || "Error";
1635
+ activeJob.error(error);
1636
+ failOutput(error);
1637
+ break;
1638
+ }
1639
+ case "process":
1640
+ void onMessage(context, options, activeJob, type, payload);
1641
+ break;
1642
+ default: {
1643
+ const error = new Error(`Unexpected worker batch message: ${type}`);
1644
+ activeJob.error(error);
1645
+ failOutput(error);
1646
+ break;
1647
+ }
1648
+ }
1649
+ }, void 0, options.signal, {
1650
+ inputBytes,
1651
+ priority: options.priority,
1652
+ admission: options.admission,
1653
+ sharedState: options.sharedState ? new SharedWorkerState(options.sharedState) : void 0,
1654
+ cancellationMode: options.cancellationMode,
1655
+ cancellationTimeout: options.cancellationTimeout
1656
+ }).catch((error) => {
1657
+ closeJobInput();
1658
+ throw error;
1659
+ });
1660
+ void job.result.catch((error) => {
1661
+ failOutput(error);
1662
+ closeJobInput();
1663
+ });
1664
+ try {
1665
+ const workerOptions = serializableOptions(options);
1666
+ if (job.isRunning) {
1667
+ job.postMessage("process-in-batches", {
1668
+ options: getTransferListForWriter(workerOptions),
1669
+ context: getTransferListForWriter(jobContext)
1670
+ }, options.inputOwnership === "copy" || options.inputOwnership === "share" ? [] : void 0);
1671
+ }
1672
+ try {
1673
+ for await (const outputBatch of outputBatches) {
1674
+ yield outputBatch;
1675
+ if (job.isRunning) {
1676
+ job.postMessage("output-ack", {});
1677
+ }
1678
+ }
1679
+ } catch (error) {
1680
+ if (error === batchJobFailed) {
1681
+ await job.result;
1682
+ }
1683
+ throw error;
1684
+ }
1685
+ await job.result;
1686
+ } finally {
1687
+ if (job.isRunning && !job.isCancelled) {
1688
+ job.abort(createAbortError2("Worker batch iterator was closed"));
1689
+ }
1690
+ closeJobInput();
1691
+ }
1692
+ }
1693
+ function throwIfAborted(signal) {
1694
+ if (!(signal == null ? void 0 : signal.aborted)) {
1695
+ return;
1696
+ }
1697
+ throw getAbortReason(signal);
1698
+ }
1699
+ function getAbortReason(signal) {
1700
+ return signal ? signal.reason : createAbortError2("Worker job was aborted");
1701
+ }
1702
+ function createAbortError2(message) {
1703
+ const error = new Error(message);
1704
+ error.name = "AbortError";
1705
+ return error;
1706
+ }
1707
+ function getAsyncIterator(input) {
1708
+ if (Symbol.asyncIterator in input) {
1709
+ return input[Symbol.asyncIterator]();
1710
+ }
1711
+ return (async function* iterateSynchronously() {
1712
+ yield* input;
1713
+ })();
1714
+ }
1715
+ function closeInputIterator(inputIterator) {
1716
+ var _a2;
1717
+ try {
1718
+ void Promise.resolve((_a2 = inputIterator.return) == null ? void 0 : _a2.call(inputIterator)).catch(() => void 0);
1719
+ } catch {
1720
+ }
1721
+ }
1722
+ async function preloadWorker(worker, options = {}, preloadOptions = {}) {
1723
+ var _a2, _b2;
1724
+ const name = getWorkerName(worker);
1725
+ const workerPool = options.workerPool ?? WorkerFarm.getWorkerFarm(options).getWorkerPool(getWorkerPoolTarget(worker, options, name));
1726
+ const count = preloadOptions.count ?? options.maxConcurrency ?? ((_a2 = options.workerPool) == null ? void 0 : _a2.maxConcurrency) ?? ((_b2 = options["core"]) == null ? void 0 : _b2.maxConcurrency) ?? 1;
1727
+ if (!Number.isSafeInteger(count) || count < 0)
1728
+ throw new RangeError("Invalid preload count");
1729
+ const preloadJobs = Array.from({ length: count }, async () => {
1730
+ const job = await workerPool.startJob(`${worker.name} preload`, onPreloadMessage, void 0, options.signal);
1731
+ job.postMessage("preload", {});
1732
+ return await job.result;
1733
+ });
1734
+ await Promise.all(preloadJobs);
1735
+ }
1736
+ function getWorkerPoolTarget(worker, options, name) {
1737
+ if (options["source"]) {
1738
+ return { name, source: options["source"], workerType: options.workerType };
1739
+ }
1740
+ const customWorkerUrl = getCustomWorkerURL(worker, options);
1741
+ if (customWorkerUrl) {
1742
+ return { name, url: customWorkerUrl, workerType: options.workerType };
1743
+ }
1744
+ if (isBrowser && worker.loadWorker) {
1745
+ return {
1746
+ name,
1747
+ workerType: options.workerType,
1748
+ loadWorker: worker.loadWorker,
1749
+ getUrl: () => getWorkerURL(worker, options),
1750
+ urlKey: getDefaultWorkerURL(worker)
1751
+ };
1752
+ }
1753
+ return { name, url: getWorkerURL(worker, options), workerType: options.workerType };
1754
+ }
1755
+ async function onMessage(context, options, job, type, payload) {
1756
+ if (job.isCancelled && type !== "done" && type !== "error")
1757
+ return;
1758
+ switch (type) {
1759
+ case "progress":
1760
+ reportProgress(job, options, payload);
1761
+ break;
1762
+ case "done":
1763
+ job.done(payload);
1764
+ break;
1765
+ case "error":
1766
+ const error = new Error(payload.error);
1767
+ error.name = payload.errorName || "Error";
1768
+ job.error(error);
1769
+ break;
1770
+ case "process":
1771
+ const { id, input, options: processOptions } = payload;
1772
+ try {
1773
+ if (!context.process) {
1774
+ job.postMessage("error", { id, error: "Worker not set up to process on main thread" });
1775
+ return;
1776
+ }
1777
+ const result = await context.process(input, { ...processOptions, signal: options.signal, onProgress: options.onProgress }, void 0, payload.context || {});
1778
+ job.postMessage("done", { id, result });
1779
+ } catch (error2) {
1780
+ const message = error2 instanceof Error ? error2.message : "unknown error";
1781
+ job.postMessage("error", { id, error: message });
1782
+ }
1783
+ break;
1784
+ default:
1785
+ console.warn(`process-on-worker: unknown message ${type}`);
1786
+ }
1787
+ }
1788
+ function onPreloadMessage(job, type, payload) {
1789
+ switch (type) {
1790
+ case "done":
1791
+ job.done(payload);
1792
+ break;
1793
+ case "error":
1794
+ job.error(new Error(payload.error));
1795
+ break;
1796
+ default:
1797
+ console.warn(`process-on-worker: unknown preload message ${type}`);
1798
+ }
1799
+ }
1800
+ function reportProgress(job, options, payload) {
1801
+ var _a2;
1802
+ if (!job.isRunning || job.isCancelled || !payload.progress)
1803
+ return;
1804
+ try {
1805
+ (_a2 = options.onProgress) == null ? void 0 : _a2.call(options, payload.progress);
1806
+ } catch (error) {
1807
+ job.abort(error);
1808
+ }
1809
+ }
1810
+ function serializableOptions(options) {
1811
+ const { signal, onProgress, onMetrics, workerPool, admission, workerType, ...serializable } = options;
1812
+ return serializable;
1813
+ }
1814
+ function validateSharedInput(options, input) {
1815
+ if (options.inputOwnership === "share" && getTransferList(input).length) {
1816
+ throw new Error("Share ownership requires SharedArrayBuffer storage; ordinary transferables are not allowed");
1817
+ }
1818
+ }
1819
+ function budgetOptions(options) {
1820
+ const { sharedState, ...inputOptions } = serializableOptions(options);
1821
+ return inputOptions;
1822
+ }
1823
+
1824
+ // dist/worker-utils/lib/worker-api/create-worker.js
1825
+ var requestId = 0;
1826
+ var activeController = null;
1827
+ var activeInputBatches = null;
1828
+ var activeOutputAcknowledgements = null;
1829
+ async function createWorker(process2, processInBatches, preload) {
1830
+ if (!await WorkerBody.inWorkerThread()) {
1831
+ return;
1832
+ }
1833
+ const context = {
1834
+ process: processOnMainThread
1835
+ };
1836
+ WorkerBody.onmessage = async (type, payload) => {
1837
+ var _a2, _b2, _c2, _d, _e;
1838
+ if (type === "cancel") {
1839
+ activeController == null ? void 0 : activeController.abort();
1840
+ activeInputBatches == null ? void 0 : activeInputBatches.close();
1841
+ activeOutputAcknowledgements == null ? void 0 : activeOutputAcknowledgements.close();
1842
+ return;
1843
+ }
1844
+ const controller = type === "process" || type === "process-in-batches" ? new AbortController() : void 0;
1845
+ if (controller)
1846
+ activeController = controller;
1847
+ const startedAt = performance.now();
1848
+ const reporter = type === "process" || type === "process-in-batches" ? createProgressReporter() : void 0;
1849
+ let sharedState;
1850
+ const throwIfAborted2 = () => {
1851
+ controller == null ? void 0 : controller.signal.throwIfAborted();
1852
+ sharedState == null ? void 0 : sharedState.throwIfCancelled();
1853
+ };
1854
+ const jobContext = {
1855
+ ...context,
1856
+ signal: controller == null ? void 0 : controller.signal,
1857
+ sharedState,
1858
+ throwIfAborted: throwIfAborted2,
1859
+ reportProgress: (progress) => {
1860
+ if (!(controller == null ? void 0 : controller.signal.aborted) && !(sharedState == null ? void 0 : sharedState.snapshot.cancelled))
1861
+ reporter == null ? void 0 : reporter.report(progress);
1862
+ }
1863
+ };
1864
+ try {
1865
+ if (controller && ((_a2 = payload.options) == null ? void 0 : _a2["sharedState"])) {
1866
+ sharedState = new SharedWorkerState(payload.options["sharedState"]);
1867
+ jobContext.sharedState = sharedState;
1868
+ }
1869
+ switch (type) {
1870
+ case "preload":
1871
+ await (preload == null ? void 0 : preload());
1872
+ WorkerBody.postMessage("done", {});
1873
+ break;
1874
+ case "process":
1875
+ throwIfAborted2();
1876
+ validateOutputOwnership((_b2 = payload.options) == null ? void 0 : _b2["outputOwnership"]);
1877
+ if (!process2) {
1878
+ throw new Error("Worker does not support atomic processing");
1879
+ }
1880
+ const result = await process2(payload.input, payload.options || {}, jobContext, payload.context || {});
1881
+ throwIfAborted2();
1882
+ reporter == null ? void 0 : reporter.finish();
1883
+ await WorkerBody.postMessage("done", {
1884
+ result,
1885
+ executionMs: performance.now() - startedAt
1886
+ }, ((_c2 = payload.options) == null ? void 0 : _c2["outputOwnership"]) === "copy");
1887
+ break;
1888
+ case "process-in-batches":
1889
+ throwIfAborted2();
1890
+ validateOutputOwnership((_d = payload.options) == null ? void 0 : _d["outputOwnership"]);
1891
+ if (!processInBatches) {
1892
+ throw new Error("Worker does not support batched processing");
1893
+ }
1894
+ const inputBatches = new AsyncQueue();
1895
+ const outputAcknowledgements = new AsyncQueue();
1896
+ activeInputBatches = inputBatches;
1897
+ activeOutputAcknowledgements = outputAcknowledgements;
1898
+ try {
1899
+ const resultIterator = processInBatches(createDemandDrivenIterator(inputBatches), payload.options || {}, jobContext, payload.context || {});
1900
+ for await (const batch of resultIterator) {
1901
+ throwIfAborted2();
1902
+ await WorkerBody.postMessage("output-batch", { result: batch }, ((_e = payload.options) == null ? void 0 : _e["outputOwnership"]) === "copy");
1903
+ await outputAcknowledgements.next();
1904
+ }
1905
+ throwIfAborted2();
1906
+ reporter == null ? void 0 : reporter.finish();
1907
+ await WorkerBody.postMessage("done", { executionMs: performance.now() - startedAt });
1908
+ } finally {
1909
+ activeInputBatches = null;
1910
+ activeOutputAcknowledgements = null;
1911
+ }
1912
+ break;
1913
+ case "input-batch":
1914
+ if (!activeInputBatches) {
1915
+ throw new Error("Worker has no active batched processing session");
1916
+ }
1917
+ activeInputBatches.push(payload.input);
1918
+ break;
1919
+ case "input-done":
1920
+ if (!activeInputBatches) {
1921
+ throw new Error("Worker has no active batched processing session");
1922
+ }
1923
+ activeInputBatches.close();
1924
+ break;
1925
+ case "output-ack":
1926
+ if (!activeOutputAcknowledgements) {
1927
+ throw new Error("Worker has no active batched processing session");
1928
+ }
1929
+ activeOutputAcknowledgements.push(void 0);
1930
+ break;
1931
+ default:
1932
+ }
1933
+ } catch (error) {
1934
+ reporter == null ? void 0 : reporter.finish((controller == null ? void 0 : controller.signal.aborted) || (sharedState == null ? void 0 : sharedState.snapshot.cancelled));
1935
+ const message = error instanceof Error ? error.message : "";
1936
+ await WorkerBody.postMessage("error", {
1937
+ error: message,
1938
+ errorName: error instanceof Error ? error.name : "Error"
1939
+ });
1940
+ } finally {
1941
+ if (controller && activeController === controller)
1942
+ activeController = null;
1943
+ }
1944
+ };
1945
+ await WorkerBody.postMessage("ready", {});
1946
+ }
1947
+ async function* createDemandDrivenIterator(inputBatches) {
1948
+ while (true) {
1949
+ await WorkerBody.postMessage("input-request", {});
1950
+ const nextBatch = await inputBatches.next();
1951
+ if (nextBatch.done) {
1952
+ return;
1953
+ }
1954
+ yield nextBatch.value;
1955
+ }
1956
+ }
1957
+ function processOnMainThread(arrayBuffer, options = {}, jobContext = {}) {
1958
+ const signal = activeController == null ? void 0 : activeController.signal;
1959
+ signal == null ? void 0 : signal.throwIfAborted();
1960
+ return new Promise((resolve, reject) => {
1961
+ const id = requestId++;
1962
+ const cleanup = () => {
1963
+ signal == null ? void 0 : signal.removeEventListener("abort", abort);
1964
+ void WorkerBody.removeEventListener(onMessage2);
1965
+ };
1966
+ const abort = () => {
1967
+ cleanup();
1968
+ reject(signal == null ? void 0 : signal.reason);
1969
+ };
1970
+ const onMessage2 = (type, payload) => {
1971
+ if (payload.id !== id)
1972
+ return;
1973
+ if (type === "done") {
1974
+ cleanup();
1975
+ resolve(payload.result);
1976
+ } else if (type === "error") {
1977
+ cleanup();
1978
+ reject(payload.error);
1979
+ }
1980
+ };
1981
+ void WorkerBody.addEventListener(onMessage2).then(async () => {
1982
+ if (signal == null ? void 0 : signal.aborted) {
1983
+ abort();
1984
+ return;
1985
+ }
1986
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
1987
+ await WorkerBody.postMessage("process", {
1988
+ id,
1989
+ input: arrayBuffer,
1990
+ options,
1991
+ context: jobContext
1992
+ });
1993
+ }).catch((error) => {
1994
+ cleanup();
1995
+ reject(error);
1996
+ });
1997
+ });
1998
+ }
1999
+ function createProgressReporter() {
2000
+ let pending2;
2001
+ let finished = false;
2002
+ let scheduled = false;
2003
+ const flush = () => {
2004
+ scheduled = false;
2005
+ if (pending2) {
2006
+ WorkerBody.postMessage("progress", { progress: pending2 });
2007
+ pending2 = void 0;
2008
+ }
2009
+ };
2010
+ return {
2011
+ /** Records progress while retaining phase transitions. */
2012
+ report(progress) {
2013
+ if (finished)
2014
+ return;
2015
+ if (pending2 && pending2.phase !== progress.phase)
2016
+ flush();
2017
+ pending2 = { ...progress };
2018
+ if (!scheduled) {
2019
+ scheduled = true;
2020
+ setTimeout(flush, 0);
2021
+ }
2022
+ },
2023
+ /** Flushes final progress and suppresses reports from stale callbacks. */
2024
+ finish(discard = false) {
2025
+ if (discard)
2026
+ pending2 = void 0;
2027
+ flush();
2028
+ finished = true;
2029
+ }
2030
+ };
2031
+ }
2032
+
2033
+ // dist/worker-utils/index.js
2034
+ var import_meta = {};
2035
+ var path = typeof __filename === "string" ? __filename.replace(/\\/g, "/") : "";
2036
+ var moduleUrl = path ? `file://${path.startsWith("/") ? "" : "/"}${encodeURI(path).replace(/#/g, "%23").replace(/\?/g, "%3F")}` : import_meta.url;
2037
+
2038
+ // dist/tasks/task-preload.js
2039
+ var pending = /* @__PURE__ */ new WeakMap();
2040
+ var loaded = /* @__PURE__ */ new WeakSet();
2041
+ function preloadTaskCode(task, signal) {
2042
+ if (!task.preload)
2043
+ return Promise.resolve();
2044
+ let promise = pending.get(task);
2045
+ if (!promise) {
2046
+ promise = Promise.resolve().then(() => task.preload()).then(() => {
2047
+ loaded.add(task);
2048
+ });
2049
+ pending.set(task, promise);
2050
+ void promise.catch(() => pending.delete(task));
2051
+ }
2052
+ return withSignal(promise, signal);
2053
+ }
2054
+ function isTaskCodeLoaded(task) {
2055
+ return !task.preload || loaded.has(task);
2056
+ }
2057
+ async function preloadTasks(tasks, options = {}) {
2058
+ var _a2, _b2, _c2, _d;
2059
+ const execution = options.execution ?? "auto";
2060
+ if (!["auto", "main-thread", "worker"].includes(execution))
2061
+ throw new TypeError("Invalid execution mode");
2062
+ (_a2 = options.signal) == null ? void 0 : _a2.throwIfAborted();
2063
+ for (const task of new Set(tasks)) {
2064
+ (_b2 = options.signal) == null ? void 0 : _b2.throwIfAborted();
2065
+ if (execution === "worker" && !task.worker)
2066
+ throw new Error("Task has no worker");
2067
+ if (execution === "main-thread" || !task.worker) {
2068
+ await preloadTaskCode(task, options.signal);
2069
+ continue;
2070
+ }
2071
+ const target = task.worker;
2072
+ if (Boolean(target.url) === Boolean(target.create))
2073
+ throw new Error("Supply exactly one worker URL or factory");
2074
+ const pool = new WorkerPool({
2075
+ name: task.id,
2076
+ url: (_c2 = target.url) == null ? void 0 : _c2.toString(),
2077
+ loadWorker: target.create,
2078
+ workerType: "module",
2079
+ maxConcurrency: 1,
2080
+ maxMobileConcurrency: 1
2081
+ });
2082
+ const descriptor = {
2083
+ id: task.id,
2084
+ name: task.id,
2085
+ module: "tasks",
2086
+ version: "prototype",
2087
+ options: {},
2088
+ worker: ((_d = target.url) == null ? void 0 : _d.toString()) ?? true,
2089
+ loadWorker: target.create,
2090
+ workerInBatches: target.capabilities.streaming
2091
+ };
2092
+ try {
2093
+ await preloadWorker(descriptor, { workerPool: pool, workerType: "module", signal: options.signal }, { count: 1 });
2094
+ } finally {
2095
+ await pool.destroy();
2096
+ }
2097
+ }
2098
+ }
2099
+ function withSignal(operation, signal) {
2100
+ if (!signal)
2101
+ return operation;
2102
+ return new Promise((resolve, reject) => {
2103
+ const abort = () => {
2104
+ signal.removeEventListener("abort", abort);
2105
+ reject(signal.reason);
2106
+ };
2107
+ signal.addEventListener("abort", abort, { once: true });
2108
+ if (signal.aborted)
2109
+ abort();
2110
+ operation.then((value) => {
2111
+ signal.removeEventListener("abort", abort);
2112
+ resolve(value);
2113
+ }, (error) => {
2114
+ signal.removeEventListener("abort", abort);
2115
+ reject(error);
2116
+ });
2117
+ });
2118
+ }
2119
+
2120
+ // dist/tasks/task-channel.js
2121
+ var TaskRequestError = class extends Error {
2122
+ };
2123
+ var TaskChannel = class {
2124
+ constructor(options) {
2125
+ this.options = options;
2126
+ this.nextId = 1;
2127
+ this.pending = /* @__PURE__ */ new Map();
2128
+ this.incoming = /* @__PURE__ */ new Map();
2129
+ }
2130
+ /** Send a request without serializing other in-flight requests. */
2131
+ request(operation, value, signal, transfer = []) {
2132
+ if (this.failure)
2133
+ return Promise.reject(this.failure.reason);
2134
+ if (signal == null ? void 0 : signal.aborted)
2135
+ return Promise.reject(signal.reason);
2136
+ const id = this.nextId++;
2137
+ return new Promise((resolve, reject) => {
2138
+ const abort = () => {
2139
+ const pending2 = this.pending.get(id);
2140
+ if (!pending2)
2141
+ return;
2142
+ this.pending.delete(id);
2143
+ pending2.cleanup();
2144
+ reject(signal == null ? void 0 : signal.reason);
2145
+ this.send({ source: "math.gl/tasks", kind: "cancel", id });
2146
+ };
2147
+ this.pending.set(id, {
2148
+ resolve,
2149
+ reject,
2150
+ cleanup: () => signal == null ? void 0 : signal.removeEventListener("abort", abort)
2151
+ });
2152
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
2153
+ this.send({ source: "math.gl/tasks", kind: "request", id, operation, value }, transfer);
2154
+ });
2155
+ }
2156
+ /** Send a one-way notification. */
2157
+ emit(operation, value, transfer = []) {
2158
+ if (this.failure)
2159
+ throw this.failure.reason;
2160
+ this.send({ source: "math.gl/tasks", kind: "event", id: 0, operation, value }, transfer);
2161
+ }
2162
+ /** Dispatch a transport message; unrelated protocols are ignored. */
2163
+ receive(message) {
2164
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h;
2165
+ if (this.failure || (message == null ? void 0 : message.source) !== "math.gl/tasks")
2166
+ return;
2167
+ if (message.kind === "failure") {
2168
+ const reason = new Error(((_a2 = message.error) == null ? void 0 : _a2.message) ?? "Task channel failed");
2169
+ this.close(reason);
2170
+ (_c2 = (_b2 = this.options).onFailure) == null ? void 0 : _c2.call(_b2, reason);
2171
+ } else if (message.kind === "result" || message.kind === "error") {
2172
+ const pending2 = this.pending.get(message.id);
2173
+ if (!pending2)
2174
+ return;
2175
+ this.pending.delete(message.id);
2176
+ pending2.cleanup();
2177
+ if (message.kind === "result")
2178
+ pending2.resolve(message.value);
2179
+ else {
2180
+ const error = new TaskRequestError(((_d = message.error) == null ? void 0 : _d.message) ?? "Task request failed");
2181
+ error.name = ((_e = message.error) == null ? void 0 : _e.name) ?? "Error";
2182
+ pending2.reject(error);
2183
+ }
2184
+ } else if (message.kind === "cancel") {
2185
+ (_f = this.incoming.get(message.id)) == null ? void 0 : _f.abort(new DOMException("Task request cancelled", "AbortError"));
2186
+ } else if (message.kind === "event") {
2187
+ try {
2188
+ (_h = (_g = this.options).handleEvent) == null ? void 0 : _h.call(_g, message.operation, message.value);
2189
+ } catch (error) {
2190
+ this.fail(error);
2191
+ }
2192
+ } else if (message.kind === "request") {
2193
+ if (this.incoming.has(message.id)) {
2194
+ this.fail(new Error("Duplicate task request identifier"));
2195
+ return;
2196
+ }
2197
+ const controller = new AbortController();
2198
+ this.incoming.set(message.id, controller);
2199
+ void Promise.resolve().then(() => {
2200
+ controller.signal.throwIfAborted();
2201
+ return this.options.handleRequest(message.operation, message.value, controller.signal);
2202
+ }).then((value) => {
2203
+ var _a3, _b3;
2204
+ if (!controller.signal.aborted && !this.failure) {
2205
+ this.send({ source: "math.gl/tasks", kind: "result", id: message.id, value }, (_b3 = (_a3 = this.options).getResultTransferList) == null ? void 0 : _b3.call(_a3, value, message.value));
2206
+ }
2207
+ }).catch((reason) => {
2208
+ if (!controller.signal.aborted && !this.failure) {
2209
+ this.send({
2210
+ source: "math.gl/tasks",
2211
+ kind: "error",
2212
+ id: message.id,
2213
+ error: {
2214
+ name: reason instanceof Error ? reason.name : "Error",
2215
+ message: reason instanceof Error ? reason.message : String(reason)
2216
+ }
2217
+ });
2218
+ }
2219
+ }).finally(() => this.incoming.delete(message.id));
2220
+ }
2221
+ }
2222
+ /** Reject all outstanding calls with a common cause and abort incoming callbacks. */
2223
+ close(reason = new Error("Task channel closed")) {
2224
+ if (this.failure)
2225
+ return;
2226
+ this.failure = { reason };
2227
+ for (const pending2 of this.pending.values()) {
2228
+ pending2.cleanup();
2229
+ pending2.reject(reason);
2230
+ }
2231
+ this.pending.clear();
2232
+ for (const controller of this.incoming.values())
2233
+ controller.abort(reason);
2234
+ this.incoming.clear();
2235
+ }
2236
+ send(message, transfer = []) {
2237
+ if (this.failure)
2238
+ return;
2239
+ try {
2240
+ this.options.send(message, transfer);
2241
+ } catch (error) {
2242
+ this.fail(error);
2243
+ }
2244
+ }
2245
+ /** Invalidate the channel and notify the peer when the transport still works. */
2246
+ fail(reason) {
2247
+ var _a2, _b2;
2248
+ if (this.failure)
2249
+ return;
2250
+ this.close(reason);
2251
+ try {
2252
+ this.options.send({
2253
+ source: "math.gl/tasks",
2254
+ kind: "failure",
2255
+ id: 0,
2256
+ error: {
2257
+ name: reason instanceof Error ? reason.name : "Error",
2258
+ message: reason instanceof Error ? reason.message : String(reason)
2259
+ }
2260
+ }, []);
2261
+ } catch {
2262
+ }
2263
+ (_b2 = (_a2 = this.options).onFailure) == null ? void 0 : _b2.call(_a2, reason);
2264
+ }
2265
+ };
2266
+
2267
+ // dist/tasks/task-runtime.js
2268
+ function assertPayload(value) {
2269
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
2270
+ throw new TypeError("Task payloads must be plain objects with named fields");
2271
+ }
2272
+ }
2273
+ function clonePayload(value, ownership = "copy") {
2274
+ assertPayload(value);
2275
+ if (!["copy", "transfer", "share"].includes(ownership))
2276
+ throw new TypeError("Invalid input ownership");
2277
+ const transfer = getTransferList(value);
2278
+ if (ownership === "share" && transfer.length)
2279
+ throw new TypeError("Share requires shared storage");
2280
+ return structuredClone(value, {
2281
+ transfer: ownership === "transfer" ? transfer : []
2282
+ });
2283
+ }
2284
+ function taskContext(state, context = {}) {
2285
+ const signal = context.signal ?? new AbortController().signal;
2286
+ return {
2287
+ state,
2288
+ signal,
2289
+ requestHost: async (operation, payload, controls) => {
2290
+ signal.throwIfAborted();
2291
+ if (!context.requestHost)
2292
+ throw new Error("No host request handler configured");
2293
+ return context.requestHost(operation, payload, controls);
2294
+ },
2295
+ emitHost: (operation, payload) => {
2296
+ var _a2;
2297
+ signal.throwIfAborted();
2298
+ (_a2 = context.emitHost) == null ? void 0 : _a2.call(context, operation, payload);
2299
+ },
2300
+ throwIfAborted: () => {
2301
+ var _a2;
2302
+ signal.throwIfAborted();
2303
+ (_a2 = context.throwIfAborted) == null ? void 0 : _a2.call(context);
2304
+ },
2305
+ reportProgress: (progress) => {
2306
+ var _a2;
2307
+ return (_a2 = context.reportProgress) == null ? void 0 : _a2.call(context, {
2308
+ ...progress,
2309
+ phase: progress.phase ?? "process",
2310
+ unit: progress.unit ?? "items"
2311
+ });
2312
+ }
2313
+ };
2314
+ }
2315
+ var TaskRuntime = class {
2316
+ constructor(task) {
2317
+ this.task = task;
2318
+ this.initialized = false;
2319
+ }
2320
+ async initialize(input, context = {}) {
2321
+ var _a2, _b2, _c2;
2322
+ if (this.initialized)
2323
+ throw new Error("Task is already initialized");
2324
+ assertPayload(input);
2325
+ await preloadTaskCode(this.task, context.signal);
2326
+ (_a2 = context.signal) == null ? void 0 : _a2.throwIfAborted();
2327
+ this.state = await ((_c2 = (_b2 = this.task).initialize) == null ? void 0 : _c2.call(_b2, input, taskContext(void 0, context)));
2328
+ this.initialized = true;
2329
+ return {};
2330
+ }
2331
+ async destroy() {
2332
+ var _a2, _b2;
2333
+ if (this.initialized) {
2334
+ this.initialized = false;
2335
+ const state = this.state;
2336
+ this.state = void 0;
2337
+ if (this.task.initialize)
2338
+ await ((_b2 = (_a2 = this.task).destroy) == null ? void 0 : _b2.call(_a2, state));
2339
+ }
2340
+ return {};
2341
+ }
2342
+ async process(input, options, context = {}) {
2343
+ if (!this.initialized)
2344
+ throw new Error("Task is not initialized");
2345
+ if (!this.task.process)
2346
+ throw new Error("Task has no atomic processor");
2347
+ assertPayload(input);
2348
+ const result = await this.task.process(input, options, taskContext(this.state, context));
2349
+ assertPayload(result);
2350
+ return result;
2351
+ }
2352
+ async *stream(inputs, options, context = {}) {
2353
+ if (!this.initialized)
2354
+ throw new Error("Task is not initialized");
2355
+ if (!this.task.processInBatches)
2356
+ throw new Error("Task has no streaming processor");
2357
+ for await (const output of this.task.processInBatches(inputs, options, taskContext(this.state, context))) {
2358
+ assertPayload(output);
2359
+ yield output;
2360
+ }
2361
+ }
2362
+ };
2363
+ async function initializeTaskWorker(task) {
2364
+ if (!await WorkerBody.inWorkerThread())
2365
+ throw new Error("initializeTaskWorker must run inside a worker");
2366
+ if (installed)
2367
+ throw new Error("A task is already installed in this worker");
2368
+ installed = true;
2369
+ const runtime = new TaskRuntime(task);
2370
+ let channelStream;
2371
+ const channel = new TaskChannel({
2372
+ getResultTransferList: (value, request) => request.outputOwnership === "transfer" ? getTransferList(value) : [],
2373
+ send: (message, transfer) => {
2374
+ const snapshot = structuredClone(message, { transfer });
2375
+ void WorkerBody.postMessage("task-channel", snapshot).catch((reason) => channel.fail(reason));
2376
+ },
2377
+ handleRequest: async (operation, value, signal) => {
2378
+ var _a2;
2379
+ const request = value;
2380
+ const context = {
2381
+ signal,
2382
+ reportProgress: (progress) => channel.emit("task:progress", { id: request.progressId, progress }),
2383
+ requestHost: (operation2, payload, controls = {}) => {
2384
+ const request2 = {
2385
+ operation: operation2,
2386
+ payload: clonePayload(payload, controls.inputOwnership),
2387
+ outputOwnership: controls.outputOwnership ?? "copy"
2388
+ };
2389
+ return channel.request("task:host-request", request2, signal, getTransferList(request2));
2390
+ },
2391
+ emitHost: (operation2, payload) => channel.emit("task:host-event", { operation: operation2, payload, id: request.progressId })
2392
+ };
2393
+ switch (operation) {
2394
+ case "initialize":
2395
+ return runtime.initialize(request.input, context);
2396
+ case "process":
2397
+ return runtime.process(request.input, request.options, context);
2398
+ case "stream-open": {
2399
+ if (channelStream)
2400
+ throw new Error("A task stream is already open");
2401
+ async function* inputs() {
2402
+ while (true) {
2403
+ const result = await channel.request("task:next-input", { outputOwnership: "transfer" }, signal);
2404
+ if (result.done)
2405
+ return;
2406
+ yield result.value;
2407
+ }
2408
+ }
2409
+ channelStream = runtime.stream(inputs(), request.options, context)[Symbol.asyncIterator]();
2410
+ return {};
2411
+ }
2412
+ case "stream-next":
2413
+ if (!channelStream)
2414
+ throw new Error("No active task stream");
2415
+ return channelStream.next();
2416
+ case "stream-close":
2417
+ try {
2418
+ await ((_a2 = channelStream == null ? void 0 : channelStream.return) == null ? void 0 : _a2.call(channelStream));
2419
+ } finally {
2420
+ channelStream = void 0;
2421
+ }
2422
+ return {};
2423
+ case "destroy":
2424
+ return runtime.destroy();
2425
+ default:
2426
+ throw new Error("Unknown task channel operation");
2427
+ }
2428
+ }
2429
+ });
2430
+ await WorkerBody.addEventListener((type, payload) => {
2431
+ if (type === "task-channel")
2432
+ channel.receive(payload);
2433
+ });
2434
+ let streamOptions = {};
2435
+ return createWorker(async (request, _options, context) => {
2436
+ switch (request.operation) {
2437
+ case "initialize":
2438
+ return runtime.initialize(request.input, context);
2439
+ case "destroy":
2440
+ return runtime.destroy();
2441
+ case "stream-options":
2442
+ streamOptions = request.options;
2443
+ return {};
2444
+ case "process":
2445
+ return runtime.process(request.input, request.options, context);
2446
+ default:
2447
+ throw new Error("Unknown task operation");
2448
+ }
2449
+ }, async function* (inputs, _options, context) {
2450
+ async function* batches() {
2451
+ for await (const input of inputs) {
2452
+ assertPayload(input);
2453
+ yield input;
2454
+ }
2455
+ }
2456
+ try {
2457
+ yield* runtime.stream(batches(), streamOptions, context);
2458
+ } finally {
2459
+ streamOptions = {};
2460
+ }
2461
+ }, () => preloadTaskCode(task));
2462
+ }
2463
+ var installed = false;
2464
+ function localContext(controls) {
2465
+ return {
2466
+ signal: controls.signal,
2467
+ reportProgress: (progress) => {
2468
+ var _a2;
2469
+ return (_a2 = controls.onProgress) == null ? void 0 : _a2.call(controls, progress);
2470
+ }
2471
+ };
2472
+ }
2473
+
2474
+ // dist/tasks/task-sync.js
2475
+ function runTaskSync(task, input, request = {}) {
2476
+ var _a2, _b2;
2477
+ if (!isTaskCodeLoaded(task))
2478
+ throw new Error("Preload task on the main thread before runTaskSync");
2479
+ if ("execution" in request)
2480
+ throw new TypeError("runTaskSync always runs on the calling thread");
2481
+ if (!task.process)
2482
+ throw new TypeError("Task has no atomic processor");
2483
+ for (const hook of [task.initialize, task.process, task.destroy]) {
2484
+ if (hook && Object.prototype.toString.call(hook) === "[object AsyncFunction]")
2485
+ throw new TypeError("runTaskSync requires synchronous lifecycle hooks");
2486
+ }
2487
+ if (request.outputOwnership && !["copy", "transfer"].includes(request.outputOwnership))
2488
+ throw new TypeError("Invalid output ownership");
2489
+ const context = taskContext(void 0, localContext(request));
2490
+ context.throwIfAborted();
2491
+ const options = request.options ?? {};
2492
+ if (request.inputOwnership === "transfer") {
2493
+ const metadata = new Set(getTransferList(options));
2494
+ if (getTransferList(input).some((buffer) => metadata.has(buffer)))
2495
+ throw new Error("Transferred input aliases reusable options; use inputOwnership: copy");
2496
+ }
2497
+ const copiedOptions = clonePayload(options);
2498
+ const initialization = clonePayload(request.initialization ?? {}, request.initializationOwnership);
2499
+ let initialized = false;
2500
+ let failure;
2501
+ let failed = false;
2502
+ let output;
2503
+ try {
2504
+ const state = (_a2 = task.initialize) == null ? void 0 : _a2.call(task, initialization, context);
2505
+ if (isThenable(state)) {
2506
+ void Promise.resolve(state).then((value) => {
2507
+ var _a3;
2508
+ return (_a3 = task.destroy) == null ? void 0 : _a3.call(task, value);
2509
+ }).catch(() => {
2510
+ });
2511
+ throw new TypeError("runTaskSync initialize returned a promise");
2512
+ }
2513
+ context.state = state;
2514
+ initialized = true;
2515
+ context.throwIfAborted();
2516
+ const copiedInput = clonePayload(input, request.inputOwnership);
2517
+ const result = task.process(copiedInput, copiedOptions, context);
2518
+ if (isThenable(result)) {
2519
+ initialized = false;
2520
+ void Promise.resolve(result).catch(() => {
2521
+ }).then(() => {
2522
+ var _a3;
2523
+ if (task.initialize)
2524
+ return (_a3 = task.destroy) == null ? void 0 : _a3.call(task, context.state);
2525
+ }).catch(() => {
2526
+ });
2527
+ throw new TypeError("runTaskSync process returned a promise");
2528
+ }
2529
+ assertPayload(result);
2530
+ context.throwIfAborted();
2531
+ output = clonePayload(result, request.outputOwnership ?? "transfer");
2532
+ } catch (error) {
2533
+ failed = true;
2534
+ failure = error;
2535
+ } finally {
2536
+ if (initialized && task.initialize) {
2537
+ try {
2538
+ const cleanup = (_b2 = task.destroy) == null ? void 0 : _b2.call(task, context.state);
2539
+ if (isThenable(cleanup)) {
2540
+ void Promise.resolve(cleanup).catch(() => {
2541
+ });
2542
+ throw new TypeError("runTaskSync destroy returned a promise");
2543
+ }
2544
+ } catch (error) {
2545
+ if (failed)
2546
+ throw new AggregateError([failure, error], "Task processing and destruction failed");
2547
+ throw error;
2548
+ }
2549
+ }
2550
+ }
2551
+ if (failed)
2552
+ throw failure;
2553
+ return output;
2554
+ }
2555
+ function isThenable(value) {
2556
+ return Boolean(value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function");
2557
+ }
2558
+
2559
+ // dist/tasks/task-operation-queue.js
2560
+ var TaskOperationQueue = class {
2561
+ constructor(maxConcurrency) {
2562
+ this.maxConcurrency = maxConcurrency;
2563
+ this.pending = [];
2564
+ this.active = 0;
2565
+ this.exclusive = false;
2566
+ this.closed = false;
2567
+ this.idleWaiters = /* @__PURE__ */ new Set();
2568
+ if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency < 1) {
2569
+ throw new RangeError("maxConcurrency must be a positive safe integer");
2570
+ }
2571
+ }
2572
+ /** Queue an operation; aborting before it starts removes it without running it. */
2573
+ run(mode, operation, signal) {
2574
+ if (this.closed)
2575
+ return Promise.reject(new Error("Task operation queue is closed"));
2576
+ if (mode !== "parallel" && mode !== "exclusive")
2577
+ return Promise.reject(new TypeError("Invalid operation mode"));
2578
+ if (signal == null ? void 0 : signal.aborted)
2579
+ return Promise.reject(signal.reason);
2580
+ return new Promise((resolve, reject) => {
2581
+ const onAbort = () => {
2582
+ const index = this.pending.indexOf(entry);
2583
+ if (index >= 0) {
2584
+ this.pending.splice(index, 1);
2585
+ entry.cancel(signal == null ? void 0 : signal.reason);
2586
+ this.pump();
2587
+ }
2588
+ };
2589
+ const entry = {
2590
+ mode,
2591
+ cancel: (reason) => {
2592
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2593
+ reject(reason);
2594
+ },
2595
+ start: () => {
2596
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2597
+ this.active++;
2598
+ if (mode === "exclusive")
2599
+ this.exclusive = true;
2600
+ void Promise.resolve().then(() => {
2601
+ signal == null ? void 0 : signal.throwIfAborted();
2602
+ return operation();
2603
+ }).then(resolve, reject).finally(() => {
2604
+ this.active--;
2605
+ if (mode === "exclusive")
2606
+ this.exclusive = false;
2607
+ this.pump();
2608
+ });
2609
+ }
2610
+ };
2611
+ this.pending.push(entry);
2612
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2613
+ if (signal == null ? void 0 : signal.aborted)
2614
+ onAbort();
2615
+ else
2616
+ this.pump();
2617
+ });
2618
+ }
2619
+ /** Reject queued calls with one cause while allowing active operations to settle. */
2620
+ cancelPending(reason) {
2621
+ this.closed = true;
2622
+ for (const entry of this.pending.splice(0))
2623
+ entry.cancel(reason);
2624
+ this.pump();
2625
+ }
2626
+ /** Stop accepting new work; accepted operations continue to completion. */
2627
+ close() {
2628
+ this.closed = true;
2629
+ return this.whenIdle();
2630
+ }
2631
+ /** Wait until the queue has no running or waiting operations. */
2632
+ whenIdle() {
2633
+ if (!this.active && !this.pending.length)
2634
+ return Promise.resolve();
2635
+ return new Promise((resolve) => this.idleWaiters.add(resolve));
2636
+ }
2637
+ pump() {
2638
+ while (!this.exclusive && this.pending.length && this.active < this.maxConcurrency) {
2639
+ const entry = this.pending[0];
2640
+ if (entry.mode === "exclusive" && this.active)
2641
+ break;
2642
+ this.pending.shift();
2643
+ entry.start();
2644
+ if (entry.mode === "exclusive")
2645
+ break;
2646
+ }
2647
+ if (!this.active && !this.pending.length) {
2648
+ for (const resolve of this.idleWaiters)
2649
+ resolve();
2650
+ this.idleWaiters.clear();
2651
+ }
2652
+ }
2653
+ };
2654
+
2655
+ // dist/tasks/task-worker-channel.js
2656
+ var TaskWorkerChannel = class {
2657
+ constructor(name, target, options) {
2658
+ var _a2;
2659
+ this.thread = new WorkerThread({
2660
+ name,
2661
+ url: (_a2 = target.url) == null ? void 0 : _a2.toString(),
2662
+ loadWorker: target.create,
2663
+ workerType: "module"
2664
+ });
2665
+ this.channel = new TaskChannel({
2666
+ ...options,
2667
+ send: (message, transfer) => this.thread.postMessage({ source: "loaders.gl/tasks", type: "task-channel", payload: message }, transfer)
2668
+ });
2669
+ this.thread.onMessage = (message) => {
2670
+ if ((message == null ? void 0 : message.type) === "task-channel")
2671
+ this.channel.receive(message.payload);
2672
+ };
2673
+ this.thread.onError = (reason) => {
2674
+ var _a3;
2675
+ this.channel.close(reason);
2676
+ (_a3 = options.onFailure) == null ? void 0 : _a3.call(options, reason);
2677
+ };
2678
+ }
2679
+ /** Settle pending calls and terminate the worker without replacing its state. */
2680
+ async destroy(reason) {
2681
+ this.channel.close(reason);
2682
+ await this.thread.destroy();
2683
+ }
2684
+ };
2685
+
2686
+ // dist/tasks/task-runner.js
2687
+ var InitializedTask = class {
2688
+ /** @internal Use TaskRunner.initializeTask. */
2689
+ constructor(task, release, initializationControls) {
2690
+ var _a2, _b2, _c2;
2691
+ this.task = task;
2692
+ this.release = release;
2693
+ this.initializationControls = initializationControls;
2694
+ this.nextProgressId = 1;
2695
+ this.progressCallbacks = /* @__PURE__ */ new Map();
2696
+ this.callbackFailures = /* @__PURE__ */ new Map();
2697
+ this.closed = false;
2698
+ this.finalized = false;
2699
+ this.streams = /* @__PURE__ */ new Set();
2700
+ this.invalid = false;
2701
+ this.controller = new AbortController();
2702
+ const controls = initializationControls;
2703
+ this.runtime = new TaskRuntime(task);
2704
+ const concurrency = controls.operationConcurrency ?? 1;
2705
+ const maximum = ((_a2 = task.concurrency) == null ? void 0 : _a2.maxConcurrency) ?? 1;
2706
+ if (!Number.isSafeInteger(maximum) || maximum < 1 || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > maximum) {
2707
+ throw new RangeError("Task concurrency must be between 1 and the task maximum");
2708
+ }
2709
+ this.operationQueue = new TaskOperationQueue(concurrency);
2710
+ this.concurrent = concurrency > 1;
2711
+ const execution = controls.execution ?? "auto";
2712
+ if (!["auto", "main-thread", "worker"].includes(execution))
2713
+ throw new TypeError("Invalid execution mode");
2714
+ if (execution === "worker" && !task.worker)
2715
+ throw new Error("Task has no worker");
2716
+ if (execution !== "main-thread" && task.worker) {
2717
+ const target = task.worker;
2718
+ if (Boolean(target.url) === Boolean(target.create))
2719
+ throw new Error("Supply exactly one worker URL or factory");
2720
+ if (this.concurrent || controls.onRequest || controls.onEvent) {
2721
+ this.workerChannel = new TaskWorkerChannel(task.id, target, {
2722
+ handleRequest: async (operation, payload, signal) => {
2723
+ if (operation === "task:next-input") {
2724
+ if (!this.channelInputs)
2725
+ throw new Error("No active task stream");
2726
+ return this.channelInputs.next();
2727
+ }
2728
+ if (!controls.onRequest)
2729
+ throw new Error("No host request handler configured");
2730
+ const request = payload;
2731
+ if (operation !== "task:host-request")
2732
+ throw new Error("Unknown host request");
2733
+ return controls.onRequest(request.operation, request.payload, signal);
2734
+ },
2735
+ getResultTransferList: (value, request) => request.outputOwnership === "transfer" ? getTransferList(value) : [],
2736
+ handleEvent: (operation, payload) => {
2737
+ var _a3, _b3;
2738
+ const { id } = payload;
2739
+ try {
2740
+ if (operation === "task:progress") {
2741
+ const event = payload;
2742
+ (_a3 = this.progressCallbacks.get(event.id) ?? this.streamProgress) == null ? void 0 : _a3(event.progress);
2743
+ } else if (operation === "task:host-event") {
2744
+ const event = payload;
2745
+ (_b3 = controls.onEvent) == null ? void 0 : _b3.call(controls, event.operation, event.payload);
2746
+ }
2747
+ } catch (reason) {
2748
+ if (this.progressCallbacks.has(id) || this.streamProgressId === id) {
2749
+ if (!this.callbackFailures.has(id))
2750
+ this.callbackFailures.set(id, { reason });
2751
+ }
2752
+ }
2753
+ },
2754
+ onFailure: (reason) => {
2755
+ this.invalid = true;
2756
+ this.operationQueue.cancelPending(reason);
2757
+ this.controller.abort(reason);
2758
+ }
2759
+ });
2760
+ return;
2761
+ }
2762
+ this.pool = new WorkerPool({
2763
+ name: task.id,
2764
+ url: (_b2 = target.url) == null ? void 0 : _b2.toString(),
2765
+ loadWorker: target.create,
2766
+ workerType: "module",
2767
+ maxConcurrency: 1,
2768
+ maxMobileConcurrency: 1
2769
+ });
2770
+ this.descriptor = {
2771
+ id: task.id,
2772
+ name: task.id,
2773
+ module: "tasks",
2774
+ version: "prototype",
2775
+ options: {},
2776
+ worker: ((_c2 = target.url) == null ? void 0 : _c2.toString()) ?? true,
2777
+ loadWorker: target.create,
2778
+ workerInBatches: target.capabilities.streaming
2779
+ };
2780
+ }
2781
+ }
2782
+ /** @internal */
2783
+ async initialize(input, controls) {
2784
+ try {
2785
+ assertPayload(input);
2786
+ await this.enqueue(() => this.invoke("initialize", input, {}, controls));
2787
+ } catch (error) {
2788
+ await this.terminate(error);
2789
+ throw error;
2790
+ }
2791
+ }
2792
+ runTask(input, ...args) {
2793
+ var _a2, _b2, _c2, _d, _e;
2794
+ if (this.invalid)
2795
+ return Promise.reject(new Error("Initialized task is invalid; initialize a new instance"));
2796
+ if (this.closed)
2797
+ return Promise.reject(new Error("Initialized task is closed"));
2798
+ const timeout = (_a2 = args[0]) == null ? void 0 : _a2.timeout;
2799
+ if (timeout !== void 0 && (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > 4294967295)) {
2800
+ return Promise.reject(new RangeError("Invalid task timeout"));
2801
+ }
2802
+ const deadline = timeout === void 0 ? void 0 : AbortSignal.timeout(timeout);
2803
+ const signal = deadline && ((_b2 = args[0]) == null ? void 0 : _b2.signal) ? AbortSignal.any([deadline, args[0].signal]) : deadline ?? ((_c2 = args[0]) == null ? void 0 : _c2.signal);
2804
+ const controls = { ...args[0], signal };
2805
+ const mode = ((_e = (_d = this.task.concurrency) == null ? void 0 : _d.getSchedulingMode) == null ? void 0 : _e.call(_d, input)) ?? "exclusive";
2806
+ return this.operationQueue.run(mode, async () => {
2807
+ var _a3;
2808
+ signal == null ? void 0 : signal.throwIfAborted();
2809
+ this.checkCapability("atomic");
2810
+ const invalidate = () => {
2811
+ if (this.concurrent) {
2812
+ this.invalid = true;
2813
+ this.operationQueue.cancelPending(signal == null ? void 0 : signal.reason);
2814
+ this.controller.abort(signal == null ? void 0 : signal.reason);
2815
+ }
2816
+ };
2817
+ signal == null ? void 0 : signal.addEventListener("abort", invalidate, { once: true });
2818
+ try {
2819
+ return await this.invoke("process", input, ((_a3 = args[0]) == null ? void 0 : _a3.options) ?? {}, controls);
2820
+ } finally {
2821
+ signal == null ? void 0 : signal.removeEventListener("abort", invalidate);
2822
+ }
2823
+ }, signal);
2824
+ }
2825
+ /** Independent calls sharing this instance, always serial and in input order. */
2826
+ runTasks(inputs, ...args) {
2827
+ var _a2;
2828
+ return this.serialStream(async function* (self2) {
2829
+ var _a3;
2830
+ self2.checkCapability("atomic");
2831
+ for await (const input of asAsync(inputs, self2.controls(args[0]).signal)) {
2832
+ yield await self2.invoke("process", input, ((_a3 = args[0]) == null ? void 0 : _a3.options) ?? {}, args[0]);
2833
+ }
2834
+ }, (_a2 = args[0]) == null ? void 0 : _a2.signal);
2835
+ }
2836
+ /** One processor invocation for the entire input iterable. */
2837
+ runTaskInBatches(inputs, ...args) {
2838
+ var _a2;
2839
+ return this.serialStream(async function* (self2) {
2840
+ var _a3, _b2, _c2, _d;
2841
+ self2.checkCapability("streaming");
2842
+ const controls = self2.controls(args[0]);
2843
+ const options = clonePayload(((_a3 = args[0]) == null ? void 0 : _a3.options) ?? {});
2844
+ async function* prepared() {
2845
+ var _a4, _b3;
2846
+ for await (const input of asAsync(inputs, controls.signal)) {
2847
+ (_a4 = controls.signal) == null ? void 0 : _a4.throwIfAborted();
2848
+ assertNoTransferAlias(input, ((_b3 = args[0]) == null ? void 0 : _b3.options) ?? {}, controls.inputOwnership);
2849
+ yield clonePayload(input, controls.inputOwnership);
2850
+ }
2851
+ }
2852
+ let completed = false;
2853
+ try {
2854
+ if (self2.workerChannel) {
2855
+ self2.channelInputs = prepared()[Symbol.asyncIterator]();
2856
+ self2.streamProgress = controls.onProgress;
2857
+ try {
2858
+ await self2.invoke("stream-open", {}, options, controls);
2859
+ while (true) {
2860
+ const result = await self2.invoke("stream-next", {}, {}, controls);
2861
+ if (result.done)
2862
+ break;
2863
+ yield result.value;
2864
+ }
2865
+ } finally {
2866
+ try {
2867
+ if (!self2.invalid)
2868
+ await self2.invoke("stream-close", {}, {}, controls);
2869
+ } finally {
2870
+ await ((_c2 = (_b2 = self2.channelInputs).return) == null ? void 0 : _c2.call(_b2));
2871
+ self2.channelInputs = void 0;
2872
+ self2.streamProgress = void 0;
2873
+ if (self2.streamProgressId !== void 0)
2874
+ self2.callbackFailures.delete(self2.streamProgressId);
2875
+ self2.streamProgressId = void 0;
2876
+ }
2877
+ }
2878
+ } else if (self2.pool) {
2879
+ await self2.invoke("stream-options", {}, options, controls);
2880
+ yield* processOnWorkerInBatches(self2.descriptor, prepared(), {
2881
+ ...self2.workerOptions(controls),
2882
+ inputOwnership: "transfer",
2883
+ workerInBatches: true
2884
+ });
2885
+ } else {
2886
+ for await (const output of self2.runtime.stream(prepared(), options, self2.runtimeContext(controls))) {
2887
+ (_d = controls.signal) == null ? void 0 : _d.throwIfAborted();
2888
+ yield clonePayload(output, controls.outputOwnership ?? "transfer");
2889
+ }
2890
+ }
2891
+ completed = true;
2892
+ } catch (error) {
2893
+ if (self2.workerChannel) {
2894
+ self2.invalid = true;
2895
+ self2.operationQueue.cancelPending(error);
2896
+ self2.controller.abort(error);
2897
+ await self2.workerChannel.destroy(error);
2898
+ }
2899
+ if (self2.pool) {
2900
+ self2.invalid = true;
2901
+ await self2.pool.destroy(error);
2902
+ }
2903
+ throw error;
2904
+ } finally {
2905
+ if (self2.pool && !completed)
2906
+ self2.invalid = true;
2907
+ if (self2.workerChannel && !completed && !self2.invalid) {
2908
+ const reason = new Error("Worker stream ended before completion");
2909
+ self2.invalid = true;
2910
+ self2.operationQueue.cancelPending(reason);
2911
+ self2.controller.abort(reason);
2912
+ await self2.workerChannel.destroy(reason);
2913
+ }
2914
+ }
2915
+ }, (_a2 = args[0]) == null ? void 0 : _a2.signal);
2916
+ }
2917
+ /** Lifecycle status of this initialized task. */
2918
+ get state() {
2919
+ if (this.invalid)
2920
+ return "invalid";
2921
+ if (this.finalized)
2922
+ return "closed";
2923
+ return this.closed ? "closing" : "ready";
2924
+ }
2925
+ /** Drain accepted work, invoke destroy, and release execution capacity. */
2926
+ close() {
2927
+ if (!this.closing) {
2928
+ this.closed = true;
2929
+ this.closing = (async () => {
2930
+ var _a2, _b2;
2931
+ try {
2932
+ await this.operationQueue.close();
2933
+ if (!this.invalid)
2934
+ await this.invoke("destroy", {}, {});
2935
+ else if (!this.pool && !this.workerChannel)
2936
+ await this.runtime.destroy();
2937
+ } finally {
2938
+ try {
2939
+ await ((_a2 = this.pool) == null ? void 0 : _a2.destroy());
2940
+ await ((_b2 = this.workerChannel) == null ? void 0 : _b2.destroy());
2941
+ } finally {
2942
+ this.finalized = true;
2943
+ this.release();
2944
+ }
2945
+ }
2946
+ })();
2947
+ }
2948
+ return this.closing;
2949
+ }
2950
+ /** Abort work. Local JavaScript must settle before its state can be destroyed. */
2951
+ async terminate(reason = new Error("Task terminated")) {
2952
+ this.operationQueue.cancelPending(reason);
2953
+ this.controller.abort(reason);
2954
+ if (this.workerChannel) {
2955
+ this.invalid = true;
2956
+ await this.workerChannel.destroy(reason);
2957
+ }
2958
+ if (this.pool) {
2959
+ this.invalid = true;
2960
+ await this.pool.destroy(reason);
2961
+ }
2962
+ await Promise.allSettled([...this.streams].map((stop) => stop()));
2963
+ await this.close();
2964
+ }
2965
+ checkCapability(kind) {
2966
+ var _a2;
2967
+ if (this.pool || this.workerChannel ? !((_a2 = this.task.worker) == null ? void 0 : _a2.capabilities[kind]) : !(kind === "atomic" ? this.task.process : this.task.processInBatches)) {
2968
+ throw new Error(`Task has no ${kind} processor for this execution route`);
2969
+ }
2970
+ }
2971
+ controls(controls = {}) {
2972
+ if (controls.outputOwnership && !["copy", "transfer"].includes(controls.outputOwnership))
2973
+ throw new TypeError("Invalid output ownership");
2974
+ return {
2975
+ ...controls,
2976
+ signal: controls.signal ? AbortSignal.any([controls.signal, this.controller.signal]) : this.controller.signal
2977
+ };
2978
+ }
2979
+ workerOptions(controls) {
2980
+ return {
2981
+ workerPool: this.pool,
2982
+ workerType: "module",
2983
+ inputOwnership: controls.inputOwnership ?? "copy",
2984
+ outputOwnership: controls.outputOwnership ?? "transfer",
2985
+ signal: controls.signal,
2986
+ onProgress: controls.onProgress,
2987
+ cancellationMode: "terminate"
2988
+ };
2989
+ }
2990
+ async invoke(operation, input, options, controls = {}) {
2991
+ var _a2, _b2, _c2, _d;
2992
+ if (this.invalid)
2993
+ throw new Error("Initialized task is invalid; initialize a new instance");
2994
+ const prepared = operation === "destroy" ? {} : this.controls(controls);
2995
+ (_a2 = prepared.signal) == null ? void 0 : _a2.throwIfAborted();
2996
+ assertPayload(input);
2997
+ assertNoTransferAlias(input, options, prepared.inputOwnership);
2998
+ const copiedOptions = clonePayload(options);
2999
+ if (this.workerChannel) {
3000
+ const progressId = this.nextProgressId++;
3001
+ const request = {
3002
+ input: clonePayload(input, prepared.inputOwnership),
3003
+ options: copiedOptions,
3004
+ outputOwnership: prepared.outputOwnership ?? "transfer",
3005
+ progressId
3006
+ };
3007
+ if (operation === "stream-open")
3008
+ this.streamProgressId = progressId;
3009
+ this.progressCallbacks.set(progressId, prepared.onProgress);
3010
+ let callbackFailure;
3011
+ try {
3012
+ const result2 = await this.workerChannel.channel.request(operation, request, prepared.signal, getTransferList(request));
3013
+ callbackFailure = this.callbackFailures.get(progressId) ?? (operation.startsWith("stream-") && this.streamProgressId !== void 0 ? this.callbackFailures.get(this.streamProgressId) : void 0);
3014
+ if (callbackFailure)
3015
+ throw callbackFailure.reason;
3016
+ return result2;
3017
+ } catch (reason) {
3018
+ if (operation === "process" && !((_b2 = prepared.signal) == null ? void 0 : _b2.aborted) && (reason instanceof TaskRequestError || callbackFailure))
3019
+ throw reason;
3020
+ this.invalid = true;
3021
+ this.operationQueue.cancelPending(reason);
3022
+ this.controller.abort(reason);
3023
+ await this.workerChannel.destroy(reason);
3024
+ throw reason;
3025
+ } finally {
3026
+ this.progressCallbacks.delete(progressId);
3027
+ if (this.streamProgressId !== progressId)
3028
+ this.callbackFailures.delete(progressId);
3029
+ }
3030
+ }
3031
+ if (this.pool) {
3032
+ try {
3033
+ return await processOnWorker(this.descriptor, { operation, input: clonePayload(input, prepared.inputOwnership), options: copiedOptions }, this.workerOptions({ ...prepared, inputOwnership: "transfer" }));
3034
+ } catch (error) {
3035
+ this.invalid = true;
3036
+ await this.pool.destroy(error);
3037
+ throw error;
3038
+ }
3039
+ }
3040
+ if (operation === "destroy")
3041
+ return this.runtime.destroy();
3042
+ const copied = clonePayload(input, prepared.inputOwnership);
3043
+ const context = this.runtimeContext(prepared);
3044
+ if (operation === "initialize") {
3045
+ const result2 = await this.runtime.initialize(copied, context);
3046
+ (_c2 = prepared.signal) == null ? void 0 : _c2.throwIfAborted();
3047
+ return result2;
3048
+ }
3049
+ const result = await this.runtime.process(copied, copiedOptions, context);
3050
+ (_d = prepared.signal) == null ? void 0 : _d.throwIfAborted();
3051
+ return clonePayload(result, prepared.outputOwnership ?? "transfer");
3052
+ }
3053
+ runtimeContext(prepared) {
3054
+ return {
3055
+ ...localContext(prepared),
3056
+ requestHost: async (operation, payload, controls = {}) => {
3057
+ const signal = prepared.signal ?? this.controller.signal;
3058
+ signal.throwIfAborted();
3059
+ const handler = this.initializationControls.onRequest;
3060
+ if (!handler)
3061
+ throw new Error("No host request handler configured");
3062
+ const result = await handler(operation, clonePayload(payload, controls.inputOwnership), signal);
3063
+ signal.throwIfAborted();
3064
+ return structuredClone(result, {
3065
+ transfer: controls.outputOwnership === "transfer" ? getTransferList(result) : []
3066
+ });
3067
+ },
3068
+ emitHost: (operation, payload) => {
3069
+ var _a2, _b2;
3070
+ return (_b2 = (_a2 = this.initializationControls).onEvent) == null ? void 0 : _b2.call(_a2, operation, structuredClone(payload));
3071
+ }
3072
+ };
3073
+ }
3074
+ enqueue(operation) {
3075
+ if (this.closed)
3076
+ return Promise.reject(new Error("Initialized task is closed"));
3077
+ return this.operationQueue.run("exclusive", operation);
3078
+ }
3079
+ serialStream(operation, signal) {
3080
+ const waiting = new AbortController();
3081
+ const queueSignal = AbortSignal.any([waiting.signal, this.controller.signal, signal].filter((value) => Boolean(value)));
3082
+ let started = false;
3083
+ const iterator = this.acquireStream(operation, queueSignal, () => {
3084
+ started = true;
3085
+ });
3086
+ const cancelWaiting = () => {
3087
+ if (!started)
3088
+ waiting.abort(new Error("Stream returned before execution"));
3089
+ };
3090
+ return {
3091
+ [Symbol.asyncIterator]() {
3092
+ return this;
3093
+ },
3094
+ next: () => iterator.next(),
3095
+ return: async () => {
3096
+ cancelWaiting();
3097
+ return iterator.return(void 0);
3098
+ },
3099
+ throw: async (reason) => {
3100
+ cancelWaiting();
3101
+ return iterator.throw(reason);
3102
+ }
3103
+ };
3104
+ }
3105
+ async *acquireStream(operation, signal, onStart) {
3106
+ if (this.closed)
3107
+ throw new Error("Initialized task is closed");
3108
+ let acquire;
3109
+ const acquired = new Promise((resolve) => {
3110
+ acquire = resolve;
3111
+ });
3112
+ let release;
3113
+ const held = new Promise((resolve) => {
3114
+ release = resolve;
3115
+ });
3116
+ const lease = this.operationQueue.run("exclusive", async () => {
3117
+ acquire();
3118
+ await held;
3119
+ }, signal);
3120
+ await Promise.race([acquired, lease]);
3121
+ if (signal.aborted) {
3122
+ release();
3123
+ throw signal.reason;
3124
+ }
3125
+ onStart();
3126
+ const iterator = operation(this)[Symbol.asyncIterator]();
3127
+ let stopping;
3128
+ const stop = () => {
3129
+ stopping ?? (stopping = (async () => {
3130
+ var _a2;
3131
+ try {
3132
+ await ((_a2 = iterator.return) == null ? void 0 : _a2.call(iterator));
3133
+ } finally {
3134
+ this.streams.delete(stop);
3135
+ release();
3136
+ }
3137
+ })());
3138
+ return stopping;
3139
+ };
3140
+ this.streams.add(stop);
3141
+ try {
3142
+ while (true) {
3143
+ this.controller.signal.throwIfAborted();
3144
+ const next = await iterator.next();
3145
+ if (next.done)
3146
+ return;
3147
+ yield next.value;
3148
+ }
3149
+ } finally {
3150
+ await stop();
3151
+ }
3152
+ }
3153
+ };
3154
+ var TaskRunner = class {
3155
+ constructor(options = {}) {
3156
+ this.active = /* @__PURE__ */ new Set();
3157
+ this.count = 0;
3158
+ this.waiters = [];
3159
+ this.closed = false;
3160
+ this.initializing = /* @__PURE__ */ new Set();
3161
+ this.iterations = /* @__PURE__ */ new Set();
3162
+ this.maxConcurrency = options.maxConcurrency ?? 1;
3163
+ if (!Number.isSafeInteger(this.maxConcurrency) || this.maxConcurrency < 1)
3164
+ throw new RangeError("maxConcurrency must be a positive safe integer");
3165
+ }
3166
+ /** Execute synchronous hooks immediately on the calling thread, without queueing. */
3167
+ runTaskSync(task, input, ...args) {
3168
+ if (this.closed)
3169
+ throw new Error("Task runner is closed");
3170
+ if (this.count >= this.maxConcurrency)
3171
+ throw new Error("Task runner has no synchronous capacity");
3172
+ this.count++;
3173
+ try {
3174
+ return runTaskSync(task, input, args[0]);
3175
+ } finally {
3176
+ const waiter = this.waiters.shift();
3177
+ if (waiter)
3178
+ waiter.resolve();
3179
+ else
3180
+ this.count--;
3181
+ }
3182
+ }
3183
+ initializeTask(task, initialization, controls = {}) {
3184
+ const pending2 = this.open(task, initialization, controls);
3185
+ this.initializing.add(pending2);
3186
+ void pending2.then(() => this.initializing.delete(pending2), () => this.initializing.delete(pending2));
3187
+ return pending2;
3188
+ }
3189
+ async runTask(task, input, ...args) {
3190
+ const request = args[0] ?? {};
3191
+ const handle = await this.initializeTask(task, request.initialization ?? {}, {
3192
+ ...request,
3193
+ inputOwnership: request.initializationOwnership ?? "copy"
3194
+ });
3195
+ return finish(handle, () => handle.runTask(input, request));
3196
+ }
3197
+ async *runTasks(task, inputs, ...args) {
3198
+ var _a2;
3199
+ const request = args[0] ?? {};
3200
+ if (this.closed)
3201
+ throw new Error("Task runner is closed");
3202
+ if (request.initializationOwnership === "transfer")
3203
+ throw new TypeError("runTasks initialization is a reusable template; use copy or share");
3204
+ const concurrency = request.concurrency ?? 1;
3205
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > this.maxConcurrency)
3206
+ throw new RangeError("concurrency must be between 1 and maxConcurrency");
3207
+ const handles = [];
3208
+ const busy = /* @__PURE__ */ new Set();
3209
+ const pending2 = [];
3210
+ const controller = new AbortController();
3211
+ this.iterations.add(controller);
3212
+ const signal = request.signal ? AbortSignal.any([request.signal, controller.signal]) : controller.signal;
3213
+ const iterator = asAsync(inputs, signal)[Symbol.asyncIterator]();
3214
+ let finished = false;
3215
+ let reading;
3216
+ try {
3217
+ while (!finished || pending2.length) {
3218
+ signal.throwIfAborted();
3219
+ if (!finished && !reading && pending2.length < concurrency) {
3220
+ reading = iterator.next().then((next) => ({ kind: "input", next }));
3221
+ }
3222
+ const event = await Promise.race([
3223
+ ...pending2.length ? [pending2[0]] : [],
3224
+ ...reading ? [reading] : []
3225
+ ]);
3226
+ if (event.kind === "result") {
3227
+ pending2.shift();
3228
+ busy.delete(event.handle);
3229
+ if (event.failed)
3230
+ throw event.error;
3231
+ yield event.value;
3232
+ continue;
3233
+ }
3234
+ reading = void 0;
3235
+ if (event.next.done) {
3236
+ finished = true;
3237
+ continue;
3238
+ }
3239
+ let handle = handles.find((candidate) => !busy.has(candidate));
3240
+ if (!handle && (handles.length === 0 || this.count < this.maxConcurrency)) {
3241
+ handle = await this.initializeTask(task, clonePayload(request.initialization ?? {}, request.initializationOwnership), {
3242
+ ...request,
3243
+ signal,
3244
+ inputOwnership: request.initializationOwnership ?? "copy"
3245
+ });
3246
+ handles.push(handle);
3247
+ }
3248
+ if (!handle) {
3249
+ const result = await pending2.shift();
3250
+ busy.delete(result.handle);
3251
+ if (result.failed)
3252
+ throw result.error;
3253
+ yield result.value;
3254
+ handle = result.handle;
3255
+ }
3256
+ busy.add(handle);
3257
+ const current = handle;
3258
+ pending2.push(handle.runTask(event.next.value, { ...request, signal }).then((value) => ({ kind: "result", handle: current, value }), (error) => ({ kind: "result", handle: current, failed: true, error })));
3259
+ }
3260
+ } finally {
3261
+ this.iterations.delete(controller);
3262
+ controller.abort(new Error("Task iteration closed"));
3263
+ try {
3264
+ if (reading)
3265
+ await reading.catch(() => {
3266
+ });
3267
+ if (!finished)
3268
+ await ((_a2 = iterator.return) == null ? void 0 : _a2.call(iterator));
3269
+ } finally {
3270
+ await Promise.all(pending2);
3271
+ await Promise.all(handles.map((handle) => handle.close()));
3272
+ }
3273
+ }
3274
+ }
3275
+ async *runTaskInBatches(task, inputs, ...args) {
3276
+ const request = args[0] ?? {};
3277
+ const handle = await this.initializeTask(task, request.initialization ?? {}, {
3278
+ ...request,
3279
+ inputOwnership: request.initializationOwnership ?? "copy"
3280
+ });
3281
+ try {
3282
+ yield* handle.runTaskInBatches(inputs, request);
3283
+ } finally {
3284
+ await handle.close();
3285
+ }
3286
+ }
3287
+ /** Close owned handles and workers. Finish or return active iterators first. */
3288
+ close() {
3289
+ if (!this.closing) {
3290
+ this.closed = true;
3291
+ for (const waiter of this.waiters.splice(0))
3292
+ waiter.reject(new Error("Task runner is closed"));
3293
+ this.closing = (async () => {
3294
+ await Promise.allSettled(this.initializing);
3295
+ const results = await Promise.allSettled([...this.active].map((handle) => handle.close()));
3296
+ const failure = results.find((result) => result.status === "rejected");
3297
+ if ((failure == null ? void 0 : failure.status) === "rejected")
3298
+ throw failure.reason;
3299
+ })();
3300
+ }
3301
+ return this.closing;
3302
+ }
3303
+ async terminate(reason = new Error("Task runner terminated")) {
3304
+ for (const controller of this.iterations)
3305
+ controller.abort(reason);
3306
+ const closing = this.close();
3307
+ await Promise.allSettled([...this.active].map((handle) => handle.terminate(reason)));
3308
+ await closing;
3309
+ }
3310
+ async open(task, initialization, controls) {
3311
+ var _a2;
3312
+ if (this.closed)
3313
+ throw new Error("Task runner is closed");
3314
+ (_a2 = controls.signal) == null ? void 0 : _a2.throwIfAborted();
3315
+ if (this.count >= this.maxConcurrency) {
3316
+ await new Promise((resolve, reject) => {
3317
+ var _a3, _b2;
3318
+ const waiter = {
3319
+ resolve: () => {
3320
+ cleanup();
3321
+ resolve();
3322
+ },
3323
+ reject: (error) => {
3324
+ cleanup();
3325
+ reject(error);
3326
+ }
3327
+ };
3328
+ const abort = () => {
3329
+ var _a4;
3330
+ this.waiters = this.waiters.filter((item) => item !== waiter);
3331
+ waiter.reject((_a4 = controls.signal) == null ? void 0 : _a4.reason);
3332
+ };
3333
+ const cleanup = () => {
3334
+ var _a4;
3335
+ return (_a4 = controls.signal) == null ? void 0 : _a4.removeEventListener("abort", abort);
3336
+ };
3337
+ this.waiters.push(waiter);
3338
+ (_a3 = controls.signal) == null ? void 0 : _a3.addEventListener("abort", abort, { once: true });
3339
+ if ((_b2 = controls.signal) == null ? void 0 : _b2.aborted)
3340
+ abort();
3341
+ });
3342
+ } else
3343
+ this.count++;
3344
+ let handle;
3345
+ let released = false;
3346
+ const release = () => {
3347
+ if (released)
3348
+ return;
3349
+ released = true;
3350
+ if (handle)
3351
+ this.active.delete(handle);
3352
+ const waiter = this.waiters.shift();
3353
+ if (waiter)
3354
+ waiter.resolve();
3355
+ else
3356
+ this.count--;
3357
+ };
3358
+ try {
3359
+ if (this.closed)
3360
+ throw new Error("Task runner is closed");
3361
+ handle = new InitializedTask(task, release, controls);
3362
+ this.active.add(handle);
3363
+ await handle.initialize(initialization, controls);
3364
+ return handle;
3365
+ } catch (error) {
3366
+ release();
3367
+ throw error;
3368
+ }
3369
+ }
3370
+ };
3371
+ async function finish(handle, operation) {
3372
+ let result;
3373
+ try {
3374
+ result = await operation();
3375
+ } catch (error) {
3376
+ try {
3377
+ await handle.close();
3378
+ } catch (cleanup) {
3379
+ throw new AggregateError([error, cleanup], "Task processing and destruction failed");
3380
+ }
3381
+ throw error;
3382
+ }
3383
+ await handle.close();
3384
+ return result;
3385
+ }
3386
+ async function* asAsync(inputs, signal) {
3387
+ var _a2, _b2;
3388
+ const iterator = Symbol.asyncIterator in inputs ? inputs[Symbol.asyncIterator]() : inputs[Symbol.iterator]();
3389
+ let done = false;
3390
+ let blocked = false;
3391
+ try {
3392
+ while (true) {
3393
+ const next = await new Promise((resolve, reject) => {
3394
+ const cleanup = () => signal == null ? void 0 : signal.removeEventListener("abort", abort);
3395
+ const abort = () => {
3396
+ cleanup();
3397
+ reject(signal == null ? void 0 : signal.reason);
3398
+ };
3399
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
3400
+ if (signal == null ? void 0 : signal.aborted) {
3401
+ abort();
3402
+ return;
3403
+ }
3404
+ try {
3405
+ blocked = true;
3406
+ Promise.resolve(iterator.next()).then((value) => {
3407
+ blocked = false;
3408
+ cleanup();
3409
+ resolve(value);
3410
+ }, (error) => {
3411
+ blocked = false;
3412
+ cleanup();
3413
+ reject(error);
3414
+ });
3415
+ } catch (error) {
3416
+ blocked = false;
3417
+ cleanup();
3418
+ reject(error);
3419
+ }
3420
+ });
3421
+ if (next.done) {
3422
+ done = true;
3423
+ return;
3424
+ }
3425
+ yield next.value;
3426
+ }
3427
+ } finally {
3428
+ if (!done) {
3429
+ if (blocked) {
3430
+ try {
3431
+ void Promise.resolve((_a2 = iterator.return) == null ? void 0 : _a2.call(iterator)).catch(() => {
3432
+ });
3433
+ } catch {
3434
+ }
3435
+ } else {
3436
+ await ((_b2 = iterator.return) == null ? void 0 : _b2.call(iterator));
3437
+ }
3438
+ }
3439
+ }
3440
+ }
3441
+ function assertNoTransferAlias(input, options, ownership) {
3442
+ if (ownership === "transfer") {
3443
+ const metadata = new Set(getTransferList(options));
3444
+ if (getTransferList(input).some((buffer) => metadata.has(buffer))) {
3445
+ throw new Error("Transferred input aliases reusable options; use inputOwnership: copy");
3446
+ }
3447
+ }
3448
+ }
3449
+
3450
+ // dist/tasks/typed-task-dispatch.js
3451
+ function createTypedTaskDispatcher(transport) {
3452
+ return transport;
3453
+ }
3454
+ //# sourceMappingURL=index.cjs.map