Skip to content

Commit

Permalink
Merge branch 'issue-398'
Browse files Browse the repository at this point in the history
  • Loading branch information
surma committed Nov 19, 2019
2 parents d1389fc + ec67bf1 commit 895cbd4
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
16 changes: 10 additions & 6 deletions src/comlink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
PostMessageWithOrigin,
WireValue,
WireValueType
} from "./protocol.js";
} from "./protocol";
export { Endpoint };

export const proxyMarker = Symbol("Comlink.proxy");
Expand Down Expand Up @@ -66,7 +66,10 @@ export type Remote<T> =
T extends boolean
? Promise<boolean>
: unknown
);
) & {
[createEndpoint]: MessagePort;
[releaseProxy]: () => void;
};

declare var x: Remote<number>;

Expand Down Expand Up @@ -202,8 +205,8 @@ function closeEndPoint(endpoint: Endpoint) {
if (isMessagePort(endpoint)) endpoint.close();
}

export function wrap<T>(ep: Endpoint): Remote<T> {
return createProxy<T>(ep) as any;
export function wrap<T>(ep: Endpoint, target?: any): Remote<T> {
return createProxy<T>(ep, [], target) as any;
}

function throwIfProxyReleased(isReleased: boolean) {
Expand All @@ -214,10 +217,11 @@ function throwIfProxyReleased(isReleased: boolean) {

function createProxy<T>(
ep: Endpoint,
path: (string | number | symbol)[] = []
path: (string | number | symbol)[] = [],
target: object = function() {}
): Remote<T> {
let isProxyReleased = false;
const proxy = new Proxy(function() {}, {
const proxy = new Proxy(target, {
get(_target, prop) {
throwIfProxyReleased(isProxyReleased);
if (prop === releaseProxy) {
Expand Down
2 changes: 1 addition & 1 deletion src/node-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* limitations under the License.
*/

import { Endpoint } from "./protocol.js";
import { Endpoint } from "./protocol";

export interface NodeEndpoint {
postMessage(message: any, transfer?: any[]): void;
Expand Down
6 changes: 6 additions & 0 deletions tests/same_window.comlink.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,12 @@ describe("Comlink in the same realm", function() {
await instance[Comlink.releaseProxy]();
expect(() => instance.method()).to.throw();
});

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);
});
});

function guardedIt(f) {
Expand Down

0 comments on commit 895cbd4

Please sign in to comment.