lantern-harness 0.1.45 → 0.2.3

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 (274) hide show
  1. package/CHANGELOG.md +242 -0
  2. package/README.md +25 -8
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-fs.mjs +93 -4
  6. package/builtin/session/lh-nav-groups.mjs +36 -1
  7. package/builtin/session/mcp-client.mjs +7 -3
  8. package/builtin/session/session-runs.mjs +5 -1
  9. package/builtin/session/skill-validation.mjs +72 -0
  10. package/builtin/session/space-layout.mjs +8 -1
  11. package/builtin/session/space-skills.mjs +758 -0
  12. package/cli/data-root.mjs +21 -4
  13. package/cli/lantern.mjs +26 -1
  14. package/cli/mcp-server.mjs +3733 -0
  15. package/cli/server.mjs +10 -2
  16. package/config/app.defaults.json +4 -2
  17. package/dist/500.html +14 -6
  18. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  19. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js +2 -0
  20. package/dist/_astro/BusinessMapBoard.CYxHcku_.js +5 -0
  21. package/dist/_astro/CaseExecBoard.CK9aGPmH.js +1 -0
  22. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  23. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  24. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  25. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  26. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  27. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  28. package/dist/_astro/DashboardBoard.qgc1s7pG.js +5 -0
  29. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  30. package/dist/_astro/DefectSubmitEntry.JI85N1-i.js +2 -0
  31. package/dist/_astro/DocsFileBrowser.z5JZ74cy.js +1 -0
  32. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.Dg765uHW.js} +1 -1
  33. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  34. package/dist/_astro/KnowledgeLibrary.mkShtVun.js +1 -0
  35. package/dist/_astro/LifeKrTasksBoard.DpAwQffE.js +1 -0
  36. package/dist/_astro/LifeKrTodosBoard.BIjPiZ8H.js +1 -0
  37. package/dist/_astro/LifeObjectivesBoard.DYwLHPEG.js +1 -0
  38. package/dist/_astro/LifePlanTypeSelect.CYaziESp.js +1 -0
  39. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.DIxoWBDA.js} +3 -3
  40. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.DuFQsMEx.js} +2 -2
  41. package/dist/_astro/LifeStagesBoard.DtOri9EW.js +1 -0
  42. package/dist/_astro/LifeYearCycleSelect.ByJ9-PGg.js +1 -0
  43. package/dist/_astro/LifeYearPlansBoard.BQN07wcv.js +1 -0
  44. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  45. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  46. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  47. package/dist/_astro/PluginsPage.B1VeDtLx.js +18 -0
  48. package/dist/_astro/PmBugsBoard.Ddl3kqqt.js +1 -0
  49. package/dist/_astro/PmIterationsBoard.BJN7disI.js +1 -0
  50. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.D78gWhqk.js} +1 -1
  51. package/dist/_astro/PmProjectsBoard.Bf8VB3t6.js +1 -0
  52. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  53. package/dist/_astro/PmRequirementsBoard.DarfGIrL.js +1 -0
  54. package/dist/_astro/PmShared.TOjBbtV8.js +1 -0
  55. package/dist/_astro/ReportsPage.BXGduuY3.js +1 -0
  56. package/dist/_astro/ReqAnalysisBoard.WLtIfBg8.js +39 -0
  57. package/dist/_astro/RequirementBreakdownLibrary.DMoeTeqX.js +2 -0
  58. package/dist/_astro/RequirementsLibrary.Iv7zOqWe.js +1 -0
  59. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  60. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  61. package/dist/_astro/SettingsDialog.BvDU9EU6.js +1 -0
  62. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  63. package/dist/_astro/SpaceSwitcher.D9bBNQBZ.js +7 -0
  64. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.DHj25OKN.js} +1 -1
  65. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  66. package/dist/_astro/TasksBoard.CXmGdylV.js +1 -0
  67. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  68. package/dist/_astro/TestReportsLibrary.BBC1TYgP.js +1 -0
  69. package/dist/_astro/TestStatsBoard.VXjP4hu6.js +1 -0
  70. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  71. package/dist/_astro/TodosBoard.-yKgp06M.js +1 -0
  72. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  73. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  74. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  75. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  76. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  77. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  78. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.C4DJiRJs.js} +1 -1
  79. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  80. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  81. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  82. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  83. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  84. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.BodP2jKm.js} +2 -2
  85. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.CC2eXegU.js} +2 -2
  86. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  87. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  88. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  89. package/dist/_astro/defect-workbench.DBmohR-y.js +6 -0
  90. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  91. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  92. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.CMMErx63.js} +1 -1
  93. package/dist/_astro/i18n.CEWjL5GX.js +7 -0
  94. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  95. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  96. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  97. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  98. package/dist/_astro/project-docs.BRgNjXhG.js +1 -0
  99. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  100. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  101. package/dist/_astro/req-analysis.BLvcktvQ.js +31 -0
  102. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  103. package/dist/_astro/{settings.38J2uD5M.js → settings.BojKNwUC.js} +2 -2
  104. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  105. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.B28rzu8J.js} +1 -1
  106. package/dist/_astro/story-review.dEBWTeOW.js +7 -0
  107. package/dist/_astro/test-points.BuNgdNcU.js +8 -0
  108. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  109. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  110. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  111. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.CWc5cQ2q.js} +1 -1
  112. package/dist/business-map/index.html +988 -0
  113. package/dist/case-exec/index.html +15 -7
  114. package/dist/{prompts → case-execution}/index.html +17 -9
  115. package/dist/cases/api/index.html +988 -0
  116. package/dist/cases/automation/index.html +988 -0
  117. package/dist/cases/functional/index.html +988 -0
  118. package/dist/cases/generate/index.html +14 -6
  119. package/dist/cases/index.html +1 -1
  120. package/dist/cases/library/index.html +1 -980
  121. package/dist/cases/other/index.html +988 -0
  122. package/dist/cases/performance/index.html +988 -0
  123. package/dist/dashboard/index.html +15 -7
  124. package/dist/defect-rules/index.html +695 -0
  125. package/dist/defect-submit/index.html +695 -0
  126. package/dist/defect-submit/templates/index.html +695 -0
  127. package/dist/docs/changelog/index.html +289 -52
  128. package/dist/docs/install/index.html +50 -12
  129. package/dist/docs/manual/index.html +230 -82
  130. package/dist/knowledge/index.html +15 -7
  131. package/dist/life/kr-tasks/index.html +15 -7
  132. package/dist/life/kr-todos/index.html +15 -7
  133. package/dist/life/objectives/index.html +15 -7
  134. package/dist/life/reviews/index.html +15 -7
  135. package/dist/life/stages/index.html +15 -7
  136. package/dist/life/year-plans/index.html +15 -7
  137. package/dist/plugins/index.html +15 -7
  138. package/dist/pm/bugs/index.html +15 -7
  139. package/dist/pm/iterations/index.html +15 -7
  140. package/dist/pm/projects/detail/index.html +15 -7
  141. package/dist/pm/projects/index.html +15 -7
  142. package/dist/pm/requirements/index.html +15 -7
  143. package/dist/reports/index.html +15 -7
  144. package/dist/requirement-analysis/index.html +15 -7
  145. package/dist/requirement-breakdowns/index.html +988 -0
  146. package/dist/requirements/index.html +15 -7
  147. package/dist/tasks/index.html +15 -7
  148. package/dist/templates/index.html +15 -7
  149. package/dist/test-automation/index.html +15 -7
  150. package/dist/test-automation/projects/index.html +15 -7
  151. package/dist/test-reports/index.html +15 -7
  152. package/dist/test-stats/index.html +15 -7
  153. package/dist/todos/index.html +15 -7
  154. package/dist/workbench/index.html +14 -6
  155. package/docs/Codex-MCP/351/233/206/346/210/220.md +340 -0
  156. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  157. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  158. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +28 -3
  159. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  160. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +65 -17
  161. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  162. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +219 -74
  163. package/lh-plugins/business-map/assistant.mjs +958 -0
  164. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  165. package/lh-plugins/business-map/jobs.mjs +749 -0
  166. package/lh-plugins/business-map/login.mjs +295 -0
  167. package/lh-plugins/business-map/sources.mjs +1014 -0
  168. package/lh-plugins/case-automation/service.mjs +921 -0
  169. package/lh-plugins/case-automation/store.mjs +231 -0
  170. package/lh-plugins/case-automation/tables.mjs +115 -0
  171. package/lh-plugins/case-automation-prompt.mjs +57 -0
  172. package/lh-plugins/case-execution/assets.mjs +180 -0
  173. package/lh-plugins/case-execution/files.mjs +829 -0
  174. package/lh-plugins/case-execution/plans.mjs +318 -0
  175. package/lh-plugins/case-execution/service.mjs +1026 -0
  176. package/lh-plugins/case-execution-prompt.mjs +36 -0
  177. package/lh-plugins/lh-business-map.mjs +2431 -0
  178. package/lh-plugins/lh-case-automation.mjs +169 -0
  179. package/lh-plugins/lh-case-design.mjs +456 -0
  180. package/lh-plugins/lh-case-execution.mjs +356 -0
  181. package/lh-plugins/lh-case-review.mjs +29 -11
  182. package/lh-plugins/lh-config.mjs +13 -0
  183. package/lh-plugins/lh-defect-submit.mjs +989 -0
  184. package/lh-plugins/lh-project-docs.mjs +55 -140
  185. package/lh-plugins/lh-reports.mjs +29 -57
  186. package/lh-plugins/lh-req-analysis.mjs +32 -3
  187. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  188. package/lh-plugins/lh-uiauto.mjs +625 -24
  189. package/lh-plugins/plugin-prompts.mjs +20 -15
  190. package/lh-plugins/req-analysis-revision.mjs +24 -0
  191. package/lh-plugins/test-points-prompt.mjs +2 -3
  192. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  193. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  194. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  195. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  196. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  197. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  198. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  199. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  200. package/lh-plugins/uiauto-explorer/runner.mjs +80 -5
  201. package/lh-plugins/uiauto-explorer/sessions.mjs +334 -18
  202. package/lh-plugins/uiauto-node.mjs +102 -11
  203. package/lh-plugins/uiauto-prompt.mjs +20 -15
  204. package/lh-plugins/uiauto-sso.mjs +407 -0
  205. package/package.json +5 -2
  206. package/skills/case-automation-bridge/SKILL.md +27 -0
  207. package/skills/case-execution/SKILL.md +41 -0
  208. package/skills/lantern-defect-submit/SKILL.md +15 -0
  209. package/skills/lantern-workflow/SKILL.md +95 -0
  210. package/skills/office/SKILL.md +26 -0
  211. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  212. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  213. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  214. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  215. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  216. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  217. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  218. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  219. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  220. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  221. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  222. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  223. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  224. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  225. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  226. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  227. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  228. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  229. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  230. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  231. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  232. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  233. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  234. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  235. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  236. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  237. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  238. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  239. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  240. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  241. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  242. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  243. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  244. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  245. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  246. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  247. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  248. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  249. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  250. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  251. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  252. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  253. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  254. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  255. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  256. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  257. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  258. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  259. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  260. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  261. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  262. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  263. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  264. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  265. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  266. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  267. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  268. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  269. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  270. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  271. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  272. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  273. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  274. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,829 @@
