UNPKG

1.65 kBPlain TextView Raw
1/**
2 * Copyright 2019 Google Inc. All Rights Reserved.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 * http://www.apache.org/licenses/LICENSE-2.0
7 * Unless required by applicable law or agreed to in writing, software
8 * distributed under the License is distributed on an "AS IS" BASIS,
9 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 * See the License for the specific language governing permissions and
11 * limitations under the License.
12 */
13
14import { Endpoint } from "./protocol.js";
15
16export interface NodeEndpoint {
17 postMessage(message: any, transfer?: any[]): void;
18 on(
19 type: string,
20 listener: EventListenerOrEventListenerObject,
21 options?: {}
22 ): void;
23 off(
24 type: string,
25 listener: EventListenerOrEventListenerObject,
26 options?: {}
27 ): void;
28 start?: () => void;
29}
30
31export default function nodeEndpoint(nep: NodeEndpoint): Endpoint {
32 const listeners = new WeakMap();
33 return {
34 postMessage: nep.postMessage.bind(nep),
35 addEventListener: (_, eh) => {
36 const l = (data: any) => {
37 if ("handleEvent" in eh) {
38 eh.handleEvent({ data } as MessageEvent);
39 } else {
40 eh({ data } as MessageEvent);
41 }
42 };
43 nep.on("message", l);
44 listeners.set(eh, l);
45 },
46 removeEventListener: (_, eh) => {
47 const l = listeners.get(eh);
48 if (!l) {
49 return;
50 }
51 nep.off("message", l);
52 listeners.delete(eh);
53 },
54 start: nep.start && nep.start.bind(nep)
55 };
56}