1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | (function (factory) {
|
14 | if (typeof module === "object" && typeof module.exports === "object") {
|
15 | var v = factory(require, exports);
|
16 | if (v !== undefined) module.exports = v;
|
17 | }
|
18 | else if (typeof define === "function" && define.amd) {
|
19 | define(["require", "exports"], factory);
|
20 | }
|
21 | else {factory([], self.MessageChannelAdapter={});}
|
22 | })(function (require, exports) {
|
23 | "use strict";
|
24 | Object.defineProperty(exports, "__esModule", { value: true });
|
25 | function wrap(smc, id = null) {
|
26 | const { port1, port2 } = new MessageChannel();
|
27 | hookup(port2, smc, id);
|
28 | return port1;
|
29 | }
|
30 | exports.wrap = wrap;
|
31 | function hookup(internalPort, smc, id = null) {
|
32 | internalPort.onmessage = (event) => {
|
33 | const msg = event.data;
|
34 | const messageChannels = Array.from(findMessageChannels(event.data));
|
35 | for (const messageChannel of messageChannels) {
|
36 | const id = generateUID();
|
37 | const channel = replaceProperty(msg, messageChannel, id);
|
38 | hookup(channel, smc, id);
|
39 | }
|
40 | const payload = JSON.stringify({ id, msg, messageChannels });
|
41 | smc.send(payload);
|
42 | };
|
43 | smc.addEventListener("message", (event) => {
|
44 | let data = {};
|
45 | try {
|
46 | data = JSON.parse(event.data);
|
47 | }
|
48 | catch (e) {
|
49 | return;
|
50 | }
|
51 | if (id && id !== data.id)
|
52 | return;
|
53 | if (!id && data.id)
|
54 | return;
|
55 | const mcs = data.messageChannels.map(messageChannel => {
|
56 | const id = messageChannel.reduce((obj, key) => obj[key], data.msg);
|
57 | const port = wrap(smc, id);
|
58 | replaceProperty(data.msg, messageChannel, port);
|
59 | return port;
|
60 | });
|
61 | internalPort.postMessage(data.msg, mcs);
|
62 | });
|
63 | }
|
64 | function replaceProperty(obj, path, newVal) {
|
65 | for (const key of path.slice(0, -1))
|
66 | obj = obj[key];
|
67 | const key = path[path.length - 1];
|
68 | const orig = obj[key];
|
69 | obj[key] = newVal;
|
70 | return orig;
|
71 | }
|
72 | function* findMessageChannels(obj, path = []) {
|
73 | if (!obj)
|
74 | return;
|
75 | if (typeof obj === "string")
|
76 | return;
|
77 | if (obj instanceof MessagePort) {
|
78 | yield path.slice();
|
79 | return;
|
80 | }
|
81 | for (const key of Object.keys(obj)) {
|
82 | path.push(key);
|
83 | yield* findMessageChannels(obj[key], path);
|
84 | path.pop();
|
85 | }
|
86 | }
|
87 | function hex4() {
|
88 | return Math.floor((1 + Math.random()) * 0x10000)
|
89 | .toString(16)
|
90 | .substring(1);
|
91 | }
|
92 | const bits = 128;
|
93 | function generateUID() {
|
94 | return new Array(bits / 16)
|
95 | .fill(0)
|
96 | .map(_ => hex4())
|
97 | .join("");
|
98 | }
|
99 | });
|