@goplus123/core-api 1.0.5 → 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 +215 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +211 -30
- 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;
|
|
@@ -157,6 +158,7 @@ declare class GrpcClient {
|
|
|
157
158
|
private hasHeader;
|
|
158
159
|
private attachInvokerHeaders;
|
|
159
160
|
private getInvokerClientKey;
|
|
161
|
+
private getServiceMethodMap;
|
|
160
162
|
private getServiceMethodDesc;
|
|
161
163
|
private getServiceViaInvoker;
|
|
162
164
|
private invokeUnary;
|
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;
|
|
@@ -157,6 +158,7 @@ declare class GrpcClient {
|
|
|
157
158
|
private hasHeader;
|
|
158
159
|
private attachInvokerHeaders;
|
|
159
160
|
private getInvokerClientKey;
|
|
161
|
+
private getServiceMethodMap;
|
|
160
162
|
private getServiceMethodDesc;
|
|
161
163
|
private getServiceViaInvoker;
|
|
162
164
|
private invokeUnary;
|
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);
|
|
@@ -148,20 +317,43 @@ var GrpcClient = class {
|
|
|
148
317
|
getInvokerClientKey(service, baseUrl) {
|
|
149
318
|
return `${String(service?.typeName ?? "")}@@${baseUrl}`;
|
|
150
319
|
}
|
|
151
|
-
|
|
320
|
+
getServiceMethodMap(service) {
|
|
321
|
+
const out = {};
|
|
322
|
+
const addMethod = (m) => {
|
|
323
|
+
if (!m) return;
|
|
324
|
+
const localName = m.localName != null ? String(m.localName) : "";
|
|
325
|
+
const name = m.name != null ? String(m.name) : "";
|
|
326
|
+
if (localName) out[localName] = m;
|
|
327
|
+
if (name && !(name in out)) out[name] = m;
|
|
328
|
+
};
|
|
329
|
+
const direct = service?.method;
|
|
330
|
+
if (direct && typeof direct === "object") {
|
|
331
|
+
for (const [k, v] of Object.entries(direct)) {
|
|
332
|
+
if (v) out[k] = v;
|
|
333
|
+
addMethod(v);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
152
336
|
const methods = service?.methods;
|
|
153
|
-
if (!methods) return void 0;
|
|
154
337
|
if (Array.isArray(methods)) {
|
|
155
|
-
for (const m of methods)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
338
|
+
for (const m of methods) addMethod(m);
|
|
339
|
+
} else if (methods && typeof methods === "object") {
|
|
340
|
+
for (const [k, v] of Object.entries(methods)) {
|
|
341
|
+
if (v) out[k] = v;
|
|
342
|
+
addMethod(v);
|
|
160
343
|
}
|
|
161
|
-
return void 0;
|
|
162
344
|
}
|
|
163
|
-
|
|
164
|
-
|
|
345
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
346
|
+
}
|
|
347
|
+
getServiceMethodDesc(service, methodName) {
|
|
348
|
+
const methodMap = this.getServiceMethodMap(service);
|
|
349
|
+
if (!methodMap) return void 0;
|
|
350
|
+
const direct = methodMap[methodName];
|
|
351
|
+
if (direct) return direct;
|
|
352
|
+
for (const m of Object.values(methodMap)) {
|
|
353
|
+
if (!m) continue;
|
|
354
|
+
const localName = m.localName != null ? String(m.localName) : "";
|
|
355
|
+
const name = m.name != null ? String(m.name) : "";
|
|
356
|
+
if (localName === methodName || name === methodName) return m;
|
|
165
357
|
}
|
|
166
358
|
return void 0;
|
|
167
359
|
}
|
|
@@ -170,24 +362,7 @@ var GrpcClient = class {
|
|
|
170
362
|
const key = this.getInvokerClientKey(service, baseUrl);
|
|
171
363
|
const cached = this.invokerClientByKey.get(key);
|
|
172
364
|
if (cached) return cached;
|
|
173
|
-
const
|
|
174
|
-
const hasMethods = methods != null;
|
|
175
|
-
const methodMap = (() => {
|
|
176
|
-
if (!methods) return void 0;
|
|
177
|
-
if (Array.isArray(methods)) {
|
|
178
|
-
const out = {};
|
|
179
|
-
for (const m of methods) {
|
|
180
|
-
if (!m) continue;
|
|
181
|
-
const localName = String(m.localName ?? "");
|
|
182
|
-
const name = String(m.name ?? "");
|
|
183
|
-
if (localName) out[localName] = m;
|
|
184
|
-
if (name && !(name in out)) out[name] = m;
|
|
185
|
-
}
|
|
186
|
-
return out;
|
|
187
|
-
}
|
|
188
|
-
if (typeof methods === "object") return methods;
|
|
189
|
-
return void 0;
|
|
190
|
-
})();
|
|
365
|
+
const methodMap = this.getServiceMethodMap(service);
|
|
191
366
|
const typeName = String(service?.typeName ?? "");
|
|
192
367
|
const client = new Proxy(
|
|
193
368
|
{},
|
|
@@ -195,7 +370,7 @@ var GrpcClient = class {
|
|
|
195
370
|
get: (_target, prop) => {
|
|
196
371
|
if (prop === "then") return void 0;
|
|
197
372
|
if (typeof prop !== "string") return void 0;
|
|
198
|
-
if (
|
|
373
|
+
if (methodMap && !(prop in methodMap)) {
|
|
199
374
|
return async () => {
|
|
200
375
|
throw new Error(`gRPC method not found: ${typeName}.${prop}`);
|
|
201
376
|
};
|
|
@@ -214,6 +389,12 @@ var GrpcClient = class {
|
|
|
214
389
|
const baseUrl = this.pickBaseUrl(typeName);
|
|
215
390
|
try {
|
|
216
391
|
if (this.invoker) {
|
|
392
|
+
this.logger?.debug?.("[Grpc:Invoker]", {
|
|
393
|
+
mode: this.invokerMode,
|
|
394
|
+
service: typeName,
|
|
395
|
+
methodName,
|
|
396
|
+
baseUrl
|
|
397
|
+
});
|
|
217
398
|
const method2 = this.getServiceMethodDesc(service, methodName);
|
|
218
399
|
const headers = await this.attachInvokerHeaders(
|
|
219
400
|
this.normalizeHeaders(options?.headers),
|