Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add iFrame RPC package initial implementation #1121

Merged
merged 1 commit into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/real-plums-suffer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@near-js/iframe-rpc": patch
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this will increment your package to 0.0.2. You can omit this file and the publish will still occur, but I'm not certain whether you'll get a GitHub release.

Just an FYI, not a blocker

---

Initial implementation - RPC via Iframes
19 changes: 19 additions & 0 deletions packages/iframe-rpc/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
env:
es6: true
node: true
extends:
- 'eslint:recommended'
- 'plugin:@typescript-eslint/eslint-recommended'
- 'plugin:@typescript-eslint/recommended'
parser: '@typescript-eslint/parser'
rules:
no-inner-declarations: off
indent:
- error
- 4
- SwitchCase: 1
'@typescript-eslint/no-explicit-any': off

parserOptions:
ecmaVersion: 2018
sourceType: module
28 changes: 28 additions & 0 deletions packages/iframe-rpc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

# IFrame RPC

The `@near-js/iframe-rpc` package facilitates async RPC calls between cross-domain frames using the `postMessage` API.


## Installation and Usage

Install [`@near-js/iframe-rpc`](https://www.npmjs.com/package/@near-js/iframe-rpc) package from the NPM registry.

```bash
# Using Yarn
yarn add @near-js/iframe-rpc

# Using NPM.
npm install @near-js/iframe-rpc
```

In your app:
```ts
import { IFrameRPC } from "@near-js/iframe-rpc";
const rpc = new IFrameRPC({...})
await rpc.isReady
// Call away!
```

## License
This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details.
19 changes: 19 additions & 0 deletions packages/iframe-rpc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@near-js/iframe-rpc",
"version": "0.0.1",
"description": "IFrame RPC client/server implementation",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"build": "tsc -p ./tsconfig.json"
},
"keywords": [],
"author": "Pagoda",
"license": "ISC",
"dependencies": {
"events": "^3.3.0"
},
"devDependencies": {
"@types/node": "^18.16.1"
}
}
15 changes: 15 additions & 0 deletions packages/iframe-rpc/src/iframe-rpc-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export class IFrameRPCError extends Error {
constructor(
override readonly message: string,
public readonly code: number
) {
super(`Error #${code}: ${message}`);
}

public toResponseError() {
return {
code: this.code,
message: this.message,
};
}
}
206 changes: 206 additions & 0 deletions packages/iframe-rpc/src/iframe-rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import EventEmitter from 'events';

import {IFrameRPCError} from './iframe-rpc-error';
import {
windowReceiver,
IMessageEvent,
IMessagePoster,
IMessageReceiver,
IRPCMethod,
IRPCResponse,
isRPCMessage,
RPCMessage,
} from './types';

function responseObjToError(obj: { code: number; message: string; }) {
return new IFrameRPCError(obj.message, obj.code);
}

export interface IRPCOptions {
target: IMessagePoster;
requesterId: string;
origin?: string;
protocolVersion?: string;
receiver?: IMessageReceiver;
}

const readyId = -1;

