@heybox/hb-sdk 0.9.6-alpha.1 → 0.9.6-alpha.11

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 (54) hide show
  1. package/CHANGELOG.md +86 -5
  2. package/README.md +37 -557
  3. package/dist/cli-chunks/{artifact-C5n7xjnz.cjs → artifact-BW6SD1G6.cjs} +3 -3
  4. package/dist/cli-chunks/{build-BgBt5SkX.cjs → build-B0Id0UTN.cjs} +8 -6
  5. package/dist/cli-chunks/{create-BL6uwtkQ.cjs → create-DVu93Ekp.cjs} +3 -1
  6. package/dist/cli-chunks/{dev-NgklQb6b.cjs → dev-CeSjpEZQ.cjs} +9613 -616
  7. package/dist/cli-chunks/{dev-context-Tf8MgSsu.cjs → dev-context-CVc_BsWR.cjs} +4 -6
  8. package/dist/cli-chunks/{doctor-CGlEf1yi.cjs → doctor-BF9mtkJr.cjs} +3 -1
  9. package/dist/cli-chunks/{games-Cc-DclmK.cjs → games-BKnDCklM.cjs} +3 -1
  10. package/dist/cli-chunks/{index-D9XLBbNV.cjs → index-Cgui_8Rk.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CmxsiTTn.cjs → index-Rp3UMZIO.cjs} +1754 -120
  12. package/dist/cli-chunks/index.esm-BK0eVYaM.cjs +154 -0
  13. package/dist/cli-chunks/{login-ZMBDHBuA.cjs → login-DpeDN-mt.cjs} +3 -3
  14. package/dist/cli-chunks/{project-vite-eM87vX9L.cjs → project-vite-Cg3jYqAJ.cjs} +3 -18
  15. package/dist/cli-chunks/{remote-DVhxpWDg.cjs → remote-BQ-9rhTb.cjs} +12 -21
  16. package/dist/cli-chunks/{runtime-permission-env-q1FWWwbV.cjs → runtime-permission-env-BgipCJ0Z.cjs} +62 -13
  17. package/dist/cli-chunks/{skill-mRXM87hY.cjs → skill-D7pd4yPq.cjs} +3 -2
  18. package/dist/cli-chunks/{version-BqHRI4Lz.cjs → version-DbjRZkb6.cjs} +1 -1
  19. package/dist/cli.cjs +3 -1
  20. package/dist/dev.cjs +1358 -0
  21. package/dist/dev.mjs +1356 -0
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DVlT56iQ.js +100 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BzRxl_MM.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +1 -0
  25. package/dist/devtools/browser-dev-host/assets/index-DY5ZynQp.js +586 -0
  26. package/dist/devtools/browser-dev-host/index.html +3 -3
  27. package/dist/index.cjs.js +232 -114
  28. package/dist/index.esm.js +232 -114
  29. package/dist/miniapp-publish.cjs.js +2 -2
  30. package/dist/miniapp-publish.esm.js +2 -2
  31. package/dist/protocol.cjs.js +5 -0
  32. package/dist/protocol.esm.js +5 -0
  33. package/dist/vite.cjs.js +1060 -203
  34. package/dist/vite.esm.js +1061 -204
  35. package/docs/device-logs.md +39 -22
  36. package/package.json +22 -9
  37. package/skill/skill.json +4 -4
  38. package/types/dev/index.d.cts +386 -0
  39. package/types/dev/index.d.mts +386 -0
  40. package/types/dev/vendor/playwright-core/LICENSE +202 -0
  41. package/types/dev/vendor/playwright-core/NOTICE +5 -0
  42. package/types/dev/vendor/playwright-core/UPSTREAM.json +5 -0
  43. package/types/dev/vendor/playwright-core/types/protocol.d.ts +24776 -0
  44. package/types/dev/vendor/playwright-core/types/structs.d.ts +52 -0
  45. package/types/dev/vendor/playwright-core/types/types.d.ts +27167 -0
  46. package/types/index.d.ts +66 -5
  47. package/types/protocol.d.ts +3 -2
  48. package/types/vite/index.d.ts +5 -4
  49. package/dist/cli-chunks/index.esm-DnyLP_Zc.cjs +0 -5216
  50. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DtWOjzCe.js +0 -103
  51. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-C2Vw0-AC.js +0 -6
  52. package/dist/devtools/browser-dev-host/assets/index-B-rjfibN.js +0 -567
  53. package/dist/devtools/browser-dev-host/assets/index-DSTlrpnQ.css +0 -1
  54. package/docs/runtime-host-migration.md +0 -128
