@loaders.gl/worker-utils 4.0.0-alpha.9 → 4.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/es5/lib/env-utils/version.js +17 -6
  2. package/dist/es5/lib/env-utils/version.js.map +1 -1
  3. package/dist/es5/lib/library-utils/library-utils.js +106 -43
  4. package/dist/es5/lib/library-utils/library-utils.js.map +1 -1
  5. package/dist/es5/lib/node/require-utils.node.js +78 -11
  6. package/dist/es5/lib/node/require-utils.node.js.map +1 -1
  7. package/dist/es5/lib/worker-api/get-worker-url.js +2 -4
  8. package/dist/es5/lib/worker-api/get-worker-url.js.map +1 -1
  9. package/dist/esm/lib/env-utils/version.js +14 -4
  10. package/dist/esm/lib/env-utils/version.js.map +1 -1
  11. package/dist/esm/lib/library-utils/library-utils.js +30 -16
  12. package/dist/esm/lib/library-utils/library-utils.js.map +1 -1
  13. package/dist/esm/lib/node/require-utils.node.js +17 -0
  14. package/dist/esm/lib/node/require-utils.node.js.map +1 -1
  15. package/dist/esm/lib/worker-api/get-worker-url.js +1 -3
  16. package/dist/esm/lib/worker-api/get-worker-url.js.map +1 -1
  17. package/dist/lib/env-utils/version.d.ts +6 -1
  18. package/dist/lib/env-utils/version.d.ts.map +1 -1
  19. package/dist/lib/library-utils/library-utils.d.ts +2 -2
  20. package/dist/lib/library-utils/library-utils.d.ts.map +1 -1
  21. package/dist/lib/node/require-utils.node.d.ts +12 -0
  22. package/dist/lib/node/require-utils.node.d.ts.map +1 -1
  23. package/dist/lib/worker-api/get-worker-url.d.ts.map +1 -1
  24. package/package.json +4 -5
  25. package/src/lib/env-utils/version.ts +25 -9
  26. package/src/lib/library-utils/library-utils.ts +42 -23
  27. package/src/lib/node/require-utils.node.ts +29 -0
  28. package/src/lib/worker-api/get-worker-url.ts +1 -4
  29. package/dist/index.js +0 -59
  30. package/dist/lib/async-queue/async-queue.js +0 -87
  31. package/dist/lib/env-utils/assert.js +0 -13
  32. package/dist/lib/env-utils/globals.js +0 -32
  33. package/dist/lib/env-utils/version.js +0 -12
  34. package/dist/lib/library-utils/library-utils.js +0 -170
  35. package/dist/lib/node/require-utils.node.js +0 -60
  36. package/dist/lib/node/worker_threads-browser.js +0 -15
  37. package/dist/lib/node/worker_threads.js +0 -33
  38. package/dist/lib/process-utils/child-process-proxy.js +0 -136
  39. package/dist/lib/process-utils/process-utils.js +0 -35
  40. package/dist/lib/worker-api/create-worker.js +0 -91
  41. package/dist/lib/worker-api/get-worker-url.js +0 -59
  42. package/dist/lib/worker-api/process-on-worker.js +0 -83
  43. package/dist/lib/worker-api/validate-worker-version.js +0 -35
  44. package/dist/lib/worker-farm/worker-body.js +0 -111
  45. package/dist/lib/worker-farm/worker-farm.js +0 -89
  46. package/dist/lib/worker-farm/worker-job.js +0 -47
  47. package/dist/lib/worker-farm/worker-pool.js +0 -164
  48. package/dist/lib/worker-farm/worker-thread.js +0 -131
  49. package/dist/lib/worker-utils/get-loadable-worker-url.js +0 -72
  50. package/dist/lib/worker-utils/get-transfer-list.js +0 -87
  51. package/dist/lib/worker-utils/remove-nontransferable-options.js +0 -27
  52. package/dist/types.js +0 -2
  53. package/dist/workers/null-worker.js +0 -7
