lantern-harness 0.1.43 → 0.1.45

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 (153) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/builtin/session/lh-nav-groups.mjs +18 -4
  4. package/dist/500.html +61 -5
  5. package/dist/_astro/Base.Bkt1lrgu.css +1 -0
  6. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.Chv7r8_9.js → Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js} +1 -1
  7. package/dist/_astro/{CaseExecBoard.DUMjSunb.js → CaseExecBoard.DICluCbK.js} +1 -1
  8. package/dist/_astro/{CaseGenerateApp.DtuOyQuv.js → CaseGenerateApp.Be3h5XPG.js} +1 -1
  9. package/dist/_astro/{CasesLibrary.B9o_jvXb.js → CasesLibrary.Buys7Cy-.js} +3 -3
  10. package/dist/_astro/ChatApp.D3BheKci.js +227 -0
  11. package/dist/_astro/ConfirmDialog.DrrPf1MB.js +1 -0
  12. package/dist/_astro/{DashboardBoard.DEvgMoqo.js → DashboardBoard.Qvf8o4v1.js} +1 -1
  13. package/dist/_astro/{DocsFileBrowser.D66pN9rp.js → DocsFileBrowser.DwKBffbM.js} +1 -1
  14. package/dist/_astro/{DocsPager.ceBEecmd.js → DocsPager.Duf4I68E.js} +1 -1
  15. package/dist/_astro/{DrawerField.CWpOf3L_.js → DrawerField.BH3p4Q4D.js} +1 -1
  16. package/dist/_astro/{KnowledgeLibrary.DYqE2mRi.js → KnowledgeLibrary.MDpMqeOd.js} +1 -1
  17. package/dist/_astro/{LifeKrTasksBoard.B7UiEutA.js → LifeKrTasksBoard.DsvW_S66.js} +1 -1
  18. package/dist/_astro/{LifeKrTodosBoard.VL7HdhNY.js → LifeKrTodosBoard.D2KTqvg1.js} +1 -1
  19. package/dist/_astro/{LifeObjectivesBoard.lLBPOHEZ.js → LifeObjectivesBoard.B0cDK934.js} +1 -1
  20. package/dist/_astro/{LifePlanTypeSelect.CdKQmlEK.js → LifePlanTypeSelect.BELDvMWU.js} +1 -1
  21. package/dist/_astro/{LifeReviewsBoard.AjO4SbsR.js → LifeReviewsBoard.BPXeVpg1.js} +1 -1
  22. package/dist/_astro/{LifeShared.CtdsQI43.js → LifeShared.tnT7aQON.js} +1 -1
  23. package/dist/_astro/{LifeStagesBoard.Dl-kTZ6K.js → LifeStagesBoard.CZftLR9K.js} +1 -1
  24. package/dist/_astro/{LifeYearCycleSelect.BILJOKXK.js → LifeYearCycleSelect.Bw2eRbSm.js} +1 -1
  25. package/dist/_astro/{LifeYearPlansBoard.BzJmi7Hw.js → LifeYearPlansBoard.DB-RJFEl.js} +1 -1
  26. package/dist/_astro/{MultiSelectDropdown.y8JMbCxO.js → MultiSelectDropdown.CBC7aNOv.js} +1 -1
  27. package/dist/_astro/NavLibraries.DdQYsZbe.js +1 -0
  28. package/dist/_astro/OverflowHint.CHZeFfUj.js +1 -0
  29. package/dist/_astro/{PluginsPage.D2OrUGY3.js → PluginsPage.C1JnInH4.js} +1 -1
  30. package/dist/_astro/PluginsPage.C3eEwy3K.js +1 -0
  31. package/dist/_astro/{PmBugsBoard.BynUocbE.js → PmBugsBoard.CGpXUTPu.js} +1 -1
  32. package/dist/_astro/{PmIterationsBoard.CvFblvfX.js → PmIterationsBoard.BaKiFIam.js} +1 -1
  33. package/dist/_astro/{PmProjectDetail.Dlm6flwk.js → PmProjectDetail.DneFVBpy.js} +1 -1
  34. package/dist/_astro/{PmProjectsBoard.B5vaWuax.js → PmProjectsBoard.BxoMF9gK.js} +1 -1
  35. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +1 -0
  36. package/dist/_astro/{PmRequirementsBoard.piRWjiYA.js → PmRequirementsBoard.DsK6RF7Q.js} +1 -1
  37. package/dist/_astro/PmShared.BK8kWRSV.js +1 -0
  38. package/dist/_astro/{PromptMountDialog.DYojFMok.js → PromptMountDialog.mrTx3U5T.js} +1 -1
  39. package/dist/_astro/PromptsLibrary.B_SUf47p.js +1 -0
  40. package/dist/_astro/{ReportsPage.B-xhGVEU.js → ReportsPage.B9lGg1_s.js} +1 -1
  41. package/dist/_astro/{ReqAnalysisBoard.B3sAOuAq.js → ReqAnalysisBoard.CIZKnCQH.js} +1 -1
  42. package/dist/_astro/{RequirementsLibrary.BGys7DeN.js → RequirementsLibrary.cJc-bnGQ.js} +1 -1
  43. package/dist/_astro/{SearchableSelect.DFZBUFIs.js → SearchableSelect.SyLRS-Jj.js} +1 -1
  44. package/dist/_astro/SelectDropdown.T3CKHaLt.js +1 -0
  45. package/dist/_astro/{SettingsDialog.CEyjZuxq.js → SettingsDialog.DYdtCvLc.js} +1 -1
  46. package/dist/_astro/{SpaceSwitcher.DJqvw5Lw.js → SpaceSwitcher.C47_S1g9.js} +1 -1
  47. package/dist/_astro/{TableFieldConfig.D0v9S2g3.js → TableFieldConfig.C7O-mL-p.js} +1 -1
  48. package/dist/_astro/{TasksBoard.DZ9LLl_c.js → TasksBoard.BUEg2BYk.js} +1 -1
  49. package/dist/_astro/{TemplatesLibrary.iyj_kFMO.js → TemplatesLibrary.BLVIphXO.js} +1 -1
  50. package/dist/_astro/{TestReportsLibrary.B6pf0d7W.js → TestReportsLibrary.DVq30Jae.js} +1 -1
  51. package/dist/_astro/{TestStatsBoard.DS_2bqWI.js → TestStatsBoard.-5BWQ6bI.js} +1 -1
  52. package/dist/_astro/{TodosBoard.CYAVDD1W.js → TodosBoard.DI_lTp2e.js} +1 -1
  53. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +2 -0
  54. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +19 -0
  55. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +1 -0
  56. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +3 -0
  57. package/dist/_astro/app-config.DkyjuL-S.js +1 -0
  58. package/dist/_astro/app-version.Cy-5oZO2.js +1 -0
  59. package/dist/_astro/{bash-tools.CfNj2sh0.js → bash-tools.D9HCzC_7.js} +1 -1
  60. package/dist/_astro/{case-gen-run.nrr97yK3.js → case-gen-run.BklG1H8k.js} +1 -1
  61. package/dist/_astro/{case-types.B51yDRdf.js → case-types.DlFkbZJN.js} +1 -1
  62. package/dist/_astro/composer-draft.llpvz3MW.js +1 -0
  63. package/dist/_astro/composer-task.DRi5tAJs.js +5 -0
  64. package/dist/_astro/{hydrate-cache.CoD1FB3T.js → hydrate-cache.B15Nrpq0.js} +1 -1
  65. package/dist/_astro/i18n.D_aOCHSN.js +7 -0
  66. package/dist/_astro/{open-docs-in-session.DJtuI1C4.js → open-docs-in-session.CRiZT022.js} +1 -1
  67. package/dist/_astro/plugins.BRvXWHLe.js +1 -0
  68. package/dist/_astro/prompts-meta.BUGutlsk.js +2 -0
  69. package/dist/_astro/{req-analysis.qmyv5cBw.js → req-analysis.B12_MGMQ.js} +1 -1
  70. package/dist/_astro/{settings.CYERib3l.js → settings.38J2uD5M.js} +2 -2
  71. package/dist/_astro/{spaces-client.DvIgFink.js → spaces-client.DV04tRyD.js} +1 -1
  72. package/dist/_astro/{story-review.2UUlN3p-.js → story-review.D2W5tEOY.js} +1 -1
  73. package/dist/_astro/{test-reports.DPQ-FMsQ.js → test-reports.CuIjlEyK.js} +1 -1
  74. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +9 -0
  75. package/dist/_astro/ui-auto.DMv940x4.js +1 -0
  76. package/dist/_astro/{view-prefs.GnvelRDj.js → view-prefs.DhdLZjGh.js} +1 -1
  77. package/dist/case-exec/index.html +62 -6
  78. package/dist/cases/generate/index.html +62 -6
  79. package/dist/cases/library/index.html +62 -6
  80. package/dist/dashboard/index.html +62 -6
  81. package/dist/docs/changelog/index.html +138 -50
  82. package/dist/docs/install/index.html +61 -5
  83. package/dist/docs/manual/index.html +129 -21
  84. package/dist/knowledge/index.html +62 -6
  85. package/dist/life/kr-tasks/index.html +62 -6
  86. package/dist/life/kr-todos/index.html +62 -6
  87. package/dist/life/objectives/index.html +62 -6
  88. package/dist/life/reviews/index.html +62 -6
  89. package/dist/life/stages/index.html +62 -6
  90. package/dist/life/year-plans/index.html +62 -6
  91. package/dist/plugins/index.html +62 -6
  92. package/dist/pm/bugs/index.html +62 -6
  93. package/dist/pm/iterations/index.html +62 -6
  94. package/dist/pm/projects/detail/index.html +62 -6
  95. package/dist/pm/projects/index.html +62 -6
  96. package/dist/pm/requirements/index.html +62 -6
  97. package/dist/prompts/index.html +62 -6
  98. package/dist/reports/index.html +62 -6
  99. package/dist/requirement-analysis/index.html +62 -6
  100. package/dist/requirements/index.html +62 -6
  101. package/dist/tasks/index.html +62 -6
  102. package/dist/templates/index.html +62 -6
  103. package/dist/test-automation/index.html +63 -7
  104. package/dist/test-automation/projects/index.html +980 -0
  105. package/dist/test-reports/index.html +62 -6
  106. package/dist/test-stats/index.html +62 -6
  107. package/dist/todos/index.html +62 -6
  108. package/dist/workbench/index.html +62 -6
  109. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +1 -1
  110. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +107 -63
  111. package/lh-plugins/lh-uiauto.mjs +2502 -51
  112. package/lh-plugins/plugin-prompts.mjs +62 -2
  113. package/lh-plugins/storage-domain.mjs +17 -4
  114. package/lh-plugins/uiauto-adapters/playwright.mjs +29 -14
  115. package/lh-plugins/uiauto-adapters/tasks.mjs +8 -2
  116. package/lh-plugins/uiauto-env.mjs +669 -0
  117. package/lh-plugins/uiauto-explorer/apps.mjs +4 -5
  118. package/lh-plugins/uiauto-explorer/emit-files.mjs +32 -9
  119. package/lh-plugins/uiauto-explorer/emit-ts.mjs +13 -2
  120. package/lh-plugins/uiauto-explorer/ir.mjs +20 -0
  121. package/lh-plugins/uiauto-explorer/sessions.mjs +36 -0
  122. package/lh-plugins/uiauto-node.mjs +327 -0
  123. package/lh-plugins/uiauto-pm.mjs +178 -0
  124. package/lh-plugins/uiauto-prompt.mjs +228 -18
  125. package/lh-plugins/uiauto-report.mjs +16 -0
  126. package/lh-plugins/uiauto-scaffold/audit.mjs +356 -0
  127. package/lh-plugins/uiauto-scaffold/index.mjs +25 -0
  128. package/lh-plugins/uiauto-scaffold/library.mjs +508 -0
  129. package/lh-plugins/uiauto-scaffold/manifest.mjs +83 -0
  130. package/lh-plugins/uiauto-scaffold/render.mjs +133 -0
  131. package/lh-plugins/uiauto-scaffold/templates/playwright-ts.json +225 -0
  132. package/lh-plugins/uiauto-scaffold/templates/playwright-ts.mjs +46 -0
  133. package/package.json +1 -1
  134. package/dist/_astro/Base.BnVp5Mf8.css +0 -1
  135. package/dist/_astro/ChatApp.CKPGFibd.js +0 -227
  136. package/dist/_astro/ConfirmDialog.D5qXeML0.js +0 -1
  137. package/dist/_astro/NavLibraries.BnaL-km5.js +0 -1
  138. package/dist/_astro/OverflowHint.pvo2Xc8R.js +0 -1
  139. package/dist/_astro/PluginsPage.CMW4hEFr.js +0 -1
  140. package/dist/_astro/PmRequirementsBoard.B8KTeso8.js +0 -1
  141. package/dist/_astro/PmShared.86HEsdd_.js +0 -1
  142. package/dist/_astro/PromptsLibrary.GpNbBTj1.js +0 -1
  143. package/dist/_astro/SelectDropdown.Dmk5n225.js +0 -1
  144. package/dist/_astro/SlideOverDrawer.C1IVOc_8.js +0 -1
  145. package/dist/_astro/UiAutoBoard.DSsiMfx2.js +0 -9
  146. package/dist/_astro/app-config.DwpFFa5D.js +0 -1
  147. package/dist/_astro/app-version.Dabxyva-.js +0 -1
  148. package/dist/_astro/composer-task.DJmluzPT.js +0 -5
  149. package/dist/_astro/i18n.vo2aElR9.js +0 -7
  150. package/dist/_astro/plugins.BmKRnp4a.js +0 -1
  151. package/dist/_astro/prompts-meta.bF2q5SUy.js +0 -2
  152. package/dist/_astro/ui-auto-prompt.COBTt5Gd.js +0 -4
  153. package/dist/_astro/ui-auto.BmC9JJ_X.js +0 -1
