@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,37 @@
1
+ import type { DirectConnectionOptions } from '../../../lib/client/direct.ts';
2
+ import type { RaydiculousX } from '../../../lib/client/raydiculousx.ts';
3
+ /** 业务 iframe 的可信启动配置;URL 入口标志不能代替宿主授权。 */
4
+ export interface ConnectAppRobotOptions {
5
+ /** 可信配置中的精确 HTTP(S) origin,不含路径、查询或片段;省略仅信任业务页面同源 Host。 */
6
+ expectedHostOrigin?: string;
7
+ /** 取消整个初始化流程;已连接后的退出使用 dispose。 */
8
+ signal?: AbortSignal;
9
+ /** 启动握手和机器人建连的总等待上限,单位 ms,默认 45000;有限数且大于 0、不超过 300000。 */
10
+ timeoutMs?: number;
11
+ /** 当前业务窗口;默认全局 window。 */
12
+ window?: Window;
13
+ /**
14
+ * 直连成功后接收可信宿主交接的访问凭据。
15
+ * @param jti - 本次授权的凭据,可用于应用自己的同源服务鉴权。
16
+ * @remarks 凭据不得记录到日志或写入 URL。
17
+ */
18
+ onPlatformCredential?: (jti: string) => void;
19
+ }
20
+ /** 业务 iframe 建连成功后使用的 {@link RaydiculousX} 客户端。 */
21
+ type AppRobot = RaydiculousX;
22
+ type Connector = (options: DirectConnectionOptions) => Promise<AppRobot>;
23
+ /**
24
+ * 接收可信父页面的启动授权,并在当前业务 iframe 中建立机器人连接。
25
+ *
26
+ * @param options - 来源、启动取消信号和等待上限,见 {@link ConnectAppRobotOptions}。
27
+ * @returns 控制通道就绪后的业务客户端。首次能力查询超时且通道仍可用时也会返回,可调用 {@link RaydiculousX.getCapabilities} 重新查询。
28
+ * @throws 来源或超时配置非法时可能同步抛出 Error;无宿主、配置冲突、取消、握手或建连失败时拒绝 Promise。
29
+ * @remarks
30
+ * 同一窗口的可信来源、启动时限、取消信号和 onPlatformCredential 回调均相同时,复用初始化 Promise。
31
+ * 失败或离场后,只有资源清理确认为 complete 才允许创建新会话。
32
+ * 此入口不负责登录或显示外壳,不会自动重连或重放动作。
33
+ */
34
+ export declare function connectAppRobot(options?: ConnectAppRobotOptions): Promise<AppRobot>;
35
+ /** 内部可注入连接工厂,供协议回归测试;业务使用 connectAppRobot。 */
36
+ export declare function connectEmbeddedApp(options: ConnectAppRobotOptions, connector: Connector, release?: () => void): Promise<AppRobot>;
37
+ export {};
@@ -0,0 +1,215 @@
1
+ import { connectToRobot } from "../../../lib/client/direct.js";
2
+ import { randomId } from "../../../lib/shared/validation.js";
3
+ import { DEFAULT_ICE_SERVERS } from "../../../lib/core/signaling/signaling-contract.js";
4
+ import { credentials, isMessage, message, origin, timeout } from "./protocol.js";
5
+ const instances = new WeakMap();
6
+ /**
7
+ * 接收可信父页面的启动授权,并在当前业务 iframe 中建立机器人连接。
8
+ *
9
+ * @param options - 来源、启动取消信号和等待上限,见 {@link ConnectAppRobotOptions}。
10
+ * @returns 控制通道就绪后的业务客户端。首次能力查询超时且通道仍可用时也会返回,可调用 {@link RaydiculousX.getCapabilities} 重新查询。
11
+ * @throws 来源或超时配置非法时可能同步抛出 Error;无宿主、配置冲突、取消、握手或建连失败时拒绝 Promise。
12
+ * @remarks
13
+ * 同一窗口的可信来源、启动时限、取消信号和 onPlatformCredential 回调均相同时,复用初始化 Promise。
14
+ * 失败或离场后,只有资源清理确认为 complete 才允许创建新会话。
15
+ * 此入口不负责登录或显示外壳,不会自动重连或重放动作。
16
+ */
17
+ export function connectAppRobot(options = {}) {
18
+ const appWindow = options.window ?? window;
19
+ if (appWindow.parent === appWindow)
20
+ return Promise.reject(new Error('请先通过 mountAppShell 或商店启动应用'));
21
+ const expected = origin(options.expectedHostOrigin ?? appWindow.location.origin);
22
+ const timeoutMs = timeout(options.timeoutMs, 45_000);
23
+ const existing = instances.get(appWindow);
24
+ if (existing) {
25
+ if (existing.origin !== expected || existing.signal !== options.signal || existing.timeoutMs !== timeoutMs ||
26
+ existing.onPlatformCredential !== options.onPlatformCredential) {
27
+ return Promise.reject(new Error('同一应用窗口不能同时使用不同启动配置'));
28
+ }
29
+ return existing.promise;
30
+ }
31
+ const entry = { origin: expected, signal: options.signal, timeoutMs,
32
+ onPlatformCredential: options.onPlatformCredential, promise: undefined };
33
+ instances.set(appWindow, entry);
34
+ const release = () => {
35
+ if (instances.get(appWindow) === entry)
36
+ instances.delete(appWindow);
37
+ };
38
+ try {
39
+ entry.promise = connectEmbeddedApp({ ...options, window: appWindow, expectedHostOrigin: expected, timeoutMs }, connectToRobot, release);
40
+ }
41
+ catch (error) {
42
+ release();
43
+ entry.promise = Promise.reject(error);
44
+ }
45
+ return entry.promise;
46
+ }
47
+ /** 内部可注入连接工厂,供协议回归测试;业务使用 connectAppRobot。 */
48
+ export function connectEmbeddedApp(options, connector, release = () => { }) {
49
+ const appWindow = options.window ?? window;
50
+ if (appWindow.parent === appWindow)
51
+ return Promise.reject(new Error('请先通过 mountAppShell 或商店启动应用'));
52
+ const expected = origin(options.expectedHostOrigin ?? appWindow.location.origin);
53
+ const bootTimeout = timeout(options.timeoutMs, 45_000);
54
+ const nonce = randomId();
55
+ const controller = new AbortController();
56
+ let port = null;
57
+ let sdk = null;
58
+ let rawDispose = null;
59
+ let connecting = null;
60
+ let closing = null;
61
+ let initReceived = false;
62
+ let settled = false;
63
+ let startupCleanupResult = 'complete';
64
+ let lastSeen = Date.now();
65
+ let readyTimer;
66
+ let bootTimer;
67
+ let watchdog;
68
+ let resolveBoot;
69
+ let rejectBoot;
70
+ const promise = new Promise((resolve, reject) => { resolveBoot = resolve; rejectBoot = reject; });
71
+ function send(type, extra = {}) {
72
+ port?.postMessage(message(type, nonce, extra));
73
+ }
74
+ function detach(reusable) {
75
+ clearInterval(readyTimer);
76
+ clearTimeout(bootTimer);
77
+ clearInterval(watchdog);
78
+ appWindow.removeEventListener('message', onMessage);
79
+ appWindow.removeEventListener('pagehide', onPageHide);
80
+ options.signal?.removeEventListener('abort', onAbort);
81
+ port?.close();
82
+ port = null;
83
+ if (reusable)
84
+ release();
85
+ }
86
+ function reject(error) {
87
+ if (!settled) {
88
+ settled = true;
89
+ rejectBoot(error);
90
+ }
91
+ }
92
+ function cleanup() {
93
+ if (closing)
94
+ return closing;
95
+ controller.abort();
96
+ reject(new Error('应用启动已取消'));
97
+ closing = (async () => {
98
+ if (!sdk && connecting) {
99
+ try {
100
+ sdk = await connecting;
101
+ }
102
+ catch (error) {
103
+ rememberCleanupFailure(error);
104
+ }
105
+ if (sdk && !rawDispose)
106
+ rawDispose = sdk.dispose.bind(sdk);
107
+ }
108
+ let result = startupCleanupResult;
109
+ try {
110
+ if (rawDispose)
111
+ result = await rawDispose();
112
+ }
113
+ catch {
114
+ result = 'failed';
115
+ }
116
+ send('closed', { result });
117
+ detach(result === 'complete');
118
+ return result;
119
+ })();
120
+ return closing;
121
+ }
122
+ function onAbort() {
123
+ reject(new Error('应用初始化已取消'));
124
+ void cleanup();
125
+ }
126
+ function rememberCleanupFailure(error) {
127
+ if (error && typeof error === 'object' && 'cleanupResult' in error &&
128
+ (error.cleanupResult === 'failed' || error.cleanupResult === 'timeout')) {
129
+ startupCleanupResult = error.cleanupResult;
130
+ }
131
+ }
132
+ function onPageHide() { void cleanup(); }
133
+ function onPort(event) {
134
+ const data = event.data;
135
+ if (!isMessage(data) || data.nonce !== nonce)
136
+ return;
137
+ lastSeen = Date.now();
138
+ if (data.type === 'ping')
139
+ send('pong');
140
+ else if (data.type === 'leave')
141
+ void cleanup();
142
+ }
143
+ function onMessage(event) {
144
+ const data = event.data;
145
+ if (initReceived || controller.signal.aborted || !isMessage(data) || data.nonce !== nonce ||
146
+ event.source !== appWindow.parent || event.origin !== expected || data.type !== 'init')
147
+ return;
148
+ if (event.ports.length !== 1)
149
+ return;
150
+ initReceived = true;
151
+ clearInterval(readyTimer);
152
+ appWindow.removeEventListener('message', onMessage);
153
+ port = event.ports[0];
154
+ port.onmessage = onPort;
155
+ port.onmessageerror = () => { void cleanup(); };
156
+ port.start();
157
+ lastSeen = Date.now();
158
+ watchdog = setInterval(() => {
159
+ if (Date.now() - lastSeen > 10_000)
160
+ void cleanup();
161
+ }, 2000);
162
+ void (async () => {
163
+ try {
164
+ const bundle = credentials(data.credentials);
165
+ connecting = connector({
166
+ ...bundle,
167
+ // ICE 由可信外壳获取。缺失时沿用默认 STUN,避免在业务页面重复取临时凭证。
168
+ iceServers: bundle.iceServers ?? DEFAULT_ICE_SERVERS,
169
+ signal: controller.signal,
170
+ onAppState: state => send('state', { state }),
171
+ onLeaveRequested: reason => send('leave-request', { reason }),
172
+ });
173
+ sdk = await connecting;
174
+ rawDispose = sdk.dispose.bind(sdk);
175
+ if (controller.signal.aborted) {
176
+ await cleanup();
177
+ return;
178
+ }
179
+ sdk.dispose = cleanup;
180
+ sdk.onAppExit(() => {
181
+ // 设备断线可能由 runtime 先开始清理;不能在其清理回调里等待自身 dispose。
182
+ queueMicrotask(() => { void cleanup(); });
183
+ });
184
+ options.onPlatformCredential?.(bundle.jti);
185
+ clearTimeout(bootTimer);
186
+ options.signal?.removeEventListener('abort', onAbort);
187
+ settled = true;
188
+ send('ready');
189
+ resolveBoot(sdk);
190
+ }
191
+ catch (error) {
192
+ rememberCleanupFailure(error);
193
+ reject(new Error('机器人直连初始化失败,请检查登录、设备和信令配置'));
194
+ if (!controller.signal.aborted)
195
+ send('error');
196
+ void cleanup();
197
+ }
198
+ })();
199
+ }
200
+ appWindow.addEventListener('message', onMessage);
201
+ appWindow.addEventListener('pagehide', onPageHide);
202
+ options.signal?.addEventListener('abort', onAbort, { once: true });
203
+ bootTimer = setTimeout(() => {
204
+ reject(new Error('应用启动超时'));
205
+ void cleanup();
206
+ }, bootTimeout);
207
+ const ready = () => appWindow.parent.postMessage(message('ready', nonce), expected);
208
+ if (options.signal?.aborted)
209
+ onAbort();
210
+ else {
211
+ readyTimer = setInterval(ready, 250);
212
+ ready();
213
+ }
214
+ return promise;
215
+ }
@@ -0,0 +1,79 @@
1
+ import type { DirectConnectionOptions } from '../../../lib/client/direct.ts';
2
+ import type { JsonValue } from '../../../lib/shared/types.ts';
3
+ /** 当前应用启动和退出阶段,不表示设备物理运动是否完成。 */
4
+ export type AppSessionPhase = 'connecting' | 'ready' | 'leaving' | 'closed';
5
+ /** Host 只交接建连授权和生命周期,机器人命令始终由应用 SDK 发送。 */
6
+ export interface AppSessionOptions {
7
+ /** 已挂载的业务 iframe。 */
8
+ iframe: HTMLIFrameElement;
9
+ /** Host 确认的应用身份;非空白字符串,最多 256 个 UTF-16 代码单元,按原值传递。 */
10
+ appId: string;
11
+ /** 可信目录中的 HTTP(S) 应用地址;相对地址按宿主页面解析,启动时添加 embedded=1。 */
12
+ appUrl: string | URL;
13
+ /**
14
+ * 为本次业务连接提供授权。
15
+ * @returns 宿主释放已有控制或发现连接后,返回业务应用的建连配置。
16
+ * @throws 宿主连接释放或授权提供失败时应拒绝 Promise。
17
+ * @remarks 只提供建连需要的字段和本次访问凭据,不交接密码或刷新令牌。
18
+ */
19
+ credentials: () => Promise<DirectConnectionOptions>;
20
+ /**
21
+ * 接收应用阶段变化。
22
+ * @param state - 当前 {@link AppSessionPhase}。
23
+ */
24
+ onState?: (state: AppSessionPhase) => void;
25
+ /**
26
+ * 接收已就绪应用发布的公开业务状态。
27
+ * @param state - 应用发布的 JSON 状态。
28
+ * @returns 可以同步处理或返回自己的异步任务。
29
+ * @remarks 业务状态独立于机器人遥测。回调抛错或拒绝不会中断会话或退出清理。
30
+ */
31
+ onAppState?: (state: JsonValue) => void | Promise<void>;
32
+ /**
33
+ * 接收启动或退出错误。
34
+ * @param error - 启动或离场过程中报告的错误。
35
+ */
36
+ onError?: (error: Error) => void;
37
+ /**
38
+ * 接收应用主动离场后的清理完成通知。
39
+ * @param reason - 应用离场原因,包括断线后完成清理的情况。
40
+ * @remarks 应用报告 complete 或由其发起的离场请求完成时触发,调用方此时可卸载 iframe。
41
+ */
42
+ onAppExit?: (reason: string) => void;
43
+ /** 从 start 到业务连接完成的上限,单位 ms,默认 45000;有限数且大于 0、不超过 300000。 */
44
+ timeoutMs?: number;
45
+ /** 等待应用停车受理及释放资源的上限,单位 ms,默认 10000;有限数且大于 0、不超过 300000。 */
46
+ leaveTimeoutMs?: number;
47
+ /** 当前宿主窗口;默认全局 window,可供宿主适配与测试注入。 */
48
+ window?: Window;
49
+ }
50
+ /** 单次应用会话;关闭后重新创建实例,不重用旧页面授权。 */
51
+ export interface AppSession {
52
+ /**
53
+ * 加载 iframe 并等待业务 SDK 报告控制通道就绪。
54
+ * @returns 业务页面确认连接可用时完成。首次能力查询超时且控制通道仍可用时也能完成。重复调用复用本次启动 Promise。
55
+ * @throws 授权、建连、等待超时或启动被离场取消时拒绝 Promise。
56
+ */
57
+ start(): Promise<void>;
58
+ /**
59
+ * 请求业务 SDK 清理资源,并等待其报告 complete。
60
+ * @param reason - 离场原因,默认 host-leave;仅用于生命周期协调。
61
+ * @returns 已确认清理完成时完成;重复离场复用等待,已经关闭时直接完成。
62
+ * @throws 应用报告 failed/timeout、生命周期端口丢失或等待超时时拒绝 Promise。
63
+ * @remarks 清理确认包括必要的停车受理,不代表实体机器人已经停稳。
64
+ */
65
+ leave(reason?: string): Promise<void>;
66
+ /**
67
+ * 请求离场,并在其结束后移除宿主监听器和端口。
68
+ * @returns 离场成功且宿主资源释放后完成;不负责卸载 iframe。
69
+ * @throws 离场失败时仍释放本地监听器,但 Promise 保留该失败,不能当作业务已安全退出。
70
+ */
71
+ dispose(): Promise<void>;
72
+ }
73
+ /**
74
+ * 为一个 iframe 创建凭据交接和生命周期会话。
75
+ * @param options - 可信应用地址、授权提供者与生命周期回调。
76
+ * @returns 会话句柄;调用 start 才加载业务页面,不在宿主中建立机器人连接。
77
+ * @throws 应用身份、来源或等待上限非法时同步抛出 Error。
78
+ */
79
+ export declare function createAppSession(options: AppSessionOptions): AppSession;
@@ -0,0 +1,214 @@
1
+ import { asJson } from "../../../lib/shared/validation.js";
2
+ import { credentials, isMessage, message, origin, timeout } from "./protocol.js";
3
+ /**
4
+ * 为一个 iframe 创建凭据交接和生命周期会话。
5
+ * @param options - 可信应用地址、授权提供者与生命周期回调。
6
+ * @returns 会话句柄;调用 start 才加载业务页面,不在宿主中建立机器人连接。
7
+ * @throws 应用身份、来源或等待上限非法时同步抛出 Error。
8
+ */
9
+ export function createAppSession(options) {
10
+ const hostWindow = options.window ?? window;
11
+ const url = new URL(options.appUrl, hostWindow.location.href);
12
+ const appOrigin = origin(url.origin);
13
+ if (!options.appId.trim() || options.appId.length > 256)
14
+ throw new Error('应用标识无效');
15
+ url.searchParams.set('embedded', '1');
16
+ // URL 中只有入口标志;校验窗口、origin 和 nonce 后定向交接凭据及生命周期端口。
17
+ const bootTimeout = timeout(options.timeoutMs, 45_000);
18
+ const leaveTimeout = timeout(options.leaveTimeoutMs, 10_000);
19
+ let nonce = null;
20
+ let port = null;
21
+ let started = null;
22
+ let leaving = null;
23
+ let resolveStart = null;
24
+ let rejectStart = null;
25
+ let resolveLeave = null;
26
+ let rejectLeave = null;
27
+ let bootTimer;
28
+ let leaveTimer;
29
+ let heartbeat;
30
+ let closed = false;
31
+ let cancelled = false;
32
+ let inFlight = false;
33
+ let credentialWork = null;
34
+ let failureReported = false;
35
+ let credentialsDelivered = false;
36
+ let appReady = false;
37
+ let lastSeen = Date.now();
38
+ function send(type, extra = {}) {
39
+ if (nonce)
40
+ port?.postMessage(message(type, nonce, extra));
41
+ }
42
+ function detach() {
43
+ clearTimeout(bootTimer);
44
+ clearTimeout(leaveTimer);
45
+ clearInterval(heartbeat);
46
+ hostWindow.removeEventListener('message', onMessage);
47
+ hostWindow.removeEventListener('pagehide', onPageHide);
48
+ port?.close();
49
+ port = null;
50
+ }
51
+ function failure(error) {
52
+ cancelled = true;
53
+ if (!failureReported)
54
+ send('leave', { reason: 'host-error' });
55
+ rejectStart?.(error);
56
+ rejectStart = resolveStart = null;
57
+ rejectLeave?.(error);
58
+ rejectLeave = resolveLeave = null;
59
+ clearTimeout(bootTimer);
60
+ clearTimeout(leaveTimer);
61
+ clearInterval(heartbeat);
62
+ if (!failureReported) {
63
+ failureReported = true;
64
+ options.onError?.(error);
65
+ }
66
+ }
67
+ function finish() {
68
+ closed = true;
69
+ cancelled = true;
70
+ rejectStart?.(new Error('应用启动已取消'));
71
+ rejectStart = resolveStart = null;
72
+ resolveLeave?.();
73
+ rejectLeave = resolveLeave = null;
74
+ detach();
75
+ options.onState?.('closed');
76
+ }
77
+ function onPort(event) {
78
+ const data = event.data;
79
+ if (!isMessage(data) || data.nonce !== nonce || closed)
80
+ return;
81
+ lastSeen = Date.now();
82
+ if (data.type === 'ready' && !cancelled) {
83
+ appReady = true;
84
+ clearTimeout(bootTimer);
85
+ resolveStart?.();
86
+ rejectStart = resolveStart = null;
87
+ options.onState?.('ready');
88
+ }
89
+ else if (data.type === 'state' && appReady && !cancelled) {
90
+ try {
91
+ const state = asJson(data.state);
92
+ // 状态展示是可选观察者;非法载荷或渲染异常不能阻断后续离场回执。
93
+ void Promise.resolve(options.onAppState?.(state)).catch(() => { });
94
+ }
95
+ catch {
96
+ // 与 SDK reportAppState 使用相同的 JSON 和字节上限,丢弃不合规状态。
97
+ }
98
+ }
99
+ else if (data.type === 'closed') {
100
+ if (data.result === 'complete') {
101
+ const spontaneous = leaving === null;
102
+ finish();
103
+ if (spontaneous)
104
+ options.onAppExit?.('app-closed');
105
+ }
106
+ else
107
+ failure(new Error('应用退出清理未完成,不能交接机器人'));
108
+ }
109
+ else if (data.type === 'error') {
110
+ failure(new Error('应用直连初始化失败,请检查设备和信令配置'));
111
+ }
112
+ else if (data.type === 'leave-request' && !leaving) {
113
+ const reason = typeof data.reason === 'string' ? data.reason.slice(0, 1024) : 'app-request';
114
+ void leave(reason).then(() => options.onAppExit?.(reason)).catch(() => { });
115
+ }
116
+ }
117
+ function onMessage(event) {
118
+ const data = event.data;
119
+ if (closed || cancelled || !isMessage(data) || data.type !== 'ready' ||
120
+ event.origin !== appOrigin || event.source !== options.iframe.contentWindow)
121
+ return;
122
+ if (nonce !== null || inFlight)
123
+ return;
124
+ nonce = data.nonce;
125
+ inFlight = true;
126
+ credentialWork = (async () => {
127
+ try {
128
+ const bundle = credentials(await options.credentials(), options.appId);
129
+ if (cancelled || closed)
130
+ return;
131
+ const channel = new MessageChannel();
132
+ lastSeen = Date.now();
133
+ port = channel.port1;
134
+ port.onmessage = onPort;
135
+ port.onmessageerror = () => failure(new Error('应用生命周期消息无效'));
136
+ port.start();
137
+ options.iframe.contentWindow.postMessage(message('init', nonce, { credentials: bundle }), appOrigin, [channel.port2]);
138
+ credentialsDelivered = true;
139
+ heartbeat = setInterval(() => {
140
+ if (Date.now() - lastSeen > 10_000) {
141
+ failure(new Error('应用生命周期连接已超时'));
142
+ detach();
143
+ }
144
+ else
145
+ send('ping');
146
+ }, 2000);
147
+ }
148
+ catch {
149
+ failure(new Error('无法交接机器人连接,请检查登录状态及旧连接是否已关闭'));
150
+ }
151
+ })();
152
+ }
153
+ function onPageHide() {
154
+ cancelled = true;
155
+ send('leave', { reason: 'pagehide' });
156
+ // 浏览器卸载不可等待;应用另有 pagehide/心跳清理,不能报告正常退出。
157
+ detach();
158
+ }
159
+ function leave(reason = 'host-leave') {
160
+ if (closed)
161
+ return Promise.resolve();
162
+ if (leaving)
163
+ return leaving;
164
+ cancelled = true;
165
+ clearTimeout(bootTimer);
166
+ options.onState?.('leaving');
167
+ rejectStart?.(new Error('应用启动已取消'));
168
+ rejectStart = resolveStart = null;
169
+ leaving = new Promise((resolve, reject) => {
170
+ resolveLeave = resolve;
171
+ rejectLeave = reject;
172
+ leaveTimer = setTimeout(() => failure(new Error('等待应用退出超时,不能确认机器人已释放')), leaveTimeout);
173
+ // 未下发凭据时没有业务连接;稍后返回的 credentials 也会被丢弃。
174
+ if (!port) {
175
+ if (credentialsDelivered) {
176
+ failure(new Error('应用生命周期连接已丢失,无法确认机器人已释放'));
177
+ return;
178
+ }
179
+ // credentials 可能正在暂停旧 Host;必须等它结束,才能允许宿主恢复发现。
180
+ void (credentialWork ?? Promise.resolve()).then(finish);
181
+ return;
182
+ }
183
+ send('leave', { reason });
184
+ });
185
+ return leaving;
186
+ }
187
+ return {
188
+ start() {
189
+ if (started)
190
+ return started;
191
+ if (closed || cancelled)
192
+ return Promise.reject(new Error('应用会话已关闭'));
193
+ started = new Promise((resolve, reject) => {
194
+ resolveStart = resolve;
195
+ rejectStart = reject;
196
+ options.onState?.('connecting');
197
+ hostWindow.addEventListener('message', onMessage);
198
+ hostWindow.addEventListener('pagehide', onPageHide);
199
+ bootTimer = setTimeout(() => failure(new Error('应用启动超时')), bootTimeout);
200
+ options.iframe.src = url.href;
201
+ });
202
+ return started;
203
+ },
204
+ leave,
205
+ async dispose() {
206
+ try {
207
+ await leave('host-dispose');
208
+ }
209
+ finally {
210
+ detach();
211
+ }
212
+ },
213
+ };
214
+ }
@@ -0,0 +1,20 @@
1
+ import type { DirectConnectionOptions } from '../../../lib/client/direct.ts';
2
+ /** 仅用于直连应用启动和生命周期;不承载机器人动作。 */
3
+ export declare const DIRECT_BOOTSTRAP_SOURCE = "microbotx-direct-bootstrap";
4
+ /** 应用启动与生命周期协议版本。 */
5
+ export declare const DIRECT_BOOTSTRAP_VERSION = 1;
6
+ export declare function message(type: string, nonce: string, extra?: Record<string, unknown>): {
7
+ source: string;
8
+ version: number;
9
+ type: string;
10
+ nonce: string;
11
+ };
12
+ export declare function isMessage(value: unknown): value is Record<string, unknown> & {
13
+ type: string;
14
+ nonce: string;
15
+ };
16
+ /** 精确 HTTP(S) 来源;禁止通配符和 opaque origin。 */
17
+ export declare function origin(value: string): string;
18
+ /** 只传建连白名单字段;不传 signal、回调或任意内部对象。 */
19
+ export declare function credentials(value: unknown, appId?: string): DirectConnectionOptions;
20
+ export declare function timeout(value: number | undefined, fallback: number): number;
@@ -0,0 +1,72 @@
1
+ import { requireOrigin, asJson } from "../../../lib/shared/validation.js";
2
+ /** 仅用于直连应用启动和生命周期;不承载机器人动作。 */
3
+ export const DIRECT_BOOTSTRAP_SOURCE = 'microbotx-direct-bootstrap';
4
+ /** 应用启动与生命周期协议版本。 */
5
+ export const DIRECT_BOOTSTRAP_VERSION = 1;
6
+ export function message(type, nonce, extra = {}) {
7
+ return { source: DIRECT_BOOTSTRAP_SOURCE, version: DIRECT_BOOTSTRAP_VERSION, type, nonce, ...extra };
8
+ }
9
+ export function isMessage(value) {
10
+ if (!value || typeof value !== 'object')
11
+ return false;
12
+ const data = value;
13
+ return data.source === DIRECT_BOOTSTRAP_SOURCE && data.version === DIRECT_BOOTSTRAP_VERSION &&
14
+ typeof data.type === 'string' && typeof data.nonce === 'string' &&
15
+ /^[a-zA-Z0-9-]{16,128}$/.test(data.nonce);
16
+ }
17
+ /** 精确 HTTP(S) 来源;禁止通配符和 opaque origin。 */
18
+ export function origin(value) {
19
+ return requireOrigin(value);
20
+ }
21
+ /** 只传建连白名单字段;不传 signal、回调或任意内部对象。 */
22
+ export function credentials(value, appId) {
23
+ if (!value || typeof value !== 'object')
24
+ throw new Error('缺少直连启动凭据');
25
+ const data = value;
26
+ if (typeof data.url !== 'string' || typeof data.jti !== 'string' || !data.jti || data.jti.length > 8192 ||
27
+ typeof data.sn !== 'string' || !data.sn || data.sn.length > 256) {
28
+ throw new Error('直连启动凭据格式错误');
29
+ }
30
+ const url = new URL(data.url);
31
+ if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
32
+ throw new Error('信令地址必须是不含凭据的 WS(S) 地址');
33
+ }
34
+ const result = { url: url.href, jti: data.jti, sn: data.sn };
35
+ const identity = appId ?? data.appId;
36
+ if (identity !== undefined) {
37
+ if (typeof identity !== 'string' || !identity.trim() || identity.length > 256)
38
+ throw new Error('应用标识无效');
39
+ result.appId = identity;
40
+ }
41
+ if (data.iceServers !== undefined) {
42
+ if (!Array.isArray(data.iceServers))
43
+ throw new Error('ICE 配置无效');
44
+ // 浏览器最终校验 RTCIceServer;先保证只包含可复制的 JSON。
45
+ asJson(data.iceServers);
46
+ result.iceServers = structuredClone(data.iceServers);
47
+ }
48
+ for (const field of ['timeoutMs', 'requestTimeoutMs', 'cleanupTimeoutMs']) {
49
+ const value = data[field];
50
+ if (value !== undefined) {
51
+ if (!Number.isFinite(value) || value <= 0)
52
+ throw new Error(`${field} 必须为正的有限毫秒数`);
53
+ result[field] = value;
54
+ }
55
+ }
56
+ if (data.theme !== undefined) {
57
+ if (data.theme !== 'light' && data.theme !== 'dark')
58
+ throw new Error('主题无效');
59
+ result.theme = data.theme;
60
+ }
61
+ if (data.config !== undefined) {
62
+ asJson(data.config);
63
+ result.config = structuredClone(data.config);
64
+ }
65
+ return result;
66
+ }
67
+ export function timeout(value, fallback) {
68
+ const result = value ?? fallback;
69
+ if (!Number.isFinite(result) || result <= 0 || result > 300_000)
70
+ throw new Error('超时必须为 1~300000 毫秒');
71
+ return result;
72
+ }
@@ -0,0 +1,30 @@
1
+ /** SDK 配套开发网关的上游地址;普通应用和用户无需填写。 */
2
+ export interface HostProxyOptions {
3
+ /** 平台 HTTP(S) 上游地址;默认 https://raydino.ridiculous-ai.com/api,仅由部署方切换。 */
4
+ apiBackend?: string;
5
+ /** 信令 WS(S) 上游地址;默认 wss://raydino.ridiculous-ai.com,仅由部署方切换。 */
6
+ signalingBackend?: string;
7
+ }
8
+ /**
9
+ * 提供 Vite server.proxy 配置,覆盖登录、注册、绑定设备、设备列表和信令。
10
+ *
11
+ * @param options - 可选的上游覆盖配置;地址合法性由使用该配置的开发服务器处理。
12
+ * @returns 可赋给 Vite server.proxy 的路径映射;只有 /ws 启用 WebSocket upgrade。
13
+ * @remarks
14
+ * 默认使用平台线上后端;生产站点由部署网关提供同样的同源路径。
15
+ * 只创建配置,不启动代理或建立网络连接;机器人业务 RPC 与 PCM 不经过此开发网关。
16
+ */
17
+ export declare function createHostProxy(options?: HostProxyOptions): Record<string, {
18
+ /** 该路径对应的 HTTP(S) 或 WS(S) 上游地址。 */
19
+ target: string;
20
+ /** 是否改写请求 Host;生成的规则均为 true。 */
21
+ changeOrigin: boolean;
22
+ /** 是否启用 WebSocket upgrade;仅 /ws 规则设置为 true。 */
23
+ ws?: boolean;
24
+ /**
25
+ * 将同源 /api 请求转为平台模块的路径。
26
+ * @param path - 匹配代理规则的请求路径。
27
+ * @returns 去掉 /api 前缀后的上游路径。
28
+ */
29
+ rewrite?: (path: string) => string;
30
+ }>;