threadsx 2.0.2 → 2.1.0

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 (53) hide show
  1. package/dist/errors.d.ts +16 -0
  2. package/dist/errors.js +31 -0
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +3 -1
  5. package/dist/master/implementation.node.js +22 -2
  6. package/dist/master/invocation-proxy.js +45 -11
  7. package/dist/master/pool.d.ts +1 -24
  8. package/dist/master/pool.js +25 -3
  9. package/dist/transferable.d.ts +1 -0
  10. package/dist/types/master.d.ts +22 -1
  11. package/dist/types/master.js +0 -1
  12. package/dist/types/worker.d.ts +1 -0
  13. package/dist/worker/implementation.browser.d.ts +1 -1
  14. package/dist/worker/implementation.worker_threads.d.ts +1 -1
  15. package/dist-esm/errors.js +26 -0
  16. package/dist-esm/index.js +1 -0
  17. package/dist-esm/master/implementation.node.js +22 -2
  18. package/dist-esm/master/invocation-proxy.js +45 -11
  19. package/dist-esm/master/pool.js +25 -3
  20. package/dist-esm/types/master.js +0 -1
  21. package/esm/common.mjs +20 -0
  22. package/esm/errors.mjs +34 -0
  23. package/esm/index.mjs +16 -0
  24. package/esm/master/get-bundle-url.browser.mjs +32 -0
  25. package/esm/master/implementation.browser.mjs +76 -0
  26. package/esm/master/implementation.mjs +24 -0
  27. package/esm/master/implementation.node.mjs +190 -0
  28. package/esm/master/index.mjs +17 -0
  29. package/esm/master/invocation-proxy.mjs +164 -0
  30. package/esm/master/pool-types.mjs +20 -0
  31. package/esm/master/pool.mjs +313 -0
  32. package/esm/master/register.mjs +14 -0
  33. package/esm/master/spawn.mjs +162 -0
  34. package/esm/master/thread.mjs +28 -0
  35. package/esm/observable-promise.mjs +155 -0
  36. package/esm/observable.mjs +45 -0
  37. package/esm/ponyfills.mjs +26 -0
  38. package/esm/promise.mjs +32 -0
  39. package/esm/serializers.mjs +55 -0
  40. package/esm/symbols.mjs +13 -0
  41. package/esm/transferable.mjs +31 -0
  42. package/esm/types/master.mjs +15 -0
  43. package/esm/types/messages.mjs +25 -0
  44. package/esm/worker/implementation.browser.mjs +31 -0
  45. package/esm/worker/implementation.mjs +22 -0
  46. package/esm/worker/implementation.worker_threads.mjs +46 -0
  47. package/esm/worker/index.mjs +224 -0
  48. package/esm/worker_threads.mjs +21 -0
  49. package/package.json +20 -20
  50. package/index.mjs +0 -4
  51. package/observable.mjs +0 -1
  52. package/register.mjs +0 -2
  53. package/worker.mjs +0 -1
