simplify3x-connect 0.0.0-stage → 0.28.0

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 (363) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -3
  3. package/dist/acText.d.ts +12 -0
  4. package/dist/acText.d.ts.map +1 -0
  5. package/dist/acText.js +44 -0
  6. package/dist/acText.js.map +1 -0
  7. package/dist/adapters/factory.d.ts +25 -0
  8. package/dist/adapters/factory.d.ts.map +1 -0
  9. package/dist/adapters/factory.js +55 -0
  10. package/dist/adapters/factory.js.map +1 -0
  11. package/dist/adapters/http.d.ts +62 -0
  12. package/dist/adapters/http.d.ts.map +1 -0
  13. package/dist/adapters/http.js +138 -0
  14. package/dist/adapters/http.js.map +1 -0
  15. package/dist/adapters/remoteMcp/adapter.d.ts +112 -0
  16. package/dist/adapters/remoteMcp/adapter.d.ts.map +1 -0
  17. package/dist/adapters/remoteMcp/adapter.js +259 -0
  18. package/dist/adapters/remoteMcp/adapter.js.map +1 -0
  19. package/dist/adapters/simplifyqa/adapter.d.ts +1390 -0
  20. package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -0
  21. package/dist/adapters/simplifyqa/adapter.js +9126 -0
  22. package/dist/adapters/simplifyqa/adapter.js.map +1 -0
  23. package/dist/adapters/simplifyqa/apiFailureReason.d.ts +11 -0
  24. package/dist/adapters/simplifyqa/apiFailureReason.d.ts.map +1 -0
  25. package/dist/adapters/simplifyqa/apiFailureReason.js +35 -0
  26. package/dist/adapters/simplifyqa/apiFailureReason.js.map +1 -0
  27. package/dist/adapters/simplifyqa/desktopConditions.d.ts +50 -0
  28. package/dist/adapters/simplifyqa/desktopConditions.d.ts.map +1 -0
  29. package/dist/adapters/simplifyqa/desktopConditions.js +95 -0
  30. package/dist/adapters/simplifyqa/desktopConditions.js.map +1 -0
  31. package/dist/adapters/simplifyqa/executionFailures.d.ts +59 -0
  32. package/dist/adapters/simplifyqa/executionFailures.d.ts.map +1 -0
  33. package/dist/adapters/simplifyqa/executionFailures.js +641 -0
  34. package/dist/adapters/simplifyqa/executionFailures.js.map +1 -0
  35. package/dist/adapters/simplifyqa/failureCategory.d.ts +26 -0
  36. package/dist/adapters/simplifyqa/failureCategory.d.ts.map +1 -0
  37. package/dist/adapters/simplifyqa/failureCategory.js +208 -0
  38. package/dist/adapters/simplifyqa/failureCategory.js.map +1 -0
  39. package/dist/adapters/simplifyqa/failureReport.d.ts +50 -0
  40. package/dist/adapters/simplifyqa/failureReport.d.ts.map +1 -0
  41. package/dist/adapters/simplifyqa/failureReport.js +383 -0
  42. package/dist/adapters/simplifyqa/failureReport.js.map +1 -0
  43. package/dist/adapters/simplifyqa/failureTypes.d.ts +193 -0
  44. package/dist/adapters/simplifyqa/failureTypes.d.ts.map +1 -0
  45. package/dist/adapters/simplifyqa/failureTypes.js +8 -0
  46. package/dist/adapters/simplifyqa/failureTypes.js.map +1 -0
  47. package/dist/adapters/simplifyqa/flow.d.ts +58 -0
  48. package/dist/adapters/simplifyqa/flow.d.ts.map +1 -0
  49. package/dist/adapters/simplifyqa/flow.js +335 -0
  50. package/dist/adapters/simplifyqa/flow.js.map +1 -0
  51. package/dist/adapters/simplifyqa/functionMatch.d.ts +53 -0
  52. package/dist/adapters/simplifyqa/functionMatch.d.ts.map +1 -0
  53. package/dist/adapters/simplifyqa/functionMatch.js +110 -0
  54. package/dist/adapters/simplifyqa/functionMatch.js.map +1 -0
  55. package/dist/adapters/simplifyqa/heal/apply.d.ts +59 -0
  56. package/dist/adapters/simplifyqa/heal/apply.d.ts.map +1 -0
  57. package/dist/adapters/simplifyqa/heal/apply.js +213 -0
  58. package/dist/adapters/simplifyqa/heal/apply.js.map +1 -0
  59. package/dist/adapters/simplifyqa/heal/diagnose.d.ts +24 -0
  60. package/dist/adapters/simplifyqa/heal/diagnose.d.ts.map +1 -0
  61. package/dist/adapters/simplifyqa/heal/diagnose.js +211 -0
  62. package/dist/adapters/simplifyqa/heal/diagnose.js.map +1 -0
  63. package/dist/adapters/simplifyqa/heal/index.d.ts +37 -0
  64. package/dist/adapters/simplifyqa/heal/index.d.ts.map +1 -0
  65. package/dist/adapters/simplifyqa/heal/index.js +83 -0
  66. package/dist/adapters/simplifyqa/heal/index.js.map +1 -0
  67. package/dist/adapters/simplifyqa/heal/plan.d.ts +67 -0
  68. package/dist/adapters/simplifyqa/heal/plan.d.ts.map +1 -0
  69. package/dist/adapters/simplifyqa/heal/plan.js +338 -0
  70. package/dist/adapters/simplifyqa/heal/plan.js.map +1 -0
  71. package/dist/adapters/simplifyqa/heal/store.d.ts +10 -0
  72. package/dist/adapters/simplifyqa/heal/store.d.ts.map +1 -0
  73. package/dist/adapters/simplifyqa/heal/store.js +40 -0
  74. package/dist/adapters/simplifyqa/heal/store.js.map +1 -0
  75. package/dist/adapters/simplifyqa/mapLimit.d.ts +3 -0
  76. package/dist/adapters/simplifyqa/mapLimit.d.ts.map +1 -0
  77. package/dist/adapters/simplifyqa/mapLimit.js +14 -0
  78. package/dist/adapters/simplifyqa/mapLimit.js.map +1 -0
  79. package/dist/adapters/simplifyqa/mapper.d.ts +159 -0
  80. package/dist/adapters/simplifyqa/mapper.d.ts.map +1 -0
  81. package/dist/adapters/simplifyqa/mapper.js +1767 -0
  82. package/dist/adapters/simplifyqa/mapper.js.map +1 -0
  83. package/dist/adapters/simplifyqa/planTree.d.ts +31 -0
  84. package/dist/adapters/simplifyqa/planTree.d.ts.map +1 -0
  85. package/dist/adapters/simplifyqa/planTree.js +110 -0
  86. package/dist/adapters/simplifyqa/planTree.js.map +1 -0
  87. package/dist/adapters/simplifyqa/searchEngine.d.ts +254 -0
  88. package/dist/adapters/simplifyqa/searchEngine.d.ts.map +1 -0
  89. package/dist/adapters/simplifyqa/searchEngine.js +1248 -0
  90. package/dist/adapters/simplifyqa/searchEngine.js.map +1 -0
  91. package/dist/adapters/simplifyqa/searchRegistry.d.ts +117 -0
  92. package/dist/adapters/simplifyqa/searchRegistry.d.ts.map +1 -0
  93. package/dist/adapters/simplifyqa/searchRegistry.js +1664 -0
  94. package/dist/adapters/simplifyqa/searchRegistry.js.map +1 -0
  95. package/dist/adapters/simplifyqa/searchResolve.d.ts +84 -0
  96. package/dist/adapters/simplifyqa/searchResolve.d.ts.map +1 -0
  97. package/dist/adapters/simplifyqa/searchResolve.js +319 -0
  98. package/dist/adapters/simplifyqa/searchResolve.js.map +1 -0
  99. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts +25 -0
  100. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts.map +1 -0
  101. package/dist/adapters/simplifyqa/stepDiagnostics.js +89 -0
  102. package/dist/adapters/simplifyqa/stepDiagnostics.js.map +1 -0
  103. package/dist/adapters/simplifyqa/stepRules.d.ts +91 -0
  104. package/dist/adapters/simplifyqa/stepRules.d.ts.map +1 -0
  105. package/dist/adapters/simplifyqa/stepRules.js +228 -0
  106. package/dist/adapters/simplifyqa/stepRules.js.map +1 -0
  107. package/dist/adapters/types.d.ts +514 -0
  108. package/dist/adapters/types.d.ts.map +1 -0
  109. package/dist/adapters/types.js +2 -0
  110. package/dist/adapters/types.js.map +1 -0
  111. package/dist/adapters/walnut/actionTypes.d.ts +16 -0
  112. package/dist/adapters/walnut/actionTypes.d.ts.map +1 -0
  113. package/dist/adapters/walnut/actionTypes.js +178 -0
  114. package/dist/adapters/walnut/actionTypes.js.map +1 -0
  115. package/dist/adapters/walnut/adapter.d.ts +235 -0
  116. package/dist/adapters/walnut/adapter.d.ts.map +1 -0
  117. package/dist/adapters/walnut/adapter.js +1120 -0
  118. package/dist/adapters/walnut/adapter.js.map +1 -0
  119. package/dist/adapters/walnut/mapper.d.ts +55 -0
  120. package/dist/adapters/walnut/mapper.d.ts.map +1 -0
  121. package/dist/adapters/walnut/mapper.js +364 -0
  122. package/dist/adapters/walnut/mapper.js.map +1 -0
  123. package/dist/cli.d.ts +3 -0
  124. package/dist/cli.d.ts.map +1 -0
  125. package/dist/cli.js +38 -0
  126. package/dist/cli.js.map +1 -0
  127. package/dist/config.d.ts +109 -0
  128. package/dist/config.d.ts.map +1 -0
  129. package/dist/config.js +272 -0
  130. package/dist/config.js.map +1 -0
  131. package/dist/connection.d.ts +105 -0
  132. package/dist/connection.d.ts.map +1 -0
  133. package/dist/connection.js +255 -0
  134. package/dist/connection.js.map +1 -0
  135. package/dist/domain/heal.d.ts +163 -0
  136. package/dist/domain/heal.d.ts.map +1 -0
  137. package/dist/domain/heal.js +55 -0
  138. package/dist/domain/heal.js.map +1 -0
  139. package/dist/domain/types.d.ts +1328 -0
  140. package/dist/domain/types.d.ts.map +1 -0
  141. package/dist/domain/types.js +8 -0
  142. package/dist/domain/types.js.map +1 -0
  143. package/dist/domain/validate.d.ts +3 -0
  144. package/dist/domain/validate.d.ts.map +1 -0
  145. package/dist/domain/validate.js +67 -0
  146. package/dist/domain/validate.js.map +1 -0
  147. package/dist/drafts/apiPatch.d.ts +9 -0
  148. package/dist/drafts/apiPatch.d.ts.map +1 -0
  149. package/dist/drafts/apiPatch.js +27 -0
  150. package/dist/drafts/apiPatch.js.map +1 -0
  151. package/dist/drafts/bulk.d.ts +24 -0
  152. package/dist/drafts/bulk.d.ts.map +1 -0
  153. package/dist/drafts/bulk.js +44 -0
  154. package/dist/drafts/bulk.js.map +1 -0
  155. package/dist/drafts/duplicate.d.ts +12 -0
  156. package/dist/drafts/duplicate.d.ts.map +1 -0
  157. package/dist/drafts/duplicate.js +59 -0
  158. package/dist/drafts/duplicate.js.map +1 -0
  159. package/dist/drafts/store.d.ts +91 -0
  160. package/dist/drafts/store.d.ts.map +1 -0
  161. package/dist/drafts/store.js +244 -0
  162. package/dist/drafts/store.js.map +1 -0
  163. package/dist/gateway.d.ts +37 -0
  164. package/dist/gateway.d.ts.map +1 -0
  165. package/dist/gateway.js +71 -0
  166. package/dist/gateway.js.map +1 -0
  167. package/dist/httpMain.d.ts +3 -0
  168. package/dist/httpMain.d.ts.map +1 -0
  169. package/dist/httpMain.js +20 -0
  170. package/dist/httpMain.js.map +1 -0
  171. package/dist/index.d.ts +3 -0
  172. package/dist/index.d.ts.map +1 -0
  173. package/dist/index.js +46 -0
  174. package/dist/index.js.map +1 -0
  175. package/dist/initAgents.d.ts +2 -0
  176. package/dist/initAgents.d.ts.map +1 -0
  177. package/dist/initAgents.js +508 -0
  178. package/dist/initAgents.js.map +1 -0
  179. package/dist/log.d.ts +17 -0
  180. package/dist/log.d.ts.map +1 -0
  181. package/dist/log.js +49 -0
  182. package/dist/log.js.map +1 -0
  183. package/dist/mcpResult.d.ts +39 -0
  184. package/dist/mcpResult.d.ts.map +1 -0
  185. package/dist/mcpResult.js +19 -0
  186. package/dist/mcpResult.js.map +1 -0
  187. package/dist/mount.d.ts +33 -0
  188. package/dist/mount.d.ts.map +1 -0
  189. package/dist/mount.js +213 -0
  190. package/dist/mount.js.map +1 -0
  191. package/dist/paramTokens.d.ts +18 -0
  192. package/dist/paramTokens.d.ts.map +1 -0
  193. package/dist/paramTokens.js +50 -0
  194. package/dist/paramTokens.js.map +1 -0
  195. package/dist/projectStore.d.ts +5 -0
  196. package/dist/projectStore.d.ts.map +1 -0
  197. package/dist/projectStore.js +60 -0
  198. package/dist/projectStore.js.map +1 -0
  199. package/dist/requestConnection.d.ts +22 -0
  200. package/dist/requestConnection.d.ts.map +1 -0
  201. package/dist/requestConnection.js +50 -0
  202. package/dist/requestConnection.js.map +1 -0
  203. package/dist/serve.d.ts +10 -0
  204. package/dist/serve.d.ts.map +1 -0
  205. package/dist/serve.js +37 -0
  206. package/dist/serve.js.map +1 -0
  207. package/dist/server.d.ts +41 -0
  208. package/dist/server.d.ts.map +1 -0
  209. package/dist/server.js +370 -0
  210. package/dist/server.js.map +1 -0
  211. package/dist/tools/actionCatalog.d.ts +24 -0
  212. package/dist/tools/actionCatalog.d.ts.map +1 -0
  213. package/dist/tools/actionCatalog.js +56 -0
  214. package/dist/tools/actionCatalog.js.map +1 -0
  215. package/dist/tools/attachment.tools.d.ts +15 -0
  216. package/dist/tools/attachment.tools.d.ts.map +1 -0
  217. package/dist/tools/attachment.tools.js +104 -0
  218. package/dist/tools/attachment.tools.js.map +1 -0
  219. package/dist/tools/backlog.tools.d.ts +13 -0
  220. package/dist/tools/backlog.tools.d.ts.map +1 -0
  221. package/dist/tools/backlog.tools.js +690 -0
  222. package/dist/tools/backlog.tools.js.map +1 -0
  223. package/dist/tools/connection.tools.d.ts +16 -0
  224. package/dist/tools/connection.tools.d.ts.map +1 -0
  225. package/dist/tools/connection.tools.js +120 -0
  226. package/dist/tools/connection.tools.js.map +1 -0
  227. package/dist/tools/defects.tools.d.ts +7 -0
  228. package/dist/tools/defects.tools.d.ts.map +1 -0
  229. package/dist/tools/defects.tools.js +108 -0
  230. package/dist/tools/defects.tools.js.map +1 -0
  231. package/dist/tools/discovery.tools.d.ts +23 -0
  232. package/dist/tools/discovery.tools.d.ts.map +1 -0
  233. package/dist/tools/discovery.tools.js +1746 -0
  234. package/dist/tools/discovery.tools.js.map +1 -0
  235. package/dist/tools/executionPlan.tools.d.ts +14 -0
  236. package/dist/tools/executionPlan.tools.d.ts.map +1 -0
  237. package/dist/tools/executionPlan.tools.js +184 -0
  238. package/dist/tools/executionPlan.tools.js.map +1 -0
  239. package/dist/tools/failure.tools.d.ts +14 -0
  240. package/dist/tools/failure.tools.d.ts.map +1 -0
  241. package/dist/tools/failure.tools.js +65 -0
  242. package/dist/tools/failure.tools.js.map +1 -0
  243. package/dist/tools/formulas.tools.d.ts +7 -0
  244. package/dist/tools/formulas.tools.d.ts.map +1 -0
  245. package/dist/tools/formulas.tools.js +84 -0
  246. package/dist/tools/formulas.tools.js.map +1 -0
  247. package/dist/tools/functionReuse.d.ts +77 -0
  248. package/dist/tools/functionReuse.d.ts.map +1 -0
  249. package/dist/tools/functionReuse.js +384 -0
  250. package/dist/tools/functionReuse.js.map +1 -0
  251. package/dist/tools/gapAnalysis.tools.d.ts +31 -0
  252. package/dist/tools/gapAnalysis.tools.d.ts.map +1 -0
  253. package/dist/tools/gapAnalysis.tools.js +287 -0
  254. package/dist/tools/gapAnalysis.tools.js.map +1 -0
  255. package/dist/tools/heal.tools.d.ts +20 -0
  256. package/dist/tools/heal.tools.d.ts.map +1 -0
  257. package/dist/tools/heal.tools.js +268 -0
  258. package/dist/tools/heal.tools.js.map +1 -0
  259. package/dist/tools/impactAnalysis.tools.d.ts +17 -0
  260. package/dist/tools/impactAnalysis.tools.d.ts.map +1 -0
  261. package/dist/tools/impactAnalysis.tools.js +352 -0
  262. package/dist/tools/impactAnalysis.tools.js.map +1 -0
  263. package/dist/tools/markdown.d.ts +13 -0
  264. package/dist/tools/markdown.d.ts.map +1 -0
  265. package/dist/tools/markdown.js +145 -0
  266. package/dist/tools/markdown.js.map +1 -0
  267. package/dist/tools/objects.tools.d.ts +7 -0
  268. package/dist/tools/objects.tools.d.ts.map +1 -0
  269. package/dist/tools/objects.tools.js +458 -0
  270. package/dist/tools/objects.tools.js.map +1 -0
  271. package/dist/tools/pipeline.tools.d.ts +11 -0
  272. package/dist/tools/pipeline.tools.d.ts.map +1 -0
  273. package/dist/tools/pipeline.tools.js +100 -0
  274. package/dist/tools/pipeline.tools.js.map +1 -0
  275. package/dist/tools/preference.tools.d.ts +15 -0
  276. package/dist/tools/preference.tools.d.ts.map +1 -0
  277. package/dist/tools/preference.tools.js +114 -0
  278. package/dist/tools/preference.tools.js.map +1 -0
  279. package/dist/tools/privileges.tools.d.ts +65 -0
  280. package/dist/tools/privileges.tools.d.ts.map +1 -0
  281. package/dist/tools/privileges.tools.js +186 -0
  282. package/dist/tools/privileges.tools.js.map +1 -0
  283. package/dist/tools/project.tools.d.ts +13 -0
  284. package/dist/tools/project.tools.d.ts.map +1 -0
  285. package/dist/tools/project.tools.js +199 -0
  286. package/dist/tools/project.tools.js.map +1 -0
  287. package/dist/tools/query.tools.d.ts +23 -0
  288. package/dist/tools/query.tools.d.ts.map +1 -0
  289. package/dist/tools/query.tools.js +368 -0
  290. package/dist/tools/query.tools.js.map +1 -0
  291. package/dist/tools/recording.tools.d.ts +58 -0
  292. package/dist/tools/recording.tools.d.ts.map +1 -0
  293. package/dist/tools/recording.tools.js +1050 -0
  294. package/dist/tools/recording.tools.js.map +1 -0
  295. package/dist/tools/recordingNames.d.ts +3 -0
  296. package/dist/tools/recordingNames.d.ts.map +1 -0
  297. package/dist/tools/recordingNames.js +16 -0
  298. package/dist/tools/recordingNames.js.map +1 -0
  299. package/dist/tools/report.tools.d.ts +12 -0
  300. package/dist/tools/report.tools.d.ts.map +1 -0
  301. package/dist/tools/report.tools.js +104 -0
  302. package/dist/tools/report.tools.js.map +1 -0
  303. package/dist/tools/run.tools.d.ts +25 -0
  304. package/dist/tools/run.tools.d.ts.map +1 -0
  305. package/dist/tools/run.tools.js +1295 -0
  306. package/dist/tools/run.tools.js.map +1 -0
  307. package/dist/tools/schemas.d.ts +860 -0
  308. package/dist/tools/schemas.d.ts.map +1 -0
  309. package/dist/tools/schemas.js +220 -0
  310. package/dist/tools/schemas.js.map +1 -0
  311. package/dist/tools/storySync.tools.d.ts +167 -0
  312. package/dist/tools/storySync.tools.d.ts.map +1 -0
  313. package/dist/tools/storySync.tools.js +678 -0
  314. package/dist/tools/storySync.tools.js.map +1 -0
  315. package/dist/tools/suiteManage.tools.d.ts +14 -0
  316. package/dist/tools/suiteManage.tools.d.ts.map +1 -0
  317. package/dist/tools/suiteManage.tools.js +112 -0
  318. package/dist/tools/suiteManage.tools.js.map +1 -0
  319. package/dist/tools/tasks.tools.d.ts +7 -0
  320. package/dist/tools/tasks.tools.d.ts.map +1 -0
  321. package/dist/tools/tasks.tools.js +101 -0
  322. package/dist/tools/tasks.tools.js.map +1 -0
  323. package/dist/tools/tcEditPublisher.d.ts +29 -0
  324. package/dist/tools/tcEditPublisher.d.ts.map +1 -0
  325. package/dist/tools/tcEditPublisher.js +61 -0
  326. package/dist/tools/tcEditPublisher.js.map +1 -0
  327. package/dist/tools/testCaseLint.d.ts +5 -0
  328. package/dist/tools/testCaseLint.d.ts.map +1 -0
  329. package/dist/tools/testCaseLint.js +112 -0
  330. package/dist/tools/testCaseLint.js.map +1 -0
  331. package/dist/tools/testPlan.tools.d.ts +12 -0
  332. package/dist/tools/testPlan.tools.d.ts.map +1 -0
  333. package/dist/tools/testPlan.tools.js +104 -0
  334. package/dist/tools/testPlan.tools.js.map +1 -0
  335. package/dist/tools/testcase.tools.d.ts +86 -0
  336. package/dist/tools/testcase.tools.d.ts.map +1 -0
  337. package/dist/tools/testcase.tools.js +1591 -0
  338. package/dist/tools/testcase.tools.js.map +1 -0
  339. package/dist/tools/testdata.tools.d.ts +7 -0
  340. package/dist/tools/testdata.tools.d.ts.map +1 -0
  341. package/dist/tools/testdata.tools.js +636 -0
  342. package/dist/tools/testdata.tools.js.map +1 -0
  343. package/dist/tools/xlsx.d.ts +8 -0
  344. package/dist/tools/xlsx.d.ts.map +1 -0
  345. package/dist/tools/xlsx.js +113 -0
  346. package/dist/tools/xlsx.js.map +1 -0
  347. package/dist/vendor/actionSignatures.d.ts +117 -0
  348. package/dist/vendor/actionSignatures.d.ts.map +1 -0
  349. package/dist/vendor/actionSignatures.js +420 -0
  350. package/dist/vendor/actionSignatures.js.map +1 -0
  351. package/dist/vendor/logger.d.ts +43 -0
  352. package/dist/vendor/logger.d.ts.map +1 -0
  353. package/dist/vendor/logger.js +184 -0
  354. package/dist/vendor/logger.js.map +1 -0
  355. package/dist/version.d.ts +10 -0
  356. package/dist/version.d.ts.map +1 -0
  357. package/dist/version.js +10 -0
  358. package/dist/version.js.map +1 -0
  359. package/dist/versionName.d.ts +21 -0
  360. package/dist/versionName.d.ts.map +1 -0
  361. package/dist/versionName.js +48 -0
  362. package/dist/versionName.js.map +1 -0
  363. package/package.json +62 -6
