prpc-postmessage 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -0
- package/dist/index.d.ts +56 -0
- package/dist/prpc-postmessage.cjs +1 -0
- package/dist/prpc-postmessage.js +106 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Colin Huang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# prpc-postmessage
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+

|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
A Promise-based RPC programming experience built on **postMessage**.
|
|
9
|
+
|
|
10
|
+
`prpc-postmessage` provides a lightweight and type-safe Promise RPC layer that makes it easy to call methods across different JavaScript execution contexts, including:
|
|
11
|
+
|
|
12
|
+
- Browser windows and iframes
|
|
13
|
+
- Main thread ↔ Service Worker
|
|
14
|
+
- Figma plugin ↔ UI
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## ✨ Features
|
|
19
|
+
|
|
20
|
+
- Promise-based RPC API
|
|
21
|
+
- TypeScript-first, fully typed methods
|
|
22
|
+
- Built on standard `postMessage`
|
|
23
|
+
- Works with Service Workers
|
|
24
|
+
- No runtime dependencies
|
|
25
|
+
- Suitable for Web and Figma plugin environments
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 📦 Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pnpm add prpc-postmessage
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
##🚀 Basic Usage
|
|
36
|
+
|
|
37
|
+
### Service Worker (RPC Server)
|
|
38
|
+
```javascript
|
|
39
|
+
import { RPCServer } from 'prpc-postmessage';
|
|
40
|
+
|
|
41
|
+
class WorkerService {
|
|
42
|
+
async add(a: number, b: number): Promise<number> {
|
|
43
|
+
return a + b;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async getVersion(): Promise<string> {
|
|
47
|
+
return 'v1.0.0';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
new RPCServer(WorkerService);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Web / Client (RPC Client)
|
|
55
|
+
```javascript
|
|
56
|
+
import { RPCClient } from 'prpc-postmessage';
|
|
57
|
+
|
|
58
|
+
await navigator.serviceWorker.ready;
|
|
59
|
+
interface PRCAPI {
|
|
60
|
+
getVersion(): Promise<string>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const client = new RPCClient<PRCAPI>({
|
|
64
|
+
target: navigator.serviceWorker
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const version = await client.getVersion();
|
|
68
|
+
console.log(version);
|
|
69
|
+
```
|
|
70
|
+
## Demo
|
|
71
|
+
[Service worker demo](https://github.com/chuandeng/prpc-postMessage/tree/main/examples/service-worker)
|
|
72
|
+
[Iframe Demo](https://github.com/chuandeng/prpc-postMessage/tree/main/examples/iframe)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
## 🧩 Supported Scenarios
|
|
76
|
+
• Window ↔ Window
|
|
77
|
+
• Window ↔ iframe
|
|
78
|
+
• Main thread ↔ Service Worker
|
|
79
|
+
• Figma plugin ↔ UI
|
|
80
|
+
|
|
81
|
+
## ⚠️ Notes
|
|
82
|
+
• The Service Worker must be activated and controlling the page
|
|
83
|
+
• Always wait for navigator.serviceWorker.ready before creating the client
|
|
84
|
+
• Messages are transported via postMessage
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
## 📄 License
|
|
88
|
+
|
|
89
|
+
MIT © chuandeng
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export declare class RPCClient<T = any> {
|
|
2
|
+
private _type?;
|
|
3
|
+
private target;
|
|
4
|
+
private origin;
|
|
5
|
+
private timeout;
|
|
6
|
+
private typePrefix;
|
|
7
|
+
private pendingRequests;
|
|
8
|
+
private isServiceWorker;
|
|
9
|
+
constructor(options: RPCClientOptions);
|
|
10
|
+
private setupListener;
|
|
11
|
+
private request;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export declare interface RPCClientOptions {
|
|
15
|
+
target: Window | ServiceWorkerContainer | MessagePort;
|
|
16
|
+
origin?: string;
|
|
17
|
+
timeout?: number;
|
|
18
|
+
typePrefix?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export declare interface RPCRequest {
|
|
22
|
+
jsonrpc: '2.0';
|
|
23
|
+
method: string;
|
|
24
|
+
params: any[];
|
|
25
|
+
id: string;
|
|
26
|
+
type?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export declare interface RPCResponse {
|
|
30
|
+
jsonrpc: '2.0';
|
|
31
|
+
result?: any;
|
|
32
|
+
error?: {
|
|
33
|
+
code: number;
|
|
34
|
+
message: string;
|
|
35
|
+
data?: any;
|
|
36
|
+
};
|
|
37
|
+
id: string;
|
|
38
|
+
type?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export declare class RPCServer {
|
|
42
|
+
private service;
|
|
43
|
+
private source?;
|
|
44
|
+
private origin;
|
|
45
|
+
private typePrefix;
|
|
46
|
+
constructor(service: any, options?: RPCServerOptions);
|
|
47
|
+
private setupListener;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export declare interface RPCServerOptions {
|
|
51
|
+
source?: Window | ServiceWorker | MessagePort;
|
|
52
|
+
origin?: string;
|
|
53
|
+
typePrefix?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export { }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var l=Object.defineProperty;var f=(n,t,s)=>t in n?l(n,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):n[t]=s;var r=(n,t,s)=>f(n,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class h{constructor(t){r(this,"_type");r(this,"target");r(this,"origin");r(this,"timeout");r(this,"typePrefix");r(this,"pendingRequests",new Map);r(this,"isServiceWorker",!1);return this.target=t.target,this.origin=t.origin||"*",this.timeout=t.timeout||1e4,this.typePrefix=t.typePrefix||"prc",this.isServiceWorker=this.target instanceof ServiceWorkerContainer,this.setupListener(),new Proxy(this,{get:(s,e)=>{if(e in s)return s[e];if(typeof e=="string"&&e!=="then")return(...o)=>this.request(e,o)}})}setupListener(){const t=s=>{if(s.type!=="message")return;const e=s.data;if(!e||e.jsonrpc!=="2.0"||!e.id)return;const o=`${this.typePrefix}-response`;if(!(e.type&&e.type!==o)&&this.pendingRequests.has(e.id)){const{resolve:c,reject:a,timer:i}=this.pendingRequests.get(e.id);clearTimeout(i),this.pendingRequests.delete(e.id),e.error?a(new Error(e.error.message)):c(e.result)}};console.log("Client listener:",this.target.name),this.isServiceWorker?this.target.addEventListener("message",t):window.addEventListener("message",t)}request(t,s){const e=Math.random().toString(36).substr(2,9);return new Promise((o,c)=>{var d;const a=setTimeout(()=>{this.pendingRequests.has(e)&&(this.pendingRequests.delete(e),c(new Error(`Request timeout for method: ${t}`)))},this.timeout);this.pendingRequests.set(e,{resolve:o,reject:c,timer:a});const i={jsonrpc:"2.0",method:t,params:s,id:e,type:`${this.typePrefix}-request`};this.isServiceWorker?(console.log("Sending request to Service Worker:",i),(d=this.target.controller)==null||d.postMessage(i)):typeof window<"u"&&this.target instanceof Window?(console.log("Sending request to Window:",this.target.name,i),this.target.postMessage(i,this.origin)):this.target.postMessage(i)})}}class p{constructor(t,s={}){r(this,"service");r(this,"source");r(this,"origin","*");r(this,"typePrefix","prc");this.service=typeof t=="function"?new t:t,this.source=s.source,this.origin=s.origin||"*",this.typePrefix=s.typePrefix||"prc",this.setupListener()}setupListener(){const t=async s=>{const e=s.data;if(console.log("Received message:",e),!e||e.jsonrpc!=="2.0"||!e.method)return;const o=`${this.typePrefix}-request`;if(!(e.type&&e.type!==o)&&typeof this.service[e.method]=="function"){let c,a;try{c=await this.service[e.method](...e.params),console.log(`[RPCServer] Method ${e.method} executed successfully`)}catch(u){a={code:-32603,message:u.message||"Internal error"}}const i={jsonrpc:"2.0",id:e.id,result:c,error:a,type:`${this.typePrefix}-response`},d=this.source??s.source;if(d){const u=d;let g=!1;try{g="closed"in u}catch{g=!0}g?u.postMessage(i,this.origin):u.postMessage(i)}}};typeof window<"u"?(window.addEventListener("message",t),console.log("[RPCServer] setupListener for window",window.name)):typeof self<"u"&&(self.addEventListener("message",t),console.log("[RPCServer] setupListener for self",self))}}exports.RPCClient=h;exports.RPCServer=p;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
var f = Object.defineProperty;
|
|
2
|
+
var h = (n, t, s) => t in n ? f(n, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : n[t] = s;
|
|
3
|
+
var r = (n, t, s) => h(n, typeof t != "symbol" ? t + "" : t, s);
|
|
4
|
+
class y {
|
|
5
|
+
constructor(t) {
|
|
6
|
+
// @ts-ignore
|
|
7
|
+
r(this, "_type");
|
|
8
|
+
r(this, "target");
|
|
9
|
+
r(this, "origin");
|
|
10
|
+
r(this, "timeout");
|
|
11
|
+
r(this, "typePrefix");
|
|
12
|
+
r(this, "pendingRequests", /* @__PURE__ */ new Map());
|
|
13
|
+
r(this, "isServiceWorker", !1);
|
|
14
|
+
return this.target = t.target, this.origin = t.origin || "*", this.timeout = t.timeout || 1e4, this.typePrefix = t.typePrefix || "prc", this.isServiceWorker = this.target instanceof ServiceWorkerContainer, this.setupListener(), new Proxy(this, {
|
|
15
|
+
get: (s, e) => {
|
|
16
|
+
if (e in s)
|
|
17
|
+
return s[e];
|
|
18
|
+
if (typeof e == "string" && e !== "then")
|
|
19
|
+
return (...o) => this.request(e, o);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
setupListener() {
|
|
24
|
+
const t = (s) => {
|
|
25
|
+
if (s.type !== "message")
|
|
26
|
+
return;
|
|
27
|
+
const e = s.data;
|
|
28
|
+
if (!e || e.jsonrpc !== "2.0" || !e.id)
|
|
29
|
+
return;
|
|
30
|
+
const o = `${this.typePrefix}-response`;
|
|
31
|
+
if (!(e.type && e.type !== o) && this.pendingRequests.has(e.id)) {
|
|
32
|
+
const { resolve: c, reject: a, timer: i } = this.pendingRequests.get(e.id);
|
|
33
|
+
clearTimeout(i), this.pendingRequests.delete(e.id), e.error ? a(new Error(e.error.message)) : c(e.result);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
console.log("Client listener:", this.target.name), this.isServiceWorker ? this.target.addEventListener("message", t) : window.addEventListener("message", t);
|
|
37
|
+
}
|
|
38
|
+
request(t, s) {
|
|
39
|
+
const e = Math.random().toString(36).substr(2, 9);
|
|
40
|
+
return new Promise((o, c) => {
|
|
41
|
+
var d;
|
|
42
|
+
const a = setTimeout(() => {
|
|
43
|
+
this.pendingRequests.has(e) && (this.pendingRequests.delete(e), c(new Error(`Request timeout for method: ${t}`)));
|
|
44
|
+
}, this.timeout);
|
|
45
|
+
this.pendingRequests.set(e, { resolve: o, reject: c, timer: a });
|
|
46
|
+
const i = {
|
|
47
|
+
jsonrpc: "2.0",
|
|
48
|
+
method: t,
|
|
49
|
+
params: s,
|
|
50
|
+
id: e,
|
|
51
|
+
type: `${this.typePrefix}-request`
|
|
52
|
+
};
|
|
53
|
+
this.isServiceWorker ? (console.log("Sending request to Service Worker:", i), (d = this.target.controller) == null || d.postMessage(i)) : typeof window < "u" && this.target instanceof Window ? (console.log("Sending request to Window:", this.target.name, i), this.target.postMessage(i, this.origin)) : this.target.postMessage(i);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
class m {
|
|
58
|
+
constructor(t, s = {}) {
|
|
59
|
+
r(this, "service");
|
|
60
|
+
r(this, "source");
|
|
61
|
+
r(this, "origin", "*");
|
|
62
|
+
r(this, "typePrefix", "prc");
|
|
63
|
+
this.service = typeof t == "function" ? new t() : t, this.source = s.source, this.origin = s.origin || "*", this.typePrefix = s.typePrefix || "prc", this.setupListener();
|
|
64
|
+
}
|
|
65
|
+
setupListener() {
|
|
66
|
+
const t = async (s) => {
|
|
67
|
+
const e = s.data;
|
|
68
|
+
if (console.log("Received message:", e), !e || e.jsonrpc !== "2.0" || !e.method)
|
|
69
|
+
return;
|
|
70
|
+
const o = `${this.typePrefix}-request`;
|
|
71
|
+
if (!(e.type && e.type !== o) && typeof this.service[e.method] == "function") {
|
|
72
|
+
let c, a;
|
|
73
|
+
try {
|
|
74
|
+
c = await this.service[e.method](...e.params), console.log(`[RPCServer] Method ${e.method} executed successfully`);
|
|
75
|
+
} catch (u) {
|
|
76
|
+
a = {
|
|
77
|
+
code: -32603,
|
|
78
|
+
message: u.message || "Internal error"
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const i = {
|
|
82
|
+
jsonrpc: "2.0",
|
|
83
|
+
id: e.id,
|
|
84
|
+
result: c,
|
|
85
|
+
error: a,
|
|
86
|
+
type: `${this.typePrefix}-response`
|
|
87
|
+
}, d = this.source ?? s.source;
|
|
88
|
+
if (d) {
|
|
89
|
+
const u = d;
|
|
90
|
+
let g = !1;
|
|
91
|
+
try {
|
|
92
|
+
g = "closed" in u;
|
|
93
|
+
} catch {
|
|
94
|
+
g = !0;
|
|
95
|
+
}
|
|
96
|
+
g ? u.postMessage(i, this.origin) : u.postMessage(i);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
typeof window < "u" ? (window.addEventListener("message", t), console.log("[RPCServer] setupListener for window", window.name)) : typeof self < "u" && (self.addEventListener("message", t), console.log("[RPCServer] setupListener for self", self));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
export {
|
|
104
|
+
y as RPCClient,
|
|
105
|
+
m as RPCServer
|
|
106
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "prpc-postmessage",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A Promise-based RPC layer built on postMessage for Web, Service Workers, and Figma plugins.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"postMessage",
|
|
7
|
+
"rpc",
|
|
8
|
+
"promise",
|
|
9
|
+
"service-worker",
|
|
10
|
+
"figma-plugin",
|
|
11
|
+
"cross-window",
|
|
12
|
+
"web"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/chuandeng/prpc-postMessage.git"
|
|
17
|
+
},
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/chuandeng/prpc-postMessage/issues"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/chuandeng/prpc-postMessage#readme",
|
|
22
|
+
"main": "dist/prpc-postmessage.umd.js",
|
|
23
|
+
"module": "dist/prpc-postmessage.mjs",
|
|
24
|
+
"types": "dist/index.d.ts",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/prpc-postmessage.mjs",
|
|
30
|
+
"require": "./dist/prpc-postmessage.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"author": "chuandeng<chuandeng99@sohu.com>",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^25.0.3",
|
|
40
|
+
"typescript": "^5.9.3",
|
|
41
|
+
"vite": "^5.4.21",
|
|
42
|
+
"vite-plugin-dts": "^4.5.4",
|
|
43
|
+
"rimraf": "^5.0.0",
|
|
44
|
+
"eslint": "^8.56.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"dev": "vite",
|
|
51
|
+
"demo-worker": "vite --open /examples/service-worker/index.html",
|
|
52
|
+
"demo-iframe": "vite --open /examples/iframe/index.html",
|
|
53
|
+
"build": "tsc && vite build",
|
|
54
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
55
|
+
"clean": "rimraf dist",
|
|
56
|
+
"lint": "eslint .",
|
|
57
|
+
"typecheck": "tsc --noEmit"
|
|
58
|
+
}
|
|
59
|
+
}
|