@lark-apaas/coding-html-devserver 0.1.14-alpha.20261118061450 → 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.
package/README.md CHANGED
@@ -1,7 +1,5 @@
1
1
  # @lark-apaas/coding-html-devserver
2
2
 
3
- 中文 | [English](./README.en-US.md)
4
-
5
3
  miaoda-coding **html stack** 的 dev/build 工具链。**vite 被封装在内部**——消费方(html 模板)只依赖本包、调它的 bin,**`package.json` 里看不到 vite、也没有 `vite.config`**。
6
4
 
7
5
  - **dev**:内部用 vite 起 dev server,拿 vite 原生 **HMR/热更新**(WS,经 `MIAODA_WS_HOST` 切独立域名穿沙箱网关) + `/dev/health` 探活 + 平台脚本注入。
@@ -47,26 +45,7 @@ coding-html-devserver build [--root src] [--out dist/output] [--no-minify]
47
45
 
48
46
  ## 公共 API
49
47
 
50
- `startBrandServer` · `buildStatic` · `createHtmlViteConfig` · `injectPlatformTags` · `injectTags` · `serializeTag` · `healthPlugin` · `platformInjectPlugin` · 类型 `HtmlTagDescriptor` 等。
51
-
52
- ## 品牌、配置与多语
53
-
54
- **读了哪些配置**:Node 侧读取脚本地址和品牌;浏览器中的基础包读取页面配置,确定环境和通信目标。缺失字段由基础包补默认值,下面的空地址指显式配置为空字符串。
55
-
56
- | 配置 | 用途 | 为空时 |
57
- |------|------|--------|
58
- | `MIAODA_APP_SETTINGS`(下发原文) | 通过 `toInlineScript` 写入 `window.MIAODA_APP_SETTINGS`,放在 CDN SDK 之前;非空旧 FORCE 主站由基础包解析后一并传递,浏览器补默认值 | 未下发或整份无效时写入空对象;仍可携带旧 FORCE 主站 |
59
- | `domainConf.mainDomain` | ws-watchdog 在浏览器调用 `getParentOrigin()`:本地 referrer → URL 参数 / 会话缓存 → 显式主站 / 旧主站变量 / 显式品牌环境默认主站 → 存量 hostname 映射 | 空主站按未设置处理,基础包继续选择目标 |
60
- | `apm.slardar.sdkUrl` / `apm.slardar.bid` | Slardar 脚本地址和 bid(`SlardarOptions.bid` 可覆盖) | sdkUrl 为空时不注入;bid 为空不控制脚本加载 |
61
- | `apm.performance.sdkUrl` | 性能采集脚本 | 不注入 |
62
- | `apm.tea.sdkUrl` | TEA 埋点脚本 | 不注入 |
63
- | `domainConf.scmCdn` | miaoda-coding-sdk 的 CDN 前缀,路径和版本保持原值 | 空字符串时不注入 |
64
- | `domainConf.previewBridgeUrl` | 预览桥完整脚本地址,国内默认保留 sf1 与原版本 | 空字符串时不注入 |
65
- | `brand` | dev 期 view-context 的 `userName`:飞书取 `zh_cn`,Lark 先取 `en_us` 再回退 `zh_cn`;以及 CLI 报错语言 | 按飞书处理 |
66
-
67
- **文案跟随什么语言**:本包唯一的多语文案是 CLI 参数报错(`--port` 非法),读者是 Agent / 开发者终端,用 `tDev` 跟随品牌:飞书为中文,Lark 为英文。`--help` 用法文本、启动和构建日志本身是英文;注入到页面里的脚本没有用户可见文案。
68
-
69
- - **验收**:`test/overseas-feishu.test.ts`(核对飞书默认资源地址、脚本顺序和参数)、`test/overseas-lark.test.ts`(Lark 品牌下无国内域名、CLI 报错为英文)。
48
+ `startDevServer` · `buildStatic` · `createHtmlViteConfig` · `injectPlatformTags` · `injectTags` · `serializeTag` · `healthPlugin` · `platformInjectPlugin` · 类型 `HtmlTagDescriptor` 等。
70
49
 
71
50
  ## 工程
72
51
 
