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,989 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ import { callMcpTool, mcpToolName } from '../builtin/session/mcp-client.mjs';
6
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
7
+ import { spaceLocalFile } from '../builtin/session/space-layout.mjs';
8
+ import { isPluginOnInSpace } from './plugin-prompts.mjs';
9
+
10
+ export const DEFECT_API = '/__tb_defect_submit';
11
+ const SERVER = 'tencent-docs';
12
+ const DEFAULT_TEMPLATE =
13
+ '用可定位的功能和实际现象写标题。按材料整理环境、重现步骤、预期结果和实际结果。\n仅填写有依据的内容。缺少信息时留空,不能猜测负责人、迭代、定级或需求编号。';
14
+ const FALLBACK_FIELDS = ['缺陷标题', '测试环境', '重现步骤', '预期结果', '实际结果', '备注'];
15
+ const FIELD_TYPES = {
16
+ text: 'text',
17
+ singleSelect: 'option',
18
+ select: 'option',
19
+ reference: 'reference',
20
+ twoWayLinkRecords: 'reference',
21
+ image: 'image',
22
+ attachment: 'attachment',
23
+ number: 'number',
24
+ checkbox: 'bool',
25
+ };
26
+ const ID = /^[a-zA-Z0-9_-]{1,100}$/;
27
+ const DRAFT_ID = /^[a-f0-9-]{36}$/;
28
+ const string = (value) => (typeof value === 'string' ? value.trim() : '');
29
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
30
+ const defectPath = (root, file) => spaceLocalFile(root, 'defect-submit', file);
31
+
32
+ function fail(message, statusCode = 400) {
33
+ throw Object.assign(new Error(message), { statusCode });
34
+ }
35
+
36
+ function read(file, fallback) {
37
+ try {
38
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
39
+ } catch (error) {
40
+ if (error.code === 'ENOENT') return fallback;
41
+ throw error;
42
+ }
43
+ }
44
+
45
+ function save(file, value) {
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const temporary = file + '.' + randomUUID() + '.tmp';
48
+ fs.writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 });
49
+ try {
50
+ fs.renameSync(temporary, file);
51
+ } finally {
52
+ fs.rmSync(temporary, { force: true });
53
+ }
54
+ }
55
+
56
+ export function parseDefectUrl(raw) {
57
+ let url;
58
+ try {
59
+ url = new URL(string(raw));
60
+ } catch {
61
+ fail('请输入完整的 HTTPS 缺陷入口地址');
62
+ }
63
+ if (url.protocol !== 'https:' || url.username || url.password) {
64
+ fail('请输入不含登录凭据的 HTTPS 缺陷入口地址');
65
+ }
66
+ const match = /^\/(?:smartsheet|sheet)\/([a-zA-Z0-9_-]{1,100})\/?$/.exec(url.pathname);
67
+ const fileId = url.origin === 'https://docs.qq.com' && match ? match[1] : '';
68
+ const tab = url.searchParams.get('tab') || '';
69
+ return {
70
+ url: fileId
71
+ ? 'https://docs.qq.com/smartsheet/' + fileId + (ID.test(tab) ? '?tab=' + tab : '')
72
+ : url.href,
73
+ platform: fileId ? 'tencent' : 'manual',
74
+ fileId,
75
+ suggestedSheetId: ID.test(tab) ? tab : '',
76
+ };
77
+ }
78
+
79
+ function tencentField(field) {
80
+ const kind = Object.hasOwn(FIELD_TYPES, field.field_type) ? FIELD_TYPES[field.field_type] : '';
81
+ const property =
82
+ field.property_single_select ||
83
+ field.property_select ||
84
+ field.property_reference ||
85
+ field.property_two_way_link_records ||
86
+ {};
87
+ return {
88
+ id: field.field_id,
89
+ title: field.field_title,
90
+ kind,
91
+ autoNumber: field.field_type === 'autoNumber',
92
+ multiple: property.is_multiple === true || field.field_type === 'select',
93
+ refSheetId: string(property.sub_id),
94
+ refFieldId: string(property.field_id),
95
+ options: (property.options || []).map(({ id, text }) => ({ id, label: text })),
96
+ };
97
+ }
98
+
99
+ function recordText(field) {
100
+ return field?.text_value?.items?.map((item) => item.text).join('') || '';
101
+ }
102
+
103
+ function canonicalValue(field) {
104
+ for (const key of [
105
+ 'text_value',
106
+ 'option_value',
107
+ 'reference_value',
108
+ 'image_value',
109
+ 'number_value',
110
+ 'bool_value',
111
+ ]) {
112
+ if (!(key in field)) continue;
113
+ const value = field[key];
114
+ if (key === 'text_value') return recordText(field);
115
+ if (key === 'option_value') return value.items.map((item) => item.id).sort();
116
+ if (key === 'reference_value') return [...value.items].sort();
117
+ if (key === 'image_value')
118
+ return value.items
119
+ .map((item) => item.image_id || item.image_url || '')
120
+ .filter(Boolean)
121
+ .sort();
122
+ return value;
123
+ }
124
+ }
125
+
126
+ function payload(field, value) {
127
+ const target = { field: field.title };
128
+ if (field.kind === 'text' && typeof value === 'string' && value.length <= 30000)
129
+ return { ...target, text_value: { items: [{ type: 'text', text: value.trim() }] } };
130
+ if (field.kind === 'number' && typeof value === 'number' && Number.isFinite(value))
131
+ return { ...target, number_value: value };
132
+ if (field.kind === 'bool' && typeof value === 'boolean') return { ...target, bool_value: value };
133
+ if (field.kind === 'option' || field.kind === 'reference') {
134
+ const ids = Array.isArray(value) ? [...new Set(value)] : [value];
135
+ const options = new Set(field.options.map(({ id }) => id));
136
+ if ((field.multiple || ids.length === 1) && ids.every((id) => options.has(id))) {
137
+ return field.kind === 'option'
138
+ ? { ...target, option_value: { items: ids.map((id) => ({ id })) } }
139
+ : { ...target, reference_value: { items: ids } };
140
+ }
141
+ }
142
+ if (field.kind === 'image') {
143
+ const ids = [...new Set((Array.isArray(value) ? value : [value]).map(string).filter(Boolean))];
144
+ if (ids.length && ids.every((id) => ID.test(id)))
145
+ return { ...target, image_value: { items: ids.map((image_id) => ({ image_id })) } };
146
+ }
147
+ if (field.kind === 'attachment')
148
+ fail('附件字段需先上传到目标平台并取得记录链接;当前规则不应把附件写成普通文本');
149
+ fail('字段「' + field.label + '」的值无效,请选用当前表的可用值');
150
+ }
151
+
152
+ const empty = (value) =>
153
+ value == null ||
154
+ value === '' ||
155
+ (typeof value === 'string' && !value.trim()) ||
156
+ (Array.isArray(value) && value.length === 0);
157
+
158
+ function iterationField(fields) {
159
+ return fields.find(
160
+ (field) =>
161
+ (field.label === '迭代版本' || field.title === '迭代版本') && field.kind === 'option',
162
+ );
163
+ }
164
+
165
+ function normalizeIterations(raw, selected) {
166
+ const iterations = [];
167
+ const add = (value) => {
168
+ const label = string(value).slice(0, 100);
169
+ if (label && label !== '无' && !iterations.includes(label)) iterations.push(label);
170
+ };
171
+ for (const value of Array.isArray(raw) ? raw : []) add(value);
172
+ const iteration = string(selected).slice(0, 100);
173
+ if (iteration && !iterations.includes(iteration)) iterations.unshift(iteration);
174
+ return {
175
+ iterations,
176
+ ...(iteration ? { iteration } : {}),
177
+ };
178
+ }
179
+
180
+ function applyRuleIteration(fields, iteration) {
181
+ const selected = string(iteration).slice(0, 100);
182
+ if (!selected) return fields;
183
+ return fields.map((field) => {
184
+ if (!iterationField([field])) return field;
185
+ const option = field.options.find((item) => item.label === selected);
186
+ return {
187
+ ...field,
188
+ defaultValue: option?.id,
189
+ rule: '使用当前规则当前迭代:' + selected + ',不要再次询问。',
190
+ ...(option ? {} : { iterationOptionMissing: true }),
191
+ };
192
+ });
193
+ }
194
+
195
+ function normalizeDefaultValue(field, value, statusCode = 400) {
196
+ if (empty(value)) return undefined;
197
+ const label = field.label || field.title || '字段';
198
+ if (field.kind === 'text') {
199
+ if (typeof value === 'object') fail('字段「' + label + '」的默认值必须是文本', statusCode);
200
+ return String(value).slice(0, 30000);
201
+ }
202
+ if (field.kind === 'number') {
203
+ const number = typeof value === 'number' ? value : Number(String(value).trim());
204
+ if (!Number.isFinite(number)) fail('字段「' + label + '」的默认值必须是有效数字', statusCode);
205
+ return number;
206
+ }
207
+ if (field.kind === 'bool') {
208
+ if (typeof value === 'boolean') return value;
209
+ if (value === 'true' || value === 'false') return value === 'true';
210
+ fail('字段「' + label + '」的默认值必须是布尔值', statusCode);
211
+ }
212
+ if (field.kind === 'option' || field.kind === 'reference') {
213
+ const ids = [...new Set((Array.isArray(value) ? value : [value]).map(string).filter(Boolean))];
214
+ if (!ids.length) return undefined;
215
+ if (!field.multiple && ids.length !== 1)
216
+ fail('字段「' + label + '」只能设置一个默认值', statusCode);
217
+ const options = field.options || [];
218
+ if (options.length) {
219
+ const available = new Set(options.map(({ id }) => id));
220
+ const invalid = ids.find((id) => !available.has(id));
221
+ if (invalid) fail('字段「' + label + '」的默认值不在当前可用选项中', statusCode);
222
+ }
223
+ return field.multiple ? ids : ids[0];
224
+ }
225
+ fail('字段「' + label + '」不支持默认值', statusCode);
226
+ }
227
+
228
+ /**
229
+ * 选项改名 / 隐藏只属于当前缺陷规则,不回写腾讯文档。
230
+ * 保存时仍以远端字段的 option ID 为边界,避免规则里混入伪造或已删除的选项。
231
+ */
232
+ function resolveOptionOverrides(field, entry = {}) {
233
+ const allOptions = Array.isArray(field.options) ? field.options : [];
234
+ const available = new Set(allOptions.map(({ id }) => id));
235
+ const hiddenOptions = [
236
+ ...new Set(
237
+ (Array.isArray(entry.hiddenOptions) ? entry.hiddenOptions : [])
238
+ .map(string)
239
+ .filter((id) => available.has(id)),
240
+ ),
241
+ ];
242
+ const hidden = new Set(hiddenOptions);
243
+ const optionLabels = {};
244
+ if (
245
+ entry.optionLabels &&
246
+ typeof entry.optionLabels === 'object' &&
247
+ !Array.isArray(entry.optionLabels)
248
+ ) {
249
+ for (const [id, value] of Object.entries(entry.optionLabels)) {
250
+ const label = string(value).slice(0, 100);
251
+ if (available.has(id) && label) optionLabels[id] = label;
252
+ }
253
+ }
254
+ const options = allOptions
255
+ .filter(({ id }) => !hidden.has(id))
256
+ .map((option) => ({ ...option, label: optionLabels[option.id] || option.label }));
257
+ return { allOptions, options, optionLabels, hiddenOptions };
258
+ }
259
+
260
+ function manualOptions(raw) {
261
+ const seen = new Set();
262
+ const labels = new Set();
263
+ const options = [];
264
+ for (const item of Array.isArray(raw) ? raw : []) {
265
+ const id = string(item?.id);
266
+ const label = string(item?.label).slice(0, 100);
267
+ if (!ID.test(id) || !label || seen.has(id) || labels.has(label)) continue;
268
+ seen.add(id);
269
+ labels.add(label);
270
+ options.push({ id, label });
271
+ }
272
+ return options;
273
+ }
274
+
275
+ function valuesWithDefaults(ctx, values) {
276
+ const next = { ...values };
277
+ for (const field of ctx.fields) {
278
+ if (field.id in next || field.defaultValue === undefined) continue;
279
+ next[field.id] = Array.isArray(field.defaultValue)
280
+ ? [...field.defaultValue]
281
+ : field.defaultValue;
282
+ }
283
+ return next;
284
+ }
285
+
286
+ function remoteFieldForEntry(schema, entry) {
287
+ const byId = schema.find(({ id }) => id === entry.id);
288
+ if (byId || entry.source !== 'manual') return byId;
289
+ const byLabel = schema.filter(({ title, kind }) => kind && title === entry.label);
290
+ return byLabel.length === 1 ? byLabel[0] : undefined;
291
+ }
292
+
293
+ export function createDefectService(root, call = callMcpTool) {
294
+ const configFile = defectPath(root, 'target.json');
295
+
296
+ async function remote(method, args) {
297
+ const result = await call(mcpToolName(SERVER, 'smartsheet.' + method), args, root);
298
+ if (!result.ok) fail('腾讯文档调用失败:' + (result.error || method), 502);
299
+ let data;
300
+ try {
301
+ const parsed = JSON.parse(result.text);
302
+ data = parsed.data ?? parsed;
303
+ } catch {
304
+ fail('腾讯文档返回了无法解析的结果', 502);
305
+ }
306
+ if (!data || data.error || (data.code && data.code !== 200))
307
+ fail('腾讯文档未完成操作:' + (data?.error || method), 502);
308
+ return data;
309
+ }
310
+
311
+ async function pages(method, args, key, limit = 50, max = 2000) {
312
+ const items = [];
313
+ let offset = 0;
314
+ for (;;) {
315
+ const result = await remote(method, { ...args, limit, offset });
316
+ if (!Array.isArray(result[key])) fail('腾讯文档返回的数据缺少 ' + key, 502);
317
+ items.push(...result[key]);
318
+ if (!result.has_more || items.length >= max) return items;
319
+ if (!Number.isInteger(result.next) || result.next <= offset)
320
+ fail('腾讯文档分页位置无效', 502);
321
+ offset = result.next;
322
+ }
323
+ }
324
+
325
+ async function fields(fileId, sheetId) {
326
+ const rows = await pages('list_fields', { file_id: fileId, sheet_id: sheetId }, 'fields');
327
+ return rows.map(tencentField);
328
+ }
329
+
330
+ async function inspect({ url, sheetId }) {
331
+ const target = parseDefectUrl(url);
332
+ if (target.platform === 'manual') return { target, sheets: [], fields: [] };
333
+ const data = await remote('list_tables', { file_id: target.fileId });
334
+ if (!Array.isArray(data.sheets)) fail('腾讯文档未返回子表列表', 502);
335
+ const sheets = data.sheets
336
+ .filter((sheet) => ID.test(sheet.sheet_id))
337
+ .map((sheet) => ({ id: sheet.sheet_id, title: sheet.title }));
338
+ const preferred = sheetId || target.suggestedSheetId;
339
+ const selected = preferred
340
+ ? sheets.find(({ id }) => id === preferred)
341
+ : sheets.find(
342
+ ({ id }) => data.sheets.find((sheet) => sheet.sheet_id === id)?.is_visible !== false,
343
+ );
344
+
345
+ if (sheetId && !selected) fail('所选子表不在这个腾讯文档里');
346
+ return {
347
+ target,
348
+ sheets,
349
+ sheetId: selected?.id || '',
350
+ fields: selected ? await fields(target.fileId, selected.id) : [],
351
+ };
352
+ }
353
+
354
+ function selectedConfig() {
355
+ const store = read(defectPath(root, 'templates.json'), null);
356
+ return store
357
+ ? store.templates.find((entry) => entry.id === store.selectedId)?.config || null
358
+ : read(configFile, null);
359
+ }
360
+
361
+ async function context(config = selectedConfig()) {
362
+ if (!config) return { configured: false };
363
+ const { target, template, mapping } = config;
364
+ if (target.platform === 'manual') {
365
+ const fields = applyRuleIteration(
366
+ mapping.map((field) => {
367
+ const fieldType = {
368
+ ...field,
369
+ title: field.label,
370
+ kind: field.kind === 'option' ? 'option' : 'text',
371
+ multiple: field.multiple === true,
372
+ options: field.kind === 'option' ? manualOptions(field.options) : [],
373
+ };
374
+ const optionState = resolveOptionOverrides(fieldType, field);
375
+ const defaultValue = normalizeDefaultValue(
376
+ { ...fieldType, options: optionState.options },
377
+ field.defaultValue,
378
+ 409,
379
+ );
380
+ return {
381
+ ...field,
382
+ title: field.label,
383
+ kind: fieldType.kind,
384
+ multiple: fieldType.multiple,
385
+ options: optionState.options,
386
+ ...(Object.keys(optionState.optionLabels).length
387
+ ? { optionLabels: optionState.optionLabels }
388
+ : {}),
389
+ ...(defaultValue === undefined ? {} : { defaultValue }),
390
+ };
391
+ }),
392
+ config.iteration,
393
+ );
394
+ return {
395
+ configured: true,
396
+ target,
397
+ template,
398
+ fields,
399
+ ...normalizeIterations(config.iterations, config.iteration),
400
+ revision: hash([root, config]),
401
+ };
402
+ }
403
+ const schema = await fields(target.fileId, target.sheetId);
404
+ const resolved = mapping.map((entry) => {
405
+ const remote = remoteFieldForEntry(schema, entry);
406
+ const field =
407
+ remote ||
408
+ (entry.source === 'manual'
409
+ ? { id: entry.id, title: entry.label, kind: 'text', options: [] }
410
+ : undefined);
411
+ if (
412
+ !field?.kind ||
413
+ (entry.source !== 'manual' &&
414
+ schema.filter(({ title }) => title === field.title).length !== 1)
415
+ )
416
+ fail('映射字段「' + entry.label + '」已变更,请重新配置缺陷入口', 409);
417
+ const optionState = resolveOptionOverrides(field, entry);
418
+ const defaultValue = normalizeDefaultValue(
419
+ { ...field, label: entry.label, options: optionState.options },
420
+ entry.defaultValue,
421
+ 409,
422
+ );
423
+ return {
424
+ ...field,
425
+ ...entry,
426
+ id: field.id,
427
+ title: field.title,
428
+ label: entry.label || field.title,
429
+ source: remote ? 'remote' : entry.source,
430
+ kind: field.kind,
431
+ multiple: field.multiple,
432
+ options: optionState.options,
433
+ ...(Object.keys(optionState.optionLabels).length
434
+ ? { optionLabels: optionState.optionLabels }
435
+ : {}),
436
+ ...(optionState.hiddenOptions.length ? { hiddenOptions: optionState.hiddenOptions } : {}),
437
+ ...(defaultValue === undefined ? {} : { defaultValue }),
438
+ };
439
+ });
440
+ const revision = hash([root, config, resolved]);
441
+ await Promise.all(
442
+ resolved
443
+ .filter(({ kind }) => kind === 'reference')
444
+ .map(async (field) => {
445
+ if (!ID.test(field.refSheetId)) fail('关联字段「' + field.label + '」缺少目标子表', 409);
446
+ const refFields = await fields(target.fileId, field.refSheetId);
447
+ const primary = refFields.find(({ id }) => id === 'fumV40');
448
+ const display = [
449
+ ...new Set(
450
+ [
451
+ refFields.find(({ id }) => id === field.refFieldId),
452
+ primary,
453
+ ...refFields.filter(({ kind }) => kind === 'text').slice(0, 2),
454
+ ]
455
+ .filter(Boolean)
456
+ .map(({ title }) => title),
457
+ ),
458
+ ];
459
+ const options = await pages(
460
+ 'list_records',
461
+ {
462
+ file_id: target.fileId,
463
+ sheet_id: field.refSheetId,
464
+ ...(display.length ? { field_titles: display } : {}),
465
+ },
466
+ 'records',
467
+ 30,
468
+ );
469
+ field.options = options
470
+ .filter((row) => ID.test(row.record_id))
471
+ .map((row) => ({
472
+ id: row.record_id,
473
+ label:
474
+ display
475
+ .map((title) =>
476
+ recordText(row.field_values?.find((cell) => cell.field === title)),
477
+ )
478
+ .filter(Boolean)
479
+ .join(' / ') || row.record_id,
480
+ }));
481
+ }),
482
+ );
483
+ const fieldsWithIteration = applyRuleIteration(resolved, config.iteration);
484
+ return {
485
+ configured: true,
486
+ target,
487
+ template,
488
+ fields: fieldsWithIteration,
489
+ ...normalizeIterations(config.iterations, config.iteration),
490
+ revision,
491
+ numberField: schema.find(({ autoNumber }) => autoNumber)?.title,
492
+ };
493
+ }
494
+
495
+ const templatesFile = defectPath(root, 'templates.json');
496
+
497
+ function templates() {
498
+ const stored = read(templatesFile, null);
499
+ if (stored) return stored;
500
+ const legacy = read(configFile, null);
501
+ return legacy
502
+ ? {
503
+ selectedId: 'legacy',
504
+ templates: [{ id: 'legacy', name: '默认缺陷规则', config: legacy }],
505
+ }
506
+ : { selectedId: '', templates: [] };
507
+ }
508
+
509
+ function deleteRule({ id }) {
510
+ const store = templates();
511
+ if (!store.templates.some((entry) => entry.id === id)) fail('规则已不存在,请刷新列表', 404);
512
+ const remaining = store.templates.filter((entry) => entry.id !== id);
513
+ const selectedId = store.selectedId === id ? remaining[0]?.id || '' : store.selectedId;
514
+ save(templatesFile, { selectedId, templates: remaining });
515
+ if (store.selectedId === id) {
516
+ const next = remaining.find((entry) => entry.id === selectedId);
517
+ if (next) save(configFile, next.config);
518
+ else fs.rmSync(configFile, { force: true });
519
+ }
520
+ return { selectedId, templates: remaining };
521
+ }
522
+
523
+ async function selectTemplate({ id }) {
524
+ const store = templates();
525
+ const entry = store.templates.find((item) => item.id === id);
526
+ if (!entry) fail('缺陷规则不存在', 404);
527
+ const ctx = await context(entry.config);
528
+ save(configFile, entry.config);
529
+ save(templatesFile, { ...store, selectedId: id });
530
+ return ctx;
531
+ }
532
+
533
+ async function configure({
534
+ url,
535
+ sheetId = '',
536
+ template = '',
537
+ mapping,
538
+ templateId = '',
539
+ name = '',
540
+ iterations = [],
541
+ iteration = '',
542
+ }) {
543
+ const inspected = await inspect({ url, sheetId });
544
+ const selected = inspected.sheets.find(({ id }) => id === inspected.sheetId);
545
+ const target =
546
+ inspected.target.platform === 'tencent'
547
+ ? { ...inspected.target, sheetId: selected?.id, sheetTitle: selected?.title }
548
+ : inspected.target;
549
+ if (target.platform === 'tencent' && !selected) fail('请先选择缺陷目标子表');
550
+ if (selected)
551
+ target.url = 'https://docs.qq.com/smartsheet/' + target.fileId + '?tab=' + selected.id;
552
+ const candidates = selected
553
+ ? inspected.fields.filter(
554
+ (field) =>
555
+ field.kind &&
556
+ inspected.fields.filter(({ title }) => title === field.title).length === 1,
557
+ )
558
+ : FALLBACK_FIELDS.map((label, index) => ({ id: 'draft_' + index, title: label }));
559
+ const entries = selected
560
+ ? mapping
561
+ : candidates.map((field) => ({
562
+ id: field.id,
563
+ label: field.title,
564
+ required: true,
565
+ }));
566
+ if (!Array.isArray(entries) || !entries.length) fail('至少映射一个缺陷字段');
567
+ const ids = new Set();
568
+ const mapped = entries.map((entry) => {
569
+ const field = candidates.find(({ id }) => id === entry?.id);
570
+ if (!field || ids.has(field.id)) fail('存在重复或不支持的缺陷字段');
571
+ ids.add(field.id);
572
+ const defaultValue = normalizeDefaultValue(
573
+ {
574
+ ...field,
575
+ label: entry.label,
576
+ kind: field.kind || 'text',
577
+ multiple: field.multiple === true,
578
+ options: field.options || [],
579
+ },
580
+ entry.defaultValue,
581
+ );
582
+ return {
583
+ id: field.id,
584
+ label: string(entry.label).slice(0, 100) || field.title,
585
+ required: entry.required === true,
586
+ ...(defaultValue === undefined ? {} : { defaultValue }),
587
+ };
588
+ });
589
+ if (!mapped.some(({ required }) => required)) fail('请至少标记一个必填字段');
590
+ const next = {
591
+ target,
592
+ template: string(template).slice(0, 12000) || DEFAULT_TEMPLATE,
593
+ mapping: mapped,
594
+ ...normalizeIterations(iterations, iteration),
595
+ };
596
+ const result = await context(next);
597
+ const store = templates();
598
+ const id = templateId || randomUUID();
599
+ if (templateId && !store.templates.some((entry) => entry.id === templateId))
600
+ fail('缺陷规则已不存在,请重新加载', 409);
601
+ const entry = { id, name: string(name).slice(0, 100) || '缺陷规则', config: next };
602
+ store.templates = [...store.templates.filter((item) => item.id !== id), entry];
603
+ store.selectedId = id;
604
+ save(templatesFile, store);
605
+ save(configFile, next);
606
+ return result;
607
+ }
608
+
609
+ async function saveRule({
610
+ id = '',
611
+ name,
612
+ url = '',
613
+ sheetId = '',
614
+ template = '',
615
+ mapping,
616
+ iterations = [],
617
+ iteration = '',
618
+ }) {
619
+ if (!string(name)) fail('请填写规则名称');
620
+ if (!Array.isArray(mapping) || !mapping.length || mapping.length > 100)
621
+ fail('请添加 1 至 100 个字段规则');
622
+ const store = templates();
623
+ if (id && !store.templates.some((entry) => entry.id === id))
624
+ fail('规则已不存在,请重新加载', 409);
625
+ /** @type {{ platform: string, url: string, fileId: string, sheetId?: string, sheetTitle?: string, suggestedSheetId?: string }} */
626
+ let target = url ? parseDefectUrl(url) : { platform: 'manual', url: '', fileId: '' };
627
+ let schema = [];
628
+ if (target.platform === 'tencent' && sheetId) {
629
+ const inspected = await inspect({ url, sheetId });
630
+ schema = inspected.fields;
631
+ target = {
632
+ ...target,
633
+ sheetId,
634
+ sheetTitle: inspected.sheets.find((sheet) => sheet.id === sheetId)?.title,
635
+ };
636
+ target.url = 'https://docs.qq.com/smartsheet/' + target.fileId + '?tab=' + sheetId;
637
+ }
638
+ const ids = new Set();
639
+ const labels = new Set();
640
+ const mapped = mapping.map((entry) => {
641
+ const label = string(entry?.label).slice(0, 100);
642
+ const fieldId = string(entry?.id);
643
+ if (!label || !ID.test(fieldId) || ids.has(fieldId) || labels.has(label))
644
+ fail('字段名称和标识不能为空或重复');
645
+ ids.add(fieldId);
646
+ labels.add(label);
647
+ const remote = remoteFieldForEntry(schema, entry);
648
+ const source = entry.source === 'manual' ? 'manual' : remote ? 'remote' : entry.source;
649
+ if (entry.source !== 'manual' && !remote) fail('链接字段已变化,请重新识别或改用手动字段');
650
+ const fieldType = remote || {
651
+ id: fieldId,
652
+ title: label,
653
+ label,
654
+ kind: entry.kind === 'option' ? 'option' : 'text',
655
+ multiple: entry.multiple === true,
656
+ options: entry.kind === 'option' ? manualOptions(entry.options) : [],
657
+ };
658
+ const optionState = resolveOptionOverrides(fieldType, entry);
659
+ const defaultValue = normalizeDefaultValue(
660
+ { ...fieldType, label, options: optionState.options },
661
+ entry.defaultValue,
662
+ );
663
+ return {
664
+ id: remote?.id || fieldId,
665
+ label,
666
+ required: entry.required === true,
667
+ source: remote ? 'remote' : source,
668
+ rule: string(entry.rule).slice(0, 6000),
669
+ kind: fieldType.kind || 'text',
670
+ multiple: fieldType.multiple === true,
671
+ options: optionState.allOptions,
672
+ ...(Object.keys(optionState.optionLabels).length
673
+ ? { optionLabels: optionState.optionLabels }
674
+ : {}),
675
+ ...(source === 'remote' && optionState.hiddenOptions.length
676
+ ? { hiddenOptions: optionState.hiddenOptions }
677
+ : {}),
678
+ ...(defaultValue === undefined ? {} : { defaultValue }),
679
+ };
680
+ });
681
+ const config = {
682
+ target,
683
+ template: string(template).slice(0, 12000),
684
+ mapping: mapped,
685
+ ...normalizeIterations(iterations, iteration),
686
+ };
687
+ const entry = { id: id || randomUUID(), name: string(name).slice(0, 100), config };
688
+ save(templatesFile, {
689
+ selectedId: entry.id,
690
+ templates: [...store.templates.filter((item) => item.id !== entry.id), entry],
691
+ });
692
+ save(configFile, config);
693
+ return entry;
694
+ }
695
+
696
+ function updateRuleIteration({ id, iterations = [], iteration = '' }) {
697
+ const store = templates();
698
+ const entry = store.templates.find((item) => item.id === id);
699
+ if (!entry) fail('规则已不存在,请刷新列表', 404);
700
+ const state = normalizeIterations(iterations, iteration);
701
+ const config = { ...entry.config, iterations: state.iterations };
702
+ if (state.iteration) config.iteration = state.iteration;
703
+ else delete config.iteration;
704
+ const next = {
705
+ ...store,
706
+ templates: store.templates.map((item) => (item.id === id ? { ...item, config } : item)),
707
+ };
708
+ save(templatesFile, next);
709
+ if (store.selectedId === id) save(configFile, config);
710
+ return { selectedId: next.selectedId, templates: next.templates };
711
+ }
712
+
713
+ function draftFile(id) {
714
+ if (!DRAFT_ID.test(id)) fail('缺陷草稿编号无效');
715
+ return defectPath(root, id + '.json');
716
+ }
717
+
718
+ function getDraft(id) {
719
+ const draft = read(draftFile(id), null);
720
+ if (!draft) fail('当前数据空间中没有该缺陷草稿', 404);
721
+ return draft;
722
+ }
723
+
724
+ function validate(ctx, values) {
725
+ if (!values || typeof values !== 'object' || Array.isArray(values)) fail('草稿字段格式无效');
726
+ const known = new Set(ctx.fields.map(({ id }) => id));
727
+ if (Object.keys(values).some((id) => !known.has(id))) fail('草稿包含未映射字段');
728
+ const missing = [];
729
+ const fieldValues = [];
730
+ for (const field of ctx.fields) {
731
+ const value = values[field.id];
732
+ if (empty(value)) {
733
+ if (field.required) missing.push(field.label);
734
+ } else {
735
+ fieldValues.push(payload(field, value));
736
+ }
737
+ }
738
+ return { missing, fieldValues };
739
+ }
740
+
741
+ async function saveDraft({ contextRevision, id = '', revision = '', values }) {
742
+ const ctx = await context();
743
+ if (!ctx.configured || ctx.revision !== contextRevision)
744
+ fail('目标或模板已变更,请重新加载', 409);
745
+ const effectiveValues = valuesWithDefaults(ctx, values);
746
+ const { missing, fieldValues } = validate(ctx, effectiveValues);
747
+ const key = id || randomUUID();
748
+ const file = draftFile(key);
749
+ const previous = id ? getDraft(id) : null;
750
+ if (
751
+ previous &&
752
+ (previous.status !== 'draft' ||
753
+ previous.revision !== revision ||
754
+ previous.contextRevision !== contextRevision ||
755
+ fs.existsSync(file + '.claim'))
756
+ ) {
757
+ fail('草稿已变更或已进入提交,请重新打开', 409);
758
+ }
759
+ const draft = {
760
+ id: key,
761
+ revision: randomUUID(),
762
+ contextRevision,
763
+ target: ctx.target,
764
+ values: effectiveValues,
765
+ missing,
766
+ preview: ctx.fields.map((field) => ({
767
+ label: field.label,
768
+ column: field.title,
769
+ value:
770
+ field.options.length && !empty(effectiveValues[field.id])
771
+ ? (Array.isArray(effectiveValues[field.id])
772
+ ? effectiveValues[field.id]
773
+ : [effectiveValues[field.id]]
774
+ )
775
+ .map((id) => field.options.find((option) => option.id === id)?.label)
776
+ .join('、')
777
+ : effectiveValues[field.id],
778
+ })),
779
+ status: 'draft',
780
+ fieldValues,
781
+ };
782
+ save(file, draft);
783
+ return draft;
784
+ }
785
+
786
+ async function verify(draft) {
787
+ if (!draft.recordId || draft.status !== 'pending') return draft;
788
+ const { fileId, sheetId } = draft.target;
789
+ const checked = await remote('list_records', {
790
+ file_id: fileId,
791
+ sheet_id: sheetId,
792
+ record_ids: [draft.recordId],
793
+ field_titles: [
794
+ ...draft.fieldValues.map(({ field }) => field),
795
+ ...(draft.numberField ? [draft.numberField] : []),
796
+ ],
797
+ });
798
+ const row = checked.records?.find(({ record_id }) => record_id === draft.recordId);
799
+ const exact =
800
+ row &&
801
+ draft.fieldValues.every((expected) => {
802
+ const actual = row.field_values?.find(({ field }) => field === expected.field);
803
+ return (
804
+ actual &&
805
+ JSON.stringify(canonicalValue(expected)) === JSON.stringify(canonicalValue(actual))
806
+ );
807
+ });
808
+ const number = row?.field_values?.find(
809
+ ({ field }) => field === draft.numberField,
810
+ )?.auto_number_value;
811
+ if (!exact || (draft.numberField && !number?.text && !number?.seq)) return draft;
812
+ const verified = {
813
+ ...draft,
814
+ status: 'submitted',
815
+ number: number?.text || number?.seq || draft.recordId,
816
+ verifiedAt: new Date().toISOString(),
817
+ };
818
+ save(draftFile(draft.id), verified);
819
+ return verified;
820
+ }
821
+
822
+ async function submit({ id, revision }) {
823
+ const draft = getDraft(id);
824
+ if (draft.revision !== revision) fail('确认版本已失效,请重新预览草稿', 409);
825
+ if (draft.status !== 'draft') return draft;
826
+ const config = selectedConfig();
827
+ const configFingerprint = hash(config);
828
+ const ctx = await context(config);
829
+ if (draft.target.platform !== 'tencent') fail('该入口仅支持导出缺陷草稿', 409);
830
+ if (ctx.revision !== draft.contextRevision) fail('目标或字段映射已变更,请重新生成草稿', 409);
831
+ const unresolvedManual = ctx.fields.filter(
832
+ (field) => field.source === 'manual' && !empty(draft.values[field.id]),
833
+ );
834
+ if (unresolvedManual.length)
835
+ fail(
836
+ '手动字段需先核对目标字段:' + unresolvedManual.map((field) => field.label).join('、'),
837
+ 409,
838
+ );
839
+ const { missing, fieldValues } = validate(ctx, draft.values);
840
+ if (missing.length) fail('请补齐必填字段:' + missing.join('、'));
841
+ const file = draftFile(id);
842
+ let claim;
843
+ try {
844
+ claim = fs.openSync(file + '.claim', 'wx', 0o600);
845
+ } catch (error) {
846
+ if (error.code === 'EEXIST') return { ...getDraft(id), status: 'pending' };
847
+ throw error;
848
+ }
849
+ fs.closeSync(claim);
850
+ const latest = getDraft(id);
851
+ if (
852
+ latest.revision !== revision ||
853
+ latest.status !== 'draft' ||
854
+ hash(selectedConfig()) !== configFingerprint
855
+ ) {
856
+ fs.rmSync(file + '.claim');
857
+ fail('提交前草稿或目标发生变化,请重新预览', 409);
858
+ }
859
+ let pending = {
860
+ ...latest,
861
+ status: 'pending',
862
+ submittedAt: new Date().toISOString(),
863
+ numberField: ctx.numberField,
864
+ };
865
+ save(file, pending);
866
+ try {
867
+ const created = await remote('add_records', {
868
+ file_id: draft.target.fileId,
869
+ sheet_id: draft.target.sheetId,
870
+ records: [{ field_values: fieldValues }],
871
+ });
872
+ const recordId = created.records?.[0]?.record_id ?? created.record_ids?.[0];
873
+ if (!ID.test(recordId || '')) return pending;
874
+ pending = { ...pending, recordId };
875
+ save(file, pending);
876
+ return await verify(pending);
877
+ } catch {
878
+ return pending;
879
+ }
880
+ }
881
+
882
+ async function receipt(id) {
883
+ const draft = getDraft(id);
884
+ if (draft.status === 'draft' && fs.existsSync(draftFile(id) + '.claim'))
885
+ return { ...draft, status: 'pending' };
886
+ try {
887
+ return await verify(draft);
888
+ } catch {
889
+ return draft;
890
+ }
891
+ }
892
+
893
+ function drafts() {
894
+ const directory = path.dirname(configFile);
895
+ if (!fs.existsSync(directory)) return [];
896
+ return fs
897
+ .readdirSync(directory)
898
+ .filter((name) => DRAFT_ID.test(name.slice(0, -5)) && name.endsWith('.json'))
899
+ .map((name) => {
900
+ const draft = getDraft(name.slice(0, -5));
901
+ return draft.status === 'draft' && fs.existsSync(path.join(directory, name + '.claim'))
902
+ ? { ...draft, status: 'pending' }
903
+ : draft;
904
+ })
905
+ .reverse();
906
+ }
907
+ return {
908
+ inspect,
909
+ saveRule,
910
+ updateRuleIteration,
911
+ deleteRule,
912
+ configure,
913
+ context,
914
+ saveDraft,
915
+ submit,
916
+ receipt,
917
+ drafts,
918
+ templates,
919
+ selectTemplate,
920
+ };
921
+ }
922
+
923
+ async function body(req) {
924
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || ''))
925
+ fail('请求必须使用 JSON', 415);
926
+ let size = 0;
927
+ const chunks = [];
928
+ for await (const chunk of req) {
929
+ size += chunk.length;
930
+ if (size > 1024 * 1024) fail('缺陷请求内容过大', 413);
931
+ chunks.push(chunk);
932
+ }
933
+ try {
934
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
935
+ } catch {
936
+ fail('请求 JSON 格式无效');
937
+ }
938
+ }
939
+
940
+ export function lhDefectSubmitPlugin() {
941
+ return {
942
+ name: 'lh-defect-submit',
943
+ configureServer(server) {
944
+ server.middlewares.use(async (req, res, next) => {
945
+ const [pathname, params] = (req.url || '').split('?');
946
+ if (pathname !== DEFECT_API && !pathname.startsWith(DEFECT_API + '/')) return next();
947
+ const json = (status, value) => {
948
+ res.statusCode = status;
949
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
950
+ res.setHeader('Cache-Control', 'no-store');
951
+ res.end(JSON.stringify(value));
952
+ };
953
+ try {
954
+ const root = getDataRoot();
955
+ if (!isPluginOnInSpace('defectSubmit', root))
956
+ fail('请先在当前空间的插件仓库开启「缺陷规则」', 403);
957
+ const service = createDefectService(root);
958
+ const action = pathname.slice(DEFECT_API.length);
959
+ let data;
960
+ if (req.method === 'GET') {
961
+ if (action === '/context') data = await service.context();
962
+ else if (action === '/templates') data = service.templates();
963
+ else if (action === '/drafts') data = { drafts: service.drafts() };
964
+ else if (action === '/receipt')
965
+ data = await service.receipt(new URLSearchParams(params).get('id') || '');
966
+ }
967
+ if (req.method === 'POST') {
968
+ if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host)
969
+ fail('缺陷提交请求必须来自当前 Lantern 页面', 403);
970
+ if (action === '/rules/delete') data = service.deleteRule(await body(req));
971
+ else if (action === '/rules/save') data = await service.saveRule(await body(req));
972
+ else if (action === '/rules/iteration')
973
+ data = service.updateRuleIteration(await body(req));
974
+ else if (action === '/select-template')
975
+ data = await service.selectTemplate(await body(req));
976
+ else if (action === '/inspect') data = await service.inspect(await body(req));
977
+ else if (action === '/target') data = await service.configure(await body(req));
978
+ else if (action === '/draft') data = await service.saveDraft(await body(req));
979
+ else if (action === '/submit') data = await service.submit(await body(req));
980
+ }
981
+ if (data === undefined) fail('未知缺陷提交操作', 404);
982
+ json(200, { ok: true, ...data });
983
+ } catch (error) {
984
+ json(error.statusCode || 500, { ok: false, error: error.message || String(error) });
985
+ }
986
+ });
987
+ },
988
+ };
989
+ }