rimless 0.4.0 → 0.5.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rimless",
3
3
  "author": "Aurélien Franky",
4
- "version": "0.4.0",
4
+ "version": "0.5.0",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/au-re/rimless",
7
7
  "description": "event base communication made easy with a promise-based API wrapping `postMessage`",
@@ -14,8 +14,9 @@
14
14
  ],
15
15
  "scripts": {
16
16
  "dev": "vite",
17
+ "format": "npx prettier --check \"./src/**/*.{js,jsx,ts,tsx,css,scss,html,md}\" --write",
17
18
  "build": "tsc -b && vite build",
18
- "lint": "eslint . --ignore-pattern '**/*.min.js'",
19
+ "lint": "eslint . --ignore-pattern='lib/*' --ignore-pattern='lib/**' --ignore-pattern '**/*.min.js'",
19
20
  "test": "vitest run",
20
21
  "preview": "vite preview",
21
22
  "storybook": "storybook dev -p 6006",
@@ -43,11 +44,12 @@
43
44
  "eslint": "^9.12.0",
44
45
  "globals": "^15.11.0",
45
46
  "happy-dom": "^15.7.4",
47
+ "prettier": "^3.5.3",
46
48
  "storybook": "^8.2.9",
47
49
  "terser": "^5.34.1",
48
50
  "typescript": "^5.5.3",
49
51
  "typescript-eslint": "^8.8.1",
50
- "vite": "^5.4.1",
52
+ "vite": "^6.3.3",
51
53
  "vite-plugin-dts": "^4.2.4",
52
54
  "vitest": "^2.0.5"
53
55
  },
