@loaders.gl/worker-utils 3.4.11 → 3.4.12

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 (32) hide show
  1. package/dist/es5/lib/env-utils/version.js +2 -2
  2. package/dist/es5/lib/library-utils/library-utils.js +1 -1
  3. package/dist/es5/lib/worker-api/get-worker-url.js +1 -1
  4. package/dist/esm/lib/env-utils/version.js +2 -2
  5. package/dist/esm/lib/library-utils/library-utils.js +1 -1
  6. package/dist/esm/lib/worker-api/get-worker-url.js +1 -1
  7. package/package.json +4 -5
  8. package/dist/index.js +0 -59
  9. package/dist/lib/async-queue/async-queue.js +0 -87
  10. package/dist/lib/env-utils/assert.js +0 -13
  11. package/dist/lib/env-utils/globals.js +0 -32
  12. package/dist/lib/env-utils/version.js +0 -12
  13. package/dist/lib/library-utils/library-utils.js +0 -170
  14. package/dist/lib/node/require-utils.node.js +0 -60
  15. package/dist/lib/node/worker_threads-browser.js +0 -15
  16. package/dist/lib/node/worker_threads.js +0 -33
  17. package/dist/lib/process-utils/child-process-proxy.js +0 -136
  18. package/dist/lib/process-utils/process-utils.js +0 -35
  19. package/dist/lib/worker-api/create-worker.js +0 -91
  20. package/dist/lib/worker-api/get-worker-url.js +0 -58
  21. package/dist/lib/worker-api/process-on-worker.js +0 -83
  22. package/dist/lib/worker-api/validate-worker-version.js +0 -35
  23. package/dist/lib/worker-farm/worker-body.js +0 -111
  24. package/dist/lib/worker-farm/worker-farm.js +0 -89
  25. package/dist/lib/worker-farm/worker-job.js +0 -47
  26. package/dist/lib/worker-farm/worker-pool.js +0 -155
  27. package/dist/lib/worker-farm/worker-thread.js +0 -131
  28. package/dist/lib/worker-utils/get-loadable-worker-url.js +0 -72
  29. package/dist/lib/worker-utils/get-transfer-list.js +0 -87
  30. package/dist/lib/worker-utils/remove-nontransferable-options.js +0 -27
  31. package/dist/types.js +0 -2
  32. package/dist/workers/null-worker.js +0 -7
