@lark-apaas/coding-html-devserver 0.1.13 → 0.1.14-alpha.20261126030250

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.
@@ -1,4 +1,5 @@
1
1
  import type { Plugin } from 'vite';
2
+ export declare const TOKEN_SCRIPT_PATH = "/@miaoda-hmr-token.js";
2
3
  /** 浏览器侧全局变量名:本插件写入,vite-client-patch 的 patch 2 在建链时读取。 */
3
4
  export declare const HMR_WS_TOKEN_GLOBAL = "__MIAODA_HMR_WS_TOKEN__";
4
5
  /**
@@ -33,12 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.HMR_WS_TOKEN_GLOBAL = void 0;
36
+ exports.HMR_WS_TOKEN_GLOBAL = exports.TOKEN_SCRIPT_PATH = void 0;
37
37
  exports.readHmrWsToken = readHmrWsToken;
38
38
  exports.hmrTokenPlugin = hmrTokenPlugin;
39
39
  const fs = __importStar(require("node:fs"));
40
40
  const path = __importStar(require("node:path"));
41
- const TOKEN_SCRIPT_PATH = '/@miaoda-hmr-token.js';
41
+ exports.TOKEN_SCRIPT_PATH = '/@miaoda-hmr-token.js';
42
42
  /** 浏览器侧全局变量名:本插件写入,vite-client-patch 的 patch 2 在建链时读取。 */
43
43
  exports.HMR_WS_TOKEN_GLOBAL = '__MIAODA_HMR_WS_TOKEN__';
44
44
  const ENV_KEY = 'MIAODA_HMR_WS_TOKEN';