package/lib/flags.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseFlags = parseFlags;
4
- const locales_1 = require("./locales");
5
4
  /**
6
5
  * 解析 CLI flags。`--port` 缺值/非整数/越界直接抛错(否则 NaN 会漏过 vite-config
7
6
  * 的 `??` fallback 流进 vite,给出难懂的报错)。
@@ -22,7 +21,7 @@ function parseFlags(argv) {
22
21
  const raw = argv[++i];
23
22
  const n = Number(raw);
24
23
  if (!Number.isInteger(n) || n < 0 || n > 65535) {
25
- throw new Error((0, locales_1.tDev)('flags.error.invalidPort', { value: raw ?? (0, locales_1.tDev)('flags.value.empty') }));
24
+ throw new Error(`--port 需要 0-65535 的整数,收到: ${raw ?? '(空)'}`);
26
25
  }
27
26
  flags.port = n;
28
27
  }
@@ -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; ' +
@@ -36,14 +36,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.wsWatchdogPlugin = wsWatchdogPlugin;
37
37
  const fs = __importStar(require("node:fs"));
38
38
  const path = __importStar(require("node:path"));
39
- const client_script_1 = require("../utils/client-script");
40
39
  const CLIENT_RUNTIME_PATH = '/@ws-watchdog.js';
41
40
  function resolveClientRuntimePath() {
42
41
  const candidates = [
43
42
  path.resolve(__dirname, '../../src/runtime/ws-watchdog-client.mjs'), // lib/plugins → src/runtime
44
43
  path.resolve(__dirname, '../runtime/ws-watchdog-client.mjs'), // src/plugins → src/runtime
45
44
  ];
46
- return candidates.find(p => fs.existsSync(p)) ?? null;
45
+ return candidates.find((p) => fs.existsSync(p)) ?? null;
47
46
  }
48
47
  function wsWatchdogPlugin(options = {}) {
49
48
  const { pingEvent = 'ws-watchdog:ping', pongEvent = 'ws-watchdog:pong', clientBasePath = '', } = options;
@@ -69,8 +68,13 @@ function wsWatchdogPlugin(options = {}) {
69
68
  }
70
69
  try {
71
70
  let code = fs.readFileSync(clientPath, 'utf-8');
72
- code = code.replace(/process\.env\.CLIENT_BASE_PATH/g, () => JSON.stringify(clientBasePath));
73
- code = (0, client_script_1.bundleClientScript)(code);
71
+ const env = {
72
+ 'process.env.FORCE_FRAMEWORK_DOMAIN_MAIN': JSON.stringify(process.env.FORCE_FRAMEWORK_DOMAIN_MAIN ?? ''),
73
+ 'process.env.CLIENT_BASE_PATH': JSON.stringify(clientBasePath),
74
+ };
75
+ for (const [k, v] of Object.entries(env)) {
76
+ code = code.replace(new RegExp(k.replace(/\./g, '\\.'), 'g'), v);
77
+ }
74
78
  res.setHeader('Content-Type', 'application/javascript');
75
79
  res.setHeader('Cache-Control', 'no-cache');
76
80
  res.end(code);
@@ -6,7 +6,6 @@ import { type OgMetaOptions } from './og-meta';
6
6
  * 平台 HTML 注入的唯一真相(编排者)。dev(vite transformIndexHtml 插件)与 build
7
7
  * (纯拷贝步骤)共用本模块。各功能域拆分在同级文件:
8
8
  * - view-context.ts:window 上下文(HBS 占位符 / 请求真值)
9
- * - app-settings.ts:向 CDN SDK 传递 window.MIAODA_APP_SETTINGS
10
9
  * - slardar.ts:Slardar + Performance + Tea 监控埋点
11
10
  * - runtime.ts:miaoda-coding-sdk runtime(TEA 页面浏览埋点;豆包来源带水印)
12
11
  * - preview-bridge.ts:妙搭预览桥(**仅 dev**)
@@ -8,13 +8,11 @@ const view_context_1 = require("./view-context");
8
8
  const slardar_1 = require("./slardar");
9
9
  const runtime_1 = require("./runtime");
10
10
  const preview_bridge_1 = require("./preview-bridge");
11
- const app_settings_1 = require("./app-settings");
12
11
  const og_meta_1 = require("./og-meta");
13
12
  /**
14
13
  * 平台 HTML 注入的唯一真相(编排者)。dev(vite transformIndexHtml 插件)与 build
15
14
  * (纯拷贝步骤)共用本模块。各功能域拆分在同级文件:
16
15
  * - view-context.ts:window 上下文(HBS 占位符 / 请求真值)
17
- * - app-settings.ts:向 CDN SDK 传递 window.MIAODA_APP_SETTINGS
18
16
  * - slardar.ts:Slardar + Performance + Tea 监控埋点
19
17
  * - runtime.ts:miaoda-coding-sdk runtime(TEA 页面浏览埋点;豆包来源带水印)
20
18
  * - preview-bridge.ts:妙搭预览桥(**仅 dev**)
@@ -40,8 +38,6 @@ function injectPlatformTags(html, opts = {}) {
40
38
  const tags = [
41
39
  ...(0, base_tag_1.baseTag)(opts.base, html),
42
40
  (0, view_context_1.viewContextTag)(mode, { appId: opts.appId }, opts.viewCtx),
43
- // 下发配置:须在 runtime(CDN SDK)之前,SDK 加载时才能读到
44
- ...(0, app_settings_1.appSettingsTags)(),
45
41
  ...(0, slardar_1.slardarTags)(opts.slardar),
46
42
  // miaoda-coding-sdk runtime:依赖 collectEvent(slardar) + appId(view-context),故排其后
47
43
  ...(0, runtime_1.runtimeTags)(mode),
@@ -4,12 +4,7 @@ import type { HtmlTagDescriptor } from '../html-tags';
4
4
  *
5
5
  * 沙箱预览外壳与页面之间的通信桥,build 产物不需要(线上不经预览外壳)。
6
6
  * 由 `injectPlatformTags` 在 `mode === 'dev'` 时注入,buildStatic(build 模式)不注入。
7
- *
8
- * 完整地址来自 domainConf.previewBridgeUrl,国内默认保留 sf1 与原版本。
9
7
  */