package/dist/dev.cjs ADDED
@@ -0,0 +1,1358 @@
1
+ 'use strict';
2
+
3
+ var promises = require('node:fs/promises');
4
+ var node_crypto = require('node:crypto');
5
+ var path = require('node:path');
6
+ var require$$0 = require('path');
7
+ var require$$1 = require('os');
8
+ var node_fs = require('node:fs');
9
+ var node_child_process = require('node:child_process');
10
+ var node_module = require('node:module');
11
+ var node_util = require('node:util');
12
+
13
+ /** 取消当前等待,不取消共享任务;迟到资源仍由各自 owner 接管和释放。 */
14
+ function awaitWithSignal(work, signal) {
15
+ if (!signal)
16
+ return work;
17
+ return new Promise((resolve, reject) => {
18
+ const abort = () => {
19
+ signal.removeEventListener('abort', abort);
20
+ reject(signal.reason);
21
+ };
22
+ signal.addEventListener('abort', abort, { once: true });
23
+ work.then((value) => {
24
+ signal.removeEventListener('abort', abort);
25
+ resolve(value);
26
+ }, (error) => {
27
+ signal.removeEventListener('abort', abort);
28
+ reject(error);
29
+ });
30
+ if (signal.aborted)
31
+ abort();
32
+ });
33
+ }
34
+
35
+ function getDefaultExportFromCjs (x) {
36
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
37
+ }
38
+
39
+ var envPaths$1 = {exports: {}};
40
+
41
+ var hasRequiredEnvPaths;
42
+
43
+ function requireEnvPaths () {
44
+ if (hasRequiredEnvPaths) return envPaths$1.exports;
45
+ hasRequiredEnvPaths = 1;
46
+ const path = require$$0;
47
+ const os = require$$1;
48
+
49
+ const homedir = os.homedir();
50
+ const tmpdir = os.tmpdir();
51
+ const {env} = process;
52
+
53
+ const macos = name => {
54
+ const library = path.join(homedir, 'Library');
55
+
56
+ return {
57
+ data: path.join(library, 'Application Support', name),
58
+ config: path.join(library, 'Preferences', name),
59
+ cache: path.join(library, 'Caches', name),
60
+ log: path.join(library, 'Logs', name),
61
+ temp: path.join(tmpdir, name)
62
+ };
63
+ };
64
+
65
+ const windows = name => {
66
+ const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
67
+ const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
68
+
69
+ return {
70
+ // Data/config/cache/log are invented by me as Windows isn't opinionated about this
71
+ data: path.join(localAppData, name, 'Data'),
72
+ config: path.join(appData, name, 'Config'),
73
+ cache: path.join(localAppData, name, 'Cache'),
74
+ log: path.join(localAppData, name, 'Log'),
75
+ temp: path.join(tmpdir, name)
76
+ };
77
+ };
78
+
79
+ // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
80
+ const linux = name => {
81
+ const username = path.basename(homedir);
82
+
83
+ return {
84
+ data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
85
+ config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
86
+ cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
87
+ // https://wiki.debian.org/XDGBaseDirectorySpecification#state
88
+ log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
89
+ temp: path.join(tmpdir, username, name)
90
+ };
91
+ };
92
+
93
+ const envPaths = (name, options) => {
94
+ if (typeof name !== 'string') {
95
+ throw new TypeError(`Expected string, got ${typeof name}`);
96
+ }
97
+
98
+ options = Object.assign({suffix: 'nodejs'}, options);
99
+
100
+ if (options.suffix) {
101
+ // Add suffix to prevent possible conflict with native apps
102
+ name += `-${options.suffix}`;
103
+ }
104
+
105
+ if (process.platform === 'darwin') {
106
+ return macos(name);
107
+ }
108
+
109
+ if (process.platform === 'win32') {
110
+ return windows(name);
111
+ }
112
+
113
+ return linux(name);
114
+ };
115
+
116
+ envPaths$1.exports = envPaths;
117
+ // TODO: Remove this for the next major release
118
+ envPaths$1.exports.default = envPaths;
119
+ return envPaths$1.exports;
120
+ }
121
+
122
+ var envPathsExports = requireEnvPaths();
123
+ var envPaths = /*@__PURE__*/getDefaultExportFromCjs(envPathsExports);
124
+
125
+ /** 仅本地开发工具使用,不属于 Mini-program SDK 或 Host wire contract。 */
126
+ const PREVIEW_PATH = '/__hb_sdk__/preview';
127
+ const PREVIEW_SELECTORS = {
128
+ device: '[data-preview-target="device"]',
129
+ screen: '[data-preview-target="screen"]',
130
+ app: '#device iframe',
131
+ workbench: '[data-testid="workbench-root"]',
132
+ };
133
+
134
+ /** 只接受普通对象字面量;null、数组与其它值一律拒绝。 */
135
+ function isRecord(value) {
136
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
137
+ }
138
+
139
+ class DevHostError extends Error {
140
+ code;
141
+ constructor(code, message) {
142
+ super(message);
143
+ this.code = code;
144
+ this.name = 'DevHostError';
145
+ }
146
+ }
147
+ const RECORD_NAME = /^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/;
148
+ const MAX_RECORDS = 128;
149
+ const MAX_JSON_BYTES = 64 * 1024;
150
+ function devHostRegistryDirectory(cacheRoot = process.env.HB_SDK_DEV_HOST_CACHE_DIR ?? envPaths('hb-sdk', { suffix: '' }).cache) {
151
+ return path.join(cacheRoot, 'dev-hosts', 'v1');
152
+ }
153
+ /** 显式端口仍核对实时身份;不要求存在本机登记,也不伪造 PID 和启动时间。 */
154
+ async function connectDevHost(input, options = {}) {
155
+ const projectRoot = await promises.realpath(input.projectRoot);
156
+ const connection = await probePort(input.port, options);
157
+ if (connection.record.projectRoot !== projectRoot) {
158
+ throw new DevHostError('PROJECT_MISMATCH', '指定端口的调试台不属于当前项目,请检查 --port 或运行 hb-sdk dev list');
159
+ }
160
+ return connection;
161
+ }
162
+ /** 隐式目标只允许当前项目唯一的有效登记,绝不选择最近会话或回退固定端口。 */
163
+ async function resolveDevHostConnection(input, options = {}) {
164
+ if (input.port !== undefined)
165
+ return connectDevHost({ projectRoot: input.projectRoot, port: input.port }, options);
166
+ const projectRoot = await promises.realpath(input.projectRoot);
167
+ const candidates = await inspectRegisteredHosts(options, projectRoot);
168
+ if (!candidates.length)
169
+ throw new DevHostError('DEV_HOST_NOT_FOUND', '当前项目没有运行中的调试台,请先运行 hb-sdk dev;可用 hb-sdk dev list 查看本机服务');
170
+ if (candidates.length > 1) {
171
+ const ports = candidates.map(({ listing }) => listing.port).sort((a, b) => a - b).join('、');
172
+ throw new DevHostError('DEV_HOST_AMBIGUOUS', `当前项目存在多个调试台(${ports}),请指定 --port <端口>`);
173
+ }
174
+ const [candidate] = candidates;
175
+ if (!candidate.connection)
176
+ throw new DevHostError('DEV_HOST_UNREACHABLE', `当前项目的调试台 ${candidate.listing.port} 暂不可达,请检查 dev 终端或显式指定 --port`);
177
+ return candidate.connection;
178
+ }
179
+ async function inspectRegisteredHosts(options, projectRoot) {
180
+ const directory = await prepareRegistryDirectory(options);
181
+ if (!directory)
182
+ return [];
183
+ const names = await promises.readdir(directory).catch((error) => {
184
+ if (error.code === 'ENOENT')
185
+ return [];
186
+ throw error;
187
+ });
188
+ const files = names.filter((name) => RECORD_NAME.test(name));
189
+ // 单次只处理有限记录;仍先清理能确认失效的条目,避免崩溃遗留积累后永远无法收敛。
190
+ const batch = files.slice(0, MAX_RECORDS);
191
+ const output = [];
192
+ let index = 0;
193
+ await Promise.all(Array.from({ length: Math.min(8, batch.length) }, async () => {
194
+ while (index < batch.length) {
195
+ const filename = path.join(directory, batch[index++]);
196
+ let record;
197
+ try {
198
+ const info = await promises.lstat(filename);
199
+ if (!info.isFile() || info.size > MAX_JSON_BYTES || (process.getuid && info.uid !== process.getuid()))
200
+ continue;
201
+ record = readRecord(JSON.parse(await promises.readFile(filename, 'utf8')));
202
+ }
203
+ catch {
204
+ // 未完成、损坏或来自不支持版本的文件不参与选路,也不自动删除未知文件。
205
+ continue;
206
+ }
207
+ if (!(options.isProcessAlive ?? isProcessAlive)(record.pid)) {
208
+ await promises.rm(filename, { force: true });
209
+ continue;
210
+ }
211
+ // 查询当前项目时不向其它项目发起握手;全局列表才检查所有在线身份。
212
+ if (projectRoot !== undefined && record.projectRoot !== projectRoot)
213
+ continue;
214
+ try {
215
+ const connection = await probePort(record.port, options);
216
+ if (connection.record.sessionId !== record.sessionId || connection.record.projectRoot !== record.projectRoot || connection.record.appUrl !== record.appUrl || connection.record.previewUrl !== record.previewUrl) {
217
+ await promises.rm(filename, { force: true });
218
+ continue;
219
+ }
220
+ connection.record = { ...connection.record, pid: record.pid, startedAt: record.startedAt };
221
+ output.push({ listing: { ...record, state: 'ready' }, connection });
222
+ }
223
+ catch (error) {
224
+ options.signal?.throwIfAborted();
225
+ if (isConnectionRefused(error)) {
226
+ await promises.rm(filename, { force: true });
227
+ continue;
228
+ }
229
+ output.push({ listing: { ...record, state: 'unreachable' } });
230
+ }
231
+ }
232
+ }));
233
+ if (files.length > MAX_RECORDS)
234
+ throw new DevHostError('DEV_HOST_REGISTRY_FULL', '本机调试台登记过多,已清理本批失效记录;请重试或检查用户缓存');
235
+ return output.sort((a, b) => a.listing.projectRoot.localeCompare(b.listing.projectRoot) || a.listing.port - b.listing.port);
236
+ }
237
+ async function probePort(port, options) {
238
+ validatePort(port);
239
+ const origin = new URL(`http://127.0.0.1:${port}`).origin;
240
+ const fetchImpl = options.fetchImpl ?? fetch;
241
+ const signal = AbortSignal.any([AbortSignal.timeout(options.requestTimeoutMs ?? 1200), ...(options.signal ? [options.signal] : [])]);
242
+ signal.throwIfAborted();
243
+ const bootstrap = await requestJson(fetchImpl, origin + '/__hb_sdk_bootstrap__', { signal });
244
+ if (typeof bootstrap.csrfToken !== 'string' || !bootstrap.csrfToken || bootstrap.csrfToken.length > 512)
245
+ throw new DevHostError('DEV_HOST_INVALID', '目标没有返回有效的调试台握手信息,请重新启动 hb-sdk dev');
246
+ const status = await requestJson(fetchImpl, origin + PREVIEW_PATH, { signal, headers: { origin, 'x-hb-sdk-csrf': bootstrap.csrfToken } });
247
+ const record = readIdentity({ ...status, port });
248
+ if (new URL(record.previewUrl).origin !== origin)
249
+ throw new DevHostError('DEV_HOST_INVALID', '目标调试台返回了不匹配的地址');
250
+ record.projectRoot = await promises.realpath(record.projectRoot);
251
+ return { record, origin, csrfToken: bootstrap.csrfToken, status };
252
+ }
253
+ /** 登记命名空间只接受真实目录,避免 mkdir/chmod 跟随缓存中的软链接。 */
254
+ async function prepareRegistryDirectory(options, create) {
255
+ const directory = devHostRegistryDirectory(options.cacheRoot);
256
+ const root = path.dirname(path.dirname(directory));
257
+ for (const [index, current] of [root, path.join(root, 'dev-hosts'), directory].entries()) {
258
+ let info = await promises.lstat(current).catch((error) => {
259
+ if (error.code === 'ENOENT')
260
+ return undefined;
261
+ throw error;
262
+ });
263
+ if (!info) {
264
+ return;
265
+ }
266
+ if (!info.isDirectory() || info.isSymbolicLink())
267
+ throw new DevHostError('DEV_HOST_REGISTRY_INVALID', '调试台登记目录不能是文件或软链接,请检查用户缓存配置');
268
+ }
269
+ return directory;
270
+ }
271
+ async function requestJson(fetchImpl, url, options) {
272
+ const response = await fetchImpl(url, { ...options, redirect: 'error' });
273
+ if (!response.ok)
274
+ throw new DevHostError('DEV_HOST_UNAVAILABLE', `调试台握手失败:HTTP ${response.status}`);
275
+ const chunks = [];
276
+ let length = 0;
277
+ const reader = response.body?.getReader();
278
+ if (!reader)
279
+ throw new DevHostError('DEV_HOST_INVALID', '调试台没有返回 JSON');
280
+ try {
281
+ while (true) {
282
+ const { done, value } = await reader.read();
283
+ if (done)
284
+ break;
285
+ length += value.length;
286
+ if (length > MAX_JSON_BYTES)
287
+ throw new DevHostError('DEV_HOST_INVALID', '调试台握手结果过大');
288
+ chunks.push(value);
289
+ }
290
+ }
291
+ finally {
292
+ await reader.cancel().catch(() => undefined);
293
+ }
294
+ let parsed;
295
+ try {
296
+ parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
297
+ }
298
+ catch {
299
+ throw new DevHostError('DEV_HOST_INVALID', '调试台返回了无效 JSON');
300
+ }
301
+ if (!isRecord(parsed))
302
+ throw new DevHostError('DEV_HOST_INVALID', '调试台返回了无效 JSON');
303
+ return parsed;
304
+ }
305
+ function readIdentity(value) {
306
+ if (!isRecord(value) || value.schemaVersion !== 1 || typeof value.projectRoot !== 'string' || !path.isAbsolute(value.projectRoot) || typeof value.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(value.sessionId)) {
307
+ throw new DevHostError('DEV_HOST_INVALID', '调试台身份信息无效');
308
+ }
309
+ validatePort(value.port);
310
+ const appUrl = readSafeLocalUrl(value.appUrl, true);
311
+ const previewUrl = readSafeLocalUrl(value.previewUrl);
312
+ if (effectivePort(new URL(previewUrl)) !== value.port)
313
+ throw new DevHostError('DEV_HOST_INVALID', '调试台端口与地址不一致');
314
+ return { schemaVersion: 1, projectRoot: value.projectRoot, sessionId: value.sessionId, appUrl, previewUrl, port: value.port };
315
+ }
316
+ function readRecord(value) {
317
+ const identity = readIdentity(value);
318
+ if (!isRecord(value) || !Number.isInteger(value.pid) || Number(value.pid) <= 0 || Number(value.pid) > 0x7fffffff || typeof value.startedAt !== 'string' || !Number.isFinite(Date.parse(value.startedAt)))
319
+ throw new DevHostError('DEV_HOST_INVALID', '调试台进程记录无效');
320
+ return { ...identity, pid: Number(value.pid), startedAt: value.startedAt };
321
+ }
322
+ function readSafeLocalUrl(value, allowHttps = false) {
323
+ if (typeof value !== 'string' || value.length > 8192)
324
+ throw new DevHostError('DEV_HOST_INVALID', '调试台地址无效');
325
+ let url;
326
+ try {
327
+ url = new URL(value);
328
+ }
329
+ catch {
330
+ throw new DevHostError('DEV_HOST_INVALID', '调试台地址无效');
331
+ }
332
+ if ((url.protocol !== 'http:' && !(allowHttps && url.protocol === 'https:')) || url.hostname !== '127.0.0.1' || url.username || url.password)
333
+ throw new DevHostError('DEV_HOST_INVALID', '调试地址必须是受支持的本机 numeric loopback');
334
+ validatePort(effectivePort(url));
335
+ // 列表只需要可打开的入口;服务会为 / 补齐 mini_url,查询串与 fragment 不落盘。
336
+ url.search = '';
337
+ url.hash = '';
338
+ return url.toString();
339
+ }
340
+ function effectivePort(url) {
341
+ return url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80;
342
+ }
343
+ function validatePort(value) {
344
+ if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65535)
345
+ throw new DevHostError('INVALID_PORT', '调试台端口无效');
346
+ }
347
+ function isProcessAlive(pid) {
348
+ try {
349
+ process.kill(pid, 0);
350
+ return true;
351
+ }
352
+ catch (error) {
353
+ return error.code === 'EPERM';
354
+ }
355
+ }
356
+ function isConnectionRefused(error) {
357
+ if (!error || typeof error !== 'object')
358
+ return false;
359
+ const cause = error;
360
+ return cause.code === 'ECONNREFUSED' || isConnectionRefused(cause.cause) || (Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every(isConnectionRefused));
361
+ }
362
+
363
+ /** CLI 与 Node 连接入口共用项目定位;不加载 Vite、终端交互或日志组件。 */
364
+ function findProjectRoot(startDir) {
365
+ let current = path.resolve(startDir);
366
+ while (true) {
367
+ if (node_fs.existsSync(path.join(current, 'package.json')))
368
+ return current;
369
+ const parent = path.dirname(current);
370
+ if (parent === current)
371
+ throw new Error('当前目录或父目录未找到 package.json');
372
+ current = parent;
373
+ }
374
+ }
375
+
376
+ /** 所有后续读取也携带当前会话凭据,端口被另一进程复用时立即失败。 */
377
+ async function requestDevHost(connection, pathname, options = {}, timeoutMs = 5000) {
378
+ const headers = new Headers(options.headers);
379
+ headers.set('origin', connection.origin);
380
+ headers.set('x-hb-sdk-csrf', connection.csrfToken);
381
+ if (options.body !== undefined)
382
+ headers.set('content-type', 'application/json');
383
+ const timeout = AbortSignal.timeout(timeoutMs);
384
+ const signal = AbortSignal.any([timeout, ...(options.signal ? [options.signal] : [])]);
385
+ try {
386
+ signal.throwIfAborted();
387
+ const response = await fetch(connection.origin + pathname, {
388
+ ...options,
389
+ headers,
390
+ redirect: 'error',
391
+ signal,
392
+ });
393
+ let value;
394
+ try {
395
+ value = await response.json();
396
+ }
397
+ catch (error) {
398
+ signal.throwIfAborted();
399
+ if (!(error instanceof SyntaxError))
400
+ throw error;
401
+ }
402
+ signal.throwIfAborted();
403
+ const result = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
404
+ if (!response.ok) {
405
+ const code = typeof result?.code === 'string' ? result.code : `HTTP_${response.status}`;
406
+ const message = typeof result?.message === 'string' ? result.message : '调试台请求失败,请检查会话后重试';
407
+ throw new DevHostError(code, `${code}: ${message}`);
408
+ }
409
+ if (!result)
410
+ throw new DevHostError('DEV_PROTOCOL_INVALID', '调试台返回了无效的 JSON 对象');
411
+ return result;
412
+ }
413
+ catch (error) {
414
+ // 外部取消保留调用者原因;本层期限和传输异常使用稳定的工具错误码。
415
+ options.signal?.throwIfAborted();
416
+ if (timeout.aborted)
417
+ throw new DevHostError('DEV_TIMEOUT', '调试台请求超时,请用 hb-sdk dev inspect 检查会话');
418
+ if (error instanceof DevHostError)
419
+ throw error;
420
+ throw new DevHostError('DEV_HOST_UNREACHABLE', '调试台连接已中断,请检查 dev 终端后重新连接');
421
+ }
422
+ }
423
+
424
+ /** 固定兼容版本;生产安装不声明 core 依赖,也不下载浏览器。 */
425
+ const PREVIEW_PLAYWRIGHT_VERSION = '1.64.1';
426
+ const execFileAsync = node_util.promisify(node_child_process.execFile);
427
+ const pending = new Map();
428
+ function previewDependencyDirectory(cacheRoot = process.env.HB_SDK_PREVIEW_CACHE_DIR ?? envPaths('hb-sdk', { suffix: '' }).cache) {
429
+ return path.join(cacheRoot, 'preview', 'playwright-core', PREVIEW_PLAYWRIGHT_VERSION);
430
+ }
431
+ /** 安装锁跨进程生效;同版本跨项目复用,失败不留下可加载的半成品。 */
432
+ function loadPreviewPlaywright(options = {}) {
433
+ const directory = previewDependencyDirectory(options.cacheRoot);
434
+ let promise = pending.get(directory);
435
+ if (!promise) {
436
+ promise = loadOrInstall(directory, options).finally(() => pending.delete(directory));
437
+ pending.set(directory, promise);
438
+ }
439
+ return promise;
440
+ }
441
+ async function readInstalled(directory) {
442
+ try {
443
+ const ready = JSON.parse(await promises.readFile(path.join(directory, 'ready.json'), 'utf8'));
444
+ const manifest = JSON.parse(await promises.readFile(path.join(directory, 'node_modules/playwright-core/package.json'), 'utf8'));
445
+ if (ready.version !== PREVIEW_PLAYWRIGHT_VERSION || manifest.version !== PREVIEW_PLAYWRIGHT_VERSION)
446
+ return;
447
+ const requireFromCache = node_module.createRequire(path.join(directory, 'package.json'));
448
+ const module = requireFromCache('playwright-core');
449
+ if (typeof module.chromium?.connectOverCDP === 'function')
450
+ return module;
451
+ }
452
+ catch {
453
+ /* 缺失或不完整时在锁内重建。 */
454
+ }
455
+ }
456
+ async function loadOrInstall(directory, options) {
457
+ const cached = await readInstalled(directory);
458
+ if (cached)
459
+ return cached;
460
+ await promises.mkdir(path.dirname(directory), { recursive: true });
461
+ const lock = directory + '.lock';
462
+ const owner = `${process.pid}:${node_crypto.randomUUID()}`;
463
+ const deadline = Date.now() + 180_000;
464
+ while (true) {
465
+ try {
466
+ await promises.mkdir(lock);
467
+ await promises.writeFile(path.join(lock, 'owner'), owner);
468
+ break;
469
+ }
470
+ catch (error) {
471
+ if (error.code !== 'EEXIST')
472
+ throw error;
473
+ const installed = await readInstalled(directory);
474
+ if (installed)
475
+ return installed;
476
+ // 安装进程异常退出后可安全重试;EPERM 表示进程仍存在。
477
+ try {
478
+ const previous = await promises.readFile(path.join(lock, 'owner'), 'utf8');
479
+ const pid = Number(previous.split(':')[0]);
480
+ if (Number.isInteger(pid) && pid > 0) {
481
+ try {
482
+ process.kill(pid, 0);
483
+ }
484
+ catch (cause) {
485
+ if (cause.code === 'ESRCH') {
486
+ if ((await promises.readFile(path.join(lock, 'owner'), 'utf8')) === previous)
487
+ await promises.rm(lock, { recursive: true, force: true });
488
+ }
489
+ }
490
+ }
491
+ }
492
+ catch {
493
+ // 极少数进程在 mkdir 后、写 owner 前退出;只回收已超过安装时限的空锁。
494
+ const age = await promises.stat(lock)
495
+ .then((info) => Date.now() - info.mtimeMs)
496
+ .catch(() => 0);
497
+ if (age > 180_000)
498
+ await promises.rm(lock, { recursive: true, force: true });
499
+ }
500
+ if (Date.now() >= deadline)
501
+ throw new Error('等待预览依赖安装超时,请稍后重试');
502
+ await new Promise((resolve) => setTimeout(resolve, 200));
503
+ }
504
+ }
505
+ const staging = `${directory}.tmp-${node_crypto.randomUUID()}`;
506
+ try {
507
+ const installed = await readInstalled(directory);
508
+ if (installed)
509
+ return installed;
510
+ options.progress?.(`首次使用预览能力,正在安装 playwright-core@${PREVIEW_PLAYWRIGHT_VERSION}(不下载浏览器)`);
511
+ await promises.mkdir(staging);
512
+ await promises.writeFile(path.join(staging, 'package.json'), JSON.stringify({ private: true }));
513
+ await (options.install ?? installPlaywright)(staging);
514
+ const manifest = JSON.parse(await promises.readFile(path.join(staging, 'node_modules/playwright-core/package.json'), 'utf8'));
515
+ if (manifest.version !== PREVIEW_PLAYWRIGHT_VERSION)
516
+ throw new Error('预览依赖版本校验失败');
517
+ await promises.writeFile(path.join(staging, 'ready.json'), JSON.stringify({ version: PREVIEW_PLAYWRIGHT_VERSION }));
518
+ // 暂存目录不能提前 require:core 内部的延迟 require 必须以晋升后的路径为基准。
519
+ await promises.access(path.join(staging, 'node_modules/playwright-core', manifest.main ?? 'index.js'));
520
+ await promises.rm(directory, { recursive: true, force: true });
521
+ await promises.rename(staging, directory);
522
+ const result = await readInstalled(directory);
523
+ if (!result)
524
+ throw new Error('无法加载已安装的预览依赖');
525
+ return result;
526
+ }
527
+ finally {
528
+ await promises.rm(staging, { recursive: true, force: true });
529
+ if ((await promises.readFile(path.join(lock, 'owner'), 'utf8').catch(() => '')) === owner)
530
+ await promises.rm(lock, { recursive: true, force: true });
531
+ }
532
+ }
533
+ async function installPlaywright(directory) {
534
+ const args = [
535
+ 'install',
536
+ '--prefix',
537
+ directory,
538
+ '--save-exact',
539
+ '--ignore-scripts',
540
+ '--no-audit',
541
+ '--no-fund',
542
+ `playwright-core@${PREVIEW_PLAYWRIGHT_VERSION}`,
543
+ ];
544
+ // Windows 的 npm.cmd 不能直接 execFile;通过 Node 执行 npm CLI,始终不经过 shell。
545
+ const npmCli = process.env.npm_execpath?.endsWith('npm-cli.js')
546
+ ? process.env.npm_execpath
547
+ : process.platform === 'win32'
548
+ ? path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js')
549
+ : undefined;
550
+ try {
551
+ await execFileAsync(npmCli ? process.execPath : 'npm', npmCli ? [npmCli, ...args] : args, {
552
+ cwd: directory,
553
+ timeout: 120_000,
554
+ maxBuffer: 1024 * 1024,
555
+ windowsHide: true,
556
+ });
557
+ }
558
+ catch {
559
+ // npm 输出可能包含私有 registry 凭据,不将原始 stdout/stderr 写入错误或 JSON。
560
+ throw new Error('安装预览依赖失败,请检查 npm、registry 和网络后重试;已有人工预览不受影响');
561
+ }
562
+ }
563
+
564
+ /**
565
+ * 有界等待:超过 timeoutMs 后由 onTimeout 决定结果(返回或抛错)。
566
+ * 计时器总会清理,迟到结果由调用方按需接管。
567
+ */
568
+ async function waitBounded(work, timeoutMs, onTimeout) {
569
+ let timer;
570
+ try {
571
+ return await Promise.race([
572
+ work,
573
+ new Promise((resolve, reject) => {
574
+ timer = setTimeout(() => {
575
+ try {
576
+ resolve(onTimeout());
577
+ }
578
+ catch (error) {
579
+ reject(error);
580
+ }
581
+ }, timeoutMs);
582
+ }),
583
+ ]);
584
+ }
585
+ finally {
586
+ clearTimeout(timer);
587
+ }
588
+ }
589
+
590
+ class PreviewTargetError extends Error {
591
+ code;
592
+ name = 'PreviewError';
593
+ constructor(code, message) {
594
+ super(message);
595
+ this.code = code;
596
+ }
597
+ }
598
+ /** 只按浏览器登记的 targetId 认领 Page;不按 URL、顺序或同地址副本猜测。 */
599
+ async function findPreviewPage(connection, targetId, signal, timeoutMs = 10_000) {
600
+ signal?.throwIfAborted();
601
+ if (!targetId)
602
+ throw unavailable();
603
+ const timeout = new AbortController();
604
+ const deadline = setTimeout(() => timeout.abort(unavailable()), timeoutMs);
605
+ const operationSignal = AbortSignal.any([timeout.signal, ...(signal ? [signal] : [])]);
606
+ try {
607
+ while (true) {
608
+ operationSignal.throwIfAborted();
609
+ if (!connection.isConnected())
610
+ throw disconnected();
611
+ for (const page of connection.contexts().flatMap((context) => context.pages())) {
612
+ operationSignal.throwIfAborted();
613
+ let session;
614
+ let matched = false;
615
+ try {
616
+ const attaching = page
617
+ .context()
618
+ .newCDPSession(page)
619
+ .then((value) => {
620
+ if (operationSignal.aborted)
621
+ void value.detach().catch(() => undefined);
622
+ return value;
623
+ });
624
+ session = await awaitWithSignal(attaching, operationSignal);
625
+ const result = await awaitWithSignal(session.send('Target.getTargetInfo'), operationSignal);
626
+ matched = isRecord(result) && isRecord(result.targetInfo) && result.targetInfo.targetId === targetId;
627
+ }
628
+ catch {
629
+ operationSignal.throwIfAborted();
630
+ if (!connection.isConnected())
631
+ throw disconnected();
632
+ // 已关闭或无法附加的候选不会变成替代目标,继续核对其它 Page 的精确 ID。
633
+ }
634
+ finally {
635
+ if (session)
636
+ await boundedDetach(session);
637
+ }
638
+ operationSignal.throwIfAborted();
639
+ if (matched)
640
+ return page;
641
+ }
642
+ await awaitWithSignal(new Promise((resolve) => setTimeout(resolve, 100)), operationSignal);
643
+ }
644
+ }
645
+ finally {
646
+ clearTimeout(deadline);
647
+ }
648
+ }
649
+ function unavailable() {
650
+ return new PreviewTargetError('PAGE_UNAVAILABLE', '本次调试标签页不可用,请运行 hb-sdk dev preview open 后重试');
651
+ }
652
+ function disconnected() {
653
+ return new PreviewTargetError('BROWSER_CLOSED', '预览浏览器连接已断开,请重新打开窗口');
654
+ }
655
+ async function boundedDetach(session) {
656
+ await waitBounded(session.detach().catch(() => undefined), 250, () => undefined);
657
+ }
658
+ /** 只核验精确命中的自有 target 内容,不通过 URL 寻找或认领页面。 */
659
+ function isPreviewDocumentUrl(actual, expected) {
660
+ try {
661
+ const current = new URL(String(actual));
662
+ const preview = new URL(expected);
663
+ return (current.origin === preview.origin &&
664
+ current.pathname === preview.pathname &&
665
+ current.searchParams.get('mini_url') === preview.searchParams.get('mini_url'));
666
+ }
667
+ catch {
668
+ return false;
669
+ }
670
+ }
671
+
672
+ /** 当前客户端无法确认焦点模拟的创建或释放;调用方应断开自己的控制连接兜底。 */
673
+ class PreviewFocusError extends Error {
674
+ code;
675
+ name = 'PreviewError';
676
+ constructor(code, message) {
677
+ super(message);
678
+ this.code = code;
679
+ }
680
+ }
681
+ /**
682
+ * 只为调用方已核验的 SDK Page 持有一份交互焦点模拟。
683
+ * 原生 Chrome 按 CDP session 聚合状态;释放只 detach 自己的 session,不显式关掉其他客户端的模拟。
684
+ */
685
+ async function acquirePreviewFocus(page, signal) {
686
+ signal?.throwIfAborted();
687
+ let session;
688
+ let releasing;
689
+ const release = () => {
690
+ if (!session)
691
+ return Promise.resolve();
692
+ return (releasing ??= detachFocus(session));
693
+ };
694
+ try {
695
+ const attaching = page
696
+ .context()
697
+ .newCDPSession(page)
698
+ .then(async (value) => {
699
+ session = value;
700
+ if (signal?.aborted) {
701
+ await release().catch(() => undefined);
702
+ signal.throwIfAborted();
703
+ }
704
+ return value;
705
+ });
706
+ const client = await awaitWithSignal(attaching, signal);
707
+ signal?.throwIfAborted();
708
+ await awaitWithSignal(client.send('Emulation.setFocusEmulationEnabled', { enabled: true }), signal);
709
+ signal?.throwIfAborted();
710
+ return release;
711
+ }
712
+ catch {
713
+ let cleanupFailed = false;
714
+ try {
715
+ await release();
716
+ }
717
+ catch {
718
+ cleanupFailed = true;
719
+ }
720
+ signal?.throwIfAborted();
721
+ if (cleanupFailed)
722
+ throw releaseFailed();
723
+ throw new PreviewFocusError('PREVIEW_FOCUS_UNAVAILABLE', '无法为当前 SDK 预览启用交互焦点模拟,请重新打开预览后重试');
724
+ }
725
+ }
726
+ async function detachFocus(session) {
727
+ try {
728
+ // detach 的同步异常同样按释放失败处理,不向调用方泄露原始协议细节。
729
+ await waitBounded(Promise.resolve().then(() => session.detach()), 500, () => {
730
+ throw releaseFailed();
731
+ });
732
+ }
733
+ catch {
734
+ throw releaseFailed();
735
+ }
736
+ }
737
+ function releaseFailed() {
738
+ return new PreviewFocusError('PREVIEW_FOCUS_RELEASE_FAILED', '未能确认交互焦点模拟已释放,请断开当前控制客户端后重新连接');
739
+ }
740
+
741
+ /**
742
+ * 在 Node.js 中连接当前项目已打开的共享预览,返回原生 Playwright 对象。
743
+ *
744
+ * @param connection - 已核验并固定的开发会话。
745
+ * @param options - 取消信号、焦点模拟和连接预算。
746
+ * @returns 精确绑定当前预览目标的 Page、动态 FrameLocator、会话快照和断连函数。
747
+ * @remarks
748
+ * 调用前需要运行 `hb-sdk dev` 并打开预览。本函数不会启动服务、打开页面或重播操作。
749
+ * 首次使用时按需安装固定版本控制库到用户缓存,不下载浏览器;共享安装有自己的有限期限,
750
+ * 不占用 `timeoutMs`,但取消后不会继续建立连接。返回前会再次核验原服务与 target 身份。
751
+ * `page` 不会在服务重启或标签页关闭后自动迁移;需要重新调用本函数。
752
+ * 原生 Playwright 操作的等待和取消由调用方自行指定,结束后应在 finally 中断连。
753
+ * 默认仅对精确 SDK Page 启用交互焦点模拟,让后台窗口的动画帧、点击与截图可以正常等待。
754
+ * 模拟会影响 document.visibilityState,并可能触发 visibilitychange;不会抢占系统焦点或修改其他页面、媒体设置。
755
+ * 多个客户端分别持有自己的模拟,disconnect 只释放本连接;需要观察真实生命周期时传 emulateFocus: false。
756
+ * @throws 目标缺失、会话变化、版本不兼容或超时时抛出带 `code` 和操作指引的 Error;取消时抛出 signal.reason。
757
+ * @example
758
+ * ```ts
759
+ * import { connectDevSession } from '@heybox/hb-sdk/dev';
760
+ *
761
+ * const dev = await connectDevSession();
762
+ * const preview = await dev.preview.connect();
763
+ * try {
764
+ * await preview.app.locator('body').screenshot({ path: 'app.png' });
765
+ * } finally {
766
+ * await preview.disconnect();
767
+ * }
768
+ * ```
769
+ * @since 0.9.6
770
+ */
771
+ async function connectPreviewBrowser(connection, options = {}) {
772
+ validateOptions(options);
773
+ options.signal?.throwIfAborted();
774
+ const budget = connectionBudget(options.timeoutMs ?? 30_000, options.signal);
775
+ const { signal } = budget;
776
+ const wait = async (work) => {
777
+ const value = await awaitWithSignal(work, signal);
778
+ budget.check();
779
+ return value;
780
+ };
781
+ let browser;
782
+ let releaseFocus;
783
+ let closing;
784
+ const disconnect = () => {
785
+ if (!browser)
786
+ return Promise.resolve();
787
+ // connectOverCDP 的 Browser.close 仅释放本客户端;不关闭 page、context 或所属浏览器 lease。
788
+ return (closing ??= Promise.resolve().then(async () => {
789
+ // 即使 detach 未获确认,随后关闭自己的 client 仍会释放该 client 的 CDP sessions。
790
+ try {
791
+ await releaseFocus?.();
792
+ }
793
+ catch {
794
+ /* 只断开本客户端兜底,不覆盖其他客户端的焦点状态。 */
795
+ }
796
+ finally {
797
+ await browser.close();
798
+ }
799
+ }));
800
+ };
801
+ try {
802
+ const projectRoot = connection.record.projectRoot;
803
+ const status = await wait(requestDevHost(connection, PREVIEW_PATH, { signal }, Math.min(5000, budget.remaining())));
804
+ const expected = await wait(readSnapshot(status, connection));
805
+ const validateCurrent = async () => {
806
+ let value;
807
+ try {
808
+ value = await wait(requestDevHost(connection, PREVIEW_PATH, { signal }, Math.min(5000, budget.remaining())));
809
+ }
810
+ catch {
811
+ signal.throwIfAborted();
812
+ throw failure('PREVIEW_SESSION_CHANGED', '当前调试台已不可用或会话已变化,请检查 dev 终端并重新调用 dev.preview.connect()');
813
+ }
814
+ const current = await wait(readSnapshot(value, connection));
815
+ if (current.targetId !== expected.targetId || current.endpoint !== expected.endpoint || current.previewUrl !== expected.previewUrl) {
816
+ throw failure('PREVIEW_TARGET_CHANGED', '预览目标已变化,请重新调用 dev.preview.connect();如页面已关闭,请先运行 hb-sdk dev preview open');
817
+ }
818
+ };
819
+ await validateCurrent();
820
+ budget.pause();
821
+ let driver;
822
+ try {
823
+ driver = await wait(loadPreviewPlaywright());
824
+ }
825
+ catch {
826
+ signal.throwIfAborted();
827
+ throw failure('DEPENDENCY_UNAVAILABLE', '无法加载固定版本预览控制库,请运行 hb-sdk dev preview setup 后重新连接');
828
+ }
829
+ budget.resume();
830
+ await validateCurrent();
831
+ const connecting = driver.chromium
832
+ .connectOverCDP(expected.endpoint, { noDefaults: true, timeout: budget.remaining() })
833
+ .then(async (connection) => {
834
+ // 唯一动态适配边界:loader 已校验固定版本,真实对象是该官方版本的 Browser。
835
+ browser = connection;
836
+ if (signal.aborted) {
837
+ await disconnect().catch(() => undefined);
838
+ signal.throwIfAborted();
839
+ }
840
+ return browser;
841
+ });
842
+ const client = await wait(connecting);
843
+ const page = await wait(findPreviewPage(client, expected.targetId, signal, budget.remaining()));
844
+ await validateCurrent();
845
+ signal.throwIfAborted();
846
+ assertPreviewContent(page, expected.previewUrl);
847
+ if (options.emulateFocus !== false) {
848
+ await wait(acquirePreviewFocus(page, signal).then(async (release) => {
849
+ releaseFocus = release;
850
+ if (signal.aborted) {
851
+ await release().catch(() => undefined);
852
+ signal.throwIfAborted();
853
+ }
854
+ }));
855
+ await validateCurrent();
856
+ budget.check();
857
+ assertPreviewContent(page, expected.previewUrl);
858
+ }
859
+ return {
860
+ page,
861
+ app: page.frameLocator(PREVIEW_SELECTORS.app),
862
+ session: { id: connection.record.sessionId, projectRoot, port: connection.record.port, cdpTargetId: expected.targetId },
863
+ disconnect,
864
+ };
865
+ }
866
+ catch (error) {
867
+ await disconnect().catch(() => undefined);
868
+ signal.throwIfAborted();
869
+ if (error instanceof PreviewConnectionError || error instanceof PreviewFocusError || error instanceof DevHostError)
870
+ throw error;
871
+ if (isRecord(error) && (error.code === 'PAGE_UNAVAILABLE' || error.code === 'BROWSER_CLOSED')) {
872
+ throw failure(String(error.code), '当前预览标签页不可用,请运行 hb-sdk dev preview open 后重新调用 dev.preview.connect()');
873
+ }
874
+ throw failure('PREVIEW_CONNECT_FAILED', '连接预览失败,请用 hb-sdk dev inspect 检查当前窗口,再重新调用 dev.preview.connect()');
875
+ }
876
+ finally {
877
+ budget.dispose();
878
+ }
879
+ }
880
+ class PreviewConnectionError extends Error {
881
+ code;
882
+ name = 'PreviewConnectionError';
883
+ constructor(code, message) {
884
+ super(message);
885
+ this.code = code;
886
+ }
887
+ }
888
+ function failure(code, message) {
889
+ return new PreviewConnectionError(code, message);
890
+ }
891
+ function incompatible() {
892
+ return failure('PREVIEW_INCOMPATIBLE', '调试台控制协议或固定驱动版本不兼容,请升级 SDK 并重新运行 hb-sdk dev');
893
+ }
894
+ async function readSnapshot(value, connection) {
895
+ if (value.schemaVersion !== 1 || !isRecord(value.playwright) || value.playwright.version !== PREVIEW_PLAYWRIGHT_VERSION)
896
+ throw incompatible();
897
+ const { projectRoot } = connection.record;
898
+ const actualRoot = typeof value.projectRoot === 'string' ? await promises.realpath(value.projectRoot).catch(() => undefined) : undefined;
899
+ if (value.sessionId !== connection.record.sessionId || actualRoot !== projectRoot) {
900
+ throw failure('PREVIEW_SESSION_CHANGED', '当前调试台已不属于原项目或会话,请重新调用 dev.preview.connect()');
901
+ }
902
+ if (!isRecord(value.browser))
903
+ throw incompatible();
904
+ if (value.browser.state !== 'ready') {
905
+ const uncertain = isRecord(value.browser.openError) && value.browser.openError.code === 'TARGET_CREATION_UNCONFIRMED';
906
+ throw failure('PREVIEW_NOT_OPEN', uncertain
907
+ ? '尚无法确认预览页,请先检查浏览器,再运行 hb-sdk dev preview open,随后重新连接'
908
+ : '当前项目尚未打开可连接的预览页,请先运行 hb-sdk dev preview open');
909
+ }
910
+ const endpoint = value.browser.cdpEndpoint;
911
+ const targetId = value.browser.cdpTargetId;
912
+ if (typeof endpoint !== 'string' ||
913
+ typeof targetId !== 'string' ||
914
+ !targetId.trim() ||
915
+ targetId.length > 512 ||
916
+ typeof value.previewUrl !== 'string')
917
+ throw incompatible();
918
+ let url;
919
+ let previewUrl;
920
+ try {
921
+ url = new URL(endpoint);
922
+ previewUrl = new URL(value.previewUrl);
923
+ }
924
+ catch {
925
+ throw incompatible();
926
+ }
927
+ if (!['http:', 'ws:'].includes(url.protocol) || url.hostname !== '127.0.0.1' || url.username || url.password || url.hash)
928
+ throw incompatible();
929
+ if (previewUrl.origin !== new URL(connection.origin).origin || previewUrl.username || previewUrl.password)
930
+ throw incompatible();
931
+ return { endpoint, targetId, previewUrl: previewUrl.toString() };
932
+ }
933
+ function assertPreviewContent(page, expectedUrl) {
934
+ if (isPreviewDocumentUrl(page.url(), expectedUrl))
935
+ return;
936
+ throw failure('PREVIEW_PAGE_CHANGED', '本次预览标签页已离开调试台,请运行 hb-sdk dev preview open 后重新调用 dev.preview.connect()');
937
+ }
938
+ function validateOptions(options) {
939
+ if (!options || typeof options !== 'object' || Array.isArray(options))
940
+ throw failure('INVALID_OPTIONS', '连接选项必须是对象');
941
+ if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 2_147_483_647))
942
+ throw failure('INVALID_TIMEOUT', 'timeoutMs 必须是有效的正整数毫秒数');
943
+ if (options.signal !== undefined &&
944
+ (!options.signal ||
945
+ typeof options.signal.addEventListener !== 'function' ||
946
+ typeof options.signal.throwIfAborted !== 'function' ||
947
+ typeof options.signal.aborted !== 'boolean'))
948
+ throw failure('INVALID_SIGNAL', 'signal 必须是 Node.js AbortSignal');
949
+ if (options.emulateFocus !== undefined && typeof options.emulateFocus !== 'boolean')
950
+ throw failure('INVALID_FOCUS', 'emulateFocus 必须是 boolean');
951
+ }
952
+ function connectionBudget(timeoutMs, external) {
953
+ const expired = new AbortController();
954
+ let signal;
955
+ try {
956
+ signal = AbortSignal.any([expired.signal, ...(external ? [external] : [])]);
957
+ }
958
+ catch {
959
+ throw failure('INVALID_SIGNAL', 'signal 必须是 Node.js AbortSignal');
960
+ }
961
+ let remaining = timeoutMs;
962
+ let deadlineAt = Date.now() + remaining;
963
+ let timer;
964
+ const start = () => {
965
+ deadlineAt = Date.now() + remaining;
966
+ timer = setTimeout(() => expired.abort(failure('PREVIEW_TIMEOUT', '连接预览超时,请检查 dev 终端;首次使用可先运行 hb-sdk dev preview setup')), remaining);
967
+ };
968
+ const check = () => {
969
+ if (timer !== undefined && Date.now() >= deadlineAt)
970
+ expired.abort(failure('PREVIEW_TIMEOUT', '连接预览超时,请检查 dev 终端后重新连接'));
971
+ signal.throwIfAborted();
972
+ };
973
+ start();
974
+ return {
975
+ signal,
976
+ check,
977
+ remaining() {
978
+ check();
979
+ return Math.max(1, deadlineAt - Date.now());
980
+ },
981
+ pause() {
982
+ check();
983
+ remaining = Math.max(1, deadlineAt - Date.now());
984
+ clearTimeout(timer);
985
+ timer = undefined;
986
+ },
987
+ resume() {
988
+ check();
989
+ start();
990
+ },
991
+ dispose() {
992
+ clearTimeout(timer);
993
+ },
994
+ };
995
+ }
996
+
997
+ /** 本机开发工具合同,不属于 Mini-program bridge 协议。 */
998
+ const DEV_DIAGNOSTICS_PATH = '/__hb_sdk__/diagnostics';
999
+ const DEV_RESOURCE_PATH = '/__hb_sdk__/resources';
1000
+ const DEV_DIAGNOSTICS_SCHEMA_VERSION = 3;
1001
+ const DEV_SANDBOX_READ_MAX_BYTES = 16 * 1024;
1002
+
1003
+ /**
1004
+ * 连接当前项目的开发会话,复用与 CLI 相同的发现、身份核验和 HTTP 查询。
1005
+ *
1006
+ * @remarks 此步及 inspect/logs 不加载 Playwright 或改变焦点。只有 preview.connect 才按需准备控制库。
1007
+ * @example
1008
+ * ```ts
1009
+ * import { connectDevSession } from '@heybox/hb-sdk/dev';
1010
+ * const dev = await connectDevSession();
1011
+ * const preview = await dev.preview.connect();
1012
+ * try {
1013
+ * await dev.waitForRuntime({ timeoutMs: 30_000 });
1014
+ * await preview.app.getByRole('button', { name: '环境信息' }).click();
1015
+ * }
1016
+ * finally { await preview.disconnect(); }
1017
+ * ```
1018
+ * @since 0.9.6
1019
+ */
1020
+ async function connectDevSession(options = {}) {
1021
+ if (!options || typeof options !== 'object' || Array.isArray(options))
1022
+ throw new DevHostError('INVALID_OPTIONS', '开发会话选项必须是对象');
1023
+ const input = { ...options };
1024
+ if (input.projectRoot !== undefined && (typeof input.projectRoot !== 'string' || !input.projectRoot.trim()))
1025
+ throw new DevHostError('INVALID_PROJECT_ROOT', 'projectRoot 必须是非空目录');
1026
+ if (input.port !== undefined && (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535))
1027
+ throw new DevHostError('INVALID_PORT', '调试台端口无效');
1028
+ const operation = requestBudget(input);
1029
+ try {
1030
+ let projectRoot;
1031
+ try {
1032
+ projectRoot = await awaitWithSignal(promises.realpath(findProjectRoot(input.projectRoot ?? process.cwd())), operation.signal);
1033
+ }
1034
+ catch {
1035
+ operation.signal.throwIfAborted();
1036
+ throw new DevHostError('PROJECT_NOT_FOUND', '未找到项目,请在小程序项目目录中运行或指定 projectRoot');
1037
+ }
1038
+ const connection = await awaitWithSignal(resolveDevHostConnection({ projectRoot, port: input.port }, { requestTimeoutMs: operation.remaining(), signal: operation.signal }), operation.signal);
1039
+ return createDevSession(connection, input.signal);
1040
+ }
1041
+ finally {
1042
+ operation.dispose();
1043
+ }
1044
+ }
1045
+ /** CLI 与 Node 共用固定连接,禁止每次操作重新发现并静默迁移到新服务。 */
1046
+ function createDevSession(connection, sessionSignal) {
1047
+ const request = async (pathname, options = {}, init = {}) => {
1048
+ const operation = requestBudget(options, sessionSignal);
1049
+ try {
1050
+ return await requestDevHost(connection, pathname, { ...init, signal: operation.signal }, operation.remaining());
1051
+ }
1052
+ finally {
1053
+ operation.dispose();
1054
+ }
1055
+ };
1056
+ const check = (value) => {
1057
+ if (value.schemaVersion !== DEV_DIAGNOSTICS_SCHEMA_VERSION)
1058
+ throw new DevHostError('DEV_PROTOCOL_INCOMPATIBLE', '开发会话诊断协议不兼容,请升级 SDK 并重启 hb-sdk dev');
1059
+ if (value.sessionId !== connection.record.sessionId)
1060
+ throw new DevHostError('DEV_SESSION_CHANGED', '开发会话已变化,请重新调用 connectDevSession');
1061
+ };
1062
+ const inspect = async (options = {}) => {
1063
+ const operation = requestBudget(options, sessionSignal);
1064
+ try {
1065
+ // 先固定预算再启动并发请求;不能在首个 Promise 启动后同步抛错,留下无人接管的拒绝。
1066
+ const timeoutMs = operation.remaining();
1067
+ const [preview, diagnostics] = await Promise.all([
1068
+ requestDevHost(connection, PREVIEW_PATH, { signal: operation.signal }, timeoutMs),
1069
+ requestDevHost(connection, DEV_DIAGNOSTICS_PATH + '?mode=inspect', { signal: operation.signal }, timeoutMs),
1070
+ ]);
1071
+ operation.remaining();
1072
+ check(diagnostics);
1073
+ if (preview.sessionId !== connection.record.sessionId || preview.projectRoot !== connection.record.projectRoot)
1074
+ throw new DevHostError('DEV_SESSION_CHANGED', '开发会话已变化,请重新连接');
1075
+ if (!Array.isArray(diagnostics.targets) ||
1076
+ !Array.isArray(diagnostics.instances) ||
1077
+ !Number.isSafeInteger(diagnostics.nextCursor) ||
1078
+ typeof diagnostics.epoch !== 'string')
1079
+ throw new DevHostError('DEV_PROTOCOL_INVALID', '开发会话返回了无效状态');
1080
+ return { ...preview, ...diagnostics };
1081
+ }
1082
+ finally {
1083
+ operation.dispose();
1084
+ }
1085
+ };
1086
+ const resolveSelection = async (selection, options) => {
1087
+ if (selection.instanceId !== undefined)
1088
+ return { instanceId: selection.instanceId };
1089
+ const snapshot = await inspect(options);
1090
+ const target = selection.targetId === undefined ? snapshot.primaryTarget : snapshot.targets.find((item) => item.targetId === selection.targetId);
1091
+ if (!target)
1092
+ throw new DevHostError('DEV_TARGET_NOT_FOUND', '目标不存在,请用 dev inspect 查看 targets');
1093
+ if (!target.currentInstanceId)
1094
+ throw new DevHostError('RUNTIME_NOT_STARTED', '该目标尚无当前实例,请查看 dev inspect');
1095
+ return { targetId: target.targetId, instanceId: target.currentInstanceId };
1096
+ };
1097
+ const logs = async (filters = {}) => {
1098
+ validateSelection(filters);
1099
+ const params = logParameters(filters);
1100
+ const value = await request(DEV_DIAGNOSTICS_PATH + '?' + params, filters);
1101
+ check(value);
1102
+ if (!Array.isArray(value.items) ||
1103
+ !Number.isSafeInteger(value.nextCursor) ||
1104
+ typeof value.epoch !== 'string' ||
1105
+ typeof value.hasMore !== 'boolean' ||
1106
+ typeof value.gap !== 'boolean')
1107
+ throw new DevHostError('DEV_PROTOCOL_INVALID', '开发会话返回了无效日志页');
1108
+ return value;
1109
+ };
1110
+ const projection = async (filters, kind) => {
1111
+ validateSelection(filters);
1112
+ logParameters(filters);
1113
+ const operation = requestBudget(filters, sessionSignal);
1114
+ try {
1115
+ let targetId = filters.targetId;
1116
+ if (targetId === undefined && filters.instanceId === undefined) {
1117
+ targetId = (await inspect({ signal: operation.signal, timeoutMs: operation.remaining() })).primaryTargetId ?? undefined;
1118
+ if (!targetId)
1119
+ throw new DevHostError('DEV_TARGET_NOT_FOUND', '尚无主预览目标,请指定 targetId 或 instanceId');
1120
+ }
1121
+ return await logs({
1122
+ ...filters,
1123
+ targetId,
1124
+ ...(kind === 'network' ? { source: 'network' } : { problems: true }),
1125
+ signal: operation.signal,
1126
+ timeoutMs: operation.remaining(),
1127
+ });
1128
+ }
1129
+ finally {
1130
+ operation.dispose();
1131
+ }
1132
+ };
1133
+ const resource = async (name, options = {}) => {
1134
+ validateSelection(options);
1135
+ if (options.path !== undefined && (typeof options.path !== 'string' || !options.path || options.path.length > 1024))
1136
+ throw new DevHostError('INVALID_RESOURCE_PATH', 'path 必须是有界非空逻辑路径');
1137
+ if (options.maxBytes !== undefined &&
1138
+ (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1 || options.maxBytes > DEV_SANDBOX_READ_MAX_BYTES))
1139
+ throw new DevHostError('INVALID_READ_LIMIT', 'maxBytes 必须是 1 至 16384 的整数');
1140
+ const operation = requestBudget({ ...options, timeoutMs: options.timeoutMs ?? 12_000 }, sessionSignal);
1141
+ try {
1142
+ const selected = await resolveSelection(options, { signal: operation.signal, timeoutMs: operation.remaining() });
1143
+ const instanceId = selected.instanceId;
1144
+ const value = await request(DEV_RESOURCE_PATH, { signal: operation.signal, timeoutMs: operation.remaining() }, {
1145
+ method: 'POST',
1146
+ body: JSON.stringify({
1147
+ instanceId,
1148
+ resource: name,
1149
+ ...(options.path !== undefined ? { path: options.path } : {}),
1150
+ ...(options.operation ? { operation: options.operation } : {}),
1151
+ ...(options.maxBytes !== undefined ? { maxBytes: options.maxBytes } : {}),
1152
+ }),
1153
+ });
1154
+ check(value);
1155
+ if (value.instanceId !== instanceId || value.resource !== name)
1156
+ throw new DevHostError('DEV_PROTOCOL_INVALID', '资源结果不属于请求实例');
1157
+ if (selected.targetId !== undefined) {
1158
+ const snapshot = await inspect({ signal: operation.signal, timeoutMs: operation.remaining() });
1159
+ if (snapshot.targets.find((target) => target.targetId === selected.targetId)?.currentInstanceId !== instanceId)
1160
+ throw new DevHostError('RUNTIME_INSTANCE_CHANGED', `目标 ${selected.targetId} 的当前实例已变化,请重新检查后显式重试`);
1161
+ }
1162
+ return value;
1163
+ }
1164
+ finally {
1165
+ operation.dispose();
1166
+ }
1167
+ };
1168
+ const action = async (command, options = {}, data = {}) => request(PREVIEW_PATH, { ...options, timeoutMs: options.timeoutMs ?? 200_000 }, {
1169
+ method: 'POST',
1170
+ body: JSON.stringify({ ...data, command, sessionId: connection.record.sessionId, projectRoot: connection.record.projectRoot }),
1171
+ });
1172
+ return {
1173
+ id: connection.record.sessionId,
1174
+ projectRoot: connection.record.projectRoot,
1175
+ port: connection.record.port,
1176
+ inspect,
1177
+ logs,
1178
+ async waitForRuntime(options = {}) {
1179
+ validateSelection(options);
1180
+ const operation = requestBudget({ ...options, timeoutMs: options.timeoutMs ?? 30_000 }, sessionSignal);
1181
+ const followsTarget = options.instanceId === undefined;
1182
+ let targetId = options.targetId;
1183
+ let instanceId = options.instanceId;
1184
+ let last;
1185
+ try {
1186
+ while (true) {
1187
+ const snapshot = await inspect({ signal: operation.signal, timeoutMs: operation.remaining() });
1188
+ targetId ??= followsTarget ? (snapshot.primaryTargetId ?? undefined) : undefined;
1189
+ const target = targetId === undefined ? undefined : snapshot.targets.find((item) => item.targetId === targetId);
1190
+ if (targetId !== undefined && !target)
1191
+ throw new DevHostError('DEV_TARGET_NOT_FOUND', '所选目标已不可查询,请查看 dev inspect');
1192
+ if (followsTarget)
1193
+ instanceId ??= target?.currentInstanceId ?? undefined;
1194
+ const instance = instanceId ? snapshot.instances.find((item) => item.instanceId === instanceId) : null;
1195
+ last = { snapshot, target: target ?? (instance ? snapshot.targets.find(item => item.targetId === instance.targetId) : undefined), instance };
1196
+ if (!instanceId && target) {
1197
+ const lastAttempt = snapshot.instances.findLast((item) => item.targetId === target.targetId && item.ownerId === target.ownerId);
1198
+ if (lastAttempt?.state === 'failed' || lastAttempt?.state === 'closed')
1199
+ throw runtimeFailure(lastAttempt, snapshot);
1200
+ if (target.state === 'closed')
1201
+ throw new DevHostError('DEV_TARGET_CLOSED', `目标 ${target.targetId} 已关闭,请重新选择目标`);
1202
+ }
1203
+ if (instanceId && !instance)
1204
+ throw new DevHostError('RUNTIME_INSTANCE_NOT_FOUND', `实例 ${instanceId} 已不可查询,请检查 dev inspect`);
1205
+ if (instance?.state === 'failed')
1206
+ throw runtimeFailure(instance, snapshot);
1207
+ if (instanceId &&
1208
+ ((followsTarget && target?.currentInstanceId !== instanceId) || (instance?.state === 'closed' && instance.reason === 'replaced')))
1209
+ throw new DevHostError('RUNTIME_INSTANCE_CHANGED', `实例 ${instanceId} 已被替换,请检查 dev inspect 后显式重试`);
1210
+ if (instance?.state === 'closed')
1211
+ throw runtimeFailure(instance, snapshot);
1212
+ if (instance?.state === 'ready' && !instance.documentVerifying && !instance.stale && (!followsTarget || (target?.state === 'attached' && !target.stale)))
1213
+ return instance;
1214
+ await delay(Math.min(100, operation.remaining()), operation.signal);
1215
+ }
1216
+ }
1217
+ catch (error) {
1218
+ if (!options.signal?.aborted && !sessionSignal?.aborted && error instanceof DevHostError && error.code === 'DEV_TIMEOUT' && last) {
1219
+ if (last.target?.stale || last.instance?.stale)
1220
+ throw runtimeWaitFailure('HOST_UNRESPONSIVE', '等待期间 Host 心跳仍未恢复,请检查目标连接和 dev inspect', last);
1221
+ throw runtimeWaitFailure(last.instance?.documentVerifying ? 'RUNTIME_DOCUMENT_VERIFYING' : 'RUNTIME_NOT_READY', last.instance?.documentVerifying ? '等待期间当前文档未完成验证,请查看 Runtime 日志' : '等待期间 Runtime 未就绪,请查看实例状态和启动日志', last);
1222
+ }
1223
+ throw error;
1224
+ }
1225
+ finally {
1226
+ operation.dispose();
1227
+ }
1228
+ },
1229
+ preview: {
1230
+ connect(options = {}) {
1231
+ return connectPreviewBrowser(connection, {
1232
+ ...options,
1233
+ signal: combinedSignal(options.signal, sessionSignal),
1234
+ });
1235
+ },
1236
+ open: (options) => action('open', options),
1237
+ select(options) {
1238
+ if (options.preset === undefined && options.orientation === undefined)
1239
+ throw new DevHostError('INVALID_SELECTION', '请提供 preset 或 orientation');
1240
+ if (options.preset === 'desktop' && options.orientation)
1241
+ throw new DevHostError('INVALID_SELECTION', '桌面方向由窗口决定');
1242
+ return action('select', options, { preset: options.preset, orientation: options.orientation });
1243
+ },
1244
+ reload: (options) => action('reload', options),
1245
+ capture(options = {}) {
1246
+ if (options.scope === 'workbench' && options.scale === 'device')
1247
+ throw new DevHostError('INVALID_CAPTURE', 'workbench 取景只支持 css');
1248
+ return action('capture', options, { scope: options.scope ?? 'device', scale: options.scale ?? 'css' });
1249
+ },
1250
+ },
1251
+ resources: {
1252
+ presentation: (options) => resource('presentation', options),
1253
+ storage: (options) => resource('storage', options),
1254
+ sandbox: (options) => resource('sandbox', { ...options, operation: 'list' }),
1255
+ sandboxRead: (options) => resource('sandbox', { ...options, operation: 'read', maxBytes: options.maxBytes ?? DEV_SANDBOX_READ_MAX_BYTES }),
1256
+ network: (filters = {}) => projection(filters, 'network'),
1257
+ problems: (filters = {}) => projection(filters, 'problems'),
1258
+ },
1259
+ };
1260
+ }
1261
+ function validateSelection(selection) {
1262
+ if (selection.targetId !== undefined && selection.instanceId !== undefined)
1263
+ throw new DevHostError('INVALID_TARGET_SELECTION', 'targetId 与 instanceId 不能同时提供');
1264
+ if (selection.targetId !== undefined && (typeof selection.targetId !== 'string' || !selection.targetId || selection.targetId.length > 200))
1265
+ throw new DevHostError('INVALID_TARGET', 'targetId 必须是有效目标 ID');
1266
+ if (selection.instanceId !== undefined && (typeof selection.instanceId !== 'string' || !/^[A-Za-z0-9_-]{1,100}$/.test(selection.instanceId)))
1267
+ throw new DevHostError('INVALID_INSTANCE', 'instanceId 必须是有效启动实例 ID');
1268
+ }
1269
+ function runtimeWaitFailure(code, message, last) {
1270
+ return Object.assign(new DevHostError(code, message), {
1271
+ targetId: last.target?.targetId ?? last.instance?.targetId ?? null,
1272
+ instanceId: last.instance?.instanceId ?? null,
1273
+ lastKnownState: last.instance?.state ?? null,
1274
+ lastSeenAt: last.target?.updatedAt ?? last.instance?.updatedAt ?? null,
1275
+ documentVerifying: last.instance?.documentVerifying === true,
1276
+ logs: { epoch: last.snapshot.epoch, through: last.snapshot.nextCursor },
1277
+ });
1278
+ }
1279
+ function runtimeFailure(instance, snapshot) {
1280
+ return Object.assign(new DevHostError(instance.error?.code ?? 'RUNTIME_CLOSED', instance.error?.message ?? instance.reason ?? 'Runtime 实例已结束'), {
1281
+ instanceId: instance.instanceId,
1282
+ diagnostic: instance.error,
1283
+ logs: { epoch: snapshot.epoch, after: Math.max(0, instance.startCursor - 1), through: instance.lastCursor },
1284
+ });
1285
+ }
1286
+ function logParameters(filters) {
1287
+ const params = new URLSearchParams();
1288
+ for (const key of ['after', 'limit', 'id', 'since']) {
1289
+ const value = filters[key];
1290
+ if (value === undefined)
1291
+ continue;
1292
+ const min = key === 'limit' || key === 'id' ? 1 : 0;
1293
+ if (!Number.isSafeInteger(value) || value < min || (key === 'limit' && value > 500))
1294
+ throw new DevHostError('INVALID_LOG_FILTER', `${key} 无效`);
1295
+ params.set(key, String(value));
1296
+ }
1297
+ if (filters.source !== undefined && !['app', 'sdk', 'runtime', 'host', 'network'].includes(filters.source))
1298
+ throw new DevHostError('INVALID_LOG_FILTER', 'source 无效');
1299
+ if (filters.level !== undefined && !['log', 'debug', 'info', 'warn', 'error'].includes(filters.level))
1300
+ throw new DevHostError('INVALID_LOG_FILTER', 'level 无效');
1301
+ if (filters.problems !== undefined) {
1302
+ if (typeof filters.problems !== 'boolean')
1303
+ throw new DevHostError('INVALID_LOG_FILTER', 'problems 无效');
1304
+ params.set('problems', String(filters.problems));
1305
+ }
1306
+ for (const key of ['targetId', 'instanceId', 'uploadSessionId', 'callId', 'phase', 'source', 'level', 'query']) {
1307
+ const value = filters[key];
1308
+ if (value !== undefined) {
1309
+ if (typeof value !== 'string' || value.length > 1024)
1310
+ throw new DevHostError('INVALID_LOG_FILTER', `${key} 无效`);
1311
+ params.set(key, value);
1312
+ }
1313
+ }
1314
+ return params;
1315
+ }
1316
+ function combinedSignal(signal, external) {
1317
+ return signal && external ? AbortSignal.any([signal, external]) : (signal ?? external);
1318
+ }
1319
+ function requestBudget(options, external) {
1320
+ const timeoutMs = options.timeoutMs ?? 5000;
1321
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647)
1322
+ throw new DevHostError('INVALID_TIMEOUT', 'timeoutMs 必须是有效的正整数毫秒数');
1323
+ const deadline = Date.now() + timeoutMs;
1324
+ const timeout = new AbortController();
1325
+ const signal = AbortSignal.any([timeout.signal, ...(external ? [external] : []), ...(options.signal ? [options.signal] : [])]);
1326
+ signal.throwIfAborted();
1327
+ const timer = setTimeout(() => timeout.abort(new DevHostError('DEV_TIMEOUT', '开发工具请求超时,请用 dev inspect 查看实例与日志')), timeoutMs);
1328
+ return {
1329
+ signal,
1330
+ remaining() {
1331
+ if (Date.now() >= deadline)
1332
+ timeout.abort(new DevHostError('DEV_TIMEOUT', '开发工具请求超时,请用 dev inspect 查看实例与日志'));
1333
+ signal.throwIfAborted();
1334
+ return Math.max(1, deadline - Date.now());
1335
+ },
1336
+ dispose() {
1337
+ clearTimeout(timer);
1338
+ },
1339
+ };
1340
+ }
1341
+ function delay(ms, signal) {
1342
+ return new Promise((resolve, reject) => {
1343
+ const abort = () => {
1344
+ clearTimeout(timer);
1345
+ signal.removeEventListener('abort', abort);
1346
+ reject(signal.reason);
1347
+ };
1348
+ const timer = setTimeout(() => {
1349
+ signal.removeEventListener('abort', abort);
1350
+ resolve();
1351
+ }, ms);
1352
+ signal.addEventListener('abort', abort, { once: true });
1353
+ if (signal.aborted)
1354
+ abort();
1355
+ });
1356
+ }
1357
+
1358
+ exports.connectDevSession = connectDevSession;