@@ -0,0 +1,669 @@
1
+ /**
2
+ * 项目环境配置:读写项目里的 `.env` / `.env.<ENV>` 文件。
3
+ *
4
+ * 口径:
5
+ * - **文件是唯一真相**:平台只做「读 → 打码 → 改动的 key」,不另存一份配置 JSON,
6
+ * 避免 `.env` 与界面两边漂移;CLI 跑的时候读到的就是面板改过的同一份文件。
7
+ * - **字段归项目,不归平台**:界面上的分组与中文说明来自项目自己的 `.env.example`
8
+ * (`readEnvSchema`),平台只约定 `ENV` / `BASE_URL` / `ALLOW_PROD` 三条运行契约。
9
+ * - 只动命中的 `KEY=` 行:注释、空行、未知变量、用户自己的写法原样保留。
10
+ * - 密钥只回 `hasValue`,不回传明文;未改动的密钥保存时保留旧值。
11
+ * - 不生成 `config.ts` / `playwright.config.ts`:那是骨架与 AI 检查的范畴。
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ /**
17
+ * 平台约定的 3 条契约 key:接口只要它们一定在界面上,
18
+ * 因为它们被骨架的 `utils/env-loader.ts` / `playwright.config.ts` 直接消费。
19
+ */
20
+ export const PLATFORM_ENV_KEYS = [
21
+ { key: 'ENV', label: '环境名', readOnly: true, hint: '由环境文件名决定,改名请新建环境' },
22
+ { key: 'BASE_URL', label: '被测地址', hint: '去掉结尾斜杠' },
23
+ {
24
+ key: 'ALLOW_PROD',
25
+ label: '允许生产运行',
26
+ hint: 'prod 环境必须为 true,否则 env-loader 拒绝运行',
27
+ },
28
+ ];
29
+
30
+ /** 环境变量模板文件名:`.env.example` / `.env.dev.example` / ... */
31
+ const EXAMPLE_FILE = /^\.env(?:\.[a-z0-9_-]+)?\.example$/;
32
+
33
+ /** 模板文件(schema)候选顺序:优先共用 `.env.example`,再按环境名兜底 */
34
+ const EXAMPLE_CANDIDATES = ['.env.example'];
35
+
36
+ /** 密钥判定:名字里像密钥的变量 */
37
+ const SECRET_NAME = /(PASSWORD|PASSWD|TOKEN|SECRET|API_?KEY|PRIVATE_KEY|CREDENTIAL|COOKIE)/i;
38
+
39
+ const ENV_LINE = /^(\s*(?:export\s+)?)([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
40
+
41
+ /** 本机回环地址:prod 配到这儿说明环境选错了(与骨架 env-loader 的判定保持一致) */
42
+ const LOOPBACK_HOST = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|$)/i;
43
+
44
+ const ENV_NAME = /^[a-z][a-z0-9_-]{0,19}$/;
45
+
46
+ /** 环境名合法性:小写字母开头,只允许小写字母 / 数字 / `_` / `-`;空串表示 `.env` 共用默认 */
47
+ export function sanitizeEnvName(name) {
48
+ const value = String(name ?? '').trim();
49
+ if (!value) return '';
50
+ return ENV_NAME.test(value) ? value : '';
51
+ }
52
+
53
+ export function isEnvNameValid(name) {
54
+ const value = String(name ?? '').trim();
55
+ return !value || ENV_NAME.test(value);
56
+ }
57
+
58
+ /**
59
+ * 骨架自带的固定环境:`.env`(各环境共用的兜底)与 `.env.prod`。
60
+ * 它们属于框架约定,不给删除入口;只有用户自己新建的 `.env.<ENV>` 才能删。
61
+ */
62
+ export function isSkeletonEnv(name) {
63
+ const value = sanitizeEnvName(name);
64
+ return value === '' || value === 'prod';
65
+ }
66
+
67
+ /** 是不是环境变量模板文件(`.env.example` 及按环境拆的变体) */
68
+ export function isExampleFileName(name) {
69
+ return EXAMPLE_FILE.test(String(name ?? '').trim());
70
+ }
71
+
72
+ /** 平台约定 key 的元数据;其它 key 返回 null(说明归项目模板管) */
73
+ export function envKeyMeta(key) {
74
+ return PLATFORM_ENV_KEYS.find((item) => item.key === key) ?? null;
75
+ }
76
+
77
+ export function isSecretKey(key) {
78
+ return SECRET_NAME.test(String(key ?? ''));
79
+ }
80
+
81
+ /**
82
+ * 拆一行的值:支持引号、未加引号的 ` # 注释`。
83
+ * `KEY=` 空值与 `KEY="a # b"` 都要还原成真正的值。
84
+ */
85
+ export function parseEnvValue(rawValue) {
86
+ const raw = String(rawValue ?? '');
87
+ const trimmed = raw.trim();
88
+ if (!trimmed) return '';
89
+ const quote = trimmed[0];
90
+ if (quote === '"' || quote === "'") {
91
+ let out = '';
92
+ for (let index = 1; index < trimmed.length; index += 1) {
93
+ const char = trimmed[index];
94
+ if (char === '\\' && quote === '"' && index + 1 < trimmed.length) {
95
+ out += trimmed[index + 1];
96
+ index += 1;
97
+ continue;
98
+ }
99
+ if (char === quote) return out;
100
+ out += char;
101
+ }
102
+ return out;
103
+ }
104
+ const commentAt = trimmed.search(/\s#/);
105
+ return (commentAt >= 0 ? trimmed.slice(0, commentAt) : trimmed).trim();
106
+ }
107
+
108
+ /** 一行的值 + 行尾注释:替换值时把用户写的注释一起保留 */
109
+ function splitValueAndComment(rawValue) {
110
+ const raw = String(rawValue ?? '');
111
+ const trimmed = raw.trim();
112
+ if (!trimmed) return { value: '', comment: '' };
113
+ const quote = trimmed[0];
114
+ if (quote === '"' || quote === "'") {
115
+ let index = 1;
116
+ for (; index < trimmed.length; index += 1) {
117
+ if (trimmed[index] === '\\' && quote === '"') {
118
+ index += 1;
119
+ continue;
120
+ }
121
+ if (trimmed[index] === quote) break;
122
+ }
123
+ if (index >= trimmed.length) return { value: parseEnvValue(trimmed), comment: '' };
124
+ return {
125
+ value: parseEnvValue(trimmed.slice(0, index + 1)),
126
+ comment: trimmed.slice(index + 1).trim(),
127
+ };
128
+ }
129
+ const commentAt = trimmed.search(/\s#/);
130
+ if (commentAt < 0) return { value: trimmed, comment: '' };
131
+ return { value: trimmed.slice(0, commentAt).trim(), comment: trimmed.slice(commentAt).trim() };
132
+ }
133
+
134
+ /**
135
+ * 写回时的值格式:含空格 / `#` / 引号时加引号。
136
+ * 优先用单引号(dotenv 对单引号只做去引号、不处理转义,JSON 里的 `"` 不用转义);
137
+ * 值里有单引号时退回双引号,三种引号都有才用反斜杠转义(极少见)。
138
+ */
139
+ export function formatEnvValue(value) {
140
+ const text = String(value ?? '');
141
+ if (!text) return '';
142
+ if (!/[\s#'"`]/.test(text) && text === text.trim()) return text;
143
+ if (!text.includes("'")) return `'${text}'`;
144
+ if (!text.includes('"')) return `"${text}"`;
145
+ if (!text.includes('`')) return `\`${text}\``;
146
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
147
+ }
148
+
149
+ /**
150
+ * 解析 `.env` 文本:保留原始行,同时给出每个 KEY 的值与所在行号。
151
+ * 只认 `KEY=value` / `export KEY=value` 两种写法,其它行(注释、空行)原样留着。
152
+ *
153
+ * 注释分两种(界面上「其它变量」靠它还原用户自己的结构):
154
+ * - `section`:前面的注释块与上一个 KEY 之间隔了空行(或就在文件开头),
155
+ * 视为分节标题,例如 `# SIP 自动应答(UDP)`;
156
+ * - `comment`:注释块紧贴在上一个 KEY 下面,视为这个 KEY 的字段说明,
157
+ * 例如 `# 签入坐席工号`。
158
+ */
159
+ export function parseEnvText(raw) {
160
+ const source = String(raw ?? '').replace(/\r\n/g, '\n');
161
+ const trailingNewline = source.endsWith('\n');
162
+ const body = trailingNewline ? source.slice(0, -1) : source;
163
+ const lines = body === '' ? [] : body.split('\n');
164
+ const entries = [];
165
+ let comments = [];
166
+ // 上一个 KEY 之后出现过空行(文件开头也算):下一次注释就是分节标题
167
+ let blank = true;
168
+ lines.forEach((line, index) => {
169
+ const matched = ENV_LINE.exec(line);
170
+ if (!matched) {
171
+ const trimmed = line.trim();
172
+ if (trimmed.startsWith('#')) comments.push(trimmed.replace(/^#+\s*/, ''));
173
+ else {
174
+ comments = [];
175
+ blank = true;
176
+ }
177
+ return;
178
+ }
179
+ const label = comments.join(' / ');
180
+ const isSection = Boolean(label) && blank;
181
+ entries.push({
182
+ key: matched[2],
183
+ value: parseEnvValue(matched[3]),
184
+ line: index,
185
+ comment: isSection ? '' : label,
186
+ section: isSection ? label : '',
187
+ });
188
+ comments = [];
189
+ blank = false;
190
+ });
191
+ return { lines, entries, trailingNewline };
192
+ }
193
+
194
+ /**
195
+ * 批量粘贴导入:把一段 `.env` 文本合并进现有文件。
196
+ *
197
+ * - 文件里已有的 key:只换值(保留原有行与行尾注释);
198
+ * - 文件里没有的 key:连它上面的注释一起,按粘贴顺序整段追加到末尾——
199
+ * 这样用户从别的项目搬过来的分节注释不会丢;
200
+ * - 只认合法 `KEY=value`,注释 / 空行只在「新增」时保留。
201
+ */
202
+ export function mergeEnvText(original, pasted) {
203
+ const incoming = parseEnvText(pasted);
204
+ const existingEntries = parseEnvText(original).entries;
205
+ const existing = new Set(existingEntries.map((entry) => entry.key));
206
+ const existingValues = new Map(
207
+ existingEntries.map((entry) => [entry.key, String(entry.value ?? '')]),
208
+ );
209
+ const updates = {};
210
+ const block = [];
211
+ const added = new Set();
212
+ /** 紧挨在下一个 KEY 上面的注释 / 空行:只在「新增这个 key」时保留 */
213
+ let buffer = [];
214
+ const source = String(pasted ?? '').replace(/\r\n/g, '\n');
215
+ for (const line of source.split('\n')) {
216
+ const matched = ENV_LINE.exec(line);
217
+ if (!matched) {
218
+ buffer.push(line.trimEnd());
219
+ continue;
220
+ }
221
+ const key = matched[2];
222
+ if (existing.has(key)) {
223
+ const nextValue = parseEnvValue(matched[3]);
224
+ // 粘贴里留空(模板常见写法)不覆盖文件里已有的值,等同「留空不改」
225
+ const keepExisting = nextValue === '' && existingValues.get(key) !== '';
226
+ if (!(key in updates) && !keepExisting) updates[key] = nextValue;
227
+ buffer = [];
228
+ continue;
229
+ }
230
+ if (added.has(key)) {
231
+ buffer = [];
232
+ continue;
233
+ }
234
+ added.add(key);
235
+ block.push(...buffer, line.trimEnd());
236
+ buffer = [];
237
+ }
238
+ // 去掉块首尾的空行(粘贴时常带上前后的空行)
239
+ while (block.length && !block[0].trim()) block.shift();
240
+ while (block.length && !block[block.length - 1].trim()) block.pop();
241
+ if (!Object.keys(updates).length && !block.length) {
242
+ return { text: String(original ?? ''), updated: 0, created: 0, total: incoming.entries.length };
243
+ }
244
+ let next = patchEnvText(original, updates);
245
+ if (block.length) {
246
+ next = next.replace(/\n+$/, '');
247
+ if (next) next += '\n\n';
248
+ next += `${block.join('\n')}\n`;
249
+ }
250
+ return {
251
+ text: next,
252
+ updated: Object.keys(updates).length,
253
+ created: added.size,
254
+ total: incoming.entries.length,
255
+ };
256
+ }
257
+
258
+ /**
259
+ * 只改命中的行:
260
+ * - `updates` 里的 key 替换值(保留缩进 / `export ` / 行尾注释);
261
+ * - `remove` 里的 key 整行删掉;
262
+ * - 缺失的 key 追加到末尾(先补一个分隔空行,避免和上面挤在一起);
263
+ * - 没在 `updates` / `remove` 里的行一个字符都不动。
264
+ */
265
+ export function patchEnvText(original, updates = {}, remove = []) {
266
+ const parsed = parseEnvText(original);
267
+ const pending = new Map(
268
+ Object.entries(updates ?? {})
269
+ .filter(([key]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(String(key)))
270
+ .map(([key, value]) => [key, String(value ?? '')]),
271
+ );
272
+ const removeSet = new Set((remove ?? []).map((key) => String(key)));
273
+ const seen = new Set();
274
+ const out = [];
275
+
276
+ for (const line of parsed.lines) {
277
+ const matched = ENV_LINE.exec(line);
278
+ if (!matched) {
279
+ out.push(line);
280
+ continue;
281
+ }
282
+ const key = matched[2];
283
+ if (removeSet.has(key)) {
284
+ seen.add(key);
285
+ continue;
286
+ }
287
+ if (!pending.has(key)) {
288
+ out.push(line);
289
+ seen.add(key);
290
+ continue;
291
+ }
292
+ const { comment } = splitValueAndComment(matched[3]);
293
+ const nextValue = formatEnvValue(pending.get(key));
294
+ out.push(`${matched[1]}${key}=${nextValue}${comment ? ` ${comment}` : ''}`);
295
+ seen.add(key);
296
+ }
297
+
298
+ const appended = [];
299
+ for (const [key, value] of pending) {
300
+ if (seen.has(key) || removeSet.has(key)) continue;
301
+ appended.push(`${key}=${formatEnvValue(value)}`);
302
+ }
303
+ if (appended.length) {
304
+ while (out.length && !out[out.length - 1].trim()) out.pop();
305
+ if (out.length) out.push('');
306
+ out.push(...appended);
307
+ out.push('');
308
+ }
309
+
310
+ const body = out.join('\n');
311
+ if (!body) return parsed.trailingNewline && original ? '\n' : '';
312
+ // 结尾空行已经由追加逻辑补上;用户原来怎么结尾就怎么结尾
313
+ if (appended.length) return body;
314
+ return parsed.trailingNewline ? `${body}\n` : body;
315
+ }
316
+
317
+ /** 打码:密钥只回 `hasValue`,界面拿不到明文 */
318
+ export function maskEnvEntries(entries) {
319
+ return entries.map((entry) => {
320
+ const secret = isSecretKey(entry.key);
321
+ return {
322
+ key: entry.key,
323
+ value: secret ? '' : entry.value,
324
+ hasValue: Boolean(entry.value),
325
+ secret,
326
+ // 是否平台契约 key(ENV / BASE_URL / ALLOW_PROD):说明文案归平台,其余归项目模板
327
+ platform: Boolean(envKeyMeta(entry.key)),
328
+ // 文件里这个 KEY 上面的分节注释 / 字段注释:界面用它还原用户自己的结构
329
+ comment: String(entry.comment ?? '').slice(0, 200),
330
+ section: String(entry.section ?? '').slice(0, 200),
331
+ };
332
+ });
333
+ }
334
+
335
+ /** 环境名 → 文件名(空串表示 `.env`) */
336
+ export function envFileName(env) {
337
+ const name = sanitizeEnvName(env);
338
+ return name ? `.env.${name}` : '.env';
339
+ }
340
+
341
+ /** 环境名 → 项目里的绝对路径;名字非法返回空串 */
342
+ export function envFilePath(dir, env) {
343
+ if (!isEnvNameValid(env)) return '';
344
+ return path.join(path.resolve(dir), envFileName(env));
345
+ }
346
+
347
+ /** 项目里已有哪些环境文件;`env: ''` 表示共用的 `.env`;模板文件不算环境 */
348
+ export function scanEnvFiles(dir) {
349
+ const list = [];
350
+ try {
351
+ if (fs.existsSync(path.join(dir, '.env'))) list.push({ env: '', file: '.env' });
352
+ for (const name of fs.readdirSync(dir)) {
353
+ if (isExampleFileName(name)) continue;
354
+ const matched = /^\.env\.([A-Za-z0-9_-]+)$/.exec(name);
355
+ if (!matched) continue;
356
+ list.push({ env: matched[1].toLowerCase(), file: name });
357
+ }
358
+ } catch {
359
+ return [];
360
+ }
361
+ return list.sort((a, b) => (a.env === '' ? -1 : b.env === '' ? 1 : a.env.localeCompare(b.env)));
362
+ }
363
+
364
+ /** 旧骨架把模板写成了 `.env.dev.example` / `.env.test.example`:统一改名成共用的 `.env.example` */
365
+ const LEGACY_EXAMPLE_FILES = ['.env.dev.example', '.env.uat.example', '.env.test.example'];
366
+
367
+ export function migrateLegacyExampleFile(dir) {
368
+ const root = path.resolve(dir);
369
+ const target = path.join(root, '.env.example');
370
+ if (fs.existsSync(target)) return '';
371
+ for (const legacy of LEGACY_EXAMPLE_FILES) {
372
+ const abs = path.join(root, legacy);
373
+ if (!fs.existsSync(abs)) continue;
374
+ try {
375
+ // 模板里的 ENV 只是占位(新建环境时按文件名重写),老文件里的 dev / test 一并清掉
376
+ const text = fs.readFileSync(abs, 'utf8').replace(/^\s*ENV\s*=.*$/m, 'ENV=');
377
+ fs.writeFileSync(target, text, 'utf8');
378
+ fs.unlinkSync(abs);
379
+ return legacy;
380
+ } catch {
381
+ return '';
382
+ }
383
+ }
384
+ return '';
385
+ }
386
+
387
+ /** 项目里实际当 schema 的模板文件绝对路径;没有返回空串 */
388
+ export function envExampleFile(dir) {
389
+ const root = path.resolve(dir);
390
+ for (const name of EXAMPLE_CANDIDATES) {
391
+ const abs = path.join(root, name);
392
+ if (fs.existsSync(abs)) return abs;
393
+ }
394
+ // 没有共用模板就退到按环境拆的:`.env.test.example` / `.env.prod.example` / 任意 `.env.*.example`(按名字排序)
395
+ try {
396
+ const found = fs
397
+ .readdirSync(root)
398
+ .filter((name) => isExampleFileName(name))
399
+ .sort((a, b) => (a === '.env.example' ? -1 : b === '.env.example' ? 1 : a.localeCompare(b)));
400
+ return found.length ? path.join(root, found[0]) : '';
401
+ } catch {
402
+ return '';
403
+ }
404
+ }
405
+
406
+ /** 模板里的值只当 placeholder:空值、占位符模板、密钥类都不展示 */
407
+ function templatePlaceholder(value) {
408
+ const text = String(value ?? '').trim();
409
+ if (!text) return '';
410
+ // `{{password}}` / `{"token":"${token}"}` 这种是模板,不是真实示例
411
+ if (text.includes('{{') || text.includes('${')) return '';
412
+ if (/password|passwd|secret|token/i.test(text)) return '';
413
+ return text.length > 60 ? '' : text;
414
+ }
415
+
416
+ /** `# KEY=value`:注释状态的可选变量,schema 里也要露出来 */
417
+ const COMMENTED_ENV_LINE = /^\s*#+\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
418
+
419
+ /**
420
+ * 读 `.env.example` 当项目的字段 schema:key 顺序、分组标题、字段中文说明都来自它。
421
+ *
422
+ * 注释约定:
423
+ * - 空行隔开的单个 `# 标题` → 下一个 key 的字段名;块里有多个 key 时升级成组标题;
424
+ * - 连着两行注释 `# 分组` + `# 字段说明` → 第一行是组标题,其余是字段说明;
425
+ * - 空行之后才出现的注释 → 组标题;紧贴 key 的注释 → 字段说明;
426
+ * - `# KEY=值` 按「可选字段」收进 schema(模板里注释掉、要用再打开)。
427
+ */
428
+ export function readEnvSchema(dir) {
429
+ const file = envExampleFile(dir);
430
+ if (!file) return { source: '', blocks: [], keys: [] };
431
+ let text = '';
432
+ try {
433
+ text = fs.readFileSync(file, 'utf8');
434
+ } catch {
435
+ return { source: '', blocks: [], keys: [] };
436
+ }
437
+ const blocks = [];
438
+ /** 紧贴 key 上方的注释块 */
439
+ let pending = [];
440
+ /** 空行之上留下的注释:视为下一个分组的标题 */
441
+ let header = '';
442
+
443
+ const pushKey = (key, rawValue, optional) => {
444
+ let title = header;
445
+ let label = '';
446
+ let hint = '';
447
+ if (pending.length === 1) {
448
+ if (title) hint = pending[0];
449
+ else label = pending[0];
450
+ } else if (pending.length > 1) {
451
+ const groupTitle = pending[0];
452
+ title = title || groupTitle;
453
+ hint = pending.slice(title === groupTitle ? 1 : 0).join(' / ');
454
+ }
455
+ const last = blocks[blocks.length - 1];
456
+ // 显式的组标题变了、或这个 key 自带一行字段名 → 另起一段;否则接到上一段
457
+ if (!last || (title && last.title !== title) || label) {
458
+ blocks.push({ title: title || '', keys: [] });
459
+ }
460
+ blocks[blocks.length - 1].keys.push({
461
+ key,
462
+ label,
463
+ hint,
464
+ placeholder: templatePlaceholder(rawValue),
465
+ ...(optional ? { optional: true } : {}),
466
+ });
467
+ pending = [];
468
+ header = '';
469
+ };
470
+
471
+ for (const line of String(text ?? '')
472
+ .replace(/\r\n/g, '\n')
473
+ .split('\n')) {
474
+ const matched = ENV_LINE.exec(line);
475
+ if (matched) {
476
+ pushKey(matched[2], matched[3], false);
477
+ continue;
478
+ }
479
+ const commented = COMMENTED_ENV_LINE.exec(line);
480
+ if (commented) {
481
+ pushKey(commented[1], commented[2], true);
482
+ continue;
483
+ }
484
+ const trimmed = line.trim();
485
+ if (trimmed) {
486
+ pending.push(trimmed.replace(/^#+\s*/, ''));
487
+ } else {
488
+ // 空行:上面攒的注释成为「分组标题」,等下一个 key 落地
489
+ if (pending.length) header = pending.join(' / ');
490
+ pending = [];
491
+ }
492
+ }
493
+ // 分组里第一个 key 带了 label、后来又并进别的 key:label 升级成组标题
494
+ for (const block of blocks) {
495
+ if (block.keys.length > 1 && !block.title) {
496
+ const first = block.keys[0];
497
+ if (first.label) {
498
+ block.title = first.label;
499
+ first.label = '';
500
+ }
501
+ }
502
+ }
503
+ // 单 key 分组:标题就是字段名,省掉重复的组标题
504
+ const out = blocks.map((block) =>
505
+ block.keys.length === 1 && block.title
506
+ ? {
507
+ title: '',
508
+ keys: [{ ...block.keys[0], label: block.title }],
509
+ }
510
+ : block,
511
+ );
512
+ return {
513
+ source: path.basename(file),
514
+ blocks: out.filter((block) => block.keys.length),
515
+ keys: out.flatMap((block) => block.keys.map((item) => item.key)),
516
+ };
517
+ }
518
+
519
+ /**
520
+ * 扫项目里所有 `.env` / `.env.*`(排除模板),只取 key 名:
521
+ * 界面用它给当前环境标注「这个 key 在 test / prod 里已经配过」,不用用户一条条加。
522
+ */
523
+ export function readEnvKeyMatrix(dir, currentEnv = '') {
524
+ const root = path.resolve(dir);
525
+ const current = sanitizeEnvName(currentEnv);
526
+ const keyEnvs = {};
527
+ const envKeys = {};
528
+ let files = [];
529
+ try {
530
+ files = fs
531
+ .readdirSync(root)
532
+ .filter((name) => /^\.env(\.[A-Za-z0-9_-]+)?$/.test(name) && !isExampleFileName(name));
533
+ } catch {
534
+ return { keyEnvs: {}, envKeys: {} };
535
+ }
536
+ for (const name of files.sort()) {
537
+ const matched = /^\.env\.([A-Za-z0-9_-]+)$/.exec(name);
538
+ const env = matched ? matched[1].toLowerCase() : '';
539
+ if (env === current) continue;
540
+ let keys = [];
541
+ try {
542
+ keys = parseEnvText(fs.readFileSync(path.join(root, name), 'utf8'))
543
+ .entries.filter((entry) => entry.key !== 'ENV' && String(entry.value ?? '').trim())
544
+ .map((entry) => entry.key)
545
+ .slice(0, 300);
546
+ } catch {
547
+ continue;
548
+ }
549
+ envKeys[env] = keys;
550
+ for (const key of keys) {
551
+ if (!keyEnvs[key]) keyEnvs[key] = [];
552
+ if (!keyEnvs[key].includes(env)) keyEnvs[key].push(env);
553
+ }
554
+ }
555
+ return { keyEnvs, envKeys };
556
+ }
557
+
558
+ /**
559
+ * 项目是不是按 `ENV` + `.env.<ENV>` 这套约定做的:
560
+ * 有 `.env.example`,或 `package.json` 里出现 `cross-env ENV=`.
561
+ */
562
+ export function hasEnvConvention(dir) {
563
+ try {
564
+ if (fs.existsSync(path.join(dir, '.env.example'))) return true;
565
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
566
+ const scripts = pkg?.scripts ?? {};
567
+ return Object.values(scripts).some((command) => /cross-env\s+ENV=/i.test(String(command)));
568
+ } catch {
569
+ return false;
570
+ }
571
+ }
572
+
573
+ /**
574
+ * `.auth/` 下的登录态文件(切环境后通常要清理)。
575
+ * 不写死文件名:骨架可能存 admin / user,也可能按业务角色自定义。
576
+ */
577
+ export function listAuthStateFiles(dir) {
578
+ const root = path.join(dir, '.auth');
579
+ try {
580
+ if (!fs.statSync(root).isDirectory()) return [];
581
+ return fs
582
+ .readdirSync(root)
583
+ .filter((name) => name.endsWith('.json'))
584
+ .sort()
585
+ .map((name) => `.auth/${name}`);
586
+ } catch {
587
+ return [];
588
+ }
589
+ }
590
+
591
+ /**
592
+ * 保存前校验:只报「一定会出问题」的,别拦着用户存半份配置。
593
+ * 业务字段(账号 / 接口登录等)由项目模板决定,这里只做通用推断 + 平台契约检查。
594
+ * 返回 `{ errors, warnings }`,都是 `{ key, message }`。
595
+ */
596
+ export function validateEnvEntries(entries = {}, env = '') {
597
+ const errors = [];
598
+ const warnings = [];
599
+ const keys = Object.keys(entries ?? {});
600
+ const get = (key) => String(entries[key] ?? '').trim();
601
+ const baseURL = get('BASE_URL');
602
+ if (baseURL) {
603
+ if (!/^https?:\/\//i.test(baseURL)) {
604
+ errors.push({ key: 'BASE_URL', message: 'BASE_URL 必须以 http:// 或 https:// 开头' });
605
+ }
606
+ if (baseURL.endsWith('/')) {
607
+ warnings.push({
608
+ key: 'BASE_URL',
609
+ message: 'BASE_URL 结尾有 /,建议去掉(拼路径时容易多一层)',
610
+ });
611
+ }
612
+ }
613
+ // 账号配对:不认具体角色名,只看 `*_USERNAME` / `*_USER` 与同前缀的 `*_PASSWORD` / `*_PASSWD` 是否成对
614
+ for (const key of keys) {
615
+ const matched = /^(.*_)?(USERNAME|USER)$/.exec(key);
616
+ if (!matched) continue;
617
+ const prefix = matched[1] ?? '';
618
+ const passKey = ['PASSWORD', 'PASSWD']
619
+ .map((suffix) => `${prefix}${suffix}`)
620
+ .find((candidate) => keys.includes(candidate));
621
+ if (!passKey) continue;
622
+ if (Boolean(get(key)) !== Boolean(get(passKey))) {
623
+ warnings.push({
624
+ key: passKey,
625
+ message: `${key} 与 ${passKey} 要成对填写,只填一半登录会失败`,
626
+ });
627
+ }
628
+ }
629
+ if (sanitizeEnvName(env) === 'prod' && get('ALLOW_PROD') !== 'true') {
630
+ // 只提示不拦:文件可以先存着,真正跑 prod 时由项目里的 env-loader 硬性拒绝
631
+ warnings.push({
632
+ key: 'ALLOW_PROD',
633
+ message: 'prod 已保存,但运行前需把 ALLOW_PROD 改成 true,否则 env-loader 会直接拒绝执行',
634
+ });
635
+ }
636
+ if (sanitizeEnvName(env) === 'prod') {
637
+ // `.env` 被忽略、不随仓库分发:prod 少了 BASE_URL 会落到 config 兜底(本机地址),
638
+ // 看着跑完了其实打的是本机,所以面板这里也要点出来(真正拦截在 env-loader)
639
+ if (!baseURL) {
640
+ warnings.push({
641
+ key: 'BASE_URL',
642
+ message: 'prod 必须显式填 BASE_URL:.env 不随仓库分发,缺了 env-loader 会直接拒绝运行',
643
+ });
644
+ } else if (LOOPBACK_HOST.test(baseURL)) {
645
+ warnings.push({
646
+ key: 'BASE_URL',
647
+ message: `prod 的 BASE_URL 指向本机地址(${baseURL}),env-loader 会拒绝运行,请改成生产域名`,
648
+ });
649
+ }
650
+ }
651
+ return { errors, warnings };
652
+ }
653
+
654
+ /**
655
+ * 任务命令与所选 ENV 冲突:命令里写死了 `ENV=uat`,shell 里后设的值会盖掉面板选择。
656
+ * 返回提示文案,没冲突返回空串。
657
+ */
658
+ export function envTaskMismatch(command, envName) {
659
+ const selected = sanitizeEnvName(envName);
660
+ if (!selected) return '';
661
+ const text = String(command ?? '');
662
+ const found = new Set();
663
+ const re = /(?:^|[\s;&|(])ENV\s*=\s*([A-Za-z0-9_-]+)/g;
664
+ let matched;
665
+ while ((matched = re.exec(text))) found.add(matched[1].toLowerCase());
666
+ const conflict = [...found].find((name) => name !== selected);
667
+ if (!conflict) return '';
668
+ return `这条任务命令里写死了 ENV=${conflict},会覆盖面板选的 ENV=${selected};换一条不带 ENV= 的任务,或把环境选成 ${conflict}。`;
669
+ }
@@ -272,7 +272,7 @@ function pruneOldIcons(cacheDir, appId, keep) {
272
272
  /**
273
273
  * 用指定应用打开文件或目录。
274
274
  * - editor:有 CLI 用 `<cli> -g file:line`(能定位到行),否则 `open -a App file`
275
- * - finder:`open -R file`(选中文件)/ `open dir`
275
+ * - finder:文件用 `open -R`(在父目录里选中它),目录直接 `open` 进目录
276
276
  * - terminal:`open -a App dir`(在目录里开终端)
277
277
  * 全部走 argv,不做字符串拼接。
278
278
  */
@@ -285,10 +285,9 @@ export async function openWith({ abs, dir, app, line }) {
285
285
 
286
286
  if (kind === 'finder') {
287
287
  if (process.platform === 'darwin') {
288
- const exists = fs.existsSync(target);
289
- await execFileAsync('open', exists && abs ? ['-R', abs] : [dir || target], {
290
- timeout: 10000,
291
- });
288
+ // 打开目录时直接进去(`open -R` 只会停在父目录选中它)
289
+ const isFile = Boolean(abs) && fs.statSync(abs, { throwIfNoEntry: false })?.isFile();
290
+ await execFileAsync('open', isFile ? ['-R', abs] : [target], { timeout: 10000 });
292
291
  return;
293
292
  }
294
293
  await openWithSystem(target);