@raydiculousx/ts-sdk 0.0.0-stage → 1.0.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.
Files changed (126) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +55 -0
  3. package/NOTICE +14 -0
  4. package/README.md +91 -3
  5. package/dist/THIRD_PARTY_NOTICES.txt +466 -0
  6. package/dist/host/src/bootstrap/client.d.ts +37 -0
  7. package/dist/host/src/bootstrap/client.js +215 -0
  8. package/dist/host/src/bootstrap/host.d.ts +79 -0
  9. package/dist/host/src/bootstrap/host.js +214 -0
  10. package/dist/host/src/bootstrap/protocol.d.ts +20 -0
  11. package/dist/host/src/bootstrap/protocol.js +72 -0
  12. package/dist/host/src/dev.d.ts +30 -0
  13. package/dist/host/src/dev.js +20 -0
  14. package/dist/host/src/entry/app.d.ts +10 -0
  15. package/dist/host/src/entry/app.js +9 -0
  16. package/dist/host/src/entry/auto.d.ts +16 -0
  17. package/dist/host/src/entry/auto.js +18747 -0
  18. package/dist/host/src/standalone/account-api.d.ts +32 -0
  19. package/dist/host/src/standalone/account-api.js +176 -0
  20. package/dist/host/src/standalone/connection-slot.d.ts +12 -0
  21. package/dist/host/src/standalone/connection-slot.js +28 -0
  22. package/dist/host/src/standalone/device-picker.d.ts +6 -0
  23. package/dist/host/src/standalone/device-picker.js +19 -0
  24. package/dist/host/src/standalone/locale.d.ts +4 -0
  25. package/dist/host/src/standalone/locale.js +35 -0
  26. package/dist/host/src/standalone/mount-host.d.ts +155 -0
  27. package/dist/host/src/standalone/mount-host.js +396 -0
  28. package/dist/host/src/standalone/mount-surface.d.ts +12 -0
  29. package/dist/host/src/standalone/mount-surface.js +69 -0
  30. package/dist/host/src/standalone/robot-setup.d.ts +61 -0
  31. package/dist/host/src/standalone/robot-setup.js +160 -0
  32. package/dist/lib/client/action-ownership.d.ts +31 -0
  33. package/dist/lib/client/action-ownership.js +182 -0
  34. package/dist/lib/client/direct.d.ts +149 -0
  35. package/dist/lib/client/direct.js +560 -0
  36. package/dist/lib/client/raydiculousx.d.ts +541 -0
  37. package/dist/lib/client/raydiculousx.js +694 -0
  38. package/dist/lib/client/runtime.d.ts +165 -0
  39. package/dist/lib/client/runtime.js +1 -0
  40. package/dist/lib/core/index.d.ts +16 -0
  41. package/dist/lib/core/index.js +9 -0
  42. package/dist/lib/core/rpc/command-channel.d.ts +345 -0
  43. package/dist/lib/core/rpc/command-channel.js +697 -0
  44. package/dist/lib/core/rpc/commands.d.ts +354 -0
  45. package/dist/lib/core/rpc/commands.js +134 -0
  46. package/dist/lib/core/rpc/request-policy.d.ts +29 -0
  47. package/dist/lib/core/rpc/request-policy.js +35 -0
  48. package/dist/lib/core/rpc/robot-api.d.ts +184 -0
  49. package/dist/lib/core/rpc/robot-api.js +34 -0
  50. package/dist/lib/core/signaling/ice-servers.d.ts +10 -0
  51. package/dist/lib/core/signaling/ice-servers.js +58 -0
  52. package/dist/lib/core/signaling/peer-negotiator.d.ts +164 -0
  53. package/dist/lib/core/signaling/peer-negotiator.js +366 -0
  54. package/dist/lib/core/signaling/signaling-client.d.ts +204 -0
  55. package/dist/lib/core/signaling/signaling-client.js +473 -0
  56. package/dist/lib/core/signaling/signaling-contract.d.ts +164 -0
  57. package/dist/lib/core/signaling/signaling-contract.js +35 -0
  58. package/dist/lib/core/signaling/signaling.d.ts +172 -0
  59. package/dist/lib/core/signaling/signaling.js +381 -0
  60. package/dist/lib/media/attach-video.d.ts +3 -0
  61. package/dist/lib/media/attach-video.js +243 -0
  62. package/dist/lib/media/direct-audio.d.ts +36 -0
  63. package/dist/lib/media/direct-audio.js +94 -0
  64. package/dist/lib/media/index.d.ts +5 -0
  65. package/dist/lib/media/index.js +3 -0
  66. package/dist/lib/media/pcm-types.d.ts +33 -0
  67. package/dist/lib/media/pcm-types.js +1 -0
  68. package/dist/lib/media/robot-audio.d.ts +64 -0
  69. package/dist/lib/media/robot-audio.js +82 -0
  70. package/dist/lib/media/robot-pcm-output.d.ts +16 -0
  71. package/dist/lib/media/robot-pcm-output.js +101 -0
  72. package/dist/lib/robot/action-upload.d.ts +32 -0
  73. package/dist/lib/robot/action-upload.js +143 -0
  74. package/dist/lib/robot/robot-commands.d.ts +148 -0
  75. package/dist/lib/robot/robot-commands.js +164 -0
  76. package/dist/lib/robot/robot-responses.d.ts +42 -0
  77. package/dist/lib/robot/robot-responses.js +226 -0
  78. package/dist/lib/robot/robot-tof.d.ts +61 -0
  79. package/dist/lib/robot/robot-tof.js +25 -0
  80. package/dist/lib/robot/robot-types.d.ts +293 -0
  81. package/dist/lib/robot/robot-types.js +17 -0
  82. package/dist/lib/shared/errors.d.ts +57 -0
  83. package/dist/lib/shared/errors.js +45 -0
  84. package/dist/lib/shared/events.d.ts +11 -0
  85. package/dist/lib/shared/events.js +40 -0
  86. package/dist/lib/shared/types.d.ts +26 -0
  87. package/dist/lib/shared/types.js +1 -0
  88. package/dist/lib/shared/validation.d.ts +29 -0
  89. package/dist/lib/shared/validation.js +87 -0
  90. package/dist/lib/version.d.ts +2 -0
  91. package/dist/lib/version.js +3 -0
  92. package/dist/raydiculousx-sdk.d.ts +26 -0
  93. package/dist/raydiculousx-sdk.js +17 -0
  94. package/docs/API.md +1106 -0
  95. package/docs/DIRECT_APPS.md +83 -0
  96. package/docs/HOST_HANDOFF.md +59 -0
  97. package/docs/HOST_PROTOCOL.md +43 -0
  98. package/docs/RELEASING.md +33 -0
  99. package/docs/assets/raydiculousx-mark.png +0 -0
  100. package/examples/README.md +10 -0
  101. package/examples/application-template/README.md +60 -0
  102. package/examples/application-template/index.html +12 -0
  103. package/examples/application-template/package.json +21 -0
  104. package/examples/application-template/src/app.config.ts +8 -0
  105. package/examples/application-template/src/app.ts +81 -0
  106. package/examples/application-template/src/dispatch.ts +29 -0
  107. package/examples/application-template/src/embed.ts +39 -0
  108. package/examples/application-template/src/env.d.ts +10 -0
  109. package/examples/application-template/src/host-origin.ts +9 -0
  110. package/examples/application-template/src/locale.ts +90 -0
  111. package/examples/application-template/src/styles.css +31 -0
  112. package/examples/application-template/tsconfig.json +24 -0
  113. package/examples/application-template/vite.config.mjs +16 -0
  114. package/examples/sdk-diagnostics/README.md +199 -0
  115. package/examples/sdk-diagnostics/assets/THIRD_PARTY_NOTICES.txt +567 -0
  116. package/examples/sdk-diagnostics/assets/auto-CnsixhmH.js +9 -0
  117. package/examples/sdk-diagnostics/assets/console-BjvPHSNK.css +1 -0
  118. package/examples/sdk-diagnostics/assets/console-BrwFsb65.js +9 -0
  119. package/examples/sdk-diagnostics/assets/favicon-BZQEit-G.ico +0 -0
  120. package/examples/sdk-diagnostics/assets/index-DXSJUMrS.js +2 -0
  121. package/examples/sdk-diagnostics/assets/messages-C1UCo5nT.js +1 -0
  122. package/examples/sdk-diagnostics/assets/robot-x3-D4wBvBN8.webp +0 -0
  123. package/examples/sdk-diagnostics/assets/styles-D3TrErcf.css +1 -0
  124. package/examples/sdk-diagnostics/index.html +15 -0
  125. package/host/README.md +34 -0
  126. package/package.json +80 -4