@@ -1,87 +0,0 @@
1
- "use strict";
2
- // From https://github.com/rauschma/async-iter-demo/tree/master/src under MIT license
3
- // http://2ality.com/2016/10/asynchronous-iteration.html
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- /**
6
- * Async Queue
7
- * - AsyncIterable: An async iterator can be
8
- * - Values can be pushed onto the queue
9
- * @example
10
- * const asyncQueue = new AsyncQueue();
11
- * setTimeout(() => asyncQueue.enqueue('tick'), 1000);
12
- * setTimeout(() => asyncQueue.enqueue(new Error('done')), 10000);
13
- * for await (const value of asyncQueue) {
14
- * console.log(value); // tick
15
- * }
16
- */
17
- class AsyncQueue {
18
- constructor() {
19
- this._values = []; // enqueues > dequeues
20
- this._settlers = []; // dequeues > enqueues
21
- this._closed = false;
22
- }
23
- /** Return an async iterator for this queue */
24
- [Symbol.asyncIterator]() {
25
- return this;
26
- }
27
- /** Push a new value - the async iterator will yield a promise resolved to this value */
28
- push(value) {
29
- return this.enqueue(value);
30
- }
31
- /**
32
- * Push a new value - the async iterator will yield a promise resolved to this value
33
- * Add an error - the async iterator will yield a promise rejected with this value
34
- */
35
- enqueue(value) {
36
- if (this._closed) {
37
- throw new Error('Closed');
38
- }
39
- if (this._settlers.length > 0) {
40
- if (this._values.length > 0) {
41
- throw new Error('Illegal internal state');
42
- }
43
- const settler = this._settlers.shift();
44
- if (value instanceof Error) {
45
- settler.reject(value);
46
- }
47
- else {
48
- settler.resolve({ value });
49
- }
50
- }
51
- else {
52
- this._values.push(value);
53
- }
54
- }
55
- /** Indicate that we not waiting for more values - The async iterator will be done */
56
- close() {
57
- while (this._settlers.length > 0) {
58
- const settler = this._settlers.shift();
59
- settler.resolve({ done: true });
60
- }
61
- this._closed = true;
62
- }
63
- // ITERATOR IMPLEMENTATION
64
- /** @returns a Promise for an IteratorResult */
65
- next() {
66
- // If values in queue, yield the first value
67
- if (this._values.length > 0) {
68
- const value = this._values.shift();
69
- if (value instanceof Error) {
70
- return Promise.reject(value);
71
- }
72
- return Promise.resolve({ done: false, value });
73
- }
74
- // If queue is closed, the iterator is done
75
- if (this._closed) {
76
- if (this._settlers.length > 0) {
77
- throw new Error('Illegal internal state');
78
- }
79
- return Promise.resolve({ done: true, value: undefined });
80
- }
81
- // Yield a promise that waits for new values to be enqueued
82
- return new Promise((resolve, reject) => {
83
- this._settlers.push({ resolve, reject });
84
- });
85
- }
86
- }
87
- exports.default = AsyncQueue;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- // Replacement for the external assert method to reduce bundle size
3
- // Note: We don't use the second "message" argument in calling code,
4
- // so no need to support it here
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.assert = void 0;
7
- /** Throws an `Error` with the optional `message` if `condition` is falsy */
8
- function assert(condition, message) {
9
- if (!condition) {
10
- throw new Error(message || 'loaders.gl assertion failed.');
11
- }
12
- }
13
- exports.assert = assert;
@@ -1,32 +0,0 @@
1
- "use strict";
2
- // Purpose: include this in your module to avoids adding dependencies on
3
- // micro modules like 'global' and 'is-browser';
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.nodeVersion = exports.isMobile = exports.isWorker = exports.isBrowser = exports.document = exports.global = exports.window = exports.self = void 0;
6
- /* eslint-disable no-restricted-globals */
7
- const globals = {
8
- self: typeof self !== 'undefined' && self,
9
- window: typeof window !== 'undefined' && window,
10
- global: typeof global !== 'undefined' && global,
11
- document: typeof document !== 'undefined' && document
12
- };
13
- const self_ = globals.self || globals.window || globals.global || {};
14
- exports.self = self_;
15
- const window_ = globals.window || globals.self || globals.global || {};
16
- exports.window = window_;
17
- const global_ = globals.global || globals.self || globals.window || {};
18
- exports.global = global_;
19
- const document_ = globals.document || {};
20
- exports.document = document_;
21
- /** true if running in the browser, false if running in Node.js */
22
- exports.isBrowser =
23
- // @ts-ignore process.browser
24
- typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
25
- /** true if running on a worker thread */
26
- exports.isWorker = typeof importScripts === 'function';
27
- /** true if running on a mobile device */
28
- exports.isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
29
- // Extract node major version
30
- const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
31
- /** Version of Node.js if running under Node, otherwise 0 */
32
- exports.nodeVersion = (matches && parseFloat(matches[1])) || 0;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- // Version constant cannot be imported, it needs to correspond to the build version of **this** module.
3
- // __VERSION__ is injected by babel-plugin-version-inline
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.VERSION = void 0;
6
- // Change to `latest` on production branches
7
- const DEFAULT_VERSION = 'beta';
8
- exports.VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : DEFAULT_VERSION;
9
- if (typeof __VERSION__ === 'undefined') {
10
- // eslint-disable-next-line
11
- console.error('loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.');
12
- }
@@ -1,170 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getLibraryUrl = exports.loadLibrary = void 0;
27
- /* global importScripts */
28
- const globals_1 = require("../env-utils/globals");
29
- const node = __importStar(require("../node/require-utils.node"));
30
- const assert_1 = require("../env-utils/assert");
31
- const version_1 = require("../env-utils/version");
32
- /**
33
- * TODO - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...
34
- * 'beta' on beta branch, 'latest' on prod branch
35
- */
36
- const LATEST = 'beta';
37
- const VERSION = typeof version_1.VERSION !== 'undefined' ? version_1.VERSION : LATEST;
38
- const loadLibraryPromises = {}; // promises
39
- /**
40
- * Dynamically loads a library ("module")
41
- *
42
- * - wasm library: Array buffer is returned
43
- * - js library: Parse JS is returned
44
- *
45
- * Method depends on environment
46
- * - browser - script element is created and installed on document
47
- * - worker - eval is called on global context
48
- * - node - file is required
49
- *
50
- * @param libraryUrl
51
- * @param moduleName
52
- * @param options
53
- */
54
- async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
55
- if (moduleName) {
56
- libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
57
- }
58
- // Ensure libraries are only loaded once
59
- loadLibraryPromises[libraryUrl] =
60
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
61
- loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
62
- return await loadLibraryPromises[libraryUrl];
63
- }
64
- exports.loadLibrary = loadLibrary;
65
- // TODO - sort out how to resolve paths for main/worker and dev/prod
66
- function getLibraryUrl(library, moduleName, options) {
67
- // Check if already a URL
68
- if (library.startsWith('http')) {
69
- return library;
70
- }
71
- // Allow application to import and supply libraries through `options.modules`
72
- const modules = options.modules || {};
73
- if (modules[library]) {
74
- return modules[library];
75
- }
76
- // Load from local files, not from CDN scripts in Node.js
77
- // TODO - needs to locate the modules directory when installed!
78
- if (!globals_1.isBrowser) {
79
- return `modules/${moduleName}/dist/libs/${library}`;
80
- }
81
- // In browser, load from external scripts
82
- if (options.CDN) {
83
- (0, assert_1.assert)(options.CDN.startsWith('http'));
84
- return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${library}`;
85
- }
86
- // TODO - loading inside workers requires paths relative to worker script location...
87
- if (globals_1.isWorker) {
88
- return `../src/libs/${library}`;
89
- }
90
- return `modules/${moduleName}/src/libs/${library}`;
91
- }
92
- exports.getLibraryUrl = getLibraryUrl;
93
- async function loadLibraryFromFile(libraryUrl) {
94
- if (libraryUrl.endsWith('wasm')) {
95
- const response = await fetch(libraryUrl);
96
- return await response.arrayBuffer();
97
- }
98
- if (!globals_1.isBrowser) {
99
- try {
100
- return node && node.requireFromFile && (await node.requireFromFile(libraryUrl));
101
- }
102
- catch {
103
- return null;
104
- }
105
- }
106
- if (globals_1.isWorker) {
107
- return importScripts(libraryUrl);
108
- }
109
- // TODO - fix - should be more secure than string parsing since observes CORS
110
- // if (isBrowser) {
111
- // return await loadScriptFromFile(libraryUrl);
112
- // }
113
- const response = await fetch(libraryUrl);
114
- const scriptSource = await response.text();
115
- return loadLibraryFromString(scriptSource, libraryUrl);
116
- }
117
- /*
118
- async function loadScriptFromFile(libraryUrl) {
119
- const script = document.createElement('script');
120
- script.src = libraryUrl;
121
- return await new Promise((resolve, reject) => {
122
- script.onload = data => {
123
- resolve(data);
124
- };
125
- script.onerror = reject;
126
- });
127
- }
128
- */
129
- // TODO - Needs security audit...
130
- // - Raw eval call
131
- // - Potentially bypasses CORS
132
- // Upside is that this separates fetching and parsing
133
- // we could create a`LibraryLoader` or`ModuleLoader`
134
- function loadLibraryFromString(scriptSource, id) {
135
- if (!globals_1.isBrowser) {
136
- return node.requireFromString && node.requireFromString(scriptSource, id);
137
- }
138
- if (globals_1.isWorker) {
139
- // Use lvalue trick to make eval run in global scope
140
- eval.call(globals_1.global, scriptSource); // eslint-disable-line no-eval
141
- // https://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript
142
- // http://perfectionkills.com/global-eval-what-are-the-options/
143
- return null;
144
- }
145
- const script = document.createElement('script');
146
- script.id = id;
147
- // most browsers like a separate text node but some throw an error. The second method covers those.
148
- try {
149
- script.appendChild(document.createTextNode(scriptSource));
150
- }
151
- catch (e) {
152
- script.text = scriptSource;
153
- }
154
- document.body.appendChild(script);
155
- return null;
156
- }
157
- // TODO - technique for module injection into worker, from THREE.DracoLoader...
158
- /*
159
- function combineWorkerWithLibrary(worker, jsContent) {
160
- var fn = wWorker.toString();
161
- var body = [
162
- '// injected',
163
- jsContent,
164
- '',
165
- '// worker',
166
- fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))
167
- ].join('\n');
168
- this.workerSourceURL = URL.createObjectURL(new Blob([body]));
169
- }
170
- */
@@ -1,60 +0,0 @@
1
- "use strict";
2
- // Fork of https://github.com/floatdrop/require-from-string/blob/master/index.js
3
- // Copyright (c) Vsevolod Strukchinsky <floatdrop@gmail.com> (github.com/floatdrop)
4
- // MIT license
5
- var __importDefault = (this && this.__importDefault) || function (mod) {
6
- return (mod && mod.__esModule) ? mod : { "default": mod };
7
- };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.requireFromString = exports.requireFromFile = void 0;
10
- // this file is not visible to webpack (it is excluded in the package.json "browser" field).
11
- const module_1 = __importDefault(require("module"));
12
- const path_1 = __importDefault(require("path"));
13
- // Node.js Dynamically require from file
14
- // Relative names are resolved relative to cwd
15
- // This indirect function is provided because webpack will try to bundle `module.require`.
16
- // this file is not visible to webpack (it is excluded in the package.json "browser" field).
17
- async function requireFromFile(filename) {
18
- if (filename.startsWith('http')) {
19
- const response = await fetch(filename);
20
- const code = await response.text();
21
- return requireFromString(code);
22
- }
23
- if (!filename.startsWith('/')) {
24
- filename = `${process.cwd()}/${filename}`;
25
- }
26
- return require(filename);
27
- }
28
- exports.requireFromFile = requireFromFile;
29
- // Dynamically require from string
30
- // - `code` - Required - Type: string - Module code.
31
- // - `filename` - Type: string - Default: '' - Optional filename.
32
- // - `options.appendPaths` Type: Array List of paths, that will be appended to module paths.
33
- // Useful, when you want to be able require modules from these paths.
34
- // - `options.prependPaths` Type: Array Same as appendPaths, but paths will be prepended.
35
- function requireFromString(code, filename = '', options) {
36
- if (typeof filename === 'object') {
37
- options = filename;
38
- filename = '';
39
- }
40
- if (typeof code !== 'string') {
41
- throw new Error(`code must be a string, not ${typeof code}`);
42
- }
43
- // @ts-ignore
44
- const paths = module_1.default._nodeModulePaths(path_1.default.dirname(filename));
45
- const parent = module.parent;
46
- // @ts-ignore
47
- const newModule = new module_1.default(filename, parent);
48
- newModule.filename = filename;
49
- newModule.paths = []
50
- .concat(options?.prependPaths || [])
51
- .concat(paths)
52
- .concat(options?.appendPaths || []);
53
- // @ts-ignore
54
- newModule._compile(code, filename);
55
- if (parent && parent.children) {
56
- parent.children.splice(parent.children.indexOf(newModule), 1);
57
- }
58
- return newModule.exports;
59
- }
60
- exports.requireFromString = requireFromString;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parentPort = exports.NodeWorkerType = exports.NodeWorker = exports.Worker = void 0;
4
- // Browser fills for Node.js built-in `worker_threads` module.
5
- // These fills are non-functional, and just intended to ensure that
6
- // `import 'worker_threads` doesn't break browser builds.
7
- // The replacement is done in package.json browser field
8
- class Worker {
9
- // eslint-disable-next-line @typescript-eslint/no-empty-function
10
- terminate() { }
11
- }
12
- exports.Worker = Worker;
13
- exports.NodeWorker = Worker;
14
- exports.NodeWorkerType = Worker;
15
- exports.parentPort = null;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
26
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
- };
29
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.NodeWorker = void 0;
31
- const WorkerThreads = __importStar(require("worker_threads"));
32
- __exportStar(require("worker_threads"), exports);
33
- exports.NodeWorker = WorkerThreads.Worker;
@@ -1,136 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- /* eslint-disable no-console */
27
- // Avoid using named imports for Node builtins to help with "empty" resolution
28
- // for bundlers targeting browser environments. Access imports & types
29
- // through the `ChildProcess` object (e.g. `ChildProcess.spawn`, `ChildProcess.ChildProcess`).
30
- const ChildProcess = __importStar(require("child_process"));
31
- const process_utils_1 = require("./process-utils");
32
- const DEFAULT_PROPS = {
33
- command: '',
34
- arguments: [],
35
- port: 5000,
36
- autoPort: true,
37
- wait: 2000,
38
- onSuccess: (processProxy) => {
39
- console.log(`Started ${processProxy.props.command}`);
40
- }
41
- };
42
- /**
43
- * Manager for a Node.js child process
44
- * Prepares arguments, starts, stops and tracks output
45
- */
46
- class ChildProcessProxy {
47
- // constructor(props?: {id?: string});
48
- constructor({ id = 'browser-driver' } = {}) {
49
- this.props = { ...DEFAULT_PROPS };
50
- this.childProcess = null;
51
- this.port = 0;
52
- this.id = id;
53
- }
54
- /** Starts a child process with the provided props */
55
- async start(props) {
56
- props = { ...DEFAULT_PROPS, ...props };
57
- this.props = props;
58
- const args = [...props.arguments];
59
- // If portArg is set, we can look up an available port
60
- this.port = Number(props.port);
61
- if (props.portArg) {
62
- if (props.autoPort) {
63
- this.port = await (0, process_utils_1.getAvailablePort)(props.port);
64
- }
65
- args.push(props.portArg, String(this.port));
66
- }
67
- return await new Promise((resolve, reject) => {
68
- try {
69
- this._setTimeout(() => {
70
- if (props.onSuccess) {
71
- props.onSuccess(this);
72
- }
73
- resolve({});
74
- });
75
- console.log(`Spawning ${props.command} ${props.arguments.join(' ')}`);
76
- const childProcess = ChildProcess.spawn(props.command, args, props.spawn);
77
- this.childProcess = childProcess;
78
- childProcess.stdout.on('data', (data) => {
79
- console.log(data.toString());
80
- });
81
- childProcess.stderr.on('data', (data) => {
82
- console.log(`Child process wrote to stderr: "${data}".`);
83
- if (!props.ignoreStderr) {
84
- this._clearTimeout();
85
- reject(new Error(data));
86
- }
87
- });
88
- childProcess.on('error', (error) => {
89
- console.log(`Child process errored with ${error}`);
90
- this._clearTimeout();
91
- reject(error);
92
- });
93
- childProcess.on('close', (code) => {
94
- console.log(`Child process exited with ${code}`);
95
- this.childProcess = null;
96
- this._clearTimeout();
97
- resolve({});
98
- });
99
- }
100
- catch (error) {
101
- reject(error);
102
- }
103
- });
104
- }
105
- /** Stops a running child process */
106
- async stop() {
107
- if (this.childProcess) {
108
- this.childProcess.kill();
109
- this.childProcess = null;
110
- }
111
- }
112
- /** Exits this process */
113
- async exit(statusCode = 0) {
114
- try {
115
- await this.stop();
116
- // eslint-disable-next-line no-process-exit
117
- process.exit(statusCode);
118
- }
119
- catch (error) {
120
- console.error(error.message || error);
121
- // eslint-disable-next-line no-process-exit
122
- process.exit(1);
123
- }
124
- }
125
- _setTimeout(callback) {
126
- if (Number(this.props.wait) > 0) {
127
- this.successTimer = setTimeout(callback, this.props.wait);
128
- }
129
- }
130
- _clearTimeout() {
131
- if (this.successTimer) {
132
- clearTimeout(this.successTimer);
133
- }
134
- }
135
- }
136
- exports.default = ChildProcessProxy;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAvailablePort = void 0;
7
- const child_process_1 = __importDefault(require("child_process"));
8
- // Get an available port
9
- // Works on Unix systems
10
- function getAvailablePort(defaultPort = 3000) {
11
- return new Promise((resolve) => {
12
- // Get a list of all ports in use
13
- child_process_1.default.exec('lsof -i -P -n | grep LISTEN', (error, stdout) => {
14
- if (error) {
15
- // likely no permission, e.g. CI
16
- resolve(defaultPort);
17
- return;
18
- }
19
- const portsInUse = [];
20
- const regex = /:(\d+) \(LISTEN\)/;
21
- stdout.split('\n').forEach((line) => {
22
- const match = regex.exec(line);
23
- if (match) {
24
- portsInUse.push(Number(match[1]));
25
- }
26
- });
27
- let port = defaultPort;
28
- while (portsInUse.includes(port)) {
29
- port++;
30
- }
31
- resolve(port);
32
- });
33
- });
34
- }
35
- exports.getAvailablePort = getAvailablePort;