1
+ import { bindCaseIdentities, recordManualVerification } from './assets.mjs';
2
+ import crypto from 'node:crypto';
3
+ import { validateDefectLinks, CASE_FIELD_ALIASES } from '../../builtin/case-workflow-contract.mjs';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ import { resolveContentRoot } from '../../builtin/session/space-layout.mjs';
8
+ import {
9
+ CASE_BACKUP_DIR_NAME,
10
+ backupDirectoryForCasePath,
11
+ } from '../../builtin/case-backup-contract.mjs';
12
+
13
+ const CASE_DIR_NAME = '用例管理';
14
+ const DEFECT_URL_HEADER = '缺陷地址';
15
+ const EXECUTION_STATUSES = ['待验证', '通过', '不通过', '阻塞', '跳过'];
16
+
17
+ const ALIASES = {
18
+ ...CASE_FIELD_ALIASES,
19
+ no: CASE_FIELD_ALIASES.no,
20
+ title: CASE_FIELD_ALIASES.title,
21
+ precondition: CASE_FIELD_ALIASES.precondition,
22
+ steps: CASE_FIELD_ALIASES.steps,
23
+ expected: CASE_FIELD_ALIASES.expected,
24
+ priority: CASE_FIELD_ALIASES.priority,
25
+ module: CASE_FIELD_ALIASES.module,
26
+ submodule: CASE_FIELD_ALIASES.submodule,
27
+ status: ['用例状态', '执行状态', '执行结果', '测试结果'],
28
+ actual: ['实际结果', '实测结果', '执行实际结果'],
29
+ executor: ['执行人', '测试人'],
30
+ executedAt: ['执行时间', '测试时间'],
31
+ evidence: ['执行证据', '截图日志', '证据'],
32
+ defectNo: ['缺陷编号', '缺陷ID', 'BUG编号', 'bug编号'],
33
+ defectUrl: ['缺陷地址', '缺陷链接', '缺陷URL', 'BUG地址', 'bug地址', 'bug链接'],
34
+ };
35
+
36
+ function text(value, max = 4000) {
37
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
38
+ }
39
+
40
+ function hashBuffer(buffer) {
41
+ return crypto.createHash('sha256').update(buffer).digest('hex');
42
+ }
43
+
44
+ function normalizeHeader(value) {
45
+ return String(value || '')
46
+ .replace(/[((][^))]*[))]/g, '')
47
+ .replace(/[\s**・·::]/g, '')
48
+ .toLowerCase();
49
+ }
50
+
51
+ function fieldMap(headers) {
52
+ const pairs = headers
53
+ .map((header) => ({ raw: String(header || ''), norm: normalizeHeader(header) }))
54
+ .filter((item) => item.raw && item.norm);
55
+ const mapped = {};
56
+ const used = new Set();
57
+ for (const [field, aliases] of Object.entries(ALIASES)) {
58
+ for (const alias of aliases.map(normalizeHeader)) {
59
+ const hit =
60
+ pairs.find((item) => !used.has(item.raw) && item.norm === alias) ||
61
+ pairs.find(
62
+ (item) =>
63
+ !used.has(item.raw) &&
64
+ alias.length >= 2 &&
65
+ item.norm.startsWith(alias) &&
66
+ item.norm.length - alias.length <= 4,
67
+ );
68
+ if (!hit) continue;
69
+ mapped[field] = hit.raw;
70
+ used.add(hit.raw);
71
+ break;
72
+ }
73
+ }
74
+ return mapped;
75
+ }
76
+
77
+ function rowValue(row, map, field) {
78
+ const header = map[field];
79
+ return header ? String(row[header] ?? '') : '';
80
+ }
81
+
82
+ function caseRoot(root) {
83
+ return resolveContentRoot(root, CASE_DIR_NAME).abs;
84
+ }
85
+
86
+ function safeCasePath(root, relativePath) {
87
+ const base = path.resolve(caseRoot(root));
88
+ const abs = path.resolve(base, text(relativePath, 1000));
89
+ if (abs === base || !abs.startsWith(base + path.sep)) {
90
+ throw Object.assign(new Error('用例文件路径越界'), { statusCode: 400 });
91
+ }
92
+ return abs;
93
+ }
94
+
95
+ function ignored(name) {
96
+ return (
97
+ name === '.DS_Store' ||
98
+ name === '.gitkeep' ||
99
+ name.startsWith('~$') ||
100
+ name.startsWith('.~lock.') ||
101
+ /\.bak(?:[-_.].*)?$/i.test(name) ||
102
+ name.endsWith('~')
103
+ );
104
+ }
105
+
106
+ function walkCaseFiles(root, dir = caseRoot(root), relative = '') {
107
+ if (!fs.existsSync(dir)) return [];
108
+ const files = [];
109
+ for (const item of fs.readdirSync(dir, { withFileTypes: true })) {
110
+ if (ignored(item.name)) continue;
111
+ const rel = relative ? `${relative}/${item.name}` : item.name;
112
+ if (item.isDirectory()) {
113
+ if (item.name === CASE_BACKUP_DIR_NAME) continue;
114
+ files.push(...walkCaseFiles(root, path.join(dir, item.name), rel));
115
+ continue;
116
+ }
117
+ if (!item.isFile() || !/\.(xlsx|xls|csv|md)$/i.test(item.name)) continue;
118
+ const abs = path.join(dir, item.name);
119
+ const stat = fs.statSync(abs);
120
+ files.push({
121
+ path: rel,
122
+ name: item.name,
123
+ ext: path.extname(item.name).toLowerCase(),
124
+ size: stat.size,
125
+ mtime: stat.mtime.toISOString(),
126
+ });
127
+ }
128
+ return files.sort(
129
+ (left, right) =>
130
+ right.mtime.localeCompare(left.mtime) || left.path.localeCompare(right.path, 'zh'),
131
+ );
132
+ }
133
+
134
+ function decodeCell(value) {
135
+ return String(value ?? '')
136
+ .replace(/<br\s*\/?>/gi, '\n')
137
+ .replace(/&lt;/g, '<')
138
+ .replace(/&gt;/g, '>')
139
+ .replace(/&amp;/g, '&')
140
+ .trim();
141
+ }
142
+
143
+ function splitMarkdownRow(line) {
144
+ return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(decodeCell);
145
+ }
146
+
147
+ function isMarkdownSeparator(line) {
148
+ return /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && /-+/.test(line);
149
+ }
150
+
151
+ function parseMarkdown(raw) {
152
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
153
+ let headerIndex = -1;
154
+ let headers = [];
155
+ for (let index = 0; index < lines.length; index += 1) {
156
+ if (!lines[index].includes('|')) continue;
157
+ const cells = splitMarkdownRow(lines[index]);
158
+ if (!cells.some((cell) => /用例|测试/.test(cell)) || cells.length < 2) continue;
159
+ headerIndex = index;
160
+ headers = cells;
161
+ break;
162
+ }
163
+ if (headerIndex < 0) {
164
+ throw Object.assign(new Error('没有找到 Markdown 用例表头'), { statusCode: 422 });
165
+ }
166
+ const rows = [];
167
+ let dataStart = headerIndex + (isMarkdownSeparator(lines[headerIndex + 1] || '') ? 2 : 1);
168
+ for (let index = dataStart; index < lines.length; index += 1) {
169
+ const line = lines[index];
170
+ if (!line.includes('|')) break;
171
+ if (isMarkdownSeparator(line)) continue;
172
+ const cells = splitMarkdownRow(line);
173
+ if (!cells.some(Boolean)) continue;
174
+ const row = {};
175
+ headers.forEach((header, column) => {
176
+ if (header) row[header] = cells[column] ?? '';
177
+ });
178
+ rows.push({ row, lineIndex: index });
179
+ }
180
+ return { kind: 'md', lines, headers, rows, headerIndex };
181
+ }
182
+
183
+ function parseCsvRecords(raw) {
184
+ const source = raw.replace(/^\uFEFF/, '');
185
+ const records = [];
186
+ let field = '';
187
+ let record = [];
188
+ let quoted = false;
189
+ for (let index = 0; index < source.length; index += 1) {
190
+ const char = source[index];
191
+ if (quoted) {
192
+ if (char === '"' && source[index + 1] === '"') {
193
+ field += '"';
194
+ index += 1;
195
+ } else if (char === '"') {
196
+ quoted = false;
197
+ } else {
198
+ field += char;
199
+ }
200
+ continue;
201
+ }
202
+ if (char === '"') {
203
+ quoted = true;
204
+ } else if (char === ',') {
205
+ record.push(field);
206
+ field = '';
207
+ } else if (char === '\n' || char === '\r') {
208
+ if (char === '\r' && source[index + 1] === '\n') index += 1;
209
+ record.push(field);
210
+ field = '';
211
+ if (record.some((cell) => cell.trim())) records.push(record);
212
+ record = [];
213
+ } else {
214
+ field += char;
215
+ }
216
+ }
217
+ record.push(field);
218
+ if (record.some((cell) => cell.trim())) records.push(record);
219
+ return records;
220
+ }
221
+
222
+ function parseCsv(raw) {
223
+ const records = parseCsvRecords(raw);
224
+ if (!records.length) throw Object.assign(new Error('CSV 没有表头'), { statusCode: 422 });
225
+ const headers = records[0].map((cell) => String(cell || '').trim());
226
+ const rows = records.slice(1).map((cells, index) => {
227
+ const row = {};
228
+ headers.forEach((header, column) => {
229
+ if (header) row[header] = String(cells[column] ?? '').trim();
230
+ });
231
+ return { row, lineIndex: index + 1 };
232
+ });
233
+ return { kind: 'csv', headers, rows };
234
+ }
235
+
236
+ function headerScore(cells) {
237
+ const headers = cells.map((cell) => String(cell || '').trim()).filter(Boolean);
238
+ const map = fieldMap(headers);
239
+ if (!map.title || !map.steps) return 0;
240
+ return Object.keys(map).length * 10 + (map.expected ? 8 : 0) + (map.no ? 4 : 0);
241
+ }
242
+
243
+ async function parseXlsx(buffer) {
244
+ const mod = await import('xlsx');
245
+ const xlsx = mod.default ?? mod;
246
+ const book = xlsx.read(buffer, { type: 'buffer', cellDates: true });
247
+ let best = null;
248
+ for (const sheetName of book.SheetNames) {
249
+ const sheet = book.Sheets[sheetName];
250
+ if (!sheet) continue;
251
+ const range = sheet['!ref'] ? xlsx.utils.decode_range(sheet['!ref']) : { s: { r: 0 } };
252
+ const table = xlsx.utils.sheet_to_json(sheet, {
253
+ header: 1,
254
+ defval: '',
255
+ raw: false,
256
+ blankrows: true,
257
+ });
258
+ const bonus = /用例|测试/.test(sheetName) ? 20 : 0;
259
+ for (let index = 0; index < Math.min(30, table.length); index += 1) {
260
+ const score = headerScore(table[index] || []) + bonus - index;
261
+ if (score <= 0) continue;
262
+ if (!best || score > best.score) {
263
+ best = {
264
+ score,
265
+ sheetName,
266
+ headerRowIndex: index,
267
+ headers: (table[index] || []).map((cell) => String(cell ?? '').trim()),
268
+ table,
269
+ sheetStartRow: range.s.r,
270
+ };
271
+ }
272
+ }
273
+ }
274
+ if (!best) throw Object.assign(new Error('没有找到 Excel 用例表头'), { statusCode: 422 });
275
+ const rows = [];
276
+ for (let index = best.headerRowIndex + 1; index < best.table.length; index += 1) {
277
+ const cells = best.table[index] || [];
278
+ if (!cells.some((cell) => String(cell ?? '').trim())) continue;
279
+ const row = {};
280
+ best.headers.forEach((header, column) => {
281
+ if (header) row[header] = String(cells[column] ?? '').trim();
282
+ });
283
+ rows.push({
284
+ row,
285
+ dataIndex: index - best.headerRowIndex - 1,
286
+ physicalRow: best.sheetStartRow + index + 1,
287
+ });
288
+ }
289
+ return {
290
+ kind: 'xlsx',
291
+ headers: best.headers.filter(Boolean),
292
+ rawHeaders: best.headers,
293
+ rows,
294
+ sheetName: best.sheetName,
295
+ headerRowIndex: best.headerRowIndex,
296
+ headerRowNumber: best.sheetStartRow + best.headerRowIndex + 1,
297
+ };
298
+ }
299
+
300
+ function rowId(row, map, index) {
301
+ const no = rowValue(row, map, 'no');
302
+ const title = rowValue(row, map, 'title');
303
+ return `${no || index + 1}\0${title}`;
304
+ }
305
+
306
+ function publicRow(parsed, item, index) {
307
+ const map = fieldMap(parsed.headers);
308
+ const row = item.row;
309
+ const status = rowValue(row, map, 'status');
310
+ const actual = rowValue(row, map, 'actual');
311
+ return {
312
+ rowIndex: index,
313
+ id: crypto
314
+ .createHash('sha1')
315
+ .update(rowId(row, map, index))
316
+ .digest('hex')
317
+ .slice(0, 16),
318
+ no: rowValue(row, map, 'no'),
319
+ title: rowValue(row, map, 'title'),
320
+ module: [rowValue(row, map, 'module'), rowValue(row, map, 'submodule')]
321
+ .filter(Boolean)
322
+ .join(' / '),
323
+ priority: rowValue(row, map, 'priority'),
324
+ precondition: rowValue(row, map, 'precondition'),
325
+ steps: rowValue(row, map, 'steps'),
326
+ expected: rowValue(row, map, 'expected'),
327
+ status,
328
+ actual,
329
+ executor: rowValue(row, map, 'executor'),
330
+ executedAt: rowValue(row, map, 'executedAt'),
331
+ evidence: rowValue(row, map, 'evidence'),
332
+ defectNo: rowValue(row, map, 'defectNo'),
333
+ defectUrl: rowValue(row, map, 'defectUrl'),
334
+ fields: parsed.headers
335
+ .filter(Boolean)
336
+ .map((header) => ({ name: String(header), value: String(row[header] ?? '') })),
337
+ };
338
+ }
339
+
340
+ export async function loadCaseDocument(root, relativePath) {
341
+ const abs = safeCasePath(root, relativePath);
342
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
343
+ throw Object.assign(new Error('用例文件不存在'), { statusCode: 404 });
344
+ }
345
+ const buffer = fs.readFileSync(abs);
346
+ const fileHash = hashBuffer(buffer);
347
+ const ext = path.extname(abs).toLowerCase();
348
+ let parsed;
349
+ if (ext === '.xlsx' || ext === '.xls') parsed = await parseXlsx(buffer);
350
+ else if (ext === '.csv') parsed = parseCsv(buffer.toString('utf8'));
351
+ else if (ext === '.md') parsed = parseMarkdown(buffer.toString('utf8'));
352
+ else throw Object.assign(new Error(`不支持 ${ext} 用例文件`), { statusCode: 415 });
353
+ const map = fieldMap(parsed.headers);
354
+ const cases = parsed.rows.map((item, index) => publicRow(parsed, item, index));
355
+ const missingColumns = [!map.status ? '用例状态' : '', !map.actual ? '实际结果' : ''].filter(
356
+ Boolean,
357
+ );
358
+ const executionIssue =
359
+ ext === '.xls'
360
+ ? '旧版 .xls 暂不支持安全写回,请先另存为 .xlsx'
361
+ : missingColumns.length
362
+ ? `缺少执行列:${missingColumns.join('、')}`
363
+ : '';
364
+ return bindCaseIdentities(root, {
365
+ path: relativePath.replaceAll('\\', '/'),
366
+ abs,
367
+ ext,
368
+ fileHash,
369
+ headers: parsed.headers,
370
+ rawHeaders: parsed.rawHeaders || parsed.headers,
371
+ sheetName: parsed.sheetName || '',
372
+ headerRowIndex: parsed.headerRowIndex ?? 0,
373
+ cases,
374
+ columns: {
375
+ expected: map.expected || '',
376
+ priority: map.priority || '',
377
+ status: map.status || '',
378
+ actual: map.actual || '',
379
+ executor: map.executor || '',
380
+ executedAt: map.executedAt || '',
381
+ evidence: map.evidence || '',
382
+ defectNo: map.defectNo || '',
383
+ defectUrl: map.defectUrl || '',
384
+ },
385
+ executable: !executionIssue,
386
+ missingColumns,
387
+ executionIssue,
388
+ statuses: EXECUTION_STATUSES,
389
+ _parsed: parsed,
390
+ _map: map,
391
+ });
392
+ }
393
+
394
+ export async function listCaseDocuments(root) {
395
+ const files = walkCaseFiles(root);
396
+ const documents = [];
397
+ for (const file of files) {
398
+ try {
399
+ const document = await loadCaseDocument(root, file.path);
400
+ documents.push({
401
+ ...file,
402
+ caseCount: document.cases.length,
403
+ executable: document.executable,
404
+ missingColumns: document.missingColumns,
405
+ executionIssue: document.executionIssue,
406
+ });
407
+ } catch (error) {
408
+ documents.push({
409
+ ...file,
410
+ caseCount: 0,
411
+ executable: false,
412
+ missingColumns: [],
413
+ executionIssue: '用例文件解析失败',
414
+ error: error instanceof Error ? error.message : String(error),
415
+ });
416
+ }
417
+ }
418
+ return documents;
419
+ }
420
+
421
+ function stamp(date = new Date()) {
422
+ const pad = (value) => String(value).padStart(2, '0');
423
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
424
+ }
425
+
426
+ export function backupCaseDocument(root, relativePath) {
427
+ const abs = safeCasePath(root, relativePath);
428
+ const backupDir = path.join(
429
+ caseRoot(root),
430
+ ...backupDirectoryForCasePath(relativePath).split('/'),
431
+ );
432
+ fs.mkdirSync(backupDir, { recursive: true });
433
+ const ext = path.extname(abs);
434
+ const base = path.basename(abs, ext);
435
+ let target = path.join(backupDir, `${base}_bak_${stamp()}${ext}`);
436
+ let index = 2;
437
+ while (fs.existsSync(target)) {
438
+ target = path.join(backupDir, `${base}_bak_${stamp()}_${index}${ext}`);
439
+ index += 1;
440
+ }
441
+ fs.copyFileSync(abs, target);
442
+ return path.relative(caseRoot(root), target).replaceAll('\\', '/');
443
+ }
444
+
445
+ function xmlEscape(value) {
446
+ return String(value ?? '')
447
+ .replace(/&/g, '&amp;')
448
+ .replace(/</g, '&lt;')
449
+ .replace(/>/g, '&gt;')
450
+ .replace(/"/g, '&quot;');
451
+ }
452
+
453
+ function columnIndex(ref) {
454
+ const letters = /^[A-Z]+/i.exec(ref)?.[0]?.toUpperCase() || 'A';
455
+ let value = 0;
456
+ for (const char of letters) value = value * 26 + char.charCodeAt(0) - 64;
457
+ return value;
458
+ }
459
+
460
+ function columnName(index) {
461
+ let value = index;
462
+ let out = '';
463
+ while (value > 0) {
464
+ value -= 1;
465
+ out = String.fromCharCode(65 + (value % 26)) + out;
466
+ value = Math.floor(value / 26);
467
+ }
468
+ return out;
469
+ }
470
+
471
+ function replaceCell(rowXml, cellRef, value, styleHint = '') {
472
+ const cellRe = /<c\b[^>]*\/>|<c\b[^>]*>[\s\S]*?<\/c>/g;
473
+ const cells = [...rowXml.matchAll(cellRe)].map((match) => match[0]);
474
+ const wanted = columnIndex(cellRef);
475
+ const existing = cells.find((cell) => {
476
+ const ref = /\br="([A-Z]+\d+)"/i.exec(cell)?.[1] || '';
477
+ return ref.toUpperCase() === cellRef.toUpperCase();
478
+ });
479
+ const style = existing ? /\bs="(\d+)"/.exec(existing)?.[1] : styleHint;
480
+ const nextCell = `<c r="${cellRef}"${style ? ` s="${style}"` : ''} t="inlineStr"><is><t xml:space="preserve">${xmlEscape(value)}</t></is></c>`;
481
+ const without = cells.filter((cell) => cell !== existing);
482
+ without.push(nextCell);
483
+ without.sort((left, right) => {
484
+ const leftRef = /\br="([A-Z]+\d+)"/i.exec(left)?.[1] || 'A1';
485
+ const rightRef = /\br="([A-Z]+\d+)"/i.exec(right)?.[1] || 'A1';
486
+ return columnIndex(leftRef) - columnIndex(rightRef);
487
+ });
488
+ const outer = rowXml.replace(cellRe, '').replace(/<\/row>$/i, '');
489
+ return `${outer}${without.join('')}</row>`;
490
+ }
491
+
492
+ async function patchXlsx(abs, parsed, rowIndex, updates) {
493
+ const { default: JSZip } = await import('jszip');
494
+ const zip = await JSZip.loadAsync(fs.readFileSync(abs));
495
+ const workbook = await zip.file('xl/workbook.xml')?.async('string');
496
+ const rels = await zip.file('xl/_rels/workbook.xml.rels')?.async('string');
497
+ if (!workbook || !rels) throw new Error('Excel 工作簿结构不完整');
498
+ const safeName = parsed.sheetName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
499
+ const sheetTag = new RegExp(`<sheet\\b[^>]*name="${safeName}"[^>]*>`, 'i').exec(workbook)?.[0];
500
+ const relationId = sheetTag ? /\br:id="([^"]+)"/i.exec(sheetTag)?.[1] : '';
501
+ const relationTag = relationId
502
+ ? new RegExp(`<Relationship\\b[^>]*Id="${relationId}"[^>]*>`, 'i').exec(rels)?.[0]
503
+ : '';
504
+ const target = relationTag ? /\bTarget="([^"]+)"/i.exec(relationTag)?.[1] || '' : '';
505
+ if (!target) throw new Error(`找不到工作表 ${parsed.sheetName}`);
506
+ const sheetPath = target.startsWith('/')
507
+ ? target.slice(1)
508
+ : path.posix.normalize(`xl/${target.replace(/^\.\//, '')}`);
509
+ const file = zip.file(sheetPath);
510
+ if (!file) throw new Error('找不到工作表 XML');
511
+ let xml = await file.async('string');
512
+ const physicalRow = parsed.rows[rowIndex]?.physicalRow;
513
+ if (!Number.isInteger(physicalRow) || physicalRow < 1) {
514
+ throw new Error('找不到要写回的 Excel 用例行');
515
+ }
516
+ const rowRe = new RegExp(`<row\\b[^>]*\\br="${physicalRow}"[^>]*>[\\s\\S]*?<\\/row>`, 'i');
517
+ let rowXml = rowRe.exec(xml)?.[0] || '';
518
+ if (!rowXml) throw new Error(`找不到第 ${physicalRow} 行`);
519
+ for (const update of updates) {
520
+ const rawHeaders = parsed.rawHeaders || parsed.headers;
521
+ const column = rawHeaders.indexOf(update.header) + 1;
522
+ if (column <= 0) continue;
523
+ rowXml = replaceCell(rowXml, `${columnName(column)}${physicalRow}`, update.value);
524
+ }
525
+ xml = xml.replace(rowRe, rowXml);
526
+ zip.file(sheetPath, xml);
527
+ const output = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
528
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
529
+ fs.writeFileSync(temp, output);
530
+ fs.renameSync(temp, abs);
531
+ }
532
+
533
+ function markdownCell(value) {
534
+ return String(value ?? '')
535
+ .replace(/\|/g, '\\|')
536
+ .replace(/\n/g, '<br>');
537
+ }
538
+
539
+ function csvCell(value) {
540
+ const raw = String(value ?? '');
541
+ return /[",\n\r]/.test(raw) ? `"${raw.replace(/"/g, '""')}"` : raw;
542
+ }
543
+
544
+ function writeTextAtomic(abs, value) {
545
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
546
+ fs.writeFileSync(temp, value, 'utf8');
547
+ fs.renameSync(temp, abs);
548
+ }
549
+
550
+ function patchText(abs, ext, parsed, rowIndex, updates) {
551
+ const raw = fs.readFileSync(abs, 'utf8');
552
+ if (ext === '.csv') {
553
+ const records = parseCsvRecords(raw);
554
+ const header = records[0] || [];
555
+ const row = records[rowIndex + 1] || [];
556
+ for (const update of updates) {
557
+ const column = header.indexOf(update.header);
558
+ if (column < 0) continue;
559
+ while (row.length <= column) row.push('');
560
+ row[column] = update.value;
561
+ }
562
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
563
+ const body = records.map((cells) => cells.map(csvCell).join(',')).join(eol);
564
+ writeTextAtomic(abs, `${raw.startsWith('\uFEFF') ? '\uFEFF' : ''}${body}${eol}`);
565
+ return;
566
+ }
567
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
568
+ const target = parsed.rows[rowIndex]?.lineIndex;
569
+ if (!Number.isInteger(target) || target < 0 || target >= lines.length) {
570
+ throw new Error('找不到要写回的 Markdown 用例行');
571
+ }
572
+ const cells = splitMarkdownRow(lines[target]);
573
+ for (const update of updates) {
574
+ const column = parsed.headers.indexOf(update.header);
575
+ if (column < 0) continue;
576
+ while (cells.length <= column) cells.push('');
577
+ cells[column] = update.value;
578
+ }
579
+ lines[target] = `| ${cells.map(markdownCell).join(' | ')} |`;
580
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
581
+ writeTextAtomic(abs, lines.join(eol));
582
+ }
583
+
584
+ async function appendXlsxHeader(abs, parsed, header) {
585
+ const { default: JSZip } = await import('jszip');
586
+ const zip = await JSZip.loadAsync(fs.readFileSync(abs));
587
+ const workbook = await zip.file('xl/workbook.xml')?.async('string');
588
+ const rels = await zip.file('xl/_rels/workbook.xml.rels')?.async('string');
589
+ if (!workbook || !rels) throw new Error('Excel 工作簿结构不完整');
590
+ const safeName = parsed.sheetName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
591
+ const sheetTag = new RegExp(`<sheet\\b[^>]*name="${safeName}"[^>]*>`, 'i').exec(workbook)?.[0];
592
+ const relationId = sheetTag ? /\br:id="([^"]+)"/i.exec(sheetTag)?.[1] : '';
593
+ const relationTag = relationId
594
+ ? new RegExp(`<Relationship\\b[^>]*Id="${relationId}"[^>]*>`, 'i').exec(rels)?.[0]
595
+ : '';
596
+ const target = relationTag ? /\bTarget="([^"]+)"/i.exec(relationTag)?.[1] || '' : '';
597
+ if (!target) throw new Error(`找不到工作表 ${parsed.sheetName}`);
598
+ const sheetPath = target.startsWith('/')
599
+ ? target.slice(1)
600
+ : path.posix.normalize(`xl/${target.replace(/^\.\//, '')}`);
601
+ const file = zip.file(sheetPath);
602
+ if (!file) throw new Error('找不到工作表 XML');
603
+ let xml = await file.async('string');
604
+ const physicalRow = parsed.headerRowNumber;
605
+ const rowRe = new RegExp(`<row\\b[^>]*\\br="${physicalRow}"[^>]*>[\\s\\S]*?<\\/row>`, 'i');
606
+ let rowXml = rowRe.exec(xml)?.[0] || '';
607
+ if (!rowXml) throw new Error(`找不到第 ${physicalRow} 行表头`);
608
+ const cells = [...rowXml.matchAll(/<c\b[^>]*\/>|<c\b[^>]*>[\s\S]*?<\/c>/g)].map(
609
+ (match) => match[0],
610
+ );
611
+ const styleHint = cells
612
+ .map((cell) => /\bs="(\d+)"/.exec(cell)?.[1] || '')
613
+ .filter(Boolean)
614
+ .at(-1);
615
+ const column = parsed.rawHeaders.length + 1;
616
+ rowXml = replaceCell(rowXml, `${columnName(column)}${physicalRow}`, header, styleHint || '');
617
+ xml = xml.replace(rowRe, rowXml);
618
+ xml = xml.replace(/<dimension\b[^>]*\bref="([^"]+)"[^>]*\/>/i, (tag, ref) => {
619
+ const start = ref.split(':')[0] || 'A1';
620
+ const endRow = /(\d+)$/.exec(ref)?.[1] || String(physicalRow);
621
+ return tag.replace(ref, `${start}:${columnName(column)}${endRow}`);
622
+ });
623
+ zip.file(sheetPath, xml);
624
+ const output = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
625
+ const temp = `${abs}.${process.pid}.${Date.now()}.tmp`;
626
+ fs.writeFileSync(temp, output);
627
+ fs.renameSync(temp, abs);
628
+ parsed.headers.push(header);
629
+ parsed.rawHeaders.push(header);
630
+ }
631
+
632
+ function appendTextHeader(abs, ext, parsed, header) {
633
+ const raw = fs.readFileSync(abs, 'utf8');
634
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
635
+ if (ext === '.csv') {
636
+ const records = parseCsvRecords(raw);
637
+ if (!records.length) throw new Error('CSV 没有表头');
638
+ records[0].push(header);
639
+ for (const row of records.slice(1)) row.push('');
640
+ const body = records.map((cells) => cells.map(csvCell).join(',')).join(eol);
641
+ writeTextAtomic(abs, `${raw.startsWith('\uFEFF') ? '\uFEFF' : ''}${body}${eol}`);
642
+ } else {
643
+ const lines = raw.replace(/\r\n/g, '\n').split('\n');
644
+ const headerIndex = parsed.headerIndex;
645
+ if (!Number.isInteger(headerIndex) || headerIndex < 0) throw new Error('找不到 Markdown 表头');
646
+ const appendToMarkdownLine = (lineIndex, value) => {
647
+ const cells = splitMarkdownRow(lines[lineIndex]);
648
+ cells.push(value);
649
+ lines[lineIndex] = `| ${cells.map(markdownCell).join(' | ')} |`;
650
+ };
651
+ appendToMarkdownLine(headerIndex, header);
652
+ if (isMarkdownSeparator(lines[headerIndex + 1] || '')) {
653
+ appendToMarkdownLine(headerIndex + 1, '---');
654
+ }
655
+ for (const row of parsed.rows) appendToMarkdownLine(row.lineIndex, '');
656
+ writeTextAtomic(abs, lines.join(eol));
657
+ }
658
+ parsed.headers.push(header);
659
+ }
660
+
661
+ async function appendCaseHeader(document, header) {
662
+ if (document.ext === '.xlsx') {
663
+ await appendXlsxHeader(document.abs, document._parsed, header);
664
+ } else if (document.ext === '.csv' || document.ext === '.md') {
665
+ appendTextHeader(document.abs, document.ext, document._parsed, header);
666
+ } else {
667
+ throw Object.assign(new Error('当前文件格式无法新增字段'), { statusCode: 415 });
668
+ }
669
+ }
670
+
671
+ export async function applyCaseExecutionResult(
672
+ root,
673
+ {
674
+ path: relativePath,
675
+ expectedFileHash,
676
+ rowIndex,
677
+ status,
678
+ actualResult,
679
+ executor = '',
680
+ executedAt = '',
681
+ evidence = '',
682
+ defectNo = '',
683
+ },
684
+ ) {
685
+ let document = await loadCaseDocument(root, relativePath);
686
+ if (document.ext === '.xls') {
687
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 415 });
688
+ }
689
+ if (!document.executable) {
690
+ throw Object.assign(new Error(document.executionIssue), {
691
+ statusCode: 422,
692
+ });
693
+ }
694
+ if (expectedFileHash !== document.fileHash) {
695
+ throw Object.assign(new Error('用例文件已被外部修改,请重新执行后再写回'), {
696
+ statusCode: 409,
697
+ currentHash: document.fileHash,
698
+ });
699
+ }
700
+ const selectedStatus = text(status, 20);
701
+ if (!EXECUTION_STATUSES.includes(selectedStatus)) {
702
+ throw Object.assign(new Error('用例状态无效'), { statusCode: 400 });
703
+ }
704
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= document.cases.length) {
705
+ throw Object.assign(new Error('用例行不存在'), { statusCode: 404 });
706
+ }
707
+ const map = document._map;
708
+ const updates = [
709
+ { header: map.status, value: selectedStatus },
710
+ { header: map.actual, value: text(actualResult, 30000) },
711
+ ...(map.executor ? [{ header: map.executor, value: text(executor, 200) }] : []),
712
+ ...(map.executedAt ? [{ header: map.executedAt, value: text(executedAt, 80) }] : []),
713
+ ...(map.evidence ? [{ header: map.evidence, value: text(evidence, 4000) }] : []),
714
+ ...(map.defectNo ? [{ header: map.defectNo, value: text(defectNo, 200) }] : []),
715
+ ].filter((item) => item.header);
716
+ const backup = backupCaseDocument(root, relativePath);
717
+ if (document.ext === '.xlsx') {
718
+ await patchXlsx(document.abs, document._parsed, rowIndex, updates);
719
+ } else if (document.ext === '.csv' || document.ext === '.md') {
720
+ patchText(document.abs, document.ext, document._parsed, rowIndex, updates);
721
+ } else {
722
+ throw Object.assign(new Error('旧版 .xls 暂不支持写回,请先另存为 .xlsx'), {
723
+ statusCode: 415,
724
+ });
725
+ }
726
+ return {
727
+ ok: true,
728
+ path: relativePath,
729
+ rowIndex,
730
+ status: selectedStatus,
731
+ backup,
732
+ fileHash: hashBuffer(fs.readFileSync(document.abs)),
733
+ };
734
+ }
735
+
736
+ export async function applyCaseFieldUpdates(
737
+ root,
738
+ { path: relativePath, expectedFileHash, rowIndex, updates },
739
+ ) {
740
+ let document = await loadCaseDocument(root, relativePath);
741
+ if (document.ext === '.xls') {
742
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 415 });
743
+ }
744
+ if (expectedFileHash !== document.fileHash) {
745
+ throw Object.assign(new Error('用例文件已被外部修改,请重新读取后再保存'), {
746
+ statusCode: 409,
747
+ currentHash: document.fileHash,
748
+ });
749
+ }
750
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= document.cases.length) {
751
+ throw Object.assign(new Error('用例行不存在'), { statusCode: 404 });
752
+ }
753
+ const normalized = (Array.isArray(updates) ? updates : [])
754
+ .slice(0, 100)
755
+ .map((update) => ({
756
+ header: text(update?.header, 500),
757
+ value: String(update?.value ?? '').slice(0, 30000),
758
+ }))
759
+ .filter((update) => update.header);
760
+ if (!normalized.length) {
761
+ throw Object.assign(new Error('没有需要保存的字段'), { statusCode: 400 });
762
+ }
763
+ for (const update of normalized) {
764
+ if (update.header === (document.columns.defectUrl || DEFECT_URL_HEADER))
765
+ update.value = validateDefectLinks(update.value);
766
+ }
767
+ let allowed = new Set(document.headers.map((header) => String(header)));
768
+ const unknown = normalized.filter((update) => !allowed.has(update.header));
769
+ if (unknown.some((update) => update.header !== DEFECT_URL_HEADER)) {
770
+ const first = unknown.find((update) => update.header !== DEFECT_URL_HEADER);
771
+ throw Object.assign(new Error(`用例文件不存在字段:${first?.header || ''}`), {
772
+ statusCode: 400,
773
+ });
774
+ }
775
+ const backup = backupCaseDocument(root, relativePath);
776
+ if (unknown.length) {
777
+ await appendCaseHeader(document, DEFECT_URL_HEADER);
778
+ document = await loadCaseDocument(root, relativePath);
779
+ allowed = new Set(document.headers.map((header) => String(header)));
780
+ if (!allowed.has(DEFECT_URL_HEADER)) {
781
+ throw new Error('缺陷地址字段追加失败');
782
+ }
783
+ }
784
+ if (document.ext === '.xlsx') {
785
+ await patchXlsx(document.abs, document._parsed, rowIndex, normalized);
786
+ } else {
787
+ patchText(document.abs, document.ext, document._parsed, rowIndex, normalized);
788
+ }
789
+ if (normalized.some((update) => update.header === document.columns.status)) {
790
+ const refreshed = await loadCaseDocument(root, relativePath);
791
+ recordManualVerification(root, refreshed, rowIndex);
792
+ }
793
+ return {
794
+ ok: true,
795
+ path: relativePath,
796
+ rowIndex,
797
+ backup,
798
+ fileHash: hashBuffer(fs.readFileSync(document.abs)),
799
+ };
800
+ }
801
+
802
+ export { EXECUTION_STATUSES, fieldMap as caseExecutionFieldMap };
803
+
804
+ export async function prepareExecutionColumns(root, raw) {
805
+ let document = await loadCaseDocument(root, raw.casePath);
806
+ const preview = {
807
+ path: document.path,
808
+ fileHash: document.fileHash,
809
+ missingColumns: document.missingColumns,
810
+ executable: document.executable,
811
+ };
812
+ if (raw.mode !== 'apply') return { ok: true, preview };
813
+ if (document.ext === '.xls')
814
+ throw Object.assign(new Error(document.executionIssue), { statusCode: 422 });
815
+ if (raw.expectedFileHash !== document.fileHash)
816
+ throw Object.assign(new Error('文件已变化,请重新预览'), { statusCode: 409 });
817
+ const backup = document.missingColumns.length ? backupCaseDocument(root, raw.casePath) : '';
818
+ for (const header of document.missingColumns) {
819
+ await appendCaseHeader(document, header);
820
+ document = await loadCaseDocument(root, raw.casePath);
821
+ }
822
+ return {
823
+ ok: true,
824
+ preview,
825
+ backup,
826
+ fileHash: document.fileHash,
827
+ executable: document.executable,
828
+ };
829
+ }