@@ -0,0 +1,560 @@
1
+ import { createSignaling, CommandChannel, DEFAULT_ICE_SERVERS } from "../core/index.js";
2
+ import { RaydiculousX } from "./raydiculousx.js";
3
+ import { ActionOwnership } from "./action-ownership.js";
4
+ import { Events } from "../shared/events.js";
5
+ import { RaydiculousXError, positiveTimeout } from "../shared/errors.js";
6
+ import { changesMotion, stopsMotion } from "../core/rpc/request-policy.js";
7
+ import { DirectAudioOutput } from "../media/direct-audio.js";
8
+ import { attachHubVideo } from "../media/attach-video.js";
9
+ import { ActionUploader } from "../robot/action-upload.js";
10
+ import { RobotAudio } from "../media/robot-audio.js";
11
+ import { asJson, randomId } from "../shared/validation.js";
12
+ import { ROBOT_METHODS } from "../robot/robot-commands.js";
13
+ import { readLightFollowResult } from "../robot/robot-responses.js";
14
+ import { iceUrlForSignaling, resolveUserIceServers } from "../core/signaling/ice-servers.js";
15
+ /** 建连失败并附带资源释放结果,供外壳判断是否允许恢复设备发现。 */
16
+ export class DirectConnectionError extends RaydiculousXError {
17
+ /** 建连失败后的软件清理结果;只有 complete 才确认本次资源已释放,不代表实体停稳。 */
18
+ cleanupResult;
19
+ /**
20
+ * 在保留错误码、公开消息和来源的同时附加清理结果。
21
+ * @param error - 已转换为可公开格式的连接失败原因。
22
+ * @param cleanupResult - 失败后等待资源释放得到的结果。
23
+ */
24
+ constructor(error, cleanupResult) {
25
+ super(error.code, error.message, error.source);
26
+ this.name = 'DirectConnectionError';
27
+ this.cleanupResult = cleanupResult;
28
+ }
29
+ }
30
+ function failure(error) {
31
+ if (error instanceof RaydiculousXError)
32
+ return error;
33
+ if (error instanceof Error && 'code' in error) {
34
+ if (error.name === 'RobotRpcError' && typeof error.code === 'number') {
35
+ const raw = 'data' in error ? error.data : undefined;
36
+ const data = {};
37
+ if (raw && typeof raw === 'object') {
38
+ if ('halted' in raw && typeof raw.halted === 'boolean')
39
+ data.halted = raw.halted;
40
+ if ('haltReason' in raw && (raw.haltReason === null || typeof raw.haltReason === 'string'))
41
+ data.haltReason = raw.haltReason;
42
+ if ('retryable' in raw && typeof raw.retryable === 'boolean')
43
+ data.retryable = raw.retryable;
44
+ if ('recoverable' in raw && typeof raw.recoverable === 'boolean')
45
+ data.recoverable = raw.recoverable;
46
+ if ('reason' in raw && typeof raw.reason === 'string')
47
+ data.reason = raw.reason;
48
+ if ('maxCommandHz' in raw && typeof raw.maxCommandHz === 'number' && Number.isFinite(raw.maxCommandHz) && raw.maxCommandHz > 0) {
49
+ data.maxCommandHz = raw.maxCommandHz;
50
+ }
51
+ }
52
+ return new RaydiculousXError(String(error.code), error.message, 'daemon', Object.keys(data).length ? data : undefined);
53
+ }
54
+ if (typeof error.code === 'string')
55
+ return new RaydiculousXError(error.code, error.message, 'transport');
56
+ }
57
+ // 传输异常可能含 URL,避免将凭据或基础设施细节转发给外壳。
58
+ return new RaydiculousXError('CONNECTION_FAILED', '机器人连接或请求失败', 'transport');
59
+ }
60
+ const lightFollowCleanupMs = 40_000;
61
+ const lightFollowStartRejected = new Set([
62
+ 'INVALID_ARGUMENT', 'UNSUPPORTED', 'NOT_READY', 'BUSY', 'BACKPRESSURE', 'TOO_MANY_REQUESTS',
63
+ 'SEND_FAILED', '-32601', '-32602', '409', '423',
64
+ ]);
65
+ function validate(options) {
66
+ const url = new URL(options.url);
67
+ if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
68
+ throw new RaydiculousXError('INVALID_ARGUMENT', '信令地址必须为不含凭据的 ws(s) 地址');
69
+ }
70
+ if (!options.jti?.trim() || !options.sn?.trim())
71
+ throw new RaydiculousXError('INVALID_ARGUMENT', '需要访问凭据与机器人序列号');
72
+ positiveTimeout(options.timeoutMs ?? 20000, 'timeoutMs');
73
+ positiveTimeout(options.cleanupTimeoutMs ?? 5000, 'cleanupTimeoutMs');
74
+ if (options.requestTimeoutMs !== undefined)
75
+ positiveTimeout(options.requestTimeoutMs, 'requestTimeoutMs');
76
+ if (options.theme !== undefined && !['light', 'dark'].includes(options.theme)) {
77
+ throw new RaydiculousXError('INVALID_ARGUMENT', 'theme 必须为 light 或 dark');
78
+ }
79
+ asJson(options.config ?? {});
80
+ }
81
+ /** 一个运行实例独占一次设备连接;断线不重放动作,也不自动创建第二条连接。 */
82
+ export class DirectRuntime {
83
+ /** 当前页面独占 WebRTC 的连接模式。 */
84
+ mode = 'direct';
85
+ events = new Events();
86
+ leaveHandlers = new Set();
87
+ requests = new AbortController();
88
+ actions = new ActionOwnership();
89
+ cleanupTimeout;
90
+ session = randomId();
91
+ outputs = new Set();
92
+ audioClosing = Promise.resolve();
93
+ detachVideo;
94
+ uploader;
95
+ sessionIceServers = DEFAULT_ICE_SERVERS;
96
+ module = null;
97
+ channel = null;
98
+ conn = null;
99
+ current;
100
+ closing = null;
101
+ closeIncomplete = false;
102
+ state = 'connecting';
103
+ off = [];
104
+ resolveReady = null;
105
+ rejectReady = null;
106
+ stopConfirmed = true;
107
+ lightFollowMayBeRunning = false;
108
+ lightFollowRevision = 0;
109
+ options;
110
+ factories;
111
+ /** 创建未启动的运行实例;参数立即校验,实际建连由 start 执行。 */
112
+ constructor(options, factories = {
113
+ signaling: createSignaling,
114
+ channel: connection => new CommandChannel({ connection, connectionEpoch: 1 }),
115
+ }) {
116
+ validate(options);
117
+ this.options = {
118
+ ...options,
119
+ ...(options.iceServers ? { iceServers: structuredClone(options.iceServers) } : {}),
120
+ ...(options.config !== undefined ? { config: structuredClone(options.config) } : {}),
121
+ };
122
+ this.factories = factories;
123
+ this.cleanupTimeout = options.cleanupTimeoutMs ?? 5000;
124
+ this.current = {
125
+ mode: 'direct', appId: options.appId ?? 'standalone', appSessionId: this.session,
126
+ robotId: options.sn, connectionEpoch: 1, connectionState: 'connecting',
127
+ daemonVersion: null, daemonProtocolVersion: null, capabilities: {}, stateSnapshot: null,
128
+ theme: options.theme ?? 'light', config: structuredClone(options.config ?? {}),
129
+ limits: { maxMessageBytes: 16384, maxPendingRequests: 32 },
130
+ };
131
+ }
132
+ /** 返回不含凭据的上下文副本,修改副本不会影响连接。 */
133
+ get context() { return structuredClone(this.current); }
134
+ /** 已开始离场或关闭;异步清理可能仍在等待。 */
135
+ get disposed() { return this.state === 'leaving' || this.state === 'closed'; }
136
+ /** 传输关闭已确认,允许页面创建新实例;媒体或回调仍可能失败或超时,不等于清理结果为 complete。 */
137
+ get closed() { return this.state === 'closed'; }
138
+ /** 当前设备 WebRTC;未建立或已释放时为 null。 */
139
+ get rtcConnection() { return this.conn?.pc ?? null; }
140
+ /** 从当前协商连接读取机器人传入音轨;不存在时为 null。 */
141
+ get incomingRobotAudioTrack() {
142
+ return new RobotAudio(this.audioOptions()).incomingRobotAudioTrack;
143
+ }
144
+ publish(patch) {
145
+ this.current = { ...this.current, ...patch };
146
+ const context = asJson(this.current);
147
+ this.events.emit('context', context);
148
+ }
149
+ /** 等待用户身份认证、WebRTC 控制通道和能力查询;失败时先清理,再拒绝 DirectConnectionError。 */
150
+ async start() {
151
+ if (this.options.signal?.aborted) {
152
+ // 初始化尚未创建传输,也要完成本实例的生命周期,允许页面重试连接。
153
+ const cleanupResult = await this.dispose();
154
+ throw new DirectConnectionError(new RaydiculousXError('ABORTED', '连接已取消'), cleanupResult);
155
+ }
156
+ const ready = new Promise((resolve, reject) => {
157
+ this.resolveReady = resolve;
158
+ this.rejectReady = reject;
159
+ });
160
+ // 在任何 await 前接上拒绝处理,避免同步失败产生未处理 rejection。
161
+ const timer = setTimeout(() => this.rejectReady?.(new RaydiculousXError('INIT_TIMEOUT', '机器人连接超时')), this.options.timeoutMs ?? 20000);
162
+ const abort = () => {
163
+ this.rejectReady?.(new RaydiculousXError('ABORTED', '连接已取消'));
164
+ if (this.state === 'ready')
165
+ void this.dispose();
166
+ };
167
+ this.options.signal?.addEventListener('abort', abort, { once: true });
168
+ this.off.push(() => this.options.signal?.removeEventListener('abort', abort));
169
+ const establish = async () => {
170
+ const mod = this.factories.signaling({
171
+ url: this.options.url, jti: this.options.jti, autoReconnect: false,
172
+ ...(this.options.iceServers ? { iceServers: this.options.iceServers } : {}),
173
+ });
174
+ this.module = mod;
175
+ this.off.push(mod.onEstablished(conn => this.established(conn)));
176
+ this.off.push(mod.onError(() => {
177
+ if (this.state === 'connecting')
178
+ this.rejectReady?.(new RaydiculousXError('CONNECTION_FAILED', '无法建立机器人连接', 'transport'));
179
+ }));
180
+ this.off.push(mod.onEnded(() => {
181
+ if (this.state === 'connecting')
182
+ this.rejectReady?.(new RaydiculousXError('CONNECTION_FAILED', '机器人连接中断', 'transport'));
183
+ if (this.state === 'ready') {
184
+ this.publish({ connectionState: 'disconnected', stateSnapshot: null });
185
+ void this.dispose();
186
+ }
187
+ }));
188
+ const auth = await mod.connectSignaling();
189
+ if (this.disposed)
190
+ return;
191
+ if (auth.role !== 'user')
192
+ throw new RaydiculousXError('INVALID_ARGUMENT', '应用必须使用用户身份连接');
193
+ this.sessionIceServers = this.options.iceServers ?? await resolveUserIceServers(iceUrlForSignaling(this.options.url), this.options.jti, this.requests.signal, { payload: auth, receivedAt: Date.now() });
194
+ if (this.disposed)
195
+ return;
196
+ await mod.negotiate(this.options.sn, this.sessionIceServers);
197
+ };
198
+ void establish().catch(error => this.rejectReady?.(failure(error)));
199
+ try {
200
+ await ready;
201
+ this.options.signal?.throwIfAborted();
202
+ if (this.disposed || !this.channel?.isReady())
203
+ throw new RaydiculousXError('CONNECTION_FAILED', '机器人通道已关闭');
204
+ this.state = 'ready';
205
+ this.publish({ connectionState: 'ready' });
206
+ const pagehide = () => {
207
+ this.channel?.shutdownFast();
208
+ void this.dispose();
209
+ };
210
+ if (typeof window !== 'undefined') {
211
+ window.addEventListener('pagehide', pagehide);
212
+ this.off.push(() => window.removeEventListener('pagehide', pagehide));
213
+ }
214
+ }
215
+ catch (error) {
216
+ const cleanupResult = await this.dispose();
217
+ throw new DirectConnectionError(failure(error), cleanupResult);
218
+ }
219
+ finally {
220
+ clearTimeout(timer);
221
+ this.resolveReady = null;
222
+ this.rejectReady = null;
223
+ }
224
+ }
225
+ established(conn) {
226
+ if (this.disposed || this.conn || conn.sn !== this.options.sn) {
227
+ conn.pc.close();
228
+ if (conn.sn !== this.options.sn)
229
+ this.rejectReady?.(new RaydiculousXError('CONTEXT_CHANGED', '连接设备不匹配'));
230
+ return;
231
+ }
232
+ this.conn = conn;
233
+ if (conn.blob)
234
+ this.uploader = new ActionUploader(conn.blob);
235
+ const channel = this.factories.channel(conn);
236
+ this.channel = channel;
237
+ this.off.push(channel.onTelemetry(frame => {
238
+ if (this.disposed)
239
+ return;
240
+ const payload = asJson(frame.params);
241
+ this.publish({ stateSnapshot: payload });
242
+ this.events.emit('robot.state', payload);
243
+ }));
244
+ this.off.push(channel.onTof(frame => {
245
+ if (!this.disposed)
246
+ this.events.emit('robot.tof', frame);
247
+ }));
248
+ this.off.push(channel.onFault(frame => this.events.emit('robot.fault', asJson(frame.params))));
249
+ this.off.push(channel.onSkill(event => {
250
+ this.actions.finishSkill(event.skill);
251
+ this.events.emit('robot.skill', event);
252
+ }));
253
+ this.off.push(channel.onAudioError(frame => {
254
+ if (!this.disposed)
255
+ this.events.emit('robot.audio.error', asJson(frame.params));
256
+ }));
257
+ this.off.push(channel.onClose(() => {
258
+ if (this.state === 'connecting')
259
+ this.rejectReady?.(new RaydiculousXError('CONNECTION_FAILED', '机器人通道已关闭'));
260
+ if (this.state === 'ready') {
261
+ this.publish({ connectionState: 'disconnected', stateSnapshot: null });
262
+ void this.dispose();
263
+ }
264
+ }));
265
+ void channel.capabilities().then(() => {
266
+ this.publishCapabilities();
267
+ this.resolveReady?.();
268
+ }).catch(error => {
269
+ const cause = failure(error);
270
+ // 单次探测丢包仍可停车或重查能力;收到不兼容的协议回包则按初始化失败处理。
271
+ if (cause.code === 'REQUEST_TIMEOUT' && channel.isReady())
272
+ this.resolveReady?.();
273
+ else
274
+ this.rejectReady?.(cause);
275
+ });
276
+ }
277
+ publishCapabilities() {
278
+ const caps = this.channel?.capabilitiesSnapshot;
279
+ if (this.disposed || !caps)
280
+ return;
281
+ this.publish({
282
+ daemonProtocolVersion: caps.protocol,
283
+ capabilities: {
284
+ move: { supported: true, schemaVersion: caps.protocol },
285
+ skills: { supported: true, schemaVersion: caps.protocol },
286
+ status: { supported: true, schemaVersion: caps.protocol },
287
+ video: { supported: caps.hasVideo, schemaVersion: caps.protocol },
288
+ audioOut: { supported: caps.hasAudioOut, schemaVersion: caps.protocol },
289
+ audioIn: { supported: caps.hasAudioIn, schemaVersion: caps.protocol },
290
+ ...(caps.hasTof === undefined ? {} : { tof: { supported: caps.hasTof, schemaVersion: caps.protocol } }),
291
+ ...(caps.hasLightFollow === undefined ? {} : { lightFollow: { supported: caps.hasLightFollow, schemaVersion: caps.protocol } }),
292
+ },
293
+ });
294
+ }
295
+ assertReady() {
296
+ if (this.disposed)
297
+ throw new RaydiculousXError('APP_DISPOSED', '应用连接已关闭');
298
+ if (this.state !== 'ready' || !this.channel?.isReady())
299
+ throw new RaydiculousXError('NOT_READY', '机器人连接未就绪');
300
+ }
301
+ /** 发送一个开放的设备请求;本地取消或超时不撤销设备动作,错误转换为 RaydiculousXError。 */
302
+ async request(method, params = null, options = {}) {
303
+ this.assertReady();
304
+ if (!Object.values(ROBOT_METHODS).includes(method)) {
305
+ throw new RaydiculousXError('UNSUPPORTED', '直连应用未开放此设备方法');
306
+ }
307
+ let value = asJson(params);
308
+ if (method === ROBOT_METHODS.doSkill && (value === null || typeof value !== 'object' || Array.isArray(value)
309
+ || (value.wait !== undefined && typeof value.wait !== 'boolean'))) {
310
+ throw new RaydiculousXError('INVALID_ARGUMENT', '技能参数无效');
311
+ }
312
+ if ((method === ROBOT_METHODS.getConfig || method === ROBOT_METHODS.listActions || method === ROBOT_METHODS.stopAudio
313
+ || method === ROBOT_METHODS.stop || method === ROBOT_METHODS.relax || method === ROBOT_METHODS.reset
314
+ || method === ROBOT_METHODS.getStatus || method === ROBOT_METHODS.getCapabilities
315
+ || method === ROBOT_METHODS.getServoState || method === ROBOT_METHODS.unsubscribeTof
316
+ || method === ROBOT_METHODS.stopLightFollow || method === ROBOT_METHODS.getLightFollowStatus) && value !== null) {
317
+ if (typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length > 0) {
318
+ throw new RaydiculousXError('INVALID_ARGUMENT', '此方法不接受参数');
319
+ }
320
+ value = null;
321
+ }
322
+ const signal = options.signal ? AbortSignal.any([options.signal, this.requests.signal]) : this.requests.signal;
323
+ const timeoutMs = options.timeoutMs ?? this.options.requestTimeoutMs;
324
+ if (signal.aborted)
325
+ throw new RaydiculousXError('ABORTED', '请求已取消', 'transport');
326
+ const startingLightFollow = method === ROBOT_METHODS.startLightFollow;
327
+ const stoppingLightFollow = method === ROBOT_METHODS.stopLightFollow;
328
+ const previousLightFollow = this.lightFollowMayBeRunning;
329
+ const lightFollowRevision = startingLightFollow || stoppingLightFollow || method === ROBOT_METHODS.getLightFollowStatus
330
+ ? ++this.lightFollowRevision : undefined;
331
+ try {
332
+ const result = await this.actions.request(method, value, async () => {
333
+ if (changesMotion(method))
334
+ this.stopConfirmed = false;
335
+ if (startingLightFollow)
336
+ this.lightFollowMayBeRunning = true;
337
+ try {
338
+ return await this.channel.request(method, value === null ? undefined : value, {
339
+ context: { appId: this.current.appId, requestId: randomId(), appSessionId: this.session, connectionEpoch: 1, robotId: this.options.sn, signal },
340
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
341
+ });
342
+ }
343
+ catch (error) {
344
+ throw failure(error);
345
+ }
346
+ });
347
+ if (method === ROBOT_METHODS.getCapabilities)
348
+ this.publishCapabilities();
349
+ if (lightFollowRevision === this.lightFollowRevision && !startingLightFollow
350
+ && result && typeof result === 'object' && !Array.isArray(result)
351
+ && result.running === false && (stoppingLightFollow ? result.accepted === true : typeof result.installed === 'boolean')) {
352
+ this.lightFollowMayBeRunning = false;
353
+ }
354
+ if (stopsMotion(method)
355
+ && result && typeof result === 'object' && !Array.isArray(result) && result.accepted === true) {
356
+ this.stopConfirmed = true;
357
+ }
358
+ // 配置回执已经由 CommandChannel 限长并从 JSON 解码,大型数值表可能超过启动消息的节点数限制。
359
+ return method === ROBOT_METHODS.getConfig ? result : asJson(result);
360
+ }
361
+ catch (error) {
362
+ const requestError = failure(error);
363
+ if (startingLightFollow && lightFollowRevision === this.lightFollowRevision && lightFollowStartRejected.has(requestError.code)) {
364
+ this.lightFollowMayBeRunning = previousLightFollow;
365
+ }
366
+ throw requestError;
367
+ }
368
+ }
369
+ /** 订阅运行事件并返回退订函数;离场后拒绝新订阅,历史事件不回放。 */
370
+ on(event, handler) {
371
+ if (this.disposed)
372
+ throw new RaydiculousXError('APP_DISPOSED', '应用连接已关闭');
373
+ if (!event || event.length > 256 || typeof handler !== 'function')
374
+ throw new RaydiculousXError('INVALID_ARGUMENT', '事件参数无效');
375
+ return this.events.on(event, handler);
376
+ }
377
+ /** 注册并行执行的离场清理回调,返回取消注册函数;开始离场后不可注册。 */
378
+ onAppExit(handler) {
379
+ if (this.disposed)
380
+ throw new RaydiculousXError('APP_DISPOSED', '应用连接已关闭');
381
+ if (typeof handler !== 'function')
382
+ throw new RaydiculousXError('INVALID_ARGUMENT', '需要清理回调');
383
+ this.leaveHandlers.add(handler);
384
+ return () => { this.leaveHandlers.delete(handler); };
385
+ }
386
+ /** 已就绪时调用外壳状态回调;配置了回调才校验并传入 JSON,不修改设备状态。 */
387
+ reportAppState(state) {
388
+ this.assertReady();
389
+ this.options.onAppState?.(asJson(state));
390
+ }
391
+ /** 请求外壳离场,未配置外壳回调时开始 dispose;同步返回不代表清理完成。 */
392
+ requestAppExit(reason = 'app-request') {
393
+ if (!reason || reason.length > 1024)
394
+ throw new RaydiculousXError('INVALID_ARGUMENT', '离场原因无效');
395
+ if (this.options.onLeaveRequested)
396
+ this.options.onLeaveRequested(reason);
397
+ else
398
+ void this.dispose();
399
+ }
400
+ audioOptions() {
401
+ return {
402
+ getConnection: () => this.rtcConnection,
403
+ hasAudioOut: () => this.channel?.capabilitiesSnapshot?.hasAudioOut === true && !this.disposed,
404
+ };
405
+ }
406
+ /** 在当前连接上传单个动作,离场时取消。 */
407
+ uploadAction(name, file, options) {
408
+ this.assertReady();
409
+ if (!this.uploader)
410
+ throw new RaydiculousXError('UNSUPPORTED', '设备连接没有动作上传通道');
411
+ return this.uploader.upload(name, file, options, this.requests.signal);
412
+ }
413
+ /** 使用已有信令连接启动独立的视频接收会话。 */
414
+ bindRobotVideo(element) {
415
+ this.assertReady();
416
+ if (!element || element.localName !== 'video' || typeof element.play !== 'function') {
417
+ throw new RaydiculousXError('INVALID_ARGUMENT', '需要 HTMLVideoElement');
418
+ }
419
+ const caps = this.channel?.capabilitiesSnapshot;
420
+ if (!this.module || !caps?.hasVideo || caps.video?.signaling !== 'hub' || caps.video.transport !== 'webrtc') {
421
+ throw new RaydiculousXError('UNSUPPORTED', '设备未提供中枢 WebRTC 视频流');
422
+ }
423
+ this.detachVideo?.();
424
+ this.detachVideo = attachHubVideo(element, this.module, this.options.sn, this.sessionIceServers, () => { this.detachVideo = undefined; });
425
+ return this.detachVideo;
426
+ }
427
+ /** 创建复用当前 WebRTC 的 PCM 输出,串行等待旧音频驱动释放。 */
428
+ createAudioOutput() {
429
+ this.assertReady();
430
+ const output = new DirectAudioOutput(this.audioOptions(), () => this.audioClosing, work => {
431
+ this.audioClosing = Promise.all([this.audioClosing, work]).then(() => undefined);
432
+ // 关闭失败由 dispose 统一汇报,避免未处理 rejection。
433
+ void this.audioClosing.catch(() => { });
434
+ this.outputs.delete(output);
435
+ });
436
+ this.outputs.add(output);
437
+ return output;
438
+ }
439
+ /** 取消业务等待并汇总软件清理结果;信令未关闭时保留占用,后续调用可重试关闭。 */
440
+ dispose() {
441
+ if (this.closing && !this.closeIncomplete)
442
+ return this.closing;
443
+ this.closeIncomplete = false;
444
+ this.state = 'leaving';
445
+ this.rejectReady?.(new RaydiculousXError('ABORTED', '连接初始化已结束'));
446
+ this.requests.abort();
447
+ this.closing = this.cleanup();
448
+ return this.closing;
449
+ }
450
+ async cleanup() {
451
+ const stopLightFollow = this.lightFollowMayBeRunning;
452
+ // start.sh 和 stop.sh 在板端按顺序处理,默认最久分别需要 20 秒和 15 秒。
453
+ const timeout = stopLightFollow && this.options.cleanupTimeoutMs === undefined ? lightFollowCleanupMs : this.cleanupTimeout;
454
+ const context = { reason: 'dispose', deadline: Date.now() + timeout };
455
+ this.detachVideo?.();
456
+ for (const output of this.outputs)
457
+ output.dispose();
458
+ let timer;
459
+ let result = 'complete';
460
+ try {
461
+ const work = Promise.allSettled([
462
+ ...[...this.leaveHandlers].map(handler => Promise.resolve().then(() => handler(context))),
463
+ this.audioClosing,
464
+ this.channel?.closeSession({ appSessionId: this.session }).then(() => { this.stopConfirmed = true; }),
465
+ stopLightFollow ? this.stopLightFollowForCleanup(timeout) : undefined,
466
+ ]).then(results => {
467
+ if (results.some(item => item.status === 'rejected'))
468
+ throw new RaydiculousXError('CLEANUP_FAILED', '应用清理未完成');
469
+ });
470
+ await Promise.race([work, new Promise((_, reject) => {
471
+ timer = setTimeout(() => reject(new RaydiculousXError('CLEANUP_TIMEOUT', '应用清理超时')), timeout);
472
+ })]);
473
+ }
474
+ catch (error) {
475
+ result = error instanceof RaydiculousXError && error.code === 'CLEANUP_TIMEOUT' ? 'timeout' : 'failed';
476
+ }
477
+ finally {
478
+ clearTimeout(timer);
479
+ if (!this.stopConfirmed)
480
+ this.channel?.shutdownFast();
481
+ for (const off of this.off.splice(0))
482
+ off();
483
+ this.channel?.dispose();
484
+ this.channel = null;
485
+ this.conn = null;
486
+ try {
487
+ await this.module?.disconnectSignaling();
488
+ this.module = null;
489
+ }
490
+ catch {
491
+ result = 'failed';
492
+ this.closeIncomplete = true;
493
+ }
494
+ this.publish({ connectionState: 'disconnected', stateSnapshot: null });
495
+ this.events.clear();
496
+ this.leaveHandlers.clear();
497
+ this.state = this.closeIncomplete ? 'leaving' : 'closed';
498
+ }
499
+ return result;
500
+ }
501
+ async stopLightFollowForCleanup(timeoutMs) {
502
+ const result = await this.channel?.request(ROBOT_METHODS.stopLightFollow, undefined, {
503
+ timeoutMs: Math.min(timeoutMs, 120_000),
504
+ });
505
+ readLightFollowResult(result, false);
506
+ this.lightFollowMayBeRunning = false;
507
+ }
508
+ }
509
+ let active = null;
510
+ /**
511
+ * 创建或复用当前页面的直连客户端,成功后机器人控制通道已就绪。
512
+ *
513
+ * @param options - 可信建连配置;凭据只用于认证,不能放入 URL、日志或公开业务状态。
514
+ * @returns 控制通道就绪后的业务客户端。
515
+ * @throws 配置校验失败或页面已有冲突或未释放的连接时,以 {@link RaydiculousXError} 拒绝 Promise。
516
+ * @throws 信令地址无法解析为 URL 时,以 TypeError 拒绝 Promise。
517
+ * @throws 初始化被取消、超时或传输失败时,在清理后以 {@link DirectConnectionError} 拒绝,清理结果见 cleanupResult。
518
+ * @remarks
519
+ * 同一页面、相同配置及回调引用复用同一个初始化 Promise;冲突配置返回 BUSY。
520
+ * 更换配置或建连失败后,应等待 dispose 并检查清理结果;传输关闭未确认时继续拒绝新会话。
521
+ * 本函数等待信令认证、WebRTC 控制通道和首次能力探测。单次探测超时且通道仍就绪时返回客户端,
522
+ * 此时能力未知,调用 getCapabilities() 可重新查询。初始化总超时和无效的协议回包仍会使建连失败。
523
+ * 业务 RPC 与媒体通过本页面连接发送;不会自动重连、重放动作或回退为 Host 代理。
524
+ */
525
+ export function connectToRobot(options) {
526
+ try {
527
+ validate(options);
528
+ if (active?.runtime.closed)
529
+ active = null;
530
+ if (active?.runtime.disposed)
531
+ throw new RaydiculousXError('BUSY', '请等待上一连接清理完成');
532
+ const key = JSON.stringify([options.url, options.jti, options.sn, options.iceServers, options.timeoutMs,
533
+ options.requestTimeoutMs, options.cleanupTimeoutMs, options.appId, options.theme, options.config]);
534
+ if (active) {
535
+ if (active.key !== key || active.options.signal !== options.signal
536
+ || active.options.onAppState !== options.onAppState || active.options.onLeaveRequested !== options.onLeaveRequested) {
537
+ throw new RaydiculousXError('BUSY', '当前页面已有其他机器人连接,请先完成 dispose');
538
+ }
539
+ return active.promise;
540
+ }
541
+ const runtime = new DirectRuntime(options);
542
+ const entry = {
543
+ key, options: { ...options }, runtime,
544
+ promise: runtime.start().then(() => {
545
+ const robot = new RaydiculousX(runtime);
546
+ entry.robot = robot;
547
+ return robot;
548
+ }).catch(error => {
549
+ if (active === entry && runtime.closed)
550
+ active = null;
551
+ throw error;
552
+ }),
553
+ };
554
+ active = entry;
555
+ return entry.promise;
556
+ }
557
+ catch (error) {
558
+ return Promise.reject(error);
559
+ }
560
+ }