@anycon/sdk 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 +176 -0
- package/README.md +240 -0
- package/README.zh-CN.md +188 -0
- package/dist/async-queue.d.ts +20 -0
- package/dist/async-queue.d.ts.map +1 -0
- package/dist/async-queue.js +95 -0
- package/dist/async-queue.js.map +1 -0
- package/dist/attachments.d.ts +53 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +228 -0
- package/dist/attachments.js.map +1 -0
- package/dist/client.d.ts +90 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +280 -0
- package/dist/client.js.map +1 -0
- package/dist/connect.d.ts +16 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +24 -0
- package/dist/connect.js.map +1 -0
- package/dist/default-storage.d.ts +4 -0
- package/dist/default-storage.d.ts.map +1 -0
- package/dist/default-storage.js +15 -0
- package/dist/default-storage.js.map +1 -0
- package/dist/emitter.d.ts +10 -0
- package/dist/emitter.d.ts.map +1 -0
- package/dist/emitter.js +38 -0
- package/dist/emitter.js.map +1 -0
- package/dist/errors.d.ts +112 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +155 -0
- package/dist/errors.js.map +1 -0
- package/dist/hub.d.ts +85 -0
- package/dist/hub.d.ts.map +1 -0
- package/dist/hub.js +362 -0
- package/dist/hub.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/link.d.ts +87 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +628 -0
- package/dist/link.js.map +1 -0
- package/dist/node.d.ts +213 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +474 -0
- package/dist/node.js.map +1 -0
- package/dist/pair.d.ts +75 -0
- package/dist/pair.d.ts.map +1 -0
- package/dist/pair.js +390 -0
- package/dist/pair.js.map +1 -0
- package/dist/permissions.d.ts +65 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +74 -0
- package/dist/permissions.js.map +1 -0
- package/dist/runtime.d.ts +5 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +15 -0
- package/dist/runtime.js.map +1 -0
- package/dist/session.d.ts +208 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +504 -0
- package/dist/session.js.map +1 -0
- package/dist/storage-file.d.ts +21 -0
- package/dist/storage-file.d.ts.map +1 -0
- package/dist/storage-file.js +62 -0
- package/dist/storage-file.js.map +1 -0
- package/dist/storage-idb.d.ts +19 -0
- package/dist/storage-idb.d.ts.map +1 -0
- package/dist/storage-idb.js +64 -0
- package/dist/storage-idb.js.map +1 -0
- package/dist/storage.d.ts +78 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +163 -0
- package/dist/storage.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/dist/ws.d.ts +41 -0
- package/dist/ws.d.ts.map +1 -0
- package/dist/ws.js +66 -0
- package/dist/ws.js.map +1 -0
- package/package.json +65 -0
- package/src/async-queue.ts +100 -0
- package/src/attachments.ts +301 -0
- package/src/client.ts +351 -0
- package/src/connect.ts +29 -0
- package/src/default-storage.ts +14 -0
- package/src/emitter.ts +40 -0
- package/src/errors.ts +218 -0
- package/src/hub.ts +456 -0
- package/src/index.ts +143 -0
- package/src/link.ts +699 -0
- package/src/node.ts +652 -0
- package/src/pair.ts +527 -0
- package/src/permissions.ts +134 -0
- package/src/runtime.ts +14 -0
- package/src/session.ts +697 -0
- package/src/storage-file.ts +78 -0
- package/src/storage-idb.ts +74 -0
- package/src/storage.ts +231 -0
- package/src/version.ts +2 -0
- package/src/ws.ts +94 -0
package/src/hub.ts
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 与 hub 的一条 WebSocket:认证(第一帧 `Control::Auth`)、信封收发、断线重连。
|
|
3
|
+
* 只管外层;Noise 和 JSON-RPC 在 link.ts。
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
CLOSE_CODE,
|
|
7
|
+
PROTOCOL_VERSION,
|
|
8
|
+
UnknownControlError,
|
|
9
|
+
controlBody,
|
|
10
|
+
controlEnvelope,
|
|
11
|
+
decodeEnvelope,
|
|
12
|
+
encodeEnvelope,
|
|
13
|
+
makeEnvelope,
|
|
14
|
+
type AuthFailReason,
|
|
15
|
+
type Control,
|
|
16
|
+
type ClientInfo,
|
|
17
|
+
type Envelope,
|
|
18
|
+
} from '@anycon/protocol'
|
|
19
|
+
|
|
20
|
+
import { Emitter } from './emitter.js'
|
|
21
|
+
import { ConnectionError, NodeRejected, PairingRequired, ProtocolMismatch } from './errors.js'
|
|
22
|
+
import {
|
|
23
|
+
WS_OPEN,
|
|
24
|
+
defaultWebSocket,
|
|
25
|
+
toBytes,
|
|
26
|
+
type WebSocketFactory,
|
|
27
|
+
type WebSocketLike,
|
|
28
|
+
} from './ws.js'
|
|
29
|
+
|
|
30
|
+
export type AuthOk = Extract<Control, { type: 'auth_ok' }>
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* `rate_limited { retry_after_ms }` 最多信到多久,毫秒(防对端给出荒谬的值把连接挂死)。
|
|
34
|
+
* docs/protocol.md § 3.1:发送方可以把它封顶在 30 s。
|
|
35
|
+
*/
|
|
36
|
+
export const RATE_WAIT_MAX_MS = 30_000
|
|
37
|
+
|
|
38
|
+
export interface BackoffOptions {
|
|
39
|
+
/** 首次重连等待,毫秒。默认 1000。 */
|
|
40
|
+
initialMs?: number
|
|
41
|
+
/** 上限,毫秒。默认 30000。 */
|
|
42
|
+
maxMs?: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface HubConnectionOptions {
|
|
46
|
+
/** WebSocket 地址(`wss://…/v1/ws`)。 */
|
|
47
|
+
url: string
|
|
48
|
+
/** 设备 token;缺省 = 「只为配对而来」的临时连接。 */
|
|
49
|
+
token?: string
|
|
50
|
+
/** 已知的设备 id(auth 帧的 `from`);临时连接留空。 */
|
|
51
|
+
deviceId?: string
|
|
52
|
+
client: ClientInfo
|
|
53
|
+
webSocket?: WebSocketFactory
|
|
54
|
+
/** WebSocket 升级请求附带的 HTTP 头(仅 Node / Bun),见 `WebSocketInit.headers`。 */
|
|
55
|
+
headers?: Record<string, string>
|
|
56
|
+
/** 掉线后自动重连。默认 false。 */
|
|
57
|
+
reconnect?: boolean | BackoffOptions
|
|
58
|
+
/** 等 `auth_ok` 的时间。默认 10 秒。 */
|
|
59
|
+
authTimeoutMs?: number
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface HubEvents {
|
|
63
|
+
authed: [AuthOk]
|
|
64
|
+
/** 除 auth / auth_ok / auth_fail 之外的控制消息。 */
|
|
65
|
+
control: [Control]
|
|
66
|
+
/** handshake / data / notify 信封。 */
|
|
67
|
+
envelope: [Envelope]
|
|
68
|
+
disconnected: [info: { code: number; reason: string; willReconnect: boolean }]
|
|
69
|
+
/** 不会再重连的终止性错误(被顶掉、被吊销、token 无效……)。 */
|
|
70
|
+
fatal: [Error]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type State = 'idle' | 'connecting' | 'authenticating' | 'ready' | 'backoff' | 'closed'
|
|
74
|
+
|
|
75
|
+
function authFailError(reason: AuthFailReason): Error {
|
|
76
|
+
switch (reason) {
|
|
77
|
+
case 'invalid':
|
|
78
|
+
return new PairingRequired('the hub rejected this device token: pair this device again')
|
|
79
|
+
case 'revoked':
|
|
80
|
+
return new NodeRejected('this device has been revoked by the hub: pair it again')
|
|
81
|
+
case 'version':
|
|
82
|
+
return new ProtocolMismatch(
|
|
83
|
+
PROTOCOL_VERSION,
|
|
84
|
+
undefined,
|
|
85
|
+
'the hub does not accept this protocol version',
|
|
86
|
+
)
|
|
87
|
+
case 'quota':
|
|
88
|
+
return new ConnectionError('the hub refused the connection: quota exceeded')
|
|
89
|
+
case 'protocol':
|
|
90
|
+
return new ConnectionError('the hub refused the connection: protocol error')
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class HubConnection extends Emitter<HubEvents> {
|
|
95
|
+
readonly #opts: HubConnectionOptions
|
|
96
|
+
readonly #factory: WebSocketFactory
|
|
97
|
+
readonly #backoff: Required<BackoffOptions>
|
|
98
|
+
readonly #authTimeoutMs: number
|
|
99
|
+
#state: State = 'idle'
|
|
100
|
+
#ws: WebSocketLike | undefined
|
|
101
|
+
#deviceId: string
|
|
102
|
+
#seq = 0
|
|
103
|
+
#attempt = 0
|
|
104
|
+
#closedByUs = false
|
|
105
|
+
#first: { resolve: (ok: AuthOk) => void; reject: (e: unknown) => void } | undefined
|
|
106
|
+
#authTimer: ReturnType<typeof setTimeout> | undefined
|
|
107
|
+
#retryTimer: ReturnType<typeof setTimeout> | undefined
|
|
108
|
+
#pendingFatal: Error | undefined
|
|
109
|
+
#lastError: unknown
|
|
110
|
+
/**
|
|
111
|
+
* `rate_limited` 要求暂停到什么时候(绝对时间,毫秒)。速率预算是 hub 按**整条连接**记的,不分节点,
|
|
112
|
+
* 所以它记在连接上,同一条连接上的所有 `NodeLink` 共用;新开一条 WebSocket 时清零。
|
|
113
|
+
*/
|
|
114
|
+
#rateUntil = 0
|
|
115
|
+
|
|
116
|
+
constructor(options: HubConnectionOptions) {
|
|
117
|
+
super()
|
|
118
|
+
this.#opts = options
|
|
119
|
+
this.#factory = options.webSocket ?? defaultWebSocket
|
|
120
|
+
const r = typeof options.reconnect === 'object' ? options.reconnect : {}
|
|
121
|
+
this.#backoff = { initialMs: r.initialMs ?? 1000, maxMs: r.maxMs ?? 30_000 }
|
|
122
|
+
this.#authTimeoutMs = options.authTimeoutMs ?? 10_000
|
|
123
|
+
this.#deviceId = options.deviceId ?? ''
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 配对完成后同一条连接就是正式设备:之后 handshake / data 信封的 `from` 要用 `PairDone.device_id`
|
|
128
|
+
* (旧的临时 id 不再有效)。
|
|
129
|
+
*/
|
|
130
|
+
adoptDeviceId(id: string): void {
|
|
131
|
+
this.#deviceId = id
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** hub 分配 / 确认的设备 id(`auth_ok` 之后可用)。 */
|
|
135
|
+
get deviceId(): string {
|
|
136
|
+
return this.#deviceId
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 到目前为止发出的最大 seq(整条 hub 连接上唯一递增,control 帧也占号)。 */
|
|
140
|
+
get lastSeq(): number {
|
|
141
|
+
return this.#seq
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* hub 通过 `rate_limited` 要求这条连接(所有节点、含重发)暂停到什么时候,绝对时间(毫秒);
|
|
146
|
+
* 没有限速或已过期是 0 或一个过去的时刻。封顶 {@link RATE_WAIT_MAX_MS},重连后清零。
|
|
147
|
+
*/
|
|
148
|
+
get rateUntil(): number {
|
|
149
|
+
return this.#rateUntil
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
get ready(): boolean {
|
|
153
|
+
return this.#state === 'ready'
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
get closed(): boolean {
|
|
157
|
+
return this.#state === 'closed'
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 连接并认证。首次失败直接拒绝;成功之后按 `reconnect` 选项自动重连。 */
|
|
161
|
+
start(): Promise<AuthOk> {
|
|
162
|
+
if (this.#state !== 'idle') return Promise.reject(new Error('HubConnection already started'))
|
|
163
|
+
return new Promise<AuthOk>((resolve, reject) => {
|
|
164
|
+
this.#first = { resolve, reject }
|
|
165
|
+
void this.#open()
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
sendControl(ctrl: Control): number {
|
|
170
|
+
const seq = this.#nextSeq()
|
|
171
|
+
// 发给 hub 的 control 帧 from / to 都填空串(hub 不看 from)。
|
|
172
|
+
this.#write(encodeEnvelope(controlEnvelope('', seq, ctrl)))
|
|
173
|
+
return seq
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 发 handshake / data / notify 信封,返回 seq。 */
|
|
177
|
+
sendEnvelope(to: string, kind: 'handshake' | 'data' | 'notify', body: Uint8Array): number {
|
|
178
|
+
return this.sendEncoded(to, kind, body).seq
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 同 `sendEnvelope`,另外返回编码后的整帧(背压重发要原样再发一遍)。 */
|
|
182
|
+
sendEncoded(
|
|
183
|
+
to: string,
|
|
184
|
+
kind: 'handshake' | 'data' | 'notify',
|
|
185
|
+
body: Uint8Array,
|
|
186
|
+
): { seq: number; frame: Uint8Array } {
|
|
187
|
+
const seq = this.#nextSeq()
|
|
188
|
+
const frame = encodeEnvelope(makeEnvelope(this.#deviceId, to, kind, seq, body))
|
|
189
|
+
this.#write(frame)
|
|
190
|
+
return { seq, frame }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 重发一帧已编码的信封(背压重试用)。 */
|
|
194
|
+
sendRaw(bytes: Uint8Array): void {
|
|
195
|
+
this.#write(bytes)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
close(code = 1000, reason = 'client closing'): void {
|
|
199
|
+
this.#closedByUs = true
|
|
200
|
+
this.#state = 'closed'
|
|
201
|
+
this.#rateUntil = 0
|
|
202
|
+
this.#clearTimers()
|
|
203
|
+
const ws = this.#ws
|
|
204
|
+
this.#ws = undefined
|
|
205
|
+
if (ws) {
|
|
206
|
+
detach(ws)
|
|
207
|
+
try {
|
|
208
|
+
ws.close(code, reason)
|
|
209
|
+
} catch {
|
|
210
|
+
// 已经关了
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
this.#first?.reject(new ConnectionError('connection closed before authentication finished'))
|
|
214
|
+
this.#first = undefined
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
#nextSeq(): number {
|
|
218
|
+
this.#seq += 1
|
|
219
|
+
return this.#seq
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#write(bytes: Uint8Array): void {
|
|
223
|
+
const ws = this.#ws
|
|
224
|
+
if (!ws || ws.readyState !== WS_OPEN || this.#state !== 'ready') {
|
|
225
|
+
throw new ConnectionError('not connected to the hub')
|
|
226
|
+
}
|
|
227
|
+
ws.send(bytes)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async #open(): Promise<void> {
|
|
231
|
+
this.#state = 'connecting'
|
|
232
|
+
this.#pendingFatal = undefined
|
|
233
|
+
this.#lastError = undefined
|
|
234
|
+
this.#rateUntil = 0 // 速率预算是按 hub 连接算的,新连接重新开始
|
|
235
|
+
let ws: WebSocketLike
|
|
236
|
+
try {
|
|
237
|
+
ws = await this.#factory(
|
|
238
|
+
this.#opts.url,
|
|
239
|
+
this.#opts.headers ? { headers: this.#opts.headers } : undefined,
|
|
240
|
+
)
|
|
241
|
+
} catch (cause) {
|
|
242
|
+
this.#failAttempt(
|
|
243
|
+
new ConnectionError(`cannot create WebSocket: ${String(cause)}`, { cause }),
|
|
244
|
+
1006,
|
|
245
|
+
'',
|
|
246
|
+
)
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
if (this.#closedByUs) {
|
|
250
|
+
detach(ws)
|
|
251
|
+
ws.close(1000, 'closed')
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
this.#ws = ws
|
|
255
|
+
ws.binaryType = 'arraybuffer'
|
|
256
|
+
ws.onopen = () => {
|
|
257
|
+
if (this.#ws !== ws) return
|
|
258
|
+
this.#state = 'authenticating'
|
|
259
|
+
this.#authTimer = setTimeout(
|
|
260
|
+
() => ws.close(CLOSE_CODE.AUTH_TIMEOUT, 'auth timeout'),
|
|
261
|
+
this.#authTimeoutMs,
|
|
262
|
+
)
|
|
263
|
+
const auth: Control = {
|
|
264
|
+
type: 'auth',
|
|
265
|
+
...(this.#opts.token ? { device_token: this.#opts.token } : {}),
|
|
266
|
+
protocol_version: PROTOCOL_VERSION,
|
|
267
|
+
client: this.#opts.client,
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
const frame = encodeEnvelope(controlEnvelope('', this.#nextSeq(), auth))
|
|
271
|
+
ws.send(frame)
|
|
272
|
+
} catch (cause) {
|
|
273
|
+
this.#pendingFatal = new ConnectionError('failed to send auth frame', { cause })
|
|
274
|
+
ws.close(1011, 'auth send failed')
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
ws.onmessage = (event) => {
|
|
278
|
+
if (this.#ws !== ws) return
|
|
279
|
+
const bytes = toBytes(event.data)
|
|
280
|
+
if (bytes) this.#onFrame(ws, bytes)
|
|
281
|
+
}
|
|
282
|
+
ws.onerror = (event) => {
|
|
283
|
+
this.#lastError = event
|
|
284
|
+
}
|
|
285
|
+
ws.onclose = (event) => {
|
|
286
|
+
if (this.#ws !== ws) return
|
|
287
|
+
this.#onClose(event.code, event.reason)
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
#onFrame(ws: WebSocketLike, bytes: Uint8Array): void {
|
|
292
|
+
let env: Envelope
|
|
293
|
+
try {
|
|
294
|
+
env = decodeEnvelope(bytes)
|
|
295
|
+
} catch {
|
|
296
|
+
return // 坏帧丢弃,不断连接
|
|
297
|
+
}
|
|
298
|
+
if (env.kind !== 'control') {
|
|
299
|
+
this.emit('envelope', env)
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
let ctrl: Control
|
|
303
|
+
try {
|
|
304
|
+
ctrl = controlBody(env)
|
|
305
|
+
} catch (err) {
|
|
306
|
+
if (err instanceof UnknownControlError) return // 版本错位时 hub 新增的控制消息:忽略
|
|
307
|
+
return
|
|
308
|
+
}
|
|
309
|
+
switch (ctrl.type) {
|
|
310
|
+
case 'auth_ok':
|
|
311
|
+
this.#clearAuthTimer()
|
|
312
|
+
this.#state = 'ready'
|
|
313
|
+
this.#attempt = 0
|
|
314
|
+
this.#deviceId = ctrl.device_id
|
|
315
|
+
if (this.#first) {
|
|
316
|
+
this.#first.resolve(ctrl)
|
|
317
|
+
this.#first = undefined
|
|
318
|
+
}
|
|
319
|
+
this.emit('authed', ctrl)
|
|
320
|
+
return
|
|
321
|
+
case 'auth_fail':
|
|
322
|
+
this.#pendingFatal = authFailError(ctrl.reason)
|
|
323
|
+
this.#clearAuthTimer()
|
|
324
|
+
// hub 随后会关连接;主动关一下,避免半开。
|
|
325
|
+
try {
|
|
326
|
+
ws.close(1000, 'auth failed')
|
|
327
|
+
} catch {
|
|
328
|
+
// ignore
|
|
329
|
+
}
|
|
330
|
+
return
|
|
331
|
+
case 'rate_limited': {
|
|
332
|
+
// 先记在连接上、再广播:各 NodeLink 的 onControl 读到的就是更新后的值。
|
|
333
|
+
// 取更晚的那个:迟到的、较短的提示不能把已有的更长的暂停缩短。
|
|
334
|
+
const wait = Math.min(Math.max(ctrl.retry_after_ms, 0), RATE_WAIT_MAX_MS)
|
|
335
|
+
this.#rateUntil = Math.max(this.#rateUntil, Date.now() + wait + Math.random() * 50)
|
|
336
|
+
this.emit('control', ctrl)
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
default:
|
|
340
|
+
this.emit('control', ctrl)
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
#onClose(code: number, reason: string): void {
|
|
345
|
+
this.#clearTimers()
|
|
346
|
+
this.#ws = undefined
|
|
347
|
+
if (this.#closedByUs || this.#state === 'closed') return
|
|
348
|
+
const wasReady = this.#state === 'ready'
|
|
349
|
+
const fatal = this.#pendingFatal ?? this.#fatalForCode(code)
|
|
350
|
+
if (fatal) {
|
|
351
|
+
this.#terminate(fatal, wasReady, code, reason)
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
if (!wasReady) {
|
|
355
|
+
// 认证完成前断开:首次尝试 → 直接失败;重连中 → 继续退避。
|
|
356
|
+
const detail = describeError(this.#lastError)
|
|
357
|
+
this.#failAttempt(
|
|
358
|
+
new ConnectionError(
|
|
359
|
+
`hub connection closed before auth_ok (code ${code}${reason ? `: ${reason}` : ''})${detail ? `: ${detail}` : ''}`,
|
|
360
|
+
{ closeCode: code },
|
|
361
|
+
),
|
|
362
|
+
code,
|
|
363
|
+
reason,
|
|
364
|
+
)
|
|
365
|
+
return
|
|
366
|
+
}
|
|
367
|
+
const willReconnect = this.#opts.reconnect !== undefined && this.#opts.reconnect !== false
|
|
368
|
+
this.emit('disconnected', { code, reason, willReconnect })
|
|
369
|
+
if (willReconnect) this.#scheduleReconnect(code)
|
|
370
|
+
else this.#state = 'closed'
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
#fatalForCode(code: number): Error | undefined {
|
|
374
|
+
if (code === CLOSE_CODE.SUPERSEDED) {
|
|
375
|
+
return new ConnectionError('another connection of this device took over (close code 4001)', {
|
|
376
|
+
closeCode: code,
|
|
377
|
+
})
|
|
378
|
+
}
|
|
379
|
+
if (code === CLOSE_CODE.REVOKED) {
|
|
380
|
+
return new NodeRejected(
|
|
381
|
+
'this device has been revoked by the hub (close code 4004): pair it again',
|
|
382
|
+
)
|
|
383
|
+
}
|
|
384
|
+
return undefined
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** 一次连接尝试在认证前失败。 */
|
|
388
|
+
#failAttempt(error: Error, code: number, reason: string): void {
|
|
389
|
+
if (this.#first) {
|
|
390
|
+
this.#state = 'closed'
|
|
391
|
+
const first = this.#first
|
|
392
|
+
this.#first = undefined
|
|
393
|
+
first.reject(error)
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
const willReconnect = this.#opts.reconnect !== undefined && this.#opts.reconnect !== false
|
|
397
|
+
if (willReconnect) {
|
|
398
|
+
this.#scheduleReconnect(code)
|
|
399
|
+
} else {
|
|
400
|
+
this.#terminate(error, false, code, reason)
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
#terminate(error: Error, wasReady: boolean, code: number, reason: string): void {
|
|
405
|
+
this.#state = 'closed'
|
|
406
|
+
this.#clearTimers()
|
|
407
|
+
const first = this.#first
|
|
408
|
+
this.#first = undefined
|
|
409
|
+
if (first) {
|
|
410
|
+
first.reject(error)
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
if (wasReady) this.emit('disconnected', { code, reason, willReconnect: false })
|
|
414
|
+
this.emit('fatal', error)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
#scheduleReconnect(code: number): void {
|
|
418
|
+
this.#state = 'backoff'
|
|
419
|
+
const attempt = this.#attempt++
|
|
420
|
+
// 4002 restarting:hub 在优雅关停,1–3 秒抖动重连,而不是指数退避。
|
|
421
|
+
const delay =
|
|
422
|
+
code === CLOSE_CODE.RESTARTING
|
|
423
|
+
? 1000 + Math.random() * 2000
|
|
424
|
+
: Math.min(this.#backoff.maxMs, this.#backoff.initialMs * 2 ** attempt) *
|
|
425
|
+
(0.5 + Math.random() * 0.5)
|
|
426
|
+
this.#retryTimer = setTimeout(() => {
|
|
427
|
+
this.#retryTimer = undefined
|
|
428
|
+
if (!this.#closedByUs) void this.#open()
|
|
429
|
+
}, delay)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
#clearAuthTimer(): void {
|
|
433
|
+
if (this.#authTimer !== undefined) clearTimeout(this.#authTimer)
|
|
434
|
+
this.#authTimer = undefined
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
#clearTimers(): void {
|
|
438
|
+
this.#clearAuthTimer()
|
|
439
|
+
if (this.#retryTimer !== undefined) clearTimeout(this.#retryTimer)
|
|
440
|
+
this.#retryTimer = undefined
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function describeError(event: unknown): string {
|
|
445
|
+
if (typeof event !== 'object' || event === null) return ''
|
|
446
|
+
const e = event as { message?: unknown; error?: { message?: unknown } }
|
|
447
|
+
const message = e.message ?? e.error?.message
|
|
448
|
+
return typeof message === 'string' ? message : ''
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function detach(ws: WebSocketLike): void {
|
|
452
|
+
ws.onopen = null
|
|
453
|
+
ws.onmessage = null
|
|
454
|
+
ws.onclose = null
|
|
455
|
+
ws.onerror = null
|
|
456
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@anycon/sdk`:anycon 的 TypeScript SDK(客户端方向)。Node ≥ 20 与浏览器同构。
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { pair, connect } from '@anycon/sdk'
|
|
6
|
+
* await pair('https://hub.example.com', { code: '7K3P-Q2MX-W4NH-8CRD', name: 'ci-runner' }) // 一次性(默认 16 位短码,`--short` 是 8 位,或 #code= 链接)
|
|
7
|
+
* const node = await connect('https://hub.example.com', { node: 'mac-mini' })
|
|
8
|
+
* const session = await node.sessions.create({ agent: 'claude-code', project: 'app' })
|
|
9
|
+
* for await (const ev of session.send('跑一下测试')) {
|
|
10
|
+
* if (ev.type === 'text_delta') process.stdout.write(ev.text)
|
|
11
|
+
* if (ev.type === 'permission') await ev.allow()
|
|
12
|
+
* }
|
|
13
|
+
* await node.close()
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export { connect, type ConnectOptions } from './connect.js'
|
|
17
|
+
export { Client, selectNode, type ClientEvents, type ClientOptions } from './client.js'
|
|
18
|
+
export {
|
|
19
|
+
PAIR_ACK_TIMEOUT_MS,
|
|
20
|
+
forgetNode,
|
|
21
|
+
pair,
|
|
22
|
+
type ForgetNodeOptions,
|
|
23
|
+
type PairOptions,
|
|
24
|
+
type PairResult,
|
|
25
|
+
} from './pair.js'
|
|
26
|
+
export {
|
|
27
|
+
Node,
|
|
28
|
+
type CreateSessionParams,
|
|
29
|
+
type Job,
|
|
30
|
+
type NodeEvents,
|
|
31
|
+
type NodeOptions,
|
|
32
|
+
} from './node.js'
|
|
33
|
+
export {
|
|
34
|
+
Session,
|
|
35
|
+
type ArchiveOptions,
|
|
36
|
+
type DeleteOptions,
|
|
37
|
+
type DiffOptions,
|
|
38
|
+
type GitStatusOptions,
|
|
39
|
+
type HistoryOptions,
|
|
40
|
+
type PermissionActions,
|
|
41
|
+
type PermissionEventData,
|
|
42
|
+
type PermissionStreamEvent,
|
|
43
|
+
type RunResult,
|
|
44
|
+
type SendOptions,
|
|
45
|
+
type StreamEvent,
|
|
46
|
+
type StreamMeta,
|
|
47
|
+
type SyncBaseOptions,
|
|
48
|
+
type TurnStream,
|
|
49
|
+
} from './session.js'
|
|
50
|
+
export {
|
|
51
|
+
IMAGE_MIME_TYPES,
|
|
52
|
+
MAX_CHUNKS_IN_FLIGHT,
|
|
53
|
+
detectImageMime,
|
|
54
|
+
type DownloadOptions,
|
|
55
|
+
type DownloadedAttachment,
|
|
56
|
+
type ImageMime,
|
|
57
|
+
type UploadImageOptions,
|
|
58
|
+
} from './attachments.js'
|
|
59
|
+
export {
|
|
60
|
+
policies,
|
|
61
|
+
type AllowAllOptions,
|
|
62
|
+
type PermissionContext,
|
|
63
|
+
type PermissionDecision,
|
|
64
|
+
type PermissionPolicy,
|
|
65
|
+
} from './permissions.js'
|
|
66
|
+
export type { LinkState } from './link.js'
|
|
67
|
+
export type { BackoffOptions } from './hub.js'
|
|
68
|
+
|
|
69
|
+
export {
|
|
70
|
+
AgentUnavailable,
|
|
71
|
+
AnyconError,
|
|
72
|
+
AttachmentError,
|
|
73
|
+
type AttachmentErrorReason,
|
|
74
|
+
ConnectionError,
|
|
75
|
+
NodeBusy,
|
|
76
|
+
NodeKeyChanged,
|
|
77
|
+
NodeOffline,
|
|
78
|
+
NodeRejected,
|
|
79
|
+
PairingFailed,
|
|
80
|
+
PairingRequired,
|
|
81
|
+
ProtocolMismatch,
|
|
82
|
+
RpcError,
|
|
83
|
+
SettingsInvalid,
|
|
84
|
+
} from './errors.js'
|
|
85
|
+
|
|
86
|
+
export {
|
|
87
|
+
MemoryStorage,
|
|
88
|
+
assertSafeProfile,
|
|
89
|
+
hubHostKey,
|
|
90
|
+
resolveProfile,
|
|
91
|
+
type SdkStorage,
|
|
92
|
+
type StoredIdentity,
|
|
93
|
+
type StoredNode,
|
|
94
|
+
} from './storage.js'
|
|
95
|
+
export { FileStorage, defaultSdkDir } from './storage-file.js'
|
|
96
|
+
export { IndexedDBStorage } from './storage-idb.js'
|
|
97
|
+
export { defaultStorage } from './default-storage.js'
|
|
98
|
+
export { toWsUrl, type WebSocketFactory, type WebSocketInit, type WebSocketLike } from './ws.js'
|
|
99
|
+
export { SDK_VERSION } from './version.js'
|
|
100
|
+
|
|
101
|
+
// 协议层类型和常用值,省得使用方再装一个包。
|
|
102
|
+
export { PROTOCOL_VERSION, METHODS, CLOSE_CODE } from '@anycon/protocol'
|
|
103
|
+
export type {
|
|
104
|
+
AgentCapabilities,
|
|
105
|
+
AgentInfo,
|
|
106
|
+
AttachmentRef,
|
|
107
|
+
BrowseEntry,
|
|
108
|
+
ClearableSetting,
|
|
109
|
+
DiffAgainst,
|
|
110
|
+
DiffFile,
|
|
111
|
+
DiffFileStatus,
|
|
112
|
+
Event,
|
|
113
|
+
GitAction,
|
|
114
|
+
LinkBlock,
|
|
115
|
+
ModelInfo,
|
|
116
|
+
ModeInfo,
|
|
117
|
+
NodeInfo,
|
|
118
|
+
PairFailReason,
|
|
119
|
+
PermissionOption,
|
|
120
|
+
PermissionRequest,
|
|
121
|
+
PermissionResolved,
|
|
122
|
+
Project,
|
|
123
|
+
ProjectKind,
|
|
124
|
+
PullRequestInfo,
|
|
125
|
+
PullRequestState,
|
|
126
|
+
SessionChanged,
|
|
127
|
+
SessionDiffResult,
|
|
128
|
+
SessionEvent,
|
|
129
|
+
SessionGitStatus,
|
|
130
|
+
SessionSettings,
|
|
131
|
+
SessionSummary,
|
|
132
|
+
SessionSyncBaseResult,
|
|
133
|
+
SessionWorkspace,
|
|
134
|
+
SessionWorktree,
|
|
135
|
+
SyncOutcome,
|
|
136
|
+
TurnDoneReason,
|
|
137
|
+
Usage,
|
|
138
|
+
WorkspaceBranchesResult,
|
|
139
|
+
WorkspaceBrowseResult,
|
|
140
|
+
WorktreeDisposal,
|
|
141
|
+
WorktreeInfo,
|
|
142
|
+
WorktreeState,
|
|
143
|
+
} from '@anycon/protocol'
|