@msaki/jsonrpc 0.0.3 → 0.1.1

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/README.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # jsonrpc
2
2
 
3
+ ## `@msaki/jsonrpc`
4
+
5
+ A minimal jsonrpc server and client library.
6
+
7
+ ```sh
8
+ bun add @msaki/jsonrpc
9
+ ```
10
+
3
11
  ## Usage
4
12
 
5
13
  ### RPC Server
@@ -32,6 +40,18 @@ console.log("JSON-RPC sever on http://localhost:4444")
32
40
 
33
41
  ### PRC Client
34
42
 
43
+ ```ts
44
+ import { initializeRpcClient } from "@msaki/jsonrpc";
45
+ const url = "http://localhost:4444";
46
+ const client = initializeRpcClient(url);
47
+ const result = client.call(
48
+ "rpc_method",
49
+ [1, 2]
50
+ );
51
+ ```
52
+
53
+ Or
54
+
35
55
  ```ts
36
56
  import { JsonRpcClient } from "@msaki/jsonrpc";
37
57
  import type {
@@ -41,13 +61,17 @@ import type {
41
61
 
42
62
  const url = "http://localhost:4444";
43
63
 
44
- const client = new JsonRpcClient(async (req: JsonRpcRequest) => {
64
+ const client = new JsonRpcClient(async (req: JsonRpcRequest<unknown>) => {
45
65
  const res = await fetch(url, {
46
66
  method: "POST",
47
67
  headers: { "Content-Type": "application/json" },
48
68
  body: JSON.stringify(req)
49
69
  });
50
70
 
51
- return (await res.json()) as JsonRpcResponse
71
+ return (await res.json()) as JsonRpcResponse<unknown, number>
52
72
  });
73
+ const result = client.call(
74
+ "rpc_method",
75
+ [1, 2]
76
+ );
53
77
  ```