@@ -0,0 +1,1767 @@
1
+ import { normalizeParamTokens, stripParamTokens } from '../../paramTokens.js';
2
+ import { splitAcceptanceCriteria } from '../../acText.js';
3
+ export { splitAcceptanceCriteria };
4
+ // ---------------------------------------------------------------------------
5
+ // Shared JSON pluckers. SQA endpoints wrap responses inconsistently -- one
6
+ // controller returns `{ status, data: [...] }`, another returns the bare
7
+ // array, another wraps it under `content` or the entity plural. `pickArray`
8
+ // and `str` walk a list of candidate keys and return the first hit, matching
9
+ // the tolerance the Java BackendClient built up against real responses.
10
+ // ---------------------------------------------------------------------------
11
+ export function pickArray(n, ...keys) {
12
+ for (const k of keys) {
13
+ const v = n?.[k];
14
+ if (Array.isArray(v))
15
+ return v;
16
+ }
17
+ return Array.isArray(n) ? n : [];
18
+ }
19
+ /** Hang `totalCount` off a mapped array as a side-band prop — SQA search responses expose it
20
+ * at the top level as `totalCount` (with `total`/`totalRecords` as tolerant fallbacks). Undefined
21
+ * when the raw response omits it (callers show `rows.length` as the total in that case). */
22
+ export function withTotal(rows, raw) {
23
+ const t = raw?.totalCount ?? raw?.total ?? raw?.totalRecords;
24
+ if (typeof t === 'number')
25
+ rows.totalCount = t;
26
+ return rows;
27
+ }
28
+ export function str(n, ...keys) {
29
+ if (n == null)
30
+ return undefined;
31
+ for (const k of keys) {
32
+ const v = n[k];
33
+ if (typeof v === 'string' && v.length)
34
+ return v;
35
+ if (typeof v === 'number')
36
+ return String(v);
37
+ }
38
+ return undefined;
39
+ }
40
+ /** Rows a reader may see: soft-deleted ones (`deleted: true`) dropped — the AI assistant's
41
+ * `deleted ≠ true` rule, for endpoints that return rows without filtering them (reports, steps). */
42
+ export function notDeleted(rows) {
43
+ return rows.filter((r) => r?.deleted !== true);
44
+ }
45
+ /** Accept a numeric id ("523") or a business code ("TC_523" / "US-897") — SQA REST paths
46
+ * parseInt the segment, so a raw business key yields NaN → 404. Strips to the numeric run. */
47
+ export function numericId(id) {
48
+ if (!id)
49
+ return '';
50
+ const m = id.match(/(\d+)/);
51
+ return m ? m[1] : id;
52
+ }
53
+ /** Map raw `tcfn_version` rows → neutral `TcVersion[]`. Shared between TC (versions inlined on
54
+ * the `/tm/testcase/getById` doc) and FN (versions come from `/tm/function/version/:id/:pid`).
55
+ * `currentVersionId` stamps `isCurrent:true` on the matching entry — pass undefined if unknown. */
56
+ export function toVersionEntries(rawVersions, currentVersionId) {
57
+ return (Array.isArray(rawVersions) ? rawVersions : [])
58
+ .map((v) => {
59
+ const vid = str(v, 'id', '_id');
60
+ if (!vid)
61
+ return null;
62
+ const name = str(v, 'name') ?? vid;
63
+ const entry = { id: vid, name };
64
+ if (typeof v?.updateVersion === 'number')
65
+ entry.updateVersion = v.updateVersion;
66
+ const rev = str(v, 'reviewApproveStatus');
67
+ if (rev)
68
+ entry.reviewApproveStatus = rev;
69
+ const ex = str(v, 'executionType');
70
+ if (ex)
71
+ entry.executionType = ex;
72
+ if (currentVersionId && vid === currentVersionId)
73
+ entry.isCurrent = true;
74
+ return entry;
75
+ })
76
+ .filter((v) => v !== null);
77
+ }
78
+ /** SQA priority is UPPERCASE on the wire; neutral is lowercase. Unknown → 'medium'. */
79
+ export function mapPriority(p) {
80
+ const s = typeof p === 'string' ? p.toLowerCase() : '';
81
+ return s === 'critical' || s === 'high' || s === 'medium' || s === 'low'
82
+ ? s : 'medium';
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // Steps. SQA stores step docs in two shapes with mostly-overlapping fields:
86
+ // • the `/tm/testcase/steps` COLLECTION (source of truth today), and
87
+ // • the INLINE `steps.manualSteps` / `steps.automationSteps` array on the TC doc
88
+ // (legacy, drifts against the collection).
89
+ // Both use the same field names, so ONE mapper covers both. See adapter.ts
90
+ // getTestCase for the read strategy (collection wins; inline is a fallback).
91
+ // ---------------------------------------------------------------------------
92
+ export const STEP_BLOCK_END_TYPES = new Set([
93
+ 'ELSE', 'ELSE_IF', 'IF_END', 'FOR_END', 'WHILE', 'WHILE_END', 'ITERATOR_END',
94
+ 'LOOP_ITERATION_END', 'FUNCTION_END',
95
+ ]);
96
+ export const STEP_LOOP_START_TYPES = new Set([
97
+ 'FOR_START', 'WHILE_START', 'ITERATOR_START', 'LOOP_ITERATION_START', 'DO',
98
+ ]);
99
+ // SQA raw `stepType` → neutral Step.stepType + Step.controlFlow.kind. Enumerated from the
100
+ // backend's own union (tcfn.service.js:2176 stepTypeMapping + validators). Everything not in
101
+ // SIMPLE / CF_KINDS falls through as a plain automation step.
102
+ const NEUTRAL_BY_TECH = {
103
+ ANDROID: 'android', IOS: 'ios', MAINFRAME: 'mainframe', DESKTOP: 'desktop', SAP: 'sap',
104
+ };
105
+ const SIMPLE_STEP_KINDS = {
106
+ NORMAL_STATEMENT: 'web',
107
+ API: 'api',
108
+ COMPARE: 'compare',
109
+ };
110
+ const CF_KINDS = new Set([
111
+ 'IF', 'ELSE', 'ELSE_IF', 'IF_END',
112
+ 'WHILE_START', 'WHILE', 'WHILE_END',
113
+ 'DO', 'DO_WHILE',
114
+ 'FOR_START', 'FOR_END', 'LOOP',
115
+ 'ITERATOR_START', 'ITERATOR_END',
116
+ 'LOOP_ITERATION_START', 'LOOP_ITERATION_END',
117
+ 'BREAK', 'CONTINUE',
118
+ ]);
119
+ const SWITCH_KINDS = new Set([
120
+ 'SWITCH_TO_API', 'SWITCH_TO_DB', 'SWITCH_TO_WEB', 'SWITCH_TO_MAINFRAME',
121
+ 'SWITCH_TO_DESKTOP', 'SWITCH_TO_SAP', 'SWITCH_TO_IOS', 'SWITCH_TO_ANDROID',
122
+ ]);
123
+ /** Round-trip whitelist: raw backend fields we preserve verbatim on the neutral Step so save
124
+ * re-emits control-flow / function / switch / api structure intact. Subset of the backend's
125
+ * step joi allow-list (testcaseValidator.js:244-306) MINUS fields the mapper always computes
126
+ * fresh (id, parentId, versionId, seq, actionId, objectId, description, expectedResult,
127
+ * technologyType, projectId, moduleId, type, deleted, recordedParam, parameterIds,
128
+ * objectParameterIds). `stepLevelActions` (skip / screenshot / continue-on-failure / skippedReport) and
129
+ * `browserType` are NOT recomputed from anything, so they must round-trip or every re-save of an existing
130
+ * step silently resets them. Duplicated (not imported from adapter.ts)
131
+ * to avoid a circular import — mapper is a leaf module. */
132
+ const STEP_ROUND_TRIP_KEYS = [
133
+ 'stepLevelActions', 'browserType',
134
+ 'sharedFnProjectId', 'apiData', 'lastActiveTab', 'userstoryId',
135
+ 'stepType', 'functionId', 'fnVersionId', 'sharedFnProjectName',
136
+ 'parameterizedParamIds', 'attachments', 'compareFiles', 'compareFileType',
137
+ 'deviceId', 'ignoreObject', 'captureScreenshot', 'screenshotEnabled',
138
+ 'conditions', 'skipParamInReport', 'paramLoopduration', 'showGroups',
139
+ 'isConditional', 'if', 'else', 'loop', 'isLoop', 'loopType', 'startFor', 'endFor',
140
+ 'loopDuration', 'switchToAndroidData', 'switchToIOSData',
141
+ 'isDebug', 'manualStepsTopreview', 'isMigrated', 'customFields',
142
+ ];
143
+ function pickRoundTrip(s) {
144
+ const out = {};
145
+ if (!s || typeof s !== 'object')
146
+ return out;
147
+ for (const k of STEP_ROUND_TRIP_KEYS)
148
+ if (s[k] !== undefined)
149
+ out[k] = s[k];
150
+ return out;
151
+ }
152
+ /** Squash a step's `recordedParam: { <paramId>: value }` map into a single readable cell
153
+ * ("packageName=us.zoom, activity=..."). Names would be nicer than ids, but the id→name
154
+ * resolution requires the project parameter dictionary — deferred; the raw id is unambiguous
155
+ * and keeps this pure. */
156
+ function formatRecordedParam(rp) {
157
+ if (!rp || typeof rp !== 'object')
158
+ return undefined;
159
+ const entries = Object.entries(rp).filter(([, v]) => v != null && v !== '');
160
+ if (!entries.length)
161
+ return undefined;
162
+ return entries.map(([k, v]) => `${k}=${String(v)}`).join(', ');
163
+ }
164
+ export function fromSqaStep(s, fallbackSeq) {
165
+ const sid = str(s, 'id', '_id', 'stepId');
166
+ const description = s?.description ?? '';
167
+ const expectedResult = s?.expectedResult ?? undefined;
168
+ const actionType = str(s, 'actionId', 'actionType') ?? '';
169
+ const seq = typeof s?.seq === 'number' ? s.seq : fallbackSeq;
170
+ const rawStepType = String(s?.stepType ?? '').toUpperCase();
171
+ // Neutral stepType routing. Manual TCs have executionType:'MANUAL' at the STEP level — that's
172
+ // the only reliable signal for the neutral 'manual' bucket (validators show `executionType`
173
+ // is a per-step string). Otherwise SIMPLE_STEP_KINDS wins, then CF, then FUNCTION, then a
174
+ // safe automation fallback.
175
+ let stepType = 'web';
176
+ if (str(s, 'executionType')?.toUpperCase() === 'MANUAL')
177
+ stepType = 'manual';
178
+ // DB is action-bound like web and rides NORMAL_STATEMENT; the technologyType is the reliable signal
179
+ // (raw stepType may be NORMAL_STATEMENT). Detect before SIMPLE_STEP_KINDS so it isn't misrouted to web.
180
+ else if (str(s, 'technologyType')?.toUpperCase() === 'DATABASE' || rawStepType === 'DATABASE')
181
+ stepType = 'database';
182
+ // The same for the other technologies — a saved Android / iOS / Mainframe / Desktop / SAP action step is NORMAL_STATEMENT
183
+ // too, and without this it hydrated as 'web' and a re-save stamped it technologyType WEB.
184
+ else if (rawStepType === 'NORMAL_STATEMENT' && NEUTRAL_BY_TECH[str(s, 'technologyType')?.toUpperCase() ?? '']) {
185
+ stepType = NEUTRAL_BY_TECH[str(s, 'technologyType').toUpperCase()];
186
+ }
187
+ else if (SIMPLE_STEP_KINDS[rawStepType])
188
+ stepType = SIMPLE_STEP_KINDS[rawStepType];
189
+ else if (rawStepType === 'FUNCTION')
190
+ stepType = 'function';
191
+ else if (rawStepType === 'FUNCTION_END')
192
+ stepType = 'function_end';
193
+ else if (CF_KINDS.has(rawStepType))
194
+ stepType = 'control_flow';
195
+ else if (SWITCH_KINDS.has(rawStepType))
196
+ stepType = 'switch';
197
+ // Object linkage: SQA stores it as either scalar `objectId` OR nested `object.id`.
198
+ // Preserving the FK is what lets tc_heal / object_update_locators find the shared object.
199
+ let objectId = str(s, 'objectId');
200
+ if (!objectId && s?.object && typeof s.object === 'object') {
201
+ objectId = str(s.object, 'id');
202
+ }
203
+ const objectName = s?.object && typeof s.object === 'object' ? str(s.object, 'name') : undefined;
204
+ // ponytail: preserve backend parameterIds so round-trip save doesn't wipe FK linkages that
205
+ // weren't derived from description ${tokens} (e.g. a "Go to URL" step with parameterIds:[841]
206
+ // even though the description has no token).
207
+ const sourceParameterIds = Array.isArray(s?.parameterIds)
208
+ ? s.parameterIds.filter((n) => typeof n === 'number' && Number.isFinite(n))
209
+ : [];
210
+ const sourceObjectParameterIds = Array.isArray(s?.objectParameterIds)
211
+ ? s.objectParameterIds.filter((n) => typeof n === 'number' && Number.isFinite(n))
212
+ : [];
213
+ // ponytail: preserve backend recordedParam as-is (id-keyed) so a save that doesn't touch values
214
+ // re-emits them intact. LLM patches via Step.recordedParam (name-keyed) override at save time.
215
+ const sourceRecordedParam = {};
216
+ if (s?.recordedParam && typeof s.recordedParam === 'object') {
217
+ for (const [k, v] of Object.entries(s.recordedParam)) {
218
+ if (typeof v === 'string')
219
+ sourceRecordedParam[k] = v;
220
+ else if (typeof v === 'number' || typeof v === 'boolean')
221
+ sourceRecordedParam[k] = String(v);
222
+ }
223
+ }
224
+ // ponytail: preserve every backend field that's on the joi allow-list but that the mapper
225
+ // doesn't recompute. This is what makes IF/FOR/WHILE/FUNCTION/SWITCH/API steps round-trip.
226
+ const sourceRaw = pickRoundTrip(s);
227
+ // Step flags as the neutral model names them, so a reader sees which steps are skipped etc. (only the ones that are on)
228
+ const sla = s?.stepLevelActions && typeof s.stepLevelActions === 'object' ? s.stepLevelActions : {};
229
+ const flags = {
230
+ ...(sla.skip === true ? { skip: true } : {}),
231
+ ...(sla.captureScreenshot === true ? { screenshot: true } : {}),
232
+ ...(sla.continueOnFailure === true ? { continueOnFailure: true } : {}),
233
+ };
234
+ const browserType = str(s, 'browserType');
235
+ // The backend's own technology for THIS step is authoritative (a DB step and a web step are both
236
+ // NORMAL_STATEMENT on the wire); fall back to the stepType→tech table for rows that omit it.
237
+ const stepTechnology = (str(s, 'technologyType') ?? TECH_BY_STEPTYPE[stepType] ?? '').toUpperCase();
238
+ const step = {
239
+ n: seq,
240
+ description,
241
+ actionType,
242
+ technologyType: stepTechnology || undefined,
243
+ stepType,
244
+ ...(Object.keys(flags).length ? { flags } : {}),
245
+ ...(browserType ? { browserType } : {}),
246
+ ...(sid ? { sourceId: sid } : {}),
247
+ ...(expectedResult ? { expectedResult } : {}),
248
+ ...(sourceParameterIds.length ? { sourceParameterIds } : {}),
249
+ ...(sourceObjectParameterIds.length ? { sourceObjectParameterIds } : {}),
250
+ ...(Object.keys(sourceRecordedParam).length ? { sourceRecordedParam } : {}),
251
+ ...(Object.keys(sourceRaw).length ? { sourceRaw } : {}),
252
+ };
253
+ // An API step's request + assertions, so a reader sees them and an edit can change them in place.
254
+ if (stepType === 'api' && s?.apiData && typeof s.apiData === 'object' && !Array.isArray(s.apiData)) {
255
+ step.api = JSON.parse(JSON.stringify(s.apiData));
256
+ }
257
+ if (objectId && objectId.toLowerCase() !== 'null') {
258
+ step.objectRef = { id: objectId, ...(objectName ? { name: objectName } : {}) };
259
+ step.sourceObjectId = objectId;
260
+ if (objectName)
261
+ step.sourceObjectName = objectName;
262
+ }
263
+ // Control-flow: keep the RAW SQA kind on controlFlow.kind so the renderer can label it exactly
264
+ // as the UI does. `conditions.ifstring` is the human-readable expression the SQA UI shows in the
265
+ // condition column — carry it into conditionText. SWITCH steps carry the target technology in the
266
+ // raw kind (SWITCH_TO_API / SWITCH_TO_DB / …): losing it on a draft save silently turns the switch
267
+ // into an empty statement, so the API/DB plugin never activates.
268
+ if (stepType === 'control_flow' || stepType === 'function_end' || stepType === 'switch') {
269
+ const conditionText = str(s?.conditions, 'ifstring');
270
+ step.controlFlow = {
271
+ kind: rawStepType === 'FUNCTION_END' ? 'FUNCTION_END' : rawStepType,
272
+ ...(conditionText ? { conditionText } : {}),
273
+ ...(typeof s?.loopDuration === 'number' ? { maxIterations: s.loopDuration } : {}),
274
+ };
275
+ }
276
+ // FUNCTION step — carry every field the ROUND-TRIP save + a human render need. Backend
277
+ // sends functionId as a number, fnVersionId as a string uuid; the neutral surface is string.
278
+ if (stepType === 'function') {
279
+ const fnId = str(s, 'functionId');
280
+ const fnVersion = str(s, 'fnVersionId');
281
+ const sharedProject = str(s, 'sharedFnProjectId');
282
+ const sharedName = str(s, 'sharedFnProjectName');
283
+ if (fnId) {
284
+ step.functionCall = {
285
+ testCaseId: fnId,
286
+ ...(fnVersion ? { versionId: fnVersion } : {}),
287
+ ...(sharedProject ? { sharedProjectId: sharedProject } : {}),
288
+ ...(sharedName ? { testCaseName: sharedName } : {}),
289
+ };
290
+ }
291
+ }
292
+ // Value column: prefer recordedParam summary (concrete values) → falls through to parameterIds
293
+ // which surface as `${name}` tokens in the description already.
294
+ const recordedSummary = formatRecordedParam(s?.recordedParam);
295
+ if (recordedSummary)
296
+ step.value = recordedSummary;
297
+ return step;
298
+ }
299
+ // ---------------------------------------------------------------------------
300
+ // Test cases.
301
+ // `toTestCase` is the projection off the RAW /tm/testcase/getById doc — it
302
+ // reads inline steps as a fallback. `applyCollectionSteps` replaces those with
303
+ // the steps-collection view when that fetch succeeds, matching what the SQA UI
304
+ // + execution + save paths use today.
305
+ // ---------------------------------------------------------------------------
306
+ const TC_PRESERVE_KEYS = ['tags', 'customFields', 'mailersList', 'linkedIssues', 'defectId', 'suiteId'];
307
+ export function toTestCase(doc) {
308
+ const id = str(doc, 'id', '_id', 'testcaseId');
309
+ const execType = str(doc, 'executionType') ?? '';
310
+ const category = execType.toUpperCase() === 'MANUAL' ? 'manual' : 'automated';
311
+ const description = str(doc, 'description');
312
+ const preconditions = str(doc, 'prerequisite', 'preconditions');
313
+ // storyRef + folderOrModule come off SQA as raw ints (userstoryId / moduleId). Project into
314
+ // neutral strings so `tc_automate` (SQA branch) can pre-fill the recording guide.
315
+ const userstoryId = typeof doc?.userstoryId === 'number' && doc.userstoryId > 0
316
+ ? String(doc.userstoryId) : undefined;
317
+ const moduleId = typeof doc?.moduleId === 'number' && doc.moduleId > 0
318
+ ? String(doc.moduleId) : undefined;
319
+ // Inline steps as fallback: prefer manualSteps for manual TCs, else automationSteps.
320
+ const stepsNode = doc?.steps;
321
+ let rawSteps = [];
322
+ if (stepsNode && typeof stepsNode === 'object') {
323
+ if (Array.isArray(stepsNode?.manualSteps) && stepsNode.manualSteps.length)
324
+ rawSteps = stepsNode.manualSteps;
325
+ else if (Array.isArray(stepsNode?.automationSteps))
326
+ rawSteps = stepsNode.automationSteps;
327
+ else if (Array.isArray(stepsNode))
328
+ rawSteps = stepsNode;
329
+ }
330
+ const steps = rawSteps.map((s, i) => fromSqaStep(s, i + 1));
331
+ // Versions: `/tm/testcase/getById` hangs a `versions[]` array on the doc (tcfn.service.js:1489),
332
+ // one entry per non-deleted tcfn_version. Current-version resolution mirrors the FE:
333
+ // `versionId` / `selectedVersionId` on the doc wins, else the doc's `versionsDetails.id`.
334
+ const currentVersionId = str(doc, 'versionId', 'selectedVersionId') ??
335
+ (doc?.versionsDetails && typeof doc.versionsDetails === 'object'
336
+ ? str(doc.versionsDetails, 'id', '_id', 'versionId')
337
+ : undefined);
338
+ const versions = toVersionEntries(Array.isArray(doc?.versions) ? doc.versions : [], currentVersionId);
339
+ const technologyType = str(doc, 'tcType');
340
+ // Raw test-case fields the neutral model has no field for — carried through an edit untouched (see TestCase.sourceTc).
341
+ const sourceTc = {};
342
+ for (const k of TC_PRESERVE_KEYS)
343
+ if (doc?.[k] !== undefined && doc[k] !== null)
344
+ sourceTc[k] = doc[k];
345
+ return {
346
+ ...(id ? { id } : {}),
347
+ title: str(doc, 'name', 'title') ?? '',
348
+ ...(description ? { description } : {}),
349
+ category,
350
+ ...(preconditions ? { preconditions } : {}),
351
+ ...(userstoryId ? { storyRef: userstoryId } : {}),
352
+ ...(moduleId ? { folderOrModule: moduleId } : {}),
353
+ ...(technologyType ? { technologyType } : {}),
354
+ // Retired-by-sync flag. The FULL read must carry it too (the list summary mapper already did):
355
+ // story_sync_testcases reads a test case with getTestCase and skips the already-obsolete ones —
356
+ // without this it re-proposed the same obsolete item on every run.
357
+ ...(typeof doc?.obsolete === 'boolean' ? { obsolete: doc.obsolete } : {}),
358
+ ...(doc?.executionPlatform && typeof doc.executionPlatform === 'object' ? { executionPlatform: doc.executionPlatform } : {}),
359
+ ...(Object.keys(sourceTc).length ? { sourceTc } : {}),
360
+ steps,
361
+ ...(versions.length ? { versions } : {}),
362
+ ...(currentVersionId ? { currentVersionId } : {}),
363
+ ...(typeof doc?.updateVersion === 'number' ? { updateVersion: doc.updateVersion } : {}),
364
+ };
365
+ }
366
+ /** Overwrite `tc.steps` with the mapped collection-endpoint rows when non-empty. */
367
+ export function applyCollectionSteps(tc, rows) {
368
+ if (!Array.isArray(rows) || rows.length === 0)
369
+ return tc;
370
+ const mapped = rows.map((s, i) => fromSqaStep(s, i + 1));
371
+ return { ...tc, steps: mapped };
372
+ }
373
+ // ---------------------------------------------------------------------------
374
+ // Functions (reusable). Same `tcfnObj` collection as TCs — type='FN' instead of 'TC'.
375
+ // Payload shape overlaps with TCs (id/code/name/description/executionType/status), plus
376
+ // `fnType` (WEB/API/ANDROID/IOS) in place of `tcType`.
377
+ // ---------------------------------------------------------------------------
378
+ export function toFunctionSummary(row) {
379
+ const id = str(row, 'id', '_id', 'functionId') ?? '';
380
+ const code = str(row, 'code');
381
+ const name = str(row, 'name', 'title') ?? '';
382
+ const description = str(row, 'description');
383
+ const fnType = str(row, 'fnType', 'tcType');
384
+ const executionType = str(row, 'executionType');
385
+ const status = str(row, 'reviewApproveStatus', 'status');
386
+ const stepCount = typeof row?.stepCount === 'number' ? row.stepCount : undefined;
387
+ return {
388
+ id,
389
+ ...(code ? { code } : {}),
390
+ name,
391
+ ...(description ? { description } : {}),
392
+ ...(fnType ? { fnType } : {}),
393
+ ...(executionType ? { executionType } : {}),
394
+ ...(status ? { status } : {}),
395
+ ...(stepCount !== undefined ? { stepCount } : {}),
396
+ };
397
+ }
398
+ /** Full function doc → neutral QaFunction. Steps are attached separately by the adapter (fetched
399
+ * from /tm/function/steps, same collection endpoint TCs use — just type='FN'). */
400
+ export function toFunction(row) {
401
+ const summary = toFunctionSummary(row);
402
+ return { ...summary, steps: [] };
403
+ }
404
+ export function toTcSummary(row) {
405
+ const id = str(row, 'id', '_id', 'testcaseId') ?? '';
406
+ const code = str(row, 'code');
407
+ const title = str(row, 'name', 'title') ?? '';
408
+ // SQA testcase rows have no priority/status/stepCount columns; do not fabricate defaults.
409
+ const stepCount = typeof row?.stepCount === 'number' ? row.stepCount : undefined;
410
+ const technologyType = str(row, 'tcType');
411
+ const executionType = str(row, 'executionType');
412
+ const obsolete = typeof row?.obsolete === 'boolean' ? row.obsolete : undefined;
413
+ return {
414
+ id,
415
+ ...(code ? { code } : {}),
416
+ title,
417
+ ...(stepCount !== undefined ? { stepCount } : {}),
418
+ ...(technologyType ? { technologyType } : {}),
419
+ ...(executionType ? { executionType } : {}),
420
+ ...(obsolete !== undefined ? { obsolete } : {}),
421
+ };
422
+ }
423
+ // ---------------------------------------------------------------------------
424
+ // Suites.
425
+ // ---------------------------------------------------------------------------
426
+ export function toSuiteSummary(row) {
427
+ const id = str(row, 'id', '_id', 'suiteId') ?? '';
428
+ const name = str(row, 'name', 'suiteName') ?? '';
429
+ const memberCount = Array.isArray(row?.testCases) ? row.testCases.length : undefined;
430
+ const suiteType = str(row, 'suiteType');
431
+ const executionType = str(row, 'lastSelectedExecutionType') ?? str(row, 'executionType');
432
+ return {
433
+ id,
434
+ name,
435
+ ...(memberCount !== undefined ? { memberCount } : {}),
436
+ ...(suiteType ? { suiteType } : {}),
437
+ ...(executionType ? { executionType: executionType.toUpperCase() } : {}),
438
+ };
439
+ }
440
+ export function toSuite(doc) {
441
+ const id = str(doc, 'id', '_id', 'suiteId');
442
+ const description = str(doc, 'description');
443
+ const executionType = (str(doc, 'lastSelectedExecutionType') ?? str(doc, 'executionType'))?.toUpperCase();
444
+ const rawMembers = Array.isArray(doc?.testCases) ? doc.testCases : [];
445
+ const members = rawMembers.map((tc, i) => ({
446
+ tcId: str(tc, 'testcaseId', 'id', '_id') ?? '',
447
+ order: typeof tc?.seq === 'number' ? tc.seq : i + 1,
448
+ }));
449
+ return {
450
+ ...(id ? { id } : {}),
451
+ name: str(doc, 'name', 'suiteName') ?? '',
452
+ ...(description ? { description } : {}),
453
+ ...(executionType ? { executionType } : {}),
454
+ members,
455
+ };
456
+ }
457
+ // ---------------------------------------------------------------------------
458
+ // User stories (`pm/userstory`). Business key comes back as `code` on SQA
459
+ // (US_123 / US-897), so `key` in the neutral shape is populated from `code`.
460
+ // ---------------------------------------------------------------------------
461
+ export function toStorySummary(row) {
462
+ const id = str(row, 'id', '_id', 'userstoryId') ?? '';
463
+ const key = str(row, 'code', 'key', 'userStoryCode');
464
+ const title = str(row, 'name', 'title', 'storyName') ?? '';
465
+ const status = str(row, 'status', 'state');
466
+ const priority = str(row, 'priority');
467
+ return {
468
+ id,
469
+ ...(key ? { key } : {}),
470
+ title,
471
+ ...(status ? { status } : {}),
472
+ ...(priority ? { priority } : {}),
473
+ };
474
+ }
475
+ export function toDefectSummary(row) {
476
+ const id = str(row, 'id', '_id') ?? '';
477
+ const code = str(row, 'code');
478
+ const title = str(row, 'name', 'title') ?? '';
479
+ const state = str(row, 'state', 'status');
480
+ const severity = str(row, 'severity');
481
+ const priority = str(row, 'priority');
482
+ // `ownerId` is an ARRAY on the defect row (a defect can have several assignees) — see
483
+ // defect-interface.ts `ownerId: number[]` — unlike the single-value `ownerId` on stories/testcases.
484
+ const assignedTo = Array.isArray(row?.ownerId)
485
+ ? row.ownerId.map((v) => String(v ?? '')).filter((v) => v.length > 0)
486
+ : undefined;
487
+ const tcIds = Array.isArray(row?.selectedTestCase)
488
+ ? row.selectedTestCase
489
+ .map((tc) => (typeof tc === 'object' ? str(tc, 'testcaseId') : String(tc ?? '')))
490
+ .filter((v) => !!v)
491
+ : undefined;
492
+ return {
493
+ id,
494
+ ...(code ? { code } : {}),
495
+ title,
496
+ ...(state ? { state } : {}),
497
+ ...(severity ? { severity } : {}),
498
+ ...(priority ? { priority } : {}),
499
+ ...(assignedTo?.length ? { assignedTo } : {}),
500
+ ...(tcIds?.length ? { tcIds } : {}),
501
+ };
502
+ }
503
+ /** Maps a `/pm/task/search` row (see `Itask` in sqa-ui) to the neutral shape. `ownerId` is an array
504
+ * on the task row, same as on a defect. */
505
+ export function toTaskSummary(row) {
506
+ const id = str(row, 'id', '_id') ?? '';
507
+ const code = str(row, 'code');
508
+ const title = str(row, 'name', 'title') ?? '';
509
+ const state = str(row, 'state', 'status');
510
+ const priority = str(row, 'priority');
511
+ const assignedTo = Array.isArray(row?.ownerId)
512
+ ? row.ownerId.map((v) => String(v ?? '')).filter((v) => v.length > 0)
513
+ : undefined;
514
+ const defectId = typeof row?.defectId === 'number' && row.defectId > 0 ? String(row.defectId) : undefined;
515
+ return {
516
+ id,
517
+ ...(code ? { code } : {}),
518
+ title,
519
+ ...(state ? { state } : {}),
520
+ ...(priority ? { priority } : {}),
521
+ ...(assignedTo?.length ? { assignedTo } : {}),
522
+ ...(defectId ? { defectId } : {}),
523
+ };
524
+ }
525
+ export function toStory(doc) {
526
+ const base = toStorySummary(doc);
527
+ const description = str(doc, 'description', 'storyDescription');
528
+ // Acceptance criteria: array of blobs/objects, or one HTML/newline string (see the splitter).
529
+ const rawAc = doc?.acceptanceCriteria ?? doc?.acceptance_criteria;
530
+ const ac = splitAcceptanceCriteria(rawAc);
531
+ // Parent + scope links — surfaced so gap_analysis / impact_analysis can walk defect→sprint→release
532
+ // without an extra listStories round-trip. `iterationId` is SQA's server-side sprint column.
533
+ const sprintId = str(doc, 'iterationId');
534
+ const releaseId = str(doc, 'releaseId');
535
+ const epicId = str(doc, 'epicId');
536
+ const featureId = str(doc, 'featureId');
537
+ return {
538
+ ...base,
539
+ ...(description ? { description } : {}),
540
+ ...(ac && ac.length ? { acceptanceCriteria: ac } : {}),
541
+ ...(sprintId ? { sprintId } : {}),
542
+ ...(releaseId ? { releaseId } : {}),
543
+ ...(epicId ? { epicId } : {}),
544
+ ...(featureId ? { featureId } : {}),
545
+ };
546
+ }
547
+ // ---------------------------------------------------------------------------
548
+ // Epics (`pm/epic`) and features (`pm/feature`). Business keys come back as
549
+ // `code` (EP_XXX / FT_XXX); numeric doc id is `id` (with `_id` as fallback).
550
+ // ---------------------------------------------------------------------------
551
+ export function toEpicSummary(row) {
552
+ const id = str(row, 'id', '_id', 'epicId') ?? '';
553
+ const key = str(row, 'code', 'key');
554
+ const name = str(row, 'name', 'epicName') ?? '';
555
+ const state = str(row, 'state', 'status');
556
+ return {
557
+ id,
558
+ ...(key ? { key } : {}),
559
+ name,
560
+ ...(state ? { state } : {}),
561
+ };
562
+ }
563
+ export function toEpic(doc) {
564
+ const base = toEpicSummary(doc);
565
+ const description = str(doc, 'description');
566
+ const plannedStartDate = str(doc, 'plannedStartDate');
567
+ const plannedEndDate = str(doc, 'plannedEndDate');
568
+ const rawEffort = doc?.estimatedEffort;
569
+ const rawOwner = doc?.ownerId;
570
+ return {
571
+ ...base,
572
+ ...(description ? { description } : {}),
573
+ ...(typeof rawEffort === 'number' ? { estimatedEffort: rawEffort } : {}),
574
+ ...(typeof rawOwner === 'number' ? { ownerId: rawOwner } : {}),
575
+ ...(plannedStartDate ? { plannedStartDate } : {}),
576
+ ...(plannedEndDate ? { plannedEndDate } : {}),
577
+ };
578
+ }
579
+ export function toFeatureSummary(row) {
580
+ const id = str(row, 'id', '_id', 'featureId') ?? '';
581
+ const key = str(row, 'code', 'key');
582
+ const name = str(row, 'name', 'featureName') ?? '';
583
+ const state = str(row, 'state', 'status');
584
+ const priority = str(row, 'priority');
585
+ const epicId = str(row, 'epicId');
586
+ return {
587
+ id,
588
+ ...(key ? { key } : {}),
589
+ name,
590
+ ...(state ? { state } : {}),
591
+ ...(priority ? { priority } : {}),
592
+ ...(epicId ? { epicId } : {}),
593
+ };
594
+ }
595
+ export function toFeature(doc) {
596
+ const base = toFeatureSummary(doc);
597
+ const description = str(doc, 'description');
598
+ const plannedStartDate = str(doc, 'plannedStartDate');
599
+ const plannedEndDate = str(doc, 'plannedEndDate');
600
+ const rawEffort = doc?.estimatedEffort;
601
+ const rawOwner = doc?.ownerId;
602
+ return {
603
+ ...base,
604
+ ...(description ? { description } : {}),
605
+ ...(typeof rawEffort === 'number' ? { estimatedEffort: rawEffort } : {}),
606
+ ...(typeof rawOwner === 'number' ? { ownerId: rawOwner } : {}),
607
+ ...(plannedStartDate ? { plannedStartDate } : {}),
608
+ ...(plannedEndDate ? { plannedEndDate } : {}),
609
+ };
610
+ }
611
+ // ---------------------------------------------------------------------------
612
+ // Modules, releases, sprints.
613
+ // ---------------------------------------------------------------------------
614
+ export function toModuleSummary(row) {
615
+ const id = str(row, 'id', 'moduleId', '_id') ?? '';
616
+ const name = str(row, 'name', 'moduleName') ?? '';
617
+ const parentId = str(row, 'parentId', 'parent', 'parentModuleId');
618
+ const isRoot = typeof row?.isRoot === 'boolean' ? row.isRoot : undefined;
619
+ const childIds = Array.isArray(row?.childIds)
620
+ ? row.childIds.filter((n) => Number.isFinite(n))
621
+ : undefined;
622
+ return {
623
+ id,
624
+ name,
625
+ ...(parentId && parentId !== '0' ? { parentId } : {}),
626
+ ...(isRoot !== undefined ? { isRoot } : {}),
627
+ ...(childIds ? { childIds } : {}),
628
+ };
629
+ }
630
+ /** Map the POST /pm/module response to a `ModuleSaved`. Throws when the server accepts the request
631
+ * but hands back no id — that "silent success" is the bug that let broken subtree creates report
632
+ * success. Callers rely on `id` for downstream operations, so anything less is a failure. */
633
+ export function toModuleSaved(raw, requestedName) {
634
+ const doc = (raw?.data ?? raw) ?? {};
635
+ const id = str(doc, 'id', '_id', 'moduleId') ?? '';
636
+ if (!id) {
637
+ throw new Error(`create_module: server returned 2xx but no id for "${requestedName}" — module NOT created`);
638
+ }
639
+ const code = str(doc, 'code');
640
+ const name = str(doc, 'name', 'moduleName') ?? requestedName;
641
+ const parentId = str(doc, 'parentId', 'parent', 'parentModuleId');
642
+ const isRoot = typeof doc?.isRoot === 'boolean' ? doc.isRoot : parentId == null;
643
+ const childIds = Array.isArray(doc?.childIds)
644
+ ? doc.childIds.filter((n) => Number.isFinite(n))
645
+ : undefined;
646
+ return {
647
+ id,
648
+ name,
649
+ isRoot,
650
+ created: true,
651
+ ...(code ? { code } : {}),
652
+ ...(parentId && parentId !== '0' ? { parentId } : {}),
653
+ ...(childIds ? { childIds } : {}),
654
+ };
655
+ }
656
+ export function toReleaseSummary(row) {
657
+ const id = str(row, 'id', '_id', 'releaseId') ?? '';
658
+ const name = str(row, 'name', 'releaseName') ?? '';
659
+ const state = str(row, 'state', 'status');
660
+ const plannedStartDate = str(row, 'plannedStartDate');
661
+ const plannedEndDate = str(row, 'plannedEndDate');
662
+ return {
663
+ id,
664
+ name,
665
+ ...(state ? { state } : {}),
666
+ ...(plannedStartDate ? { plannedStartDate } : {}),
667
+ ...(plannedEndDate ? { plannedEndDate } : {}),
668
+ };
669
+ }
670
+ export function toSprintSummary(row) {
671
+ const id = str(row, 'id', '_id', 'sprintId') ?? '';
672
+ const name = str(row, 'name', 'sprintName') ?? '';
673
+ const releaseId = str(row, 'releaseId');
674
+ const state = str(row, 'state', 'status');
675
+ const plannedStartDate = str(row, 'plannedStartDate');
676
+ const plannedEndDate = str(row, 'plannedEndDate');
677
+ return {
678
+ id,
679
+ name,
680
+ ...(releaseId ? { releaseId } : {}),
681
+ ...(state ? { state } : {}),
682
+ ...(plannedStartDate ? { plannedStartDate } : {}),
683
+ ...(plannedEndDate ? { plannedEndDate } : {}),
684
+ };
685
+ }
686
+ // ---------------------------------------------------------------------------
687
+ // Objects — the shared object (locator) library. `attributes[]` is the SQA
688
+ // wire shape; the neutral QaObject exposes it as `locators`.
689
+ // ---------------------------------------------------------------------------
690
+ /** Stored image refs are `{ url: '/download/recording/.../<file>' }` with no extension and a path
691
+ * relative to the SimplifyQA host; the UI appends `.png`. Return an absolute, loadable URL. */
692
+ export function toImageUrl(ref, baseUrl) {
693
+ const raw = typeof ref === 'string' ? ref : typeof ref?.url === 'string' ? ref.url : '';
694
+ if (!raw.trim())
695
+ return undefined;
696
+ if (/^(data:|blob:)/i.test(raw))
697
+ return raw;
698
+ const withExt = /\.(png|jpe?g|gif|webp)$/i.test(raw) ? raw : `${raw}.png`;
699
+ if (/^https?:\/\//i.test(withExt))
700
+ return withExt;
701
+ if (!baseUrl)
702
+ return withExt;
703
+ return `${baseUrl.replace(/\/+$/, '')}/${withExt.replace(/^\/+/, '')}`;
704
+ }
705
+ export function toObject(doc, baseUrl) {
706
+ const id = str(doc, 'id', '_id');
707
+ const rawAttrs = Array.isArray(doc?.attributes) ? doc.attributes : [];
708
+ const locators = rawAttrs
709
+ .filter((a) => typeof a?.name === 'string' && typeof a?.value === 'string')
710
+ .map((a) => ({
711
+ name: String(a.name),
712
+ value: String(a.value),
713
+ ...(a.unique === true ? { unique: true } : {}),
714
+ }));
715
+ const name = str(doc, 'disname', 'description', 'placeholder') ?? '';
716
+ const objectType = str(doc, 'technology');
717
+ const description = str(doc, 'description');
718
+ const moduleId = doc?.moduleId != null ? String(doc.moduleId) : undefined;
719
+ const parameterIds = Array.isArray(doc?.parameterId)
720
+ ? doc.parameterId.map((p) => String(p)).filter((p) => p && p !== 'null')
721
+ : undefined;
722
+ const thumbnailUrl = toImageUrl(doc?.thumbnail_url, baseUrl);
723
+ const pageScreenshotUrl = toImageUrl(doc?.pageScreenShot_url, baseUrl);
724
+ const objectTemplateId = doc?.objecttemplateId != null
725
+ ? String(doc.objecttemplateId)
726
+ : (doc?.objectTemplateId != null ? String(doc.objectTemplateId) : undefined);
727
+ return {
728
+ ...(id ? { id } : {}),
729
+ name,
730
+ ...(objectType ? { objectType } : {}),
731
+ locators,
732
+ ...(objectTemplateId ? { objectTemplateId } : {}),
733
+ ...(thumbnailUrl ? { thumbnailUrl } : {}),
734
+ ...(pageScreenshotUrl ? { pageScreenshotUrl } : {}),
735
+ ...(description ? { description } : {}),
736
+ ...(moduleId ? { moduleId } : {}),
737
+ ...(parameterIds?.length ? { parameterIds } : {}),
738
+ };
739
+ }
740
+ // ---------------------------------------------------------------------------
741
+ // Write-side helpers. `${name}` token extraction + secret detection + payload
742
+ // builders for POST/PUT /tm/testcase (`testcaseObj`).
743
+ // ---------------------------------------------------------------------------
744
+ // Mirrors the UI's PARAM_TOKEN_RE: SQA parameter names may contain spaces ("prefix value_4").
745
+ const PARAM_TOKEN = /\$\{([^{}]+?)\}/g;
746
+ /** Unique `${name}` tokens in a step description, in first-seen order. */
747
+ export function extractParamNames(description) {
748
+ if (!description)
749
+ return [];
750
+ const seen = [];
751
+ for (const m of description.matchAll(PARAM_TOKEN)) {
752
+ const name = m[1];
753
+ if (!seen.includes(name))
754
+ seen.push(name);
755
+ }
756
+ return seen;
757
+ }
758
+ /** Parameter names referenced INSIDE a DATABASE step's argument value (a filter, query, document, …), as `${name}`
759
+ * or `{{name}}`, in first-seen order. Purely numeric `{{123}}` is an already-bound id, not a name. */
760
+ export function extractValueParamNames(value) {
761
+ if (typeof value !== 'string' || !value)
762
+ return [];
763
+ const seen = [];
764
+ for (const re of [PARAM_TOKEN, /\{\{([^{}]+?)\}\}/g]) {
765
+ for (const m of value.matchAll(re)) {
766
+ const name = m[1].trim();
767
+ if (name && !/^\d+$/.test(name) && !seen.includes(name))
768
+ seen.push(name);
769
+ }
770
+ }
771
+ return seen;
772
+ }
773
+ /** A Runtime (store) parameter's test-data value is its STORAGE KEY: blank means "use the parameter's own name". A
774
+ * placeholder such as `[]` / `{}` / `null` written there by a prompt as an "initial value" would instead make `[]` the
775
+ * key — shared by every store slot that does the same, so one step's empty result overwrites another's data and later
776
+ * reads come back `[]`. Placeholders become blank; a real, deliberate key is kept. */
777
+ export function runtimeSlotValue(value) {
778
+ const v = (value ?? '').trim();
779
+ return /^(\[\s*\]|\{\s*\}|null|undefined|""|'')$/i.test(v) ? '' : (value ?? '');
780
+ }
781
+ /** An API step's request after a parameter replacement: every `{{<oldId>}}` (or `{{<oldName>}}`) becomes the new one and the
782
+ * step's `inputParameters` entry follows, so the request, its input list and `parameterIds` all agree. */
783
+ function swapApiParams(node, swaps) {
784
+ if (!swaps.length)
785
+ return node;
786
+ let json = JSON.stringify(node);
787
+ for (const w of swaps) {
788
+ json = json.split(`{{${w.fromId}}}`).join(`{{${w.toId}}}`).split(`{{${w.from}}}`).join(`{{${w.to}}}`);
789
+ }
790
+ const out = JSON.parse(json);
791
+ if (Array.isArray(out['inputParameters'])) {
792
+ out['inputParameters'] = out['inputParameters'].map((p) => {
793
+ const w = swaps.find((x) => p['id'] === x.fromId);
794
+ return w ? { ...p, id: w.toId, name: w.to } : p;
795
+ });
796
+ }
797
+ return out;
798
+ }
799
+ /** Put the test case's saved tags / custom fields / mailers / linked issues / defects / suites back on an UPDATE payload.
800
+ * The builders start from empty defaults; without this every re-save of an existing test case reset them. A create has no
801
+ * saved copy, so nothing changes there. */
802
+ function withSavedTcFields(tcfnObj, tc) {
803
+ const merged = tc.sourceTc ? { ...tcfnObj, ...tc.sourceTc } : { ...tcfnObj };
804
+ // Neutral fields the caller can legitimately CHANGE (journal_modify set_meta) must win over the
805
+ // copied raw doc — otherwise editing tags/… looks successful but the old value is re-sent.
806
+ if (tc.tags !== undefined)
807
+ merged['tags'] = tc.tags;
808
+ return merged;
809
+ }
810
+ /** Bind the parameters referenced inside a DATABASE step's argument value.
811
+ * The agent only substitutes `{{name}}` there, and only for parameters listed in the step's `parameterizedParamIds`
812
+ * (ParameterizedArgument) — a `${name}` stays literal text, so e.g. a Mongo filter on `…-${suffix}` matched nothing.
813
+ * Rewrites each `${name}` / `{{name}}` whose name resolves to a known parameter into `{{name}}` and returns the ids;
814
+ * unknown names and the argument's own name are left exactly as written. */
815
+ export function bindValueParams(value, paramIdByName, selfName) {
816
+ const ids = [];
817
+ const bind = (whole, raw) => {
818
+ const name = raw.trim();
819
+ const id = /^\d+$/.test(name) || name === selfName ? undefined : paramIdByName.get(name);
820
+ if (id == null)
821
+ return whole;
822
+ if (!ids.includes(id))
823
+ ids.push(id);
824
+ return `{{${name}}}`;
825
+ };
826
+ const out = value
827
+ .replace(/\{\{([^{}]+?)\}\}/g, (w, n) => bind(w, n))
828
+ .replace(/\$\{([^{}]+?)\}/g, (w, n) => bind(w, n));
829
+ return { value: out, ids };
830
+ }
831
+ /** `{{name}}` token used INSIDE an API request object (url / headers / body / auth / query) — the
832
+ * SQA API editor's placeholder syntax, distinct from the `${name}` used in step DESCRIPTIONS.
833
+ * The editor persists these bound to numeric parameter ids as `{{<paramId>}}`. */
834
+ // Must mirror the UI's PARAM_TOKEN_RE: SQA parameter names may contain spaces
835
+ // (e.g. "prefix value_4", "expected partial text_17"). A narrower regex silently
836
+ // leaves those tokens unresolved, so they never become {{<id>}} / inputParameters.
837
+ const API_PARAM_TOKEN = /\{\{([^{}]+?)\}\}/g;
838
+ /**
839
+ * The API-TC assertion editor is keyed by the RESPONSE JSON, not the live request syntax:
840
+ * statusCode / responseTime / responseSize
841
+ * response.<body.path> (body keys are under `response`)
842
+ * <header-name> with `key` (Received Headers tab)
843
+ * MCP callers naturally use `$.body.x` / `$.headers.X-Foo` (the live resolver's syntax), so
844
+ * translate those to the editor shape before persisting. Without this the assertions are stored
845
+ * but the editor's pathValidation cannot map them, making them look missing.
846
+ */
847
+ /**
848
+ * The assertion editor's condition enum is `LESSER_THAN` / `LESSER_THAN_OR_EQUAL_TO`
849
+ * (testcase-management/assertion/assertion.model.ts) — NOT `LESS_THAN`. An assertion persisted with
850
+ * the wrong token renders with a blank condition in the UI (and can look like it was never added),
851
+ * so every common synonym is folded onto the enum on save.
852
+ */
853
+ export function canonicalApiCondition(raw) {
854
+ if (typeof raw !== 'string')
855
+ return raw;
856
+ const k = raw.trim().toUpperCase().replace(/[\s-]+/g, '_');
857
+ const map = {
858
+ LESS_THAN: 'LESSER_THAN',
859
+ LESSER: 'LESSER_THAN',
860
+ LT: 'LESSER_THAN',
861
+ LESS_THAN_OR_EQUAL_TO: 'LESSER_THAN_OR_EQUAL_TO',
862
+ LESS_THAN_OR_EQUALS: 'LESSER_THAN_OR_EQUAL_TO',
863
+ LESSER_THAN_OR_EQUALS: 'LESSER_THAN_OR_EQUAL_TO',
864
+ LTE: 'LESSER_THAN_OR_EQUAL_TO',
865
+ GREATER_THAN_OR_EQUALS: 'GREATER_THAN_OR_EQUAL_TO',
866
+ GTE: 'GREATER_THAN_OR_EQUAL_TO',
867
+ EQUALS_TO: 'EQUALS',
868
+ EQUAL: 'EQUALS',
869
+ NOT_EQUAL: 'NOT_EQUALS',
870
+ NOT_EQUALS_TO: 'NOT_EQUALS',
871
+ NOT_CONTAINS: 'DOES_NOT_CONTAIN',
872
+ IS_EMPTY: 'EQUAL_TO_EMPTY',
873
+ IS_NOT_EMPTY: 'NOT_EMPTY',
874
+ IS_NULL: 'EQUAL_TO_NULL',
875
+ IS_NOT_NULL: 'NOT_EQUAL_TO_NULL',
876
+ };
877
+ return map[k] ?? k;
878
+ }
879
+ /**
880
+ * Fill the API request/document defaults the SQA editor expects. An API step authored by a model
881
+ * (`add_step` with just `{ requestData: { httpData: { url, method } } }`) is otherwise saved with a
882
+ * PARTIAL `apiData`: the API popup then indexes `requestStyle` / `query_params` / `headers` /
883
+ * `authorization` / `body.data` and throws while loading or saving, so its edits never persist and
884
+ * its parameter list never renders. Emitting the full shape keeps every step openable/saveable.
885
+ */
886
+ function normalizeApiDataShape(apiData) {
887
+ if (!apiData || typeof apiData !== 'object' || Array.isArray(apiData))
888
+ return;
889
+ if (typeof apiData['requestStyle'] !== 'string' || !apiData['requestStyle'])
890
+ apiData['requestStyle'] = 'HTTP';
891
+ let requestData = apiData['requestData'];
892
+ if (!requestData || typeof requestData !== 'object' || Array.isArray(requestData)) {
893
+ requestData = {};
894
+ apiData['requestData'] = requestData;
895
+ }
896
+ const rd = requestData;
897
+ if (!rd['grpcData'] || typeof rd['grpcData'] !== 'object' || Array.isArray(rd['grpcData']))
898
+ rd['grpcData'] = {};
899
+ if (apiData['requestStyle'] === 'HTTP') {
900
+ let httpData = rd['httpData'];
901
+ if (!httpData || typeof httpData !== 'object' || Array.isArray(httpData)) {
902
+ httpData = {};
903
+ rd['httpData'] = httpData;
904
+ }
905
+ const h = httpData;
906
+ if (typeof h['url'] !== 'string')
907
+ h['url'] = '';
908
+ if (typeof h['method'] !== 'string' || !h['method'])
909
+ h['method'] = 'GET';
910
+ if (!Array.isArray(h['query_params']))
911
+ h['query_params'] = [];
912
+ if (!Array.isArray(h['path_params']))
913
+ h['path_params'] = [];
914
+ if (!Array.isArray(h['headers']))
915
+ h['headers'] = [];
916
+ if (!h['authorization'] || typeof h['authorization'] !== 'object' || Array.isArray(h['authorization'])) {
917
+ h['authorization'] = {
918
+ type: 'NO_AUTHORIZATION',
919
+ bearerToken: { value: '' },
920
+ apiKey: { key: '', value: '', type: 'REQUEST_HEADER' },
921
+ basicAuth: { username: '', password: '' },
922
+ };
923
+ }
924
+ if (!h['body'] || typeof h['body'] !== 'object' || Array.isArray(h['body'])) {
925
+ h['body'] = {
926
+ type: 'NONE',
927
+ data: {
928
+ payload: '',
929
+ graphqlVariables: '',
930
+ FORM_DATA: [{ key: '', value: '', description: '', active: false, formDataKey: 'TEXT' }],
931
+ X_WWW_FORM_URLENCODED: [{ key: '', value: '', description: '', active: false }],
932
+ },
933
+ };
934
+ }
935
+ }
936
+ if (!Array.isArray(apiData['inputParameters']))
937
+ apiData['inputParameters'] = [];
938
+ if (!Array.isArray(apiData['responseParameters']))
939
+ apiData['responseParameters'] = [];
940
+ if (!Array.isArray(apiData['assertions']))
941
+ apiData['assertions'] = [];
942
+ }
943
+ function normalizeApiAssertions(raw) {
944
+ if (!Array.isArray(raw))
945
+ return [];
946
+ const special = new Set(['statusCode', 'responseTime', 'responseSize', 'responseBody']);
947
+ const lastSegment = (path) => {
948
+ const noIndex = path.replace(/\[[^\]]*\]/g, '');
949
+ const parts = noIndex.split('.').filter(Boolean);
950
+ return parts[parts.length - 1] ?? path;
951
+ };
952
+ return raw.map((entry) => {
953
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
954
+ return entry;
955
+ const o = { ...entry };
956
+ const rawPath = typeof o['path'] === 'string' ? o['path'].trim() : '';
957
+ const explicitKey = typeof o['key'] === 'string' ? o['key'].trim() : '';
958
+ let path = rawPath;
959
+ let key = explicitKey;
960
+ if (special.has(rawPath)) {
961
+ key = explicitKey || rawPath;
962
+ }
963
+ else if (rawPath.startsWith('$.headers.')) {
964
+ // The execution plugin resolves headers from `responseHeaders.<name>` (Constants.RESPONSE_HEADERKEY).
965
+ key = rawPath.slice('$.headers.'.length).trim();
966
+ path = `responseHeaders.${key}`;
967
+ }
968
+ else if (rawPath.startsWith('response.')) {
969
+ key = explicitKey || lastSegment(rawPath.slice('response.'.length));
970
+ }
971
+ else if (rawPath.startsWith('$.body.')) {
972
+ const rest = rawPath.slice('$.body.'.length);
973
+ path = `response.${rest}`;
974
+ key = explicitKey || lastSegment(rest);
975
+ }
976
+ else if (rawPath.startsWith('$.')) {
977
+ const rest = rawPath.slice(2);
978
+ path = `response.${rest}`;
979
+ key = explicitKey || lastSegment(rest);
980
+ }
981
+ else if (rawPath.startsWith('responseHeaders.')) {
982
+ // Already in the saved shape — leave it (re-normalizing would double the prefix on every re-save).
983
+ key = explicitKey || rawPath.slice('responseHeaders.'.length);
984
+ }
985
+ else if (explicitKey) {
986
+ // Header-style assertion supplied as { key, path }.
987
+ path = rawPath ? `responseHeaders.${rawPath}` : `responseHeaders.${explicitKey}`;
988
+ }
989
+ else {
990
+ path = `response.${rawPath}`;
991
+ key = lastSegment(rawPath);
992
+ }
993
+ return {
994
+ ...o,
995
+ path,
996
+ ...(key ? { key } : {}),
997
+ ...(o['condition'] !== undefined ? { condition: canonicalApiCondition(o['condition']) } : {}),
998
+ ...(o['caseSensitive'] === undefined ? { caseSensitive: false } : {}),
999
+ };
1000
+ });
1001
+ }
1002
+ /** Recursively collect unique `{{name}}` tokens from every string in an API request object. */
1003
+ export function extractApiParamNames(node, out = []) {
1004
+ if (typeof node === 'string') {
1005
+ for (const m of node.matchAll(API_PARAM_TOKEN)) {
1006
+ const name = m[1];
1007
+ if (!out.includes(name))
1008
+ out.push(name);
1009
+ }
1010
+ }
1011
+ else if (Array.isArray(node)) {
1012
+ for (const v of node)
1013
+ extractApiParamNames(v, out);
1014
+ }
1015
+ else if (node && typeof node === 'object') {
1016
+ for (const v of Object.values(node))
1017
+ extractApiParamNames(v, out);
1018
+ }
1019
+ return out;
1020
+ }
1021
+ /** Map a `body.type` to the editor's `lastActiveTab.subTab` (mirrors apiImport.service.js). */
1022
+ const API_BODY_SUBTAB = {
1023
+ JSON: 'JSON', FORM_DATA: 'FORM_DATA', X_WWW_FORM_URLENCODED: 'X_WWW_FORM_URLENCODED',
1024
+ TEXT: 'TEXT', XML: 'XML', GRAPHQL: 'GRAPHQL',
1025
+ };
1026
+ /**
1027
+ * Deep-clone an API request object, rewriting each `{{name}}` token whose name was resolved to a
1028
+ * parameter into `{{<paramId>}}` — the exact form the SQA UI/Postman importer persists. An
1029
+ * unresolvable token is left untouched (better to surface it than to silently drop the request).
1030
+ * Collects the ordered unique `{id,name}` pairs substituted (drives `parameterIds` +
1031
+ * `apiData.inputParameters`).
1032
+ */
1033
+ function substituteApiParams(node, paramIdByName, params) {
1034
+ if (typeof node === 'string') {
1035
+ return node.replace(API_PARAM_TOKEN, (whole, name) => {
1036
+ const id = paramIdByName.get(name);
1037
+ if (id == null)
1038
+ return whole;
1039
+ if (!params.some((p) => p.id === id))
1040
+ params.push({ id, name });
1041
+ return `{{${id}}}`;
1042
+ });
1043
+ }
1044
+ if (Array.isArray(node))
1045
+ return node.map((v) => substituteApiParams(v, paramIdByName, params));
1046
+ if (node && typeof node === 'object') {
1047
+ const out = {};
1048
+ for (const [k, v] of Object.entries(node)) {
1049
+ out[k] = substituteApiParams(v, paramIdByName, params);
1050
+ }
1051
+ return out;
1052
+ }
1053
+ return node;
1054
+ }
1055
+ /** `body.type` of an API request object, or undefined when absent (→ lastActiveTab.subTab NONE). */
1056
+ function apiBodyType(apiData) {
1057
+ const httpData = apiData['requestData']?.['httpData'];
1058
+ const body = httpData?.['body'];
1059
+ const type = body?.['type'];
1060
+ return typeof type === 'string' ? type : undefined;
1061
+ }
1062
+ /** Auto-mask heuristic: names containing password/secret/token/apikey/auth/credential get
1063
+ * `protected:true` on parameter creation. A missed real secret is worse than a false positive
1064
+ * the user can uncheck in the UI. */
1065
+ export function looksSensitive(name) {
1066
+ if (!name)
1067
+ return false;
1068
+ const n = name.toLowerCase();
1069
+ return n.includes('password') || n.includes('passwd') || n.includes('secret')
1070
+ || n.includes('token') || n.includes('apikey') || n.includes('api_key')
1071
+ || n.includes('auth') || n.includes('credential')
1072
+ || n.includes('confirm') || n.includes('retype') || n.includes('reenter')
1073
+ || n.includes('re-enter') || n.includes('repeat') || n.includes('pwd');
1074
+ }
1075
+ /** Pick a default value for a param: `tc.data[name]` wins; else the step's own `value`; else "". */
1076
+ export function paramDefault(name, data, stepValue) {
1077
+ if (data && Object.prototype.hasOwnProperty.call(data, name))
1078
+ return String(data[name] ?? '');
1079
+ return stepValue ?? '';
1080
+ }
1081
+ /** Neutral Step.stepType → SQA `technologyType` on the step + `tcType` on the TC.
1082
+ * Exported so the adapter's per-step resolver keys the action catalog by the same technology
1083
+ * labels the mapper writes into the step. */
1084
+ export const TECH_BY_STEPTYPE = {
1085
+ web: 'WEB',
1086
+ android: 'ANDROID',
1087
+ ios: 'IOS',
1088
+ api: 'API',
1089
+ database: 'DATABASE',
1090
+ mainframe: 'MAINFRAME',
1091
+ desktop: 'DESKTOP',
1092
+ sap: 'SAP',
1093
+ };
1094
+ /**
1095
+ * True when a neutral `stepType: 'api'` step is a real API REQUEST (it carries an `api` payload),
1096
+ * as opposed to an API-TECHNOLOGY step that uses a generic action (e.g. "Store from JSON" —
1097
+ * `actionId: 140`, `stepType: 'API'`, no `apiData`). The backend stores both under `stepType: 'API'`
1098
+ * + `technologyType: 'API'`, so the request payload — not the step/technology type — is what tells
1099
+ * them apart. Getting this wrong saves a generic action step as an action-less API step (its action
1100
+ * and parameters vanish) and turns it into an empty API request.
1101
+ */
1102
+ export function isApiRequestStep(s) {
1103
+ if (s.stepType !== 'api')
1104
+ return false;
1105
+ const isRequest = (v) => {
1106
+ if (!v || typeof v !== 'object' || Array.isArray(v))
1107
+ return false;
1108
+ const o = v;
1109
+ return o['requestData'] !== undefined || o['requestStyle'] !== undefined;
1110
+ };
1111
+ const raw = s.sourceRaw && typeof s.sourceRaw === 'object' ? s.sourceRaw : undefined;
1112
+ return isRequest(s.api) || isRequest(raw?.['apiData']);
1113
+ }
1114
+ /** Technologies that don't bind a real device/browser at save time — the backend defaults
1115
+ * executionPlatform for them (or ignores it). Keeps the WEB-only guard below from firing on
1116
+ * tcTypes where there's nothing to default. */
1117
+ const NO_PLATFORM_TECHS = new Set(['API', 'DATABASE', 'MAINFRAME', 'DESKTOP', 'SAP']);
1118
+ /** Pick the tcType from the first step whose stepType we recognize as an automation technology.
1119
+ * Falls back to WEB — matches the SQA UI's default when the user starts a fresh automation TC. */
1120
+ export function deriveTcType(tc) {
1121
+ // A saved test case already has its type; recomputing it from the first step mis-types a mixed one (API then DB).
1122
+ if (tc.technologyType)
1123
+ return tc.technologyType.toUpperCase();
1124
+ for (const s of tc.steps ?? []) {
1125
+ // A step may carry its technology explicitly. Function-call steps do: their technology is the
1126
+ // FUNCTION's own (WEB/API/ANDROID/IOS/…), resolved from the function catalog at save time —
1127
+ // a function call has no technology of its own to read from `stepType`.
1128
+ const stepTech = s.technologyType;
1129
+ if (stepTech)
1130
+ return stepTech.toUpperCase();
1131
+ const tech = TECH_BY_STEPTYPE[s.stepType];
1132
+ if (tech)
1133
+ return tech;
1134
+ }
1135
+ // Refuse to guess: an all-function test case whose functions could not be resolved used to be
1136
+ // silently saved as WEB, so an API/Android/iOS function suite became a browser test case.
1137
+ const steps = tc.steps ?? [];
1138
+ const onlyFunctions = steps.length > 0
1139
+ && steps.every((s) => s.stepType === 'function' || s.stepType === 'function_end');
1140
+ if (onlyFunctions) {
1141
+ throw new Error('This test case is built only from function calls, so its technology is the functions\' own. ' +
1142
+ 'Pass `technologyType` (WEB | API | ANDROID | IOS | DATABASE | MAINFRAME | DESKTOP | SAP) on the draft, ' +
1143
+ 'or save it while the function catalog is reachable so it can be resolved from the functions\' fnType. ' +
1144
+ 'Saving it as WEB would run a non-web suite through the browser runner.');
1145
+ }
1146
+ return 'WEB';
1147
+ }
1148
+ /** SQA-empty `mailersList` shape — the frontend and joi validator expect the three arrays, not
1149
+ * a bare `{}`. Verified against the real create payload for TC-584. */
1150
+ const EMPTY_MAILERS = { users: [], nonUsers: [], groups: [] };
1151
+ /** Locate the version entry the neutral TestCase currently points at, so update payloads carry
1152
+ * the REAL versionId (not `''`, which the backend interprets as "create a new version" —
1153
+ * see tcfn.service.js:233 — and produces the empty-steps-after-save symptom). Returns an empty
1154
+ * object when unresolved; callers then fall back to `id:''` (correct for CREATE). */
1155
+ function currentVersionFor(tc) {
1156
+ const id = tc.currentVersionId;
1157
+ if (!id || !Array.isArray(tc.versions))
1158
+ return {};
1159
+ const v = tc.versions.find((entry) => entry.id === id);
1160
+ return v ? { id: v.id, name: v.name, ...(typeof v.updateVersion === 'number' ? { updateVersion: v.updateVersion } : {}) } : {};
1161
+ }
1162
+ /**
1163
+ * Assemble the `testcaseObj` payload for POST/PUT /tm/testcase (multipart). Branches on
1164
+ * `tc.category`: manual → `steps.manualSteps` (legacy behavior), automated → `steps.automationSteps`
1165
+ * with resolved actionId/objectId/parameterIds. See `buildManualPayload` and
1166
+ * `buildAutomationPayload` below for the per-branch shapes; both share the wrapper.
1167
+ */
1168
+ export function buildTestcasePayload(inputs) {
1169
+ return inputs.tc.category === 'automated'
1170
+ ? buildAutomationPayload(inputs)
1171
+ : buildManualPayload(inputs);
1172
+ }
1173
+ /**
1174
+ * Manual TC payload. Mirrors Java's `buildTestcasePayload` exactly on wire shape:
1175
+ * - `tcfnObj` — TC-level meta. `deleted` is required on UPDATE and rejected on CREATE.
1176
+ * - `versionsDetails` — a minimal `{name:'v1.0', id:''}` stub matches what the SQA UI sends
1177
+ * for a fresh TC; UPDATE also carries `deleted:false` because the validator requires it.
1178
+ * - `steps.manualSteps` — one entry per neutral step; `automationSteps` is emitted empty.
1179
+ * - Every step gets `parameterIds[]` for the `${name}` tokens in its description.
1180
+ */
1181
+ function buildManualPayload(inputs) {
1182
+ const { projectId, moduleId, userstoryId, existingId, tc, paramIdByName } = inputs;
1183
+ // ponytail: emit the same field set as the SQA UI payload, always — validators + $set on the
1184
+ // backend depend on presence, even for empty defaults. Loader-mutator-saver semantics.
1185
+ const tcfnObj = {
1186
+ ...(existingId ? { id: Number.parseInt(existingId, 10) } : {}),
1187
+ name: tc.title ?? '',
1188
+ userstoryId: userstoryId ?? null,
1189
+ defectId: [],
1190
+ suiteId: [],
1191
+ description: stripParamTokens(normalizeParamTokens(tc.description ?? '') ?? '') ?? '',
1192
+ projectId,
1193
+ tcType: 'WEB',
1194
+ executionType: 'MANUAL',
1195
+ // Round-trip the flag: an edit/re-save must never silently RESET `obsolete` to false (that used to
1196
+ // revive a TC the story sync had retired). Revival is explicit: set_meta { obsolete: false }.
1197
+ obsolete: tc.obsolete === true,
1198
+ linkedIssues: [],
1199
+ moduleId,
1200
+ prerequisite: stripParamTokens(normalizeParamTokens(tc.preconditions ?? '') ?? '') ?? '',
1201
+ customFields: {},
1202
+ tags: [],
1203
+ mailersList: EMPTY_MAILERS,
1204
+ updateVersion: tc.updateVersion ?? 0,
1205
+ ...(existingId ? { deleted: false } : {}),
1206
+ };
1207
+ // On UPDATE, use the CURRENT version's real id/name/updateVersion so the backend updates
1208
+ // that version row instead of minting a new one (empty `id` triggers create at tcfn.service.js:233).
1209
+ const curVer = existingId ? currentVersionFor(tc) : {};
1210
+ const versionsDetails = {
1211
+ name: curVer.name ?? 'v1.0',
1212
+ id: curVer.id ?? '',
1213
+ syncONOFF: '',
1214
+ manualStepsTopreview: false,
1215
+ updateVersion: curVer.updateVersion ?? 0,
1216
+ executionType: 'MANUAL',
1217
+ reviewApproveStatus: '',
1218
+ functionProjectIds: [projectId],
1219
+ ...(existingId ? { deleted: false } : {}),
1220
+ };
1221
+ const manualSteps = [];
1222
+ const steps = Array.isArray(tc.steps) ? tc.steps : [];
1223
+ steps.forEach((s, i) => {
1224
+ // `${{name}}` (API-style) must never reach the product: it renders literally and never binds
1225
+ // a parameter. Normalise to the product's `${name}` form first, THEN strip the braces for the
1226
+ // manual prose (a human reads/executes these) — the parameter binding is carried separately.
1227
+ const descRaw = normalizeParamTokens(s.description ?? '') ?? '';
1228
+ const desc = stripParamTokens(descRaw) ?? '';
1229
+ const expected = stripParamTokens(normalizeParamTokens(s.expectedResult ?? '') ?? '') ?? '';
1230
+ const paramIds = [];
1231
+ const recordedParam = {};
1232
+ for (const name of extractParamNames(descRaw)) {
1233
+ const id = paramIdByName.get(name);
1234
+ if (id == null)
1235
+ continue;
1236
+ paramIds.push(id);
1237
+ recordedParam[String(id)] = paramDefault(name, tc.data, undefined);
1238
+ }
1239
+ // Round-trip: a HYDRATED step keeps its backend parameterIds even when the prose no longer
1240
+ // carries ${tokens} (the manual mapper strips them for readability). Without this, re-saving a
1241
+ // loaded manual TC — e.g. saving an updated VERSION — silently drops every parameter binding and
1242
+ // its test data (the new version's iteration came out empty).
1243
+ if (paramIds.length === 0) {
1244
+ for (const id of (s.sourceParameterIds ?? [])) {
1245
+ if (typeof id === 'number' && Number.isFinite(id) && !paramIds.includes(id))
1246
+ paramIds.push(id);
1247
+ }
1248
+ for (const [k, v] of Object.entries(s.sourceRecordedParam ?? {})) {
1249
+ if (recordedParam[k] == null)
1250
+ recordedParam[k] = String(v);
1251
+ }
1252
+ }
1253
+ const rawSlaManual = s.sourceRaw?.['stepLevelActions'] ?? {};
1254
+ const step = {
1255
+ // ponytail: `deleted` is required on UPDATE and REJECTED on CREATE by the backend validator
1256
+ // (steps.manualSteps[*].deleted) — emit it only when updating, mirroring tcfnObj above.
1257
+ ...(existingId ? { deleted: false } : {}),
1258
+ // ponytail: pass through the backend step uuid on round-trip. Missing `id` sends every step
1259
+ // down the backend's CREATE branch (tcfn.service.js:355), which mints a fresh uuid and
1260
+ // orphans the original row — duplication instead of update.
1261
+ ...(s.sourceId ? { id: s.sourceId } : {}),
1262
+ // ponytail: same rationale as buildAutomationPayload — parentId + versionId are part of the
1263
+ // update filter at tcfn.service.js:406; omitting them causes the upsert to insert an orphan.
1264
+ ...(existingId ? { parentId: Number.parseInt(existingId, 10) } : {}),
1265
+ ...(existingId && curVer.id ? { versionId: curVer.id } : {}),
1266
+ projectId,
1267
+ moduleId,
1268
+ type: 'TC',
1269
+ stepType: 'NORMAL_STATEMENT',
1270
+ seq: i + 1,
1271
+ description: desc,
1272
+ expectedResult: expected,
1273
+ executionType: 'MANUAL',
1274
+ // Step-level flags (skip / capture screenshot / continue-on-failure) are valid on MANUAL
1275
+ // steps too — the validators allow the field. Without this, enabling Skip on a manual TC
1276
+ // looked successful but was silently dropped on save.
1277
+ stepLevelActions: {
1278
+ ...rawSlaManual,
1279
+ skip: s.flags?.skip ?? rawSlaManual['skip'] ?? false,
1280
+ captureScreenshot: s.flags?.screenshot ?? rawSlaManual['captureScreenshot'] ?? false,
1281
+ continueOnFailure: s.flags?.continueOnFailure ?? rawSlaManual['continueOnFailure'] ?? false,
1282
+ skippedReport: rawSlaManual['skippedReport'] ?? false,
1283
+ },
1284
+ // ponytail: always emit — matches UI payload shape. UI sends `[]`/`{}` on every step, backend
1285
+ // joi validators + $set semantics assume presence.
1286
+ parameterIds: paramIds,
1287
+ recordedParam,
1288
+ };
1289
+ manualSteps.push(step);
1290
+ });
1291
+ return {
1292
+ tcfnObj: withSavedTcFields(tcfnObj, tc),
1293
+ versionsDetails,
1294
+ steps: { automationSteps: [], manualSteps },
1295
+ operation: 'TC',
1296
+ type: 'TC',
1297
+ };
1298
+ }
1299
+ /**
1300
+ * Automation TC payload. Mirrors the shape observed on a saved SQA automation TC (TC-584, WEB +
1301
+ * ANDROID validation samples):
1302
+ * - `tcfnObj.executionType: 'AUTOMATION'` + `originalExecutinType: 'AUTOMATION'`.
1303
+ * - `tcfnObj.tcType` derived from the first automation step's `stepType` (web / android / …).
1304
+ * - `tcfnObj.executionPlatform` — WEB defaults to Chrome server-side (omitted here), non-WEB
1305
+ * REQUIRES `tc.executionPlatform` from the caller (device serial + name).
1306
+ * - `steps.automationSteps[]` — one entry per neutral step. Each carries the resolved
1307
+ * `actionId` (numeric FK to the SQA `action` collection) + `objectId` (numeric FK to the
1308
+ * shared `object` collection, or null when the action doesn't need one) + `parameterIds` +
1309
+ * `recordedParam:{<id>:value}` (drives the default iteration on save).
1310
+ * - Always-present step defaults (`conditions`, `loop`, `stepLevelActions`, `attachments`)
1311
+ * are emitted every time — the joi validator + backend read these unconditionally on
1312
+ * execution, and the sample confirms they're present on simple straight-line steps too.
1313
+ *
1314
+ * Straight-line only in this cut — FUNCTION / IF / FOR / WHILE / API / SWITCH are ponytail-
1315
+ * deferred to a follow-up (need a real control-flow sample to validate the `conditions.children[]`
1316
+ * shape end-to-end).
1317
+ */
1318
+ function buildAutomationPayload(inputs) {
1319
+ const { projectId, moduleId, userstoryId, existingId, tc, paramIdByName, stepResolutions, paramAccessById } = inputs;
1320
+ const tcType = deriveTcType(tc);
1321
+ // WEB: backend auto-defaults executionPlatform to Chrome (tcfn.service.js:206-213), so omit
1322
+ // when the caller didn't supply one. API / MAINFRAME / DATABASE / DESKTOP / SAP: no device/
1323
+ // browser to bind — synthesize a flat executionPlatform so the save goes through (matches the
1324
+ // special-case already used in adapter.ts:2956 for suite entries). Only ANDROID / IOS actually
1325
+ // need the caller to pick a device — but on UPDATE the backend already has the platform stored,
1326
+ // so omitting it is safe; throwing here would make journal_modify (editStepsDirect → updateTestCase)
1327
+ // fail for every Android/iOS TC whose getById response doesn't echo executionPlatform.
1328
+ if (tcType !== 'WEB' && !tc.executionPlatform) {
1329
+ if (NO_PLATFORM_TECHS.has(tcType)) {
1330
+ tc.executionPlatform = { id: tcType, name: tcType, technologyType: tcType, type: 'NONE' };
1331
+ }
1332
+ else if (!existingId) {
1333
+ throw new Error(`Automation TC "${tc.title}" needs \`executionPlatform\` for tcType=${tcType} — set ` +
1334
+ `tc.executionPlatform:{id:<deviceSerial>, name, technologyType:'${tcType}', type:'REAL_DEVICE'|'CLOUD_DEVICE'}. ` +
1335
+ `For Android, call mobile_list_devices to see the available devices.`);
1336
+ }
1337
+ // UPDATE without executionPlatform: omit from payload — backend preserves the stored value.
1338
+ }
1339
+ // ponytail: mirror the real UI payload field-for-field (see the working PUT captured on 2026-09-17
1340
+ // for TC-635). Loader-mutator-saver semantics — always emit, empty defaults included.
1341
+ const tcfnObj = {
1342
+ ...(existingId ? { id: Number.parseInt(existingId, 10) } : {}),
1343
+ name: tc.title ?? '',
1344
+ userstoryId: userstoryId ?? null,
1345
+ defectId: [],
1346
+ suiteId: [],
1347
+ description: normalizeParamTokens(tc.description ?? '') ?? '',
1348
+ projectId,
1349
+ tcType,
1350
+ executionType: 'AUTOMATION',
1351
+ obsolete: tc.obsolete === true,
1352
+ linkedIssues: [],
1353
+ moduleId,
1354
+ prerequisite: normalizeParamTokens(tc.preconditions ?? '') ?? '',
1355
+ customFields: {},
1356
+ tags: [],
1357
+ mailersList: EMPTY_MAILERS,
1358
+ originalExecutinType: 'AUTOMATION',
1359
+ updateVersion: tc.updateVersion ?? 0,
1360
+ ...(existingId ? { deleted: false } : {}),
1361
+ ...(tc.executionPlatform ? { executionPlatform: tc.executionPlatform } : {}),
1362
+ };
1363
+ // On UPDATE, use the CURRENT version's real id/name/updateVersion so the backend updates
1364
+ // that version row instead of minting a new one (empty `id` triggers create at tcfn.service.js:233,
1365
+ // which orphans all saved steps under a fresh version and leaves the UI's view empty).
1366
+ const curVer = existingId ? currentVersionFor(tc) : {};
1367
+ const versionsDetails = {
1368
+ name: curVer.name ?? 'v1.0',
1369
+ id: curVer.id ?? '',
1370
+ syncONOFF: '',
1371
+ manualStepsTopreview: false,
1372
+ updateVersion: curVer.updateVersion ?? 0,
1373
+ executionType: 'AUTOMATION',
1374
+ reviewApproveStatus: '',
1375
+ functionProjectIds: [projectId],
1376
+ ...(existingId ? { deleted: false } : {}),
1377
+ };
1378
+ const automationSteps = [];
1379
+ const steps = Array.isArray(tc.steps) ? tc.steps : [];
1380
+ steps.forEach((s, i) => {
1381
+ const desc = s.description ?? '';
1382
+ const technologyType = TECH_BY_STEPTYPE[s.stepType] ?? tcType;
1383
+ const resolution = stepResolutions?.[i];
1384
+ // ponytail: control-flow / function / switch / manual steps have a null-actionId slot from
1385
+ // resolveAutomationSteps — they don't need action resolution to be valid.
1386
+ const isControlFlow = s.stepType === 'control_flow' || s.stepType === 'function' || s.stepType === 'function_end' || s.stepType === 'switch' || s.stepType === 'manual';
1387
+ if (!isControlFlow && !resolution) {
1388
+ throw new Error(`Automation TC "${tc.title}" step ${i + 1}: missing action resolution — the adapter did ` +
1389
+ 'not resolve `actionId` for this step. Check that the neutral Step.actionType maps to a ' +
1390
+ 'known SQA action for this technology.');
1391
+ }
1392
+ // parameterIds + recordedParam resolution order:
1393
+ // 1. Seed from backend-preserved sourceParameterIds / sourceRecordedParam (round-trip
1394
+ // intact — a save that doesn't touch anything re-emits the same values).
1395
+ // 2. Description ${tokens}: register the param id + a DEFAULT value from tc.data. Never
1396
+ // overrides an already-seeded id — a token default must not wipe a real recorded value.
1397
+ // 3. LLM patches (s.recordedParam, name-keyed): resolve name → id and OVERRIDE. This is
1398
+ // how "change the URL parameter to X" via tc_draft_update flows through to the wire.
1399
+ const paramIds = [...(s.sourceParameterIds ?? [])];
1400
+ const seenIds = new Set(paramIds);
1401
+ const recordedParamOut = { ...(s.sourceRecordedParam ?? {}) };
1402
+ const registerId = (id) => {
1403
+ if (!seenIds.has(id)) {
1404
+ paramIds.push(id);
1405
+ seenIds.add(id);
1406
+ }
1407
+ };
1408
+ const setValue = (id, value, override) => {
1409
+ const key = String(id);
1410
+ if (override || !(key in recordedParamOut))
1411
+ recordedParamOut[key] = value;
1412
+ };
1413
+ const seenNames = new Set();
1414
+ const addByName = (name, value, override) => {
1415
+ if (seenNames.has(name))
1416
+ return;
1417
+ seenNames.add(name);
1418
+ // A purely-numeric key is an ALREADY-BOUND parameter ID, not a parameter name. A step that was
1419
+ // read from the backend and re-added (or patched) carries `recordedParam: {"7001": "sub_ln"}`;
1420
+ // looking that up as a name would bind a different parameter literally called "7001" (and the
1421
+ // save path used to CREATE one). Bind the id the user already had.
1422
+ if (/^\d+$/.test(name)) {
1423
+ const id = Number.parseInt(name, 10);
1424
+ if (Number.isFinite(id)) {
1425
+ registerId(id);
1426
+ if (value !== undefined)
1427
+ setValue(id, value, override);
1428
+ }
1429
+ return;
1430
+ }
1431
+ const id = paramIdByName.get(name);
1432
+ if (id == null)
1433
+ return;
1434
+ registerId(id);
1435
+ if (value !== undefined)
1436
+ setValue(id, value, override);
1437
+ };
1438
+ // Replace-a-parameter edits (swapParams) run FIRST, on the seeded (saved) bindings: the new parameter takes the OLD
1439
+ // one's slot — appending it would leave the old parameter in the action's argument slot — and the old one's value,
1440
+ // description token, `{{name}}` references and parameterized id all follow. Idempotent: a step that already uses
1441
+ // `to` and no longer `from` is left alone.
1442
+ let descNow = desc;
1443
+ let patchRecorded = s.recordedParam;
1444
+ const srcRaw = (s.sourceRaw ?? {});
1445
+ const swappedParameterized = Array.isArray(srcRaw['parameterizedParamIds'])
1446
+ ? [...srcRaw['parameterizedParamIds']] : [];
1447
+ const swapsApplied = [];
1448
+ const swapText = (text, from, to) => text.split('${' + from + '}').join('${' + to + '}').split('{{' + from + '}}').join('{{' + to + '}}');
1449
+ for (const sw of s.swapParams ?? []) {
1450
+ const fromId = paramIdByName.get(sw.from);
1451
+ const toId = paramIdByName.get(sw.to);
1452
+ if (fromId == null || toId == null) {
1453
+ throw new Error(`Step ${i + 1}: cannot replace parameter "${sw.from}" with "${sw.to}" — ${fromId == null ? sw.from : sw.to} is not a known parameter.`);
1454
+ }
1455
+ if (fromId === toId)
1456
+ continue;
1457
+ const at = paramIds.indexOf(fromId);
1458
+ const usesInApi = JSON.stringify(s.api ?? srcRaw['apiData'] ?? {}).includes(`{{${fromId}}}`);
1459
+ if (at < 0 && !usesInApi && !swappedParameterized.includes(fromId)) {
1460
+ if (paramIds.includes(toId) || swappedParameterized.includes(toId))
1461
+ continue; // already swapped
1462
+ throw new Error(`Step ${i + 1} does not use parameter "${sw.from}", so it cannot be replaced with "${sw.to}".`);
1463
+ }
1464
+ if (at >= 0) {
1465
+ if (paramIds.includes(toId))
1466
+ paramIds.splice(at, 1);
1467
+ else
1468
+ paramIds[at] = toId;
1469
+ seenIds.delete(fromId);
1470
+ seenIds.add(toId);
1471
+ delete recordedParamOut[String(fromId)];
1472
+ recordedParamOut[String(toId)] = sw.value ?? tc.data?.[sw.to] ?? '';
1473
+ }
1474
+ const k = swappedParameterized.indexOf(fromId);
1475
+ if (k >= 0)
1476
+ swappedParameterized[k] = toId;
1477
+ descNow = swapText(descNow, sw.from, sw.to);
1478
+ if (patchRecorded) {
1479
+ patchRecorded = Object.fromEntries(Object.entries(patchRecorded).map(([n, v]) => [n, typeof v === 'string' ? swapText(v, sw.from, sw.to) : v]));
1480
+ }
1481
+ swapsApplied.push({ fromId, toId, from: sw.from, to: sw.to });
1482
+ }
1483
+ // Description tokens seed defaults but don't override
1484
+ for (const name of extractParamNames(descNow))
1485
+ addByName(name, tc.data?.[name] ?? s.value, false);
1486
+ // LLM patches override
1487
+ // DATABASE steps: a parameter referenced inside an argument value (a filter on `…-${suffix}`) must be written as
1488
+ // `{{name}}` and listed in parameterizedParamIds, or the agent runs it with the literal text.
1489
+ const parameterizedIds = [];
1490
+ if (patchRecorded) {
1491
+ for (const [name, value] of Object.entries(patchRecorded)) {
1492
+ let out = value;
1493
+ if (s.runtimeParameters?.includes(name))
1494
+ out = runtimeSlotValue(value);
1495
+ else if (s.stepType === 'database' && typeof value === 'string') {
1496
+ const bound = bindValueParams(value, paramIdByName, name);
1497
+ out = bound.value;
1498
+ for (const id of bound.ids)
1499
+ if (!parameterizedIds.includes(id))
1500
+ parameterizedIds.push(id);
1501
+ }
1502
+ addByName(name, out, true);
1503
+ }
1504
+ }
1505
+ const objectParamIds = [...(s.sourceObjectParameterIds ?? [])];
1506
+ // ponytail: spread the round-tripped raw fields FIRST so control-flow / function / switch /
1507
+ // api / attachments / conditions / loop / functionId / fnVersionId / apiData / etc. all
1508
+ // survive. Explicit computed fields below override where they overlap.
1509
+ const rawBase = (s.sourceRaw ?? {});
1510
+ // An API step is only "action-less" when it is a real REQUEST. An API-technology step using a
1511
+ // generic action ("Store from JSON" etc.) has an actionId and no apiData — it must keep both.
1512
+ const apiRequestStep = isApiRequestStep({ stepType: s.stepType, api: s.api, sourceRaw: rawBase });
1513
+ const rawStepType = typeof rawBase['stepType'] === 'string' ? rawBase['stepType'] : undefined;
1514
+ // stepLevelActions: merge — keep any extra flags from source, our four win where they exist.
1515
+ const rawSLA = rawBase['stepLevelActions'] ?? {};
1516
+ // ponytail: wire stepType resolution ladder for FRESH steps (no sourceRaw):
1517
+ // 1. Round-trip sourceRaw.stepType wins if present (IF/FOR/FUNCTION preserved from DB)
1518
+ // 2. Function step → 'FUNCTION' | 'FUNCTION_END'
1519
+ // 3. Control-flow step → uppercase(controlFlow.kind) (e.g. "IF", "FOR_START", "WHILE")
1520
+ // 4. Everything else → 'NORMAL_STATEMENT'
1521
+ // This is what makes `add_step({stepType: 'control_flow', controlFlow: {kind: 'IF'}})` and
1522
+ // `add_step({stepType: 'function', functionCall: {testCaseId: '99'}})` actually work.
1523
+ let wireStepType = rawStepType;
1524
+ if (!wireStepType) {
1525
+ if (s.stepType === 'function')
1526
+ wireStepType = 'FUNCTION';
1527
+ else if (s.stepType === 'function_end')
1528
+ wireStepType = 'FUNCTION_END';
1529
+ // API steps carry the backend's dedicated wire type 'API' (NOT NORMAL_STATEMENT) — that is
1530
+ // what routes the row to the api-step-card and the api plugin at execution. Postman import
1531
+ // and the SQA UI both emit 'API'.
1532
+ else if (s.stepType === 'api')
1533
+ wireStepType = 'API';
1534
+ else if (s.stepType === 'control_flow' && s.controlFlow?.kind)
1535
+ wireStepType = String(s.controlFlow.kind).toUpperCase();
1536
+ // A TECHNOLOGY SWITCH is its own neutral kind (`stepType: 'switch'`, controlFlow.kind =
1537
+ // SWITCH_TO_API / _DB / _WEB / …). Without this branch it fell through to NORMAL_STATEMENT with
1538
+ // no action, so a hybrid save wrote a plain statement and execution died with
1539
+ // "Action.displayName() because action() is null" — the switch (and every step after it) never ran.
1540
+ else if (s.stepType === 'switch' && s.controlFlow?.kind)
1541
+ wireStepType = String(s.controlFlow.kind).toUpperCase();
1542
+ else
1543
+ wireStepType = 'NORMAL_STATEMENT';
1544
+ }
1545
+ // --- API step ------------------------------------------------------------------------------
1546
+ // An API step carries its whole request in `api` (neutral) / `apiData` (wire/round-trip) and
1547
+ // needs NO action or object binding — Postman import and the SQA UI both emit actionId:null.
1548
+ // The request's `{{name}}` tokens are rewritten to `{{<paramId>}}` (the form the editor
1549
+ // persists), and the substituted ids are registered so parameterIds/recordedParam — and hence
1550
+ // the default testdata iteration (ITR-1) — are populated at save by createTcFn.
1551
+ let apiData;
1552
+ let apiLastActiveTab;
1553
+ if (apiRequestStep) {
1554
+ const source = swapApiParams((s.api ?? rawBase['apiData']) ?? {}, swapsApplied);
1555
+ const apiParams = [];
1556
+ apiData = substituteApiParams(source, paramIdByName, apiParams);
1557
+ // Always persist the FULL editor shape (requestStyle / query_params / headers / authorization /
1558
+ // body.data / arrays): a partial apiData makes the API popup throw on load/save.
1559
+ normalizeApiDataShape(apiData);
1560
+ // Persist assertions in the API-TC editor's shape (response.* / header key), not the
1561
+ // MCP live-request syntax ($.body.* / $.headers.*), so they render in the Assertions tab.
1562
+ if (apiData['assertions'] !== undefined) {
1563
+ apiData['assertions'] = normalizeApiAssertions(apiData['assertions']);
1564
+ }
1565
+ // Register the substituted ids AND seed each one's default value (tc.data / the recorder's
1566
+ // name-keyed recordedParam patches), so parameterIds + recordedParam are both populated and
1567
+ // createTcFn builds the default testdata iteration (ITR-1) for the request.
1568
+ for (const { id, name } of apiParams) {
1569
+ registerId(id);
1570
+ setValue(id, String(tc.data?.[name] ?? s.recordedParam?.[name] ?? ''), false);
1571
+ }
1572
+ if (apiParams.length || paramIds.length) {
1573
+ // A parameter the recording generated/stored at runtime MUST stay RUNTIME here. The API executor builds
1574
+ // its arguments from `apiData.inputParameters`; hard-coding LOCAL made it substitute the test-data
1575
+ // placeholder (e.g. "apivalue") instead of the runtime value, so a hybrid generate → store → API step
1576
+ // sent the wrong body even though the store step had stored the value correctly.
1577
+ const runtimeNames = new Set((s.runtimeParameters ?? []).map((n) => n.toLowerCase()));
1578
+ // ROUND-TRIP: an EDIT of an existing API step must keep the binding the database already has.
1579
+ // A hydrated step does not carry `runtimeParameters`, so without this an edit would downgrade a
1580
+ // RUNTIME parameter to LOCAL and break a working hybrid test case.
1581
+ const priorInput = new Map();
1582
+ if (Array.isArray(apiData['inputParameters'])) {
1583
+ for (const raw of apiData['inputParameters']) {
1584
+ const id = typeof raw['id'] === 'number' ? raw['id'] : Number(raw['id']);
1585
+ if (!Number.isFinite(id))
1586
+ continue;
1587
+ priorInput.set(id, { ...raw, id });
1588
+ }
1589
+ }
1590
+ // id → name, so a parameter bound only through recordedParam / sourceParameterIds (not a
1591
+ // {{name}} token in the request) still appears in the popup's parameter list. The popup and
1592
+ // the executor read inputParameters, not parameterIds — leaving it out made the parameters
1593
+ // look missing even though the step had them.
1594
+ const nameById = new Map();
1595
+ for (const [name, id] of paramIdByName)
1596
+ if (!nameById.has(id))
1597
+ nameById.set(id, name);
1598
+ for (const p of apiParams)
1599
+ if (!nameById.has(p.id))
1600
+ nameById.set(p.id, p.name);
1601
+ const boundIds = [...new Set([...paramIds, ...apiParams.map((p) => p.id)])];
1602
+ apiData['inputParameters'] = boundIds.map((id) => {
1603
+ const prev = priorInput.get(id);
1604
+ const name = prev && typeof prev['name'] === 'string' && prev['name']
1605
+ ? prev['name']
1606
+ : (nameById.get(id) ?? String(id));
1607
+ // The parameter catalog is authoritative: if it is a RUNTIME parameter, the executor must
1608
+ // take its value from the runtime store. Recording used to save it as LOCAL, so the first
1609
+ // run sent the record-time literal for step 3 (only a later UI save corrected it).
1610
+ const catalogRuntime = (paramAccessById?.get(id) ?? '').toUpperCase() === 'RUNTIME';
1611
+ const isRuntime = catalogRuntime || runtimeNames.has(name.toLowerCase());
1612
+ // Existing LOCAL entry: keep it byte-for-byte (round-trip). A RUNTIME one is upgraded.
1613
+ if (prev)
1614
+ return isRuntime ? { ...prev, parameterAccessType: 'RUNTIME' } : prev;
1615
+ return {
1616
+ id,
1617
+ name,
1618
+ parameterAccessType: isRuntime ? 'RUNTIME' : 'LOCAL',
1619
+ parameterDataType: 'ALPHANUMERIC',
1620
+ // Required by the executor's runtime branch: Parameter.runtimeParameterKey() is dereferenced
1621
+ // without a null check, and a missing field made the run die with an NPE.
1622
+ runtimeParameterKey: 'NONE',
1623
+ };
1624
+ });
1625
+ }
1626
+ apiLastActiveTab = { mainTab: 'body', subTab: API_BODY_SUBTAB[apiBodyType(apiData) ?? ''] ?? 'NONE' };
1627
+ }
1628
+ // FUNCTION step: derive functionId + fnVersionId from neutral functionCall when no sourceRaw
1629
+ // (LLM authored a fresh function-call step via add_step).
1630
+ // The database keeps a function call as numeric ids (functionId / fnVersionId / sharedFnProjectId); the neutral
1631
+ // functionCall is what a prompt edits, and it is the up-to-date one (a hydrated step carries both and they agree).
1632
+ // So functionCall wins over the round-tripped raw copy — otherwise "call a different function" is silently ignored —
1633
+ // and a business code like "FN_12" is turned into its id, never into NaN (which dropped the binding).
1634
+ const rawFnId = typeof rawBase['functionId'] === 'number' ? rawBase['functionId'] : undefined;
1635
+ const rawFnVersion = typeof rawBase['fnVersionId'] === 'string' ? rawBase['fnVersionId'] : undefined;
1636
+ const callId = s.functionCall?.testCaseId ? Number.parseInt(numericId(s.functionCall.testCaseId), 10) : undefined;
1637
+ if (s.functionCall?.testCaseId && !Number.isFinite(callId)) {
1638
+ throw new Error(`Step ${i + 1}: function "${s.functionCall.testCaseId}" is not a function id or code (e.g. 12 or FN_12).`);
1639
+ }
1640
+ const wireFunctionId = callId ?? rawFnId;
1641
+ const wireFnVersionId = s.functionCall?.versionId ?? rawFnVersion;
1642
+ if (callId !== undefined && rawFnId !== undefined && callId !== rawFnId && wireFnVersionId === rawFnVersion && rawFnVersion) {
1643
+ throw new Error(`Step ${i + 1}: the function was changed from ${rawFnId} to ${callId} but functionCall.versionId still points at the old ` +
1644
+ `function's version. Pass functionCall.versionId = a version id of function ${callId} (its newest version).`);
1645
+ }
1646
+ const wireSharedFnProjectId = (s.functionCall?.sharedProjectId ? Number.parseInt(numericId(s.functionCall.sharedProjectId), 10) : undefined)
1647
+ ?? (typeof rawBase['sharedFnProjectId'] === 'number' ? rawBase['sharedFnProjectId'] : undefined);
1648
+ // Control-flow step: derive conditions.ifstring + loopDuration from neutral controlFlow.
1649
+ const wireConditions = rawBase['conditions']
1650
+ ?? (s.controlFlow?.conditionText ? { ifstring: s.controlFlow.conditionText, children: [] } : { ifstring: '', children: [] });
1651
+ const wireLoopDuration = (typeof rawBase['loopDuration'] === 'number' ? rawBase['loopDuration'] : undefined)
1652
+ ?? s.controlFlow?.maxIterations;
1653
+ const step = {
1654
+ ...rawBase,
1655
+ // ponytail: `deleted` is required on UPDATE and REJECTED on CREATE by the backend validator
1656
+ // (steps.automationSteps[*].deleted) — emit it only when updating, mirroring tcfnObj above.
1657
+ ...(existingId ? { deleted: false } : {}),
1658
+ // ponytail: pass through the backend step uuid on round-trip. Without `id`, every step
1659
+ // routes to tcfn.service.js:355 CREATE branch, mints a new uuid, orphans the original row.
1660
+ ...(s.sourceId ? { id: s.sourceId } : {}),
1661
+ // ponytail: parentId + versionId REQUIRED on update — tcfn.service.js:406 builds the update
1662
+ // filter `{id, customerId, projectId, parentId, type}` and without parentId it becomes
1663
+ // `{parentId: undefined}` → misses the existing row → upsert inserts a new orphan step
1664
+ // with no parentId. UI query `{parentId: tcId, versionId, deleted:false}` then finds nothing.
1665
+ ...(existingId ? { parentId: Number.parseInt(existingId, 10) } : {}),
1666
+ ...(existingId && curVer.id ? { versionId: curVer.id } : {}),
1667
+ projectId,
1668
+ // Only emit actionId/objectId for steps that resolve to an action (straight-line automation).
1669
+ // Control-flow / function / switch steps have no action; the sourceRaw spread carries their
1670
+ // functionId / conditions / loop instead.
1671
+ ...(resolution && resolution.actionId != null
1672
+ ? {
1673
+ actionId: resolution.actionId,
1674
+ // ponytail: undefined objectId means "preserve DB value" (existing step with no round-trip
1675
+ // objectRef.id). null is a valid emitted value (fresh step where the action doesn't need one).
1676
+ objectId: resolution.objectId === undefined ? null : resolution.objectId,
1677
+ }
1678
+ : {}),
1679
+ // API step: emit the explicit action-less shape the backend/api-card expects (Postman import
1680
+ // sets both to null), plus the request payload and the editor's active-tab hint.
1681
+ ...(apiRequestStep ? { actionId: null, objectId: null } : {}),
1682
+ ...(apiData ? { apiData } : {}),
1683
+ ...(apiLastActiveTab ? { lastActiveTab: apiLastActiveTab } : {}),
1684
+ // Round-tripped attachments (source) preserved via spread above; default to [] if fresh.
1685
+ attachments: Array.isArray(rawBase['attachments']) ? rawBase['attachments'] : [],
1686
+ conditions: wireConditions,
1687
+ description: normalizeParamTokens(descNow) ?? '',
1688
+ executionType: 'AUTOMATION',
1689
+ expectedResult: normalizeParamTokens(s.expectedResult ?? '') ?? '',
1690
+ loop: rawBase['loop'] ?? { loopType: 'for', loopIteration: null },
1691
+ ...(wireLoopDuration !== undefined ? { loopDuration: wireLoopDuration } : {}),
1692
+ moduleId,
1693
+ // Function-call fields — emitted only for FUNCTION steps (rawBase spread already carries
1694
+ // them for round-tripped functions; these derivations cover fresh add_step callers).
1695
+ ...(wireFunctionId !== undefined && Number.isFinite(wireFunctionId) ? { functionId: wireFunctionId } : {}),
1696
+ ...(wireFnVersionId ? { fnVersionId: wireFnVersionId } : {}),
1697
+ ...(wireSharedFnProjectId !== undefined && Number.isFinite(wireSharedFnProjectId) ? { sharedFnProjectId: wireSharedFnProjectId } : {}),
1698
+ objectParameterIds: objectParamIds,
1699
+ // a browser set (or changed) through the prompt wins; otherwise the round-tripped one from rawBase stands
1700
+ ...(s.browserType ? { browserType: s.browserType } : {}),
1701
+ // ponytail: always emit — matches UI payload shape. Sending `[]` / `{}` is how UI signals
1702
+ // "this step has no params/values"; the joi validator + backend $set semantics assume presence.
1703
+ parameterIds: paramIds,
1704
+ ...(parameterizedIds.length || swapsApplied.length
1705
+ ? { parameterizedParamIds: [...new Set([...swappedParameterized, ...parameterizedIds])] }
1706
+ : {}),
1707
+ recordedParam: recordedParamOut,
1708
+ seq: i + 1,
1709
+ stepLevelActions: {
1710
+ ...rawSLA,
1711
+ skip: s.flags?.skip ?? rawSLA['skip'] ?? false,
1712
+ captureScreenshot: s.flags?.screenshot ?? rawSLA['captureScreenshot'] ?? false,
1713
+ continueOnFailure: s.flags?.continueOnFailure ?? rawSLA['continueOnFailure'] ?? false,
1714
+ skippedReport: rawSLA['skippedReport'] ?? false,
1715
+ },
1716
+ // Wire stepType: sourceRaw wins on round-trip; for fresh steps, translated from neutral
1717
+ // stepType + controlFlow.kind + function marker (see wireStepType computation above).
1718
+ stepType: wireStepType,
1719
+ technologyType,
1720
+ type: 'TC',
1721
+ };
1722
+ automationSteps.push(step);
1723
+ });
1724
+ return {
1725
+ tcfnObj: withSavedTcFields(tcfnObj, tc),
1726
+ versionsDetails,
1727
+ steps: { automationSteps, manualSteps: [] },
1728
+ operation: 'TC',
1729
+ type: 'TC',
1730
+ };
1731
+ }
1732
+ /** Neutral SavedRef from a POST/PUT /tm/testcase response. Tolerates a bare doc or a `data`-wrapped
1733
+ * response; prefers the business `code` (TC_xxx) for productUrl deep links but uses the numeric id
1734
+ * when only that is present. */
1735
+ export function toSavedRef(raw, created) {
1736
+ const flat = (raw?.data ?? raw) ?? {};
1737
+ const id = str(flat, 'id', '_id', 'testcaseId') ?? '';
1738
+ return {
1739
+ id,
1740
+ created,
1741
+ };
1742
+ }
1743
+ // ---------------------------------------------------------------------------
1744
+ // Suites (write). The update PUT reshapes the members list under a strict
1745
+ // allow-list; anything else on the raw doc is rejected. Shared helpers are:
1746
+ // • normalizeSuiteEntry — copy an existing members[] row into the allow-list.
1747
+ // • Adapter builds each ADD entry by fetching the target TC, so those helpers
1748
+ // stay in the adapter (they need IO).
1749
+ // ---------------------------------------------------------------------------
1750
+ /** Copy an existing suite testCases[] row into the strict allow-list; drop `id`, audit fields, etc. */
1751
+ export function normalizeSuiteEntry(m) {
1752
+ const out = {};
1753
+ const keep = ['testcaseId', 'code', 'seq', 'stepId', 'version', 'versionId', 'tcType', 'projectId', 'executionPlatform'];
1754
+ for (const k of keep)
1755
+ if (m?.[k] !== undefined)
1756
+ out[k] = m[k];
1757
+ return out;
1758
+ }
1759
+ /** The 15+ allow-listed suite-level keys the update validator accepts. */
1760
+ export const SUITE_UPDATE_ALLOWED_KEYS = [
1761
+ 'id', 'name', 'description', 'state', 'suiteType', 'projectId', 'autoDefectLog',
1762
+ 'autoReExecCount', 'autoReExecTriggerOn', 'newBrowserSession', 'terminateOnFailure',
1763
+ 'minimumContainerCount', 'maximumContainerCount', 'copySuiteName', 'copiedFrom',
1764
+ 'mailersList', 'tags', 'customFields', 'agentId', 'cloudAgentId',
1765
+ 'lastSelectedExecutionType', 'updateVersion',
1766
+ ];
1767
+ //# sourceMappingURL=mapper.js.map