@goplus123/core-api 1.0.6 → 1.0.7
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 +88 -11
- package/dist/index.cjs +180 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +176 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -129,7 +129,7 @@ interface GrpcClientConfig {
|
|
|
129
129
|
headers?: Record<string, string>;
|
|
130
130
|
getHeaders?: () => Record<string, string> | null | undefined | Promise<Record<string, string> | null | undefined>;
|
|
131
131
|
logger?: ApiLogger;
|
|
132
|
-
invoker?: GrpcInvoker;
|
|
132
|
+
invoker?: GrpcInvoker | 'builtin';
|
|
133
133
|
}
|
|
134
134
|
/**
|
|
135
135
|
* 通用 gRPC 客户端封装 (基于 ConnectRPC)
|
|
@@ -149,6 +149,7 @@ declare class GrpcClient {
|
|
|
149
149
|
private getHeaders?;
|
|
150
150
|
private logger?;
|
|
151
151
|
private invoker?;
|
|
152
|
+
private invokerMode;
|
|
152
153
|
private invokerClientByKey;
|
|
153
154
|
constructor(config: GrpcClientConfig);
|
|
154
155
|
private createTransport;
|
package/dist/index.d.ts
CHANGED
|
@@ -129,7 +129,7 @@ interface GrpcClientConfig {
|
|
|
129
129
|
headers?: Record<string, string>;
|
|
130
130
|
getHeaders?: () => Record<string, string> | null | undefined | Promise<Record<string, string> | null | undefined>;
|
|
131
131
|
logger?: ApiLogger;
|
|
132
|
-
invoker?: GrpcInvoker;
|
|
132
|
+
invoker?: GrpcInvoker | 'builtin';
|
|
133
133
|
}
|
|
134
134
|
/**
|
|
135
135
|
* 通用 gRPC 客户端封装 (基于 ConnectRPC)
|
|
@@ -149,6 +149,7 @@ declare class GrpcClient {
|
|
|
149
149
|
private getHeaders?;
|
|
150
150
|
private logger?;
|
|
151
151
|
private invoker?;
|
|
152
|
+
private invokerMode;
|
|
152
153
|
private invokerClientByKey;
|
|
153
154
|
constructor(config: GrpcClientConfig);
|
|
154
155
|
private createTransport;
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,173 @@
|
|
|
2
2
|
import { createClient } from "@connectrpc/connect";
|
|
3
3
|
import { createConnectTransport, createGrpcWebTransport } from "@connectrpc/connect-web";
|
|
4
4
|
import { create } from "@bufbuild/protobuf";
|
|
5
|
+
|
|
6
|
+
// src/client/invokers/builtinGrpcWebInvoker.ts
|
|
7
|
+
import { fromBinary, toBinary } from "@bufbuild/protobuf";
|
|
8
|
+
function createBuiltinGrpcWebInvoker(options) {
|
|
9
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
10
|
+
const logger = options.logger;
|
|
11
|
+
if (!fetchImpl) {
|
|
12
|
+
return {
|
|
13
|
+
unary: async () => {
|
|
14
|
+
throw new Error("fetch is not available in current environment");
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const grpcWebEncodeUnary = (messageBytes) => {
|
|
19
|
+
const out = new Uint8Array(5 + messageBytes.byteLength);
|
|
20
|
+
out[0] = 0;
|
|
21
|
+
const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
|
|
22
|
+
view.setUint32(1, messageBytes.byteLength, false);
|
|
23
|
+
out.set(messageBytes, 5);
|
|
24
|
+
return out;
|
|
25
|
+
};
|
|
26
|
+
const bytesToAscii = (bytes) => {
|
|
27
|
+
let s = "";
|
|
28
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
29
|
+
return s;
|
|
30
|
+
};
|
|
31
|
+
const parseGrpcWebTrailers = (bytes) => {
|
|
32
|
+
const text = bytesToAscii(bytes);
|
|
33
|
+
const out = {};
|
|
34
|
+
for (const line of text.split("\r\n")) {
|
|
35
|
+
if (!line) continue;
|
|
36
|
+
const idx = line.indexOf(":");
|
|
37
|
+
if (idx < 0) continue;
|
|
38
|
+
const k = line.slice(0, idx).trim().toLowerCase();
|
|
39
|
+
const v = line.slice(idx + 1).trim();
|
|
40
|
+
out[k] = v;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
};
|
|
44
|
+
const grpcWebDecodeUnary = (body) => {
|
|
45
|
+
let offset = 0;
|
|
46
|
+
let message;
|
|
47
|
+
let trailers = {};
|
|
48
|
+
while (offset + 5 <= body.byteLength) {
|
|
49
|
+
const flags = body[offset];
|
|
50
|
+
const length = new DataView(body.buffer, body.byteOffset + offset + 1, 4).getUint32(0, false);
|
|
51
|
+
offset += 5;
|
|
52
|
+
if (offset + length > body.byteLength) break;
|
|
53
|
+
const frame = body.subarray(offset, offset + length);
|
|
54
|
+
offset += length;
|
|
55
|
+
const isTrailer = (flags & 128) === 128;
|
|
56
|
+
if (isTrailer) {
|
|
57
|
+
trailers = { ...trailers, ...parseGrpcWebTrailers(frame) };
|
|
58
|
+
} else if (message == null) {
|
|
59
|
+
message = frame;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { message, trailers };
|
|
63
|
+
};
|
|
64
|
+
const joinUrl = (baseUrl, path) => {
|
|
65
|
+
return baseUrl.replace(/\/+$/, "") + "/" + path.replace(/^\/+/, "");
|
|
66
|
+
};
|
|
67
|
+
const capitalizeRpcName = (methodName) => {
|
|
68
|
+
if (!methodName) return methodName;
|
|
69
|
+
return methodName[0].toUpperCase() + methodName.slice(1);
|
|
70
|
+
};
|
|
71
|
+
const getGrpcWebPath = (service, methodName, method) => {
|
|
72
|
+
const typeName = String(service?.typeName ?? "");
|
|
73
|
+
const rpcName = String(method?.name ?? "") || capitalizeRpcName(methodName);
|
|
74
|
+
return `${typeName}/${rpcName}`;
|
|
75
|
+
};
|
|
76
|
+
const safeDecodeGrpcMessage = (value) => {
|
|
77
|
+
if (!value) return value;
|
|
78
|
+
try {
|
|
79
|
+
return decodeURIComponent(value);
|
|
80
|
+
} catch {
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
unary: async (args) => {
|
|
86
|
+
const service = String(args.service?.typeName ?? "");
|
|
87
|
+
const startedAt = Date.now();
|
|
88
|
+
let url;
|
|
89
|
+
const contentType = "application/grpc-web+proto";
|
|
90
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
|
|
91
|
+
const timeoutMs = args.callOptions?.timeoutMs;
|
|
92
|
+
const timeoutId = controller && typeof timeoutMs === "number" ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
|
|
93
|
+
try {
|
|
94
|
+
const method = args.method;
|
|
95
|
+
if (!method) {
|
|
96
|
+
throw new Error(`gRPC method not found: ${service}.${args.methodName}`);
|
|
97
|
+
}
|
|
98
|
+
url = joinUrl(args.baseUrl, getGrpcWebPath(args.service, args.methodName, method));
|
|
99
|
+
const requestBytes = toBinary(method.input, args.request);
|
|
100
|
+
const body = grpcWebEncodeUnary(requestBytes);
|
|
101
|
+
logger?.debug?.("[Grpc:Invoker:Builtin:Start]", {
|
|
102
|
+
service,
|
|
103
|
+
methodName: args.methodName,
|
|
104
|
+
baseUrl: args.baseUrl,
|
|
105
|
+
url,
|
|
106
|
+
timeoutMs,
|
|
107
|
+
requestBytes: requestBytes.byteLength
|
|
108
|
+
});
|
|
109
|
+
const res = await fetchImpl(url, {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: {
|
|
112
|
+
...args.headers,
|
|
113
|
+
"content-type": contentType,
|
|
114
|
+
accept: contentType,
|
|
115
|
+
"x-grpc-web": "1"
|
|
116
|
+
},
|
|
117
|
+
body: body.buffer,
|
|
118
|
+
signal: controller?.signal
|
|
119
|
+
});
|
|
120
|
+
logger?.debug?.("[Grpc:Invoker:Builtin:Http]", {
|
|
121
|
+
service,
|
|
122
|
+
methodName: args.methodName,
|
|
123
|
+
url,
|
|
124
|
+
ok: res.ok,
|
|
125
|
+
status: res.status,
|
|
126
|
+
statusText: res.statusText,
|
|
127
|
+
durationMs: Date.now() - startedAt
|
|
128
|
+
});
|
|
129
|
+
if (!res.ok) {
|
|
130
|
+
throw new Error(`gRPC fetch failed: ${res.status} ${res.statusText}`);
|
|
131
|
+
}
|
|
132
|
+
const raw = new Uint8Array(await res.arrayBuffer());
|
|
133
|
+
const decoded = grpcWebDecodeUnary(raw);
|
|
134
|
+
const statusFromHeaders = typeof res.headers?.get === "function" ? res.headers.get("grpc-status") : void 0;
|
|
135
|
+
const msgFromHeaders = typeof res.headers?.get === "function" ? res.headers.get("grpc-message") : void 0;
|
|
136
|
+
const grpcStatus = decoded.trailers["grpc-status"] ?? statusFromHeaders ?? "0";
|
|
137
|
+
const grpcMessage = safeDecodeGrpcMessage(
|
|
138
|
+
decoded.trailers["grpc-message"] ?? msgFromHeaders
|
|
139
|
+
);
|
|
140
|
+
logger?.debug?.("[Grpc:Invoker:Builtin:End]", {
|
|
141
|
+
service,
|
|
142
|
+
methodName: args.methodName,
|
|
143
|
+
url,
|
|
144
|
+
grpcStatus,
|
|
145
|
+
grpcMessage,
|
|
146
|
+
durationMs: Date.now() - startedAt
|
|
147
|
+
});
|
|
148
|
+
if (grpcStatus !== "0") {
|
|
149
|
+
const msg = grpcMessage ?? "gRPC request failed";
|
|
150
|
+
throw new Error(`gRPC status=${grpcStatus} message=${msg}`);
|
|
151
|
+
}
|
|
152
|
+
if (!decoded.message) throw new Error("gRPC response message missing");
|
|
153
|
+
return fromBinary(method.output, decoded.message);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
logger?.error?.("[Grpc:Invoker:Builtin:Error]", {
|
|
156
|
+
service,
|
|
157
|
+
methodName: args.methodName,
|
|
158
|
+
baseUrl: args.baseUrl,
|
|
159
|
+
url,
|
|
160
|
+
durationMs: Date.now() - startedAt,
|
|
161
|
+
error
|
|
162
|
+
});
|
|
163
|
+
throw error;
|
|
164
|
+
} finally {
|
|
165
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/client/grpcClient.ts
|
|
5
172
|
var GrpcApiError = class extends Error {
|
|
6
173
|
name = "GrpcApiError";
|
|
7
174
|
service;
|
|
@@ -32,6 +199,7 @@ var GrpcClient = class {
|
|
|
32
199
|
getHeaders;
|
|
33
200
|
logger;
|
|
34
201
|
invoker;
|
|
202
|
+
invokerMode;
|
|
35
203
|
invokerClientByKey;
|
|
36
204
|
constructor(config) {
|
|
37
205
|
this.baseUrl = config.baseUrl;
|
|
@@ -42,7 +210,6 @@ var GrpcClient = class {
|
|
|
42
210
|
this.getToken = config.getToken;
|
|
43
211
|
this.headers = config.headers;
|
|
44
212
|
this.getHeaders = config.getHeaders;
|
|
45
|
-
this.invoker = config.invoker;
|
|
46
213
|
this.logger = config.logger ?? (config.debug ? { debug: console.log, info: console.log, warn: console.warn, error: console.error } : void 0);
|
|
47
214
|
this.interceptors = [
|
|
48
215
|
this.createRpcFromInterceptor(),
|
|
@@ -53,6 +220,8 @@ var GrpcClient = class {
|
|
|
53
220
|
this.transportByBaseUrl = /* @__PURE__ */ new Map();
|
|
54
221
|
this.transport = this.createTransport(this.baseUrl);
|
|
55
222
|
this.invokerClientByKey = /* @__PURE__ */ new Map();
|
|
223
|
+
this.invokerMode = config.invoker === "builtin" ? "builtin" : config.invoker ? "custom" : "none";
|
|
224
|
+
this.invoker = config.invoker === "builtin" ? createBuiltinGrpcWebInvoker({ fetch: this.fetchImpl, logger: this.logger }) : config.invoker;
|
|
56
225
|
}
|
|
57
226
|
createTransport(baseUrl) {
|
|
58
227
|
const cached = this.transportByBaseUrl.get(baseUrl);
|
|
@@ -220,6 +389,12 @@ var GrpcClient = class {
|
|
|
220
389
|
const baseUrl = this.pickBaseUrl(typeName);
|
|
221
390
|
try {
|
|
222
391
|
if (this.invoker) {
|
|
392
|
+
this.logger?.debug?.("[Grpc:Invoker]", {
|
|
393
|
+
mode: this.invokerMode,
|
|
394
|
+
service: typeName,
|
|
395
|
+
methodName,
|
|
396
|
+
baseUrl
|
|
397
|
+
});
|
|
223
398
|
const method2 = this.getServiceMethodDesc(service, methodName);
|
|
224
399
|
const headers = await this.attachInvokerHeaders(
|
|
225
400
|
this.normalizeHeaders(options?.headers),
|