Full Code of GoogleChromeLabs/comlink for AI

main 114a4a6448a8 cached
57 files
114.5 KB
29.3k tokens
99 symbols
1 requests
Download .txt
Repository: GoogleChromeLabs/comlink
Branch: main
Commit: 114a4a6448a8
Files: 57
Total size: 114.5 KB

Directory structure:
gitextract_piinu2uq/

├── .gitignore
├── .husky/
│   └── pre-commit
├── .travis.yml
├── CHANGELOG.md
├── CODEOWNERS
├── CONTRIBUTING
├── CONTRIBUTORS
├── Dockerfile
├── LICENSE
├── README.md
├── docs/
│   ├── examples/
│   │   ├── 01-simple-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 02-callback-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 03-classes-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 04-eventlistener-example/
│   │   │   ├── README.md
│   │   │   ├── event.transferhandler.js
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 05-serviceworker-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 06-node-example/
│   │   │   ├── main.mjs
│   │   │   └── worker.mjs
│   │   ├── 07-sharedworker-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   └── 99-nonworker-examples/
│   │       └── iframes/
│   │           ├── README.md
│   │           ├── iframe.html
│   │           └── index.html
│   └── index.html
├── karma.conf.js
├── package.json
├── renovate.json
├── rollup.config.mjs
├── src/
│   ├── comlink.ts
│   ├── node-adapter.ts
│   └── protocol.ts
├── structured-clone-table.md
├── tests/
│   ├── cross-origin.comlink.test.js
│   ├── fixtures/
│   │   ├── attack-iframe.html
│   │   ├── iframe.html
│   │   ├── two-way-iframe.html
│   │   └── worker.js
│   ├── iframe.comlink.test.js
│   ├── node/
│   │   ├── main.mjs
│   │   └── worker.mjs
│   ├── same_window.comlink.test.js
│   ├── tsconfig.json
│   ├── two-way-iframe.comlink.test.js
│   ├── type-checks.ts
│   └── worker.comlink.test.js
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.pem
*.swp
node_modules
*.bak
dist
.*_cache*
package-lock.json


================================================
FILE: .husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm test


================================================
FILE: .travis.yml
================================================
sudo: required

services:
  - docker

script:
  - docker build -t comlink .
  - docker run --rm -v `pwd`:/usr/src comlink


================================================
FILE: CHANGELOG.md
================================================
# v3 -> v4

- Added support for NodeJS 11+ workers
- `Comlink.proxy()` is now called `Comlink.wrap()`
- `Comlink.proxyValue()` is now called `Comlink.proxy()`
- Transferable values are _not_ transferred by default anymore. They need to be wrapped with `Comlink.transfer()`
- Rewrote TypeScript types
- New folder structure in the GitHub repo and in the npm module


================================================
FILE: CODEOWNERS
================================================
@surma


================================================
FILE: CONTRIBUTING
================================================
Want to contribute? Great! First, read this page (including the small print at the end).

### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement]
(https://cla.developers.google.com/about/google-individual)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.

### Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.

### The small print
Contributions made by corporations are covered by a different agreement than
the one above, the
[Software Grant and Corporate Contributor License Agreement]
(https://cla.developers.google.com/about/google-corporate).


================================================
FILE: CONTRIBUTORS
================================================
# People who have agreed to one of the CLAs and can contribute patches.
# The AUTHORS file lists the copyright holders; this file
# lists people.  For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# https://developers.google.com/open-source/cla/individual
# https://developers.google.com/open-source/cla/corporate
#
# Names should be added to this file as:
#     Name <email address>
Surma <surma@google.com>


================================================
FILE: Dockerfile
================================================
FROM selenium/node-chrome:latest@sha256:31be7ba7ebe6db9f9b266c10fc5f6fce7568791a6ade91b6b6d20a29a988ef5b

USER root

RUN apt-get update -qqy \
  && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \
  && rm /bin/sh && ln -s /bin/bash /bin/sh \
  && chown seluser /usr/local

ENV NVM_DIR /usr/local/nvm
RUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash \
  && source $NVM_DIR/nvm.sh \
  && nvm install v11

ENV CHROME_BIN /opt/google/chrome/chrome
ENV INSIDE_DOCKER=1

WORKDIR /usr/src
ENTRYPOINT source $NVM_DIR/nvm.sh && npm i && npm test


================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2017 Google Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: README.md
================================================
# Comlink

Comlink makes [WebWorkers][webworker] enjoyable. Comlink is a **tiny library (1.1kB)**, that removes the mental barrier of thinking about `postMessage` and hides the fact that you are working with workers.

At a more abstract level it is an RPC implementation for `postMessage` and [ES6 Proxies][es6 proxy].

```
$ npm install --save comlink
```

![Comlink in action](https://user-images.githubusercontent.com/234957/54164510-cdab2d80-4454-11e9-92d0-7356aa6c5746.png)

## Browsers support & bundle size

![Chrome 56+](https://img.shields.io/badge/Chrome-56+-green.svg?style=flat-square)
![Edge 15+](https://img.shields.io/badge/Edge-15+-green.svg?style=flat-square)
![Firefox 52+](https://img.shields.io/badge/Firefox-52+-green.svg?style=flat-square)
![Opera 43+](https://img.shields.io/badge/Opera-43+-green.svg?style=flat-square)
![Safari 10.1+](https://img.shields.io/badge/Safari-10.1+-green.svg?style=flat-square)
![Samsung Internet 6.0+](https://img.shields.io/badge/Samsung_Internet-6.0+-green.svg?style=flat-square)

Browsers without [ES6 Proxy] support can use the [proxy-polyfill].

**Size**: ~2.5k, ~1.2k gzip’d, ~1.1k brotli’d

## Introduction

On mobile phones, and especially on low-end mobile phones, it is important to keep the main thread as idle as possible so it can respond to user interactions quickly and provide a jank-free experience. **The UI thread ought to be for UI work only**. WebWorkers are a web API that allow you to run code in a separate thread. To communicate with another thread, WebWorkers offer the `postMessage` API. You can send JavaScript objects as messages using `myWorker.postMessage(someObject)`, triggering a `message` event inside the worker.

Comlink turns this messaged-based API into a something more developer-friendly by providing an RPC implementation: Values from one thread can be used within the other thread (and vice versa) just like local values.

## Examples

### [Running a simple function](./docs/examples/01-simple-example)

**main.js**

```javascript
import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
async function init() {
  const worker = new Worker("worker.js");
  // WebWorkers use `postMessage` and therefore work with Comlink.
  const obj = Comlink.wrap(worker);
  alert(`Counter: ${await obj.counter}`);
  await obj.inc();
  alert(`Counter: ${await obj.counter}`);
}
init();
```

**worker.js**

```javascript
importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

Comlink.expose(obj);
```

### [Callbacks](./docs/examples/02-callback-example)

**main.js**

```javascript
import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
// import * as Comlink from "../../../dist/esm/comlink.mjs";
function callback(value) {
  alert(`Result: ${value}`);
}
async function init() {
  const remoteFunction = Comlink.wrap(new Worker("worker.js"));
  await remoteFunction(Comlink.proxy(callback));
}
init();
```

**worker.js**

```javascript
importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

async function remoteFunction(cb) {
  await cb("A string from a worker");
}

Comlink.expose(remoteFunction);
```

### [`SharedWorker`](./docs/examples/07-sharedworker-example)

When using Comlink with a [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) you have to:

1. Use the [`port`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/port) property, of the `SharedWorker` instance, when calling `Comlink.wrap`.
2. Call `Comlink.expose` within the [`onconnect`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorkerGlobalScope/onconnect) callback of the shared worker.

**Pro tip:** You can access DevTools for any shared worker currently running in Chrome by going to: **chrome://inspect/#workers**

**main.js**

```javascript
import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
async function init() {
  const worker = new SharedWorker("worker.js");
  /**
   * SharedWorkers communicate via the `postMessage` function in their `port` property.
   * Therefore you must use the SharedWorker's `port` property when calling `Comlink.wrap`.
   */
  const obj = Comlink.wrap(worker.port);
  alert(`Counter: ${await obj.counter}`);
  await obj.inc();
  alert(`Counter: ${await obj.counter}`);
}
init();
```

**worker.js**

```javascript
importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

/**
 * When a connection is made into this shared worker, expose `obj`
 * via the connection `port`.
 */
onconnect = function (event) {
  const port = event.ports[0];

  Comlink.expose(obj, port);
};

// Single line alternative:
// onconnect = (e) => Comlink.expose(obj, e.ports[0]);
```

**For additional examples, please see the [docs/examples](./docs/examples) directory in the project.**

## API

### `Comlink.wrap(endpoint)` and `Comlink.expose(value, endpoint?, allowedOrigins?)`

Comlink’s goal is to make _exposed_ values from one thread available in the other. `expose` exposes `value` on `endpoint`, where `endpoint` is a [`postMessage`-like interface][endpoint] and `allowedOrigins` is an array of
RegExp or strings defining which origins should be allowed access (defaults to special case of `['*']` for all origins).

`wrap` wraps the _other_ end of the message channel and returns a proxy. The proxy will have all properties and functions of the exposed value, but access and invocations are inherently asynchronous. This means that a function that returns a number will now return _a promise_ for a number. **As a rule of thumb: If you are using the proxy, put `await` in front of it.** Exceptions will be caught and re-thrown on the other side.

### `Comlink.transfer(value, transferables)` and `Comlink.proxy(value)`

By default, every function parameter, return value and object property value is copied, in the sense of [structured cloning]. Structured cloning can be thought of as deep copying, but has some limitations. See [this table][structured clone table] for details.

If you want a value to be transferred rather than copied — provided the value is or contains a [`Transferable`][transferable] — you can wrap the value in a `transfer()` call and provide a list of transferable values:

```js
const data = new Uint8Array([1, 2, 3, 4, 5]);
await myProxy.someFunction(Comlink.transfer(data, [data.buffer]));
```

Lastly, you can use `Comlink.proxy(value)`. When using this Comlink will neither copy nor transfer the value, but instead send a proxy. Both threads now work on the same value. This is useful for callbacks, for example, as functions are neither structured cloneable nor transferable.

```js
myProxy.onready = Comlink.proxy((data) => {
  /* ... */
});
```

### Transfer handlers and event listeners

It is common that you want to use Comlink to add an event listener, where the event source is on another thread:

```js
button.addEventListener("click", myProxy.onClick.bind(myProxy));
```

While this won’t throw immediately, `onClick` will never actually be called. This is because [`Event`][event] is neither structured cloneable nor transferable. As a workaround, Comlink offers transfer handlers.

Each function parameter and return value is given to _all_ registered transfer handlers. If one of the event handler signals that it can process the value by returning `true` from `canHandle()`, it is now responsible for serializing the value to structured cloneable data and for deserializing the value. A transfer handler has be set up on _both sides_ of the message channel. Here’s an example transfer handler for events:

```js
Comlink.transferHandlers.set("EVENT", {
  canHandle: (obj) => obj instanceof Event,
  serialize: (ev) => {
    return [
      {
        target: {
          id: ev.target.id,
          classList: [...ev.target.classList],
        },
      },
      [],
    ];
  },
  deserialize: (obj) => obj,
});
```

Note that this particular transfer handler won’t create an actual `Event`, but just an object that has the `event.target.id` and `event.target.classList` property. Often, this is enough. If not, the transfer handler can be easily augmented to provide all necessary data.

### `Comlink.releaseProxy`

Every proxy created by Comlink has the `[releaseProxy]()` method.
Calling it will detach the proxy and the exposed object from the message channel, allowing both ends to be garbage collected.

```js
const proxy = Comlink.wrap(port);
// ... use the proxy ...
proxy[Comlink.releaseProxy]();
```

If the browser supports the [WeakRef proposal], `[releaseProxy]()` will be called automatically when the proxy created by `wrap()` gets garbage collected.

### `Comlink.finalizer`

If an exposed object has a property `[Comlink.finalizer]`, the property will be invoked as a function when the proxy is being released. This can happen either through a manual invocation of `[releaseProxy]()` or automatically during garbage collection if the runtime supports the [WeakRef proposal] (see `Comlink.releaseProxy` above). Note that when the finalizer function is invoked, the endpoint is closed and no more communication can happen.

### `Comlink.createEndpoint`

Every proxy created by Comlink has the `[createEndpoint]()` method.
Calling it will return a new `MessagePort`, that has been hooked up to the same object as the proxy that `[createEndpoint]()` has been called on.

```js
const port = myProxy[Comlink.createEndpoint]();
const newProxy = Comlink.wrap(port);
```

### `Comlink.windowEndpoint(window, context = self, targetOrigin = "*")`

Windows and Web Workers have a slightly different variants of `postMessage`. If you want to use Comlink to communicate with an iframe or another window, you need to wrap it with `windowEndpoint()`.

`window` is the window that should be communicate with. `context` is the `EventTarget` on which messages _from_ the `window` can be received (often `self`). `targetOrigin` is passed through to `postMessage` and allows to filter messages by origin. For details, see the documentation for [`Window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).

For a usage example, take a look at the non-worker examples in the `docs` folder.

## TypeScript

Comlink does provide TypeScript types. When you `expose()` something of type `T`, the corresponding `wrap()` call will return something of type `Comlink.Remote<T>`. While this type has been battle-tested over some time now, it is implemented on a best-effort basis. There are some nuances that are incredibly hard if not impossible to encode correctly in TypeScript’s type system. It _may_ sometimes be necessary to force a certain type using `as unknown as <type>`.

## Node

Comlink works with Node’s [`worker_threads`][worker_threads] module. Take a look at the example in the `docs` folder.

[webworker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
[umd]: https://github.com/umdjs/umd
[transferable]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects
[messageport]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
[examples]: https://github.com/GoogleChromeLabs/comlink/tree/master/docs/examples
[dist]: https://github.com/GoogleChromeLabs/comlink/tree/master/dist
[delivrjs]: https://cdn.jsdelivr.net/
[es6 proxy]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
[proxy-polyfill]: https://github.com/GoogleChrome/proxy-polyfill
[endpoint]: src/protocol.ts
[structured cloning]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[structured clone table]: structured-clone-table.md
[event]: https://developer.mozilla.org/en-US/docs/Web/API/Event
[worker_threads]: https://nodejs.org/api/worker_threads.html
[weakref proposal]: https://github.com/tc39/proposal-weakrefs

## Additional Resources

- [Simplify Web Worker code with Comlink](https://davidea.st/articles/comlink-simple-web-worker)

---

License Apache-2.0


================================================
FILE: docs/examples/01-simple-example/README.md
================================================
This example shows how to setup Comlink between a website and a worker.


================================================
FILE: docs/examples/01-simple-example/index.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../dist/esm/comlink.mjs";

  async function init() {
    const worker = new Worker("worker.js");
    // WebWorkers use `postMessage` and therefore work with Comlink.
    const obj = Comlink.wrap(worker);

    alert(`Counter: ${await obj.counter}`);
    await obj.inc();
    alert(`Counter: ${await obj.counter}`);
  }

  init();
</script>


================================================
FILE: docs/examples/01-simple-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

Comlink.expose(obj);


================================================
FILE: docs/examples/02-callback-example/README.md
================================================
This example shows how to pass callbacks.


================================================
FILE: docs/examples/02-callback-example/index.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../dist/esm/comlink.mjs";

  function callback(value) {
    alert(`Result: ${value}`);
  }

  async function init() {
    const remoteFunction = Comlink.wrap(new Worker("worker.js"));
    await remoteFunction(Comlink.proxy(callback));
  }

  init();
</script>


================================================
FILE: docs/examples/02-callback-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

async function remoteFunction(cb) {
  await cb("A string from a worker");
}

Comlink.expose(remoteFunction);


================================================
FILE: docs/examples/03-classes-example/README.md
================================================
This example shows how to export and use classes.


================================================
FILE: docs/examples/03-classes-example/index.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../dist/esm/comlink.mjs";

  let instance1, instance2;
  async function showState() {
    alert(`instance1.counter = ${await instance1.counter},
      instance2.counter = ${await instance2.counter}`);
  }

  async function init() {
    const MyClass = Comlink.wrap(new Worker("worker.js"));
    instance1 = await new MyClass();
    instance2 = await new MyClass(42);
    await showState();
    await instance1.increment();
    await instance2.increment(23);
    await showState();
  }

  init();
</script>


================================================
FILE: docs/examples/03-classes-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

class MyClass {
  constructor(init = 0) {
    console.log(init);
    this._counter = init;
  }

  get counter() {
    return this._counter;
  }

  increment(delta = 1) {
    this._counter += delta;
  }
}

Comlink.expose(MyClass);


================================================
FILE: docs/examples/04-eventlistener-example/README.md
================================================
This example shows how a simple `TransferHandler` can allow to use remote event listeners or event targets.


================================================
FILE: docs/examples/04-eventlistener-example/event.transferhandler.js
================================================
Comlink.transferHandlers.set("event", {
  canHandle(obj) {
    return obj instanceof Event;
  },
  serialize(obj) {
    return [
      {
        targetId: obj && obj.target && obj.target.id,
        targetClassList: obj &&
          obj.target &&
          obj.target.classList && [...obj.target.classList],
        detail: obj && obj.detail,
      },
      [],
    ];
  },
  deserialize(obj) {
    return obj;
  },
});


================================================
FILE: docs/examples/04-eventlistener-example/index.html
================================================
<!DOCTYPE html>
Open DevTools and click the button.
<button id="mainbtn" class="btn btn--big">Click me</button>
<script src="https://unpkg.com/comlink/dist/umd/comlink.js"></script>
<!-- <script src="../../../dist/umd/comlink.js"></script> -->
<script src="./event.transferhandler.js"></script>
<script>
  const worker = new Worker("worker.js");
  const api = Comlink.wrap(worker);

  document
    .querySelector("#mainbtn")
    .addEventListener("click", api.onclick.bind(api));
</script>


================================================
FILE: docs/examples/04-eventlistener-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");
importScripts("event.transferhandler.js");

Comlink.expose({
  onclick(ev) {
    console.log(
      `Click! Button id: ${ev.targetId}, Button classes: ${JSON.stringify(
        ev.targetClassList
      )}`
    );
  },
});


================================================
FILE: docs/examples/05-serviceworker-example/README.md
================================================
This example shows how to setup Comlink between a website and a service worker.


================================================
FILE: docs/examples/05-serviceworker-example/index.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../dist/esm/comlink.mjs";

  async function initComlink() {
    const { port1, port2 } = new MessageChannel();
    const msg = {
      comlinkInit: true,
      port: port1,
    };
    navigator.serviceWorker.controller.postMessage(msg, [port1]);

    const swProxy = Comlink.wrap(port2);
    console.log(await swProxy.counter);
    await swProxy.inc();
    console.log(await swProxy.counter);
  }

  if (navigator.serviceWorker.controller) {
    initComlink();
  }
  navigator.serviceWorker.addEventListener("controllerchange", initComlink);
  navigator.serviceWorker.register("worker.js");
</script>


================================================
FILE: docs/examples/05-serviceworker-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

addEventListener("install", () => skipWaiting());
addEventListener("activate", () => clients.claim());

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

self.addEventListener("message", (event) => {
  if (event.data.comlinkInit) {
    Comlink.expose(obj, event.data.port);
    return;
  }
});


================================================
FILE: docs/examples/06-node-example/main.mjs
================================================
import { Worker } from "worker_threads";
import * as Comlink from "../../../dist/esm/comlink.mjs";
import nodeEndpoint from "../../../dist/esm/node-adapter.mjs";

async function init() {
  const worker = new Worker("./worker.mjs");

  const api = Comlink.wrap(nodeEndpoint(worker));
  console.log(await api.doMath());
}
init();


================================================
FILE: docs/examples/06-node-example/worker.mjs
================================================
import { parentPort } from "worker_threads";
import * as Comlink from "../../../dist/esm/comlink.mjs";
import nodeEndpoint from "../../../dist/esm/node-adapter.mjs";

const api = {
  doMath() {
    return 4;
  },
};
Comlink.expose(api, nodeEndpoint(parentPort));


================================================
FILE: docs/examples/07-sharedworker-example/README.md
================================================
This example shows how to setup Comlink between a website and a `SharedWorker`.


================================================
FILE: docs/examples/07-sharedworker-example/index.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../dist/esm/comlink.mjs";

  async function init() {
    const worker = new SharedWorker("worker.js");
    /**
     * SharedWorkers communicate via the `postMessage` function in their `port` property.
     * Therefore you must use the SharedWorker's `port` property when calling `Comlink.wrap`.
     */
    const obj = Comlink.wrap(worker.port);

    alert(`Counter: ${await obj.counter}`);
    await obj.inc();
    alert(`Counter: ${await obj.counter}`);
  }

  init();
</script>


================================================
FILE: docs/examples/07-sharedworker-example/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");

const obj = {
  counter: 0,
  inc() {
    this.counter++;
  },
};

/**
 * When a connection is made into this shared worker, expose `obj`
 * via the connection `port`.
 */
onconnect = function (event) {
  const port = event.ports[0];

  Comlink.expose(obj, port);
};

// Single line alternative:
// onconnect = (e) => Comlink.expose(obj, e.ports[0]);


================================================
FILE: docs/examples/99-nonworker-examples/iframes/README.md
================================================
This example shows how to set up Comlink between a window and an embedded iframe using `Comlink.windowEndpoint()`.


================================================
FILE: docs/examples/99-nonworker-examples/iframes/iframe.html
================================================
<!DOCTYPE html>

<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../../dist/esm/comlink.mjs";
  function add(a, b) {
    return a + b;
  }
  Comlink.expose(add, Comlink.windowEndpoint(self.parent));
</script>


================================================
FILE: docs/examples/99-nonworker-examples/iframes/index.html
================================================
<!DOCTYPE html>

<iframe src="iframe.html"></iframe>
<script type="module">
  import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
  // import * as Comlink from "../../../../dist/esm/comlink.mjs";
  async function main() {
    const ifr = document.querySelector("iframe");
    await new Promise((resolve) => (ifr.onload = resolve));
    const f = Comlink.wrap(Comlink.windowEndpoint(ifr.contentWindow));
    alert(`1 + 3 = ${await f(1, 3)}`);
  }
  main();
</script>


================================================
FILE: docs/index.html
================================================
<!DOCTYPE html>
<meta
  http-equiv="refresh"
  content="0; https://github.com/GoogleChromeLabs/comlink"
/>


================================================
FILE: karma.conf.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = function (config) {
  const configuration = {
    basePath: "",
    frameworks: ["mocha", "chai", "detectBrowsers"],
    files: [
      {
        pattern: "tests/fixtures/*",
        included: false,
      },
      {
        pattern: "dist/**/*.@(mjs|js)",
        included: false,
      },
      {
        pattern: "tests/*.test.js",
        type: "module",
      },
    ],
    reporters: ["progress"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    singleRun: true,
    concurrency: Infinity,
    detectBrowsers: {
      enabled: true,
      usePhantomJS: false,
      preferHeadless: true,
      postDetection: (availableBrowsers) => {
        if (process.env.INSIDE_DOCKER) {
          return ["DockerChrome"];
        } else if (process.env.CHROME_ONLY) {
          return ["ChromeHeadless"];
        } else {
          // Filtering SafariTechPreview because I am having
          // local issues and I have no idea how to fix them.
          // I know that’s not a good reason to disable tests,
          // but Safari TP is relatively unimportant.
          return availableBrowsers.filter(
            (browser) => browser !== "SafariTechPreview"
          );
        }
      },
    },
    customLaunchers: {
      DockerChrome: {
        base: "ChromeHeadless",
        flags: ["--no-sandbox"],
      },
    },
  };

  config.set(configuration);
};


================================================
FILE: package.json
================================================
{
  "name": "comlink",
  "version": "4.4.2",
  "description": "Comlink makes WebWorkers enjoyable",
  "main": "dist/umd/comlink.js",
  "module": "dist/esm/comlink.mjs",
  "types": "dist/umd/comlink.d.ts",
  "sideEffects": false,
  "scripts": {
    "build": "rollup -c",
    "test:unit": "karma start",
    "test:node": "mocha ./tests/node/main.mjs",
    "test:types": "tsc -p ./tests/tsconfig.json",
    "test:types:watch": "npm run test:types -- --watch",
    "test": "npm run fmt_test && npm run build && npm run test:types && npm run test:unit && npm run test:node",
    "fmt": "prettier --write './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{,**/}*.{mjs,js,ts,md,json,html}'",
    "fmt_test": "test $(prettier -l './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{**/,}*.{mjs,js,ts,md,json,html}' | wc -l) -eq 0",
    "watchtest": "CHROME_ONLY=1 karma start --no-single-run"
  },
  "author": {
    "name": "Surma",
    "email": "surma@google.com"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleChromeLabs/comlink.git"
  },
  "license": "Apache-2.0",
  "devDependencies": {
    "@rollup/plugin-terser": "0.4.0",
    "@rollup/plugin-typescript": "11.0.0",
    "chai": "^4.3.7",
    "conditional-type-checks": "1.0.6",
    "husky": "8.0.3",
    "karma": "6.4.1",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "3.1.1",
    "karma-detect-browsers": "2.3.3",
    "karma-firefox-launcher": "2.1.2",
    "karma-mocha": "2.0.1",
    "karma-safari-launcher": "1.0.0",
    "karma-safaritechpreview-launcher": "2.0.2",
    "mocha": "10.2.0",
    "prettier": "2.8.3",
    "rimraf": "4.1.2",
    "rollup": "3.10.1",
    "tslib": "2.4.1",
    "typescript": "4.9.4"
  }
}


================================================
FILE: renovate.json
================================================
{
  "extends": [":library"],
  "assignees": ["surma"]
}


================================================
FILE: rollup.config.mjs
================================================
import typescript from "@rollup/plugin-typescript";
import terser from "@rollup/plugin-terser";
import { sync } from "rimraf";

function config({ format, minify, input, ext = "js" }) {
  const dir = `dist/${format}/`;
  const minifierSuffix = minify ? ".min" : "";
  return {
    input: `./src/${input}.ts`,
    output: {
      name: "Comlink",
      file: `${dir}/${input}${minifierSuffix}.${ext}`,
      format,
      sourcemap: true,
    },
    plugins: [
      typescript({
        tsconfig: "./tsconfig.json",
        compilerOptions: {
          declaration: true,
          declarationDir: ".",
          sourceMap: true,
          outDir: "dist",
        },
      }),
      minify
        ? terser({
            compress: true,
            mangle: true,
          })
        : undefined,
    ].filter(Boolean),
  };
}

sync("dist");

export default [
  { input: "comlink", format: "esm", minify: false, ext: "mjs" },
  { input: "comlink", format: "esm", minify: true, ext: "mjs" },
  { input: "comlink", format: "esm", minify: false },
  { input: "comlink", format: "esm", minify: true },
  { input: "comlink", format: "umd", minify: false },
  { input: "comlink", format: "umd", minify: true },
  { input: "node-adapter", format: "esm", minify: false, ext: "mjs" },
  { input: "node-adapter", format: "esm", minify: true, ext: "mjs" },
  { input: "node-adapter", format: "umd", minify: false },
  { input: "node-adapter", format: "umd", minify: true },
].map(config);


================================================
FILE: src/comlink.ts
================================================
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {
  Endpoint,
  EventSource,
  Message,
  MessageType,
  PostMessageWithOrigin,
  WireValue,
  WireValueType,
} from "./protocol";
export type { Endpoint };

export const proxyMarker = Symbol("Comlink.proxy");
export const createEndpoint = Symbol("Comlink.endpoint");
export const releaseProxy = Symbol("Comlink.releaseProxy");
export const finalizer = Symbol("Comlink.finalizer");

const throwMarker = Symbol("Comlink.thrown");

/**
 * Interface of values that were marked to be proxied with `comlink.proxy()`.
 * Can also be implemented by classes.
 */
export interface ProxyMarked {
  [proxyMarker]: true;
}

/**
 * Takes a type and wraps it in a Promise, if it not already is one.
 * This is to avoid `Promise<Promise<T>>`.
 *
 * This is the inverse of `Unpromisify<T>`.
 */
type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
/**
 * Takes a type that may be Promise and unwraps the Promise type.
 * If `P` is not a Promise, it returns `P`.
 *
 * This is the inverse of `Promisify<T>`.
 */
type Unpromisify<P> = P extends Promise<infer T> ? T : P;

/**
 * Takes the raw type of a remote property and returns the type that is visible to the local thread on the proxy.
 *
 * Note: This needs to be its own type alias, otherwise it will not distribute over unions.
 * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
 */
type RemoteProperty<T> =
  // If the value is a method, comlink will proxy it automatically.
  // Objects are only proxied if they are marked to be proxied.
  // Otherwise, the property is converted to a Promise that resolves the cloned value.
  T extends Function | ProxyMarked ? Remote<T> : Promisify<T>;

/**
 * Takes the raw type of a property as a remote thread would see it through a proxy (e.g. when passed in as a function
 * argument) and returns the type that the local thread has to supply.
 *
 * This is the inverse of `RemoteProperty<T>`.
 *
 * Note: This needs to be its own type alias, otherwise it will not distribute over unions. See
 * https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
 */
type LocalProperty<T> = T extends Function | ProxyMarked
  ? Local<T>
  : Unpromisify<T>;

/**
 * Proxies `T` if it is a `ProxyMarked`, clones it otherwise (as handled by structured cloning and transfer handlers).
 */
export type ProxyOrClone<T> = T extends ProxyMarked ? Remote<T> : T;
/**
 * Inverse of `ProxyOrClone<T>`.
 */
export type UnproxyOrClone<T> = T extends RemoteObject<ProxyMarked>
  ? Local<T>
  : T;

/**
 * Takes the raw type of a remote object in the other thread and returns the type as it is visible to the local thread
 * when proxied with `Comlink.proxy()`.
 *
 * This does not handle call signatures, which is handled by the more general `Remote<T>` type.
 *
 * @template T The raw type of a remote object as seen in the other thread.
 */
export type RemoteObject<T> = { [P in keyof T]: RemoteProperty<T[P]> };
/**
 * Takes the type of an object as a remote thread would see it through a proxy (e.g. when passed in as a function
 * argument) and returns the type that the local thread has to supply.
 *
 * This does not handle call signatures, which is handled by the more general `Local<T>` type.
 *
 * This is the inverse of `RemoteObject<T>`.
 *
 * @template T The type of a proxied object.
 */
export type LocalObject<T> = { [P in keyof T]: LocalProperty<T[P]> };

/**
 * Additional special comlink methods available on each proxy returned by `Comlink.wrap()`.
 */
export interface ProxyMethods {
  [createEndpoint]: () => Promise<MessagePort>;
  [releaseProxy]: () => void;
}

/**
 * Takes the raw type of a remote object, function or class in the other thread and returns the type as it is visible to
 * the local thread from the proxy return value of `Comlink.wrap()` or `Comlink.proxy()`.
 */
export type Remote<T> =
  // Handle properties
  RemoteObject<T> &
    // Handle call signature (if present)
    (T extends (...args: infer TArguments) => infer TReturn
      ? (
          ...args: { [I in keyof TArguments]: UnproxyOrClone<TArguments[I]> }
        ) => Promisify<ProxyOrClone<Unpromisify<TReturn>>>
      : unknown) &
    // Handle construct signature (if present)
    // The return of construct signatures is always proxied (whether marked or not)
    (T extends { new (...args: infer TArguments): infer TInstance }
      ? {
          new (
            ...args: {
              [I in keyof TArguments]: UnproxyOrClone<TArguments[I]>;
            }
          ): Promisify<Remote<TInstance>>;
        }
      : unknown) &
    // Include additional special comlink methods available on the proxy.
    ProxyMethods;

/**
 * Expresses that a type can be either a sync or async.
 */
type MaybePromise<T> = Promise<T> | T;

/**
 * Takes the raw type of a remote object, function or class as a remote thread would see it through a proxy (e.g. when
 * passed in as a function argument) and returns the type the local thread has to supply.
 *
 * This is the inverse of `Remote<T>`. It takes a `Remote<T>` and returns its original input `T`.
 */
export type Local<T> =
  // Omit the special proxy methods (they don't need to be supplied, comlink adds them)
  Omit<LocalObject<T>, keyof ProxyMethods> &
    // Handle call signatures (if present)
    (T extends (...args: infer TArguments) => infer TReturn
      ? (
          ...args: { [I in keyof TArguments]: ProxyOrClone<TArguments[I]> }
        ) => // The raw function could either be sync or async, but is always proxied automatically
        MaybePromise<UnproxyOrClone<Unpromisify<TReturn>>>
      : unknown) &
    // Handle construct signature (if present)
    // The return of construct signatures is always proxied (whether marked or not)
    (T extends { new (...args: infer TArguments): infer TInstance }
      ? {
          new (
            ...args: {
              [I in keyof TArguments]: ProxyOrClone<TArguments[I]>;
            }
          ): // The raw constructor could either be sync or async, but is always proxied automatically
          MaybePromise<Local<Unpromisify<TInstance>>>;
        }
      : unknown);

const isObject = (val: unknown): val is object =>
  (typeof val === "object" && val !== null) || typeof val === "function";

/**
 * Customizes the serialization of certain values as determined by `canHandle()`.
 *
 * @template T The input type being handled by this transfer handler.
 * @template S The serialized type sent over the wire.
 */
export interface TransferHandler<T, S> {
  /**
   * Gets called for every value to determine whether this transfer handler
   * should serialize the value, which includes checking that it is of the right
   * type (but can perform checks beyond that as well).
   */
  canHandle(value: unknown): value is T;

  /**
   * Gets called with the value if `canHandle()` returned `true` to produce a
   * value that can be sent in a message, consisting of structured-cloneable
   * values and/or transferrable objects.
   */
  serialize(value: T): [S, Transferable[]];

  /**
   * Gets called to deserialize an incoming value that was serialized in the
   * other thread with this transfer handler (known through the name it was
   * registered under).
   */
  deserialize(value: S): T;
}

/**
 * Internal transfer handle to handle objects marked to proxy.
 */
const proxyTransferHandler: TransferHandler<object, MessagePort> = {
  canHandle: (val): val is ProxyMarked =>
    isObject(val) && (val as ProxyMarked)[proxyMarker],
  serialize(obj) {
    const { port1, port2 } = new MessageChannel();
    expose(obj, port1);
    return [port2, [port2]];
  },
  deserialize(port) {
    port.start();
    return wrap(port);
  },
};

interface ThrownValue {
  [throwMarker]: unknown; // just needs to be present
  value: unknown;
}
type SerializedThrownValue =
  | { isError: true; value: Error }
  | { isError: false; value: unknown };
type PendingListenersMap = Map<
  string,
  (value: WireValue | PromiseLike<WireValue>) => void
>;
type EndpointWithPendingListeners = {
  endpoint: Endpoint;
  pendingListeners: PendingListenersMap;
};

/**
 * Internal transfer handler to handle thrown exceptions.
 */
const throwTransferHandler: TransferHandler<
  ThrownValue,
  SerializedThrownValue
> = {
  canHandle: (value): value is ThrownValue =>
    isObject(value) && throwMarker in value,
  serialize({ value }) {
    let serialized: SerializedThrownValue;
    if (value instanceof Error) {
      serialized = {
        isError: true,
        value: {
          message: value.message,
          name: value.name,
          stack: value.stack,
        },
      };
    } else {
      serialized = { isError: false, value };
    }
    return [serialized, []];
  },
  deserialize(serialized) {
    if (serialized.isError) {
      throw Object.assign(
        new Error(serialized.value.message),
        serialized.value
      );
    }
    throw serialized.value;
  },
};

/**
 * Allows customizing the serialization of certain values.
 */
export const transferHandlers = new Map<
  string,
  TransferHandler<unknown, unknown>
>([
  ["proxy", proxyTransferHandler],
  ["throw", throwTransferHandler],
]);

function isAllowedOrigin(
  allowedOrigins: (string | RegExp)[],
  origin: string
): boolean {
  for (const allowedOrigin of allowedOrigins) {
    if (origin === allowedOrigin || allowedOrigin === "*") {
      return true;
    }
    if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
      return true;
    }
  }
  return false;
}

export function expose(
  obj: any,
  ep: Endpoint = globalThis as any,
  allowedOrigins: (string | RegExp)[] = ["*"]
) {
  ep.addEventListener("message", function callback(ev: MessageEvent) {
    if (!ev || !ev.data) {
      return;
    }
    if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
      console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
      return;
    }
    const { id, type, path } = {
      path: [] as string[],
      ...(ev.data as Message),
    };
    const argumentList = (ev.data.argumentList || []).map(fromWireValue);
    let returnValue;
    try {
      const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);
      const rawValue = path.reduce((obj, prop) => obj[prop], obj);
      switch (type) {
        case MessageType.GET:
          {
            returnValue = rawValue;
          }
          break;
        case MessageType.SET:
          {
            parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
            returnValue = true;
          }
          break;
        case MessageType.APPLY:
          {
            returnValue = rawValue.apply(parent, argumentList);
          }
          break;
        case MessageType.CONSTRUCT:
          {
            const value = new rawValue(...argumentList);
            returnValue = proxy(value);
          }
          break;
        case MessageType.ENDPOINT:
          {
            const { port1, port2 } = new MessageChannel();
            expose(obj, port2);
            returnValue = transfer(port1, [port1]);
          }
          break;
        case MessageType.RELEASE:
          {
            returnValue = undefined;
          }
          break;
        default:
          return;
      }
    } catch (value) {
      returnValue = { value, [throwMarker]: 0 };
    }
    Promise.resolve(returnValue)
      .catch((value) => {
        return { value, [throwMarker]: 0 };
      })
      .then((returnValue) => {
        const [wireValue, transferables] = toWireValue(returnValue);
        ep.postMessage({ ...wireValue, id }, transferables);
        if (type === MessageType.RELEASE) {
          // detach and deactive after sending release response above.
          ep.removeEventListener("message", callback as any);
          closeEndPoint(ep);
          if (finalizer in obj && typeof obj[finalizer] === "function") {
            obj[finalizer]();
          }
        }
      })
      .catch((error) => {
        // Send Serialization Error To Caller
        const [wireValue, transferables] = toWireValue({
          value: new TypeError("Unserializable return value"),
          [throwMarker]: 0,
        });
        ep.postMessage({ ...wireValue, id }, transferables);
      });
  } as any);
  if (ep.start) {
    ep.start();
  }
}

function isMessagePort(endpoint: Endpoint): endpoint is MessagePort {
  return endpoint.constructor.name === "MessagePort";
}

function closeEndPoint(endpoint: Endpoint) {
  if (isMessagePort(endpoint)) endpoint.close();
}

export function wrap<T>(ep: Endpoint, target?: any): Remote<T> {
  const pendingListeners : PendingListenersMap = new Map();

  ep.addEventListener("message", function handleMessage(ev: Event) {
    const { data } = ev as MessageEvent;
    if (!data || !data.id) {
      return;
    }
    const resolver = pendingListeners.get(data.id);
    if (!resolver) {
      return;
    }

    try {
      resolver(data);
    } finally {
      pendingListeners.delete(data.id);
    }
  });

  return createProxy<T>({ endpoint: ep, pendingListeners }, [], target) as any;
}

function throwIfProxyReleased(isReleased: boolean) {
  if (isReleased) {
    throw new Error("Proxy has been released and is not useable");
  }
}

function releaseEndpoint(epWithPendingListeners: EndpointWithPendingListeners) {
  return requestResponseMessage(epWithPendingListeners, {
    type: MessageType.RELEASE,
  }).then(() => {
    closeEndPoint(epWithPendingListeners.endpoint);
  });
}

interface FinalizationRegistry<T> {
  new (cb: (heldValue: T) => void): FinalizationRegistry<T>;
  register(
    weakItem: object,
    heldValue: T,
    unregisterToken?: object | undefined
  ): void;
  unregister(unregisterToken: object): void;
}
declare var FinalizationRegistry: FinalizationRegistry<EndpointWithPendingListeners>;

const proxyCounter = new WeakMap<EndpointWithPendingListeners, number>();
const proxyFinalizers =
  "FinalizationRegistry" in globalThis &&
  new FinalizationRegistry(
    (epWithPendingListeners: EndpointWithPendingListeners) => {
      const newCount = (proxyCounter.get(epWithPendingListeners) || 0) - 1;
      proxyCounter.set(epWithPendingListeners, newCount);
      if (newCount === 0) {
        releaseEndpoint(epWithPendingListeners).finally(() => {
          epWithPendingListeners.pendingListeners.clear();
        });
      }
    }
  );

function registerProxy(
  proxy: object,
  epWithPendingListeners: EndpointWithPendingListeners
) {
  const newCount = (proxyCounter.get(epWithPendingListeners) || 0) + 1;
  proxyCounter.set(epWithPendingListeners, newCount);
  if (proxyFinalizers) {
    proxyFinalizers.register(proxy, epWithPendingListeners, proxy);
  }
}

function unregisterProxy(proxy: object) {
  if (proxyFinalizers) {
    proxyFinalizers.unregister(proxy);
  }
}

function createProxy<T>(
  epWithPendingListeners: EndpointWithPendingListeners,
  path: (string | number | symbol)[] = [],
  target: object = function () {}
): Remote<T> {
  let isProxyReleased = false;
  const proxy = new Proxy(target, {
    get(_target, prop) {
      throwIfProxyReleased(isProxyReleased);
      if (prop === releaseProxy) {
        return () => {
          unregisterProxy(proxy);
          releaseEndpoint(epWithPendingListeners).finally(() => {
            epWithPendingListeners.pendingListeners.clear();
          });
          isProxyReleased = true;
        };
      }
      if (prop === "then") {
        if (path.length === 0) {
          return { then: () => proxy };
        }
        const r = requestResponseMessage(epWithPendingListeners, {
          type: MessageType.GET,
          path: path.map((p) => p.toString()),
        }).then(fromWireValue);
        return r.then.bind(r);
      }
      return createProxy(epWithPendingListeners, [...path, prop]);
    },
    set(_target, prop, rawValue) {
      throwIfProxyReleased(isProxyReleased);
      // FIXME: ES6 Proxy Handler `set` methods are supposed to return a
      // boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯
      const [value, transferables] = toWireValue(rawValue);
      return requestResponseMessage(
        epWithPendingListeners,
        {
          type: MessageType.SET,
          path: [...path, prop].map((p) => p.toString()),
          value,
        },
        transferables
      ).then(fromWireValue) as any;
    },
    apply(_target, _thisArg, rawArgumentList) {
      throwIfProxyReleased(isProxyReleased);
      const last = path[path.length - 1];
      if ((last as any) === createEndpoint) {
        return requestResponseMessage(epWithPendingListeners, {
          type: MessageType.ENDPOINT,
        }).then(fromWireValue);
      }
      // We just pretend that `bind()` didn’t happen.
      if (last === "bind") {
        return createProxy(epWithPendingListeners, path.slice(0, -1));
      }
      const [argumentList, transferables] = processArguments(rawArgumentList);
      return requestResponseMessage(
        epWithPendingListeners,
        {
          type: MessageType.APPLY,
          path: path.map((p) => p.toString()),
          argumentList,
        },
        transferables
      ).then(fromWireValue);
    },
    construct(_target, rawArgumentList) {
      throwIfProxyReleased(isProxyReleased);
      const [argumentList, transferables] = processArguments(rawArgumentList);
      return requestResponseMessage(
        epWithPendingListeners,
        {
          type: MessageType.CONSTRUCT,
          path: path.map((p) => p.toString()),
          argumentList,
        },
        transferables
      ).then(fromWireValue);
    },
  });
  registerProxy(proxy, epWithPendingListeners);
  return proxy as any;
}

function myFlat<T>(arr: (T | T[])[]): T[] {
  return Array.prototype.concat.apply([], arr);
}

function processArguments(argumentList: any[]): [WireValue[], Transferable[]] {
  const processed = argumentList.map(toWireValue);
  return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
}

const transferCache = new WeakMap<any, Transferable[]>();
export function transfer<T>(obj: T, transfers: Transferable[]): T {
  transferCache.set(obj, transfers);
  return obj;
}

export function proxy<T extends {}>(obj: T): T & ProxyMarked {
  return Object.assign(obj, { [proxyMarker]: true }) as any;
}

export function windowEndpoint(
  w: PostMessageWithOrigin,
  context: EventSource = globalThis,
  targetOrigin = "*"
): Endpoint {
  return {
    postMessage: (msg: any, transferables: Transferable[]) =>
      w.postMessage(msg, targetOrigin, transferables),
    addEventListener: context.addEventListener.bind(context),
    removeEventListener: context.removeEventListener.bind(context),
  };
}

function toWireValue(value: any): [WireValue, Transferable[]] {
  for (const [name, handler] of transferHandlers) {
    if (handler.canHandle(value)) {
      const [serializedValue, transferables] = handler.serialize(value);
      return [
        {
          type: WireValueType.HANDLER,
          name,
          value: serializedValue,
        },
        transferables,
      ];
    }
  }
  return [
    {
      type: WireValueType.RAW,
      value,
    },
    transferCache.get(value) || [],
  ];
}

function fromWireValue(value: WireValue): any {
  switch (value.type) {
    case WireValueType.HANDLER:
      return transferHandlers.get(value.name)!.deserialize(value.value);
    case WireValueType.RAW:
      return value.value;
  }
}

function requestResponseMessage(
  epWithPendingListeners: EndpointWithPendingListeners,
  msg: Message,
  transfers?: Transferable[]
): Promise<WireValue> {
  const ep = epWithPendingListeners.endpoint;
  const pendingListeners = epWithPendingListeners.pendingListeners;
  return new Promise((resolve) => {
    const id = generateUUID();
    pendingListeners.set(id, resolve);
    if (ep.start) {
      ep.start();
    }
    ep.postMessage({ id, ...msg }, transfers);
});
}

function generateUUID(): string {
  return new Array(4)
    .fill(0)
    .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
    .join("-");
}


================================================
FILE: src/node-adapter.ts
================================================
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { Endpoint } from "./protocol";

export interface NodeEndpoint {
  postMessage(message: any, transfer?: any[]): void;
  on(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: {}
  ): void;
  off(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: {}
  ): void;
  start?: () => void;
}

export default function nodeEndpoint(nep: NodeEndpoint): Endpoint {
  const listeners = new WeakMap();
  return {
    postMessage: nep.postMessage.bind(nep),
    addEventListener: (_, eh) => {
      const l = (data: any) => {
        if ("handleEvent" in eh) {
          eh.handleEvent({ data } as MessageEvent);
        } else {
          eh({ data } as MessageEvent);
        }
      };
      nep.on("message", l);
      listeners.set(eh, l);
    },
    removeEventListener: (_, eh) => {
      const l = listeners.get(eh);
      if (!l) {
        return;
      }
      nep.off("message", l);
      listeners.delete(eh);
    },
    start: nep.start && nep.start.bind(nep),
  };
}


================================================
FILE: src/protocol.ts
================================================
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

export interface EventSource {
  addEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: {}
  ): void;

  removeEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: {}
  ): void;
}

export interface PostMessageWithOrigin {
  postMessage(
    message: any,
    targetOrigin: string,
    transfer?: Transferable[]
  ): void;
}

export interface Endpoint extends EventSource {
  postMessage(message: any, transfer?: Transferable[]): void;

  start?: () => void;
}

export const enum WireValueType {
  RAW = "RAW",
  PROXY = "PROXY",
  THROW = "THROW",
  HANDLER = "HANDLER",
}

export interface RawWireValue {
  id?: string;
  type: WireValueType.RAW;
  value: {};
}

export interface HandlerWireValue {
  id?: string;
  type: WireValueType.HANDLER;
  name: string;
  value: unknown;
}

export type WireValue = RawWireValue | HandlerWireValue;

export type MessageID = string;

export const enum MessageType {
  GET = "GET",
  SET = "SET",
  APPLY = "APPLY",
  CONSTRUCT = "CONSTRUCT",
  ENDPOINT = "ENDPOINT",
  RELEASE = "RELEASE",
}

export interface GetMessage {
  id?: MessageID;
  type: MessageType.GET;
  path: string[];
}

export interface SetMessage {
  id?: MessageID;
  type: MessageType.SET;
  path: string[];
  value: WireValue;
}

export interface ApplyMessage {
  id?: MessageID;
  type: MessageType.APPLY;
  path: string[];
  argumentList: WireValue[];
}

export interface ConstructMessage {
  id?: MessageID;
  type: MessageType.CONSTRUCT;
  path: string[];
  argumentList: WireValue[];
}

export interface EndpointMessage {
  id?: MessageID;
  type: MessageType.ENDPOINT;
}

export interface ReleaseMessage {
  id?: MessageID;
  type: MessageType.RELEASE;
}

export type Message =
  | GetMessage
  | SetMessage
  | ApplyMessage
  | ConstructMessage
  | EndpointMessage
  | ReleaseMessage;


================================================
FILE: structured-clone-table.md
================================================
# Behavior of [Structured Clone]

[Structured clone] is JavaScript’s algorithm to create “deep copies” of values. It is used for `postMessage()` and therefore is used extensively under the hood with Comlink. By default, every function parameter and function return value is structured cloned. Here is a table of how the structured clone algorithm handles different kinds of values. Or to phrase it differently: If you pass a value from the left side as a parameter into a proxy’d function, the actual function code will get what is listed on the right side.

| Input                      |     Output     | Notes                                                                                        |
| -------------------------- | :------------: | -------------------------------------------------------------------------------------------- |
| `[1,2,3]`                  |   `[1,2,3]`    | Full copy                                                                                    |
| `{a: 1, b: 2}`             | `{a: 1, b: 2}` | Full copy                                                                                    |
| `{a: 1, b() { return 2; }` |    `{a: 1}`    | Full copy, functions omitted                                                                 |
| `new MyClass()`            |    `{...}`     | Just the properties                                                                          |
| `Map`                      |     `Map`      | [`Map`][map] is structured cloneable                                                         |
| `Set`                      |     `Set`      | [`Set`][set] is structured cloneable                                                         |
| `ArrayBuffer`              | `ArrayBuffer`  | [`ArrayBuffer`][arraybuffer] is structured cloneable                                         |
| `Uint32Array`              | `Uint32Array`  | [`Uint32Array`][uint32array] and all the other typed arrays are structured cloneable         |
| `Event`                    |       ❌       |                                                                                              |
| Any DOM element            |       ❌       |                                                                                              |
| `MessagePort`              |       ❌       | Only transferable, not structured cloneable                                                  |
| `Request`                  |       ❌       |                                                                                              |
| `Response`                 |       ❌       |                                                                                              |
| `ReadableStream`           |       ❌       | [Streams are planned to be transferable][transferable streams], but not structured cloneable |

[structured clone]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
[arraybuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
[uint32array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array
[transferable streams]: https://github.com/whatwg/streams/blob/master/transferable-streams-explainer.md


================================================
FILE: tests/cross-origin.comlink.test.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as Comlink from "/base/dist/esm/comlink.mjs";

describe("Comlink origin filtering", function () {
  it("rejects messages from unknown origin", async function () {
    // expose on our window so comlink is listening to window postmessage
    const obj = { my: "value" };
    Comlink.expose(obj, self, [/^http:\/\/localhost(:[0-9]+)?\/?$/]);

    let handler;
    // juggle async timings to get the attack started
    const attackComplete = new Promise((resolve, reject) => {
      handler = (ev) => {
        if (ev.data === "ready" && ev.origin === "null") {
          // tell the iframe it can start the attack
          ifr.contentWindow.postMessage("start", "*");
        } else if (ev.data === "done") {
          // confirm the attack failed, the prototype was not updated
          expect(Object.prototype.foo).to.be.undefined;
          expect(obj.my).to.equal("value");
          resolve();
        }
      };
      window.addEventListener("message", handler);
    });
    // create a sandboxed iframe for the attack
    const ifr = document.createElement("iframe");
    ifr.sandbox.add("allow-scripts");
    ifr.src = "/base/tests/fixtures/attack-iframe.html";
    document.body.appendChild(ifr);
    // wait for the iframe to load
    await new Promise((resolve) => (ifr.onload = resolve));
    // and wait for the attack to complete
    await attackComplete;
    window.removeEventListener("message", handler);
    ifr.remove();
  });
  it("accepts messages from matching origin", async function () {
    // expose on our window so comlink is listening to window postmessage
    const obj = { my: "value" };
    Comlink.expose(obj, self, [/^http:\/\/localhost(:[0-9]+)?\/?$/]);

    let handler;
    // juggle async timings to get the attack started
    const attackComplete = new Promise((resolve, reject) => {
      handler = (ev) => {
        if (ev.data === "ready" && ev.origin === window.origin) {
          // tell the iframe it can start the attack
          ifr.contentWindow.postMessage("start", "*");
        } else if (ev.data === "done") {
          // confirm the attack succeeded, the prototype was updated
          expect(Object.prototype.foo).to.equal("x");
          expect(obj.my).to.equal("value");
          resolve();
        }
      };
      window.addEventListener("message", handler);
    });
    // create a sandboxed iframe for the attack, but with same origin
    const ifr = document.createElement("iframe");
    ifr.sandbox.add("allow-scripts", "allow-same-origin");
    ifr.src = "/base/tests/fixtures/attack-iframe.html";
    document.body.appendChild(ifr);
    // wait for the iframe to load
    await new Promise((resolve) => (ifr.onload = resolve));
    // and wait for the attack to complete
    await attackComplete;
    window.removeEventListener("message", handler);
    ifr.remove();
  });
});


================================================
FILE: tests/fixtures/attack-iframe.html
================================================
<html>
  <body>
    <script>
      window.addEventListener("message", (ev) => {
        if (ev.data === "start") {
          // send back a message to modify the prototype
          parent.postMessage(
            {
              type: "SET",
              value: { type: "RAW", value: "x" },
              path: ["__proto__", "foo"],
            },
            "*"
          );
          parent.postMessage("done", "*");
        }
      });
      parent.postMessage("ready", "*");
    </script>
  </body>
</html>


================================================
FILE: tests/fixtures/iframe.html
================================================
<script type="module">
  import * as Comlink from "/base/dist/esm/comlink.mjs";

  Comlink.expose((a, b) => a + b, Comlink.windowEndpoint(self.parent));
</script>


================================================
FILE: tests/fixtures/two-way-iframe.html
================================================
<script type="module">
  import * as Comlink from "/base/dist/esm/comlink.mjs";

  const parentEndpoint = Comlink.windowEndpoint(self.parent);
  const wrappedParent = Comlink.wrap(parentEndpoint);

  Comlink.expose(async (a, b) => {
    return a + (await wrappedParent(b));
  }, parentEndpoint);
</script>


================================================
FILE: tests/fixtures/worker.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

importScripts("/base/dist/umd/comlink.js");

Comlink.expose((a, b) => a + b);


================================================
FILE: tests/iframe.comlink.test.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as Comlink from "/base/dist/esm/comlink.mjs";

describe("Comlink across iframes", function () {
  beforeEach(function () {
    this.ifr = document.createElement("iframe");
    this.ifr.sandbox.add("allow-scripts", "allow-same-origin");
    this.ifr.src = "/base/tests/fixtures/iframe.html";
    document.body.appendChild(this.ifr);
    return new Promise((resolve) => (this.ifr.onload = resolve));
  });

  afterEach(function () {
    this.ifr.remove();
  });

  it("can communicate", async function () {
    const proxy = Comlink.wrap(Comlink.windowEndpoint(this.ifr.contentWindow));
    expect(await proxy(1, 3)).to.equal(4);
  });
});


================================================
FILE: tests/node/main.mjs
================================================
import { Worker } from "worker_threads";
import * as Comlink from "../../dist/esm/comlink.mjs";
import nodeEndpoint from "../../dist/esm/node-adapter.mjs";
import { expect } from "chai";

describe("node", () => {
  describe("Comlink across workers", function () {
    beforeEach(function () {
      this.worker = new Worker("./tests/node/worker.mjs");
    });

    afterEach(function () {
      this.worker.terminate();
    });

    it("can communicate", async function () {
      const proxy = Comlink.wrap(nodeEndpoint(this.worker));
      expect(await proxy(1, 3)).to.equal(4);
    });

    it("can tunnels a new endpoint with createEndpoint", async function () {
      const proxy = Comlink.wrap(nodeEndpoint(this.worker));
      const otherEp = await proxy[Comlink.createEndpoint]();
      const otherProxy = Comlink.wrap(otherEp);
      expect(await otherProxy(20, 1)).to.equal(21);
    });

    it("releaseProxy closes MessagePort created by createEndpoint", async function () {
      const proxy = Comlink.wrap(nodeEndpoint(this.worker));
      const otherEp = await proxy[Comlink.createEndpoint]();
      const otherProxy = Comlink.wrap(otherEp);
      expect(await otherProxy(20, 1)).to.equal(21);

      await new Promise((resolve) => {
        otherEp.close = resolve; // Resolve the promise when the MessagePort is closed.
        otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort.
      });
    });
  });
});


================================================
FILE: tests/node/worker.mjs
================================================
import { parentPort } from "worker_threads";
import * as Comlink from "../../dist/esm/comlink.mjs";
import nodeEndpoint from "../../dist/esm/node-adapter.mjs";

Comlink.expose((a, b) => a + b, nodeEndpoint(parentPort));


================================================
FILE: tests/same_window.comlink.test.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as Comlink from "/base/dist/esm/comlink.mjs";

class SampleClass {
  constructor(counterInit = 1) {
    this._counter = counterInit;
    this._promise = Promise.resolve(4);
  }

  static get SOME_NUMBER() {
    return 4;
  }

  static ADD(a, b) {
    return a + b;
  }

  get counter() {
    return this._counter;
  }

  set counter(value) {
    this._counter = value;
  }

  get promise() {
    return this._promise;
  }

  method() {
    return 4;
  }

  increaseCounter(delta = 1) {
    this._counter += delta;
  }

  promiseFunc() {
    return new Promise((resolve) => setTimeout((_) => resolve(4), 100));
  }

  proxyFunc() {
    return Comlink.proxy({
      counter: 0,
      inc() {
        this.counter++;
      },
    });
  }

  throwsAnError() {
    throw Error("OMG");
  }
}

describe("Comlink in the same realm", function () {
  beforeEach(function () {
    const { port1, port2 } = new MessageChannel();
    port1.start();
    port2.start();
    this.port1 = port1;
    this.port2 = port2;
  });

  it("can work with objects", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose({ value: 4 }, this.port2);
    expect(await thing.value).to.equal(4);
  });

  it("can work with functions on an object", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose({ f: (_) => 4 }, this.port2);
    expect(await thing.f()).to.equal(4);
  });

  it("can work with functions", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((_) => 4, this.port2);
    expect(await thing()).to.equal(4);
  });

  it("can work with objects that have undefined properties", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose({ x: undefined }, this.port2);
    expect(await thing.x).to.be.undefined;
  });

  it("can keep the stack and message of thrown errors", async function () {
    let stack;
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((_) => {
      const error = Error("OMG");
      stack = error.stack;
      throw error;
    }, this.port2);
    try {
      await thing();
      throw "Should have thrown";
    } catch (err) {
      expect(err).to.not.eq("Should have thrown");
      expect(err.message).to.equal("OMG");
      expect(err.stack).to.equal(stack);
    }
  });

  it("can forward an async function error", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(
      {
        async throwError() {
          throw new Error("Should have thrown");
        },
      },
      this.port2
    );
    try {
      await thing.throwError();
    } catch (err) {
      expect(err.message).to.equal("Should have thrown");
    }
  });

  it("can rethrow non-error objects", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((_) => {
      throw { test: true };
    }, this.port2);
    try {
      await thing();
      throw "Should have thrown";
    } catch (err) {
      expect(err).to.not.equal("Should have thrown");
      expect(err.test).to.equal(true);
    }
  });

  it("can rethrow scalars", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((_) => {
      throw "oops";
    }, this.port2);
    try {
      await thing();
      throw "Should have thrown";
    } catch (err) {
      expect(err).to.not.equal("Should have thrown");
      expect(err).to.equal("oops");
      expect(typeof err).to.equal("string");
    }
  });

  it("can rethrow null", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((_) => {
      throw null;
    }, this.port2);
    try {
      await thing();
      throw "Should have thrown";
    } catch (err) {
      expect(err).to.not.equal("Should have thrown");
      expect(err).to.equal(null);
      expect(typeof err).to.equal("object");
    }
  });

  it("can work with parameterized functions", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((a, b) => a + b, this.port2);
    expect(await thing(1, 3)).to.equal(4);
  });

  it("can work with functions that return promises", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(
      (_) => new Promise((resolve) => setTimeout((_) => resolve(4), 100)),
      this.port2
    );
    expect(await thing()).to.equal(4);
  });

  it("can work with classes", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.method()).to.equal(4);
  });

  it("can pass parameters to class constructor", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing(23);
    expect(await instance.counter).to.equal(23);
  });

  it("can access a class in an object", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose({ SampleClass }, this.port2);
    const instance = await new thing.SampleClass();
    expect(await instance.method()).to.equal(4);
  });

  it("can work with class instance properties", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance._counter).to.equal(1);
  });

  it("can set class instance properties", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance._counter).to.equal(1);
    await (instance._counter = 4);
    expect(await instance._counter).to.equal(4);
  });

  it("can work with class instance methods", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.counter).to.equal(1);
    await instance.increaseCounter();
    expect(await instance.counter).to.equal(2);
  });

  it("can handle throwing class instance methods", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    return instance
      .throwsAnError()
      .then((_) => Promise.reject())
      .catch((err) => {});
  });

  it("can work with class instance methods multiple times", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.counter).to.equal(1);
    await instance.increaseCounter();
    await instance.increaseCounter(5);
    expect(await instance.counter).to.equal(7);
  });

  it("can work with class instance methods that return promises", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.promiseFunc()).to.equal(4);
  });

  it("can work with class instance properties that are promises", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance._promise).to.equal(4);
  });

  it("can work with class instance getters that are promises", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.promise).to.equal(4);
  });

  it("can work with static class properties", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    expect(await thing.SOME_NUMBER).to.equal(4);
  });

  it("can work with static class methods", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    expect(await thing.ADD(1, 3)).to.equal(4);
  });

  it("can work with bound class instance methods", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.counter).to.equal(1);
    const method = instance.increaseCounter.bind(instance);
    await method();
    expect(await instance.counter).to.equal(2);
  });

  it("can work with class instance getters", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance.counter).to.equal(1);
    await instance.increaseCounter();
    expect(await instance.counter).to.equal(2);
  });

  it("can work with class instance setters", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    expect(await instance._counter).to.equal(1);
    await (instance.counter = 4);
    expect(await instance._counter).to.equal(4);
  });

  const hasBroadcastChannel = (_) => "BroadcastChannel" in self;
  guardedIt(hasBroadcastChannel)(
    "will work with BroadcastChannel",
    async function () {
      const b1 = new BroadcastChannel("comlink_bc_test");
      const b2 = new BroadcastChannel("comlink_bc_test");
      const thing = Comlink.wrap(b1);
      Comlink.expose((b) => 40 + b, b2);
      expect(await thing(2)).to.equal(42);
    }
  );

  // Buffer transfers seem to have regressed in Safari 11.1, it’s fixed in 11.2.
  const isNotSafari11_1 = (_) =>
    !/11\.1(\.[0-9]+)? Safari/.test(navigator.userAgent);
  guardedIt(isNotSafari11_1)("will transfer buffers", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((b) => b.byteLength, this.port2);
    const buffer = new Uint8Array([1, 2, 3]).buffer;
    expect(await thing(Comlink.transfer(buffer, [buffer]))).to.equal(3);
    expect(buffer.byteLength).to.equal(0);
  });

  guardedIt(isNotSafari11_1)("will copy TypedArrays", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((b) => b, this.port2);
    const array = new Uint8Array([1, 2, 3]);
    const receive = await thing(array);
    expect(array).to.not.equal(receive);
    expect(array.byteLength).to.equal(receive.byteLength);
    expect([...array]).to.deep.equal([...receive]);
  });

  guardedIt(isNotSafari11_1)("will copy nested TypedArrays", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((b) => b, this.port2);
    const array = new Uint8Array([1, 2, 3]);
    const receive = await thing({
      v: 1,
      array,
    });
    expect(array).to.not.equal(receive.array);
    expect(array.byteLength).to.equal(receive.array.byteLength);
    expect([...array]).to.deep.equal([...receive.array]);
  });

  guardedIt(isNotSafari11_1)(
    "will transfer deeply nested buffers",
    async function () {
      const thing = Comlink.wrap(this.port1);
      Comlink.expose((a) => a.b.c.d.byteLength, this.port2);
      const buffer = new Uint8Array([1, 2, 3]).buffer;
      expect(
        await thing(Comlink.transfer({ b: { c: { d: buffer } } }, [buffer]))
      ).to.equal(3);
      expect(buffer.byteLength).to.equal(0);
    }
  );

  it("will transfer a message port", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose((a) => a.postMessage("ohai"), this.port2);
    const { port1, port2 } = new MessageChannel();
    await thing(Comlink.transfer(port2, [port2]));
    return new Promise((resolve) => {
      port1.onmessage = (event) => {
        expect(event.data).to.equal("ohai");
        resolve();
      };
    });
  });

  it("will wrap marked return values", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(
      (_) =>
        Comlink.proxy({
          counter: 0,
          inc() {
            this.counter += 1;
          },
        }),
      this.port2
    );
    const obj = await thing();
    expect(await obj.counter).to.equal(0);
    await obj.inc();
    expect(await obj.counter).to.equal(1);
  });

  it("will wrap marked return values from class instance methods", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    const obj = await instance.proxyFunc();
    expect(await obj.counter).to.equal(0);
    await obj.inc();
    expect(await obj.counter).to.equal(1);
  });

  it("will wrap marked parameter values", async function () {
    const thing = Comlink.wrap(this.port1);
    const local = {
      counter: 0,
      inc() {
        this.counter++;
      },
    };
    Comlink.expose(async function (f) {
      await f.inc();
    }, this.port2);
    expect(local.counter).to.equal(0);
    await thing(Comlink.proxy(local));
    expect(await local.counter).to.equal(1);
  });

  it("will wrap marked assignments", function (done) {
    const thing = Comlink.wrap(this.port1);
    const obj = {
      onready: null,
      call() {
        this.onready();
      },
    };
    Comlink.expose(obj, this.port2);

    thing.onready = Comlink.proxy(() => done());
    thing.call();
  });

  it("will wrap marked parameter values, simple function", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(async function (f) {
      await f();
    }, this.port2);
    // Weird code because Mocha
    await new Promise(async (resolve) => {
      thing(Comlink.proxy((_) => resolve()));
    });
  });

  it("will wrap multiple marked parameter values, simple function", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(async function (f1, f2, f3) {
      return (await f1()) + (await f2()) + (await f3());
    }, this.port2);
    // Weird code because Mocha
    expect(
      await thing(
        Comlink.proxy((_) => 1),
        Comlink.proxy((_) => 2),
        Comlink.proxy((_) => 3)
      )
    ).to.equal(6);
  });

  it("will proxy deeply nested values", async function () {
    const thing = Comlink.wrap(this.port1);
    const obj = {
      a: {
        v: 4,
      },
      b: Comlink.proxy({
        v: 5,
      }),
    };
    Comlink.expose(obj, this.port2);

    const a = await thing.a;
    const b = await thing.b;
    expect(await a.v).to.equal(4);
    expect(await b.v).to.equal(5);
    await (a.v = 8);
    await (b.v = 9);
    // Workaround for a weird scheduling inconsistency in Firefox.
    // This test failed, but not when run in isolation, and only
    // in Firefox. I think there might be problem with task ordering.
    await new Promise((resolve) => setTimeout(resolve, 1));
    expect(await thing.a.v).to.equal(4);
    expect(await thing.b.v).to.equal(9);
  });

  it("will handle undefined parameters", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose({ f: (_) => 4 }, this.port2);
    expect(await thing.f(undefined)).to.equal(4);
  });

  it("can handle destructuring", async function () {
    Comlink.expose(
      {
        a: 4,
        get b() {
          return 5;
        },
        c() {
          return 6;
        },
      },
      this.port2
    );
    const { a, b, c } = Comlink.wrap(this.port1);
    expect(await a).to.equal(4);
    expect(await b).to.equal(5);
    expect(await c()).to.equal(6);
  });

  it("lets users define transfer handlers", function (done) {
    Comlink.transferHandlers.set("event", {
      canHandle(obj) {
        return obj instanceof Event;
      },
      serialize(obj) {
        return [obj.data, []];
      },
      deserialize(data) {
        return new MessageEvent("message", { data });
      },
    });

    Comlink.expose((ev) => {
      expect(ev).to.be.an.instanceOf(Event);
      expect(ev.data).to.deep.equal({ a: 1 });
      done();
    }, this.port1);
    const thing = Comlink.wrap(this.port2);

    const { port1, port2 } = new MessageChannel();
    port1.addEventListener("message", thing.bind(this));
    port1.start();
    port2.postMessage({ a: 1 });
  });

  it("can tunnels a new endpoint with createEndpoint", async function () {
    Comlink.expose(
      {
        a: 4,
        c() {
          return 5;
        },
      },
      this.port2
    );
    const proxy = Comlink.wrap(this.port1);
    const otherEp = await proxy[Comlink.createEndpoint]();
    const otherProxy = Comlink.wrap(otherEp);
    expect(await otherProxy.a).to.equal(4);
    expect(await proxy.a).to.equal(4);
    expect(await otherProxy.c()).to.equal(5);
    expect(await proxy.c()).to.equal(5);
  });

  it("released proxy should no longer be useable and throw an exception", async function () {
    const thing = Comlink.wrap(this.port1);
    Comlink.expose(SampleClass, this.port2);
    const instance = await new thing();
    await instance[Comlink.releaseProxy]();
    expect(() => instance.method()).to.throw();
  });

  it("released proxy should invoke finalizer", async function () {
    let finalized = false;
    Comlink.expose(
      {
        a: "thing",
        [Comlink.finalizer]: () => {
          finalized = true;
        },
      },
      this.port2
    );
    const instance = Comlink.wrap(this.port1);
    expect(await instance.a).to.equal("thing");
    await instance[Comlink.releaseProxy]();
    // wait a beat to let the events process
    await new Promise((resolve) => setTimeout(resolve, 1));
    expect(finalized).to.be.true;
  });

  // commented out this test as it could be unreliable in various browsers as
  // it has to wait for GC to kick in which could happen at any timing
  // this does seem to work when testing locally
  it.skip("released proxy via GC should invoke finalizer", async function () {
    let finalized = false;
    Comlink.expose(
      {
        a: "thing",
        [Comlink.finalizer]: () => {
          finalized = true;
        },
      },
      this.port2
    );

    let registry;

    // set a long enough timeout to wait for a garbage collection
    this.timeout(10000);
    // promise will resolve when the proxy is garbage collected
    await new Promise(async (resolve, reject) => {
      registry = new FinalizationRegistry((heldValue) => {
        heldValue();
      });

      const instance = Comlink.wrap(this.port1);
      registry.register(instance, resolve);
      expect(await instance.a).to.equal("thing");
    });
    // wait a beat to let the events process
    await new Promise((resolve) => setTimeout(resolve, 1));
    expect(finalized).to.be.true;
  });

  it("can proxy with a given target", async function () {
    const thing = Comlink.wrap(this.port1, { value: {} });
    Comlink.expose({ value: 4 }, this.port2);
    expect(await thing.value).to.equal(4);
  });

  it("can handle unserializable types", async function () {
    const thing = Comlink.wrap(this.port1, { value: {} });
    Comlink.expose({ value: () => "boom" }, this.port2);

    try {
      await thing.value;
    } catch (err) {
      expect(err.message).to.equal("Unserializable return value");
    }
  });
});

function guardedIt(f) {
  return f() ? it : xit;
}


================================================
FILE: tests/tsconfig.json
================================================
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "noEmit": true
  },
  "include": ["./**/*.ts"]
}


================================================
FILE: tests/two-way-iframe.comlink.test.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as Comlink from "/base/dist/esm/comlink.mjs";

describe("Comlink across iframes", function () {
  beforeEach(function () {
    this.ifr = document.createElement("iframe");
    this.ifr.sandbox.add("allow-scripts", "allow-same-origin");
    this.ifr.src = "/base/tests/fixtures/two-way-iframe.html";
    document.body.appendChild(this.ifr);
    return new Promise((resolve) => (this.ifr.onload = resolve));
  });

  afterEach(function () {
    this.ifr.remove();
  });

  it("can communicate both ways", async function () {
    let called = false;
    const iframe = Comlink.windowEndpoint(this.ifr.contentWindow);
    Comlink.expose((a) => {
      called = true;
      return ++a;
    }, iframe);
    const proxy = Comlink.wrap(iframe);
    expect(await proxy(1, 3)).to.equal(5);
    expect(called).to.equal(true);
  });
});


================================================
FILE: tests/type-checks.ts
================================================
import { assert, Has, NotHas, IsAny, IsExact } from "conditional-type-checks";

import * as Comlink from "../src/comlink.js";

async function closureSoICanUseAwait() {
  {
    function simpleNumberFunction() {
      return 4;
    }

    const proxy = Comlink.wrap<typeof simpleNumberFunction>(0 as any);
    assert<IsAny<typeof proxy>>(false);
    const v = proxy();
    assert<Has<typeof v, Promise<number>>>(true);
  }

  {
    function simpleObjectFunction() {
      return { a: 3 };
    }

    const proxy = Comlink.wrap<typeof simpleObjectFunction>(0 as any);
    const v = await proxy();
    assert<Has<typeof v, { a: number }>>(true);
  }

  {
    async function simpleAsyncFunction() {
      return { a: 3 };
    }

    const proxy = Comlink.wrap<typeof simpleAsyncFunction>(0 as any);
    const v = await proxy();
    assert<Has<typeof v, { a: number }>>(true);
  }

  {
    function functionWithProxy() {
      return Comlink.proxy({ a: 3 });
    }

    const proxy = Comlink.wrap<typeof functionWithProxy>(0 as any);
    const subproxy = await proxy();
    const prop = subproxy.a;
    assert<Has<typeof prop, Promise<number>>>(true);
  }

  {
    class X {
      static staticFunc() {
        return 4;
      }
      private f = 4;
      public g = 9;
      sayHi() {
        return "hi";
      }
    }

    const proxy = Comlink.wrap<typeof X>(0 as any);
    assert<Has<typeof proxy, { staticFunc: () => Promise<number> }>>(true);
    const instance = await new proxy();
    assert<Has<typeof instance, { sayHi: () => Promise<string> }>>(true);
    assert<Has<typeof instance, { g: Promise<number> }>>(true);
    assert<NotHas<typeof instance, { f: Promise<number> }>>(true);
    assert<IsAny<typeof instance>>(false);
  }

  {
    const x = {
      a: 4,
      b() {
        return 9;
      },
      c: {
        d: 3,
      },
    };

    const proxy = Comlink.wrap<typeof x>(0 as any);
    assert<IsAny<typeof proxy>>(false);
    const a = proxy.a;
    assert<Has<typeof a, Promise<number>>>(true);
    assert<IsAny<typeof a>>(false);
    const b = proxy.b;
    assert<Has<typeof b, () => Promise<number>>>(true);
    assert<IsAny<typeof b>>(false);
    const subproxy = proxy.c;
    assert<Has<typeof subproxy, Promise<{ d: number }>>>(true);
    assert<IsAny<typeof subproxy>>(false);
    const copy = await proxy.c;
    assert<Has<typeof copy, { d: number }>>(true);
  }

  {
    Comlink.wrap(new MessageChannel().port1);
    Comlink.expose({}, new MessageChannel().port2);

    interface Baz {
      baz: number;
      method(): number;
    }

    class Foo {
      constructor(cParam: string) {
        const self = this;
        assert<IsExact<typeof self.proxyProp, Bar & Comlink.ProxyMarked>>(true);
      }
      prop1: string = "abc";
      proxyProp = Comlink.proxy(new Bar());
      methodWithTupleParams(...args: [string] | [number, string]): number {
        return 123;
      }
      methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked {
        return Comlink.proxy({ baz: 123, method: () => 123 });
      }
      methodWithProxyParameter(param: Baz & Comlink.ProxyMarked): void {}
    }

    class Bar {
      prop2: string | number = "abc";
      method(param: string): number {
        return 123;
      }
      methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked {
        return Comlink.proxy({ baz: 123, method: () => 123 });
      }
    }
    const proxy = Comlink.wrap<Foo>(Comlink.windowEndpoint(self));
    assert<IsExact<typeof proxy, Comlink.Remote<Foo>>>(true);

    proxy[Comlink.releaseProxy]();
    const endp = proxy[Comlink.createEndpoint]();
    assert<IsExact<typeof endp, Promise<MessagePort>>>(true);

    assert<IsAny<typeof proxy.prop1>>(false);
    assert<Has<typeof proxy.prop1, Promise<string>>>(true);

    const r1 = proxy.methodWithTupleParams(123, "abc");
    assert<IsExact<typeof r1, Promise<number>>>(true);

    const r2 = proxy.methodWithTupleParams("abc");
    assert<IsExact<typeof r2, Promise<number>>>(true);

    assert<
      IsExact<typeof proxy.proxyProp, Comlink.Remote<Bar & Comlink.ProxyMarked>>
    >(true);

    assert<IsAny<typeof proxy.proxyProp.prop2>>(false);
    assert<Has<typeof proxy.proxyProp.prop2, Promise<string>>>(true);
    assert<Has<typeof proxy.proxyProp.prop2, Promise<number>>>(true);

    const r3 = proxy.proxyProp.method("param");
    assert<IsAny<typeof r3>>(false);
    assert<Has<typeof r3, Promise<number>>>(true);

    // @ts-expect-error
    proxy.proxyProp.method(123);

    // @ts-expect-error
    proxy.proxyProp.method();

    const r4 = proxy.methodWithProxiedReturnValue();
    assert<IsAny<typeof r4>>(false);
    assert<
      IsExact<typeof r4, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>>
    >(true);

    const r5 = proxy.proxyProp.methodWithProxiedReturnValue();
    assert<
      IsExact<typeof r5, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>>
    >(true);

    const r6 = (await proxy.methodWithProxiedReturnValue()).baz;
    assert<IsAny<typeof r6>>(false);
    assert<Has<typeof r6, Promise<number>>>(true);

    const r7 = (await proxy.methodWithProxiedReturnValue()).method();
    assert<IsAny<typeof r7>>(false);
    assert<Has<typeof r7, Promise<number>>>(true);

    const ProxiedFooClass = Comlink.wrap<typeof Foo>(
      Comlink.windowEndpoint(self)
    );
    const inst1 = await new ProxiedFooClass("test");
    assert<IsExact<typeof inst1, Comlink.Remote<Foo>>>(true);
    inst1[Comlink.releaseProxy]();
    inst1[Comlink.createEndpoint]();

    // @ts-expect-error
    await new ProxiedFooClass(123);

    // @ts-expect-error
    await new ProxiedFooClass();

    //
    // Tests for advanced proxy use cases
    //

    // Type round trips
    // This tests that Local is the exact inverse of Remote for objects:
    assert<
      IsExact<
        Comlink.Local<Comlink.Remote<Comlink.ProxyMarked>>,
        Comlink.ProxyMarked
      >
    >(true);
    // This tests that Local is the exact inverse of Remote for functions, with one difference:
    // The local version of a remote function can be either implemented as a sync or async function,
    // because Remote<T> always makes the function async.
    assert<
      IsExact<
        Comlink.Local<Comlink.Remote<(a: number) => string>>,
        (a: number) => string | Promise<string>
      >
    >(true);

    interface Subscriber<T> {
      closed?: boolean;
      next?: (value: T) => void;
    }
    interface Unsubscribable {
      unsubscribe(): void;
    }
    /** A Subscribable that can get proxied by Comlink */
    interface ProxyableSubscribable<T> extends Comlink.ProxyMarked {
      subscribe(
        subscriber: Comlink.Remote<Subscriber<T> & Comlink.ProxyMarked>
      ): Unsubscribable & Comlink.ProxyMarked;
    }

    /** Simple parameter object that gets cloned (not proxied) */
    interface Params {
      textDocument: string;
    }

    class Registry {
      async registerProvider(
        provider: Comlink.Remote<
          ((params: Params) => ProxyableSubscribable<string>) &
            Comlink.ProxyMarked
        >
      ) {
        const resultPromise = provider({ textDocument: "foo" });
        assert<
          IsExact<
            typeof resultPromise,
            Promise<Comlink.Remote<ProxyableSubscribable<string>>>
          >
        >(true);
        const result = await resultPromise;

        const subscriptionPromise = result.subscribe({
          [Comlink.proxyMarker]: true,
          next: (value) => {
            assert<IsExact<typeof value, string>>(true);
          },
        });
        assert<
          IsExact<
            typeof subscriptionPromise,
            Promise<Comlink.Remote<Unsubscribable & Comlink.ProxyMarked>>
          >
        >(true);
        const subscriber = Comlink.proxy({
          next: (value: string) => console.log(value),
        });
        result.subscribe(subscriber);

        const r1 = (await subscriptionPromise).unsubscribe();
        assert<IsExact<typeof r1, Promise<void>>>(true);
      }
    }
    const proxy2 = Comlink.wrap<Registry>(Comlink.windowEndpoint(self));

    proxy2.registerProvider(
      // Synchronous callback
      Comlink.proxy(({ textDocument }: Params) => {
        const subscribable = Comlink.proxy({
          subscribe(
            subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked>
          ): Unsubscribable & Comlink.ProxyMarked {
            // Important to test here is that union types (such as Function | undefined) distribute properly
            // when wrapped in Promises/proxied

            assert<IsAny<typeof subscriber.closed>>(false);
            assert<
              IsExact<
                typeof subscriber.closed,
                Promise<true> | Promise<false> | Promise<undefined> | undefined
              >
            >(true);

            assert<IsAny<typeof subscriber.next>>(false);
            assert<
              IsExact<
                typeof subscriber.next,
                | Comlink.Remote<(value: string) => void>
                | Promise<undefined>
                | undefined
              >
            >(true);

            // @ts-expect-error
            subscriber.next();

            if (subscriber.next) {
              // Only checking for presence is not enough, since it could be a Promise
              // @ts-expect-error
              subscriber.next();
            }

            if (typeof subscriber.next === "function") {
              subscriber.next("abc");
            }

            return Comlink.proxy({ unsubscribe() {} });
          },
        });
        assert<Has<typeof subscribable, Comlink.ProxyMarked>>(true);
        return subscribable;
      })
    );
    proxy2.registerProvider(
      // Async callback
      Comlink.proxy(async ({ textDocument }: Params) => {
        const subscribable = Comlink.proxy({
          subscribe(
            subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked>
          ): Unsubscribable & Comlink.ProxyMarked {
            assert<IsAny<typeof subscriber.next>>(false);
            assert<
              IsExact<
                typeof subscriber.next,
                | Comlink.Remote<(value: string) => void>
                | Promise<undefined>
                | undefined
              >
            >(true);

            // Only checking for presence is not enough, since it could be a Promise
            if (typeof subscriber.next === "function") {
              subscriber.next("abc");
            }
            return Comlink.proxy({ unsubscribe() {} });
          },
        });
        return subscribable;
      })
    );
  }

  // Transfer handlers
  {
    const urlTransferHandler: Comlink.TransferHandler<URL, string> = {
      canHandle: (val): val is URL => {
        assert<IsExact<typeof val, unknown>>(true);
        return val instanceof URL;
      },
      serialize: (url) => {
        assert<IsExact<typeof url, URL>>(true);
        return [url.href, []];
      },
      deserialize: (str) => {
        assert<IsExact<typeof str, string>>(true);
        return new URL(str);
      },
    };
    Comlink.transferHandlers.set("URL", urlTransferHandler);
  }
}


================================================
FILE: tests/worker.comlink.test.js
================================================
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as Comlink from "/base/dist/esm/comlink.mjs";

describe("Comlink across workers", function () {
  beforeEach(function () {
    this.worker = new Worker("/base/tests/fixtures/worker.js");
  });

  afterEach(function () {
    this.worker.terminate();
  });

  it("can communicate", async function () {
    const proxy = Comlink.wrap(this.worker);
    expect(await proxy(1, 3)).to.equal(4);
  });

  it("can tunnels a new endpoint with createEndpoint", async function () {
    const proxy = Comlink.wrap(this.worker);
    const otherEp = await proxy[Comlink.createEndpoint]();
    const otherProxy = Comlink.wrap(otherEp);
    expect(await otherProxy(20, 1)).to.equal(21);
  });

  it("releaseProxy closes MessagePort created by createEndpoint", async function () {
    const proxy = Comlink.wrap(this.worker);
    const otherEp = await proxy[Comlink.createEndpoint]();
    const otherProxy = Comlink.wrap(otherEp);
    expect(await otherProxy(20, 1)).to.equal(21);

    await new Promise((resolve) => {
      otherEp.close = resolve; // Resolve the promise when the MessagePort is closed.
      otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort.
    });
  });
});


================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */,
    "module": "esnext" /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "esnext",
      "dom"
    ] /* Specify library files to be included in the compilation:  */,
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true /* Generates corresponding '.d.ts' file. */,
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "removeComments": false,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  },
  "include": ["src/**/*.ts"],
  "exclude": ["dist"]
}
Download .txt
gitextract_piinu2uq/

├── .gitignore
├── .husky/
│   └── pre-commit
├── .travis.yml
├── CHANGELOG.md
├── CODEOWNERS
├── CONTRIBUTING
├── CONTRIBUTORS
├── Dockerfile
├── LICENSE
├── README.md
├── docs/
│   ├── examples/
│   │   ├── 01-simple-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 02-callback-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 03-classes-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 04-eventlistener-example/
│   │   │   ├── README.md
│   │   │   ├── event.transferhandler.js
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 05-serviceworker-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   ├── 06-node-example/
│   │   │   ├── main.mjs
│   │   │   └── worker.mjs
│   │   ├── 07-sharedworker-example/
│   │   │   ├── README.md
│   │   │   ├── index.html
│   │   │   └── worker.js
│   │   └── 99-nonworker-examples/
│   │       └── iframes/
│   │           ├── README.md
│   │           ├── iframe.html
│   │           └── index.html
│   └── index.html
├── karma.conf.js
├── package.json
├── renovate.json
├── rollup.config.mjs
├── src/
│   ├── comlink.ts
│   ├── node-adapter.ts
│   └── protocol.ts
├── structured-clone-table.md
├── tests/
│   ├── cross-origin.comlink.test.js
│   ├── fixtures/
│   │   ├── attack-iframe.html
│   │   ├── iframe.html
│   │   ├── two-way-iframe.html
│   │   └── worker.js
│   ├── iframe.comlink.test.js
│   ├── node/
│   │   ├── main.mjs
│   │   └── worker.mjs
│   ├── same_window.comlink.test.js
│   ├── tsconfig.json
│   ├── two-way-iframe.comlink.test.js
│   ├── type-checks.ts
│   └── worker.comlink.test.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (99 symbols across 15 files)

FILE: docs/examples/01-simple-example/worker.js
  method inc (line 19) | inc() {

FILE: docs/examples/02-callback-example/worker.js
  function remoteFunction (line 17) | async function remoteFunction(cb) {

FILE: docs/examples/03-classes-example/worker.js
  class MyClass (line 17) | class MyClass {
    method constructor (line 18) | constructor(init = 0) {
    method counter (line 23) | get counter() {
    method increment (line 27) | increment(delta = 1) {

FILE: docs/examples/04-eventlistener-example/event.transferhandler.js
  method canHandle (line 2) | canHandle(obj) {
  method serialize (line 5) | serialize(obj) {
  method deserialize (line 17) | deserialize(obj) {

FILE: docs/examples/04-eventlistener-example/worker.js
  method onclick (line 19) | onclick(ev) {

FILE: docs/examples/05-serviceworker-example/worker.js
  method inc (line 22) | inc() {

FILE: docs/examples/06-node-example/main.mjs
  function init (line 5) | async function init() {

FILE: docs/examples/06-node-example/worker.mjs
  method doMath (line 6) | doMath() {

FILE: docs/examples/07-sharedworker-example/worker.js
  method inc (line 19) | inc() {

FILE: rollup.config.mjs
  function config (line 5) | function config({ format, minify, input, ext = "js" }) {

FILE: src/comlink.ts
  type ProxyMarked (line 29) | interface ProxyMarked {
  type Promisify (line 39) | type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
  type Unpromisify (line 46) | type Unpromisify<P> = P extends Promise<infer T> ? T : P;
  type RemoteProperty (line 54) | type RemoteProperty<T> =
  type LocalProperty (line 69) | type LocalProperty<T> = T extends Function | ProxyMarked
  type ProxyOrClone (line 76) | type ProxyOrClone<T> = T extends ProxyMarked ? Remote<T> : T;
  type UnproxyOrClone (line 80) | type UnproxyOrClone<T> = T extends RemoteObject<ProxyMarked>
  type RemoteObject (line 92) | type RemoteObject<T> = { [P in keyof T]: RemoteProperty<T[P]> };
  type LocalObject (line 103) | type LocalObject<T> = { [P in keyof T]: LocalProperty<T[P]> };
  type ProxyMethods (line 108) | interface ProxyMethods {
  type Remote (line 117) | type Remote<T> =
  type MaybePromise (line 143) | type MaybePromise<T> = Promise<T> | T;
  type Local (line 151) | type Local<T> =
  type TransferHandler (line 183) | interface TransferHandler<T, S> {
  method serialize (line 212) | serialize(obj) {
  method deserialize (line 217) | deserialize(port) {
  type ThrownValue (line 223) | interface ThrownValue {
  type SerializedThrownValue (line 227) | type SerializedThrownValue =
  type PendingListenersMap (line 230) | type PendingListenersMap = Map<
  type EndpointWithPendingListeners (line 234) | type EndpointWithPendingListeners = {
  method serialize (line 248) | serialize({ value }) {
  method deserialize (line 264) | deserialize(serialized) {
  function isAllowedOrigin (line 286) | function isAllowedOrigin(
  function expose (line 301) | function expose(
  function isMessagePort (line 394) | function isMessagePort(endpoint: Endpoint): endpoint is MessagePort {
  function closeEndPoint (line 398) | function closeEndPoint(endpoint: Endpoint) {
  function wrap (line 402) | function wrap<T>(ep: Endpoint, target?: any): Remote<T> {
  function throwIfProxyReleased (line 425) | function throwIfProxyReleased(isReleased: boolean) {
  function releaseEndpoint (line 431) | function releaseEndpoint(epWithPendingListeners: EndpointWithPendingList...
  type FinalizationRegistry (line 439) | interface FinalizationRegistry<T> {
  function registerProxy (line 465) | function registerProxy(
  function unregisterProxy (line 476) | function unregisterProxy(proxy: object) {
  function createProxy (line 482) | function createProxy<T>(
  function myFlat (line 568) | function myFlat<T>(arr: (T | T[])[]): T[] {
  function processArguments (line 572) | function processArguments(argumentList: any[]): [WireValue[], Transferab...
  function transfer (line 578) | function transfer<T>(obj: T, transfers: Transferable[]): T {
  function proxy (line 583) | function proxy<T extends {}>(obj: T): T & ProxyMarked {
  function windowEndpoint (line 587) | function windowEndpoint(
  function toWireValue (line 600) | function toWireValue(value: any): [WireValue, Transferable[]] {
  function fromWireValue (line 623) | function fromWireValue(value: WireValue): any {
  function requestResponseMessage (line 632) | function requestResponseMessage(
  function generateUUID (line 649) | function generateUUID(): string {

FILE: src/node-adapter.ts
  type NodeEndpoint (line 9) | interface NodeEndpoint {
  function nodeEndpoint (line 24) | function nodeEndpoint(nep: NodeEndpoint): Endpoint {

FILE: src/protocol.ts
  type EventSource (line 7) | interface EventSource {
  type PostMessageWithOrigin (line 21) | interface PostMessageWithOrigin {
  type Endpoint (line 29) | interface Endpoint extends EventSource {
  type WireValueType (line 35) | const enum WireValueType {
  type RawWireValue (line 42) | interface RawWireValue {
  type HandlerWireValue (line 48) | interface HandlerWireValue {
  type WireValue (line 55) | type WireValue = RawWireValue | HandlerWireValue;
  type MessageID (line 57) | type MessageID = string;
  type MessageType (line 59) | const enum MessageType {
  type GetMessage (line 68) | interface GetMessage {
  type SetMessage (line 74) | interface SetMessage {
  type ApplyMessage (line 81) | interface ApplyMessage {
  type ConstructMessage (line 88) | interface ConstructMessage {
  type EndpointMessage (line 95) | interface EndpointMessage {
  type ReleaseMessage (line 100) | interface ReleaseMessage {
  type Message (line 105) | type Message =

FILE: tests/same_window.comlink.test.js
  class SampleClass (line 16) | class SampleClass {
    method constructor (line 17) | constructor(counterInit = 1) {
    method SOME_NUMBER (line 22) | static get SOME_NUMBER() {
    method ADD (line 26) | static ADD(a, b) {
    method counter (line 30) | get counter() {
    method counter (line 34) | set counter(value) {
    method promise (line 38) | get promise() {
    method method (line 42) | method() {
    method increaseCounter (line 46) | increaseCounter(delta = 1) {
    method promiseFunc (line 50) | promiseFunc() {
    method proxyFunc (line 54) | proxyFunc() {
    method throwsAnError (line 63) | throwsAnError() {
  method throwError (line 123) | async throwError() {
  method inc (line 400) | inc() {
  method inc (line 426) | inc() {
  method call (line 442) | call() {
  method b (line 514) | get b() {
  method c (line 517) | c() {
  method canHandle (line 531) | canHandle(obj) {
  method serialize (line 534) | serialize(obj) {
  method deserialize (line 537) | deserialize(data) {
  method c (line 559) | c() {
  function guardedIt (line 653) | function guardedIt(f) {

FILE: tests/type-checks.ts
  function closureSoICanUseAwait (line 5) | async function closureSoICanUseAwait() {
Condensed preview — 57 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (125K chars).
[
  {
    "path": ".gitignore",
    "chars": 64,
    "preview": "*.pem\n*.swp\nnode_modules\n*.bak\ndist\n.*_cache*\npackage-lock.json\n"
  },
  {
    "path": ".husky/pre-commit",
    "chars": 62,
    "preview": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpm test\n"
  },
  {
    "path": ".travis.yml",
    "chars": 122,
    "preview": "sudo: required\n\nservices:\n  - docker\n\nscript:\n  - docker build -t comlink .\n  - docker run --rm -v `pwd`:/usr/src comlin"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 364,
    "preview": "# v3 -> v4\n\n- Added support for NodeJS 11+ workers\n- `Comlink.proxy()` is now called `Comlink.wrap()`\n- `Comlink.proxyVa"
  },
  {
    "path": "CODEOWNERS",
    "chars": 7,
    "preview": "@surma\n"
  },
  {
    "path": "CONTRIBUTING",
    "chars": 1450,
    "preview": "Want to contribute? Great! First, read this page (including the small print at the end).\n\n### Before you contribute\nBefo"
  },
  {
    "path": "CONTRIBUTORS",
    "chars": 465,
    "preview": "# People who have agreed to one of the CLAs and can contribute patches.\n# The AUTHORS file lists the copyright holders; "
  },
  {
    "path": "Dockerfile",
    "chars": 575,
    "preview": "FROM selenium/node-chrome:latest@sha256:31be7ba7ebe6db9f9b266c10fc5f6fce7568791a6ade91b6b6d20a29a988ef5b\n\nUSER root\n\nRUN"
  },
  {
    "path": "LICENSE",
    "chars": 11341,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 12244,
    "preview": "# Comlink\n\nComlink makes [WebWorkers][webworker] enjoyable. Comlink is a **tiny library (1.1kB)**, that removes the ment"
  },
  {
    "path": "docs/examples/01-simple-example/README.md",
    "chars": 72,
    "preview": "This example shows how to setup Comlink between a website and a worker.\n"
  },
  {
    "path": "docs/examples/01-simple-example/index.html",
    "chars": 493,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/01-simple-example/worker.js",
    "chars": 812,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/02-callback-example/README.md",
    "chars": 42,
    "preview": "This example shows how to pass callbacks.\n"
  },
  {
    "path": "docs/examples/02-callback-example/index.html",
    "chars": 414,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/02-callback-example/worker.js",
    "chars": 833,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/03-classes-example/README.md",
    "chars": 50,
    "preview": "This example shows how to export and use classes.\n"
  },
  {
    "path": "docs/examples/03-classes-example/index.html",
    "chars": 660,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/03-classes-example/worker.js",
    "chars": 954,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/04-eventlistener-example/README.md",
    "chars": 108,
    "preview": "This example shows how a simple `TransferHandler` can allow to use remote event listeners or event targets.\n"
  },
  {
    "path": "docs/examples/04-eventlistener-example/event.transferhandler.js",
    "chars": 420,
    "preview": "Comlink.transferHandlers.set(\"event\", {\n  canHandle(obj) {\n    return obj instanceof Event;\n  },\n  serialize(obj) {\n    "
  },
  {
    "path": "docs/examples/04-eventlistener-example/index.html",
    "chars": 490,
    "preview": "<!DOCTYPE html>\nOpen DevTools and click the button.\n<button id=\"mainbtn\" class=\"btn btn--big\">Click me</button>\n<script "
  },
  {
    "path": "docs/examples/04-eventlistener-example/worker.js",
    "chars": 945,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/05-serviceworker-example/README.md",
    "chars": 80,
    "preview": "This example shows how to setup Comlink between a website and a service worker.\n"
  },
  {
    "path": "docs/examples/05-serviceworker-example/index.html",
    "chars": 755,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/05-serviceworker-example/worker.js",
    "chars": 1035,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/06-node-example/main.mjs",
    "chars": 328,
    "preview": "import { Worker } from \"worker_threads\";\nimport * as Comlink from \"../../../dist/esm/comlink.mjs\";\nimport nodeEndpoint f"
  },
  {
    "path": "docs/examples/06-node-example/worker.mjs",
    "chars": 263,
    "preview": "import { parentPort } from \"worker_threads\";\nimport * as Comlink from \"../../../dist/esm/comlink.mjs\";\nimport nodeEndpoi"
  },
  {
    "path": "docs/examples/07-sharedworker-example/README.md",
    "chars": 80,
    "preview": "This example shows how to setup Comlink between a website and a `SharedWorker`.\n"
  },
  {
    "path": "docs/examples/07-sharedworker-example/index.html",
    "chars": 635,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/07-sharedworker-example/worker.js",
    "chars": 1075,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/README.md",
    "chars": 115,
    "preview": "This example shows how to set up Comlink between a window and an embedded iframe using `Comlink.windowEndpoint()`.\n"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/iframe.html",
    "chars": 298,
    "preview": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  /"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/index.html",
    "chars": 489,
    "preview": "<!DOCTYPE html>\n\n<iframe src=\"iframe.html\"></iframe>\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.co"
  },
  {
    "path": "docs/index.html",
    "chars": 107,
    "preview": "<!DOCTYPE html>\n<meta\n  http-equiv=\"refresh\"\n  content=\"0; https://github.com/GoogleChromeLabs/comlink\"\n/>\n"
  },
  {
    "path": "karma.conf.js",
    "chars": 2027,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "package.json",
    "chars": 1708,
    "preview": "{\n  \"name\": \"comlink\",\n  \"version\": \"4.4.2\",\n  \"description\": \"Comlink makes WebWorkers enjoyable\",\n  \"main\": \"dist/umd/"
  },
  {
    "path": "renovate.json",
    "chars": 56,
    "preview": "{\n  \"extends\": [\":library\"],\n  \"assignees\": [\"surma\"]\n}\n"
  },
  {
    "path": "rollup.config.mjs",
    "chars": 1477,
    "preview": "import typescript from \"@rollup/plugin-typescript\";\nimport terser from \"@rollup/plugin-terser\";\nimport { sync } from \"ri"
  },
  {
    "path": "src/comlink.ts",
    "chars": 20181,
    "preview": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  Endpoint,\n  EventSou"
  },
  {
    "path": "src/node-adapter.ts",
    "chars": 1125,
    "preview": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Endpoint } from \"./pro"
  },
  {
    "path": "src/protocol.ts",
    "chars": 1981,
    "preview": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface EventSource {\n"
  },
  {
    "path": "structured-clone-table.md",
    "chars": 3458,
    "preview": "# Behavior of [Structured Clone]\n\n[Structured clone] is JavaScript’s algorithm to create “deep copies” of values. It is "
  },
  {
    "path": "tests/cross-origin.comlink.test.js",
    "chars": 3464,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tests/fixtures/attack-iframe.html",
    "chars": 514,
    "preview": "<html>\n  <body>\n    <script>\n      window.addEventListener(\"message\", (ev) => {\n        if (ev.data === \"start\") {\n     "
  },
  {
    "path": "tests/fixtures/iframe.html",
    "chars": 163,
    "preview": "<script type=\"module\">\n  import * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\n  Comlink.expose((a, b) => a + b, Comli"
  },
  {
    "path": "tests/fixtures/two-way-iframe.html",
    "chars": 306,
    "preview": "<script type=\"module\">\n  import * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\n  const parentEndpoint = Comlink.window"
  },
  {
    "path": "tests/fixtures/worker.js",
    "chars": 687,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tests/iframe.comlink.test.js",
    "chars": 1256,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tests/node/main.mjs",
    "chars": 1466,
    "preview": "import { Worker } from \"worker_threads\";\nimport * as Comlink from \"../../dist/esm/comlink.mjs\";\nimport nodeEndpoint from"
  },
  {
    "path": "tests/node/worker.mjs",
    "chars": 220,
    "preview": "import { parentPort } from \"worker_threads\";\nimport * as Comlink from \"../../dist/esm/comlink.mjs\";\nimport nodeEndpoint "
  },
  {
    "path": "tests/same_window.comlink.test.js",
    "chars": 19663,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tests/tsconfig.json",
    "chars": 111,
    "preview": "{\n  \"extends\": \"../tsconfig.json\",\n  \"compilerOptions\": {\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*.ts\"]\n}\n"
  },
  {
    "path": "tests/two-way-iframe.comlink.test.js",
    "chars": 1443,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tests/type-checks.ts",
    "chars": 11179,
    "preview": "import { assert, Has, NotHas, IsAny, IsExact } from \"conditional-type-checks\";\n\nimport * as Comlink from \"../src/comlink"
  },
  {
    "path": "tests/worker.comlink.test.js",
    "chars": 1823,
    "preview": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "tsconfig.json",
    "chars": 4668,
    "preview": "{\n  \"compilerOptions\": {\n    /* Basic Options */\n    \"target\": \"es2015\" /* Specify ECMAScript target version: 'ES3' (def"
  }
]

About this extraction

This page contains the full source code of the GoogleChromeLabs/comlink GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 57 files (114.5 KB), approximately 29.3k tokens, and a symbol index with 99 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!