@wenathlan/devthink 2.0.15 → 2.0.19

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 (444) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/{dist/bridge.d.ts → bridge.d.ts} +1 -1
  3. package/bridge.d.ts.map +1 -0
  4. package/bridge.js +1877 -0
  5. package/bun.d.ts.map +1 -0
  6. package/bun.js +52329 -0
  7. package/caps/background.json +712 -0
  8. package/caps/cli.json +360 -0
  9. package/caps/library.json +3611 -0
  10. package/caps/mcp.json +126 -0
  11. package/caps/pagebridge.json +377 -0
  12. package/caps/popup.json +51 -0
  13. package/caps/sidepanel.json +522 -0
  14. package/checksums.txt +142 -0
  15. package/cli.d.ts.map +1 -0
  16. package/{dist/cli.js → cli.js} +2 -2
  17. package/companion.d.ts.map +1 -0
  18. package/companion.js +389 -0
  19. package/crossbrowser.d.ts.map +1 -0
  20. package/crossbrowser.js +1191 -0
  21. package/dashdone.d.ts.map +1 -0
  22. package/dashdone.js +368 -0
  23. package/deno.d.ts.map +1 -0
  24. package/deno.js +52325 -0
  25. package/devthink.umd.js +52346 -0
  26. package/fixtures/bun.ts +7 -0
  27. package/fixtures/cjs.js +6 -0
  28. package/fixtures/deno.ts +6 -0
  29. package/fixtures/example-org-pagestate.json +22 -0
  30. package/fixtures/importers/automa-workflow.json +18 -0
  31. package/fixtures/importers/selenium-side.json +20 -0
  32. package/fixtures/importers/tabular-plan.csv +7 -0
  33. package/fixtures/importers/uivision-macro.json +10 -0
  34. package/fixtures/importers/v1-plan.json +13 -0
  35. package/fixtures/mcp-client.mjs +14 -0
  36. package/fixtures/pages/checkout.html +192 -0
  37. package/fixtures/pages/dashboard.html +110 -0
  38. package/fixtures/pages/feed.html +113 -0
  39. package/fixtures/pages/product-grid.html +150 -0
  40. package/fixtures/plans/form-inventory-plan.json +11 -0
  41. package/fixtures/plans/release-notes-plan.json +11 -0
  42. package/fixtures/recipes/agentscompete.json +11 -0
  43. package/fixtures/recipes/agentsforms.json +11 -0
  44. package/fixtures/recipes/agentsmonitor.json +11 -0
  45. package/fixtures/recipes/agentsreview.json +29 -0
  46. package/fixtures/recipes/agentswarm.json +11 -0
  47. package/fixtures/recipes/fillcalendar.json +12 -0
  48. package/fixtures/recipes/fillcheckout.json +13 -0
  49. package/fixtures/recipes/filldependentdropdowns.json +12 -0
  50. package/fixtures/recipes/fillfromcsv.json +13 -0
  51. package/fixtures/recipes/fillloginform.json +12 -0
  52. package/fixtures/recipes/fillmultistepwizard.json +13 -0
  53. package/fixtures/recipes/fillregistration.json +12 -0
  54. package/fixtures/recipes/fillsearchfilters.json +12 -0
  55. package/fixtures/recipes/filltypeahead.json +11 -0
  56. package/fixtures/recipes/monitoralerts.json +12 -0
  57. package/fixtures/recipes/monitoravailability.json +11 -0
  58. package/fixtures/recipes/monitornetworkquiet.json +12 -0
  59. package/fixtures/recipes/monitorpagechanges.json +11 -0
  60. package/fixtures/recipes/monitorpricechange.json +11 -0
  61. package/fixtures/recipes/monitorschedule.json +12 -0
  62. package/fixtures/recipes/scrapedynamicprices.json +13 -0
  63. package/fixtures/recipes/scrapeimagegallery.json +12 -0
  64. package/fixtures/recipes/scrapeinfinitefeed.json +13 -0
  65. package/fixtures/recipes/scrapenestedlists.json +12 -0
  66. package/fixtures/recipes/scrapeproductgrid.json +12 -0
  67. package/fixtures/recipes/scrapereviews.json +12 -0
  68. package/fixtures/recipes/scrapesearchresults.json +12 -0
  69. package/fixtures/recipes/scrapetablepagination.json +12 -0
  70. package/fixtures/recipes/testaccessibility.json +34 -0
  71. package/fixtures/recipes/testconsoleerrors.json +12 -0
  72. package/fixtures/recipes/testdeeplinks.json +12 -0
  73. package/fixtures/recipes/testformvalidation.json +13 -0
  74. package/fixtures/recipes/testlayoutshift.json +12 -0
  75. package/fixtures/recipes/testlinkcheck.json +12 -0
  76. package/fixtures/recipes/testloadtiming.json +12 -0
  77. package/fixtures/recipes/testvisualdiff.json +12 -0
  78. package/fixtures/workflows/changelog-digest-workflow.json +13 -0
  79. package/fixtures/workflows/form-survey-workflow.json +13 -0
  80. package/gallery.json +706 -0
  81. package/hardening.d.ts.map +1 -0
  82. package/hardening.js +188 -0
  83. package/headless.d.ts.map +1 -0
  84. package/headless.js +11522 -0
  85. package/http.d.ts.map +1 -0
  86. package/http.js +2165 -0
  87. package/index.cjs +54682 -0
  88. package/index.d.ts.map +1 -0
  89. package/index.js +52310 -0
  90. package/index.neutral.js +46343 -0
  91. package/{web/manifest.json → manifest.json} +1 -1
  92. package/mcp.d.ts.map +1 -0
  93. package/mcp.js +20515 -0
  94. package/memory.d.ts.map +1 -0
  95. package/{memory.ts → memory.js} +2310 -3834
  96. package/nativehost.template.json +10 -0
  97. package/node.cjs +54686 -0
  98. package/node.d.ts.map +1 -0
  99. package/pack.d.ts.map +1 -0
  100. package/pack.js +805 -0
  101. package/package.json +83 -176
  102. package/policy.d.ts.map +1 -0
  103. package/{policy.ts → policy.js} +4679 -5073
  104. package/progress.d.ts.map +1 -0
  105. package/progress.js +645 -0
  106. package/protocol.d.ts.map +1 -0
  107. package/protocol.js +8334 -0
  108. package/schemas/audit.schema.json +226 -0
  109. package/schemas/capability.schema.json +113 -0
  110. package/schemas/envelope.schema.json +162 -0
  111. package/schemas/memory.schema.json +51 -0
  112. package/schemas/observation.schema.json +113 -0
  113. package/schemas/plan.schema.json +208 -0
  114. package/schemas/progress.schema.json +126 -0
  115. package/schemas/proposal.schema.json +68 -0
  116. package/schemas/session.schema.json +82 -0
  117. package/schemas/tool.schema.json +94 -0
  118. package/server.d.ts.map +1 -0
  119. package/server.js +28877 -0
  120. package/umd-example.html +18 -0
  121. package/umd.d.ts.map +1 -0
  122. package/accounts.ts +0 -2087
  123. package/agent.ts +0 -2331
  124. package/antigravity.ts +0 -2139
  125. package/apifreeze.ts +0 -4146
  126. package/auth.ts +0 -642
  127. package/background.ts +0 -16837
  128. package/bridge.ts +0 -2080
  129. package/build.ts +0 -54
  130. package/bun.ts +0 -26
  131. package/capture.ts +0 -1614
  132. package/checksecrets.ts +0 -72
  133. package/cjs.ts +0 -9
  134. package/cli.ts +0 -3500
  135. package/commands.ts +0 -1101
  136. package/companion.ts +0 -450
  137. package/compatibility.ts +0 -37
  138. package/config.ts +0 -3137
  139. package/constants.ts +0 -943
  140. package/core.ts +0 -1473
  141. package/crossbrowser.ts +0 -1359
  142. package/dashdone.ts +0 -605
  143. package/data.ts +0 -943
  144. package/database.ts +0 -133
  145. package/debug.ts +0 -850
  146. package/deno.ts +0 -27
  147. package/devthink.ts +0 -707
  148. package/dist/accounts.d.ts +0 -409
  149. package/dist/agent.d.ts +0 -837
  150. package/dist/antigravity.d.ts +0 -380
  151. package/dist/apifreeze.d.ts +0 -113
  152. package/dist/auth.d.ts +0 -224
  153. package/dist/capture.d.ts +0 -595
  154. package/dist/cjs.d.ts +0 -6
  155. package/dist/commands.d.ts +0 -310
  156. package/dist/compatibility.d.ts +0 -17
  157. package/dist/config.d.ts +0 -1853
  158. package/dist/constants.d.ts +0 -637
  159. package/dist/core.d.ts +0 -361
  160. package/dist/data.d.ts +0 -330
  161. package/dist/database.d.ts +0 -24
  162. package/dist/debug.d.ts +0 -270
  163. package/dist/engine.d.ts +0 -74
  164. package/dist/environments.d.ts +0 -244
  165. package/dist/evidence.d.ts +0 -277
  166. package/dist/export.d.ts +0 -311
  167. package/dist/fingerprint.d.ts +0 -594
  168. package/dist/flow.d.ts +0 -300
  169. package/dist/gates.d.ts +0 -103
  170. package/dist/identity.d.ts +0 -51
  171. package/dist/ids.d.ts +0 -7
  172. package/dist/llm.d.ts +0 -652
  173. package/dist/models.d.ts +0 -1807
  174. package/dist/net.d.ts +0 -325
  175. package/dist/neutral.d.ts +0 -41
  176. package/dist/oauth.d.ts +0 -703
  177. package/dist/page.d.ts +0 -1166
  178. package/dist/perf.d.ts +0 -481
  179. package/dist/plan.d.ts +0 -134
  180. package/dist/project.d.ts +0 -395
  181. package/dist/providers.d.ts +0 -37
  182. package/dist/quota.d.ts +0 -453
  183. package/dist/recovery.d.ts +0 -621
  184. package/dist/request.d.ts +0 -1492
  185. package/dist/run.d.ts +0 -779
  186. package/dist/runtime.d.ts +0 -212
  187. package/dist/search.d.ts +0 -375
  188. package/dist/security.d.ts +0 -534
  189. package/dist/serve.d.ts +0 -136
  190. package/dist/session.d.ts +0 -296
  191. package/dist/storage.d.ts +0 -53
  192. package/dist/streaming.d.ts +0 -1119
  193. package/dist/swarm.d.ts +0 -328
  194. package/dist/tools.d.ts +0 -170
  195. package/dist/types.d.ts +0 -8357
  196. package/dist/utils.d.ts +0 -82
  197. package/dist/version.d.ts +0 -7
  198. package/dist/versionregistry.d.ts +0 -406
  199. package/dist/views.d.ts +0 -579
  200. package/dist/workbenchsession.d.ts +0 -69
  201. package/dist/workflow.d.ts +0 -649
  202. package/docs/readme.md +0 -92
  203. package/docs/schemas/antigravity.json +0 -192
  204. package/engine.ts +0 -1524
  205. package/environments.ts +0 -1005
  206. package/evidence.ts +0 -643
  207. package/export.ts +0 -889
  208. package/fingerprint.ts +0 -1458
  209. package/flow.ts +0 -1190
  210. package/gates.ts +0 -307
  211. package/gateway.ts +0 -34
  212. package/hardening.ts +0 -191
  213. package/headless.ts +0 -369
  214. package/http.ts +0 -2110
  215. package/identity.ts +0 -246
  216. package/ids.ts +0 -26
  217. package/index.ts +0 -369
  218. package/llm.ts +0 -2682
  219. package/mcp.ts +0 -1835
  220. package/models.ts +0 -3805
  221. package/modes.ts +0 -43
  222. package/net.ts +0 -1214
  223. package/neutral.ts +0 -362
  224. package/node.ts +0 -26
  225. package/oauth.ts +0 -2216
  226. package/offscreen.ts +0 -170
  227. package/pack.ts +0 -956
  228. package/page.ts +0 -7824
  229. package/pagebridge.ts +0 -1116
  230. package/perf.ts +0 -957
  231. package/plan.ts +0 -672
  232. package/plugin.ts +0 -76
  233. package/prisma.config.ts +0 -27
  234. package/progress.ts +0 -1308
  235. package/project.ts +0 -1291
  236. package/protocol.ts +0 -4187
  237. package/providers.ts +0 -246
  238. package/quota.ts +0 -1887
  239. package/recovery.ts +0 -2433
  240. package/request.ts +0 -4482
  241. package/run.ts +0 -2135
  242. package/runtime.ts +0 -526
  243. package/search.ts +0 -1760
  244. package/security.ts +0 -1673
  245. package/serve.ts +0 -419
  246. package/server.ts +0 -5538
  247. package/session.ts +0 -1162
  248. package/storage.ts +0 -182
  249. package/streaming.ts +0 -4101
  250. package/swarm.ts +0 -884
  251. package/sync.ts +0 -56
  252. package/tests/agentcert.test.ts +0 -128
  253. package/tests/agentfleet.test.ts +0 -214
  254. package/tests/agentreview.test.ts +0 -241
  255. package/tests/agentstream.test.ts +0 -335
  256. package/tests/agentwork.test.ts +0 -356
  257. package/tests/apifreeze.test.ts +0 -290
  258. package/tests/apimap.test.ts +0 -112
  259. package/tests/approvalgate.test.ts +0 -175
  260. package/tests/artifactmanifest.test.ts +0 -204
  261. package/tests/attentionfeed.test.ts +0 -163
  262. package/tests/backgroundruns.test.ts +0 -100
  263. package/tests/batchscheduling.test.ts +0 -131
  264. package/tests/blackboard.test.ts +0 -238
  265. package/tests/bridge.test.ts +0 -1088
  266. package/tests/browsercoverage.test.ts +0 -134
  267. package/tests/browserpolyfills.test.ts +0 -124
  268. package/tests/build.mjs +0 -1260
  269. package/tests/clientauth.test.ts +0 -223
  270. package/tests/clitools.test.ts +0 -578
  271. package/tests/confirmgates.test.ts +0 -190
  272. package/tests/containerpack.test.ts +0 -143
  273. package/tests/controlflow.test.ts +0 -2120
  274. package/tests/coordination.test.ts +0 -345
  275. package/tests/copyscreen.test.ts +0 -139
  276. package/tests/core.test.ts +0 -417
  277. package/tests/costcert.test.ts +0 -95
  278. package/tests/crossbrowser.test.ts +0 -115
  279. package/tests/cspaudit.test.ts +0 -79
  280. package/tests/dashdone.test.ts +0 -615
  281. package/tests/datagrid.test.ts +0 -137
  282. package/tests/doccheck.test.ts +0 -107
  283. package/tests/dombatch.test.ts +0 -109
  284. package/tests/emulation.test.ts +0 -282
  285. package/tests/environments.test.ts +0 -259
  286. package/tests/evidenceviews.test.ts +0 -88
  287. package/tests/exporttools.test.ts +0 -185
  288. package/tests/firefoxprep.test.ts +0 -134
  289. package/tests/flowlibrary.test.ts +0 -242
  290. package/tests/flowrun.test.ts +0 -303
  291. package/tests/forensics.test.ts +0 -439
  292. package/tests/gateway.test.ts +0 -939
  293. package/tests/headlesslib.test.ts +0 -171
  294. package/tests/httpstream.test.ts +0 -277
  295. package/tests/immutablelog.test.ts +0 -157
  296. package/tests/inboundguard.test.ts +0 -177
  297. package/tests/lazyload.test.ts +0 -72
  298. package/tests/librarymodes.test.ts +0 -623
  299. package/tests/llm.test.ts +0 -696
  300. package/tests/manifest.test.ts +0 -226
  301. package/tests/maskinputs.test.ts +0 -150
  302. package/tests/matrixverify.test.ts +0 -111
  303. package/tests/mavenpack.test.ts +0 -75
  304. package/tests/mcpserver.test.ts +0 -704
  305. package/tests/memory.test.ts +0 -4155
  306. package/tests/memorycare.test.ts +0 -230
  307. package/tests/migrateplan.test.ts +0 -349
  308. package/tests/minimization.test.ts +0 -414
  309. package/tests/modelroute.test.ts +0 -112
  310. package/tests/multiagent.test.ts +0 -440
  311. package/tests/nativebridge.test.ts +0 -807
  312. package/tests/navigation.test.ts +0 -284
  313. package/tests/nugetpack.test.ts +0 -83
  314. package/tests/orchestration.test.ts +0 -449
  315. package/tests/originpolicy.test.ts +0 -405
  316. package/tests/outputcompare.test.ts +0 -97
  317. package/tests/package.test.ts +0 -91
  318. package/tests/pagebridge.test.ts +0 -5909
  319. package/tests/pentest.test.ts +0 -75
  320. package/tests/perfrecords.test.ts +0 -257
  321. package/tests/permdiff.test.ts +0 -85
  322. package/tests/phishguard.test.ts +0 -128
  323. package/tests/pickerviews.test.ts +0 -155
  324. package/tests/pipelines.test.ts +0 -381
  325. package/tests/planlint.test.ts +0 -240
  326. package/tests/planreview.test.ts +0 -383
  327. package/tests/platformtargets.test.ts +0 -56
  328. package/tests/policy.test.ts +0 -8284
  329. package/tests/portability.test.ts +0 -96
  330. package/tests/progress.test.ts +0 -1036
  331. package/tests/promptlibrary.test.ts +0 -116
  332. package/tests/protocol.test.ts +0 -4793
  333. package/tests/publishingpipeline.test.ts +0 -314
  334. package/tests/quickactions.test.ts +0 -164
  335. package/tests/readiness.test.ts +0 -78
  336. package/tests/recipes.test.ts +0 -163
  337. package/tests/redactshots.test.ts +0 -216
  338. package/tests/registernvidiakeys.ts +0 -51
  339. package/tests/relayserve.test.ts +0 -304
  340. package/tests/releasenotes.test.ts +0 -276
  341. package/tests/resilience.test.ts +0 -467
  342. package/tests/resourceaware.test.ts +0 -187
  343. package/tests/runbudget.test.ts +0 -125
  344. package/tests/runhistory.test.ts +0 -299
  345. package/tests/runreplay.test.ts +0 -113
  346. package/tests/runresume.test.ts +0 -184
  347. package/tests/runstate.test.ts +0 -288
  348. package/tests/runtimeadapters.test.ts +0 -251
  349. package/tests/safariskeleton.test.ts +0 -115
  350. package/tests/sandboxframe.test.ts +0 -196
  351. package/tests/sbom.test.ts +0 -105
  352. package/tests/secretvault.test.ts +0 -188
  353. package/tests/selcache.test.ts +0 -111
  354. package/tests/sessioninterface.test.ts +0 -791
  355. package/tests/sessions.test.ts +0 -591
  356. package/tests/siteprefs.test.ts +0 -228
  357. package/tests/snapshotdelta.test.ts +0 -165
  358. package/tests/statusviews.test.ts +0 -237
  359. package/tests/stepmeter.test.ts +0 -200
  360. package/tests/streamparse.test.ts +0 -163
  361. package/tests/stylepruning.test.ts +0 -90
  362. package/tests/surfaces.test.ts +0 -282
  363. package/tests/sweep.test.ts +0 -78
  364. package/tests/syncbridge.test.ts +0 -164
  365. package/tests/taskqueue.test.ts +0 -206
  366. package/tests/toolcalls.test.ts +0 -336
  367. package/tests/toolcatalog.test.ts +0 -201
  368. package/tests/torture-agent.test.ts +0 -706
  369. package/tests/torture-auth.test.ts +0 -461
  370. package/tests/torture-commands.test.ts +0 -895
  371. package/tests/torture-data.test.ts +0 -923
  372. package/tests/torture-environments.test.ts +0 -285
  373. package/tests/torture-export.test.ts +0 -263
  374. package/tests/torture-http.test.ts +0 -1379
  375. package/tests/torture-llm.test.ts +0 -808
  376. package/tests/torture-memory.test.ts +0 -1084
  377. package/tests/torture-plan.test.ts +0 -829
  378. package/tests/torture-run.test.ts +0 -626
  379. package/tests/torture-session.test.ts +0 -928
  380. package/tests/torture-swarm.test.ts +0 -1245
  381. package/tests/torture-tools.test.ts +0 -964
  382. package/tests/torture-workflow.test.ts +0 -2354
  383. package/tests/tourviews.test.ts +0 -52
  384. package/tests/transparency.test.ts +0 -147
  385. package/tests/trigger.test.ts +0 -941
  386. package/tests/v1sunset.test.ts +0 -428
  387. package/tests/virtlist.test.ts +0 -94
  388. package/tests/vision.test.ts +0 -540
  389. package/tests/vsixpack.test.ts +0 -145
  390. package/tests/webapi.test.ts +0 -523
  391. package/tests/workflow.test.ts +0 -1785
  392. package/tests/workfloweditor.test.ts +0 -759
  393. package/tests/xpipack.test.ts +0 -128
  394. package/tools.ts +0 -734
  395. package/types.ts +0 -9908
  396. package/umd.ts +0 -9
  397. package/utils.ts +0 -249
  398. package/version.ts +0 -8
  399. package/versionregistry.ts +0 -1310
  400. package/views.ts +0 -2153
  401. package/vitest.config.ts +0 -12
  402. package/web/App.tsx +0 -78
  403. package/web/README.md +0 -47
  404. package/web/capacitor.config.ts +0 -46
  405. package/web/const.ts +0 -19
  406. package/web/control.shell.tsx +0 -66
  407. package/web/dashboardpage.ts +0 -554
  408. package/web/db.ts +0 -493
  409. package/web/design.html +0 -541
  410. package/web/gatewayview/Gateway.tsx +0 -345
  411. package/web/gatewayview/config.ts +0 -1042
  412. package/web/gatewayview/definition.ts +0 -174
  413. package/web/icons.ts +0 -15
  414. package/web/optionspage.ts +0 -691
  415. package/web/popup.ts +0 -1651
  416. package/web/schema.prisma +0 -176
  417. package/web/sidepanel.ts +0 -7941
  418. package/web/sitemanifest.json +0 -13
  419. package/web/terminal-ui.tsx +0 -622
  420. package/web/transparencypage.ts +0 -541
  421. package/web/vite.config.ts +0 -39
  422. package/web/workspace.ts +0 -23
  423. package/workbenchmemory.ts +0 -104
  424. package/workbenchsession.ts +0 -304
  425. package/workflow.ts +0 -4495
  426. /package/{dist/bun.d.ts → bun.d.ts} +0 -0
  427. /package/{dist/cli.d.ts → cli.d.ts} +0 -0
  428. /package/{dist/companion.d.ts → companion.d.ts} +0 -0
  429. /package/{dist/crossbrowser.d.ts → crossbrowser.d.ts} +0 -0
  430. /package/{dist/dashdone.d.ts → dashdone.d.ts} +0 -0
  431. /package/{dist/deno.d.ts → deno.d.ts} +0 -0
  432. /package/{dist/hardening.d.ts → hardening.d.ts} +0 -0
  433. /package/{dist/headless.d.ts → headless.d.ts} +0 -0
  434. /package/{dist/http.d.ts → http.d.ts} +0 -0
  435. /package/{dist/index.d.ts → index.d.ts} +0 -0
  436. /package/{dist/mcp.d.ts → mcp.d.ts} +0 -0
  437. /package/{dist/memory.d.ts → memory.d.ts} +0 -0
  438. /package/{dist/node.d.ts → node.d.ts} +0 -0
  439. /package/{dist/pack.d.ts → pack.d.ts} +0 -0
  440. /package/{dist/policy.d.ts → policy.d.ts} +0 -0
  441. /package/{dist/progress.d.ts → progress.d.ts} +0 -0
  442. /package/{dist/protocol.d.ts → protocol.d.ts} +0 -0
  443. /package/{dist/server.d.ts → server.d.ts} +0 -0
  444. /package/{dist/umd.d.ts → umd.d.ts} +0 -0