export class IFrameRPC extends EventEmitter {
public readonly isReady: Promise<void>;
private calls: {
[id: number]: (err: null | IFrameRPCError, result: any) => void;
} = Object.create(null);
private lastCallId = 0;
private remoteProtocolVersion: string | undefined;
private readonly removeMessageListener: () => void;

constructor(private readonly options: IRPCOptions) {
super();
this.removeMessageListener = (options.receiver || windowReceiver).readMessages(this.messageEventListener);

this.isReady = this.createReadyPromise();
}

private createReadyPromise() {
return new Promise<void>(resolve => {
const response = {protocolVersion: this.options.protocolVersion || '1.0'};

this.bindMethodHandler('ready', () => {
resolve();
return response;
});

this.callMethod<void>('ready', response)
.then(resolve)
.catch(resolve);
});
}

static getReadyInstance(options: IRPCOptions): Promise<IFrameRPC> {
const rpc = new IFrameRPC(options);
return rpc.isReady.then(() => rpc);
}

public bindMethodHandler<T>(method: string, handler: (params: T) => Promise<any> | any): this {
this.on(method, (data: IRPCMethod<T>) => {
new Promise(resolve => resolve(handler(data.params)))
.then((result) => ({
type: 'response',
requesterId: this.options.requesterId,
id: data.id,
result,
} as IRPCResponse<any>))
.catch((err: Error) => ({
type: 'response',
requesterId: this.options.requesterId,
id: data.id,
error:
err instanceof IFrameRPCError
? err.toResponseError()
: {code: 0, message: err.stack || err.message},
} as IRPCResponse<any>))
.then(message => {
this.emit('sendResponse', message);
this.post(message);
});
});

return this;
}

public callMethod<T>(method: string, params: object): Promise<T> {
const id = method === 'ready' ? readyId : this.lastCallId;
const message: IRPCMethod<any> = {
type: 'method',
requesterId: this.options.requesterId,
id,
params,
method,
};

this.emit('sendMethod', message);
this.post(message);

return new Promise((resolve, reject) => {
this.calls[id] = (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
};
});
}

public destroy() {
this.emit('destroy');
this.removeMessageListener();
}

public remoteVersion(): string | undefined {
return this.remoteProtocolVersion;
}

private handleResponse(message: IRPCResponse<any>) {
const handler = this.calls[message.id];
if (!handler) {
return;
}

if (message.error) {
handler(responseObjToError(message.error), null);
} else {
handler(null, message.result);
}

delete this.calls[message.id];
}

private post<T>(message: RPCMessage<T>) {
this.options.target.postMessage(JSON.stringify(message), this.options.origin || '*');
}

static isReadySignal(message: RPCMessage<any>) {
if (message.type === 'method' && message.method === 'ready') {
return true;
}

return message.type === 'response' && message.id === readyId;
}

private messageEventListener = (ev: IMessageEvent) => {
if (this.options.origin && this.options.origin !== '*' && ev.origin !== this.options.origin) {
return;
}

let message: RPCMessage<any>;
try {
message = JSON.parse(ev.data);
} catch (e) {
return;
}

if (!isRPCMessage(message) || message.requesterId !== this.options.requesterId) {
return;
}

if (IFrameRPC.isReadySignal(message)) {
const params: { protocolVersion: string } | undefined =
message.type === 'method' ? message.params : message.result;
this.remoteProtocolVersion = params?.protocolVersion ?? this.remoteProtocolVersion;

this.emit('isReady', true);
return;
}

this.emit('dataReceived', message);
this.handleMessage(message);
};

private handleMessage(message: RPCMessage<any>) {
switch (message.type) {
case 'method':
this.emit('methodReceived', message);
if (this.listeners(message.method).length > 0) {
this.emit(message.method, message);
return;
}

this.post({
type: 'response',
requesterId: this.options.requesterId,
id: message.id,
error: {code: 4003, message: `Unknown method name "${message.method}"`},
result: null,
});
break;
case 'response':
this.emit('responseReceived', message);
this.handleResponse(message);
break;
default:
// Ignore
}
}
}
26 changes: 26 additions & 0 deletions packages/iframe-rpc/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Portions derived from microsoft/mixer JS
/*MIT License

Copyright (c) Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

export * from './iframe-rpc-error';
export * from './iframe-rpc';
export * from './types';
48 changes: 48 additions & 0 deletions packages/iframe-rpc/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export type RPCMessage<T> = IRPCMethod<T> | IRPCResponse<T>;

export interface IRPCMethod<T> {
type: 'method';
requesterId: string;
id: number;
method: string;
params: T;
}

export interface IRPCResponse<T> {
type: 'response';
requesterId: string;
id: number;
result: T;
error?: {
code: number;
message: string;
};
}

export function isRPCMessage(data: any): data is RPCMessage<any> {
return (data.type === 'method' || data.type === 'response')
&& typeof data.id === 'number'
&& typeof data.requesterId === 'string';
}

export interface IMessageEvent {
data: any;
origin: string;
}

export interface IMessagePoster {
postMessage(data: any, targetOrigin: string): void;
}

export interface IMessageReceiver {
readMessages(callback: (ev: IMessageEvent) => void): () => void;
}

export const windowReceiver: IMessageReceiver = {
readMessages(callback) {
window.addEventListener('message', callback);

// Unsubscribe handler for consumers to call to stop listening
return () => window.removeEventListener('message', callback);
},
};
9 changes: 9 additions & 0 deletions packages/iframe-rpc/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.browser.json",
"compilerOptions": {
"outDir": "./lib",
},
"files": [
"src/index.ts"
]
}
Loading