@xylabs/threads 3.0.4

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 (171) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +227 -0
  4. package/dist/common.d.ts +4 -0
  5. package/dist/common.js +18 -0
  6. package/dist/index.d.ts +7 -0
  7. package/dist/index.js +27 -0
  8. package/dist/master/get-bundle-url.browser.d.ts +3 -0
  9. package/dist/master/get-bundle-url.browser.js +29 -0
  10. package/dist/master/implementation.browser.d.ts +4 -0
  11. package/dist/master/implementation.browser.js +69 -0
  12. package/dist/master/implementation.d.ts +6 -0
  13. package/dist/master/implementation.js +41 -0
  14. package/dist/master/implementation.node.d.ts +5 -0
  15. package/dist/master/implementation.node.js +255 -0
  16. package/dist/master/index.d.ts +13 -0
  17. package/dist/master/index.js +16 -0
  18. package/dist/master/invocation-proxy.d.ts +3 -0
  19. package/dist/master/invocation-proxy.js +130 -0
  20. package/dist/master/pool-types.d.ts +65 -0
  21. package/dist/master/pool-types.js +15 -0
  22. package/dist/master/pool.d.ts +90 -0
  23. package/dist/master/pool.js +281 -0
  24. package/dist/master/register.d.ts +1 -0
  25. package/dist/master/register.js +12 -0
  26. package/dist/master/spawn.d.ts +20 -0
  27. package/dist/master/spawn.js +130 -0
  28. package/dist/master/thread.d.ts +12 -0
  29. package/dist/master/thread.js +22 -0
  30. package/dist/observable-promise.d.ts +38 -0
  31. package/dist/observable-promise.js +156 -0
  32. package/dist/observable.d.ts +19 -0
  33. package/dist/observable.js +43 -0
  34. package/dist/ponyfills.d.ts +8 -0
  35. package/dist/ponyfills.js +22 -0
  36. package/dist/promise.d.ts +5 -0
  37. package/dist/promise.js +29 -0
  38. package/dist/serializers.d.ts +16 -0
  39. package/dist/serializers.js +41 -0
  40. package/dist/symbols.d.ts +5 -0
  41. package/dist/symbols.js +8 -0
  42. package/dist/transferable.d.ts +42 -0
  43. package/dist/transferable.js +28 -0
  44. package/dist/types/master.d.ts +99 -0
  45. package/dist/types/master.js +14 -0
  46. package/dist/types/messages.d.ts +62 -0
  47. package/dist/types/messages.js +20 -0
  48. package/dist/types/worker.d.ts +11 -0
  49. package/dist/types/worker.js +2 -0
  50. package/dist/worker/bundle-entry.d.ts +1 -0
  51. package/dist/worker/bundle-entry.js +27 -0
  52. package/dist/worker/implementation.browser.d.ts +7 -0
  53. package/dist/worker/implementation.browser.js +28 -0
  54. package/dist/worker/implementation.d.ts +3 -0
  55. package/dist/worker/implementation.js +24 -0
  56. package/dist/worker/implementation.tiny-worker.d.ts +7 -0
  57. package/dist/worker/implementation.tiny-worker.js +38 -0
  58. package/dist/worker/implementation.worker_threads.d.ts +8 -0
  59. package/dist/worker/implementation.worker_threads.js +42 -0
  60. package/dist/worker/index.d.ts +13 -0
  61. package/dist/worker/index.js +195 -0
  62. package/dist/worker_threads.d.ts +8 -0
  63. package/dist/worker_threads.js +17 -0
  64. package/dist-esm/common.js +12 -0
  65. package/dist-esm/index.js +6 -0
  66. package/dist-esm/master/get-bundle-url.browser.js +25 -0
  67. package/dist-esm/master/implementation.browser.js +64 -0
  68. package/dist-esm/master/implementation.js +15 -0
  69. package/dist-esm/master/implementation.node.js +224 -0
  70. package/dist-esm/master/index.js +9 -0
  71. package/dist-esm/master/invocation-proxy.js +122 -0
  72. package/dist-esm/master/pool-types.js +12 -0
  73. package/dist-esm/master/pool.js +273 -0
  74. package/dist-esm/master/register.js +10 -0
  75. package/dist-esm/master/spawn.js +123 -0
  76. package/dist-esm/master/thread.js +19 -0
  77. package/dist-esm/observable-promise.js +152 -0
  78. package/dist-esm/observable.js +38 -0
  79. package/dist-esm/ponyfills.js +18 -0
  80. package/dist-esm/promise.js +25 -0
  81. package/dist-esm/serializers.js +37 -0
  82. package/dist-esm/symbols.js +5 -0
  83. package/dist-esm/transferable.js +23 -0
  84. package/dist-esm/types/master.js +11 -0
  85. package/dist-esm/types/messages.js +17 -0
  86. package/dist-esm/types/worker.js +1 -0
  87. package/dist-esm/worker/bundle-entry.js +11 -0
  88. package/dist-esm/worker/implementation.browser.js +26 -0
  89. package/dist-esm/worker/implementation.js +19 -0
  90. package/dist-esm/worker/implementation.tiny-worker.js +36 -0
  91. package/dist-esm/worker/implementation.worker_threads.js +37 -0
  92. package/dist-esm/worker/index.js +186 -0
  93. package/dist-esm/worker_threads.js +14 -0
  94. package/index.mjs +11 -0
  95. package/observable.d.ts +2 -0
  96. package/observable.js +3 -0
  97. package/observable.mjs +5 -0
  98. package/package.json +141 -0
  99. package/register.d.ts +3 -0
  100. package/register.js +3 -0
  101. package/register.mjs +2 -0
  102. package/rollup.config.js +16 -0
  103. package/src/common.ts +16 -0
  104. package/src/index.ts +8 -0
  105. package/src/master/get-bundle-url.browser.ts +31 -0
  106. package/src/master/implementation.browser.ts +80 -0
  107. package/src/master/implementation.node.ts +284 -0
  108. package/src/master/implementation.ts +21 -0
  109. package/src/master/index.ts +20 -0
  110. package/src/master/invocation-proxy.ts +146 -0
  111. package/src/master/pool-types.ts +83 -0
  112. package/src/master/pool.ts +391 -0
  113. package/src/master/register.ts +10 -0
  114. package/src/master/spawn.ts +172 -0
  115. package/src/master/thread.ts +26 -0
  116. package/src/observable-promise.ts +181 -0
  117. package/src/observable.ts +43 -0
  118. package/src/ponyfills.ts +31 -0
  119. package/src/promise.ts +26 -0
  120. package/src/serializers.ts +67 -0
  121. package/src/symbols.ts +5 -0
  122. package/src/transferable.ts +68 -0
  123. package/src/types/master.ts +130 -0
  124. package/src/types/messages.ts +81 -0
  125. package/src/types/worker.ts +14 -0
  126. package/src/worker/bundle-entry.ts +10 -0
  127. package/src/worker/implementation.browser.ts +40 -0
  128. package/src/worker/implementation.tiny-worker.ts +52 -0
  129. package/src/worker/implementation.ts +23 -0
  130. package/src/worker/implementation.worker_threads.ts +50 -0
  131. package/src/worker/index.ts +228 -0
  132. package/src/worker_threads.ts +28 -0
  133. package/test/lib/serialization.ts +38 -0
  134. package/test/observable-promise.test.ts +189 -0
  135. package/test/observable.test.ts +86 -0
  136. package/test/pool.test.ts +173 -0
  137. package/test/serialization.test.ts +21 -0
  138. package/test/spawn.chromium.mocha.ts +49 -0
  139. package/test/spawn.test.ts +71 -0
  140. package/test/streaming.test.ts +27 -0
  141. package/test/transferables.test.ts +69 -0
  142. package/test/workers/arraybuffer-xor.ts +11 -0
  143. package/test/workers/count-to-five.ts +13 -0
  144. package/test/workers/counter.ts +20 -0
  145. package/test/workers/faulty-function.ts +6 -0
  146. package/test/workers/hello-world.ts +6 -0
  147. package/test/workers/increment.ts +9 -0
  148. package/test/workers/minmax.ts +25 -0
  149. package/test/workers/serialization.ts +12 -0
  150. package/test/workers/top-level-throw.ts +1 -0
  151. package/test-tooling/rollup/app.js +20 -0
  152. package/test-tooling/rollup/rollup.config.ts +15 -0
  153. package/test-tooling/rollup/rollup.test.ts +44 -0
  154. package/test-tooling/rollup/worker.js +7 -0
  155. package/test-tooling/tsconfig/minimal-tsconfig.test.ts +7 -0
  156. package/test-tooling/tsconfig/minimal.ts +10 -0
  157. package/test-tooling/webpack/addition-worker.ts +10 -0
  158. package/test-tooling/webpack/app-with-inlined-worker.ts +29 -0
  159. package/test-tooling/webpack/app.ts +58 -0
  160. package/test-tooling/webpack/pool-worker.ts +6 -0
  161. package/test-tooling/webpack/raw-loader.d.ts +4 -0
  162. package/test-tooling/webpack/webpack.chromium.mocha.ts +21 -0
  163. package/test-tooling/webpack/webpack.node.config.js +38 -0
  164. package/test-tooling/webpack/webpack.test.ts +90 -0
  165. package/test-tooling/webpack/webpack.web.config.js +35 -0
  166. package/types/is-observable.d.ts +7 -0
  167. package/types/tiny-worker.d.ts +4 -0
  168. package/types/webworker.d.ts +9 -0
  169. package/worker.d.ts +2 -0
  170. package/worker.js +3 -0
  171. package/worker.mjs +7 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog - threads.js