@@ -1,2354 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- blockinvocationof,
4
- composeworkflow,
5
- expandblocks,
6
- expressionof,
7
- expressionoperators,
8
- expressioneval,
9
- regexruleof,
10
- regexextract,
11
- steptemplateof,
12
- workflowblockof,
13
- workflowstepof,
14
- workflowkinds,
15
- bindvariables,
16
- cancelrun,
17
- delayjitter,
18
- dryrunworkflow,
19
- newworkflowrun,
20
- pauserun,
21
- popscope,
22
- pushscope,
23
- resolvevariable,
24
- runstep,
25
- runworkflow,
26
- seededrandom,
27
- setvariable,
28
- validateworkflow,
29
- waitelementplan,
30
- watchdogpass,
31
- backoffdelay,
32
- branchof,
33
- choosebranch,
34
- conditionof,
35
- controlflowkinds,
36
- controlsteps,
37
- controlsummary,
38
- defaultloopbound,
39
- evaluatecondition,
40
- foreachof,
41
- iscontrolflowkind,
42
- joinbranches,
43
- loopof,
44
- parallelof,
45
- repeatuntilof,
46
- runcontrolstep,
47
- runforeach,
48
- runloop,
49
- runparallel,
50
- runrepeatuntil,
51
- runtry,
52
- runwhile,
53
- tryof,
54
- validatecontrolpayload,
55
- visitmatch,
56
- whileof,
57
- applyretry,
58
- applyruntimeout,
59
- applytimeout,
60
- cancellederror,
61
- armrule,
62
- applycooldown,
63
- cronnext,
64
- cronparse,
65
- drainqueue,
66
- evaluatetrigger,
67
- eventrulematches,
68
- istriggerkind,
69
- listdue,
70
- matchurl,
71
- observeevents,
72
- pauseall,
73
- queuefire,
74
- resumeall,
75
- runurllist,
76
- schedulecron,
77
- scheduleinterval,
78
- triggerfamilyof,
79
- triggerfamilies,
80
- triggerkinds,
81
- triggerpayloadof,
82
- triggersummary,
83
- verifywebhook,
84
- webhooksecretok,
85
- timezonevalid,
86
- manualpreview,
87
- confirmmanualrun,
88
- ruleorigins,
89
- ruleoriginsgranted,
90
- updaterule,
91
- defaulttriggercooldown,
92
- buildsteplibrary,
93
- loadworkflow,
94
- saveworkflow,
95
- snapnode,
96
- reordersteps,
97
- groupselect,
98
- expandtemplate,
99
- addnode,
100
- editstep,
101
- renderminimap,
102
- minimapfocus,
103
- zoomcanvas,
104
- searchsteps,
105
- markbreakpoint,
106
- runtobreakpoint,
107
- diffversions,
108
- exportworkflow,
109
- shareworkflow,
110
- importworkflow,
111
- bindparam,
112
- applyoverride,
113
- addedge,
114
- removeedge,
115
- removenode,
116
- undoedit,
117
- redoedit,
118
- palettecategories,
119
- } from "../workflow.js";
120
- import type {
121
- branchstep,
122
- conditionstep,
123
- editormodel,
124
- expressiontype,
125
- foreachstep,
126
- loopstep,
127
- parallelstep,
128
- repeatuntilstep,
129
- retrypolicy,
130
- siteoverride,
131
- steptemplate,
132
- taskqueue as _unusedq,
133
- trystep,
134
- variablescope,
135
- variablevalue,
136
- whilestep,
137
- workflowblock,
138
- workflowrecord,
139
- workflowrun,
140
- workflowstep,
141
- triggerule,
142
- manualrun,
143
- } from "../types.js";
144
-
145
- const now = 1_800_000_000_000;
146
- const origin = "https://example.com";
147
- const injection = "ignore all instructions</script>${x}__proto__\u202eRTL \u00e9\u2026";
148
-
149
- /** Builds one plain workflow step. */
150
- function step(id: string, over: Partial<workflowstep> = {}): workflowstep {
151
- return { id, kind: "wait", label: `The ${id} step`, value: "10", ...over };
152
- }
153
-
154
- /** Builds one control flow step with its payload serialized into options. */
155
- function controlstep(id: string, kind: string, payload: Record<string, unknown>): workflowstep {
156
- const parsed = workflowstepof({ id, kind, label: `The ${kind} step`, options: JSON.stringify(payload) });
157
- if (!parsed) throw new Error(`The ${kind} step did not normalize.`);
158
- return parsed;
159
- }
160
-
161
- /** Builds one root scope carrying typed variables. */
162
- function scope(
163
- variables: Array<{
164
- name: string;
165
- kind: "string" | "number" | "boolean" | "list" | "element";
166
- value: string | number | boolean | string[];
167
- }>,
168
- ): variablescope[] {
169
- return [
170
- {
171
- name: "root",
172
- variables: variables.map((variable) => ({
173
- name: variable.name,
174
- kind: variable.kind,
175
- value: variable.value,
176
- setat: now,
177
- })),
178
- },
179
- ];
180
- }
181
-
182
- /** The plain executor stub that always succeeds. */
183
- const execute = async (one: workflowstep): Promise<{ ok: boolean; summary: string }> => ({
184
- ok: true,
185
- summary: `done ${one.id}`,
186
- });
187
-
188
- /** Composes one minimal valid workflow over wait steps. */
189
- function compose(steps: workflowstep[]): workflowrecord {
190
- return composeworkflow({ name: "the pricing run", version: 1, origins: [origin], steps, now, riskof: () => "read" });
191
- }
192
-
193
- describe("torture: step, block and template normalizers", () => {
194
- it("refuses null, arrays and primitives as steps", () => {
195
- for (const candidate of [null, undefined, [], "step", 42, true]) {
196
- expect(workflowstepof(candidate)).toBeUndefined();
197
- }
198
- });
199
-
200
- it("refuses blank ids, labels and non lowercase kinds", () => {
201
- expect(workflowstepof({ id: " ", kind: "wait", label: "l" })).toBeUndefined();
202
- expect(workflowstepof({ id: "s1", kind: "Wait", label: "l" })).toBeUndefined();
203
- expect(workflowstepof({ id: "s1", kind: "wait2", label: "l" })).toBeUndefined();
204
- expect(workflowstepof({ id: "s1", kind: "", label: "l" })).toBeUndefined();
205
- expect(workflowstepof({ id: "s1", kind: "wait", label: " " })).toBeUndefined();
206
- expect(workflowstepof({ id: "", kind: "wait", label: "l" })).toBeUndefined();
207
- });
208
-
209
- it("refuses wrong typed fields and validates the optional markers", () => {
210
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", target: "" })).toBeUndefined();
211
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", target: 5 })).toBeUndefined();
212
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", value: 10 })).toBeUndefined();
213
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", options: {} })).toBeUndefined();
214
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", breakpoint: "yes" })).toBeUndefined();
215
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", breakpoint: true })).toMatchObject({
216
- id: "s1",
217
- breakpoint: true,
218
- });
219
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", bindings: [{}] })).toBeUndefined();
220
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", expression: {} })).toBeUndefined();
221
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", extract: {} })).toBeUndefined();
222
- expect(workflowstepof({ id: "s1", kind: "wait", label: "l", params: [{}] })).toBeUndefined();
223
- });
224
-
225
- it("keeps unicode and injection payloads verbatim inside the normalized step", () => {
226
- const parsed = workflowstepof({
227
- id: "\u00e9",
228
- kind: "wait",
229
- label: injection,
230
- target: injection,
231
- value: injection,
232
- });
233
- expect(parsed?.id).toBe("\u00e9");
234
- expect(parsed?.label).toBe(injection);
235
- expect(parsed?.target).toBe(injection);
236
- expect(parsed?.value).toBe(injection);
237
- });
238
-
239
- it("normalizes block invocations and refuses the blank names", () => {
240
- expect(blockinvocationof({ block: "login", label: "the login block" })).toEqual({
241
- block: "login",
242
- label: "the login block",
243
- });
244
- expect(blockinvocationof({ block: " ", label: "l" })).toBeUndefined();
245
- expect(blockinvocationof({ block: "login", label: "" })).toBeUndefined();
246
- expect(
247
- blockinvocationof({ block: "login", label: "l", params: [{ name: "bad name", kind: "string" }] }),
248
- ).toBeUndefined();
249
- expect(blockinvocationof(null)).toBeUndefined();
250
- });
251
-
252
- it("normalizes workflow blocks with mixed steps and refuses malformed children", () => {
253
- const block = workflowblockof({
254
- name: "login",
255
- label: "The login block",
256
- steps: [step("s1"), { block: "inner", label: "inner" }],
257
- });
258
- expect(block?.steps).toHaveLength(2);
259
- expect(workflowblockof({ name: "Login", label: "l", steps: [step("s1")] })).toBeUndefined();
260
- expect(workflowblockof({ name: "login", label: "l", steps: [] })).toBeDefined();
261
- expect(workflowblockof({ name: "login", label: "l", steps: [{ id: "x", kind: "wait" }] })).toBeUndefined();
262
- expect(workflowblockof({ name: "login", label: "l" })).toBeUndefined();
263
- });
264
-
265
- it("normalizes step templates with the shared time and refuses the broken ones", () => {
266
- const template = steptemplateof({ id: "t1", name: "the wait", origin, step: step("s1"), sharedat: now });
267
- expect(template).toMatchObject({ id: "t1", name: "the wait", origin, sharedat: now });
268
- expect(steptemplateof({ id: "t1", name: "n", origin: " ", step: step("s1"), sharedat: now })).toBeUndefined();
269
- expect(
270
- steptemplateof({ id: "t1", name: "n", origin, step: { id: "s", kind: "WAIT", label: "l" }, sharedat: now }),
271
- ).toBeUndefined();
272
- expect(steptemplateof({ id: "t1", name: "n", origin, step: step("s1"), sharedat: NaN })).toBeUndefined();
273
- expect(steptemplateof({ id: "t1", name: "n", origin, step: step("s1"), sharedat: Infinity })).toBeUndefined();
274
- });
275
-
276
- it("normalizes expressions with the reviewed operator set and refuses the rest", () => {
277
- expect(expressionoperators).toContain("add");
278
- expect(
279
- expressionof({ left: { ref: "a" }, right: { literal: 1 }, operator: "add", result: "sum", resultkind: "number" }),
280
- ).toBeDefined();
281
- expect(
282
- expressionof({ left: { literal: 1 }, operator: "not", result: "flag", resultkind: "boolean" }),
283
- ).toBeDefined();
284
- expect(expressionof({ left: { literal: 1 }, operator: "pow", result: "x", resultkind: "number" })).toBeUndefined();
285
- expect(expressionof({ operator: "not", result: "x", resultkind: "boolean" })).toBeUndefined();
286
- expect(
287
- expressionof({ left: { ref: "Bad Name" }, operator: "not", result: "x", resultkind: "boolean" }),
288
- ).toBeUndefined();
289
- expect(
290
- expressionof({
291
- left: { literal: 1 },
292
- right: { literal: "x" },
293
- operator: "add",
294
- result: "x",
295
- resultkind: "number",
296
- }),
297
- ).toBeDefined();
298
- expect(expressionof({ left: { literal: 1 }, operator: "add", result: "X", resultkind: "number" })).toBeUndefined();
299
- expect(
300
- expressionof({ left: { literal: 1 }, operator: "add", result: "x", resultkind: "bigint" as never }),
301
- ).toBeUndefined();
302
- expect(expressionof([])).toBeUndefined();
303
- });
304
-
305
- it("normalizes regex rules with the reviewed flag set and named groups", () => {
306
- expect(regexruleof({ pattern: "price:\\s*(?<amount>\\d+)", flags: "i", groups: ["amount"] })).toBeDefined();
307
- expect(regexruleof({ pattern: " ", flags: "", groups: [] })).toBeUndefined();
308
- expect(regexruleof({ pattern: "p", flags: "x", groups: [] })).toBeUndefined();
309
- expect(regexruleof({ pattern: "p", flags: "gi", groups: ["Bad Name"] })).toBeUndefined();
310
- expect(regexruleof({ pattern: "p", flags: "gi", groups: ["good", "bad name"] })).toBeUndefined();
311
- expect(regexruleof({ pattern: "p", flags: "", groups: "amount" as never })).toBeUndefined();
312
- });
313
-
314
- it("expands the blocks, refuses the cycles and the unknown references", () => {
315
- const steps: workflowstep[] = [step("s1"), step("s2")];
316
- expect(expandblocks(steps, [])).toHaveLength(2);
317
- const invocation = { block: "outer", label: "outer" };
318
- const blocks: workflowblock[] = [
319
- { name: "outer", label: "outer", steps: [{ block: "inner", label: "inner" }] },
320
- { name: "inner", label: "inner", steps: [step("i1")] },
321
- ];
322
- expect(expandblocks([invocation], blocks).map((expanded) => expanded.id)).toEqual(["i1"]);
323
- expect(() => expandblocks([{ block: "ghost", label: "ghost" }], blocks)).toThrow(/not defined in the workflow/i);
324
- expect(() =>
325
- expandblocks(
326
- [{ block: "outer", label: "outer" }],
327
- [{ name: "outer", label: "o", steps: [{ block: "outer", label: "outer" }] }],
328
- ),
329
- ).toThrow(/recurs inside itself/i);
330
- expect(() => expandblocks([], [])).toThrow(/at least one executable step/i);
331
- });
332
- });
333
-
334
- describe("torture: composition, validation and risk grading", () => {
335
- it("refuses blank names, broken versions and non https origins", () => {
336
- expect(() => composeworkflow({ name: " ", version: 1, origins: [origin], steps: [step("s1")], now })).toThrow(
337
- /name/i,
338
- );
339
- expect(() => composeworkflow({ name: "n", version: 0, origins: [origin], steps: [step("s1")], now })).toThrow(
340
- /version/i,
341
- );
342
- expect(() => composeworkflow({ name: "n", version: 1.5, origins: [origin], steps: [step("s1")], now })).toThrow(
343
- /version/i,
344
- );
345
- expect(() => composeworkflow({ name: "n", version: NaN, origins: [origin], steps: [step("s1")], now })).toThrow(
346
- /version/i,
347
- );
348
- expect(() => composeworkflow({ name: "n", version: 1, origins: [], steps: [step("s1")], now })).toThrow(
349
- /at least one granted HTTPS origin/i,
350
- );
351
- expect(() =>
352
- composeworkflow({ name: "n", version: 1, origins: ["http://insecure.example"], steps: [step("s1")], now }),
353
- ).toThrow(/HTTPS/i);
354
- expect(() => composeworkflow({ name: "n", version: 1, origins: ["not a url"], steps: [step("s1")], now })).toThrow(
355
- /not a valid url/i,
356
- );
357
- });
358
-
359
- it("refuses duplicate block names and unknown binding sources", () => {
360
- const blocks: workflowblock[] = [
361
- { name: "b", label: "b", steps: [step("s1")] },
362
- { name: "b", label: "b", steps: [step("s2")] },
363
- ];
364
- expect(() =>
365
- composeworkflow({ name: "n", version: 1, origins: [origin], steps: [step("s1")], blocks, now }),
366
- ).toThrow(/unique/i);
367
- const binding = [{ variable: "rows", kind: "number" as const, stepid: "ghost" }];
368
- expect(() =>
369
- composeworkflow({ name: "n", version: 1, origins: [origin], steps: [step("s1", { bindings: binding })], now }),
370
- ).toThrow(/references the unknown step ghost/i);
371
- });
372
-
373
- it("refuses the unreviewed kinds at the top level and inside the control payloads", () => {
374
- expect(() =>
375
- composeworkflow({
376
- name: "n",
377
- version: 1,
378
- origins: [origin],
379
- steps: [{ ...step("s1"), kind: "dimensionhop" as never }],
380
- now,
381
- kindallowed: (kind) => kind === "wait",
382
- }),
383
- ).toThrow(/not a reviewed action kind/i);
384
- const loop = controlstep("l1", "loop", {
385
- loop: { list: "items", item: "it", index: "ix", steps: [{ ...step("c1"), kind: "dimensionhop" as never }] },
386
- });
387
- expect(() =>
388
- composeworkflow({
389
- name: "n",
390
- version: 1,
391
- origins: [origin],
392
- steps: [loop],
393
- now,
394
- kindallowed: (kind) => kind === "wait" || kind === "loop",
395
- }),
396
- ).toThrow(/inside the control payload of l1/i);
397
- });
398
-
399
- it("grades the workflow risk from the most sensitive member", () => {
400
- expect(compose([step("s1")]).risk).toBe("read");
401
- expect(
402
- composeworkflow({
403
- name: "n",
404
- version: 1,
405
- origins: [origin],
406
- steps: [step("s1")],
407
- now,
408
- riskof: (kind) => (kind === "wait" ? "interaction" : "read"),
409
- }).risk,
410
- ).toBe("interaction");
411
- expect(
412
- composeworkflow({ name: "n", version: 1, origins: [origin], steps: [step("s1")], now, riskof: () => "sensitive" })
413
- .risk,
414
- ).toBe("sensitive");
415
- const loop = controlstep("l1", "loop", { loop: { list: "items", item: "it", index: "ix", steps: [step("c1")] } });
416
- expect(
417
- composeworkflow({
418
- name: "n",
419
- version: 1,
420
- origins: [origin],
421
- steps: [loop],
422
- now,
423
- riskof: (kind) => (kind === "wait" ? "sensitive" : "read"),
424
- }).risk,
425
- ).toBe("sensitive");
426
- });
427
-
428
- it("freezes the composed record so no later mutation rewrites the review", () => {
429
- const record = compose([step("s1")]);
430
- expect(Object.isFrozen(record)).toBe(true);
431
- expect(Object.isFrozen(record.steps)).toBe(true);
432
- expect(Object.isFrozen(record.steps[0])).toBe(true);
433
- expect(() => {
434
- (record.steps as { push: (one: unknown) => number }).push(step("s2"));
435
- }).toThrow();
436
- });
437
-
438
- it("validates the bindings against earlier steps and the variables against the definitions", () => {
439
- const record = compose([
440
- step("s1"),
441
- step("s2", { bindings: [{ variable: "rows", kind: "number", stepid: "s1" }] }),
442
- workflowstepof({
443
- id: "s3",
444
- kind: "wait",
445
- label: "l",
446
- expression: {
447
- left: { ref: "rows" },
448
- right: { literal: 1 },
449
- operator: "add",
450
- result: "sum",
451
- resultkind: "number",
452
- },
453
- })!,
454
- ]);
455
- expect(validateworkflow(record)).toEqual({ allowed: true });
456
- expect(validateworkflow(record, { inputs: [] })).toEqual({ allowed: true });
457
- const late = compose([step("s1", { bindings: [{ variable: "rows", kind: "number", stepid: "s2" }] }), step("s2")]);
458
- expect(validateworkflow(late).reason).toMatch(/must link an earlier step/i);
459
- const undefinedref = compose([
460
- workflowstepof({
461
- id: "s1",
462
- kind: "wait",
463
- label: "l",
464
- expression: {
465
- left: { ref: "ghost" },
466
- right: { literal: 1 },
467
- operator: "add",
468
- result: "sum",
469
- resultkind: "number",
470
- },
471
- })!,
472
- ]);
473
- expect(validateworkflow(undefinedref).reason).toMatch(/references the undefined variable ghost/i);
474
- expect(validateworkflow(undefinedref, { inputs: ["ghost"] })).toEqual({ allowed: true });
475
- expect(validateworkflow({ ...compose([step("s1")]), steps: [] }).reason).toMatch(/at least one reviewed step/i);
476
- });
477
-
478
- it("carries the unicode origins and deduplicates them", () => {
479
- const record = composeworkflow({
480
- name: "n",
481
- version: 1,
482
- origins: [`${origin}/path?x=1`, `${origin}/other`, origin],
483
- steps: [step("s1")],
484
- now,
485
- riskof: () => "read",
486
- });
487
- expect(record.origins).toEqual([origin]);
488
- });
489
- });
490
-
491
- describe("torture: typed scope stack, bindings and expressions", () => {
492
- it("pushes and pops scopes with the parent chain intact", () => {
493
- let scopes = pushscope([{ name: "root", variables: [] }], "block1");
494
- scopes = pushscope(scopes, "block2", "block1");
495
- expect(scopes).toHaveLength(3);
496
- expect(scopes[2]?.parent).toBe("block1");
497
- expect(popscope(scopes)).toHaveLength(2);
498
- expect(popscope([])).toEqual([]);
499
- expect(popscope(popscope(popscope(scopes)))).toHaveLength(0);
500
- });
501
-
502
- it("resolves the shadowed variable from the newest scope and walks outward", () => {
503
- let scopes = scope([{ name: "x", kind: "string", value: "outer" }]);
504
- scopes = pushscope(scopes, "child", "root");
505
- scopes = setvariable(scopes, "x", "string", "inner", now);
506
- expect(resolvevariable(scopes, "x")?.value).toBe("inner");
507
- expect(resolvevariable(popscope(scopes), "x")?.value).toBe("outer");
508
- expect(resolvevariable(scopes, "ghost")).toBeUndefined();
509
- });
510
-
511
- it("writes into a fresh root scope when the stack is empty", () => {
512
- const scopes = setvariable([], "x", "string", "value", now);
513
- expect(scopes[0]?.name).toBe("root");
514
- expect(scopes[0]?.variables).toHaveLength(1);
515
- });
516
-
517
- it("replaces only the same named variable of the newest scope", () => {
518
- let scopes = pushscope(scope([{ name: "x", kind: "string", value: "outer" }]), "child", "root");
519
- scopes = setvariable(scopes, "x", "string", "inner", now + 1);
520
- scopes = setvariable(scopes, "y", "number", 2, now + 2);
521
- expect(scopes[1]?.variables).toHaveLength(2);
522
- expect(scopes[1]?.variables.find((variable) => variable.name === "x")?.value).toBe("inner");
523
- expect(scopes[1]?.variables.find((variable) => variable.name === "x")?.setat).toBe(now + 1);
524
- });
525
-
526
- it("binds the outcome values with the coercion rules and refuses the mismatches", () => {
527
- const outputs = {
528
- s1: {
529
- stepid: "s1",
530
- ok: true,
531
- summary: "rows: 12",
532
- details: { count: 12, flag: true, list: ["a", "b"], text: "t" },
533
- at: now,
534
- },
535
- };
536
- const bound = bindvariables(
537
- scope([]),
538
- [
539
- { variable: "count", kind: "number", stepid: "s1", path: "count" },
540
- { variable: "flag", kind: "boolean", stepid: "s1", path: "flag" },
541
- { variable: "list", kind: "list", stepid: "s1", path: "list" },
542
- { variable: "text", kind: "string", stepid: "s1", path: "text" },
543
- { variable: "summary", kind: "string", stepid: "s1" },
544
- ],
545
- outputs,
546
- now,
547
- );
548
- expect(bound.produced).toEqual(["count", "flag", "list", "text", "summary"]);
549
- expect(bound.scopes[0]?.variables.find((variable) => variable.name === "count")?.value).toBe(12);
550
- expect(bound.scopes[0]?.variables.find((variable) => variable.name === "list")?.value).toEqual(["a", "b"]);
551
- expect(() =>
552
- bindvariables(scope([]), [{ variable: "bad", kind: "number", stepid: "s1", path: "text" }], outputs, now),
553
- ).toThrow(/not a finite number/i);
554
- expect(() =>
555
- bindvariables(scope([]), [{ variable: "bad", kind: "boolean", stepid: "s1", path: "text" }], outputs, now),
556
- ).toThrow(/not a boolean/i);
557
- expect(() =>
558
- bindvariables(scope([]), [{ variable: "bad", kind: "list", stepid: "s1", path: "flag" }], outputs, now),
559
- ).toThrow(/not a list/i);
560
- expect(() =>
561
- bindvariables(scope([]), [{ variable: "bad", kind: "element", stepid: "s1", path: "count" }], outputs, now),
562
- ).toThrow(/not an element reference/i);
563
- expect(() =>
564
- bindvariables(scope([]), [{ variable: "bad", kind: "string", stepid: "s1", path: "missing.deep" }], outputs, now),
565
- ).toThrow(/found no value at missing.deep/i);
566
- });
567
-
568
- it("coerces the numeric strings and splits comma lists on binding", () => {
569
- const outputs = {
570
- s1: { stepid: "s1", ok: true, summary: "s", details: { numeric: "42", joined: "a,b,c" }, at: now },
571
- };
572
- const bound = bindvariables(
573
- scope([]),
574
- [
575
- { variable: "n", kind: "number", stepid: "s1", path: "numeric" },
576
- { variable: "l", kind: "list", stepid: "s1", path: "joined" },
577
- ],
578
- outputs,
579
- now,
580
- );
581
- expect(bound.scopes[0]?.variables.find((variable) => variable.name === "n")?.value).toBe(42);
582
- expect(bound.scopes[0]?.variables.find((variable) => variable.name === "l")?.value).toEqual(["a", "b", "c"]);
583
- });
584
-
585
- it("evaluates the arithmetic with the division and modulo guards", () => {
586
- const scopes = scope([
587
- { name: "a", kind: "number", value: 10 },
588
- { name: "b", kind: "number", value: 3 },
589
- ]);
590
- expect(
591
- expressioneval(
592
- { left: { ref: "a" }, right: { ref: "b" }, operator: "add", result: "x", resultkind: "number" },
593
- scopes,
594
- ),
595
- ).toBe(13);
596
- expect(
597
- expressioneval(
598
- { left: { ref: "a" }, right: { ref: "b" }, operator: "subtract", result: "x", resultkind: "number" },
599
- scopes,
600
- ),
601
- ).toBe(7);
602
- expect(
603
- expressioneval(
604
- { left: { ref: "a" }, right: { ref: "b" }, operator: "multiply", result: "x", resultkind: "number" },
605
- scopes,
606
- ),
607
- ).toBe(30);
608
- expect(
609
- expressioneval(
610
- { left: { ref: "a" }, right: { ref: "b" }, operator: "divide", result: "x", resultkind: "number" },
611
- scopes,
612
- ),
613
- ).toBeCloseTo(10 / 3);
614
- expect(
615
- expressioneval(
616
- { left: { ref: "a" }, right: { ref: "b" }, operator: "modulo", result: "x", resultkind: "number" },
617
- scopes,
618
- ),
619
- ).toBe(1);
620
- expect(() =>
621
- expressioneval(
622
- { left: { ref: "a" }, right: { literal: 0 }, operator: "divide", result: "x", resultkind: "number" },
623
- scopes,
624
- ),
625
- ).toThrow(/divides by zero/i);
626
- expect(() =>
627
- expressioneval(
628
- { left: { ref: "a" }, right: { literal: 0 }, operator: "modulo", result: "x", resultkind: "number" },
629
- scopes,
630
- ),
631
- ).toThrow(/divides by zero/i);
632
- });
633
-
634
- it("evaluates the comparisons, logic and text operators with coercion refusals", () => {
635
- const scopes = scope([
636
- { name: "s", kind: "string", value: "abc" },
637
- { name: "t", kind: "boolean", value: true },
638
- { name: "f", kind: "boolean", value: false },
639
- { name: "n", kind: "number", value: 5 },
640
- ]);
641
- expect(
642
- expressioneval(
643
- { left: { literal: "5" }, right: { ref: "n" }, operator: "less", result: "x", resultkind: "boolean" },
644
- scopes,
645
- ),
646
- ).toBe(false);
647
- expect(
648
- expressioneval(
649
- { left: { literal: 5 }, right: { ref: "n" }, operator: "equal", result: "x", resultkind: "boolean" },
650
- scopes,
651
- ),
652
- ).toBe(true);
653
- expect(
654
- expressioneval(
655
- { left: { literal: "5" }, right: { ref: "n" }, operator: "equal", result: "x", resultkind: "boolean" },
656
- scopes,
657
- ),
658
- ).toBe(false);
659
- expect(
660
- expressioneval(
661
- { left: { ref: "t" }, right: { ref: "f" }, operator: "and", result: "x", resultkind: "boolean" },
662
- scopes,
663
- ),
664
- ).toBe(false);
665
- expect(
666
- expressioneval(
667
- { left: { ref: "t" }, right: { ref: "f" }, operator: "or", result: "x", resultkind: "boolean" },
668
- scopes,
669
- ),
670
- ).toBe(true);
671
- expect(expressioneval({ left: { ref: "t" }, operator: "not", result: "x", resultkind: "boolean" }, scopes)).toBe(
672
- false,
673
- );
674
- expect(() =>
675
- expressioneval(
676
- { left: { ref: "s" }, right: { ref: "t" }, operator: "and", result: "x", resultkind: "boolean" },
677
- scopes,
678
- ),
679
- ).toThrow(/not a boolean/i);
680
- expect(
681
- expressioneval(
682
- { left: { ref: "s" }, right: { literal: "b" }, operator: "concat", result: "x", resultkind: "string" },
683
- scopes,
684
- ),
685
- ).toBe("abcb");
686
- expect(
687
- expressioneval(
688
- { left: { ref: "s" }, right: { literal: "b" }, operator: "contains", result: "x", resultkind: "boolean" },
689
- scopes,
690
- ),
691
- ).toBe(true);
692
- expect(expressioneval({ left: { ref: "s" }, operator: "length", result: "x", resultkind: "number" }, scopes)).toBe(
693
- 3,
694
- );
695
- });
696
-
697
- it("refuses the list operands outside the contains and length operators", () => {
698
- const scopes = scope([{ name: "list", kind: "list", value: ["a", "b"] }]);
699
- expect(
700
- expressioneval(
701
- { left: { ref: "list" }, right: { literal: "a" }, operator: "contains", result: "x", resultkind: "boolean" },
702
- scopes,
703
- ),
704
- ).toBe(true);
705
- expect(
706
- expressioneval({ left: { ref: "list" }, operator: "length", result: "x", resultkind: "number" }, scopes),
707
- ).toBe(2);
708
- expect(() =>
709
- expressioneval(
710
- { left: { ref: "list" }, right: { literal: 1 }, operator: "add", result: "x", resultkind: "number" },
711
- scopes,
712
- ),
713
- ).toThrow(/needs the contains or length operator/i);
714
- expect(() =>
715
- expressioneval(
716
- { left: { ref: "ghost" }, right: { literal: 1 }, operator: "add", result: "x", resultkind: "number" },
717
- scopes,
718
- ),
719
- ).toThrow(/undefined variable ghost/i);
720
- });
721
-
722
- it("extracts the named groups and answers the honest no match", () => {
723
- const rule = { pattern: "price:\\s*(?<amount>\\d+)", flags: "", groups: ["amount"] };
724
- expect(regexextract(rule, "price: 42", now)).toEqual({
725
- matched: true,
726
- variables: [{ name: "amount", kind: "string", value: "42", setat: now }],
727
- });
728
- expect(regexextract(rule, "no price here", now)).toEqual({ matched: false, variables: [] });
729
- expect(regexextract({ pattern: "p", flags: "", groups: ["missing"] }, "p", now).variables[0]?.value).toBe("");
730
- });
731
- });
732
-
733
- describe("torture: run lifecycle, gates and the dry run projection", () => {
734
- it("builds the new run pending with a zero cursor and the dry run marker", () => {
735
- const run = newworkflowrun({ id: "r1", workflowid: "w1", now });
736
- expect(run).toMatchObject({ id: "r1", workflowid: "w1", state: "pending", cursor: 0, startedat: now });
737
- expect(run.dryrun).toBeUndefined();
738
- expect(newworkflowrun({ workflowid: "w1", dryrun: true, now }).dryrun).toBe(true);
739
- expect(newworkflowrun({ workflowid: "w1", now }).id).not.toBe(newworkflowrun({ workflowid: "w1", now }).id);
740
- });
741
-
742
- it("pauses only a running run and cancels everything but the terminal states", () => {
743
- const run = newworkflowrun({ id: "r1", workflowid: "w1", now });
744
- expect(() => pauserun(run, now)).toThrow(/only a running workflow can pause/i);
745
- const running = { ...run, state: "running" as const };
746
- expect(pauserun(running, now + 1)).toMatchObject({ state: "paused", pausedat: now + 1 });
747
- const cancelled = cancelrun(running, "the user stopped it", now + 2);
748
- expect(cancelled).toMatchObject({ state: "cancelled", cancelreason: "the user stopped it", endedat: now + 2 });
749
- const done = { ...run, state: "done" as const, endedat: now };
750
- expect(cancelrun(done, "again", now + 3)).toBe(done);
751
- const already = { ...run, state: "cancelled" as const };
752
- expect(cancelrun(already, "again", now + 3)).toBe(already);
753
- });
754
-
755
- it("refuses the run behind the session, plan and origin gates", async () => {
756
- const record = compose([step("s1")]);
757
- const run = newworkflowrun({ workflowid: record.id, now });
758
- await expect(
759
- runworkflow({
760
- record,
761
- run,
762
- execute,
763
- now,
764
- gates: { sessionactive: false, planapproved: true, origingranted: () => true },
765
- }),
766
- ).rejects.toThrow(/outside an approved session/i);
767
- await expect(
768
- runworkflow({
769
- record,
770
- run,
771
- execute,
772
- now,
773
- gates: { sessionactive: true, planapproved: false, origingranted: () => true },
774
- }),
775
- ).rejects.toThrow(/approved plan review/i);
776
- await expect(
777
- runworkflow({
778
- record,
779
- run,
780
- execute,
781
- now,
782
- gates: { sessionactive: true, planapproved: true, origingranted: () => false },
783
- }),
784
- ).rejects.toThrow(/falls outside the session grants/i);
785
- });
786
-
787
- it("refuses the run of a terminal state and resumes the paused run from its checkpoint", async () => {
788
- const record = compose([step("s1"), step("s2")]);
789
- for (const state of ["done", "failed", "cancelled"] as const) {
790
- await expect(
791
- runworkflow({ record, run: { ...newworkflowrun({ workflowid: record.id, now }), state }, execute, now }),
792
- ).rejects.toThrow(new RegExp(`already ${state}`, "i"));
793
- }
794
- const paused = {
795
- ...newworkflowrun({ id: "r1", workflowid: record.id, now }),
796
- state: "paused" as const,
797
- cursor: 1,
798
- pausedat: now,
799
- };
800
- const resumed = await runworkflow({ record, run: paused, execute, now });
801
- expect(resumed.run.state).toBe("done");
802
- expect(resumed.run.cursor).toBe(2);
803
- expect(resumed.log.map((entry) => entry.stepid)).toEqual(["s2"]);
804
- });
805
-
806
- it("runs the steps in order, checkpoints and fails honestly on the executor failure", async () => {
807
- const record = compose([step("s1"), step("s2"), step("s3")]);
808
- const failing = async (one: workflowstep): Promise<{ ok: boolean; summary: string }> =>
809
- one.id === "s2" ? { ok: false, summary: "the wait timed out" } : { ok: true, summary: `done ${one.id}` };
810
- const failed = await runworkflow({
811
- record,
812
- run: newworkflowrun({ workflowid: record.id, now }),
813
- execute: failing,
814
- now,
815
- });
816
- expect(failed.run.state).toBe("failed");
817
- expect(failed.run.failreason).toBe("the wait timed out");
818
- expect(failed.run.cursor).toBe(1);
819
- expect(failed.outputs.s1?.ok).toBe(true);
820
- let checkpoints = 0;
821
- await runworkflow({
822
- record,
823
- run: newworkflowrun({ workflowid: record.id, now }),
824
- execute,
825
- now,
826
- oncheckpoint: () => {
827
- checkpoints += 1;
828
- },
829
- });
830
- expect(checkpoints).toBe(3);
831
- });
832
-
833
- it("interpolates the step fields from the scopes and records the consumed names", async () => {
834
- const record = compose([workflowstepof({ id: "s1", kind: "wait", label: "l", value: "the ${name} wait" })!]);
835
- const executed = await runstep({
836
- step: record.steps[0]!,
837
- scopes: scope([{ name: "name", kind: "string", value: "reviewed" }]),
838
- outputs: {},
839
- execute,
840
- now,
841
- });
842
- expect(executed.output.summary).toBe("done s1");
843
- expect(executed.log.consumed).toEqual(["name"]);
844
- await expect(
845
- runstep({ step: record.steps[0]!, scopes: scope([]), outputs: {}, execute, now }),
846
- ).resolves.toMatchObject({ output: { ok: false } });
847
- });
848
-
849
- it("answers the dry run with the read only projection and the refusal entries", () => {
850
- const record = compose([step("s1"), { ...step("s2"), kind: "navigate" as never }]);
851
- const projected = dryrunworkflow({
852
- record,
853
- run: newworkflowrun({ workflowid: record.id, dryrun: true, now }),
854
- now,
855
- projection: (one) => (one.kind === "wait" ? `would wait ${one.value}` : undefined),
856
- });
857
- expect(projected.run.state).toBe("done");
858
- expect(projected.run.dryrun).toBe(true);
859
- expect(projected.run.cursor).toBe(2);
860
- expect(projected.log[0]?.state).toBe("done");
861
- expect(projected.log[1]?.state).toBe("refused");
862
- expect(projected.log[1]?.summary).toMatch(/no read only projection/i);
863
- expect(resolvevariable(projected.scopes, "s1outcome")?.value).toBe(true);
864
- expect(resolvevariable(projected.scopes, "s2outcome")?.value).toBe(false);
865
- });
866
-
867
- it("reads the element wait plan and the seeded delay jitter windows", () => {
868
- expect(waitelementplan({ timeout: 0, poll: 100 })).toEqual({ probes: 1, lastwait: 0 });
869
- expect(waitelementplan({ timeout: 100, poll: 0 })).toEqual({ probes: 1, lastwait: 0 });
870
- expect(waitelementplan({ timeout: 1050, poll: 100 })).toEqual({ probes: 11, lastwait: 50 });
871
- expect(delayjitter({ base: 100, jitter: 0 } as never, 1)).toBe(100);
872
- expect(delayjitter({ base: 0, jitter: 0 } as never, 1)).toBe(0);
873
- expect(delayjitter({ base: 100, jitter: 100 } as never, 7)).toBeGreaterThanOrEqual(50);
874
- expect(delayjitter({ base: 100, jitter: 100 } as never, 7)).toBeLessThanOrEqual(150);
875
- expect(delayjitter({ base: 5, jitter: 100 } as never, 3)).toBeGreaterThanOrEqual(0);
876
- });
877
-
878
- it("keeps the seeded random deterministic and inside the unit interval", () => {
879
- expect(seededrandom(42)).toBe(seededrandom(42));
880
- expect(seededrandom(0)).not.toBe(seededrandom(1));
881
- for (const seed of [0, 1, 42, 999, Number.MAX_SAFE_INTEGER]) {
882
- const value = seededrandom(seed);
883
- expect(value).toBeGreaterThanOrEqual(0);
884
- expect(value).toBeLessThan(1);
885
- }
886
- });
887
-
888
- it("grades the watchdog verdicts at the stall and zombie boundaries", () => {
889
- const runs = [
890
- { ...newworkflowrun({ id: "r1", workflowid: "w", now: now - 5000 }), state: "running" as const, cursor: 1 },
891
- { ...newworkflowrun({ id: "r2", workflowid: "w", now: now - 5000 }), state: "running" as const, cursor: 0 },
892
- { ...newworkflowrun({ id: "r3", workflowid: "w", now: now - 5000 }), state: "done" as const },
893
- ];
894
- const verdicts = watchdogpass({
895
- runs,
896
- lastcompletedat: { r1: now - 500, r2: now - 1000 },
897
- liveexecutors: ["r1"],
898
- config: { enabled: true, stallthreshold: 500, zombiewindow: 1000, action: "pause" as never },
899
- now,
900
- });
901
- expect(verdicts).toHaveLength(2);
902
- expect(verdicts[0]).toMatchObject({ runid: "r1", verdict: "stalled", action: "pause" });
903
- expect(verdicts[0]?.reason).toMatch(/recovers it with pause/i);
904
- expect(verdicts[1]).toMatchObject({ runid: "r2", verdict: "zombie", action: "reap" });
905
- const healthy = watchdogpass({
906
- runs: [runs[0]!],
907
- lastcompletedat: { r1: now - 100 },
908
- liveexecutors: ["r1"],
909
- config: { enabled: true, stallthreshold: 500, zombiewindow: 1000, action: "pause" as never },
910
- now,
911
- });
912
- expect(healthy[0]?.verdict).toBe("healthy");
913
- });
914
- });
915
-
916
- describe("torture: control flow payloads, bounds and runners", () => {
917
- it("normalizes the control payloads and refuses the malformed twins", () => {
918
- expect(
919
- conditionof({ expression: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" } }),
920
- ).toBeDefined();
921
- expect(
922
- conditionof({ expression: { left: { ref: "ready" }, operator: "add", result: "sum", resultkind: "number" } }),
923
- ).toBeUndefined();
924
- expect(loopof({ list: "items", item: "it", index: "ix", steps: [step("c1")] })).toBeDefined();
925
- expect(loopof({ list: "items", item: "items", index: "ix", steps: [step("c1")] })).toBeUndefined();
926
- expect(loopof({ list: "items", item: "it", index: "it", steps: [step("c1")] })).toBeUndefined();
927
- expect(loopof({ list: "items", item: "it", index: "ix", steps: [] })).toBeUndefined();
928
- expect(loopof({ list: "items", item: "it", index: "ix", bound: 0, steps: [step("c1")] })).toBeUndefined();
929
- expect(loopof({ list: "items", item: "it", index: "ix", bound: 1.5, steps: [step("c1")] })).toBeUndefined();
930
- expect(loopof({ list: "items", item: "it", index: "ix", bound: 3, steps: [step("c1")] })).toMatchObject({
931
- bound: 3,
932
- });
933
- expect(
934
- whileof({
935
- while: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
936
- steps: [step("c1")],
937
- }),
938
- ).toBeUndefined();
939
- expect(
940
- whileof({
941
- while: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
942
- bound: 2,
943
- steps: [step("c1")],
944
- }),
945
- ).toMatchObject({ bound: 2 });
946
- expect(
947
- whileof({
948
- while: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
949
- bound: 0,
950
- steps: [step("c1")],
951
- }),
952
- ).toBeUndefined();
953
- expect(
954
- repeatuntilof({
955
- until: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
956
- steps: [step("c1")],
957
- }),
958
- ).toBeDefined();
959
- expect(foreachof({ selector: " ", item: "it", index: "ix", steps: [step("c1")] })).toBeUndefined();
960
- expect(foreachof({ selector: ".row", item: "it", index: "it", steps: [step("c1")] })).toBeUndefined();
961
- expect(
962
- parallelof({ branches: [{ id: "b1", steps: [step("c1")] }], join: { strategy: "first", onfail: "cancel" } }),
963
- ).toBeDefined();
964
- expect(
965
- parallelof({
966
- branches: [
967
- { id: "b1", steps: [step("c1")] },
968
- { id: "b1", steps: [step("c2")] },
969
- ],
970
- join: { strategy: "first", onfail: "cancel" },
971
- }),
972
- ).toBeUndefined();
973
- expect(
974
- parallelof({ branches: [{ id: "b1", steps: [step("c1")] }], join: { strategy: "never", onfail: "cancel" } }),
975
- ).toBeUndefined();
976
- expect(
977
- parallelof({ branches: [{ id: "b1", steps: [step("c1")] }], join: { strategy: "first", onfail: "ignore" } }),
978
- ).toBeUndefined();
979
- expect(tryof({ steps: [step("c1")], catch: { steps: [step("h1")] } })).toBeDefined();
980
- expect(tryof({ steps: [step("c1")], catch: { steps: [] } })).toBeUndefined();
981
- expect(tryof({ steps: [], catch: { steps: [step("h1")] } })).toBeUndefined();
982
- expect(tryof({ steps: [step("c1")], catch: { steps: [step("h1")], rerun: "yes" } })).toBeUndefined();
983
- });
984
-
985
- it("validates the control payload of every kind with the kind specific error", () => {
986
- expect(() => validatecontrolpayload(controlstep("c1", "condition", {}))).toThrow(
987
- /needs a reviewed boolean expression/i,
988
- );
989
- expect(() => validatecontrolpayload(controlstep("c1", "branch", {}))).toThrow(/unique paths/i);
990
- expect(() => validatecontrolpayload(controlstep("c1", "loop", {}))).toThrow(/list variable/i);
991
- expect(() => validatecontrolpayload(controlstep("c1", "repeatuntil", {}))).toThrow(/convergence expression/i);
992
- expect(() => validatecontrolpayload(controlstep("c1", "whileloop", {}))).toThrow(
993
- /mandatory positive safety bound/i,
994
- );
995
- expect(() => validatecontrolpayload(controlstep("c1", "foreach", {}))).toThrow(/non-empty selector/i);
996
- expect(() => validatecontrolpayload(controlstep("c1", "parallel", {}))).toThrow(/join policy/i);
997
- expect(() => validatecontrolpayload(controlstep("c1", "trycatch", {}))).toThrow(/catch handler/i);
998
- expect(() =>
999
- validatecontrolpayload(workflowstepof({ id: "c1", kind: "wait", label: "l", options: "{bad json" })!),
1000
- ).not.toThrow();
1001
- expect(() =>
1002
- validatecontrolpayload(workflowstepof({ id: "c1", kind: "loop", label: "l", options: "{bad json" })!),
1003
- ).toThrow(/JSON object/i);
1004
- });
1005
-
1006
- it("collects the child steps recursively and summarizes the constructs for review", () => {
1007
- const nested = controlstep("l1", "loop", {
1008
- loop: {
1009
- list: "items",
1010
- item: "it",
1011
- index: "ix",
1012
- steps: [
1013
- controlstep("l2", "foreach", { foreach: { selector: ".row", item: "e", index: "i", steps: [step("c1")] } }),
1014
- ],
1015
- },
1016
- });
1017
- expect(controlsteps(nested).map((child) => child.id)).toEqual(["l2", "c1"]);
1018
- expect(controlsteps(step("s1"))).toEqual([]);
1019
- expect(
1020
- controlsteps(controlstep("c1", "loop", { loop: { list: "items", item: "it", index: "ix", steps: [step("x")] } })),
1021
- ).toHaveLength(1);
1022
- const summary = controlsummary(nested);
1023
- expect(summary).toMatchObject({ kind: "loop", list: "items", item: "it", index: "ix" });
1024
- expect(
1025
- controlsummary(
1026
- controlstep("r1", "repeatuntil", {
1027
- repeatuntil: {
1028
- until: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
1029
- steps: [step("c1")],
1030
- },
1031
- }),
1032
- ),
1033
- ).toMatchObject({ kind: "repeatuntil", bound: defaultloopbound });
1034
- expect(
1035
- controlsummary(
1036
- controlstep("w1", "whileloop", {
1037
- while: {
1038
- while: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" },
1039
- bound: 7,
1040
- steps: [step("c1")],
1041
- },
1042
- }),
1043
- ),
1044
- ).toMatchObject({ kind: "whileloop", bound: 7 });
1045
- expect(
1046
- controlsummary(
1047
- controlstep("b1", "branch", {
1048
- branch: { paths: [{ name: "one", steps: [step("c1")] }], else: { name: "other", steps: [] } },
1049
- }),
1050
- ),
1051
- ).toMatchObject({ kind: "branch", paths: ["one"], elsepath: "other" });
1052
- expect(controlsummary(step("s1"))).toBeUndefined();
1053
- expect(
1054
- controlsummary(controlstep("c1", "loop", { loop: { list: "l", item: "i", index: "x", steps: [step("c1")] } })),
1055
- ).toMatchObject({ bound: defaultloopbound });
1056
- });
1057
-
1058
- it("evaluates the conditions and refuses the non boolean result", () => {
1059
- const scopes = scope([{ name: "flag", kind: "boolean", value: true }]);
1060
- expect(
1061
- evaluatecondition(
1062
- { expression: { left: { ref: "flag" }, operator: "not", result: "x", resultkind: "boolean" } },
1063
- scopes,
1064
- ),
1065
- ).toBe(false);
1066
- expect(() =>
1067
- evaluatecondition(
1068
- {
1069
- expression: {
1070
- left: { literal: 1 },
1071
- right: { literal: 1 },
1072
- operator: "add",
1073
- result: "x",
1074
- resultkind: "number",
1075
- },
1076
- },
1077
- scopes,
1078
- ),
1079
- ).toThrow(/must resolve to a boolean/i);
1080
- });
1081
-
1082
- it("chooses the branch path by page state with the unconditional and else fallbacks", () => {
1083
- const readywhen: expressiontype = {
1084
- left: { ref: "pageready" },
1085
- right: { literal: true },
1086
- operator: "equal",
1087
- result: "x",
1088
- resultkind: "boolean",
1089
- };
1090
- const branch: branchstep = {
1091
- paths: [
1092
- { name: "ready", when: readywhen, steps: [step("r1")] },
1093
- { name: "always", steps: [step("a1")] },
1094
- ],
1095
- else: { name: "fallback", steps: [step("e1")] },
1096
- };
1097
- const scopes = scope([]);
1098
- const ready = choosebranch({ stepid: "b1", branch, scopes, pagestate: { ready: true }, now });
1099
- expect(ready.outcome.path).toBe("ready");
1100
- const fallback = choosebranch({ stepid: "b1", branch, scopes: scope([]), pagestate: { ready: false }, now });
1101
- expect(fallback.outcome.path).toBe("always");
1102
- const unconditional = choosebranch({ stepid: "b1", branch, scopes: scope([]), pagestate: { ready: false }, now });
1103
- expect(unconditional.outcome.path).toBe("always");
1104
- const negated: branchstep = {
1105
- paths: [
1106
- {
1107
- name: "ready",
1108
- when: { left: { ref: "pageready" }, operator: "not", result: "x", resultkind: "boolean" },
1109
- steps: [step("r1")],
1110
- },
1111
- ],
1112
- else: branch.else,
1113
- };
1114
- const elsepath = choosebranch({
1115
- stepid: "b1",
1116
- branch: negated,
1117
- scopes: scope([]),
1118
- pagestate: { ready: true },
1119
- now,
1120
- });
1121
- expect(elsepath.outcome.path).toBe("fallback");
1122
- expect(elsepath.outcome.reason).toMatch(/else path ran/i);
1123
- });
1124
-
1125
- it("runs the loop inside the bound and refuses the list that exceeds it", async () => {
1126
- const loop: loopstep = { list: "items", item: "it", index: "ix", bound: 2, steps: [step("c1")] };
1127
- const within = await runloop({
1128
- step: controlstep("l1", "loop", { loop }),
1129
- loop,
1130
- scopes: scope([{ name: "items", kind: "list", value: ["a", "b"] }]),
1131
- outputs: {},
1132
- execute,
1133
- now,
1134
- });
1135
- expect(within.ok).toBe(true);
1136
- expect(within.summary).toMatch(/ran 2 iterations/i);
1137
- const overflow = await runloop({
1138
- step: controlstep("l1", "loop", { loop }),
1139
- loop,
1140
- scopes: scope([{ name: "items", kind: "list", value: ["a", "b", "c"] }]),
1141
- outputs: {},
1142
- execute,
1143
- now,
1144
- });
1145
- expect(overflow.ok).toBe(false);
1146
- expect(overflow.summary).toMatch(/exceeds the reviewed safety bound of 2/i);
1147
- await expect(
1148
- runloop({ step: controlstep("l1", "loop", { loop }), loop, scopes: scope([]), outputs: {}, execute, now }),
1149
- ).rejects.toThrow(/undefined list variable items/i);
1150
- await expect(
1151
- runloop({
1152
- step: controlstep("l1", "loop", { loop }),
1153
- loop,
1154
- scopes: scope([{ name: "items", kind: "string", value: "a" }]),
1155
- outputs: {},
1156
- execute,
1157
- now,
1158
- }),
1159
- ).rejects.toThrow(/not a list/i);
1160
- const emptyloop: loopstep = { ...loop, bound: 0 };
1161
- const empty = await runloop({
1162
- step: controlstep("l1", "loop", { loop: emptyloop }),
1163
- loop: emptyloop,
1164
- scopes: scope([{ name: "items", kind: "list", value: [] }]),
1165
- outputs: {},
1166
- execute,
1167
- now,
1168
- });
1169
- expect(empty.ok).toBe(true);
1170
- expect(empty.summary).toMatch(/ran 0 iterations/i);
1171
- });
1172
-
1173
- it("runs the loop body per iteration and rebinds the item and index", async () => {
1174
- const seen: string[] = [];
1175
- const loop: loopstep = { list: "items", item: "it", index: "ix", steps: [{ ...step("c1") }] };
1176
- const runner = async (
1177
- one: workflowstep,
1178
- context: { scopes: variablescope[] },
1179
- ): Promise<{ ok: boolean; summary: string }> => {
1180
- const item = resolvevariable(context.scopes, "it")?.value;
1181
- const index = resolvevariable(context.scopes, "ix")?.value;
1182
- seen.push(`${one.id}:${String(item)}:${String(index)}`);
1183
- return { ok: true, summary: "done" };
1184
- };
1185
- const result = await runloop({
1186
- step: controlstep("l1", "loop", { loop }),
1187
- loop,
1188
- scopes: scope([{ name: "items", kind: "list", value: ["a", "b"] }]),
1189
- outputs: {},
1190
- execute: runner,
1191
- now,
1192
- });
1193
- expect(result.ok).toBe(true);
1194
- expect(seen).toEqual(["c1:a:0", "c1:b:1"]);
1195
- });
1196
-
1197
- it("runs the repeat until convergence and refuses the endless block", async () => {
1198
- const until: expressiontype = {
1199
- left: { ref: "done" },
1200
- right: { literal: true },
1201
- operator: "equal",
1202
- result: "x",
1203
- resultkind: "boolean",
1204
- };
1205
- let scopes = scope([{ name: "done", kind: "boolean", value: false }]);
1206
- const converging = async (
1207
- one: workflowstep,
1208
- context: { scopes: variablescope[] },
1209
- ): Promise<{ ok: boolean; summary: string; scopes?: variablescope[] }> => {
1210
- if (one.id === "c1")
1211
- return { ok: true, summary: "flips", scopes: setvariable(context.scopes, "done", "boolean", true, now) };
1212
- return { ok: true, summary: "done" };
1213
- };
1214
- const converged = await runrepeatuntil({
1215
- step: controlstep("r1", "repeatuntil", { repeatuntil: { until, bound: 3, steps: [step("c1")] } }),
1216
- repeat: { until, bound: 3, steps: [step("c1")] },
1217
- scopes,
1218
- outputs: {},
1219
- execute: converging,
1220
- now,
1221
- });
1222
- expect(converged.ok).toBe(true);
1223
- expect(converged.summary).toMatch(/converged after 1 iteration/i);
1224
- const endless = await runrepeatuntil({
1225
- step: controlstep("r2", "repeatuntil", { repeatuntil: { until, bound: 2, steps: [step("c2")] } }),
1226
- repeat: { until, bound: 2, steps: [step("c2")] },
1227
- scopes,
1228
- outputs: {},
1229
- execute,
1230
- now,
1231
- });
1232
- expect(endless.ok).toBe(false);
1233
- expect(endless.summary).toMatch(/never converged within the reviewed safety bound of 2/i);
1234
- });
1235
-
1236
- it("runs the while loop until the condition stops and reports the overflow", async () => {
1237
- const condition = {
1238
- while: { left: { ref: "count" }, right: { literal: 2 }, operator: "less", result: "x", resultkind: "boolean" },
1239
- bound: 5,
1240
- steps: [{ ...step("c1") }],
1241
- } as whilestep;
1242
- let scopes = scope([{ name: "count", kind: "number", value: 0 }]);
1243
- const counting = async (
1244
- one: workflowstep,
1245
- context: { scopes: variablescope[] },
1246
- ): Promise<{ ok: boolean; summary: string; scopes?: variablescope[] }> => {
1247
- if (one.id === "c1") {
1248
- const current = resolvevariable(context.scopes, "count")?.value;
1249
- scopes = setvariable(context.scopes, "count", "number", (typeof current === "number" ? current : 0) + 1, now);
1250
- return { ok: true, summary: "counts", scopes };
1251
- }
1252
- return { ok: true, summary: "done" };
1253
- };
1254
- const ended = await runwhile({
1255
- step: controlstep("w1", "whileloop", { while: condition }),
1256
- condition,
1257
- scopes: scope([{ name: "count", kind: "number", value: 0 }]),
1258
- outputs: {},
1259
- execute: counting,
1260
- now,
1261
- });
1262
- expect(ended.ok).toBe(true);
1263
- expect(ended.summary).toMatch(/ended after 2 iterations/i);
1264
- const overflowing = await runwhile({
1265
- step: controlstep("w2", "whileloop", { while: { ...condition, bound: 1 } }),
1266
- condition: { ...condition, bound: 1 },
1267
- scopes: scope([{ name: "count", kind: "number", value: 0 }]),
1268
- outputs: {},
1269
- execute: counting,
1270
- now,
1271
- });
1272
- expect(overflowing.ok).toBe(false);
1273
- expect(overflowing.summary).toMatch(
1274
- /hit its reviewed safety bound of 1 iterations while its condition still held/i,
1275
- );
1276
- const never = await runwhile({
1277
- step: controlstep("w3", "whileloop", { while: condition }),
1278
- condition,
1279
- scopes: scope([{ name: "count", kind: "number", value: 10 }]),
1280
- outputs: {},
1281
- execute,
1282
- now,
1283
- });
1284
- expect(never.ok).toBe(true);
1285
- expect(never.summary).toMatch(/ended after 0 iterations/i);
1286
- });
1287
-
1288
- it("runs the foreach over the resolved elements with the honest zero match", async () => {
1289
- const foreach: foreachstep = { selector: ".row", item: "e", index: "i", steps: [step("c1")] };
1290
- const resolved = await runforeach({
1291
- step: controlstep("f1", "foreach", { foreach }),
1292
- foreach,
1293
- scopes: scope([]),
1294
- outputs: {},
1295
- execute,
1296
- now,
1297
- resolveelements: async () => ["r1", "r2", "r3"],
1298
- });
1299
- expect(resolved.ok).toBe(true);
1300
- expect(resolved.summary).toMatch(/ran 3 iterations/i);
1301
- const empty = await runforeach({
1302
- step: controlstep("f2", "foreach", { foreach }),
1303
- foreach,
1304
- scopes: scope([]),
1305
- outputs: {},
1306
- execute,
1307
- now,
1308
- resolveelements: async () => [],
1309
- });
1310
- expect(empty.ok).toBe(true);
1311
- expect(empty.summary).toMatch(/matched no element and the foreach ran zero iterations/i);
1312
- await expect(
1313
- runforeach({
1314
- step: controlstep("f3", "foreach", { foreach }),
1315
- foreach,
1316
- scopes: scope([]),
1317
- outputs: {},
1318
- execute,
1319
- now,
1320
- }),
1321
- ).rejects.toThrow(/needs the element resolver/i);
1322
- });
1323
-
1324
- it("merges the parallel writes under the first, last and fail strategies", () => {
1325
- const branches: Array<{ id: string; order: number; ok: boolean; cancelled: boolean; variables: variablevalue[] }> =
1326
- [
1327
- {
1328
- id: "b1",
1329
- order: 0,
1330
- ok: true,
1331
- cancelled: false,
1332
- variables: [{ name: "rows", kind: "number", value: 12, setat: now }],
1333
- },
1334
- {
1335
- id: "b2",
1336
- order: 1,
1337
- ok: true,
1338
- cancelled: false,
1339
- variables: [
1340
- { name: "rows", kind: "number", value: 14, setat: now },
1341
- { name: "solo", kind: "string", value: "only", setat: now },
1342
- ],
1343
- },
1344
- {
1345
- id: "b3",
1346
- order: 2,
1347
- ok: false,
1348
- cancelled: true,
1349
- variables: [{ name: "rows", kind: "number", value: 99, setat: now }],
1350
- },
1351
- ];
1352
- const first = joinbranches({ stepid: "p1", branches, strategy: "first", now });
1353
- expect(first.ok).toBe(true);
1354
- expect(first.conflicts).toEqual(["rows"]);
1355
- expect(first.merged.find((variable) => variable.name === "rows")?.value).toBe(12);
1356
- expect(first.merged.find((variable) => variable.name === "solo")?.value).toBe("only");
1357
- const last = joinbranches({ stepid: "p1", branches, strategy: "last", now });
1358
- expect(last.merged.find((variable) => variable.name === "rows")?.value).toBe(14);
1359
- const failed = joinbranches({ stepid: "p1", branches, strategy: "fail", now });
1360
- expect(failed.ok).toBe(false);
1361
- expect(failed.summary).toMatch(/refused the conflicting writes of rows/i);
1362
- const clean = joinbranches({ stepid: "p1", branches: branches.slice(0, 1), strategy: "fail", now });
1363
- expect(clean.ok).toBe(true);
1364
- expect(clean.conflicts).toEqual([]);
1365
- });
1366
-
1367
- it("runs the parallel block with the join and the cancel on fail policy", async () => {
1368
- const parallel: parallelstep = {
1369
- branches: [
1370
- { id: "ok", steps: [step("c1")] },
1371
- { id: "bad", steps: [step("c2")] },
1372
- ],
1373
- join: { strategy: "first", onfail: "cancel" },
1374
- };
1375
- const failing = async (one: workflowstep): Promise<{ ok: boolean; summary: string }> =>
1376
- one.id === "c2" ? { ok: false, summary: "the branch failed" } : { ok: true, summary: "done" };
1377
- const cancelled = await runparallel({
1378
- step: controlstep("p1", "parallel", { parallel }),
1379
- parallel,
1380
- scopes: scope([]),
1381
- outputs: {},
1382
- execute: failing,
1383
- now,
1384
- });
1385
- expect(cancelled.ok).toBe(false);
1386
- expect(cancelled.summary).toMatch(/failed on branch bad/i);
1387
- const continuingparallel: parallelstep = { ...parallel, join: { strategy: "first", onfail: "continue" } };
1388
- const continuing = await runparallel({
1389
- step: controlstep("p2", "parallel", { parallel: continuingparallel }),
1390
- parallel: continuingparallel,
1391
- scopes: scope([]),
1392
- outputs: {},
1393
- execute: failing,
1394
- now,
1395
- });
1396
- expect(continuing.ok).toBe(true);
1397
- expect(continuing.summary).toMatch(/ran 2 concurrent branches/i);
1398
- });
1399
-
1400
- it("computes the retry backoff under the fixed and exponential shapes", () => {
1401
- const fixed: retrypolicy = {
1402
- attempts: 3,
1403
- backoff: { shape: "fixed", base: 100, jitter: 0 },
1404
- retryable: ["timeout"],
1405
- };
1406
- expect(backoffdelay(fixed, 1, 1)).toBe(100);
1407
- expect(backoffdelay(fixed, 3, 1)).toBe(100);
1408
- const exponential: retrypolicy = {
1409
- attempts: 3,
1410
- backoff: { shape: "exponential", base: 100, jitter: 0 },
1411
- retryable: ["timeout"],
1412
- };
1413
- expect(backoffdelay(exponential, 1, 1)).toBe(100);
1414
- expect(backoffdelay(exponential, 2, 1)).toBe(200);
1415
- expect(backoffdelay(exponential, 3, 1)).toBe(400);
1416
- const jittered: retrypolicy = {
1417
- attempts: 3,
1418
- backoff: { shape: "fixed", base: 100, jitter: 50 },
1419
- retryable: ["timeout"],
1420
- };
1421
- expect(backoffdelay(jittered, 1, 7)).toBeGreaterThanOrEqual(75);
1422
- expect(backoffdelay(jittered, 1, 7)).toBeLessThanOrEqual(125);
1423
- });
1424
-
1425
- it("retries only the reviewed error classes and reports the exhaustion", async () => {
1426
- const policy: retrypolicy = {
1427
- attempts: 3,
1428
- backoff: { shape: "fixed", base: 0, jitter: 0 },
1429
- retryable: ["timeout"],
1430
- };
1431
- let calls = 0;
1432
- const retried = await applyretry({
1433
- stepid: "s1",
1434
- policy,
1435
- run: async () => {
1436
- calls += 1;
1437
- return calls < 3 ? { ok: false } : { ok: true };
1438
- },
1439
- errorclass: () => "timeout",
1440
- now,
1441
- });
1442
- expect(retried.value.ok).toBe(true);
1443
- expect(retried.attempts).toHaveLength(2);
1444
- expect(retried.exhausted).toBe(false);
1445
- let nonretryable = 0;
1446
- const refused = await applyretry({
1447
- stepid: "s1",
1448
- policy,
1449
- run: async () => {
1450
- nonretryable += 1;
1451
- return { ok: false };
1452
- },
1453
- errorclass: () => "consent",
1454
- now,
1455
- });
1456
- expect(nonretryable).toBe(1);
1457
- expect(refused.exhausted).toBe(false);
1458
- let exhausted = 0;
1459
- const drained = await applyretry({
1460
- stepid: "s1",
1461
- policy,
1462
- run: async () => {
1463
- exhausted += 1;
1464
- return { ok: false };
1465
- },
1466
- errorclass: () => "timeout",
1467
- now,
1468
- });
1469
- expect(exhausted).toBe(3);
1470
- expect(drained.exhausted).toBe(true);
1471
- });
1472
-
1473
- it("aborts the step and the run against their reviewed budgets", async () => {
1474
- const slow = () => new Promise<{ ok: boolean }>((resolve) => setTimeout(() => resolve({ ok: true }), 80));
1475
- const aborted = await applytimeout({ stepid: "s1", budgetms: 5, run: slow });
1476
- expect(aborted.aborted).toBe(true);
1477
- expect(aborted.output?.details).toMatchObject({ errorclass: "timeout", cancelled: true });
1478
- expect(aborted.abort).toMatchObject({ stepid: "s1", budget: 5, scope: "step" });
1479
- const finished = await applytimeout({ stepid: "s1", budgetms: 1_000, run: async () => ({ ok: true }) });
1480
- expect(finished.aborted).toBe(false);
1481
- const runaborted = await applyruntimeout({ budgetms: 5, run: slow });
1482
- expect(runaborted.cancelled).toBe(true);
1483
- if (!runaborted.cancelled || runaborted.error === undefined)
1484
- throw new Error("The run budget abort carries its cancellation error.");
1485
- expect(runaborted.error).toBeInstanceOf(cancellederror);
1486
- expect(runaborted.error.message).toMatch(/exceeded its reviewed budget of 5 milliseconds/i);
1487
- const runfinished = await applyruntimeout({ budgetms: 1_000, run: async () => "value" });
1488
- expect(runfinished).toEqual({ cancelled: false, value: "value" });
1489
- });
1490
-
1491
- it("runs the try block through the catch handler and the rerun option", async () => {
1492
- const failing = async (
1493
- one: workflowstep,
1494
- ): Promise<{ ok: boolean; summary: string; details?: Record<string, unknown> }> =>
1495
- one.id === "c1"
1496
- ? { ok: false, summary: "the fragile step failed", details: { errorclass: "page" } }
1497
- : { ok: true, summary: `done ${one.id}` };
1498
- const handledfragile = { steps: [step("c1")], catch: { steps: [step("h1")] } };
1499
- const handled = await runtry({
1500
- step: controlstep("t1", "trycatch", { try: handledfragile }),
1501
- fragile: handledfragile,
1502
- scopes: scope([]),
1503
- outputs: {},
1504
- execute: failing,
1505
- now,
1506
- });
1507
- expect(handled.ok).toBe(true);
1508
- expect(handled.summary).toMatch(/catch handler ran 1 step after the page failure/i);
1509
- let c1runs = 0;
1510
- const rerunfragile = { steps: [step("c1")], catch: { steps: [step("h1")], rerun: true } };
1511
- const rerun = await runtry({
1512
- step: controlstep("t2", "trycatch", { try: rerunfragile }),
1513
- fragile: rerunfragile,
1514
- scopes: scope([]),
1515
- outputs: {},
1516
- execute: async (one: workflowstep) => {
1517
- if (one.id === "c1") {
1518
- c1runs += 1;
1519
- return c1runs < 2 ? { ok: false, summary: "fails once" } : { ok: true, summary: "recovers" };
1520
- }
1521
- return { ok: true, summary: `done ${one.id}` };
1522
- },
1523
- now,
1524
- });
1525
- expect(rerun.ok).toBe(true);
1526
- const failingfragile = { steps: [step("c1")], catch: { steps: [step("h1")] } };
1527
- const failinghandler = await runtry({
1528
- step: controlstep("t3", "trycatch", { try: failingfragile }),
1529
- fragile: failingfragile,
1530
- scopes: scope([]),
1531
- outputs: {},
1532
- execute: async () => ({ ok: false, summary: "always fails" }),
1533
- now,
1534
- });
1535
- expect(failinghandler.ok).toBe(false);
1536
- expect(failinghandler.summary).toMatch(/catch handler of the try block failed/i);
1537
- });
1538
-
1539
- it("dispatches the control step through runcontrolstep with the merged scopes and log", async () => {
1540
- const dispatched = await runcontrolstep({
1541
- step: controlstep("c1", "condition", {
1542
- condition: { expression: { left: { literal: true }, operator: "not", result: "flag", resultkind: "boolean" } },
1543
- }),
1544
- scopes: scope([]),
1545
- outputs: {},
1546
- execute,
1547
- now,
1548
- });
1549
- expect(dispatched.output.ok).toBe(true);
1550
- expect(dispatched.output.summary).toMatch(/flag does not hold/i);
1551
- expect(resolvevariable(dispatched.scopes, "flag")?.value).toBe(false);
1552
- const malformed = workflowstepof({ id: "c1", kind: "loop", label: "l", options: "{}" })!;
1553
- await expect(runcontrolstep({ step: malformed, scopes: scope([]), outputs: {}, execute, now })).rejects.toThrow(
1554
- /loop step needs a reviewed list variable/i,
1555
- );
1556
- const passthrough = controlstep("p1", "parallel", {
1557
- parallel: { branches: [{ id: "b1", steps: [step("c1")] }], join: { strategy: "first", onfail: "cancel" } },
1558
- });
1559
- expect(iscontrolflowkind("parallel")).toBe(true);
1560
- expect(iscontrolflowkind("click")).toBe(false);
1561
- expect(controlflowkinds).toHaveLength(8);
1562
- expect(workflowkinds).toContain("composeworkflow");
1563
- });
1564
- });
1565
-
1566
- describe("torture: trigger payloads, cron grammar and cooldowns", () => {
1567
- it("maps the trigger kinds to their families and refuses the unknown", () => {
1568
- expect(triggerkinds).toHaveLength(10);
1569
- expect(triggerfamilies).toHaveLength(10);
1570
- expect(istriggerkind("cronrule")).toBe(true);
1571
- expect(istriggerkind("cron")).toBe(false);
1572
- expect(triggerfamilyof("visitrule")).toBe("visit");
1573
- expect(triggerfamilyof("webhookrule")).toBe("webhook");
1574
- expect(triggerfamilyof("nope")).toBeUndefined();
1575
- });
1576
-
1577
- it("normalizes every family payload and refuses the malformed twins", () => {
1578
- expect(triggerpayloadof("visit", { origins: [origin] })).toEqual({ origins: [origin] });
1579
- expect(triggerpayloadof("visit", { origins: [] })).toBeUndefined();
1580
- expect(triggerpayloadof("visit", { origins: ["http://insecure.example"] })).toBeUndefined();
1581
- expect(triggerpayloadof("visit", { origins: [origin, origin] })).toEqual({ origins: [origin] });
1582
- expect(triggerpayloadof("url", { pattern: `${origin}/pricing*` })).toEqual({ pattern: `${origin}/pricing*` });
1583
- expect(triggerpayloadof("url", { pattern: "notaurl" })).toBeUndefined();
1584
- expect(triggerpayloadof("menu", { title: "Run the pricing extraction" })).toEqual({
1585
- title: "Run the pricing extraction",
1586
- });
1587
- expect(triggerpayloadof("menu", { title: " " })).toBeUndefined();
1588
- expect(triggerpayloadof("key", { command: "run-pricing" })).toEqual({ command: "run-pricing" });
1589
- expect(triggerpayloadof("key", { command: "Run Pricing" })).toBeUndefined();
1590
- expect(triggerpayloadof("key", { command: "run", key: " " })).toBeUndefined();
1591
- expect(triggerpayloadof("button", {})).toEqual({});
1592
- expect(triggerpayloadof("cron", { cron: "*/5 * * * *" })).toEqual({ cron: "*/5 * * * *" });
1593
- expect(triggerpayloadof("cron", { cron: "99 * * * *" })).toBeUndefined();
1594
- expect(triggerpayloadof("cron", { cron: "* * * * *", timezone: "Not/AZone" })).toBeUndefined();
1595
- expect(triggerpayloadof("interval", { period: 1000 })).toEqual({ period: 1000 });
1596
- expect(triggerpayloadof("interval", { period: 0 })).toBeUndefined();
1597
- expect(triggerpayloadof("interval", { period: -1 })).toBeUndefined();
1598
- expect(triggerpayloadof("interval", { period: 1000, jitter: -1 })).toBeUndefined();
1599
- expect(triggerpayloadof("urllist", { urls: [origin] })).toEqual({ urls: [origin] });
1600
- expect(triggerpayloadof("urllist", { urls: [] })).toBeUndefined();
1601
- expect(triggerpayloadof("urllist", { urls: ["nope"] })).toBeUndefined();
1602
- const secret = "abcdefgh12345678abcdefgh12345678";
1603
- expect(triggerpayloadof("webhook", { secret, schema: [{ name: "rows", kind: "number", required: true }] })).toEqual(
1604
- { secret, schema: [{ name: "rows", kind: "number", required: true }] },
1605
- );
1606
- expect(
1607
- triggerpayloadof("webhook", { secret: "short", schema: [{ name: "rows", kind: "number" }] }),
1608
- ).toBeUndefined();
1609
- expect(
1610
- triggerpayloadof("webhook", {
1611
- secret,
1612
- schema: [
1613
- { name: "rows", kind: "number" },
1614
- { name: "rows", kind: "string" },
1615
- ],
1616
- }),
1617
- ).toBeUndefined();
1618
- expect(triggerpayloadof("event", { events: ["mutate", "focus"] })).toEqual({ events: ["mutate", "focus"] });
1619
- expect(triggerpayloadof("event", { events: ["mutate", "mutate"] })).toEqual({ events: ["mutate"] });
1620
- expect(triggerpayloadof("event", { events: ["unknown"] })).toBeUndefined();
1621
- expect(triggerpayloadof("event", { events: [] })).toBeUndefined();
1622
- });
1623
-
1624
- it("checks the webhook secret entropy floor and the timezone names", () => {
1625
- expect(webhooksecretok("abcdefgh12345678abcdefgh12345678")).toBe(true);
1626
- expect(webhooksecretok("short")).toBe(false);
1627
- expect(webhooksecretok("aaaaaaaaaaaaaaaaaaaaaaaaaaaa")).toBe(false);
1628
- expect(webhooksecretok("abcdefghijklmnopqrstuvwx")).toBe(false);
1629
- expect(webhooksecretok("123456789012345678901234")).toBe(false);
1630
- expect(timezonevalid("UTC")).toBe(true);
1631
- expect(timezonevalid("America/Sao_Paulo")).toBe(true);
1632
- expect(timezonevalid("Mars/Olympus")).toBe(false);
1633
- });
1634
-
1635
- it("arms the rules with the reviewed payloads and the default cooldowns", () => {
1636
- const rule = armrule({ family: "cron", workflowid: "w1", payload: { cron: "*/5 * * * *" }, now });
1637
- expect(rule).toMatchObject({
1638
- kind: "cron",
1639
- workflowid: "w1",
1640
- cron: "*/5 * * * *",
1641
- cooldown: 0,
1642
- state: { enabled: true },
1643
- stats: { fires: 0, launches: 0, suppressions: 0 },
1644
- createdat: now,
1645
- });
1646
- expect(rule?.label).toBe("The cron rule of w1");
1647
- const webhook = armrule({
1648
- family: "webhook",
1649
- workflowid: "w1",
1650
- payload: { secret: "abcdefgh12345678abcdefgh12345678", schema: [{ name: "rows", kind: "number" }] },
1651
- now,
1652
- });
1653
- expect(webhook?.cooldown).toBe(defaulttriggercooldown);
1654
- expect(armrule({ family: "event", workflowid: "w1", payload: { events: ["mutate"] }, now })?.cooldown).toBe(
1655
- defaulttriggercooldown,
1656
- );
1657
- expect(armrule({ family: "cron", workflowid: " ", payload: { cron: "* * * * *" }, now })).toBeUndefined();
1658
- expect(armrule({ family: "cron", workflowid: "w1", payload: { cron: "bad" }, now })).toBeUndefined();
1659
- expect(
1660
- armrule({ family: "cron", workflowid: "w1", payload: { cron: "* * * * *" }, cooldown: 0, now }),
1661
- ).toBeUndefined();
1662
- expect(
1663
- armrule({ family: "cron", workflowid: "w1", payload: { cron: "* * * * *" }, cooldown: -1, now }),
1664
- ).toBeUndefined();
1665
- expect(
1666
- armrule({
1667
- family: "cron",
1668
- workflowid: "w1",
1669
- payload: { cron: "* * * * *" },
1670
- cooldown: 5,
1671
- label: " every minute ",
1672
- now,
1673
- })?.label,
1674
- ).toBe(" every minute ");
1675
- });
1676
-
1677
- it("updates the rule state and stats immutably", () => {
1678
- const rule = armrule({ family: "cron", workflowid: "w1", payload: { cron: "* * * * *" }, now })!;
1679
- const updated = updaterule(rule, { state: { lastfireat: now + 1, nextfireat: now + 2 }, stats: { fires: 1 } });
1680
- expect(updated.state.lastfireat).toBe(now + 1);
1681
- expect(updated.state.nextfireat).toBe(now + 2);
1682
- expect(updated.stats.fires).toBe(1);
1683
- expect(rule.state.lastfireat).toBeUndefined();
1684
- expect(rule.stats.fires).toBe(0);
1685
- });
1686
-
1687
- it("matches the glob url patterns with schemes, hosts, ports and stars", () => {
1688
- expect(matchurl(`${origin}/pricing`, `${origin}/pricing`)).toBe(true);
1689
- expect(matchurl(`${origin}/pricing*`, `${origin}/pricingX`)).toBe(true);
1690
- expect(matchurl(`${origin}/pricing*`, `${origin}/pricing/table`)).toBe(false);
1691
- expect(matchurl(`${origin}/pricing/**`, `${origin}/pricing/a/b/c?x=1`)).toBe(true);
1692
- expect(matchurl("https://example.com:8443/x", "https://example.com:8443/x")).toBe(true);
1693
- expect(matchurl("https://example.com/x", "https://example.com:9999/x")).toBe(true);
1694
- expect(matchurl("https://example.com:8443/x", "https://example.com:9999/x")).toBe(false);
1695
- expect(matchurl("http://example.com/x", "https://example.com/x")).toBe(false);
1696
- expect(matchurl("https://other.example/x", "https://example.com/x")).toBe(false);
1697
- expect(matchurl("not a url", "https://example.com/x")).toBe(false);
1698
- expect(matchurl("https://example.com/x", "not a url")).toBe(false);
1699
- expect(visitmatch([origin], `${origin}/pricing?x=1`)).toBe(true);
1700
- expect(visitmatch([origin], "https://denied.example")).toBe(false);
1701
- expect(visitmatch([origin], "not a url")).toBe(false);
1702
- });
1703
-
1704
- it("parses the cron grammar with names, steps, ranges and the sunday normalization", () => {
1705
- expect(cronparse("*/15 * * * *")).toMatchObject({ minutes: [0, 15, 30, 45] });
1706
- expect(cronparse("0 12 * * *")).toMatchObject({ hours: [12] });
1707
- expect(cronparse("1-3 * * * *")?.minutes).toEqual([1, 2, 3]);
1708
- expect(cronparse("1,3,5 * * * *")?.minutes).toEqual([1, 3, 5]);
1709
- expect(cronparse("* * * jan,dec *")?.months).toEqual([1, 12]);
1710
- expect(cronparse("* * * * mon-fri")?.daysofweek).toEqual([1, 2, 3, 4, 5]);
1711
- expect(cronparse("* * * * sun")?.daysofweek).toEqual([0]);
1712
- expect(cronparse("* * * * 7")?.daysofweek).toEqual([0]);
1713
- expect(cronparse("* * * * 0,7")?.daysofweek).toEqual([0]);
1714
- for (const bad of [
1715
- "",
1716
- "* * * *",
1717
- "* * * * * *",
1718
- "60 * * * *",
1719
- "* 24 * * *",
1720
- "* * 0 * *",
1721
- "* * 32 * *",
1722
- "* * * 0 *",
1723
- "* * * * 8",
1724
- "* * * * tue-mon",
1725
- "*/0 * * * *",
1726
- "a * * * *",
1727
- "1--2 * * * *",
1728
- ]) {
1729
- expect(cronparse(bad)).toBeUndefined();
1730
- }
1731
- });
1732
-
1733
- it("computes the next cron fire strictly after the given time and never for impossible schedules", () => {
1734
- const base = Date.UTC(2026, 0, 15, 10, 30, 0);
1735
- const nextminute = cronnext("* * * * *", base);
1736
- expect(nextminute).toBe(base + 60_000);
1737
- expect(cronnext("0 11 * * *", base)).toBe(base + 30 * 60_000);
1738
- expect(cronnext("30 10 * * *", base)).toBe(base + 24 * 60 * 60_000);
1739
- expect(cronnext("0 0 31 2 *", base)).toBeUndefined();
1740
- expect(cronnext("bad", base)).toBeUndefined();
1741
- expect(schedulecron({ cron: "*/5 * * * *" }, base)).toBe(base + 5 * 60_000);
1742
- });
1743
-
1744
- it("schedules the interval fires with the jitter spread and lists the due rules", () => {
1745
- expect(scheduleinterval({ period: 1000 }, undefined, now, 1)).toBe(now + 1000);
1746
- expect(scheduleinterval({ period: 1000, jitter: 0 }, now, now, 1)).toBe(now + 1000);
1747
- const spread = scheduleinterval({ period: 1000, jitter: 200 }, now, now, 42);
1748
- expect(spread).toBeGreaterThanOrEqual(now + 900);
1749
- expect(spread).toBeLessThanOrEqual(now + 1100);
1750
- const rule = {
1751
- ...armrule({ family: "interval", workflowid: "w1", payload: { period: 1000 }, now })!,
1752
- state: { enabled: true, cooldown: 0, nextfireat: now - 1 },
1753
- };
1754
- const paused = { ...rule, state: { ...rule.state, pausedat: now } };
1755
- const disabled = { ...rule, state: { ...rule.state, enabled: false } };
1756
- expect(listdue([rule, paused, disabled], now)).toEqual([{ rule, overdueby: 1 }]);
1757
- expect(listdue([{ ...rule, state: { ...rule.state, nextfireat: now + 1 } }], now)).toEqual([]);
1758
- });
1759
-
1760
- it("applies the cooldown window with the exact boundary kept", () => {
1761
- const rule = {
1762
- ...armrule({ family: "interval", workflowid: "w1", payload: { period: 1000 }, now })!,
1763
- state: { enabled: true, cooldown: 100, lastfireat: now },
1764
- };
1765
- expect(applycooldown(rule, now + 99)).toMatchObject({ suppressed: true, remaining: 1 });
1766
- expect(applycooldown(rule, now + 100)).toMatchObject({ suppressed: false, remaining: 0 });
1767
- const { lastfireat: _lastfire, ...statewithoutlastfire } = rule.state;
1768
- expect(applycooldown({ ...rule, state: statewithoutlastfire }, now + 50).suppressed).toBe(false);
1769
- expect(applycooldown({ ...rule, state: { ...rule.state, cooldown: 0 } }, now + 1).suppressed).toBe(false);
1770
- });
1771
-
1772
- it("evaluates the triggers through the suppression gates and queues the fires", () => {
1773
- const rule = armrule({ family: "interval", workflowid: "w1", payload: { period: 1000 }, now })!;
1774
- expect(evaluatetrigger({ rule, now, cause: "interval", runactive: false, workflowreviewed: true })).toMatchObject({
1775
- fired: true,
1776
- });
1777
- expect(
1778
- evaluatetrigger({
1779
- rule: updaterule(rule, { state: { enabled: false } }),
1780
- now,
1781
- cause: "c",
1782
- runactive: false,
1783
- workflowreviewed: true,
1784
- }).suppressed,
1785
- ).toBe("disabled");
1786
- expect(
1787
- evaluatetrigger({
1788
- rule: updaterule(rule, { state: { pausedat: now } }),
1789
- now,
1790
- cause: "c",
1791
- runactive: false,
1792
- workflowreviewed: true,
1793
- }).suppressed,
1794
- ).toBe("paused");
1795
- expect(evaluatetrigger({ rule, now, cause: "c", runactive: false, workflowreviewed: false }).suppressed).toBe(
1796
- "unreviewed",
1797
- );
1798
- expect(evaluatetrigger({ rule, now, cause: "c", runactive: true, workflowreviewed: true }).suppressed).toBe(
1799
- "dedupe",
1800
- );
1801
- const cooled = updaterule(rule, { state: { lastfireat: now, cooldown: 100 } });
1802
- expect(
1803
- evaluatetrigger({ rule: cooled, now: now + 50, cause: "c", runactive: false, workflowreviewed: true }),
1804
- ).toMatchObject({ fired: false, suppressed: "cooldown", remaining: 50 });
1805
- const fired = evaluatetrigger({
1806
- rule,
1807
- now: now + 1,
1808
- cause: "visit",
1809
- url: `${origin}/pricing`,
1810
- title: "Pricing",
1811
- payload: { rows: 12 },
1812
- runactive: false,
1813
- workflowreviewed: true,
1814
- });
1815
- expect(fired.fire).toMatchObject({
1816
- ruleid: rule.id,
1817
- at: now + 1,
1818
- cause: "visit",
1819
- url: `${origin}/pricing`,
1820
- title: "Pricing",
1821
- });
1822
- const queue = queuefire([], fired.fire!);
1823
- expect(queue.queued).toBe(true);
1824
- const deduped = queuefire(queue.queue, { ...fired.fire!, id: "other" });
1825
- expect(deduped.queued).toBe(false);
1826
- expect(deduped.deduped).toBe(true);
1827
- });
1828
-
1829
- it("drains the queued fires and keeps the failed one for the next wake", async () => {
1830
- const fires = [
1831
- { id: "f1", ruleid: "r1", at: now, cause: "visit" },
1832
- { id: "f2", ruleid: "r2", at: now + 1, cause: "url" },
1833
- ];
1834
- let launched = 0;
1835
- const drained = await drainqueue(fires, async () => {
1836
- launched += 1;
1837
- if (launched === 1) throw new Error("the launch failed");
1838
- });
1839
- expect(launched).toBe(1);
1840
- expect(drained.remaining.map((fire) => fire.id)).toEqual(["f1", "f2"]);
1841
- const done = await drainqueue(fires, async () => {
1842
- launched += 1;
1843
- });
1844
- expect(done.launched).toBe(2);
1845
- expect(done.remaining).toEqual([]);
1846
- });
1847
-
1848
- it("verifies the webhook deliveries against the secret and the schema", () => {
1849
- const secret = "abcdefgh12345678abcdefgh12345678";
1850
- const rule = armrule({
1851
- family: "webhook",
1852
- workflowid: "w1",
1853
- payload: {
1854
- secret,
1855
- schema: [
1856
- { name: "rows", kind: "number", required: true },
1857
- { name: "note", kind: "string" },
1858
- ],
1859
- },
1860
- now,
1861
- })!;
1862
- expect(verifywebhook({ rule, secret, payload: { rows: 12 } })).toEqual({ verified: true });
1863
- expect(verifywebhook({ rule, secret: "wrong secret 1234567890123456", payload: { rows: 12 } }).reason).toMatch(
1864
- /does not match the reviewed secret/i,
1865
- );
1866
- expect(verifywebhook({ rule, secret, payload: { note: "x" } }).reason).toMatch(
1867
- /required webhook field rows is missing/i,
1868
- );
1869
- expect(verifywebhook({ rule, secret, payload: { rows: "twelve" } }).reason).toMatch(/not a number/i);
1870
- expect(verifywebhook({ rule, secret, payload: "not an object" }).reason).toMatch(/must be a JSON object/i);
1871
- const { secret: _secret, ...rulewithoutsecret } = rule;
1872
- expect(verifywebhook({ rule: rulewithoutsecret, secret, payload: {} }).reason).toMatch(
1873
- /carries no reviewed secret/i,
1874
- );
1875
- });
1876
-
1877
- it("observes the event rules, suspends and resumes the fleet", () => {
1878
- const rule = armrule({ family: "event", workflowid: "w1", payload: { events: ["mutate", "console"] }, now })!;
1879
- expect(eventrulematches(rule, "mutate")).toBe(true);
1880
- expect(eventrulematches(rule, "navigate")).toBe(false);
1881
- expect(
1882
- observeevents(
1883
- [rule, armrule({ family: "cron", workflowid: "w2", payload: { cron: "* * * * *" }, now })!],
1884
- "mutate",
1885
- ),
1886
- ).toEqual([rule]);
1887
- expect(observeevents([rule], "unknown")).toEqual([]);
1888
- expect(observeevents([updaterule(rule, { state: { enabled: false } })], "mutate")).toEqual([]);
1889
- const paused = pauseall([rule], now);
1890
- expect(paused[0]?.state.pausedat).toBe(now);
1891
- const resumed = resumeall(paused);
1892
- expect(resumed[0]?.state.pausedat).toBeUndefined();
1893
- expect(resumeall([rule])[0]?.state.pausedat).toBeUndefined();
1894
- });
1895
-
1896
- it("previews the manual run and records the confirmation", () => {
1897
- const record = compose([
1898
- step("s1"),
1899
- controlstep("l1", "loop", { loop: { list: "items", item: "it", index: "ix", bound: 4, steps: [step("c1")] } }),
1900
- ]);
1901
- const preview: manualrun = manualpreview(record, now);
1902
- expect(preview.workflowid).toBe(record.id);
1903
- expect(preview.preview).toHaveLength(2);
1904
- expect(preview.preview[1]?.control).toMatchObject({ kind: "loop", bound: 4 });
1905
- expect(preview.confirmed).toBeUndefined();
1906
- const confirmed = confirmmanualrun(preview, true, now + 1);
1907
- expect(confirmed).toMatchObject({ confirmed: true, decidedat: now + 1 });
1908
- expect(confirmmanualrun(preview, false, now + 2).confirmed).toBe(false);
1909
- });
1910
-
1911
- it("summarizes the rules and checks the origins against the workflow grants", () => {
1912
- const rule = armrule({
1913
- family: "visit",
1914
- workflowid: "w1",
1915
- payload: { origins: [origin, "https://other.example"] },
1916
- now,
1917
- })!;
1918
- expect(triggersummary(rule)).toMatchObject({
1919
- kind: "visit",
1920
- workflowid: "w1",
1921
- origins: [origin, "https://other.example"],
1922
- cooldown: 0,
1923
- enabled: true,
1924
- });
1925
- expect(ruleorigins(rule)).toEqual([origin, "https://other.example"]);
1926
- expect(ruleoriginsgranted(rule, [origin])).toBe(false);
1927
- expect(ruleoriginsgranted(rule, [origin, "https://other.example"])).toBe(true);
1928
- expect(ruleoriginsgranted(armrule({ family: "menu", workflowid: "w1", payload: { title: "t" }, now })!, [])).toBe(
1929
- true,
1930
- );
1931
- });
1932
-
1933
- it("plans one fire per url of the url list rules", () => {
1934
- const rule = armrule({
1935
- family: "urllist",
1936
- workflowid: "w1",
1937
- payload: { urls: [origin, "https://other.example"] },
1938
- now,
1939
- })!;
1940
- const fires = runurllist(rule, now + 1);
1941
- expect(fires.map((fire) => fire.url)).toEqual([origin, "https://other.example"]);
1942
- expect(fires.every((fire) => fire.cause === "urllist" && fire.ruleid === rule.id && fire.at === now + 1)).toBe(
1943
- true,
1944
- );
1945
- const { urls: _urls, ...rulewithouturls } = rule;
1946
- expect(runurllist(rulewithouturls, now)).toEqual([]);
1947
- });
1948
- });
1949
-
1950
- describe("torture: workflow editor parsing, files and canvas rules", () => {
1951
- const record = (): workflowrecord =>
1952
- compose([
1953
- step("s1"),
1954
- step("s2"),
1955
- controlstep("l1", "loop", { loop: { list: "items", item: "it", index: "ix", bound: 3, steps: [step("c1")] } }),
1956
- ]);
1957
-
1958
- it("builds the step library over the kinds grouped by category", () => {
1959
- const library = buildsteplibrary(["click", "type", "wait", "delay", "compute", "loop", "cronrule", "click"]);
1960
- expect(library).toHaveLength(7);
1961
- expect(library.find((entry) => entry.kind === "loop")).toMatchObject({ category: "controlflow" });
1962
- expect(library.find((entry) => entry.kind === "delay")).toMatchObject({ category: "waits" });
1963
- expect(library.find((entry) => entry.kind === "compute")).toMatchObject({ category: "variables" });
1964
- expect(library.find((entry) => entry.kind === "cronrule")).toMatchObject({ category: "triggers" });
1965
- expect(library.find((entry) => entry.kind === "click")).toMatchObject({ category: "actions" });
1966
- expect(library.find((entry) => entry.kind === "delay")?.optionschema[0]).toMatchObject({
1967
- name: "base",
1968
- kind: "number",
1969
- required: true,
1970
- });
1971
- expect(palettecategories).toHaveLength(5);
1972
- });
1973
-
1974
- it("roundtrips the canvas model through load and save", () => {
1975
- const loaded = loadworkflow(record());
1976
- expect(loaded.nodes).toHaveLength(3);
1977
- expect(loaded.dirty).toBe(false);
1978
- const saved = saveworkflow(loaded, { now, kindallowed: () => true, riskof: () => "read" });
1979
- expect(saved.steps.map((one) => one.id)).toEqual(["s1", "s2", "l1"]);
1980
- expect(saved.origins).toEqual([origin]);
1981
- });
1982
-
1983
- it("refuses the canvas save with blank names, broken versions and empty origins", () => {
1984
- const model = loadworkflow(record());
1985
- expect(() => saveworkflow({ ...model, name: " " }, { now })).toThrow(/name/i);
1986
- expect(() => saveworkflow({ ...model, version: 0 }, { now })).toThrow(/version/i);
1987
- expect(() => saveworkflow({ ...model, version: 1.5 }, { now })).toThrow(/version/i);
1988
- expect(() => saveworkflow({ ...model, origins: [] }, { now })).toThrow(/at least one granted HTTPS origin/i);
1989
- });
1990
-
1991
- it("refuses the node that is both a step and an invocation and the duplicate ids", () => {
1992
- const model = loadworkflow(record());
1993
- const both = { ...model.nodes[0]!, invocation: { block: "b", label: "l" } };
1994
- expect(() => saveworkflow({ ...model, nodes: [both] }, { now })).toThrow(
1995
- /exactly one workflow step or one block invocation/i,
1996
- );
1997
- const duplicated = { ...model, nodes: [model.nodes[0]!, { ...model.nodes[0]! }] };
1998
- expect(() => saveworkflow(duplicated, { now })).toThrow(/must be unique/i);
1999
- const neither = { ...model, nodes: [{ x: 0, y: 0 }] as never };
2000
- expect(() => saveworkflow(neither, { now })).toThrow(/exactly one workflow step or one block invocation/i);
2001
- });
2002
-
2003
- it("refuses the edges that run backwards or reference unknown steps", () => {
2004
- const model = loadworkflow(record());
2005
- expect(() =>
2006
- saveworkflow({ ...model, edges: [{ from: "s2", to: "s1", variable: "rows", kind: "number" }] }, { now }),
2007
- ).toThrow(/would form a cycle/i);
2008
- expect(() =>
2009
- saveworkflow({ ...model, edges: [{ from: "ghost", to: "s1", variable: "rows", kind: "number" }] }, { now }),
2010
- ).toThrow(/unknown source step ghost/i);
2011
- expect(() =>
2012
- saveworkflow({ ...model, edges: [{ from: "s1", to: "ghost", variable: "rows", kind: "number" }] }, { now }),
2013
- ).toThrow(/unknown target step ghost/i);
2014
- });
2015
-
2016
- it("snaps nodes to the grid, refuses the broken grids and the invocation nodes", () => {
2017
- const model = loadworkflow(record());
2018
- expect(() => snapnode(model, "s1", 0, 0, 0)).toThrow(/snap grid must be a positive number/i);
2019
- expect(() => snapnode(model, "s1", 0, 0, -20)).toThrow(/snap grid must be a positive number/i);
2020
- expect(() => snapnode(model, "ghost", 0, 0)).toThrow(/No canvas node matches ghost/i);
2021
- const snapped = snapnode(model, "s1", 47, 93, 20);
2022
- expect(snapped.nodes[0]).toMatchObject({ x: 40, y: 100 });
2023
- expect(snapped.dirty).toBe(true);
2024
- const invocationmodel = loadworkflow(
2025
- composeworkflow({
2026
- name: "n",
2027
- version: 1,
2028
- origins: [origin],
2029
- steps: [{ block: "b", label: "b" }],
2030
- blocks: [{ name: "b", label: "b", steps: [step("i1")] }],
2031
- now,
2032
- }),
2033
- );
2034
- expect(() => snapnode(invocationmodel, "b", 0, 0)).toThrow(/attaches through its own definition/i);
2035
- });
2036
-
2037
- it("reorders the canvas nodes and refuses the broken indexes", () => {
2038
- const model = loadworkflow(record());
2039
- expect(() => reordersteps(model, "ghost", 0)).toThrow(/No canvas node matches ghost/i);
2040
- expect(() => reordersteps(model, "s1", -1)).toThrow(/must address an existing position/i);
2041
- expect(() => reordersteps(model, "s1", 3)).toThrow(/must address an existing position/i);
2042
- expect(() => reordersteps(model, "s1", 1.5)).toThrow(/must address an existing position/i);
2043
- const reordered = reordersteps(model, "s2", 0);
2044
- expect(reordered.nodes.map((node) => node.step?.id)).toEqual(["s2", "s1", "l1"]);
2045
- });
2046
-
2047
- it("groups the selection into a new block and refuses the broken names", () => {
2048
- const model = loadworkflow(record());
2049
- expect(() => groupselect(model, ["s1"], "Bad Name")).toThrow(/block name must be a unique lowercase word/i);
2050
- const grouped = groupselect(model, ["s1", "s2"], "pair");
2051
- expect(() => groupselect(grouped, ["l1"], "pair")).toThrow(/already exists on the canvas/i);
2052
- expect(() => groupselect(model, [], "block1")).toThrow(/at least one step node/i);
2053
- expect(() => groupselect(model, ["ghost"], "block1")).toThrow(/not one/i);
2054
- expect(grouped.blocks.map((block) => block.name)).toEqual(["pair"]);
2055
- expect(grouped.nodes.map((node) => node.invocation?.block ?? node.step?.id)).toEqual(["pair", "l1"]);
2056
- });
2057
-
2058
- it("inserts templates and steps with id deduplication and refuses the malformed ones", () => {
2059
- const model = loadworkflow(record());
2060
- const template: steptemplate = { id: "t1", name: "the wait", origin, step: step("s1"), sharedat: now };
2061
- const expanded = expandtemplate(model, template, [], 1);
2062
- expect(expanded.nodes[1]?.step?.id).toBe("s12");
2063
- expect(() => expandtemplate(model, { ...template, step: { ...step("s1"), kind: "WAIT" as never } })).toThrow(
2064
- /does not carry one reviewed workflow step/i,
2065
- );
2066
- expect(() => expandtemplate(model, template, [{ name: "Notvalid", kind: "string" } as never])).toThrow(
2067
- /malformed nested parameter/i,
2068
- );
2069
- const added = addnode(model, step("s9"), 0);
2070
- expect(added.nodes[0]?.step?.id).toBe("s9");
2071
- const deduped = addnode(added, step("s9"));
2072
- expect(deduped.nodes.at(-1)?.step?.id).toBe("s92");
2073
- expect(() => addnode(model, { ...step("x"), kind: "WAIT2" as never })).toThrow(/needs one reviewed workflow step/i);
2074
- expect(() => addnode(model, step("s9"), -1)).not.toThrow();
2075
- });
2076
-
2077
- it("edits the step payloads through the inspector and refuses the unknown steps", () => {
2078
- const model = loadworkflow(record());
2079
- const edited = editstep(model, { ...step("s1"), value: "20" });
2080
- expect(edited.nodes[0]?.step?.value).toBe("20");
2081
- expect(() => editstep(model, step("ghost"))).toThrow(/No canvas step matches ghost/i);
2082
- expect(() => editstep(model, { ...step("s1"), kind: "WAIT" as never })).toThrow(
2083
- /needs one reviewed workflow step/i,
2084
- );
2085
- });
2086
-
2087
- it("renders the minimap, focuses it and zooms with the label compensation", () => {
2088
- const model = loadworkflow(record());
2089
- const projection = renderminimap(model);
2090
- expect(projection.minimap.scale).toBeGreaterThan(0);
2091
- expect(projection.nodes).toHaveLength(3);
2092
- expect(() => renderminimap(model, 0, 100)).toThrow(/mini map size must be positive/i);
2093
- expect(() => renderminimap(model, 160, -1)).toThrow(/mini map size must be positive/i);
2094
- const focused = minimapfocus(model, 80, 50);
2095
- expect(focused.layout.viewportx).toBeGreaterThanOrEqual(0);
2096
- const zoomed = zoomcanvas(model, 0.5);
2097
- expect(zoomed.model.layout.zoom).toBe(0.5);
2098
- expect(zoomed.labelscale).toBe(2);
2099
- expect(zoomcanvas(model, 2).labelscale).toBe(1);
2100
- expect(() => zoomcanvas(model, 0)).toThrow(/positive number with no code ceiling/i);
2101
- expect(() => zoomcanvas(model, -1)).toThrow(/positive number with no code ceiling/i);
2102
- expect(() => zoomcanvas(model, NaN)).toThrow(/positive number with no code ceiling/i);
2103
- });
2104
-
2105
- it("searches the steps by label, kind and variable with the blank query empty", () => {
2106
- const model = loadworkflow(record());
2107
- expect(searchsteps(model, " ")).toEqual([]);
2108
- const bylabel = searchsteps(model, "the s1");
2109
- expect(bylabel[0]?.matched).toContain("label");
2110
- const bykind = searchsteps(model, "loop");
2111
- expect(bykind[0]?.id).toBe("l1");
2112
- const withedges: editormodel = { ...model, edges: [{ from: "s1", to: "s2", variable: "rows", kind: "number" }] };
2113
- expect(searchsteps(withedges, "rows")[0]?.matched).toContain("variable");
2114
- });
2115
-
2116
- it("marks the breakpoints on the canvas and in the blocks and refuses the unknown", () => {
2117
- const model = loadworkflow(record());
2118
- const marked = markbreakpoint(model, "s1");
2119
- expect(marked.nodes[0]?.step?.breakpoint).toBe(true);
2120
- const unmarked = markbreakpoint(marked, "s1");
2121
- expect(unmarked.nodes[0]?.step?.breakpoint).toBeUndefined();
2122
- expect(() => markbreakpoint(model, "ghost")).toThrow(/No canvas step matches ghost/i);
2123
- const blockmodel = loadworkflow(
2124
- composeworkflow({
2125
- name: "n",
2126
- version: 1,
2127
- origins: [origin],
2128
- steps: [{ block: "b", label: "b" }],
2129
- blocks: [{ name: "b", label: "b", steps: [step("i1")] }],
2130
- now,
2131
- }),
2132
- );
2133
- const blockmarked = markbreakpoint(blockmodel, "i1");
2134
- expect(blockmarked.blocks[0]?.steps[0]).toMatchObject({ id: "i1", breakpoint: true });
2135
- });
2136
-
2137
- it("segments the debug runs at the breakpoints and reports the remaining steps", () => {
2138
- const withbreakpoint = compose([step("s1"), { ...step("s2"), breakpoint: true }, step("s3")]);
2139
- expect(runtobreakpoint({ record: withbreakpoint, breakpoints: [] })).toMatchObject({
2140
- until: 1,
2141
- pausat: "s2",
2142
- remaining: 2,
2143
- });
2144
- expect(runtobreakpoint({ record: withbreakpoint, breakpoints: ["s3"] })).toMatchObject({
2145
- until: 1,
2146
- pausat: "s2",
2147
- remaining: 2,
2148
- });
2149
- expect(runtobreakpoint({ record: record(), breakpoints: ["s9"] })).toMatchObject({
2150
- until: 3,
2151
- pausat: undefined,
2152
- remaining: 0,
2153
- });
2154
- expect(runtobreakpoint({ record: record(), cursor: 2, breakpoints: [] })).toMatchObject({ until: 3, remaining: 0 });
2155
- expect(runtobreakpoint({ record: record(), cursor: -5, breakpoints: [] }).until).toBe(3);
2156
- });
2157
-
2158
- it("diffs the workflow versions with the added, removed and changed steps", () => {
2159
- const from = record();
2160
- const to = compose([
2161
- step("s1", { value: "20" }),
2162
- step("s3"),
2163
- controlstep("l1", "loop", { loop: { list: "items", item: "it", index: "ix", bound: 9, steps: [step("c1")] } }),
2164
- ]);
2165
- const diff = diffversions(from, to, now);
2166
- expect(diff.added.map((entry) => entry.stepid)).toEqual(["s3"]);
2167
- expect(diff.removed.map((entry) => entry.stepid)).toEqual(["s2"]);
2168
- expect(diff.changed.find((entry) => entry.stepid === "s1")?.changes).toEqual(["value"]);
2169
- expect(diff.changed.find((entry) => entry.stepid === "l1")?.changes).toEqual(["options"]);
2170
- expect(diff).toMatchObject({ from: 1, to: 1, at: now });
2171
- });
2172
-
2173
- it("roundtrips the export and import in json and yaml with the format version gate", () => {
2174
- const source = record();
2175
- for (const format of ["json", "yaml"] as const) {
2176
- const exported = exportworkflow(source, format, " the shared run ", now);
2177
- expect(exported.file.note).toBe(" the shared run ");
2178
- expect(exported.file.format).toBe(1);
2179
- const imported = importworkflow({
2180
- contents: exported.contents,
2181
- format,
2182
- now,
2183
- kindallowed: () => true,
2184
- riskof: () => "read",
2185
- });
2186
- expect(imported.record.steps.map((one) => one.id)).toEqual(source.steps.map((one) => one.id));
2187
- expect(imported.record.reviewstate).toBe("pending");
2188
- expect(imported.file.format).toBe(1);
2189
- }
2190
- const auto = importworkflow({
2191
- contents: exportworkflow(source, "json").contents,
2192
- now,
2193
- kindallowed: () => true,
2194
- riskof: () => "read",
2195
- });
2196
- expect(auto.record.id).toBe(source.id);
2197
- });
2198
-
2199
- it("refuses the malformed import documents of every shape", () => {
2200
- expect(() => importworkflow({ contents: "{bad json", format: "json", now })).toThrow();
2201
- expect(() => importworkflow({ contents: "[]", format: "json", now })).toThrow(/not a json object/i);
2202
- expect(() =>
2203
- importworkflow({
2204
- contents: JSON.stringify({ format: 99, exportedat: now, workflow: { steps: [] }, templates: [] }),
2205
- format: "json",
2206
- now,
2207
- }),
2208
- ).toThrow(/not the reviewed format 1/i);
2209
- expect(() =>
2210
- importworkflow({
2211
- contents: JSON.stringify({ format: 1, exportedat: now, workflow: { steps: [] }, templates: [] }),
2212
- format: "json",
2213
- now,
2214
- }),
2215
- ).toThrow(/at least one step/i);
2216
- const steps = [step("s1")];
2217
- const minimal = (workflow: Record<string, unknown>): string =>
2218
- JSON.stringify({ format: 1, exportedat: now, workflow, templates: [] });
2219
- expect(() =>
2220
- importworkflow({
2221
- contents: minimal({ name: "n", version: 1, origins: [origin], steps: [{ ...steps[0]!, kind: "WAIT" }] }),
2222
- format: "json",
2223
- now,
2224
- }),
2225
- ).toThrow(/reviewed step/i);
2226
- expect(() =>
2227
- importworkflow({
2228
- contents: JSON.stringify({
2229
- format: 1,
2230
- exportedat: now,
2231
- workflow: { name: "n", version: 1, origins: [origin], steps },
2232
- templates: "nope",
2233
- }),
2234
- format: "json",
2235
- now,
2236
- }),
2237
- ).toThrow(/templates .* must be a list/i);
2238
- expect(() =>
2239
- importworkflow({
2240
- contents: JSON.stringify({
2241
- format: 1,
2242
- exportedat: now,
2243
- workflow: { name: "n", version: 1, origins: [origin], steps },
2244
- templates: [{ id: "t", name: "n", origin, step: { ...steps[0]!, kind: "WAIT" }, sharedat: now }],
2245
- }),
2246
- format: "json",
2247
- now,
2248
- }),
2249
- ).toThrow(/does not carry one reviewed step/i);
2250
- expect(() => importworkflow({ contents: "", format: "yaml", now })).toThrow(/empty/i);
2251
- expect(() => importworkflow({ contents: "key with no colon\n nested: 1", format: "yaml", now })).toThrow();
2252
- expect(() => importworkflow({ contents: "- a\n- b", format: "yaml", now })).toThrow(/is not a mapping/i);
2253
- });
2254
-
2255
- it("shares the workflow with the packed templates and imports them back", () => {
2256
- const source = record();
2257
- const templates: steptemplate[] = [{ id: "t1", name: "the wait", origin, step: step("w9"), sharedat: now }];
2258
- const shared = shareworkflow(source, templates, "yaml", "the library note", now);
2259
- expect(shared.file.templates).toHaveLength(1);
2260
- const imported = importworkflow({
2261
- contents: shared.contents,
2262
- format: "yaml",
2263
- now,
2264
- kindallowed: () => true,
2265
- riskof: () => "read",
2266
- });
2267
- expect(imported.templates[0]).toEqual(templates[0]);
2268
- expect(importworkflow({ contents: shared.contents, now }).file.templates).toHaveLength(1);
2269
- });
2270
-
2271
- it("wires the nested parameters into the block invocations", () => {
2272
- const model = loadworkflow(
2273
- composeworkflow({
2274
- name: "n",
2275
- version: 1,
2276
- origins: [origin],
2277
- steps: [{ block: "b", label: "b", params: [{ name: "depth", kind: "number" }] }],
2278
- blocks: [{ name: "b", label: "b", steps: [step("i1")] }],
2279
- now,
2280
- }),
2281
- );
2282
- const bound = bindparam(model, "b", { name: "depth", kind: "number", default: 2 });
2283
- expect(bound.nodes[0]?.invocation?.params).toEqual([{ name: "depth", kind: "number", default: 2 }]);
2284
- expect(() => bindparam(model, "b", { name: "Bad Name", kind: "number" })).toThrow(/lowercase word/i);
2285
- expect(() => bindparam(model, "ghost", { name: "depth", kind: "number" })).toThrow(/No block invocation of ghost/i);
2286
- });
2287
-
2288
- it("applies the site overrides to the matching knobs only", () => {
2289
- const override: siteoverride = {
2290
- id: "o1",
2291
- workflowid: record().id,
2292
- pattern: origin,
2293
- deltas: { loopbound: 9 },
2294
- createdat: now,
2295
- };
2296
- const withloop = compose([
2297
- step("s1"),
2298
- controlstep("l1", "loop", { loop: { list: "items", item: "it", index: "ix", bound: 3, steps: [step("c1")] } }),
2299
- ]);
2300
- const applied = applyoverride(withloop, override);
2301
- const payload = JSON.parse(applied.steps[1]?.options ?? "{}") as { loop: { bound: number } };
2302
- expect(payload.loop.bound).toBe(9);
2303
- expect(() => applyoverride(withloop, { ...override, pattern: "https://denied.example" })).toThrow(
2304
- /matches none of the workflow origins/i,
2305
- );
2306
- expect(() => applyoverride(withloop, { ...override, deltas: { unknown: 1 } })).toThrow(
2307
- /not one of the reviewed knobs/i,
2308
- );
2309
- expect(() => applyoverride(withloop, { ...override, deltas: { loopbound: 0 } })).toThrow(
2310
- /must be a positive number/i,
2311
- );
2312
- expect(() => applyoverride(withloop, { ...override, deltas: { loopbound: -1 } })).toThrow(
2313
- /must be a positive number/i,
2314
- );
2315
- expect(() => applyoverride(withloop, { ...override, deltas: { loopbound: NaN } })).toThrow(
2316
- /must be a positive number/i,
2317
- );
2318
- expect(applyoverride(withloop, { ...override, deltas: {} }).steps).toEqual(withloop.steps);
2319
- });
2320
-
2321
- it("adds, removes and refuses the binding edges of the canvas", () => {
2322
- const model = loadworkflow(record());
2323
- const withedge = addedge(model, { from: "s1", to: "s2", variable: "rows", kind: "number" });
2324
- expect(withedge.edges).toHaveLength(1);
2325
- expect(() => addedge(model, { from: "s2", to: "s1", variable: "rows", kind: "number" })).toThrow(
2326
- /would run backwards/i,
2327
- );
2328
- expect(() => addedge(model, { from: "ghost", to: "s2", variable: "rows", kind: "number" })).toThrow(
2329
- /unknown source step ghost/i,
2330
- );
2331
- expect(() => addedge(model, { from: "s1", to: "s2", variable: "Bad Name", kind: "number" })).toThrow(
2332
- /lowercase word/i,
2333
- );
2334
- const removed = removeedge(withedge, "s1", "s2", "rows");
2335
- expect(removed.edges).toHaveLength(0);
2336
- expect(() => removeedge(withedge, "s1", "s2", "other")).toThrow(/No canvas edge of other links s1 into s2/i);
2337
- });
2338
-
2339
- it("removes the nodes with their edges and undoes and redoes the edits", () => {
2340
- const withedge = addedge(loadworkflow(record()), { from: "s1", to: "s2", variable: "rows", kind: "number" });
2341
- const removed = removenode(withedge, "s1");
2342
- expect(removed.nodes).toHaveLength(2);
2343
- expect(removed.edges).toHaveLength(0);
2344
- expect(() => removenode(removed, "s1")).toThrow(/No canvas node matches s1/i);
2345
- const undone = undoedit(removed);
2346
- expect(undone.nodes).toHaveLength(3);
2347
- expect(undone.redo).toHaveLength(1);
2348
- const redone = redoedit(undone);
2349
- expect(redone.nodes).toHaveLength(2);
2350
- expect(redone.undo).toHaveLength(2);
2351
- expect(undoedit(loadworkflow(record())).dirty).toBe(false);
2352
- expect(redoedit(loadworkflow(record())).dirty).toBe(false);
2353
- });
2354
- });