@lvce-editor/json-rpc 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 ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023, Lvce Editor
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # @lvce-editor/json-rpc
2
+
3
+ JsonRpc implementation.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @lvce-editor/json-rpc
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import * as JsonRpc from '@lvce-editor/json-rpc'
15
+
16
+ const ipc = {
17
+ send(message) {
18
+ JsonRpc.resolve(message.id, message.params[0], message.params[1])
19
+ },
20
+ }
21
+
22
+ await JsonRpc.invoke(ipc, 'add', 1, 2) // returns 3
23
+ ```
24
+
25
+ ## Gitpod
26
+
27
+ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/lvce-editor/json-rpc)
@@ -0,0 +1,3 @@
1
+ export const invoke: (method: string, ...params: any[]) => Promise<any>
2
+
3
+ export const resolve: (id: number, message: any) => void
package/dist/index.js ADDED
@@ -0,0 +1,234 @@
1
+ const Two = '2.0';
2
+
3
+ const create$2 = (method, params) => {
4
+ return {
5
+ jsonrpc: Two,
6
+ method,
7
+ params: params,
8
+ }
9
+ };
10
+
11
+ const state$1 = {
12
+ id: 0,
13
+ };
14
+
15
+ const create$1 = () => {
16
+ return ++state$1.id
17
+ };
18
+
19
+ const withResolvers = () => {
20
+ /**
21
+ * @type {any}
22
+ */
23
+ let _resolve;
24
+ /**
25
+ * @type {any}
26
+ */
27
+ let _reject;
28
+ const promise = new Promise((resolve, reject) => {
29
+ _resolve = resolve;
30
+ _reject = reject;
31
+ });
32
+ return {
33
+ resolve: _resolve,
34
+ reject: _reject,
35
+ promise,
36
+ }
37
+ };
38
+
39
+ const state = {
40
+ callbacks: Object.create(null),
41
+ };
42
+
43
+ const registerPromise = () => {
44
+ const id = create$1();
45
+ const { resolve, promise } = withResolvers();
46
+ state.callbacks[id] = resolve;
47
+ return { id, promise }
48
+ };
49
+
50
+ const create = (method, params) => {
51
+ const { id, promise } = registerPromise();
52
+ const message = {
53
+ jsonrpc: Two,
54
+ method,
55
+ params,
56
+ id,
57
+ };
58
+ return {
59
+ message,
60
+ promise,
61
+ }
62
+ };
63
+
64
+ class JsonRpcError extends Error {
65
+ constructor(message) {
66
+ super(message);
67
+ this.name = 'JsonRpcError';
68
+ }
69
+ }
70
+
71
+ const DomException = 'DOMException';
72
+ const ReferenceError$1 = 'ReferenceError';
73
+ const SyntaxError$1 = 'SyntaxError';
74
+ const TypeError$1 = 'TypeError';
75
+
76
+ const getErrorConstructor = (message, type) => {
77
+ if (type) {
78
+ switch (type) {
79
+ case DomException:
80
+ return DOMException
81
+ case TypeError$1:
82
+ return TypeError
83
+ case SyntaxError$1:
84
+ return SyntaxError
85
+ case ReferenceError$1:
86
+ return ReferenceError
87
+ default:
88
+ return Error
89
+ }
90
+ }
91
+ if (message.startsWith('TypeError: ')) {
92
+ return TypeError
93
+ }
94
+ if (message.startsWith('SyntaxError: ')) {
95
+ return SyntaxError
96
+ }
97
+ if (message.startsWith('ReferenceError: ')) {
98
+ return ReferenceError
99
+ }
100
+ return Error
101
+ };
102
+
103
+ const NewLine = '\n';
104
+
105
+ /**
106
+ *
107
+ * @param {string} string
108
+ * @param {number|undefined} startIndex
109
+ * @returns
110
+ */
111
+ const getNewLineIndex = (string, startIndex = undefined) => {
112
+ return string.indexOf(NewLine, startIndex)
113
+ };
114
+
115
+ const joinLines = (lines) => {
116
+ return lines.join(NewLine)
117
+ };
118
+
119
+ const MethodNotFound = -32601;
120
+
121
+ const splitLines = (lines) => {
122
+ return lines.split(NewLine)
123
+ };
124
+
125
+ const constructError = (message, type, name) => {
126
+ const ErrorConstructor = getErrorConstructor(message, type);
127
+ if (ErrorConstructor === DOMException && name) {
128
+ return new ErrorConstructor(message, name)
129
+ }
130
+ if (ErrorConstructor === Error) {
131
+ const error = new Error(message);
132
+ if (name && name !== 'VError') {
133
+ error.name = name;
134
+ }
135
+ return error
136
+ }
137
+ return new ErrorConstructor(message)
138
+ };
139
+
140
+ const getParentStack = (error) => {
141
+ let parentStack = error.stack || error.data || error.message || '';
142
+ if (parentStack.startsWith(' at')) {
143
+ parentStack = error.message + NewLine + parentStack;
144
+ }
145
+ return parentStack
146
+ };
147
+
148
+ const restoreJsonRpcError = (error) => {
149
+ if (error && error instanceof Error) {
150
+ return error
151
+ }
152
+ const currentStack = joinLines(splitLines(new Error().stack).slice(1));
153
+ if (error && error.code && error.code === MethodNotFound) {
154
+ const restoredError = new JsonRpcError(error.message);
155
+ const parentStack = getParentStack(error);
156
+ restoredError.stack = parentStack + NewLine + currentStack;
157
+ return restoredError
158
+ }
159
+ if (error && error.message) {
160
+ const restoredError = constructError(error.message, error.type, error.name);
161
+ if (error.data) {
162
+ if (error.data.stack && error.data.type && error.message) {
163
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
164
+ } else if (error.data.stack) {
165
+ restoredError.stack = error.data.stack;
166
+ }
167
+ if (error.data.codeFrame) {
168
+ // @ts-ignore
169
+ restoredError.codeFrame = error.data.codeFrame;
170
+ }
171
+ if (error.data.code) {
172
+ // @ts-ignore
173
+ restoredError.code = error.data.code;
174
+ }
175
+ if (error.data.type) {
176
+ // @ts-ignore
177
+ restoredError.name = error.data.type;
178
+ }
179
+ } else {
180
+ if (error.stack) {
181
+ // TODO accessing stack might be slow
182
+ const lowerStack = restoredError.stack || '';
183
+ // @ts-ignore
184
+ const indexNewLine = getNewLineIndex(lowerStack);
185
+ const parentStack = getParentStack(error);
186
+ // @ts-ignore
187
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
188
+ }
189
+ if (error.codeFrame) {
190
+ // @ts-ignore
191
+ restoredError.codeFrame = error.codeFrame;
192
+ }
193
+ }
194
+ return restoredError
195
+ }
196
+ if (typeof error === 'string') {
197
+ return new Error(`JsonRpc Error: ${error}`)
198
+ }
199
+ return new Error(`JsonRpc Error: ${error}`)
200
+ };
201
+
202
+ const unwrapJsonRpcResult = (responseMessage) => {
203
+ if ('error' in responseMessage) {
204
+ const restoredError = restoreJsonRpcError(responseMessage.error);
205
+ throw restoredError
206
+ }
207
+ if ('result' in responseMessage) {
208
+ return responseMessage.result
209
+ }
210
+ throw new JsonRpcError('unexpected response message')
211
+ };
212
+
213
+ const send = (transport, method, ...params) => {
214
+ const message = create$2(method, params);
215
+ transport.send(message);
216
+ };
217
+
218
+ const invoke = async (ipc, method, ...params) => {
219
+ const { message, promise } = create(method, params);
220
+ ipc.send(message);
221
+ const responseMessage = await promise;
222
+ const result = unwrapJsonRpcResult(responseMessage);
223
+ return result
224
+ };
225
+
226
+ const invokeAndTransfer = async (ipc, handle, method, ...params) => {
227
+ const { message, promise } = create(method, params);
228
+ ipc.sendAndTransfer(message, handle);
229
+ const responseMessage = await promise;
230
+ const result = unwrapJsonRpcResult(responseMessage);
231
+ return result
232
+ };
233
+
234
+ export { invoke, invokeAndTransfer, send };
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@lvce-editor/json-rpc",
3
+ "version": "0.1.0",
4
+ "description": "JsonRpc implementation",
5
+ "main": "dist/index.js",
6
+ "type": "module",
7
+ "types": "dist/index.d.ts",
8
+ "keywords": [
9
+ "json-rpc"
10
+ ],
11
+ "author": "Lvce Editor",
12
+ "license": "MIT",
13
+ "dependencies": {
14
+ "@lvce-editor/assert": "^1.0.1"
15
+ }
16
+ }