@ait-co/devtools 0.1.58 → 0.1.60

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 (79) hide show
  1. package/dist/deeplink-BONXxWEO.cjs +44 -0
  2. package/dist/deeplink-BONXxWEO.cjs.map +1 -0
  3. package/dist/deeplink-CCGiyoHq.cjs +44 -0
  4. package/dist/deeplink-CCGiyoHq.cjs.map +1 -0
  5. package/dist/deeplink-CaO6hZVG.js +44 -0
  6. package/dist/deeplink-CaO6hZVG.js.map +1 -0
  7. package/dist/deeplink-Cqli4qzm.js +44 -0
  8. package/dist/deeplink-Cqli4qzm.js.map +1 -0
  9. package/dist/devtools-opener-BbUXBzgA.js +65 -0
  10. package/dist/devtools-opener-BbUXBzgA.js.map +1 -0
  11. package/dist/devtools-opener-Bp671YXu.cjs +62 -0
  12. package/dist/devtools-opener-Bp671YXu.cjs.map +1 -0
  13. package/dist/devtools-opener-D84kZFtR.js +65 -0
  14. package/dist/devtools-opener-D84kZFtR.js.map +1 -0
  15. package/dist/devtools-opener-h6A-UjzC.cjs +62 -0
  16. package/dist/devtools-opener-h6A-UjzC.cjs.map +1 -0
  17. package/dist/mcp/cli.js +862 -403
  18. package/dist/mcp/cli.js.map +1 -1
  19. package/dist/mcp/server.js +5 -1
  20. package/dist/mcp/server.js.map +1 -1
  21. package/dist/panel/index.d.ts +15 -9
  22. package/dist/panel/index.d.ts.map +1 -1
  23. package/dist/panel/index.js +27705 -1965
  24. package/dist/panel/index.js.map +1 -1
  25. package/dist/qr-http-server-Byk0Yjk_.cjs +901 -0
  26. package/dist/qr-http-server-Byk0Yjk_.cjs.map +1 -0
  27. package/dist/qr-http-server-D_Aj5Vq6.cjs +901 -0
  28. package/dist/qr-http-server-D_Aj5Vq6.cjs.map +1 -0
  29. package/dist/qr-http-server-N4mX8GaC.js +901 -0
  30. package/dist/qr-http-server-N4mX8GaC.js.map +1 -0
  31. package/dist/qr-http-server-kYvmlXlg.js +901 -0
  32. package/dist/qr-http-server-kYvmlXlg.js.map +1 -0
  33. package/dist/relay-secret-store-5A7_7zOp.js +111 -0
  34. package/dist/relay-secret-store-5A7_7zOp.js.map +1 -0
  35. package/dist/{relay-secret-store-DqyUoeXy.js → relay-secret-store-C4QQN5NA.js} +3 -3
  36. package/dist/{relay-secret-store-DqyUoeXy.js.map → relay-secret-store-C4QQN5NA.js.map} +1 -1
  37. package/dist/{relay-secret-store-DnTNl-9z.cjs → relay-secret-store-CLkF8Pa0.cjs} +3 -2
  38. package/dist/{relay-secret-store-DnTNl-9z.cjs.map → relay-secret-store-CLkF8Pa0.cjs.map} +1 -1
  39. package/dist/relay-url-store-COG2dSql.cjs +113 -0
  40. package/dist/relay-url-store-COG2dSql.cjs.map +1 -0
  41. package/dist/relay-url-store-WKfo0VQV.js +112 -0
  42. package/dist/relay-url-store-WKfo0VQV.js.map +1 -0
  43. package/dist/relay-url-store-qaoe0zOD.js +118 -0
  44. package/dist/relay-url-store-qaoe0zOD.js.map +1 -0
  45. package/dist/totp-86i_CNqh.js +3 -0
  46. package/dist/{totp-D0a8VwoR.js → totp-BIrJHsQn.js} +1 -1
  47. package/dist/{totp-D0a8VwoR.js.map → totp-BIrJHsQn.js.map} +1 -1
  48. package/dist/{totp-BkP5yU2K.js → totp-BjtKFt88.js} +2 -2
  49. package/dist/{totp-BkP5yU2K.js.map → totp-BjtKFt88.js.map} +1 -1
  50. package/dist/totp-BxtxuEt4.js +64 -0
  51. package/dist/totp-BxtxuEt4.js.map +1 -0
  52. package/dist/totp-D9rndqg_.cjs +64 -0
  53. package/dist/totp-D9rndqg_.cjs.map +1 -0
  54. package/dist/{totp-DLgGbySX.cjs → totp-DA8vjAi7.cjs} +2 -1
  55. package/dist/{totp-DLgGbySX.cjs.map → totp-DA8vjAi7.cjs.map} +1 -1
  56. package/dist/{tunnel-nKYPtc-g.cjs → tunnel-GieyWa22.cjs} +114 -3
  57. package/dist/tunnel-GieyWa22.cjs.map +1 -0
  58. package/dist/{tunnel-CI61NvPI.js → tunnel-JuZ5_Pci.js} +114 -4
  59. package/dist/tunnel-JuZ5_Pci.js.map +1 -0
  60. package/dist/unplugin/index.cjs +116 -4
  61. package/dist/unplugin/index.cjs.map +1 -1
  62. package/dist/unplugin/index.d.cts +20 -1
  63. package/dist/unplugin/index.d.cts.map +1 -1
  64. package/dist/unplugin/index.d.ts +20 -1
  65. package/dist/unplugin/index.d.ts.map +1 -1
  66. package/dist/unplugin/index.js +116 -5
  67. package/dist/unplugin/index.js.map +1 -1
  68. package/dist/unplugin/tunnel.cjs +114 -2
  69. package/dist/unplugin/tunnel.cjs.map +1 -1
  70. package/dist/unplugin/tunnel.d.cts +62 -1
  71. package/dist/unplugin/tunnel.d.cts.map +1 -1
  72. package/dist/unplugin/tunnel.d.ts +62 -1
  73. package/dist/unplugin/tunnel.d.ts.map +1 -1
  74. package/dist/unplugin/tunnel.js +113 -3
  75. package/dist/unplugin/tunnel.js.map +1 -1
  76. package/package.json +11 -3
  77. package/dist/totp-CQFmgOhM.js +0 -3
  78. package/dist/tunnel-CI61NvPI.js.map +0 -1
  79. package/dist/tunnel-nKYPtc-g.cjs.map +0 -1
@@ -1,5 +1,70 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { createUnplugin } from "unplugin";
3
+ //#region src/shared/parent-watcher.ts
4
+ /**
5
+ * Shared parent-PID watcher — used by both the MCP debug daemon and the
6
+ * unplugin tunnel path to self-terminate when the parent process (e.g. Claude
7
+ * Code, vite) has died or been reparented without sending SIGTERM/SIGHUP.
8
+ *
9
+ * Intentionally react-free and Node-stdlib-only so this module is safe to
10
+ * import from the MCP daemon bundle (`dist/mcp/cli.js`) without violating the
11
+ * install-graph invariant.
12
+ */
13
+ /**
14
+ * Returns `true` when the given PID refers to a running process.
15
+ *
16
+ * Uses `process.kill(pid, 0)` — a no-op signal that succeeds when the process
17
+ * exists and we have permission to signal it; throws ESRCH when it doesn't exist.
18
+ */
19
+ function isPidAlive(pid) {
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ } catch (err) {
24
+ if (err.code === "EPERM") return true;
25
+ return false;
26
+ }
27
+ }
28
+ /**
29
+ * Starts a periodic watcher that detects when the parent process (e.g. Claude
30
+ * Code) has died without sending SIGTERM/SIGHUP, and calls `onOrphaned` so the
31
+ * daemon can self-terminate rather than running as a zombie.
32
+ *
33
+ * Mirrors the `startAttachWatcher` pattern: `setInterval`-based, returns
34
+ * `{ stop(): void }`, injectable deps for testability.
35
+ *
36
+ * @param onOrphaned - Called once when the parent is gone.
37
+ * @param opts.intervalMs - Poll interval in milliseconds (default 5 000).
38
+ * @param opts.initialPpid - Parent PID to watch (default `process.ppid`).
39
+ * @param opts.isAlive - Predicate to test if a PID is running (default `isPidAlive`).
40
+ * @param opts.getPpid - Supplier of current ppid (default `() => process.ppid`).
41
+ * Detects ppid changes as well as death.
42
+ * @param opts.log - Logger (default `process.stderr.write`).
43
+ *
44
+ * @returns `stop` — call during shutdown to clear the interval.
45
+ */
46
+ function startParentWatcher(onOrphaned, opts) {
47
+ const { intervalMs = 5e3, initialPpid = process.ppid, isAlive = isPidAlive, getPpid = () => process.ppid, log = (msg) => process.stderr.write(msg) } = opts ?? {};
48
+ if (initialPpid <= 1) {
49
+ log("[ait-debug] parent-pid watcher: no parent to watch (ppid<=1), skipping\n");
50
+ return { stop() {} };
51
+ }
52
+ let fired = false;
53
+ const handle = setInterval(() => {
54
+ if (fired) return;
55
+ const currentPpid = getPpid();
56
+ if (currentPpid !== initialPpid || !isAlive(initialPpid)) {
57
+ fired = true;
58
+ clearInterval(handle);
59
+ log(`[ait-debug] parent-pid watcher: parent PID ${initialPpid} is gone (currentPpid=${currentPpid}) — shutting down\n`);
60
+ onOrphaned();
61
+ }
62
+ }, intervalMs);
63
+ return { stop() {
64
+ clearInterval(handle);
65
+ } };
66
+ }
67
+ //#endregion
3
68
  //#region src/unplugin/index.ts
4
69
  /**
5
70
  * @ait-co/devtools unplugin
@@ -47,6 +112,27 @@ const ANALYTICS_ID = "@apps-in-toss/web-analytics";
47
112
  const WEBVIEW_BRIDGE_ID = "@apps-in-toss/webview-bridge";
48
113
  /** MCP state endpoint path — browser panel POSTs here, MCP server GETs here */
49
114
  const MCP_STATE_PATH = "/api/ait-devtools/state";