10
- /** HTML 预览桥使用独立地址,保留国内 sf1 前缀。 */
11
- export declare function getPreviewBridgeUrl(): string;
12
- /** 预览桥地址(模块加载时按配置求值,保留原导出名供外部引用) */
13
- export declare const MIAODA_PREVIEW_BRIDGE_URL: string;
14
- /** 预览桥 script 清单(head-prepend,尽早建立与外壳的通信);配置显式关闭地址时不注入。 */
8
+ export declare const MIAODA_PREVIEW_BRIDGE_URL = "https://sf1-scmcdn-cn.feishucdn.com/obj/feishu-static/apaas/miaoda-preview-bridge/1.0.0.5/miaoda-preview-bridge.iife.min.js";
9
+ /** 预览桥 script 清单(head-prepend,尽早建立与外壳的通信)。 */
15
10
  export declare function previewBridgeTags(): HtmlTagDescriptor[];
@@ -1,27 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MIAODA_PREVIEW_BRIDGE_URL = void 0;
4
- exports.getPreviewBridgeUrl = getPreviewBridgeUrl;
5
4
  exports.previewBridgeTags = previewBridgeTags;
6
- const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
7
5
  /**
8
6
  * 妙搭预览桥(preview bridge)—— **仅开发环境**注入。
9
7
  *
10
8
  * 沙箱预览外壳与页面之间的通信桥,build 产物不需要(线上不经预览外壳)。
11
9
  * 由 `injectPlatformTags` 在 `mode === 'dev'` 时注入,buildStatic(build 模式)不注入。
12
- *
13
- * 完整地址来自 domainConf.previewBridgeUrl,国内默认保留 sf1 与原版本。
14
10
  */
15
- /** HTML 预览桥使用独立地址,保留国内 sf1 前缀。 */
16
- function getPreviewBridgeUrl() {
17
- return (0, miaoda_common_settings_1.readSettings)('domainConf.previewBridgeUrl') ?? '';
18
- }
19
- /** 预览桥地址(模块加载时按配置求值,保留原导出名供外部引用) */
20
- exports.MIAODA_PREVIEW_BRIDGE_URL = getPreviewBridgeUrl();
21
- /** 预览桥 script 清单(head-prepend,尽早建立与外壳的通信);配置显式关闭地址时不注入。 */
11
+ exports.MIAODA_PREVIEW_BRIDGE_URL = 'https://sf1-scmcdn-cn.feishucdn.com/obj/feishu-static/apaas/miaoda-preview-bridge/1.0.0.5/miaoda-preview-bridge.iife.min.js';
12
+ /** 预览桥 script 清单(head-prepend,尽早建立与外壳的通信)。 */
22
13
  function previewBridgeTags() {
23
- const src = getPreviewBridgeUrl();
24
- if (!src)
25
- return [];
26
- return [{ tag: 'script', attrs: { src }, injectTo: 'head-prepend' }];
14
+ return [{ tag: 'script', attrs: { src: exports.MIAODA_PREVIEW_BRIDGE_URL }, injectTo: 'head-prepend' }];
27
15
  }
@@ -1,6 +1,3 @@
1
1
  import type { HtmlTagDescriptor } from '../html-tags';
2
- /**
3
- * miaoda-coding-sdk runtime 的 head-prepend script tag(dev → .dev.js / build → .min.js)。
4
- * 配置里没有 SCM CDN 前缀时不注入。
5
- */
2
+ /** miaoda-coding-sdk runtime 的 head-prepend script tag(dev → .dev.js / build → .min.js)。 */
6
3
  export declare function runtimeTags(mode: 'build' | 'dev'): HtmlTagDescriptor[];
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runtimeTags = runtimeTags;
4
- const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
5
4
  /**
6
5
  * 注入 `@lark-apaas/miaoda-coding-sdk` 的 runtime 产物(TEA 页面浏览埋点 + 水印)。
7
6
  *
@@ -15,19 +14,13 @@ const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
15
14
  const DOUBAO_SOURCE = '5';
16
15
  /** miaoda-coding-sdk 的 CDN 版本(发布后随版本回填)。 */
17
16
  const CODING_SDK_VERSION = '0.0.1';