package/lib/guest.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import { EventHandlers, IConnection, ISchema } from './types';
2
- declare function connect(schema?: ISchema, eventHandlers?: EventHandlers): Promise<IConnection>;
3
- declare const _default: {
4
- connect: typeof connect;
5
- };
6
- export default _default;
package/lib/helpers.d.ts DELETED
@@ -1,23 +0,0 @@
1
- export declare const CONNECTION_TIMEOUT = 1000;
2
- /**
3
- * check if run in a webworker
4
- *
5
- * @param event
6
- */
7
- export declare function isWorker(): boolean;
8
- /**
9
- * we cannot send functions through postMessage
10
- * extract the path to all functions in the schema
11
- *
12
- * @param obj
13
- */
14
- export declare function extractMethods(obj: any): string[];
15
- /**
16
- * convert the url into an origin (remove paths)
17
- *
18
- * @param url
19
- */
20
- export declare function getOriginFromURL(url: string | null): string;
21
- export declare function get(obj: any, path: string | Array<string | number>, defaultValue?: any): any;
22
- export declare function set(obj: any, path: string | (string | number)[], value: any): any;
23
- export declare function generateId(length?: number): string;
package/lib/host.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { IConnection, ISchema } from './types';
2
- /**
3
- * Perform a handshake with the target iframe, when the handshake is confirmed
4
- * resolve the connection object containing RPCs and properties
5
- *
6
- * @param iframe
7
- * @param schema
8
- * @returns Promise
9
- */
10
- declare function connect(guest: HTMLIFrameElement | Worker, schema?: ISchema): Promise<IConnection>;
11
- declare const _default: {
12
- connect: typeof connect;
13
- };
14
- export default _default;
package/lib/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import { default as guest } from './guest';
2
- import { default as host } from './host';
3
- export { host, guest };
4
- export * from './types';
package/lib/rimless.js DELETED
@@ -1,187 +0,0 @@
1
- function h() {
2
- return typeof window > "u" && typeof self < "u";
3
- }
4
- function L(t) {
5
- const o = [];
6
- return function s(n, r = "") {
7
- Object.keys(n).forEach((e) => {
8
- const c = r ? `${r}.${e}` : e;
9
- n[e] === Object(n[e]) && s(n[e], c), typeof n[e] == "function" && o.push(c);
10
- });
11
- }(t), o;
12
- }
13
- const N = /^(https?:|file:)?\/\/([^/:]+)?(:(\d+))?/, O = { "http:": "80", "https:": "443" };
14
- function C(t) {
15
- const { location: o } = document, s = N.exec(t || "");
16
- let n, r, e;
17
- if (s ? [, n = o.protocol, r, , e] = s : (n = o.protocol, r = o.hostname, e = o.port), n === "file:")
18
- return "null";
19
- const c = e && e !== O[n] ? `:${e}` : "";
20
- return `${n}//${r}${c}`;
21
- }
22
- function I(t, o, s) {
23
- const n = Array.isArray(o) ? o : o.split(".").filter(Boolean);
24
- let r = t;
25
- for (const e of n)
26
- if (r = r == null ? void 0 : r[e], r === void 0)
27
- return s;
28
- return r;
29
- }
30
- function _(t, o, s) {
31
- if (!t || typeof t != "object") return t;
32
- const n = Array.isArray(o) ? o : o.split(".").map((e) => e.match(/^\d+$/) ? Number(e) : e);
33
- let r = t;
34
- for (let e = 0; e < n.length; e++) {
35
- const c = n[e];
36
- e === n.length - 1 ? r[c] = s : ((!r[c] || typeof r[c] != "object") && (r[c] = typeof n[e + 1] == "number" ? [] : {}), r = r[c]);
37
- }
38
- return t;
39
- }
40
- function m(t = 10) {
41
- const o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
42
- let s = "";
43
- for (let n = 0; n < t; n++)
44
- s += o.charAt(Math.floor(Math.random() * o.length));
45
- return s;
46
- }
47
- var f = /* @__PURE__ */ ((t) => (t.MESSAGE = "message", t))(f || {}), l = /* @__PURE__ */ ((t) => (t.HANDSHAKE_REQUEST = "RIMLESS/HANDSHAKE_REQUEST", t.HANDSHAKE_REPLY = "RIMLESS/HANDSHAKE_REPLY", t.RPC_REQUEST = "RIMLESS/RPC_REQUEST", t.RPC_RESOLVE = "RIMLESS/RPC_RESOLVE", t.RPC_REJECT = "RIMLESS/RPC_REJECT", t))(l || {});
48
- function y(t = {}, o = [], s, n) {
49
- const r = [];
50
- return o.forEach((e) => {
51
- async function c(a) {
52
- const { action: i, callID: u, connectionID: S, callName: d, args: p = [] } = a.data;
53
- if (i !== l.RPC_REQUEST || !u || !d || d !== e || S !== s) return;
54
- const E = {
55
- action: l.RPC_RESOLVE,
56
- callID: u,
57
- callName: d,
58
- connectionID: S,
59
- error: null,
60
- result: null
61
- };
62
- try {
63
- const R = await I(t, e)(...p);
64
- E.result = JSON.parse(JSON.stringify(R));
65
- } catch (R) {
66
- E.action = l.RPC_REJECT, E.error = JSON.parse(JSON.stringify(R, Object.getOwnPropertyNames(R)));
67
- }
68
- n ? n.postMessage(E) : h() ? self.postMessage(E) : a.source.postMessage(E, a.origin);
69
- }
70
- n ? n.addEventListener(f.MESSAGE, c) : self.addEventListener(f.MESSAGE, c), r.push(() => self.removeEventListener(f.MESSAGE, c));
71
- }), () => r.forEach((e) => e());
72
- }
73
- function w(t, o, s, n = [], r) {
74
- return (...e) => new Promise((c, a) => {
75
- const i = m();
76
- function u(d) {
77
- const { callID: p, connectionID: E, callName: R, result: A, error: D, action: g } = d.data;
78
- if (!(!p || !R) && R === t && E === o) {
79
- if (g === l.RPC_RESOLVE) return c(A);
80
- if (g === l.RPC_REJECT) return a(D);
81
- }
82
- }
83
- const S = {
84
- action: l.RPC_REQUEST,
85
- args: JSON.parse(JSON.stringify(e)),
86
- callID: i,
87
- callName: t,
88
- connectionID: o
89
- };
90
- r ? r.addEventListener(f.MESSAGE, u) : self.addEventListener(f.MESSAGE, u), n.push(() => self.removeEventListener(f.MESSAGE, u)), r ? r.postMessage(S) : h() ? self.postMessage(S) : (s.source || s.target).postMessage(S, s.origin);
91
- });
92
- }
93
- function P(t = {}, o = [], s, n, r) {
94
- const e = { ...t }, c = [];
95
- return o.forEach((a) => {
96
- const i = w(a, s, n, c, r);
97
- _(e, a, i);
98
- }), {
99
- remote: e,
100
- unregisterRemote: () => c.forEach((a) => a())
101
- };
102
- }
103
- function H(t = {}, o) {
104
- return new Promise((s) => {
105
- const n = L(t);
106
- async function r(c) {
107
- var E;
108
- if (c.data.action !== l.HANDSHAKE_REPLY) return;
109
- const a = y(t, n, c.data.connectionID), { remote: i, unregisterRemote: u } = P(
110
- c.data.schema,
111
- c.data.methods,
112
- c.data.connectionID,
113
- c
114
- );
115
- await ((E = o == null ? void 0 : o.onConnectionSetup) == null ? void 0 : E.call(o, i));
116
- const S = {
117
- action: l.HANDSHAKE_REPLY,
118
- connectionID: c.data.connectionID
119
- };
120
- return h() ? self.postMessage(S) : window.parent.postMessage(S, "*"), s({ remote: i, close: () => {
121
- self.removeEventListener(f.MESSAGE, r), u(), a();
122
- } });
123
- }
124
- self.addEventListener(f.MESSAGE, r);
125
- const e = {
126
- action: l.HANDSHAKE_REQUEST,
127
- methods: n,
128
- schema: JSON.parse(JSON.stringify(t))
129
- };
130
- h() ? self.postMessage(e) : window.parent.postMessage(e, "*");
131
- });
132
- }
133
- const G = {
134
- connect: H
135
- }, M = {};
136
- function J(t, o) {
137
- const s = t.getAttribute("src"), n = C(s), r = o.origin === n, e = o.source === t.contentWindow;
138
- return r && e;
139
- }
140
- function T(t, o = {}) {
141
- if (!t) throw new Error("a target is required");
142
- const s = t.onerror !== void 0 && t.onmessage !== void 0, n = s ? t : window;
143
- return new Promise((r) => {
144
- const e = m();
145
- function c(i) {
146
- if (!s && !J(t, i) || i.data.action !== l.HANDSHAKE_REQUEST) return;
147
- const u = L(o), S = y(
148
- o,
149
- u,
150
- e,
151
- s ? t : void 0
152
- ), { remote: d, unregisterRemote: p } = P(
153
- i.data.schema,
154
- i.data.methods,
155
- e,
156
- i,
157
- s ? t : void 0
158
- ), E = {
159
- action: l.HANDSHAKE_REPLY,
160
- connectionID: e,
161
- methods: u,
162
- schema: JSON.parse(JSON.stringify(o))
163
- };
164
- s ? t.postMessage(E) : i.source.postMessage(E, i.origin);
165
- const A = { remote: d, close: () => {
166
- n.removeEventListener(f.MESSAGE, c), p(), S(), s && t.terminate();
167
- } };
168
- M[e] = A;
169
- }
170
- n.addEventListener(f.MESSAGE, c);
171
- function a(i) {
172
- if (i.data.action === l.HANDSHAKE_REPLY)
173
- return r(M[i.data.connectionID]);
174
- }
175
- n.addEventListener(f.MESSAGE, a);
176
- });
177
- }
178
- const K = {
179
- connect: T
180
- };
181
- export {
182
- l as actions,
183
- f as events,
184
- G as guest,
185
- K as host
186
- };
187
- //# sourceMappingURL=rimless.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rimless.js","sources":["../src/helpers.ts","../src/types.ts","../src/rpc.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["export const CONNECTION_TIMEOUT = 1000;\n\n/**\n * check if run in a webworker\n *\n * @param event\n */\nexport function isWorker(): boolean {\n return typeof window === \"undefined\" && typeof self !== \"undefined\";\n}\n\n/**\n * we cannot send functions through postMessage\n * extract the path to all functions in the schema\n *\n * @param obj\n */\nexport function extractMethods(obj: any) {\n const paths: string[] = [];\n (function parse(obj: any, path = \"\") {\n Object.keys(obj).forEach((prop) => {\n const propPath = path ? `${path}.${prop}` : prop;\n if (obj[prop] === Object(obj[prop])) {\n parse(obj[prop], propPath);\n }\n if (typeof obj[prop] === \"function\") {\n paths.push(propPath);\n }\n });\n })(obj);\n return paths;\n}\n\nconst urlRegex = /^(https?:|file:)?\\/\\/([^/:]+)?(:(\\d+))?/;\nconst ports: any = { \"http:\": \"80\", \"https:\": \"443\" };\n\n/**\n * convert the url into an origin (remove paths)\n *\n * @param url\n */\nexport function getOriginFromURL(url: string | null) {\n const { location } = document;\n\n const regexResult = urlRegex.exec(url || \"\");\n let protocol;\n let hostname;\n let port;\n\n if (regexResult) {\n // It's an absolute URL. Use the parsed info.\n // regexResult[1] will be undefined if the URL starts with //\n [, protocol = location.protocol, hostname, , port] = regexResult;\n } else {\n // It's a relative path. Use the current location's info.\n protocol = location.protocol;\n hostname = location.hostname;\n port = location.port;\n }\n\n // If the protocol is file, the origin is \"null\"\n // The origin of a document with file protocol is an opaque origin\n // and its serialization \"null\" [1]\n // [1] https://html.spec.whatwg.org/multipage/origin.html#origin\n if (protocol === \"file:\") {\n return \"null\";\n }\n\n // If the port is the default for the protocol, we don't want to add it to the origin string\n // or it won't match the message's event.origin.\n const portSuffix = port && port !== ports[protocol] ? `:${port}` : \"\";\n return `${protocol}//${hostname}${portSuffix}`;\n}\n\nexport function get(obj: any, path: string | Array<string | number>, defaultValue?: any): any {\n const keys = Array.isArray(path) ? path : path.split(\".\").filter(Boolean);\n let result = obj;\n\n for (const key of keys) {\n result = result?.[key];\n if (result === undefined) {\n return defaultValue;\n }\n }\n\n return result;\n}\n\nexport function set(obj: any, path: string | (string | number)[], value: any): any {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const pathArray = Array.isArray(path) ? path : path.split(\".\").map((key) => (key.match(/^\\d+$/) ? Number(key) : key));\n\n let current = obj;\n\n for (let i = 0; i < pathArray.length; i++) {\n const key = pathArray[i];\n\n if (i === pathArray.length - 1) {\n current[key] = value;\n } else {\n if (!current[key] || typeof current[key] !== \"object\") {\n current[key] = typeof pathArray[i + 1] === \"number\" ? [] : {};\n }\n current = current[key];\n }\n }\n\n return obj;\n}\n\nexport function generateId(length: number = 10): string {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n let result = \"\";\n for (let i = 0; i < length; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n}\n","export enum events {\n MESSAGE = \"message\",\n}\n\nexport enum actions {\n HANDSHAKE_REQUEST = \"RIMLESS/HANDSHAKE_REQUEST\",\n HANDSHAKE_REPLY = \"RIMLESS/HANDSHAKE_REPLY\",\n RPC_REQUEST = \"RIMLESS/RPC_REQUEST\",\n RPC_RESOLVE = \"RIMLESS/RPC_RESOLVE\",\n RPC_REJECT = \"RIMLESS/RPC_REJECT\",\n}\n\nexport interface ISchema {\n [prop: string]: any;\n}\n\nexport interface IConnection {\n remote: ISchema;\n close: () => void;\n}\n\nexport interface IConnections {\n [connectionID: string]: IConnection;\n}\n\nexport interface IEvent extends EventListener {\n source?: Window;\n origin?: string;\n data?: IHandshakeRequestPayload | IHandshakeConfirmationPayload | IRPCRequestPayload | IRPCResolvePayload;\n}\n\nexport interface IHandshakeRequestPayload {\n action: actions.HANDSHAKE_REQUEST;\n connectionID?: string;\n methods: any[];\n schema: ISchema;\n}\n\nexport interface IHandshakeConfirmationPayload {\n action: actions.HANDSHAKE_REPLY;\n connectionID: string;\n methods: any[];\n schema: ISchema;\n}\n\nexport interface IRPCRequestPayload {\n action: actions.RPC_REQUEST;\n args: any[];\n callID: string;\n callName: string;\n connectionID?: string;\n}\n\nexport interface IRPCResolvePayload {\n action: actions.RPC_RESOLVE | actions.RPC_REJECT;\n result?: any | null;\n error?: Error | null;\n callID: string;\n callName: string;\n connectionID: string;\n}\n\nexport interface EventHandlers {\n onConnectionSetup: (remote: ISchema) => Promise<void>;\n}\n","import { generateId, get, isWorker, set } from \"./helpers\";\nimport { actions, events, IRPCRequestPayload, IRPCResolvePayload, ISchema } from \"./types\";\n\n/**\n * for each function in the schema\n * 1. subscribe to an event that the remote can call\n * 2. listen for calls from the remote. When called execute the function and emit the results.\n *\n * @param methods an array of method ids from the local schema\n * @param _connectionID\n * @return a function to cancel all subscriptions\n */\nexport function registerLocalMethods(\n schema: ISchema = {},\n methods: any[] = [],\n _connectionID: string,\n guest?: Worker\n): any {\n const listeners: any[] = [];\n methods.forEach((methodName) => {\n // handle a remote calling a local method\n async function handleCall(event: any) {\n const { action, callID, connectionID, callName, args = [] } = event.data as IRPCRequestPayload;\n\n if (action !== actions.RPC_REQUEST) return;\n if (!callID || !callName) return;\n if (callName !== methodName) return;\n if (connectionID !== _connectionID) return;\n\n const payload: IRPCResolvePayload = {\n action: actions.RPC_RESOLVE,\n callID,\n callName,\n connectionID,\n error: null,\n result: null,\n };\n\n // run function and return the results to the remote\n try {\n const result = await get(schema, methodName)(...args);\n payload.result = JSON.parse(JSON.stringify(result));\n } catch (error) {\n payload.action = actions.RPC_REJECT;\n payload.error = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)));\n }\n\n if (guest) guest.postMessage(payload);\n else if (isWorker()) (self as any).postMessage(payload);\n else event.source.postMessage(payload, event.origin);\n }\n\n // subscribe to the call event\n if (guest) guest.addEventListener(events.MESSAGE, handleCall);\n else self.addEventListener(events.MESSAGE, handleCall);\n\n listeners.push(() => self.removeEventListener(events.MESSAGE, handleCall));\n });\n\n return () => listeners.forEach((unregister) => unregister());\n}\n\n/**\n * Create a function that will make an RPC request to the remote with some arguments.\n * Listen to an event that returns the results from the remote.\n *\n * @param _callName\n * @param _connectionID\n * @param event\n * @param listeners\n * @param guest\n *\n * @returns a promise with the result of the RPC\n */\nexport function createRPC(\n _callName: string,\n _connectionID: string,\n event: any,\n listeners: Array<() => void> = [],\n guest?: Worker\n) {\n return (...args: any) => {\n return new Promise((resolve, reject) => {\n const callID = generateId();\n\n // on RPC response\n function handleResponse(event: any) {\n const { callID, connectionID, callName, result, error, action } = event.data as IRPCResolvePayload;\n\n if (!callID || !callName) return;\n if (callName !== _callName) return;\n if (connectionID !== _connectionID) return;\n\n // resolve the response\n if (action === actions.RPC_RESOLVE) return resolve(result);\n if (action === actions.RPC_REJECT) return reject(error);\n }\n\n // send the RPC request with arguments\n const payload = {\n action: actions.RPC_REQUEST,\n args: JSON.parse(JSON.stringify(args)),\n callID,\n callName: _callName,\n connectionID: _connectionID,\n };\n\n if (guest) guest.addEventListener(events.MESSAGE, handleResponse);\n else self.addEventListener(events.MESSAGE, handleResponse);\n listeners.push(() => self.removeEventListener(events.MESSAGE, handleResponse));\n\n if (guest) guest.postMessage(payload);\n else if (isWorker()) (self as any).postMessage(payload);\n else (event.source || event.target).postMessage(payload, event.origin);\n });\n };\n}\n\n/**\n * create an object based on the remote schema and methods. Functions in that object will\n * emit an event that will trigger the RPC on the remote.\n *\n * @param schema\n * @param methods\n * @param _connectionID\n * @param event\n * @param guest\n */\nexport function registerRemoteMethods(\n schema: ISchema = {},\n methods: any[] = [],\n _connectionID: string,\n event: any,\n guest?: Worker\n) {\n const remote = { ...schema };\n const listeners: Array<() => void> = [];\n\n methods.forEach((methodName) => {\n const rpc = createRPC(methodName, _connectionID, event, listeners, guest);\n set(remote, methodName, rpc);\n });\n\n return {\n remote,\n unregisterRemote: () => listeners.forEach((unregister) => unregister()),\n };\n}\n","import { extractMethods, isWorker } from \"./helpers\";\nimport { registerLocalMethods, registerRemoteMethods } from \"./rpc\";\nimport { actions, EventHandlers, events, IConnection, ISchema } from \"./types\";\n\nfunction connect(schema: ISchema = {}, eventHandlers?: EventHandlers): Promise<IConnection> {\n return new Promise((resolve) => {\n const localMethods = extractMethods(schema);\n\n // on handshake response\n async function handleHandshakeResponse(event: any) {\n if (event.data.action !== actions.HANDSHAKE_REPLY) return;\n\n // register local methods\n const unregisterLocal = registerLocalMethods(schema, localMethods, event.data.connectionID);\n\n // register remote methods\n const { remote, unregisterRemote } = registerRemoteMethods(\n event.data.schema,\n event.data.methods,\n event.data.connectionID,\n event\n );\n\n await eventHandlers?.onConnectionSetup?.(remote);\n\n // send a HANDSHAKE REPLY to the host\n const payload = {\n action: actions.HANDSHAKE_REPLY,\n connectionID: event.data.connectionID,\n };\n\n if (isWorker()) self.postMessage(payload);\n else window.parent.postMessage(payload, \"*\");\n\n // close the connection and all listeners when called\n const close = () => {\n self.removeEventListener(events.MESSAGE, handleHandshakeResponse);\n unregisterRemote();\n unregisterLocal();\n };\n\n // resolve connection object\n const connection = { remote, close };\n return resolve(connection);\n }\n\n // subscribe to HANDSHAKE REPLY MESSAGES\n self.addEventListener(events.MESSAGE, handleHandshakeResponse);\n\n const payload = {\n action: actions.HANDSHAKE_REQUEST,\n methods: localMethods,\n schema: JSON.parse(JSON.stringify(schema)),\n };\n\n if (isWorker()) (self as any).postMessage(payload);\n else window.parent.postMessage(payload, \"*\");\n });\n}\n\nexport default {\n connect,\n};\n","import { extractMethods, generateId, getOriginFromURL } from \"./helpers\";\nimport { registerLocalMethods, registerRemoteMethods } from \"./rpc\";\nimport { actions, events, IConnection, IConnections, ISchema } from \"./types\";\n\nconst connections: IConnections = {};\n\nfunction isValidTarget(iframe: HTMLIFrameElement, event: any) {\n const childURL = iframe.getAttribute(\"src\");\n const childOrigin = getOriginFromURL(childURL);\n const hasProperOrigin = event.origin === childOrigin;\n const hasProperSource = event.source === iframe.contentWindow;\n\n return hasProperOrigin && hasProperSource;\n}\n\n/**\n * Perform a handshake with the target iframe, when the handshake is confirmed\n * resolve the connection object containing RPCs and properties\n *\n * @param iframe\n * @param schema\n * @returns Promise\n */\nfunction connect(guest: HTMLIFrameElement | Worker, schema: ISchema = {}): Promise<IConnection> {\n if (!guest) throw new Error(\"a target is required\");\n\n const guestIsWorker = (guest as Worker).onerror !== undefined && (guest as Worker).onmessage !== undefined;\n const listeners = guestIsWorker ? guest : window;\n\n return new Promise((resolve) => {\n const connectionID = generateId();\n\n // on handshake request\n function handleHandshake(event: any) {\n if (!guestIsWorker && !isValidTarget(guest as HTMLIFrameElement, event)) return;\n if (event.data.action !== actions.HANDSHAKE_REQUEST) return;\n\n // register local methods\n const localMethods = extractMethods(schema);\n const unregisterLocal = registerLocalMethods(\n schema,\n localMethods,\n connectionID,\n guestIsWorker ? (guest as Worker) : undefined\n );\n\n // register remote methods\n const { remote, unregisterRemote } = registerRemoteMethods(\n event.data.schema,\n event.data.methods,\n connectionID,\n event,\n guestIsWorker ? (guest as Worker) : undefined\n );\n\n const payload = {\n action: actions.HANDSHAKE_REPLY,\n connectionID,\n methods: localMethods,\n schema: JSON.parse(JSON.stringify(schema)),\n };\n\n // confirm the connection\n if (guestIsWorker) (guest as Worker).postMessage(payload);\n else event.source.postMessage(payload, event.origin);\n\n // close the connection and all listeners when called\n const close = () => {\n listeners.removeEventListener(events.MESSAGE, handleHandshake);\n unregisterRemote();\n unregisterLocal();\n if (guestIsWorker) (guest as Worker).terminate();\n };\n\n const connection: IConnection = { remote, close };\n connections[connectionID] = connection;\n }\n\n // subscribe to HANDSHAKE MESSAGES\n listeners.addEventListener(events.MESSAGE, handleHandshake);\n\n // on handshake reply\n function handleHandshakeReply(event: any) {\n if (event.data.action !== actions.HANDSHAKE_REPLY) return;\n return resolve(connections[event.data.connectionID]);\n }\n\n listeners.addEventListener(events.MESSAGE, handleHandshakeReply);\n });\n}\n\nexport default {\n connect,\n};\n"],"names":["isWorker","extractMethods","obj","paths","parse","path","prop","propPath","urlRegex","ports","getOriginFromURL","url","location","regexResult","protocol","hostname","port","portSuffix","get","defaultValue","keys","result","key","set","value","pathArray","current","i","generateId","length","chars","events","actions","registerLocalMethods","schema","methods","_connectionID","guest","listeners","methodName","handleCall","event","action","callID","connectionID","callName","args","payload","error","unregister","createRPC","_callName","resolve","reject","handleResponse","registerRemoteMethods","remote","rpc","connect","eventHandlers","localMethods","handleHandshakeResponse","_a","unregisterLocal","unregisterRemote","connections","isValidTarget","iframe","childURL","childOrigin","hasProperOrigin","hasProperSource","guestIsWorker","handleHandshake","connection","handleHandshakeReply","host"],"mappings":"AAOO,SAASA,IAAoB;AAClC,SAAO,OAAO,SAAW,OAAe,OAAO,OAAS;AAC1D;AAQO,SAASC,EAAeC,GAAU;AACvC,QAAMC,IAAkB,CAAA;AACxB,SAAC,SAASC,EAAMF,GAAUG,IAAO,IAAI;AACnC,WAAO,KAAKH,CAAG,EAAE,QAAQ,CAACI,MAAS;AACjC,YAAMC,IAAWF,IAAO,GAAGA,CAAI,IAAIC,CAAI,KAAKA;AAC5C,MAAIJ,EAAII,CAAI,MAAM,OAAOJ,EAAII,CAAI,CAAC,KAC1BJ,EAAAA,EAAII,CAAI,GAAGC,CAAQ,GAEvB,OAAOL,EAAII,CAAI,KAAM,cACvBH,EAAM,KAAKI,CAAQ;AAAA,IACrB,CACD;AAAA,IACAL,CAAG,GACCC;AACT;AAEA,MAAMK,IAAW,2CACXC,IAAa,EAAE,SAAS,MAAM,UAAU,MAAM;AAO7C,SAASC,EAAiBC,GAAoB;AAC7C,QAAA,EAAE,UAAAC,EAAa,IAAA,UAEfC,IAAcL,EAAS,KAAKG,KAAO,EAAE;AACvC,MAAAG,GACAC,GACAC;AAiBJ,MAfIH,IAGF,CAAG,EAAAC,IAAWF,EAAS,UAAUG,GAAY,EAAAC,CAAI,IAAIH,KAGrDC,IAAWF,EAAS,UACpBG,IAAWH,EAAS,UACpBI,IAAOJ,EAAS,OAOdE,MAAa;AACR,WAAA;AAKH,QAAAG,IAAaD,KAAQA,MAASP,EAAMK,CAAQ,IAAI,IAAIE,CAAI,KAAK;AACnE,SAAO,GAAGF,CAAQ,KAAKC,CAAQ,GAAGE,CAAU;AAC9C;AAEgB,SAAAC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M;AAU7C,YAAAiC,IAA0B,EAAE,QAAAlB,GAAQ,OAP5B,MAAM;AACR,QAAAlB,EAAA,oBAAoBP,EAAO,SAAS0C,CAAe,GAC5CT,KACDD,KACZS,KAAgBnC,EAAiB;MAAU;AAIjD,MAAA4B,EAAYrB,CAAY,IAAI8B;AAAA,IAC9B;AAGU,IAAApC,EAAA,iBAAiBP,EAAO,SAAS0C,CAAe;AAG1D,aAASE,EAAqBlC,GAAY;AACxC,UAAIA,EAAM,KAAK,WAAWT,EAAQ;AAClC,eAAOoB,EAAQa,EAAYxB,EAAM,KAAK,YAAY,CAAC;AAAA,IACrD;AAEU,IAAAH,EAAA,iBAAiBP,EAAO,SAAS4C,CAAoB;AAAA,EAAA,CAChE;AACH;AAEA,MAAeC,IAAA;AAAA,EACb,SAAAlB;AACF;"}
@@ -1,2 +0,0 @@
1
- var rimless=function(h){"use strict";function g(){return typeof window>"u"&&typeof self<"u"}function M(t){const o=[];return function s(n,r=""){Object.keys(n).forEach(e=>{const i=r?`${r}.${e}`:e;n[e]===Object(n[e])&&s(n[e],i),typeof n[e]=="function"&&o.push(i)})}(t),o}const N=/^(https?:|file:)?\/\/([^/:]+)?(:(\d+))?/,O={"http:":"80","https:":"443"};function C(t){const{location:o}=document,s=N.exec(t||"");let n,r,e;if(s?[,n=o.protocol,r,,e]=s:(n=o.protocol,r=o.hostname,e=o.port),n==="file:")return"null";const i=e&&e!==O[n]?`:${e}`:"";return`${n}//${r}${i}`}function I(t,o,s){const n=Array.isArray(o)?o:o.split(".").filter(Boolean);let r=t;for(const e of n)if(r=r==null?void 0:r[e],r===void 0)return s;return r}function _(t,o,s){if(!t||typeof t!="object")return t;const n=Array.isArray(o)?o:o.split(".").map(e=>e.match(/^\d+$/)?Number(e):e);let r=t;for(let e=0;e<n.length;e++){const i=n[e];e===n.length-1?r[i]=s:((!r[i]||typeof r[i]!="object")&&(r[i]=typeof n[e+1]=="number"?[]:{}),r=r[i])}return t}function L(t=10){const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let s="";for(let n=0;n<t;n++)s+=o.charAt(Math.floor(Math.random()*o.length));return s}var f=(t=>(t.MESSAGE="message",t))(f||{}),a=(t=>(t.HANDSHAKE_REQUEST="RIMLESS/HANDSHAKE_REQUEST",t.HANDSHAKE_REPLY="RIMLESS/HANDSHAKE_REPLY",t.RPC_REQUEST="RIMLESS/RPC_REQUEST",t.RPC_RESOLVE="RIMLESS/RPC_RESOLVE",t.RPC_REJECT="RIMLESS/RPC_REJECT",t))(a||{});function m(t={},o=[],s,n){const r=[];return o.forEach(e=>{async function i(l){const{action:c,callID:u,connectionID:S,callName:d,args:p=[]}=l.data;if(c!==a.RPC_REQUEST||!u||!d||d!==e||S!==s)return;const E={action:a.RPC_RESOLVE,callID:u,callName:d,connectionID:S,error:null,result:null};try{const R=await I(t,e)(...p);E.result=JSON.parse(JSON.stringify(R))}catch(R){E.action=a.RPC_REJECT,E.error=JSON.parse(JSON.stringify(R,Object.getOwnPropertyNames(R)))}n?n.postMessage(E):g()?self.postMessage(E):l.source.postMessage(E,l.origin)}n?n.addEventListener(f.MESSAGE,i):self.addEventListener(f.MESSAGE,i),r.push(()=>self.removeEventListener(f.MESSAGE,i))}),()=>r.forEach(e=>e())}function w(t,o,s,n=[],r){return(...e)=>new Promise((i,l)=>{const c=L();function u(d){const{callID:p,connectionID:E,callName:R,result:A,error:U,action:D}=d.data;if(!(!p||!R)&&R===t&&E===o){if(D===a.RPC_RESOLVE)return i(A);if(D===a.RPC_REJECT)return l(U)}}const S={action:a.RPC_REQUEST,args:JSON.parse(JSON.stringify(e)),callID:c,callName:t,connectionID:o};r?r.addEventListener(f.MESSAGE,u):self.addEventListener(f.MESSAGE,u),n.push(()=>self.removeEventListener(f.MESSAGE,u)),r?r.postMessage(S):g()?self.postMessage(S):(s.source||s.target).postMessage(S,s.origin)})}function y(t={},o=[],s,n,r){const e={...t},i=[];return o.forEach(l=>{const c=w(l,s,n,i,r);_(e,l,c)}),{remote:e,unregisterRemote:()=>i.forEach(l=>l())}}function H(t={},o){return new Promise(s=>{const n=M(t);async function r(i){var E;if(i.data.action!==a.HANDSHAKE_REPLY)return;const l=m(t,n,i.data.connectionID),{remote:c,unregisterRemote:u}=y(i.data.schema,i.data.methods,i.data.connectionID,i);await((E=o==null?void 0:o.onConnectionSetup)==null?void 0:E.call(o,c));const S={action:a.HANDSHAKE_REPLY,connectionID:i.data.connectionID};return g()?self.postMessage(S):window.parent.postMessage(S,"*"),s({remote:c,close:()=>{self.removeEventListener(f.MESSAGE,r),u(),l()}})}self.addEventListener(f.MESSAGE,r);const e={action:a.HANDSHAKE_REQUEST,methods:n,schema:JSON.parse(JSON.stringify(t))};g()?self.postMessage(e):window.parent.postMessage(e,"*")})}const J={connect:H},P={};function T(t,o){const s=t.getAttribute("src"),n=C(s),r=o.origin===n,e=o.source===t.contentWindow;return r&&e}function G(t,o={}){if(!t)throw new Error("a target is required");const s=t.onerror!==void 0&&t.onmessage!==void 0,n=s?t:window;return new Promise(r=>{const e=L();function i(c){if(!s&&!T(t,c)||c.data.action!==a.HANDSHAKE_REQUEST)return;const u=M(o),S=m(o,u,e,s?t:void 0),{remote:d,unregisterRemote:p}=y(c.data.schema,c.data.methods,e,c,s?t:void 0),E={action:a.HANDSHAKE_REPLY,connectionID:e,methods:u,schema:JSON.parse(JSON.stringify(o))};s?t.postMessage(E):c.source.postMessage(E,c.origin);const A={remote:d,close:()=>{n.removeEventListener(f.MESSAGE,i),p(),S(),s&&t.terminate()}};P[e]=A}n.addEventListener(f.MESSAGE,i);function l(c){if(c.data.action===a.HANDSHAKE_REPLY)return r(P[c.data.connectionID])}n.addEventListener(f.MESSAGE,l)})}const K={connect:G};return h.actions=a,h.events=f,h.guest=J,h.host=K,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h}({});
2
- //# sourceMappingURL=rimless.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rimless.min.js","sources":["../src/helpers.ts","../src/types.ts","../src/rpc.ts","../src/guest.ts","../src/host.ts"],"sourcesContent":["export const CONNECTION_TIMEOUT = 1000;\n\n/**\n * check if run in a webworker\n *\n * @param event\n */\nexport function isWorker(): boolean {\n return typeof window === \"undefined\" && typeof self !== \"undefined\";\n}\n\n/**\n * we cannot send functions through postMessage\n * extract the path to all functions in the schema\n *\n * @param obj\n */\nexport function extractMethods(obj: any) {\n const paths: string[] = [];\n (function parse(obj: any, path = \"\") {\n Object.keys(obj).forEach((prop) => {\n const propPath = path ? `${path}.${prop}` : prop;\n if (obj[prop] === Object(obj[prop])) {\n parse(obj[prop], propPath);\n }\n if (typeof obj[prop] === \"function\") {\n paths.push(propPath);\n }\n });\n })(obj);\n return paths;\n}\n\nconst urlRegex = /^(https?:|file:)?\\/\\/([^/:]+)?(:(\\d+))?/;\nconst ports: any = { \"http:\": \"80\", \"https:\": \"443\" };\n\n/**\n * convert the url into an origin (remove paths)\n *\n * @param url\n */\nexport function getOriginFromURL(url: string | null) {\n const { location } = document;\n\n const regexResult = urlRegex.exec(url || \"\");\n let protocol;\n let hostname;\n let port;\n\n if (regexResult) {\n // It's an absolute URL. Use the parsed info.\n // regexResult[1] will be undefined if the URL starts with //\n [, protocol = location.protocol, hostname, , port] = regexResult;\n } else {\n // It's a relative path. Use the current location's info.\n protocol = location.protocol;\n hostname = location.hostname;\n port = location.port;\n }\n\n // If the protocol is file, the origin is \"null\"\n // The origin of a document with file protocol is an opaque origin\n // and its serialization \"null\" [1]\n // [1] https://html.spec.whatwg.org/multipage/origin.html#origin\n if (protocol === \"file:\") {\n return \"null\";\n }\n\n // If the port is the default for the protocol, we don't want to add it to the origin string\n // or it won't match the message's event.origin.\n const portSuffix = port && port !== ports[protocol] ? `:${port}` : \"\";\n return `${protocol}//${hostname}${portSuffix}`;\n}\n\nexport function get(obj: any, path: string | Array<string | number>, defaultValue?: any): any {\n const keys = Array.isArray(path) ? path : path.split(\".\").filter(Boolean);\n let result = obj;\n\n for (const key of keys) {\n result = result?.[key];\n if (result === undefined) {\n return defaultValue;\n }\n }\n\n return result;\n}\n\nexport function set(obj: any, path: string | (string | number)[], value: any): any {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const pathArray = Array.isArray(path) ? path : path.split(\".\").map((key) => (key.match(/^\\d+$/) ? Number(key) : key));\n\n let current = obj;\n\n for (let i = 0; i < pathArray.length; i++) {\n const key = pathArray[i];\n\n if (i === pathArray.length - 1) {\n current[key] = value;\n } else {\n if (!current[key] || typeof current[key] !== \"object\") {\n current[key] = typeof pathArray[i + 1] === \"number\" ? [] : {};\n }\n current = current[key];\n }\n }\n\n return obj;\n}\n\nexport function generateId(length: number = 10): string {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n let result = \"\";\n for (let i = 0; i < length; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n}\n","export enum events {\n MESSAGE = \"message\",\n}\n\nexport enum actions {\n HANDSHAKE_REQUEST = \"RIMLESS/HANDSHAKE_REQUEST\",\n HANDSHAKE_REPLY = \"RIMLESS/HANDSHAKE_REPLY\",\n RPC_REQUEST = \"RIMLESS/RPC_REQUEST\",\n RPC_RESOLVE = \"RIMLESS/RPC_RESOLVE\",\n RPC_REJECT = \"RIMLESS/RPC_REJECT\",\n}\n\nexport interface ISchema {\n [prop: string]: any;\n}\n\nexport interface IConnection {\n remote: ISchema;\n close: () => void;\n}\n\nexport interface IConnections {\n [connectionID: string]: IConnection;\n}\n\nexport interface IEvent extends EventListener {\n source?: Window;\n origin?: string;\n data?: IHandshakeRequestPayload | IHandshakeConfirmationPayload | IRPCRequestPayload | IRPCResolvePayload;\n}\n\nexport interface IHandshakeRequestPayload {\n action: actions.HANDSHAKE_REQUEST;\n connectionID?: string;\n methods: any[];\n schema: ISchema;\n}\n\nexport interface IHandshakeConfirmationPayload {\n action: actions.HANDSHAKE_REPLY;\n connectionID: string;\n methods: any[];\n schema: ISchema;\n}\n\nexport interface IRPCRequestPayload {\n action: actions.RPC_REQUEST;\n args: any[];\n callID: string;\n callName: string;\n connectionID?: string;\n}\n\nexport interface IRPCResolvePayload {\n action: actions.RPC_RESOLVE | actions.RPC_REJECT;\n result?: any | null;\n error?: Error | null;\n callID: string;\n callName: string;\n connectionID: string;\n}\n\nexport interface EventHandlers {\n onConnectionSetup: (remote: ISchema) => Promise<void>;\n}\n","import { generateId, get, isWorker, set } from \"./helpers\";\nimport { actions, events, IRPCRequestPayload, IRPCResolvePayload, ISchema } from \"./types\";\n\n/**\n * for each function in the schema\n * 1. subscribe to an event that the remote can call\n * 2. listen for calls from the remote. When called execute the function and emit the results.\n *\n * @param methods an array of method ids from the local schema\n * @param _connectionID\n * @return a function to cancel all subscriptions\n */\nexport function registerLocalMethods(\n schema: ISchema = {},\n methods: any[] = [],\n _connectionID: string,\n guest?: Worker\n): any {\n const listeners: any[] = [];\n methods.forEach((methodName) => {\n // handle a remote calling a local method\n async function handleCall(event: any) {\n const { action, callID, connectionID, callName, args = [] } = event.data as IRPCRequestPayload;\n\n if (action !== actions.RPC_REQUEST) return;\n if (!callID || !callName) return;\n if (callName !== methodName) return;\n if (connectionID !== _connectionID) return;\n\n const payload: IRPCResolvePayload = {\n action: actions.RPC_RESOLVE,\n callID,\n callName,\n connectionID,\n error: null,\n result: null,\n };\n\n // run function and return the results to the remote\n try {\n const result = await get(schema, methodName)(...args);\n payload.result = JSON.parse(JSON.stringify(result));\n } catch (error) {\n payload.action = actions.RPC_REJECT;\n payload.error = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)));\n }\n\n if (guest) guest.postMessage(payload);\n else if (isWorker()) (self as any).postMessage(payload);\n else event.source.postMessage(payload, event.origin);\n }\n\n // subscribe to the call event\n if (guest) guest.addEventListener(events.MESSAGE, handleCall);\n else self.addEventListener(events.MESSAGE, handleCall);\n\n listeners.push(() => self.removeEventListener(events.MESSAGE, handleCall));\n });\n\n return () => listeners.forEach((unregister) => unregister());\n}\n\n/**\n * Create a function that will make an RPC request to the remote with some arguments.\n * Listen to an event that returns the results from the remote.\n *\n * @param _callName\n * @param _connectionID\n * @param event\n * @param listeners\n * @param guest\n *\n * @returns a promise with the result of the RPC\n */\nexport function createRPC(\n _callName: string,\n _connectionID: string,\n event: any,\n listeners: Array<() => void> = [],\n guest?: Worker\n) {\n return (...args: any) => {\n return new Promise((resolve, reject) => {\n const callID = generateId();\n\n // on RPC response\n function handleResponse(event: any) {\n const { callID, connectionID, callName, result, error, action } = event.data as IRPCResolvePayload;\n\n if (!callID || !callName) return;\n if (callName !== _callName) return;\n if (connectionID !== _connectionID) return;\n\n // resolve the response\n if (action === actions.RPC_RESOLVE) return resolve(result);\n if (action === actions.RPC_REJECT) return reject(error);\n }\n\n // send the RPC request with arguments\n const payload = {\n action: actions.RPC_REQUEST,\n args: JSON.parse(JSON.stringify(args)),\n callID,\n callName: _callName,\n connectionID: _connectionID,\n };\n\n if (guest) guest.addEventListener(events.MESSAGE, handleResponse);\n else self.addEventListener(events.MESSAGE, handleResponse);\n listeners.push(() => self.removeEventListener(events.MESSAGE, handleResponse));\n\n if (guest) guest.postMessage(payload);\n else if (isWorker()) (self as any).postMessage(payload);\n else (event.source || event.target).postMessage(payload, event.origin);\n });\n };\n}\n\n/**\n * create an object based on the remote schema and methods. Functions in that object will\n * emit an event that will trigger the RPC on the remote.\n *\n * @param schema\n * @param methods\n * @param _connectionID\n * @param event\n * @param guest\n */\nexport function registerRemoteMethods(\n schema: ISchema = {},\n methods: any[] = [],\n _connectionID: string,\n event: any,\n guest?: Worker\n) {\n const remote = { ...schema };\n const listeners: Array<() => void> = [];\n\n methods.forEach((methodName) => {\n const rpc = createRPC(methodName, _connectionID, event, listeners, guest);\n set(remote, methodName, rpc);\n });\n\n return {\n remote,\n unregisterRemote: () => listeners.forEach((unregister) => unregister()),\n };\n}\n","import { extractMethods, isWorker } from \"./helpers\";\nimport { registerLocalMethods, registerRemoteMethods } from \"./rpc\";\nimport { actions, EventHandlers, events, IConnection, ISchema } from \"./types\";\n\nfunction connect(schema: ISchema = {}, eventHandlers?: EventHandlers): Promise<IConnection> {\n return new Promise((resolve) => {\n const localMethods = extractMethods(schema);\n\n // on handshake response\n async function handleHandshakeResponse(event: any) {\n if (event.data.action !== actions.HANDSHAKE_REPLY) return;\n\n // register local methods\n const unregisterLocal = registerLocalMethods(schema, localMethods, event.data.connectionID);\n\n // register remote methods\n const { remote, unregisterRemote } = registerRemoteMethods(\n event.data.schema,\n event.data.methods,\n event.data.connectionID,\n event\n );\n\n await eventHandlers?.onConnectionSetup?.(remote);\n\n // send a HANDSHAKE REPLY to the host\n const payload = {\n action: actions.HANDSHAKE_REPLY,\n connectionID: event.data.connectionID,\n };\n\n if (isWorker()) self.postMessage(payload);\n else window.parent.postMessage(payload, \"*\");\n\n // close the connection and all listeners when called\n const close = () => {\n self.removeEventListener(events.MESSAGE, handleHandshakeResponse);\n unregisterRemote();\n unregisterLocal();\n };\n\n // resolve connection object\n const connection = { remote, close };\n return resolve(connection);\n }\n\n // subscribe to HANDSHAKE REPLY MESSAGES\n self.addEventListener(events.MESSAGE, handleHandshakeResponse);\n\n const payload = {\n action: actions.HANDSHAKE_REQUEST,\n methods: localMethods,\n schema: JSON.parse(JSON.stringify(schema)),\n };\n\n if (isWorker()) (self as any).postMessage(payload);\n else window.parent.postMessage(payload, \"*\");\n });\n}\n\nexport default {\n connect,\n};\n","import { extractMethods, generateId, getOriginFromURL } from \"./helpers\";\nimport { registerLocalMethods, registerRemoteMethods } from \"./rpc\";\nimport { actions, events, IConnection, IConnections, ISchema } from \"./types\";\n\nconst connections: IConnections = {};\n\nfunction isValidTarget(iframe: HTMLIFrameElement, event: any) {\n const childURL = iframe.getAttribute(\"src\");\n const childOrigin = getOriginFromURL(childURL);\n const hasProperOrigin = event.origin === childOrigin;\n const hasProperSource = event.source === iframe.contentWindow;\n\n return hasProperOrigin && hasProperSource;\n}\n\n/**\n * Perform a handshake with the target iframe, when the handshake is confirmed\n * resolve the connection object containing RPCs and properties\n *\n * @param iframe\n * @param schema\n * @returns Promise\n */\nfunction connect(guest: HTMLIFrameElement | Worker, schema: ISchema = {}): Promise<IConnection> {\n if (!guest) throw new Error(\"a target is required\");\n\n const guestIsWorker = (guest as Worker).onerror !== undefined && (guest as Worker).onmessage !== undefined;\n const listeners = guestIsWorker ? guest : window;\n\n return new Promise((resolve) => {\n const connectionID = generateId();\n\n // on handshake request\n function handleHandshake(event: any) {\n if (!guestIsWorker && !isValidTarget(guest as HTMLIFrameElement, event)) return;\n if (event.data.action !== actions.HANDSHAKE_REQUEST) return;\n\n // register local methods\n const localMethods = extractMethods(schema);\n const unregisterLocal = registerLocalMethods(\n schema,\n localMethods,\n connectionID,\n guestIsWorker ? (guest as Worker) : undefined\n );\n\n // register remote methods\n const { remote, unregisterRemote } = registerRemoteMethods(\n event.data.schema,\n event.data.methods,\n connectionID,\n event,\n guestIsWorker ? (guest as Worker) : undefined\n );\n\n const payload = {\n action: actions.HANDSHAKE_REPLY,\n connectionID,\n methods: localMethods,\n schema: JSON.parse(JSON.stringify(schema)),\n };\n\n // confirm the connection\n if (guestIsWorker) (guest as Worker).postMessage(payload);\n else event.source.postMessage(payload, event.origin);\n\n // close the connection and all listeners when called\n const close = () => {\n listeners.removeEventListener(events.MESSAGE, handleHandshake);\n unregisterRemote();\n unregisterLocal();\n if (guestIsWorker) (guest as Worker).terminate();\n };\n\n const connection: IConnection = { remote, close };\n connections[connectionID] = connection;\n }\n\n // subscribe to HANDSHAKE MESSAGES\n listeners.addEventListener(events.MESSAGE, handleHandshake);\n\n // on handshake reply\n function handleHandshakeReply(event: any) {\n if (event.data.action !== actions.HANDSHAKE_REPLY) return;\n return resolve(connections[event.data.connectionID]);\n }\n\n listeners.addEventListener(events.MESSAGE, handleHandshakeReply);\n });\n}\n\nexport default {\n connect,\n};\n"],"names":["isWorker","extractMethods","obj","paths","parse","path","prop","propPath","urlRegex","ports","getOriginFromURL","url","location","regexResult","protocol","hostname","port","portSuffix","get","defaultValue","keys","result","key","set","value","pathArray","current","i","generateId","length","chars","events","actions","registerLocalMethods","schema","methods","_connectionID","guest","listeners","methodName","handleCall","event","action","callID","connectionID","callName","args","payload","error","unregister","createRPC","_callName","resolve","reject","handleResponse","registerRemoteMethods","remote","rpc","connect","eventHandlers","localMethods","handleHandshakeResponse","unregisterLocal","unregisterRemote","_a","connections","isValidTarget","iframe","childURL","childOrigin","hasProperOrigin","hasProperSource","guestIsWorker","handleHandshake","connection","handleHandshakeReply","host"],"mappings":"qCAOO,SAASA,GAAoB,CAClC,OAAO,OAAO,OAAW,KAAe,OAAO,KAAS,GAC1D,CAQO,SAASC,EAAeC,EAAU,CACvC,MAAMC,EAAkB,CAAA,EACxB,OAAC,SAASC,EAAMF,EAAUG,EAAO,GAAI,CACnC,OAAO,KAAKH,CAAG,EAAE,QAASI,GAAS,CACjC,MAAMC,EAAWF,EAAO,GAAGA,CAAI,IAAIC,CAAI,GAAKA,EACxCJ,EAAII,CAAI,IAAM,OAAOJ,EAAII,CAAI,CAAC,GAC1BJ,EAAAA,EAAII,CAAI,EAAGC,CAAQ,EAEvB,OAAOL,EAAII,CAAI,GAAM,YACvBH,EAAM,KAAKI,CAAQ,CACrB,CACD,GACAL,CAAG,EACCC,CACT,CAEA,MAAMK,EAAW,0CACXC,EAAa,CAAE,QAAS,KAAM,SAAU,KAAM,EAO7C,SAASC,EAAiBC,EAAoB,CAC7C,KAAA,CAAE,SAAAC,CAAa,EAAA,SAEfC,EAAcL,EAAS,KAAKG,GAAO,EAAE,EACvC,IAAAG,EACAC,EACAC,EAiBJ,GAfIH,EAGF,CAAG,CAAAC,EAAWF,EAAS,SAAUG,EAAY,CAAAC,CAAI,EAAIH,GAGrDC,EAAWF,EAAS,SACpBG,EAAWH,EAAS,SACpBI,EAAOJ,EAAS,MAOdE,IAAa,QACR,MAAA,OAKH,MAAAG,EAAaD,GAAQA,IAASP,EAAMK,CAAQ,EAAI,IAAIE,CAAI,GAAK,GACnE,MAAO,GA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,CACH,CAEe,MAAAC,EAAA,CACb,QAAAlB,CACF"}
package/lib/rpc.d.ts DELETED
@@ -1,40 +0,0 @@
1
- import { ISchema } from './types';
2
- /**
3
- * for each function in the schema
4
- * 1. subscribe to an event that the remote can call
5
- * 2. listen for calls from the remote. When called execute the function and emit the results.
6
- *
7
- * @param methods an array of method ids from the local schema
8
- * @param _connectionID
9
- * @return a function to cancel all subscriptions
10
- */
11
- export declare function registerLocalMethods(schema: ISchema | undefined, methods: any[] | undefined, _connectionID: string, guest?: Worker): any;
12
- /**
13
- * Create a function that will make an RPC request to the remote with some arguments.
14
- * Listen to an event that returns the results from the remote.
15
- *
16
- * @param _callName
17
- * @param _connectionID
18
- * @param event
19
- * @param listeners
20
- * @param guest
21
- *
22
- * @returns a promise with the result of the RPC
23
- */
24
- export declare function createRPC(_callName: string, _connectionID: string, event: any, listeners?: Array<() => void>, guest?: Worker): (...args: any) => Promise<unknown>;
25
- /**
26
- * create an object based on the remote schema and methods. Functions in that object will
27
- * emit an event that will trigger the RPC on the remote.
28
- *
29
- * @param schema
30
- * @param methods
31
- * @param _connectionID
32
- * @param event
33
- * @param guest
34
- */
35
- export declare function registerRemoteMethods(schema: ISchema | undefined, methods: any[] | undefined, _connectionID: string, event: any, guest?: Worker): {
36
- remote: {
37
- [x: string]: any;
38
- };
39
- unregisterRemote: () => void;
40
- };
package/lib/types.d.ts DELETED
@@ -1,55 +0,0 @@
1
- export declare enum events {
2
- MESSAGE = "message"
3
- }
4
- export declare enum actions {
5
- HANDSHAKE_REQUEST = "RIMLESS/HANDSHAKE_REQUEST",
6
- HANDSHAKE_REPLY = "RIMLESS/HANDSHAKE_REPLY",
7
- RPC_REQUEST = "RIMLESS/RPC_REQUEST",
8
- RPC_RESOLVE = "RIMLESS/RPC_RESOLVE",
9
- RPC_REJECT = "RIMLESS/RPC_REJECT"
10
- }
11
- export interface ISchema {
12
- [prop: string]: any;
13
- }
14
- export interface IConnection {
15
- remote: ISchema;
16
- close: () => void;
17
- }
18
- export interface IConnections {
19
- [connectionID: string]: IConnection;
20
- }
21
- export interface IEvent extends EventListener {
22
- source?: Window;
23
- origin?: string;
24
- data?: IHandshakeRequestPayload | IHandshakeConfirmationPayload | IRPCRequestPayload | IRPCResolvePayload;
25
- }
26
- export interface IHandshakeRequestPayload {
27
- action: actions.HANDSHAKE_REQUEST;
28
- connectionID?: string;
29
- methods: any[];
30
- schema: ISchema;
31
- }
32
- export interface IHandshakeConfirmationPayload {
33
- action: actions.HANDSHAKE_REPLY;
34
- connectionID: string;
35
- methods: any[];
36
- schema: ISchema;
37
- }
38
- export interface IRPCRequestPayload {
39
- action: actions.RPC_REQUEST;
40
- args: any[];
41
- callID: string;
42
- callName: string;
43
- connectionID?: string;
44
- }
45
- export interface IRPCResolvePayload {
46
- action: actions.RPC_RESOLVE | actions.RPC_REJECT;
47
- result?: any | null;
48
- error?: Error | null;
49
- callID: string;
50
- callName: string;
51
- connectionID: string;
52
- }
53
- export interface EventHandlers {
54
- onConnectionSetup: (remote: ISchema) => Promise<void>;
55
- }