keymaster-api-protocol 0.0.0-stage → 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 +661 -0
- package/dist/envelope.d.ts +75 -0
- package/dist/envelope.js +55 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +105 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/methods.gen.d.ts +56 -0
- package/dist/methods.gen.js +225 -0
- package/dist/types.gen.d.ts +446 -0
- package/dist/types.gen.js +3 -0
- package/dist/ws.d.ts +100 -0
- package/dist/ws.js +635 -0
- package/package.json +28 -4
- package/README.md +0 -3
package/dist/ws.js
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
import { Product, APIVersion, WSPath, MethodTimeout, KnownTopics } from "./methods.gen.js";
|
|
2
|
+
import { ProtocolError, TransportError, ParseError, VersionError } from "./errors.js";
|
|
3
|
+
import { defaultLimits, decodeAttachment, encodeAttachment } from "./envelope.js";
|
|
4
|
+
/** 完整二进制帧允许的协议头开销;与服务端 SetReadLimit 的附加额度一致。 */
|
|
5
|
+
const BinaryFrameOverheadMaxBytes = 64 * 1024;
|
|
6
|
+
function toWSURL(base) {
|
|
7
|
+
const b = base.replace(/\/+$/, "");
|
|
8
|
+
if (b.startsWith("ws://") || b.startsWith("wss://")) {
|
|
9
|
+
return b.endsWith(WSPath) ? b : b + WSPath;
|
|
10
|
+
}
|
|
11
|
+
if (b.startsWith("http://"))
|
|
12
|
+
return "ws://" + b.slice("http://".length) + WSPath;
|
|
13
|
+
if (b.startsWith("https://"))
|
|
14
|
+
return "wss://" + b.slice("https://".length) + WSPath;
|
|
15
|
+
if (b.includes("://"))
|
|
16
|
+
return b + WSPath;
|
|
17
|
+
return "ws://" + b + WSPath;
|
|
18
|
+
}
|
|
19
|
+
function timeoutFor(cat) {
|
|
20
|
+
if (cat === "probe")
|
|
21
|
+
return 3000;
|
|
22
|
+
if (cat === "short")
|
|
23
|
+
return 10000;
|
|
24
|
+
if (cat === "long")
|
|
25
|
+
return 30000;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
let reqSeq = 0;
|
|
29
|
+
function newRequestID() {
|
|
30
|
+
reqSeq += 1;
|
|
31
|
+
return `r${reqSeq}`;
|
|
32
|
+
}
|
|
33
|
+
/** 单 WS 连接:串行写入、并发请求关联、超时/取消/关闭清理。 */
|
|
34
|
+
export class KmWSClient {
|
|
35
|
+
ws = null;
|
|
36
|
+
pending = new Map();
|
|
37
|
+
inflight = 0;
|
|
38
|
+
closed = false;
|
|
39
|
+
instanceId = "";
|
|
40
|
+
connectionId = "";
|
|
41
|
+
limits = defaultLimits();
|
|
42
|
+
// lastSeq 按主题记录;server 保证同一主题的 EventMsg.Seq 连续。
|
|
43
|
+
subs = new Map();
|
|
44
|
+
writeQueue = Promise.resolve();
|
|
45
|
+
connStatus = 'connecting';
|
|
46
|
+
statusListeners = new Set();
|
|
47
|
+
constructor() { }
|
|
48
|
+
/** 订阅连接状态变化;立即以当前状态回调一次,返回取消订阅函数。 */
|
|
49
|
+
onConnectionChange(fn) {
|
|
50
|
+
this.statusListeners.add(fn);
|
|
51
|
+
try {
|
|
52
|
+
fn(this.connStatus);
|
|
53
|
+
}
|
|
54
|
+
catch { /* ignore */ }
|
|
55
|
+
return () => { this.statusListeners.delete(fn); };
|
|
56
|
+
}
|
|
57
|
+
getStatus() {
|
|
58
|
+
return this.connStatus;
|
|
59
|
+
}
|
|
60
|
+
setStatus(s) {
|
|
61
|
+
if (this.connStatus === s)
|
|
62
|
+
return;
|
|
63
|
+
this.connStatus = s;
|
|
64
|
+
for (const fn of this.statusListeners) {
|
|
65
|
+
try {
|
|
66
|
+
fn(s);
|
|
67
|
+
}
|
|
68
|
+
catch { /* ignore */ }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
static async connect(baseURL, client) {
|
|
72
|
+
const c = new KmWSClient();
|
|
73
|
+
const url = toWSURL(baseURL);
|
|
74
|
+
const ws = new WebSocket(url);
|
|
75
|
+
ws.binaryType = 'arraybuffer';
|
|
76
|
+
c.ws = ws;
|
|
77
|
+
await new Promise((resolve, reject) => {
|
|
78
|
+
let settled = false;
|
|
79
|
+
const cleanup = () => {
|
|
80
|
+
if (timer)
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
ws.removeEventListener("open", onOpen);
|
|
83
|
+
ws.removeEventListener("message", onMsg);
|
|
84
|
+
ws.removeEventListener("error", onError);
|
|
85
|
+
ws.removeEventListener("close", onClose);
|
|
86
|
+
};
|
|
87
|
+
const fail = (err) => {
|
|
88
|
+
if (settled)
|
|
89
|
+
return;
|
|
90
|
+
settled = true;
|
|
91
|
+
cleanup();
|
|
92
|
+
try {
|
|
93
|
+
ws.close();
|
|
94
|
+
}
|
|
95
|
+
catch { /* ignore */ }
|
|
96
|
+
reject(err);
|
|
97
|
+
};
|
|
98
|
+
const onOpen = () => {
|
|
99
|
+
try {
|
|
100
|
+
ws.send(JSON.stringify({ type: "hello", product: Product, apiVersion: APIVersion, client }));
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
fail(new TransportError("hello", e));
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const onMsg = (ev) => {
|
|
107
|
+
let msg;
|
|
108
|
+
try {
|
|
109
|
+
msg = JSON.parse(String(ev.data));
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
fail(new ParseError("welcome", e));
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (msg.type === "welcome") {
|
|
116
|
+
if (msg.product !== Product || msg.apiVersion !== APIVersion) {
|
|
117
|
+
fail(new VersionError("hello", "apiVersion", String(msg.apiVersion), APIVersion));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (settled)
|
|
121
|
+
return;
|
|
122
|
+
settled = true;
|
|
123
|
+
cleanup();
|
|
124
|
+
c.instanceId = msg.instanceId;
|
|
125
|
+
c.connectionId = msg.connectionId;
|
|
126
|
+
if (msg.limits?.jsonControlMaxBytes)
|
|
127
|
+
c.limits = msg.limits;
|
|
128
|
+
c.setStatus('connected');
|
|
129
|
+
resolve();
|
|
130
|
+
}
|
|
131
|
+
else if (msg.type === "response" && msg.error) {
|
|
132
|
+
if (msg.error.code === "VERSION_MISMATCH")
|
|
133
|
+
fail(new VersionError("hello", "apiVersion", "", APIVersion));
|
|
134
|
+
else
|
|
135
|
+
fail(new ProtocolError("hello", msg.error.code, msg.error.message));
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const onError = () => fail(new TransportError("dial " + url, "websocket error"));
|
|
139
|
+
const onClose = () => fail(new TransportError("dial " + url, "连接在握手完成前关闭"));
|
|
140
|
+
// 期限覆盖整个握手(open + welcome),不能在 open 时提前清除。
|
|
141
|
+
const timer = setTimeout(() => fail(new TransportError("dial " + url, "等待 welcome 超时")), 10000);
|
|
142
|
+
ws.addEventListener("open", onOpen);
|
|
143
|
+
ws.addEventListener("message", onMsg);
|
|
144
|
+
ws.addEventListener("error", onError);
|
|
145
|
+
ws.addEventListener("close", onClose);
|
|
146
|
+
});
|
|
147
|
+
if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
|
|
148
|
+
throw new TransportError("dial " + url, "连接在握手完成前关闭");
|
|
149
|
+
}
|
|
150
|
+
ws.addEventListener("message", (ev) => c.onMessage(ev));
|
|
151
|
+
ws.addEventListener("close", () => c.failAll(new TransportError("read", "连接已关闭")));
|
|
152
|
+
return c;
|
|
153
|
+
}
|
|
154
|
+
getInstanceId() {
|
|
155
|
+
return this.instanceId;
|
|
156
|
+
}
|
|
157
|
+
getConnectionId() {
|
|
158
|
+
return this.connectionId;
|
|
159
|
+
}
|
|
160
|
+
sendJSON(v) {
|
|
161
|
+
const raw = JSON.stringify(v);
|
|
162
|
+
if (raw.length > this.limits.jsonControlMaxBytes) {
|
|
163
|
+
throw new ProtocolError("send", "TOO_LARGE", "控制消息过大");
|
|
164
|
+
}
|
|
165
|
+
const ws = this.ws;
|
|
166
|
+
if (!ws || this.closed)
|
|
167
|
+
throw new TransportError("send", "连接已关闭");
|
|
168
|
+
const next = this.writeQueue.then(() => new Promise((resolve, reject) => {
|
|
169
|
+
try {
|
|
170
|
+
ws.send(raw);
|
|
171
|
+
resolve();
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
reject(new TransportError("send", e));
|
|
175
|
+
}
|
|
176
|
+
}));
|
|
177
|
+
// 单次写失败不能毒化后续写队列;当前请求由自身超时收尾,后续请求仍可发送。
|
|
178
|
+
this.writeQueue = next.catch(() => { });
|
|
179
|
+
}
|
|
180
|
+
sendBinary(frame, bodyBytes) {
|
|
181
|
+
// 附件正文与完整帧分别限制:帧还包含 4 字节头长和 JSON 头,不能把它
|
|
182
|
+
// 计入正文上限,否则恰好 16 MiB 的合法附件会被误拒。
|
|
183
|
+
if (bodyBytes > this.limits.binarySingleMaxBytes) {
|
|
184
|
+
throw new ProtocolError("send", "TOO_LARGE", "附件过大");
|
|
185
|
+
}
|
|
186
|
+
if (frame.length > this.limits.binarySingleMaxBytes + BinaryFrameOverheadMaxBytes) {
|
|
187
|
+
throw new ProtocolError("send", "TOO_LARGE", "附件帧过大");
|
|
188
|
+
}
|
|
189
|
+
const ws = this.ws;
|
|
190
|
+
if (!ws || this.closed)
|
|
191
|
+
throw new TransportError("send", "连接已关闭");
|
|
192
|
+
const buf = frame.buffer.slice(frame.byteOffset, frame.byteOffset + frame.byteLength);
|
|
193
|
+
const next = this.writeQueue.then(() => new Promise((resolve, reject) => {
|
|
194
|
+
try {
|
|
195
|
+
ws.send(buf);
|
|
196
|
+
resolve();
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
reject(new TransportError("send", e));
|
|
200
|
+
}
|
|
201
|
+
}));
|
|
202
|
+
this.writeQueue = next.catch(() => { });
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* 带二进制附件的调用:先发送 request,再逐个发送 AttachBegin + 二进制帧。
|
|
206
|
+
* 服务端先回 AttachBegin/二进制,最后回 Response;收集齐后以
|
|
207
|
+
* `{ result, binaries }` 形式返回。附件较大时超时放宽到 45 秒。
|
|
208
|
+
*/
|
|
209
|
+
async callWithBinary(ctx, method, params, attachments = {}) {
|
|
210
|
+
const cat = MethodTimeout[method];
|
|
211
|
+
if (cat === undefined)
|
|
212
|
+
throw new ProtocolError(method, "BAD_REQUEST", "未知方法");
|
|
213
|
+
if (this.closed)
|
|
214
|
+
throw new TransportError(method, "连接已关闭");
|
|
215
|
+
if (this.inflight >= this.limits.connInflightRequests) {
|
|
216
|
+
throw new ProtocolError(method, "TOO_LARGE", "在途请求过多");
|
|
217
|
+
}
|
|
218
|
+
for (const [name, data] of Object.entries(attachments)) {
|
|
219
|
+
if (data.length > this.limits.binarySingleMaxBytes) {
|
|
220
|
+
throw new ProtocolError(method, "TOO_LARGE", `附件 ${name} 过大`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const id = newRequestID();
|
|
224
|
+
// 附件上传需要声明期限(30s)+ 服务端执行;固定 45 秒上限。
|
|
225
|
+
const timeoutMs = 45000;
|
|
226
|
+
return new Promise((resolve, reject) => {
|
|
227
|
+
let timer;
|
|
228
|
+
const expected = new Map();
|
|
229
|
+
const binaries = new Map();
|
|
230
|
+
const cleanup = () => {
|
|
231
|
+
// onMessage 已删除 pending 并扣减 inflight;只有仍存在时才清理,
|
|
232
|
+
// 避免带附件调用在响应路径被重复扣减。
|
|
233
|
+
if (this.pending.delete(id))
|
|
234
|
+
this.inflight -= 1;
|
|
235
|
+
if (timer)
|
|
236
|
+
clearTimeout(timer);
|
|
237
|
+
ctx?.signal?.removeEventListener("abort", onAbort);
|
|
238
|
+
};
|
|
239
|
+
const onAbort = () => {
|
|
240
|
+
cleanup();
|
|
241
|
+
try {
|
|
242
|
+
this.sendJSON({ type: "cancel", id: newRequestID(), targetId: id });
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
/* ignore */
|
|
246
|
+
}
|
|
247
|
+
reject(new TransportError(method, ctx?.signal?.reason ?? "调用者取消"));
|
|
248
|
+
};
|
|
249
|
+
if (ctx?.signal?.aborted) {
|
|
250
|
+
onAbort();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
ctx?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
254
|
+
timer = setTimeout(() => {
|
|
255
|
+
cleanup();
|
|
256
|
+
try {
|
|
257
|
+
this.sendJSON({ type: "cancel", id: newRequestID(), targetId: id });
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
/* ignore */
|
|
261
|
+
}
|
|
262
|
+
reject(new TransportError(method, "调用超时"));
|
|
263
|
+
}, timeoutMs);
|
|
264
|
+
const entry = {
|
|
265
|
+
method,
|
|
266
|
+
resolve: (v) => {
|
|
267
|
+
cleanup();
|
|
268
|
+
const out = {};
|
|
269
|
+
for (const [k, val] of binaries)
|
|
270
|
+
out[k] = val;
|
|
271
|
+
resolve({ result: v, binaries: out });
|
|
272
|
+
},
|
|
273
|
+
reject: (e) => {
|
|
274
|
+
cleanup();
|
|
275
|
+
reject(e);
|
|
276
|
+
},
|
|
277
|
+
timer,
|
|
278
|
+
binaries,
|
|
279
|
+
expected,
|
|
280
|
+
};
|
|
281
|
+
this.pending.set(id, entry);
|
|
282
|
+
this.inflight += 1;
|
|
283
|
+
try {
|
|
284
|
+
const decls = Object.entries(attachments).map(([name, data]) => ({ id: name, bytes: data.length }));
|
|
285
|
+
this.sendJSON({ type: "request", id, method, params, attachments: decls });
|
|
286
|
+
for (const [name, data] of Object.entries(attachments)) {
|
|
287
|
+
this.sendJSON({ type: "binary-begin", requestId: id, attachmentId: name, declaredBytes: data.length });
|
|
288
|
+
this.sendBinary(encodeAttachment(id, name, data), data.length);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
catch (e) {
|
|
292
|
+
cleanup();
|
|
293
|
+
reject(e);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
async call(ctx, method, params) {
|
|
298
|
+
const cat = MethodTimeout[method];
|
|
299
|
+
if (cat === undefined)
|
|
300
|
+
throw new ProtocolError(method, "BAD_REQUEST", "未知方法");
|
|
301
|
+
if (this.closed)
|
|
302
|
+
throw new TransportError(method, "连接已关闭");
|
|
303
|
+
if (this.inflight >= this.limits.connInflightRequests) {
|
|
304
|
+
throw new ProtocolError(method, "TOO_LARGE", "在途请求过多");
|
|
305
|
+
}
|
|
306
|
+
const id = newRequestID();
|
|
307
|
+
const timeoutMs = timeoutFor(cat);
|
|
308
|
+
return new Promise((resolve, reject) => {
|
|
309
|
+
let timer;
|
|
310
|
+
const cleanup = () => {
|
|
311
|
+
// onMessage 已删除 pending 并扣减 inflight;只有仍存在时才清理,
|
|
312
|
+
// 避免带附件调用在响应路径被重复扣减。
|
|
313
|
+
if (this.pending.delete(id))
|
|
314
|
+
this.inflight -= 1;
|
|
315
|
+
if (timer)
|
|
316
|
+
clearTimeout(timer);
|
|
317
|
+
ctx?.signal?.removeEventListener("abort", onAbort);
|
|
318
|
+
};
|
|
319
|
+
const onAbort = () => {
|
|
320
|
+
cleanup();
|
|
321
|
+
try {
|
|
322
|
+
this.sendJSON({ type: "cancel", id: newRequestID(), targetId: id });
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
/* ignore */
|
|
326
|
+
}
|
|
327
|
+
reject(new TransportError(method, ctx?.signal?.reason ?? "调用者取消"));
|
|
328
|
+
};
|
|
329
|
+
if (ctx?.signal?.aborted) {
|
|
330
|
+
onAbort();
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
ctx?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
334
|
+
if (timeoutMs !== null) {
|
|
335
|
+
timer = setTimeout(() => {
|
|
336
|
+
cleanup();
|
|
337
|
+
try {
|
|
338
|
+
this.sendJSON({ type: "cancel", id: newRequestID(), targetId: id });
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
/* ignore */
|
|
342
|
+
}
|
|
343
|
+
reject(new TransportError(method, "调用超时"));
|
|
344
|
+
}, timeoutMs);
|
|
345
|
+
}
|
|
346
|
+
this.pending.set(id, {
|
|
347
|
+
method,
|
|
348
|
+
resolve: (v) => {
|
|
349
|
+
cleanup();
|
|
350
|
+
resolve(v);
|
|
351
|
+
},
|
|
352
|
+
reject: (e) => {
|
|
353
|
+
cleanup();
|
|
354
|
+
reject(e);
|
|
355
|
+
},
|
|
356
|
+
timer,
|
|
357
|
+
});
|
|
358
|
+
this.inflight += 1;
|
|
359
|
+
try {
|
|
360
|
+
this.sendJSON({ type: "request", id, method, params });
|
|
361
|
+
}
|
|
362
|
+
catch (e) {
|
|
363
|
+
cleanup();
|
|
364
|
+
reject(e);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
subscribeEvents(topics, handlers, opts = {}) {
|
|
369
|
+
for (const t of topics) {
|
|
370
|
+
if (!KnownTopics.includes(t)) {
|
|
371
|
+
throw new ProtocolError("events.subscribe", "BAD_REQUEST", `未知主题: ${t}`);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const id = newRequestID();
|
|
375
|
+
const sub = { topics, onSnapshot: handlers.onSnapshot, onEvent: handlers.onEvent, onResync: handlers.onResync, lastSeq: new Map() };
|
|
376
|
+
this.subs.set(id, sub);
|
|
377
|
+
this.sendJSON({ type: "subscribe", id, topics });
|
|
378
|
+
const cancel = () => {
|
|
379
|
+
try {
|
|
380
|
+
this.sendJSON({ type: "unsubscribe", id: newRequestID(), subscriptionId: id, topics });
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
/* ignore */
|
|
384
|
+
}
|
|
385
|
+
this.subs.delete(id);
|
|
386
|
+
};
|
|
387
|
+
opts.signal?.addEventListener("abort", cancel, { once: true });
|
|
388
|
+
return cancel;
|
|
389
|
+
}
|
|
390
|
+
close() {
|
|
391
|
+
if (this.closed)
|
|
392
|
+
return;
|
|
393
|
+
this.closed = true;
|
|
394
|
+
try {
|
|
395
|
+
this.ws?.close(1000, "bye");
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
/* ignore */
|
|
399
|
+
}
|
|
400
|
+
this.failAll(new TransportError("close", "连接已关闭"));
|
|
401
|
+
}
|
|
402
|
+
// ---- 类型化业务方法(Web/CLI 共用同一方法表) ----
|
|
403
|
+
async status() {
|
|
404
|
+
return (await this.call(undefined, "status.get"));
|
|
405
|
+
}
|
|
406
|
+
async info() {
|
|
407
|
+
return (await this.call(undefined, "info.get"));
|
|
408
|
+
}
|
|
409
|
+
async unlock(password) {
|
|
410
|
+
return (await this.call(undefined, "wallet.unlock", { password }));
|
|
411
|
+
}
|
|
412
|
+
async listRoots() {
|
|
413
|
+
return (await this.call(undefined, "roots.list"));
|
|
414
|
+
}
|
|
415
|
+
async addRoot(path, revision) {
|
|
416
|
+
return (await this.call(undefined, "roots.add", { path, revision }));
|
|
417
|
+
}
|
|
418
|
+
async removeRoot(id, revision) {
|
|
419
|
+
return (await this.call(undefined, "roots.remove", { id, revision }));
|
|
420
|
+
}
|
|
421
|
+
async setDefaultRoot(id, revision) {
|
|
422
|
+
return (await this.call(undefined, "roots.setDefault", { id, revision }));
|
|
423
|
+
}
|
|
424
|
+
async listFiles() {
|
|
425
|
+
return (await this.call(undefined, "files.list"));
|
|
426
|
+
}
|
|
427
|
+
async browse(path) {
|
|
428
|
+
return (await this.call(undefined, "files.browse", { path }));
|
|
429
|
+
}
|
|
430
|
+
async getSettings() {
|
|
431
|
+
return (await this.call(undefined, "settings.get"));
|
|
432
|
+
}
|
|
433
|
+
async updateSettings(params) {
|
|
434
|
+
return (await this.call(undefined, "settings.update", params));
|
|
435
|
+
}
|
|
436
|
+
async resetSettings(revision) {
|
|
437
|
+
return (await this.call(undefined, "settings.reset", { revision }));
|
|
438
|
+
}
|
|
439
|
+
async refreshCatalog(rootId, force) {
|
|
440
|
+
return this.call(undefined, "catalog.refresh", { rootId, force });
|
|
441
|
+
}
|
|
442
|
+
async collectorStatus() {
|
|
443
|
+
return (await this.call(undefined, "collector.status"));
|
|
444
|
+
}
|
|
445
|
+
async collectorHistory() {
|
|
446
|
+
return (await this.call(undefined, "collector.history"));
|
|
447
|
+
}
|
|
448
|
+
async collectorDescribe(seedHash, description) {
|
|
449
|
+
return (await this.call(undefined, "collector.describe", { seedHash, description }));
|
|
450
|
+
}
|
|
451
|
+
async collectorFlush() {
|
|
452
|
+
return (await this.call(undefined, "collector.flush"));
|
|
453
|
+
}
|
|
454
|
+
async collectorRetry() {
|
|
455
|
+
return (await this.call(undefined, "collector.retry"));
|
|
456
|
+
}
|
|
457
|
+
async listTasks() {
|
|
458
|
+
return (await this.call(undefined, "tasks.list"));
|
|
459
|
+
}
|
|
460
|
+
async createTask(seedHashHex) {
|
|
461
|
+
return (await this.call(undefined, "tasks.create", { seedHashHex }));
|
|
462
|
+
}
|
|
463
|
+
async cancelTask(seedHashHex) {
|
|
464
|
+
return (await this.call(undefined, "tasks.cancel", { seedHashHex }));
|
|
465
|
+
}
|
|
466
|
+
async approvalsList() {
|
|
467
|
+
return this.call(undefined, "connect.approvals.list");
|
|
468
|
+
}
|
|
469
|
+
async approvalsDecide(approvalId, decision, grantAuto) {
|
|
470
|
+
return this.call(undefined, "connect.approvals.decide", grantAuto === undefined ? { approvalId, decision } : { approvalId, decision, grantAuto });
|
|
471
|
+
}
|
|
472
|
+
async bindingsList() {
|
|
473
|
+
return this.call(undefined, "connect.bindings.list");
|
|
474
|
+
}
|
|
475
|
+
async authList() {
|
|
476
|
+
return this.call(undefined, "connect.auth.list");
|
|
477
|
+
}
|
|
478
|
+
async authRevoke(origin, appPublicKey, appId) {
|
|
479
|
+
return this.call(undefined, "connect.auth.revoke", { origin, appPublicKey, appId });
|
|
480
|
+
}
|
|
481
|
+
async permissionsList(applicationKey) {
|
|
482
|
+
return this.call(undefined, "connect.permissions.list", applicationKey ? { applicationKey } : {});
|
|
483
|
+
}
|
|
484
|
+
async permissionsRevoke(applicationKey, method) {
|
|
485
|
+
return this.call(undefined, "connect.permissions.revoke", { applicationKey, method });
|
|
486
|
+
}
|
|
487
|
+
async historyList(applicationKey, limit) {
|
|
488
|
+
const params = {};
|
|
489
|
+
if (applicationKey)
|
|
490
|
+
params["applicationKey"] = applicationKey;
|
|
491
|
+
if (limit !== undefined)
|
|
492
|
+
params["limit"] = limit;
|
|
493
|
+
return this.call(undefined, "connect.history.list", params);
|
|
494
|
+
}
|
|
495
|
+
async appsList() {
|
|
496
|
+
return this.call(undefined, "connect.apps.list");
|
|
497
|
+
}
|
|
498
|
+
async connectionPause(authorizationId) {
|
|
499
|
+
return this.call(undefined, "connect.connection.pause", { authorizationId });
|
|
500
|
+
}
|
|
501
|
+
async connectExec(params) {
|
|
502
|
+
return this.call(undefined, "connect.request.exec", params);
|
|
503
|
+
}
|
|
504
|
+
async walletCreate(password, network) {
|
|
505
|
+
return this.call(undefined, "wallet.create", { password, network });
|
|
506
|
+
}
|
|
507
|
+
async walletImport(password, keyMaterial) {
|
|
508
|
+
return this.call(undefined, "wallet.import", { password, keyMaterial });
|
|
509
|
+
}
|
|
510
|
+
onMessage(ev) {
|
|
511
|
+
const data = ev.data;
|
|
512
|
+
if (typeof data !== "string") {
|
|
513
|
+
// 二进制帧:按 {4B 头长 + JSON 头 + 原始字节} 解码并路由到对应请求。
|
|
514
|
+
const bytes = data instanceof ArrayBuffer
|
|
515
|
+
? new Uint8Array(data)
|
|
516
|
+
: data instanceof Uint8Array
|
|
517
|
+
? data
|
|
518
|
+
: null;
|
|
519
|
+
if (!bytes)
|
|
520
|
+
return;
|
|
521
|
+
let hdr;
|
|
522
|
+
let body;
|
|
523
|
+
try {
|
|
524
|
+
const decoded = decodeAttachment(bytes, -1);
|
|
525
|
+
hdr = { requestId: decoded.requestId, attachmentId: decoded.attachmentId };
|
|
526
|
+
body = decoded.data;
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
const p = this.pending.get(hdr.requestId);
|
|
532
|
+
if (!p || !p.binaries)
|
|
533
|
+
return;
|
|
534
|
+
const want = p.expected?.get(hdr.attachmentId);
|
|
535
|
+
if (want !== undefined && body.length !== want)
|
|
536
|
+
return;
|
|
537
|
+
p.binaries.set(hdr.attachmentId, body);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
let msg;
|
|
541
|
+
try {
|
|
542
|
+
msg = JSON.parse(data);
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
const t = msg["type"];
|
|
548
|
+
if (t === "binary-begin") {
|
|
549
|
+
// 服务端声明即将发送的附件;记录期望长度用于校验。
|
|
550
|
+
const b = msg;
|
|
551
|
+
if (typeof b.requestId !== "string" || typeof b.attachmentId !== "string" || typeof b.declaredBytes !== "number")
|
|
552
|
+
return;
|
|
553
|
+
const p = this.pending.get(b.requestId);
|
|
554
|
+
if (!p)
|
|
555
|
+
return;
|
|
556
|
+
if (!p.expected)
|
|
557
|
+
p.expected = new Map();
|
|
558
|
+
if (!p.binaries)
|
|
559
|
+
p.binaries = new Map();
|
|
560
|
+
if (!p.expected.has(b.attachmentId)) {
|
|
561
|
+
p.expected.set(b.attachmentId, b.declaredBytes);
|
|
562
|
+
}
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (t === "response") {
|
|
566
|
+
const id = msg["id"];
|
|
567
|
+
const p = this.pending.get(id);
|
|
568
|
+
if (!p)
|
|
569
|
+
return;
|
|
570
|
+
this.pending.delete(id);
|
|
571
|
+
this.inflight -= 1;
|
|
572
|
+
if (p.timer)
|
|
573
|
+
clearTimeout(p.timer);
|
|
574
|
+
const err = msg["error"];
|
|
575
|
+
if (err)
|
|
576
|
+
p.reject(new ProtocolError(p.method, err.code, err.message, id, err.retryable));
|
|
577
|
+
else
|
|
578
|
+
p.resolve(msg["result"] ?? null);
|
|
579
|
+
}
|
|
580
|
+
else if (t === "snapshot") {
|
|
581
|
+
const snap = msg;
|
|
582
|
+
// 快照只投递给签发它的订阅;服务端未带 id 的旧帧才按主题集合回退匹配。
|
|
583
|
+
const direct = snap.id ? this.subs.get(snap.id) : undefined;
|
|
584
|
+
if (direct) {
|
|
585
|
+
direct.onSnapshot?.(snap);
|
|
586
|
+
}
|
|
587
|
+
else if (!snap.id) {
|
|
588
|
+
for (const s of this.subs.values()) {
|
|
589
|
+
if (s.topics.length === snap.topics.length && s.topics.every((topic) => snap.topics.includes(topic))) {
|
|
590
|
+
s.onSnapshot?.(snap);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
else if (t === "event") {
|
|
596
|
+
const e = msg;
|
|
597
|
+
if (e.instanceId && e.instanceId !== this.instanceId)
|
|
598
|
+
return;
|
|
599
|
+
for (const s of this.subs.values()) {
|
|
600
|
+
// 空主题集合表示全部主题;server 的 EventMsg.Seq 按主题连续。
|
|
601
|
+
if (s.topics.length > 0 && !s.topics.includes(e.topic))
|
|
602
|
+
continue;
|
|
603
|
+
const last = s.lastSeq.get(e.topic) ?? 0;
|
|
604
|
+
if (e.seq <= last)
|
|
605
|
+
continue;
|
|
606
|
+
if (last !== 0 && e.seq !== last + 1)
|
|
607
|
+
s.onResync?.();
|
|
608
|
+
// 缺口时仍推进并投递当前事件;状态重同步会补齐缺失内容,不能让
|
|
609
|
+
// 客户端因一次缺口永久卡在同一序号。
|
|
610
|
+
s.lastSeq.set(e.topic, e.seq);
|
|
611
|
+
s.onEvent?.(e);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
else if (t === "resync") {
|
|
615
|
+
const id = msg["id"];
|
|
616
|
+
if (id && this.subs.has(id)) {
|
|
617
|
+
this.subs.get(id).onResync?.();
|
|
618
|
+
}
|
|
619
|
+
else {
|
|
620
|
+
for (const s of this.subs.values())
|
|
621
|
+
s.onResync?.();
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
failAll(err) {
|
|
626
|
+
for (const [, p] of this.pending) {
|
|
627
|
+
if (p.timer)
|
|
628
|
+
clearTimeout(p.timer);
|
|
629
|
+
p.reject(err);
|
|
630
|
+
}
|
|
631
|
+
this.pending.clear();
|
|
632
|
+
this.inflight = 0;
|
|
633
|
+
this.setStatus('disconnected');
|
|
634
|
+
}
|
|
635
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keymaster-api-protocol",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Keymaster 后台业务 API v1 契约 SDK(DTO 与 WebSocket/进程内客户端,Go/TS 同契约)",
|
|
5
|
+
"license": "AGPL-3.0-only",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"build": "rm -rf dist && tsc",
|
|
21
|
+
"test": "vitest run --passWithNoTests",
|
|
22
|
+
"prepublishOnly": "npm run typecheck && npm run build && npm test"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^24.13.3",
|
|
27
|
+
"typescript": "5.9.3",
|
|
28
|
+
"vitest": "3.2.4"
|
|
29
|
+
}
|
|
30
|
+
}
|
package/README.md
DELETED