@@ -0,0 +1,45 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ import { Observable } from 'observable-fns';
8
+ export { Observable } from 'observable-fns';
9
+
10
+ const $observers = Symbol("observers");
11
+ /**
12
+ * Observable subject. Implements the Observable interface, but also exposes
13
+ * the `next()`, `error()`, `complete()` methods to initiate observable
14
+ * updates "from the outside".
15
+ *
16
+ * Use `Observable.from(subject)` to derive an observable that proxies all
17
+ * values, errors and the completion raised on this subject, but does not
18
+ * expose the `next()`, `error()`, `complete()` methods.
19
+ */
20
+ class Subject extends Observable {
21
+ constructor() {
22
+ super(observer => {
23
+ this[$observers] = [
24
+ ...(this[$observers] || []),
25
+ observer
26
+ ];
27
+ const unsubscribe = () => {
28
+ this[$observers] = this[$observers].filter(someObserver => someObserver !== observer);
29
+ };
30
+ return unsubscribe;
31
+ });
32
+ this[$observers] = [];
33
+ }
34
+ complete() {
35
+ this[$observers].forEach(observer => observer.complete());
36
+ }
37
+ error(error) {
38
+ this[$observers].forEach(observer => observer.error(error));
39
+ }
40
+ next(value) {
41
+ this[$observers].forEach(observer => observer.next(value));
42
+ }
43
+ }
44
+
45
+ export { Subject };
@@ -0,0 +1,26 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ // Based on <https://github.com/es-shims/Promise.allSettled/blob/master/implementation.js>
8
+ function allSettled(values) {
9
+ return Promise.all(values.map(item => {
10
+ const onFulfill = (value) => {
11
+ return { status: 'fulfilled', value };
12
+ };
13
+ const onReject = (reason) => {
14
+ return { status: 'rejected', reason };
15
+ };
16
+ const itemPromise = Promise.resolve(item);
17
+ try {
18
+ return itemPromise.then(onFulfill, onReject);
19
+ }
20
+ catch (error) {
21
+ return Promise.reject(error);
22
+ }
23
+ }));
24
+ }
25
+
26
+ export { allSettled };
@@ -0,0 +1,32 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ const doNothing = () => undefined;
8
+ /**
9
+ * Creates a new promise and exposes its resolver function.
10
+ * Use with care!
11
+ */
12
+ function createPromiseWithResolver() {
13
+ let alreadyResolved = false;
14
+ let resolvedTo;
15
+ let resolver = doNothing;
16
+ const promise = new Promise(resolve => {
17
+ if (alreadyResolved) {
18
+ resolve(resolvedTo);
19
+ }
20
+ else {
21
+ resolver = resolve;
22
+ }
23
+ });
24
+ const exposedResolver = (value) => {
25
+ alreadyResolved = true;
26
+ resolvedTo = value;
27
+ resolver(resolvedTo);
28
+ };
29
+ return [promise, exposedResolver];
30
+ }
31
+
32
+ export { createPromiseWithResolver };
@@ -0,0 +1,55 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ function extendSerializer(extend, implementation) {
8
+ const fallbackDeserializer = extend.deserialize.bind(extend);
9
+ const fallbackSerializer = extend.serialize.bind(extend);
10
+ return {
11
+ deserialize(message) {
12
+ return implementation.deserialize(message, fallbackDeserializer);
13
+ },
14
+ serialize(input) {
15
+ return implementation.serialize(input, fallbackSerializer);
16
+ }
17
+ };
18
+ }
19
+ const DefaultErrorSerializer = {
20
+ deserialize(message) {
21
+ return Object.assign(Error(message.message), {
22
+ name: message.name,
23
+ stack: message.stack
24
+ });
25
+ },
26
+ serialize(error) {
27
+ return {
28
+ __error_marker: "$$error",
29
+ message: error.message,
30
+ name: error.name,
31
+ stack: error.stack
32
+ };
33
+ }
34
+ };
35
+ const isSerializedError = (thing) => thing && typeof thing === "object" && "__error_marker" in thing && thing.__error_marker === "$$error";
36
+ const DefaultSerializer = {
37
+ deserialize(message) {
38
+ if (isSerializedError(message)) {
39
+ return DefaultErrorSerializer.deserialize(message);
40
+ }
41
+ else {
42
+ return message;
43
+ }
44
+ },
45
+ serialize(input) {
46
+ if (input instanceof Error) {
47
+ return DefaultErrorSerializer.serialize(input);
48
+ }
49
+ else {
50
+ return input;
51
+ }
52
+ }
53
+ };
54
+
55
+ export { DefaultSerializer, extendSerializer };
@@ -0,0 +1,13 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ const $errors = Symbol("thread.errors");
8
+ const $events = Symbol("thread.events");
9
+ const $terminate = Symbol("thread.terminate");
10
+ const $transferable = Symbol("thread.transferable");
11
+ const $worker = Symbol("thread.worker");
12
+
13
+ export { $errors, $events, $terminate, $transferable, $worker };
@@ -0,0 +1,31 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ import { $transferable } from './symbols.mjs';
8
+
9
+ function isTransferable(thing) {
10
+ if (!thing || typeof thing !== "object")
11
+ return false;
12
+ // Don't check too thoroughly, since the list of transferable things in JS might grow over time
13
+ return true;
14
+ }
15
+ function isTransferDescriptor(thing) {
16
+ return thing && typeof thing === "object" && thing[$transferable];
17
+ }
18
+ function Transfer(payload, transferables) {
19
+ if (!transferables) {
20
+ if (!isTransferable(payload))
21
+ throw Error();
22
+ transferables = [payload];
23
+ }
24
+ return {
25
+ [$transferable]: true,
26
+ send: payload,
27
+ transferables
28
+ };
29
+ }
30
+
31
+ export { Transfer, isTransferDescriptor };
@@ -0,0 +1,15 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ /** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
8
+ var WorkerEventType;
9
+ (function (WorkerEventType) {
10
+ WorkerEventType["internalError"] = "internalError";
11
+ WorkerEventType["message"] = "message";
12
+ WorkerEventType["termination"] = "termination";
13
+ })(WorkerEventType || (WorkerEventType = {}));
14
+
15
+ export { WorkerEventType };
@@ -0,0 +1,25 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ /////////////////////////////
8
+ // Messages sent by master:
9
+ var MasterMessageType;
10
+ (function (MasterMessageType) {
11
+ MasterMessageType["cancel"] = "cancel";
12
+ MasterMessageType["run"] = "run";
13
+ })(MasterMessageType || (MasterMessageType = {}));
14
+ ////////////////////////////
15
+ // Messages sent by worker:
16
+ var WorkerMessageType;
17
+ (function (WorkerMessageType) {
18
+ WorkerMessageType["error"] = "error";
19
+ WorkerMessageType["init"] = "init";
20
+ WorkerMessageType["result"] = "result";
21
+ WorkerMessageType["running"] = "running";
22
+ WorkerMessageType["uncaughtError"] = "uncaughtError";
23
+ })(WorkerMessageType || (WorkerMessageType = {}));
24
+
25
+ export { MasterMessageType, WorkerMessageType };
@@ -0,0 +1,31 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ /// <reference lib="dom" />
8
+ const isWorkerRuntime = function isWorkerRuntime() {
9
+ const isWindowContext = typeof self !== "undefined" && typeof Window !== "undefined" && self instanceof Window;
10
+ return typeof self !== "undefined" && typeof self.postMessage === "function" && !isWindowContext;
11
+ };
12
+ const postMessageToMaster = function postMessageToMaster(data, transferList) {
13
+ self.postMessage(data, transferList);
14
+ };
15
+ const subscribeToMasterMessages = function subscribeToMasterMessages(onMessage) {
16
+ const messageHandler = (messageEvent) => {
17
+ onMessage(messageEvent.data);
18
+ };
19
+ const unsubscribe = () => {
20
+ self.removeEventListener("message", messageHandler);
21
+ };
22
+ self.addEventListener("message", messageHandler);
23
+ return unsubscribe;
24
+ };
25
+ var WebWorkerImplementation = {
26
+ isWorkerRuntime,
27
+ postMessageToMaster,
28
+ subscribeToMasterMessages
29
+ };
30
+
31
+ export { WebWorkerImplementation as default };
@@ -0,0 +1,22 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ import WebWorkerImplementation from './implementation.browser.mjs';
8
+ import WorkerThreadsImplementation from './implementation.worker_threads.mjs';
9
+
10
+ /*
11
+ * This file is only a stub to make './implementation' resolve to the right module.
12
+ */
13
+ const runningInNode = typeof process !== 'undefined' && process.arch !== 'browser' && 'pid' in process;
14
+ function selectNodeImplementation() {
15
+ WorkerThreadsImplementation.testImplementation();
16
+ return WorkerThreadsImplementation;
17
+ }
18
+ var Implementation = runningInNode
19
+ ? selectNodeImplementation()
20
+ : WebWorkerImplementation;
21
+
22
+ export { Implementation as default };
@@ -0,0 +1,46 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ import getImplementation from '../worker_threads.mjs';
8
+
9
+ function assertMessagePort(port) {
10
+ if (!port) {
11
+ throw Error("Invariant violation: MessagePort to parent is not available.");
12
+ }
13
+ return port;
14
+ }
15
+ const isWorkerRuntime = function isWorkerRuntime() {
16
+ return !getImplementation().isMainThread;
17
+ };
18
+ const postMessageToMaster = function postMessageToMaster(data, transferList) {
19
+ assertMessagePort(getImplementation().parentPort).postMessage(data, transferList);
20
+ };
21
+ const subscribeToMasterMessages = function subscribeToMasterMessages(onMessage) {
22
+ const parentPort = getImplementation().parentPort;
23
+ if (!parentPort) {
24
+ throw Error("Invariant violation: MessagePort to parent is not available.");
25
+ }
26
+ const messageHandler = (message) => {
27
+ onMessage(message);
28
+ };
29
+ const unsubscribe = () => {
30
+ assertMessagePort(parentPort).off("message", messageHandler);
31
+ };
32
+ assertMessagePort(parentPort).on("message", messageHandler);
33
+ return unsubscribe;
34
+ };
35
+ function testImplementation() {
36
+ // Will throw if `worker_threads` are not available
37
+ getImplementation();
38
+ }
39
+ var WorkerThreadsImplementation = {
40
+ isWorkerRuntime,
41
+ postMessageToMaster,
42
+ subscribeToMasterMessages,
43
+ testImplementation
44
+ };
45
+
46
+ export { WorkerThreadsImplementation as default };
@@ -0,0 +1,224 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ import { serialize, deserialize } from '../common.mjs';
8
+ export { registerSerializer } from '../common.mjs';
9
+ import { isTransferDescriptor } from '../transferable.mjs';
10
+ export { Transfer } from '../transferable.mjs';
11
+ import { WorkerMessageType, MasterMessageType } from '../types/messages.mjs';
12
+ import Implementation from './implementation.mjs';
13
+
14
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
15
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
+ return new (P || (P = Promise))(function (resolve, reject) {
17
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
21
+ });
22
+ };
23
+ /** Returns `true` if this code is currently running in a worker. */
24
+ const isWorkerRuntime = Implementation.isWorkerRuntime;
25
+ let exposeCalled = false;
26
+ const activeSubscriptions = new Map();
27
+ const isMasterJobCancelMessage = (thing) => thing && thing.type === MasterMessageType.cancel;
28
+ const isMasterJobRunMessage = (thing) => thing && thing.type === MasterMessageType.run;
29
+ /**
30
+ * Detects observables via the `Symbol.observable` / `@@observable` interop protocol.
31
+ * Inlined from the `is-observable` package (which is now ESM-only) to keep the
32
+ * CommonJS build working without an extra dependency.
33
+ */
34
+ function isInteropObservable(thing) {
35
+ if (!thing) {
36
+ return false;
37
+ }
38
+ const observableSymbol = Symbol.observable;
39
+ if (typeof observableSymbol === "symbol" && typeof thing[observableSymbol] === "function") {
40
+ return thing === thing[observableSymbol]();
41
+ }
42
+ if (typeof thing["@@observable"] === "function") {
43
+ return thing === thing["@@observable"]();
44
+ }
45
+ return false;
46
+ }
47
+ /**
48
+ * There are issues with interop observable detection not recognizing zen-observable's instances.
49
+ * We are using `observable-fns`, but it's based on zen-observable, too.
50
+ */
51
+ const isObservable = (thing) => isInteropObservable(thing) || isZenObservable(thing);
52
+ function isZenObservable(thing) {
53
+ return thing && typeof thing === "object" && typeof thing.subscribe === "function";
54
+ }
55
+ function deconstructTransfer(thing) {
56
+ return isTransferDescriptor(thing)
57
+ ? { payload: thing.send, transferables: thing.transferables }
58
+ : { payload: thing, transferables: undefined };
59
+ }
60
+ function postFunctionInitMessage() {
61
+ const initMessage = {
62
+ type: WorkerMessageType.init,
63
+ exposed: {
64
+ type: "function"
65
+ }
66
+ };
67
+ Implementation.postMessageToMaster(initMessage);
68
+ }
69
+ function postModuleInitMessage(methodNames) {
70
+ const initMessage = {
71
+ type: WorkerMessageType.init,
72
+ exposed: {
73
+ type: "module",
74
+ methods: methodNames
75
+ }
76
+ };
77
+ Implementation.postMessageToMaster(initMessage);
78
+ }
79
+ function postJobErrorMessage(uid, rawError) {
80
+ const { payload: error, transferables } = deconstructTransfer(rawError);
81
+ const errorMessage = {
82
+ type: WorkerMessageType.error,
83
+ uid,
84
+ error: serialize(error)
85
+ };
86
+ Implementation.postMessageToMaster(errorMessage, transferables);
87
+ }
88
+ function postJobResultMessage(uid, completed, resultValue) {
89
+ const { payload, transferables } = deconstructTransfer(resultValue);
90
+ const resultMessage = {
91
+ type: WorkerMessageType.result,
92
+ uid,
93
+ complete: completed ? true : undefined,
94
+ payload
95
+ };
96
+ Implementation.postMessageToMaster(resultMessage, transferables);
97
+ }
98
+ function postJobStartMessage(uid, resultType) {
99
+ const startMessage = {
100
+ type: WorkerMessageType.running,
101
+ uid,
102
+ resultType
103
+ };
104
+ Implementation.postMessageToMaster(startMessage);
105
+ }
106
+ function postUncaughtErrorMessage(error) {
107
+ try {
108
+ const errorMessage = {
109
+ type: WorkerMessageType.uncaughtError,
110
+ error: serialize(error)
111
+ };
112
+ Implementation.postMessageToMaster(errorMessage);
113
+ }
114
+ catch (subError) {
115
+ console.error("Not reporting uncaught error back to master thread as it " +
116
+ "occured while reporting an uncaught error already." +
117
+ "\nLatest error:", subError, "\nOriginal error:", error);
118
+ }
119
+ }
120
+ function runFunction(jobUID, fn, args) {
121
+ return __awaiter(this, void 0, void 0, function* () {
122
+ let syncResult;
123
+ try {
124
+ syncResult = fn(...args);
125
+ }
126
+ catch (error) {
127
+ return postJobErrorMessage(jobUID, error);
128
+ }
129
+ const resultType = isObservable(syncResult) ? "observable" : "promise";
130
+ postJobStartMessage(jobUID, resultType);
131
+ if (isObservable(syncResult)) {
132
+ const subscription = syncResult.subscribe(value => postJobResultMessage(jobUID, false, serialize(value)), error => {
133
+ postJobErrorMessage(jobUID, serialize(error));
134
+ activeSubscriptions.delete(jobUID);
135
+ }, () => {
136
+ postJobResultMessage(jobUID, true);
137
+ activeSubscriptions.delete(jobUID);
138
+ });
139
+ activeSubscriptions.set(jobUID, subscription);
140
+ }
141
+ else {
142
+ try {
143
+ const result = yield syncResult;
144
+ postJobResultMessage(jobUID, true, serialize(result));
145
+ }
146
+ catch (error) {
147
+ postJobErrorMessage(jobUID, serialize(error));
148
+ }
149
+ }
150
+ });
151
+ }
152
+ /**
153
+ * Expose a function or a module (an object whose values are functions)
154
+ * to the main thread. Must be called exactly once in every worker thread
155
+ * to signal its API to the main thread.
156
+ *
157
+ * @param exposed Function or object whose values are functions
158
+ */
159
+ function expose(exposed) {
160
+ if (!Implementation.isWorkerRuntime()) {
161
+ throw Error("expose() called in the master thread.");
162
+ }
163
+ if (exposeCalled) {
164
+ throw Error("expose() called more than once. This is not possible. Pass an object to expose() if you want to expose multiple functions.");
165
+ }
166
+ exposeCalled = true;
167
+ if (typeof exposed === "function") {
168
+ Implementation.subscribeToMasterMessages(messageData => {
169
+ if (isMasterJobRunMessage(messageData) && !messageData.method) {
170
+ runFunction(messageData.uid, exposed, messageData.args.map(deserialize));
171
+ }
172
+ });
173
+ postFunctionInitMessage();
174
+ }
175
+ else if (typeof exposed === "object" && exposed) {
176
+ Implementation.subscribeToMasterMessages(messageData => {
177
+ if (isMasterJobRunMessage(messageData) && messageData.method) {
178
+ runFunction(messageData.uid, exposed[messageData.method], messageData.args.map(deserialize));
179
+ }
180
+ });
181
+ const methodNames = Object.keys(exposed).filter(key => typeof exposed[key] === "function");
182
+ postModuleInitMessage(methodNames);
183
+ }
184
+ else {
185
+ throw Error(`Invalid argument passed to expose(). Expected a function or an object, got: ${exposed}`);
186
+ }
187
+ Implementation.subscribeToMasterMessages(messageData => {
188
+ if (isMasterJobCancelMessage(messageData)) {
189
+ const jobUID = messageData.uid;
190
+ const subscription = activeSubscriptions.get(jobUID);
191
+ if (subscription) {
192
+ subscription.unsubscribe();
193
+ activeSubscriptions.delete(jobUID);
194
+ }
195
+ }
196
+ });
197
+ }
198
+ if (typeof self !== "undefined" && typeof self.addEventListener === "function" && Implementation.isWorkerRuntime()) {
199
+ self.addEventListener("error", event => {
200
+ // Post with some delay, so the master had some time to subscribe to messages
201
+ setTimeout(() => postUncaughtErrorMessage(event.error || event), 250);
202
+ });
203
+ self.addEventListener("unhandledrejection", event => {
204
+ const error = event.reason;
205
+ if (error && typeof error.message === "string") {
206
+ // Post with some delay, so the master had some time to subscribe to messages
207
+ setTimeout(() => postUncaughtErrorMessage(error), 250);
208
+ }
209
+ });
210
+ }
211
+ if (typeof process !== "undefined" && typeof process.on === "function" && Implementation.isWorkerRuntime()) {
212
+ process.on("uncaughtException", (error) => {
213
+ // Post with some delay, so the master had some time to subscribe to messages
214
+ setTimeout(() => postUncaughtErrorMessage(error), 250);
215
+ });
216
+ process.on("unhandledRejection", (error) => {
217
+ if (error && typeof error.message === "string") {
218
+ // Post with some delay, so the master had some time to subscribe to messages
219
+ setTimeout(() => postUncaughtErrorMessage(error), 250);
220
+ }
221
+ });
222
+ }
223
+
224
+ export { expose, isWorkerRuntime };
@@ -0,0 +1,21 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import { fileURLToPath as __fileURLToPath } from "url";
3
+ import { dirname as __pathDirname } from "path";
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __pathDirname(__filename);
7
+ // Webpack hack
8
+ let implementation;
9
+ function selectImplementation() {
10
+ return typeof __non_webpack_require__ === "function"
11
+ ? __non_webpack_require__("worker_threads")
12
+ : eval("require")("worker_threads");
13
+ }
14
+ function getImplementation() {
15
+ if (!implementation) {
16
+ implementation = selectImplementation();
17
+ }
18
+ return implementation;
19
+ }
20
+
21
+ export { getImplementation as default };