@@ -0,0 +1,10 @@
1
+ import type { JsonRpcRequest, JsonRpcResponse } from "./types";
2
+ export declare class JsonRpcClient {
3
+ private send;
4
+ private id;
5
+ constructor(send: (req: JsonRpcRequest<unknown>) => Promise<JsonRpcResponse<unknown, number>>);
6
+ call<Method = string, Result = unknown, E = unknown>(method: Method, params?: unknown[]): Promise<Result | E>;
7
+ notify<Method = string>(method: Method, params?: unknown[]): Promise<JsonRpcResponse<unknown, number>>;
8
+ }
9
+ export declare function initializeRpcClient(url: string): JsonRpcClient;
10
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/D,qBAAa,aAAa;IAItB,OAAO,CAAC,IAAI;IAHd,OAAO,CAAC,EAAE,CAAI;gBAGJ,IAAI,EAAE,CAAC,GAAG,EAAE,cAAc,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,eAAe,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAGrF,IAAI,CAAC,MAAM,GAAG,MAAM,EAAE,MAAM,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;IAcnH,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE;CAQ3D;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,CAW9D"}
package/dist/client.js ADDED
@@ -0,0 +1,40 @@
1
+ export class JsonRpcClient {
2
+ send;
3
+ id = 0;
4
+ constructor(send) {
5
+ this.send = send;
6
+ }
7
+ async call(method, params) {
8
+ const request = {
9
+ jsonrpc: "2.0",
10
+ method,
11
+ params,
12
+ id: ++this.id,
13
+ };
14
+ const response = await this.send(request);
15
+ if ("error" in response) {
16
+ return response.error;
17
+ }
18
+ return response.result;
19
+ }
20
+ notify(method, params) {
21
+ const request = {
22
+ jsonrpc: "2.0",
23
+ method,
24
+ params
25
+ };
26
+ return this.send(request);
27
+ }
28
+ }
29
+ export function initializeRpcClient(url) {
30
+ const client = new JsonRpcClient(async (req) => {
31
+ const res = await fetch(url, {
32
+ method: "POST",
33
+ headers: { "Content-Type": "application/json" },
34
+ body: JSON.stringify(req)
35
+ });
36
+ return (await res.json());
37
+ });
38
+ return client;
39
+ }
40
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,aAAa;IAId;IAHF,EAAE,GAAG,CAAC,CAAA;IAEd,YACU,IAAiF;QAAjF,SAAI,GAAJ,IAAI,CAA6E;IACxF,CAAC;IAEJ,KAAK,CAAC,IAAI,CAAiD,MAAc,EAAE,MAAkB;QAC3F,MAAM,OAAO,GAA2B;YACtC,OAAO,EAAE,KAAK;YACd,MAAM;YACN,MAAM;YACN,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE;SACd,CAAA;QACD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,OAAO,IAAI,QAAQ,EAAE,CAAC;YACxB,OAAO,QAAQ,CAAC,KAAU,CAAA;QAC5B,CAAC;QACD,OAAO,QAAQ,CAAC,MAAgB,CAAA;IAClC,CAAC;IAED,MAAM,CAAkB,MAAc,EAAE,MAAkB;QACxD,MAAM,OAAO,GAA2B;YACtC,OAAO,EAAE,KAAK;YACd,MAAM;YACN,MAAM;SACP,CAAA;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC3B,CAAC;CACF;AAED,MAAM,UAAU,mBAAmB,CAAC,GAAW;IAC7C,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,KAAK,EAAE,GAA4B,EAAE,EAAE;QACtE,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YAC3B,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC;SAC1B,CAAC,CAAC;QAEH,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAqC,CAAA;IAC/D,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,47 +1,4 @@
1
- type JsonRpcId = string | number | null;
2
- interface JsonRpcRequest {
3
- jsonrpc: "2.0";
4
- method: string;
5
- params?: unknown;
6
- id?: JsonRpcId;
7
- }
8
- interface JsonRpcSuccess {
9
- jsonrpc: "2.0";
10
- result: unknown;
11
- id: JsonRpcId;
12
- }
13
- interface JsonRpcErrorObject {
14
- code: number;
15
- message: string;
16
- data?: unknown;
17
- }
18
- interface JsonRpcError {
19
- jsonrpc: "2.0";
20
- error: JsonRpcErrorObject;
21
- id: JsonRpcId;
22
- }
23
- type JsonRpcResponse = JsonRpcSuccess | JsonRpcError;
24
-
25
- declare const INVALID_REQUEST = -32600;
26
- declare const METHOD_NOT_FOUND = -32601;
27
- declare const INVALID_PARAMS = -32602;
28
- declare const INTERNAL_ERROR = -32603;
29
- declare const PARSE_ERROR = -32700;
30
- declare const REQUEST_ABORTED = -32800;
31
- type Handler = (params: any) => any | Promise<any>;
32
- declare class JsonRpcServer {
33
- private methods;
34
- register(method: string, handler: Handler): void;
35
- handle(raw: unknown): Promise<JsonRpcResponse | JsonRpcResponse[] | null>;
36
- private error;
37
- }
38
-
39
- declare class JsonRpcClient {
40
- private send;
41
- private id;
42
- constructor(send: (req: JsonRpcRequest) => Promise<JsonRpcResponse>);
43
- call<T = unknown>(method: string, params?: unknown): Promise<T>;
44
- notify(method: string, params?: unknown): Promise<JsonRpcResponse>;
45
- }
46
-
47
- export { type Handler, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, JsonRpcClient, type JsonRpcError, type JsonRpcErrorObject, type JsonRpcId, type JsonRpcRequest, type JsonRpcResponse, JsonRpcServer, type JsonRpcSuccess, METHOD_NOT_FOUND, PARSE_ERROR, REQUEST_ABORTED };
1
+ export * from "./types";
2
+ export * from "./server";
3
+ export * from "./client";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AACvB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC"}
package/dist/index.js CHANGED
@@ -1,133 +1,4 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- INTERNAL_ERROR: () => INTERNAL_ERROR,
24
- INVALID_PARAMS: () => INVALID_PARAMS,
25
- INVALID_REQUEST: () => INVALID_REQUEST,
26
- JsonRpcClient: () => JsonRpcClient,
27
- JsonRpcServer: () => JsonRpcServer,
28
- METHOD_NOT_FOUND: () => METHOD_NOT_FOUND,
29
- PARSE_ERROR: () => PARSE_ERROR,
30
- REQUEST_ABORTED: () => REQUEST_ABORTED
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/server.ts
35
- var INVALID_REQUEST = -32600;
36
- var METHOD_NOT_FOUND = -32601;
37
- var INVALID_PARAMS = -32602;
38
- var INTERNAL_ERROR = -32603;
39
- var PARSE_ERROR = -32700;
40
- var REQUEST_ABORTED = -32800;
41
- var JsonRpcServer = class {
42
- methods = /* @__PURE__ */ new Map();
43
- register(method, handler) {
44
- this.methods.set(method, handler);
45
- }
46
- async handle(raw) {
47
- if (Array.isArray(raw)) {
48
- if (raw.length === 0) {
49
- return this.error(null, INVALID_REQUEST, "Invalid request");
50
- }
51
- const responses = await Promise.all(
52
- raw.map((item) => this.handle(item))
53
- );
54
- const filtered = responses.filter(
55
- (r) => r !== null
56
- );
57
- return filtered.length > 0 ? filtered : null;
58
- }
59
- let req = raw;
60
- if (typeof req !== "object" || req === null || req.jsonrpc !== "2.0" || typeof req.method !== "string") {
61
- return this.error(null, INVALID_REQUEST, "Invalid request");
62
- }
63
- const id = typeof req?.id === "string" || typeof req?.id === "number" || req?.id === null ? req.id : null;
64
- const handler = this.methods.get(req.method);
65
- if (!handler) {
66
- return id === null ? null : this.error(req.id, METHOD_NOT_FOUND, "Method not found");
67
- }
68
- try {
69
- const result = await handler(req.params);
70
- if (req.id === void 0) return null;
71
- return {
72
- jsonrpc: "2.0",
73
- result,
74
- id: req.id
75
- };
76
- } catch (err) {
77
- return this.error(
78
- req.id ?? null,
79
- INTERNAL_ERROR,
80
- "Internal error",
81
- err instanceof Error ? err.message : err
82
- );
83
- }
84
- }
85
- error(id, code, message, data) {
86
- return {
87
- jsonrpc: "2.0",
88
- error: { code, message, data },
89
- id: id ?? null
90
- };
91
- }
92
- };
93
-
94
- // src/client.ts
95
- var JsonRpcClient = class {
96
- constructor(send) {
97
- this.send = send;
98
- }
99
- id = 0;
100
- async call(method, params) {
101
- const request = {
102
- jsonrpc: "2.0",
103
- method,
104
- params,
105
- id: ++this.id
106
- };
107
- const response = await this.send(request);
108
- if ("error" in response) {
109
- const e = response.error;
110
- throw new Error(`RPC error ${e.code} ${e.message}`);
111
- }
112
- return response.result;
113
- }
114
- notify(method, params) {
115
- const request = {
116
- jsonrpc: "2.0",
117
- method,
118
- params
119
- };
120
- return this.send(request);
121
- }
122
- };
123
- // Annotate the CommonJS export names for ESM import in node:
124
- 0 && (module.exports = {
125
- INTERNAL_ERROR,
126
- INVALID_PARAMS,
127
- INVALID_REQUEST,
128
- JsonRpcClient,
129
- JsonRpcServer,
130
- METHOD_NOT_FOUND,
131
- PARSE_ERROR,
132
- REQUEST_ABORTED
133
- });
1
+ export * from "./types";
2
+ export * from "./server";
3
+ export * from "./client";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AACvB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { JsonRpcResponse } from "./types";
2
+ export declare enum JsonRpcErrorCodes {
3
+ INVALID_REQUEST = -32600,
4
+ METHOD_NOT_FOUND = -32601,
5
+ INVALID_PARAMS = -32602,
6
+ INTERNAL_ERROR = -32603,
7
+ PARSE_ERROR = -32700,
8
+ REQUEST_ABORTED = -32800
9
+ }
10
+ export type Handler<Result> = (params: any) => any | Promise<Result>;
11
+ export declare class JsonRpcServer {
12
+ private methods;
13
+ register(method: string, handler: Handler<any>): void;
14
+ handle<Result, Method = string>(raw: unknown): Promise<JsonRpcResponse<Result, JsonRpcErrorCodes | number> | JsonRpcResponse<Result, JsonRpcErrorCodes | number>[] | null>;
15
+ private error;
16
+ }
17
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,SAAS,CAAC;AAE/D,oBAAY,iBAAiB;IAC3B,eAAe,SAAS;IACxB,gBAAgB,SAAS;IACzB,cAAc,SAAS;IACvB,cAAc,SAAS;IACvB,WAAW,SAAS;IACpB,eAAe,SAAS;CACzB;AACD,MAAM,MAAM,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;AAEpE,qBAAa,aAAa;IACxB,OAAO,CAAC,OAAO,CAAkC;IAEjD,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC;IAIxC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAClC,GAAG,EAAE,OAAO,GACX,OAAO,CAAC,eAAe,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAAC,GAAG,eAAe,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAAC,EAAE,GAAG,IAAI,CAAC;IAuD9H,OAAO,CAAC,KAAK;CAYd"}
package/dist/server.js ADDED
@@ -0,0 +1,62 @@
1
+ export var JsonRpcErrorCodes;
2
+ (function (JsonRpcErrorCodes) {
3
+ JsonRpcErrorCodes[JsonRpcErrorCodes["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
4
+ JsonRpcErrorCodes[JsonRpcErrorCodes["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
5
+ JsonRpcErrorCodes[JsonRpcErrorCodes["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
6
+ JsonRpcErrorCodes[JsonRpcErrorCodes["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
7
+ JsonRpcErrorCodes[JsonRpcErrorCodes["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
8
+ JsonRpcErrorCodes[JsonRpcErrorCodes["REQUEST_ABORTED"] = -32800] = "REQUEST_ABORTED";
9
+ })(JsonRpcErrorCodes || (JsonRpcErrorCodes = {}));
10
+ export class JsonRpcServer {
11
+ methods = new Map();
12
+ register(method, handler) {
13
+ this.methods.set(method, handler);
14
+ }
15
+ async handle(raw) {
16
+ // handle batch
17
+ if (Array.isArray(raw)) {
18
+ if (raw.length === 0) {
19
+ return this.error(null, JsonRpcErrorCodes.INVALID_REQUEST, "Invalid request");
20
+ }
21
+ const responses = await Promise.all(raw.map(item => this.handle(item)));
22
+ const filtered = responses.filter((r) => r !== null);
23
+ return filtered.length > 0 ? filtered : null;
24
+ }
25
+ // handle single response
26
+ let req = raw;
27
+ if (typeof req !== "object" ||
28
+ req === null ||
29
+ req.jsonrpc !== "2.0" ||
30
+ typeof req.method !== "string") {
31
+ return this.error(null, JsonRpcErrorCodes.INVALID_REQUEST, "Invalid request");
32
+ }
33
+ const id = typeof req?.id === "string" ||
34
+ typeof req?.id === "number" ||
35
+ req?.id === null ? req.id : null;
36
+ const handler = this.methods.get(req.method);
37
+ if (!handler) {
38
+ return id === null ? null : this.error(req.id, JsonRpcErrorCodes.METHOD_NOT_FOUND, "Method not found");
39
+ }
40
+ try {
41
+ const result = await handler(req.params);
42
+ if (req.id === undefined)
43
+ return null; // notification
44
+ return {
45
+ jsonrpc: "2.0",
46
+ result,
47
+ id: req.id
48
+ };
49
+ }
50
+ catch (err) {
51
+ return this.error(req.id ?? null, JsonRpcErrorCodes.INTERNAL_ERROR, "Internal error", err instanceof Error ? err.message : err);
52
+ }
53
+ }
54
+ error(id, code, message, data) {
55
+ return {
56
+ jsonrpc: "2.0",
57
+ error: { code, message, data },
58
+ id: id ?? null
59
+ };
60
+ }
61
+ }
62
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,24 @@
1
+ export type JsonRpcId = string | number | null;
2
+ export interface JsonRpcRequest<Method> {
3
+ jsonrpc: "2.0";
4
+ method: Method;
5
+ params?: unknown[];
6
+ id?: JsonRpcId;
7
+ }
8
+ export interface JsonRpcSuccess<Result> {
9
+ jsonrpc: "2.0";
10
+ result: Result;
11
+ id: JsonRpcId;
12
+ }
13
+ export interface JsonRpcErrorObject<ErrorCode> {
14
+ code: ErrorCode;
15
+ message: string;
16
+ data?: unknown;
17
+ }
18
+ export interface JsonRpcError<ErrorCode> {
19
+ jsonrpc: "2.0";
20
+ error: JsonRpcErrorObject<ErrorCode>;
21
+ id: JsonRpcId;
22
+ }
23
+ export type JsonRpcResponse<Result, ErrorCode> = JsonRpcSuccess<Result> | JsonRpcError<ErrorCode>;
24
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;AAE9C,MAAM,WAAW,cAAc,CAAC,MAAM;IACpC,OAAO,EAAE,KAAK,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,OAAO,EAAE,CAAA;IAClB,EAAE,CAAC,EAAE,SAAS,CAAA;CACf;AAED,MAAM,WAAW,cAAc,CAAC,MAAM;IACpC,OAAO,EAAE,KAAK,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,EAAE,EAAE,SAAS,CAAA;CACd;AAED,MAAM,WAAW,kBAAkB,CAAC,SAAS;IAC3C,IAAI,EAAE,SAAS,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,OAAO,CAAA;CACf;AAED,MAAM,WAAW,YAAY,CAAC,SAAS;IACrC,OAAO,EAAE,KAAK,CAAA;IACd,KAAK,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAA;IACpC,EAAE,EAAE,SAAS,CAAA;CACd;AAED,MAAM,MAAM,eAAe,CAAC,MAAM,EAAE,SAAS,IAAI,cAAc,CAAC,MAAM,CAAC,GAAG,YAAY,CAAC,SAAS,CAAC,CAAA"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@msaki/jsonrpc",
3
3
  "author": "Meek Msaki",
4
- "version": "0.0.3",
4
+ "version": "0.1.1",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
8
8
  "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "src"
12
+ ],
9
13
  "repository": {
10
14
  "type": "git",
11
15
  "url": "git+https://github.com/mmsaki/libs.git",
@@ -16,13 +20,12 @@
16
20
  "directory": "dist"
17
21
  },
18
22
  "scripts": {
19
- "build": "tsup index.ts --format cjs,esm --dts",
20
- "publish": "bun run build && npm publish --access public",
23
+ "build": "tsc -p tsconfig.json",
24
+ "publish": "bun run build && bun publish --access public",
21
25
  "lint": "tsc"
22
26
  },
23
27
  "devDependencies": {
24
- "@types/bun": "latest",
25
- "tsup": "^8.5.1"
28
+ "@types/bun": "latest"
26
29
  },
27
30
  "peerDependencies": {
28
31
  "typescript": "^5"
package/src/client.ts CHANGED
@@ -4,11 +4,11 @@ export class JsonRpcClient {
4
4
  private id = 0
5
5
 
6
6
  constructor(
7
- private send: (req: JsonRpcRequest) => Promise<JsonRpcResponse>
7
+ private send: (req: JsonRpcRequest<unknown>) => Promise<JsonRpcResponse<unknown, number>>
8
8
  ) {}
9
9
 
10
- async call<T = unknown>(method: string, params?: unknown): Promise<T> {
11
- const request: JsonRpcRequest = {
10
+ async call<Method = string, Result = unknown, E = unknown>(method: Method, params?: unknown[]): Promise<Result | E> {
11
+ const request: JsonRpcRequest<Method> = {
12
12
  jsonrpc: "2.0",
13
13
  method,
14
14
  params,
@@ -16,14 +16,13 @@ export class JsonRpcClient {
16
16
  }
17
17
  const response = await this.send(request);
18
18
  if ("error" in response) {
19
- const e = response.error
20
- throw new Error(`RPC error ${e.code} ${e.message}`)
19
+ return response.error as E
21
20
  }
22
- return response.result as T
21
+ return response.result as Result
23
22
  }
24
23
 
25
- notify(method: string, params?: unknown) {
26
- const request: JsonRpcRequest = {
24
+ notify<Method = string>(method: Method, params?: unknown[]) {
25
+ const request: JsonRpcRequest<Method> = {
27
26
  jsonrpc: "2.0",
28
27
  method,
29
28
  params
@@ -31,3 +30,16 @@ export class JsonRpcClient {
31
30
  return this.send(request)
32
31
  }
33
32
  }
33
+
34
+ export function initializeRpcClient(url: string): JsonRpcClient {
35
+ const client = new JsonRpcClient(async (req: JsonRpcRequest<unknown>) => {
36
+ const res = await fetch(url, {
37
+ method: "POST",
38
+ headers: { "Content-Type": "application/json" },
39
+ body: JSON.stringify(req)
40
+ });
41
+
42
+ return (await res.json()) as JsonRpcResponse<unknown, number>
43
+ });
44
+ return client;
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./types"
2
+ export * from "./server";
3
+ export * from "./client";
package/src/server.ts CHANGED
@@ -1,58 +1,59 @@
1
- import type { JsonRpcResponse, JsonRpcRequest } from "./types";
1
+ import type { JsonRpcResponse, JsonRpcRequest } from "./types";
2
2
 
3
- export const INVALID_REQUEST = -32600;
4
- export const METHOD_NOT_FOUND = -32601;
5
- export const INVALID_PARAMS = -32602; // unused
6
- export const INTERNAL_ERROR = -32603;
7
- export const PARSE_ERROR = -32700; // unused
8
- export const REQUEST_ABORTED = -32800; // unused
9
-
10
- export type Handler = (params: any) => any | Promise<any>
3
+ export enum JsonRpcErrorCodes {
4
+ INVALID_REQUEST = -32600,
5
+ METHOD_NOT_FOUND = -32601,
6
+ INVALID_PARAMS = -32602,
7
+ INTERNAL_ERROR = -32603,
8
+ PARSE_ERROR = -32700,
9
+ REQUEST_ABORTED = -32800,
10
+ }
11
+ export type Handler<Result> = (params: any) => any | Promise<Result>
11
12
 
12
13
  export class JsonRpcServer {
13
- private methods = new Map<string, Handler>()
14
+ private methods = new Map<string, Handler<any>>()
14
15
 
15
- register(method: string, handler: Handler) {
16
+ register(method: string, handler: Handler<any>) {
16
17
  this.methods.set(method, handler)
17
18
  }
18
19
 
19
- async handle(
20
- raw: unknown,
21
- ): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {
20
+ async handle<Result, Method = string>(
21
+ raw: unknown,
22
+ ): Promise<JsonRpcResponse<Result, JsonRpcErrorCodes | number> | JsonRpcResponse<Result, JsonRpcErrorCodes | number>[] | null> {
22
23
  // handle batch
23
24
  if (Array.isArray(raw)) {
24
25
  if (raw.length === 0) {
25
- return this.error(null, INVALID_REQUEST, "Invalid request")
26
+ return this.error(null, JsonRpcErrorCodes.INVALID_REQUEST, "Invalid request")
26
27
  }
27
28
  const responses = await Promise.all(
28
29
  raw.map(item => this.handle(item))
29
30
  )
30
- const filtered = responses.filter(
31
- (r): r is JsonRpcResponse => r !== null
31
+ const filtered = responses.filter(
32
+ (r): r is JsonRpcResponse<Result, JsonRpcErrorCodes | number> => r !== null
32
33
  )
33
34
  return filtered.length > 0 ? filtered : null
34
35
  }
35
36
 
36
37
  // handle single response
37
- let req = raw as Partial<JsonRpcRequest>
38
+ let req = raw as Partial<JsonRpcRequest<Method>>
38
39
 
39
40
  if (
40
41
  typeof req !== "object" ||
41
- req === null ||
42
- req.jsonrpc !== "2.0" ||
43
- typeof req.method !== "string"
42
+ req === null ||
43
+ req.jsonrpc !== "2.0" ||
44
+ typeof req.method !== "string"
44
45
  ) {
45
- return this.error(null, INVALID_REQUEST, "Invalid request")
46
+ return this.error(null, JsonRpcErrorCodes.INVALID_REQUEST, "Invalid request")
46
47
  }
47
-
48
- const id =
48
+
49
+ const id =
49
50
  typeof (req as any)?.id === "string" ||
50
- typeof (req as any)?.id === "number" ||
51
- (req as any)?.id === null ? (req as any).id : null
51
+ typeof (req as any)?.id === "number" ||
52
+ (req as any)?.id === null ? (req as any).id : null
52
53
 
53
54
  const handler = this.methods.get(req.method)
54
55
  if (!handler) {
55
- return id === null ? null : this.error(req.id, METHOD_NOT_FOUND, "Method not found")
56
+ return id === null ? null : this.error(req.id, JsonRpcErrorCodes.METHOD_NOT_FOUND, "Method not found")
56
57
  }
57
58
 
58
59
  try {
@@ -66,19 +67,19 @@ export class JsonRpcServer {
66
67
  } catch (err) {
67
68
  return this.error(
68
69
  req.id ?? null,
69
- INTERNAL_ERROR,
70
+ JsonRpcErrorCodes.INTERNAL_ERROR,
70
71
  "Internal error",
71
72
  err instanceof Error ? err.message : err
72
73
  )
73
74
  }
74
75
  }
75
76
 
76
- private error(
77
- id: JsonRpcRequest["id"],
78
- code: number,
77
+ private error<Result, Method = string>(
78
+ id: JsonRpcRequest<Method>["id"],
79
+ code: JsonRpcErrorCodes | number,
79
80
  message: string,
80
81
  data?: unknown
81
- ): JsonRpcResponse {
82
+ ): JsonRpcResponse<Result, JsonRpcErrorCodes | number> {
82
83
  return {
83
84
  jsonrpc: "2.0",
84
85
  error: { code, message, data },
package/src/types.ts CHANGED
@@ -1,28 +1,28 @@
1
1
  export type JsonRpcId = string | number | null
2
2
 
3
- export interface JsonRpcRequest {
3
+ export interface JsonRpcRequest<Method> {
4
4
  jsonrpc: "2.0"
5
- method: string
6
- params?: unknown
5
+ method: Method
6
+ params?: unknown[]
7
7
  id?: JsonRpcId
8
8
  }
9
9
 
10
- export interface JsonRpcSuccess {
10
+ export interface JsonRpcSuccess<Result> {
11
11
  jsonrpc: "2.0"
12
- result: unknown
12
+ result: Result
13
13
  id: JsonRpcId
14
14
  }
15
15
 
16
- export interface JsonRpcErrorObject {
17
- code: number
16
+ export interface JsonRpcErrorObject<ErrorCode> {
17
+ code: ErrorCode
18
18
  message: string
19
19
  data?: unknown
20
20
  }
21
21
 
22
- export interface JsonRpcError {
22
+ export interface JsonRpcError<ErrorCode> {
23
23
  jsonrpc: "2.0"
24
- error: JsonRpcErrorObject
24
+ error: JsonRpcErrorObject<ErrorCode>
25
25
  id: JsonRpcId
26
26
  }
27
27
 
28
- export type JsonRpcResponse = JsonRpcSuccess | JsonRpcError
28
+ export type JsonRpcResponse<Result, ErrorCode> = JsonRpcSuccess<Result> | JsonRpcError<ErrorCode>
package/dist/index.d.mts DELETED
@@ -1,47 +0,0 @@
1
- type JsonRpcId = string | number | null;
2
- interface JsonRpcRequest {
3
- jsonrpc: "2.0";
4
- method: string;
5
- params?: unknown;
6
- id?: JsonRpcId;
7
- }
8
- interface JsonRpcSuccess {
9
- jsonrpc: "2.0";
10
- result: unknown;
11
- id: JsonRpcId;
12
- }
13
- interface JsonRpcErrorObject {
14
- code: number;
15
- message: string;
16
- data?: unknown;
17
- }
18
- interface JsonRpcError {
19
- jsonrpc: "2.0";
20
- error: JsonRpcErrorObject;
21
- id: JsonRpcId;
22
- }
23
- type JsonRpcResponse = JsonRpcSuccess | JsonRpcError;
24
-
25
- declare const INVALID_REQUEST = -32600;
26
- declare const METHOD_NOT_FOUND = -32601;
27
- declare const INVALID_PARAMS = -32602;
28
- declare const INTERNAL_ERROR = -32603;
29
- declare const PARSE_ERROR = -32700;
30
- declare const REQUEST_ABORTED = -32800;
31
- type Handler = (params: any) => any | Promise<any>;
32
- declare class JsonRpcServer {
33
- private methods;
34
- register(method: string, handler: Handler): void;
35
- handle(raw: unknown): Promise<JsonRpcResponse | JsonRpcResponse[] | null>;
36
- private error;
37
- }
38
-
39
- declare class JsonRpcClient {
40
- private send;
41
- private id;
42
- constructor(send: (req: JsonRpcRequest) => Promise<JsonRpcResponse>);
43
- call<T = unknown>(method: string, params?: unknown): Promise<T>;
44
- notify(method: string, params?: unknown): Promise<JsonRpcResponse>;
45
- }
46
-
47
- export { type Handler, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, JsonRpcClient, type JsonRpcError, type JsonRpcErrorObject, type JsonRpcId, type JsonRpcRequest, type JsonRpcResponse, JsonRpcServer, type JsonRpcSuccess, METHOD_NOT_FOUND, PARSE_ERROR, REQUEST_ABORTED };
package/dist/index.mjs DELETED
@@ -1,99 +0,0 @@
1
- // src/server.ts
2
- var INVALID_REQUEST = -32600;
3
- var METHOD_NOT_FOUND = -32601;
4
- var INVALID_PARAMS = -32602;
5
- var INTERNAL_ERROR = -32603;
6
- var PARSE_ERROR = -32700;
7
- var REQUEST_ABORTED = -32800;
8
- var JsonRpcServer = class {
9
- methods = /* @__PURE__ */ new Map();
10
- register(method, handler) {
11
- this.methods.set(method, handler);
12
- }
13
- async handle(raw) {
14
- if (Array.isArray(raw)) {
15
- if (raw.length === 0) {
16
- return this.error(null, INVALID_REQUEST, "Invalid request");
17
- }
18
- const responses = await Promise.all(
19
- raw.map((item) => this.handle(item))
20
- );
21
- const filtered = responses.filter(
22
- (r) => r !== null
23
- );
24
- return filtered.length > 0 ? filtered : null;
25
- }
26
- let req = raw;
27
- if (typeof req !== "object" || req === null || req.jsonrpc !== "2.0" || typeof req.method !== "string") {
28
- return this.error(null, INVALID_REQUEST, "Invalid request");
29
- }
30
- const id = typeof req?.id === "string" || typeof req?.id === "number" || req?.id === null ? req.id : null;
31
- const handler = this.methods.get(req.method);
32
- if (!handler) {
33
- return id === null ? null : this.error(req.id, METHOD_NOT_FOUND, "Method not found");
34
- }
35
- try {
36
- const result = await handler(req.params);
37
- if (req.id === void 0) return null;
38
- return {
39
- jsonrpc: "2.0",
40
- result,
41
- id: req.id
42
- };
43
- } catch (err) {
44
- return this.error(
45
- req.id ?? null,
46
- INTERNAL_ERROR,
47
- "Internal error",
48
- err instanceof Error ? err.message : err
49
- );
50
- }
51
- }
52
- error(id, code, message, data) {
53
- return {
54
- jsonrpc: "2.0",
55
- error: { code, message, data },
56
- id: id ?? null
57
- };
58
- }
59
- };
60
-
61
- // src/client.ts
62
- var JsonRpcClient = class {
63
- constructor(send) {
64
- this.send = send;
65
- }
66
- id = 0;
67
- async call(method, params) {
68
- const request = {
69
- jsonrpc: "2.0",
70
- method,
71
- params,
72
- id: ++this.id
73
- };
74
- const response = await this.send(request);
75
- if ("error" in response) {
76
- const e = response.error;
77
- throw new Error(`RPC error ${e.code} ${e.message}`);
78
- }
79
- return response.result;
80
- }
81
- notify(method, params) {
82
- const request = {
83
- jsonrpc: "2.0",
84
- method,
85
- params
86
- };
87
- return this.send(request);
88
- }
89
- };
90
- export {
91
- INTERNAL_ERROR,
92
- INVALID_PARAMS,
93
- INVALID_REQUEST,
94
- JsonRpcClient,
95
- JsonRpcServer,
96
- METHOD_NOT_FOUND,
97
- PARSE_ERROR,
98
- REQUEST_ABORTED
99
- };
package/index.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from "./src/types"
2
- export * from "./src/server";
3
- export * from "./src/client";
package/tsconfig.json DELETED
@@ -1,28 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": [
5
- "ESNext"
6
- ],
7
- "target": "ESNext",
8
- "module": "Preserve",
9
- "moduleDetection": "force",
10
- "jsx": "react-jsx",
11
- "allowJs": true,
12
- // Bundler mode
13
- "moduleResolution": "bundler",
14
- "allowImportingTsExtensions": true,
15
- "verbatimModuleSyntax": true,
16
- "noEmit": true,
17
- // Best practices
18
- "strict": true,
19
- "skipLibCheck": true,
20
- "noFallthroughCasesInSwitch": true,
21
- "noUncheckedIndexedAccess": true,
22
- "noImplicitOverride": true,
23
- // Some stricter flags (disabled by default)
24
- "noUnusedLocals": false,
25
- "noUnusedParameters": false,
26
- "noPropertyAccessFromIndexSignature": false
27
- }
28
- }