@@ -84,7 +84,7 @@ function readHmrWsToken() {
84
84
  * 仅 dev(`apply: 'serve'`),token 绝不进 build 产物。
85
85
  */
86
86
  function hmrTokenPlugin(options = {}) {
87
- const scriptPath = (options.clientBasePath ?? '') + TOKEN_SCRIPT_PATH;
87
+ const scriptPath = (options.clientBasePath ?? '') + exports.TOKEN_SCRIPT_PATH;
88
88
  return {
89
89
  name: 'miaoda-hmr-token',
90
90
  apply: 'serve',
@@ -92,10 +92,28 @@ function hmrTokenPlugin(options = {}) {
92
92
  server.middlewares.use((req, res, next) => {
93
93
  if (req.url?.split('?')[0] !== scriptPath)
94
94
  return next();
95
- res.setHeader('Content-Type', 'application/javascript');
95
+ // JSON 查询交给后置中间件,沿用 Vite 的 host 校验和 base 处理。
96
+ if (req.headers.accept === 'application/json')
97
+ return next();
96
98
  res.setHeader('Cache-Control', 'no-store');
99
+ res.setHeader('Content-Type', 'application/javascript');
97
100
  res.end(`window.${exports.HMR_WS_TOKEN_GLOBAL} = ${JSON.stringify(readHmrWsToken())};`);
98
101
  });
102
+ return () => {
103
+ server.middlewares.use((req, res, next) => {
104
+ if (req.url?.split('?')[0] !== exports.TOKEN_SCRIPT_PATH || req.headers.accept !== 'application/json')
105
+ return next();
106
+ res.setHeader('Cache-Control', 'no-store');
107
+ res.setHeader('X-Content-Type-Options', 'nosniff');
108
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
109
+ if (req.method !== 'GET' || req.headers['sec-fetch-site'] !== 'same-origin') {
110
+ res.statusCode = 403;
111
+ return res.end();
112
+ }
113
+ res.setHeader('Content-Type', 'application/json');
114
+ res.end(JSON.stringify({ token: server.config.webSocketToken }));
115
+ });
116
+ };
99
117
  },
100
118
  transformIndexHtml() {
101
119
  const tags = [
@@ -1,3 +1,5 @@
1
1
  import type { Plugin } from 'vite';
2
+ export declare function hasViteInstanceChanged(tokenUrl: URL, pageToken: string): Promise<boolean>;
3
+ export declare function notifyParentConnected(configuredOrigin: string): void;
2
4
  export declare function viteClientPatchPlugin(): Plugin;
3
5
  export default viteClientPatchPlugin;
@@ -1,24 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasViteInstanceChanged = hasViteInstanceChanged;
4
+ exports.notifyParentConnected = notifyParentConnected;
3
5
  exports.viteClientPatchPlugin = viteClientPatchPlugin;
4
6
  const hmr_token_1 = require("./hmr-token");
5
7
  /**
6
- * 抑制 `@vite/client` 在 HMR WS 重连成功后的 `location.reload()`。
7
- *
8
- * 背景(沙箱反向代理场景):电脑休眠唤醒后 WS 断连重连。Vite 客户端走
9
- * `waitForSuccessfulPing()` 用新 TCP 连接握手成功,立刻发 `location.reload()`;
10
- * 但 reload 用的是浏览器 HTTP/2 连接池里复用的休眠前死连接,
11
- * 导致 ~18s `ERR_CONNECTION_TIMED_OUT` 白屏。
12
- *
13
- * 解:transform 拦截 `vite/dist/client/client.mjs`,把 reload 换成 WS 重连——重连与
14
- * 探活同为 WebSocket 通道,不碰 HTTP/2 连接池,上述白屏不再触发;失败只打 warn,
15
- * 由用户决定是否刷新。顺带保住探活地址上的 `sandbox_token`:Vite 原本 `url.search = ""`
16
- * 会把它一起抹掉,导致探活恒被沙箱网关 401(`ws_proxy_service.go` 的 `token == ""`)。
8
+ * 断线探活保留沙箱 token。探活成功后向原 token 脚本查询一次 Vite 实例是否变化。
9
+ * 仅在确认实例变化时刷新预览,加载新实例的模块图。同一实例沿用原 WS 重连,查询失败时有限重试,
10
+ * 避免休眠唤醒后因无条件刷新而把仍可用的页面替换成超时白屏。
17
11
  *
18
12
  * 仅 dev(`apply: 'serve'`)。
19
- *
20
- * 行为对齐 `@lark-apaas/coding-preset-vite-react` 的同名插件 —— html stack 跑在
21
- * 同一套沙箱反代链路里,重连白屏与 WS 鉴权两个问题同样成立。
22
13
  */
23
14
  const DISCONNECT_RECOVERY_PATTERN = /url\.search = "";\r?\n(\s*)await waitForSuccessfulPing\(url\.href\);\r?\n\s*location\.reload\(\);/;
24
15
  /**
@@ -63,6 +54,58 @@ const CONNECTED_LOG_PATTERN = /console\.debug\((`\[vite\] connected\.`)\)/;
63
54
  */
64
55
  const PING_IN_WORKER_PATTERN = /(function waitForSuccessfulPing\(socketUrl\) \{\s*if \()typeof SharedWorker === "undefined"(\))/;
65
56
  const PING_IN_PAGE_MARKER = /function waitForSuccessfulPing\(socketUrl\) \{\s*if \(true\)/;
57
+ // 注入 @vite/client 后在浏览器执行,依赖由参数传入。
58
+ async function hasViteInstanceChanged(tokenUrl, pageToken) {
59
+ const maxAttempts = 5;
60
+ for (let attempt = 1;; attempt++) {
61
+ try {
62
+ const response = await fetch(tokenUrl, {
63
+ mode: 'same-origin',
64
+ cache: 'no-store',
65
+ headers: { Accept: 'application/json' },
66
+ signal: AbortSignal.timeout(3000),
67
+ });
68
+ if (!response.ok)
69
+ throw new Error(`HTTP ${response.status}`);
70
+ const { token } = await response.json();
71
+ if (typeof token !== 'string' || !token)
72
+ throw new Error('Missing Vite token');
73
+ return token !== pageToken;
74
+ }
75
+ catch (error) {
76
+ if (attempt === maxAttempts)
77
+ throw error;
78
+ await new Promise(resolve => setTimeout(resolve, 500 * attempt));
79
+ }
80
+ }
81
+ }
82
+ // 此函数随 transform 写入浏览器客户端。只发送连接状态,不携带握手参数。
83
+ function notifyParentConnected(configuredOrigin) {
84
+ if (typeof window === 'undefined' || window.parent === window)
85
+ return;
86
+ try {
87
+ let target = new URLSearchParams(window.location.search).get('__parentOrigin');
88
+ if (!target) {
89
+ try {
90
+ target = window.sessionStorage.getItem('__parentOrigin');
91
+ }
92
+ catch { /* storage unavailable */ }
93
+ }
94
+ target ||= configuredOrigin || window.location.ancestorOrigins?.[0] || document.referrer;
95
+ if (!target)
96
+ return;
97
+ const url = new URL(target);
98
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
99
+ return;
100
+ window.parent.postMessage({
101
+ type: 'DevServerMessage',
102
+ data: { type: 'devServer-status', status: 'connected' },
103
+ }, url.origin);
104
+ }
105
+ catch (error) {
106
+ console.warn('[miaoda-html-vite-client-patch] Could not notify the preview host.', error);
107
+ }
108
+ }
66
109
  function viteClientPatchPlugin() {
67
110
  return {
68
111
  name: 'miaoda-html-vite-client-patch',
@@ -72,16 +115,33 @@ function viteClientPatchPlugin() {
72
115
  if (!id.includes('vite/dist/client/client.mjs'))
73
116
  return;
74
117
  let patched = code;
75
- // patch 1: 重写断线恢复——探活保住 sandbox_token,探活成功后重连(失败只打 warn)
118
+ // patch 1: 探活保住 sandbox_token,Vite 实例变更才刷新预览。
76
119
  if (DISCONNECT_RECOVERY_PATTERN.test(patched)) {
77
- patched = patched.replace(DISCONNECT_RECOVERY_PATTERN, (_, indent) => 'const __st = url.searchParams.get("sandbox_token");\n' +
78
- indent +
79
- 'url.search = __st ? "?sandbox_token=" + encodeURIComponent(__st) : "";\n' +
80
- indent +
81
- 'await waitForSuccessfulPing(url.href);\n' +
82
- indent +
83
- 'transport.connect(createHMRHandler(handleMessage)).catch((e) => { ' +
84
- "console.warn('[miaoda-html-vite-client-patch] HMR reconnect failed (ignored):', e); });");
120
+ let checkInstance = '';
121
+ if (/\bconst wsToken\s*=/.test(patched)) {
122
+ patched = `const hasViteInstanceChanged = ${hasViteInstanceChanged.toString()};\n${patched}`;
123
+ checkInstance = `
124
+ const tokenUrl = new URL(${JSON.stringify('..' + hmr_token_1.TOKEN_SCRIPT_PATH)}, import.meta.url);
125
+ try {
126
+ if (await hasViteInstanceChanged(tokenUrl, wsToken)) {
127
+ location.reload();
128
+ return;
129
+ }
130
+ } catch (error) {
131
+ console.warn("[miaoda-html-vite-client-patch] Preview unavailable", error);
132
+ return;
133
+ }`;
134
+ }
135
+ else {
136
+ console.warn('[miaoda-html-vite-client-patch] wsToken declaration missing; using existing reconnect.');
137
+ }
138
+ const recovery = `const __st = url.searchParams.get("sandbox_token");
139
+ url.search = __st ? "?sandbox_token=" + encodeURIComponent(__st) : "";
140
+ await waitForSuccessfulPing(url.href);${checkInstance}
141
+ transport.connect(createHMRHandler(handleMessage)).catch((error) => {
142
+ console.warn('[miaoda-html-vite-client-patch] HMR reconnect failed (ignored):', error);
143
+ });`;
144
+ patched = patched.replace(DISCONNECT_RECOVERY_PATTERN, (_, indent) => recovery.replace(/\n/g, '\n' + indent));
85
145
  }
86
146
  else {
87
147
  console.warn('[miaoda-html-vite-client-patch] disconnect-recovery pattern not found in @vite/client. ' +
@@ -113,7 +173,8 @@ function viteClientPatchPlugin() {
113
173
  }
114
174
  // patch 5: 连接成功日志 debug → log,让 client-toolkit 的 console 劫持能收到
115
175
  if (CONNECTED_LOG_PATTERN.test(patched)) {
116
- patched = patched.replace(CONNECTED_LOG_PATTERN, 'console.log($1)');
176
+ const origin = JSON.stringify(process.env.FORCE_FRAMEWORK_DOMAIN_MAIN || '');
177
+ patched = patched.replace(CONNECTED_LOG_PATTERN, (_, message) => `console.log(${message}); (${notifyParentConnected.toString()})(${origin})`);
117
178
  }
118
179
  else {
119
180
  console.warn('[miaoda-html-vite-client-patch] connected-log pattern not found in @vite/client; ' +
@@ -23,9 +23,9 @@ export interface HtmlViteOptions {
23
23
  * + runtime-url-fix(撕掉 vite 给后端运行时绝对 URL 误加的 base 前缀)。
24
24
  *
25
25
  * 沙箱 WS 韧性(dev only,对齐 coding-preset-vite-react):
26
- * - `viteClientPatchPlugin`:删 WS 重连后的 `location.reload()`(休眠唤醒白屏),
26
+ * - `viteClientPatchPlugin`:探活后仅在 Vite 实例变化时刷新预览,同一实例直接重连,
27
27
  * 并让 HMR 长链 URL 在建链时取页面上的 `sandbox_token`(穿网关鉴权)。
28
- * - `hmrTokenPlugin`:每次页面加载现读 env 文件下发最新 token(沙箱暂停恢复续签后无需重启)。
28
+ * - `hmrTokenPlugin`:首屏脚本下发沙箱 token,重连时同源 JSON 请求返回当前 Vite 实例的 token。
29
29
  * - `wsWatchdogPlugin`:检测僵尸 WS,判死后 postMessage 通知沙箱外壳。
30
30
  */
31
31
  export declare function createHtmlViteConfig(opts?: HtmlViteOptions): InlineConfig;
@@ -31,9 +31,9 @@ const normalize_base_path_1 = require("./normalize-base-path");
31
31
  * + runtime-url-fix(撕掉 vite 给后端运行时绝对 URL 误加的 base 前缀)。
32
32
  *
33
33
  * 沙箱 WS 韧性(dev only,对齐 coding-preset-vite-react):
34
- * - `viteClientPatchPlugin`:删 WS 重连后的 `location.reload()`(休眠唤醒白屏),
34
+ * - `viteClientPatchPlugin`:探活后仅在 Vite 实例变化时刷新预览,同一实例直接重连,
35
35
  * 并让 HMR 长链 URL 在建链时取页面上的 `sandbox_token`(穿网关鉴权)。
36
- * - `hmrTokenPlugin`:每次页面加载现读 env 文件下发最新 token(沙箱暂停恢复续签后无需重启)。
36
+ * - `hmrTokenPlugin`:首屏脚本下发沙箱 token,重连时同源 JSON 请求返回当前 Vite 实例的 token。
37
37
  * - `wsWatchdogPlugin`:检测僵尸 WS,判死后 postMessage 通知沙箱外壳。
38
38
  */
39
39
  function createHtmlViteConfig(opts = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/coding-html-devserver",
3
- "version": "0.1.13",
3
+ "version": "0.1.14-alpha.20261126030250",
4
4
  "description": "Dev/build toolchain for the miaoda-coding html (pure HTML) stack. Wraps vite (dev + HMR) behind a bin so the template never sees vite; build is pure-copy + platform-script injection + optional minify.",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",