115
+ /**
116
+ * Resolves the effective tunnel option (#425).
117
+ *
118
+ * An explicit `tunnel` value (including `false`) always takes priority over
119
+ * env vars — the `??` operator means `undefined` (= omitted) falls through,
120
+ * but `false` / `true` / an object are preserved as-is (non-breaking).
121
+ *
122
+ * When the option is omitted:
123
+ * - `AIT_TUNNEL=1` enables the base screen-preview tunnel.
124
+ * - `AIT_TUNNEL_CDP=1` (requires `AIT_TUNNEL`) upgrades to the CDP relay.
125
+ * - Neither set → `false` (disabled).
126
+ *
127
+ * Extracted as a pure function so it can be unit-tested without standing up
128
+ * a full Vite dev server.
129
+ *
130
+ * @param explicit - The `tunnel` option as passed by the consumer (or `undefined` when omitted).
131
+ * @param env - The process environment (injectable for testing).
132
+ */
133
+ function resolveTunnelOption(explicit, env) {
134
+ return explicit ?? (env.AIT_TUNNEL ? { cdp: !!env.AIT_TUNNEL_CDP } : false);
135
+ }
50
136
  const aitDevtoolsPlugin = createUnplugin((options) => {
51
137
  const isDev = process.env.NODE_ENV !== "production";
52
138
  const shouldEnable = isDev || (options?.forceEnable ?? false);
@@ -54,7 +140,7 @@ const aitDevtoolsPlugin = createUnplugin((options) => {
54
140
  const shouldPanel = shouldEnable && (options?.panel ?? true);
55
141
  const shouldMcp = shouldEnable && (options?.mcp ?? false);
56
142
  let lastState = null;
57
- const tunnelOpt = options?.tunnel;
143
+ const tunnelOpt = resolveTunnelOption(options?.tunnel, process.env);
58
144
  const shouldTunnel = isDev && !!tunnelOpt;
59
145
  const tunnelConfig = typeof tunnelOpt === "object" ? tunnelOpt : {};
60
146
  return {
@@ -123,6 +209,9 @@ const aitDevtoolsPlugin = createUnplugin((options) => {
123
209
  let tunnel = null;
124
210
  let relayTunnel = null;
125
211
  let relay = null;
212
+ let qrDashboard = null;
213
+ let relayUrlDeleteFn = null;
214
+ let parentWatcher = null;
126
215
  const httpServer = server.httpServer;
127
216
  httpServer?.once("listening", () => {
128
217
  const address = httpServer?.address();
@@ -131,14 +220,15 @@ const aitDevtoolsPlugin = createUnplugin((options) => {
131
220
  console.warn("[@ait-co/devtools] tunnel: could not determine the dev server port; skipping.");
132
221
  return;
133
222
  }
134
- import("../tunnel-CI61NvPI.js").then(async ({ startQuickTunnel, printTunnelBanner }) => {
223
+ import("../tunnel-JuZ5_Pci.js").then(async ({ startQuickTunnel, printTunnelBanner, startTunnelDashboard }) => {
135
224
  const t = await startQuickTunnel(port);
136
225
  tunnel = t;
137
226
  let relayWssUrl;
227
+ let relayHttpUrl;
138
228
  if (tunnelConfig.cdp) try {
139
- const { ensureRelaySecret } = await import("../relay-secret-store-DqyUoeXy.js");
229
+ const { ensureRelaySecret } = await import("../relay-secret-store-C4QQN5NA.js");
140
230
  await ensureRelaySecret({ projectRoot: server.config.root });
141
- const { assertRelayAuthConfigured, buildRelayVerifyAuth } = await import("../totp-BkP5yU2K.js");
231
+ const { assertRelayAuthConfigured, buildRelayVerifyAuth } = await import("../totp-BjtKFt88.js");
142
232
  assertRelayAuthConfigured();
143
233
  const verifyAuth = buildRelayVerifyAuth();
144
234
  const { startChiiRelay } = await import("../chii-relay-itXOz7kS.js");
@@ -149,6 +239,7 @@ const aitDevtoolsPlugin = createUnplugin((options) => {
149
239
  relay = r;
150
240
  const rt = await startQuickTunnel(r.port);
151
241
  relayTunnel = rt;
242
+ relayHttpUrl = rt.url;
152
243
  relayWssUrl = rt.url.replace(/^https:/, "wss:");
153
244
  } catch (err) {
154
245
  console.warn(`[@ait-co/devtools] tunnel: CDP relay not started — screen preview works without on-device debugging: ${err instanceof Error ? err.message : String(err)}`);
@@ -157,18 +248,38 @@ const aitDevtoolsPlugin = createUnplugin((options) => {
157
248
  qr: tunnelConfig.qr,
158
249
  relayWssUrl
159
250
  });
251
+ const { writeRelayUrls, deleteRelayUrls } = await import("../relay-url-store-WKfo0VQV.js");
252
+ await writeRelayUrls({
253
+ projectRoot: server.config.root,
254
+ tunnelBaseUrl: t.url,
255
+ ...relayHttpUrl !== void 0 ? { relayBaseUrl: relayHttpUrl } : {}
256
+ });
257
+ relayUrlDeleteFn = (root) => deleteRelayUrls({ projectRoot: root });
258
+ if (relayWssUrl) qrDashboard = await startTunnelDashboard({
259
+ tunnelUrl: t.url,
260
+ relayWssUrl,
261
+ qr: tunnelConfig.qr
262
+ }) ?? null;
263
+ parentWatcher = startParentWatcher(() => {
264
+ cleanup();
265
+ process.exit(0);
266
+ });
160
267
  }).catch((err) => {
161
268
  console.warn(`[@ait-co/devtools] tunnel failed to start: ${err instanceof Error ? err.message : String(err)}`);
162
269
  });
163
270
  });
164
271
  const cleanup = () => {
272
+ parentWatcher?.stop();
165
273
  tunnel?.stop();
166
274
  relayTunnel?.stop();
167
275
  relay?.close();
276
+ qrDashboard?.close();
277
+ relayUrlDeleteFn?.(server.config.root);
168
278
  };
169
279
  httpServer?.once("close", cleanup);
170
280
  process.once("SIGINT", cleanup);
171
281
  process.once("SIGTERM", cleanup);
282
+ process.once("SIGHUP", cleanup);
172
283
  process.once("exit", cleanup);
173
284
  }
174
285
  }
@@ -181,6 +292,6 @@ const rollup = aitDevtoolsPlugin.rollup;
181
292
  const esbuild = aitDevtoolsPlugin.esbuild;
182
293
  const rspack = aitDevtoolsPlugin.rspack;
183
294
  //#endregion
184
- export { aitDevtoolsPlugin as default, esbuild, rollup, rspack, vite, webpack };
295
+ export { aitDevtoolsPlugin as default, esbuild, resolveTunnelOption, rollup, rspack, vite, webpack };
185
296
 
186
297
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/unplugin/index.ts"],"sourcesContent":["/**\n * @ait-co/devtools unplugin\n *\n * 모든 주요 번들러를 지원하는 단일 플러그인.\n * @apps-in-toss/web-framework → @ait-co/devtools/mock 으로 alias 설정.\n *\n * Usage:\n * import aitDevtools from '@ait-co/devtools/unplugin';\n *\n * // Vite\n * export default { plugins: [aitDevtools.vite()] };\n *\n * // Webpack / Next.js\n * config.plugins.push(aitDevtools.webpack());\n *\n * // Rspack\n * config.plugins.push(aitDevtools.rspack());\n *\n * // esbuild\n * { plugins: [aitDevtools.esbuild()] }\n *\n * // Rollup\n * { plugins: [aitDevtools.rollup()] }\n */\n\nimport { fileURLToPath } from 'node:url';\nimport { createUnplugin } from 'unplugin';\n\n/**\n * Resolve `@ait-co/devtools/mock` to its real file path at plugin-load time.\n *\n * Returning the bare specifier from `resolveId` would stop the bundler from\n * walking node_modules for it — Vite 8+ treats such a non-null string as the\n * final resolved id and serves it via the virtual `/@id/` prefix, which 404s\n * because we don't provide a `load` hook. Resolving to an absolute path here\n * lets every supported bundler load the file the normal way.\n */\nconst MOCK_PATH = (() => {\n try {\n return fileURLToPath(import.meta.resolve('@ait-co/devtools/mock'));\n } catch {\n // Fallback for runtimes where `import.meta.resolve` is unavailable.\n return '@ait-co/devtools/mock';\n }\n})();\n\nexport interface AitDevtoolsOptions {\n /**\n * 패널 자동 주입 여부 (default: true)\n * true이면 진입점에 floating panel import를 자동 추가한다.\n */\n panel?: boolean;\n /**\n * production 환경에서도 devtools를 강제로 활성화 (default: false)\n */\n forceEnable?: boolean;\n /**\n * mock alias 활성화 여부. default: true (development), false (production + forceEnable)\n */\n mock?: boolean;\n /**\n * Vite dev server에 MCP state endpoint를 추가할지 여부 (default: false).\n *\n * `true`로 설정하면:\n * - GET /api/ait-devtools/state — 마지막으로 브라우저가 push한 mock state 스냅샷 반환\n * - POST /api/ait-devtools/state — 브라우저 panel이 상태 변경 시 자동 push (panel 내부 처리)\n *\n * 이 endpoint를 `@ait-co/devtools` MCP stdio server가 읽어 AI 에이전트에 mock state를 노출한다.\n * Vite 전용: webpack/rspack/esbuild/rollup 환경에서는 무시된다.\n */\n mcp?: boolean;\n /**\n * Vite dev 서버를 Cloudflare quick tunnel(`*.trycloudflare.com`, 계정 불필요)로\n * 외부 노출해 실제 폰에서 미리보기. **Vite dev 모드 전용** — production은\n * `forceEnable`이어도 터널을 띄우지 않는다 (의도치 않은 노출 방지). 다른 번들러는\n * 무시. `true`면 기본 동작, 객체로 세부 설정 가능.\n */\n tunnel?:\n | boolean\n | {\n /** 노출할 포트 (미지정 시 dev 서버가 실제 listen한 포트 자동 감지). */\n port?: number;\n /** 터미널 ASCII QR 출력 (default: true). */\n qr?: boolean;\n /**\n * 환경 2(실기기 PWA)에 CDP 디버깅 배선 (default: false).\n *\n * `true`면 dev 서버 HTTP 터널과 **별도로** Chii relay를 띄우고 그 relay에\n * 두 번째 quick tunnel을 붙여, launcher QR deep-link에 `&debug=1&relay=<wss>`를\n * 실어 보낸다. 폰의 PWA iframe이 in-app debug gate를 통과해 target.js를 주입받고,\n * AI host MCP가 그 relay에 client로 붙으면 실기기 WebKit 위에서 CDP 디버깅이 열린다.\n * mock SDK는 그대로라 `call_sdk`는 환경 2에서 mock을 친다 (fidelity 사다리의\n * 설계 의도 — SDK fidelity가 필요하면 환경 3로 올라간다).\n */\n cdp?: boolean;\n };\n}\n\nconst FRAMEWORK_ID = '@apps-in-toss/web-framework';\nconst BRIDGE_ID = '@apps-in-toss/web-bridge'; // back-compat (2.x)\nconst ANALYTICS_ID = '@apps-in-toss/web-analytics'; // back-compat (2.x)\nconst WEBVIEW_BRIDGE_ID = '@apps-in-toss/webview-bridge'; // 3.0+\n\n/** MCP state endpoint path — browser panel POSTs here, MCP server GETs here */\nconst MCP_STATE_PATH = '/api/ait-devtools/state';\n\nconst aitDevtoolsPlugin = createUnplugin((options?: AitDevtoolsOptions) => {\n const isDev = process.env.NODE_ENV !== 'production';\n const shouldEnable = isDev || (options?.forceEnable ?? false);\n const shouldMock = shouldEnable && (options?.mock ?? isDev);\n const shouldPanel = shouldEnable && (options?.panel ?? true);\n const shouldMcp = shouldEnable && (options?.mcp ?? false);\n\n // In-memory store for the last state snapshot pushed by the browser panel.\n // Only allocated when mcp: true to avoid any overhead in the common case.\n let lastState: string | null = null;\n\n // Tunnel is dev-only and Vite-only. Never under production — even with\n // forceEnable — so a production build can't accidentally expose itself.\n const tunnelOpt = options?.tunnel;\n const shouldTunnel = isDev && !!tunnelOpt;\n const tunnelConfig = typeof tunnelOpt === 'object' ? tunnelOpt : {};\n\n return {\n name: 'ait-co-devtools',\n enforce: 'pre' as const,\n\n resolveId(id: string) {\n if (!shouldMock) return null;\n // @apps-in-toss/web-framework → @ait-co/devtools/mock (absolute path)\n if (\n id === FRAMEWORK_ID ||\n id === WEBVIEW_BRIDGE_ID ||\n id === BRIDGE_ID ||\n id === ANALYTICS_ID\n ) {\n return MOCK_PATH;\n }\n return null;\n },\n\n transformInclude(id: string) {\n if (!shouldPanel) return false;\n // 진입점 파일에만 패널 import를 주입\n return (\n /\\.(tsx?|jsx?)$/.test(id) &&\n /\\/(main|index|entry|app)\\.[tj]sx?$/i.test(id) &&\n !id.includes('node_modules')\n );\n },\n\n transform(code: string) {\n // transformInclude가 이미 shouldPanel을 확인하지만, 안전망으로 유지\n if (!shouldPanel) return null;\n // 이미 패널이 import 되어있으면 스킵\n if (code.includes('@ait-co/devtools/panel')) return null;\n // transformInclude가 진입점 파일만 통과시키므로 바로 prepend\n return `import '@ait-co/devtools/panel';\\n${code}`;\n },\n\n // Vite-only: register the MCP state HTTP endpoint on the dev server, and\n // optionally start a Cloudflare quick tunnel once the dev server is listening.\n // Non-Vite bundlers do not have a dev server concept so this is silently\n // skipped (unplugin passes `vite` key only when building for Vite).\n vite: {\n config() {\n if (!shouldTunnel) return;\n // Vite blocks requests whose Host header isn't in `server.allowedHosts`\n // (defaults to localhost only). The quick-tunnel hostname is random per\n // run, so allow the whole `.trycloudflare.com` suffix while the tunnel\n // is on. (A leading `.` makes Vite match the domain and its subdomains.)\n return { server: { allowedHosts: ['.trycloudflare.com'] } };\n },\n\n configureServer(server: import('vite').ViteDevServer) {\n // MCP state endpoint: browser panel POSTs state here, MCP stdio server GETs it.\n if (shouldMcp) {\n server.middlewares.use(MCP_STATE_PATH, (req, res) => {\n // Allow Claude Code / AI agents (running locally) to read state\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (req.method === 'GET') {\n if (lastState === null) {\n res.writeHead(503, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'No state received yet. Open the app in a browser first.',\n }),\n );\n return;\n }\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(lastState);\n return;\n }\n\n if (req.method === 'POST') {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => {\n try {\n const body = Buffer.concat(chunks).toString('utf-8');\n // Validate it's parseable JSON before caching\n JSON.parse(body);\n lastState = body;\n res.writeHead(204);\n res.end();\n } catch {\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Invalid JSON' }));\n }\n });\n return;\n }\n\n res.writeHead(405, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Method not allowed' }));\n });\n }\n\n // Tunnel: start a Cloudflare quick tunnel once the dev server is listening.\n if (shouldTunnel) {\n let tunnel: { stop: () => void } | null = null;\n // env-2 CDP wiring (tunnel.cdp): a second tunnel + Chii relay, torn\n // down alongside the HTTP tunnel. Fire-and-forget close on teardown.\n let relayTunnel: { stop: () => void } | null = null;\n let relay: { close: () => Promise<void> } | null = null;\n const httpServer = server.httpServer;\n\n httpServer?.once('listening', () => {\n const address = httpServer?.address();\n const port =\n tunnelConfig.port ??\n (address && typeof address === 'object' ? address.port : undefined);\n if (!port) {\n console.warn(\n '[@ait-co/devtools] tunnel: could not determine the dev server port; skipping.',\n );\n return;\n }\n // Dynamic import keeps `cloudflared` / `qrcode-terminal` off the\n // module graph unless the tunnel is actually used.\n import('./tunnel.js')\n .then(async ({ startQuickTunnel, printTunnelBanner }) => {\n const t = await startQuickTunnel(port);\n tunnel = t;\n\n // env-2 CDP: boot a Chii relay (OS-assigned local port) and a\n // second quick tunnel to it. The relay's https tunnel URL becomes\n // the `wss://` relay the launcher QR carries (&debug=1&relay=).\n let relayWssUrl: string | undefined;\n if (tunnelConfig.cdp) {\n try {\n // Relay-auth baseline (issue #250): the env-2 CDP relay is\n // reachable over a public `*.trycloudflare.com` tunnel, so a\n // configured TOTP secret is MANDATORY and the relay enforces\n // it on every WS upgrade.\n //\n // First-run auto-mint (issue #394, project-local #396): if\n // AIT_DEBUG_TOTP_SECRET is not yet set, ensureRelaySecret()\n // mints a 256-bit random secret, persists it to the project-\n // local file <project>/.ait_relay (0600, anchored at the\n // nearest package.json directory above server.config.root),\n // and injects it into process.env so the following\n // assertRelayAuthConfigured() call succeeds. On subsequent\n // runs the persisted value is loaded silently — no manual\n // export needed. The MCP daemon reads the SAME file read-only\n // via loadRelaySecretReadOnly() when switching to a relay env.\n // SECRET-HANDLING: neither ensureRelaySecret nor the\n // guard/predicate log the secret value.\n const { ensureRelaySecret } = await import('../mcp/relay-secret-store.js');\n await ensureRelaySecret({ projectRoot: server.config.root });\n const { assertRelayAuthConfigured, buildRelayVerifyAuth } = await import(\n '../mcp/totp.js'\n );\n assertRelayAuthConfigured();\n const verifyAuth = buildRelayVerifyAuth();\n const { startChiiRelay } = await import('../mcp/chii-relay.js');\n const r = await startChiiRelay({ port: 0, verifyAuth });\n relay = r;\n const rt = await startQuickTunnel(r.port);\n relayTunnel = rt;\n relayWssUrl = rt.url.replace(/^https:/, 'wss:');\n } catch (err: unknown) {\n console.warn(\n `[@ait-co/devtools] tunnel: CDP relay not started — screen preview works without on-device debugging: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n await printTunnelBanner(t.url, { qr: tunnelConfig.qr, relayWssUrl });\n })\n .catch((err: unknown) => {\n console.warn(\n `[@ait-co/devtools] tunnel failed to start: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n });\n\n const cleanup = () => {\n tunnel?.stop();\n relayTunnel?.stop();\n void relay?.close();\n };\n httpServer?.once('close', cleanup);\n process.once('SIGINT', cleanup);\n process.once('SIGTERM', cleanup);\n process.once('exit', cleanup);\n }\n },\n },\n };\n});\n\nexport const vite = aitDevtoolsPlugin.vite;\nexport const webpack = aitDevtoolsPlugin.webpack;\nexport const rollup = aitDevtoolsPlugin.rollup;\nexport const esbuild = aitDevtoolsPlugin.esbuild;\nexport const rspack = aitDevtoolsPlugin.rspack;\n\nexport default aitDevtoolsPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,mBAAmB;AACvB,KAAI;AACF,SAAO,cAAc,OAAO,KAAK,QAAQ,wBAAwB,CAAC;SAC5D;AAEN,SAAO;;IAEP;AAsDJ,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,oBAAoB;;AAG1B,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB,gBAAgB,YAAiC;CACzE,MAAM,QAAQ,QAAQ,IAAI,aAAa;CACvC,MAAM,eAAe,UAAU,SAAS,eAAe;CACvD,MAAM,aAAa,iBAAiB,SAAS,QAAQ;CACrD,MAAM,cAAc,iBAAiB,SAAS,SAAS;CACvD,MAAM,YAAY,iBAAiB,SAAS,OAAO;CAInD,IAAI,YAA2B;CAI/B,MAAM,YAAY,SAAS;CAC3B,MAAM,eAAe,SAAS,CAAC,CAAC;CAChC,MAAM,eAAe,OAAO,cAAc,WAAW,YAAY,EAAE;AAEnE,QAAO;EACL,MAAM;EACN,SAAS;EAET,UAAU,IAAY;AACpB,OAAI,CAAC,WAAY,QAAO;AAExB,OACE,OAAO,gBACP,OAAO,qBACP,OAAO,aACP,OAAO,aAEP,QAAO;AAET,UAAO;;EAGT,iBAAiB,IAAY;AAC3B,OAAI,CAAC,YAAa,QAAO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EnD;QACD;OACJ;KAEF,MAAM,gBAAgB;AACpB,cAAQ,MAAM;AACd,mBAAa,MAAM;AACd,aAAO,OAAO;;AAErB,iBAAY,KAAK,SAAS,QAAQ;AAClC,aAAQ,KAAK,UAAU,QAAQ;AAC/B,aAAQ,KAAK,WAAW,QAAQ;AAChC,aAAQ,KAAK,QAAQ,QAAQ;;;GAGlC;EACF;EACD;AAEF,MAAa,OAAO,kBAAkB;AACtC,MAAa,UAAU,kBAAkB;AACzC,MAAa,SAAS,kBAAkB;AACxC,MAAa,UAAU,kBAAkB;AACzC,MAAa,SAAS,kBAAkB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/shared/parent-watcher.ts","../../src/unplugin/index.ts"],"sourcesContent":["/**\n * Shared parent-PID watcher — used by both the MCP debug daemon and the\n * unplugin tunnel path to self-terminate when the parent process (e.g. Claude\n * Code, vite) has died or been reparented without sending SIGTERM/SIGHUP.\n *\n * Intentionally react-free and Node-stdlib-only so this module is safe to\n * import from the MCP daemon bundle (`dist/mcp/cli.js`) without violating the\n * install-graph invariant.\n */\n\n// ---------------------------------------------------------------------------\n// isPidAlive — extracted from src/mcp/server-lock.ts\n// ---------------------------------------------------------------------------\n\n/**\n * Returns `true` when the given PID refers to a running process.\n *\n * Uses `process.kill(pid, 0)` — a no-op signal that succeeds when the process\n * exists and we have permission to signal it; throws ESRCH when it doesn't exist.\n */\nexport function isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err: unknown) {\n // ESRCH = no such process → stale lock.\n // EPERM = process exists but we can't signal it (still alive).\n if ((err as NodeJS.ErrnoException).code === 'EPERM') return true;\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// startParentWatcher — extracted from src/mcp/debug-server.ts\n// ---------------------------------------------------------------------------\n\n/**\n * Starts a periodic watcher that detects when the parent process (e.g. Claude\n * Code) has died without sending SIGTERM/SIGHUP, and calls `onOrphaned` so the\n * daemon can self-terminate rather than running as a zombie.\n *\n * Mirrors the `startAttachWatcher` pattern: `setInterval`-based, returns\n * `{ stop(): void }`, injectable deps for testability.\n *\n * @param onOrphaned - Called once when the parent is gone.\n * @param opts.intervalMs - Poll interval in milliseconds (default 5 000).\n * @param opts.initialPpid - Parent PID to watch (default `process.ppid`).\n * @param opts.isAlive - Predicate to test if a PID is running (default `isPidAlive`).\n * @param opts.getPpid - Supplier of current ppid (default `() => process.ppid`).\n * Detects ppid changes as well as death.\n * @param opts.log - Logger (default `process.stderr.write`).\n *\n * @returns `stop` — call during shutdown to clear the interval.\n */\nexport function startParentWatcher(\n onOrphaned: () => void,\n opts?: {\n intervalMs?: number;\n initialPpid?: number;\n isAlive?: (pid: number) => boolean;\n getPpid?: () => number;\n log?: (msg: string) => void;\n },\n): { stop(): void } {\n const {\n intervalMs = 5_000,\n initialPpid = process.ppid,\n isAlive = isPidAlive,\n getPpid = () => process.ppid,\n log = (msg: string) => process.stderr.write(msg),\n } = opts ?? {};\n\n // PID 1 is init/launchd — running under a process manager or as a detached\n // daemon. There is no meaningful parent to watch; skip the watcher entirely.\n if (initialPpid <= 1) {\n log('[ait-debug] parent-pid watcher: no parent to watch (ppid<=1), skipping\\n');\n return { stop() {} };\n }\n\n let fired = false;\n\n const handle = setInterval(() => {\n if (fired) return;\n\n const currentPpid = getPpid();\n const orphaned = currentPpid !== initialPpid || !isAlive(initialPpid);\n\n if (orphaned) {\n fired = true;\n clearInterval(handle);\n log(\n `[ait-debug] parent-pid watcher: parent PID ${initialPpid} is gone (currentPpid=${currentPpid}) — shutting down\\n`,\n );\n onOrphaned();\n }\n }, intervalMs);\n\n return {\n stop() {\n clearInterval(handle);\n },\n };\n}\n","/**\n * @ait-co/devtools unplugin\n *\n * 모든 주요 번들러를 지원하는 단일 플러그인.\n * @apps-in-toss/web-framework → @ait-co/devtools/mock 으로 alias 설정.\n *\n * Usage:\n * import aitDevtools from '@ait-co/devtools/unplugin';\n *\n * // Vite\n * export default { plugins: [aitDevtools.vite()] };\n *\n * // Webpack / Next.js\n * config.plugins.push(aitDevtools.webpack());\n *\n * // Rspack\n * config.plugins.push(aitDevtools.rspack());\n *\n * // esbuild\n * { plugins: [aitDevtools.esbuild()] }\n *\n * // Rollup\n * { plugins: [aitDevtools.rollup()] }\n */\n\nimport { fileURLToPath } from 'node:url';\nimport { createUnplugin } from 'unplugin';\nimport { startParentWatcher } from '../shared/parent-watcher.js';\n\n/**\n * Resolve `@ait-co/devtools/mock` to its real file path at plugin-load time.\n *\n * Returning the bare specifier from `resolveId` would stop the bundler from\n * walking node_modules for it — Vite 8+ treats such a non-null string as the\n * final resolved id and serves it via the virtual `/@id/` prefix, which 404s\n * because we don't provide a `load` hook. Resolving to an absolute path here\n * lets every supported bundler load the file the normal way.\n */\nconst MOCK_PATH = (() => {\n try {\n return fileURLToPath(import.meta.resolve('@ait-co/devtools/mock'));\n } catch {\n // Fallback for runtimes where `import.meta.resolve` is unavailable.\n return '@ait-co/devtools/mock';\n }\n})();\n\nexport interface AitDevtoolsOptions {\n /**\n * 패널 자동 주입 여부 (default: true)\n * true이면 진입점에 floating panel import를 자동 추가한다.\n */\n panel?: boolean;\n /**\n * production 환경에서도 devtools를 강제로 활성화 (default: false)\n */\n forceEnable?: boolean;\n /**\n * mock alias 활성화 여부. default: true (development), false (production + forceEnable)\n */\n mock?: boolean;\n /**\n * Vite dev server에 MCP state endpoint를 추가할지 여부 (default: false).\n *\n * `true`로 설정하면:\n * - GET /api/ait-devtools/state — 마지막으로 브라우저가 push한 mock state 스냅샷 반환\n * - POST /api/ait-devtools/state — 브라우저 panel이 상태 변경 시 자동 push (panel 내부 처리)\n *\n * 이 endpoint를 `@ait-co/devtools` MCP stdio server가 읽어 AI 에이전트에 mock state를 노출한다.\n * Vite 전용: webpack/rspack/esbuild/rollup 환경에서는 무시된다.\n */\n mcp?: boolean;\n /**\n * Vite dev 서버를 Cloudflare quick tunnel(`*.trycloudflare.com`, 계정 불필요)로\n * 외부 노출해 실제 폰에서 미리보기. **Vite dev 모드 전용** — production은\n * `forceEnable`이어도 터널을 띄우지 않는다 (의도치 않은 노출 방지). 다른 번들러는\n * 무시. `true`면 기본 동작, 객체로 세부 설정 가능.\n */\n tunnel?:\n | boolean\n | {\n /** 노출할 포트 (미지정 시 dev 서버가 실제 listen한 포트 자동 감지). */\n port?: number;\n /** 터미널 ASCII QR 출력 (default: true). */\n qr?: boolean;\n /**\n * 환경 2(실기기 PWA)에 CDP 디버깅 배선 (default: false).\n *\n * `true`면 dev 서버 HTTP 터널과 **별도로** Chii relay를 띄우고 그 relay에\n * 두 번째 quick tunnel을 붙여, launcher QR deep-link에 `&debug=1&relay=<wss>`를\n * 실어 보낸다. 폰의 PWA iframe이 in-app debug gate를 통과해 target.js를 주입받고,\n * AI host MCP가 그 relay에 client로 붙으면 실기기 WebKit 위에서 CDP 디버깅이 열린다.\n * mock SDK는 그대로라 `call_sdk`는 환경 2에서 mock을 친다 (fidelity 사다리의\n * 설계 의도 — SDK fidelity가 필요하면 환경 3로 올라간다).\n */\n cdp?: boolean;\n };\n}\n\nconst FRAMEWORK_ID = '@apps-in-toss/web-framework';\nconst BRIDGE_ID = '@apps-in-toss/web-bridge'; // back-compat (2.x)\nconst ANALYTICS_ID = '@apps-in-toss/web-analytics'; // back-compat (2.x)\nconst WEBVIEW_BRIDGE_ID = '@apps-in-toss/webview-bridge'; // 3.0+\n\n/** MCP state endpoint path — browser panel POSTs here, MCP server GETs here */\nconst MCP_STATE_PATH = '/api/ait-devtools/state';\n\n/**\n * Resolves the effective tunnel option (#425).\n *\n * An explicit `tunnel` value (including `false`) always takes priority over\n * env vars — the `??` operator means `undefined` (= omitted) falls through,\n * but `false` / `true` / an object are preserved as-is (non-breaking).\n *\n * When the option is omitted:\n * - `AIT_TUNNEL=1` enables the base screen-preview tunnel.\n * - `AIT_TUNNEL_CDP=1` (requires `AIT_TUNNEL`) upgrades to the CDP relay.\n * - Neither set → `false` (disabled).\n *\n * Extracted as a pure function so it can be unit-tested without standing up\n * a full Vite dev server.\n *\n * @param explicit - The `tunnel` option as passed by the consumer (or `undefined` when omitted).\n * @param env - The process environment (injectable for testing).\n */\nexport function resolveTunnelOption(\n explicit: AitDevtoolsOptions['tunnel'],\n env: Record<string, string | undefined>,\n): AitDevtoolsOptions['tunnel'] {\n return explicit ?? (env.AIT_TUNNEL ? { cdp: !!env.AIT_TUNNEL_CDP } : false);\n}\n\nconst aitDevtoolsPlugin = createUnplugin((options?: AitDevtoolsOptions) => {\n const isDev = process.env.NODE_ENV !== 'production';\n const shouldEnable = isDev || (options?.forceEnable ?? false);\n const shouldMock = shouldEnable && (options?.mock ?? isDev);\n const shouldPanel = shouldEnable && (options?.panel ?? true);\n const shouldMcp = shouldEnable && (options?.mcp ?? false);\n\n // In-memory store for the last state snapshot pushed by the browser panel.\n // Only allocated when mcp: true to avoid any overhead in the common case.\n let lastState: string | null = null;\n\n // Tunnel is dev-only and Vite-only. Never under production — even with\n // forceEnable — so a production build can't accidentally expose itself.\n //\n // Tunnel toggle resolution (#425): an explicit `tunnel` option always wins;\n // when omitted, fall back to the AIT_TUNNEL / AIT_TUNNEL_CDP env vars so a\n // consumer needs no `tunnel:` line in vite.config to enable env-2 preview.\n // AIT_TUNNEL gates the base (screen preview); AIT_TUNNEL_CDP upgrades to the\n // CDP relay. Production safety is unchanged — the existing\n // `shouldTunnel = isDev && !!tunnelOpt` guard below still blocks prod builds.\n const tunnelOpt = resolveTunnelOption(options?.tunnel, process.env);\n const shouldTunnel = isDev && !!tunnelOpt;\n const tunnelConfig = typeof tunnelOpt === 'object' ? tunnelOpt : {};\n\n return {\n name: 'ait-co-devtools',\n enforce: 'pre' as const,\n\n resolveId(id: string) {\n if (!shouldMock) return null;\n // @apps-in-toss/web-framework → @ait-co/devtools/mock (absolute path)\n if (\n id === FRAMEWORK_ID ||\n id === WEBVIEW_BRIDGE_ID ||\n id === BRIDGE_ID ||\n id === ANALYTICS_ID\n ) {\n return MOCK_PATH;\n }\n return null;\n },\n\n transformInclude(id: string) {\n if (!shouldPanel) return false;\n // 진입점 파일에만 패널 import를 주입\n return (\n /\\.(tsx?|jsx?)$/.test(id) &&\n /\\/(main|index|entry|app)\\.[tj]sx?$/i.test(id) &&\n !id.includes('node_modules')\n );\n },\n\n transform(code: string) {\n // transformInclude가 이미 shouldPanel을 확인하지만, 안전망으로 유지\n if (!shouldPanel) return null;\n // 이미 패널이 import 되어있으면 스킵\n if (code.includes('@ait-co/devtools/panel')) return null;\n // transformInclude가 진입점 파일만 통과시키므로 바로 prepend\n return `import '@ait-co/devtools/panel';\\n${code}`;\n },\n\n // Vite-only: register the MCP state HTTP endpoint on the dev server, and\n // optionally start a Cloudflare quick tunnel once the dev server is listening.\n // Non-Vite bundlers do not have a dev server concept so this is silently\n // skipped (unplugin passes `vite` key only when building for Vite).\n vite: {\n config() {\n if (!shouldTunnel) return;\n // Vite blocks requests whose Host header isn't in `server.allowedHosts`\n // (defaults to localhost only). The quick-tunnel hostname is random per\n // run, so allow the whole `.trycloudflare.com` suffix while the tunnel\n // is on. (A leading `.` makes Vite match the domain and its subdomains.)\n return { server: { allowedHosts: ['.trycloudflare.com'] } };\n },\n\n configureServer(server: import('vite').ViteDevServer) {\n // MCP state endpoint: browser panel POSTs state here, MCP stdio server GETs it.\n if (shouldMcp) {\n server.middlewares.use(MCP_STATE_PATH, (req, res) => {\n // Allow Claude Code / AI agents (running locally) to read state\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (req.method === 'GET') {\n if (lastState === null) {\n res.writeHead(503, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error: 'No state received yet. Open the app in a browser first.',\n }),\n );\n return;\n }\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(lastState);\n return;\n }\n\n if (req.method === 'POST') {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => {\n try {\n const body = Buffer.concat(chunks).toString('utf-8');\n // Validate it's parseable JSON before caching\n JSON.parse(body);\n lastState = body;\n res.writeHead(204);\n res.end();\n } catch {\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Invalid JSON' }));\n }\n });\n return;\n }\n\n res.writeHead(405, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Method not allowed' }));\n });\n }\n\n // Tunnel: start a Cloudflare quick tunnel once the dev server is listening.\n if (shouldTunnel) {\n let tunnel: { stop: () => void } | null = null;\n // env-2 CDP wiring (tunnel.cdp): a second tunnel + Chii relay, torn\n // down alongside the HTTP tunnel. Fire-and-forget close on teardown.\n let relayTunnel: { stop: () => void } | null = null;\n let relay: { close: () => Promise<void> } | null = null;\n // env-2 HTML dashboard (issue #408): local 127.0.0.1 HTTP server that\n // serves the QR + connect-steps + FAQ page (env 3/4 UX parity), opened\n // in the browser when CDP is wired + GUI present. Torn down with the\n // tunnel. Only set when the dashboard actually started.\n let qrDashboard: { close: () => Promise<void> } | null = null;\n // env-2 URL file store (#424): captured after the first writeRelayUrls\n // call so cleanup() can call deleteRelayUrls without a re-import.\n // SECRET-HANDLING: the stored function reference never carries URL values.\n let relayUrlDeleteFn: ((projectRoot: string) => Promise<void>) | null = null;\n // #420: parent-PID watcher — self-terminate when vite's parent dies so\n // cloudflared children don't become zombies holding stale tunnels.\n let parentWatcher: { stop(): void } | null = null;\n const httpServer = server.httpServer;\n\n httpServer?.once('listening', () => {\n const address = httpServer?.address();\n const port =\n tunnelConfig.port ??\n (address && typeof address === 'object' ? address.port : undefined);\n if (!port) {\n console.warn(\n '[@ait-co/devtools] tunnel: could not determine the dev server port; skipping.',\n );\n return;\n }\n // Dynamic import keeps `cloudflared` / `qrcode-terminal` off the\n // module graph unless the tunnel is actually used.\n import('./tunnel.js')\n .then(async ({ startQuickTunnel, printTunnelBanner, startTunnelDashboard }) => {\n const t = await startQuickTunnel(port);\n tunnel = t;\n\n // env-2 CDP: boot a Chii relay (OS-assigned local port) and a\n // second quick tunnel to it. The relay's https tunnel URL becomes\n // the `wss://` relay the launcher QR carries (&debug=1&relay=).\n let relayWssUrl: string | undefined;\n // SECRET-HANDLING: relayHttpUrl carries the relay host — never logged.\n let relayHttpUrl: string | undefined;\n if (tunnelConfig.cdp) {\n try {\n // Relay-auth baseline (issue #250): the env-2 CDP relay is\n // reachable over a public `*.trycloudflare.com` tunnel, so a\n // configured TOTP secret is MANDATORY and the relay enforces\n // it on every WS upgrade.\n //\n // First-run auto-mint (issue #394, project-local #396): if\n // AIT_DEBUG_TOTP_SECRET is not yet set, ensureRelaySecret()\n // mints a 256-bit random secret, persists it to the project-\n // local file <project>/.ait_relay (0600, anchored at the\n // nearest package.json directory above server.config.root),\n // and injects it into process.env so the following\n // assertRelayAuthConfigured() call succeeds. On subsequent\n // runs the persisted value is loaded silently — no manual\n // export needed. The MCP daemon reads the SAME file read-only\n // via loadRelaySecretReadOnly() when switching to a relay env.\n // SECRET-HANDLING: neither ensureRelaySecret nor the\n // guard/predicate log the secret value.\n const { ensureRelaySecret } = await import('../mcp/relay-secret-store.js');\n await ensureRelaySecret({ projectRoot: server.config.root });\n const { assertRelayAuthConfigured, buildRelayVerifyAuth } = await import(\n '../mcp/totp.js'\n );\n assertRelayAuthConfigured();\n const verifyAuth = buildRelayVerifyAuth();\n const { startChiiRelay } = await import('../mcp/chii-relay.js');\n const r = await startChiiRelay({ port: 0, verifyAuth });\n relay = r;\n const rt = await startQuickTunnel(r.port);\n relayTunnel = rt;\n // SECRET-HANDLING: rt.url is the https relay base — stored in\n // relayHttpUrl for .ait_urls write below; never logged.\n relayHttpUrl = rt.url;\n relayWssUrl = rt.url.replace(/^https:/, 'wss:');\n } catch (err: unknown) {\n console.warn(\n `[@ait-co/devtools] tunnel: CDP relay not started — screen preview works without on-device debugging: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n\n await printTunnelBanner(t.url, { qr: tunnelConfig.qr, relayWssUrl });\n\n // env-2 URL file-based discovery (#424): write .ait_urls so the\n // MCP daemon can discover the relay/tunnel URLs without manual env\n // var copy-paste. SECRET-HANDLING: URL values are never logged.\n // Capture deleteRelayUrls in the outer-scope fn so cleanup() can\n // call it without re-importing (no async in signal handlers).\n const { writeRelayUrls, deleteRelayUrls } = await import(\n '../mcp/relay-url-store.js'\n );\n await writeRelayUrls({\n projectRoot: server.config.root,\n tunnelBaseUrl: t.url,\n ...(relayHttpUrl !== undefined ? { relayBaseUrl: relayHttpUrl } : {}),\n });\n relayUrlDeleteFn = (root: string) => deleteRelayUrls({ projectRoot: root });\n\n // env-2 HTML dashboard (issue #408): when CDP is wired and a GUI\n // is present, serve the same QR+FAQ dashboard env 3/4 uses and\n // open it in the browser. No-op (returns undefined) for the\n // screen-only tunnel, headless, qr:false, or AIT_AUTO_DEVTOOLS=0\n // — the ASCII QR above remains the fallback in those cases.\n if (relayWssUrl) {\n qrDashboard =\n (await startTunnelDashboard({\n tunnelUrl: t.url,\n relayWssUrl,\n qr: tunnelConfig.qr,\n })) ?? null;\n }\n\n // #420: start watching the parent PID now that tunnel resources\n // are allocated. When the parent dies/reparents, clean up\n // synchronously (stops cloudflared children) then exit.\n parentWatcher = startParentWatcher(() => {\n cleanup();\n process.exit(0);\n });\n })\n .catch((err: unknown) => {\n console.warn(\n `[@ait-co/devtools] tunnel failed to start: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n });\n });\n\n const cleanup = () => {\n parentWatcher?.stop();\n tunnel?.stop();\n relayTunnel?.stop();\n void relay?.close();\n void qrDashboard?.close();\n // env-2 URL file cleanup (#424): remove .ait_urls on teardown so a\n // stale file doesn't cause the MCP daemon to attempt a doomed attach.\n // SECRET-HANDLING: relayUrlDeleteFn never logs the path or URL values.\n void relayUrlDeleteFn?.(server.config.root);\n };\n httpServer?.once('close', cleanup);\n process.once('SIGINT', cleanup);\n process.once('SIGTERM', cleanup);\n process.once('SIGHUP', cleanup);\n process.once('exit', cleanup);\n }\n },\n },\n };\n});\n\nexport const vite = aitDevtoolsPlugin.vite;\nexport const webpack = aitDevtoolsPlugin.webpack;\nexport const rollup = aitDevtoolsPlugin.rollup;\nexport const esbuild = aitDevtoolsPlugin.esbuild;\nexport const rspack = aitDevtoolsPlugin.rspack;\n\nexport default aitDevtoolsPlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,SAAgB,WAAW,KAAsB;AAC/C,KAAI;AACF,UAAQ,KAAK,KAAK,EAAE;AACpB,SAAO;UACA,KAAc;AAGrB,MAAK,IAA8B,SAAS,QAAS,QAAO;AAC5D,SAAO;;;;;;;;;;;;;;;;;;;;;AA0BX,SAAgB,mBACd,YACA,MAOkB;CAClB,MAAM,EACJ,aAAa,KACb,cAAc,QAAQ,MACtB,UAAU,YACV,gBAAgB,QAAQ,MACxB,OAAO,QAAgB,QAAQ,OAAO,MAAM,IAAI,KAC9C,QAAQ,EAAE;AAId,KAAI,eAAe,GAAG;AACpB,MAAI,2EAA2E;AAC/E,SAAO,EAAE,OAAO,IAAI;;CAGtB,IAAI,QAAQ;CAEZ,MAAM,SAAS,kBAAkB;AAC/B,MAAI,MAAO;EAEX,MAAM,cAAc,SAAS;AAG7B,MAFiB,gBAAgB,eAAe,CAAC,QAAQ,YAAY,EAEvD;AACZ,WAAQ;AACR,iBAAc,OAAO;AACrB,OACE,8CAA8C,YAAY,wBAAwB,YAAY,qBAC/F;AACD,eAAY;;IAEb,WAAW;AAEd,QAAO,EACL,OAAO;AACL,gBAAc,OAAO;IAExB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/DH,MAAM,mBAAmB;AACvB,KAAI;AACF,SAAO,cAAc,OAAO,KAAK,QAAQ,wBAAwB,CAAC;SAC5D;AAEN,SAAO;;IAEP;AAsDJ,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,oBAAoB;;AAG1B,MAAM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O,IAAI,GAEnD;QACD;OACJ;KAEF,MAAM,gBAAgB;AACpB,qBAAe,MAAM;AACrB,cAAQ,MAAM;AACd,mBAAa,MAAM;AACd,aAAO,OAAO;AACd,mBAAa,OAAO;AAIpB,yBAAmB,OAAO,OAAO,KAAK;;AAE7C,iBAAY,KAAK,SAAS,QAAQ;AAClC,aAAQ,KAAK,UAAU,QAAQ;AAC/B,aAAQ,KAAK,WAAW,QAAQ;AAChC,aAAQ,KAAK,UAAU,QAAQ;AAC/B,aAAQ,KAAK,QAAQ,QAAQ;;;GAGlC;EACF;EACD;AAEF,MAAa,OAAO,kBAAkB;AACtC,MAAa,UAAU,kBAAkB;AACzC,MAAa,SAAS,kBAAkB;AACxC,MAAa,UAAU,kBAAkB;AACzC,MAAa,SAAS,kBAAkB"}
@@ -77,6 +77,101 @@ async function printTunnelBanner(url, opts = {}) {
77
77
  });
78
78
  }
79
79
  }
80
+ /**
81
+ * Heuristic: can this process open a GUI browser? Mirrors `canOpenBrowser` in
82
+ * `src/mcp/tools.ts` but is re-declared here (not imported) so the tunnel path
83
+ * does not statically pull the heavy MCP `tools.ts` module graph into the lazy
84
+ * `import('./tunnel.js')` chunk. Kept in sync with the MCP copy.
85
+ *
86
+ * - macOS / Windows → assume yes (env-2 dev normally runs on the user's Mac).
87
+ * - Linux → require `DISPLAY` or `WAYLAND_DISPLAY`.
88
+ * - CI (`CI=true`/`CI=1`) → no.
89
+ */
90
+ function canOpenBrowser() {
91
+ if (process.env.CI === "true" || process.env.CI === "1") return false;
92
+ const platform = process.platform;
93
+ if (platform === "darwin" || platform === "win32") return true;
94
+ if (platform === "linux") return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);
95
+ return false;
96
+ }
97
+ /**
98
+ * Env-2 UX parity with env 3/4 (issue #408): when CDP wiring is on and a GUI is
99
+ * available, start the SAME `127.0.0.1` HTML dashboard (QR image + connect steps
100
+ * + FAQ) that the MCP `build_attach_url` path serves, and auto-open it in the
101
+ * browser. headless / opt-out falls back to the terminal ASCII QR (printed
102
+ * separately by {@link printTunnelBanner}).
103
+ *
104
+ * Every part the install-graph invariant depends on (`qrcode`, the MCP HTTP
105
+ * server, the opener) is reached only through dynamic `import()` here, inside
106
+ * the already-lazy `tunnel.js` chunk — nothing is added to the common build
107
+ * graph or the MCP-only install graph.
108
+ *
109
+ * TOTP encapsulation: the dashboard's `getDashboardState` closure mints a FRESH
110
+ * TOTP `at=` code on every call via `generateTotp(secret, Date.now())` and folds
111
+ * it into a fresh `buildLauncherAttachUrl(...)`. Because the QR is re-rendered on
112
+ * each SSE push / page reload from this closure, the code a phone scans is always
113
+ * within its 30 s window — no stale code is baked into static HTML.
114
+ *
115
+ * SECRET-HANDLING: the tunnel host, relay wssUrl, TOTP code, and `.ait_relay`
116
+ * value/path are NEVER written to stdout/stderr/logs here. They live only inside
117
+ * the attach URL (HTML body + `/qr.png` query, per qr-http-server's invariant).
118
+ * The only thing opened/logged is `http://127.0.0.1:<port>` (local, safe).
119
+ *
120
+ * @returns the dashboard handle when it started (caller wires `close()` into the
121
+ * tunnel cleanup), or `undefined` when skipped (no relay, `qr:false`, headless,
122
+ * opt-out, or a start failure) — in which case ASCII QR fallback stands alone.
123
+ */
124
+ async function startTunnelDashboard(opts) {
125
+ const log = opts.log ?? ((m) => console.log(m));
126
+ if (!opts.relayWssUrl) return void 0;
127
+ if (opts.qr === false) return void 0;
128
+ const { isAutoDevtoolsDisabled } = await Promise.resolve().then(() => require("../devtools-opener-h6A-UjzC.cjs"));
129
+ if (!(opts.shouldOpen ?? (() => !isAutoDevtoolsDisabled() && canOpenBrowser()))()) return void 0;
130
+ const { startQrHttpServer } = await Promise.resolve().then(() => require("../qr-http-server-D_Aj5Vq6.cjs"));
131
+ const { buildLauncherAttachUrl } = await Promise.resolve().then(() => require("../deeplink-CCGiyoHq.cjs"));
132
+ const { generateTotp } = await Promise.resolve().then(() => require("../totp-D9rndqg_.cjs"));
133
+ const getDashboardState = () => {
134
+ const secret = process.env.AIT_DEBUG_TOTP_SECRET;
135
+ const totpCode = secret ? generateTotp(secret, Date.now()) : void 0;
136
+ const attachUrl = buildLauncherAttachUrl(opts.tunnelUrl, opts.relayWssUrl, totpCode);
137
+ return {
138
+ tunnel: {
139
+ up: true,
140
+ wssUrl: opts.relayWssUrl
141
+ },
142
+ pages: null,
143
+ attachUrl
144
+ };
145
+ };
146
+ let server;
147
+ try {
148
+ server = await startQrHttpServer(getDashboardState);
149
+ } catch {
150
+ return;
151
+ }
152
+ const dashboardUrl = `http://127.0.0.1:${server.port}`;
153
+ const { openUrlInBrowser } = await Promise.resolve().then(() => require("../devtools-opener-h6A-UjzC.cjs"));
154
+ log(openUrlInBrowser(dashboardUrl) ? ` │ Opened a QR dashboard in your browser: ${dashboardUrl}` : ` │ Open this QR dashboard in your browser: ${dashboardUrl}`);
155
+ return {
156
+ url: dashboardUrl,
157
+ close: () => server.close()
158
+ };
159
+ }
160
+ /**
161
+ * Sanitize cloudflared stderr output for error diagnostics (#421).
162
+ *
163
+ * Masks `*.trycloudflare.com` hostnames and full `https://` / `wss://` URLs
164
+ * that carry those hostnames so tunnel host values never appear in error
165
+ * messages. Diagnostic content (error codes, reasons, JSON blobs) is preserved.
166
+ *
167
+ * SECRET-HANDLING: tunnel host is SECRET-class per harness policy — only
168
+ * placeholder text is emitted.
169
+ */
170
+ function sanitizeCloudflaredOutput(line) {
171
+ let s = line.replace(/(?:https?|wss?):\/\/[a-z0-9-]+\.trycloudflare\.com(?:\/[^\s]*)*/gi, (m) => m.replace(/[a-z0-9-]+\.trycloudflare\.com/i, "<HOST>.trycloudflare.com"));
172
+ s = s.replace(/[a-z0-9-]+\.trycloudflare\.com/gi, "<HOST>.trycloudflare.com");
173
+ return s;
174
+ }
80
175
  const URL_TIMEOUT_MS = 2e4;
81
176
  /**
82
177
  * Start an unauthenticated Cloudflare quick tunnel to `http://localhost:<port>`
@@ -100,10 +195,20 @@ async function startQuickTunnel(port) {
100
195
  } catch {}
101
196
  };
102
197
  return new Promise((resolve, reject) => {
198
+ const stderrLines = [];
199
+ /**
200
+ * Format the last `n` sanitized stderr lines as a diagnostic appendix.
201
+ * Returns an empty string when no lines have been collected.
202
+ */
203
+ const stderrTail = (n = 15) => {
204
+ if (stderrLines.length === 0) return "";
205
+ const tail = stderrLines.slice(-n).map(sanitizeCloudflaredOutput).join("");
206
+ return `\ncloudflared 출력 (마지막 ${Math.min(n, stderrLines.length)}줄):\n${tail}`;
207
+ };
103
208
  const timer = setTimeout(() => {
104
209
  cleanup();
105
210
  stop();
106
- reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] cloudflared did not report a tunnel URL within ${URL_TIMEOUT_MS / 1e3}s. Check your network connection, or run \`cloudflared tunnel --url http://localhost:${port}\` manually.`));
211
+ reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] cloudflared did not report a tunnel URL within ${URL_TIMEOUT_MS / 1e3}s. Check your network connection, or run \`cloudflared tunnel --url http://localhost:${port}\` manually.${stderrTail()}`));
107
212
  }, URL_TIMEOUT_MS);
108
213
  const onUrl = (line) => {
109
214
  const found = parseTrycloudflareUrl(line);
@@ -115,13 +220,18 @@ async function startQuickTunnel(port) {
115
220
  stop
116
221
  });
117
222
  };
223
+ const pushStderr = (line) => {
224
+ stderrLines.push(line);
225
+ };
118
226
  const cleanup = () => {
119
227
  tunnel.off("stdout", onUrl);
120
228
  tunnel.off("stderr", onUrl);
229
+ tunnel.off("stderr", pushStderr);
121
230
  };
122
231
  tunnel.once("url", onUrl);
123
232
  tunnel.on("stdout", onUrl);
124
233
  tunnel.on("stderr", onUrl);
234
+ tunnel.on("stderr", pushStderr);
125
235
  tunnel.once("error", (err) => {
126
236
  clearTimeout(timer);
127
237
  cleanup();
@@ -132,7 +242,7 @@ async function startQuickTunnel(port) {
132
242
  if (stopped) return;
133
243
  clearTimeout(timer);
134
244
  cleanup();
135
- reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] cloudflared exited (code ${code ?? "null"}) before reporting a tunnel URL.`));
245
+ reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] cloudflared exited (code ${code ?? "null"}) before reporting a tunnel URL.${stderrTail()}`));
136
246
  });
137
247
  });
