easy-web-worker 1.0.6 → 1.0.8

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.
@@ -1,57 +1,95 @@
1
- import * as IEasyWebWorker from './EasyWebWorkerTypes';
1
+ import { EasyWebWorkerBody, IWorkerConfig } from './EasyWebWorkerTypes';
2
+ import { CancelablePromise } from 'cancelable-promise-jq';
2
3
  /**
3
- * This is a class to create global-store objects
4
- * @template IPayload - Indicates if your WORKERS messages requires a parameter to be provided, NULL indicates they doesn't
5
- * @template IResult - Indicates if your WORKERS messages has a result... NULL indicates all you messages are Promise<void>
6
- * @param {IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult> | IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult>[]} workerBody -
7
- * this parameter should be a function or set of functions that will become the body of your Web-Worker
8
- * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
9
- * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
10
- * you could easily identify what is on the context of your Worker.
11
- * @param {Partial<IEasyWebWorker.IWorkerConfig>} WorkerConfig - You could add extra configuration to your worker,
12
- * consult IWorkerConfig description to have more information
13
- * */
14
- declare class EasyWebWorker<IPayload = null, IResult = void> implements IEasyWebWorker.IEasyWebWorker<IPayload, IResult> {
15
- protected workerBody: IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult> | IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult>[] | string;
4
+ * This is a class to create global-store objects
5
+ * @template IPayload - Indicates if your WORKERS messages requires a parameter to be provided, NULL indicates they doesn't
6
+ * @template IResult - Indicates if your WORKERS messages has a result... NULL indicates all you messages are Promise<void>
7
+ * @param {EasyWebWorkerBody<IPayload, IResult> | EasyWebWorkerBody<IPayload, IResult>[]} workerBody -
8
+ * this parameter should be a function or set of functions that will become the body of your Web-Worker
9
+ * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
10
+ * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
11
+ * you could easily identify what is on the context of your Worker.
12
+ * @param {Partial<IWorkerConfig>} WorkerConfig - You could add extra configuration to your worker,
13
+ * consult IWorkerConfig description to have more information
14
+ * */
15
+ export declare class EasyWebWorker<IPayload = null, IResult = void> {
16
+ /**
17
+ * this parameter should be a function or set of functions that will become the body of your Web-Worker
18
+ * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
19
+ * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
20
+ * you could easily identify what is on the context of your Worker.
21
+ */
22
+ protected workerBody: EasyWebWorkerBody<IPayload, IResult> | EasyWebWorkerBody<IPayload, IResult>[] | string;
16
23
  name: string;
17
- private worker;
24
+ /**
25
+ * @deprecated Directly modifying the worker may lead to unexpected behavior. Use it only if you know what you are doing.
26
+ */
27
+ worker: Worker;
28
+ /**
29
+ * These where send to the worker but not yet resolved
30
+ */
18
31
  private messagesQueue;
32
+ /**
33
+ * This is the URL of the worker file
34
+ */
19
35
  workerUrl: string;
20
- protected scripts: string[];
36
+ /**
37
+ * This is the list of scripts that will be imported into the worker
38
+ */
39
+ scripts: string[];
40
+ /**
41
+ * This is the callback that will be executed when the worker throws an error
42
+ */
43
+ onWorkerError: (error: ErrorEvent) => void;
21
44
  protected get isExternalWorkerFile(): boolean;
22
- constructor(workerBody: IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult> | IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult>[] | string, { scripts, name, }?: Partial<IEasyWebWorker.IWorkerConfig>);
45
+ constructor(
46
+ /**
47
+ * this parameter should be a function or set of functions that will become the body of your Web-Worker
48
+ * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
49
+ * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
50
+ * you could easily identify what is on the context of your Worker.
51
+ */
52
+ workerBody: EasyWebWorkerBody<IPayload, IResult> | EasyWebWorkerBody<IPayload, IResult>[] | string,
53
+ /**
54
+ * You could import scripts into your worker, this is useful if you want to use external libraries
55
+ */
56
+ { scripts, name, onWorkerError }?: Partial<IWorkerConfig>);
23
57
  private RemoveMessageFromQueue;
58
+ /**
59
+ * Categorizes the worker response and executes the corresponding callback
60
+ */
24
61
  private executeMessageCallback;
25
62
  protected getWorkerUrl(): string;
26
63
  protected createWorker(): Worker;
27
64
  /**
28
- * Disable the resolve of all current WebWorkers messages, no any of the current messages gonna call onProgress callback, neither promise.resolve
29
- */
30
- cancelAll(): void;
31
- /**
32
- * Send a message to the worker queue
33
- * @param {IPayload} payload - whatever json data you want to send to the worker
34
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
35
- */
36
- send(...payload: IPayload extends null ? [null?] : [IPayload]): IEasyWebWorker.IMessagePromise<IResult>;
37
- /**
38
- * Web Workers works as a QUEUE, sometimes a new message actually would be the only message that you'll want to resolve...
39
- * you could use OVERRIDE to that purpose.
40
- * @param {IPayload} payload - whatever json data you want to send to the worker
41
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
42
- */
43
- override(...payload: IPayload extends null ? [null?] : [IPayload]): IEasyWebWorker.IMessagePromise<IResult>;
44
- /**
45
- * Web Workers works as a QUEUE, sometimes a new message actually would be the only message that you'll want to resolve...
46
- * you could use OVERRIDE to that purpose.
47
- * @param {IPayload} payload - whatever json data you want to send to the worker
48
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
49
- */
50
- overrideAfterCurrent(...payload: IPayload extends null ? [null?] : [IPayload]): IEasyWebWorker.IMessagePromise<IResult>;
51
- /**
52
- * This method will remove the WebWorker and the BlobUrl
53
- */
65
+ * Terminates the worker and remove all messages from the queue
66
+ * Execute the cancel callback of each message in the queue if provided
67
+ * @param {unknown} reason - reason why the worker was terminated
68
+ */
69
+ cancelAll(reason?: unknown): void;
70
+ /**
71
+ * Send a message to the worker queue
72
+ * @param {IPayload} payload - whatever json data you want to send to the worker
73
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
74
+ */
75
+ send: IPayload extends null ? () => CancelablePromise<IResult> : (payload: IPayload) => CancelablePromise<IResult>;
76
+ /**
77
+ * This method terminate all current messages and send a new one to the worker queue
78
+ * @param {IPayload} payload - whatever json data you want to send to the worker, should be serializable
79
+ * @param {unknown} reason - reason why the worker was terminated
80
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
81
+ */
82
+ override: IPayload extends null ? (reason?: unknown) => CancelablePromise<IResult> : (payload: IPayload, reason?: unknown) => CancelablePromise<IResult>;
83
+ /**
84
+ * This method will alow the current message to be completed and send a new one to the worker queue after it, all the messages after the current one will be canceled
85
+ * @param {IPayload} payload - whatever json data you want to send to the worker should be serializable
86
+ * @param {unknown} reason - reason why the worker was terminated
87
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
88
+ */
89
+ overrideAfterCurrent: IPayload extends null ? (reason?: unknown) => CancelablePromise<IResult> : (payload: IPayload, reason?: unknown) => CancelablePromise<IResult>;
90
+ /**
91
+ * This method will remove the WebWorker and the BlobUrl
92
+ */
54
93
  dispose(): void;
55
94
  }
56
95
  export default EasyWebWorker;
57
- //# sourceMappingURL=EasyWebWorker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EasyWebWorker.d.ts","sourceRoot":"","sources":["../src/EasyWebWorker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,cAAc,MAAM,sBAAsB,CAAC;AAKvD;;;;;;;;;;;IAWI;AACJ,cAAM,aAAa,CAAE,QAAQ,GAAG,IAAI,EAAE,OAAO,GAAG,IAAI,CAAE,YAAW,cAAc,CAAC,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC;IAiB3G,SAAS,CAAC,UAAU,EAAE,cAAc,CAAC,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,cAAc,CAAC,iBAAiB,CAAC,QAAQ,EAA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ACI,IAAI,gCAeD,kBAAkB,OAAO,CAAC,aACtB,QAAQ,KAAK,kBAAkB,OAAO,CAAC,CAAC;IAEtD;;;;;OAKG;IACI,QAAQ,oCASD,OAAO,KAAK,kBAAkB,OAAO,CAAC,aACtC,QAAQ,WAAW,OAAO,KAAK,kBAAkB,OAAO,CAAC,CAAC;IAExE;;;;;OAKG;IACI,oBAAoB,oCAkBb,OAAO,KAAK,kBAAkB,OAAO,CAAC,aACtC,QAAQ,WAAW,OAAO,KAAK,kBAAkB,OAAO,CAAC,CAAC;IAExE;;OAEG;IACI,OAAO,IAAI,IAAI;CAOvB;AAED,eAAe,aAAa,CAAC"}
@@ -1,143 +1,226 @@
1
1
  "use strict";
2
+ var __read = (this && this.__read) || function (o, n) {
3
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
4
+ if (!m) return o;
5
+ var i = m.call(o), r, ar = [], e;
6
+ try {
7
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
8
+ }
9
+ catch (error) { e = { error: error }; }
10
+ finally {
11
+ try {
12
+ if (r && !r.done && (m = i["return"])) m.call(i);
13
+ }
14
+ finally { if (e) throw e.error; }
15
+ }
16
+ return ar;
17
+ };
18
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
+ if (ar || !(i in from)) {
21
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
+ ar[i] = from[i];
23
+ }
24
+ }
25
+ return to.concat(ar || Array.prototype.slice.call(from));
26
+ };
2
27
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const EasyWebWorkerMessage_1 = tslib_1.__importDefault(require("./EasyWebWorkerMessage"));
5
- const EasyWebWorkerFactory_1 = tslib_1.__importDefault(require("./EasyWebWorkerFactory"));
6
- const EasyWebWorkerFixtures_1 = require("./EasyWebWorkerFixtures");
28
+ exports.EasyWebWorker = void 0;
29
+ var EasyWebWorkerMessage_1 = require("./EasyWebWorkerMessage");
30
+ var EasyWebWorkerFactory_1 = require("./EasyWebWorkerFactory");
31
+ var EasyWebWorkerFixtures_1 = require("./EasyWebWorkerFixtures");
7
32
  /**
8
- * This is a class to create global-store objects
9
- * @template IPayload - Indicates if your WORKERS messages requires a parameter to be provided, NULL indicates they doesn't
10
- * @template IResult - Indicates if your WORKERS messages has a result... NULL indicates all you messages are Promise<void>
11
- * @param {IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult> | IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult>[]} workerBody -
12
- * this parameter should be a function or set of functions that will become the body of your Web-Worker
13
- * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
14
- * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
15
- * you could easily identify what is on the context of your Worker.
16
- * @param {Partial<IEasyWebWorker.IWorkerConfig>} WorkerConfig - You could add extra configuration to your worker,
17
- * consult IWorkerConfig description to have more information
18
- * */
19
- class EasyWebWorker {
20
- constructor(workerBody, { scripts = [], name, } = {}) {
33
+ * This is a class to create global-store objects
34
+ * @template IPayload - Indicates if your WORKERS messages requires a parameter to be provided, NULL indicates they doesn't
35
+ * @template IResult - Indicates if your WORKERS messages has a result... NULL indicates all you messages are Promise<void>
36
+ * @param {EasyWebWorkerBody<IPayload, IResult> | EasyWebWorkerBody<IPayload, IResult>[]} workerBody -
37
+ * this parameter should be a function or set of functions that will become the body of your Web-Worker
38
+ * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
39
+ * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
40
+ * you could easily identify what is on the context of your Worker.
41
+ * @param {Partial<IWorkerConfig>} WorkerConfig - You could add extra configuration to your worker,
42
+ * consult IWorkerConfig description to have more information
43
+ * */
44
+ var EasyWebWorker = /** @class */ (function () {
45
+ function EasyWebWorker(
46
+ /**
47
+ * this parameter should be a function or set of functions that will become the body of your Web-Worker
48
+ * IMPORTANT!! all WORKERS content is gonna be transpiled on run time, so you can not use any variable, method of resource that weren't included into the WORKER.
49
+ * the above the reason of why we are injecting all worker context into the MessageBody Callbacks, so,
50
+ * you could easily identify what is on the context of your Worker.
51
+ */
52
+ workerBody,
53
+ /**
54
+ * You could import scripts into your worker, this is useful if you want to use external libraries
55
+ */
56
+ _a) {
57
+ var
58
+ /**
59
+ * You could import scripts into your worker, this is useful if you want to use external libraries
60
+ */
61
+ _b = _a === void 0 ? {} : _a, _c = _b.scripts, scripts = _c === void 0 ? [] : _c, name = _b.name, _d = _b.onWorkerError, onWorkerError = _d === void 0 ? null : _d;
62
+ var _this = this;
21
63
  this.workerBody = workerBody;
22
- this.messagesQueue = [];
23
- this.workerUrl = '';
64
+ /**
65
+ * These where send to the worker but not yet resolved
66
+ */
67
+ this.messagesQueue = new Map();
68
+ /**
69
+ * This is the list of scripts that will be imported into the worker
70
+ */
24
71
  this.scripts = [];
25
- this.name = name || EasyWebWorkerFixtures_1.generatedId();
26
- this.scripts = scripts;
27
- this.worker = this.createWorker();
28
- }
29
- get isExternalWorkerFile() {
30
- return typeof this.workerBody === 'string';
31
- }
32
- RemoveMessageFromQueue(messageId) {
33
- this.messagesQueue = this.messagesQueue.filter(({ messageId: key }) => key !== messageId);
34
- }
35
- executeMessageCallback(event) {
36
- // eslint-disable-next-line max-len
37
- const message = this.messagesQueue.find(({ messageId: key }) => key === event.data.messageId);
38
- if (message) {
39
- const { payload, error, progressPercentage } = event.data;
40
- // worker was disposed
41
- if (!this.worker) {
42
- this.RemoveMessageFromQueue(message.messageId);
43
- message.wasCompleted = true;
44
- return;
72
+ /**
73
+ * Send a message to the worker queue
74
+ * @param {IPayload} payload - whatever json data you want to send to the worker
75
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
76
+ */
77
+ this.send = (function () {
78
+ var _a;
79
+ var payload = [];
80
+ for (var _i = 0; _i < arguments.length; _i++) {
81
+ payload[_i] = arguments[_i];
45
82
  }
46
- if (progressPercentage !== undefined) {
47
- message.reportProgress(progressPercentage);
48
- return;
83
+ var _b = __read(payload, 1), $payload = _b[0];
84
+ var message = new EasyWebWorkerMessage_1.EasyWebWorkerMessage($payload);
85
+ var messageId = message.messageId;
86
+ _this.messagesQueue.set(message.messageId, message);
87
+ (_a = _this.worker) === null || _a === void 0 ? void 0 : _a.postMessage({
88
+ messageId: messageId,
89
+ payload: $payload,
90
+ });
91
+ return message.decoupledPromise.promise;
92
+ });
93
+ /**
94
+ * This method terminate all current messages and send a new one to the worker queue
95
+ * @param {IPayload} payload - whatever json data you want to send to the worker, should be serializable
96
+ * @param {unknown} reason - reason why the worker was terminated
97
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
98
+ */
99
+ this.override = (function () {
100
+ var _a = [];
101
+ for (var _i = 0; _i < arguments.length; _i++) {
102
+ _a[_i] = arguments[_i];
49
103
  }
50
- this.RemoveMessageFromQueue(message.messageId);
51
- if (error) {
52
- message.reject(error);
53
- return;
104
+ var _b = __read(_a, 2), payload = _b[0], reason = _b[1];
105
+ _this.cancelAll(reason);
106
+ return _this.send.apply(_this, __spreadArray([], __read([payload]), false));
107
+ });
108
+ /**
109
+ * This method will alow the current message to be completed and send a new one to the worker queue after it, all the messages after the current one will be canceled
110
+ * @param {IPayload} payload - whatever json data you want to send to the worker should be serializable
111
+ * @param {unknown} reason - reason why the worker was terminated
112
+ * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
113
+ */
114
+ this.overrideAfterCurrent = (function () {
115
+ var _a = [];
116
+ for (var _i = 0; _i < arguments.length; _i++) {
117
+ _a[_i] = arguments[_i];
54
118
  }
55
- if (message.wasCanceled) {
56
- message.wasCompleted = true;
57
- return;
119
+ var _b = __read(_a, 2), payload = _b[0], reason = _b[1];
120
+ if (_this.messagesQueue.size) {
121
+ var _c = __read(_this.messagesQueue, 1), firstItem = _c[0];
122
+ var _d = __read(firstItem, 2), currentMessage = _d[1];
123
+ _this.messagesQueue.delete(currentMessage.messageId);
124
+ _this.cancelAll(reason);
125
+ _this.messagesQueue.set(currentMessage.messageId, currentMessage);
58
126
  }
59
- message.resolve(...(payload || []));
60
- }
127
+ return _this.send.apply(_this, __spreadArray([], __read([payload]), false));
128
+ });
129
+ this.name = name || (0, EasyWebWorkerFixtures_1.generatedId)();
130
+ this.scripts = scripts;
131
+ this.worker = this.createWorker();
132
+ this.onWorkerError = onWorkerError;
61
133
  }
62
- getWorkerUrl() {
134
+ Object.defineProperty(EasyWebWorker.prototype, "isExternalWorkerFile", {
135
+ get: function () {
136
+ return typeof this.workerBody === 'string';
137
+ },
138
+ enumerable: false,
139
+ configurable: true
140
+ });
141
+ EasyWebWorker.prototype.RemoveMessageFromQueue = function (messageId) {
142
+ this.messagesQueue.delete(messageId);
143
+ };
144
+ /**
145
+ * Categorizes the worker response and executes the corresponding callback
146
+ */
147
+ EasyWebWorker.prototype.executeMessageCallback = function (event) {
148
+ var _a;
149
+ var message = (_a = this.messagesQueue.get(event.data.messageId)) !== null && _a !== void 0 ? _a : null;
150
+ if (!message)
151
+ return;
152
+ var _b = event.data, payload = _b.payload, reason = _b.reason, wasCanceled = _b.wasCanceled, progressPercentage = _b.progressPercentage;
153
+ // worker was disposed before the message was resolved
154
+ if (!this.worker) {
155
+ this.RemoveMessageFromQueue(message.messageId);
156
+ return;
157
+ }
158
+ // execute progress callback
159
+ if (progressPercentage !== undefined) {
160
+ message.reportProgress(progressPercentage);
161
+ return;
162
+ }
163
+ // remove message from queue
164
+ this.RemoveMessageFromQueue(message.messageId);
165
+ message.wasCompleted = false;
166
+ if (wasCanceled) {
167
+ message.cancel(reason);
168
+ return;
169
+ }
170
+ if (reason) {
171
+ message.reject(reason);
172
+ return;
173
+ }
174
+ message.wasCompleted = true;
175
+ // resolve message with the serialized payload
176
+ message.resolve.apply(message, __spreadArray([], __read((payload !== null && payload !== void 0 ? payload : [])), false));
177
+ };
178
+ EasyWebWorker.prototype.getWorkerUrl = function () {
63
179
  if (this.isExternalWorkerFile) {
64
180
  return this.workerBody;
65
181
  }
66
- return EasyWebWorkerFactory_1.default
67
- .blobWorker(this.workerBody, this.scripts);
68
- }
69
- createWorker() {
182
+ return EasyWebWorkerFactory_1.easyWebWorkerFactory.blobWorker(this.workerBody, this.scripts);
183
+ };
184
+ EasyWebWorker.prototype.createWorker = function () {
185
+ var _this = this;
70
186
  this.workerUrl = this.getWorkerUrl();
71
- const worker = new Worker(this.workerUrl, {
187
+ var worker = new Worker(this.workerUrl, {
72
188
  name: this.name,
73
189
  });
74
- worker.onmessage = (event) => this.executeMessageCallback(event);
75
- worker.onerror = (error) => this.executeMessageCallback({ data: { error } });
190
+ worker.onmessage = function (event) {
191
+ _this.executeMessageCallback(event);
192
+ };
193
+ /**
194
+ * If not handled, the error will be thrown to the global scope
195
+ */
196
+ worker.onerror = function (reason) {
197
+ if (!_this.onWorkerError)
198
+ throw reason;
199
+ _this.onWorkerError(reason);
200
+ };
76
201
  return worker;
77
- }
78
- /**
79
- * Disable the resolve of all current WebWorkers messages, no any of the current messages gonna call onProgress callback, neither promise.resolve
80
- */
81
- cancelAll() {
82
- this.messagesQueue.forEach((message) => message.cancel());
83
- this.messagesQueue = [];
84
- }
202
+ };
85
203
  /**
86
- * Send a message to the worker queue
87
- * @param {IPayload} payload - whatever json data you want to send to the worker
88
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
89
- */
90
- send(...payload) {
204
+ * Terminates the worker and remove all messages from the queue
205
+ * Execute the cancel callback of each message in the queue if provided
206
+ * @param {unknown} reason - reason why the worker was terminated
207
+ */
208
+ EasyWebWorker.prototype.cancelAll = function (reason) {
91
209
  var _a;
92
- const [_payload] = payload;
93
- const message = new EasyWebWorkerMessage_1.default(_payload);
94
- const { messageId } = message;
95
- this.messagesQueue.push(message);
96
- (_a = this.worker) === null || _a === void 0 ? void 0 : _a.postMessage({
97
- messageId,
98
- payload: _payload,
99
- });
100
- const result = message.promise;
101
- result.onProgress = (callback) => {
102
- message.reportProgress = callback;
103
- return message.promise;
104
- };
105
- return result;
106
- }
107
- /**
108
- * Web Workers works as a QUEUE, sometimes a new message actually would be the only message that you'll want to resolve...
109
- * you could use OVERRIDE to that purpose.
110
- * @param {IPayload} payload - whatever json data you want to send to the worker
111
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
112
- */
113
- override(...payload) {
114
- this.cancelAll();
115
- return this.send(...payload);
116
- }
117
- /**
118
- * Web Workers works as a QUEUE, sometimes a new message actually would be the only message that you'll want to resolve...
119
- * you could use OVERRIDE to that purpose.
120
- * @param {IPayload} payload - whatever json data you want to send to the worker
121
- * @returns {IMessagePromise<IResult>} generated defer that will be resolved when the message completed
122
- */
123
- overrideAfterCurrent(...payload) {
124
- if (this.messagesQueue.length) {
125
- const [currentMessage] = this.messagesQueue;
126
- this.cancelAll();
127
- currentMessage.wasCanceled = false;
128
- this.messagesQueue.push(currentMessage);
129
- }
130
- return this.send(...payload);
131
- }
210
+ (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
211
+ var messages = Array.from(this.messagesQueue.values());
212
+ messages.forEach(function (message) { return message.cancel(reason); });
213
+ this.messagesQueue = new Map();
214
+ };
132
215
  /**
133
- * This method will remove the WebWorker and the BlobUrl
134
- */
135
- dispose() {
136
- var _a;
216
+ * This method will remove the WebWorker and the BlobUrl
217
+ */
218
+ EasyWebWorker.prototype.dispose = function () {
137
219
  this.cancelAll();
138
- (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();
139
220
  URL.revokeObjectURL(this.workerUrl);
140
221
  this.worker = null;
141
- }
142
- }
222
+ };
223
+ return EasyWebWorker;
224
+ }());
225
+ exports.EasyWebWorker = EasyWebWorker;
143
226
  exports.default = EasyWebWorker;
@@ -1,9 +1,8 @@
1
- import * as IEasyWebWorker from "./EasyWebWorkerTypes";
2
- export declare class EasyWebWorkerFactory {
1
+ import { EasyWebWorkerBody } from './EasyWebWorkerTypes';
2
+ declare class EasyWebWorkerFactory {
3
3
  private getImportScriptsTemplate;
4
4
  blob(source: string, imports?: string[]): string;
5
- blobWorker<IPayload = null, IResult = void>(source: IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult> | IEasyWebWorker.EasyWebWorkerBody<IPayload, IResult>[], imports?: string[]): string;
5
+ blobWorker<IPayload = null, IResult = void>(source: EasyWebWorkerBody<IPayload, IResult> | EasyWebWorkerBody<IPayload, IResult>[], imports?: string[]): string;
6
6
  }
7
- declare const _default: EasyWebWorkerFactory;
8
- export default _default;
9
- //# sourceMappingURL=EasyWebWorkerFactory.d.ts.map
7
+ export declare const easyWebWorkerFactory: EasyWebWorkerFactory;
8
+ export {};
@@ -1 +1 @@
1
- {"version":3,"file":"EasyWebWorkerFactory.d.ts","sourceRoot":"","sources":["../src/EasyWebWorkerFactory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,cAAc,MAAM,sBAAsB,CAAC;AAEvD,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,wBAAwB;IAMzB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,MAAM,EAAO;IAW3C,UAAU,CAAC,QAAQ,GAAG,IAAI,EAAE,OAAO,GAAG,IAAI,EAC/C,MAAM,EACF,cAAc,CAAC,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,GACnD,cAAc,CAAC,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,EACzD,OAAO,GAAE,MAAM,EAAO;CAwBzB;;AAED,wBAA0C"}
1
+ {"version":3,"file":"EasyWebWorkerFactory.d.ts","sourceRoot":"","sources":["../src/EasyWebWorkerFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,cAAM,oBAAoB;IACxB,OAAO,CAAC,wBAAwB;IAMzB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,MAAM,EAAO;IAW3C,UAAU,CAAC,QAAQ,GAAG,IAAI,EAAE,OAAO,GAAG,IAAI,EAC/C,MAAM,EACF,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,GACpC,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,EAC1C,OAAO,GAAE,MAAM,EAAO;CAyBzB;AAED,eAAO,MAAM,oBAAoB,sBAA6B,CAAC"}
@@ -1,31 +1,35 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EasyWebWorkerFactory = void 0;
4
- const EasyWebWorkerFixtures_1 = require("./EasyWebWorkerFixtures");
5
- class EasyWebWorkerFactory {
6
- getImportScriptsTemplate(scripts = []) {
7
- if (!scripts.length)
8
- return "";
9
- return `self.importScripts(["${scripts.join('","')}"]);`;
3
+ exports.easyWebWorkerFactory = void 0;
4
+ var EasyWebWorkerFixtures_1 = require("./EasyWebWorkerFixtures");
5
+ var EasyWebWorkerFactory = /** @class */ (function () {
6
+ function EasyWebWorkerFactory() {
10
7
  }
11
- blob(source, imports = []) {
12
- const content = `${this.getImportScriptsTemplate(imports)}
13
- ${source}`;
8
+ EasyWebWorkerFactory.prototype.getImportScriptsTemplate = function (scripts) {
9
+ if (scripts === void 0) { scripts = []; }
10
+ if (!scripts.length)
11
+ return '';
12
+ return "self.importScripts([\"".concat(scripts.join('","'), "\"]);");
13
+ };
14
+ EasyWebWorkerFactory.prototype.blob = function (source, imports) {
15
+ if (imports === void 0) { imports = []; }
16
+ var content = "".concat(this.getImportScriptsTemplate(imports), "\n ").concat(source);
14
17
  return (window.URL || window.webkitURL).createObjectURL(new Blob([content], {
15
- type: "application/javascript",
18
+ type: 'application/javascript',
16
19
  }));
17
- }
18
- blobWorker(source, imports = []) {
19
- const template = EasyWebWorkerFixtures_1.WorkerTemplate();
20
- const contentCollection = Array.isArray(source) ? source : [source];
20
+ };
21
+ EasyWebWorkerFactory.prototype.blobWorker = function (source, imports) {
22
+ if (imports === void 0) { imports = []; }
23
+ var template = (0, EasyWebWorkerFixtures_1.WorkerTemplate)();
24
+ var contentCollection = Array.isArray(source) ? source : [source];
21
25
  return (window.URL || window.webkitURL).createObjectURL(new Blob([
22
- `${this.getImportScriptsTemplate(imports)}
23
- ${template}
24
- ${contentCollection
25
- .map((content, index) => `// content #${index}\n(${content.toString()})(easyWorker, self);`)
26
- .join("\n\n")}`,
27
- ], { type: "application/javascript" }));
28
- }
29
- }
30
- exports.EasyWebWorkerFactory = EasyWebWorkerFactory;
31
- exports.default = new EasyWebWorkerFactory();
26
+ "".concat(this.getImportScriptsTemplate(imports), "\n \n ").concat(template, "\n \n ").concat(contentCollection
27
+ .map(function (content, index) {
28
+ return "// content #".concat(index, "\n(").concat(content.toString(), ")(easyWorker, self);");
29
+ })
30
+ .join('\n\n')),
31
+ ], { type: 'application/javascript' }));
32
+ };
33
+ return EasyWebWorkerFactory;
34
+ }());
35
+ exports.easyWebWorkerFactory = new EasyWebWorkerFactory();
@@ -1,4 +1,5 @@
1
1
  export declare const generatedId: () => string;
2
+ /**
3
+ * This is the template of the worker, should be and string to avoid compilation issues
4
+ */
2
5
  export declare const WorkerTemplate: () => string;
3
- export default generatedId;
4
- //# sourceMappingURL=EasyWebWorkerFixtures.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EasyWebWorkerFixtures.d.ts","sourceRoot":"","sources":["../src/EasyWebWorkerFixtures.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,WAAW,QAAO,MACsC,CAAC;AAEtE,eAAO,MAAM,cAAc,cAgC1B,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"EasyWebWorkerFixtures.d.ts","sourceRoot":"","sources":["../src/EasyWebWorkerFixtures.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,QAAO,MACsC,CAAC;AAEtE;;GAEG;AACH,eAAO,MAAM,cAAc,cAgC1B,CAAC"}