2
+
3
+ ## v1.0
4
+
5
+ For newer versions of `threads`, visit the [releases page](https://github.com/andywer/threads.js/releases) on GitHub.
6
+
7
+ You will find a description of each release's changes there.
8
+
9
+ ## v0.x
10
+
11
+ For old versions of `threads`, see the [CHANGELOG.md on the `v0` branch](https://github.com/andywer/threads.js/blob/v0/CHANGELOG.md).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Andy Wermke
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,227 @@
1
+ <h1 align="center">
2
+ <img alt="threads.js" src="./docs/assets/logo-label.png" width="75%" />
3
+ </h1>
4
+ <p align="center">
5
+ <a href="https://travis-ci.org/andywer/threads.js" target="_blank"><img alt="Build status" src="https://img.shields.io/travis/andywer/threads.js/v1.svg?style=flat-square"></a>
6
+ <a href="https://www.npmjs.com/package/threads" target="_blank"><img alt="npm (tag)" src="https://img.shields.io/npm/v/threads.svg?style=flat-square"></a>
7
+ <a href="https://gitter.im/threadsjs/community" target="_blank"><img alt="Chat room" src="https://img.shields.io/badge/chat-gitter.im-orange" /></a>
8
+ </p>
9
+
10
+ <br />
11
+
12
+ Offload CPU-intensive tasks to worker threads in node.js, web browsers and electron using one uniform API.
13
+
14
+ Uses web workers in the browser, `worker_threads` in node 12+ and [`tiny-worker`](https://github.com/avoidwork/tiny-worker) in node 8 to 11.
15
+
16
+ ### Features
17
+
18
+ * First-class support for **async functions** & **observables**
19
+ * Write code once, run it **on all platforms**
20
+ * Manage bulk task executions with **thread pools**
21
+ * Use **require()** and **import**/**export** in workers
22
+ * Works great with **webpack**
23
+
24
+ ### Version 0.x
25
+
26
+ You can find the old version 0.12 of threads.js on the [`v0` branch](https://github.com/andywer/threads.js/tree/v0). All the content on this page refers to version 1.0 which is a rewrite of the library with a whole new API.
27
+
28
+ ## Installation
29
+
30
+ ```
31
+ npm install threads tiny-worker
32
+ ```
33
+
34
+ *You only need to install the `tiny-worker` package to support node.js < 12. It's an optional dependency and used as a fallback if `worker_threads` are not available.*
35
+
36
+ ## Platform support
37
+
38
+ <details>
39
+ <summary>Run on node.js</summary>
40
+
41
+ <p></p>
42
+
43
+ Running code using threads.js in node works out of the box.
44
+
45
+ Note that we wrap the native `Worker`, so `new Worker("./foo/bar")` will resolve the path relative to the module that calls it, not relative to the current working directory.
46
+
47
+ That aligns it with the behavior when bundling the code with webpack or parcel.
48
+
49
+ </details>
50
+
51
+ <details>
52
+ <summary>Webpack build setup</summary>
53
+
54
+ #### Webpack config
55
+
56
+ Use with the [`threads-plugin`](https://github.com/andywer/threads-plugin). It will transparently detect all `new Worker("./unbundled-path")` expressions, bundles the worker code and replaces the `new Worker(...)` path with the worker bundle path, so you don't need to explicitly use the `worker-loader` or define extra entry points.
57
+
58
+ ```sh
59
+ npm install -D threads-plugin
60
+ ```
61
+
62
+ Then add it to your `webpack.config.js`:
63
+
64
+ ```diff
65
+ + const ThreadsPlugin = require('threads-plugin');
66
+
67
+ module.exports = {
68
+ // ...
69
+ plugins: [
70
+ + new ThreadsPlugin()
71
+ ]
72
+ // ...
73
+ }
74
+ ```
75
+
76
+ #### Node.js bundles
77
+
78
+ If you are using webpack to create a bundle that will be run in node (webpack config `target: "node"`), you also need to specify that the `tiny-worker` package used for node < 12 should not be bundled:
79
+
80
+ ```diff
81
+ module.exports = {
82
+ // ...
83
+ + externals: {
84
+ + "tiny-worker": "tiny-worker"
85
+ + }
86
+ // ...
87
+ }
88
+ ```
89
+
90
+ Make sure that `tiny-worker` is listed in your `package.json` `dependencies` in that case.
91
+
92
+ #### When using TypeScript
93
+
94
+ Note: You'll need to be using Typescript version 4+, as the types generated by threads.js are not supported in Typescript 3.
95
+
96
+ Make sure the TypeScript compiler keeps the `import` / `export` statements intact, so webpack resolves them. Otherwise the `threads-plugin` won't be able to do its job.
97
+
98
+ ```diff
99
+ module.exports = {
100
+ // ...
101
+ module: {
102
+ rules: [
103
+ {
104
+ test: /\.ts$/,
105
+ loader: "ts-loader",
106
+ + options: {
107
+ + compilerOptions: {
108
+ + module: "esnext"
109
+ + }
110
+ + }
111
+ }
112
+ ]
113
+ },
114
+ // ...
115
+ }
116
+ ```
117
+
118
+ </details>
119
+
120
+ <details>
121
+ <summary>Parcel bundler setup</summary>
122
+
123
+ <p></p>
124
+
125
+ You need to import `threads/register` once at the beginning of your application code (in the master code, not in the workers):
126
+
127
+ ```diff
128
+ import { spawn } from "threads"
129
+ + import "threads/register"
130
+
131
+ // ...
132
+
133
+ const work = await spawn(new Worker("./worker"))
134
+ ```
135
+
136
+ This registers the library's `Worker` implementation for your platform as the global `Worker`. This is necessary, since you cannot `import { Worker } from "threads"` or Parcel won't recognize `new Worker()` as a web worker anymore.
137
+
138
+ Be aware that this might affect any code that tries to instantiate a normal web worker `Worker` and now instead instantiates a threads.js `Worker`. The threads.js `Worker` is just a web worker with some sugar on top, but that sugar might have unexpected side effects on third-party libraries.
139
+
140
+ Everything else should work out of the box.
141
+
142
+ </details>
143
+
144
+ ## Getting Started
145
+
146
+ ### Basics
147
+
148
+ ```js
149
+ // master.js
150
+ import { spawn, Thread, Worker } from "threads"
151
+
152
+ const auth = await spawn(new Worker("./workers/auth"))
153
+ const hashed = await auth.hashPassword("Super secret password", "1234")
154
+
155
+ console.log("Hashed password:", hashed)
156
+
157
+ await Thread.terminate(auth)
158
+ ```
159
+
160
+ ```js
161
+ // workers/auth.js
162
+ import sha256 from "js-sha256"
163
+ import { expose } from "threads/worker"
164
+
165
+ expose({
166
+ hashPassword(password, salt) {
167
+ return sha256(password + salt)
168
+ }
169
+ })
170
+ ```
171
+
172
+ ### spawn()
173
+
174
+ The `hashPassword()` function of the `auth` object in the master code proxies the call to the `hashPassword()` function in the worker:
175
+
176
+ If the worker's function returns a promise or an observable then you can just use the return value as such in the master code. If the function returns a primitive value, expect the master function to return a promise resolving to that value.
177
+
178
+ ### expose()
179
+
180
+ Use `expose()` to make a function or an object containing methods callable from the master thread.
181
+
182
+ In case of exposing an object, `spawn()` will asynchronously return an object exposing all the object's functions. If you `expose()` a function, `spawn` will also return a callable function, not an object.
183
+
184
+ ## Usage
185
+
186
+ <p>
187
+ Find the full documentation on the <a href="https://threads.js.org/" rel="nofollow">website</a>:
188
+ </p>
189
+
190
+ - [**Quick start**](https://threads.js.org/getting-started)
191
+ - [**Basic usage**](https://threads.js.org/usage)
192
+ - [**Using observables**](https://threads.js.org/usage-observables)
193
+ - [**Thread pools**](https://threads.js.org/usage-pool)
194
+ - [**Advanced**](https://threads.js.org/usage-advanced)
195
+
196
+ ## Webpack
197
+
198
+ Threads.js works with webpack. Usually all you need to do is adding the
199
+ [`threads-plugin`](https://github.com/andywer/threads-plugin).
200
+
201
+ See [Build with webpack](https://threads.js.org/getting-started#build-with-webpack)
202
+ on the website for details.
203
+
204
+ <!--
205
+ ## API
206
+
207
+ TODO
208
+ -->
209
+
210
+ ## Debug
211
+
212
+ We are using the [`debug`](https://github.com/visionmedia/debug) package to provide opt-in debug logging. All the package's debug messages have a scope starting with `threads:`, with different sub-scopes:
213
+
214
+ - `threads:master:messages`
215
+ - `threads:master:spawn`
216
+ - `threads:master:thread-utils`
217
+ - `threads:pool:${poolName || poolID}`
218
+
219
+ Set it to `DEBUG=threads:*` to enable all the library's debug logging. To run its tests with full debug logging, for instance:
220
+
221
+ ```
222
+ DEBUG=threads:* npm test
223
+ ```
224
+
225
+ ## License
226
+
227
+ MIT
@@ -0,0 +1,4 @@
1
+ import { JsonSerializable, SerializerImplementation } from './serializers';
2
+ export declare function registerSerializer(serializer: SerializerImplementation<JsonSerializable>): void;
3
+ export declare function deserialize(message: JsonSerializable): any;
4
+ export declare function serialize(input: any): JsonSerializable;
package/dist/common.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serialize = exports.deserialize = exports.registerSerializer = void 0;
4
+ /* eslint-disable @typescript-eslint/no-explicit-any */
5
+ const serializers_1 = require("./serializers");
6
+ let registeredSerializer = serializers_1.DefaultSerializer;
7
+ function registerSerializer(serializer) {
8
+ registeredSerializer = (0, serializers_1.extendSerializer)(registeredSerializer, serializer);
9
+ }
10
+ exports.registerSerializer = registerSerializer;
11
+ function deserialize(message) {
12
+ return registeredSerializer.deserialize(message);
13
+ }
14
+ exports.deserialize = deserialize;
15
+ function serialize(input) {
16
+ return registeredSerializer.serialize(input);
17
+ }
18
+ exports.serialize = serialize;
@@ -0,0 +1,7 @@
1
+ export { registerSerializer } from './common';
2
+ export * from './master/index';
3
+ export { QueuedTask } from './master/pool';
4
+ export { ExposedToThreadType as ExposedAs } from './master/spawn';
5
+ export { DefaultSerializer, JsonSerializable, Serializer, SerializerImplementation } from './serializers';
6
+ export { Transfer, TransferDescriptor } from './transferable';
7
+ export { expose } from './worker/index';
package/dist/index.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.expose = exports.Transfer = exports.DefaultSerializer = exports.registerSerializer = void 0;
18
+ /* eslint-disable import/no-internal-modules */
19
+ var common_1 = require("./common");
20
+ Object.defineProperty(exports, "registerSerializer", { enumerable: true, get: function () { return common_1.registerSerializer; } });
21
+ __exportStar(require("./master/index"), exports);
22
+ var serializers_1 = require("./serializers");
23
+ Object.defineProperty(exports, "DefaultSerializer", { enumerable: true, get: function () { return serializers_1.DefaultSerializer; } });
24
+ var transferable_1 = require("./transferable");
25
+ Object.defineProperty(exports, "Transfer", { enumerable: true, get: function () { return transferable_1.Transfer; } });
26
+ var index_1 = require("./worker/index");
27
+ Object.defineProperty(exports, "expose", { enumerable: true, get: function () { return index_1.expose; } });
@@ -0,0 +1,3 @@
1
+ declare function getBundleURLCached(): string;
2
+ declare function getBaseURL(url: string): string;
3
+ export { getBaseURL, getBundleURLCached as getBundleURL };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ // Source: <https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/builtins/bundle-url.js>
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.getBundleURL = exports.getBaseURL = void 0;
5
+ let bundleURL;
6
+ function getBundleURLCached() {
7
+ if (!bundleURL) {
8
+ bundleURL = getBundleURL();
9
+ }
10
+ return bundleURL;
11
+ }
12
+ exports.getBundleURL = getBundleURLCached;
13
+ function getBundleURL() {
14
+ // Attempt to find the URL of the current script and use that as the base URL
15
+ try {
16
+ throw new Error('getBundleURL failed');
17
+ }
18
+ catch (err) {
19
+ const matches = ('' + err.stack).match(/(https?|file|ftp|chrome-extension|moz-extension):\/\/[^\n)]+/g);
20
+ if (matches) {
21
+ return getBaseURL(matches[0]);
22
+ }
23
+ }
24
+ return '/';
25
+ }
26
+ function getBaseURL(url) {
27
+ return ('' + url).replace(/^((?:https?|file|ftp|chrome-extension|moz-extension):\/\/.+)?\/[^/]+(?:\?.*)?$/, '$1') + '/';
28
+ }
29
+ exports.getBaseURL = getBaseURL;
@@ -0,0 +1,4 @@
1
+ import { ImplementationExport } from '../types/master';
2
+ export declare const defaultPoolSize: number;
3
+ export declare function getWorkerImplementation(): ImplementationExport;
4
+ export declare function isWorkerRuntime(): boolean;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ // tslint:disable max-classes-per-file
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.isWorkerRuntime = exports.getWorkerImplementation = exports.defaultPoolSize = void 0;
5
+ const get_bundle_url_browser_1 = require("./get-bundle-url.browser");
6
+ exports.defaultPoolSize = typeof navigator !== 'undefined' && navigator.hardwareConcurrency ? navigator.hardwareConcurrency : 4;
7
+ const isAbsoluteURL = (value) => /^[A-Za-z][\d+.A-Za-z\-]*:/.test(value);
8
+ function createSourceBlobURL(code) {
9
+ const blob = new Blob([code], { type: 'application/javascript' });
10
+ return URL.createObjectURL(blob);
11
+ }
12
+ function selectWorkerImplementation() {
13
+ if (typeof Worker === 'undefined') {
14
+ // Might happen on Safari, for instance
15
+ // The idea is to only fail if the constructor is actually used
16
+ return class NoWebWorker {
17
+ constructor() {
18
+ throw new Error("No web worker implementation available. You might have tried to spawn a worker within a worker in a browser that doesn't support workers in workers.");
19
+ }
20
+ };
21
+ }
22
+ class WebWorker extends Worker {
23
+ constructor(url, options) {
24
+ if (typeof url === 'string' && options && options._baseURL) {
25
+ url = new URL(url, options._baseURL);
26
+ }
27
+ else if (typeof url === 'string' && !isAbsoluteURL(url) && /^file:\/\//i.test((0, get_bundle_url_browser_1.getBundleURL)())) {
28
+ url = new URL(url, (0, get_bundle_url_browser_1.getBundleURL)().replace(/\/[^/]+$/, '/'));
29
+ if (options?.CORSWorkaround ?? true) {
30
+ url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`);
31
+ }
32
+ }
33
+ if (typeof url === 'string' &&
34
+ isAbsoluteURL(url) && // Create source code blob loading JS file via `importScripts()`
35
+ // to circumvent worker CORS restrictions
36
+ (options?.CORSWorkaround ?? true)) {
37
+ url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`);
38
+ }
39
+ super(url, options);
40
+ }
41
+ }
42
+ class BlobWorker extends WebWorker {
43
+ constructor(blob, options) {
44
+ const url = window.URL.createObjectURL(blob);
45
+ super(url, options);
46
+ }
47
+ static fromText(source, options) {
48
+ const blob = new window.Blob([source], { type: 'text/javascript' });
49
+ return new BlobWorker(blob, options);
50
+ }
51
+ }
52
+ return {
53
+ blob: BlobWorker,
54
+ default: WebWorker,
55
+ };
56
+ }
57
+ let implementation;
58
+ function getWorkerImplementation() {
59
+ if (!implementation) {
60
+ implementation = selectWorkerImplementation();
61
+ }
62
+ return implementation;
63
+ }
64
+ exports.getWorkerImplementation = getWorkerImplementation;
65
+ function isWorkerRuntime() {
66
+ const isWindowContext = typeof self !== 'undefined' && typeof Window !== 'undefined' && self instanceof Window;
67
+ return typeof self !== 'undefined' && self['postMessage'] && !isWindowContext ? true : false;
68
+ }
69
+ exports.isWorkerRuntime = isWorkerRuntime;
@@ -0,0 +1,6 @@
1
+ import * as BrowserImplementation from './implementation.browser';
2
+ /** Default size of pools. Depending on the platform the value might vary from device to device. */
3
+ export declare const defaultPoolSize: number;
4
+ export declare const getWorkerImplementation: typeof BrowserImplementation.getWorkerImplementation;
5
+ /** Returns `true` if this code is currently running in a worker. */
6
+ export declare const isWorkerRuntime: typeof BrowserImplementation.isWorkerRuntime;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /*
3
+ * This file is only a stub to make './implementation' resolve to the right module.
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || function (mod) {
22
+ if (mod && mod.__esModule) return mod;
23
+ var result = {};
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25
+ __setModuleDefault(result, mod);
26
+ return result;
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.isWorkerRuntime = exports.getWorkerImplementation = exports.defaultPoolSize = void 0;
30
+ // We alias `src/master/implementation` to `src/master/implementation.browser` for web
31
+ // browsers already in the package.json, so if get here, it's safe to pass-through the
32
+ // node implementation
33
+ const BrowserImplementation = __importStar(require("./implementation.browser"));
34
+ const NodeImplementation = __importStar(require("./implementation.node"));
35
+ const runningInNode = typeof process !== 'undefined' && process.arch !== 'browser' && 'pid' in process;
36
+ const implementation = runningInNode ? NodeImplementation : BrowserImplementation;
37
+ /** Default size of pools. Depending on the platform the value might vary from device to device. */
38
+ exports.defaultPoolSize = implementation.defaultPoolSize;
39
+ exports.getWorkerImplementation = implementation.getWorkerImplementation;
40
+ /** Returns `true` if this code is currently running in a worker. */
41
+ exports.isWorkerRuntime = implementation.isWorkerRuntime;
@@ -0,0 +1,5 @@
1
+ /// <reference lib="dom" />
2
+ import { ImplementationExport } from '../types/master';
3
+ export declare const defaultPoolSize: number;
4
+ export declare function getWorkerImplementation(): ImplementationExport;
5
+ export declare function isWorkerRuntime(): boolean;