@@ -1,155 +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
- const globals_1 = require("../env-utils/globals");
7
- const worker_thread_1 = __importDefault(require("./worker-thread"));
8
- const worker_job_1 = __importDefault(require("./worker-job"));
9
- /**
10
- * Process multiple data messages with small pool of identical workers
11
- */
12
- class WorkerPool {
13
- /** Checks if workers are supported on this platform */
14
- static isSupported() {
15
- return worker_thread_1.default.isSupported();
16
- }
17
- /**
18
- * @param processor - worker function
19
- * @param maxConcurrency - max count of workers
20
- */
21
- constructor(props) {
22
- this.name = 'unnamed';
23
- this.maxConcurrency = 1;
24
- this.maxMobileConcurrency = 1;
25
- this.onDebug = () => { };
26
- this.reuseWorkers = true;
27
- this.props = {};
28
- this.jobQueue = [];
29
- this.idleQueue = [];
30
- this.count = 0;
31
- this.isDestroyed = false;
32
- this.source = props.source;
33
- this.url = props.url;
34
- this.setProps(props);
35
- }
36
- /**
37
- * Terminates all workers in the pool
38
- * @note Can free up significant memory
39
- */
40
- destroy() {
41
- // Destroy idle workers, active Workers will be destroyed on completion
42
- this.idleQueue.forEach((worker) => worker.destroy());
43
- this.isDestroyed = true;
44
- }
45
- setProps(props) {
46
- this.props = { ...this.props, ...props };
47
- if (props.name !== undefined) {
48
- this.name = props.name;
49
- }
50
- if (props.maxConcurrency !== undefined) {
51
- this.maxConcurrency = props.maxConcurrency;
52
- }
53
- if (props.maxMobileConcurrency !== undefined) {
54
- this.maxMobileConcurrency = props.maxMobileConcurrency;
55
- }
56
- if (props.reuseWorkers !== undefined) {
57
- this.reuseWorkers = props.reuseWorkers;
58
- }
59
- if (props.onDebug !== undefined) {
60
- this.onDebug = props.onDebug;
61
- }
62
- }
63
- async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
64
- // Promise resolves when thread starts working on this job
65
- const startPromise = new Promise((onStart) => {
66
- // Promise resolves when thread completes or fails working on this job
67
- this.jobQueue.push({ name, onMessage, onError, onStart });
68
- return this;
69
- });
70
- this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
71
- return await startPromise;
72
- }
73
- // PRIVATE
74
- /**
75
- * Starts first queued job if worker is available or can be created
76
- * Called when job is started and whenever a worker returns to the idleQueue
77
- */
78
- async _startQueuedJob() {
79
- if (!this.jobQueue.length) {
80
- return;
81
- }
82
- const workerThread = this._getAvailableWorker();
83
- if (!workerThread) {
84
- return;
85
- }
86
- // We have a worker, dequeue and start the job
87
- const queuedJob = this.jobQueue.shift();
88
- if (queuedJob) {
89
- // Emit a debug event
90
- // @ts-ignore
91
- this.onDebug({
92
- message: 'Starting job',
93
- name: queuedJob.name,
94
- workerThread,
95
- backlog: this.jobQueue.length
96
- });
97
- // Create a worker job to let the app access thread and manage job completion
98
- const job = new worker_job_1.default(queuedJob.name, workerThread);
99
- // Set the worker thread's message handlers
100
- workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);
101
- workerThread.onError = (error) => queuedJob.onError(job, error);
102
- // Resolve the start promise so that the app can start sending messages to worker
103
- queuedJob.onStart(job);
104
- // Wait for the app to signal that the job is complete, then return worker to queue
105
- try {
106
- await job.result;
107
- }
108
- finally {
109
- this.returnWorkerToQueue(workerThread);
110
- }
111
- }
112
- }
113
- /**
114
- * Returns a worker to the idle queue
115
- * Destroys the worker if
116
- * - pool is destroyed
117
- * - if this pool doesn't reuse workers
118
- * - if maxConcurrency has been lowered
119
- * @param worker
120
- */
121
- returnWorkerToQueue(worker) {
122
- const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
123
- if (shouldDestroyWorker) {
124
- worker.destroy();
125
- this.count--;
126
- }
127
- else {
128
- this.idleQueue.push(worker);
129
- }
130
- if (!this.isDestroyed) {
131
- this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
132
- }
133
- }
134
- /**
135
- * Returns idle worker or creates new worker if maxConcurrency has not been reached
136
- */
137
- _getAvailableWorker() {
138
- // If a worker has completed and returned to the queue, it can be used
139
- if (this.idleQueue.length > 0) {
140
- return this.idleQueue.shift() || null;
141
- }
142
- // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source
143
- if (this.count < this._getMaxConcurrency()) {
144
- this.count++;
145
- const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;
146
- return new worker_thread_1.default({ name, source: this.source, url: this.url });
147
- }
148
- // No worker available, have to wait
149
- return null;
150
- }
151
- _getMaxConcurrency() {
152
- return globals_1.isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
153
- }
154
- }
155
- exports.default = WorkerPool;
@@ -1,131 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const worker_threads_1 = require("../node/worker_threads");
5
- const globals_1 = require("../env-utils/globals");
6
- const assert_1 = require("../env-utils/assert");
7
- const get_loadable_worker_url_1 = require("../worker-utils/get-loadable-worker-url");
8
- const get_transfer_list_1 = require("../worker-utils/get-transfer-list");
9
- const NOOP = () => { };
10
- /**
11
- * Represents one worker thread
12
- */
13
- class WorkerThread {
14
- /** Checks if workers are supported on this platform */
15
- static isSupported() {
16
- return ((typeof Worker !== 'undefined' && globals_1.isBrowser) ||
17
- (typeof worker_threads_1.NodeWorker !== 'undefined' && !globals_1.isBrowser));
18
- }
19
- constructor(props) {
20
- this.terminated = false;
21
- this._loadableURL = '';
22
- const { name, source, url } = props;
23
- (0, assert_1.assert)(source || url); // Either source or url must be defined
24
- this.name = name;
25
- this.source = source;
26
- this.url = url;
27
- this.onMessage = NOOP;
28
- this.onError = (error) => console.log(error); // eslint-disable-line
29
- this.worker = globals_1.isBrowser ? this._createBrowserWorker() : this._createNodeWorker();
30
- }
31
- /**
32
- * Terminate this worker thread
33
- * @note Can free up significant memory
34
- */
35
- destroy() {
36
- this.onMessage = NOOP;
37
- this.onError = NOOP;
38
- this.worker.terminate(); // eslint-disable-line @typescript-eslint/no-floating-promises
39
- this.terminated = true;
40
- }
41
- get isRunning() {
42
- return Boolean(this.onMessage);
43
- }
44
- /**
45
- * Send a message to this worker thread
46
- * @param data any data structure, ideally consisting mostly of transferrable objects
47
- * @param transferList If not supplied, calculated automatically by traversing data
48
- */
49
- postMessage(data, transferList) {
50
- transferList = transferList || (0, get_transfer_list_1.getTransferList)(data);
51
- // @ts-ignore
52
- this.worker.postMessage(data, transferList);
53
- }
54
- // PRIVATE
55
- /**
56
- * Generate a standard Error from an ErrorEvent
57
- * @param event
58
- */
59
- _getErrorFromErrorEvent(event) {
60
- // Note Error object does not have the expected fields if loading failed completely
61
- // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers
62
- // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
63
- let message = 'Failed to load ';
64
- message += `worker ${this.name} from ${this.url}. `;
65
- if (event.message) {
66
- message += `${event.message} in `;
67
- }
68
- // const hasFilename = event.filename && !event.filename.startsWith('blob:');
69
- // message += hasFilename ? event.filename : this.source.slice(0, 100);
70
- if (event.lineno) {
71
- message += `:${event.lineno}:${event.colno}`;
72
- }
73
- return new Error(message);
74
- }
75
- /**
76
- * Creates a worker thread on the browser
77
- */
78
- _createBrowserWorker() {
79
- this._loadableURL = (0, get_loadable_worker_url_1.getLoadableWorkerURL)({ source: this.source, url: this.url });
80
- const worker = new Worker(this._loadableURL, { name: this.name });
81
- worker.onmessage = (event) => {
82
- if (!event.data) {
83
- this.onError(new Error('No data received'));
84
- }
85
- else {
86
- this.onMessage(event.data);
87
- }
88
- };
89
- // This callback represents an uncaught exception in the worker thread
90
- worker.onerror = (error) => {
91
- this.onError(this._getErrorFromErrorEvent(error));
92
- this.terminated = true;
93
- };
94
- // TODO - not clear when this would be called, for now just log in case it happens
95
- worker.onmessageerror = (event) => console.error(event); // eslint-disable-line
96
- return worker;
97
- }
98
- /**
99
- * Creates a worker thread in node.js
100
- * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool
101
- */
102
- _createNodeWorker() {
103
- let worker;
104
- if (this.url) {
105
- // Make sure relative URLs start with './'
106
- const absolute = this.url.includes(':/') || this.url.startsWith('/');
107
- const url = absolute ? this.url : `./${this.url}`;
108
- // console.log('Starting work from', url);
109
- worker = new worker_threads_1.NodeWorker(url, { eval: false });
110
- }
111
- else if (this.source) {
112
- worker = new worker_threads_1.NodeWorker(this.source, { eval: true });
113
- }
114
- else {
115
- throw new Error('no worker');
116
- }
117
- worker.on('message', (data) => {
118
- // console.error('message', data);
119
- this.onMessage(data);
120
- });
121
- worker.on('error', (error) => {
122
- // console.error('error', error);
123
- this.onError(error);
124
- });
125
- worker.on('exit', (code) => {
126
- // console.error('exit', code);
127
- });
128
- return worker;
129
- }
130
- }
131
- exports.default = WorkerThread;
@@ -1,72 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLoadableWorkerURL = void 0;
4
- const assert_1 = require("../env-utils/assert");
5
- const workerURLCache = new Map();
6
- /**
7
- * Creates a loadable URL from worker source or URL
8
- * that can be used to create `Worker` instances.
9
- * Due to CORS issues it may be necessary to wrap a URL in a small importScripts
10
- * @param props
11
- * @param props.source Worker source
12
- * @param props.url Worker URL
13
- * @returns loadable url
14
- */
15
- function getLoadableWorkerURL(props) {
16
- (0, assert_1.assert)((props.source && !props.url) || (!props.source && props.url)); // Either source or url must be defined
17
- let workerURL = workerURLCache.get(props.source || props.url);
18
- if (!workerURL) {
19
- // Differentiate worker urls from worker source code
20
- if (props.url) {
21
- workerURL = getLoadableWorkerURLFromURL(props.url);
22
- workerURLCache.set(props.url, workerURL);
23
- }
24
- if (props.source) {
25
- workerURL = getLoadableWorkerURLFromSource(props.source);
26
- workerURLCache.set(props.source, workerURL);
27
- }
28
- }
29
- (0, assert_1.assert)(workerURL);
30
- return workerURL;
31
- }
32
- exports.getLoadableWorkerURL = getLoadableWorkerURL;
33
- /**
34
- * Build a loadable worker URL from worker URL
35
- * @param url
36
- * @returns loadable URL
37
- */
38
- function getLoadableWorkerURLFromURL(url) {
39
- // A local script url, we can use it to initialize a Worker directly
40
- if (!url.startsWith('http')) {
41
- return url;
42
- }
43
- // A remote script, we need to use `importScripts` to load from different origin
44
- const workerSource = buildScriptSource(url);
45
- return getLoadableWorkerURLFromSource(workerSource);
46
- }
47
- /**
48
- * Build a loadable worker URL from worker source
49
- * @param workerSource
50
- * @returns loadable url
51
- */
52
- function getLoadableWorkerURLFromSource(workerSource) {
53
- const blob = new Blob([workerSource], { type: 'application/javascript' });
54
- return URL.createObjectURL(blob);
55
- }
56
- /**
57
- * Per spec, worker cannot be initialized with a script from a different origin
58
- * However a local worker script can still import scripts from other origins,
59
- * so we simply build a wrapper script.
60
- *
61
- * @param workerUrl
62
- * @returns source
63
- */
64
- function buildScriptSource(workerUrl) {
65
- return `\
66
- try {
67
- importScripts('${workerUrl}');
68
- } catch (error) {
69
- console.error(error);
70
- throw error;
71
- }`;
72
- }
@@ -1,87 +0,0 @@
1
- "use strict";
2
- // NOTE - there is a copy of this function is both in core and loader-utils
3
- // core does not need all the utils in loader-utils, just this one.
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.getTransferListForWriter = exports.getTransferList = void 0;
6
- /**
7
- * Returns an array of Transferrable objects that can be used with postMessage
8
- * https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
9
- * @param object data to be sent via postMessage
10
- * @param recursive - not for application use
11
- * @param transfers - not for application use
12
- * @returns a transfer list that can be passed to postMessage
13
- */
14
- function getTransferList(object, recursive = true, transfers) {
15
- // Make sure that items in the transfer list is unique
16
- const transfersSet = transfers || new Set();
17
- if (!object) {
18
- // ignore
19
- }
20
- else if (isTransferable(object)) {
21
- transfersSet.add(object);
22
- }
23
- else if (isTransferable(object.buffer)) {
24
- // Typed array
25
- transfersSet.add(object.buffer);
26
- }
27
- else if (ArrayBuffer.isView(object)) {
28
- // object is a TypeArray viewing into a SharedArrayBuffer (not transferable)
29
- // Do not iterate through the content in this case
30
- }
31
- else if (recursive && typeof object === 'object') {
32
- for (const key in object) {
33
- // Avoid perf hit - only go one level deep
34
- getTransferList(object[key], recursive, transfersSet);
35
- }
36
- }
37
- // If transfers is defined, is internal recursive call
38
- // Otherwise it's called by the user
39
- return transfers === undefined ? Array.from(transfersSet) : [];
40
- }
41
- exports.getTransferList = getTransferList;
42
- // https://developer.mozilla.org/en-US/docs/Web/API/Transferable
43
- function isTransferable(object) {
44
- if (!object) {
45
- return false;
46
- }
47
- if (object instanceof ArrayBuffer) {
48
- return true;
49
- }
50
- if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
51
- return true;
52
- }
53
- if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
54
- return true;
55
- }
56
- // @ts-ignore
57
- if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
58
- return true;
59
- }
60
- return false;
61
- }
62
- /**
63
- * Recursively drop non serializable values like functions and regexps.
64
- * @param object
65
- */
66
- function getTransferListForWriter(object) {
67
- if (object === null) {
68
- return {};
69
- }
70
- const clone = Object.assign({}, object);
71
- Object.keys(clone).forEach((key) => {
72
- // Typed Arrays and Arrays are passed with no change
73
- if (typeof object[key] === 'object' &&
74
- !ArrayBuffer.isView(object[key]) &&
75
- !(object[key] instanceof Array)) {
76
- clone[key] = getTransferListForWriter(object[key]);
77
- }
78
- else if (typeof clone[key] === 'function' || clone[key] instanceof RegExp) {
79
- clone[key] = {};
80
- }
81
- else {
82
- clone[key] = object[key];
83
- }
84
- });
85
- return clone;
86
- }
87
- exports.getTransferListForWriter = getTransferListForWriter;
@@ -1,27 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeNontransferableOptions = void 0;
4
- /**
5
- * Recursively drop non serializable values like functions and regexps.
6
- * @param object
7
- */
8
- function removeNontransferableOptions(object) {
9
- if (object === null) {
10
- return {};
11
- }
12
- const clone = Object.assign({}, object);
13
- Object.keys(clone).forEach((key) => {
14
- // Checking if it is an object and not a typed array.
15
- if (typeof object[key] === 'object' && !ArrayBuffer.isView(object[key])) {
16
- clone[key] = removeNontransferableOptions(object[key]);
17
- }
18
- else if (typeof clone[key] === 'function' || clone[key] instanceof RegExp) {
19
- clone[key] = {};
20
- }
21
- else {
22
- clone[key] = object[key];
23
- }
24
- });
25
- return clone;
26
- }
27
- exports.removeNontransferableOptions = removeNontransferableOptions;
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const create_worker_1 = require("../lib/worker-api/create-worker");
4
- (0, create_worker_1.createWorker)(async (data) => {
5
- // @ts-ignore
6
- return data;
7
- });