From f2be15ca9bc199b1c27d8126c8ff0bc114cbf421 Mon Sep 17 00:00:00 2001 From: Ken Bynell Date: Wed, 22 May 2024 23:19:52 -0500 Subject: [PATCH] remove workerpool dep, need something else i guess --- commands/debug2.js | 24 +- commands/packMod.js | 5 +- commands/worker_test.js | 13 +- node_modules/.package-lock.json | 7 +- node_modules/workerpool/HISTORY.md | 395 ---- node_modules/workerpool/LICENSE | 201 -- node_modules/workerpool/README.md | 530 ----- node_modules/workerpool/dist/worker.js | 288 --- node_modules/workerpool/dist/worker.js.map | 1 - node_modules/workerpool/dist/worker.min.js | 2 - .../workerpool/dist/worker.min.js.map | 1 - node_modules/workerpool/dist/workerpool.js | 1737 ----------------- .../workerpool/dist/workerpool.js.map | 1 - .../workerpool/dist/workerpool.min.js | 3 - .../dist/workerpool.min.js.LICENSE.txt | 24 - .../workerpool/dist/workerpool.min.js.map | 1 - node_modules/workerpool/package.json | 57 - node_modules/workerpool/src/Pool.js | 476 ----- node_modules/workerpool/src/Promise.js | 293 --- node_modules/workerpool/src/WorkerHandler.js | 547 ------ .../workerpool/src/debug-port-allocator.js | 28 - node_modules/workerpool/src/environment.js | 30 - .../src/generated/embeddedWorker.js | 6 - node_modules/workerpool/src/header.js | 24 - node_modules/workerpool/src/index.js | 60 - .../workerpool/src/requireFoolWebpack.js | 8 - node_modules/workerpool/src/transfer.js | 12 - node_modules/workerpool/src/types.js | 46 - .../workerpool/src/validateOptions.js | 51 - node_modules/workerpool/src/worker.js | 256 --- node_modules/workerpool/types/Pool.d.ts | 130 -- node_modules/workerpool/types/Promise.d.ts | 125 -- .../workerpool/types/WorkerHandler.d.ts | 89 - .../types/debug-port-allocator.d.ts | 8 - .../workerpool/types/environment.d.ts | 4 - .../types/generated/embeddedWorker.d.ts | 2 - node_modules/workerpool/types/index.d.ts | 43 - node_modules/workerpool/types/transfer.d.ts | 19 - node_modules/workerpool/types/types.d.ts | 99 - .../workerpool/types/validateOptions.d.ts | 4 - node_modules/workerpool/types/worker.d.ts | 8 - package-lock.json | 6 - package.json | 1 - support_files/config.js | 31 +- support_files/conversion_junction.js | 10 +- support_files/helper_functions.js | 28 +- 46 files changed, 43 insertions(+), 5691 deletions(-) delete mode 100644 node_modules/workerpool/HISTORY.md delete mode 100644 node_modules/workerpool/LICENSE delete mode 100644 node_modules/workerpool/README.md delete mode 100644 node_modules/workerpool/dist/worker.js delete mode 100644 node_modules/workerpool/dist/worker.js.map delete mode 100644 node_modules/workerpool/dist/worker.min.js delete mode 100644 node_modules/workerpool/dist/worker.min.js.map delete mode 100644 node_modules/workerpool/dist/workerpool.js delete mode 100644 node_modules/workerpool/dist/workerpool.js.map delete mode 100644 node_modules/workerpool/dist/workerpool.min.js delete mode 100644 node_modules/workerpool/dist/workerpool.min.js.LICENSE.txt delete mode 100644 node_modules/workerpool/dist/workerpool.min.js.map delete mode 100644 node_modules/workerpool/package.json delete mode 100644 node_modules/workerpool/src/Pool.js delete mode 100644 node_modules/workerpool/src/Promise.js delete mode 100644 node_modules/workerpool/src/WorkerHandler.js delete mode 100644 node_modules/workerpool/src/debug-port-allocator.js delete mode 100644 node_modules/workerpool/src/environment.js delete mode 100644 node_modules/workerpool/src/generated/embeddedWorker.js delete mode 100644 node_modules/workerpool/src/header.js delete mode 100644 node_modules/workerpool/src/index.js delete mode 100644 node_modules/workerpool/src/requireFoolWebpack.js delete mode 100644 node_modules/workerpool/src/transfer.js delete mode 100644 node_modules/workerpool/src/types.js delete mode 100644 node_modules/workerpool/src/validateOptions.js delete mode 100644 node_modules/workerpool/src/worker.js delete mode 100644 node_modules/workerpool/types/Pool.d.ts delete mode 100644 node_modules/workerpool/types/Promise.d.ts delete mode 100644 node_modules/workerpool/types/WorkerHandler.d.ts delete mode 100644 node_modules/workerpool/types/debug-port-allocator.d.ts delete mode 100644 node_modules/workerpool/types/environment.d.ts delete mode 100644 node_modules/workerpool/types/generated/embeddedWorker.d.ts delete mode 100644 node_modules/workerpool/types/index.d.ts delete mode 100644 node_modules/workerpool/types/transfer.d.ts delete mode 100644 node_modules/workerpool/types/types.d.ts delete mode 100644 node_modules/workerpool/types/validateOptions.d.ts delete mode 100644 node_modules/workerpool/types/worker.d.ts diff --git a/commands/debug2.js b/commands/debug2.js index 7f489b76..05f67dcf 100644 --- a/commands/debug2.js +++ b/commands/debug2.js @@ -2,7 +2,6 @@ const vscode = require('vscode'); const fs = require('fs'); const os = require('os'); -const { Worker, isMainThread, parentPort } = require('worker_threads'); const path = require('path'); const LSLIB_DLL = 'LSLib.dll'; @@ -13,30 +12,13 @@ const { lslibPath, rootModPath } = getConfig(); const compatRootModPath = path.join(rootModPath + "\\"); const lslibToolsPath = path.join(lslibPath, TOOL_SUBDIR); -const { CREATE_LOGGER, raiseError, raiseInfo } = require('../support_files/log_utils.js'); -const bg3mh_logger = CREATE_LOGGER(); const { FIND_FILES, getFormats } = require('../support_files/lslib_utils.js'); - + const debug2 = vscode.commands.registerCommand('bg3-mod-helper.debug2Command', async function () { - const config = getConfig(); - const localizationPath = path.join(config.rootModPath, 'Localization'); let halfCoreCount = os.availableParallelism() / 2; - // raiseInfo(`half of your cpu's cores: ${halfCoreCount}`); - - try { - console.log(await FIND_FILES(getFormats().lsx)); - } - catch (err) { - console.error(err); - } - - - // after you are through with this command, the following line must be uncommented and the only thing left for this file to be considered cleaned up. - // raiseInfo("hi dipshit :)"); - - + // const vscode = require('vscode'); }); -module.exports = debug2; +module.exports = { debug2 } diff --git a/commands/packMod.js b/commands/packMod.js index b7e3d603..7a1567c8 100644 --- a/commands/packMod.js +++ b/commands/packMod.js @@ -3,7 +3,7 @@ const path = require('path'); const fs = require('fs'); const { exec } = require('child_process'); -const { getConfig } = require('../support_files/config'); +const { getConfig, getModName } = require('../support_files/config'); const { rootModPath } = getConfig(); const { CREATE_LOGGER, raiseError, raiseInfo } = require('../support_files/log_utils'); @@ -14,7 +14,6 @@ const vscodeDirPath = path.join(rootModPath, '.vscode'); const { v4: uuidv4 } = require('uuid'); const { convert } = require('../support_files/conversion_junction.js'); -const { getModName } = require('../support_files/helper_functions.js'); const { getFormats } = require('../support_files/lslib_utils.js'); const { pak } = getFormats(); @@ -23,7 +22,7 @@ const { pak } = getFormats(); const packModCommand = vscode.commands.registerCommand('bg3-mod-helper.packMod', async function () { raiseInfo("pack button clicked"); const { rootModPath, modDestPath, lslibPath, autoLaunchOnPack } = getConfig(); - const modName = await getModName(); + const modName = getModName(); const modsDirPath = path.normalize(rootModPath + "\\Mods"); const metaPath = path.normalize(modsDirPath + "\\" + modName + "\\meta.lsx"); diff --git a/commands/worker_test.js b/commands/worker_test.js index de606300..27dad586 100644 --- a/commands/worker_test.js +++ b/commands/worker_test.js @@ -1,12 +1,3 @@ -const { CREATE_LOGGER, raiseError, raiseInfo } = require('../support_files/log_utils.js'); -const bg3mh_logger = CREATE_LOGGER(); - -const { parentPort } = require('worker_threads'); - -function test_func() { - raiseInfo("hi dipshit :)"); - return "hi dipshit :)"; - -} - +// const { CREATE_LOGGER, raiseError, raiseInfo } = require('../support_files/log_utils.js'); +// const bg3mh_logger = CREATE_LOGGER(); diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 36e2e4c4..ee0ac817 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,6 +1,6 @@ { "name": "bg3-mod-helper", - "version": "2.2.1", + "version": "3.5.0", "lockfileVersion": 3, "requires": true, "packages": { @@ -1725,11 +1725,6 @@ "string-width": "^1.0.2 || 2 || 3 || 4" } }, - "node_modules/workerpool": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.1.1.tgz", - "integrity": "sha512-EFoFTSEo9m4V4wNrwzVRjxnf/E/oBpOzcI/R5CIugJhl9RsCiq525rszo4AtqcjQQoqFdu2E3H82AnbtpaQHvg==" - }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", diff --git a/node_modules/workerpool/HISTORY.md b/node_modules/workerpool/HISTORY.md deleted file mode 100644 index d5b455b3..00000000 --- a/node_modules/workerpool/HISTORY.md +++ /dev/null @@ -1,395 +0,0 @@ -# workerpool history -https://github.com/josdejong/workerpool - - -## 2024-04-06, version 9.1.1 - -- Fix: events not emitted when using (#439). Thanks @t0oF-azpn. - - -## 2024-01-18, version 9.1.0 - -- Support capturing the stdout/stderr streams from the workers (#425, #423). - Thanks @cpendery. - - -## 2023-12-22, version 9.0.4 - -- Improve the logic to detect the Node.js platform (#421). Thanks @tamuratak. - - -## 2023-12-20, version 9.0.3 - -- Improve types: unwrap Promise types (#419). Thanks @joshkel. - - -## 2023-12-19, version 9.0.2 - -- Export the `Proxy` type (see #417). Thanks @tamuratak. -- Use workerpool's `Promise` type definition (see #417). Thanks @tamuratak. - - -## 2023-12-18, version 9.0.1 - -- Export the types `Pool`, `WorkerPoolOptions`, and `WorkerRegisterOptions`, - see #416. Thanks @joshkel. - - -## 2023-12-18, version 9.0.0 - -BREAKING CHANGE: the library now comes with TypeScript type definitions -included. There may be minor differences between the new, embedded type -definitions and the implementation from `@types/workerpool` that was needed -before. For example, `type WorkerPool` is called `type Pool` now. - -- Generate TypeScript types from JSDoc comments. Thanks @tamuratak. - - -## 2023-10-25, version 8.0.0 - -BREAKING CHANGE: the library now throws an Error when passing unknown or -inherited properties for `workerOpts`, `workerThreadOpts` and `forkOpts`. - -- Fix: throw an error in case of unknown properties or inherited properties - in `workerOpts`, `workerThreadOpts` and `forkOpts` to protect against - security issues related to prototype pollution - (see ea5368c5e53d97120b952ffad151a318c1ff073c). -- Fix: #56 document the return type of all functions. -- Docs: added a full usage example with Vite and Webpack5 (#408), - thanks @KonghaYao. - - -## 2023-10-25, version 7.0.0 - -BREAKING CHANGE: The setup to bundle `workerpool` has been replaced. This should -be a drop-in replacement, but it may have impact depending on your setup. - -- Switched build setup from Webpack to Rollup, see #403. Thanks @KonghaYao. - - -## 2023-10-11, version 6.5.1 - -- Fix: `workerThreadOpts` not working when `workerType: auto`, see #357. - - -## 2023-09-13, version 6.5.0 - -- Implement support for passing options to web workers constructors (#400, - #322). Thanks @DonatJR. - - -## 2023-08-21, version 6.4.2 - -- Fix: a bug in the timeout of termination (#395, #387). Thanks @Michsior14. - - -## 2023-08-17, version 6.4.1 - -- Fix: worker termination before it's ready (#394, #387). Thanks @Michsior14. - - -## 2023-02-24, version 6.4.0 - -- Support transferable objects (#3, #374). Thanks @Michsior14. -- Implement a new callback `onTerminate` at the worker side, which can be used - to clean up resources, and an option `workerTerminateTimeout` which forcefully - terminates a worker if it doesn't finish in time (#353, #377). - Thanks @Michsior14. -- Pass `workerThreadOpts` to the `onTerminateWorker` callback (#376). - Thanks @Michsior14. - - -## 2022-11-07, version 6.3.1 - -- Fix #318: debug ports not being released when terminating a pool. - - -## 2022-10-24, version 6.3.0 - -- Implement option `workerThreadOpts` to pass options to a worker of type - `thread`, a `worker_thread` (#357, fixes #356). Thanks @galElmalah. - -## 2022-04-11, version 6.2.1 - -- Fix #343: `.terminate()` sometimes throwing an exception. - - -## 2022-01-15, version 6.2.0 - -- Implement callbacks `onCreateWorker` and `onTerminateWorker`. Thanks @forty. -- Fix #326: robustness fix when terminating a workerpool. - - -## 2021-06-17, version 6.1.5 - -- Fix v6.1.4 not being marked as latest anymore on npm due to bug fix - release v2.3.4. - - -## 2021-04-05, version 6.1.4 - -- Fix terminating a pool throwing an error when used in the browser. - Regression introduced in `v6.1.3`. - - -## 2021-04-01, version 6.1.3 - -- Fix #147: disregard messages from terminated workers. - Thanks @hhprogram and @Madgvox. - - -## 2021-03-09, version 6.1.2 - -- Fix #253, add `./src` again in the published npm package, reverting the change - in `v6.1.1` (see also #243). - - -## 2021-03-08, version 6.1.1 - -- Remove redundant `./src` folder from the published npm package, see #243. - Thanks @Nytelife26. - - -## 2021-01-31, version 6.1.0 - -- Implemented support for sending events from the worker to the main thread, - see #51, #227. Thanks @Akryum. -- Fix an issue in Node.js nightly, see #230. Thanks @aduh95. -- Fix #232 `workerpool` not working on IE 10. - - -## 2021-01-16, version 6.0.4 - -- Make evaluation of offloaded functions a bit more secure by using - `new Function` instead of `eval`. Thanks @tjenkinson. - - -## 2020-10-28, version 6.0.3 - -- Fixes and more robustness in terminating workers. Thanks @boneskull. - - -## 2020-10-03, version 6.0.2 - -- Fix #32, #175: the promise returned by `Pool.terminate()` now waits until - subprocesses are dead before resolving. Thanks @boneskull. - - -## 2020-09-23, version 6.0.1 - -- Removed examples from the npm package. Thanks @madbence. - - -## 2020-05-13, version 6.0.0 - -BREAKING CHANGE: the library entry points are changed and new source maps are -added. This may have impact on your project depending on your setup. - -- Created separate library entry points in package.json for node.js and browser. - Thanks @boneskull. -- Generated source maps for both minified and non-minified bundles. -- Removed deprecation warnings for `options.nodeWorker` (renamed to - `options.workerType`) and `pool.clear()` (renamed to `pool.terminate()`). - - -## 2019-12-31, version 5.0.4 - -- Fixed #121: `isMainThread` not working when using `worker_threads`. -- Drop official support for node.js 8 (end of life). - - -## 2019-12-23, version 5.0.3 - -- Fixed library not working in the browser. See #106. - - -## 2019-11-06, version 5.0.2 - -- Fixed environment detection in browser. See #106. Thanks @acgrid. - - -## 2019-10-13, version 5.0.1 - -- Fixed #96: WorkerPool not cancelling any pending tasks on termination. - - -## 2019-08-25, version 5.0.0 - -- Deprecated option `nodeWorker` and created a new, more extensive option - `workerType` giving full control over the selected type of worker. - Added new option `'web'` to enforce use a Web Worker. See #85, #74. -- In a node.js environment, the default `workerType` is changed from - `'process'` to `'thread'`. See #85, #50. -- Improved detection of environment (`browser` or `node`), fixing wrong - detection in a Jest test environment. See #85. - - -## 2019-08-21, version 4.0.0 - -- Pass argument `--max-old-space-size` to child processes. Thanks @patte. -- Removed redundant dependencies, upgraded all devDependencies. -- Fixed Webpack issues of missing modules `child_process` and `worker_threads`. - See #43. -- Bundled library changed due to the upgrade to Webpack 4. This could possibly - lead to breaking changes. -- Implemented new option `maxQueueSize`. Thanks @colomboe. -- Fixed exiting workers when the parent process is killed. Thanks @RogerKang. -- Fixed #81: Option `minWorkers: 'max'` not using the configured `maxWorkers`. -- Fixed not passing `nodeWorker` to workers initialized when creating a pool. - Thanks @spacelan. -- Internal restructure of the code: moved from `lib` to `src`. - - -## 2019-03-12, version 3.1.2 - -- Improved error message when a node.js worker unexpectedly exits (see #58). - Thanks @stefanpenner. - -- Allocate debug ports safely, this fixes an issue cause workers to exit - unexpectedly if more then one worker pool is active, and the process is - started with a debugger (`node debug` or `node --inspect`). - Thanks @stefanpenner. - - -## 2019-02-25, version 3.1.1 - -- Fix option `nodeWorker: 'auto'` not using worker threads when available. - Thanks @stefanpenner. - - -## 2019-02-17, version 3.1.0 - -- Implemented support for using `worker_threads` in Node.js, via the new option - `nodeWorker: 'thread'`. Thanks @stefanpenner. - - -## 2018-12-11, version 3.0.0 - -- Enable usage in ES6 Webpack projects. -- Dropped support for AMD module system. - - -## 2021-06-17, version 2.3.4 - -- Backport fix for Node.js 16, see #309. Thanks @mansona. - - -## 2018-09-12, version 2.3.3 - -- Fixed space in license field in `package.json`. Thanks @sagotsky. - - -## 2018-09-08, version 2.3.2 - -- Add licence field to `package.json`. Thanks @greyd. - - -## 2018-07-24, version 2.3.1 - -- Fixed bug where tasks that are cancelled in a Pool's queue - causes following tasks to not run. Thanks @greemo. - - -## 2017-09-30, version 2.3.0 - -- New method `Pool.terminate(force, timeout)` which will replace - `Pool.clear(force)`. Thanks @jimsugg. -- Fixed issue with never terminating zombie child processes. - Thanks @jimsugg. - - -## 2017-08-20, version 2.2.4 - -- Fixed a debug issue: look for `--inspect` within argument strings, - instead of exact match. Thanks @jimsugg. - - -## 2017-08-19, version 2.2.3 - -- Updated all examples to neatly include `.catch(...)` callbacks. - - -## 2017-07-08, version 2.2.2 - -- Fixed #25: timer of a timeout starting when the task is created - instead of when the task is started. Thanks @eclipsesk for input. - - -## 2017-05-07, version 2.2.1 - -- Fixed #2 and #19: support for debugging child processes. Thanks @tptee. - - -## 2016-11-26, version 2.2.0 - -- Implemented #18: method `pool.stats()`. - - -## 2016-10-11, version 2.1.0 - -- Implemented support for registering the workers methods asynchronously. - This enables asynchronous initialization of workers, for example when - using AMD modules. Thanks @natlibfi-arlehiko. -- Implemented environment variables `platform`, `isMainThread`, and `cpus`. - Thanks @natlibfi-arlehiko. -- Implemented option `minWorkers`. Thanks @sergei202. - - -## 2016-09-18, version 2.0.0 - -- Replaced conversion of Error-objecting using serializerr to custom - implementation to prevent issues with serializing/deserializing functions. - This conversion implementation loses the prototype object which means that - e.g. 'TypeError' will become just 'Error' in the main code. See #8. - Thanks @natlibfi-arlehiko. - - -## 2016-09-12, version 1.3.1 - -- Fix for a bug in PhantomJS (see #7). Thanks @natlibfi-arlehiko. - - -## 2016-08-21, version 1.3.0 - -- Determine `maxWorkers` as the number of CPU's minus one in browsers too. See #6. - - -## 2016-06-25, version 1.2.1 - -- Fixed #5 error when loading via AMD or bundling using Webpack. - - -## 2016-05-22, version 1.2.0 - -- Implemented serializing errors with stacktrace. Thanks @mujx. - - -## 2016-01-25, version 1.1.0 - -- Added an error message when wrongly calling `pool.proxy`. -- Fixed function `worker.pool` not accepting both a script and options. See #1. - Thanks @freund17. - - -## 2014-05-29, version 1.0.0 - -- Merged function `Pool.run` into `Pool.exec`, simplifying the API. - - -## 2014-05-14, version 0.2.0 - -- Implemented support for cancelling running tasks. -- Implemented support for cancelling running tasks after a timeout. - - -## 2014-05-07, version 0.1.0 - -- Implemented support for both node.js and the browser. -- Implemented offloading functions. -- Implemented worker proxy. -- Added docs and examples. - - -## 2014-05-02, version 0.0.1 - -- Module name registered at npm. diff --git a/node_modules/workerpool/LICENSE b/node_modules/workerpool/LICENSE deleted file mode 100644 index aabdcfae..00000000 --- a/node_modules/workerpool/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright (C) 2014-2024 Jos de Jong wjosdejong@gmail.com - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/workerpool/README.md b/node_modules/workerpool/README.md deleted file mode 100644 index 22c96b3d..00000000 --- a/node_modules/workerpool/README.md +++ /dev/null @@ -1,530 +0,0 @@ -# workerpool - -**workerpool** offers an easy way to create a pool of workers for both dynamically offloading computations as well as managing a pool of dedicated workers. **workerpool** basically implements a [thread pool pattern](http://en.wikipedia.org/wiki/Thread_pool_pattern). There is a pool of workers to execute tasks. New tasks are put in a queue. A worker executes one task at a time, and once finished, picks a new task from the queue. Workers can be accessed via a natural, promise based proxy, as if they are available straight in the main application. - -**workerpool** runs on node.js, Chrome, Firefox, Opera, Safari, and IE10+. - -## Features - -- Easy to use -- Runs in the browser and on node.js -- Dynamically offload functions to a worker -- Access workers via a proxy -- Cancel running tasks -- Set a timeout on tasks -- Handles crashed workers -- Small: 7 kB minified and gzipped -- Supports transferable objects (only for web workers and worker_threads) - -## Why - -JavaScript is based upon a single event loop which handles one event at a time. Jeremy Epstein [explains this clearly](http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/): - -> In Node.js everything runs in parallel, except your code. -> What this means is that all I/O code that you write in Node.js is non-blocking, -> while (conversely) all non-I/O code that you write in Node.js is blocking. - -This means that CPU heavy tasks will block other tasks from being executed. In case of a browser environment, the browser will not react to user events like a mouse click while executing a CPU intensive task (the browser "hangs"). In case of a node.js server, the server will not respond to any new request while executing a single, heavy request. - -For front-end processes, this is not a desired situation. -Therefore, CPU intensive tasks should be offloaded from the main event loop onto dedicated _workers_. In a browser environment, [Web Workers](http://www.html5rocks.com/en/tutorials/workers/basics/) can be used. In node.js, [child processes](https://nodejs.org/api/child_process.html) and [worker_threads](https://nodejs.org/api/worker_threads.html) are available. An application should be split in separate, decoupled parts, which can run independent of each other in a parallelized way. Effectively, this results in an architecture which achieves concurrency by means of isolated processes and message passing. - -## Install - -Install via npm: - - npm install workerpool - -## Load - -To load workerpool in a node.js application (both main application as well as workers): - -```js -const workerpool = require('workerpool'); -``` - -To load workerpool in the browser: - -```html - -``` - -To load workerpool in a web worker in the browser: - -```js -importScripts('workerpool.js'); -``` - -## Use - -### Offload functions dynamically - -In the following example there is a function `add`, which is offloaded dynamically to a worker to be executed for a given set of arguments. - -**myApp.js** - -```js -const workerpool = require('workerpool'); -const pool = workerpool.pool(); - -function add(a, b) { - return a + b; -} - -pool - .exec(add, [3, 4]) - .then(function (result) { - console.log('result', result); // outputs 7 - }) - .catch(function (err) { - console.error(err); - }) - .then(function () { - pool.terminate(); // terminate all workers when done - }); -``` - -Note that both function and arguments must be static and stringifiable, as they need to be sent to the worker in a serialized form. In case of large functions or function arguments, the overhead of sending the data to the worker can be significant. - -### Dedicated workers - -A dedicated worker can be created in a separate script, and then used via a worker pool. - -**myWorker.js** - -```js -const workerpool = require('workerpool'); - -// a deliberately inefficient implementation of the fibonacci sequence -function fibonacci(n) { - if (n < 2) return n; - return fibonacci(n - 2) + fibonacci(n - 1); -} - -// create a worker and register public functions -workerpool.worker({ - fibonacci: fibonacci, -}); -``` - -This worker can be used by a worker pool: - -**myApp.js** - -```js -const workerpool = require('workerpool'); - -// create a worker pool using an external worker script -const pool = workerpool.pool(__dirname + '/myWorker.js'); - -// run registered functions on the worker via exec -pool - .exec('fibonacci', [10]) - .then(function (result) { - console.log('Result: ' + result); // outputs 55 - }) - .catch(function (err) { - console.error(err); - }) - .then(function () { - pool.terminate(); // terminate all workers when done - }); - -// or run registered functions on the worker via a proxy: -pool - .proxy() - .then(function (worker) { - return worker.fibonacci(10); - }) - .then(function (result) { - console.log('Result: ' + result); // outputs 55 - }) - .catch(function (err) { - console.error(err); - }) - .then(function () { - pool.terminate(); // terminate all workers when done - }); -``` - -Worker can also initialize asynchronously: - -**myAsyncWorker.js** - -```js -define(['workerpool/dist/workerpool'], function (workerpool) { - // a deliberately inefficient implementation of the fibonacci sequence - function fibonacci(n) { - if (n < 2) return n; - return fibonacci(n - 2) + fibonacci(n - 1); - } - - // create a worker and register public functions - workerpool.worker({ - fibonacci: fibonacci, - }); -}); -``` - -## Examples - -Examples are available in the examples directory: - -[https://github.com/josdejong/workerpool/tree/master/examples](https://github.com/josdejong/workerpool/tree/master/examples) - -## API - -The API of workerpool consists of two parts: a function `workerpool.pool` to create a worker pool, and a function `workerpool.worker` to create a worker. - -### pool - -A workerpool can be created using the function `workerpool.pool`: - -`workerpool.pool([script: string] [, options: Object]) : Pool` - -When a `script` argument is provided, the provided script will be started as a dedicated worker. When no `script` argument is provided, a default worker is started which can be used to offload functions dynamically via `Pool.exec`. Note that on node.js, `script` must be an absolute file path like `__dirname + '/myWorker.js'`. In a browser environment, `script` can also be a data URL like `'data:application/javascript;base64,...'`. This allows embedding the bundled code of a worker in your main application. See `examples/embeddedWorker` for a demo. - -The following options are available: - -- `minWorkers: number | 'max'`. The minimum number of workers that must be initialized and kept available. Setting this to `'max'` will create `maxWorkers` default workers (see below). -- `maxWorkers: number`. The default number of maxWorkers is the number of CPU's minus one. When the number of CPU's could not be determined (for example in older browsers), `maxWorkers` is set to 3. -- `maxQueueSize: number`. The maximum number of tasks allowed to be queued. Can be used to prevent running out of memory. If the maximum is exceeded, adding a new task will throw an error. The default value is `Infinity`. -- `workerType: 'auto' | 'web' | 'process' | 'thread'`. - - In case of `'auto'` (default), workerpool will automatically pick a suitable type of worker: when in a browser environment, `'web'` will be used. When in a node.js environment, `worker_threads` will be used if available (Node.js >= 11.7.0), else `child_process` will be used. - - In case of `'web'`, a Web Worker will be used. Only available in a browser environment. - - In case of `'process'`, `child_process` will be used. Only available in a node.js environment. - - In case of `'thread'`, `worker_threads` will be used. If `worker_threads` are not available, an error is thrown. Only available in a node.js environment. -- `workerTerminateTimeout: number`. The timeout in milliseconds to wait for a worker to cleanup it's resources on termination before stopping it forcefully. Default value is `1000`. -- `forkArgs: String[]`. For `process` worker type. An array passed as `args` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options) -- `forkOpts: Object`. For `process` worker type. An object passed as `options` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options). See nodejs documentation for available options. -- `workerOpts: Object`. For `web` worker type. An object passed to the [constructor of the web worker](https://html.spec.whatwg.org/multipage/workers.html#dom-worker). See [WorkerOptions specification](https://html.spec.whatwg.org/multipage/workers.html#workeroptions) for available options. -- `workerThreadOpts: Object`. For `worker` worker type. An object passed to [worker_threads.options](https://nodejs.org/api/worker_threads.html#new-workerfilename-options). See nodejs documentation for available options. -- `onCreateWorker: Function`. A callback that is called whenever a worker is being created. It can be used to allocate resources for each worker for example. The callback is passed as argument an object with the following properties: - - `forkArgs: String[]`: the `forkArgs` option of this pool - - `forkOpts: Object`: the `forkOpts` option of this pool - - `workerOpts: Object`: the `workerOpts` option of this pool - - `script: string`: the `script` option of this pool - Optionally, this callback can return an object containing one or more of the above properties. The provided properties will be used to override the Pool properties for the worker being created. -- `onTerminateWorker: Function`. A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The callback is passed as argument an object as described for `onCreateWorker`, with each property sets with the value for the worker being terminated. -- `emitStdStreams: boolean`. For `process` or `thread` worker type. If `true`, the worker will emit `stdout` and `stderr` events instead of passing it through to the parent streams. Default value is `false`. - -> Important note on `'workerType'`: when sending and receiving primitive data types (plain JSON) from and to a worker, the different worker types (`'web'`, `'process'`, `'thread'`) can be used interchangeably. However, when using more advanced data types like buffers, the API and returned results can vary. In these cases, it is best not to use the `'auto'` setting but have a fixed `'workerType'` and good unit testing in place. - -A worker pool contains the following functions: - -- `Pool.exec(method: Function | string, params: Array | null [, options: Object]) : Promise`
- Execute a function on a worker with given arguments. - - - When `method` is a string, a method with this name must exist at the worker and must be registered to make it accessible via the pool. The function will be executed on the worker with given parameters. - - When `method` is a function, the provided function `fn` will be stringified, send to the worker, and executed there with the provided parameters. The provided function must be static, it must not depend on variables in a surrounding scope. - - The following options are available: - - `on: (payload: any) => void`. An event listener, to handle events sent by the worker for this execution. See [Events](#events) for more details. - - `transfer: Object[]`. A list of transferable objects to send to the worker. Not supported by `process` worker type. See [example](./examples/transferableObjects.js) for usage. - -- `Pool.proxy() : Promise`
- Create a proxy for the worker pool. The proxy contains a proxy for all methods available on the worker. All methods return promises resolving the methods result. - -- `Pool.stats() : Object`
- Retrieve statistics on workers, and active and pending tasks. - - Returns an object containing the following properties: - - ``` - { - totalWorkers: 0, - busyWorkers: 0, - idleWorkers: 0, - pendingTasks: 0, - activeTasks: 0 - } - ``` - -- `Pool.terminate([force: boolean [, timeout: number]]) : Promise` - - If parameter `force` is false (default), workers will finish the tasks they are working on before terminating themselves. Any pending tasks will be rejected with an error 'Pool terminated'. When `force` is true, all workers are terminated immediately without finishing running tasks. If `timeout` is provided, worker will be forced to terminate when the timeout expires and the worker has not finished. - -The function `Pool.exec` and the proxy functions all return a `Promise`. The promise has the following functions available: - -- `Promise.then(fn: Function) : Promise`
- Get the result of the promise once resolve. -- `Promise.catch(fn: Function) : Promise`
- Get the error of the promise when rejected. -- `Promise.cancel() : Promise`
- A running task can be cancelled. The worker executing the task is enforced to terminate immediately. - The promise will be rejected with a `Promise.CancellationError`. -- `Promise.timeout(delay: number) : Promise`
- Cancel a running task when it is not resolved or rejected within given delay in milliseconds. The timer will start when the task is actually started, not when the task is created and queued. - The worker executing the task is enforced to terminate immediately. - The promise will be rejected with a `Promise.TimeoutError`. - -Example usage: - -```js -const workerpool = require('workerpool'); - -function add(a, b) { - return a + b; -} - -const pool1 = workerpool.pool(); - -// offload a function to a worker -pool1 - .exec(add, [2, 4]) - .then(function (result) { - console.log(result); // will output 6 - }) - .catch(function (err) { - console.error(err); - }); - -// create a dedicated worker -const pool2 = workerpool.pool(__dirname + '/myWorker.js'); - -// supposed myWorker.js contains a function 'fibonacci' -pool2 - .exec('fibonacci', [10]) - .then(function (result) { - console.log(result); // will output 55 - }) - .catch(function (err) { - console.error(err); - }); - -// send a transferable object to the worker -// supposed myWorker.js contains a function 'sum' -const toTransfer = new Uint8Array(2).map((_v, i) => i) -pool2 - .exec('sum', [toTransfer], { transfer: [toTransfer.buffer] }) - .then(function (result) { - console.log(result); // will output 3 - }) - .catch(function (err) { - console.error(err); - }); - -// create a proxy to myWorker.js -pool2 - .proxy() - .then(function (myWorker) { - return myWorker.fibonacci(10); - }) - .then(function (result) { - console.log(result); // will output 55 - }) - .catch(function (err) { - console.error(err); - }); - -// create a pool with a specified maximum number of workers -const pool3 = workerpool.pool({ maxWorkers: 7 }); -``` - -### worker - -A worker is constructed as: - -`workerpool.worker([methods: Object] [, options: Object]) : void` - -Argument `methods` is optional and can be an object with functions available in the worker. Registered functions will be available via the worker pool. - -The following options are available: - -- `onTerminate: ([code: number]) => Promise | void`. A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The difference with pool's `onTerminateWorker` is that this callback runs in the worker context, while `onTerminateWorker` is executed on the main thread. - - -Example usage: - -```js -// file myWorker.js -const workerpool = require('workerpool'); - -function add(a, b) { - return a + b; -} - -function multiply(a, b) { - return a * b; -} - -// create a worker and register functions -workerpool.worker({ - add: add, - multiply: multiply, -}); -``` - -Asynchronous results can be handled by returning a Promise from a function in the worker: - -```js -// file myWorker.js -const workerpool = require('workerpool'); - -function timeout(delay) { - return new Promise(function (resolve, reject) { - setTimeout(resolve, delay); - }); -} - -// create a worker and register functions -workerpool.worker({ - timeout: timeout, -}); -``` - -Transferable objects can be sent back to the pool using `Transfer` helper class: - -```js -// file myWorker.js -const workerpool = require('workerpool'); - -function array(size) { - var array = new Uint8Array(size).map((_v, i) => i); - return new workerpool.Transfer(array, [array.buffer]); -} - -// create a worker and register functions -workerpool.worker({ - array: array, -}); -``` - -### Events - -You can send data back from workers to the pool while the task is being executed using the `workerEmit` function: - -`workerEmit(payload: any) : unknown` - -This function only works inside a worker **and** during a task. - -Example: - -```js -// file myWorker.js -const workerpool = require('workerpool'); - -function eventExample(delay) { - workerpool.workerEmit({ - status: 'in_progress', - }); - - workerpool.workerEmit({ - status: 'complete', - }); - - return true; -} - -// create a worker and register functions -workerpool.worker({ - eventExample: eventExample, -}); -``` - -To receive those events, you can use the `on` option of the pool `exec` method: - -```js -pool.exec('eventExample', [], { - on: function (payload) { - if (payload.status === 'in_progress') { - console.log('In progress...'); - } else if (payload.status === 'complete') { - console.log('Done!'); - } - }, -}); -``` - -### Utilities - -Following properties are available for convenience: - -- **platform**: The Javascript platform. Either _node_ or _browser_ -- **isMainThread**: Whether the code is running in main thread or not (Workers) -- **cpus**: The number of CPUs/cores available - -## Roadmap - -- Implement functions for parallel processing: `map`, `reduce`, `forEach`, - `filter`, `some`, `every`, ... -- Implement graceful degradation on old browsers not supporting webworkers: - fallback to processing tasks in the main application. -- Implement session support: be able to handle a series of related tasks by a - single worker, which can keep a state for the session. - -## Related libraries - -- https://github.com/andywer/threads.js -- https://github.com/piscinajs/piscina -- https://github.com/learnboost/cluster -- https://github.com/adambom/parallel.js -- https://github.com/padolsey/operative -- https://github.com/calvinmetcalf/catiline -- https://github.com/Unitech/pm2 -- https://github.com/godaddy/node-cluster-service -- https://github.com/ramesaliyev/EasyWebWorker -- https://github.com/rvagg/node-worker-farm - -## Build - -First clone the project from github: - - git clone git://github.com/josdejong/workerpool.git - cd workerpool - -Install the project dependencies: - - npm install - -Then, the project can be build by executing the build script via npm: - - npm run build - -This will build the library workerpool.js and workerpool.min.js from the source -files and put them in the folder dist. - -## Test - -To execute tests for the library, install the project dependencies once: - - npm install - -Then, the tests can be executed: - - npm test - -To test code coverage of the tests: - - npm run coverage - -To see the coverage results, open the generated report in your browser: - - ./coverage/index.html - -## Publish - -- Describe changes in HISTORY.md -- Update version in package.json, run `npm install` to update it in `package-lock.json` too. -- Push to Github -- Deploy to npm via `npm publish` -- Add a git tag with the version number like: - ``` - git tag v1.2.3 - git push --tags - ``` - -## License - -Copyright (C) 2014-2024 Jos de Jong - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/node_modules/workerpool/dist/worker.js b/node_modules/workerpool/dist/worker.js deleted file mode 100644 index 9e43c46d..00000000 --- a/node_modules/workerpool/dist/worker.js +++ /dev/null @@ -1,288 +0,0 @@ -/** - * workerpool.js - * https://github.com/josdejong/workerpool - * - * Offload tasks to a pool of workers on node.js and in the browser. - * - * @version 9.1.1 - * @date 2024-04-06 - * - * @license - * Copyright (C) 2014-2022 Jos de Jong - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.worker = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var worker$1 = {}; - - /** - * The helper class for transferring data from the worker to the main thread. - * - * @param {Object} message The object to deliver to the main thread. - * @param {Object[]} transfer An array of transferable Objects to transfer ownership of. - */ - function Transfer(message, transfer) { - this.message = message; - this.transfer = transfer; - } - var transfer = Transfer; - - /** - * worker must be started as a child process or a web worker. - * It listens for RPC messages from the parent process. - */ - (function (exports) { - var Transfer = transfer; - - /** - * Special message sent by parent which causes the worker to terminate itself. - * Not a "message object"; this string is the entire message. - */ - var TERMINATE_METHOD_ID = '__workerpool-terminate__'; - - // var nodeOSPlatform = require('./environment').nodeOSPlatform; - - // create a worker API for sending and receiving messages which works both on - // node.js and in the browser - var worker = { - exit: function () {} - }; - if (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') { - // worker in the browser - worker.on = function (event, callback) { - addEventListener(event, function (message) { - callback(message.data); - }); - }; - worker.send = function (message) { - postMessage(message); - }; - } else if (typeof process !== 'undefined') { - // node.js - - var WorkerThreads; - try { - WorkerThreads = require('worker_threads'); - } catch (error) { - if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') ; else { - throw error; - } - } - if (WorkerThreads && /* if there is a parentPort, we are in a WorkerThread */ - WorkerThreads.parentPort !== null) { - var parentPort = WorkerThreads.parentPort; - worker.send = parentPort.postMessage.bind(parentPort); - worker.on = parentPort.on.bind(parentPort); - worker.exit = process.exit.bind(process); - } else { - worker.on = process.on.bind(process); - // ignore transfer argument since it is not supported by process - worker.send = function (message) { - process.send(message); - }; - // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly - worker.on('disconnect', function () { - process.exit(1); - }); - worker.exit = process.exit.bind(process); - } - } else { - throw new Error('Script must be executed as a worker'); - } - function convertError(error) { - return Object.getOwnPropertyNames(error).reduce(function (product, name) { - return Object.defineProperty(product, name, { - value: error[name], - enumerable: true - }); - }, {}); - } - - /** - * Test whether a value is a Promise via duck typing. - * @param {*} value - * @returns {boolean} Returns true when given value is an object - * having functions `then` and `catch`. - */ - function isPromise(value) { - return value && typeof value.then === 'function' && typeof value.catch === 'function'; - } - - // functions available externally - worker.methods = {}; - - /** - * Execute a function with provided arguments - * @param {String} fn Stringified function - * @param {Array} [args] Function arguments - * @returns {*} - */ - worker.methods.run = function run(fn, args) { - var f = new Function('return (' + fn + ').apply(null, arguments);'); - return f.apply(f, args); - }; - - /** - * Get a list with methods available on this worker - * @return {String[]} methods - */ - worker.methods.methods = function methods() { - return Object.keys(worker.methods); - }; - - /** - * Custom handler for when the worker is terminated. - */ - worker.terminationHandler = undefined; - - /** - * Cleanup and exit the worker. - * @param {Number} code - * @returns - */ - worker.cleanupAndExit = function (code) { - var _exit = function () { - worker.exit(code); - }; - if (!worker.terminationHandler) { - return _exit(); - } - var result = worker.terminationHandler(code); - if (isPromise(result)) { - result.then(_exit, _exit); - } else { - _exit(); - } - }; - var currentRequestId = null; - worker.on('message', function (request) { - if (request === TERMINATE_METHOD_ID) { - return worker.cleanupAndExit(0); - } - try { - var method = worker.methods[request.method]; - if (method) { - currentRequestId = request.id; - - // execute the function - var result = method.apply(method, request.params); - if (isPromise(result)) { - // promise returned, resolve this and then return - result.then(function (result) { - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - currentRequestId = null; - }).catch(function (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - currentRequestId = null; - }); - } else { - // immediate result - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - currentRequestId = null; - } - } else { - throw new Error('Unknown method "' + request.method + '"'); - } - } catch (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - } - }); - - /** - * Register methods to the worker - * @param {Object} [methods] - * @param {import('./types.js').WorkerRegisterOptions} [options] - */ - worker.register = function (methods, options) { - if (methods) { - for (var name in methods) { - if (methods.hasOwnProperty(name)) { - worker.methods[name] = methods[name]; - } - } - } - if (options) { - worker.terminationHandler = options.onTerminate; - } - worker.send('ready'); - }; - worker.emit = function (payload) { - if (currentRequestId) { - if (payload instanceof Transfer) { - worker.send({ - id: currentRequestId, - isEvent: true, - payload: payload.message - }, payload.transfer); - return; - } - worker.send({ - id: currentRequestId, - isEvent: true, - payload - }); - } - }; - { - exports.add = worker.register; - exports.emit = worker.emit; - } - })(worker$1); - var worker = /*@__PURE__*/getDefaultExportFromCjs(worker$1); - - return worker; - -})); -//# sourceMappingURL=worker.js.map diff --git a/node_modules/workerpool/dist/worker.js.map b/node_modules/workerpool/dist/worker.js.map deleted file mode 100644 index 59e653bb..00000000 --- a/node_modules/workerpool/dist/worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"worker.js","sources":["../src/transfer.js","../src/worker.js"],"sourcesContent":["/**\n * The helper class for transferring data from the worker to the main thread.\n *\n * @param {Object} message The object to deliver to the main thread.\n * @param {Object[]} transfer An array of transferable Objects to transfer ownership of.\n */\nfunction Transfer(message, transfer) {\n this.message = message;\n this.transfer = transfer;\n}\n\nmodule.exports = Transfer;\n","/**\n * worker must be started as a child process or a web worker.\n * It listens for RPC messages from the parent process.\n */\nvar Transfer = require('./transfer');\n\n/**\n * Special message sent by parent which causes the worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\n// var nodeOSPlatform = require('./environment').nodeOSPlatform;\n\n// create a worker API for sending and receiving messages which works both on\n// node.js and in the browser\nvar worker = {\n exit: function() {}\n};\nif (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') {\n // worker in the browser\n worker.on = function (event, callback) {\n addEventListener(event, function (message) {\n callback(message.data);\n })\n };\n worker.send = function (message) {\n postMessage(message);\n };\n}\nelse if (typeof process !== 'undefined') {\n // node.js\n\n var WorkerThreads;\n try {\n WorkerThreads = require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads, fallback to sub-process based workers\n } else {\n throw error;\n }\n }\n\n if (WorkerThreads &&\n /* if there is a parentPort, we are in a WorkerThread */\n WorkerThreads.parentPort !== null) {\n var parentPort = WorkerThreads.parentPort;\n worker.send = parentPort.postMessage.bind(parentPort);\n worker.on = parentPort.on.bind(parentPort);\n worker.exit = process.exit.bind(process);\n } else {\n worker.on = process.on.bind(process);\n // ignore transfer argument since it is not supported by process\n worker.send = function (message) {\n process.send(message);\n };\n // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly\n worker.on('disconnect', function () {\n process.exit(1);\n });\n worker.exit = process.exit.bind(process);\n }\n}\nelse {\n throw new Error('Script must be executed as a worker');\n}\n\nfunction convertError(error) {\n return Object.getOwnPropertyNames(error).reduce(function(product, name) {\n return Object.defineProperty(product, name, {\n\tvalue: error[name],\n\tenumerable: true\n });\n }, {});\n}\n\n/**\n * Test whether a value is a Promise via duck typing.\n * @param {*} value\n * @returns {boolean} Returns true when given value is an object\n * having functions `then` and `catch`.\n */\nfunction isPromise(value) {\n return value && (typeof value.then === 'function') && (typeof value.catch === 'function');\n}\n\n// functions available externally\nworker.methods = {};\n\n/**\n * Execute a function with provided arguments\n * @param {String} fn Stringified function\n * @param {Array} [args] Function arguments\n * @returns {*}\n */\nworker.methods.run = function run(fn, args) {\n var f = new Function('return (' + fn + ').apply(null, arguments);');\n return f.apply(f, args);\n};\n\n/**\n * Get a list with methods available on this worker\n * @return {String[]} methods\n */\nworker.methods.methods = function methods() {\n return Object.keys(worker.methods);\n};\n\n/**\n * Custom handler for when the worker is terminated.\n */\nworker.terminationHandler = undefined;\n\n/**\n * Cleanup and exit the worker.\n * @param {Number} code \n * @returns \n */\nworker.cleanupAndExit = function(code) {\n var _exit = function() {\n worker.exit(code);\n }\n\n if(!worker.terminationHandler) {\n return _exit();\n }\n\n var result = worker.terminationHandler(code);\n if (isPromise(result)) {\n result.then(_exit, _exit);\n } else {\n _exit();\n }\n}\n\nvar currentRequestId = null;\n\nworker.on('message', function (request) {\n if (request === TERMINATE_METHOD_ID) {\n return worker.cleanupAndExit(0);\n }\n try {\n var method = worker.methods[request.method];\n\n if (method) {\n currentRequestId = request.id;\n \n // execute the function\n var result = method.apply(method, request.params);\n\n if (isPromise(result)) {\n // promise returned, resolve this and then return\n result\n .then(function (result) {\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n currentRequestId = null;\n })\n .catch(function (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n currentRequestId = null;\n });\n }\n else {\n // immediate result\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n\n currentRequestId = null;\n }\n }\n else {\n throw new Error('Unknown method \"' + request.method + '\"');\n }\n }\n catch (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n }\n});\n\n/**\n * Register methods to the worker\n * @param {Object} [methods]\n * @param {import('./types.js').WorkerRegisterOptions} [options]\n */\nworker.register = function (methods, options) {\n\n if (methods) {\n for (var name in methods) {\n if (methods.hasOwnProperty(name)) {\n worker.methods[name] = methods[name];\n }\n }\n }\n\n if (options) {\n worker.terminationHandler = options.onTerminate;\n }\n\n worker.send('ready');\n};\n\nworker.emit = function (payload) {\n if (currentRequestId) {\n if (payload instanceof Transfer) {\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload: payload.message\n }, payload.transfer);\n return;\n }\n\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload\n });\n }\n};\n\nif (typeof exports !== 'undefined') {\n exports.add = worker.register;\n exports.emit = worker.emit;\n}\n"],"names":["Transfer","message","transfer","require$$0","TERMINATE_METHOD_ID","worker","exit","self","postMessage","addEventListener","on","event","callback","data","send","process","WorkerThreads","require","error","code","parentPort","bind","Error","convertError","Object","getOwnPropertyNames","reduce","product","name","defineProperty","value","enumerable","isPromise","then","catch","methods","run","fn","args","f","Function","apply","keys","terminationHandler","undefined","cleanupAndExit","_exit","result","currentRequestId","request","method","id","params","err","register","options","hasOwnProperty","onTerminate","emit","payload","isEvent","exports","add"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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GAAA;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/workerpool/dist/worker.min.js b/node_modules/workerpool/dist/worker.min.js deleted file mode 100644 index c238a0d3..00000000 --- a/node_modules/workerpool/dist/worker.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if("undefined"!=typeof self&&"function"==typeof postMessage&&"function"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if("undefined"==typeof process)throw new Error("Script must be executed as a worker");var o;try{o=require("worker_threads")}catch(e){if("object"!=typeof e||null===e||"MODULE_NOT_FOUND"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on("disconnect",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&"function"==typeof e.then&&"function"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function("return ("+e+").apply(null, arguments);");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on("message",(function(e){if("__workerpool-terminate__"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error('Unknown method "'+e.method+'"');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send("ready")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)})); -//# sourceMappingURL=worker.min.js.map diff --git a/node_modules/workerpool/dist/worker.min.js.map b/node_modules/workerpool/dist/worker.min.js.map deleted file mode 100644 index 9b9f03f5..00000000 --- a/node_modules/workerpool/dist/worker.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"worker.min.js","sources":["../src/transfer.js","../src/worker.js"],"sourcesContent":["/**\n * The helper class for transferring data from the worker to the main thread.\n *\n * @param {Object} message The object to deliver to the main thread.\n * @param {Object[]} transfer An array of transferable Objects to transfer ownership of.\n */\nfunction Transfer(message, transfer) {\n this.message = message;\n this.transfer = transfer;\n}\n\nmodule.exports = Transfer;\n","/**\n * worker must be started as a child process or a web worker.\n * It listens for RPC messages from the parent process.\n */\nvar Transfer = require('./transfer');\n\n/**\n * Special message sent by parent which causes the worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\n// var nodeOSPlatform = require('./environment').nodeOSPlatform;\n\n// create a worker API for sending and receiving messages which works both on\n// node.js and in the browser\nvar worker = {\n exit: function() {}\n};\nif (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') {\n // worker in the browser\n worker.on = function (event, callback) {\n addEventListener(event, function (message) {\n callback(message.data);\n })\n };\n worker.send = function (message) {\n postMessage(message);\n };\n}\nelse if (typeof process !== 'undefined') {\n // node.js\n\n var WorkerThreads;\n try {\n WorkerThreads = require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads, fallback to sub-process based workers\n } else {\n throw error;\n }\n }\n\n if (WorkerThreads &&\n /* if there is a parentPort, we are in a WorkerThread */\n WorkerThreads.parentPort !== null) {\n var parentPort = WorkerThreads.parentPort;\n worker.send = parentPort.postMessage.bind(parentPort);\n worker.on = parentPort.on.bind(parentPort);\n worker.exit = process.exit.bind(process);\n } else {\n worker.on = process.on.bind(process);\n // ignore transfer argument since it is not supported by process\n worker.send = function (message) {\n process.send(message);\n };\n // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly\n worker.on('disconnect', function () {\n process.exit(1);\n });\n worker.exit = process.exit.bind(process);\n }\n}\nelse {\n throw new Error('Script must be executed as a worker');\n}\n\nfunction convertError(error) {\n return Object.getOwnPropertyNames(error).reduce(function(product, name) {\n return Object.defineProperty(product, name, {\n\tvalue: error[name],\n\tenumerable: true\n });\n }, {});\n}\n\n/**\n * Test whether a value is a Promise via duck typing.\n * @param {*} value\n * @returns {boolean} Returns true when given value is an object\n * having functions `then` and `catch`.\n */\nfunction isPromise(value) {\n return value && (typeof value.then === 'function') && (typeof value.catch === 'function');\n}\n\n// functions available externally\nworker.methods = {};\n\n/**\n * Execute a function with provided arguments\n * @param {String} fn Stringified function\n * @param {Array} [args] Function arguments\n * @returns {*}\n */\nworker.methods.run = function run(fn, args) {\n var f = new Function('return (' + fn + ').apply(null, arguments);');\n return f.apply(f, args);\n};\n\n/**\n * Get a list with methods available on this worker\n * @return {String[]} methods\n */\nworker.methods.methods = function methods() {\n return Object.keys(worker.methods);\n};\n\n/**\n * Custom handler for when the worker is terminated.\n */\nworker.terminationHandler = undefined;\n\n/**\n * Cleanup and exit the worker.\n * @param {Number} code \n * @returns \n */\nworker.cleanupAndExit = function(code) {\n var _exit = function() {\n worker.exit(code);\n }\n\n if(!worker.terminationHandler) {\n return _exit();\n }\n\n var result = worker.terminationHandler(code);\n if (isPromise(result)) {\n result.then(_exit, _exit);\n } else {\n _exit();\n }\n}\n\nvar currentRequestId = null;\n\nworker.on('message', function (request) {\n if (request === TERMINATE_METHOD_ID) {\n return worker.cleanupAndExit(0);\n }\n try {\n var method = worker.methods[request.method];\n\n if (method) {\n currentRequestId = request.id;\n \n // execute the function\n var result = method.apply(method, request.params);\n\n if (isPromise(result)) {\n // promise returned, resolve this and then return\n result\n .then(function (result) {\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n currentRequestId = null;\n })\n .catch(function (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n currentRequestId = null;\n });\n }\n else {\n // immediate result\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n\n currentRequestId = null;\n }\n }\n else {\n throw new Error('Unknown method \"' + request.method + '\"');\n }\n }\n catch (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n }\n});\n\n/**\n * Register methods to the worker\n * @param {Object} [methods]\n * @param {import('./types.js').WorkerRegisterOptions} [options]\n */\nworker.register = function (methods, options) {\n\n if (methods) {\n for (var name in methods) {\n if (methods.hasOwnProperty(name)) {\n worker.methods[name] = methods[name];\n }\n }\n }\n\n if (options) {\n worker.terminationHandler = options.onTerminate;\n }\n\n worker.send('ready');\n};\n\nworker.emit = function (payload) {\n if (currentRequestId) {\n if (payload instanceof Transfer) {\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload: payload.message\n }, payload.transfer);\n return;\n }\n\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload\n });\n }\n};\n\nif (typeof exports !== 'undefined') {\n exports.add = worker.register;\n exports.emit = worker.emit;\n}\n"],"names":["transfer","message","this","Transfer","require$$0","worker","exit","self","postMessage","addEventListener","on","event","callback","data","send","process","Error","WorkerThreads","require","error","code","parentPort","bind","convertError","Object","getOwnPropertyNames","reduce","product","name","defineProperty","value","enumerable","isPromise","then","catch","methods","run","fn","args","f","Function","apply","keys","terminationHandler","undefined","cleanupAndExit","_exit","result","currentRequestId","request","method","id","params","err","register","options","hasOwnProperty","onTerminate","emit","payload","isEvent","exports","add"],"mappings":"oVAWA,IAAAA,EALA,SAAkBC,EAASD,GACzBE,KAAKD,QAAUA,EACfC,KAAKF,SAAWA,CAClB,qBCLA,IAAIG,EAAWC,EAYXC,EAAS,CACXC,KAAM,WAAa,GAErB,GAAoB,oBAATC,MAA+C,mBAAhBC,aAA0D,mBAArBC,iBAE7EJ,EAAOK,GAAK,SAAUC,EAAOC,GAC3BH,iBAAiBE,GAAO,SAAUV,GAChCW,EAASX,EAAQY,KACvB,KAEER,EAAOS,KAAO,SAAUb,GACtBO,YAAYP,QAGX,IAAuB,oBAAZc,QAmCd,MAAM,IAAIC,MAAM,uCAhChB,IAAIC,EACJ,IACEA,EAAgBC,QAAQ,iBACzB,CAAC,MAAMC,GACN,GAAqB,iBAAVA,GAAgC,OAAVA,GAAiC,qBAAfA,EAAMC,KAGvD,MAAMD,CAET,CAED,GAAIF,GAE2B,OAA7BA,EAAcI,WAAqB,CACnC,IAAIA,EAAcJ,EAAcI,WAChChB,EAAOS,KAAOO,EAAWb,YAAYc,KAAKD,GAC1ChB,EAAOK,GAAKW,EAAWX,GAAGY,KAAKD,GAC/BhB,EAAOC,KAAOS,QAAQT,KAAKgB,KAAKP,QACpC,MACIV,EAAOK,GAAKK,QAAQL,GAAGY,KAAKP,SAE5BV,EAAOS,KAAO,SAAUb,GACtBc,QAAQD,KAAKb,IAGfI,EAAOK,GAAG,cAAc,WACtBK,QAAQT,KAAK,EACnB,IACID,EAAOC,KAAOS,QAAQT,KAAKgB,KAAKP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A,EACR5B,MAAO,OAGX6B,EAAmB,IACjC,IACad,OAAM,SAAUmB,GACfhD,EAAOS,KAAK,CACVqC,GAAIF,EAAQE,GACZJ,OAAQ,KACR5B,MAAOI,EAAa8B,KAEtBL,EAAmB,IACjC,KAIYD,aAAkB5C,EACpBE,EAAOS,KAAK,CACVqC,GAAIF,EAAQE,GACZJ,OAAQA,EAAO9C,QACfkB,MAAO,MACN4B,EAAO/C,UAEVK,EAAOS,KAAK,CACVqC,GAAIF,EAAQE,GACZJ,OAAQA,EACR5B,MAAO,OAIX6B,EAAmB,KAMxB,CACD,MAAOK,GACLhD,EAAOS,KAAK,CACVqC,GAAIF,EAAQE,GACZJ,OAAQ,KACR5B,MAAOI,EAAa8B,IAEvB,CACH,IAOAhD,EAAOiD,SAAW,SAAUnB,EAASoB,GAEnC,GAAIpB,EACF,IAAK,IAAIP,KAAQO,EACXA,EAAQqB,eAAe5B,KACzBvB,EAAO8B,QAAQP,GAAQO,EAAQP,IAKjC2B,IACFlD,EAAOsC,mBAAqBY,EAAQE,aAGtCpD,EAAOS,KAAK,UAGdT,EAAOqD,KAAO,SAAUC,GACtB,GAAIX,EAAkB,CACpB,GAAIW,aAAmBxD,EAMrB,YALAE,EAAOS,KAAK,CACVqC,GAAIH,EACJY,SAAS,EACTD,QAASA,EAAQ1D,SAChB0D,EAAQ3D,UAIbK,EAAOS,KAAK,CACVqC,GAAIH,EACJY,SAAS,EACTD,WAEH,GAIDE,EAAcC,IAAAzD,EAAOiD,SACrBO,EAAeH,KAAArD,EAAOqD"} \ No newline at end of file diff --git a/node_modules/workerpool/dist/workerpool.js b/node_modules/workerpool/dist/workerpool.js deleted file mode 100644 index 461333d4..00000000 --- a/node_modules/workerpool/dist/workerpool.js +++ /dev/null @@ -1,1737 +0,0 @@ -/** - * workerpool.js - * https://github.com/josdejong/workerpool - * - * Offload tasks to a pool of workers on node.js and in the browser. - * - * @version 9.1.1 - * @date 2024-04-06 - * - * @license - * Copyright (C) 2014-2022 Jos de Jong - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.workerpool = {})); -})(this, (function (exports) { 'use strict'; - - var src = {}; - - var environment = {exports: {}}; - - (function (module) { - // source: https://github.com/flexdinesh/browser-or-node - // source: https://github.com/mozilla/pdf.js/blob/7ea0e40e588864cd938d1836ec61f1928d3877d3/src/shared/util.js#L24 - var isNode = function (nodeProcess) { - return typeof nodeProcess !== 'undefined' && nodeProcess.versions != null && nodeProcess.versions.node != null && nodeProcess + '' === '[object process]'; - }; - module.exports.isNode = isNode; - - // determines the JavaScript platform: browser or node - module.exports.platform = typeof process !== 'undefined' && isNode(process) ? 'node' : 'browser'; - - // determines whether the code is running in main thread or not - // note that in node.js we have to check both worker_thread and child_process - var worker_threads = module.exports.platform === 'node' && require('worker_threads'); - module.exports.isMainThread = module.exports.platform === 'node' ? (!worker_threads || worker_threads.isMainThread) && !process.connected : typeof Window !== 'undefined'; - - // determines the number of cpus available - module.exports.cpus = module.exports.platform === 'browser' ? self.navigator.hardwareConcurrency : require('os').cpus().length; - })(environment); - var environmentExports = environment.exports; - - var _Promise$1 = {}; - - var hasRequired_Promise; - function require_Promise() { - if (hasRequired_Promise) return _Promise$1; - hasRequired_Promise = 1; - - /** - * Promise - * - * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa - * @template T - * @template [E=Error] - * @param {Function} handler Called as handler(resolve: Function, reject: Function) - * @param {Promise} [parent] Parent promise for propagation of cancel and timeout - */ - function Promise(handler, parent) { - var me = this; - if (!(this instanceof Promise)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } - if (typeof handler !== 'function') { - throw new SyntaxError('Function parameter handler(resolve, reject) missing'); - } - var _onSuccess = []; - var _onFail = []; - - // status - /** - * @readonly - */ - this.resolved = false; - /** - * @readonly - */ - this.rejected = false; - /** - * @readonly - */ - this.pending = true; - - /** - * Process onSuccess and onFail callbacks: add them to the queue. - * Once the promise is resolved, the function _promise is replace. - * @param {Function} onSuccess - * @param {Function} onFail - * @private - */ - var _process = function (onSuccess, onFail) { - _onSuccess.push(onSuccess); - _onFail.push(onFail); - }; - - /** - * Add an onSuccess callback and optionally an onFail callback to the Promise - * @template TT - * @template [TE=never] - * @param {(r: T) => TT | PromiseLike} onSuccess - * @param {(r: E) => TE | PromiseLike} [onFail] - * @returns {Promise} promise - */ - this.then = function (onSuccess, onFail) { - return new Promise(function (resolve, reject) { - var s = onSuccess ? _then(onSuccess, resolve, reject) : resolve; - var f = onFail ? _then(onFail, resolve, reject) : reject; - _process(s, f); - }, me); - }; - - /** - * Resolve the promise - * @param {*} result - * @type {Function} - */ - var _resolve = function (result) { - // update status - me.resolved = true; - me.rejected = false; - me.pending = false; - _onSuccess.forEach(function (fn) { - fn(result); - }); - _process = function (onSuccess, onFail) { - onSuccess(result); - }; - _resolve = _reject = function () {}; - return me; - }; - - /** - * Reject the promise - * @param {Error} error - * @type {Function} - */ - var _reject = function (error) { - // update status - me.resolved = false; - me.rejected = true; - me.pending = false; - _onFail.forEach(function (fn) { - fn(error); - }); - _process = function (onSuccess, onFail) { - onFail(error); - }; - _resolve = _reject = function () {}; - return me; - }; - - /** - * Cancel the promise. This will reject the promise with a CancellationError - * @returns {this} self - */ - this.cancel = function () { - if (parent) { - parent.cancel(); - } else { - _reject(new CancellationError()); - } - return me; - }; - - /** - * Set a timeout for the promise. If the promise is not resolved within - * the time, the promise will be cancelled and a TimeoutError is thrown. - * If the promise is resolved in time, the timeout is removed. - * @param {number} delay Delay in milliseconds - * @returns {this} self - */ - this.timeout = function (delay) { - if (parent) { - parent.timeout(delay); - } else { - var timer = setTimeout(function () { - _reject(new TimeoutError('Promise timed out after ' + delay + ' ms')); - }, delay); - me.always(function () { - clearTimeout(timer); - }); - } - return me; - }; - - // attach handler passing the resolve and reject functions - handler(function (result) { - _resolve(result); - }, function (error) { - _reject(error); - }); - } - - /** - * Execute given callback, then call resolve/reject based on the returned result - * @param {Function} callback - * @param {Function} resolve - * @param {Function} reject - * @returns {Function} - * @private - */ - function _then(callback, resolve, reject) { - return function (result) { - try { - var res = callback(result); - if (res && typeof res.then === 'function' && typeof res['catch'] === 'function') { - // method returned a promise - res.then(resolve, reject); - } else { - resolve(res); - } - } catch (error) { - reject(error); - } - }; - } - - /** - * Add an onFail callback to the Promise - * @template TT - * @param {(error: E) => TT | PromiseLike} onFail - * @returns {Promise} promise - */ - Promise.prototype['catch'] = function (onFail) { - return this.then(null, onFail); - }; - - // TODO: add support for Promise.catch(Error, callback) - // TODO: add support for Promise.catch(Error, Error, callback) - - /** - * Execute given callback when the promise either resolves or rejects. - * @template TT - * @param {() => Promise} fn - * @returns {Promise} promise - */ - Promise.prototype.always = function (fn) { - return this.then(fn, fn); - }; - - /** - * Create a promise which resolves when all provided promises are resolved, - * and fails when any of the promises resolves. - * @param {Promise[]} promises - * @returns {Promise} promise - */ - Promise.all = function (promises) { - return new Promise(function (resolve, reject) { - var remaining = promises.length, - results = []; - if (remaining) { - promises.forEach(function (p, i) { - p.then(function (result) { - results[i] = result; - remaining--; - if (remaining == 0) { - resolve(results); - } - }, function (error) { - remaining = 0; - reject(error); - }); - }); - } else { - resolve(results); - } - }); - }; - - /** - * Create a promise resolver - * @returns {{promise: Promise, resolve: Function, reject: Function}} resolver - */ - Promise.defer = function () { - var resolver = {}; - resolver.promise = new Promise(function (resolve, reject) { - resolver.resolve = resolve; - resolver.reject = reject; - }); - return resolver; - }; - - /** - * Create a cancellation error - * @param {String} [message] - * @extends Error - */ - function CancellationError(message) { - this.message = message || 'promise cancelled'; - this.stack = new Error().stack; - } - CancellationError.prototype = new Error(); - CancellationError.prototype.constructor = Error; - CancellationError.prototype.name = 'CancellationError'; - Promise.CancellationError = CancellationError; - - /** - * Create a timeout error - * @param {String} [message] - * @extends Error - */ - function TimeoutError(message) { - this.message = message || 'timeout exceeded'; - this.stack = new Error().stack; - } - TimeoutError.prototype = new Error(); - TimeoutError.prototype.constructor = Error; - TimeoutError.prototype.name = 'TimeoutError'; - Promise.TimeoutError = TimeoutError; - _Promise$1.Promise = Promise; - return _Promise$1; - } - - var WorkerHandler = {exports: {}}; - - var validateOptions = {}; - - /** - * Validate that the object only contains known option names - * - Throws an error when unknown options are detected - * - Throws an error when some of the allowed options are attached - * @param {Object | undefined} options - * @param {string[]} allowedOptionNames - * @param {string} objectName - * @retrun {Object} Returns the original options - */ - var hasRequiredValidateOptions; - function requireValidateOptions() { - if (hasRequiredValidateOptions) return validateOptions; - hasRequiredValidateOptions = 1; - validateOptions.validateOptions = function validateOptions(options, allowedOptionNames, objectName) { - if (!options) { - return; - } - var optionNames = options ? Object.keys(options) : []; - - // check for unknown properties - var unknownOptionName = optionNames.find(optionName => !allowedOptionNames.includes(optionName)); - if (unknownOptionName) { - throw new Error('Object "' + objectName + '" contains an unknown option "' + unknownOptionName + '"'); - } - - // check for inherited properties which are not present on the object itself - var illegalOptionName = allowedOptionNames.find(allowedOptionName => { - return Object.prototype[allowedOptionName] && !optionNames.includes(allowedOptionName); - }); - if (illegalOptionName) { - throw new Error('Object "' + objectName + '" contains an inherited option "' + illegalOptionName + '" which is ' + 'not defined in the object itself but in its prototype. Only plain objects are allowed. ' + 'Please remove the option from the prototype or override it with a value "undefined".'); - } - return options; - }; - - // source: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker - validateOptions.workerOptsNames = ['credentials', 'name', 'type']; - - // source: https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options - validateOptions.forkOptsNames = ['cwd', 'detached', 'env', 'execPath', 'execArgv', 'gid', 'serialization', 'signal', 'killSignal', 'silent', 'stdio', 'uid', 'windowsVerbatimArguments', 'timeout']; - - // source: https://nodejs.org/api/worker_threads.html#new-workerfilename-options - validateOptions.workerThreadOptsNames = ['argv', 'env', 'eval', 'execArgv', 'stdin', 'stdout', 'stderr', 'workerData', 'trackUnmanagedFds', 'transferList', 'resourceLimits', 'name']; - return validateOptions; - } - - /** - * embeddedWorker.js contains an embedded version of worker.js. - * This file is automatically generated, - * changes made in this file will be overwritten. - */ - var embeddedWorker; - var hasRequiredEmbeddedWorker; - function requireEmbeddedWorker() { - if (hasRequiredEmbeddedWorker) return embeddedWorker; - hasRequiredEmbeddedWorker = 1; - embeddedWorker = "!function(e,n){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=n():\"function\"==typeof define&&define.amd?define(n):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){\"use strict\";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\"default\")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if(\"undefined\"!=typeof self&&\"function\"==typeof postMessage&&\"function\"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if(\"undefined\"==typeof process)throw new Error(\"Script must be executed as a worker\");var o;try{o=require(\"worker_threads\")}catch(e){if(\"object\"!=typeof e||null===e||\"MODULE_NOT_FOUND\"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on(\"disconnect\",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&\"function\"==typeof e.then&&\"function\"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function(\"return (\"+e+\").apply(null, arguments);\");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on(\"message\",(function(e){if(\"__workerpool-terminate__\"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error('Unknown method \"'+e.method+'\"');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send(\"ready\")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)}));\n//# sourceMappingURL=worker.min.js.map\n"; - return embeddedWorker; - } - - var hasRequiredWorkerHandler; - function requireWorkerHandler() { - if (hasRequiredWorkerHandler) return WorkerHandler.exports; - hasRequiredWorkerHandler = 1; - var { - Promise - } = require_Promise(); - var environment = environmentExports; - const { - validateOptions, - forkOptsNames, - workerThreadOptsNames, - workerOptsNames - } = requireValidateOptions(); - - /** - * Special message sent by parent which causes a child process worker to terminate itself. - * Not a "message object"; this string is the entire message. - */ - var TERMINATE_METHOD_ID = '__workerpool-terminate__'; - function ensureWorkerThreads() { - var WorkerThreads = tryRequireWorkerThreads(); - if (!WorkerThreads) { - throw new Error('WorkerPool: workerType = \'thread\' is not supported, Node >= 11.7.0 required'); - } - return WorkerThreads; - } - - // check whether Worker is supported by the browser - function ensureWebWorker() { - // Workaround for a bug in PhantomJS (Or QtWebkit): https://github.com/ariya/phantomjs/issues/14534 - if (typeof Worker !== 'function' && (typeof Worker !== 'object' || typeof Worker.prototype.constructor !== 'function')) { - throw new Error('WorkerPool: Web Workers not supported'); - } - } - function tryRequireWorkerThreads() { - try { - return require('worker_threads'); - } catch (error) { - if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') { - // no worker_threads available (old version of node.js) - return null; - } else { - throw error; - } - } - } - - // get the default worker script - function getDefaultWorker() { - if (environment.platform === 'browser') { - // test whether the browser supports all features that we need - if (typeof Blob === 'undefined') { - throw new Error('Blob not supported by the browser'); - } - if (!window.URL || typeof window.URL.createObjectURL !== 'function') { - throw new Error('URL.createObjectURL not supported by the browser'); - } - - // use embedded worker.js - var blob = new Blob([requireEmbeddedWorker()], { - type: 'text/javascript' - }); - return window.URL.createObjectURL(blob); - } else { - // use external worker.js in current directory - return __dirname + '/worker.js'; - } - } - function setupWorker(script, options) { - if (options.workerType === 'web') { - // browser only - ensureWebWorker(); - return setupBrowserWorker(script, options.workerOpts, Worker); - } else if (options.workerType === 'thread') { - // node.js only - WorkerThreads = ensureWorkerThreads(); - return setupWorkerThreadWorker(script, WorkerThreads, options); - } else if (options.workerType === 'process' || !options.workerType) { - // node.js only - return setupProcessWorker(script, resolveForkOptions(options), require('child_process')); - } else { - // options.workerType === 'auto' or undefined - if (environment.platform === 'browser') { - ensureWebWorker(); - return setupBrowserWorker(script, options.workerOpts, Worker); - } else { - // environment.platform === 'node' - var WorkerThreads = tryRequireWorkerThreads(); - if (WorkerThreads) { - return setupWorkerThreadWorker(script, WorkerThreads, options); - } else { - return setupProcessWorker(script, resolveForkOptions(options), require('child_process')); - } - } - } - } - function setupBrowserWorker(script, workerOpts, Worker) { - // validate the options right before creating the worker (not when creating the pool) - validateOptions(workerOpts, workerOptsNames, 'workerOpts'); - - // create the web worker - var worker = new Worker(script, workerOpts); - worker.isBrowserWorker = true; - // add node.js API to the web worker - worker.on = function (event, callback) { - this.addEventListener(event, function (message) { - callback(message.data); - }); - }; - worker.send = function (message, transfer) { - this.postMessage(message, transfer); - }; - return worker; - } - function setupWorkerThreadWorker(script, WorkerThreads, options) { - // validate the options right before creating the worker thread (not when creating the pool) - validateOptions(options?.workerThreadOpts, workerThreadOptsNames, 'workerThreadOpts'); - var worker = new WorkerThreads.Worker(script, { - stdout: options?.emitStdStreams ?? false, - // pipe worker.STDOUT to process.STDOUT if not requested - stderr: options?.emitStdStreams ?? false, - // pipe worker.STDERR to process.STDERR if not requested - ...options?.workerThreadOpts - }); - worker.isWorkerThread = true; - worker.send = function (message, transfer) { - this.postMessage(message, transfer); - }; - worker.kill = function () { - this.terminate(); - return true; - }; - worker.disconnect = function () { - this.terminate(); - }; - if (options?.emitStdStreams) { - worker.stdout.on('data', data => worker.emit("stdout", data)); - worker.stderr.on('data', data => worker.emit("stderr", data)); - } - return worker; - } - function setupProcessWorker(script, options, child_process) { - // validate the options right before creating the child process (not when creating the pool) - validateOptions(options.forkOpts, forkOptsNames, 'forkOpts'); - - // no WorkerThreads, fallback to sub-process based workers - var worker = child_process.fork(script, options.forkArgs, options.forkOpts); - - // ignore transfer argument since it is not supported by process - var send = worker.send; - worker.send = function (message) { - return send.call(worker, message); - }; - if (options.emitStdStreams) { - worker.stdout.on('data', data => worker.emit("stdout", data)); - worker.stderr.on('data', data => worker.emit("stderr", data)); - } - worker.isChildProcess = true; - return worker; - } - - // add debug flags to child processes if the node inspector is active - function resolveForkOptions(opts) { - opts = opts || {}; - var processExecArgv = process.execArgv.join(' '); - var inspectorActive = processExecArgv.indexOf('--inspect') !== -1; - var debugBrk = processExecArgv.indexOf('--debug-brk') !== -1; - var execArgv = []; - if (inspectorActive) { - execArgv.push('--inspect=' + opts.debugPort); - if (debugBrk) { - execArgv.push('--debug-brk'); - } - } - process.execArgv.forEach(function (arg) { - if (arg.indexOf('--max-old-space-size') > -1) { - execArgv.push(arg); - } - }); - return Object.assign({}, opts, { - forkArgs: opts.forkArgs, - forkOpts: Object.assign({}, opts.forkOpts, { - execArgv: (opts.forkOpts && opts.forkOpts.execArgv || []).concat(execArgv), - stdio: opts.emitStdStreams ? "pipe" : undefined - }) - }); - } - - /** - * Converts a serialized error to Error - * @param {Object} obj Error that has been serialized and parsed to object - * @return {Error} The equivalent Error. - */ - function objectToError(obj) { - var temp = new Error(''); - var props = Object.keys(obj); - for (var i = 0; i < props.length; i++) { - temp[props[i]] = obj[props[i]]; - } - return temp; - } - function handleEmittedStdPayload(handler, payload) { - // TODO: refactor if parallel task execution gets added - if (Object.keys(handler.processing).length !== 1) { - return; - } - var task = Object.values(handler.processing)[0]; - if (task.options && typeof task.options.on === 'function') { - task.options.on(payload); - } - } - - /** - * A WorkerHandler controls a single worker. This worker can be a child process - * on node.js or a WebWorker in a browser environment. - * @param {String} [script] If no script is provided, a default worker with a - * function run will be created. - * @param {import('./types.js').WorkerPoolOptions} [_options] See docs - * @constructor - */ - function WorkerHandler$1(script, _options) { - var me = this; - var options = _options || {}; - this.script = script || getDefaultWorker(); - this.worker = setupWorker(this.script, options); - this.debugPort = options.debugPort; - this.forkOpts = options.forkOpts; - this.forkArgs = options.forkArgs; - this.workerOpts = options.workerOpts; - this.workerThreadOpts = options.workerThreadOpts; - this.workerTerminateTimeout = options.workerTerminateTimeout; - - // The ready message is only sent if the worker.add method is called (And the default script is not used) - if (!script) { - this.worker.ready = true; - } - - // queue for requests that are received before the worker is ready - this.requestQueue = []; - this.worker.on("stdout", function (data) { - handleEmittedStdPayload(me, { - "stdout": data.toString() - }); - }); - this.worker.on("stderr", function (data) { - handleEmittedStdPayload(me, { - "stderr": data.toString() - }); - }); - this.worker.on('message', function (response) { - if (me.terminated) { - return; - } - if (typeof response === 'string' && response === 'ready') { - me.worker.ready = true; - dispatchQueuedRequests(); - } else { - // find the task from the processing queue, and run the tasks callback - var id = response.id; - var task = me.processing[id]; - if (task !== undefined) { - if (response.isEvent) { - if (task.options && typeof task.options.on === 'function') { - task.options.on(response.payload); - } - } else { - // remove the task from the queue - delete me.processing[id]; - - // test if we need to terminate - if (me.terminating === true) { - // complete worker termination if all tasks are finished - me.terminate(); - } - - // resolve the task's promise - if (response.error) { - task.resolver.reject(objectToError(response.error)); - } else { - task.resolver.resolve(response.result); - } - } - } - } - }); - - // reject all running tasks on worker error - function onError(error) { - me.terminated = true; - for (var id in me.processing) { - if (me.processing[id] !== undefined) { - me.processing[id].resolver.reject(error); - } - } - me.processing = Object.create(null); - } - - // send all queued requests to worker - function dispatchQueuedRequests() { - for (const request of me.requestQueue.splice(0)) { - me.worker.send(request.message, request.transfer); - } - } - var worker = this.worker; - // listen for worker messages error and exit - this.worker.on('error', onError); - this.worker.on('exit', function (exitCode, signalCode) { - var message = 'Workerpool Worker terminated Unexpectedly\n'; - message += ' exitCode: `' + exitCode + '`\n'; - message += ' signalCode: `' + signalCode + '`\n'; - message += ' workerpool.script: `' + me.script + '`\n'; - message += ' spawnArgs: `' + worker.spawnargs + '`\n'; - message += ' spawnfile: `' + worker.spawnfile + '`\n'; - message += ' stdout: `' + worker.stdout + '`\n'; - message += ' stderr: `' + worker.stderr + '`\n'; - onError(new Error(message)); - }); - this.processing = Object.create(null); // queue with tasks currently in progress - - this.terminating = false; - this.terminated = false; - this.cleaning = false; - this.terminationHandler = null; - this.lastId = 0; - } - - /** - * Get a list with methods available on the worker. - * @return {Promise.} methods - */ - WorkerHandler$1.prototype.methods = function () { - return this.exec('methods'); - }; - - /** - * Execute a method with given parameters on the worker - * @param {String} method - * @param {Array} [params] - * @param {{resolve: Function, reject: Function}} [resolver] - * @param {import('./types.js').ExecOptions} [options] - * @return {Promise.<*, Error>} result - */ - WorkerHandler$1.prototype.exec = function (method, params, resolver, options) { - if (!resolver) { - resolver = Promise.defer(); - } - - // generate a unique id for the task - var id = ++this.lastId; - - // register a new task as being in progress - this.processing[id] = { - id: id, - resolver: resolver, - options: options - }; - - // build a JSON-RPC request - var request = { - message: { - id: id, - method: method, - params: params - }, - transfer: options && options.transfer - }; - if (this.terminated) { - resolver.reject(new Error('Worker is terminated')); - } else if (this.worker.ready) { - // send the request to the worker - this.worker.send(request.message, request.transfer); - } else { - this.requestQueue.push(request); - } - - // on cancellation, force the worker to terminate - var me = this; - return resolver.promise.catch(function (error) { - if (error instanceof Promise.CancellationError || error instanceof Promise.TimeoutError) { - // remove this task from the queue. It is already rejected (hence this - // catch event), and else it will be rejected again when terminating - delete me.processing[id]; - - // terminate worker - return me.terminateAndNotify(true).then(function () { - throw error; - }, function (err) { - throw err; - }); - } else { - throw error; - } - }); - }; - - /** - * Test whether the worker is processing any tasks or cleaning up before termination. - * @return {boolean} Returns true if the worker is busy - */ - WorkerHandler$1.prototype.busy = function () { - return this.cleaning || Object.keys(this.processing).length > 0; - }; - - /** - * Terminate the worker. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {function} [callback=null] If provided, will be called when process terminates. - */ - WorkerHandler$1.prototype.terminate = function (force, callback) { - var me = this; - if (force) { - // cancel all tasks in progress - for (var id in this.processing) { - if (this.processing[id] !== undefined) { - this.processing[id].resolver.reject(new Error('Worker terminated')); - } - } - this.processing = Object.create(null); - } - if (typeof callback === 'function') { - this.terminationHandler = callback; - } - if (!this.busy()) { - // all tasks are finished. kill the worker - var cleanup = function (err) { - me.terminated = true; - me.cleaning = false; - if (me.worker != null && me.worker.removeAllListeners) { - // removeAllListeners is only available for child_process - me.worker.removeAllListeners('message'); - } - me.worker = null; - me.terminating = false; - if (me.terminationHandler) { - me.terminationHandler(err, me); - } else if (err) { - throw err; - } - }; - if (this.worker) { - if (typeof this.worker.kill === 'function') { - if (this.worker.killed) { - cleanup(new Error('worker already killed!')); - return; - } - - // child process and worker threads - var cleanExitTimeout = setTimeout(function () { - if (me.worker) { - me.worker.kill(); - } - }, this.workerTerminateTimeout); - this.worker.once('exit', function () { - clearTimeout(cleanExitTimeout); - if (me.worker) { - me.worker.killed = true; - } - cleanup(); - }); - if (this.worker.ready) { - this.worker.send(TERMINATE_METHOD_ID); - } else { - this.requestQueue.push({ - message: TERMINATE_METHOD_ID - }); - } - - // mark that the worker is cleaning up resources - // to prevent new tasks from being executed - this.cleaning = true; - return; - } else if (typeof this.worker.terminate === 'function') { - this.worker.terminate(); // web worker - this.worker.killed = true; - } else { - throw new Error('Failed to terminate worker'); - } - } - cleanup(); - } else { - // we can't terminate immediately, there are still tasks being executed - this.terminating = true; - } - }; - - /** - * Terminate the worker, returning a Promise that resolves when the termination has been done. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ - WorkerHandler$1.prototype.terminateAndNotify = function (force, timeout) { - var resolver = Promise.defer(); - if (timeout) { - resolver.promise.timeout(timeout); - } - this.terminate(force, function (err, worker) { - if (err) { - resolver.reject(err); - } else { - resolver.resolve(worker); - } - }); - return resolver.promise; - }; - WorkerHandler.exports = WorkerHandler$1; - WorkerHandler.exports._tryRequireWorkerThreads = tryRequireWorkerThreads; - WorkerHandler.exports._setupProcessWorker = setupProcessWorker; - WorkerHandler.exports._setupBrowserWorker = setupBrowserWorker; - WorkerHandler.exports._setupWorkerThreadWorker = setupWorkerThreadWorker; - WorkerHandler.exports.ensureWorkerThreads = ensureWorkerThreads; - return WorkerHandler.exports; - } - - var debugPortAllocator; - var hasRequiredDebugPortAllocator; - function requireDebugPortAllocator() { - if (hasRequiredDebugPortAllocator) return debugPortAllocator; - hasRequiredDebugPortAllocator = 1; - var MAX_PORTS = 65535; - debugPortAllocator = DebugPortAllocator; - function DebugPortAllocator() { - this.ports = Object.create(null); - this.length = 0; - } - DebugPortAllocator.prototype.nextAvailableStartingAt = function (starting) { - while (this.ports[starting] === true) { - starting++; - } - if (starting >= MAX_PORTS) { - throw new Error('WorkerPool debug port limit reached: ' + starting + '>= ' + MAX_PORTS); - } - this.ports[starting] = true; - this.length++; - return starting; - }; - DebugPortAllocator.prototype.releasePort = function (port) { - delete this.ports[port]; - this.length--; - }; - return debugPortAllocator; - } - - var Pool_1; - var hasRequiredPool; - function requirePool() { - if (hasRequiredPool) return Pool_1; - hasRequiredPool = 1; - var { - Promise - } = require_Promise(); - var WorkerHandler = requireWorkerHandler(); - var environment = environmentExports; - var DebugPortAllocator = requireDebugPortAllocator(); - var DEBUG_PORT_ALLOCATOR = new DebugPortAllocator(); - /** - * A pool to manage workers, which can be created using the function workerpool.pool. - * - * @param {String} [script] Optional worker script - * @param {import('./types.js').WorkerPoolOptions} [options] See docs - * @constructor - */ - function Pool(script, options) { - if (typeof script === 'string') { - /** @readonly */ - this.script = script || null; - } else { - this.script = null; - options = script; - } - - /** @private */ - this.workers = []; // queue with all workers - /** @private */ - this.tasks = []; // queue with tasks awaiting execution - - options = options || {}; - - /** @readonly */ - this.forkArgs = Object.freeze(options.forkArgs || []); - /** @readonly */ - this.forkOpts = Object.freeze(options.forkOpts || {}); - /** @readonly */ - this.workerOpts = Object.freeze(options.workerOpts || {}); - /** @readonly */ - this.workerThreadOpts = Object.freeze(options.workerThreadOpts || {}); - /** @private */ - this.debugPortStart = options.debugPortStart || 43210; - /** @readonly @deprecated */ - this.nodeWorker = options.nodeWorker; - /** @readonly - * @type {'auto' | 'web' | 'process' | 'thread'} - */ - this.workerType = options.workerType || options.nodeWorker || 'auto'; - /** @readonly */ - this.maxQueueSize = options.maxQueueSize || Infinity; - /** @readonly */ - this.workerTerminateTimeout = options.workerTerminateTimeout || 1000; - - /** @readonly */ - this.onCreateWorker = options.onCreateWorker || (() => null); - /** @readonly */ - this.onTerminateWorker = options.onTerminateWorker || (() => null); - - /** @readonly */ - this.emitStdStreams = options.emitStdStreams || false; - - // configuration - if (options && 'maxWorkers' in options) { - validateMaxWorkers(options.maxWorkers); - /** @readonly */ - this.maxWorkers = options.maxWorkers; - } else { - this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1); - } - if (options && 'minWorkers' in options) { - if (options.minWorkers === 'max') { - /** @readonly */ - this.minWorkers = this.maxWorkers; - } else { - validateMinWorkers(options.minWorkers); - this.minWorkers = options.minWorkers; - this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers); // in case minWorkers is higher than maxWorkers - } - this._ensureMinWorkers(); - } - - /** @private */ - this._boundNext = this._next.bind(this); - if (this.workerType === 'thread') { - WorkerHandler.ensureWorkerThreads(); - } - } - - /** - * Execute a function on a worker. - * - * Example usage: - * - * var pool = new Pool() - * - * // call a function available on the worker - * pool.exec('fibonacci', [6]) - * - * // offload a function - * function add(a, b) { - * return a + b - * }; - * pool.exec(add, [2, 4]) - * .then(function (result) { - * console.log(result); // outputs 6 - * }) - * .catch(function(error) { - * console.log(error); - * }); - * @template { (...args: any[]) => any } T - * @param {String | T} method Function name or function. - * If `method` is a string, the corresponding - * method on the worker will be executed - * If `method` is a Function, the function - * will be stringified and executed via the - * workers built-in function `run(fn, args)`. - * @param {Parameters | null} [params] Function arguments applied when calling the function - * @param {import('./types.js').ExecOptions} [options] Options - * @return {Promise>} - */ - Pool.prototype.exec = function (method, params, options) { - // validate type of arguments - if (params && !Array.isArray(params)) { - throw new TypeError('Array expected as argument "params"'); - } - if (typeof method === 'string') { - var resolver = Promise.defer(); - if (this.tasks.length >= this.maxQueueSize) { - throw new Error('Max queue size of ' + this.maxQueueSize + ' reached'); - } - - // add a new task to the queue - var tasks = this.tasks; - var task = { - method: method, - params: params, - resolver: resolver, - timeout: null, - options: options - }; - tasks.push(task); - - // replace the timeout method of the Promise with our own, - // which starts the timer as soon as the task is actually started - var originalTimeout = resolver.promise.timeout; - resolver.promise.timeout = function timeout(delay) { - if (tasks.indexOf(task) !== -1) { - // task is still queued -> start the timer later on - task.timeout = delay; - return resolver.promise; - } else { - // task is already being executed -> start timer immediately - return originalTimeout.call(resolver.promise, delay); - } - }; - - // trigger task execution - this._next(); - return resolver.promise; - } else if (typeof method === 'function') { - // send stringified function and function arguments to worker - return this.exec('run', [String(method), params], options); - } else { - throw new TypeError('Function or string expected as argument "method"'); - } - }; - - /** - * Create a proxy for current worker. Returns an object containing all - * methods available on the worker. All methods return promises resolving the methods result. - * @template { { [k: string]: (...args: any[]) => any } } T - * @return {Promise, Error>} Returns a promise which resolves with a proxy object - */ - Pool.prototype.proxy = function () { - if (arguments.length > 0) { - throw new Error('No arguments expected'); - } - var pool = this; - return this.exec('methods').then(function (methods) { - var proxy = {}; - methods.forEach(function (method) { - proxy[method] = function () { - return pool.exec(method, Array.prototype.slice.call(arguments)); - }; - }); - return proxy; - }); - }; - - /** - * Creates new array with the results of calling a provided callback function - * on every element in this array. - * @param {Array} array - * @param {function} callback Function taking two arguments: - * `callback(currentValue, index)` - * @return {Promise.} Returns a promise which resolves with an Array - * containing the results of the callback function - * executed for each of the array elements. - */ - /* TODO: implement map - Pool.prototype.map = function (array, callback) { - }; - */ - - /** - * Grab the first task from the queue, find a free worker, and assign the - * worker to the task. - * @private - */ - Pool.prototype._next = function () { - if (this.tasks.length > 0) { - // there are tasks in the queue - - // find an available worker - var worker = this._getWorker(); - if (worker) { - // get the first task from the queue - var me = this; - var task = this.tasks.shift(); - - // check if the task is still pending (and not cancelled -> promise rejected) - if (task.resolver.promise.pending) { - // send the request to the worker - var promise = worker.exec(task.method, task.params, task.resolver, task.options).then(me._boundNext).catch(function () { - // if the worker crashed and terminated, remove it from the pool - if (worker.terminated) { - return me._removeWorker(worker); - } - }).then(function () { - me._next(); // trigger next task in the queue - }); - - // start queued timer now - if (typeof task.timeout === 'number') { - promise.timeout(task.timeout); - } - } else { - // The task taken was already complete (either rejected or resolved), so just trigger next task in the queue - me._next(); - } - } - } - }; - - /** - * Get an available worker. If no worker is available and the maximum number - * of workers isn't yet reached, a new worker will be created and returned. - * If no worker is available and the maximum number of workers is reached, - * null will be returned. - * - * @return {WorkerHandler | null} worker - * @private - */ - Pool.prototype._getWorker = function () { - // find a non-busy worker - var workers = this.workers; - for (var i = 0; i < workers.length; i++) { - var worker = workers[i]; - if (worker.busy() === false) { - return worker; - } - } - if (workers.length < this.maxWorkers) { - // create a new worker - worker = this._createWorkerHandler(); - workers.push(worker); - return worker; - } - return null; - }; - - /** - * Remove a worker from the pool. - * Attempts to terminate worker if not already terminated, and ensures the minimum - * pool size is met. - * @param {WorkerHandler} worker - * @return {Promise} - * @private - */ - Pool.prototype._removeWorker = function (worker) { - var me = this; - DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort); - // _removeWorker will call this, but we need it to be removed synchronously - this._removeWorkerFromList(worker); - // If minWorkers set, spin up new workers to replace the crashed ones - this._ensureMinWorkers(); - // terminate the worker (if not already terminated) - return new Promise(function (resolve, reject) { - worker.terminate(false, function (err) { - me.onTerminateWorker({ - forkArgs: worker.forkArgs, - forkOpts: worker.forkOpts, - workerThreadOpts: worker.workerThreadOpts, - script: worker.script - }); - if (err) { - reject(err); - } else { - resolve(worker); - } - }); - }); - }; - - /** - * Remove a worker from the pool list. - * @param {WorkerHandler} worker - * @private - */ - Pool.prototype._removeWorkerFromList = function (worker) { - // remove from the list with workers - var index = this.workers.indexOf(worker); - if (index !== -1) { - this.workers.splice(index, 1); - } - }; - - /** - * Close all active workers. Tasks currently being executed will be finished first. - * @param {boolean} [force=false] If false (default), the workers are terminated - * after finishing all tasks currently in - * progress. If true, the workers will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ - Pool.prototype.terminate = function (force, timeout) { - var me = this; - - // cancel any pending tasks - this.tasks.forEach(function (task) { - task.resolver.reject(new Error('Pool terminated')); - }); - this.tasks.length = 0; - var f = function (worker) { - DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort); - this._removeWorkerFromList(worker); - }; - var removeWorker = f.bind(this); - var promises = []; - var workers = this.workers.slice(); - workers.forEach(function (worker) { - var termPromise = worker.terminateAndNotify(force, timeout).then(removeWorker).always(function () { - me.onTerminateWorker({ - forkArgs: worker.forkArgs, - forkOpts: worker.forkOpts, - workerThreadOpts: worker.workerThreadOpts, - script: worker.script - }); - }); - promises.push(termPromise); - }); - return Promise.all(promises); - }; - - /** - * Retrieve statistics on tasks and workers. - * @return {{totalWorkers: number, busyWorkers: number, idleWorkers: number, pendingTasks: number, activeTasks: number}} Returns an object with statistics - */ - Pool.prototype.stats = function () { - var totalWorkers = this.workers.length; - var busyWorkers = this.workers.filter(function (worker) { - return worker.busy(); - }).length; - return { - totalWorkers: totalWorkers, - busyWorkers: busyWorkers, - idleWorkers: totalWorkers - busyWorkers, - pendingTasks: this.tasks.length, - activeTasks: busyWorkers - }; - }; - - /** - * Ensures that a minimum of minWorkers is up and running - * @private - */ - Pool.prototype._ensureMinWorkers = function () { - if (this.minWorkers) { - for (var i = this.workers.length; i < this.minWorkers; i++) { - this.workers.push(this._createWorkerHandler()); - } - } - }; - - /** - * Helper function to create a new WorkerHandler and pass all options. - * @return {WorkerHandler} - * @private - */ - Pool.prototype._createWorkerHandler = function () { - const overriddenParams = this.onCreateWorker({ - forkArgs: this.forkArgs, - forkOpts: this.forkOpts, - workerOpts: this.workerOpts, - workerThreadOpts: this.workerThreadOpts, - script: this.script - }) || {}; - return new WorkerHandler(overriddenParams.script || this.script, { - forkArgs: overriddenParams.forkArgs || this.forkArgs, - forkOpts: overriddenParams.forkOpts || this.forkOpts, - workerOpts: overriddenParams.workerOpts || this.workerOpts, - workerThreadOpts: overriddenParams.workerThreadOpts || this.workerThreadOpts, - debugPort: DEBUG_PORT_ALLOCATOR.nextAvailableStartingAt(this.debugPortStart), - workerType: this.workerType, - workerTerminateTimeout: this.workerTerminateTimeout, - emitStdStreams: this.emitStdStreams - }); - }; - - /** - * Ensure that the maxWorkers option is an integer >= 1 - * @param {*} maxWorkers - * @returns {boolean} returns true maxWorkers has a valid value - */ - function validateMaxWorkers(maxWorkers) { - if (!isNumber(maxWorkers) || !isInteger(maxWorkers) || maxWorkers < 1) { - throw new TypeError('Option maxWorkers must be an integer number >= 1'); - } - } - - /** - * Ensure that the minWorkers option is an integer >= 0 - * @param {*} minWorkers - * @returns {boolean} returns true when minWorkers has a valid value - */ - function validateMinWorkers(minWorkers) { - if (!isNumber(minWorkers) || !isInteger(minWorkers) || minWorkers < 0) { - throw new TypeError('Option minWorkers must be an integer number >= 0'); - } - } - - /** - * Test whether a variable is a number - * @param {*} value - * @returns {boolean} returns true when value is a number - */ - function isNumber(value) { - return typeof value === 'number'; - } - - /** - * Test whether a number is an integer - * @param {number} value - * @returns {boolean} Returns true if value is an integer - */ - function isInteger(value) { - return Math.round(value) == value; - } - Pool_1 = Pool; - return Pool_1; - } - - var worker$1 = {}; - - /** - * The helper class for transferring data from the worker to the main thread. - * - * @param {Object} message The object to deliver to the main thread. - * @param {Object[]} transfer An array of transferable Objects to transfer ownership of. - */ - var transfer; - var hasRequiredTransfer; - function requireTransfer() { - if (hasRequiredTransfer) return transfer; - hasRequiredTransfer = 1; - function Transfer(message, transfer) { - this.message = message; - this.transfer = transfer; - } - transfer = Transfer; - return transfer; - } - - /** - * worker must be started as a child process or a web worker. - * It listens for RPC messages from the parent process. - */ - var hasRequiredWorker; - function requireWorker() { - if (hasRequiredWorker) return worker$1; - hasRequiredWorker = 1; - (function (exports) { - var Transfer = requireTransfer(); - - /** - * Special message sent by parent which causes the worker to terminate itself. - * Not a "message object"; this string is the entire message. - */ - var TERMINATE_METHOD_ID = '__workerpool-terminate__'; - - // var nodeOSPlatform = require('./environment').nodeOSPlatform; - - // create a worker API for sending and receiving messages which works both on - // node.js and in the browser - var worker = { - exit: function () {} - }; - if (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') { - // worker in the browser - worker.on = function (event, callback) { - addEventListener(event, function (message) { - callback(message.data); - }); - }; - worker.send = function (message) { - postMessage(message); - }; - } else if (typeof process !== 'undefined') { - // node.js - - var WorkerThreads; - try { - WorkerThreads = require('worker_threads'); - } catch (error) { - if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') ; else { - throw error; - } - } - if (WorkerThreads && /* if there is a parentPort, we are in a WorkerThread */ - WorkerThreads.parentPort !== null) { - var parentPort = WorkerThreads.parentPort; - worker.send = parentPort.postMessage.bind(parentPort); - worker.on = parentPort.on.bind(parentPort); - worker.exit = process.exit.bind(process); - } else { - worker.on = process.on.bind(process); - // ignore transfer argument since it is not supported by process - worker.send = function (message) { - process.send(message); - }; - // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly - worker.on('disconnect', function () { - process.exit(1); - }); - worker.exit = process.exit.bind(process); - } - } else { - throw new Error('Script must be executed as a worker'); - } - function convertError(error) { - return Object.getOwnPropertyNames(error).reduce(function (product, name) { - return Object.defineProperty(product, name, { - value: error[name], - enumerable: true - }); - }, {}); - } - - /** - * Test whether a value is a Promise via duck typing. - * @param {*} value - * @returns {boolean} Returns true when given value is an object - * having functions `then` and `catch`. - */ - function isPromise(value) { - return value && typeof value.then === 'function' && typeof value.catch === 'function'; - } - - // functions available externally - worker.methods = {}; - - /** - * Execute a function with provided arguments - * @param {String} fn Stringified function - * @param {Array} [args] Function arguments - * @returns {*} - */ - worker.methods.run = function run(fn, args) { - var f = new Function('return (' + fn + ').apply(null, arguments);'); - return f.apply(f, args); - }; - - /** - * Get a list with methods available on this worker - * @return {String[]} methods - */ - worker.methods.methods = function methods() { - return Object.keys(worker.methods); - }; - - /** - * Custom handler for when the worker is terminated. - */ - worker.terminationHandler = undefined; - - /** - * Cleanup and exit the worker. - * @param {Number} code - * @returns - */ - worker.cleanupAndExit = function (code) { - var _exit = function () { - worker.exit(code); - }; - if (!worker.terminationHandler) { - return _exit(); - } - var result = worker.terminationHandler(code); - if (isPromise(result)) { - result.then(_exit, _exit); - } else { - _exit(); - } - }; - var currentRequestId = null; - worker.on('message', function (request) { - if (request === TERMINATE_METHOD_ID) { - return worker.cleanupAndExit(0); - } - try { - var method = worker.methods[request.method]; - if (method) { - currentRequestId = request.id; - - // execute the function - var result = method.apply(method, request.params); - if (isPromise(result)) { - // promise returned, resolve this and then return - result.then(function (result) { - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - currentRequestId = null; - }).catch(function (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - currentRequestId = null; - }); - } else { - // immediate result - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - currentRequestId = null; - } - } else { - throw new Error('Unknown method "' + request.method + '"'); - } - } catch (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - } - }); - - /** - * Register methods to the worker - * @param {Object} [methods] - * @param {import('./types.js').WorkerRegisterOptions} [options] - */ - worker.register = function (methods, options) { - if (methods) { - for (var name in methods) { - if (methods.hasOwnProperty(name)) { - worker.methods[name] = methods[name]; - } - } - } - if (options) { - worker.terminationHandler = options.onTerminate; - } - worker.send('ready'); - }; - worker.emit = function (payload) { - if (currentRequestId) { - if (payload instanceof Transfer) { - worker.send({ - id: currentRequestId, - isEvent: true, - payload: payload.message - }, payload.transfer); - return; - } - worker.send({ - id: currentRequestId, - isEvent: true, - payload - }); - } - }; - { - exports.add = worker.register; - exports.emit = worker.emit; - } - })(worker$1); - return worker$1; - } - - const { - platform, - isMainThread, - cpus - } = environmentExports; - - /** @typedef {import("./Pool")} Pool */ - /** @typedef {import("./types.js").WorkerPoolOptions} WorkerPoolOptions */ - /** @typedef {import("./types.js").WorkerRegisterOptions} WorkerRegisterOptions */ - - /** - * @template { { [k: string]: (...args: any[]) => any } } T - * @typedef {import('./types.js').Proxy} Proxy - */ - - /** - * @overload - * Create a new worker pool - * @param {WorkerPoolOptions} [script] - * @returns {Pool} pool - */ - /** - * @overload - * Create a new worker pool - * @param {string} [script] - * @param {WorkerPoolOptions} [options] - * @returns {Pool} pool - */ - function pool(script, options) { - var Pool = requirePool(); - return new Pool(script, options); - } - var pool_1 = src.pool = pool; - - /** - * Create a worker and optionally register a set of methods to the worker. - * @param {{ [k: string]: (...args: any[]) => any }} [methods] - * @param {WorkerRegisterOptions} [options] - */ - function worker(methods, options) { - var worker = requireWorker(); - worker.add(methods, options); - } - var worker_1 = src.worker = worker; - - /** - * Sends an event to the parent worker pool. - * @param {any} payload - */ - function workerEmit(payload) { - var worker = requireWorker(); - worker.emit(payload); - } - var workerEmit_1 = src.workerEmit = workerEmit; - const { - Promise: Promise$1 - } = require_Promise(); - var _Promise = src.Promise = Promise$1; - var Transfer = src.Transfer = requireTransfer(); - var platform_1 = src.platform = platform; - var isMainThread_1 = src.isMainThread = isMainThread; - var cpus_1 = src.cpus = cpus; - - exports.Promise = _Promise; - exports.Transfer = Transfer; - exports.cpus = cpus_1; - exports.default = src; - exports.isMainThread = isMainThread_1; - exports.platform = platform_1; - exports.pool = pool_1; - exports.worker = worker_1; - exports.workerEmit = workerEmit_1; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); -//# sourceMappingURL=workerpool.js.map diff --git a/node_modules/workerpool/dist/workerpool.js.map b/node_modules/workerpool/dist/workerpool.js.map deleted file mode 100644 index 6cc65953..00000000 --- a/node_modules/workerpool/dist/workerpool.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"workerpool.js","sources":["../src/environment.js","../src/Promise.js","../src/validateOptions.js","../src/generated/embeddedWorker.js","../src/WorkerHandler.js","../src/debug-port-allocator.js","../src/Pool.js","../src/transfer.js","../src/worker.js","../src/index.js"],"sourcesContent":["\n// source: https://github.com/flexdinesh/browser-or-node\n// source: https://github.com/mozilla/pdf.js/blob/7ea0e40e588864cd938d1836ec61f1928d3877d3/src/shared/util.js#L24\nvar isNode = function (nodeProcess) {\n return (\n typeof nodeProcess !== 'undefined' &&\n nodeProcess.versions != null &&\n nodeProcess.versions.node != null &&\n nodeProcess + '' === '[object process]'\n );\n}\nmodule.exports.isNode = isNode\n\n// determines the JavaScript platform: browser or node\nmodule.exports.platform = typeof process !== 'undefined' && isNode(process)\n ? 'node'\n : 'browser';\n\n// determines whether the code is running in main thread or not\n// note that in node.js we have to check both worker_thread and child_process\nvar worker_threads = module.exports.platform === 'node' && require('worker_threads');\nmodule.exports.isMainThread = module.exports.platform === 'node'\n ? ((!worker_threads || worker_threads.isMainThread) && !process.connected)\n : typeof Window !== 'undefined';\n\n// determines the number of cpus available\nmodule.exports.cpus = module.exports.platform === 'browser'\n ? self.navigator.hardwareConcurrency\n : require('os').cpus().length;\n\n","'use strict';\n\n/**\n * Promise\n *\n * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa \n * @template T\n * @template [E=Error]\n * @param {Function} handler Called as handler(resolve: Function, reject: Function)\n * @param {Promise} [parent] Parent promise for propagation of cancel and timeout\n */\nfunction Promise(handler, parent) {\n var me = this;\n\n if (!(this instanceof Promise)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n if (typeof handler !== 'function') {\n throw new SyntaxError('Function parameter handler(resolve, reject) missing');\n }\n\n var _onSuccess = [];\n var _onFail = [];\n\n // status\n /**\n * @readonly\n */\n this.resolved = false;\n /**\n * @readonly\n */\n this.rejected = false;\n /**\n * @readonly\n */\n this.pending = true;\n\n /**\n * Process onSuccess and onFail callbacks: add them to the queue.\n * Once the promise is resolved, the function _promise is replace.\n * @param {Function} onSuccess\n * @param {Function} onFail\n * @private\n */\n var _process = function (onSuccess, onFail) {\n _onSuccess.push(onSuccess);\n _onFail.push(onFail);\n };\n\n /**\n * Add an onSuccess callback and optionally an onFail callback to the Promise\n * @template TT\n * @template [TE=never]\n * @param {(r: T) => TT | PromiseLike} onSuccess\n * @param {(r: E) => TE | PromiseLike} [onFail]\n * @returns {Promise} promise\n */\n this.then = function (onSuccess, onFail) {\n return new Promise(function (resolve, reject) {\n var s = onSuccess ? _then(onSuccess, resolve, reject) : resolve;\n var f = onFail ? _then(onFail, resolve, reject) : reject;\n\n _process(s, f);\n }, me);\n };\n\n /**\n * Resolve the promise\n * @param {*} result\n * @type {Function}\n */\n var _resolve = function (result) {\n // update status\n me.resolved = true;\n me.rejected = false;\n me.pending = false;\n\n _onSuccess.forEach(function (fn) {\n fn(result);\n });\n\n _process = function (onSuccess, onFail) {\n onSuccess(result);\n };\n\n _resolve = _reject = function () { };\n\n return me;\n };\n\n /**\n * Reject the promise\n * @param {Error} error\n * @type {Function}\n */\n var _reject = function (error) {\n // update status\n me.resolved = false;\n me.rejected = true;\n me.pending = false;\n\n _onFail.forEach(function (fn) {\n fn(error);\n });\n\n _process = function (onSuccess, onFail) {\n onFail(error);\n };\n\n _resolve = _reject = function () { }\n\n return me;\n };\n\n /**\n * Cancel the promise. This will reject the promise with a CancellationError\n * @returns {this} self\n */\n this.cancel = function () {\n if (parent) {\n parent.cancel();\n }\n else {\n _reject(new CancellationError());\n }\n\n return me;\n };\n\n /**\n * Set a timeout for the promise. If the promise is not resolved within\n * the time, the promise will be cancelled and a TimeoutError is thrown.\n * If the promise is resolved in time, the timeout is removed.\n * @param {number} delay Delay in milliseconds\n * @returns {this} self\n */\n this.timeout = function (delay) {\n if (parent) {\n parent.timeout(delay);\n }\n else {\n var timer = setTimeout(function () {\n _reject(new TimeoutError('Promise timed out after ' + delay + ' ms'));\n }, delay);\n\n me.always(function () {\n clearTimeout(timer);\n });\n }\n\n return me;\n };\n\n // attach handler passing the resolve and reject functions\n handler(function (result) {\n _resolve(result);\n }, function (error) {\n _reject(error);\n });\n}\n\n/**\n * Execute given callback, then call resolve/reject based on the returned result\n * @param {Function} callback\n * @param {Function} resolve\n * @param {Function} reject\n * @returns {Function}\n * @private\n */\nfunction _then(callback, resolve, reject) {\n return function (result) {\n try {\n var res = callback(result);\n if (res && typeof res.then === 'function' && typeof res['catch'] === 'function') {\n // method returned a promise\n res.then(resolve, reject);\n }\n else {\n resolve(res);\n }\n }\n catch (error) {\n reject(error);\n }\n }\n}\n\n/**\n * Add an onFail callback to the Promise\n * @template TT\n * @param {(error: E) => TT | PromiseLike} onFail\n * @returns {Promise} promise\n */\nPromise.prototype['catch'] = function (onFail) {\n return this.then(null, onFail);\n};\n\n// TODO: add support for Promise.catch(Error, callback)\n// TODO: add support for Promise.catch(Error, Error, callback)\n\n/**\n * Execute given callback when the promise either resolves or rejects.\n * @template TT\n * @param {() => Promise} fn\n * @returns {Promise} promise\n */\nPromise.prototype.always = function (fn) {\n return this.then(fn, fn);\n};\n\n/**\n * Create a promise which resolves when all provided promises are resolved,\n * and fails when any of the promises resolves.\n * @param {Promise[]} promises\n * @returns {Promise} promise\n */\nPromise.all = function (promises){\n return new Promise(function (resolve, reject) {\n var remaining = promises.length,\n results = [];\n\n if (remaining) {\n promises.forEach(function (p, i) {\n p.then(function (result) {\n results[i] = result;\n remaining--;\n if (remaining == 0) {\n resolve(results);\n }\n }, function (error) {\n remaining = 0;\n reject(error);\n });\n });\n }\n else {\n resolve(results);\n }\n });\n};\n\n/**\n * Create a promise resolver\n * @returns {{promise: Promise, resolve: Function, reject: Function}} resolver\n */\nPromise.defer = function () {\n var resolver = {};\n\n resolver.promise = new Promise(function (resolve, reject) {\n resolver.resolve = resolve;\n resolver.reject = reject;\n });\n\n return resolver;\n};\n\n/**\n * Create a cancellation error\n * @param {String} [message]\n * @extends Error\n */\nfunction CancellationError(message) {\n this.message = message || 'promise cancelled';\n this.stack = (new Error()).stack;\n}\n\nCancellationError.prototype = new Error();\nCancellationError.prototype.constructor = Error;\nCancellationError.prototype.name = 'CancellationError';\n\nPromise.CancellationError = CancellationError;\n\n\n/**\n * Create a timeout error\n * @param {String} [message]\n * @extends Error\n */\nfunction TimeoutError(message) {\n this.message = message || 'timeout exceeded';\n this.stack = (new Error()).stack;\n}\n\nTimeoutError.prototype = new Error();\nTimeoutError.prototype.constructor = Error;\nTimeoutError.prototype.name = 'TimeoutError';\n\nPromise.TimeoutError = TimeoutError;\n\n\nexports.Promise = Promise;\n","/**\n * Validate that the object only contains known option names\n * - Throws an error when unknown options are detected\n * - Throws an error when some of the allowed options are attached\n * @param {Object | undefined} options\n * @param {string[]} allowedOptionNames\n * @param {string} objectName\n * @retrun {Object} Returns the original options\n */\nexports.validateOptions = function validateOptions(options, allowedOptionNames, objectName) {\n if (!options) {\n return\n }\n\n var optionNames = options ? Object.keys(options) : []\n\n // check for unknown properties\n var unknownOptionName = optionNames.find(optionName => !allowedOptionNames.includes(optionName))\n if (unknownOptionName) {\n throw new Error('Object \"' + objectName + '\" contains an unknown option \"' + unknownOptionName + '\"')\n }\n\n // check for inherited properties which are not present on the object itself\n var illegalOptionName = allowedOptionNames.find(allowedOptionName => {\n return Object.prototype[allowedOptionName] && !optionNames.includes(allowedOptionName)\n })\n if (illegalOptionName) {\n throw new Error('Object \"' + objectName + '\" contains an inherited option \"' + illegalOptionName + '\" which is ' +\n 'not defined in the object itself but in its prototype. Only plain objects are allowed. ' +\n 'Please remove the option from the prototype or override it with a value \"undefined\".')\n }\n\n return options\n}\n\n// source: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker\nexports.workerOptsNames = [\n 'credentials', 'name', 'type' ]\n\n// source: https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options\nexports.forkOptsNames = [\n 'cwd', 'detached', 'env', 'execPath', 'execArgv', 'gid', 'serialization',\n 'signal', 'killSignal', 'silent', 'stdio', 'uid', 'windowsVerbatimArguments',\n 'timeout'\n]\n\n// source: https://nodejs.org/api/worker_threads.html#new-workerfilename-options\nexports.workerThreadOptsNames = [\n 'argv', 'env', 'eval', 'execArgv', 'stdin', 'stdout', 'stderr', 'workerData',\n 'trackUnmanagedFds', 'transferList', 'resourceLimits', 'name'\n]\n","/**\n * embeddedWorker.js contains an embedded version of worker.js.\n * This file is automatically generated,\n * changes made in this file will be overwritten.\n */\nmodule.exports = \"!function(e,n){\\\"object\\\"==typeof exports&&\\\"undefined\\\"!=typeof module?module.exports=n():\\\"function\\\"==typeof define&&define.amd?define(n):(e=\\\"undefined\\\"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){\\\"use strict\\\";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\\\"default\\\")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if(\\\"undefined\\\"!=typeof self&&\\\"function\\\"==typeof postMessage&&\\\"function\\\"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if(\\\"undefined\\\"==typeof process)throw new Error(\\\"Script must be executed as a worker\\\");var o;try{o=require(\\\"worker_threads\\\")}catch(e){if(\\\"object\\\"!=typeof e||null===e||\\\"MODULE_NOT_FOUND\\\"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on(\\\"disconnect\\\",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&\\\"function\\\"==typeof e.then&&\\\"function\\\"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function(\\\"return (\\\"+e+\\\").apply(null, arguments);\\\");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on(\\\"message\\\",(function(e){if(\\\"__workerpool-terminate__\\\"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error('Unknown method \\\"'+e.method+'\\\"');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send(\\\"ready\\\")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)}));\\n//# sourceMappingURL=worker.min.js.map\\n\";\n","'use strict';\n\nvar {Promise} = require('./Promise');\nvar environment = require('./environment');\nconst {validateOptions, forkOptsNames, workerThreadOptsNames, workerOptsNames} = require(\"./validateOptions\");\n\n/**\n * Special message sent by parent which causes a child process worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\nfunction ensureWorkerThreads() {\n var WorkerThreads = tryRequireWorkerThreads()\n if (!WorkerThreads) {\n throw new Error('WorkerPool: workerType = \\'thread\\' is not supported, Node >= 11.7.0 required')\n }\n\n return WorkerThreads;\n}\n\n// check whether Worker is supported by the browser\nfunction ensureWebWorker() {\n // Workaround for a bug in PhantomJS (Or QtWebkit): https://github.com/ariya/phantomjs/issues/14534\n if (typeof Worker !== 'function' && (typeof Worker !== 'object' || typeof Worker.prototype.constructor !== 'function')) {\n throw new Error('WorkerPool: Web Workers not supported');\n }\n}\n\nfunction tryRequireWorkerThreads() {\n try {\n return require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads available (old version of node.js)\n return null;\n } else {\n throw error;\n }\n }\n}\n\n// get the default worker script\nfunction getDefaultWorker() {\n if (environment.platform === 'browser') {\n // test whether the browser supports all features that we need\n if (typeof Blob === 'undefined') {\n throw new Error('Blob not supported by the browser');\n }\n if (!window.URL || typeof window.URL.createObjectURL !== 'function') {\n throw new Error('URL.createObjectURL not supported by the browser');\n }\n\n // use embedded worker.js\n var blob = new Blob([require('./generated/embeddedWorker')], {type: 'text/javascript'});\n return window.URL.createObjectURL(blob);\n }\n else {\n // use external worker.js in current directory\n return __dirname + '/worker.js';\n }\n}\n\nfunction setupWorker(script, options) {\n if (options.workerType === 'web') { // browser only\n ensureWebWorker();\n return setupBrowserWorker(script, options.workerOpts, Worker);\n } else if (options.workerType === 'thread') { // node.js only\n WorkerThreads = ensureWorkerThreads();\n return setupWorkerThreadWorker(script, WorkerThreads, options);\n } else if (options.workerType === 'process' || !options.workerType) { // node.js only\n return setupProcessWorker(script, resolveForkOptions(options), require('child_process'));\n } else { // options.workerType === 'auto' or undefined\n if (environment.platform === 'browser') {\n ensureWebWorker();\n return setupBrowserWorker(script, options.workerOpts, Worker);\n }\n else { // environment.platform === 'node'\n var WorkerThreads = tryRequireWorkerThreads();\n if (WorkerThreads) {\n return setupWorkerThreadWorker(script, WorkerThreads, options);\n } else {\n return setupProcessWorker(script, resolveForkOptions(options), require('child_process'));\n }\n }\n }\n}\n\nfunction setupBrowserWorker(script, workerOpts, Worker) {\n // validate the options right before creating the worker (not when creating the pool)\n validateOptions(workerOpts, workerOptsNames, 'workerOpts')\n\n // create the web worker\n var worker = new Worker(script, workerOpts);\n\n worker.isBrowserWorker = true;\n // add node.js API to the web worker\n worker.on = function (event, callback) {\n this.addEventListener(event, function (message) {\n callback(message.data);\n });\n };\n worker.send = function (message, transfer) {\n this.postMessage(message, transfer);\n };\n return worker;\n}\n\nfunction setupWorkerThreadWorker(script, WorkerThreads, options) {\n // validate the options right before creating the worker thread (not when creating the pool)\n validateOptions(options?.workerThreadOpts, workerThreadOptsNames, 'workerThreadOpts')\n\n var worker = new WorkerThreads.Worker(script, {\n stdout: options?.emitStdStreams ?? false, // pipe worker.STDOUT to process.STDOUT if not requested\n stderr: options?.emitStdStreams ?? false, // pipe worker.STDERR to process.STDERR if not requested\n ...options?.workerThreadOpts\n });\n worker.isWorkerThread = true;\n worker.send = function(message, transfer) {\n this.postMessage(message, transfer);\n };\n\n worker.kill = function() {\n this.terminate();\n return true;\n };\n\n worker.disconnect = function() {\n this.terminate();\n };\n\n if (options?.emitStdStreams) {\n worker.stdout.on('data', (data) => worker.emit(\"stdout\", data))\n worker.stderr.on('data', (data) => worker.emit(\"stderr\", data))\n }\n\n return worker;\n}\n\nfunction setupProcessWorker(script, options, child_process) {\n // validate the options right before creating the child process (not when creating the pool)\n validateOptions(options.forkOpts, forkOptsNames, 'forkOpts')\n\n // no WorkerThreads, fallback to sub-process based workers\n var worker = child_process.fork(\n script,\n options.forkArgs,\n options.forkOpts\n );\n\n // ignore transfer argument since it is not supported by process\n var send = worker.send;\n worker.send = function (message) {\n return send.call(worker, message);\n };\n\n if (options.emitStdStreams) {\n worker.stdout.on('data', (data) => worker.emit(\"stdout\", data))\n worker.stderr.on('data', (data) => worker.emit(\"stderr\", data))\n }\n\n worker.isChildProcess = true;\n return worker;\n}\n\n// add debug flags to child processes if the node inspector is active\nfunction resolveForkOptions(opts) {\n opts = opts || {};\n\n var processExecArgv = process.execArgv.join(' ');\n var inspectorActive = processExecArgv.indexOf('--inspect') !== -1;\n var debugBrk = processExecArgv.indexOf('--debug-brk') !== -1;\n\n var execArgv = [];\n if (inspectorActive) {\n execArgv.push('--inspect=' + opts.debugPort);\n\n if (debugBrk) {\n execArgv.push('--debug-brk');\n }\n }\n\n process.execArgv.forEach(function(arg) {\n if (arg.indexOf('--max-old-space-size') > -1) {\n execArgv.push(arg)\n }\n })\n\n return Object.assign({}, opts, {\n forkArgs: opts.forkArgs,\n forkOpts: Object.assign({}, opts.forkOpts, {\n execArgv: (opts.forkOpts && opts.forkOpts.execArgv || [])\n .concat(execArgv),\n stdio: opts.emitStdStreams ? \"pipe\": undefined\n })\n });\n}\n\n/**\n * Converts a serialized error to Error\n * @param {Object} obj Error that has been serialized and parsed to object\n * @return {Error} The equivalent Error.\n */\nfunction objectToError (obj) {\n var temp = new Error('')\n var props = Object.keys(obj)\n\n for (var i = 0; i < props.length; i++) {\n temp[props[i]] = obj[props[i]]\n }\n\n return temp\n}\n\nfunction handleEmittedStdPayload(handler, payload) {\n // TODO: refactor if parallel task execution gets added\n if (Object.keys(handler.processing).length !== 1) {\n return;\n }\n var task = Object.values(handler.processing)[0]\n if (task.options && typeof task.options.on === 'function') {\n task.options.on(payload);\n }\n}\n\n/**\n * A WorkerHandler controls a single worker. This worker can be a child process\n * on node.js or a WebWorker in a browser environment.\n * @param {String} [script] If no script is provided, a default worker with a\n * function run will be created.\n * @param {import('./types.js').WorkerPoolOptions} [_options] See docs\n * @constructor\n */\nfunction WorkerHandler(script, _options) {\n var me = this;\n var options = _options || {};\n\n this.script = script || getDefaultWorker();\n this.worker = setupWorker(this.script, options);\n this.debugPort = options.debugPort;\n this.forkOpts = options.forkOpts;\n this.forkArgs = options.forkArgs;\n this.workerOpts = options.workerOpts;\n this.workerThreadOpts = options.workerThreadOpts\n this.workerTerminateTimeout = options.workerTerminateTimeout;\n\n // The ready message is only sent if the worker.add method is called (And the default script is not used)\n if (!script) {\n this.worker.ready = true;\n }\n\n // queue for requests that are received before the worker is ready\n this.requestQueue = [];\n\n this.worker.on(\"stdout\", function (data) {\n handleEmittedStdPayload(me, {\"stdout\": data.toString()})\n })\n this.worker.on(\"stderr\", function (data) {\n handleEmittedStdPayload(me, {\"stderr\": data.toString()})\n })\n\n this.worker.on('message', function (response) {\n if (me.terminated) {\n return;\n }\n if (typeof response === 'string' && response === 'ready') {\n me.worker.ready = true;\n dispatchQueuedRequests();\n } else {\n // find the task from the processing queue, and run the tasks callback\n var id = response.id;\n var task = me.processing[id];\n if (task !== undefined) {\n if (response.isEvent) {\n if (task.options && typeof task.options.on === 'function') {\n task.options.on(response.payload);\n }\n } else {\n // remove the task from the queue\n delete me.processing[id];\n\n // test if we need to terminate\n if (me.terminating === true) {\n // complete worker termination if all tasks are finished\n me.terminate();\n }\n\n // resolve the task's promise\n if (response.error) {\n task.resolver.reject(objectToError(response.error));\n }\n else {\n task.resolver.resolve(response.result);\n }\n }\n }\n }\n });\n\n // reject all running tasks on worker error\n function onError(error) {\n me.terminated = true;\n\n for (var id in me.processing) {\n if (me.processing[id] !== undefined) {\n me.processing[id].resolver.reject(error);\n }\n }\n me.processing = Object.create(null);\n }\n\n // send all queued requests to worker\n function dispatchQueuedRequests()\n {\n for(const request of me.requestQueue.splice(0)) {\n me.worker.send(request.message, request.transfer);\n }\n }\n\n var worker = this.worker;\n // listen for worker messages error and exit\n this.worker.on('error', onError);\n this.worker.on('exit', function (exitCode, signalCode) {\n var message = 'Workerpool Worker terminated Unexpectedly\\n';\n\n message += ' exitCode: `' + exitCode + '`\\n';\n message += ' signalCode: `' + signalCode + '`\\n';\n\n message += ' workerpool.script: `' + me.script + '`\\n';\n message += ' spawnArgs: `' + worker.spawnargs + '`\\n';\n message += ' spawnfile: `' + worker.spawnfile + '`\\n'\n\n message += ' stdout: `' + worker.stdout + '`\\n'\n message += ' stderr: `' + worker.stderr + '`\\n'\n\n onError(new Error(message));\n });\n\n this.processing = Object.create(null); // queue with tasks currently in progress\n\n this.terminating = false;\n this.terminated = false;\n this.cleaning = false;\n this.terminationHandler = null;\n this.lastId = 0;\n}\n\n/**\n * Get a list with methods available on the worker.\n * @return {Promise.} methods\n */\nWorkerHandler.prototype.methods = function () {\n return this.exec('methods');\n};\n\n/**\n * Execute a method with given parameters on the worker\n * @param {String} method\n * @param {Array} [params]\n * @param {{resolve: Function, reject: Function}} [resolver]\n * @param {import('./types.js').ExecOptions} [options]\n * @return {Promise.<*, Error>} result\n */\nWorkerHandler.prototype.exec = function(method, params, resolver, options) {\n if (!resolver) {\n resolver = Promise.defer();\n }\n\n // generate a unique id for the task\n var id = ++this.lastId;\n\n // register a new task as being in progress\n this.processing[id] = {\n id: id,\n resolver: resolver,\n options: options\n };\n\n // build a JSON-RPC request\n var request = {\n message: {\n id: id,\n method: method,\n params: params\n },\n transfer: options && options.transfer\n };\n\n if (this.terminated) {\n resolver.reject(new Error('Worker is terminated'));\n } else if (this.worker.ready) {\n // send the request to the worker\n this.worker.send(request.message, request.transfer);\n } else {\n this.requestQueue.push(request);\n }\n\n // on cancellation, force the worker to terminate\n var me = this;\n return resolver.promise.catch(function (error) {\n if (error instanceof Promise.CancellationError || error instanceof Promise.TimeoutError) {\n // remove this task from the queue. It is already rejected (hence this\n // catch event), and else it will be rejected again when terminating\n delete me.processing[id];\n\n // terminate worker\n return me.terminateAndNotify(true)\n .then(function() {\n throw error;\n }, function(err) {\n throw err;\n });\n } else {\n throw error;\n }\n })\n};\n\n/**\n * Test whether the worker is processing any tasks or cleaning up before termination.\n * @return {boolean} Returns true if the worker is busy\n */\nWorkerHandler.prototype.busy = function () {\n return this.cleaning || Object.keys(this.processing).length > 0;\n};\n\n/**\n * Terminate the worker.\n * @param {boolean} [force=false] If false (default), the worker is terminated\n * after finishing all tasks currently in\n * progress. If true, the worker will be\n * terminated immediately.\n * @param {function} [callback=null] If provided, will be called when process terminates.\n */\nWorkerHandler.prototype.terminate = function (force, callback) {\n var me = this;\n if (force) {\n // cancel all tasks in progress\n for (var id in this.processing) {\n if (this.processing[id] !== undefined) {\n this.processing[id].resolver.reject(new Error('Worker terminated'));\n }\n }\n this.processing = Object.create(null);\n }\n\n if (typeof callback === 'function') {\n this.terminationHandler = callback;\n }\n if (!this.busy()) {\n // all tasks are finished. kill the worker\n var cleanup = function(err) {\n me.terminated = true;\n me.cleaning = false;\n if (me.worker != null && me.worker.removeAllListeners) {\n // removeAllListeners is only available for child_process\n me.worker.removeAllListeners('message');\n }\n me.worker = null;\n me.terminating = false;\n if (me.terminationHandler) {\n me.terminationHandler(err, me);\n } else if (err) {\n throw err;\n }\n }\n\n if (this.worker) {\n if (typeof this.worker.kill === 'function') {\n if (this.worker.killed) {\n cleanup(new Error('worker already killed!'));\n return;\n }\n\n // child process and worker threads\n var cleanExitTimeout = setTimeout(function() {\n if (me.worker) {\n me.worker.kill();\n }\n }, this.workerTerminateTimeout);\n\n this.worker.once('exit', function() {\n clearTimeout(cleanExitTimeout);\n if (me.worker) {\n me.worker.killed = true;\n }\n cleanup();\n });\n\n if (this.worker.ready) {\n this.worker.send(TERMINATE_METHOD_ID);\n } else {\n this.requestQueue.push({ message: TERMINATE_METHOD_ID });\n }\n\n // mark that the worker is cleaning up resources\n // to prevent new tasks from being executed\n this.cleaning = true;\n return;\n }\n else if (typeof this.worker.terminate === 'function') {\n this.worker.terminate(); // web worker\n this.worker.killed = true;\n }\n else {\n throw new Error('Failed to terminate worker');\n }\n }\n cleanup();\n }\n else {\n // we can't terminate immediately, there are still tasks being executed\n this.terminating = true;\n }\n};\n\n/**\n * Terminate the worker, returning a Promise that resolves when the termination has been done.\n * @param {boolean} [force=false] If false (default), the worker is terminated\n * after finishing all tasks currently in\n * progress. If true, the worker will be\n * terminated immediately.\n * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected\n * after timeout if worker process has not been terminated.\n * @return {Promise.}\n */\nWorkerHandler.prototype.terminateAndNotify = function (force, timeout) {\n var resolver = Promise.defer();\n if (timeout) {\n resolver.promise.timeout(timeout);\n }\n this.terminate(force, function(err, worker) {\n if (err) {\n resolver.reject(err);\n } else {\n resolver.resolve(worker);\n }\n });\n return resolver.promise;\n};\n\nmodule.exports = WorkerHandler;\nmodule.exports._tryRequireWorkerThreads = tryRequireWorkerThreads;\nmodule.exports._setupProcessWorker = setupProcessWorker;\nmodule.exports._setupBrowserWorker = setupBrowserWorker;\nmodule.exports._setupWorkerThreadWorker = setupWorkerThreadWorker;\nmodule.exports.ensureWorkerThreads = ensureWorkerThreads;\n","'use strict';\n\nvar MAX_PORTS = 65535;\nmodule.exports = DebugPortAllocator;\nfunction DebugPortAllocator() {\n this.ports = Object.create(null);\n this.length = 0;\n}\n\nDebugPortAllocator.prototype.nextAvailableStartingAt = function(starting) {\n while (this.ports[starting] === true) {\n starting++;\n }\n\n if (starting >= MAX_PORTS) {\n throw new Error('WorkerPool debug port limit reached: ' + starting + '>= ' + MAX_PORTS );\n }\n\n this.ports[starting] = true;\n this.length++;\n return starting;\n};\n\nDebugPortAllocator.prototype.releasePort = function(port) {\n delete this.ports[port];\n this.length--;\n};\n\n","var {Promise} = require('./Promise');\nvar WorkerHandler = require('./WorkerHandler');\nvar environment = require('./environment');\nvar DebugPortAllocator = require('./debug-port-allocator');\nvar DEBUG_PORT_ALLOCATOR = new DebugPortAllocator();\n/**\n * A pool to manage workers, which can be created using the function workerpool.pool.\n *\n * @param {String} [script] Optional worker script\n * @param {import('./types.js').WorkerPoolOptions} [options] See docs\n * @constructor\n */\nfunction Pool(script, options) {\n if (typeof script === 'string') {\n /** @readonly */\n this.script = script || null;\n }\n else {\n this.script = null;\n options = script;\n }\n\n /** @private */\n this.workers = []; // queue with all workers\n /** @private */\n this.tasks = []; // queue with tasks awaiting execution\n\n options = options || {};\n\n /** @readonly */\n this.forkArgs = Object.freeze(options.forkArgs || []);\n /** @readonly */\n this.forkOpts = Object.freeze(options.forkOpts || {});\n /** @readonly */\n this.workerOpts = Object.freeze(options.workerOpts || {});\n /** @readonly */\n this.workerThreadOpts = Object.freeze(options.workerThreadOpts || {})\n /** @private */\n this.debugPortStart = (options.debugPortStart || 43210);\n /** @readonly @deprecated */\n this.nodeWorker = options.nodeWorker;\n /** @readonly\n * @type {'auto' | 'web' | 'process' | 'thread'}\n */\n this.workerType = options.workerType || options.nodeWorker || 'auto'\n /** @readonly */\n this.maxQueueSize = options.maxQueueSize || Infinity;\n /** @readonly */\n this.workerTerminateTimeout = options.workerTerminateTimeout || 1000;\n\n /** @readonly */\n this.onCreateWorker = options.onCreateWorker || (() => null);\n /** @readonly */\n this.onTerminateWorker = options.onTerminateWorker || (() => null);\n\n /** @readonly */\n this.emitStdStreams = options.emitStdStreams || false\n\n // configuration\n if (options && 'maxWorkers' in options) {\n validateMaxWorkers(options.maxWorkers);\n /** @readonly */\n this.maxWorkers = options.maxWorkers;\n }\n else {\n this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1);\n }\n\n if (options && 'minWorkers' in options) {\n if(options.minWorkers === 'max') {\n /** @readonly */\n this.minWorkers = this.maxWorkers;\n } else {\n validateMinWorkers(options.minWorkers);\n this.minWorkers = options.minWorkers;\n this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers); // in case minWorkers is higher than maxWorkers\n }\n this._ensureMinWorkers();\n }\n\n /** @private */\n this._boundNext = this._next.bind(this);\n\n\n if (this.workerType === 'thread') {\n WorkerHandler.ensureWorkerThreads();\n }\n}\n\n\n/**\n * Execute a function on a worker.\n *\n * Example usage:\n *\n * var pool = new Pool()\n *\n * // call a function available on the worker\n * pool.exec('fibonacci', [6])\n *\n * // offload a function\n * function add(a, b) {\n * return a + b\n * };\n * pool.exec(add, [2, 4])\n * .then(function (result) {\n * console.log(result); // outputs 6\n * })\n * .catch(function(error) {\n * console.log(error);\n * });\n * @template { (...args: any[]) => any } T\n * @param {String | T} method Function name or function.\n * If `method` is a string, the corresponding\n * method on the worker will be executed\n * If `method` is a Function, the function\n * will be stringified and executed via the\n * workers built-in function `run(fn, args)`.\n * @param {Parameters | null} [params] Function arguments applied when calling the function\n * @param {import('./types.js').ExecOptions} [options] Options\n * @return {Promise>}\n */\nPool.prototype.exec = function (method, params, options) {\n // validate type of arguments\n if (params && !Array.isArray(params)) {\n throw new TypeError('Array expected as argument \"params\"');\n }\n\n if (typeof method === 'string') {\n var resolver = Promise.defer();\n\n if (this.tasks.length >= this.maxQueueSize) {\n throw new Error('Max queue size of ' + this.maxQueueSize + ' reached');\n }\n\n // add a new task to the queue\n var tasks = this.tasks;\n var task = {\n method: method,\n params: params,\n resolver: resolver,\n timeout: null,\n options: options\n };\n tasks.push(task);\n\n // replace the timeout method of the Promise with our own,\n // which starts the timer as soon as the task is actually started\n var originalTimeout = resolver.promise.timeout;\n resolver.promise.timeout = function timeout (delay) {\n if (tasks.indexOf(task) !== -1) {\n // task is still queued -> start the timer later on\n task.timeout = delay;\n return resolver.promise;\n }\n else {\n // task is already being executed -> start timer immediately\n return originalTimeout.call(resolver.promise, delay);\n }\n };\n\n // trigger task execution\n this._next();\n\n return resolver.promise;\n }\n else if (typeof method === 'function') {\n // send stringified function and function arguments to worker\n return this.exec('run', [String(method), params], options);\n }\n else {\n throw new TypeError('Function or string expected as argument \"method\"');\n }\n};\n\n/**\n * Create a proxy for current worker. Returns an object containing all\n * methods available on the worker. All methods return promises resolving the methods result.\n * @template { { [k: string]: (...args: any[]) => any } } T\n * @return {Promise, Error>} Returns a promise which resolves with a proxy object\n */\nPool.prototype.proxy = function () {\n if (arguments.length > 0) {\n throw new Error('No arguments expected');\n }\n\n var pool = this;\n return this.exec('methods')\n .then(function (methods) {\n var proxy = {};\n\n methods.forEach(function (method) {\n proxy[method] = function () {\n return pool.exec(method, Array.prototype.slice.call(arguments));\n }\n });\n\n return proxy;\n });\n};\n\n/**\n * Creates new array with the results of calling a provided callback function\n * on every element in this array.\n * @param {Array} array\n * @param {function} callback Function taking two arguments:\n * `callback(currentValue, index)`\n * @return {Promise.} Returns a promise which resolves with an Array\n * containing the results of the callback function\n * executed for each of the array elements.\n */\n/* TODO: implement map\nPool.prototype.map = function (array, callback) {\n};\n*/\n\n/**\n * Grab the first task from the queue, find a free worker, and assign the\n * worker to the task.\n * @private\n */\nPool.prototype._next = function () {\n if (this.tasks.length > 0) {\n // there are tasks in the queue\n\n // find an available worker\n var worker = this._getWorker();\n if (worker) {\n // get the first task from the queue\n var me = this;\n var task = this.tasks.shift();\n\n // check if the task is still pending (and not cancelled -> promise rejected)\n if (task.resolver.promise.pending) {\n // send the request to the worker\n var promise = worker.exec(task.method, task.params, task.resolver, task.options)\n .then(me._boundNext)\n .catch(function () {\n // if the worker crashed and terminated, remove it from the pool\n if (worker.terminated) {\n return me._removeWorker(worker);\n }\n }).then(function() {\n me._next(); // trigger next task in the queue\n });\n\n // start queued timer now\n if (typeof task.timeout === 'number') {\n promise.timeout(task.timeout);\n }\n } else {\n // The task taken was already complete (either rejected or resolved), so just trigger next task in the queue\n me._next();\n }\n }\n }\n};\n\n/**\n * Get an available worker. If no worker is available and the maximum number\n * of workers isn't yet reached, a new worker will be created and returned.\n * If no worker is available and the maximum number of workers is reached,\n * null will be returned.\n *\n * @return {WorkerHandler | null} worker\n * @private\n */\nPool.prototype._getWorker = function() {\n // find a non-busy worker\n var workers = this.workers;\n for (var i = 0; i < workers.length; i++) {\n var worker = workers[i];\n if (worker.busy() === false) {\n return worker;\n }\n }\n\n if (workers.length < this.maxWorkers) {\n // create a new worker\n worker = this._createWorkerHandler();\n workers.push(worker);\n return worker;\n }\n\n return null;\n};\n\n/**\n * Remove a worker from the pool.\n * Attempts to terminate worker if not already terminated, and ensures the minimum\n * pool size is met.\n * @param {WorkerHandler} worker\n * @return {Promise}\n * @private\n */\nPool.prototype._removeWorker = function(worker) {\n var me = this;\n\n DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort);\n // _removeWorker will call this, but we need it to be removed synchronously\n this._removeWorkerFromList(worker);\n // If minWorkers set, spin up new workers to replace the crashed ones\n this._ensureMinWorkers();\n // terminate the worker (if not already terminated)\n return new Promise(function(resolve, reject) {\n worker.terminate(false, function(err) {\n me.onTerminateWorker({\n forkArgs: worker.forkArgs,\n forkOpts: worker.forkOpts,\n workerThreadOpts: worker.workerThreadOpts,\n script: worker.script\n });\n if (err) {\n reject(err);\n } else {\n resolve(worker);\n }\n });\n });\n};\n\n/**\n * Remove a worker from the pool list.\n * @param {WorkerHandler} worker\n * @private\n */\nPool.prototype._removeWorkerFromList = function(worker) {\n // remove from the list with workers\n var index = this.workers.indexOf(worker);\n if (index !== -1) {\n this.workers.splice(index, 1);\n }\n};\n\n/**\n * Close all active workers. Tasks currently being executed will be finished first.\n * @param {boolean} [force=false] If false (default), the workers are terminated\n * after finishing all tasks currently in\n * progress. If true, the workers will be\n * terminated immediately.\n * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected\n * after timeout if worker process has not been terminated.\n * @return {Promise.}\n */\nPool.prototype.terminate = function (force, timeout) {\n var me = this;\n\n // cancel any pending tasks\n this.tasks.forEach(function (task) {\n task.resolver.reject(new Error('Pool terminated'));\n });\n this.tasks.length = 0;\n\n var f = function (worker) {\n DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort);\n this._removeWorkerFromList(worker);\n };\n var removeWorker = f.bind(this);\n\n var promises = [];\n var workers = this.workers.slice();\n workers.forEach(function (worker) {\n var termPromise = worker.terminateAndNotify(force, timeout)\n .then(removeWorker)\n .always(function() {\n me.onTerminateWorker({\n forkArgs: worker.forkArgs,\n forkOpts: worker.forkOpts,\n workerThreadOpts: worker.workerThreadOpts,\n script: worker.script\n });\n });\n promises.push(termPromise);\n });\n return Promise.all(promises);\n};\n\n/**\n * Retrieve statistics on tasks and workers.\n * @return {{totalWorkers: number, busyWorkers: number, idleWorkers: number, pendingTasks: number, activeTasks: number}} Returns an object with statistics\n */\nPool.prototype.stats = function () {\n var totalWorkers = this.workers.length;\n var busyWorkers = this.workers.filter(function (worker) {\n return worker.busy();\n }).length;\n\n return {\n totalWorkers: totalWorkers,\n busyWorkers: busyWorkers,\n idleWorkers: totalWorkers - busyWorkers,\n\n pendingTasks: this.tasks.length,\n activeTasks: busyWorkers\n };\n};\n\n/**\n * Ensures that a minimum of minWorkers is up and running\n * @private\n */\nPool.prototype._ensureMinWorkers = function() {\n if (this.minWorkers) {\n for(var i = this.workers.length; i < this.minWorkers; i++) {\n this.workers.push(this._createWorkerHandler());\n }\n }\n};\n\n/**\n * Helper function to create a new WorkerHandler and pass all options.\n * @return {WorkerHandler}\n * @private\n */\nPool.prototype._createWorkerHandler = function () {\n const overriddenParams = this.onCreateWorker({\n forkArgs: this.forkArgs,\n forkOpts: this.forkOpts,\n workerOpts: this.workerOpts,\n workerThreadOpts: this.workerThreadOpts,\n script: this.script\n }) || {};\n\n return new WorkerHandler(overriddenParams.script || this.script, {\n forkArgs: overriddenParams.forkArgs || this.forkArgs,\n forkOpts: overriddenParams.forkOpts || this.forkOpts,\n workerOpts: overriddenParams.workerOpts || this.workerOpts,\n workerThreadOpts: overriddenParams.workerThreadOpts || this.workerThreadOpts,\n debugPort: DEBUG_PORT_ALLOCATOR.nextAvailableStartingAt(this.debugPortStart),\n workerType: this.workerType,\n workerTerminateTimeout: this.workerTerminateTimeout,\n emitStdStreams: this.emitStdStreams,\n });\n}\n\n/**\n * Ensure that the maxWorkers option is an integer >= 1\n * @param {*} maxWorkers\n * @returns {boolean} returns true maxWorkers has a valid value\n */\nfunction validateMaxWorkers(maxWorkers) {\n if (!isNumber(maxWorkers) || !isInteger(maxWorkers) || maxWorkers < 1) {\n throw new TypeError('Option maxWorkers must be an integer number >= 1');\n }\n}\n\n/**\n * Ensure that the minWorkers option is an integer >= 0\n * @param {*} minWorkers\n * @returns {boolean} returns true when minWorkers has a valid value\n */\nfunction validateMinWorkers(minWorkers) {\n if (!isNumber(minWorkers) || !isInteger(minWorkers) || minWorkers < 0) {\n throw new TypeError('Option minWorkers must be an integer number >= 0');\n }\n}\n\n/**\n * Test whether a variable is a number\n * @param {*} value\n * @returns {boolean} returns true when value is a number\n */\nfunction isNumber(value) {\n return typeof value === 'number';\n}\n\n/**\n * Test whether a number is an integer\n * @param {number} value\n * @returns {boolean} Returns true if value is an integer\n */\nfunction isInteger(value) {\n return Math.round(value) == value;\n}\n\nmodule.exports = Pool;\n","/**\n * The helper class for transferring data from the worker to the main thread.\n *\n * @param {Object} message The object to deliver to the main thread.\n * @param {Object[]} transfer An array of transferable Objects to transfer ownership of.\n */\nfunction Transfer(message, transfer) {\n this.message = message;\n this.transfer = transfer;\n}\n\nmodule.exports = Transfer;\n","/**\n * worker must be started as a child process or a web worker.\n * It listens for RPC messages from the parent process.\n */\nvar Transfer = require('./transfer');\n\n/**\n * Special message sent by parent which causes the worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\n// var nodeOSPlatform = require('./environment').nodeOSPlatform;\n\n// create a worker API for sending and receiving messages which works both on\n// node.js and in the browser\nvar worker = {\n exit: function() {}\n};\nif (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') {\n // worker in the browser\n worker.on = function (event, callback) {\n addEventListener(event, function (message) {\n callback(message.data);\n })\n };\n worker.send = function (message) {\n postMessage(message);\n };\n}\nelse if (typeof process !== 'undefined') {\n // node.js\n\n var WorkerThreads;\n try {\n WorkerThreads = require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads, fallback to sub-process based workers\n } else {\n throw error;\n }\n }\n\n if (WorkerThreads &&\n /* if there is a parentPort, we are in a WorkerThread */\n WorkerThreads.parentPort !== null) {\n var parentPort = WorkerThreads.parentPort;\n worker.send = parentPort.postMessage.bind(parentPort);\n worker.on = parentPort.on.bind(parentPort);\n worker.exit = process.exit.bind(process);\n } else {\n worker.on = process.on.bind(process);\n // ignore transfer argument since it is not supported by process\n worker.send = function (message) {\n process.send(message);\n };\n // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly\n worker.on('disconnect', function () {\n process.exit(1);\n });\n worker.exit = process.exit.bind(process);\n }\n}\nelse {\n throw new Error('Script must be executed as a worker');\n}\n\nfunction convertError(error) {\n return Object.getOwnPropertyNames(error).reduce(function(product, name) {\n return Object.defineProperty(product, name, {\n\tvalue: error[name],\n\tenumerable: true\n });\n }, {});\n}\n\n/**\n * Test whether a value is a Promise via duck typing.\n * @param {*} value\n * @returns {boolean} Returns true when given value is an object\n * having functions `then` and `catch`.\n */\nfunction isPromise(value) {\n return value && (typeof value.then === 'function') && (typeof value.catch === 'function');\n}\n\n// functions available externally\nworker.methods = {};\n\n/**\n * Execute a function with provided arguments\n * @param {String} fn Stringified function\n * @param {Array} [args] Function arguments\n * @returns {*}\n */\nworker.methods.run = function run(fn, args) {\n var f = new Function('return (' + fn + ').apply(null, arguments);');\n return f.apply(f, args);\n};\n\n/**\n * Get a list with methods available on this worker\n * @return {String[]} methods\n */\nworker.methods.methods = function methods() {\n return Object.keys(worker.methods);\n};\n\n/**\n * Custom handler for when the worker is terminated.\n */\nworker.terminationHandler = undefined;\n\n/**\n * Cleanup and exit the worker.\n * @param {Number} code \n * @returns \n */\nworker.cleanupAndExit = function(code) {\n var _exit = function() {\n worker.exit(code);\n }\n\n if(!worker.terminationHandler) {\n return _exit();\n }\n\n var result = worker.terminationHandler(code);\n if (isPromise(result)) {\n result.then(_exit, _exit);\n } else {\n _exit();\n }\n}\n\nvar currentRequestId = null;\n\nworker.on('message', function (request) {\n if (request === TERMINATE_METHOD_ID) {\n return worker.cleanupAndExit(0);\n }\n try {\n var method = worker.methods[request.method];\n\n if (method) {\n currentRequestId = request.id;\n \n // execute the function\n var result = method.apply(method, request.params);\n\n if (isPromise(result)) {\n // promise returned, resolve this and then return\n result\n .then(function (result) {\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n currentRequestId = null;\n })\n .catch(function (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n currentRequestId = null;\n });\n }\n else {\n // immediate result\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n\n currentRequestId = null;\n }\n }\n else {\n throw new Error('Unknown method \"' + request.method + '\"');\n }\n }\n catch (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n }\n});\n\n/**\n * Register methods to the worker\n * @param {Object} [methods]\n * @param {import('./types.js').WorkerRegisterOptions} [options]\n */\nworker.register = function (methods, options) {\n\n if (methods) {\n for (var name in methods) {\n if (methods.hasOwnProperty(name)) {\n worker.methods[name] = methods[name];\n }\n }\n }\n\n if (options) {\n worker.terminationHandler = options.onTerminate;\n }\n\n worker.send('ready');\n};\n\nworker.emit = function (payload) {\n if (currentRequestId) {\n if (payload instanceof Transfer) {\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload: payload.message\n }, payload.transfer);\n return;\n }\n\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload\n });\n }\n};\n\nif (typeof exports !== 'undefined') {\n exports.add = worker.register;\n exports.emit = worker.emit;\n}\n","const {platform, isMainThread, cpus} = require('./environment');\n\n/** @typedef {import(\"./Pool\")} Pool */\n/** @typedef {import(\"./types.js\").WorkerPoolOptions} WorkerPoolOptions */\n/** @typedef {import(\"./types.js\").WorkerRegisterOptions} WorkerRegisterOptions */\n\n/**\n * @template { { [k: string]: (...args: any[]) => any } } T\n * @typedef {import('./types.js').Proxy} Proxy\n */\n\n/**\n * @overload\n * Create a new worker pool\n * @param {WorkerPoolOptions} [script]\n * @returns {Pool} pool\n */\n/**\n * @overload\n * Create a new worker pool\n * @param {string} [script]\n * @param {WorkerPoolOptions} [options]\n * @returns {Pool} pool\n */\nfunction pool(script, options) {\n var Pool = require('./Pool');\n\n return new Pool(script, options);\n};\nexports.pool = pool;\n\n/**\n * Create a worker and optionally register a set of methods to the worker.\n * @param {{ [k: string]: (...args: any[]) => any }} [methods]\n * @param {WorkerRegisterOptions} [options]\n */\nfunction worker(methods, options) {\n var worker = require('./worker');\n worker.add(methods, options);\n};\nexports.worker = worker;\n\n/**\n * Sends an event to the parent worker pool.\n * @param {any} payload \n */\nfunction workerEmit(payload) {\n var worker = require('./worker');\n worker.emit(payload);\n};\nexports.workerEmit = workerEmit;\n\nconst {Promise} = require('./Promise');\nexports.Promise = Promise;\n\nexports.Transfer = require('./transfer');\n\nexports.platform = platform;\nexports.isMainThread = isMainThread;\nexports.cpus = cpus;\n"],"names":["isNode","nodeProcess","versions","node","module","exports","platform","process","worker_threads","require","isMainThread","connected","Window","cpus","self","navigator","hardwareConcurrency","length","Promise","handler","parent","me","SyntaxError","_onSuccess","_onFail","resolved","rejected","pending","_process","onSuccess","onFail","push","then","resolve","reject","s","_then","f","_resolve","result","forEach","fn","_reject","error","cancel","CancellationError","timeout","delay","timer","setTimeout","TimeoutError","always","clearTimeout","callback","res","prototype","all","promises","remaining","results","p","i","defer","resolver","promise","message","stack","Error","constructor","name","_Promise","validateOptions","options","allowedOptionNames","objectName","optionNames","Object","keys","unknownOptionName","find","optionName","includes","illegalOptionName","allowedOptionName","workerOptsNames","forkOptsNames","workerThreadOptsNames","embeddedWorker","require$$0","environment","require$$1","require$$2","TERMINATE_METHOD_ID","ensureWorkerThreads","WorkerThreads","tryRequireWorkerThreads","ensureWebWorker","Worker","code","getDefaultWorker","Blob","window","URL","createObjectURL","blob","require$$3","type","__dirname","setupWorker","script","workerType","setupBrowserWorker","workerOpts","setupWorkerThreadWorker","setupProcessWorker","resolveForkOptions","worker","isBrowserWorker","on","event","addEventListener","data","send","transfer","postMessage","workerThreadOpts","stdout","emitStdStreams","stderr","isWorkerThread","kill","terminate","disconnect","emit","child_process","forkOpts","fork","forkArgs","call","isChildProcess","opts","processExecArgv","execArgv","join","inspectorActive","indexOf","debugBrk","debugPort","arg","assign","concat","stdio","undefined","objectToError","obj","temp","props","handleEmittedStdPayload","payload","processing","task","values","WorkerHandler","_options","workerTerminateTimeout","ready","requestQueue","toString","response","terminated","dispatchQueuedRequests","id","isEvent","terminating","onError","create","request","splice","exitCode","signalCode","spawnargs","spawnfile","cleaning","terminationHandler","lastId","methods","exec","method","params","catch","terminateAndNotify","err","busy","force","cleanup","removeAllListeners","killed","cleanExitTimeout","once","WorkerHandlerModule","_tryRequireWorkerThreads","_setupProcessWorker","_setupBrowserWorker","_setupWorkerThreadWorker","MAX_PORTS","debugPortAllocator","DebugPortAllocator","ports","nextAvailableStartingAt","starting","releasePort","port","DEBUG_PORT_ALLOCATOR","Pool","workers","tasks","freeze","debugPortStart","nodeWorker","maxQueueSize","Infinity","onCreateWorker","onTerminateWorker","validateMaxWorkers","maxWorkers","Math","max","minWorkers","validateMinWorkers","_ensureMinWorkers","_boundNext","_next","bind","Array","isArray","TypeError","originalTimeout","String","proxy","arguments","pool","slice","_getWorker","shift","_removeWorker","_createWorkerHandler","_removeWorkerFromList","index","removeWorker","termPromise","stats","totalWorkers","busyWorkers","filter","idleWorkers","pendingTasks","activeTasks","overriddenParams","isNumber","isInteger","value","round","Pool_1","Transfer","exit","parentPort","convertError","getOwnPropertyNames","reduce","product","defineProperty","enumerable","isPromise","run","args","Function","apply","cleanupAndExit","_exit","currentRequestId","register","hasOwnProperty","onTerminate","add","pool_1","src","worker_1","workerEmit","workerEmit_1","require$$4","platform_1","isMainThread_1","cpus_1"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EACA;EACA;EACA,EAAA,IAAIA,MAAM,GAAG,UAAUC,WAAW,EAAE;MAClC,OACE,OAAOA,WAAW,KAAK,WAAW,IAClCA,WAAW,CAACC,QAAQ,IAAI,IAAI,IAC5BD,WAAW,CAACC,QAAQ,CAACC,IAAI,IAAI,IAAI,IACjCF,WAAW,GAAG,EAAE,KAAK,kBAAkB,CAAA;KAE1C,CAAA;EACDG,EAAAA,MAAA,CAAAC,OAAA,CAAAL,MAAA,GAAwBA,MAAM,CAAA;;EAE9B;EACAI,EAAAA,MAA0B,CAAAC,OAAA,CAAAC,QAAA,GAAA,OAAOC,OAAO,KAAK,WAAW,IAAIP,MAAM,CAACO,OAAO,CAAC,GACvE,MAAM,GACN,SAAS,CAAA;;EAEb;EACA;EACA,EAAA,IAAIC,cAAc,GAAGJ,MAAM,CAACC,OAAO,CAACC,QAAQ,KAAK,MAAM,IAAIG,OAAQ,CAAA,gBAAgB,CAAC,CAAA;EACpFL,EAAAA,MAAA,CAAAC,OAAA,CAAAK,YAAA,GAA8BN,MAAM,CAACC,OAAO,CAACC,QAAQ,KAAK,MAAM,GAC3D,CAAC,CAACE,cAAc,IAAIA,cAAc,CAACE,YAAY,KAAK,CAACH,OAAO,CAACI,SAAS,GACvE,OAAOC,MAAM,KAAK,WAAW,CAAA;;EAEjC;EACAR,EAAAA,MAAA,CAAAC,OAAA,CAAAQ,IAAA,GAAsBT,MAAM,CAACC,OAAO,CAACC,QAAQ,KAAK,SAAS,GACvDQ,IAAI,CAACC,SAA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git a/node_modules/workerpool/dist/workerpool.min.js b/node_modules/workerpool/dist/workerpool.min.js deleted file mode 100644 index 417d1702..00000000 --- a/node_modules/workerpool/dist/workerpool.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see workerpool.min.js.LICENSE.txt */ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).workerpool={})}(this,(function(e){"use strict";var r={},t={exports:{}};!function(e){var r=function(e){return void 0!==e&&null!=e.versions&&null!=e.versions.node&&e+""=="[object process]"};e.exports.isNode=r,e.exports.platform="undefined"!=typeof process&&r(process)?"node":"browser";var t="node"===e.exports.platform&&require("worker_threads");e.exports.isMainThread="node"===e.exports.platform?(!t||t.isMainThread)&&!process.connected:"undefined"!=typeof Window,e.exports.cpus="browser"===e.exports.platform?self.navigator.hardwareConcurrency:require("os").cpus().length}(t);var n,o=t.exports,i={};function s(){if(n)return i;function e(n,i){var s=this;if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");if("function"!=typeof n)throw new SyntaxError("Function parameter handler(resolve, reject) missing");var a=[],u=[];this.resolved=!1,this.rejected=!1,this.pending=!0;var c=function(e,r){a.push(e),u.push(r)};this.then=function(t,n){return new e((function(e,o){var i=t?r(t,e,o):e,s=n?r(n,e,o):o;c(i,s)}),s)};var f=function(e){return s.resolved=!0,s.rejected=!1,s.pending=!1,a.forEach((function(r){r(e)})),c=function(r,t){r(e)},f=d=function(){},s},d=function(e){return s.resolved=!1,s.rejected=!0,s.pending=!1,u.forEach((function(r){r(e)})),c=function(r,t){t(e)},f=d=function(){},s};this.cancel=function(){return i?i.cancel():d(new t),s},this.timeout=function(e){if(i)i.timeout(e);else{var r=setTimeout((function(){d(new o("Promise timed out after "+e+" ms"))}),e);s.always((function(){clearTimeout(r)}))}return s},n((function(e){f(e)}),(function(e){d(e)}))}function r(e,r,t){return function(n){try{var o=e(n);o&&"function"==typeof o.then&&"function"==typeof o.catch?o.then(r,t):r(o)}catch(e){t(e)}}}function t(e){this.message=e||"promise cancelled",this.stack=(new Error).stack}function o(e){this.message=e||"timeout exceeded",this.stack=(new Error).stack}return n=1,e.prototype.catch=function(e){return this.then(null,e)},e.prototype.always=function(e){return this.then(e,e)},e.all=function(r){return new e((function(e,t){var n=r.length,o=[];n?r.forEach((function(r,i){r.then((function(r){o[i]=r,0==--n&&e(o)}),(function(e){n=0,t(e)}))})):e(o)}))},e.defer=function(){var r={};return r.promise=new e((function(e,t){r.resolve=e,r.reject=t})),r},t.prototype=new Error,t.prototype.constructor=Error,t.prototype.name="CancellationError",e.CancellationError=t,o.prototype=new Error,o.prototype.constructor=Error,o.prototype.name="TimeoutError",e.TimeoutError=o,i.Promise=e,i}var a,u,c,f,d,p,h,l,m={exports:{}},k={};function w(){return a||(a=1,k.validateOptions=function(e,r,t){if(e){var n=e?Object.keys(e):[],o=n.find((e=>!r.includes(e)));if(o)throw new Error('Object "'+t+'" contains an unknown option "'+o+'"');var i=r.find((e=>Object.prototype[e]&&!n.includes(e)));if(i)throw new Error('Object "'+t+'" contains an inherited option "'+i+'" which is not defined in the object itself but in its prototype. Only plain objects are allowed. Please remove the option from the prototype or override it with a value "undefined".');return e}},k.workerOptsNames=["credentials","name","type"],k.forkOptsNames=["cwd","detached","env","execPath","execArgv","gid","serialization","signal","killSignal","silent","stdio","uid","windowsVerbatimArguments","timeout"],k.workerThreadOptsNames=["argv","env","eval","execArgv","stdin","stdout","stderr","workerData","trackUnmanagedFds","transferList","resourceLimits","name"]),k}function v(){if(f)return m.exports;f=1;var{Promise:e}=s(),r=o;const{validateOptions:t,forkOptsNames:n,workerThreadOptsNames:i,workerOptsNames:a}=w();var d="__workerpool-terminate__";function p(){var e=l();if(!e)throw new Error("WorkerPool: workerType = 'thread' is not supported, Node >= 11.7.0 required");return e}function h(){if("function"!=typeof Worker&&("object"!=typeof Worker||"function"!=typeof Worker.prototype.constructor))throw new Error("WorkerPool: Web Workers not supported")}function l(){try{return require("worker_threads")}catch(e){if("object"==typeof e&&null!==e&&"MODULE_NOT_FOUND"===e.code)return null;throw e}}function k(e,r,n){t(r,a,"workerOpts");var o=new n(e,r);return o.isBrowserWorker=!0,o.on=function(e,r){this.addEventListener(e,(function(e){r(e.data)}))},o.send=function(e,r){this.postMessage(e,r)},o}function v(e,r,n){t(n?.workerThreadOpts,i,"workerThreadOpts");var o=new r.Worker(e,{stdout:n?.emitStdStreams??!1,stderr:n?.emitStdStreams??!1,...n?.workerThreadOpts});return o.isWorkerThread=!0,o.send=function(e,r){this.postMessage(e,r)},o.kill=function(){return this.terminate(),!0},o.disconnect=function(){this.terminate()},n?.emitStdStreams&&(o.stdout.on("data",(e=>o.emit("stdout",e))),o.stderr.on("data",(e=>o.emit("stderr",e)))),o}function y(e,r,o){t(r.forkOpts,n,"forkOpts");var i=o.fork(e,r.forkArgs,r.forkOpts),s=i.send;return i.send=function(e){return s.call(i,e)},r.emitStdStreams&&(i.stdout.on("data",(e=>i.emit("stdout",e))),i.stderr.on("data",(e=>i.emit("stderr",e)))),i.isChildProcess=!0,i}function g(e){e=e||{};var r=process.execArgv.join(" "),t=-1!==r.indexOf("--inspect"),n=-1!==r.indexOf("--debug-brk"),o=[];return t&&(o.push("--inspect="+e.debugPort),n&&o.push("--debug-brk")),process.execArgv.forEach((function(e){e.indexOf("--max-old-space-size")>-1&&o.push(e)})),Object.assign({},e,{forkArgs:e.forkArgs,forkOpts:Object.assign({},e.forkOpts,{execArgv:(e.forkOpts&&e.forkOpts.execArgv||[]).concat(o),stdio:e.emitStdStreams?"pipe":void 0})})}function O(e,r){if(1===Object.keys(e.processing).length){var t=Object.values(e.processing)[0];t.options&&"function"==typeof t.options.on&&t.options.on(r)}}function b(e,t){var n=this,o=t||{};function i(e){for(var r in n.terminated=!0,n.processing)void 0!==n.processing[r]&&n.processing[r].resolver.reject(e);n.processing=Object.create(null)}this.script=e||function(){if("browser"===r.platform){if("undefined"==typeof Blob)throw new Error("Blob not supported by the browser");if(!window.URL||"function"!=typeof window.URL.createObjectURL)throw new Error("URL.createObjectURL not supported by the browser");var e=new Blob([c?u:(c=1,u='!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if("undefined"!=typeof self&&"function"==typeof postMessage&&"function"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if("undefined"==typeof process)throw new Error("Script must be executed as a worker");var o;try{o=require("worker_threads")}catch(e){if("object"!=typeof e||null===e||"MODULE_NOT_FOUND"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on("disconnect",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&"function"==typeof e.then&&"function"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function("return ("+e+").apply(null, arguments);");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on("message",(function(e){if("__workerpool-terminate__"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error(\'Unknown method "\'+e.method+\'"\');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send("ready")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)}));\n//# sourceMappingURL=worker.min.js.map\n')],{type:"text/javascript"});return window.URL.createObjectURL(e)}return __dirname+"/worker.js"}(),this.worker=function(e,t){if("web"===t.workerType)return h(),k(e,t.workerOpts,Worker);if("thread"===t.workerType)return v(e,n=p(),t);if("process"!==t.workerType&&t.workerType){if("browser"===r.platform)return h(),k(e,t.workerOpts,Worker);var n=l();return n?v(e,n,t):y(e,g(t),require("child_process"))}return y(e,g(t),require("child_process"))}(this.script,o),this.debugPort=o.debugPort,this.forkOpts=o.forkOpts,this.forkArgs=o.forkArgs,this.workerOpts=o.workerOpts,this.workerThreadOpts=o.workerThreadOpts,this.workerTerminateTimeout=o.workerTerminateTimeout,e||(this.worker.ready=!0),this.requestQueue=[],this.worker.on("stdout",(function(e){O(n,{stdout:e.toString()})})),this.worker.on("stderr",(function(e){O(n,{stderr:e.toString()})})),this.worker.on("message",(function(e){if(!n.terminated)if("string"==typeof e&&"ready"===e)n.worker.ready=!0,function(){for(const e of n.requestQueue.splice(0))n.worker.send(e.message,e.transfer)}();else{var r=e.id,t=n.processing[r];void 0!==t&&(e.isEvent?t.options&&"function"==typeof t.options.on&&t.options.on(e.payload):(delete n.processing[r],!0===n.terminating&&n.terminate(),e.error?t.resolver.reject(function(e){for(var r=new Error(""),t=Object.keys(e),n=0;n0},b.prototype.terminate=function(e,r){var t=this;if(e){for(var n in this.processing)void 0!==this.processing[n]&&this.processing[n].resolver.reject(new Error("Worker terminated"));this.processing=Object.create(null)}if("function"==typeof r&&(this.terminationHandler=r),this.busy())this.terminating=!0;else{var o=function(e){if(t.terminated=!0,t.cleaning=!1,null!=t.worker&&t.worker.removeAllListeners&&t.worker.removeAllListeners("message"),t.worker=null,t.terminating=!1,t.terminationHandler)t.terminationHandler(e,t);else if(e)throw e};if(this.worker){if("function"==typeof this.worker.kill){if(this.worker.killed)return void o(new Error("worker already killed!"));var i=setTimeout((function(){t.worker&&t.worker.kill()}),this.workerTerminateTimeout);return this.worker.once("exit",(function(){clearTimeout(i),t.worker&&(t.worker.killed=!0),o()})),this.worker.ready?this.worker.send(d):this.requestQueue.push({message:d}),void(this.cleaning=!0)}if("function"!=typeof this.worker.terminate)throw new Error("Failed to terminate worker");this.worker.terminate(),this.worker.killed=!0}o()}},b.prototype.terminateAndNotify=function(r,t){var n=e.defer();return t&&n.promise.timeout(t),this.terminate(r,(function(e,r){e?n.reject(e):n.resolve(r)})),n.promise},m.exports=b,m.exports._tryRequireWorkerThreads=l,m.exports._setupProcessWorker=y,m.exports._setupBrowserWorker=k,m.exports._setupWorkerThreadWorker=v,m.exports.ensureWorkerThreads=p,m.exports}function y(){if(l)return h;l=1;var{Promise:e}=s(),r=v(),t=o,n=new(function(){if(p)return d;function e(){this.ports=Object.create(null),this.length=0}return p=1,d=e,e.prototype.nextAvailableStartingAt=function(e){for(;!0===this.ports[e];)e++;if(e>=65535)throw new Error("WorkerPool debug port limit reached: "+e+">= 65535");return this.ports[e]=!0,this.length++,e},e.prototype.releasePort=function(e){delete this.ports[e],this.length--},d}());function i(e,n){"string"==typeof e?this.script=e||null:(this.script=null,n=e),this.workers=[],this.tasks=[],n=n||{},this.forkArgs=Object.freeze(n.forkArgs||[]),this.forkOpts=Object.freeze(n.forkOpts||{}),this.workerOpts=Object.freeze(n.workerOpts||{}),this.workerThreadOpts=Object.freeze(n.workerThreadOpts||{}),this.debugPortStart=n.debugPortStart||43210,this.nodeWorker=n.nodeWorker,this.workerType=n.workerType||n.nodeWorker||"auto",this.maxQueueSize=n.maxQueueSize||1/0,this.workerTerminateTimeout=n.workerTerminateTimeout||1e3,this.onCreateWorker=n.onCreateWorker||(()=>null),this.onTerminateWorker=n.onTerminateWorker||(()=>null),this.emitStdStreams=n.emitStdStreams||!1,n&&"maxWorkers"in n?(!function(e){if(!a(e)||!u(e)||e<1)throw new TypeError("Option maxWorkers must be an integer number >= 1")}(n.maxWorkers),this.maxWorkers=n.maxWorkers):this.maxWorkers=Math.max((t.cpus||4)-1,1),n&&"minWorkers"in n&&("max"===n.minWorkers?this.minWorkers=this.maxWorkers:(!function(e){if(!a(e)||!u(e)||e<0)throw new TypeError("Option minWorkers must be an integer number >= 0")}(n.minWorkers),this.minWorkers=n.minWorkers,this.maxWorkers=Math.max(this.minWorkers,this.maxWorkers)),this._ensureMinWorkers()),this._boundNext=this._next.bind(this),"thread"===this.workerType&&r.ensureWorkerThreads()}function a(e){return"number"==typeof e}function u(e){return Math.round(e)==e}return i.prototype.exec=function(r,t,n){if(t&&!Array.isArray(t))throw new TypeError('Array expected as argument "params"');if("string"==typeof r){var o=e.defer();if(this.tasks.length>=this.maxQueueSize)throw new Error("Max queue size of "+this.maxQueueSize+" reached");var i=this.tasks,s={method:r,params:t,resolver:o,timeout:null,options:n};i.push(s);var a=o.promise.timeout;return o.promise.timeout=function(e){return-1!==i.indexOf(s)?(s.timeout=e,o.promise):a.call(o.promise,e)},this._next(),o.promise}if("function"==typeof r)return this.exec("run",[String(r),t],n);throw new TypeError('Function or string expected as argument "method"')},i.prototype.proxy=function(){if(arguments.length>0)throw new Error("No arguments expected");var e=this;return this.exec("methods").then((function(r){var t={};return r.forEach((function(r){t[r]=function(){return e.exec(r,Array.prototype.slice.call(arguments))}})),t}))},i.prototype._next=function(){if(this.tasks.length>0){var e=this._getWorker();if(e){var r=this,t=this.tasks.shift();if(t.resolver.promise.pending){var n=e.exec(t.method,t.params,t.resolver,t.options).then(r._boundNext).catch((function(){if(e.terminated)return r._removeWorker(e)})).then((function(){r._next()}));"number"==typeof t.timeout&&n.timeout(t.timeout)}else r._next()}}},i.prototype._getWorker=function(){for(var e=this.workers,r=0;r - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ diff --git a/node_modules/workerpool/dist/workerpool.min.js.map b/node_modules/workerpool/dist/workerpool.min.js.map deleted file mode 100644 index c5a38caa..00000000 --- a/node_modules/workerpool/dist/workerpool.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"workerpool.min.js","sources":["../src/environment.js","../src/Promise.js","../src/validateOptions.js","../src/WorkerHandler.js","../src/generated/embeddedWorker.js","../src/Pool.js","../src/debug-port-allocator.js","../src/transfer.js","../src/worker.js","../src/index.js"],"sourcesContent":["\n// source: https://github.com/flexdinesh/browser-or-node\n// source: https://github.com/mozilla/pdf.js/blob/7ea0e40e588864cd938d1836ec61f1928d3877d3/src/shared/util.js#L24\nvar isNode = function (nodeProcess) {\n return (\n typeof nodeProcess !== 'undefined' &&\n nodeProcess.versions != null &&\n nodeProcess.versions.node != null &&\n nodeProcess + '' === '[object process]'\n );\n}\nmodule.exports.isNode = isNode\n\n// determines the JavaScript platform: browser or node\nmodule.exports.platform = typeof process !== 'undefined' && isNode(process)\n ? 'node'\n : 'browser';\n\n// determines whether the code is running in main thread or not\n// note that in node.js we have to check both worker_thread and child_process\nvar worker_threads = module.exports.platform === 'node' && require('worker_threads');\nmodule.exports.isMainThread = module.exports.platform === 'node'\n ? ((!worker_threads || worker_threads.isMainThread) && !process.connected)\n : typeof Window !== 'undefined';\n\n// determines the number of cpus available\nmodule.exports.cpus = module.exports.platform === 'browser'\n ? self.navigator.hardwareConcurrency\n : require('os').cpus().length;\n\n","'use strict';\n\n/**\n * Promise\n *\n * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa \n * @template T\n * @template [E=Error]\n * @param {Function} handler Called as handler(resolve: Function, reject: Function)\n * @param {Promise} [parent] Parent promise for propagation of cancel and timeout\n */\nfunction Promise(handler, parent) {\n var me = this;\n\n if (!(this instanceof Promise)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n if (typeof handler !== 'function') {\n throw new SyntaxError('Function parameter handler(resolve, reject) missing');\n }\n\n var _onSuccess = [];\n var _onFail = [];\n\n // status\n /**\n * @readonly\n */\n this.resolved = false;\n /**\n * @readonly\n */\n this.rejected = false;\n /**\n * @readonly\n */\n this.pending = true;\n\n /**\n * Process onSuccess and onFail callbacks: add them to the queue.\n * Once the promise is resolved, the function _promise is replace.\n * @param {Function} onSuccess\n * @param {Function} onFail\n * @private\n */\n var _process = function (onSuccess, onFail) {\n _onSuccess.push(onSuccess);\n _onFail.push(onFail);\n };\n\n /**\n * Add an onSuccess callback and optionally an onFail callback to the Promise\n * @template TT\n * @template [TE=never]\n * @param {(r: T) => TT | PromiseLike} onSuccess\n * @param {(r: E) => TE | PromiseLike} [onFail]\n * @returns {Promise} promise\n */\n this.then = function (onSuccess, onFail) {\n return new Promise(function (resolve, reject) {\n var s = onSuccess ? _then(onSuccess, resolve, reject) : resolve;\n var f = onFail ? _then(onFail, resolve, reject) : reject;\n\n _process(s, f);\n }, me);\n };\n\n /**\n * Resolve the promise\n * @param {*} result\n * @type {Function}\n */\n var _resolve = function (result) {\n // update status\n me.resolved = true;\n me.rejected = false;\n me.pending = false;\n\n _onSuccess.forEach(function (fn) {\n fn(result);\n });\n\n _process = function (onSuccess, onFail) {\n onSuccess(result);\n };\n\n _resolve = _reject = function () { };\n\n return me;\n };\n\n /**\n * Reject the promise\n * @param {Error} error\n * @type {Function}\n */\n var _reject = function (error) {\n // update status\n me.resolved = false;\n me.rejected = true;\n me.pending = false;\n\n _onFail.forEach(function (fn) {\n fn(error);\n });\n\n _process = function (onSuccess, onFail) {\n onFail(error);\n };\n\n _resolve = _reject = function () { }\n\n return me;\n };\n\n /**\n * Cancel the promise. This will reject the promise with a CancellationError\n * @returns {this} self\n */\n this.cancel = function () {\n if (parent) {\n parent.cancel();\n }\n else {\n _reject(new CancellationError());\n }\n\n return me;\n };\n\n /**\n * Set a timeout for the promise. If the promise is not resolved within\n * the time, the promise will be cancelled and a TimeoutError is thrown.\n * If the promise is resolved in time, the timeout is removed.\n * @param {number} delay Delay in milliseconds\n * @returns {this} self\n */\n this.timeout = function (delay) {\n if (parent) {\n parent.timeout(delay);\n }\n else {\n var timer = setTimeout(function () {\n _reject(new TimeoutError('Promise timed out after ' + delay + ' ms'));\n }, delay);\n\n me.always(function () {\n clearTimeout(timer);\n });\n }\n\n return me;\n };\n\n // attach handler passing the resolve and reject functions\n handler(function (result) {\n _resolve(result);\n }, function (error) {\n _reject(error);\n });\n}\n\n/**\n * Execute given callback, then call resolve/reject based on the returned result\n * @param {Function} callback\n * @param {Function} resolve\n * @param {Function} reject\n * @returns {Function}\n * @private\n */\nfunction _then(callback, resolve, reject) {\n return function (result) {\n try {\n var res = callback(result);\n if (res && typeof res.then === 'function' && typeof res['catch'] === 'function') {\n // method returned a promise\n res.then(resolve, reject);\n }\n else {\n resolve(res);\n }\n }\n catch (error) {\n reject(error);\n }\n }\n}\n\n/**\n * Add an onFail callback to the Promise\n * @template TT\n * @param {(error: E) => TT | PromiseLike} onFail\n * @returns {Promise} promise\n */\nPromise.prototype['catch'] = function (onFail) {\n return this.then(null, onFail);\n};\n\n// TODO: add support for Promise.catch(Error, callback)\n// TODO: add support for Promise.catch(Error, Error, callback)\n\n/**\n * Execute given callback when the promise either resolves or rejects.\n * @template TT\n * @param {() => Promise} fn\n * @returns {Promise} promise\n */\nPromise.prototype.always = function (fn) {\n return this.then(fn, fn);\n};\n\n/**\n * Create a promise which resolves when all provided promises are resolved,\n * and fails when any of the promises resolves.\n * @param {Promise[]} promises\n * @returns {Promise} promise\n */\nPromise.all = function (promises){\n return new Promise(function (resolve, reject) {\n var remaining = promises.length,\n results = [];\n\n if (remaining) {\n promises.forEach(function (p, i) {\n p.then(function (result) {\n results[i] = result;\n remaining--;\n if (remaining == 0) {\n resolve(results);\n }\n }, function (error) {\n remaining = 0;\n reject(error);\n });\n });\n }\n else {\n resolve(results);\n }\n });\n};\n\n/**\n * Create a promise resolver\n * @returns {{promise: Promise, resolve: Function, reject: Function}} resolver\n */\nPromise.defer = function () {\n var resolver = {};\n\n resolver.promise = new Promise(function (resolve, reject) {\n resolver.resolve = resolve;\n resolver.reject = reject;\n });\n\n return resolver;\n};\n\n/**\n * Create a cancellation error\n * @param {String} [message]\n * @extends Error\n */\nfunction CancellationError(message) {\n this.message = message || 'promise cancelled';\n this.stack = (new Error()).stack;\n}\n\nCancellationError.prototype = new Error();\nCancellationError.prototype.constructor = Error;\nCancellationError.prototype.name = 'CancellationError';\n\nPromise.CancellationError = CancellationError;\n\n\n/**\n * Create a timeout error\n * @param {String} [message]\n * @extends Error\n */\nfunction TimeoutError(message) {\n this.message = message || 'timeout exceeded';\n this.stack = (new Error()).stack;\n}\n\nTimeoutError.prototype = new Error();\nTimeoutError.prototype.constructor = Error;\nTimeoutError.prototype.name = 'TimeoutError';\n\nPromise.TimeoutError = TimeoutError;\n\n\nexports.Promise = Promise;\n","/**\n * Validate that the object only contains known option names\n * - Throws an error when unknown options are detected\n * - Throws an error when some of the allowed options are attached\n * @param {Object | undefined} options\n * @param {string[]} allowedOptionNames\n * @param {string} objectName\n * @retrun {Object} Returns the original options\n */\nexports.validateOptions = function validateOptions(options, allowedOptionNames, objectName) {\n if (!options) {\n return\n }\n\n var optionNames = options ? Object.keys(options) : []\n\n // check for unknown properties\n var unknownOptionName = optionNames.find(optionName => !allowedOptionNames.includes(optionName))\n if (unknownOptionName) {\n throw new Error('Object \"' + objectName + '\" contains an unknown option \"' + unknownOptionName + '\"')\n }\n\n // check for inherited properties which are not present on the object itself\n var illegalOptionName = allowedOptionNames.find(allowedOptionName => {\n return Object.prototype[allowedOptionName] && !optionNames.includes(allowedOptionName)\n })\n if (illegalOptionName) {\n throw new Error('Object \"' + objectName + '\" contains an inherited option \"' + illegalOptionName + '\" which is ' +\n 'not defined in the object itself but in its prototype. Only plain objects are allowed. ' +\n 'Please remove the option from the prototype or override it with a value \"undefined\".')\n }\n\n return options\n}\n\n// source: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker\nexports.workerOptsNames = [\n 'credentials', 'name', 'type' ]\n\n// source: https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options\nexports.forkOptsNames = [\n 'cwd', 'detached', 'env', 'execPath', 'execArgv', 'gid', 'serialization',\n 'signal', 'killSignal', 'silent', 'stdio', 'uid', 'windowsVerbatimArguments',\n 'timeout'\n]\n\n// source: https://nodejs.org/api/worker_threads.html#new-workerfilename-options\nexports.workerThreadOptsNames = [\n 'argv', 'env', 'eval', 'execArgv', 'stdin', 'stdout', 'stderr', 'workerData',\n 'trackUnmanagedFds', 'transferList', 'resourceLimits', 'name'\n]\n","'use strict';\n\nvar {Promise} = require('./Promise');\nvar environment = require('./environment');\nconst {validateOptions, forkOptsNames, workerThreadOptsNames, workerOptsNames} = require(\"./validateOptions\");\n\n/**\n * Special message sent by parent which causes a child process worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\nfunction ensureWorkerThreads() {\n var WorkerThreads = tryRequireWorkerThreads()\n if (!WorkerThreads) {\n throw new Error('WorkerPool: workerType = \\'thread\\' is not supported, Node >= 11.7.0 required')\n }\n\n return WorkerThreads;\n}\n\n// check whether Worker is supported by the browser\nfunction ensureWebWorker() {\n // Workaround for a bug in PhantomJS (Or QtWebkit): https://github.com/ariya/phantomjs/issues/14534\n if (typeof Worker !== 'function' && (typeof Worker !== 'object' || typeof Worker.prototype.constructor !== 'function')) {\n throw new Error('WorkerPool: Web Workers not supported');\n }\n}\n\nfunction tryRequireWorkerThreads() {\n try {\n return require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads available (old version of node.js)\n return null;\n } else {\n throw error;\n }\n }\n}\n\n// get the default worker script\nfunction getDefaultWorker() {\n if (environment.platform === 'browser') {\n // test whether the browser supports all features that we need\n if (typeof Blob === 'undefined') {\n throw new Error('Blob not supported by the browser');\n }\n if (!window.URL || typeof window.URL.createObjectURL !== 'function') {\n throw new Error('URL.createObjectURL not supported by the browser');\n }\n\n // use embedded worker.js\n var blob = new Blob([require('./generated/embeddedWorker')], {type: 'text/javascript'});\n return window.URL.createObjectURL(blob);\n }\n else {\n // use external worker.js in current directory\n return __dirname + '/worker.js';\n }\n}\n\nfunction setupWorker(script, options) {\n if (options.workerType === 'web') { // browser only\n ensureWebWorker();\n return setupBrowserWorker(script, options.workerOpts, Worker);\n } else if (options.workerType === 'thread') { // node.js only\n WorkerThreads = ensureWorkerThreads();\n return setupWorkerThreadWorker(script, WorkerThreads, options);\n } else if (options.workerType === 'process' || !options.workerType) { // node.js only\n return setupProcessWorker(script, resolveForkOptions(options), require('child_process'));\n } else { // options.workerType === 'auto' or undefined\n if (environment.platform === 'browser') {\n ensureWebWorker();\n return setupBrowserWorker(script, options.workerOpts, Worker);\n }\n else { // environment.platform === 'node'\n var WorkerThreads = tryRequireWorkerThreads();\n if (WorkerThreads) {\n return setupWorkerThreadWorker(script, WorkerThreads, options);\n } else {\n return setupProcessWorker(script, resolveForkOptions(options), require('child_process'));\n }\n }\n }\n}\n\nfunction setupBrowserWorker(script, workerOpts, Worker) {\n // validate the options right before creating the worker (not when creating the pool)\n validateOptions(workerOpts, workerOptsNames, 'workerOpts')\n\n // create the web worker\n var worker = new Worker(script, workerOpts);\n\n worker.isBrowserWorker = true;\n // add node.js API to the web worker\n worker.on = function (event, callback) {\n this.addEventListener(event, function (message) {\n callback(message.data);\n });\n };\n worker.send = function (message, transfer) {\n this.postMessage(message, transfer);\n };\n return worker;\n}\n\nfunction setupWorkerThreadWorker(script, WorkerThreads, options) {\n // validate the options right before creating the worker thread (not when creating the pool)\n validateOptions(options?.workerThreadOpts, workerThreadOptsNames, 'workerThreadOpts')\n\n var worker = new WorkerThreads.Worker(script, {\n stdout: options?.emitStdStreams ?? false, // pipe worker.STDOUT to process.STDOUT if not requested\n stderr: options?.emitStdStreams ?? false, // pipe worker.STDERR to process.STDERR if not requested\n ...options?.workerThreadOpts\n });\n worker.isWorkerThread = true;\n worker.send = function(message, transfer) {\n this.postMessage(message, transfer);\n };\n\n worker.kill = function() {\n this.terminate();\n return true;\n };\n\n worker.disconnect = function() {\n this.terminate();\n };\n\n if (options?.emitStdStreams) {\n worker.stdout.on('data', (data) => worker.emit(\"stdout\", data))\n worker.stderr.on('data', (data) => worker.emit(\"stderr\", data))\n }\n\n return worker;\n}\n\nfunction setupProcessWorker(script, options, child_process) {\n // validate the options right before creating the child process (not when creating the pool)\n validateOptions(options.forkOpts, forkOptsNames, 'forkOpts')\n\n // no WorkerThreads, fallback to sub-process based workers\n var worker = child_process.fork(\n script,\n options.forkArgs,\n options.forkOpts\n );\n\n // ignore transfer argument since it is not supported by process\n var send = worker.send;\n worker.send = function (message) {\n return send.call(worker, message);\n };\n\n if (options.emitStdStreams) {\n worker.stdout.on('data', (data) => worker.emit(\"stdout\", data))\n worker.stderr.on('data', (data) => worker.emit(\"stderr\", data))\n }\n\n worker.isChildProcess = true;\n return worker;\n}\n\n// add debug flags to child processes if the node inspector is active\nfunction resolveForkOptions(opts) {\n opts = opts || {};\n\n var processExecArgv = process.execArgv.join(' ');\n var inspectorActive = processExecArgv.indexOf('--inspect') !== -1;\n var debugBrk = processExecArgv.indexOf('--debug-brk') !== -1;\n\n var execArgv = [];\n if (inspectorActive) {\n execArgv.push('--inspect=' + opts.debugPort);\n\n if (debugBrk) {\n execArgv.push('--debug-brk');\n }\n }\n\n process.execArgv.forEach(function(arg) {\n if (arg.indexOf('--max-old-space-size') > -1) {\n execArgv.push(arg)\n }\n })\n\n return Object.assign({}, opts, {\n forkArgs: opts.forkArgs,\n forkOpts: Object.assign({}, opts.forkOpts, {\n execArgv: (opts.forkOpts && opts.forkOpts.execArgv || [])\n .concat(execArgv),\n stdio: opts.emitStdStreams ? \"pipe\": undefined\n })\n });\n}\n\n/**\n * Converts a serialized error to Error\n * @param {Object} obj Error that has been serialized and parsed to object\n * @return {Error} The equivalent Error.\n */\nfunction objectToError (obj) {\n var temp = new Error('')\n var props = Object.keys(obj)\n\n for (var i = 0; i < props.length; i++) {\n temp[props[i]] = obj[props[i]]\n }\n\n return temp\n}\n\nfunction handleEmittedStdPayload(handler, payload) {\n // TODO: refactor if parallel task execution gets added\n if (Object.keys(handler.processing).length !== 1) {\n return;\n }\n var task = Object.values(handler.processing)[0]\n if (task.options && typeof task.options.on === 'function') {\n task.options.on(payload);\n }\n}\n\n/**\n * A WorkerHandler controls a single worker. This worker can be a child process\n * on node.js or a WebWorker in a browser environment.\n * @param {String} [script] If no script is provided, a default worker with a\n * function run will be created.\n * @param {import('./types.js').WorkerPoolOptions} [_options] See docs\n * @constructor\n */\nfunction WorkerHandler(script, _options) {\n var me = this;\n var options = _options || {};\n\n this.script = script || getDefaultWorker();\n this.worker = setupWorker(this.script, options);\n this.debugPort = options.debugPort;\n this.forkOpts = options.forkOpts;\n this.forkArgs = options.forkArgs;\n this.workerOpts = options.workerOpts;\n this.workerThreadOpts = options.workerThreadOpts\n this.workerTerminateTimeout = options.workerTerminateTimeout;\n\n // The ready message is only sent if the worker.add method is called (And the default script is not used)\n if (!script) {\n this.worker.ready = true;\n }\n\n // queue for requests that are received before the worker is ready\n this.requestQueue = [];\n\n this.worker.on(\"stdout\", function (data) {\n handleEmittedStdPayload(me, {\"stdout\": data.toString()})\n })\n this.worker.on(\"stderr\", function (data) {\n handleEmittedStdPayload(me, {\"stderr\": data.toString()})\n })\n\n this.worker.on('message', function (response) {\n if (me.terminated) {\n return;\n }\n if (typeof response === 'string' && response === 'ready') {\n me.worker.ready = true;\n dispatchQueuedRequests();\n } else {\n // find the task from the processing queue, and run the tasks callback\n var id = response.id;\n var task = me.processing[id];\n if (task !== undefined) {\n if (response.isEvent) {\n if (task.options && typeof task.options.on === 'function') {\n task.options.on(response.payload);\n }\n } else {\n // remove the task from the queue\n delete me.processing[id];\n\n // test if we need to terminate\n if (me.terminating === true) {\n // complete worker termination if all tasks are finished\n me.terminate();\n }\n\n // resolve the task's promise\n if (response.error) {\n task.resolver.reject(objectToError(response.error));\n }\n else {\n task.resolver.resolve(response.result);\n }\n }\n }\n }\n });\n\n // reject all running tasks on worker error\n function onError(error) {\n me.terminated = true;\n\n for (var id in me.processing) {\n if (me.processing[id] !== undefined) {\n me.processing[id].resolver.reject(error);\n }\n }\n me.processing = Object.create(null);\n }\n\n // send all queued requests to worker\n function dispatchQueuedRequests()\n {\n for(const request of me.requestQueue.splice(0)) {\n me.worker.send(request.message, request.transfer);\n }\n }\n\n var worker = this.worker;\n // listen for worker messages error and exit\n this.worker.on('error', onError);\n this.worker.on('exit', function (exitCode, signalCode) {\n var message = 'Workerpool Worker terminated Unexpectedly\\n';\n\n message += ' exitCode: `' + exitCode + '`\\n';\n message += ' signalCode: `' + signalCode + '`\\n';\n\n message += ' workerpool.script: `' + me.script + '`\\n';\n message += ' spawnArgs: `' + worker.spawnargs + '`\\n';\n message += ' spawnfile: `' + worker.spawnfile + '`\\n'\n\n message += ' stdout: `' + worker.stdout + '`\\n'\n message += ' stderr: `' + worker.stderr + '`\\n'\n\n onError(new Error(message));\n });\n\n this.processing = Object.create(null); // queue with tasks currently in progress\n\n this.terminating = false;\n this.terminated = false;\n this.cleaning = false;\n this.terminationHandler = null;\n this.lastId = 0;\n}\n\n/**\n * Get a list with methods available on the worker.\n * @return {Promise.} methods\n */\nWorkerHandler.prototype.methods = function () {\n return this.exec('methods');\n};\n\n/**\n * Execute a method with given parameters on the worker\n * @param {String} method\n * @param {Array} [params]\n * @param {{resolve: Function, reject: Function}} [resolver]\n * @param {import('./types.js').ExecOptions} [options]\n * @return {Promise.<*, Error>} result\n */\nWorkerHandler.prototype.exec = function(method, params, resolver, options) {\n if (!resolver) {\n resolver = Promise.defer();\n }\n\n // generate a unique id for the task\n var id = ++this.lastId;\n\n // register a new task as being in progress\n this.processing[id] = {\n id: id,\n resolver: resolver,\n options: options\n };\n\n // build a JSON-RPC request\n var request = {\n message: {\n id: id,\n method: method,\n params: params\n },\n transfer: options && options.transfer\n };\n\n if (this.terminated) {\n resolver.reject(new Error('Worker is terminated'));\n } else if (this.worker.ready) {\n // send the request to the worker\n this.worker.send(request.message, request.transfer);\n } else {\n this.requestQueue.push(request);\n }\n\n // on cancellation, force the worker to terminate\n var me = this;\n return resolver.promise.catch(function (error) {\n if (error instanceof Promise.CancellationError || error instanceof Promise.TimeoutError) {\n // remove this task from the queue. It is already rejected (hence this\n // catch event), and else it will be rejected again when terminating\n delete me.processing[id];\n\n // terminate worker\n return me.terminateAndNotify(true)\n .then(function() {\n throw error;\n }, function(err) {\n throw err;\n });\n } else {\n throw error;\n }\n })\n};\n\n/**\n * Test whether the worker is processing any tasks or cleaning up before termination.\n * @return {boolean} Returns true if the worker is busy\n */\nWorkerHandler.prototype.busy = function () {\n return this.cleaning || Object.keys(this.processing).length > 0;\n};\n\n/**\n * Terminate the worker.\n * @param {boolean} [force=false] If false (default), the worker is terminated\n * after finishing all tasks currently in\n * progress. If true, the worker will be\n * terminated immediately.\n * @param {function} [callback=null] If provided, will be called when process terminates.\n */\nWorkerHandler.prototype.terminate = function (force, callback) {\n var me = this;\n if (force) {\n // cancel all tasks in progress\n for (var id in this.processing) {\n if (this.processing[id] !== undefined) {\n this.processing[id].resolver.reject(new Error('Worker terminated'));\n }\n }\n this.processing = Object.create(null);\n }\n\n if (typeof callback === 'function') {\n this.terminationHandler = callback;\n }\n if (!this.busy()) {\n // all tasks are finished. kill the worker\n var cleanup = function(err) {\n me.terminated = true;\n me.cleaning = false;\n if (me.worker != null && me.worker.removeAllListeners) {\n // removeAllListeners is only available for child_process\n me.worker.removeAllListeners('message');\n }\n me.worker = null;\n me.terminating = false;\n if (me.terminationHandler) {\n me.terminationHandler(err, me);\n } else if (err) {\n throw err;\n }\n }\n\n if (this.worker) {\n if (typeof this.worker.kill === 'function') {\n if (this.worker.killed) {\n cleanup(new Error('worker already killed!'));\n return;\n }\n\n // child process and worker threads\n var cleanExitTimeout = setTimeout(function() {\n if (me.worker) {\n me.worker.kill();\n }\n }, this.workerTerminateTimeout);\n\n this.worker.once('exit', function() {\n clearTimeout(cleanExitTimeout);\n if (me.worker) {\n me.worker.killed = true;\n }\n cleanup();\n });\n\n if (this.worker.ready) {\n this.worker.send(TERMINATE_METHOD_ID);\n } else {\n this.requestQueue.push({ message: TERMINATE_METHOD_ID });\n }\n\n // mark that the worker is cleaning up resources\n // to prevent new tasks from being executed\n this.cleaning = true;\n return;\n }\n else if (typeof this.worker.terminate === 'function') {\n this.worker.terminate(); // web worker\n this.worker.killed = true;\n }\n else {\n throw new Error('Failed to terminate worker');\n }\n }\n cleanup();\n }\n else {\n // we can't terminate immediately, there are still tasks being executed\n this.terminating = true;\n }\n};\n\n/**\n * Terminate the worker, returning a Promise that resolves when the termination has been done.\n * @param {boolean} [force=false] If false (default), the worker is terminated\n * after finishing all tasks currently in\n * progress. If true, the worker will be\n * terminated immediately.\n * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected\n * after timeout if worker process has not been terminated.\n * @return {Promise.}\n */\nWorkerHandler.prototype.terminateAndNotify = function (force, timeout) {\n var resolver = Promise.defer();\n if (timeout) {\n resolver.promise.timeout(timeout);\n }\n this.terminate(force, function(err, worker) {\n if (err) {\n resolver.reject(err);\n } else {\n resolver.resolve(worker);\n }\n });\n return resolver.promise;\n};\n\nmodule.exports = WorkerHandler;\nmodule.exports._tryRequireWorkerThreads = tryRequireWorkerThreads;\nmodule.exports._setupProcessWorker = setupProcessWorker;\nmodule.exports._setupBrowserWorker = setupBrowserWorker;\nmodule.exports._setupWorkerThreadWorker = setupWorkerThreadWorker;\nmodule.exports.ensureWorkerThreads = ensureWorkerThreads;\n","/**\n * embeddedWorker.js contains an embedded version of worker.js.\n * This file is automatically generated,\n * changes made in this file will be overwritten.\n */\nmodule.exports = \"!function(e,n){\\\"object\\\"==typeof exports&&\\\"undefined\\\"!=typeof module?module.exports=n():\\\"function\\\"==typeof define&&define.amd?define(n):(e=\\\"undefined\\\"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){\\\"use strict\\\";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\\\"default\\\")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if(\\\"undefined\\\"!=typeof self&&\\\"function\\\"==typeof postMessage&&\\\"function\\\"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if(\\\"undefined\\\"==typeof process)throw new Error(\\\"Script must be executed as a worker\\\");var o;try{o=require(\\\"worker_threads\\\")}catch(e){if(\\\"object\\\"!=typeof e||null===e||\\\"MODULE_NOT_FOUND\\\"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on(\\\"disconnect\\\",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&\\\"function\\\"==typeof e.then&&\\\"function\\\"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function(\\\"return (\\\"+e+\\\").apply(null, arguments);\\\");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on(\\\"message\\\",(function(e){if(\\\"__workerpool-terminate__\\\"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error('Unknown method \\\"'+e.method+'\\\"');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send(\\\"ready\\\")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)}));\\n//# sourceMappingURL=worker.min.js.map\\n\";\n","var {Promise} = require('./Promise');\nvar WorkerHandler = require('./WorkerHandler');\nvar environment = require('./environment');\nvar DebugPortAllocator = require('./debug-port-allocator');\nvar DEBUG_PORT_ALLOCATOR = new DebugPortAllocator();\n/**\n * A pool to manage workers, which can be created using the function workerpool.pool.\n *\n * @param {String} [script] Optional worker script\n * @param {import('./types.js').WorkerPoolOptions} [options] See docs\n * @constructor\n */\nfunction Pool(script, options) {\n if (typeof script === 'string') {\n /** @readonly */\n this.script = script || null;\n }\n else {\n this.script = null;\n options = script;\n }\n\n /** @private */\n this.workers = []; // queue with all workers\n /** @private */\n this.tasks = []; // queue with tasks awaiting execution\n\n options = options || {};\n\n /** @readonly */\n this.forkArgs = Object.freeze(options.forkArgs || []);\n /** @readonly */\n this.forkOpts = Object.freeze(options.forkOpts || {});\n /** @readonly */\n this.workerOpts = Object.freeze(options.workerOpts || {});\n /** @readonly */\n this.workerThreadOpts = Object.freeze(options.workerThreadOpts || {})\n /** @private */\n this.debugPortStart = (options.debugPortStart || 43210);\n /** @readonly @deprecated */\n this.nodeWorker = options.nodeWorker;\n /** @readonly\n * @type {'auto' | 'web' | 'process' | 'thread'}\n */\n this.workerType = options.workerType || options.nodeWorker || 'auto'\n /** @readonly */\n this.maxQueueSize = options.maxQueueSize || Infinity;\n /** @readonly */\n this.workerTerminateTimeout = options.workerTerminateTimeout || 1000;\n\n /** @readonly */\n this.onCreateWorker = options.onCreateWorker || (() => null);\n /** @readonly */\n this.onTerminateWorker = options.onTerminateWorker || (() => null);\n\n /** @readonly */\n this.emitStdStreams = options.emitStdStreams || false\n\n // configuration\n if (options && 'maxWorkers' in options) {\n validateMaxWorkers(options.maxWorkers);\n /** @readonly */\n this.maxWorkers = options.maxWorkers;\n }\n else {\n this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1);\n }\n\n if (options && 'minWorkers' in options) {\n if(options.minWorkers === 'max') {\n /** @readonly */\n this.minWorkers = this.maxWorkers;\n } else {\n validateMinWorkers(options.minWorkers);\n this.minWorkers = options.minWorkers;\n this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers); // in case minWorkers is higher than maxWorkers\n }\n this._ensureMinWorkers();\n }\n\n /** @private */\n this._boundNext = this._next.bind(this);\n\n\n if (this.workerType === 'thread') {\n WorkerHandler.ensureWorkerThreads();\n }\n}\n\n\n/**\n * Execute a function on a worker.\n *\n * Example usage:\n *\n * var pool = new Pool()\n *\n * // call a function available on the worker\n * pool.exec('fibonacci', [6])\n *\n * // offload a function\n * function add(a, b) {\n * return a + b\n * };\n * pool.exec(add, [2, 4])\n * .then(function (result) {\n * console.log(result); // outputs 6\n * })\n * .catch(function(error) {\n * console.log(error);\n * });\n * @template { (...args: any[]) => any } T\n * @param {String | T} method Function name or function.\n * If `method` is a string, the corresponding\n * method on the worker will be executed\n * If `method` is a Function, the function\n * will be stringified and executed via the\n * workers built-in function `run(fn, args)`.\n * @param {Parameters | null} [params] Function arguments applied when calling the function\n * @param {import('./types.js').ExecOptions} [options] Options\n * @return {Promise>}\n */\nPool.prototype.exec = function (method, params, options) {\n // validate type of arguments\n if (params && !Array.isArray(params)) {\n throw new TypeError('Array expected as argument \"params\"');\n }\n\n if (typeof method === 'string') {\n var resolver = Promise.defer();\n\n if (this.tasks.length >= this.maxQueueSize) {\n throw new Error('Max queue size of ' + this.maxQueueSize + ' reached');\n }\n\n // add a new task to the queue\n var tasks = this.tasks;\n var task = {\n method: method,\n params: params,\n resolver: resolver,\n timeout: null,\n options: options\n };\n tasks.push(task);\n\n // replace the timeout method of the Promise with our own,\n // which starts the timer as soon as the task is actually started\n var originalTimeout = resolver.promise.timeout;\n resolver.promise.timeout = function timeout (delay) {\n if (tasks.indexOf(task) !== -1) {\n // task is still queued -> start the timer later on\n task.timeout = delay;\n return resolver.promise;\n }\n else {\n // task is already being executed -> start timer immediately\n return originalTimeout.call(resolver.promise, delay);\n }\n };\n\n // trigger task execution\n this._next();\n\n return resolver.promise;\n }\n else if (typeof method === 'function') {\n // send stringified function and function arguments to worker\n return this.exec('run', [String(method), params], options);\n }\n else {\n throw new TypeError('Function or string expected as argument \"method\"');\n }\n};\n\n/**\n * Create a proxy for current worker. Returns an object containing all\n * methods available on the worker. All methods return promises resolving the methods result.\n * @template { { [k: string]: (...args: any[]) => any } } T\n * @return {Promise, Error>} Returns a promise which resolves with a proxy object\n */\nPool.prototype.proxy = function () {\n if (arguments.length > 0) {\n throw new Error('No arguments expected');\n }\n\n var pool = this;\n return this.exec('methods')\n .then(function (methods) {\n var proxy = {};\n\n methods.forEach(function (method) {\n proxy[method] = function () {\n return pool.exec(method, Array.prototype.slice.call(arguments));\n }\n });\n\n return proxy;\n });\n};\n\n/**\n * Creates new array with the results of calling a provided callback function\n * on every element in this array.\n * @param {Array} array\n * @param {function} callback Function taking two arguments:\n * `callback(currentValue, index)`\n * @return {Promise.} Returns a promise which resolves with an Array\n * containing the results of the callback function\n * executed for each of the array elements.\n */\n/* TODO: implement map\nPool.prototype.map = function (array, callback) {\n};\n*/\n\n/**\n * Grab the first task from the queue, find a free worker, and assign the\n * worker to the task.\n * @private\n */\nPool.prototype._next = function () {\n if (this.tasks.length > 0) {\n // there are tasks in the queue\n\n // find an available worker\n var worker = this._getWorker();\n if (worker) {\n // get the first task from the queue\n var me = this;\n var task = this.tasks.shift();\n\n // check if the task is still pending (and not cancelled -> promise rejected)\n if (task.resolver.promise.pending) {\n // send the request to the worker\n var promise = worker.exec(task.method, task.params, task.resolver, task.options)\n .then(me._boundNext)\n .catch(function () {\n // if the worker crashed and terminated, remove it from the pool\n if (worker.terminated) {\n return me._removeWorker(worker);\n }\n }).then(function() {\n me._next(); // trigger next task in the queue\n });\n\n // start queued timer now\n if (typeof task.timeout === 'number') {\n promise.timeout(task.timeout);\n }\n } else {\n // The task taken was already complete (either rejected or resolved), so just trigger next task in the queue\n me._next();\n }\n }\n }\n};\n\n/**\n * Get an available worker. If no worker is available and the maximum number\n * of workers isn't yet reached, a new worker will be created and returned.\n * If no worker is available and the maximum number of workers is reached,\n * null will be returned.\n *\n * @return {WorkerHandler | null} worker\n * @private\n */\nPool.prototype._getWorker = function() {\n // find a non-busy worker\n var workers = this.workers;\n for (var i = 0; i < workers.length; i++) {\n var worker = workers[i];\n if (worker.busy() === false) {\n return worker;\n }\n }\n\n if (workers.length < this.maxWorkers) {\n // create a new worker\n worker = this._createWorkerHandler();\n workers.push(worker);\n return worker;\n }\n\n return null;\n};\n\n/**\n * Remove a worker from the pool.\n * Attempts to terminate worker if not already terminated, and ensures the minimum\n * pool size is met.\n * @param {WorkerHandler} worker\n * @return {Promise}\n * @private\n */\nPool.prototype._removeWorker = function(worker) {\n var me = this;\n\n DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort);\n // _removeWorker will call this, but we need it to be removed synchronously\n this._removeWorkerFromList(worker);\n // If minWorkers set, spin up new workers to replace the crashed ones\n this._ensureMinWorkers();\n // terminate the worker (if not already terminated)\n return new Promise(function(resolve, reject) {\n worker.terminate(false, function(err) {\n me.onTerminateWorker({\n forkArgs: worker.forkArgs,\n forkOpts: worker.forkOpts,\n workerThreadOpts: worker.workerThreadOpts,\n script: worker.script\n });\n if (err) {\n reject(err);\n } else {\n resolve(worker);\n }\n });\n });\n};\n\n/**\n * Remove a worker from the pool list.\n * @param {WorkerHandler} worker\n * @private\n */\nPool.prototype._removeWorkerFromList = function(worker) {\n // remove from the list with workers\n var index = this.workers.indexOf(worker);\n if (index !== -1) {\n this.workers.splice(index, 1);\n }\n};\n\n/**\n * Close all active workers. Tasks currently being executed will be finished first.\n * @param {boolean} [force=false] If false (default), the workers are terminated\n * after finishing all tasks currently in\n * progress. If true, the workers will be\n * terminated immediately.\n * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected\n * after timeout if worker process has not been terminated.\n * @return {Promise.}\n */\nPool.prototype.terminate = function (force, timeout) {\n var me = this;\n\n // cancel any pending tasks\n this.tasks.forEach(function (task) {\n task.resolver.reject(new Error('Pool terminated'));\n });\n this.tasks.length = 0;\n\n var f = function (worker) {\n DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort);\n this._removeWorkerFromList(worker);\n };\n var removeWorker = f.bind(this);\n\n var promises = [];\n var workers = this.workers.slice();\n workers.forEach(function (worker) {\n var termPromise = worker.terminateAndNotify(force, timeout)\n .then(removeWorker)\n .always(function() {\n me.onTerminateWorker({\n forkArgs: worker.forkArgs,\n forkOpts: worker.forkOpts,\n workerThreadOpts: worker.workerThreadOpts,\n script: worker.script\n });\n });\n promises.push(termPromise);\n });\n return Promise.all(promises);\n};\n\n/**\n * Retrieve statistics on tasks and workers.\n * @return {{totalWorkers: number, busyWorkers: number, idleWorkers: number, pendingTasks: number, activeTasks: number}} Returns an object with statistics\n */\nPool.prototype.stats = function () {\n var totalWorkers = this.workers.length;\n var busyWorkers = this.workers.filter(function (worker) {\n return worker.busy();\n }).length;\n\n return {\n totalWorkers: totalWorkers,\n busyWorkers: busyWorkers,\n idleWorkers: totalWorkers - busyWorkers,\n\n pendingTasks: this.tasks.length,\n activeTasks: busyWorkers\n };\n};\n\n/**\n * Ensures that a minimum of minWorkers is up and running\n * @private\n */\nPool.prototype._ensureMinWorkers = function() {\n if (this.minWorkers) {\n for(var i = this.workers.length; i < this.minWorkers; i++) {\n this.workers.push(this._createWorkerHandler());\n }\n }\n};\n\n/**\n * Helper function to create a new WorkerHandler and pass all options.\n * @return {WorkerHandler}\n * @private\n */\nPool.prototype._createWorkerHandler = function () {\n const overriddenParams = this.onCreateWorker({\n forkArgs: this.forkArgs,\n forkOpts: this.forkOpts,\n workerOpts: this.workerOpts,\n workerThreadOpts: this.workerThreadOpts,\n script: this.script\n }) || {};\n\n return new WorkerHandler(overriddenParams.script || this.script, {\n forkArgs: overriddenParams.forkArgs || this.forkArgs,\n forkOpts: overriddenParams.forkOpts || this.forkOpts,\n workerOpts: overriddenParams.workerOpts || this.workerOpts,\n workerThreadOpts: overriddenParams.workerThreadOpts || this.workerThreadOpts,\n debugPort: DEBUG_PORT_ALLOCATOR.nextAvailableStartingAt(this.debugPortStart),\n workerType: this.workerType,\n workerTerminateTimeout: this.workerTerminateTimeout,\n emitStdStreams: this.emitStdStreams,\n });\n}\n\n/**\n * Ensure that the maxWorkers option is an integer >= 1\n * @param {*} maxWorkers\n * @returns {boolean} returns true maxWorkers has a valid value\n */\nfunction validateMaxWorkers(maxWorkers) {\n if (!isNumber(maxWorkers) || !isInteger(maxWorkers) || maxWorkers < 1) {\n throw new TypeError('Option maxWorkers must be an integer number >= 1');\n }\n}\n\n/**\n * Ensure that the minWorkers option is an integer >= 0\n * @param {*} minWorkers\n * @returns {boolean} returns true when minWorkers has a valid value\n */\nfunction validateMinWorkers(minWorkers) {\n if (!isNumber(minWorkers) || !isInteger(minWorkers) || minWorkers < 0) {\n throw new TypeError('Option minWorkers must be an integer number >= 0');\n }\n}\n\n/**\n * Test whether a variable is a number\n * @param {*} value\n * @returns {boolean} returns true when value is a number\n */\nfunction isNumber(value) {\n return typeof value === 'number';\n}\n\n/**\n * Test whether a number is an integer\n * @param {number} value\n * @returns {boolean} Returns true if value is an integer\n */\nfunction isInteger(value) {\n return Math.round(value) == value;\n}\n\nmodule.exports = Pool;\n","'use strict';\n\nvar MAX_PORTS = 65535;\nmodule.exports = DebugPortAllocator;\nfunction DebugPortAllocator() {\n this.ports = Object.create(null);\n this.length = 0;\n}\n\nDebugPortAllocator.prototype.nextAvailableStartingAt = function(starting) {\n while (this.ports[starting] === true) {\n starting++;\n }\n\n if (starting >= MAX_PORTS) {\n throw new Error('WorkerPool debug port limit reached: ' + starting + '>= ' + MAX_PORTS );\n }\n\n this.ports[starting] = true;\n this.length++;\n return starting;\n};\n\nDebugPortAllocator.prototype.releasePort = function(port) {\n delete this.ports[port];\n this.length--;\n};\n\n","/**\n * The helper class for transferring data from the worker to the main thread.\n *\n * @param {Object} message The object to deliver to the main thread.\n * @param {Object[]} transfer An array of transferable Objects to transfer ownership of.\n */\nfunction Transfer(message, transfer) {\n this.message = message;\n this.transfer = transfer;\n}\n\nmodule.exports = Transfer;\n","/**\n * worker must be started as a child process or a web worker.\n * It listens for RPC messages from the parent process.\n */\nvar Transfer = require('./transfer');\n\n/**\n * Special message sent by parent which causes the worker to terminate itself.\n * Not a \"message object\"; this string is the entire message.\n */\nvar TERMINATE_METHOD_ID = '__workerpool-terminate__';\n\n// var nodeOSPlatform = require('./environment').nodeOSPlatform;\n\n// create a worker API for sending and receiving messages which works both on\n// node.js and in the browser\nvar worker = {\n exit: function() {}\n};\nif (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') {\n // worker in the browser\n worker.on = function (event, callback) {\n addEventListener(event, function (message) {\n callback(message.data);\n })\n };\n worker.send = function (message) {\n postMessage(message);\n };\n}\nelse if (typeof process !== 'undefined') {\n // node.js\n\n var WorkerThreads;\n try {\n WorkerThreads = require('worker_threads');\n } catch(error) {\n if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') {\n // no worker_threads, fallback to sub-process based workers\n } else {\n throw error;\n }\n }\n\n if (WorkerThreads &&\n /* if there is a parentPort, we are in a WorkerThread */\n WorkerThreads.parentPort !== null) {\n var parentPort = WorkerThreads.parentPort;\n worker.send = parentPort.postMessage.bind(parentPort);\n worker.on = parentPort.on.bind(parentPort);\n worker.exit = process.exit.bind(process);\n } else {\n worker.on = process.on.bind(process);\n // ignore transfer argument since it is not supported by process\n worker.send = function (message) {\n process.send(message);\n };\n // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly\n worker.on('disconnect', function () {\n process.exit(1);\n });\n worker.exit = process.exit.bind(process);\n }\n}\nelse {\n throw new Error('Script must be executed as a worker');\n}\n\nfunction convertError(error) {\n return Object.getOwnPropertyNames(error).reduce(function(product, name) {\n return Object.defineProperty(product, name, {\n\tvalue: error[name],\n\tenumerable: true\n });\n }, {});\n}\n\n/**\n * Test whether a value is a Promise via duck typing.\n * @param {*} value\n * @returns {boolean} Returns true when given value is an object\n * having functions `then` and `catch`.\n */\nfunction isPromise(value) {\n return value && (typeof value.then === 'function') && (typeof value.catch === 'function');\n}\n\n// functions available externally\nworker.methods = {};\n\n/**\n * Execute a function with provided arguments\n * @param {String} fn Stringified function\n * @param {Array} [args] Function arguments\n * @returns {*}\n */\nworker.methods.run = function run(fn, args) {\n var f = new Function('return (' + fn + ').apply(null, arguments);');\n return f.apply(f, args);\n};\n\n/**\n * Get a list with methods available on this worker\n * @return {String[]} methods\n */\nworker.methods.methods = function methods() {\n return Object.keys(worker.methods);\n};\n\n/**\n * Custom handler for when the worker is terminated.\n */\nworker.terminationHandler = undefined;\n\n/**\n * Cleanup and exit the worker.\n * @param {Number} code \n * @returns \n */\nworker.cleanupAndExit = function(code) {\n var _exit = function() {\n worker.exit(code);\n }\n\n if(!worker.terminationHandler) {\n return _exit();\n }\n\n var result = worker.terminationHandler(code);\n if (isPromise(result)) {\n result.then(_exit, _exit);\n } else {\n _exit();\n }\n}\n\nvar currentRequestId = null;\n\nworker.on('message', function (request) {\n if (request === TERMINATE_METHOD_ID) {\n return worker.cleanupAndExit(0);\n }\n try {\n var method = worker.methods[request.method];\n\n if (method) {\n currentRequestId = request.id;\n \n // execute the function\n var result = method.apply(method, request.params);\n\n if (isPromise(result)) {\n // promise returned, resolve this and then return\n result\n .then(function (result) {\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n currentRequestId = null;\n })\n .catch(function (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n currentRequestId = null;\n });\n }\n else {\n // immediate result\n if (result instanceof Transfer) {\n worker.send({\n id: request.id,\n result: result.message,\n error: null\n }, result.transfer);\n } else {\n worker.send({\n id: request.id,\n result: result,\n error: null\n });\n }\n\n currentRequestId = null;\n }\n }\n else {\n throw new Error('Unknown method \"' + request.method + '\"');\n }\n }\n catch (err) {\n worker.send({\n id: request.id,\n result: null,\n error: convertError(err)\n });\n }\n});\n\n/**\n * Register methods to the worker\n * @param {Object} [methods]\n * @param {import('./types.js').WorkerRegisterOptions} [options]\n */\nworker.register = function (methods, options) {\n\n if (methods) {\n for (var name in methods) {\n if (methods.hasOwnProperty(name)) {\n worker.methods[name] = methods[name];\n }\n }\n }\n\n if (options) {\n worker.terminationHandler = options.onTerminate;\n }\n\n worker.send('ready');\n};\n\nworker.emit = function (payload) {\n if (currentRequestId) {\n if (payload instanceof Transfer) {\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload: payload.message\n }, payload.transfer);\n return;\n }\n\n worker.send({\n id: currentRequestId,\n isEvent: true,\n payload\n });\n }\n};\n\nif (typeof exports !== 'undefined') {\n exports.add = worker.register;\n exports.emit = worker.emit;\n}\n","const {platform, isMainThread, cpus} = require('./environment');\n\n/** @typedef {import(\"./Pool\")} Pool */\n/** @typedef {import(\"./types.js\").WorkerPoolOptions} WorkerPoolOptions */\n/** @typedef {import(\"./types.js\").WorkerRegisterOptions} WorkerRegisterOptions */\n\n/**\n * @template { { [k: string]: (...args: any[]) => any } } T\n * @typedef {import('./types.js').Proxy} Proxy\n */\n\n/**\n * @overload\n * Create a new worker pool\n * @param {WorkerPoolOptions} [script]\n * @returns {Pool} pool\n */\n/**\n * @overload\n * Create a new worker pool\n * @param {string} [script]\n * @param {WorkerPoolOptions} [options]\n * @returns {Pool} pool\n */\nfunction pool(script, options) {\n var Pool = require('./Pool');\n\n return new Pool(script, options);\n};\nexports.pool = pool;\n\n/**\n * Create a worker and optionally register a set of methods to the worker.\n * @param {{ [k: string]: (...args: any[]) => any }} [methods]\n * @param {WorkerRegisterOptions} [options]\n */\nfunction worker(methods, options) {\n var worker = require('./worker');\n worker.add(methods, options);\n};\nexports.worker = worker;\n\n/**\n * Sends an event to the parent worker pool.\n * @param {any} payload \n */\nfunction workerEmit(payload) {\n var worker = require('./worker');\n worker.emit(payload);\n};\nexports.workerEmit = workerEmit;\n\nconst {Promise} = require('./Promise');\nexports.Promise = Promise;\n\nexports.Transfer = require('./transfer');\n\nexports.platform = platform;\nexports.isMainThread = isMainThread;\nexports.cpus = cpus;\n"],"names":["isNode","nodeProcess","versions","node","module","exports","platform","process","worker_threads","require","isMainThread","connected","Window","cpus","self","navigator","hardwareConcurrency","length","Promise","handler","parent","me","this","SyntaxError","_onSuccess","_onFail","resolved","rejected","pending","_process","onSuccess","onFail","push","then","resolve","reject","s","_then","f","_resolve","result","forEach","fn","_reject","error","cancel","CancellationError","timeout","delay","timer","setTimeout","TimeoutError","always","clearTimeout","callback","res","message","stack","Error","prototype","all","promises","remaining","results","p","i","defer","resolver","promise","constructor","name","_Promise","validateOptions","options","allowedOptionNames","objectName","optionNames","Object","keys","unknownOptionName","find","optionName","includes","illegalOptionName","allowedOptionName","workerOptsNames","forkOptsNames","workerThreadOptsNames","require$$0","environment","require$$1","require$$2","TERMINATE_METHOD_ID","ensureWorkerThreads","WorkerThreads","tryRequireWorkerThreads","ensureWebWorker","Worker","code","setupBrowserWorker","script","workerOpts","worker","isBrowserWorker","on","event","addEventListener","data","send","transfer","postMessage","setupWorkerThreadWorker","workerThreadOpts","stdout","emitStdStreams","stderr","isWorkerThread","kill","terminate","disconnect","emit","setupProcessWorker","child_process","forkOpts","fork","forkArgs","call","isChildProcess","resolveForkOptions","opts","processExecArgv","execArgv","join","inspectorActive","indexOf","debugBrk","debugPort","arg","assign","concat","stdio","undefined","handleEmittedStdPayload","payload","processing","task","values","WorkerHandler","_options","onError","id","terminated","create","Blob","window","URL","createObjectURL","blob","embeddedWorker","type","__dirname","getDefaultWorker","workerType","setupWorker","workerTerminateTimeout","ready","requestQueue","toString","response","request","splice","dispatchQueuedRequests","isEvent","terminating","obj","temp","props","objectToError","exitCode","signalCode","spawnargs","spawnfile","cleaning","terminationHandler","lastId","methods","exec","method","params","catch","terminateAndNotify","err","busy","force","cleanup","removeAllListeners","killed","cleanExitTimeout","once","WorkerHandlerModule","_tryRequireWorkerThreads","_setupProcessWorker","_setupBrowserWorker","_setupWorkerThreadWorker","DEBUG_PORT_ALLOCATOR","DebugPortAllocator","ports","debugPortAllocator","nextAvailableStartingAt","starting","releasePort","port","require$$3","Pool","workers","tasks","freeze","debugPortStart","nodeWorker","maxQueueSize","Infinity","onCreateWorker","onTerminateWorker","maxWorkers","isNumber","isInteger","TypeError","validateMaxWorkers","Math","max","minWorkers","validateMinWorkers","_ensureMinWorkers","_boundNext","_next","bind","value","round","Array","isArray","originalTimeout","String","proxy","arguments","pool","slice","_getWorker","shift","_removeWorker","_createWorkerHandler","_removeWorkerFromList","index","removeWorker","termPromise","stats","totalWorkers","busyWorkers","filter","idleWorkers","pendingTasks","activeTasks","overriddenParams","Pool_1","Transfer","exit","parentPort","convertError","getOwnPropertyNames","reduce","product","defineProperty","enumerable","isPromise","run","args","Function","apply","cleanupAndExit","_exit","currentRequestId","register","hasOwnProperty","onTerminate","add","pool_1","src","worker_1","workerEmit_1","workerEmit","require$$4","platform_1","isMainThread_1","cpus_1"],"mappings":";uRAGA,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ACN6B,KAAKuB,EACd,EAGA,MAAO7H,QAAAA,GAAWkM,IAClB,IAAe7I,EAAAsN,EAAA3Q,QAAGA,EAEFqP,EAAAsB,EAAAtB,SAAG0B,IAEHC,EAAAL,EAAAvR,SAAGA,EACC6R,EAAAN,EAAAnR,aAAGA,EACvB0R,EAAAP,EAAAhR,KAAeA"} \ No newline at end of file diff --git a/node_modules/workerpool/package.json b/node_modules/workerpool/package.json deleted file mode 100644 index 3e33bba8..00000000 --- a/node_modules/workerpool/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "workerpool", - "license": "Apache-2.0", - "version": "9.1.1", - "description": "Offload tasks to a pool of workers on node.js and in the browser", - "homepage": "https://github.com/josdejong/workerpool", - "author": "Jos de Jong (https://github.com/josdejong)", - "repository": { - "type": "git", - "url": "git://github.com/josdejong/workerpool.git" - }, - "keywords": [ - "worker", - "web worker", - "cluster", - "pool", - "isomorphic" - ], - "main": "src/index.js", - "browser": "dist/workerpool.js", - "types": "types/index.d.ts", - "files": [ - "dist", - "src", - "types", - "HISTORY.md", - "LICENSE", - "README.md" - ], - "scripts": { - "build": "rollup -c rollup.config.mjs && npm run build:types", - "build:types": "tsc -p .", - "watch": "rollup -c rollup.config.mjs -w", - "test": "npm run build && mocha test && npm run test:types", - "test:types": "tsc -p test/types", - "test:debug": "npm run build && mocha debug test", - "coverage": "npm run build && c8 mocha && c8 report --reporter=html && echo Coverage report is available at ./coverage/index.html", - "prepublishOnly": "npm run test" - }, - "devDependencies": { - "@types/node": "20.12.5", - "@babel/core": "7.24.4", - "@babel/preset-env": "7.24.4", - "@rollup/plugin-babel": "6.0.4", - "@rollup/plugin-commonjs": "25.0.7", - "@rollup/plugin-json": "6.1.0", - "@rollup/plugin-node-resolve": "15.2.3", - "@rollup/plugin-terser": "0.4.4", - "c8": "9.1.0", - "date-format": "4.0.14", - "fs-extra": "11.2.0", - "find-process": "1.4.7", - "mocha": "10.4.0", - "rollup": "4.14.0", - "typescript": "5.4.4" - } -} diff --git a/node_modules/workerpool/src/Pool.js b/node_modules/workerpool/src/Pool.js deleted file mode 100644 index 3f762b2f..00000000 --- a/node_modules/workerpool/src/Pool.js +++ /dev/null @@ -1,476 +0,0 @@ -var {Promise} = require('./Promise'); -var WorkerHandler = require('./WorkerHandler'); -var environment = require('./environment'); -var DebugPortAllocator = require('./debug-port-allocator'); -var DEBUG_PORT_ALLOCATOR = new DebugPortAllocator(); -/** - * A pool to manage workers, which can be created using the function workerpool.pool. - * - * @param {String} [script] Optional worker script - * @param {import('./types.js').WorkerPoolOptions} [options] See docs - * @constructor - */ -function Pool(script, options) { - if (typeof script === 'string') { - /** @readonly */ - this.script = script || null; - } - else { - this.script = null; - options = script; - } - - /** @private */ - this.workers = []; // queue with all workers - /** @private */ - this.tasks = []; // queue with tasks awaiting execution - - options = options || {}; - - /** @readonly */ - this.forkArgs = Object.freeze(options.forkArgs || []); - /** @readonly */ - this.forkOpts = Object.freeze(options.forkOpts || {}); - /** @readonly */ - this.workerOpts = Object.freeze(options.workerOpts || {}); - /** @readonly */ - this.workerThreadOpts = Object.freeze(options.workerThreadOpts || {}) - /** @private */ - this.debugPortStart = (options.debugPortStart || 43210); - /** @readonly @deprecated */ - this.nodeWorker = options.nodeWorker; - /** @readonly - * @type {'auto' | 'web' | 'process' | 'thread'} - */ - this.workerType = options.workerType || options.nodeWorker || 'auto' - /** @readonly */ - this.maxQueueSize = options.maxQueueSize || Infinity; - /** @readonly */ - this.workerTerminateTimeout = options.workerTerminateTimeout || 1000; - - /** @readonly */ - this.onCreateWorker = options.onCreateWorker || (() => null); - /** @readonly */ - this.onTerminateWorker = options.onTerminateWorker || (() => null); - - /** @readonly */ - this.emitStdStreams = options.emitStdStreams || false - - // configuration - if (options && 'maxWorkers' in options) { - validateMaxWorkers(options.maxWorkers); - /** @readonly */ - this.maxWorkers = options.maxWorkers; - } - else { - this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1); - } - - if (options && 'minWorkers' in options) { - if(options.minWorkers === 'max') { - /** @readonly */ - this.minWorkers = this.maxWorkers; - } else { - validateMinWorkers(options.minWorkers); - this.minWorkers = options.minWorkers; - this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers); // in case minWorkers is higher than maxWorkers - } - this._ensureMinWorkers(); - } - - /** @private */ - this._boundNext = this._next.bind(this); - - - if (this.workerType === 'thread') { - WorkerHandler.ensureWorkerThreads(); - } -} - - -/** - * Execute a function on a worker. - * - * Example usage: - * - * var pool = new Pool() - * - * // call a function available on the worker - * pool.exec('fibonacci', [6]) - * - * // offload a function - * function add(a, b) { - * return a + b - * }; - * pool.exec(add, [2, 4]) - * .then(function (result) { - * console.log(result); // outputs 6 - * }) - * .catch(function(error) { - * console.log(error); - * }); - * @template { (...args: any[]) => any } T - * @param {String | T} method Function name or function. - * If `method` is a string, the corresponding - * method on the worker will be executed - * If `method` is a Function, the function - * will be stringified and executed via the - * workers built-in function `run(fn, args)`. - * @param {Parameters | null} [params] Function arguments applied when calling the function - * @param {import('./types.js').ExecOptions} [options] Options - * @return {Promise>} - */ -Pool.prototype.exec = function (method, params, options) { - // validate type of arguments - if (params && !Array.isArray(params)) { - throw new TypeError('Array expected as argument "params"'); - } - - if (typeof method === 'string') { - var resolver = Promise.defer(); - - if (this.tasks.length >= this.maxQueueSize) { - throw new Error('Max queue size of ' + this.maxQueueSize + ' reached'); - } - - // add a new task to the queue - var tasks = this.tasks; - var task = { - method: method, - params: params, - resolver: resolver, - timeout: null, - options: options - }; - tasks.push(task); - - // replace the timeout method of the Promise with our own, - // which starts the timer as soon as the task is actually started - var originalTimeout = resolver.promise.timeout; - resolver.promise.timeout = function timeout (delay) { - if (tasks.indexOf(task) !== -1) { - // task is still queued -> start the timer later on - task.timeout = delay; - return resolver.promise; - } - else { - // task is already being executed -> start timer immediately - return originalTimeout.call(resolver.promise, delay); - } - }; - - // trigger task execution - this._next(); - - return resolver.promise; - } - else if (typeof method === 'function') { - // send stringified function and function arguments to worker - return this.exec('run', [String(method), params], options); - } - else { - throw new TypeError('Function or string expected as argument "method"'); - } -}; - -/** - * Create a proxy for current worker. Returns an object containing all - * methods available on the worker. All methods return promises resolving the methods result. - * @template { { [k: string]: (...args: any[]) => any } } T - * @return {Promise, Error>} Returns a promise which resolves with a proxy object - */ -Pool.prototype.proxy = function () { - if (arguments.length > 0) { - throw new Error('No arguments expected'); - } - - var pool = this; - return this.exec('methods') - .then(function (methods) { - var proxy = {}; - - methods.forEach(function (method) { - proxy[method] = function () { - return pool.exec(method, Array.prototype.slice.call(arguments)); - } - }); - - return proxy; - }); -}; - -/** - * Creates new array with the results of calling a provided callback function - * on every element in this array. - * @param {Array} array - * @param {function} callback Function taking two arguments: - * `callback(currentValue, index)` - * @return {Promise.} Returns a promise which resolves with an Array - * containing the results of the callback function - * executed for each of the array elements. - */ -/* TODO: implement map -Pool.prototype.map = function (array, callback) { -}; -*/ - -/** - * Grab the first task from the queue, find a free worker, and assign the - * worker to the task. - * @private - */ -Pool.prototype._next = function () { - if (this.tasks.length > 0) { - // there are tasks in the queue - - // find an available worker - var worker = this._getWorker(); - if (worker) { - // get the first task from the queue - var me = this; - var task = this.tasks.shift(); - - // check if the task is still pending (and not cancelled -> promise rejected) - if (task.resolver.promise.pending) { - // send the request to the worker - var promise = worker.exec(task.method, task.params, task.resolver, task.options) - .then(me._boundNext) - .catch(function () { - // if the worker crashed and terminated, remove it from the pool - if (worker.terminated) { - return me._removeWorker(worker); - } - }).then(function() { - me._next(); // trigger next task in the queue - }); - - // start queued timer now - if (typeof task.timeout === 'number') { - promise.timeout(task.timeout); - } - } else { - // The task taken was already complete (either rejected or resolved), so just trigger next task in the queue - me._next(); - } - } - } -}; - -/** - * Get an available worker. If no worker is available and the maximum number - * of workers isn't yet reached, a new worker will be created and returned. - * If no worker is available and the maximum number of workers is reached, - * null will be returned. - * - * @return {WorkerHandler | null} worker - * @private - */ -Pool.prototype._getWorker = function() { - // find a non-busy worker - var workers = this.workers; - for (var i = 0; i < workers.length; i++) { - var worker = workers[i]; - if (worker.busy() === false) { - return worker; - } - } - - if (workers.length < this.maxWorkers) { - // create a new worker - worker = this._createWorkerHandler(); - workers.push(worker); - return worker; - } - - return null; -}; - -/** - * Remove a worker from the pool. - * Attempts to terminate worker if not already terminated, and ensures the minimum - * pool size is met. - * @param {WorkerHandler} worker - * @return {Promise} - * @private - */ -Pool.prototype._removeWorker = function(worker) { - var me = this; - - DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort); - // _removeWorker will call this, but we need it to be removed synchronously - this._removeWorkerFromList(worker); - // If minWorkers set, spin up new workers to replace the crashed ones - this._ensureMinWorkers(); - // terminate the worker (if not already terminated) - return new Promise(function(resolve, reject) { - worker.terminate(false, function(err) { - me.onTerminateWorker({ - forkArgs: worker.forkArgs, - forkOpts: worker.forkOpts, - workerThreadOpts: worker.workerThreadOpts, - script: worker.script - }); - if (err) { - reject(err); - } else { - resolve(worker); - } - }); - }); -}; - -/** - * Remove a worker from the pool list. - * @param {WorkerHandler} worker - * @private - */ -Pool.prototype._removeWorkerFromList = function(worker) { - // remove from the list with workers - var index = this.workers.indexOf(worker); - if (index !== -1) { - this.workers.splice(index, 1); - } -}; - -/** - * Close all active workers. Tasks currently being executed will be finished first. - * @param {boolean} [force=false] If false (default), the workers are terminated - * after finishing all tasks currently in - * progress. If true, the workers will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ -Pool.prototype.terminate = function (force, timeout) { - var me = this; - - // cancel any pending tasks - this.tasks.forEach(function (task) { - task.resolver.reject(new Error('Pool terminated')); - }); - this.tasks.length = 0; - - var f = function (worker) { - DEBUG_PORT_ALLOCATOR.releasePort(worker.debugPort); - this._removeWorkerFromList(worker); - }; - var removeWorker = f.bind(this); - - var promises = []; - var workers = this.workers.slice(); - workers.forEach(function (worker) { - var termPromise = worker.terminateAndNotify(force, timeout) - .then(removeWorker) - .always(function() { - me.onTerminateWorker({ - forkArgs: worker.forkArgs, - forkOpts: worker.forkOpts, - workerThreadOpts: worker.workerThreadOpts, - script: worker.script - }); - }); - promises.push(termPromise); - }); - return Promise.all(promises); -}; - -/** - * Retrieve statistics on tasks and workers. - * @return {{totalWorkers: number, busyWorkers: number, idleWorkers: number, pendingTasks: number, activeTasks: number}} Returns an object with statistics - */ -Pool.prototype.stats = function () { - var totalWorkers = this.workers.length; - var busyWorkers = this.workers.filter(function (worker) { - return worker.busy(); - }).length; - - return { - totalWorkers: totalWorkers, - busyWorkers: busyWorkers, - idleWorkers: totalWorkers - busyWorkers, - - pendingTasks: this.tasks.length, - activeTasks: busyWorkers - }; -}; - -/** - * Ensures that a minimum of minWorkers is up and running - * @private - */ -Pool.prototype._ensureMinWorkers = function() { - if (this.minWorkers) { - for(var i = this.workers.length; i < this.minWorkers; i++) { - this.workers.push(this._createWorkerHandler()); - } - } -}; - -/** - * Helper function to create a new WorkerHandler and pass all options. - * @return {WorkerHandler} - * @private - */ -Pool.prototype._createWorkerHandler = function () { - const overriddenParams = this.onCreateWorker({ - forkArgs: this.forkArgs, - forkOpts: this.forkOpts, - workerOpts: this.workerOpts, - workerThreadOpts: this.workerThreadOpts, - script: this.script - }) || {}; - - return new WorkerHandler(overriddenParams.script || this.script, { - forkArgs: overriddenParams.forkArgs || this.forkArgs, - forkOpts: overriddenParams.forkOpts || this.forkOpts, - workerOpts: overriddenParams.workerOpts || this.workerOpts, - workerThreadOpts: overriddenParams.workerThreadOpts || this.workerThreadOpts, - debugPort: DEBUG_PORT_ALLOCATOR.nextAvailableStartingAt(this.debugPortStart), - workerType: this.workerType, - workerTerminateTimeout: this.workerTerminateTimeout, - emitStdStreams: this.emitStdStreams, - }); -} - -/** - * Ensure that the maxWorkers option is an integer >= 1 - * @param {*} maxWorkers - * @returns {boolean} returns true maxWorkers has a valid value - */ -function validateMaxWorkers(maxWorkers) { - if (!isNumber(maxWorkers) || !isInteger(maxWorkers) || maxWorkers < 1) { - throw new TypeError('Option maxWorkers must be an integer number >= 1'); - } -} - -/** - * Ensure that the minWorkers option is an integer >= 0 - * @param {*} minWorkers - * @returns {boolean} returns true when minWorkers has a valid value - */ -function validateMinWorkers(minWorkers) { - if (!isNumber(minWorkers) || !isInteger(minWorkers) || minWorkers < 0) { - throw new TypeError('Option minWorkers must be an integer number >= 0'); - } -} - -/** - * Test whether a variable is a number - * @param {*} value - * @returns {boolean} returns true when value is a number - */ -function isNumber(value) { - return typeof value === 'number'; -} - -/** - * Test whether a number is an integer - * @param {number} value - * @returns {boolean} Returns true if value is an integer - */ -function isInteger(value) { - return Math.round(value) == value; -} - -module.exports = Pool; diff --git a/node_modules/workerpool/src/Promise.js b/node_modules/workerpool/src/Promise.js deleted file mode 100644 index bbfaabca..00000000 --- a/node_modules/workerpool/src/Promise.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -/** - * Promise - * - * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa - * @template T - * @template [E=Error] - * @param {Function} handler Called as handler(resolve: Function, reject: Function) - * @param {Promise} [parent] Parent promise for propagation of cancel and timeout - */ -function Promise(handler, parent) { - var me = this; - - if (!(this instanceof Promise)) { - throw new SyntaxError('Constructor must be called with the new operator'); - } - - if (typeof handler !== 'function') { - throw new SyntaxError('Function parameter handler(resolve, reject) missing'); - } - - var _onSuccess = []; - var _onFail = []; - - // status - /** - * @readonly - */ - this.resolved = false; - /** - * @readonly - */ - this.rejected = false; - /** - * @readonly - */ - this.pending = true; - - /** - * Process onSuccess and onFail callbacks: add them to the queue. - * Once the promise is resolved, the function _promise is replace. - * @param {Function} onSuccess - * @param {Function} onFail - * @private - */ - var _process = function (onSuccess, onFail) { - _onSuccess.push(onSuccess); - _onFail.push(onFail); - }; - - /** - * Add an onSuccess callback and optionally an onFail callback to the Promise - * @template TT - * @template [TE=never] - * @param {(r: T) => TT | PromiseLike} onSuccess - * @param {(r: E) => TE | PromiseLike} [onFail] - * @returns {Promise} promise - */ - this.then = function (onSuccess, onFail) { - return new Promise(function (resolve, reject) { - var s = onSuccess ? _then(onSuccess, resolve, reject) : resolve; - var f = onFail ? _then(onFail, resolve, reject) : reject; - - _process(s, f); - }, me); - }; - - /** - * Resolve the promise - * @param {*} result - * @type {Function} - */ - var _resolve = function (result) { - // update status - me.resolved = true; - me.rejected = false; - me.pending = false; - - _onSuccess.forEach(function (fn) { - fn(result); - }); - - _process = function (onSuccess, onFail) { - onSuccess(result); - }; - - _resolve = _reject = function () { }; - - return me; - }; - - /** - * Reject the promise - * @param {Error} error - * @type {Function} - */ - var _reject = function (error) { - // update status - me.resolved = false; - me.rejected = true; - me.pending = false; - - _onFail.forEach(function (fn) { - fn(error); - }); - - _process = function (onSuccess, onFail) { - onFail(error); - }; - - _resolve = _reject = function () { } - - return me; - }; - - /** - * Cancel the promise. This will reject the promise with a CancellationError - * @returns {this} self - */ - this.cancel = function () { - if (parent) { - parent.cancel(); - } - else { - _reject(new CancellationError()); - } - - return me; - }; - - /** - * Set a timeout for the promise. If the promise is not resolved within - * the time, the promise will be cancelled and a TimeoutError is thrown. - * If the promise is resolved in time, the timeout is removed. - * @param {number} delay Delay in milliseconds - * @returns {this} self - */ - this.timeout = function (delay) { - if (parent) { - parent.timeout(delay); - } - else { - var timer = setTimeout(function () { - _reject(new TimeoutError('Promise timed out after ' + delay + ' ms')); - }, delay); - - me.always(function () { - clearTimeout(timer); - }); - } - - return me; - }; - - // attach handler passing the resolve and reject functions - handler(function (result) { - _resolve(result); - }, function (error) { - _reject(error); - }); -} - -/** - * Execute given callback, then call resolve/reject based on the returned result - * @param {Function} callback - * @param {Function} resolve - * @param {Function} reject - * @returns {Function} - * @private - */ -function _then(callback, resolve, reject) { - return function (result) { - try { - var res = callback(result); - if (res && typeof res.then === 'function' && typeof res['catch'] === 'function') { - // method returned a promise - res.then(resolve, reject); - } - else { - resolve(res); - } - } - catch (error) { - reject(error); - } - } -} - -/** - * Add an onFail callback to the Promise - * @template TT - * @param {(error: E) => TT | PromiseLike} onFail - * @returns {Promise} promise - */ -Promise.prototype['catch'] = function (onFail) { - return this.then(null, onFail); -}; - -// TODO: add support for Promise.catch(Error, callback) -// TODO: add support for Promise.catch(Error, Error, callback) - -/** - * Execute given callback when the promise either resolves or rejects. - * @template TT - * @param {() => Promise} fn - * @returns {Promise} promise - */ -Promise.prototype.always = function (fn) { - return this.then(fn, fn); -}; - -/** - * Create a promise which resolves when all provided promises are resolved, - * and fails when any of the promises resolves. - * @param {Promise[]} promises - * @returns {Promise} promise - */ -Promise.all = function (promises){ - return new Promise(function (resolve, reject) { - var remaining = promises.length, - results = []; - - if (remaining) { - promises.forEach(function (p, i) { - p.then(function (result) { - results[i] = result; - remaining--; - if (remaining == 0) { - resolve(results); - } - }, function (error) { - remaining = 0; - reject(error); - }); - }); - } - else { - resolve(results); - } - }); -}; - -/** - * Create a promise resolver - * @returns {{promise: Promise, resolve: Function, reject: Function}} resolver - */ -Promise.defer = function () { - var resolver = {}; - - resolver.promise = new Promise(function (resolve, reject) { - resolver.resolve = resolve; - resolver.reject = reject; - }); - - return resolver; -}; - -/** - * Create a cancellation error - * @param {String} [message] - * @extends Error - */ -function CancellationError(message) { - this.message = message || 'promise cancelled'; - this.stack = (new Error()).stack; -} - -CancellationError.prototype = new Error(); -CancellationError.prototype.constructor = Error; -CancellationError.prototype.name = 'CancellationError'; - -Promise.CancellationError = CancellationError; - - -/** - * Create a timeout error - * @param {String} [message] - * @extends Error - */ -function TimeoutError(message) { - this.message = message || 'timeout exceeded'; - this.stack = (new Error()).stack; -} - -TimeoutError.prototype = new Error(); -TimeoutError.prototype.constructor = Error; -TimeoutError.prototype.name = 'TimeoutError'; - -Promise.TimeoutError = TimeoutError; - - -exports.Promise = Promise; diff --git a/node_modules/workerpool/src/WorkerHandler.js b/node_modules/workerpool/src/WorkerHandler.js deleted file mode 100644 index 224c7645..00000000 --- a/node_modules/workerpool/src/WorkerHandler.js +++ /dev/null @@ -1,547 +0,0 @@ -'use strict'; - -var {Promise} = require('./Promise'); -var environment = require('./environment'); -const {validateOptions, forkOptsNames, workerThreadOptsNames, workerOptsNames} = require("./validateOptions"); - -/** - * Special message sent by parent which causes a child process worker to terminate itself. - * Not a "message object"; this string is the entire message. - */ -var TERMINATE_METHOD_ID = '__workerpool-terminate__'; - -function ensureWorkerThreads() { - var WorkerThreads = tryRequireWorkerThreads() - if (!WorkerThreads) { - throw new Error('WorkerPool: workerType = \'thread\' is not supported, Node >= 11.7.0 required') - } - - return WorkerThreads; -} - -// check whether Worker is supported by the browser -function ensureWebWorker() { - // Workaround for a bug in PhantomJS (Or QtWebkit): https://github.com/ariya/phantomjs/issues/14534 - if (typeof Worker !== 'function' && (typeof Worker !== 'object' || typeof Worker.prototype.constructor !== 'function')) { - throw new Error('WorkerPool: Web Workers not supported'); - } -} - -function tryRequireWorkerThreads() { - try { - return require('worker_threads'); - } catch(error) { - if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') { - // no worker_threads available (old version of node.js) - return null; - } else { - throw error; - } - } -} - -// get the default worker script -function getDefaultWorker() { - if (environment.platform === 'browser') { - // test whether the browser supports all features that we need - if (typeof Blob === 'undefined') { - throw new Error('Blob not supported by the browser'); - } - if (!window.URL || typeof window.URL.createObjectURL !== 'function') { - throw new Error('URL.createObjectURL not supported by the browser'); - } - - // use embedded worker.js - var blob = new Blob([require('./generated/embeddedWorker')], {type: 'text/javascript'}); - return window.URL.createObjectURL(blob); - } - else { - // use external worker.js in current directory - return __dirname + '/worker.js'; - } -} - -function setupWorker(script, options) { - if (options.workerType === 'web') { // browser only - ensureWebWorker(); - return setupBrowserWorker(script, options.workerOpts, Worker); - } else if (options.workerType === 'thread') { // node.js only - WorkerThreads = ensureWorkerThreads(); - return setupWorkerThreadWorker(script, WorkerThreads, options); - } else if (options.workerType === 'process' || !options.workerType) { // node.js only - return setupProcessWorker(script, resolveForkOptions(options), require('child_process')); - } else { // options.workerType === 'auto' or undefined - if (environment.platform === 'browser') { - ensureWebWorker(); - return setupBrowserWorker(script, options.workerOpts, Worker); - } - else { // environment.platform === 'node' - var WorkerThreads = tryRequireWorkerThreads(); - if (WorkerThreads) { - return setupWorkerThreadWorker(script, WorkerThreads, options); - } else { - return setupProcessWorker(script, resolveForkOptions(options), require('child_process')); - } - } - } -} - -function setupBrowserWorker(script, workerOpts, Worker) { - // validate the options right before creating the worker (not when creating the pool) - validateOptions(workerOpts, workerOptsNames, 'workerOpts') - - // create the web worker - var worker = new Worker(script, workerOpts); - - worker.isBrowserWorker = true; - // add node.js API to the web worker - worker.on = function (event, callback) { - this.addEventListener(event, function (message) { - callback(message.data); - }); - }; - worker.send = function (message, transfer) { - this.postMessage(message, transfer); - }; - return worker; -} - -function setupWorkerThreadWorker(script, WorkerThreads, options) { - // validate the options right before creating the worker thread (not when creating the pool) - validateOptions(options?.workerThreadOpts, workerThreadOptsNames, 'workerThreadOpts') - - var worker = new WorkerThreads.Worker(script, { - stdout: options?.emitStdStreams ?? false, // pipe worker.STDOUT to process.STDOUT if not requested - stderr: options?.emitStdStreams ?? false, // pipe worker.STDERR to process.STDERR if not requested - ...options?.workerThreadOpts - }); - worker.isWorkerThread = true; - worker.send = function(message, transfer) { - this.postMessage(message, transfer); - }; - - worker.kill = function() { - this.terminate(); - return true; - }; - - worker.disconnect = function() { - this.terminate(); - }; - - if (options?.emitStdStreams) { - worker.stdout.on('data', (data) => worker.emit("stdout", data)) - worker.stderr.on('data', (data) => worker.emit("stderr", data)) - } - - return worker; -} - -function setupProcessWorker(script, options, child_process) { - // validate the options right before creating the child process (not when creating the pool) - validateOptions(options.forkOpts, forkOptsNames, 'forkOpts') - - // no WorkerThreads, fallback to sub-process based workers - var worker = child_process.fork( - script, - options.forkArgs, - options.forkOpts - ); - - // ignore transfer argument since it is not supported by process - var send = worker.send; - worker.send = function (message) { - return send.call(worker, message); - }; - - if (options.emitStdStreams) { - worker.stdout.on('data', (data) => worker.emit("stdout", data)) - worker.stderr.on('data', (data) => worker.emit("stderr", data)) - } - - worker.isChildProcess = true; - return worker; -} - -// add debug flags to child processes if the node inspector is active -function resolveForkOptions(opts) { - opts = opts || {}; - - var processExecArgv = process.execArgv.join(' '); - var inspectorActive = processExecArgv.indexOf('--inspect') !== -1; - var debugBrk = processExecArgv.indexOf('--debug-brk') !== -1; - - var execArgv = []; - if (inspectorActive) { - execArgv.push('--inspect=' + opts.debugPort); - - if (debugBrk) { - execArgv.push('--debug-brk'); - } - } - - process.execArgv.forEach(function(arg) { - if (arg.indexOf('--max-old-space-size') > -1) { - execArgv.push(arg) - } - }) - - return Object.assign({}, opts, { - forkArgs: opts.forkArgs, - forkOpts: Object.assign({}, opts.forkOpts, { - execArgv: (opts.forkOpts && opts.forkOpts.execArgv || []) - .concat(execArgv), - stdio: opts.emitStdStreams ? "pipe": undefined - }) - }); -} - -/** - * Converts a serialized error to Error - * @param {Object} obj Error that has been serialized and parsed to object - * @return {Error} The equivalent Error. - */ -function objectToError (obj) { - var temp = new Error('') - var props = Object.keys(obj) - - for (var i = 0; i < props.length; i++) { - temp[props[i]] = obj[props[i]] - } - - return temp -} - -function handleEmittedStdPayload(handler, payload) { - // TODO: refactor if parallel task execution gets added - if (Object.keys(handler.processing).length !== 1) { - return; - } - var task = Object.values(handler.processing)[0] - if (task.options && typeof task.options.on === 'function') { - task.options.on(payload); - } -} - -/** - * A WorkerHandler controls a single worker. This worker can be a child process - * on node.js or a WebWorker in a browser environment. - * @param {String} [script] If no script is provided, a default worker with a - * function run will be created. - * @param {import('./types.js').WorkerPoolOptions} [_options] See docs - * @constructor - */ -function WorkerHandler(script, _options) { - var me = this; - var options = _options || {}; - - this.script = script || getDefaultWorker(); - this.worker = setupWorker(this.script, options); - this.debugPort = options.debugPort; - this.forkOpts = options.forkOpts; - this.forkArgs = options.forkArgs; - this.workerOpts = options.workerOpts; - this.workerThreadOpts = options.workerThreadOpts - this.workerTerminateTimeout = options.workerTerminateTimeout; - - // The ready message is only sent if the worker.add method is called (And the default script is not used) - if (!script) { - this.worker.ready = true; - } - - // queue for requests that are received before the worker is ready - this.requestQueue = []; - - this.worker.on("stdout", function (data) { - handleEmittedStdPayload(me, {"stdout": data.toString()}) - }) - this.worker.on("stderr", function (data) { - handleEmittedStdPayload(me, {"stderr": data.toString()}) - }) - - this.worker.on('message', function (response) { - if (me.terminated) { - return; - } - if (typeof response === 'string' && response === 'ready') { - me.worker.ready = true; - dispatchQueuedRequests(); - } else { - // find the task from the processing queue, and run the tasks callback - var id = response.id; - var task = me.processing[id]; - if (task !== undefined) { - if (response.isEvent) { - if (task.options && typeof task.options.on === 'function') { - task.options.on(response.payload); - } - } else { - // remove the task from the queue - delete me.processing[id]; - - // test if we need to terminate - if (me.terminating === true) { - // complete worker termination if all tasks are finished - me.terminate(); - } - - // resolve the task's promise - if (response.error) { - task.resolver.reject(objectToError(response.error)); - } - else { - task.resolver.resolve(response.result); - } - } - } - } - }); - - // reject all running tasks on worker error - function onError(error) { - me.terminated = true; - - for (var id in me.processing) { - if (me.processing[id] !== undefined) { - me.processing[id].resolver.reject(error); - } - } - me.processing = Object.create(null); - } - - // send all queued requests to worker - function dispatchQueuedRequests() - { - for(const request of me.requestQueue.splice(0)) { - me.worker.send(request.message, request.transfer); - } - } - - var worker = this.worker; - // listen for worker messages error and exit - this.worker.on('error', onError); - this.worker.on('exit', function (exitCode, signalCode) { - var message = 'Workerpool Worker terminated Unexpectedly\n'; - - message += ' exitCode: `' + exitCode + '`\n'; - message += ' signalCode: `' + signalCode + '`\n'; - - message += ' workerpool.script: `' + me.script + '`\n'; - message += ' spawnArgs: `' + worker.spawnargs + '`\n'; - message += ' spawnfile: `' + worker.spawnfile + '`\n' - - message += ' stdout: `' + worker.stdout + '`\n' - message += ' stderr: `' + worker.stderr + '`\n' - - onError(new Error(message)); - }); - - this.processing = Object.create(null); // queue with tasks currently in progress - - this.terminating = false; - this.terminated = false; - this.cleaning = false; - this.terminationHandler = null; - this.lastId = 0; -} - -/** - * Get a list with methods available on the worker. - * @return {Promise.} methods - */ -WorkerHandler.prototype.methods = function () { - return this.exec('methods'); -}; - -/** - * Execute a method with given parameters on the worker - * @param {String} method - * @param {Array} [params] - * @param {{resolve: Function, reject: Function}} [resolver] - * @param {import('./types.js').ExecOptions} [options] - * @return {Promise.<*, Error>} result - */ -WorkerHandler.prototype.exec = function(method, params, resolver, options) { - if (!resolver) { - resolver = Promise.defer(); - } - - // generate a unique id for the task - var id = ++this.lastId; - - // register a new task as being in progress - this.processing[id] = { - id: id, - resolver: resolver, - options: options - }; - - // build a JSON-RPC request - var request = { - message: { - id: id, - method: method, - params: params - }, - transfer: options && options.transfer - }; - - if (this.terminated) { - resolver.reject(new Error('Worker is terminated')); - } else if (this.worker.ready) { - // send the request to the worker - this.worker.send(request.message, request.transfer); - } else { - this.requestQueue.push(request); - } - - // on cancellation, force the worker to terminate - var me = this; - return resolver.promise.catch(function (error) { - if (error instanceof Promise.CancellationError || error instanceof Promise.TimeoutError) { - // remove this task from the queue. It is already rejected (hence this - // catch event), and else it will be rejected again when terminating - delete me.processing[id]; - - // terminate worker - return me.terminateAndNotify(true) - .then(function() { - throw error; - }, function(err) { - throw err; - }); - } else { - throw error; - } - }) -}; - -/** - * Test whether the worker is processing any tasks or cleaning up before termination. - * @return {boolean} Returns true if the worker is busy - */ -WorkerHandler.prototype.busy = function () { - return this.cleaning || Object.keys(this.processing).length > 0; -}; - -/** - * Terminate the worker. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {function} [callback=null] If provided, will be called when process terminates. - */ -WorkerHandler.prototype.terminate = function (force, callback) { - var me = this; - if (force) { - // cancel all tasks in progress - for (var id in this.processing) { - if (this.processing[id] !== undefined) { - this.processing[id].resolver.reject(new Error('Worker terminated')); - } - } - this.processing = Object.create(null); - } - - if (typeof callback === 'function') { - this.terminationHandler = callback; - } - if (!this.busy()) { - // all tasks are finished. kill the worker - var cleanup = function(err) { - me.terminated = true; - me.cleaning = false; - if (me.worker != null && me.worker.removeAllListeners) { - // removeAllListeners is only available for child_process - me.worker.removeAllListeners('message'); - } - me.worker = null; - me.terminating = false; - if (me.terminationHandler) { - me.terminationHandler(err, me); - } else if (err) { - throw err; - } - } - - if (this.worker) { - if (typeof this.worker.kill === 'function') { - if (this.worker.killed) { - cleanup(new Error('worker already killed!')); - return; - } - - // child process and worker threads - var cleanExitTimeout = setTimeout(function() { - if (me.worker) { - me.worker.kill(); - } - }, this.workerTerminateTimeout); - - this.worker.once('exit', function() { - clearTimeout(cleanExitTimeout); - if (me.worker) { - me.worker.killed = true; - } - cleanup(); - }); - - if (this.worker.ready) { - this.worker.send(TERMINATE_METHOD_ID); - } else { - this.requestQueue.push({ message: TERMINATE_METHOD_ID }); - } - - // mark that the worker is cleaning up resources - // to prevent new tasks from being executed - this.cleaning = true; - return; - } - else if (typeof this.worker.terminate === 'function') { - this.worker.terminate(); // web worker - this.worker.killed = true; - } - else { - throw new Error('Failed to terminate worker'); - } - } - cleanup(); - } - else { - // we can't terminate immediately, there are still tasks being executed - this.terminating = true; - } -}; - -/** - * Terminate the worker, returning a Promise that resolves when the termination has been done. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ -WorkerHandler.prototype.terminateAndNotify = function (force, timeout) { - var resolver = Promise.defer(); - if (timeout) { - resolver.promise.timeout(timeout); - } - this.terminate(force, function(err, worker) { - if (err) { - resolver.reject(err); - } else { - resolver.resolve(worker); - } - }); - return resolver.promise; -}; - -module.exports = WorkerHandler; -module.exports._tryRequireWorkerThreads = tryRequireWorkerThreads; -module.exports._setupProcessWorker = setupProcessWorker; -module.exports._setupBrowserWorker = setupBrowserWorker; -module.exports._setupWorkerThreadWorker = setupWorkerThreadWorker; -module.exports.ensureWorkerThreads = ensureWorkerThreads; diff --git a/node_modules/workerpool/src/debug-port-allocator.js b/node_modules/workerpool/src/debug-port-allocator.js deleted file mode 100644 index 7688883f..00000000 --- a/node_modules/workerpool/src/debug-port-allocator.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var MAX_PORTS = 65535; -module.exports = DebugPortAllocator; -function DebugPortAllocator() { - this.ports = Object.create(null); - this.length = 0; -} - -DebugPortAllocator.prototype.nextAvailableStartingAt = function(starting) { - while (this.ports[starting] === true) { - starting++; - } - - if (starting >= MAX_PORTS) { - throw new Error('WorkerPool debug port limit reached: ' + starting + '>= ' + MAX_PORTS ); - } - - this.ports[starting] = true; - this.length++; - return starting; -}; - -DebugPortAllocator.prototype.releasePort = function(port) { - delete this.ports[port]; - this.length--; -}; - diff --git a/node_modules/workerpool/src/environment.js b/node_modules/workerpool/src/environment.js deleted file mode 100644 index e20797a5..00000000 --- a/node_modules/workerpool/src/environment.js +++ /dev/null @@ -1,30 +0,0 @@ - -// source: https://github.com/flexdinesh/browser-or-node -// source: https://github.com/mozilla/pdf.js/blob/7ea0e40e588864cd938d1836ec61f1928d3877d3/src/shared/util.js#L24 -var isNode = function (nodeProcess) { - return ( - typeof nodeProcess !== 'undefined' && - nodeProcess.versions != null && - nodeProcess.versions.node != null && - nodeProcess + '' === '[object process]' - ); -} -module.exports.isNode = isNode - -// determines the JavaScript platform: browser or node -module.exports.platform = typeof process !== 'undefined' && isNode(process) - ? 'node' - : 'browser'; - -// determines whether the code is running in main thread or not -// note that in node.js we have to check both worker_thread and child_process -var worker_threads = module.exports.platform === 'node' && require('worker_threads'); -module.exports.isMainThread = module.exports.platform === 'node' - ? ((!worker_threads || worker_threads.isMainThread) && !process.connected) - : typeof Window !== 'undefined'; - -// determines the number of cpus available -module.exports.cpus = module.exports.platform === 'browser' - ? self.navigator.hardwareConcurrency - : require('os').cpus().length; - diff --git a/node_modules/workerpool/src/generated/embeddedWorker.js b/node_modules/workerpool/src/generated/embeddedWorker.js deleted file mode 100644 index 84ff6a0e..00000000 --- a/node_modules/workerpool/src/generated/embeddedWorker.js +++ /dev/null @@ -1,6 +0,0 @@ -/** - * embeddedWorker.js contains an embedded version of worker.js. - * This file is automatically generated, - * changes made in this file will be overwritten. - */ -module.exports = "!function(e,n){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=n():\"function\"==typeof define&&define.amd?define(n):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).worker=n()}(this,(function(){\"use strict\";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\"default\")?e.default:e}var n={};var t=function(e,n){this.message=e,this.transfer=n};return function(e){var n=t,r={exit:function(){}};if(\"undefined\"!=typeof self&&\"function\"==typeof postMessage&&\"function\"==typeof addEventListener)r.on=function(e,n){addEventListener(e,(function(e){n(e.data)}))},r.send=function(e){postMessage(e)};else{if(\"undefined\"==typeof process)throw new Error(\"Script must be executed as a worker\");var o;try{o=require(\"worker_threads\")}catch(e){if(\"object\"!=typeof e||null===e||\"MODULE_NOT_FOUND\"!==e.code)throw e}if(o&&null!==o.parentPort){var i=o.parentPort;r.send=i.postMessage.bind(i),r.on=i.on.bind(i),r.exit=process.exit.bind(process)}else r.on=process.on.bind(process),r.send=function(e){process.send(e)},r.on(\"disconnect\",(function(){process.exit(1)})),r.exit=process.exit.bind(process)}function s(e){return Object.getOwnPropertyNames(e).reduce((function(n,t){return Object.defineProperty(n,t,{value:e[t],enumerable:!0})}),{})}function d(e){return e&&\"function\"==typeof e.then&&\"function\"==typeof e.catch}r.methods={},r.methods.run=function(e,n){var t=new Function(\"return (\"+e+\").apply(null, arguments);\");return t.apply(t,n)},r.methods.methods=function(){return Object.keys(r.methods)},r.terminationHandler=void 0,r.cleanupAndExit=function(e){var n=function(){r.exit(e)};if(!r.terminationHandler)return n();var t=r.terminationHandler(e);d(t)?t.then(n,n):n()};var u=null;r.on(\"message\",(function(e){if(\"__workerpool-terminate__\"===e)return r.cleanupAndExit(0);try{var t=r.methods[e.method];if(!t)throw new Error('Unknown method \"'+e.method+'\"');u=e.id;var o=t.apply(t,e.params);d(o)?o.then((function(t){t instanceof n?r.send({id:e.id,result:t.message,error:null},t.transfer):r.send({id:e.id,result:t,error:null}),u=null})).catch((function(n){r.send({id:e.id,result:null,error:s(n)}),u=null})):(o instanceof n?r.send({id:e.id,result:o.message,error:null},o.transfer):r.send({id:e.id,result:o,error:null}),u=null)}catch(n){r.send({id:e.id,result:null,error:s(n)})}})),r.register=function(e,n){if(e)for(var t in e)e.hasOwnProperty(t)&&(r.methods[t]=e[t]);n&&(r.terminationHandler=n.onTerminate),r.send(\"ready\")},r.emit=function(e){if(u){if(e instanceof n)return void r.send({id:u,isEvent:!0,payload:e.message},e.transfer);r.send({id:u,isEvent:!0,payload:e})}},e.add=r.register,e.emit=r.emit}(n),e(n)}));\n//# sourceMappingURL=worker.min.js.map\n"; diff --git a/node_modules/workerpool/src/header.js b/node_modules/workerpool/src/header.js deleted file mode 100644 index 8beef142..00000000 --- a/node_modules/workerpool/src/header.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * workerpool.js - * https://github.com/josdejong/workerpool - * - * Offload tasks to a pool of workers on node.js and in the browser. - * - * @version @@version - * @date @@date - * - * @license - * Copyright (C) 2014-2022 Jos de Jong - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ diff --git a/node_modules/workerpool/src/index.js b/node_modules/workerpool/src/index.js deleted file mode 100644 index c1e1a594..00000000 --- a/node_modules/workerpool/src/index.js +++ /dev/null @@ -1,60 +0,0 @@ -const {platform, isMainThread, cpus} = require('./environment'); - -/** @typedef {import("./Pool")} Pool */ -/** @typedef {import("./types.js").WorkerPoolOptions} WorkerPoolOptions */ -/** @typedef {import("./types.js").WorkerRegisterOptions} WorkerRegisterOptions */ - -/** - * @template { { [k: string]: (...args: any[]) => any } } T - * @typedef {import('./types.js').Proxy} Proxy - */ - -/** - * @overload - * Create a new worker pool - * @param {WorkerPoolOptions} [script] - * @returns {Pool} pool - */ -/** - * @overload - * Create a new worker pool - * @param {string} [script] - * @param {WorkerPoolOptions} [options] - * @returns {Pool} pool - */ -function pool(script, options) { - var Pool = require('./Pool'); - - return new Pool(script, options); -}; -exports.pool = pool; - -/** - * Create a worker and optionally register a set of methods to the worker. - * @param {{ [k: string]: (...args: any[]) => any }} [methods] - * @param {WorkerRegisterOptions} [options] - */ -function worker(methods, options) { - var worker = require('./worker'); - worker.add(methods, options); -}; -exports.worker = worker; - -/** - * Sends an event to the parent worker pool. - * @param {any} payload - */ -function workerEmit(payload) { - var worker = require('./worker'); - worker.emit(payload); -}; -exports.workerEmit = workerEmit; - -const {Promise} = require('./Promise'); -exports.Promise = Promise; - -exports.Transfer = require('./transfer'); - -exports.platform = platform; -exports.isMainThread = isMainThread; -exports.cpus = cpus; diff --git a/node_modules/workerpool/src/requireFoolWebpack.js b/node_modules/workerpool/src/requireFoolWebpack.js deleted file mode 100644 index 15b208ec..00000000 --- a/node_modules/workerpool/src/requireFoolWebpack.js +++ /dev/null @@ -1,8 +0,0 @@ -// source of inspiration: https://github.com/sindresorhus/require-fool-webpack -var requireFoolWebpack = eval( - 'typeof require !== \'undefined\' ' + - '? require ' + - ': function (module) { throw new Error(\'Module " + module + " not found.\') }' -); - -module.exports = requireFoolWebpack; diff --git a/node_modules/workerpool/src/transfer.js b/node_modules/workerpool/src/transfer.js deleted file mode 100644 index 2e51c09c..00000000 --- a/node_modules/workerpool/src/transfer.js +++ /dev/null @@ -1,12 +0,0 @@ -/** - * The helper class for transferring data from the worker to the main thread. - * - * @param {Object} message The object to deliver to the main thread. - * @param {Object[]} transfer An array of transferable Objects to transfer ownership of. - */ -function Transfer(message, transfer) { - this.message = message; - this.transfer = transfer; -} - -module.exports = Transfer; diff --git a/node_modules/workerpool/src/types.js b/node_modules/workerpool/src/types.js deleted file mode 100644 index d07658fc..00000000 --- a/node_modules/workerpool/src/types.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @typedef {Object} WorkerArg - * @property {string[]} [forkArgs] The `forkArgs` option of this pool - * @property {import('child_process').ForkOptions} [forkOpts] The `forkOpts` option of this pool - * @property {WorkerOptions} [workerOpts] The `workerOpts` option of this pool - * @property {import('worker_threads').WorkerOptions} [workerThreadOpts] The `workerThreadOpts` option of this pool - * @property {string} [script] The `script` option of this pool - */ - -/** - * @typedef {Object} WorkerPoolOptions - * @property {number | 'max'} [minWorkers] The minimum number of workers that must be initialized and kept available. Setting this to `'max'` will create `maxWorkers` default workers - * @property {number} [maxWorkers] The default number of maxWorkers is the number of CPU's minus one. When the number of CPU's could not be determined (for example in older browsers), `maxWorkers` is set to 3. - * @property {number} [maxQueueSize] The maximum number of tasks allowed to be queued. Can be used to prevent running out of memory. If the maximum is exceeded, adding a new task will throw an error. The default value is `Infinity`. - * @property {'auto' | 'web' | 'process' | 'thread'} [workerType] - * - In case of `'auto'` (default), workerpool will automatically pick a suitable type of worker: when in a browser environment, `'web'` will be used. When in a node.js environment, `worker_threads` will be used if available (Node.js >= 11.7.0), else `child_process` will be used. - * - In case of `'web'`, a Web Worker will be used. Only available in a browser environment. - * - In case of `'process'`, `child_process` will be used. Only available in a node.js environment. - * - In case of `'thread'`, `worker_threads` will be used. If `worker_threads` are not available, an error is thrown. Only available in a node.js environment. - * @property {number} [workerTerminateTimeout] The timeout in milliseconds to wait for a worker to clean up it's resources on termination before stopping it forcefully. Default value is `1000`. - * @property {string[]} [forkArgs] For `process` worker type. An array passed as `args` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options) - * @property {import('child_process').ForkOptions} [forkOpts] For `process` worker type. An object passed as `options` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options). - * @property {WorkerOptions} [workerOpts] For `web` worker type. An object passed to the [constructor of the web worker](https://html.spec.whatwg.org/multipage/workers.html#dom-worker). See [WorkerOptions specification](https://html.spec.whatwg.org/multipage/workers.html#workeroptions) for available options. - * @property {import('worker_threads').WorkerOptions} [workerThreadOpts] Object`. For `worker` worker type. An object passed to [worker_threads.options](https://nodejs.org/api/worker_threads.html#new-workerfilename-options). - * @property {boolean} [emitStdStreams] Capture stdout and stderr from the worker and emit them via the `stdout` and `stderr` events. Not supported by the `web` worker type. - * @property { (arg: WorkerArg) => WorkerArg | undefined } [onCreateWorker] A callback that is called whenever a worker is being created. It can be used to allocate resources for each worker for example. Optionally, this callback can return an object containing one or more of the `WorkerArg` properties. The provided properties will be used to override the Pool properties for the worker being created. - * @property { (arg: WorkerArg) => void } [onTerminateWorker] A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The callback is passed as argument an object as described for `onCreateWorker`, with each property sets with the value for the worker being terminated. - */ - -/** - * @typedef {Object} ExecOptions - * @property {(payload: any) => unknown} [on] An event listener, to handle events sent by the worker for this execution. - * @property {Object[]} [transfer] A list of transferable objects to send to the worker. Not supported by `process` worker type. See ./examples/transferableObjects.js for usage. - */ - -/** - * @typedef {Object} WorkerRegisterOptions - * @property {(code: number | undefined) => PromiseLike | void} [onTerminate] A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The difference with pool's `onTerminateWorker` is that this callback runs in the worker context, while onTerminateWorker is executed on the main thread. - */ - -/** - * @template { { [k: string]: (...args: any[]) => any } } T - * @typedef {{ [M in keyof T]: (...args: Parameters) => import('./Promise.js').Promise>; }} Proxy - */ - -module.exports = {} diff --git a/node_modules/workerpool/src/validateOptions.js b/node_modules/workerpool/src/validateOptions.js deleted file mode 100644 index 7ec2ed55..00000000 --- a/node_modules/workerpool/src/validateOptions.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Validate that the object only contains known option names - * - Throws an error when unknown options are detected - * - Throws an error when some of the allowed options are attached - * @param {Object | undefined} options - * @param {string[]} allowedOptionNames - * @param {string} objectName - * @retrun {Object} Returns the original options - */ -exports.validateOptions = function validateOptions(options, allowedOptionNames, objectName) { - if (!options) { - return - } - - var optionNames = options ? Object.keys(options) : [] - - // check for unknown properties - var unknownOptionName = optionNames.find(optionName => !allowedOptionNames.includes(optionName)) - if (unknownOptionName) { - throw new Error('Object "' + objectName + '" contains an unknown option "' + unknownOptionName + '"') - } - - // check for inherited properties which are not present on the object itself - var illegalOptionName = allowedOptionNames.find(allowedOptionName => { - return Object.prototype[allowedOptionName] && !optionNames.includes(allowedOptionName) - }) - if (illegalOptionName) { - throw new Error('Object "' + objectName + '" contains an inherited option "' + illegalOptionName + '" which is ' + - 'not defined in the object itself but in its prototype. Only plain objects are allowed. ' + - 'Please remove the option from the prototype or override it with a value "undefined".') - } - - return options -} - -// source: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker -exports.workerOptsNames = [ - 'credentials', 'name', 'type' ] - -// source: https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options -exports.forkOptsNames = [ - 'cwd', 'detached', 'env', 'execPath', 'execArgv', 'gid', 'serialization', - 'signal', 'killSignal', 'silent', 'stdio', 'uid', 'windowsVerbatimArguments', - 'timeout' -] - -// source: https://nodejs.org/api/worker_threads.html#new-workerfilename-options -exports.workerThreadOptsNames = [ - 'argv', 'env', 'eval', 'execArgv', 'stdin', 'stdout', 'stderr', 'workerData', - 'trackUnmanagedFds', 'transferList', 'resourceLimits', 'name' -] diff --git a/node_modules/workerpool/src/worker.js b/node_modules/workerpool/src/worker.js deleted file mode 100644 index f7659216..00000000 --- a/node_modules/workerpool/src/worker.js +++ /dev/null @@ -1,256 +0,0 @@ -/** - * worker must be started as a child process or a web worker. - * It listens for RPC messages from the parent process. - */ -var Transfer = require('./transfer'); - -/** - * Special message sent by parent which causes the worker to terminate itself. - * Not a "message object"; this string is the entire message. - */ -var TERMINATE_METHOD_ID = '__workerpool-terminate__'; - -// var nodeOSPlatform = require('./environment').nodeOSPlatform; - -// create a worker API for sending and receiving messages which works both on -// node.js and in the browser -var worker = { - exit: function() {} -}; -if (typeof self !== 'undefined' && typeof postMessage === 'function' && typeof addEventListener === 'function') { - // worker in the browser - worker.on = function (event, callback) { - addEventListener(event, function (message) { - callback(message.data); - }) - }; - worker.send = function (message) { - postMessage(message); - }; -} -else if (typeof process !== 'undefined') { - // node.js - - var WorkerThreads; - try { - WorkerThreads = require('worker_threads'); - } catch(error) { - if (typeof error === 'object' && error !== null && error.code === 'MODULE_NOT_FOUND') { - // no worker_threads, fallback to sub-process based workers - } else { - throw error; - } - } - - if (WorkerThreads && - /* if there is a parentPort, we are in a WorkerThread */ - WorkerThreads.parentPort !== null) { - var parentPort = WorkerThreads.parentPort; - worker.send = parentPort.postMessage.bind(parentPort); - worker.on = parentPort.on.bind(parentPort); - worker.exit = process.exit.bind(process); - } else { - worker.on = process.on.bind(process); - // ignore transfer argument since it is not supported by process - worker.send = function (message) { - process.send(message); - }; - // register disconnect handler only for subprocess worker to exit when parent is killed unexpectedly - worker.on('disconnect', function () { - process.exit(1); - }); - worker.exit = process.exit.bind(process); - } -} -else { - throw new Error('Script must be executed as a worker'); -} - -function convertError(error) { - return Object.getOwnPropertyNames(error).reduce(function(product, name) { - return Object.defineProperty(product, name, { - value: error[name], - enumerable: true - }); - }, {}); -} - -/** - * Test whether a value is a Promise via duck typing. - * @param {*} value - * @returns {boolean} Returns true when given value is an object - * having functions `then` and `catch`. - */ -function isPromise(value) { - return value && (typeof value.then === 'function') && (typeof value.catch === 'function'); -} - -// functions available externally -worker.methods = {}; - -/** - * Execute a function with provided arguments - * @param {String} fn Stringified function - * @param {Array} [args] Function arguments - * @returns {*} - */ -worker.methods.run = function run(fn, args) { - var f = new Function('return (' + fn + ').apply(null, arguments);'); - return f.apply(f, args); -}; - -/** - * Get a list with methods available on this worker - * @return {String[]} methods - */ -worker.methods.methods = function methods() { - return Object.keys(worker.methods); -}; - -/** - * Custom handler for when the worker is terminated. - */ -worker.terminationHandler = undefined; - -/** - * Cleanup and exit the worker. - * @param {Number} code - * @returns - */ -worker.cleanupAndExit = function(code) { - var _exit = function() { - worker.exit(code); - } - - if(!worker.terminationHandler) { - return _exit(); - } - - var result = worker.terminationHandler(code); - if (isPromise(result)) { - result.then(_exit, _exit); - } else { - _exit(); - } -} - -var currentRequestId = null; - -worker.on('message', function (request) { - if (request === TERMINATE_METHOD_ID) { - return worker.cleanupAndExit(0); - } - try { - var method = worker.methods[request.method]; - - if (method) { - currentRequestId = request.id; - - // execute the function - var result = method.apply(method, request.params); - - if (isPromise(result)) { - // promise returned, resolve this and then return - result - .then(function (result) { - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - currentRequestId = null; - }) - .catch(function (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - currentRequestId = null; - }); - } - else { - // immediate result - if (result instanceof Transfer) { - worker.send({ - id: request.id, - result: result.message, - error: null - }, result.transfer); - } else { - worker.send({ - id: request.id, - result: result, - error: null - }); - } - - currentRequestId = null; - } - } - else { - throw new Error('Unknown method "' + request.method + '"'); - } - } - catch (err) { - worker.send({ - id: request.id, - result: null, - error: convertError(err) - }); - } -}); - -/** - * Register methods to the worker - * @param {Object} [methods] - * @param {import('./types.js').WorkerRegisterOptions} [options] - */ -worker.register = function (methods, options) { - - if (methods) { - for (var name in methods) { - if (methods.hasOwnProperty(name)) { - worker.methods[name] = methods[name]; - } - } - } - - if (options) { - worker.terminationHandler = options.onTerminate; - } - - worker.send('ready'); -}; - -worker.emit = function (payload) { - if (currentRequestId) { - if (payload instanceof Transfer) { - worker.send({ - id: currentRequestId, - isEvent: true, - payload: payload.message - }, payload.transfer); - return; - } - - worker.send({ - id: currentRequestId, - isEvent: true, - payload - }); - } -}; - -if (typeof exports !== 'undefined') { - exports.add = worker.register; - exports.emit = worker.emit; -} diff --git a/node_modules/workerpool/types/Pool.d.ts b/node_modules/workerpool/types/Pool.d.ts deleted file mode 100644 index da7faddc..00000000 --- a/node_modules/workerpool/types/Pool.d.ts +++ /dev/null @@ -1,130 +0,0 @@ -/// -/// -export = Pool; -/** - * A pool to manage workers, which can be created using the function workerpool.pool. - * - * @param {String} [script] Optional worker script - * @param {import('./types.js').WorkerPoolOptions} [options] See docs - * @constructor - */ -declare function Pool(script?: string | undefined, options?: import("./types.js").WorkerPoolOptions | undefined): void; -declare class Pool { - /** - * A pool to manage workers, which can be created using the function workerpool.pool. - * - * @param {String} [script] Optional worker script - * @param {import('./types.js').WorkerPoolOptions} [options] See docs - * @constructor - */ - constructor(script?: string | undefined, options?: import("./types.js").WorkerPoolOptions | undefined); - /** @readonly */ - readonly script: string | null; - /** @private */ - private workers; - /** @private */ - private tasks; - /** @readonly */ - readonly forkArgs: readonly string[]; - /** @readonly */ - readonly forkOpts: Readonly; - /** @readonly */ - readonly workerOpts: Readonly; - /** @readonly */ - readonly workerThreadOpts: Readonly; - /** @private */ - private debugPortStart; - /** @readonly @deprecated */ - readonly nodeWorker: any; - /** @readonly - * @type {'auto' | 'web' | 'process' | 'thread'} - */ - readonly workerType: 'auto' | 'web' | 'process' | 'thread'; - /** @readonly */ - readonly maxQueueSize: number; - /** @readonly */ - readonly workerTerminateTimeout: number; - /** @readonly */ - readonly onCreateWorker: ((arg: import("./types.js").WorkerArg) => import("./types.js").WorkerArg | undefined) | (() => null); - /** @readonly */ - readonly onTerminateWorker: (arg: import("./types.js").WorkerArg) => void; - /** @readonly */ - readonly emitStdStreams: boolean; - /** @readonly */ - readonly maxWorkers: number | undefined; - /** @readonly */ - readonly minWorkers: number | undefined; - /** @private */ - private _boundNext; - /** - * Execute a function on a worker. - * - * Example usage: - * - * var pool = new Pool() - * - * // call a function available on the worker - * pool.exec('fibonacci', [6]) - * - * // offload a function - * function add(a, b) { - * return a + b - * }; - * pool.exec(add, [2, 4]) - * .then(function (result) { - * console.log(result); // outputs 6 - * }) - * .catch(function(error) { - * console.log(error); - * }); - * @template { (...args: any[]) => any } T - * @param {String | T} method Function name or function. - * If `method` is a string, the corresponding - * method on the worker will be executed - * If `method` is a Function, the function - * will be stringified and executed via the - * workers built-in function `run(fn, args)`. - * @param {Parameters | null} [params] Function arguments applied when calling the function - * @param {import('./types.js').ExecOptions} [options] Options - * @return {Promise>} - */ - exec any>(method: string | T, params?: Parameters | null | undefined, options?: import("./types.js").ExecOptions | undefined): Promise, Error>; - /** - * Create a proxy for current worker. Returns an object containing all - * methods available on the worker. All methods return promises resolving the methods result. - * @template { { [k: string]: (...args: any[]) => any } } T - * @return {Promise, Error>} Returns a promise which resolves with a proxy object - */ - proxy any; - }>(...args: any[]): Promise, Error>; - private _next; - private _getWorker; - private _removeWorker; - private _removeWorkerFromList; - /** - * Close all active workers. Tasks currently being executed will be finished first. - * @param {boolean} [force=false] If false (default), the workers are terminated - * after finishing all tasks currently in - * progress. If true, the workers will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ - terminate(force?: boolean | undefined, timeout?: number | undefined): Promise; - /** - * Retrieve statistics on tasks and workers. - * @return {{totalWorkers: number, busyWorkers: number, idleWorkers: number, pendingTasks: number, activeTasks: number}} Returns an object with statistics - */ - stats(): { - totalWorkers: number; - busyWorkers: number; - idleWorkers: number; - pendingTasks: number; - activeTasks: number; - }; - private _ensureMinWorkers; - private _createWorkerHandler; -} -import { Promise } from "./Promise"; diff --git a/node_modules/workerpool/types/Promise.d.ts b/node_modules/workerpool/types/Promise.d.ts deleted file mode 100644 index 6e95670e..00000000 --- a/node_modules/workerpool/types/Promise.d.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Promise - * - * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa - * @template T - * @template [E=Error] - * @param {Function} handler Called as handler(resolve: Function, reject: Function) - * @param {Promise} [parent] Parent promise for propagation of cancel and timeout - */ -export function Promise(handler: Function, parent?: Promise | undefined): void; -export class Promise { - /** - * Promise - * - * Inspired by https://gist.github.com/RubaXa/8501359 from RubaXa - * @template T - * @template [E=Error] - * @param {Function} handler Called as handler(resolve: Function, reject: Function) - * @param {Promise} [parent] Parent promise for propagation of cancel and timeout - */ - constructor(handler: Function, parent?: Promise | undefined); - /** - * @readonly - */ - readonly resolved: boolean; - /** - * @readonly - */ - readonly rejected: boolean; - /** - * @readonly - */ - readonly pending: boolean; - /** - * Add an onSuccess callback and optionally an onFail callback to the Promise - * @template TT - * @template [TE=never] - * @param {(r: T) => TT | PromiseLike} onSuccess - * @param {(r: E) => TE | PromiseLike} [onFail] - * @returns {Promise} promise - */ - then: (onSuccess: (r: T) => TT | PromiseLike, onFail?: ((r: E) => TE | PromiseLike) | undefined) => Promise; - /** - * Cancel the promise. This will reject the promise with a CancellationError - * @returns {this} self - */ - cancel: () => this; - /** - * Set a timeout for the promise. If the promise is not resolved within - * the time, the promise will be cancelled and a TimeoutError is thrown. - * If the promise is resolved in time, the timeout is removed. - * @param {number} delay Delay in milliseconds - * @returns {this} self - */ - timeout: (delay: number) => this; - /** - * Add an onFail callback to the Promise - * @template TT - * @param {(error: E) => TT | PromiseLike} onFail - * @returns {Promise} promise - */ - catch(onFail: (error: E) => TT_1 | PromiseLike): Promise; - /** - * Execute given callback when the promise either resolves or rejects. - * @template TT - * @param {() => Promise} fn - * @returns {Promise} promise - */ - always(fn: () => Promise): Promise; -} -export namespace Promise { - /** - * Create a promise which resolves when all provided promises are resolved, - * and fails when any of the promises resolves. - * @param {Promise[]} promises - * @returns {Promise} promise - */ - export function all(promises: Promise[]): Promise; - /** - * Create a promise resolver - * @returns {{promise: Promise, resolve: Function, reject: Function}} resolver - */ - export function defer(): { - promise: Promise; - resolve: Function; - reject: Function; - }; - export { CancellationError }; - export { TimeoutError }; -} -/** - * Create a cancellation error - * @param {String} [message] - * @extends Error - */ -declare function CancellationError(message?: string | undefined): void; -declare class CancellationError { - /** - * Create a cancellation error - * @param {String} [message] - * @extends Error - */ - constructor(message?: string | undefined); - message: string; - stack: string | undefined; - name: string; -} -/** - * Create a timeout error - * @param {String} [message] - * @extends Error - */ -declare function TimeoutError(message?: string | undefined): void; -declare class TimeoutError { - /** - * Create a timeout error - * @param {String} [message] - * @extends Error - */ - constructor(message?: string | undefined); - message: string; - stack: string | undefined; - name: string; -} -export {}; diff --git a/node_modules/workerpool/types/WorkerHandler.d.ts b/node_modules/workerpool/types/WorkerHandler.d.ts deleted file mode 100644 index a7ba2d68..00000000 --- a/node_modules/workerpool/types/WorkerHandler.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -/// -/// -export = WorkerHandler; -/** - * A WorkerHandler controls a single worker. This worker can be a child process - * on node.js or a WebWorker in a browser environment. - * @param {String} [script] If no script is provided, a default worker with a - * function run will be created. - * @param {import('./types.js').WorkerPoolOptions} [_options] See docs - * @constructor - */ -declare function WorkerHandler(script?: string | undefined, _options?: import("./types.js").WorkerPoolOptions | undefined): void; -declare class WorkerHandler { - /** - * A WorkerHandler controls a single worker. This worker can be a child process - * on node.js or a WebWorker in a browser environment. - * @param {String} [script] If no script is provided, a default worker with a - * function run will be created. - * @param {import('./types.js').WorkerPoolOptions} [_options] See docs - * @constructor - */ - constructor(script?: string | undefined, _options?: import("./types.js").WorkerPoolOptions | undefined); - script: any; - worker: any; - debugPort: any; - forkOpts: import("child_process").ForkOptions | undefined; - forkArgs: string[] | undefined; - workerOpts: WorkerOptions | undefined; - workerThreadOpts: import("worker_threads").WorkerOptions | undefined; - workerTerminateTimeout: number | undefined; - requestQueue: any[]; - processing: any; - terminating: boolean; - terminated: boolean; - cleaning: boolean; - terminationHandler: Function | null; - lastId: number; - /** - * Get a list with methods available on the worker. - * @return {Promise.} methods - */ - methods(): Promise; - /** - * Execute a method with given parameters on the worker - * @param {String} method - * @param {Array} [params] - * @param {{resolve: Function, reject: Function}} [resolver] - * @param {import('./types.js').ExecOptions} [options] - * @return {Promise.<*, Error>} result - */ - exec(method: string, params?: any[] | undefined, resolver?: { - resolve: Function; - reject: Function; - } | undefined, options?: import("./types.js").ExecOptions | undefined): Promise; - /** - * Test whether the worker is processing any tasks or cleaning up before termination. - * @return {boolean} Returns true if the worker is busy - */ - busy(): boolean; - /** - * Terminate the worker. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {function} [callback=null] If provided, will be called when process terminates. - */ - terminate(force?: boolean | undefined, callback?: Function | undefined): void; - /** - * Terminate the worker, returning a Promise that resolves when the termination has been done. - * @param {boolean} [force=false] If false (default), the worker is terminated - * after finishing all tasks currently in - * progress. If true, the worker will be - * terminated immediately. - * @param {number} [timeout] If provided and non-zero, worker termination promise will be rejected - * after timeout if worker process has not been terminated. - * @return {Promise.} - */ - terminateAndNotify(force?: boolean | undefined, timeout?: number | undefined): Promise; -} -declare namespace WorkerHandler { - export { tryRequireWorkerThreads as _tryRequireWorkerThreads, setupProcessWorker as _setupProcessWorker, setupBrowserWorker as _setupBrowserWorker, setupWorkerThreadWorker as _setupWorkerThreadWorker, ensureWorkerThreads }; -} -import { Promise } from "./Promise"; -declare function tryRequireWorkerThreads(): typeof import("worker_threads") | null; -declare function setupProcessWorker(script: any, options: any, child_process: any): any; -declare function setupBrowserWorker(script: any, workerOpts: any, Worker: any): any; -declare function setupWorkerThreadWorker(script: any, WorkerThreads: any, options: any): any; -declare function ensureWorkerThreads(): typeof import("worker_threads"); diff --git a/node_modules/workerpool/types/debug-port-allocator.d.ts b/node_modules/workerpool/types/debug-port-allocator.d.ts deleted file mode 100644 index 562ef065..00000000 --- a/node_modules/workerpool/types/debug-port-allocator.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export = DebugPortAllocator; -declare function DebugPortAllocator(): void; -declare class DebugPortAllocator { - ports: any; - length: number; - nextAvailableStartingAt(starting: any): any; - releasePort(port: any): void; -} diff --git a/node_modules/workerpool/types/environment.d.ts b/node_modules/workerpool/types/environment.d.ts deleted file mode 100644 index ee855603..00000000 --- a/node_modules/workerpool/types/environment.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const platform: "node" | "browser"; -export const isMainThread: boolean; -export const cpus: number; -export function isNode(nodeProcess: any): boolean; diff --git a/node_modules/workerpool/types/generated/embeddedWorker.d.ts b/node_modules/workerpool/types/generated/embeddedWorker.d.ts deleted file mode 100644 index 763ab625..00000000 --- a/node_modules/workerpool/types/generated/embeddedWorker.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: string; -export = _exports; diff --git a/node_modules/workerpool/types/index.d.ts b/node_modules/workerpool/types/index.d.ts deleted file mode 100644 index 26ae3f6f..00000000 --- a/node_modules/workerpool/types/index.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -export const Transfer: typeof import("./transfer"); -export type Pool = import("./Pool"); -export type WorkerPoolOptions = import("./types.js").WorkerPoolOptions; -export type WorkerRegisterOptions = import("./types.js").WorkerRegisterOptions; -/** - * - */ -export type Proxy any; -}> = import('./types.js').Proxy; -/** - * @overload - * Create a new worker pool - * @param {WorkerPoolOptions} [script] - * @returns {Pool} pool - */ -export function pool(script?: import("./types.js").WorkerPoolOptions | undefined): import("./Pool"); -/** - * @overload - * Create a new worker pool - * @param {string} [script] - * @param {WorkerPoolOptions} [options] - * @returns {Pool} pool - */ -export function pool(script?: string | undefined, options?: import("./types.js").WorkerPoolOptions | undefined): import("./Pool"); -/** - * Create a worker and optionally register a set of methods to the worker. - * @param {{ [k: string]: (...args: any[]) => any }} [methods] - * @param {WorkerRegisterOptions} [options] - */ -export function worker(methods?: { - [k: string]: (...args: any[]) => any; -} | undefined, options?: import("./types.js").WorkerRegisterOptions | undefined): void; -/** - * Sends an event to the parent worker pool. - * @param {any} payload - */ -export function workerEmit(payload: any): void; -import { Promise } from "./Promise"; -import { platform } from "./environment"; -import { isMainThread } from "./environment"; -import { cpus } from "./environment"; -export { Promise, platform, isMainThread, cpus }; diff --git a/node_modules/workerpool/types/transfer.d.ts b/node_modules/workerpool/types/transfer.d.ts deleted file mode 100644 index dfbcdec2..00000000 --- a/node_modules/workerpool/types/transfer.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -export = Transfer; -/** - * The helper class for transferring data from the worker to the main thread. - * - * @param {Object} message The object to deliver to the main thread. - * @param {Object[]} transfer An array of transferable Objects to transfer ownership of. - */ -declare function Transfer(message: Object, transfer: Object[]): void; -declare class Transfer { - /** - * The helper class for transferring data from the worker to the main thread. - * - * @param {Object} message The object to deliver to the main thread. - * @param {Object[]} transfer An array of transferable Objects to transfer ownership of. - */ - constructor(message: Object, transfer: Object[]); - message: Object; - transfer: Object[]; -} diff --git a/node_modules/workerpool/types/types.d.ts b/node_modules/workerpool/types/types.d.ts deleted file mode 100644 index 04ca14c1..00000000 --- a/node_modules/workerpool/types/types.d.ts +++ /dev/null @@ -1,99 +0,0 @@ -/// -/// -export type WorkerArg = { - /** - * The `forkArgs` option of this pool - */ - forkArgs?: string[] | undefined; - /** - * The `forkOpts` option of this pool - */ - forkOpts?: import("child_process").ForkOptions | undefined; - /** - * The `workerOpts` option of this pool - */ - workerOpts?: WorkerOptions | undefined; - /** - * The `workerThreadOpts` option of this pool - */ - workerThreadOpts?: import("worker_threads").WorkerOptions | undefined; - /** - * The `script` option of this pool - */ - script?: string | undefined; -}; -export type WorkerPoolOptions = { - /** - * The minimum number of workers that must be initialized and kept available. Setting this to `'max'` will create `maxWorkers` default workers - */ - minWorkers?: number | "max" | undefined; - /** - * The default number of maxWorkers is the number of CPU's minus one. When the number of CPU's could not be determined (for example in older browsers), `maxWorkers` is set to 3. - */ - maxWorkers?: number | undefined; - /** - * The maximum number of tasks allowed to be queued. Can be used to prevent running out of memory. If the maximum is exceeded, adding a new task will throw an error. The default value is `Infinity`. - */ - maxQueueSize?: number | undefined; - /** - * - In case of `'auto'` (default), workerpool will automatically pick a suitable type of worker: when in a browser environment, `'web'` will be used. When in a node.js environment, `worker_threads` will be used if available (Node.js >= 11.7.0), else `child_process` will be used. - * - In case of `'web'`, a Web Worker will be used. Only available in a browser environment. - * - In case of `'process'`, `child_process` will be used. Only available in a node.js environment. - * - In case of `'thread'`, `worker_threads` will be used. If `worker_threads` are not available, an error is thrown. Only available in a node.js environment. - */ - workerType?: "auto" | "web" | "process" | "thread" | undefined; - /** - * The timeout in milliseconds to wait for a worker to clean up it's resources on termination before stopping it forcefully. Default value is `1000`. - */ - workerTerminateTimeout?: number | undefined; - /** - * For `process` worker type. An array passed as `args` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options) - */ - forkArgs?: string[] | undefined; - /** - * For `process` worker type. An object passed as `options` to [child_process.fork](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options). - */ - forkOpts?: import("child_process").ForkOptions | undefined; - /** - * For `web` worker type. An object passed to the [constructor of the web worker](https://html.spec.whatwg.org/multipage/workers.html#dom-worker). See [WorkerOptions specification](https://html.spec.whatwg.org/multipage/workers.html#workeroptions) for available options. - */ - workerOpts?: WorkerOptions | undefined; - /** - * Object`. For `worker` worker type. An object passed to [worker_threads.options](https://nodejs.org/api/worker_threads.html#new-workerfilename-options). - */ - workerThreadOpts?: import("worker_threads").WorkerOptions | undefined; - /** - * Capture stdout and stderr from the worker and emit them via the `stdout` and `stderr` events. Not supported by the `web` worker type. - */ - emitStdStreams?: boolean | undefined; - /** - * A callback that is called whenever a worker is being created. It can be used to allocate resources for each worker for example. Optionally, this callback can return an object containing one or more of the `WorkerArg` properties. The provided properties will be used to override the Pool properties for the worker being created. - */ - onCreateWorker?: ((arg: WorkerArg) => WorkerArg | undefined) | undefined; - /** - * A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The callback is passed as argument an object as described for `onCreateWorker`, with each property sets with the value for the worker being terminated. - */ - onTerminateWorker?: ((arg: WorkerArg) => void) | undefined; -}; -export type ExecOptions = { - /** - * An event listener, to handle events sent by the worker for this execution. - */ - on?: ((payload: any) => unknown) | undefined; - /** - * A list of transferable objects to send to the worker. Not supported by `process` worker type. See ./examples/transferableObjects.js for usage. - */ - transfer?: Object[] | undefined; -}; -export type WorkerRegisterOptions = { - /** - * A callback that is called whenever a worker is being terminated. It can be used to release resources that might have been allocated for this specific worker. The difference with pool's `onTerminateWorker` is that this callback runs in the worker context, while onTerminateWorker is executed on the main thread. - */ - onTerminate?: ((code: number | undefined) => PromiseLike | void) | undefined; -}; -/** - * - */ -export type Proxy any; -}> = { [M in keyof T]: (...args: Parameters) => import("./Promise.js").Promise, Error>; }; diff --git a/node_modules/workerpool/types/validateOptions.d.ts b/node_modules/workerpool/types/validateOptions.d.ts deleted file mode 100644 index 7e4ec451..00000000 --- a/node_modules/workerpool/types/validateOptions.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export function validateOptions(options: Object | undefined, allowedOptionNames: string[], objectName: string): Object | undefined; -export const workerOptsNames: string[]; -export const forkOptsNames: string[]; -export const workerThreadOptsNames: string[]; diff --git a/node_modules/workerpool/types/worker.d.ts b/node_modules/workerpool/types/worker.d.ts deleted file mode 100644 index bc761097..00000000 --- a/node_modules/workerpool/types/worker.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Register methods to the worker - * @param {Object} [methods] - * @param {import('./types.js').WorkerRegisterOptions} [options] - */ -declare function register(methods?: Object | undefined, options?: import("./types.js").WorkerRegisterOptions | undefined): void; -export function emit(payload: any): void; -export { register as add }; diff --git a/package-lock.json b/package-lock.json index e26ed93f..5842df0a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,6 @@ "node-fetch": "^3.3.2", "node-gyp": "^10.1.0", "uuid": "^9.0.1", - "workerpool": "^9.1.1", "xmlbuilder": "^15.1.1" }, "engines": { @@ -1743,11 +1742,6 @@ "string-width": "^1.0.2 || 2 || 3 || 4" } }, - "node_modules/workerpool": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.1.1.tgz", - "integrity": "sha512-EFoFTSEo9m4V4wNrwzVRjxnf/E/oBpOzcI/R5CIugJhl9RsCiq525rszo4AtqcjQQoqFdu2E3H82AnbtpaQHvg==" - }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", diff --git a/package.json b/package.json index e481004b..620273ea 100644 --- a/package.json +++ b/package.json @@ -427,7 +427,6 @@ "node-fetch": "^3.3.2", "node-gyp": "^10.1.0", "uuid": "^9.0.1", - "workerpool": "^9.1.1", "xmlbuilder": "^15.1.1" }, "license": "LGPL-3.0-or-later" diff --git a/support_files/config.js b/support_files/config.js index 63fb6111..925aa8e3 100644 --- a/support_files/config.js +++ b/support_files/config.js @@ -1,8 +1,10 @@ const vscode = require('vscode'); +const fs = require('fs'); const path = require('path'); let config = {}; + function setConfig(newConfig) { config = newConfig; } @@ -20,6 +22,33 @@ function normalizeExcludedFiles(excludedFiles) { } +function getModName() { + const { rootModPath } = getConfig(); + const modsDirPath = path.join(rootModPath, 'Mods'); + + try { + if (!fs.existsSync(modsDirPath)) { + vscode.window.showErrorMessage('Mods directory does not exist.'); + return ''; + } + + const files = fs.readdirSync(modsDirPath); + const directories = files.filter(file => + fs.statSync(path.join(modsDirPath, file)).isDirectory() + ); + + if (directories.length === 1) { + return directories[0]; + } else { + return ''; + } + } catch (error) { + vscode.window.showErrorMessage(`Error reading directories in ${modsDirPath}: ${error}`); + return ''; + } +} + + function getConfig() { const config = vscode.workspace.getConfiguration('bg3ModHelper'); return { @@ -36,4 +65,4 @@ function getConfig() { gameInstallLocation: path.normalize(config.get('gameInstallLocation')) }; } -module.exports = { setConfig, getConfig }; +module.exports = { setConfig, getConfig, getModName }; diff --git a/support_files/conversion_junction.js b/support_files/conversion_junction.js index 0b87e240..d39f4935 100644 --- a/support_files/conversion_junction.js +++ b/support_files/conversion_junction.js @@ -9,9 +9,7 @@ const { lsx, xml, pak } = getFormats(); const { CREATE_LOGGER, raiseError, raiseInfo } = require('./log_utils'); const bg3mh_logger = CREATE_LOGGER(); -const { getConfig } = require('./config.js'); - -const { getModName } = require('./helper_functions.js'); +const { getConfig, getModName } = require('./config.js'); const { isLoca, processLoca, getLocaOutputPath } = require('./loca_convert'); const { isLsf, processLsf, getLsfOutputPath } = require('./lsf_convert'); @@ -43,7 +41,7 @@ function getDynamicPath(filePath) { } -async function convert(convertPath, targetExt = path.extname(getDynamicPath(convertPath)), modName_ = '') { +async function convert(convertPath, targetExt = path.extname(getDynamicPath(convertPath)), modName = getModName()) { const { rootModPath } = getConfig(); console.log('targetExt:' + targetExt); @@ -61,10 +59,10 @@ async function convert(convertPath, targetExt = path.extname(getDynamicPath(conv await convert(rootModPath, lsx) .then(() => raiseInfo(`lsx conversion done`, false)); - processPak(rootModPath, modName_); + processPak(rootModPath, modName); } else if (fs.statSync(convertPath).isFile()) { - processPak(convertPath, modName_, 'n/a'); + processPak(convertPath, modName, 'n/a'); } } else if (Array.isArray(convertPath)) { diff --git a/support_files/helper_functions.js b/support_files/helper_functions.js index 7b2e531c..555c41d0 100644 --- a/support_files/helper_functions.js +++ b/support_files/helper_functions.js @@ -65,30 +65,4 @@ async function findInstancesInWorkspace(word, currentFilePath, maxFilesToShow) { return instances; } -async function getModName() { - const { rootModPath } = getConfig(); - const modsDirPath = path.join(rootModPath, 'Mods'); - - try { - if (!fs.existsSync(modsDirPath)) { - vscode.window.showErrorMessage('Mods directory does not exist.'); - return ''; - } - - const files = fs.readdirSync(modsDirPath); - const directories = files.filter(file => - fs.statSync(path.join(modsDirPath, file)).isDirectory() - ); - - if (directories.length === 1) { - return directories[0]; - } else { - return ''; - } - } catch (error) { - vscode.window.showErrorMessage(`Error reading directories in ${modsDirPath}: ${error}`); - return ''; - } -} - -module.exports = { insertText, findInstancesInWorkspace, getFullPath, getModName }; \ No newline at end of file +module.exports = { insertText, findInstancesInWorkspace, getFullPath }; \ No newline at end of file