promise-worker-bi 4.0.3 → 4.1.0

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.
package/README.md CHANGED
@@ -16,22 +16,20 @@ Inside your main bundle:
16
16
  // main.js
17
17
  import { PWBHost } from "promise-worker-bi";
18
18
 
19
- var worker = new Worker("worker.js");
20
- var promiseWorker = new PWBHost(worker);
19
+ const worker = new Worker("worker.js");
20
+ const promiseWorker = new PWBHost(worker);
21
21
 
22
22
  // Only needed if you send messages from the worker to the host
23
- promiseWorker.register(function(message) {
23
+ promiseWorker.register((message) => {
24
24
  return "pong2";
25
25
  });
26
26
 
27
- promiseWorker
28
- .postMessage("ping")
29
- .then(function(response) {
30
- // handle response 'pong'
31
- })
32
- .catch(function(error) {
33
- // handle error
34
- });
27
+ try {
28
+ const response = await promiseWorker.postMessage("ping");
29
+ // handle response 'pong'
30
+ } catch (error) {
31
+ // handle error
32
+ }
35
33
  ```
36
34
 
37
35
  Inside your `worker.js` bundle:
@@ -40,48 +38,37 @@ Inside your `worker.js` bundle:
40
38
  // worker.js
41
39
  import { PWBWorker } from "promise-worker-bi";
42
40
 
43
- var promiseWorker = new PWBWorker();
41
+ const promiseWorker = new PWBWorker();
44
42
 
45
43
  // Only needed if you send messages from the host to the worker
46
- promiseWorker.register(function(message) {
44
+ promiseWorker.register((message) => {
47
45
  return "pong";
48
46
  });
49
47
 
50
- promiseWorker
51
- .postMessage("ping2")
52
- .then(function(response) {
53
- // handle response 'pong2'
54
- })
55
- .catch(function(error) {
56
- // handle error
57
- });
48
+ try {
49
+ const response = await promiseWorker.postMessage("ping2");
50
+ // handle response 'pong2'
51
+ } catch (error) {
52
+ // handle error
53
+ }
58
54
  ```
59
55
 
60
56
  **Notice that except for initialization of the `promiseWorker` object, the API is identical in the browser and in the worker. Either one can initiate a message.** In all of the subsequent examples, `promiseWorker` initialization is omitted, so you can put the two blocks of code respectively in the worker and browser, or in the browser and worker.
61
57
 
62
- And it's even better with async/await:
63
-
64
- ```js
65
- const response = await promiseWorker.postMessage("ping2");
66
- // response contains 'pong2'
67
- ```
68
-
69
58
  ### Message format
70
59
 
71
- The message you send can be any object, array, string, number, etc. - anything that is serializable by the structured clone algorithm:
60
+ The message you send can be any object, array, string, number, etc. - anything that is serializable by the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm):
72
61
 
73
62
  ```js
74
- promiseWorker
75
- .postMessage({
76
- hello: "world",
77
- answer: 42,
78
- "this is fun": true
79
- })
80
- .then(/* ... */);
63
+ await promiseWorker.postMessage({
64
+ hello: "world",
65
+ answer: 42,
66
+ "this is fun": true,
67
+ });
81
68
  ```
82
69
 
83
70
  ```js
84
- promiseWorker.register(function(message) {
71
+ promiseWorker.register((message) => {
85
72
  console.log(message); // { hello: 'world', answer: 42, 'this is fun': true }
86
73
  });
87
74
  ```
@@ -91,17 +78,14 @@ promiseWorker.register(function(message) {
91
78
  The registered handler can return either a Promise or a normal value:
92
79
 
93
80
  ```js
94
- promiseWorker.register(function() {
95
- return Promise.resolve().then(function() {
96
- return "much async, very promise";
97
- });
81
+ promiseWorker.register(async () => {
82
+ "much async, very promise";
98
83
  });
99
84
  ```
100
85
 
101
86
  ```js
102
- promiseWorker.postMessage(null).then(function (message) {
103
- console.log(message): // 'much async, very promise'
104
- });
87
+ const message = await promiseWorker.postMessage(null);
88
+ console.log(message): // 'much async, very promise'
105
89
  ```
106
90
 
107
91
  ### Error handling
@@ -109,23 +93,27 @@ promiseWorker.postMessage(null).then(function (message) {
109
93
  Any thrown errors or asynchronous rejections during a response will be propagated as a rejected promise. For instance:
110
94
 
111
95
  ```js
112
- promiseWorker.register(function(message) {
96
+ promiseWorker.register((message) => {
113
97
  throw new Error("naughty!");
114
98
  });
115
99
  ```
116
100
 
117
101
  ```js
118
- promiseWorker.postMessage("whoops").catch(function(err) {
119
- console.log(err.message); // 'naughty!'
120
- });
102
+ try {
103
+ await promiseWorker.postMessage("whoops");
104
+ } catch (error) {
105
+ console.log(error.message); // 'naughty!'
106
+ }
121
107
  ```
122
108
 
123
109
  But what about errors in the worker that are _not_ during a response? (Errors in the host, you can handle as you would normally do.)
124
110
 
125
- For a Web Worker, we could just use [the normal `error` event](https://developer.mozilla.org/en-US/docs/Web/API/AbstractWorker/onerror) and be fine. But for a Shared Worker, that is not the case, because browsers seem to handle errors inside Shared Workers differently (currently Firefox seems to send the normal `error` event to all hosts, but [Chrome does not](https://bugs.chromium.org/p/chromium/issues/detail?id=105001)). Therefore, promise-worker-bi includes a unified API that works in Web Workers and Shared Workers.
111
+ For a Web Worker, we could just use [the normal `error` event](https://developer.mozilla.org/en-US/docs/Web/API/AbstractWorker/onerror) and be fine. But for a Shared Worker, that is not the case, because browsers seem to handle errors inside Shared Workers differently (currently Firefox seems to send the normal `error` event to all hosts, but [Chrome does not](https://bugs.chromium.org/p/chromium/issues/detail?id=105001)).
112
+
113
+ Therefore, promise-worker-bi includes a unified API that works in Web Workers and Shared Workers. Include some code like this in your host:
126
114
 
127
115
  ```js
128
- promiseWorker.registerError(function(err) {
116
+ promiseWorker.registerError((error) => {
129
117
  console.log("Error inside worker!", err);
130
118
  });
131
119
  ```
@@ -141,21 +129,17 @@ If you use a source map for your worker script, this will not be reflected in th
141
129
  If you need to send messages of multiple types to the worker, just add some type information to the message you send:
142
130
 
143
131
  ```js
144
- promiseWorker
145
- .postMessage({
146
- type: "en"
147
- })
148
- .then(/* ... */);
149
-
150
- promiseWorker
151
- .postMessage({
152
- type: "fr"
153
- })
154
- .then(/* ... */);
132
+ const response1 = await promiseWorker.postMessage({
133
+ type: "en",
134
+ });
135
+
136
+ const response2 = await promiseWorker.postMessage({
137
+ type: "en",
138
+ });
155
139
  ```
156
140
 
157
141
  ```js
158
- promiseWorker.register(function(message) {
142
+ promiseWorker.register((message) => {
159
143
  if (message.type === "en") {
160
144
  return "Hello!";
161
145
  } else if (message.type === "fr") {
@@ -174,19 +158,18 @@ Here's an example:
174
158
  // main.js
175
159
  import { PWBHost } from "promise-worker-bi";
176
160
 
177
- var worker = new SharedWorker("worker.js");
178
- var promiseWorker = new PWBHost(worker);
161
+ const worker = new SharedWorker("worker.js");
162
+ const promiseWorker = new PWBHost(worker);
179
163
 
180
- promiseWorker.register(function(message) {
164
+ promiseWorker.register((message) => {
181
165
  console.log(message);
182
166
  });
183
167
 
184
168
  // setTimeout is just to give you enough time to open main.js and main2.js in
185
169
  // two separate tabs.
186
- setTimeout(function() {
187
- promiseWorker.postMessage("broadcast").then(function(response) {
188
- console.log("Echoed response:", response);
189
- });
170
+ setTimeout(async () => {
171
+ const response = await promiseWorker.postMessage("broadcast");
172
+ console.log("Echoed response:", response);
190
173
  }, 1000);
191
174
  ```
192
175
 
@@ -194,19 +177,18 @@ setTimeout(function() {
194
177
  // main2.js
195
178
  import { PWBHost } from "promise-worker-bi";
196
179
 
197
- var worker = new SharedWorker("worker.js");
198
- var promiseWorker = new PWBHost(worker);
180
+ const worker = new SharedWorker("worker.js");
181
+ const promiseWorker = new PWBHost(worker);
199
182
 
200
- promiseWorker.register(function(message) {
183
+ promiseWorker.register((message) => {
201
184
  console.log(message);
202
185
  });
203
186
 
204
187
  // setTimeout is just to give you enough time to open main.js and main2.js in
205
188
  // two separate tabs.
206
- setTimeout(function() {
207
- promiseWorker.postMessage("just this tab").then(function(response) {
208
- console.log("Echoed response:", response);
209
- });
189
+ setTimeout(() => {
190
+ const reponse = await promiseWorker.postMessage("just this tab");
191
+ console.log("Echoed response:", response);
210
192
  }, 2000);
211
193
  ```
212
194
 
@@ -214,13 +196,13 @@ setTimeout(function() {
214
196
  // worker.js
215
197
  import { PWBWorker } from "promise-worker-bi";
216
198
 
217
- var promiseWorker = new PWBWorker();
199
+ const promiseWorker = new PWBWorker();
218
200
 
219
- promiseWorker.register(function(message, hostID) {
201
+ promiseWorker.register((message, hostID) => {
220
202
  if (message === "broadcast") {
221
203
  promiseWorker.postMessage("to all tabs");
222
204
  } else {
223
- promiseWorker.postMessage("hello host " + hostID, hostID);
205
+ promiseWorker.postMessage(`hello host ${hostID}`, hostID);
224
206
  }
225
207
 
226
208
  return message;
@@ -240,8 +222,43 @@ And this in the second tab:
240
222
 
241
223
  (If you open main2.js first, "hello host 1" will instead be "hello host 0".)
242
224
 
225
+ ### Transferable objects
226
+
227
+ It is possible to [transfer certain types of objects](https://developer.mozilla.org/en-US/docs/Glossary/Transferable_objects) from host to worker or from worker to host. The syntax is similar to how it works with [a normal `postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage), where an array of the objects to be transferred is added as an additional parameter.
228
+
229
+ One tricky thing - because `promiseWorker.postMessage` already has a second argument for specifying an optional `hostID` value fo sending a message from a shared worker to a specific host, the transferables argument is the third argument:
230
+
231
+ ```js
232
+ const buffer = new ArrayBuffer(1);
233
+ promiseWorker.postMessage(buffer, hostID, [buffer]);
234
+ ```
235
+
236
+ From host to worker, the `hostID` argument doesn't do anything, so in most situations (host -> worker, web worker -> host, shared worker -> all hosts) you can pass `undefined` as the second argument:
237
+
238
+ ```js
239
+ const buffer = new ArrayBuffer(1);
240
+ promiseWorker.postMessage(buffer, undefined, [buffer]);
241
+ ```
242
+
243
+ If you want to respond to a message by sending a transferable object back, such as if you want to send an object a worker for processing and then return it to the host, you can do it like this, in either the worker or host:
244
+
245
+ ```js
246
+ promiseWorker.register(async (message) => {
247
+ const processedMessage = await processMessage(message);
248
+
249
+ return {
250
+ message: processedMessage,
251
+ _PWB_TRANSFER: [processedMessage.someTransferableProprty],
252
+ };
253
+ });
254
+ ```
255
+
256
+ That `_PWB_TRANSFER` property is used internally by promise-worker-bi under the assumption that no normal object in your application would have a property with that name.
257
+
243
258
  ## Browser support
244
259
 
260
+ In theory it should work in:
261
+
245
262
  - Chrome
246
263
  - Firefox
247
264
  - Safari 8+
@@ -250,8 +267,6 @@ And this in the second tab:
250
267
  - iOS 8+
251
268
  - Android 4.4+
252
269
 
253
- Old browsers will need Map and Promise polyfills.
254
-
255
270
  There used to be automated tests in various browsers via [zuul](https://github.com/defunctzombie/zuul) and Sauce Labs, but it suffered bit rot and I could no longer get it to work consistently (PRs welcome!). Currently, `yarn test` uses [Karma](https://karma-runner.github.io/) to run tests in whatever versions of Chrome and Firefox you have installed.
256
271
 
257
272
  ## API
@@ -286,8 +301,12 @@ Register a message handler wherever you will be receiving messages: in the worke
286
301
 
287
302
  The `hostID` parameter is only defined inside a shared worker, in which case it is a unique number identifying the host that the message came from.
288
303
 
289
- #### `promiseWorker.postMessage(message: any, hostID?: number): Promise<any>`
304
+ The return value of the callback function (shown above as `any`) must resolve to something [structured cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
305
+
306
+ If you want to [transfer an object](https://developer.mozilla.org/en-US/docs/Glossary/Transferable_objects) in the return value of the callback, then the return type should be `{ message: any, transfer: Transferable[] }` rather than just `any`.
307
+
308
+ #### `promiseWorker.postMessage(message: any, hostID?: number, transfer?: Transferable[]): Promise<any>`
290
309
 
291
- Send a message to the browser or worker and return a Promise.
310
+ Send a message to the browser or worker and return a Promise. `message` must resolve to something [structured cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
292
311
 
293
312
  The `hostID` parameter is only meaningful when sending a message from a shared worker. If you leave it out, it will send the message to all hosts. If you include it, it will send the message only to that specific host. You can get the `hostID` from the `promiseWorker.register` function described above.
package/dist/commonjs.js CHANGED
@@ -21,23 +21,23 @@ const toFakeError = error => {
21
21
  if (typeof error.stack === "string") {
22
22
  fakeError.stack = error.stack;
23
23
  } // These are non-standard properties, I think only in some versions of Firefox
24
- // @ts-ignore
24
+ // @ts-expect-error
25
25
 
26
26
 
27
27
  if (typeof error.fileName === "string") {
28
- // @ts-ignore
28
+ // @ts-expect-error
29
29
  fakeError.fileName = error.fileName;
30
- } // @ts-ignore
30
+ } // @ts-expect-error
31
31
 
32
32
 
33
33
  if (typeof error.columnNumber === "number") {
34
- // @ts-ignore
34
+ // @ts-expect-error
35
35
  fakeError.columnNumber = error.columnNumber;
36
- } // @ts-ignore
36
+ } // @ts-expect-error
37
37
 
38
38
 
39
39
  if (typeof error.lineNumber === "number") {
40
- // @ts-ignore
40
+ // @ts-expect-error
41
41
  fakeError.lineNumber = error.lineNumber;
42
42
  }
43
43
 
@@ -63,9 +63,9 @@ const logError = err => {
63
63
  class PWBBase {
64
64
  constructor() {
65
65
  // console.log('constructor', worker);
66
- this._callbacks = new Map();
66
+ this._callbacks = new Map(); // eslint-disable-next-line @typescript-eslint/no-empty-function
67
67
 
68
- this._queryCallback = () => {}; // @ts-ignore
68
+ this._queryCallback = () => {}; // @ts-expect-error
69
69
 
70
70
 
71
71
  this._onMessage = this._onMessage.bind(this);
@@ -74,13 +74,9 @@ class PWBBase {
74
74
  register(cb) {
75
75
  // console.log('register', cb);
76
76
  this._queryCallback = cb;
77
- } // eslint-disable-next-line
77
+ } // From worker, 2nd param could be hostID if sending to specific host. From UI, 2nd param could be an array of transferable objects
78
78
 
79
79
 
80
- _postMessage(obj, targetHostID) {
81
- throw new Error("Not implemented");
82
- }
83
-
84
80
  _postResponse(messageID, error, result, hostID) {
85
81
  // console.log('_postResponse', messageID, error, result);
86
82
  if (error) {
@@ -88,7 +84,12 @@ class PWBBase {
88
84
 
89
85
  this._postMessage([MSGTYPE_RESPONSE, messageID, toFakeError(error)], hostID);
90
86
  } else {
91
- this._postMessage([MSGTYPE_RESPONSE, messageID, null, result], hostID);
87
+ // Hackily identify when message contains transferable objects
88
+ if (typeof result === "object" && result !== null && result.hasOwnProperty("message") && result.hasOwnProperty("_PWB_TRANSFER")) {
89
+ this._postMessage([MSGTYPE_RESPONSE, messageID, null, result.message], hostID, result._PWB_TRANSFER);
90
+ } else {
91
+ this._postMessage([MSGTYPE_RESPONSE, messageID, null, result], hostID);
92
+ }
92
93
  }
93
94
  }
94
95
 
@@ -189,16 +190,16 @@ class PWBHost extends PWBBase {
189
190
  // console.log(worker instanceof Worker);
190
191
  //
191
192
  // So instead, let's do this test for worker.port which only exists on shared workers.
192
- // @ts-ignore
193
+ // @ts-expect-error
193
194
 
194
195
  if (worker.port === undefined) {
195
- this._workerType = "Worker"; // @ts-ignore
196
+ this._workerType = "Worker"; // @ts-expect-error
196
197
 
197
198
  worker.addEventListener("message", this._onMessage);
198
199
  } else {
199
- this._workerType = "SharedWorker"; // @ts-ignore - it doesn't know if _worker is Worker or SharedWorker, but I do
200
+ this._workerType = "SharedWorker"; // @ts-expect-error - it doesn't know if _worker is Worker or SharedWorker, but I do
200
201
 
201
- worker.port.addEventListener("message", this._onMessage); // @ts-ignore - it doesn't know if _worker is Worker or SharedWorker, but I do
202
+ worker.port.addEventListener("message", this._onMessage); // @ts-expect-error - it doesn't know if _worker is Worker or SharedWorker, but I do
202
203
 
203
204
  worker.port.start(); // Handle tab close. This isn't perfect, but there is no perfect method
204
205
  // http://stackoverflow.com/q/13662089/786644 and this should work like
@@ -228,21 +229,21 @@ class PWBHost extends PWBBase {
228
229
  });
229
230
  }
230
231
 
231
- _postMessage(obj) {
232
- // console.log('_postMessage', obj);
232
+ _postMessage(obj, _hostID, transfer) {
233
+ // console.log('_postMessage', obj, _hostID, transfer);
233
234
  if (this._workerType === "Worker") {
234
- // @ts-ignore - it doesn't know if _worker is Worker or SharedWorker, but I do
235
- this._worker.postMessage(obj);
235
+ // @ts-expect-error - it doesn't know if _worker is Worker or SharedWorker, but I do
236
+ this._worker.postMessage(obj, transfer);
236
237
  } else if (this._workerType === "SharedWorker") {
237
- // @ts-ignore - it doesn't know if _worker is Worker or SharedWorker, but I do
238
- this._worker.port.postMessage(obj);
238
+ // @ts-expect-error - it doesn't know if _worker is Worker or SharedWorker, but I do
239
+ this._worker.port.postMessage(obj, transfer);
239
240
  } else {
240
241
  throw new Error("WTF");
241
242
  }
242
243
  }
243
244
 
244
- postMessage(userMessage) {
245
- // console.log('postMessage', userMessage, targetHostID);
245
+ postMessage(userMessage, _hostID, transfer) {
246
+ // console.log('postMessage', userMessage, _hostID, transfer);
246
247
  const actuallyPostMessage = (resolve, reject) => {
247
248
  const messageID = messageIDs;
248
249
  messageIDs += 1;
@@ -256,7 +257,7 @@ class PWBHost extends PWBBase {
256
257
  }
257
258
  });
258
259
 
259
- this._postMessage(messageToSend);
260
+ this._postMessage(messageToSend, undefined, transfer);
260
261
  };
261
262
 
262
263
  return new Promise((resolve, reject) => {
@@ -320,12 +321,12 @@ class PWBWorker extends PWBBase {
320
321
  this._hosts = new Map();
321
322
  this._maxHostID = -1;
322
323
 
323
- if ( // @ts-ignore
324
- typeof SharedWorkerGlobalScope !== "undefined" && // @ts-ignore
324
+ if ( // @ts-expect-error
325
+ typeof SharedWorkerGlobalScope !== "undefined" && // @ts-expect-error
325
326
  self instanceof SharedWorkerGlobalScope) {
326
327
  this._workerType = "SharedWorker";
327
328
  self.addEventListener("connect", e => {
328
- // @ts-ignore
329
+ // @ts-expect-error
329
330
  const port = e.ports[0];
330
331
  port.addEventListener("message", e2 => this._onMessage(e2)); // eslint-disable-line no-undef
331
332
 
@@ -365,7 +366,7 @@ class PWBWorker extends PWBBase {
365
366
  }
366
367
  }
367
368
 
368
- _postMessage(obj, targetHostID) {
369
+ _postMessage(obj, targetHostID, transfer) {
369
370
  // console.log('_postMessage', obj, targetHostID);
370
371
  if (this._workerType === "SharedWorker") {
371
372
  // If targetHostID has been deleted, this will do nothing, which is fine I think
@@ -373,18 +374,19 @@ class PWBWorker extends PWBBase {
373
374
  port
374
375
  }, hostID) => {
375
376
  if (targetHostID === undefined || targetHostID === hostID) {
376
- port.postMessage(obj);
377
+ // @ts-expect-error TypeScript thinks transfer can't be undefined
378
+ port.postMessage(obj, transfer);
377
379
  }
378
380
  });
379
381
  } else if (this._workerType === "Worker") {
380
- // @ts-ignore
381
- self.postMessage(obj);
382
+ // @ts-expect-error TypeScript thinks self is window, which has a different postMessage call signature. In a worker, this is correct.
383
+ self.postMessage(obj, transfer);
382
384
  } else {
383
385
  throw new Error("WTF");
384
386
  }
385
387
  }
386
388
 
387
- postMessage(userMessage, targetHostID) {
389
+ postMessage(userMessage, targetHostID, transfer) {
388
390
  // console.log('postMessage', userMessage, targetHostID);
389
391
  const actuallyPostMessage = (resolve, reject) => {
390
392
  const messageID = messageIDs;
@@ -399,7 +401,7 @@ class PWBWorker extends PWBBase {
399
401
  }
400
402
  });
401
403
 
402
- this._postMessage(messageToSend, targetHostID);
404
+ this._postMessage(messageToSend, targetHostID, transfer);
403
405
  };
404
406
 
405
407
  return new Promise((resolve, reject) => {