18
- /** SCM CDN 上的存储路径;域名前缀取自配置 domainConf.scmCdn。 */
19
- const CODING_SDK_PATH = 'obj/feishu-static/miaoda/coding-sdk';
20
- /**
21
- * miaoda-coding-sdk runtime 的 head-prepend script tag(dev → .dev.js / build → .min.js)。
22
- * 配置里没有 SCM CDN 前缀时不注入。
23
- */
17
+ /** sf3 SCM CDN 基址。 */
18
+ const CDN_BASE = 'https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-sdk';
19
+ /** miaoda-coding-sdk runtime 的 head-prepend script tag(dev → .dev.js / build → .min.js)。 */
24
20
  function runtimeTags(mode) {
25
- const base = (0, miaoda_common_settings_1.readSettings)('domainConf.scmCdn');
26
- if (!base)
27
- return [];
28
21
  const entry = String(process.env.MIAODA_APP_SOURCE) === DOUBAO_SOURCE ? 'doubao-runtime' : 'runtime';
29
22
  const variant = mode === 'dev' ? 'dev' : 'min';
30
- const src = `${base.replace(/\/+$/, '')}/${CODING_SDK_PATH}/${CODING_SDK_VERSION}/${entry}.${variant}.js`;
23
+ const src = `${CDN_BASE}/${CODING_SDK_VERSION}/${entry}.${variant}.js`;
31
24
  return [
32
25
  {
33
26
  tag: 'script',
@@ -3,17 +3,14 @@ import type { HtmlTagDescriptor } from '../html-tags';
3
3
  * Slardar + Performance + Tea 监控埋点的 head-prepend script 清单。
4
4
  * 能力对齐 `@lark-apaas/coding-preset-vite-react` 的 slardar 插件。
5
5
  *
6
- * 依赖 view-context 提前注入 `window.tenantId/appId/userId`(值带 `?? ''`
6
+ * 依赖 view-context 提前注入 `window.tenantId/appId/userId/ENVIRONMENT`(值带 `?? ''`
7
7
  * 兜底,缺失不崩,只是埋点维度为空)。
8
8
  */
9
9
  export interface SlardarOptions {
10
- /** Business ID。默认取配置 `apm.slardar.bid`。 */
10
+ /** Business ID。默认 `apaas_miaoda`。 */
11
11
  bid?: string;
12
12
  /** SDK 暴露在 window 上的全局名。默认 `KSlardarWeb`。 */
13
13
  globalName?: string;
14
14
  }
15
- /**
16
- * Slardar + Performance + Tea 监控埋点的 head-prepend script 清单。
17
- * 地址和 bid 取配置;配置里没有某个脚本地址时不注入该脚本。
18
- */
15
+ /** Slardar + Performance + Tea 监控埋点的 head-prepend script 清单。 */
19
16
  export declare function slardarTags(options?: SlardarOptions): HtmlTagDescriptor[];
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.slardarTags = slardarTags;
4
- const client_script_1 = require("../utils/client-script");
5
- const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
6
4
  /**
7
5
  * HTML 解析时同步执行的内联脚本(早于任何外部资源加载):建 KSlardarWeb 命令队列
8
6
  * stub + 立即注册 capture 阶段的资源/运行时错误监听,SDK 就绪前入 buffer,onload 后 flush。
@@ -43,20 +41,10 @@ function buildEarlyResourceErrorScript(globalName) {
43
41
  });
44
42
  })('${globalName}');`;
45
43
  }
46
- function buildSlardarScript(sdkUrl, bid, globalName) {
47
- const hashIndex = sdkUrl.indexOf('#');
48
- const hash = hashIndex < 0 ? '' : sdkUrl.slice(hashIndex);
49
- const address = hashIndex < 0 ? sdkUrl : sdkUrl.slice(0, hashIndex);
50
- const queryIndex = address.indexOf('?');
51
- const path = queryIndex < 0 ? address : address.slice(0, queryIndex);
52
- const query = new URLSearchParams(queryIndex < 0 ? '' : address.slice(queryIndex + 1));
53
- query.set('bid', bid);
54
- query.set('globalName', globalName);
55
- const url = `${path}?${query}${hash}`;
56
- return (0, client_script_1.bundleClientScript)(`
57
- import { readSettings } from '@lark-apaas/miaoda-common-settings';
44
+ function buildSlardarScript(bid, globalName) {
45
+ return `
58
46
  const slardarScript = document.createElement('script');
59
- slardarScript.src = ${JSON.stringify(url)};
47
+ slardarScript.src = 'https://lf3-short.ibytedapm.com/slardar/fe/sdk-web/browser.cn.js?bid=${bid}&globalName=${globalName}';
60
48
  slardarScript.crossOrigin = 'anonymous';
61
49
  slardarScript.onload = function() {
62
50
  if (window.${globalName}) {
@@ -65,8 +53,8 @@ function buildSlardarScript(sdkUrl, bid, globalName) {
65
53
  appId: window.appId ?? '',
66
54
  });
67
55
  window.${globalName}('init', {
68
- bid: ${JSON.stringify(bid)},
69
- env: ({ boe: 'staging', pre: 'gray', online: 'online' })[readSettings('env')],
56
+ bid: '${bid}',
57
+ env: window.ENVIRONMENT || 'online',
70
58
  userId: window.userId ?? '',
71
59
  });
72
60
  window.${globalName}('start');
@@ -82,9 +70,9 @@ function buildSlardarScript(sdkUrl, bid, globalName) {
82
70
  console.warn('Failed to load Slardar script');
83
71
  };
84
72
  document.head.appendChild(slardarScript);
85
- `, 'iife');
73
+ `;
86
74
  }
87
- function buildTeaScript(sdkUrl) {
75
+ function buildTeaScript() {
88
76
  return `
89
77
  (function (win, export_obj) {
90
78
  win['LogAnalyticsObject'] = export_obj;
@@ -97,7 +85,7 @@ function buildTeaScript(sdkUrl) {
97
85
  })(window, 'collectEvent');
98
86
 
99
87
  const teaScript = document.createElement('script');
100
- teaScript.src = ${JSON.stringify(sdkUrl).replace(/</g, '\\u003c')};
88
+ teaScript.src = 'https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.1/collect.js';
101
89
  teaScript.crossOrigin = 'anonymous';
102
90
  teaScript.async = true;
103
91
  teaScript.onerror = function() {
@@ -106,47 +94,23 @@ function buildTeaScript(sdkUrl) {
106
94
  document.head.appendChild(teaScript);
107
95
  `;
108
96
  }
109
- /**
110
- * Slardar + Performance + Tea 监控埋点的 head-prepend script 清单。
111
- * 地址和 bid 取配置;配置里没有某个脚本地址时不注入该脚本。
112
- */
97
+ /** Slardar + Performance + Tea 监控埋点的 head-prepend script 清单。 */
113
98
  function slardarTags(options = {}) {
114
- const { globalName = 'KSlardarWeb' } = options;
115
- const slardarUrl = (0, miaoda_common_settings_1.readSettings)('apm.slardar.sdkUrl');
116
- const bid = options.bid ?? (0, miaoda_common_settings_1.readSettings)('apm.slardar.bid') ?? '';
117
- const performanceUrl = (0, miaoda_common_settings_1.readSettings)('apm.performance.sdkUrl');
118
- const teaUrl = (0, miaoda_common_settings_1.readSettings)('apm.tea.sdkUrl');
119
- const tags = [];
120
- if (slardarUrl) {
99
+ const { bid = 'apaas_miaoda', globalName = 'KSlardarWeb' } = options;
100
+ return [
121
101
  // 必须最先:内联资源错误捕获 + KSlardarWeb 命令队列 stub
122
- tags.push({
123
- tag: 'script',
124
- children: buildEarlyResourceErrorScript(globalName),
125
- injectTo: 'head-prepend',
126
- }, {
127
- tag: 'script',
128
- children: buildSlardarScript(slardarUrl, bid, globalName),
129
- injectTo: 'head-prepend',
130
- });
131
- }
132
- if (performanceUrl) {
133
- tags.push({
102
+ { tag: 'script', children: buildEarlyResourceErrorScript(globalName), injectTo: 'head-prepend' },
103
+ { tag: 'script', children: buildSlardarScript(bid, globalName), injectTo: 'head-prepend' },
104
+ {
134
105
  tag: 'script',
135
106
  attrs: {
136
- src: performanceUrl,
107
+ src: 'https://sf3-scmcdn-cn.feishucdn.com/obj/unpkg/byted/performance/0.2.3/dist/performance.iife.js',
137
108
  'data-app-name': 'builderV3',
138
109
  crossorigin: 'anonymous',
139
110
  defer: true,
140
111
  },
141
112
  injectTo: 'head-prepend',
142
- });
143
- }
144
- if (teaUrl) {
145
- tags.push({
146
- tag: 'script',
147
- children: buildTeaScript(teaUrl),
148
- injectTo: 'head-prepend',
149
- });
150
- }
151
- return tags;
113
+ },
114
+ { tag: 'script', children: buildTeaScript(), injectTo: 'head-prepend' },
115
+ ];
152
116
  }
@@ -4,7 +4,6 @@ exports.requestContext = void 0;
4
4
  exports.buildRenderContext = buildRenderContext;
5
5
  exports.viewContextTag = viewContextTag;
6
6
  const node_async_hooks_1 = require("node:async_hooks");
7
- const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
8
7
  /**
9
8
  * 启动期上下文注入:把 appId/userId/tenantId 等挂到 `window`,供业务代码与 slardar 读。
10
9
  * 能力对齐 `@lark-apaas/coding-preset-vite-react` 的 view-context 插件。
@@ -41,23 +40,13 @@ function readDevEnvironment() {
41
40
  const v = process.env.FORCE_FRAMEWORK_ENVIRONMENT;
42
41
  return v && v.trim() ? v.trim() : 'online';
43
42
  }
44
- /**
45
- * dev 期用户名按品牌选:飞书取 zh_cn(与原逻辑一致);Lark 依次取 en_us → zh_cn → 任一非空的语言
46
- * (与 nestjs-core、auth-sdk 同一顺序)。
47
- */
48
- function pickUserName(name) {
49
- if ((0, miaoda_common_settings_1.readSettings)('brand') === 'lark') {
50
- return name?.en_us || name?.zh_cn || Object.values(name ?? {}).find(Boolean) || '';
51
- }
52
- return name?.zh_cn ?? '';
53
- }
54
43
  /** 从 incoming request 抽出 server 端能拿到的 view-context 字段。 */
55
44
  function buildRenderContext(req) {
56
45
  const user = parseSudaWebUser(req.headers[SUDA_HEADER]);
57
46
  return {
58
47
  userId: user?.user_id ?? '',
59
48
  tenantId: user?.tenant_id ?? '',
60
- userName: pickUserName(user?.user_name),
49
+ userName: user?.user_name?.zh_cn ?? '',
61
50
  csrfToken: parseCsrfToken(req.headers.cookie),
62
51
  environment: readDevEnvironment(),
63
52
  };
@@ -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.14-alpha.20261118061450",
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",
@@ -8,9 +8,7 @@
8
8
  "files": [
9
9
  "lib",
10
10
  "bin",
11
- "src/runtime",
12
- "README.md",
13
- "README.en-US.md"
11
+ "src/runtime"
14
12
  ],
15
13
  "scripts": {
16
14
  "build": "tsc",
@@ -21,16 +19,12 @@
21
19
  "prepublishOnly": "npm run build"
22
20
  },
23
21
  "dependencies": {
24
- "@lark-apaas/miaoda-common-settings": "1.0.1-alpha.20261118061506",
25
- "esbuild": "^0.25.4",
26
22
  "html-minifier-terser": "^7.2.0",
27
23
  "vite": "^8.0.0"
28
24
  },
29
25
  "devDependencies": {
30
26
  "@types/html-minifier-terser": "^7.0.2",
31
- "@types/jsdom": "^28",
32
27
  "@types/node": "^22.0.0",
33
- "jsdom": "^28.1.0",
34
28
  "typescript": "^5.6.0",
35
29
  "vitest": "^3.0.0"
36
30
  },
@@ -1,4 +1,3 @@
1
- import { getParentOrigin } from '@lark-apaas/miaoda-common-settings';
2
1
  /* eslint-env browser */
3
2
 
4
3
  /**
@@ -61,7 +60,7 @@ export function createWatchdog(deps, options = {}) {
61
60
  }
62
61
  }
63
62
 
64
- deps.onCustom(pongEvent, raw => {
63
+ deps.onCustom(pongEvent, (raw) => {
65
64
  const data = /** @type {{ echo?: number } | undefined} */ (raw);
66
65
  if (typeof data?.echo !== 'number' || !recentPings.has(data.echo)) return;
67
66
  recentPings.delete(data.echo);
@@ -77,13 +76,44 @@ export function createWatchdog(deps, options = {}) {
77
76
 
78
77
  // postMessage 的 targetOrigin 必须显式指定,禁止用 '*'。
79
78
 
79
+ const PARENT_ORIGIN_KEY = '__parentOrigin';
80
+
81
+ function getParentOriginFromParams() {
82
+ try {
83
+ const origin = new URLSearchParams(window.location.search).get(PARENT_ORIGIN_KEY);
84
+ if (origin) {
85
+ try { sessionStorage.setItem(PARENT_ORIGIN_KEY, origin); } catch { /* 忽略 */ }
86
+ return origin;
87
+ }
88
+ } catch { /* 忽略 URL 解析失败 */ }
89
+ try { return sessionStorage.getItem(PARENT_ORIGIN_KEY) || undefined; }
90
+ catch { return undefined; }
91
+ }
92
+
93
+ function getLegacyParentOrigin() {
94
+ const { origin } = window.location;
95
+ if (origin.includes('force.feishuapp.net')) return 'https://force.feishu.cn';
96
+ if (origin.includes('force-pre.feishuapp.net')) return 'https://force.feishu-pre.cn';
97
+ if (origin.includes('force.byted.org')) return 'https://force.feishu-boe.cn';
98
+ if (origin.includes('feishuapp.cn') || origin.includes('miaoda.feishuapp.net')) return 'https://miaoda.feishu.cn';
99
+ if (origin.includes('fsapp.kundou.cn') || origin.includes('miaoda-pre.feishuapp.net')) return 'https://miaoda.feishu-pre.cn';
100
+ return 'https://miaoda.feishu-boe.cn';
101
+ }
102
+
103
+ function resolveParentOrigin() {
104
+ const paramOrigin = getParentOriginFromParams();
105
+ if (paramOrigin) return paramOrigin;
106
+ // plugin middleware 在送出脚本时把这个 token 编译期替换成字符串字面量。
107
+ return process.env.FORCE_FRAMEWORK_DOMAIN_MAIN || getLegacyParentOrigin();
108
+ }
109
+
80
110
  function postStatus(status) {
81
111
  try {
82
- const origin = getParentOrigin();
112
+ const origin = resolveParentOrigin();
83
113
  if (!origin) return;
84
114
  window.parent.postMessage(
85
115
  { type: 'DevServerMessage', data: { type: 'devServer-status', status } },
86
- origin
116
+ origin,
87
117
  );
88
118
  } catch (e) {
89
119
  console.error('[fullstack-ws-watchdog] postMessage error:', e);
@@ -98,23 +128,18 @@ const CLIENT_BASE_PATH = process.env.CLIENT_BASE_PATH || '';
98
128
  if (typeof window !== 'undefined' && window.parent !== window) {
99
129
  (async () => {
100
130
  try {
101
- const { createHotContext } = await import(
102
- CLIENT_BASE_PATH + '/@vite/client'
103
- );
131
+ const { createHotContext } = await import(CLIENT_BASE_PATH + '/@vite/client');
104
132
  const hot = createHotContext(CLIENT_BASE_PATH + '/@ws-watchdog.js');
105
133
  createWatchdog({
106
134
  sendCustom: (event, data) => {
107
135
  // 断连时 hot.send 可能抛;吞掉即可——missed 已在 onTick 顶部累加。
108
- try {
109
- hot.send(event, data);
110
- } catch (e) {
111
- console.warn('[fullstack-ws-watchdog] send failed:', e);
112
- }
136
+ try { hot.send(event, data); }
137
+ catch (e) { console.warn('[fullstack-ws-watchdog] send failed:', e); }
113
138
  },
114
139
  onCustom: (event, cb) => hot.on(event, cb),
115
140
  postStatus,
116
141
  setInterval: (handler, ms) => window.setInterval(handler, ms),
117
- clearInterval: handle => window.clearInterval(handle),
142
+ clearInterval: (handle) => window.clearInterval(handle),
118
143
  });
119
144
  } catch (e) {
120
145
  console.warn('[fullstack-ws-watchdog] bootstrap failed:', e);
package/README.en-US.md DELETED
@@ -1,75 +0,0 @@
1
- # @lark-apaas/coding-html-devserver
2
-
3
- [中文](./README.md) | English
4
-
5
- The dev/build toolchain for the miaoda-coding **html stack**. **Vite is wrapped inside the package**: consumers (html templates) depend only on this package and call its bin, so **neither vite nor a `vite.config` appears in their `package.json`**.
6
-
7
- - **dev**: starts a dev server with vite internally, getting vite's native **HMR/hot reload** (WS, switched to a dedicated domain through `MIAODA_WS_HOST` to get through the sandbox gateway) + `/dev/health` liveness probe + platform script injection.
8
- - **build**: **does not use vite build**; it simply copies `src → dist/output` (file names/paths/structure kept verbatim) + platform script injection + optional HTML minification.
9
- - **Platform script injection**: dev and build share one list; **users never see it** and source files stay clean.
10
-
11
- ## Why it is designed this way
12
-
13
- The html stack needs vite's **instant hot reload experience** (polling can't keep up), so dev borrows vite directly. But vite build bundles, adds hashes and rewrites paths, which conflicts with "plain HTML output = source", so build does its own plain copy. Vite stays an internal dependency of this package throughout and is transparent to users.
14
-
15
- ## Usage
16
-
17
- ```jsonc
18
- // Consumer (html template) package.json — vite never appears
19
- "devDependencies": { "@lark-apaas/coding-html-devserver": "^0.1.0" },
20
- "scripts": {
21
- "dev": "coding-html-devserver dev",
22
- "build": "coding-html-devserver build"
23
- }
24
- ```
25
-
26
- ```bash
27
- coding-html-devserver dev [--root src] [--port 8001] [--host 0.0.0.0]
28
- coding-html-devserver build [--root src] [--out dist/output] [--no-minify]
29
- ```
30
-
31
- Port precedence: `--port` > `CLIENT_DEV_PORT` env > `8001`. It binds `0.0.0.0`, uses `allowedHosts: true`, and sets no `base` (the prefix is stripped by the sandbox gateway). When `MIAODA_WS_HOST` is present, HMR switches to a dedicated WS domain (matching the vite-react gateway approach).
32
-
33
- ## Platform injection (option A: baked into the SDK)
34
-
35
- The injection list is the internal constant `PLATFORM_TAGS`; it ships with each version and users cannot configure it. Changing what is injected = publish a new version → bump the template → re-render. There is only one injection implementation (`injectTags`): dev calls it through the vite `transformIndexHtml` plugin and build calls it after copying, so both paths behave the same.
36
-
37
- Descriptors follow vite's `HtmlTagDescriptor`:
38
-
39
- ```ts
40
- { tag: 'script', attrs: { src: 'https://cdn/x.js', async: true }, injectTo: 'head' } // External CDN script
41
- { tag: 'script', children: 'window.__X__=1', injectTo: 'head-prepend' } // Inline JS
42
- ```
43
-
44
- Mechanics: grouped by `injectTo` with order preserved, deduplicated by the same `src`/`id`, inline `</script>` escaped, and a fallback anchor for malformed HTML.
45
-
46
- > `PLATFORM_TAGS` is currently an empty placeholder list; the mechanism is fully implemented and tested, and the real platform script URLs can be filled in once decided, with no impact on the API.
47
-
48
- ## Public API
49
-
50
- `startBrandServer` · `buildStatic` · `createHtmlViteConfig` · `injectPlatformTags` · `injectTags` · `serializeTag` · `healthPlugin` · `platformInjectPlugin` · types such as `HtmlTagDescriptor`.
51
-
52
- ## Brand, Settings and i18n
53
-
54
- **Settings read**: Node resolves script URLs and the brand; the shared package in the browser resolves the environment and message destination from page settings. Missing fields use shared defaults; empty URLs below mean explicitly configured empty strings.
55
-
56
- | Setting | Purpose | When empty |
57
- |---------|---------|------------|
58
- | `MIAODA_APP_SETTINGS` (raw injected value) | Written to `window.MIAODA_APP_SETTINGS` through `toInlineScript` before CDN SDKs; a nonempty legacy FORCE main site is resolved by the shared package and forwarded, and browser code fills defaults | Missing or invalid input produces an empty object, optionally carrying the legacy FORCE main site |
59
- | `domainConf.mainDomain` | The watchdog calls `getParentOrigin()` in the browser: local referrer → URL parameter / session cache → explicit main site / legacy variable / explicit brand-environment default → legacy hostname mapping | An empty main site is treated as unset; the shared package resolves the destination |
60
- | `apm.slardar.sdkUrl` / `apm.slardar.bid` | Slardar script URL and bid (`SlardarOptions.bid` overrides it) | Empty sdkUrl skips injection; an empty bid does not control loading |
61
- | `apm.performance.sdkUrl` | Performance collection script | Not injected |
62
- | `apm.tea.sdkUrl` | TEA tracking script | Not injected |
63
- | `domainConf.scmCdn` | CDN prefix for miaoda-coding-sdk; existing path and version | Empty string disables injection |
64
- | `domainConf.previewBridgeUrl` | Full preview bridge URL; Feishu keeps sf1 and its original version | Empty string disables injection |
65
- | `brand` | `userName` in dev view-context: `zh_cn` for Feishu; for Lark `en_us` first, falling back to `zh_cn`. Also the CLI error language | Treated as Feishu |
66
-
67
- **Text language**: the only localized text is the CLI argument error (invalid `--port`), read by the Agent or a developer's terminal, so it uses `tDev` and follows the brand: Chinese for Feishu, English for Lark. The `--help` usage text and the startup / build logs are English already; scripts injected into pages carry no user-visible text.
68
-
69
- - **Verification**: `test/overseas-feishu.test.ts` (checks Feishu resource defaults, script order and parameters), `test/overseas-lark.test.ts` (no domestic domains under Lark, English CLI errors).
70
-
71
- ## Engineering
72
-
73
- ESM package (vite 8 is ESM-only). `tsc → lib/` (NodeNext). Node ≥22.
74
-
75
- Design doc: [`docs/superpowers/plans/2026-06-05-html-devserver-sdk.md`](../../../docs/superpowers/plans/2026-06-05-html-devserver-sdk.md)
@@ -1,13 +0,0 @@
1
- /** CLI 输出与报错,语言跟随品牌(见 tDev) */
2
- declare const devMessages: {
3
- 'flags.error.invalidPort': {
4
- 'zh-CN': string;
5
- 'en-US': string;
6
- };
7
- 'flags.value.empty': {
8
- 'zh-CN': string;
9
- 'en-US': string;
10
- };
11
- };
12
- export type DevMessageKey = keyof typeof devMessages;
13
- export default devMessages;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- /** CLI 输出与报错,语言跟随品牌(见 tDev) */
4
- const devMessages = {
5
- 'flags.error.invalidPort': {
6
- 'zh-CN': '--port 需要 0-65535 的整数,收到: {value}',
7
- 'en-US': '--port must be an integer between 0 and 65535, got: {value}',
8
- },
9
- 'flags.value.empty': {
10
- 'zh-CN': '(空)',
11
- 'en-US': '(empty)',
12
- },
13
- };
14
- exports.default = devMessages;
@@ -1,6 +0,0 @@
1
- import { type DevMessageKey } from './dev-messages';
2
- /**
3
- * CLI 输出与报错的文案,语言跟随应用品牌:飞书为中文,Lark 为英文。
4
- * 每次调用时读取当前配置。
5
- */
6
- export declare function tDev(key: DevMessageKey, params?: Record<string, string | number>): string;
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.tDev = tDev;
7
- const i18n_1 = require("@lark-apaas/miaoda-common-settings/i18n");
8
- const dev_messages_1 = __importDefault(require("./dev-messages"));
9
- const devI18n = (0, i18n_1.createI18nForDev)(dev_messages_1.default);
10
- /**
11
- * CLI 输出与报错的文案,语言跟随应用品牌:飞书为中文,Lark 为英文。
12
- * 每次调用时读取当前配置。
13
- */
14
- function tDev(key, params) {
15
- return devI18n.t(key, params);
16
- }
@@ -1,3 +0,0 @@
1
- import type { HtmlTagDescriptor } from '../html-tags';
2
- /** 将平台配置传给 CDN SDK,页面环境由浏览器中的基础包读取。 */
3
- export declare function appSettingsTags(): HtmlTagDescriptor[];
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.appSettingsTags = appSettingsTags;
4
- const miaoda_common_settings_1 = require("@lark-apaas/miaoda-common-settings");
5
- /** 将平台配置传给 CDN SDK,页面环境由浏览器中的基础包读取。 */
6
- function appSettingsTags() {
7
- let settings = {};
8
- try {
9
- const value = JSON.parse(process.env.MIAODA_APP_SETTINGS ?? '{}');
10
- if (value &&
11
- typeof value === 'object' &&
12
- !Array.isArray(value) &&
13
- (value.schemaVersion === undefined || value.schemaVersion === 1))
14
- settings = value;
15
- }
16
- catch {
17
- /* 使用品牌默认配置 */
18
- }
19
- if (process.env.FORCE_FRAMEWORK_DOMAIN_MAIN) {
20
- settings = {
21
- ...settings,
22
- domainConf: {
23
- ...settings.domainConf,
24
- mainDomain: (0, miaoda_common_settings_1.readSettings)('domainConf.mainDomain'),
25
- },
26
- };
27
- }
28
- return [
29
- {
30
- tag: 'script',
31
- children: (0, miaoda_common_settings_1.toInlineScript)(settings),
32
- injectTo: 'head-prepend',
33
- },
34
- ];
35
- }
@@ -1,2 +0,0 @@
1
- /** 将基础包打进浏览器脚本,环境判断在页面执行时完成。 */
2
- export declare function bundleClientScript(code: string, format?: 'esm' | 'iife'): string;
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bundleClientScript = bundleClientScript;
4
- const esbuild_1 = require("esbuild");
5
- /** 将基础包打进浏览器脚本,环境判断在页面执行时完成。 */
6
- function bundleClientScript(code, format = 'esm') {
7
- const define = {};
8
- for (const key of [
9
- 'MIAODA_APP_SETTINGS',
10
- 'FORCE_FRAMEWORK_DOMAIN_MAIN',
11
- 'FORCE_FRAMEWORK_ENVIRONMENT',
12
- ]) {
13
- define[`process.env.${key}`] =
14
- JSON.stringify(process.env[key]) ?? 'undefined';
15
- }
16
- define['process.env.MIAODA_APP_SETTINGS'] = 'undefined';
17
- return (0, esbuild_1.buildSync)({
18
- stdin: {
19
- contents: code,
20
- resolveDir: __dirname,
21
- sourcefile: 'platform-client.js',
22
- },
23
- bundle: true,
24
- write: false,
25
- platform: 'browser',
26
- format,
27
- target: 'es2020',
28
- define,
29
- }).outputFiles[0].text;
30
- }