138
248
  }
@@ -140,6 +250,8 @@ async function startQuickTunnel(port) {
140
250
  exports.buildLauncherDeepLink = buildLauncherDeepLink;
141
251
  exports.parseTrycloudflareUrl = parseTrycloudflareUrl;
142
252
  exports.printTunnelBanner = printTunnelBanner;
253
+ exports.sanitizeCloudflaredOutput = sanitizeCloudflaredOutput;
143
254
  exports.startQuickTunnel = startQuickTunnel;
255
+ exports.startTunnelDashboard = startTunnelDashboard;
144
256
 
145
257
  //# sourceMappingURL=tunnel.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tunnel.cjs","names":[],"sources":["../../src/unplugin/tunnel.ts"],"sourcesContent":["/**\n * Cloudflare quick-tunnel helper for the devtools unplugin.\n *\n * Loaded lazily (`await import('./tunnel.js')`) only when the `tunnel` option is\n * on, so `cloudflared` / `qrcode-terminal` are never pulled in for the common\n * case. This is the one place in `@ait-co/devtools` that depends on Node-only\n * APIs (`child_process` via the `cloudflared` wrapper) — keep it thin and out of\n * jsdom unit tests; the spawn path is verified by hand / e2e (same spirit as the\n * \"web 모드는 e2e\" rule in CLAUDE.md). The pure helpers below\n * (`parseTrycloudflareUrl`, `printTunnelBanner`) are unit-tested.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\n\n/** Matches the public URL cloudflared prints for an unauthenticated quick tunnel. */\nconst TRYCLOUDFLARE_RE = /https:\\/\\/[a-z0-9-]+\\.trycloudflare\\.com/i;\n\n/**\n * Extract the `https://<sub>.trycloudflare.com` URL from a line of cloudflared\n * output, or `null` if the line doesn't contain one. Pulled out as a pure\n * function so it can be unit-tested without spawning anything.\n */\nexport function parseTrycloudflareUrl(line: string): string | null {\n const m = line.match(TRYCLOUDFLARE_RE);\n return m ? m[0] : null;\n}\n\nexport interface PrintTunnelBannerOptions {\n /** Print an ASCII QR encoding the tunnel URL (default: true). */\n qr?: boolean;\n /** Sink for the banner text (default: `console.log`). Injected for testing. */\n log?: (msg: string) => void;\n /**\n * The `wss://` relay URL of the env-2 CDP tunnel, if `tunnel.cdp` is on. When\n * present the QR deep-link additionally carries `&debug=1&relay=<wss>` so the\n * framed PWA passes the in-app debug gate and attaches a Chii target — the\n * same single scan opens screen preview *and* CDP debugging.\n */\n relayWssUrl?: string;\n}\n\nconst LAUNCHER_URL = 'https://devtools.aitc.dev/launcher/';\n\n/**\n * Build the deep-link URL that QR codes encode: when the launcher PWA is\n * already on the phone's home screen, scanning this opens it directly into the\n * live view for `tunnelUrl` (the launcher consumes `?url=` and clears it).\n * Plain-text raw URL is no longer enough — the launcher gates its setup UI to\n * the installed PWA, so a raw tunnel URL opened in a normal browser tab would\n * land on a \"please install\" screen.\n *\n * When `relayWssUrl` is given (env-2 CDP wiring), the deep-link also carries\n * `&debug=1&relay=<wss>`; the launcher folds those onto the framed tunnel URL so\n * the in-app debug gate's Layer C (`debug=1` opt-in + `relay=<wss>`) is met and\n * a Chii target.js is injected into the live view.\n */\nexport function buildLauncherDeepLink(tunnelUrl: string, relayWssUrl?: string): string {\n const base = `${LAUNCHER_URL}?url=${encodeURIComponent(tunnelUrl)}`;\n if (!relayWssUrl) return base;\n return `${base}&debug=1&relay=${encodeURIComponent(relayWssUrl)}`;\n}\n\n/**\n * Print the terminal banner announcing the live tunnel: the public URL, an ASCII\n * QR encoding a launcher deep-link, and a one-line note that quick tunnels are\n * ephemeral, unauthenticated and not for production. Pure w.r.t. side effects\n * other than the injected `log` sink and `qrcode-terminal` — unit-tested.\n */\nexport async function printTunnelBanner(\n url: string,\n opts: PrintTunnelBannerOptions = {},\n): Promise<void> {\n const log = opts.log ?? ((m: string) => console.log(m));\n const deepLink = buildLauncherDeepLink(url, opts.relayWssUrl);\n const lines: string[] = [\n '',\n ' ┌─ @ait-co/devtools · live tunnel ────────────────────────────',\n ` │ ${url}`,\n ' │',\n ` │ Install the launcher PWA once: ${LAUNCHER_URL}`,\n ' │ Then scan the QR below — it opens the launcher directly',\n ' │ into this tunnel URL (no manual paste needed).',\n ...(opts.relayWssUrl\n ? [\n ' │ The same scan also attaches CDP — connect your AI host',\n ' │ to the relay and debug the live view on-device.',\n ]\n : []),\n ' │ Quick tunnels are unauthenticated, change every run, and are',\n ' │ not for production use.',\n ' └──────────────────────────────────────────────────────────────',\n '',\n ];\n log(lines.join('\\n'));\n\n if (opts.qr !== false) {\n // qrcode-terminal is only pulled in on this code path (ambient types live\n // in src/qrcode-terminal.d.ts).\n const qrcode = (await import('qrcode-terminal')).default;\n await new Promise<void>((resolve) => {\n qrcode.generate(deepLink, { small: true }, (out) => {\n log(out);\n resolve();\n });\n });\n }\n}\n\nexport interface QuickTunnel {\n /** The public `https://*.trycloudflare.com` URL. */\n url: string;\n /** Stop the underlying `cloudflared` process. Idempotent. */\n stop: () => void;\n}\n\nconst URL_TIMEOUT_MS = 20_000;\n\n/**\n * Start an unauthenticated Cloudflare quick tunnel to `http://localhost:<port>`\n * and resolve once the public URL is known. Downloads the `cloudflared` binary\n * on first use if it is not already installed. Rejects with a friendly error if\n * no URL appears within {@link URL_TIMEOUT_MS}.\n */\nexport async function startQuickTunnel(port: number): Promise<QuickTunnel> {\n const cloudflared = await import('cloudflared');\n const { bin, install, Tunnel } = cloudflared;\n\n if (!existsSync(bin)) {\n await mkdir(dirname(bin), { recursive: true });\n await install(bin);\n }\n\n const tunnel = Tunnel.quick(`http://localhost:${port}`);\n let stopped = false;\n const stop = () => {\n if (stopped) return;\n stopped = true;\n try {\n tunnel.stop();\n } catch {\n // process may already be gone\n }\n };\n\n return new Promise<QuickTunnel>((resolve, reject) => {\n const timer = setTimeout(() => {\n cleanup();\n stop();\n reject(\n new Error(\n `[@ait-co/devtools] cloudflared did not report a tunnel URL within ${\n URL_TIMEOUT_MS / 1000\n }s. Check your network connection, or run \\`cloudflared tunnel --url http://localhost:${port}\\` manually.`,\n ),\n );\n }, URL_TIMEOUT_MS);\n\n const onUrl = (line: string) => {\n const found = parseTrycloudflareUrl(line);\n if (!found) return;\n clearTimeout(timer);\n // Stop scanning further output once we have the URL.\n cleanup();\n resolve({ url: found, stop });\n };\n\n const cleanup = () => {\n tunnel.off('stdout', onUrl);\n tunnel.off('stderr', onUrl);\n };\n\n // The library emits a parsed `url` event; we also scan raw stdout/stderr in\n // case the output format shifts.\n tunnel.once('url', onUrl);\n tunnel.on('stdout', onUrl);\n tunnel.on('stderr', onUrl);\n tunnel.once('error', (err: Error) => {\n clearTimeout(timer);\n cleanup();\n stop();\n reject(err);\n });\n tunnel.once('exit', (code: number | null) => {\n if (stopped) return;\n clearTimeout(timer);\n cleanup();\n reject(\n new Error(\n `[@ait-co/devtools] cloudflared exited (code ${code ?? 'null'}) before reporting a tunnel URL.`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,sBAAsB,MAA6B;CACjE,MAAM,IAAI,KAAK,MAAM,iBAAiB;AACtC,QAAO,IAAI,EAAE,KAAK;;AAiBpB,MAAM,eAAe;;;;;;;;;;;;;;AAerB,SAAgB,sBAAsB,WAAmB,aAA8B;CACrF,MAAM,OAAO,GAAG,aAAa,OAAO,mBAAmB,UAAU;AACjE,KAAI,CAAC,YAAa,QAAO;AACzB,QAAO,GAAG,KAAK,iBAAiB,mBAAmB,YAAY;;;;;;;;AASjE,eAAsB,kBACpB,KACA,OAAiC,EAAE,EACpB;CACf,MAAM,MAAM,KAAK,SAAS,MAAc,QAAQ,IAAI,EAAE;CACtD,MAAM,WAAW,sBAAsB,KAAK,KAAK,YAAY;AAoB7D,KAnBwB;EACtB;EACA;EACA,QAAQ;EACR;EACA,wCAAwC;EACxC;EACA;EACA,GAAI,KAAK,cACL,CACE,+DACA,uDACD,GACD,EAAE;EACN;EACA;EACA;EACA;EACD,CACS,KAAK,KAAK,CAAC;AAErB,KAAI,KAAK,OAAO,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S;AACb,gBAAa,MAAM;AACnB,YAAS;AACT,0BACE,IAAI,MACF,+CAA+C,QAAQ,OAAO,kCAC/D,CACF;IACD;GACF"}
1
+ {"version":3,"file":"tunnel.cjs","names":[],"sources":["../../src/unplugin/tunnel.ts"],"sourcesContent":["/**\n * Cloudflare quick-tunnel helper for the devtools unplugin.\n *\n * Loaded lazily (`await import('./tunnel.js')`) only when the `tunnel` option is\n * on, so `cloudflared` / `qrcode-terminal` are never pulled in for the common\n * case. This is the one place in `@ait-co/devtools` that depends on Node-only\n * APIs (`child_process` via the `cloudflared` wrapper) — keep it thin and out of\n * jsdom unit tests; the spawn path is verified by hand / e2e (same spirit as the\n * \"web 모드는 e2e\" rule in CLAUDE.md). The pure helpers below\n * (`parseTrycloudflareUrl`, `printTunnelBanner`) are unit-tested.\n */\n\nimport { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\n\n/** Matches the public URL cloudflared prints for an unauthenticated quick tunnel. */\nconst TRYCLOUDFLARE_RE = /https:\\/\\/[a-z0-9-]+\\.trycloudflare\\.com/i;\n\n/**\n * Extract the `https://<sub>.trycloudflare.com` URL from a line of cloudflared\n * output, or `null` if the line doesn't contain one. Pulled out as a pure\n * function so it can be unit-tested without spawning anything.\n */\nexport function parseTrycloudflareUrl(line: string): string | null {\n const m = line.match(TRYCLOUDFLARE_RE);\n return m ? m[0] : null;\n}\n\nexport interface PrintTunnelBannerOptions {\n /** Print an ASCII QR encoding the tunnel URL (default: true). */\n qr?: boolean;\n /** Sink for the banner text (default: `console.log`). Injected for testing. */\n log?: (msg: string) => void;\n /**\n * The `wss://` relay URL of the env-2 CDP tunnel, if `tunnel.cdp` is on. When\n * present the QR deep-link additionally carries `&debug=1&relay=<wss>` so the\n * framed PWA passes the in-app debug gate and attaches a Chii target — the\n * same single scan opens screen preview *and* CDP debugging.\n */\n relayWssUrl?: string;\n}\n\nconst LAUNCHER_URL = 'https://devtools.aitc.dev/launcher/';\n\n/**\n * Build the deep-link URL that QR codes encode: when the launcher PWA is\n * already on the phone's home screen, scanning this opens it directly into the\n * live view for `tunnelUrl` (the launcher consumes `?url=` and clears it).\n * Plain-text raw URL is no longer enough — the launcher gates its setup UI to\n * the installed PWA, so a raw tunnel URL opened in a normal browser tab would\n * land on a \"please install\" screen.\n *\n * When `relayWssUrl` is given (env-2 CDP wiring), the deep-link also carries\n * `&debug=1&relay=<wss>`; the launcher folds those onto the framed tunnel URL so\n * the in-app debug gate's Layer C (`debug=1` opt-in + `relay=<wss>`) is met and\n * a Chii target.js is injected into the live view.\n */\nexport function buildLauncherDeepLink(tunnelUrl: string, relayWssUrl?: string): string {\n const base = `${LAUNCHER_URL}?url=${encodeURIComponent(tunnelUrl)}`;\n if (!relayWssUrl) return base;\n return `${base}&debug=1&relay=${encodeURIComponent(relayWssUrl)}`;\n}\n\n/**\n * Print the terminal banner announcing the live tunnel: the public URL, an ASCII\n * QR encoding a launcher deep-link, and a one-line note that quick tunnels are\n * ephemeral, unauthenticated and not for production. Pure w.r.t. side effects\n * other than the injected `log` sink and `qrcode-terminal` — unit-tested.\n */\nexport async function printTunnelBanner(\n url: string,\n opts: PrintTunnelBannerOptions = {},\n): Promise<void> {\n const log = opts.log ?? ((m: string) => console.log(m));\n const deepLink = buildLauncherDeepLink(url, opts.relayWssUrl);\n const lines: string[] = [\n '',\n ' ┌─ @ait-co/devtools · live tunnel ────────────────────────────',\n ` │ ${url}`,\n ' │',\n ` │ Install the launcher PWA once: ${LAUNCHER_URL}`,\n ' │ Then scan the QR below — it opens the launcher directly',\n ' │ into this tunnel URL (no manual paste needed).',\n ...(opts.relayWssUrl\n ? [\n ' │ The same scan also attaches CDP — connect your AI host',\n ' │ to the relay and debug the live view on-device.',\n ]\n : []),\n ' │ Quick tunnels are unauthenticated, change every run, and are',\n ' │ not for production use.',\n ' └──────────────────────────────────────────────────────────────',\n '',\n ];\n log(lines.join('\\n'));\n\n if (opts.qr !== false) {\n // qrcode-terminal is only pulled in on this code path (ambient types live\n // in src/qrcode-terminal.d.ts).\n const qrcode = (await import('qrcode-terminal')).default;\n await new Promise<void>((resolve) => {\n qrcode.generate(deepLink, { small: true }, (out) => {\n log(out);\n resolve();\n });\n });\n }\n}\n\n/**\n * Heuristic: can this process open a GUI browser? Mirrors `canOpenBrowser` in\n * `src/mcp/tools.ts` but is re-declared here (not imported) so the tunnel path\n * does not statically pull the heavy MCP `tools.ts` module graph into the lazy\n * `import('./tunnel.js')` chunk. Kept in sync with the MCP copy.\n *\n * - macOS / Windows → assume yes (env-2 dev normally runs on the user's Mac).\n * - Linux → require `DISPLAY` or `WAYLAND_DISPLAY`.\n * - CI (`CI=true`/`CI=1`) → no.\n */\nfunction canOpenBrowser(): boolean {\n if (process.env.CI === 'true' || process.env.CI === '1') return false;\n const platform = process.platform;\n if (platform === 'darwin' || platform === 'win32') return true;\n if (platform === 'linux') {\n return Boolean(process.env.DISPLAY ?? process.env.WAYLAND_DISPLAY);\n }\n return false;\n}\n\n/** Handle returned by {@link startTunnelDashboard}. */\nexport interface TunnelDashboard {\n /** `http://127.0.0.1:<port>` — the local dashboard URL opened in the browser. */\n url: string;\n /** Tear down the local HTTP server. Idempotent via the underlying server. */\n close: () => Promise<void>;\n}\n\nexport interface StartTunnelDashboardOptions {\n /** The public `https://*.trycloudflare.com` app tunnel URL the launcher frames. */\n tunnelUrl: string;\n /** The `wss://` relay URL of the env-2 CDP tunnel. REQUIRED — the dashboard is a CDP-only UX. */\n relayWssUrl: string;\n /** Mirror of `tunnel.qr` — when `false` the dashboard is skipped (no browser open). */\n qr?: boolean;\n /**\n * Override the GUI/opt-out gate (testing only). When omitted the real\n * `canOpenBrowser()` + `AIT_AUTO_DEVTOOLS` checks decide.\n */\n shouldOpen?: () => boolean;\n /** Sink for the one-line \"opened in browser\" note (default: `console.log`). Injected for testing. */\n log?: (msg: string) => void;\n}\n\n/**\n * Env-2 UX parity with env 3/4 (issue #408): when CDP wiring is on and a GUI is\n * available, start the SAME `127.0.0.1` HTML dashboard (QR image + connect steps\n * + FAQ) that the MCP `build_attach_url` path serves, and auto-open it in the\n * browser. headless / opt-out falls back to the terminal ASCII QR (printed\n * separately by {@link printTunnelBanner}).\n *\n * Every part the install-graph invariant depends on (`qrcode`, the MCP HTTP\n * server, the opener) is reached only through dynamic `import()` here, inside\n * the already-lazy `tunnel.js` chunk — nothing is added to the common build\n * graph or the MCP-only install graph.\n *\n * TOTP encapsulation: the dashboard's `getDashboardState` closure mints a FRESH\n * TOTP `at=` code on every call via `generateTotp(secret, Date.now())` and folds\n * it into a fresh `buildLauncherAttachUrl(...)`. Because the QR is re-rendered on\n * each SSE push / page reload from this closure, the code a phone scans is always\n * within its 30 s window — no stale code is baked into static HTML.\n *\n * SECRET-HANDLING: the tunnel host, relay wssUrl, TOTP code, and `.ait_relay`\n * value/path are NEVER written to stdout/stderr/logs here. They live only inside\n * the attach URL (HTML body + `/qr.png` query, per qr-http-server's invariant).\n * The only thing opened/logged is `http://127.0.0.1:<port>` (local, safe).\n *\n * @returns the dashboard handle when it started (caller wires `close()` into the\n * tunnel cleanup), or `undefined` when skipped (no relay, `qr:false`, headless,\n * opt-out, or a start failure) — in which case ASCII QR fallback stands alone.\n */\nexport async function startTunnelDashboard(\n opts: StartTunnelDashboardOptions,\n): Promise<TunnelDashboard | undefined> {\n const log = opts.log ?? ((m: string) => console.log(m));\n\n // Gate: dashboard is a CDP-only UX (needs a relay to attach to).\n if (!opts.relayWssUrl) return undefined;\n // Opt-out via `tunnel.qr:false` (same toggle that suppresses the ASCII QR).\n if (opts.qr === false) return undefined;\n\n // GUI + AIT_AUTO_DEVTOOLS gate. Reuse the MCP opener's opt-out predicate so\n // the env-2 path honours the same `AIT_AUTO_DEVTOOLS=0` switch as env 3/4.\n const { isAutoDevtoolsDisabled } = await import('../mcp/devtools-opener.js');\n const gateOpen = opts.shouldOpen ?? (() => !isAutoDevtoolsDisabled() && canOpenBrowser());\n if (!gateOpen()) return undefined;\n\n const { startQrHttpServer } = await import('../mcp/qr-http-server.js');\n const { buildLauncherAttachUrl } = await import('../mcp/deeplink.js');\n const { generateTotp } = await import('../mcp/totp.js');\n\n // getDashboardState — mints a fresh TOTP + attach URL on every call so the QR\n // the dashboard renders (on load and on each SSE push) is never expired.\n // SECRET-HANDLING: the secret is read from env AT CALL TIME (it was injected\n // by ensureRelaySecret in the same CDP block) and is used only to compute the\n // at= code folded into attachUrl. tunnel.up is always true here — the relay\n // tunnel is already up by the time this runs.\n const getDashboardState = () => {\n const secret = process.env.AIT_DEBUG_TOTP_SECRET;\n const totpCode = secret ? generateTotp(secret, Date.now()) : undefined;\n const attachUrl = buildLauncherAttachUrl(opts.tunnelUrl, opts.relayWssUrl, totpCode);\n // pages: null — env 2(unplugin)는 데몬이 아니라 vite 플러그인 안이라\n // startChiiRelay 핸들이 connected target을 노출하지 않는다. 라이브 page 목록을\n // 알 수 없으므로 거짓 빈 목록 대신 \"연결된 Pages\" 섹션 자체를 숨긴다(#411).\n // env 3/4(debug-server.ts)는 router.active.listTargets()로 실제 목록을 채운다.\n return { tunnel: { up: true, wssUrl: opts.relayWssUrl }, pages: null, attachUrl };\n };\n\n let server: Awaited<ReturnType<typeof startQrHttpServer>>;\n try {\n server = await startQrHttpServer(getDashboardState);\n } catch {\n // SECRET-HANDLING: do not surface the error (could embed paths/hosts). The\n // ASCII QR printed by printTunnelBanner stays as the fallback.\n return undefined;\n }\n\n const dashboardUrl = `http://127.0.0.1:${server.port}`;\n\n const { openUrlInBrowser } = await import('../mcp/devtools-opener.js');\n const opened = openUrlInBrowser(dashboardUrl);\n // SECRET-HANDLING: only the local 127.0.0.1 URL is logged — never the tunnel\n // host, relay wssUrl, or TOTP code.\n log(\n opened\n ? ` │ Opened a QR dashboard in your browser: ${dashboardUrl}`\n : ` │ Open this QR dashboard in your browser: ${dashboardUrl}`,\n );\n\n return {\n url: dashboardUrl,\n close: () => server.close(),\n };\n}\n\nexport interface QuickTunnel {\n /** The public `https://*.trycloudflare.com` URL. */\n url: string;\n /** Stop the underlying `cloudflared` process. Idempotent. */\n stop: () => void;\n}\n\n/**\n * Sanitize cloudflared stderr output for error diagnostics (#421).\n *\n * Masks `*.trycloudflare.com` hostnames and full `https://` / `wss://` URLs\n * that carry those hostnames so tunnel host values never appear in error\n * messages. Diagnostic content (error codes, reasons, JSON blobs) is preserved.\n *\n * SECRET-HANDLING: tunnel host is SECRET-class per harness policy — only\n * placeholder text is emitted.\n */\nexport function sanitizeCloudflaredOutput(line: string): string {\n // Full URL forms: https://xxx.trycloudflare.com/… and wss://xxx.trycloudflare.com/…\n let s = line.replace(/(?:https?|wss?):\\/\\/[a-z0-9-]+\\.trycloudflare\\.com(?:\\/[^\\s]*)*/gi, (m) =>\n m.replace(/[a-z0-9-]+\\.trycloudflare\\.com/i, '<HOST>.trycloudflare.com'),\n );\n // Bare hostname without scheme (e.g. printed in cloudflared JSON logs)\n s = s.replace(/[a-z0-9-]+\\.trycloudflare\\.com/gi, '<HOST>.trycloudflare.com');\n return s;\n}\n\nconst URL_TIMEOUT_MS = 20_000;\n\n/**\n * Start an unauthenticated Cloudflare quick tunnel to `http://localhost:<port>`\n * and resolve once the public URL is known. Downloads the `cloudflared` binary\n * on first use if it is not already installed. Rejects with a friendly error if\n * no URL appears within {@link URL_TIMEOUT_MS}.\n */\nexport async function startQuickTunnel(port: number): Promise<QuickTunnel> {\n const cloudflared = await import('cloudflared');\n const { bin, install, Tunnel } = cloudflared;\n\n if (!existsSync(bin)) {\n await mkdir(dirname(bin), { recursive: true });\n await install(bin);\n }\n\n const tunnel = Tunnel.quick(`http://localhost:${port}`);\n let stopped = false;\n const stop = () => {\n if (stopped) return;\n stopped = true;\n try {\n tunnel.stop();\n } catch {\n // process may already be gone\n }\n };\n\n return new Promise<QuickTunnel>((resolve, reject) => {\n // #421: accumulate stderr to attach as diagnostics on failure.\n // SECRET-HANDLING: lines are sanitized before inclusion in error messages.\n const stderrLines: string[] = [];\n\n /**\n * Format the last `n` sanitized stderr lines as a diagnostic appendix.\n * Returns an empty string when no lines have been collected.\n */\n const stderrTail = (n = 15): string => {\n if (stderrLines.length === 0) return '';\n const tail = stderrLines.slice(-n).map(sanitizeCloudflaredOutput).join('');\n return `\\ncloudflared 출력 (마지막 ${Math.min(n, stderrLines.length)}줄):\\n${tail}`;\n };\n\n const timer = setTimeout(() => {\n cleanup();\n stop();\n reject(\n new Error(\n `[@ait-co/devtools] cloudflared did not report a tunnel URL within ${\n URL_TIMEOUT_MS / 1000\n }s. Check your network connection, or run \\`cloudflared tunnel --url http://localhost:${port}\\` manually.${stderrTail()}`,\n ),\n );\n }, URL_TIMEOUT_MS);\n\n const onUrl = (line: string) => {\n const found = parseTrycloudflareUrl(line);\n if (!found) return;\n clearTimeout(timer);\n // Stop scanning further output once we have the URL.\n cleanup();\n resolve({ url: found, stop });\n };\n\n // Accumulate stderr lines for diagnostics (#421). Named so it can be\n // removed from the listener list when cleanup() runs.\n const pushStderr = (line: string) => {\n stderrLines.push(line);\n };\n\n const cleanup = () => {\n tunnel.off('stdout', onUrl);\n tunnel.off('stderr', onUrl);\n tunnel.off('stderr', pushStderr);\n };\n\n // The library emits a parsed `url` event; we also scan raw stdout/stderr in\n // case the output format shifts.\n tunnel.once('url', onUrl);\n tunnel.on('stdout', onUrl);\n tunnel.on('stderr', onUrl);\n // Second stderr listener: accumulate all lines for error diagnostics.\n tunnel.on('stderr', pushStderr);\n tunnel.once('error', (err: Error) => {\n clearTimeout(timer);\n cleanup();\n stop();\n reject(err);\n });\n tunnel.once('exit', (code: number | null) => {\n if (stopped) return;\n clearTimeout(timer);\n cleanup();\n reject(\n new Error(\n `[@ait-co/devtools] cloudflared exited (code ${code ?? 'null'}) before reporting a tunnel URL.${stderrTail()}`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,mBAAmB;;;;;;AAOzB,SAAgB,sBAAsB,MAA6B;CACjE,MAAM,IAAI,KAAK,MAAM,iBAAiB;AACtC,QAAO,IAAI,EAAE,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,IAAI;IACX;AACF,SAAO,KAAK,SAAS,SAAwB;AAC3C,OAAI,QAAS;AACb,gBAAa,MAAM;AACnB,YAAS;AACT,0BACE,IAAI,MACF,+CAA+C,QAAQ,OAAO,kCAAkC,YAAY,GAC7G,CACF;IACD;GACF"}
@@ -50,12 +50,73 @@ declare function buildLauncherDeepLink(tunnelUrl: string, relayWssUrl?: string):
50
50
  * other than the injected `log` sink and `qrcode-terminal` — unit-tested.
51
51
  */
52
52
  declare function printTunnelBanner(url: string, opts?: PrintTunnelBannerOptions): Promise<void>;
53
+ /** Handle returned by {@link startTunnelDashboard}. */
54
+ interface TunnelDashboard {
55
+ /** `http://127.0.0.1:<port>` — the local dashboard URL opened in the browser. */
56
+ url: string;
57
+ /** Tear down the local HTTP server. Idempotent via the underlying server. */
58
+ close: () => Promise<void>;
59
+ }
60
+ interface StartTunnelDashboardOptions {
61
+ /** The public `https://*.trycloudflare.com` app tunnel URL the launcher frames. */
62
+ tunnelUrl: string;
63
+ /** The `wss://` relay URL of the env-2 CDP tunnel. REQUIRED — the dashboard is a CDP-only UX. */
64
+ relayWssUrl: string;
65
+ /** Mirror of `tunnel.qr` — when `false` the dashboard is skipped (no browser open). */
66
+ qr?: boolean;
67
+ /**
68
+ * Override the GUI/opt-out gate (testing only). When omitted the real
69
+ * `canOpenBrowser()` + `AIT_AUTO_DEVTOOLS` checks decide.
70
+ */
71
+ shouldOpen?: () => boolean;
72
+ /** Sink for the one-line "opened in browser" note (default: `console.log`). Injected for testing. */
73
+ log?: (msg: string) => void;
74
+ }
75
+ /**
76
+ * Env-2 UX parity with env 3/4 (issue #408): when CDP wiring is on and a GUI is
77
+ * available, start the SAME `127.0.0.1` HTML dashboard (QR image + connect steps
78
+ * + FAQ) that the MCP `build_attach_url` path serves, and auto-open it in the
79
+ * browser. headless / opt-out falls back to the terminal ASCII QR (printed
80
+ * separately by {@link printTunnelBanner}).
81
+ *
82
+ * Every part the install-graph invariant depends on (`qrcode`, the MCP HTTP
83
+ * server, the opener) is reached only through dynamic `import()` here, inside
84
+ * the already-lazy `tunnel.js` chunk — nothing is added to the common build
85
+ * graph or the MCP-only install graph.
86
+ *
87
+ * TOTP encapsulation: the dashboard's `getDashboardState` closure mints a FRESH
88
+ * TOTP `at=` code on every call via `generateTotp(secret, Date.now())` and folds
89
+ * it into a fresh `buildLauncherAttachUrl(...)`. Because the QR is re-rendered on
90
+ * each SSE push / page reload from this closure, the code a phone scans is always
91
+ * within its 30 s window — no stale code is baked into static HTML.
92
+ *
93
+ * SECRET-HANDLING: the tunnel host, relay wssUrl, TOTP code, and `.ait_relay`
94
+ * value/path are NEVER written to stdout/stderr/logs here. They live only inside
95
+ * the attach URL (HTML body + `/qr.png` query, per qr-http-server's invariant).
96
+ * The only thing opened/logged is `http://127.0.0.1:<port>` (local, safe).
97
+ *
98
+ * @returns the dashboard handle when it started (caller wires `close()` into the
99
+ * tunnel cleanup), or `undefined` when skipped (no relay, `qr:false`, headless,
100
+ * opt-out, or a start failure) — in which case ASCII QR fallback stands alone.
101
+ */
102
+ declare function startTunnelDashboard(opts: StartTunnelDashboardOptions): Promise<TunnelDashboard | undefined>;
53
103
  interface QuickTunnel {
54
104
  /** The public `https://*.trycloudflare.com` URL. */
55
105
  url: string;
56
106
  /** Stop the underlying `cloudflared` process. Idempotent. */
57
107
  stop: () => void;
58
108
  }
109
+ /**
110
+ * Sanitize cloudflared stderr output for error diagnostics (#421).
111
+ *
112
+ * Masks `*.trycloudflare.com` hostnames and full `https://` / `wss://` URLs
113
+ * that carry those hostnames so tunnel host values never appear in error
114
+ * messages. Diagnostic content (error codes, reasons, JSON blobs) is preserved.
115
+ *
116
+ * SECRET-HANDLING: tunnel host is SECRET-class per harness policy — only
117
+ * placeholder text is emitted.
118
+ */
119
+ declare function sanitizeCloudflaredOutput(line: string): string;
59
120
  /**
60
121
  * Start an unauthenticated Cloudflare quick tunnel to `http://localhost:<port>`
61
122
  * and resolve once the public URL is known. Downloads the `cloudflared` binary
@@ -64,5 +125,5 @@ interface QuickTunnel {
64
125
  */
65
126
  declare function startQuickTunnel(port: number): Promise<QuickTunnel>;
66
127
  //#endregion
67
- export { PrintTunnelBannerOptions, QuickTunnel, buildLauncherDeepLink, parseTrycloudflareUrl, printTunnelBanner, startQuickTunnel };
128
+ export { PrintTunnelBannerOptions, QuickTunnel, StartTunnelDashboardOptions, TunnelDashboard, buildLauncherDeepLink, parseTrycloudflareUrl, printTunnelBanner, sanitizeCloudflaredOutput, startQuickTunnel, startTunnelDashboard };
68
129
  //# sourceMappingURL=tunnel.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tunnel.d.cts","names":[],"sources":["../../src/unplugin/tunnel.ts"],"mappings":";;AAwBA;;;;;AAKA;;;;;;;;;;iBALgB,qBAAA,CAAsB,IAAA;AAAA,UAKrB,wBAAA;;EAEf,EAAA;EA2B2E;EAzB3E,GAAA,IAAO,GAAA;EAqC8B;;;;;;EA9BrC,WAAA;AAAA;;AAsEF;;;;;AAeA;;;;;;;iBAnEgB,qBAAA,CAAsB,SAAA,UAAmB,WAAA;;;;;;;iBAYnC,iBAAA,CACpB,GAAA,UACA,IAAA,GAAM,wBAAA,GACL,OAAA;AAAA,UAqCc,WAAA;;EAEf,GAAA;;EAEA,IAAA;AAAA;;;;;;;iBAWoB,gBAAA,CAAiB,IAAA,WAAe,OAAA,CAAQ,WAAA"}
1
+ {"version":3,"file":"tunnel.d.cts","names":[],"sources":["../../src/unplugin/tunnel.ts"],"mappings":";;AAwBA;;;;;AAKA;;;;;;;;;;iBALgB,qBAAA,CAAsB,IAAA;AAAA,UAKrB,wBAAA;;EAEf,EAAA;EA2B2E;EAzB3E,GAAA,IAAO,GAAA;EAqC8B;;;;;;EA9BrC,WAAA;AAAA;;AA2FF;;;;;;;;;AAOA;;;iBAhFgB,qBAAA,CAAsB,SAAA,UAAmB,WAAA;;;;;;;iBAYnC,iBAAA,CACpB,GAAA,UACA,IAAA,GAAM,wBAAA,GACL,OAAA;;UA0Dc,eAAA;E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