@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,396 @@
1
+ import { createSignaling } from "../../../lib/core/index.js";
2
+ import { ICE_SERVERS_PATH, resolveUserIceServers } from "../../../lib/core/signaling/ice-servers.js";
3
+ import { connectToRobot } from "../../../lib/client/direct.js";
4
+ import { createAppSession } from "../bootstrap/host.js";
5
+ import { ConnectionSlot } from "./connection-slot.js";
6
+ import { createHostSurface } from "./mount-surface.js";
7
+ import { loadDevicePicker } from "./device-picker.js";
8
+ import { AccountApiError, bindDevice, unbindDevice, listBoundDevices, mergeBoundDevices, passwordLogin, registerAccount } from "./account-api.js";
9
+ import { getLocale, setLocale, watchLocale } from "./locale.js";
10
+ import { initialRobotSetup, RobotSetupSession } from "./robot-setup.js";
11
+ /**
12
+ * 挂载登录、选设备、业务 iframe 和结束按钮。
13
+ * 选定设备时关闭发现连接,准备连接释放后再向业务 iframe 交接建连凭据。
14
+ */
15
+ export function createHostController(options, render) {
16
+ const defaultSignaling = new URL('/ws', location.href);
17
+ defaultSignaling.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
18
+ const signalingUrl = options.signalingUrl ?? defaultSignaling.href;
19
+ const surface = createHostSurface(options);
20
+ const root = surface.root;
21
+ const lifetime = new AbortController();
22
+ const discovery = new ConnectionSlot();
23
+ let offDiscovery = null;
24
+ let active = null;
25
+ let setup = null;
26
+ let auth = null;
27
+ let boundDevices = [];
28
+ let pickerRequest = null;
29
+ let disposed = false;
30
+ let generation = 0;
31
+ let busy = false;
32
+ let leavePromise = null;
33
+ let view;
34
+ const appName = (locale) => locale === 'en' ? options.appNameEn ?? options.appName : options.appName;
35
+ const locale = getLocale();
36
+ let state = {
37
+ phase: 'login', locale, appName: appName(locale), busy: false,
38
+ status: '', error: false, devices: [], robotName: null, registeredAccount: null, robotSetup: null,
39
+ };
40
+ function update(next) {
41
+ if (disposed)
42
+ return;
43
+ state = { ...state, ...next };
44
+ view?.render(state);
45
+ }
46
+ function report(error) {
47
+ update({ status: error instanceof Error ? error.message : '操作失败,请重试', error: true });
48
+ }
49
+ async function run(work) {
50
+ if (busy || disposed)
51
+ return;
52
+ busy = true;
53
+ update({ busy: true, error: false });
54
+ try {
55
+ await work();
56
+ }
57
+ catch (error) {
58
+ report(error);
59
+ }
60
+ finally {
61
+ busy = leavePromise !== null;
62
+ update({ busy });
63
+ }
64
+ }
65
+ async function closeDiscovery() {
66
+ offDiscovery?.();
67
+ offDiscovery = null;
68
+ await discovery.close();
69
+ }
70
+ async function expireAccount() {
71
+ generation++;
72
+ pickerRequest?.abort();
73
+ await closeDiscovery();
74
+ if (disposed)
75
+ return;
76
+ auth = null;
77
+ boundDevices = [];
78
+ update({ phase: 'login', devices: [], robotName: null, status: '登录已失效,请重新登录', error: true });
79
+ }
80
+ async function pick() {
81
+ const current = ++generation;
82
+ pickerRequest?.abort();
83
+ const request = new AbortController();
84
+ pickerRequest = request;
85
+ await closeDiscovery();
86
+ if (disposed || !auth || current !== generation)
87
+ return;
88
+ const account = auth;
89
+ update({ phase: 'devices', devices: mergeBoundDevices(boundDevices, []), robotName: null, status: '', error: false, robotSetup: null });
90
+ const mod = discovery.open(() => createSignaling({ url: signalingUrl, jti: account.jti, autoReconnect: false,
91
+ ...(options.iceServers ? { iceServers: options.iceServers } : {}) }));
92
+ const isCurrent = () => !disposed && !active && current === generation && auth === account;
93
+ let boundReady = false;
94
+ let accountError = null;
95
+ let discoveryError = null;
96
+ const publish = () => {
97
+ if (!isCurrent())
98
+ return;
99
+ const signalState = mod.getState();
100
+ const error = accountError ?? discoveryError ?? signalState.error;
101
+ const online = boundReady && !error && signalState.authed && signalState.ws === 'open' ? signalState.devices : [];
102
+ update({ devices: mergeBoundDevices(boundDevices, online), status: error ?? '', error: !!error });
103
+ };
104
+ offDiscovery = mod.subscribe(publish);
105
+ await Promise.all([
106
+ listBoundDevices(account.jti, AbortSignal.any([lifetime.signal, request.signal]), options.deviceListUrl).then(devices => {
107
+ if (!isCurrent())
108
+ return;
109
+ boundDevices = devices;
110
+ boundReady = true;
111
+ publish();
112
+ }).catch(async (error) => {
113
+ if (!isCurrent())
114
+ return;
115
+ if (error instanceof AccountApiError && (error.status === 401 || error.code === 401)) {
116
+ await expireAccount();
117
+ return;
118
+ }
119
+ accountError = error instanceof Error ? error.message : '设备列表加载失败,请重试';
120
+ publish();
121
+ }),
122
+ loadDevicePicker(mod, isCurrent, publish, async (error) => {
123
+ discoveryError = error instanceof Error ? error.message : '设备在线状态加载失败,请刷新重试';
124
+ await closeDiscovery();
125
+ publish();
126
+ }, payload => { account.discoveryAuth = { payload, receivedAt: Date.now() }; }),
127
+ ]);
128
+ }
129
+ async function refreshAfterBinding(label) {
130
+ // 账号操作已成功;刷新失败只提示刷新,不要求用户重复账号操作。
131
+ try {
132
+ await pick();
133
+ if (state.phase === 'devices' && state.error)
134
+ update({ status: `${label}成功,但${state.status}` });
135
+ }
136
+ catch {
137
+ update({ devices: mergeBoundDevices(boundDevices, []), error: true, status: `${label}成功,但设备列表刷新失败,请点击刷新设备` });
138
+ }
139
+ }
140
+ async function bind(serialNo) {
141
+ if (busy || disposed || !auth || active || state.phase !== 'devices') {
142
+ throw new Error('当前无法绑定,请稍后重试');
143
+ }
144
+ const serial = serialNo.trim();
145
+ if (serial && boundDevices.some(device => device.sn.toUpperCase() === serial.toUpperCase())) {
146
+ throw new Error('该设备已在你的账户下,无需重复绑定');
147
+ }
148
+ const account = auth;
149
+ busy = true;
150
+ update({ busy: true });
151
+ try {
152
+ await bindDevice(account.jti, serial, lifetime.signal, options.bindDeviceUrl);
153
+ if (disposed || auth !== account)
154
+ return;
155
+ await refreshAfterBinding('绑定');
156
+ }
157
+ catch (error) {
158
+ if (!disposed && auth === account && error instanceof AccountApiError && (error.status === 401 || error.code === 401)) {
159
+ await expireAccount();
160
+ }
161
+ throw error;
162
+ }
163
+ finally {
164
+ busy = leavePromise !== null;
165
+ update({ busy });
166
+ }
167
+ }
168
+ async function unbind(id) {
169
+ if (busy || disposed || !auth || active || state.phase !== 'devices') {
170
+ throw new Error('请先结束当前操作,再解绑设备');
171
+ }
172
+ if (!boundDevices.some(device => device.id === id))
173
+ throw new Error('设备不在当前账号列表中,请刷新后重试');
174
+ const account = auth;
175
+ busy = true;
176
+ update({ busy: true });
177
+ try {
178
+ await unbindDevice(account.jti, id, lifetime.signal, options.unbindDeviceUrl);
179
+ if (disposed || auth !== account)
180
+ return;
181
+ // 即使随后的列表请求失败,也不能继续显示或连接已确认解绑的设备。
182
+ boundDevices = boundDevices.filter(device => device.id !== id);
183
+ await refreshAfterBinding('解绑');
184
+ }
185
+ catch (error) {
186
+ if (!disposed && auth === account && error instanceof AccountApiError && (error.status === 401 || error.code === 401)) {
187
+ await expireAccount();
188
+ }
189
+ throw error;
190
+ }
191
+ finally {
192
+ busy = leavePromise !== null;
193
+ update({ busy });
194
+ }
195
+ }
196
+ function launch(sn) {
197
+ if (active || setup || disposed || !auth)
198
+ return;
199
+ const robot = state.devices.find(device => device.sn === sn && device.online);
200
+ if (!robot) {
201
+ throw new Error('请选择当前在线的机器人');
202
+ }
203
+ generation++;
204
+ pickerRequest?.abort();
205
+ const selectedAuth = auth;
206
+ const appId = options.appId ?? options.appName;
207
+ let iceServers = options.iceServers;
208
+ view.appContainer.replaceChildren();
209
+ update({ phase: 'app', robotName: robot.name, status: '', error: false, robotSetup: initialRobotSetup });
210
+ const preparation = new RobotSetupSession(async (signal) => {
211
+ await closeDiscovery();
212
+ signal.throwIfAborted();
213
+ iceServers ??= await resolveUserIceServers(options.iceServersUrl ?? ICE_SERVERS_PATH, selectedAuth.jti, signal, selectedAuth.discoveryAuth);
214
+ signal.throwIfAborted();
215
+ return connectToRobot({ url: signalingUrl, jti: selectedAuth.jti, sn, iceServers, appId, signal });
216
+ }, robotSetup => {
217
+ if (disposed || setup !== preparation || leavePromise)
218
+ return;
219
+ update({ robotSetup });
220
+ if (robotSetup.step === 'ready' && !robotSetup.busy) {
221
+ void (async () => {
222
+ await preparation.close();
223
+ if (disposed || setup !== preparation || leavePromise)
224
+ return;
225
+ setup = null;
226
+ await openApp({ url: signalingUrl, jti: selectedAuth.jti, sn, appId,
227
+ ...(iceServers ? { iceServers } : {}),
228
+ ...(options.theme ? { theme: options.theme } : {}),
229
+ ...(options.config !== undefined ? { config: options.config } : {}),
230
+ });
231
+ })().catch(report);
232
+ }
233
+ });
234
+ setup = preparation;
235
+ return preparation.check();
236
+ }
237
+ async function openApp(credentials) {
238
+ const iframe = document.createElement('iframe');
239
+ iframe.title = state.appName;
240
+ iframe.allow = `autoplay; microphone ${options.enableMicrophone ? "'src'" : "'none'"}; camera ${options.enableCamera ? "'src'" : "'none'"}`;
241
+ view.appContainer.replaceChildren(iframe);
242
+ update({ robotSetup: null, status: '正在连接机器人…', error: false });
243
+ active = createAppSession({
244
+ iframe,
245
+ appId: options.appId ?? options.appName,
246
+ appUrl: options.appUrl ?? location.href,
247
+ credentials: async () => credentials,
248
+ onState: phase => {
249
+ update({ status: ({ connecting: '正在连接机器人…', ready: '应用运行中', leaving: '正在结束应用…', closed: '应用已结束' })[phase], error: false });
250
+ },
251
+ onAppState: appState => {
252
+ if (appState && typeof appState === 'object' && !Array.isArray(appState) &&
253
+ typeof appState.message === 'string' && appState.message.trim()) {
254
+ update({ status: appState.message.slice(0, 160), error: false });
255
+ }
256
+ },
257
+ onError: report,
258
+ onAppExit: () => { void leave().catch(report); },
259
+ });
260
+ await active.start();
261
+ }
262
+ function leave() {
263
+ if (leavePromise)
264
+ return leavePromise;
265
+ if (disposed || (!active && !setup))
266
+ return Promise.resolve();
267
+ busy = true;
268
+ update({ busy: true, status: '正在结束应用…', error: false });
269
+ leavePromise = (async () => {
270
+ await setup?.close();
271
+ setup = null;
272
+ await active?.leave('standalone-leave');
273
+ await active?.dispose();
274
+ active = null;
275
+ if (!disposed)
276
+ await pick();
277
+ })().finally(() => {
278
+ leavePromise = null;
279
+ busy = false;
280
+ update({ busy: false });
281
+ });
282
+ return leavePromise;
283
+ }
284
+ async function authenticate(input) {
285
+ update({ status: '正在登录…' });
286
+ const work = options.authenticate ?? (value => passwordLogin(value, options));
287
+ const result = await work({ ...input, signal: lifetime.signal });
288
+ if (disposed)
289
+ return;
290
+ if (typeof result.jti !== 'string' || !result.jti)
291
+ throw new Error('认证未返回可用凭据');
292
+ auth = { jti: result.jti };
293
+ boundDevices = [];
294
+ await pick();
295
+ }
296
+ try {
297
+ view = render(root, {
298
+ setLocale,
299
+ login: input => run(async () => {
300
+ if (auth || state.phase !== 'login')
301
+ return;
302
+ await authenticate(input);
303
+ }),
304
+ register: input => run(async () => {
305
+ if (auth || state.phase !== 'register')
306
+ return;
307
+ update({ status: '正在创建账户…' });
308
+ const account = await registerAccount({ ...input, signal: lifetime.signal }, options);
309
+ if (disposed)
310
+ return;
311
+ // 注册已成功便离开注册页;登录失败后只重试登录,避免再次创建同一账户。
312
+ update({ phase: 'login', registeredAccount: { phone: input.phone.trim(), code: account.code } });
313
+ try {
314
+ await authenticate(input);
315
+ }
316
+ catch (error) {
317
+ const message = error instanceof Error ? error.message : '请稍后重试';
318
+ throw new Error(`注册成功,但自动登录失败:${message}。请使用手机号和刚才设置的密码登录。`);
319
+ }
320
+ }),
321
+ showAuthPage: phase => {
322
+ if (busy || disposed || auth || (state.phase !== 'login' && state.phase !== 'register'))
323
+ return;
324
+ update({ phase, status: '', error: false, ...(phase === 'register' ? { registeredAccount: null } : {}) });
325
+ },
326
+ connect: sn => run(async () => { await launch(sn); }),
327
+ checkRobot: async () => { if (!leavePromise)
328
+ await setup?.check(); },
329
+ prepareRobot: async (action) => { if (!leavePromise)
330
+ await setup?.perform(action); },
331
+ bind,
332
+ unbind,
333
+ refresh: () => run(async () => {
334
+ if (!auth || active || setup)
335
+ return;
336
+ await pick();
337
+ }),
338
+ logout: () => run(async () => {
339
+ generation++;
340
+ pickerRequest?.abort();
341
+ await setup?.close();
342
+ setup = null;
343
+ await active?.leave('standalone-logout');
344
+ await active?.dispose();
345
+ active = null;
346
+ await closeDiscovery();
347
+ auth = null;
348
+ boundDevices = [];
349
+ update({ phase: 'login', devices: [], robotName: null, status: '', error: false, registeredAccount: null, robotSetup: null });
350
+ }),
351
+ leave: () => leave().catch(report),
352
+ });
353
+ watchLocale(() => {
354
+ const locale = getLocale();
355
+ if (state.locale === locale)
356
+ return;
357
+ const name = appName(locale);
358
+ const iframe = view?.appContainer.querySelector('iframe');
359
+ if (iframe)
360
+ iframe.title = name;
361
+ update({ locale, appName: name });
362
+ }, lifetime.signal);
363
+ view.render(state);
364
+ }
365
+ catch (error) {
366
+ lifetime.abort();
367
+ try {
368
+ view?.dispose();
369
+ }
370
+ finally {
371
+ surface.dispose();
372
+ }
373
+ throw error;
374
+ }
375
+ return {
376
+ leave,
377
+ async dispose() {
378
+ disposed = true;
379
+ generation++;
380
+ pickerRequest?.abort();
381
+ lifetime.abort();
382
+ await setup?.close();
383
+ setup = null;
384
+ await active?.dispose();
385
+ active = null;
386
+ await closeDiscovery();
387
+ auth = null;
388
+ try {
389
+ view?.dispose();
390
+ }
391
+ finally {
392
+ surface.dispose();
393
+ }
394
+ },
395
+ };
396
+ }
@@ -0,0 +1,12 @@
1
+ /** 外壳接管的页面资源;不参与认证、信令或机器人连接。 */
2
+ export interface HostSurface {
3
+ /** 独立样式与 React 视图的挂载节点。 */
4
+ root: HTMLElement;
5
+ /** 移除外壳并恢复容器内容与页面滚动设置;可重复调用。 */
6
+ dispose(): void;
7
+ }
8
+ /** 创建全屏或局部外壳,避免业务容器的布局约束传入登录界面。 */
9
+ export declare function createHostSurface(options: {
10
+ container?: HTMLElement;
11
+ layout?: 'viewport' | 'container';
12
+ }): HostSurface;
@@ -0,0 +1,69 @@
1
+ const containers = new Set();
2
+ const viewports = new WeakSet();
3
+ /** 创建全屏或局部外壳,避免业务容器的布局约束传入登录界面。 */
4
+ export function createHostSurface(options) {
5
+ const container = options.container ?? document.body;
6
+ const layout = options.layout ?? 'viewport';
7
+ if (layout !== 'viewport' && layout !== 'container')
8
+ throw new Error('未知的外壳布局模式');
9
+ if (!(container instanceof HTMLElement) || container.ownerDocument !== document || !container.isConnected
10
+ || container === document.documentElement) {
11
+ throw new Error('外壳需要当前页面中已连接的 HTMLElement 容器');
12
+ }
13
+ if ([...containers].some(owned => owned.contains(container) || container.contains(owned))
14
+ || viewports.has(document) || (layout === 'viewport' && containers.size > 0)) {
15
+ throw new Error('挂载目标已有 SDK 外壳,请先等待 dispose() 完成');
16
+ }
17
+ const root = document.createElement('div');
18
+ root.className = 'RaydiculousX-host-root';
19
+ root.dataset.layout = layout;
20
+ // Shadow DOM 保护内部组件;宿主节点也必须摆脱普通页面对 div 的布局规则。
21
+ const properties = {
22
+ all: 'initial', display: 'block', 'box-sizing': 'border-box',
23
+ width: '100%', height: '100%', 'min-width': '0', 'min-height': '0',
24
+ 'max-width': 'none', 'max-height': 'none', margin: '0', padding: '0',
25
+ border: '0', overflow: 'hidden', isolation: 'isolate',
26
+ ...(layout === 'viewport'
27
+ ? { position: 'fixed', inset: '0', 'z-index': '2147483000' }
28
+ : { position: 'relative', contain: 'layout paint', 'align-self': 'stretch', 'justify-self': 'stretch', flex: '1 1 auto' }),
29
+ };
30
+ for (const [name, value] of Object.entries(properties))
31
+ root.style.setProperty(name, value, 'important');
32
+ const previous = [...container.childNodes];
33
+ const scrolling = layout === 'viewport' ? [document.documentElement, document.body].flatMap(element => ['overflow-x', 'overflow-y'].map(property => ({
34
+ element, property, value: element.style.getPropertyValue(property), priority: element.style.getPropertyPriority(property),
35
+ }))) : [];
36
+ containers.add(container);
37
+ if (layout === 'viewport')
38
+ viewports.add(document);
39
+ container.replaceChildren();
40
+ // 全屏界面放在 body 下,避开目标容器祖先的 transform、contain、裁剪和尺寸限制。
41
+ (layout === 'viewport' ? document.body : container).append(root);
42
+ for (const { element, property } of scrolling)
43
+ element.style.setProperty(property, 'hidden', 'important');
44
+ let disposed = false;
45
+ return {
46
+ root,
47
+ dispose() {
48
+ if (disposed)
49
+ return;
50
+ disposed = true;
51
+ root.remove();
52
+ // 应用若已主动接管原容器,销毁旧外壳不能覆盖它的新内容。
53
+ if (!container.hasChildNodes())
54
+ container.append(...previous);
55
+ for (const { element, property, value, priority } of scrolling) {
56
+ if (element.style.getPropertyValue(property) !== 'hidden'
57
+ || element.style.getPropertyPriority(property) !== 'important')
58
+ continue;
59
+ if (value)
60
+ element.style.setProperty(property, value, priority);
61
+ else
62
+ element.style.removeProperty(property);
63
+ }
64
+ containers.delete(container);
65
+ if (layout === 'viewport')
66
+ viewports.delete(document);
67
+ },
68
+ };
69
+ }
@@ -0,0 +1,61 @@
1
+ import type { RaydiculousX } from '../../../lib/client/raydiculousx.ts';
2
+ type SetupRobot = Pick<RaydiculousX, 'getStatus' | 'reset' | 'init' | 'enable' | 'dispose' | 'disposed'>;
3
+ /** 用户可手动触发的准备操作。 */
4
+ export type RobotSetupAction = 'reset' | 'init' | 'enable';
5
+ /** 外壳启动引导的显示状态。 */
6
+ export interface RobotSetupViewState {
7
+ /** 由执行器和策略状态确定的当前步骤。 */
8
+ step: 'checking' | 'unavailable' | 'waiting' | 'fault' | 'init' | 'homing' | 'enable' | 'enabling' | 'ready';
9
+ /** 本次手动操作尚未结束。 */
10
+ busy: boolean;
11
+ /** 设备已回到初始姿态。 */
12
+ homed: boolean;
13
+ /** 当前故障允许手动复位。 */
14
+ canReset: boolean;
15
+ /** 设备报告的故障原因。 */
16
+ faultReason: string | null;
17
+ /** 是否锁存了急停。 */
18
+ halted: boolean;
19
+ /** 准备操作或状态查询失败时的提示。 */
20
+ error: string | null;
21
+ }
22
+ export declare const initialRobotSetup: RobotSetupViewState;
23
+ /** 暂时持有外壳的机器人连接,仅在验收设备状态后交接给业务页面。 */
24
+ export declare class RobotSetupSession {
25
+ private readonly controller;
26
+ private readonly connecting;
27
+ private readonly timer;
28
+ private readonly publish;
29
+ private state;
30
+ private checkWork;
31
+ private closing;
32
+ private robot;
33
+ private needsManualInit;
34
+ private needsManualEnable;
35
+ private enableAccepted;
36
+ private waitingUntil;
37
+ private awaiting;
38
+ constructor(open: (signal: AbortSignal) => Promise<SetupRobot>, publish: (state: RobotSetupViewState) => void);
39
+ /**
40
+ * 刷新设备准备状态。轮询与手动刷新复用正在进行的查询。
41
+ * @returns 状态已处理或当前阶段无需刷新时完成。查询错误通过准备界面报告。
42
+ */
43
+ check(): Promise<void>;
44
+ /**
45
+ * 重新读取状态,再执行当前步骤允许的手动操作。
46
+ * @param action - 用户选择的复位、上电归位或启用策略操作。
47
+ * @returns 已处理本次操作或跳过不适用的步骤时完成。设备拒绝或查询失败通过准备界面报告。
48
+ */
49
+ perform(action: RobotSetupAction): Promise<void>;
50
+ /**
51
+ * 停止状态轮询,取消建连并等待准备连接释放。
52
+ * @returns 确认准备连接已清理时完成。重复调用复用同一 Promise。
53
+ * @throws 清理失败或未确认完成时拒绝 Promise,外壳须等待释放成功才能启动业务 iframe。
54
+ */
55
+ close(): Promise<void>;
56
+ private canPerform;
57
+ private update;
58
+ private read;
59
+ private applyStatus;
60
+ }
61
+ export {};