effect 4.1.4 → 4.1.6

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 (890) hide show
  1. package/THIRD_PARTY_NOTICES.md +88 -0
  2. package/ai-docs/package.json +2 -2
  3. package/dist/Arbitrary.d.ts +44 -2
  4. package/dist/Arbitrary.d.ts.map +1 -1
  5. package/dist/Arbitrary.js +9 -1
  6. package/dist/Arbitrary.js.map +1 -1
  7. package/dist/BigInt.d.ts +200 -1
  8. package/dist/BigInt.d.ts.map +1 -1
  9. package/dist/BigInt.js +105 -9
  10. package/dist/BigInt.js.map +1 -1
  11. package/dist/Cache.d.ts.map +1 -1
  12. package/dist/Cache.js +4 -2
  13. package/dist/Cache.js.map +1 -1
  14. package/dist/Cause.d.ts +3 -3
  15. package/dist/Cause.js +1 -1
  16. package/dist/Channel.d.ts +104 -7
  17. package/dist/Channel.d.ts.map +1 -1
  18. package/dist/Channel.js +73 -4
  19. package/dist/Channel.js.map +1 -1
  20. package/dist/Chunk.d.ts +5 -0
  21. package/dist/Chunk.d.ts.map +1 -1
  22. package/dist/Chunk.js +7 -2
  23. package/dist/Chunk.js.map +1 -1
  24. package/dist/Clock.d.ts +5 -2
  25. package/dist/Clock.d.ts.map +1 -1
  26. package/dist/Clock.js +2 -1
  27. package/dist/Clock.js.map +1 -1
  28. package/dist/Codegen.d.ts +300 -0
  29. package/dist/Codegen.d.ts.map +1 -0
  30. package/dist/Codegen.js +526 -0
  31. package/dist/Codegen.js.map +1 -0
  32. package/dist/Config.d.ts +31 -2
  33. package/dist/Config.d.ts.map +1 -1
  34. package/dist/Config.js +12 -1
  35. package/dist/Config.js.map +1 -1
  36. package/dist/ConfigProvider.d.ts +11 -1
  37. package/dist/ConfigProvider.d.ts.map +1 -1
  38. package/dist/ConfigProvider.js +17 -6
  39. package/dist/ConfigProvider.js.map +1 -1
  40. package/dist/Effect.d.ts +1008 -127
  41. package/dist/Effect.d.ts.map +1 -1
  42. package/dist/Effect.js +410 -49
  43. package/dist/Effect.js.map +1 -1
  44. package/dist/Equal.d.ts +4 -4
  45. package/dist/Equal.d.ts.map +1 -1
  46. package/dist/Equal.js +78 -65
  47. package/dist/Equal.js.map +1 -1
  48. package/dist/Equivalence.d.ts +11 -9
  49. package/dist/Equivalence.d.ts.map +1 -1
  50. package/dist/Equivalence.js +15 -12
  51. package/dist/Equivalence.js.map +1 -1
  52. package/dist/Fiber.d.ts +58 -8
  53. package/dist/Fiber.d.ts.map +1 -1
  54. package/dist/Fiber.js +28 -4
  55. package/dist/Fiber.js.map +1 -1
  56. package/dist/FiberHandle.d.ts +81 -10
  57. package/dist/FiberHandle.d.ts.map +1 -1
  58. package/dist/FiberHandle.js +40 -8
  59. package/dist/FiberHandle.js.map +1 -1
  60. package/dist/FiberMap.d.ts +80 -10
  61. package/dist/FiberMap.d.ts.map +1 -1
  62. package/dist/FiberMap.js +37 -6
  63. package/dist/FiberMap.js.map +1 -1
  64. package/dist/FiberSet.d.ts +93 -8
  65. package/dist/FiberSet.d.ts.map +1 -1
  66. package/dist/FiberSet.js +46 -4
  67. package/dist/FiberSet.js.map +1 -1
  68. package/dist/Formatter.d.ts +2 -0
  69. package/dist/Formatter.d.ts.map +1 -1
  70. package/dist/Formatter.js +2 -0
  71. package/dist/Formatter.js.map +1 -1
  72. package/dist/Hash.d.ts.map +1 -1
  73. package/dist/Hash.js +24 -17
  74. package/dist/Hash.js.map +1 -1
  75. package/dist/LayerMap.d.ts +12 -3
  76. package/dist/LayerMap.d.ts.map +1 -1
  77. package/dist/LayerMap.js +12 -2
  78. package/dist/LayerMap.js.map +1 -1
  79. package/dist/LayerRef.d.ts +3 -3
  80. package/dist/LayerRef.d.ts.map +1 -1
  81. package/dist/LayerRef.js +3 -3
  82. package/dist/LayerRef.js.map +1 -1
  83. package/dist/Logger.d.ts +37 -13
  84. package/dist/Logger.d.ts.map +1 -1
  85. package/dist/Logger.js +39 -10
  86. package/dist/Logger.js.map +1 -1
  87. package/dist/Match.d.ts +35 -23
  88. package/dist/Match.d.ts.map +1 -1
  89. package/dist/Match.js +16 -0
  90. package/dist/Match.js.map +1 -1
  91. package/dist/Metric.js +1 -1
  92. package/dist/Metric.js.map +1 -1
  93. package/dist/Option.d.ts +4 -1
  94. package/dist/Option.d.ts.map +1 -1
  95. package/dist/Option.js +6 -2
  96. package/dist/Option.js.map +1 -1
  97. package/dist/Order.d.ts +7 -5
  98. package/dist/Order.d.ts.map +1 -1
  99. package/dist/Order.js +8 -3
  100. package/dist/Order.js.map +1 -1
  101. package/dist/Pool.d.ts +4 -3
  102. package/dist/Pool.d.ts.map +1 -1
  103. package/dist/Pool.js +21 -18
  104. package/dist/Pool.js.map +1 -1
  105. package/dist/Predicate.d.ts +4 -1
  106. package/dist/Predicate.d.ts.map +1 -1
  107. package/dist/Predicate.js +5 -1
  108. package/dist/Predicate.js.map +1 -1
  109. package/dist/Queue.d.ts +69 -22
  110. package/dist/Queue.d.ts.map +1 -1
  111. package/dist/Queue.js +40 -18
  112. package/dist/Queue.js.map +1 -1
  113. package/dist/Rational.d.ts +179 -0
  114. package/dist/Rational.d.ts.map +1 -1
  115. package/dist/Rational.js +63 -0
  116. package/dist/Rational.js.map +1 -1
  117. package/dist/Request.d.ts +20 -0
  118. package/dist/Request.d.ts.map +1 -1
  119. package/dist/Request.js +20 -0
  120. package/dist/Request.js.map +1 -1
  121. package/dist/Result.d.ts +3 -1
  122. package/dist/Result.d.ts.map +1 -1
  123. package/dist/Result.js +5 -2
  124. package/dist/Result.js.map +1 -1
  125. package/dist/Schema.d.ts +90 -19
  126. package/dist/Schema.d.ts.map +1 -1
  127. package/dist/Schema.js +92 -414
  128. package/dist/Schema.js.map +1 -1
  129. package/dist/SchemaAST.d.ts.map +1 -1
  130. package/dist/SchemaAST.js +11 -7
  131. package/dist/SchemaAST.js.map +1 -1
  132. package/dist/SchemaGetter.d.ts +5 -6
  133. package/dist/SchemaGetter.d.ts.map +1 -1
  134. package/dist/SchemaGetter.js +14 -10
  135. package/dist/SchemaGetter.js.map +1 -1
  136. package/dist/SchemaRepresentation.d.ts +19 -64
  137. package/dist/SchemaRepresentation.d.ts.map +1 -1
  138. package/dist/SchemaRepresentation.js +1 -28
  139. package/dist/SchemaRepresentation.js.map +1 -1
  140. package/dist/SchemaTransformation.d.ts +11 -10
  141. package/dist/SchemaTransformation.d.ts.map +1 -1
  142. package/dist/SchemaTransformation.js +12 -11
  143. package/dist/SchemaTransformation.js.map +1 -1
  144. package/dist/Scope.d.ts +12 -6
  145. package/dist/Scope.d.ts.map +1 -1
  146. package/dist/Scope.js +12 -6
  147. package/dist/Scope.js.map +1 -1
  148. package/dist/ScopedCache.d.ts.map +1 -1
  149. package/dist/ScopedCache.js +8 -5
  150. package/dist/ScopedCache.js.map +1 -1
  151. package/dist/Semaphore.d.ts.map +1 -1
  152. package/dist/Semaphore.js +18 -4
  153. package/dist/Semaphore.js.map +1 -1
  154. package/dist/Stream.d.ts +128 -5
  155. package/dist/Stream.d.ts.map +1 -1
  156. package/dist/Stream.js +179 -43
  157. package/dist/Stream.js.map +1 -1
  158. package/dist/String.d.ts +57 -3
  159. package/dist/String.d.ts.map +1 -1
  160. package/dist/String.js +63 -5
  161. package/dist/String.js.map +1 -1
  162. package/dist/Struct.d.ts +135 -1
  163. package/dist/Struct.d.ts.map +1 -1
  164. package/dist/Struct.js +64 -5
  165. package/dist/Struct.js.map +1 -1
  166. package/dist/TextDiff.d.ts +105 -0
  167. package/dist/TextDiff.d.ts.map +1 -1
  168. package/dist/TextDiff.js +137 -24
  169. package/dist/TextDiff.js.map +1 -1
  170. package/dist/Tracer.d.ts +10 -0
  171. package/dist/Tracer.d.ts.map +1 -1
  172. package/dist/Tracer.js +2 -0
  173. package/dist/Tracer.js.map +1 -1
  174. package/dist/TxPriorityQueue.js +2 -2
  175. package/dist/TxPriorityQueue.js.map +1 -1
  176. package/dist/ai/LanguageModel.d.ts.map +1 -1
  177. package/dist/ai/LanguageModel.js +1 -1
  178. package/dist/ai/LanguageModel.js.map +1 -1
  179. package/dist/ai/McpServer.d.ts +199 -4
  180. package/dist/ai/McpServer.d.ts.map +1 -1
  181. package/dist/ai/McpServer.js +143 -18
  182. package/dist/ai/McpServer.js.map +1 -1
  183. package/dist/ai/Prompt.d.ts +3 -1
  184. package/dist/ai/Prompt.d.ts.map +1 -1
  185. package/dist/ai/Prompt.js +17 -3
  186. package/dist/ai/Prompt.js.map +1 -1
  187. package/dist/ai/Skill.d.ts +172 -0
  188. package/dist/ai/Skill.d.ts.map +1 -0
  189. package/dist/ai/Skill.js +209 -0
  190. package/dist/ai/Skill.js.map +1 -0
  191. package/dist/ai/Tool.d.ts +3 -2
  192. package/dist/ai/Tool.d.ts.map +1 -1
  193. package/dist/ai/Tool.js +3 -2
  194. package/dist/ai/Tool.js.map +1 -1
  195. package/dist/ai/Toolkit.d.ts.map +1 -1
  196. package/dist/ai/Toolkit.js +5 -1
  197. package/dist/ai/Toolkit.js.map +1 -1
  198. package/dist/ai/index.d.ts +5 -0
  199. package/dist/ai/index.d.ts.map +1 -1
  200. package/dist/ai/index.js +5 -0
  201. package/dist/ai/index.js.map +1 -1
  202. package/dist/chat/Chat.d.ts +90 -0
  203. package/dist/chat/Chat.d.ts.map +1 -0
  204. package/dist/chat/Chat.js +127 -0
  205. package/dist/chat/Chat.js.map +1 -0
  206. package/dist/chat/ChatAdapter.d.ts +386 -0
  207. package/dist/chat/ChatAdapter.d.ts.map +1 -0
  208. package/dist/chat/ChatAdapter.js +110 -0
  209. package/dist/chat/ChatAdapter.js.map +1 -0
  210. package/dist/chat/ChatError.d.ts +500 -0
  211. package/dist/chat/ChatError.d.ts.map +1 -0
  212. package/dist/chat/ChatError.js +521 -0
  213. package/dist/chat/ChatError.js.map +1 -0
  214. package/dist/chat/ChatEvent.d.ts +321 -0
  215. package/dist/chat/ChatEvent.d.ts.map +1 -0
  216. package/dist/chat/ChatEvent.js +163 -0
  217. package/dist/chat/ChatEvent.js.map +1 -0
  218. package/dist/chat/ChatHandler.d.ts +81 -0
  219. package/dist/chat/ChatHandler.d.ts.map +1 -0
  220. package/dist/chat/ChatHandler.js +85 -0
  221. package/dist/chat/ChatHandler.js.map +1 -0
  222. package/dist/chat/ChatInteraction.d.ts +1519 -0
  223. package/dist/chat/ChatInteraction.d.ts.map +1 -0
  224. package/dist/chat/ChatInteraction.js +1052 -0
  225. package/dist/chat/ChatInteraction.js.map +1 -0
  226. package/dist/chat/ChatMarkdown.d.ts +280 -0
  227. package/dist/chat/ChatMarkdown.d.ts.map +1 -0
  228. package/dist/chat/ChatMarkdown.js +1172 -0
  229. package/dist/chat/ChatMarkdown.js.map +1 -0
  230. package/dist/chat/ChatMessage.d.ts +224 -0
  231. package/dist/chat/ChatMessage.d.ts.map +1 -0
  232. package/dist/chat/ChatMessage.js +172 -0
  233. package/dist/chat/ChatMessage.js.map +1 -0
  234. package/dist/chat/ChatTest.d.ts +407 -0
  235. package/dist/chat/ChatTest.d.ts.map +1 -0
  236. package/dist/chat/ChatTest.js +2145 -0
  237. package/dist/chat/ChatTest.js.map +1 -0
  238. package/dist/chat/ChatThread.d.ts +92 -0
  239. package/dist/chat/ChatThread.d.ts.map +1 -0
  240. package/dist/chat/ChatThread.js +116 -0
  241. package/dist/chat/ChatThread.js.map +1 -0
  242. package/dist/chat/ChatUi.d.ts +362 -0
  243. package/dist/chat/ChatUi.d.ts.map +1 -0
  244. package/dist/chat/ChatUi.js +209 -0
  245. package/dist/chat/ChatUi.js.map +1 -0
  246. package/dist/chat/index.d.ts +60 -0
  247. package/dist/chat/index.d.ts.map +1 -0
  248. package/dist/chat/index.js +61 -0
  249. package/dist/chat/index.js.map +1 -0
  250. package/dist/chat/internal/retries.d.ts +2 -0
  251. package/dist/chat/internal/retries.d.ts.map +1 -0
  252. package/dist/chat/internal/retries.js +7 -0
  253. package/dist/chat/internal/retries.js.map +1 -0
  254. package/dist/cli/CliOutput.d.ts.map +1 -1
  255. package/dist/cli/CliOutput.js +6 -7
  256. package/dist/cli/CliOutput.js.map +1 -1
  257. package/dist/cli/Command.d.ts +20 -2
  258. package/dist/cli/Command.d.ts.map +1 -1
  259. package/dist/cli/Command.js +4 -0
  260. package/dist/cli/Command.js.map +1 -1
  261. package/dist/cli/Prompt.d.ts +5 -6
  262. package/dist/cli/Prompt.d.ts.map +1 -1
  263. package/dist/cli/Prompt.js +9 -4
  264. package/dist/cli/Prompt.js.map +1 -1
  265. package/dist/cli/internal/command.d.ts +1 -1
  266. package/dist/cli/internal/command.d.ts.map +1 -1
  267. package/dist/cli/internal/config.d.ts +1 -1
  268. package/dist/cli/internal/config.d.ts.map +1 -1
  269. package/dist/cli/internal/config.js +3 -3
  270. package/dist/cli/internal/config.js.map +1 -1
  271. package/dist/cluster/ClusterCron.d.ts +21 -1
  272. package/dist/cluster/ClusterCron.d.ts.map +1 -1
  273. package/dist/cluster/ClusterCron.js +24 -6
  274. package/dist/cluster/ClusterCron.js.map +1 -1
  275. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  276. package/dist/cluster/ClusterWorkflowEngine.js +183 -103
  277. package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
  278. package/dist/cluster/MessageStorage.d.ts +56 -0
  279. package/dist/cluster/MessageStorage.d.ts.map +1 -1
  280. package/dist/cluster/MessageStorage.js +18 -2
  281. package/dist/cluster/MessageStorage.js.map +1 -1
  282. package/dist/cluster/Sharding.d.ts.map +1 -1
  283. package/dist/cluster/Sharding.js +15 -3
  284. package/dist/cluster/Sharding.js.map +1 -1
  285. package/dist/cluster/ShardingConfig.d.ts +6 -0
  286. package/dist/cluster/ShardingConfig.d.ts.map +1 -1
  287. package/dist/cluster/ShardingConfig.js.map +1 -1
  288. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  289. package/dist/cluster/SqlMessageStorage.js +58 -37
  290. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  291. package/dist/cluster/SqlRunnerStorage.d.ts.map +1 -1
  292. package/dist/cluster/SqlRunnerStorage.js +18 -8
  293. package/dist/cluster/SqlRunnerStorage.js.map +1 -1
  294. package/dist/cluster/internal/entityActivation.js +2 -0
  295. package/dist/cluster/internal/entityActivation.js.map +1 -1
  296. package/dist/cluster/internal/entityManager.js +20 -13
  297. package/dist/cluster/internal/entityManager.js.map +1 -1
  298. package/dist/cluster/internal/entityReaper.js +1 -1
  299. package/dist/cluster/internal/entityReaper.js.map +1 -1
  300. package/dist/crypto/Kdf.d.ts +2 -1
  301. package/dist/crypto/Kdf.d.ts.map +1 -1
  302. package/dist/crypto/Kdf.js +2 -1
  303. package/dist/crypto/Kdf.js.map +1 -1
  304. package/dist/crypto/Password.d.ts +162 -0
  305. package/dist/crypto/Password.d.ts.map +1 -0
  306. package/dist/crypto/Password.js +217 -0
  307. package/dist/crypto/Password.js.map +1 -0
  308. package/dist/crypto/index.d.ts +5 -0
  309. package/dist/crypto/index.d.ts.map +1 -1
  310. package/dist/crypto/index.js +5 -0
  311. package/dist/crypto/index.js.map +1 -1
  312. package/dist/encoding/Base64.d.ts +63 -0
  313. package/dist/encoding/Base64.d.ts.map +1 -1
  314. package/dist/encoding/Base64.js +82 -1
  315. package/dist/encoding/Base64.js.map +1 -1
  316. package/dist/encoding/Base64Url.d.ts +1 -0
  317. package/dist/encoding/Base64Url.d.ts.map +1 -1
  318. package/dist/encoding/Base64Url.js +7 -1
  319. package/dist/encoding/Base64Url.js.map +1 -1
  320. package/dist/encoding/Csv.d.ts.map +1 -1
  321. package/dist/encoding/Csv.js +44 -16
  322. package/dist/encoding/Csv.js.map +1 -1
  323. package/dist/encoding/Hex.d.ts +5 -0
  324. package/dist/encoding/Hex.d.ts.map +1 -1
  325. package/dist/encoding/Hex.js +5 -0
  326. package/dist/encoding/Hex.js.map +1 -1
  327. package/dist/encoding/SchemaBinary.d.ts.map +1 -1
  328. package/dist/encoding/SchemaBinary.js +13 -124
  329. package/dist/encoding/SchemaBinary.js.map +1 -1
  330. package/dist/encoding/Sse.d.ts +1 -0
  331. package/dist/encoding/Sse.d.ts.map +1 -1
  332. package/dist/encoding/Sse.js +7 -5
  333. package/dist/encoding/Sse.js.map +1 -1
  334. package/dist/encoding/Xml.d.ts +153 -18
  335. package/dist/encoding/Xml.d.ts.map +1 -1
  336. package/dist/encoding/Xml.js +379 -57
  337. package/dist/encoding/Xml.js.map +1 -1
  338. package/dist/eventlog/EventJournal.d.ts.map +1 -1
  339. package/dist/eventlog/EventJournal.js +3 -8
  340. package/dist/eventlog/EventJournal.js.map +1 -1
  341. package/dist/eventlog/SqlEventLogServerEncrypted.js +6 -8
  342. package/dist/eventlog/SqlEventLogServerEncrypted.js.map +1 -1
  343. package/dist/http/FetchHttpClient.d.ts +2 -1
  344. package/dist/http/FetchHttpClient.d.ts.map +1 -1
  345. package/dist/http/FetchHttpClient.js +14 -10
  346. package/dist/http/FetchHttpClient.js.map +1 -1
  347. package/dist/http/FindMyWay/internal/router.js +163 -116
  348. package/dist/http/FindMyWay/internal/router.js.map +1 -1
  349. package/dist/http/FindMyWay.d.ts +99 -0
  350. package/dist/http/FindMyWay.d.ts.map +1 -1
  351. package/dist/http/FindMyWay.js +39 -0
  352. package/dist/http/FindMyWay.js.map +1 -1
  353. package/dist/http/Headers.d.ts +201 -3
  354. package/dist/http/Headers.d.ts.map +1 -1
  355. package/dist/http/Headers.js +205 -3
  356. package/dist/http/Headers.js.map +1 -1
  357. package/dist/http/HttpClient.d.ts.map +1 -1
  358. package/dist/http/HttpClient.js +12 -8
  359. package/dist/http/HttpClient.js.map +1 -1
  360. package/dist/http/HttpClientError.d.ts +1 -0
  361. package/dist/http/HttpClientError.d.ts.map +1 -1
  362. package/dist/http/HttpClientError.js +32 -9
  363. package/dist/http/HttpClientError.js.map +1 -1
  364. package/dist/http/HttpClientRequest.d.ts +46 -0
  365. package/dist/http/HttpClientRequest.d.ts.map +1 -1
  366. package/dist/http/HttpClientRequest.js +15 -0
  367. package/dist/http/HttpClientRequest.js.map +1 -1
  368. package/dist/http/HttpClientResponse.d.ts +132 -0
  369. package/dist/http/HttpClientResponse.d.ts.map +1 -1
  370. package/dist/http/HttpClientResponse.js +83 -0
  371. package/dist/http/HttpClientResponse.js.map +1 -1
  372. package/dist/http/HttpMiddleware.d.ts.map +1 -1
  373. package/dist/http/HttpMiddleware.js +16 -9
  374. package/dist/http/HttpMiddleware.js.map +1 -1
  375. package/dist/http/HttpRouter.d.ts +49 -1
  376. package/dist/http/HttpRouter.d.ts.map +1 -1
  377. package/dist/http/HttpRouter.js +70 -20
  378. package/dist/http/HttpRouter.js.map +1 -1
  379. package/dist/http/HttpServerResponse.d.ts +118 -0
  380. package/dist/http/HttpServerResponse.d.ts.map +1 -1
  381. package/dist/http/HttpServerResponse.js +67 -58
  382. package/dist/http/HttpServerResponse.js.map +1 -1
  383. package/dist/http/Mime.d.ts.map +1 -1
  384. package/dist/http/Mime.js +3 -2
  385. package/dist/http/Mime.js.map +1 -1
  386. package/dist/http/Multipart.d.ts.map +1 -1
  387. package/dist/http/Multipart.js +0 -5
  388. package/dist/http/Multipart.js.map +1 -1
  389. package/dist/http/MultipartParser/internal/contentType.d.ts +6 -0
  390. package/dist/http/MultipartParser/internal/contentType.d.ts.map +1 -1
  391. package/dist/http/MultipartParser/internal/contentType.js +1 -1
  392. package/dist/http/MultipartParser/internal/contentType.js.map +1 -1
  393. package/dist/http/internal/clientPath.d.ts +2 -0
  394. package/dist/http/internal/clientPath.d.ts.map +1 -0
  395. package/dist/http/internal/clientPath.js +24 -0
  396. package/dist/http/internal/clientPath.js.map +1 -0
  397. package/dist/http/internal/compression.d.ts.map +1 -1
  398. package/dist/http/internal/compression.js +2 -2
  399. package/dist/http/internal/compression.js.map +1 -1
  400. package/dist/http/internal/mediaType.d.ts.map +1 -0
  401. package/dist/{http-api → http}/internal/mediaType.js +4 -0
  402. package/dist/{http-api → http}/internal/mediaType.js.map +1 -1
  403. package/dist/http/internal/redactedPath.d.ts +2 -0
  404. package/dist/http/internal/redactedPath.d.ts.map +1 -0
  405. package/dist/http/internal/redactedPath.js +140 -0
  406. package/dist/http/internal/redactedPath.js.map +1 -0
  407. package/dist/http/internal/requestState.js +1 -0
  408. package/dist/http/internal/requestState.js.map +1 -1
  409. package/dist/http/internal/tracing.js +5 -3
  410. package/dist/http/internal/tracing.js.map +1 -1
  411. package/dist/http-api/HttpApi.d.ts +13 -2
  412. package/dist/http-api/HttpApi.d.ts.map +1 -1
  413. package/dist/http-api/HttpApi.js +43 -6
  414. package/dist/http-api/HttpApi.js.map +1 -1
  415. package/dist/http-api/HttpApiBuilder.d.ts.map +1 -1
  416. package/dist/http-api/HttpApiBuilder.js +7 -3
  417. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  418. package/dist/http-api/HttpApiClient.d.ts.map +1 -1
  419. package/dist/http-api/HttpApiClient.js +29 -12
  420. package/dist/http-api/HttpApiClient.js.map +1 -1
  421. package/dist/http-api/HttpApiEndpoint.d.ts.map +1 -1
  422. package/dist/http-api/HttpApiEndpoint.js +1 -1
  423. package/dist/http-api/HttpApiEndpoint.js.map +1 -1
  424. package/dist/http-api/HttpApiScalar.d.ts +4 -0
  425. package/dist/http-api/HttpApiScalar.d.ts.map +1 -1
  426. package/dist/http-api/HttpApiScalar.js +10 -1
  427. package/dist/http-api/HttpApiScalar.js.map +1 -1
  428. package/dist/http-api/HttpApiSchema.d.ts.map +1 -1
  429. package/dist/http-api/HttpApiSchema.js +1 -1
  430. package/dist/http-api/HttpApiSchema.js.map +1 -1
  431. package/dist/http-api/OpenApi.d.ts +2 -0
  432. package/dist/http-api/OpenApi.d.ts.map +1 -1
  433. package/dist/http-api/internal/httpApiScalar.js +5 -2
  434. package/dist/http-api/internal/httpApiScalar.js.map +1 -1
  435. package/dist/http-api/internal/redactedKeys.d.ts +2 -0
  436. package/dist/http-api/internal/redactedKeys.d.ts.map +1 -0
  437. package/dist/http-api/internal/redactedKeys.js +37 -0
  438. package/dist/http-api/internal/redactedKeys.js.map +1 -0
  439. package/dist/index.d.ts +5 -0
  440. package/dist/index.d.ts.map +1 -1
  441. package/dist/index.js +5 -0
  442. package/dist/index.js.map +1 -1
  443. package/dist/internal/arbitrary/model.js +0 -5
  444. package/dist/internal/arbitrary/model.js.map +1 -1
  445. package/dist/internal/arbitrary/regexp.js +2 -1
  446. package/dist/internal/arbitrary/regexp.js.map +1 -1
  447. package/dist/internal/arbitrary/runner.d.ts.map +1 -1
  448. package/dist/internal/arbitrary/runner.js +21 -16
  449. package/dist/internal/arbitrary/runner.js.map +1 -1
  450. package/dist/internal/arbitrary/schema.js +140 -23
  451. package/dist/internal/arbitrary/schema.js.map +1 -1
  452. package/dist/internal/base64.js +34 -2
  453. package/dist/internal/base64.js.map +1 -1
  454. package/dist/internal/codegen.d.ts +2 -0
  455. package/dist/internal/codegen.d.ts.map +1 -0
  456. package/dist/internal/codegen.js +59 -0
  457. package/dist/internal/codegen.js.map +1 -0
  458. package/dist/internal/core.js +3 -3
  459. package/dist/internal/core.js.map +1 -1
  460. package/dist/internal/dateTime.js +61 -29
  461. package/dist/internal/dateTime.js.map +1 -1
  462. package/dist/internal/effect.js +30 -8
  463. package/dist/internal/effect.js.map +1 -1
  464. package/dist/internal/equal.js +14 -13
  465. package/dist/internal/equal.js.map +1 -1
  466. package/dist/internal/hash.js +4 -1
  467. package/dist/internal/hash.js.map +1 -1
  468. package/dist/internal/hashMap.js +7 -7
  469. package/dist/internal/hashMap.js.map +1 -1
  470. package/dist/internal/matcher.js +19 -18
  471. package/dist/internal/matcher.js.map +1 -1
  472. package/dist/internal/record.js +18 -4
  473. package/dist/internal/record.js.map +1 -1
  474. package/dist/internal/result.js +1 -1
  475. package/dist/internal/result.js.map +1 -1
  476. package/dist/internal/schema/codeExpression.d.ts +4 -0
  477. package/dist/internal/schema/codeExpression.d.ts.map +1 -0
  478. package/dist/internal/schema/codeExpression.js +179 -0
  479. package/dist/internal/schema/codeExpression.js.map +1 -0
  480. package/dist/internal/schema/codeImports.d.ts +8 -0
  481. package/dist/internal/schema/codeImports.d.ts.map +1 -0
  482. package/dist/internal/schema/codeImports.js +135 -0
  483. package/dist/internal/schema/codeImports.js.map +1 -0
  484. package/dist/internal/schema/codeTokens.d.ts +8 -0
  485. package/dist/internal/schema/codeTokens.d.ts.map +1 -0
  486. package/dist/internal/schema/codeTokens.js +17 -0
  487. package/dist/internal/schema/codeTokens.js.map +1 -0
  488. package/dist/internal/schema/passthrough.d.ts +2 -0
  489. package/dist/internal/schema/passthrough.d.ts.map +1 -0
  490. package/dist/internal/schema/passthrough.js +8 -0
  491. package/dist/internal/schema/passthrough.js.map +1 -0
  492. package/dist/internal/schema/schemaCodegen.d.ts +2 -0
  493. package/dist/internal/schema/schemaCodegen.d.ts.map +1 -0
  494. package/dist/internal/schema/schemaCodegen.js +378 -0
  495. package/dist/internal/schema/schemaCodegen.js.map +1 -0
  496. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts +2 -0
  497. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts.map +1 -0
  498. package/dist/internal/schema/schemaCodegenBuiltIns.js +425 -0
  499. package/dist/internal/schema/schemaCodegenBuiltIns.js.map +1 -0
  500. package/dist/internal/schema/toEquivalence.js +3 -4
  501. package/dist/internal/schema/toEquivalence.js.map +1 -1
  502. package/dist/internal/schema/toJsonSchemaDocument.js +11 -4
  503. package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -1
  504. package/dist/internal/trie.js +51 -64
  505. package/dist/internal/trie.js.map +1 -1
  506. package/dist/internal/utf8.d.ts +2 -0
  507. package/dist/internal/utf8.d.ts.map +1 -0
  508. package/dist/internal/utf8.js +151 -0
  509. package/dist/internal/utf8.js.map +1 -0
  510. package/dist/internal/version.js +1 -1
  511. package/dist/jose/JoseError.d.ts +51 -1
  512. package/dist/jose/JoseError.d.ts.map +1 -1
  513. package/dist/jose/JoseError.js +25 -18
  514. package/dist/jose/JoseError.js.map +1 -1
  515. package/dist/jose/Jwks.d.ts +13 -0
  516. package/dist/jose/Jwks.d.ts.map +1 -1
  517. package/dist/jose/Jwks.js +10 -2
  518. package/dist/jose/Jwks.js.map +1 -1
  519. package/dist/jose/internal/compact.js +10 -5
  520. package/dist/jose/internal/compact.js.map +1 -1
  521. package/dist/observability/Otlp.d.ts +19 -0
  522. package/dist/observability/Otlp.d.ts.map +1 -1
  523. package/dist/observability/Otlp.js +10 -0
  524. package/dist/observability/Otlp.js.map +1 -1
  525. package/dist/observability/OtlpExporter.d.ts +49 -13
  526. package/dist/observability/OtlpExporter.d.ts.map +1 -1
  527. package/dist/observability/OtlpExporter.js +133 -50
  528. package/dist/observability/OtlpExporter.js.map +1 -1
  529. package/dist/observability/OtlpLogger.d.ts +14 -0
  530. package/dist/observability/OtlpLogger.d.ts.map +1 -1
  531. package/dist/observability/OtlpLogger.js +15 -5
  532. package/dist/observability/OtlpLogger.js.map +1 -1
  533. package/dist/observability/OtlpMetrics.d.ts.map +1 -1
  534. package/dist/observability/OtlpMetrics.js +2 -0
  535. package/dist/observability/OtlpMetrics.js.map +1 -1
  536. package/dist/observability/OtlpTracer.d.ts +14 -0
  537. package/dist/observability/OtlpTracer.d.ts.map +1 -1
  538. package/dist/observability/OtlpTracer.js +10 -2
  539. package/dist/observability/OtlpTracer.js.map +1 -1
  540. package/dist/observability/internal/otlpProtobuf.d.ts +4 -2
  541. package/dist/observability/internal/otlpProtobuf.d.ts.map +1 -1
  542. package/dist/observability/internal/otlpProtobuf.js +238 -156
  543. package/dist/observability/internal/otlpProtobuf.js.map +1 -1
  544. package/dist/persistence/KeyValueStore.d.ts.map +1 -1
  545. package/dist/persistence/KeyValueStore.js +6 -4
  546. package/dist/persistence/KeyValueStore.js.map +1 -1
  547. package/dist/persistence/PersistedQueue.d.ts.map +1 -1
  548. package/dist/persistence/PersistedQueue.js +20 -3
  549. package/dist/persistence/PersistedQueue.js.map +1 -1
  550. package/dist/protobuf/ProtobufDescriptor.d.ts +377 -0
  551. package/dist/protobuf/ProtobufDescriptor.d.ts.map +1 -0
  552. package/dist/protobuf/ProtobufDescriptor.js +135 -0
  553. package/dist/protobuf/ProtobufDescriptor.js.map +1 -0
  554. package/dist/protobuf/ProtobufDescriptorProto.d.ts +2083 -0
  555. package/dist/protobuf/ProtobufDescriptorProto.d.ts.map +1 -0
  556. package/dist/protobuf/ProtobufDescriptorProto.js +2674 -0
  557. package/dist/protobuf/ProtobufDescriptorProto.js.map +1 -0
  558. package/dist/protobuf/ProtobufMessage.d.ts +183 -0
  559. package/dist/protobuf/ProtobufMessage.d.ts.map +1 -0
  560. package/dist/protobuf/ProtobufMessage.js +232 -0
  561. package/dist/protobuf/ProtobufMessage.js.map +1 -0
  562. package/dist/protobuf/ProtobufReader.d.ts +350 -0
  563. package/dist/protobuf/ProtobufReader.d.ts.map +1 -0
  564. package/dist/protobuf/ProtobufReader.js +698 -0
  565. package/dist/protobuf/ProtobufReader.js.map +1 -0
  566. package/dist/protobuf/ProtobufWriter.d.ts +224 -0
  567. package/dist/protobuf/ProtobufWriter.d.ts.map +1 -0
  568. package/dist/protobuf/ProtobufWriter.js +483 -0
  569. package/dist/protobuf/ProtobufWriter.js.map +1 -0
  570. package/dist/protobuf/index.d.ts +30 -0
  571. package/dist/protobuf/index.d.ts.map +1 -0
  572. package/dist/protobuf/index.js +31 -0
  573. package/dist/protobuf/index.js.map +1 -0
  574. package/dist/protobuf/internal/binary.d.ts +2 -0
  575. package/dist/protobuf/internal/binary.d.ts.map +1 -0
  576. package/dist/protobuf/internal/binary.js +966 -0
  577. package/dist/protobuf/internal/binary.js.map +1 -0
  578. package/dist/protobuf/internal/resolve.d.ts +2 -0
  579. package/dist/protobuf/internal/resolve.d.ts.map +1 -0
  580. package/dist/protobuf/internal/resolve.js +463 -0
  581. package/dist/protobuf/internal/resolve.js.map +1 -0
  582. package/dist/protobuf/internal/wireType.d.ts +2 -0
  583. package/dist/protobuf/internal/wireType.d.ts.map +1 -0
  584. package/dist/protobuf/internal/wireType.js +10 -0
  585. package/dist/protobuf/internal/wireType.js.map +1 -0
  586. package/dist/reactivity/AsyncResult.d.ts +3 -0
  587. package/dist/reactivity/AsyncResult.d.ts.map +1 -1
  588. package/dist/reactivity/AsyncResult.js +4 -1
  589. package/dist/reactivity/AsyncResult.js.map +1 -1
  590. package/dist/reactivity/Atom.d.ts +10 -4
  591. package/dist/reactivity/Atom.d.ts.map +1 -1
  592. package/dist/reactivity/Atom.js +48 -22
  593. package/dist/reactivity/Atom.js.map +1 -1
  594. package/dist/reactivity/AtomHttpApi.d.ts +5 -0
  595. package/dist/reactivity/AtomHttpApi.d.ts.map +1 -1
  596. package/dist/reactivity/AtomHttpApi.js +5 -1
  597. package/dist/reactivity/AtomHttpApi.js.map +1 -1
  598. package/dist/reactivity/AtomRegistry.js +13 -0
  599. package/dist/reactivity/AtomRegistry.js.map +1 -1
  600. package/dist/reactivity/AtomRpc.d.ts +5 -0
  601. package/dist/reactivity/AtomRpc.d.ts.map +1 -1
  602. package/dist/reactivity/AtomRpc.js +6 -1
  603. package/dist/reactivity/AtomRpc.js.map +1 -1
  604. package/dist/rpc/Rpc.d.ts +25 -0
  605. package/dist/rpc/Rpc.d.ts.map +1 -1
  606. package/dist/rpc/Rpc.js +18 -0
  607. package/dist/rpc/Rpc.js.map +1 -1
  608. package/dist/rpc/RpcClient.d.ts.map +1 -1
  609. package/dist/rpc/RpcClient.js +70 -22
  610. package/dist/rpc/RpcClient.js.map +1 -1
  611. package/dist/rpc/RpcGroup.d.ts +6 -1
  612. package/dist/rpc/RpcGroup.d.ts.map +1 -1
  613. package/dist/rpc/RpcGroup.js +4 -0
  614. package/dist/rpc/RpcGroup.js.map +1 -1
  615. package/dist/rpc/RpcMiddleware.d.ts +9 -0
  616. package/dist/rpc/RpcMiddleware.d.ts.map +1 -1
  617. package/dist/rpc/RpcMiddleware.js.map +1 -1
  618. package/dist/rpc/RpcSerialization.d.ts +7 -1
  619. package/dist/rpc/RpcSerialization.d.ts.map +1 -1
  620. package/dist/rpc/RpcSerialization.js +22 -5
  621. package/dist/rpc/RpcSerialization.js.map +1 -1
  622. package/dist/rpc/RpcServer.d.ts.map +1 -1
  623. package/dist/rpc/RpcServer.js +33 -18
  624. package/dist/rpc/RpcServer.js.map +1 -1
  625. package/dist/schema/SchemaCompiler/runtime.js +2 -1
  626. package/dist/schema/SchemaCompiler/runtime.js.map +1 -1
  627. package/dist/schema/VariantSchema.d.ts +10 -2
  628. package/dist/schema/VariantSchema.d.ts.map +1 -1
  629. package/dist/schema/VariantSchema.js +7 -1
  630. package/dist/schema/VariantSchema.js.map +1 -1
  631. package/dist/socket/Socket.d.ts +24 -10
  632. package/dist/socket/Socket.d.ts.map +1 -1
  633. package/dist/socket/Socket.js +52 -17
  634. package/dist/socket/Socket.js.map +1 -1
  635. package/dist/sql/Migrator.d.ts +3 -0
  636. package/dist/sql/Migrator.d.ts.map +1 -1
  637. package/dist/sql/Migrator.js +12 -6
  638. package/dist/sql/Migrator.js.map +1 -1
  639. package/dist/sql/SqlClient.d.ts.map +1 -1
  640. package/dist/sql/SqlClient.js +5 -1
  641. package/dist/sql/SqlClient.js.map +1 -1
  642. package/dist/sql/SqlModel.d.ts.map +1 -1
  643. package/dist/sql/SqlModel.js +1 -0
  644. package/dist/sql/SqlModel.js.map +1 -1
  645. package/dist/testing/TestConsole.d.ts +96 -0
  646. package/dist/testing/TestConsole.d.ts.map +1 -1
  647. package/dist/testing/TestConsole.js +78 -6
  648. package/dist/testing/TestConsole.js.map +1 -1
  649. package/dist/testing/TestSchema.d.ts +5 -1
  650. package/dist/testing/TestSchema.d.ts.map +1 -1
  651. package/dist/testing/TestSchema.js +7 -2
  652. package/dist/testing/TestSchema.js.map +1 -1
  653. package/dist/workers/SharedMemory.d.ts +115 -0
  654. package/dist/workers/SharedMemory.d.ts.map +1 -0
  655. package/dist/workers/SharedMemory.js +149 -0
  656. package/dist/workers/SharedMemory.js.map +1 -0
  657. package/dist/workers/Transferable.d.ts.map +1 -1
  658. package/dist/workers/Transferable.js +1 -4
  659. package/dist/workers/Transferable.js.map +1 -1
  660. package/dist/workers/index.d.ts +5 -0
  661. package/dist/workers/index.d.ts.map +1 -1
  662. package/dist/workers/index.js +5 -0
  663. package/dist/workers/index.js.map +1 -1
  664. package/dist/workflow/Activity.d.ts +18 -0
  665. package/dist/workflow/Activity.d.ts.map +1 -1
  666. package/dist/workflow/Activity.js +13 -4
  667. package/dist/workflow/Activity.js.map +1 -1
  668. package/dist/workflow/Workflow.d.ts +10 -9
  669. package/dist/workflow/Workflow.d.ts.map +1 -1
  670. package/dist/workflow/Workflow.js +33 -22
  671. package/dist/workflow/Workflow.js.map +1 -1
  672. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  673. package/dist/workflow/WorkflowEngine.js +28 -12
  674. package/dist/workflow/WorkflowEngine.js.map +1 -1
  675. package/dist/workflow/internal/retry.d.ts +2 -0
  676. package/dist/workflow/internal/retry.d.ts.map +1 -0
  677. package/dist/workflow/internal/retry.js +11 -0
  678. package/dist/workflow/internal/retry.js.map +1 -0
  679. package/dist/workflow/internal/scope.d.ts +2 -0
  680. package/dist/workflow/internal/scope.d.ts.map +1 -0
  681. package/dist/workflow/internal/scope.js +26 -0
  682. package/dist/workflow/internal/scope.js.map +1 -0
  683. package/package.json +8 -5
  684. package/src/Arbitrary.ts +60 -3
  685. package/src/BigInt.ts +247 -9
  686. package/src/Cache.ts +4 -2
  687. package/src/Cause.ts +3 -3
  688. package/src/Channel.ts +105 -8
  689. package/src/Chunk.ts +7 -3
  690. package/src/Clock.ts +5 -2
  691. package/src/Codegen.ts +746 -0
  692. package/src/Config.ts +35 -4
  693. package/src/ConfigProvider.ts +24 -7
  694. package/src/Effect.ts +1095 -157
  695. package/src/Equal.ts +85 -79
  696. package/src/Equivalence.ts +16 -13
  697. package/src/Fiber.ts +58 -8
  698. package/src/FiberHandle.ts +86 -12
  699. package/src/FiberMap.ts +83 -10
  700. package/src/FiberSet.ts +96 -8
  701. package/src/Formatter.ts +2 -0
  702. package/src/Hash.ts +30 -22
  703. package/src/LayerMap.ts +14 -4
  704. package/src/LayerRef.ts +8 -6
  705. package/src/Logger.ts +68 -25
  706. package/src/Match.ts +94 -50
  707. package/src/Metric.ts +1 -1
  708. package/src/Option.ts +9 -5
  709. package/src/Order.ts +10 -5
  710. package/src/Pool.ts +22 -17
  711. package/src/Predicate.ts +7 -3
  712. package/src/Queue.ts +84 -31
  713. package/src/Rational.ts +198 -0
  714. package/src/Request.ts +20 -0
  715. package/src/Result.ts +9 -6
  716. package/src/Schema.ts +145 -325
  717. package/src/SchemaAST.ts +15 -5
  718. package/src/SchemaGetter.ts +17 -10
  719. package/src/SchemaRepresentation.ts +19 -74
  720. package/src/SchemaTransformation.ts +12 -11
  721. package/src/Scope.ts +12 -6
  722. package/src/ScopedCache.ts +8 -5
  723. package/src/Semaphore.ts +18 -4
  724. package/src/Stream.ts +233 -53
  725. package/src/String.ts +84 -7
  726. package/src/Struct.ts +138 -5
  727. package/src/TextDiff.ts +186 -30
  728. package/src/Tracer.ts +10 -0
  729. package/src/TxPriorityQueue.ts +2 -2
  730. package/src/ai/LanguageModel.ts +2 -1
  731. package/src/ai/McpServer.ts +306 -26
  732. package/src/ai/Prompt.ts +20 -3
  733. package/src/ai/Skill.ts +236 -0
  734. package/src/ai/Tool.ts +3 -2
  735. package/src/ai/Toolkit.ts +3 -1
  736. package/src/ai/index.ts +6 -0
  737. package/src/chat/Chat.ts +164 -0
  738. package/src/chat/ChatAdapter.ts +444 -0
  739. package/src/chat/ChatError.ts +684 -0
  740. package/src/chat/ChatEvent.ts +221 -0
  741. package/src/chat/ChatHandler.ts +102 -0
  742. package/src/chat/ChatInteraction.ts +1979 -0
  743. package/src/chat/ChatMarkdown.ts +1406 -0
  744. package/src/chat/ChatMessage.ts +213 -0
  745. package/src/chat/ChatTest.ts +2606 -0
  746. package/src/chat/ChatThread.ts +132 -0
  747. package/src/chat/ChatUi.ts +320 -0
  748. package/src/chat/index.ts +72 -0
  749. package/src/chat/internal/retries.ts +7 -0
  750. package/src/cli/CliOutput.ts +4 -5
  751. package/src/cli/Command.ts +20 -2
  752. package/src/cli/Prompt.ts +15 -9
  753. package/src/cli/internal/config.ts +8 -8
  754. package/src/cluster/ClusterCron.ts +33 -10
  755. package/src/cluster/ClusterWorkflowEngine.ts +214 -119
  756. package/src/cluster/MessageStorage.ts +51 -2
  757. package/src/cluster/Sharding.ts +17 -3
  758. package/src/cluster/ShardingConfig.ts +3 -0
  759. package/src/cluster/SqlMessageStorage.ts +97 -54
  760. package/src/cluster/SqlRunnerStorage.ts +21 -8
  761. package/src/cluster/internal/entityActivation.ts +6 -0
  762. package/src/cluster/internal/entityManager.ts +27 -14
  763. package/src/cluster/internal/entityReaper.ts +1 -1
  764. package/src/crypto/Kdf.ts +2 -1
  765. package/src/crypto/Password.ts +258 -0
  766. package/src/crypto/index.ts +6 -0
  767. package/src/encoding/Base64.ts +84 -1
  768. package/src/encoding/Base64Url.ts +7 -1
  769. package/src/encoding/Csv.ts +47 -20
  770. package/src/encoding/Hex.ts +5 -0
  771. package/src/encoding/SchemaBinary.ts +13 -79
  772. package/src/encoding/Sse.ts +7 -5
  773. package/src/encoding/Xml.ts +485 -68
  774. package/src/eventlog/EventJournal.ts +3 -8
  775. package/src/eventlog/SqlEventLogServerEncrypted.ts +9 -9
  776. package/src/http/FetchHttpClient.ts +8 -5
  777. package/src/http/FindMyWay/internal/router.ts +181 -129
  778. package/src/http/FindMyWay.ts +106 -0
  779. package/src/http/Headers.ts +309 -3
  780. package/src/http/HttpClient.ts +21 -8
  781. package/src/http/HttpClientError.ts +42 -9
  782. package/src/http/HttpClientRequest.ts +51 -0
  783. package/src/http/HttpClientResponse.ts +156 -0
  784. package/src/http/HttpMiddleware.ts +23 -10
  785. package/src/http/HttpRouter.ts +84 -20
  786. package/src/http/HttpServerResponse.ts +159 -61
  787. package/src/http/Mime.ts +3 -2
  788. package/src/http/Multipart.ts +0 -5
  789. package/src/http/MultipartParser/internal/contentType.ts +1 -1
  790. package/src/http/internal/clientPath.ts +39 -0
  791. package/src/http/internal/compression.ts +2 -2
  792. package/src/{http-api → http}/internal/mediaType.ts +4 -0
  793. package/src/http/internal/redactedPath.ts +148 -0
  794. package/src/http/internal/requestState.ts +2 -0
  795. package/src/http/internal/tracing.ts +6 -3
  796. package/src/http-api/HttpApi.ts +50 -6
  797. package/src/http-api/HttpApiBuilder.ts +11 -3
  798. package/src/http-api/HttpApiClient.ts +40 -13
  799. package/src/http-api/HttpApiEndpoint.ts +1 -1
  800. package/src/http-api/HttpApiScalar.ts +9 -1
  801. package/src/http-api/HttpApiSchema.ts +1 -1
  802. package/src/http-api/OpenApi.ts +2 -0
  803. package/src/http-api/internal/httpApiScalar.ts +5 -1
  804. package/src/http-api/internal/redactedKeys.ts +40 -0
  805. package/src/index.ts +6 -0
  806. package/src/internal/arbitrary/model.ts +3 -9
  807. package/src/internal/arbitrary/regexp.ts +3 -1
  808. package/src/internal/arbitrary/runner.ts +28 -14
  809. package/src/internal/arbitrary/schema.ts +140 -35
  810. package/src/internal/base64.ts +57 -2
  811. package/src/internal/codegen.ts +53 -0
  812. package/src/internal/core.ts +3 -3
  813. package/src/internal/dateTime.ts +73 -37
  814. package/src/internal/effect.ts +56 -111
  815. package/src/internal/equal.ts +37 -17
  816. package/src/internal/hash.ts +5 -1
  817. package/src/internal/hashMap.ts +8 -7
  818. package/src/internal/matcher.ts +36 -114
  819. package/src/internal/record.ts +19 -4
  820. package/src/internal/result.ts +1 -1
  821. package/src/internal/schema/codeExpression.ts +179 -0
  822. package/src/internal/schema/codeImports.ts +142 -0
  823. package/src/internal/schema/codeTokens.ts +39 -0
  824. package/src/internal/schema/passthrough.ts +8 -0
  825. package/src/internal/schema/schemaCodegen.ts +544 -0
  826. package/src/internal/schema/schemaCodegenBuiltIns.ts +343 -0
  827. package/src/internal/schema/toEquivalence.ts +3 -5
  828. package/src/internal/schema/toJsonSchemaDocument.ts +13 -4
  829. package/src/internal/trie.ts +46 -60
  830. package/src/internal/utf8.ts +106 -0
  831. package/src/internal/version.ts +1 -1
  832. package/src/jose/JoseError.ts +34 -0
  833. package/src/jose/Jwks.ts +23 -4
  834. package/src/jose/internal/compact.ts +14 -5
  835. package/src/observability/Otlp.ts +29 -0
  836. package/src/observability/OtlpExporter.ts +209 -76
  837. package/src/observability/OtlpLogger.ts +29 -5
  838. package/src/observability/OtlpMetrics.ts +2 -0
  839. package/src/observability/OtlpTracer.ts +24 -3
  840. package/src/observability/internal/otlpProtobuf.ts +386 -457
  841. package/src/persistence/KeyValueStore.ts +17 -14
  842. package/src/persistence/PersistedQueue.ts +21 -4
  843. package/src/protobuf/ProtobufDescriptor.ts +503 -0
  844. package/src/protobuf/ProtobufDescriptorProto.ts +3611 -0
  845. package/src/protobuf/ProtobufMessage.ts +277 -0
  846. package/src/protobuf/ProtobufReader.ts +756 -0
  847. package/src/protobuf/ProtobufWriter.ts +530 -0
  848. package/src/protobuf/index.ts +36 -0
  849. package/src/protobuf/internal/binary.ts +1215 -0
  850. package/src/protobuf/internal/resolve.ts +533 -0
  851. package/src/protobuf/internal/wireType.ts +9 -0
  852. package/src/reactivity/AsyncResult.ts +6 -1
  853. package/src/reactivity/Atom.ts +67 -34
  854. package/src/reactivity/AtomHttpApi.ts +10 -1
  855. package/src/reactivity/AtomRegistry.ts +16 -0
  856. package/src/reactivity/AtomRpc.ts +11 -1
  857. package/src/rpc/Rpc.ts +31 -0
  858. package/src/rpc/RpcClient.ts +56 -22
  859. package/src/rpc/RpcGroup.ts +9 -1
  860. package/src/rpc/RpcMiddleware.ts +9 -0
  861. package/src/rpc/RpcSerialization.ts +26 -6
  862. package/src/rpc/RpcServer.ts +33 -20
  863. package/src/schema/SchemaCompiler/runtime.ts +2 -3
  864. package/src/schema/VariantSchema.ts +12 -4
  865. package/src/socket/Socket.ts +67 -20
  866. package/src/sql/Migrator.ts +10 -12
  867. package/src/sql/SqlClient.ts +14 -8
  868. package/src/sql/SqlModel.ts +4 -0
  869. package/src/testing/TestConsole.ts +119 -9
  870. package/src/testing/TestSchema.ts +8 -3
  871. package/src/workers/SharedMemory.ts +227 -0
  872. package/src/workers/Transferable.ts +1 -5
  873. package/src/workers/index.ts +6 -0
  874. package/src/workflow/Activity.ts +28 -4
  875. package/src/workflow/Workflow.ts +68 -44
  876. package/src/workflow/WorkflowEngine.ts +41 -16
  877. package/src/workflow/internal/retry.ts +12 -0
  878. package/src/workflow/internal/scope.ts +36 -0
  879. package/dist/http-api/internal/mediaType.d.ts.map +0 -1
  880. package/dist/internal/schema/toCodeDocument.d.ts +0 -2
  881. package/dist/internal/schema/toCodeDocument.d.ts.map +0 -1
  882. package/dist/internal/schema/toCodeDocument.js +0 -447
  883. package/dist/internal/schema/toCodeDocument.js.map +0 -1
  884. package/dist/observability/internal/protobuf.d.ts +0 -2
  885. package/dist/observability/internal/protobuf.d.ts.map +0 -1
  886. package/dist/observability/internal/protobuf.js +0 -169
  887. package/dist/observability/internal/protobuf.js.map +0 -1
  888. package/src/internal/schema/toCodeDocument.ts +0 -578
  889. package/src/observability/internal/protobuf.ts +0 -225
  890. /package/dist/{http-api → http}/internal/mediaType.d.ts +0 -0
@@ -0,0 +1,2606 @@
1
+ /**
2
+ * Testing tools for chat adapters and their consumers.
3
+ *
4
+ * `layer` builds a whole chat in memory: `Chat`, its registry and one fake
5
+ * adapter with configurable capabilities and fault injection. `conformance`
6
+ * is the suite of rules every adapter obeys, as plain Effects keyed by rule
7
+ * name. `checkMessage`, `checkEvent` and `checkInteraction` assert the
8
+ * invariants every message, event and interaction holds, for fixture tests
9
+ * and live runs.
10
+ *
11
+ * **Details**
12
+ *
13
+ * The fake adapter's mention syntax is `<@id>` for a user, `<@&id>` for a
14
+ * role, `<#id>` for a channel and `<!id>` for a broadcast.
15
+ *
16
+ * @stability unstable
17
+ * @since 4.1.5
18
+ */
19
+ import * as Bytes from "../Bytes.ts"
20
+ import * as Clock from "../Clock.ts"
21
+ import * as Context from "../Context.ts"
22
+ import * as DateTime from "../DateTime.ts"
23
+ import * as Duration from "../Duration.ts"
24
+ import * as Effect from "../Effect.ts"
25
+ import * as Exit from "../Exit.ts"
26
+ import * as Layer from "../Layer.ts"
27
+ import * as Option from "../Option.ts"
28
+ import * as Predicate from "../Predicate.ts"
29
+ import * as Schema from "../Schema.ts"
30
+ import * as Stream from "../Stream.ts"
31
+ import * as Str from "../String.ts"
32
+ import * as Chat from "./Chat.ts"
33
+ import type { ChatAdapter, Descriptor, File, NativeStream, Posted } from "./ChatAdapter.ts"
34
+ import { checkMessageLength, Registry, retrySafe } from "./ChatAdapter.ts"
35
+ import type { ChatErrorReason } from "./ChatError.ts"
36
+ import {
37
+ Capability,
38
+ ChatError,
39
+ fileRefused,
40
+ Forbidden,
41
+ interactionExpired,
42
+ InvalidRequest,
43
+ isChatError,
44
+ NotFound,
45
+ RateLimited,
46
+ TooLarge,
47
+ Transport,
48
+ Unsupported
49
+ } from "./ChatError.ts"
50
+ import type { ThreadKind } from "./ChatEvent.ts"
51
+ import * as ChatEvent from "./ChatEvent.ts"
52
+ import { ChatHandler } from "./ChatHandler.ts"
53
+ import type { NotAccepted } from "./ChatHandler.ts"
54
+ import * as ChatInteraction from "./ChatInteraction.ts"
55
+ import type { Attachment, Mention, ReplyTo } from "./ChatMessage.ts"
56
+ import * as ChatMessage from "./ChatMessage.ts"
57
+ import * as ChatThread from "./ChatThread.ts"
58
+ import type * as ChatUi from "./ChatUi.ts"
59
+
60
+ /**
61
+ * Reads a slice of `ChatMessage.text` as one of the platform's mention
62
+ * tokens.
63
+ *
64
+ * **Details**
65
+ *
66
+ * The core does not know any platform's syntax, so the caller supplies it. A
67
+ * slice that is not a mention token returns `None`.
68
+ *
69
+ * @stability unstable
70
+ * @category models
71
+ * @since 4.1.5
72
+ */
73
+ export type ParseMention = (slice: string) => Option.Option<{
74
+ readonly kind: Mention["kind"]
75
+ readonly id: string
76
+ }>
77
+
78
+ /**
79
+ * One call the fake adapter received, in order. Every attempt is a call, so a
80
+ * retried request shows up once per attempt.
81
+ *
82
+ * @stability unstable
83
+ * @category models
84
+ * @since 4.1.5
85
+ */
86
+ export interface Call {
87
+ readonly op: string
88
+ readonly thread: ChatThread.ChatThread
89
+ readonly messageId?: string | undefined
90
+ readonly markdown?: string | undefined
91
+ readonly files?: ReadonlyArray<File> | undefined
92
+ readonly outcome: "ok" | ChatErrorReason["_tag"]
93
+ }
94
+
95
+ /**
96
+ * Error for a click on an element the message does not carry, or on a
97
+ * message that is gone.
98
+ *
99
+ * @stability unstable
100
+ * @category errors
101
+ * @since 4.1.5
102
+ */
103
+ export class NoSuchElement extends Schema.TaggedError<NoSuchElement>("effect/chat/ChatTest/NoSuchElement")(
104
+ "NoSuchElement",
105
+ { messageId: Schema.String, id: Schema.String }
106
+ ) {}
107
+
108
+ /**
109
+ * Service that controls the fake adapter built by `layer`.
110
+ *
111
+ * **Details**
112
+ *
113
+ * - `makeThread` creates a fresh address: a channel by default, a direct
114
+ * conversation, or a thread under a user's message in a fresh channel.
115
+ * - `userPosts` puts another identity's message in a thread and returns its
116
+ * event without delivering it. `deliver` delivers an event the way an
117
+ * adapter does, by calling the `ChatHandler` service.
118
+ * - `messages` is what a thread shows now, oldest first, and `calls` is every
119
+ * call the adapter received.
120
+ * - `failNext` makes the next `times` calls of `op` fail with `reason`.
121
+ * `landed` makes the write happen anyway, which is what `uncertain` means.
122
+ * The native stream's ops are `nativeStream.start`, `nativeStream.append`
123
+ * and `nativeStream.stop`.
124
+ * - `refuseFiles` makes the next `times` posts with files fail `denied` with
125
+ * detail `file_refused`, storing nothing. Text-only posts do not consume it.
126
+ * - `clickStop` is a user clicking stop on a native stream. It closes
127
+ * nothing, as on Slack: the stream keeps taking text, and
128
+ * `NativeStream.stop` then reports `stopped: true`.
129
+ * - `closeStream` closes a native stream from outside, so the next append
130
+ * gives `closed`, or `stopped` after a click.
131
+ * - `click` builds the click on element `id` of a message from what the
132
+ * fake stored at `post` or `edit`, without delivering it. For a select,
133
+ * `option` is the encoded value of the option to choose, the first by
134
+ * default. It fails `NoSuchElement` when the message has no such element,
135
+ * or no such option, or is gone.
136
+ * - `command` builds a command typed at `thread`, without delivering it.
137
+ * `text` defaults to the empty string. The fake has no registration, so
138
+ * any id can be typed.
139
+ * - `submit` builds the submit of a modal. It takes the click or the command
140
+ * that opened it, because an `OpenModal` reply does not say where it was
141
+ * opened from and a `ModalSubmitted` has to. A command gives a submit
142
+ * with no `messageId`. `values` are by field id, still encoded, and an
143
+ * empty one is left out, as for an optional field left empty.
144
+ * - `interact` delivers an interaction the way an adapter does: through
145
+ * `ChatInteraction.handle` with the layer's `interactionDeadline`, then
146
+ * the fake's own checks on an `OpenModal` (the `modals` capability,
147
+ * `limits.modalMetadataLength` against the modal's id plus its encoded
148
+ * metadata, and `limits.modalFields`), calling `Handler.refused` when one
149
+ * fails. It succeeds with the handler's reply as it returned it, or
150
+ * `Late`. An `OpenModal` shows in `calls` as op `openModal`.
151
+ * - For a command, `interact` runs the checks of `post` on a `Respond`
152
+ * (the element capabilities, `limits.messageLength` and the element
153
+ * limits), and refuses a private `Respond` or `Defer` without
154
+ * `ephemeral`. A `Respond` shows in `calls` as op `respond`, and a
155
+ * `followUp` as op `followUp`, each with the command's thread and the
156
+ * Markdown. Neither is stored as a message.
157
+ * - The fake's `followUp` succeeds once for a `Defer` that `interact`
158
+ * returned, inside `limits.followUpAge` on `Clock`. Later, a second time,
159
+ * or for a deferral the fake never saw, it fails `NotFound` with detail
160
+ * `interaction_expired`. Failing the second call is stricter than either
161
+ * platform, to catch a handler that relies on more than one: Slack posts
162
+ * another message and Discord replaces the first.
163
+ *
164
+ * @stability unstable
165
+ * @category services
166
+ * @since 4.1.5
167
+ */
168
+ export class ChatTest extends Context.Service<ChatTest, {
169
+ readonly platform: string
170
+ readonly selfId: string
171
+ readonly makeThread: (kind?: ThreadKind) => Effect.Effect<ChatThread.ChatThread>
172
+ readonly userPosts: (thread: ChatThread.ChatThread, message: {
173
+ readonly text: string
174
+ readonly authorId?: string | undefined
175
+ readonly isBot?: boolean | undefined
176
+ readonly mentionsSelf?: boolean | undefined
177
+ readonly replyTo?: ReplyTo | undefined
178
+ readonly files?: ReadonlyArray<File> | undefined
179
+ }) => Effect.Effect<ChatEvent.ChatEvent>
180
+ readonly deliver: (event: ChatEvent.ChatEvent) => Effect.Effect<void, NotAccepted, ChatHandler>
181
+ readonly messages: (thread: ChatThread.ChatThread) => Effect.Effect<ReadonlyArray<ChatMessage.ChatMessage>>
182
+ readonly calls: Effect.Effect<ReadonlyArray<Call>>
183
+ readonly failNext: (op: string, reason: ChatErrorReason, options?: {
184
+ readonly times?: number | undefined
185
+ readonly landed?: boolean | undefined
186
+ }) => Effect.Effect<void>
187
+ readonly refuseFiles: (options?: { readonly times?: number | undefined }) => Effect.Effect<void>
188
+ readonly clickStop: (messageId: string) => Effect.Effect<void>
189
+ readonly closeStream: (messageId: string) => Effect.Effect<void>
190
+ readonly click: (messageId: string, id: string, options?: {
191
+ readonly userId?: string | undefined
192
+ readonly option?: string | undefined
193
+ }) => Effect.Effect<ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged, NoSuchElement>
194
+ readonly command: (thread: ChatThread.ChatThread, id: string, options?: {
195
+ readonly text?: string | undefined
196
+ readonly userId?: string | undefined
197
+ }) => Effect.Effect<ChatInteraction.CommandInvoked>
198
+ readonly submit: (
199
+ from: ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged | ChatInteraction.CommandInvoked,
200
+ opened: ChatInteraction.OpenModal,
201
+ values: Readonly<Record<string, string>>,
202
+ options?: { readonly userId?: string | undefined }
203
+ ) => Effect.Effect<ChatInteraction.ModalSubmitted>
204
+ readonly interact: {
205
+ (event: ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged): Effect.Effect<
206
+ ChatInteraction.ClickReply | ChatInteraction.Late,
207
+ never,
208
+ ChatInteraction.Handler
209
+ >
210
+ (event: ChatInteraction.ModalSubmitted): Effect.Effect<
211
+ ChatInteraction.SubmitReply | ChatInteraction.Late,
212
+ never,
213
+ ChatInteraction.Handler
214
+ >
215
+ (event: ChatInteraction.CommandInvoked): Effect.Effect<
216
+ ChatInteraction.CommandReply | ChatInteraction.Late,
217
+ never,
218
+ ChatInteraction.Handler
219
+ >
220
+ }
221
+ }>()("effect/chat/ChatTest") {}
222
+
223
+ // -----------------------------------------------------------------------------
224
+ // fake adapter
225
+ // -----------------------------------------------------------------------------
226
+
227
+ const allCapabilities: ReadonlyArray<Capability> = Capability.literals
228
+
229
+ /** Counts code points. */
230
+ const codePoints = (markdown: string): number => {
231
+ let count = 0
232
+ for (const _ of markdown) count++
233
+ return count
234
+ }
235
+
236
+ interface StoredStream {
237
+ readonly startedAt: number
238
+ open: boolean
239
+ clicked: boolean
240
+ }
241
+
242
+ /** An append holds back an unclosed `<` tail, as Slack does, up to this many characters. */
243
+ const heldBound = 100
244
+
245
+ interface StoredThread {
246
+ readonly thread: ChatThread.ChatThread
247
+ readonly kind: ThreadKind
248
+ readonly name?: string | undefined
249
+ readonly parent?: ChatThread.ChatThread | undefined
250
+ readonly openerId?: string | undefined
251
+ readonly createdAt: DateTime.Utc
252
+ }
253
+
254
+ interface StoredMessage {
255
+ readonly id: string
256
+ readonly thread: ChatThread.ChatThread
257
+ readonly authorId: string
258
+ readonly isBot: boolean
259
+ readonly isSelf: boolean
260
+ text: string
261
+ mentions: ReadonlyArray<Mention>
262
+ readonly replyTo?: ReplyTo | undefined
263
+ readonly attachments: ReadonlyArray<{ readonly attachment: Attachment; readonly content: Uint8Array }>
264
+ readonly timestamp: DateTime.Utc
265
+ actions: ReadonlyArray<ChatUi.Action>
266
+ }
267
+
268
+ interface Fault {
269
+ readonly reason: ChatErrorReason
270
+ remaining: number
271
+ readonly landed: boolean
272
+ }
273
+
274
+ const mentionPattern = /<(@&|@|#|!)([^<>\s]+)>/g
275
+
276
+ const mentionKinds: Record<string, Mention["kind"]> = {
277
+ "@": "user",
278
+ "@&": "role",
279
+ "#": "channel",
280
+ "!": "broadcast"
281
+ }
282
+
283
+ const parseMentions = (text: string, selfId: string): ReadonlyArray<Mention> =>
284
+ Array.from(text.matchAll(mentionPattern), (match) => {
285
+ const kind = mentionKinds[match[1]]
286
+ return {
287
+ kind,
288
+ id: match[2],
289
+ start: match.index,
290
+ end: match.index + match[0].length,
291
+ isSelf: kind === "user" && match[2] === selfId
292
+ }
293
+ })
294
+
295
+ const downloadChunkSize = 1024
296
+
297
+ const makeFake = (options: {
298
+ readonly platform: string
299
+ readonly selfId: string
300
+ readonly capabilities: ReadonlyArray<Capability>
301
+ readonly limits: Partial<Descriptor["limits"]>
302
+ readonly measure: Descriptor["measure"]
303
+ readonly interactionDeadline: Duration.Duration
304
+ }) => {
305
+ const { platform, selfId } = options
306
+ const capabilities = new Set(options.capabilities)
307
+ const messageLength = options.limits.messageLength ?? 4000
308
+ const hasActions = capabilities.has("buttons") || capabilities.has("selects")
309
+ const descriptor: Descriptor = {
310
+ platform,
311
+ capabilities,
312
+ measure: options.measure,
313
+ limits: {
314
+ messageLength,
315
+ filesPerMessage: 10,
316
+ uploadBytes: 10 * 1024 * 1024,
317
+ minWriteInterval: Duration.zero,
318
+ ...(capabilities.has("nativeStream") ? { streamLength: messageLength, streamAge: Duration.minutes(10) } : {}),
319
+ ...(hasActions ? { actionsPerMessage: 25, actionDataLength: 100 } : {}),
320
+ ...(capabilities.has("modals") ? { modalMetadataLength: 100, modalFields: 5 } : {}),
321
+ ...(capabilities.has("commands") ? { followUpAge: Duration.minutes(15) } : {}),
322
+ ...options.limits
323
+ }
324
+ }
325
+ const streams = new Map<string, StoredStream>()
326
+ const threads = new Map<string, StoredThread>()
327
+ const messages = new Map<string, StoredMessage>()
328
+ const order: Array<string> = []
329
+ const threadUnder = new Map<string, ChatThread.ChatThread>()
330
+ const users = new Map<string, { readonly isBot: boolean }>([[selfId, { isBot: true }]])
331
+ const calls: Array<Call> = []
332
+ /** Deferrals `interact` returned, by the command's raw id, with when they were made. */
333
+ const deferrals = new Map<string, { readonly at: number; used: boolean }>()
334
+ let refusedFiles = 0
335
+ const faults = new Map<string, Array<Fault>>()
336
+ let counter = 0
337
+ const nextId = (prefix: string) => prefix + String(++counter)
338
+
339
+ const chatError = (op: string, reason: ChatErrorReason) => new ChatError({ platform, op, reason })
340
+ const fail = (op: string, reason: ChatErrorReason) => Effect.fail(chatError(op, reason))
341
+
342
+ const toMessage = (message: StoredMessage): ChatMessage.ChatMessage => ({
343
+ id: message.id,
344
+ thread: message.thread,
345
+ author: {
346
+ id: message.authorId,
347
+ name: message.isSelf ? "test-bot" : message.authorId,
348
+ isBot: message.isBot,
349
+ isSelf: message.isSelf
350
+ },
351
+ text: message.text,
352
+ mentions: message.mentions,
353
+ ...(message.replyTo === undefined ? {} : {
354
+ replyTo: message.replyTo.authorId === undefined
355
+ ? message.replyTo
356
+ : { ...message.replyTo, isSelf: message.replyTo.authorId === selfId }
357
+ }),
358
+ attachments: message.attachments.map((stored) => stored.attachment),
359
+ timestamp: message.timestamp,
360
+ raw: {
361
+ type: "message",
362
+ id: message.id,
363
+ channel: message.thread.id,
364
+ user: message.authorId,
365
+ text: message.text
366
+ }
367
+ })
368
+
369
+ const findThread = (op: string, thread: ChatThread.ChatThread) =>
370
+ Effect.suspend(() => {
371
+ const stored = threads.get(thread.id)
372
+ return stored === undefined ? fail(op, new NotFound({ detail: "thread_not_found" })) : Effect.succeed(stored)
373
+ })
374
+
375
+ const listMessages = (stored: StoredThread): Array<StoredMessage> => {
376
+ const list: Array<StoredMessage> = []
377
+ if (stored.openerId !== undefined) {
378
+ const opener = messages.get(stored.openerId)
379
+ if (opener !== undefined) list.push(opener)
380
+ }
381
+ for (const id of order) {
382
+ const message = messages.get(id)
383
+ if (message !== undefined && ChatThread.equals(message.thread, stored.thread)) list.push(message)
384
+ }
385
+ return list
386
+ }
387
+
388
+ const findMessage = (op: string, thread: ChatThread.ChatThread, messageId: string) =>
389
+ Effect.flatMap(findThread(op, thread), (stored) => {
390
+ const message = listMessages(stored).find((message) => message.id === messageId)
391
+ return message === undefined
392
+ ? fail(op, new NotFound({ detail: "message_not_found" }))
393
+ : Effect.succeed(message)
394
+ })
395
+
396
+ const store = (message: Omit<StoredMessage, "id" | "timestamp">) =>
397
+ Effect.map(DateTime.now, (timestamp) => {
398
+ const stored: StoredMessage = { ...message, id: nextId("m"), timestamp }
399
+ messages.set(stored.id, stored)
400
+ order.push(stored.id)
401
+ return stored
402
+ })
403
+
404
+ const storeFiles = (files: ReadonlyArray<File> | undefined) =>
405
+ (files ?? []).map((file) => ({
406
+ attachment: {
407
+ id: nextId("f"),
408
+ name: file.name,
409
+ contentType: file.contentType,
410
+ size: file.content.length
411
+ },
412
+ content: file.content
413
+ }))
414
+
415
+ /** Stores a message from the bot. The author `replyTo` names is read from the stored target. */
416
+ const postOwn = Effect.fnUntraced(function*(op: string, thread: ChatThread.ChatThread, message: {
417
+ readonly text: string
418
+ readonly replyTo: ReplyTo | undefined
419
+ readonly attachments: StoredMessage["attachments"]
420
+ readonly actions: ReadonlyArray<ChatUi.Action>
421
+ }) {
422
+ const target = message.replyTo === undefined
423
+ ? undefined
424
+ : yield* findMessage(op, thread, message.replyTo.messageId)
425
+ const stored = yield* store({
426
+ ...message,
427
+ thread,
428
+ authorId: selfId,
429
+ isBot: true,
430
+ isSelf: true,
431
+ mentions: [],
432
+ replyTo: target === undefined ? undefined : { messageId: target.id, authorId: target.authorId }
433
+ })
434
+ return { id: stored.id, thread, timestamp: stored.timestamp } satisfies Posted
435
+ })
436
+
437
+ const createThread = (
438
+ op: string,
439
+ thread: ChatThread.ChatThread,
440
+ messageId: string,
441
+ name: string | undefined
442
+ ) =>
443
+ Effect.flatMap(findMessage(op, thread, messageId), (message) => {
444
+ const existing = threadUnder.get(message.id)
445
+ if (existing !== undefined) return Effect.succeed(existing)
446
+ const parent = threads.get(message.thread.id)!
447
+ if (parent.kind === "thread" || !ChatThread.equals(message.thread, thread)) {
448
+ return fail(op, new InvalidRequest({ detail: "cannot_thread_reply" }))
449
+ }
450
+ return Effect.map(DateTime.now, (createdAt) => {
451
+ const created = ChatThread.make(platform, thread.id + "/" + message.id)
452
+ threads.set(created.id, {
453
+ thread: created,
454
+ kind: "thread",
455
+ name,
456
+ parent: thread,
457
+ openerId: message.id,
458
+ createdAt
459
+ })
460
+ threadUnder.set(message.id, created)
461
+ return created
462
+ })
463
+ })
464
+
465
+ /** The capabilities a message's elements need. */
466
+ const actionNeeds = (actions: ReadonlyArray<ChatUi.Action> | undefined): Array<Capability> => {
467
+ const needs: Array<Capability> = []
468
+ if (actions?.some((action) => action._tag !== "Select")) needs.push("buttons")
469
+ if (actions?.some((action) => action._tag === "Select")) needs.push("selects")
470
+ return needs
471
+ }
472
+
473
+ /** The element limits, counted in code points, as both adapters count them. */
474
+ const checkActions = (op: string, actions: ReadonlyArray<ChatUi.Action>) =>
475
+ Effect.suspend(() => {
476
+ const { actionDataLength, actionsPerMessage } = descriptor.limits
477
+ if (actionsPerMessage !== undefined && actions.length > actionsPerMessage) {
478
+ return fail(op, new TooLarge({ detail: "too_many_actions" }))
479
+ }
480
+ const data = actions.flatMap((action) =>
481
+ action._tag === "Button"
482
+ ? [codePoints(action.id) + codePoints(action.value ?? "")]
483
+ : action._tag === "Select"
484
+ ? action.options.map((option) => codePoints(action.id) + codePoints(option.value))
485
+ : []
486
+ )
487
+ if (actionDataLength !== undefined && data.some((length) => length > actionDataLength)) {
488
+ return fail(op, new TooLarge({ detail: "action_data_too_long" }))
489
+ }
490
+ return Effect.void
491
+ })
492
+
493
+ /** Why a modal would not open, if it would not. */
494
+ const modalRefusal = (modal: ChatUi.Modal): ChatError | undefined => {
495
+ const { modalFields, modalMetadataLength } = descriptor.limits
496
+ if (!capabilities.has("modals")) return chatError("openModal", new Unsupported({ capability: "modals" }))
497
+ if (
498
+ modalMetadataLength !== undefined &&
499
+ codePoints(modal.id) + codePoints(modal.metadata ?? "") > modalMetadataLength
500
+ ) {
501
+ return chatError("openModal", new TooLarge({ detail: "modal_metadata_too_long" }))
502
+ }
503
+ if (modalFields !== undefined && modal.elements.length > modalFields) {
504
+ return chatError("openModal", new TooLarge({ detail: "too_many_fields" }))
505
+ }
506
+ return undefined
507
+ }
508
+
509
+ /** The capabilities a command's answer needs. */
510
+ const answerNeeds = (
511
+ visibility: ChatInteraction.Visibility,
512
+ actions?: ReadonlyArray<ChatUi.Action> | undefined
513
+ ): Array<Capability> => [...(visibility === "ephemeral" ? ["ephemeral" as const] : []), ...actionNeeds(actions)]
514
+
515
+ /** The id the fake gave a command it built, which keys its deferral. */
516
+ const commandKey = ({ raw }: ChatInteraction.CommandInvoked): string | undefined =>
517
+ Predicate.hasProperty(raw, "id") && typeof raw.id === "string" ? raw.id : undefined
518
+
519
+ const takeFault = (op: string): Fault | undefined => {
520
+ const queue = faults.get(op)
521
+ const fault = queue?.[0]
522
+ if (fault === undefined) return undefined
523
+ fault.remaining--
524
+ if (fault.remaining <= 0) queue!.shift()
525
+ return fault
526
+ }
527
+
528
+ const attempt = <A>(
529
+ call: Omit<Call, "outcome">,
530
+ needs: ReadonlyArray<Capability>,
531
+ body: Effect.Effect<A, ChatError>,
532
+ retries: boolean = true
533
+ ): Effect.Effect<A, ChatError> =>
534
+ (retries ? retrySafe : <X>(effect: X) => effect)(Effect.suspend(() => {
535
+ const record = (outcome: Call["outcome"]) => calls.push({ ...call, outcome })
536
+ const missing = needs.find((capability) => !descriptor.capabilities.has(capability))
537
+ if (missing !== undefined) {
538
+ record("Unsupported")
539
+ return fail(call.op, new Unsupported({ capability: missing }))
540
+ }
541
+ if (call.op === "post" && (call.files?.length ?? 0) > 0 && refusedFiles > 0) {
542
+ refusedFiles--
543
+ record("Forbidden")
544
+ return fail(call.op, new Forbidden({ detail: fileRefused }))
545
+ }
546
+ const fault = takeFault(call.op)
547
+ if (fault !== undefined) {
548
+ record(fault.reason._tag)
549
+ const failure = fail(call.op, fault.reason)
550
+ return fault.landed ? Effect.flatMap(Effect.exit(body), () => failure) : failure
551
+ }
552
+ return body.pipe(
553
+ Effect.tap(() => Effect.sync(() => record("ok"))),
554
+ Effect.tapError((error) => Effect.sync(() => record(error.reason._tag)))
555
+ )
556
+ }))
557
+
558
+ /** Whether a native stream is open on the message, closing it once it is past `limits.streamAge`. */
559
+ const isOpen = (messageId: string) =>
560
+ Effect.map(Clock.currentTimeMillis, (now) => {
561
+ const stream = streams.get(messageId)
562
+ if (stream === undefined || !stream.open) return false
563
+ const age = descriptor.limits.streamAge
564
+ if (age !== undefined && now - stream.startedAt >= Duration.toMillis(age)) stream.open = false
565
+ return stream.open
566
+ })
567
+
568
+ const streamLength = () => descriptor.limits.streamLength ?? descriptor.limits.messageLength
569
+
570
+ const nativeStream: NativeStream = {
571
+ start: (thread, content) =>
572
+ attempt(
573
+ { op: "nativeStream.start", thread, markdown: content.markdown },
574
+ content.replyTo === undefined ? ["nativeStream"] : ["nativeStream", "replyTo"],
575
+ Effect.gen(function*() {
576
+ yield* findThread("nativeStream.start", thread)
577
+ yield* checkMessageLength(descriptor, "nativeStream.start", content.markdown)
578
+ if (descriptor.measure(content.markdown) > streamLength()) {
579
+ return yield* fail("nativeStream.start", new TooLarge({ subject: "text", detail: "msg_too_long" }))
580
+ }
581
+ const posted = yield* postOwn("nativeStream.start", thread, {
582
+ text: Str.toWellFormed(content.markdown),
583
+ replyTo: content.replyTo,
584
+ attachments: [],
585
+ actions: []
586
+ })
587
+ streams.set(posted.id, { startedAt: yield* Clock.currentTimeMillis, open: true, clicked: false })
588
+ return posted
589
+ })
590
+ ),
591
+ append: (thread, messageId, markdown, appendOptions) =>
592
+ attempt(
593
+ { op: "nativeStream.append", thread, messageId, markdown },
594
+ ["nativeStream"],
595
+ Effect.gen(function*() {
596
+ const message = yield* findMessage("nativeStream.append", thread, messageId)
597
+ const stream = streams.get(message.id)
598
+ if (stream === undefined || !(yield* isOpen(message.id))) {
599
+ return { state: stream?.clicked === true ? "stopped" as const : "closed" as const, held: 0 }
600
+ }
601
+ let held = 0
602
+ const flush = appendOptions?.flush === true
603
+ const open = markdown.lastIndexOf("<")
604
+ if (!flush && open !== -1 && !markdown.includes(">", open)) {
605
+ held = markdown.length - open
606
+ if (held > heldBound) held = 0
607
+ }
608
+ // A trailing high surrogate waits for its other half.
609
+ if (!flush && held === 0 && /[\ud800-\udbff]$/.test(markdown)) held = 1
610
+ const sent = Str.toWellFormed(markdown.slice(0, markdown.length - held))
611
+ if (descriptor.measure(message.text + sent) > streamLength()) {
612
+ return yield* fail("nativeStream.append", new TooLarge({ subject: "text", detail: "msg_too_long" }))
613
+ }
614
+ message.text += sent
615
+ return { state: "open" as const, held }
616
+ }),
617
+ false
618
+ ),
619
+ stop: (thread, messageId) =>
620
+ attempt(
621
+ { op: "nativeStream.stop", thread, messageId },
622
+ ["nativeStream"],
623
+ Effect.gen(function*() {
624
+ const message = yield* findMessage("nativeStream.stop", thread, messageId)
625
+ const stream = streams.get(message.id)
626
+ if (stream === undefined || !(yield* isOpen(message.id))) return { stopped: false }
627
+ stream.open = false
628
+ return { stopped: stream.clicked }
629
+ })
630
+ )
631
+ }
632
+
633
+ const streamFor = (op: string, messageId: string) =>
634
+ Effect.suspend(() => {
635
+ const stream = streams.get(messageId)
636
+ return stream === undefined
637
+ ? Effect.die(new Error("ChatTest." + op + ": no native stream " + messageId))
638
+ : Effect.succeed(stream)
639
+ })
640
+
641
+ const adapter: ChatAdapter = {
642
+ descriptor,
643
+ ...(capabilities.has("nativeStream") ? { nativeStream } : {}),
644
+ post: (thread, content) => {
645
+ const files = content.files ?? []
646
+ const needs: Array<Capability> = []
647
+ if (files.length > 0) needs.push("files")
648
+ if (content.replyTo !== undefined) needs.push("replyTo")
649
+ needs.push(...actionNeeds(content.actions))
650
+ return attempt(
651
+ { op: "post", thread, markdown: content.markdown, files: content.files },
652
+ needs,
653
+ Effect.gen(function*() {
654
+ yield* findThread("post", thread)
655
+ yield* checkMessageLength(descriptor, "post", content.markdown, content.actions)
656
+ yield* checkActions("post", content.actions ?? [])
657
+ if (
658
+ files.length > descriptor.limits.filesPerMessage ||
659
+ files.some((file) => file.content.length > descriptor.limits.uploadBytes)
660
+ ) {
661
+ return yield* fail("post", new TooLarge({ subject: "files", detail: fileRefused }))
662
+ }
663
+ return yield* postOwn("post", thread, {
664
+ text: content.markdown,
665
+ replyTo: content.replyTo,
666
+ attachments: storeFiles(files),
667
+ actions: content.actions ?? []
668
+ })
669
+ })
670
+ )
671
+ },
672
+ edit: (thread, messageId, content) =>
673
+ attempt(
674
+ { op: "edit", thread, messageId, markdown: content.markdown },
675
+ ["edit", ...actionNeeds(content.actions)],
676
+ Effect.gen(function*() {
677
+ const message = yield* findMessage("edit", thread, messageId)
678
+ if (!message.isSelf) return yield* fail("edit", new Forbidden({ detail: "cant_update_message" }))
679
+ if (yield* isOpen(message.id)) {
680
+ return yield* fail("edit", new InvalidRequest({ detail: "streaming_state_conflict" }))
681
+ }
682
+ yield* checkMessageLength(descriptor, "edit", content.markdown, content.actions)
683
+ yield* checkActions("edit", content.actions ?? [])
684
+ message.text = content.markdown
685
+ message.mentions = []
686
+ message.actions = content.actions ?? []
687
+ })
688
+ ),
689
+ delete: (thread, messageId) =>
690
+ attempt(
691
+ { op: "delete", thread, messageId },
692
+ ["delete"],
693
+ Effect.gen(function*() {
694
+ const message = yield* findMessage("delete", thread, messageId)
695
+ if (!message.isSelf) return yield* fail("delete", new Forbidden({ detail: "cant_delete_message" }))
696
+ if (yield* isOpen(message.id)) {
697
+ return yield* fail("delete", new InvalidRequest({ detail: "cant_delete_message" }))
698
+ }
699
+ messages.delete(message.id)
700
+ })
701
+ ),
702
+ fetchMessage: (thread, messageId) =>
703
+ attempt(
704
+ { op: "fetchMessage", thread, messageId },
705
+ ["fetchMessage"],
706
+ Effect.map(findMessage("fetchMessage", thread, messageId), toMessage)
707
+ ),
708
+ history: (thread, options) =>
709
+ Stream.unwrap(attempt(
710
+ { op: "history", thread, messageId: options.from },
711
+ ["history"],
712
+ Effect.gen(function*() {
713
+ const stored = yield* findThread("history", thread)
714
+ const list = listMessages(stored).map(toMessage)
715
+ if (options.direction === "backward") list.reverse()
716
+ if (options.from === undefined) return Stream.fromIterable(list)
717
+ const index = list.findIndex((message) => message.id === options.from)
718
+ if (index === -1) return yield* fail("history", new NotFound({ detail: "message_not_found" }))
719
+ return Stream.fromIterable(list.slice(index + 1))
720
+ })
721
+ )),
722
+ download: (thread, attachment, options) =>
723
+ Stream.unwrap(attempt(
724
+ { op: "download", thread },
725
+ ["download"],
726
+ Effect.suspend(() => {
727
+ let content: Uint8Array | undefined
728
+ for (const message of messages.values()) {
729
+ const found = message.attachments.find((stored) => stored.attachment.id === attachment.id)
730
+ if (found !== undefined) content = found.content
731
+ }
732
+ if (content === undefined) return fail("download", new NotFound({ detail: "file_not_found" }))
733
+ const chunks: Array<Uint8Array> = []
734
+ for (let offset = 0; offset < content.length && offset < options.maxBytes; offset += downloadChunkSize) {
735
+ const end = Math.min(offset + downloadChunkSize, content.length)
736
+ if (end > options.maxBytes) break
737
+ chunks.push(content.slice(offset, end))
738
+ }
739
+ const tooLarge = content.length > options.maxBytes
740
+ ? Stream.fail(chatError("download", new TooLarge({ detail: "max_bytes" })))
741
+ : Stream.empty
742
+ return Effect.succeed(Stream.concat(Stream.fromIterable(chunks), tooLarge))
743
+ })
744
+ )),
745
+ startThread: (thread, messageId, startOptions) =>
746
+ attempt(
747
+ { op: "startThread", thread, messageId },
748
+ ["startThread"],
749
+ createThread("startThread", thread, messageId, startOptions?.name)
750
+ ),
751
+ getThread: (thread) =>
752
+ attempt(
753
+ { op: "getThread", thread },
754
+ ["getThread"],
755
+ Effect.map(findThread("getThread", thread), (stored) => ({
756
+ thread: stored.thread,
757
+ kind: stored.kind,
758
+ name: stored.name,
759
+ parent: stored.parent,
760
+ createdAt: stored.createdAt,
761
+ raw: { id: stored.thread.id, kind: stored.kind }
762
+ }))
763
+ ),
764
+ opener: (thread) =>
765
+ attempt(
766
+ { op: "opener", thread },
767
+ ["opener"],
768
+ Effect.map(findThread("opener", thread), (stored) => {
769
+ const opener = stored.openerId === undefined ? undefined : messages.get(stored.openerId)
770
+ return opener === undefined ? Option.none() : Option.some(toMessage(opener))
771
+ })
772
+ ),
773
+ getUser: (id, userOptions) =>
774
+ attempt(
775
+ { op: "getUser", thread: userOptions?.in ?? ChatThread.make(platform, "") },
776
+ ["getUser"],
777
+ Effect.suspend(() => {
778
+ const user = users.get(id)
779
+ return user === undefined
780
+ ? fail("getUser", new NotFound({ detail: "user_not_found" }))
781
+ : Effect.succeed({
782
+ id,
783
+ name: id === selfId ? "test-bot" : id,
784
+ isBot: user.isBot,
785
+ isSelf: id === selfId,
786
+ raw: { id }
787
+ })
788
+ })
789
+ ),
790
+ followUp: (deferred, content) =>
791
+ attempt(
792
+ { op: "followUp", thread: deferred.command.thread, markdown: content.markdown },
793
+ ["commands", ...answerNeeds(deferred.visibility, content.actions)],
794
+ Effect.gen(function*() {
795
+ const key = commandKey(deferred.command)
796
+ const stored = key === undefined ? undefined : deferrals.get(key)
797
+ const age = descriptor.limits.followUpAge
798
+ const now = yield* Clock.currentTimeMillis
799
+ if (
800
+ stored === undefined || stored.used ||
801
+ (age !== undefined && now - stored.at >= Duration.toMillis(age))
802
+ ) {
803
+ return yield* fail("followUp", new NotFound({ detail: interactionExpired }))
804
+ }
805
+ yield* checkMessageLength(descriptor, "followUp", content.markdown, content.actions)
806
+ yield* checkActions("followUp", content.actions ?? [])
807
+ stored.used = true
808
+ }),
809
+ false
810
+ )
811
+ }
812
+
813
+ const addThread = (kind: "channel" | "direct") =>
814
+ Effect.map(DateTime.now, (createdAt) => {
815
+ const thread = ChatThread.make(platform, nextId(kind === "channel" ? "c" : "d"))
816
+ threads.set(thread.id, { thread, kind, createdAt })
817
+ return thread
818
+ })
819
+
820
+ const userPosts: ChatTest["Service"]["userPosts"] = Effect.fnUntraced(function*(thread, message) {
821
+ const stored = threads.get(thread.id)
822
+ if (stored === undefined) return yield* Effect.die(new Error("ChatTest.userPosts: unknown thread"))
823
+ const authorId = message.authorId ?? "user"
824
+ const isBot = message.isBot ?? false
825
+ users.set(authorId, { isBot })
826
+ const text = message.mentionsSelf === true ? "<@" + selfId + "> " + message.text : message.text
827
+ const replyTarget = message.replyTo === undefined ? undefined : messages.get(message.replyTo.messageId)
828
+ const created = yield* store({
829
+ thread,
830
+ authorId,
831
+ isBot,
832
+ isSelf: false,
833
+ text,
834
+ mentions: parseMentions(text, selfId),
835
+ // The author is read from the stored message, as a platform does, not from the caller.
836
+ replyTo: message.replyTo === undefined ? undefined : {
837
+ messageId: message.replyTo.messageId,
838
+ ...(replyTarget === undefined ? {} : { authorId: replyTarget.authorId })
839
+ },
840
+ attachments: storeFiles(message.files),
841
+ actions: []
842
+ })
843
+ return ChatEvent.MessageCreated.make({
844
+ thread,
845
+ kind: stored.kind,
846
+ message: toMessage(created),
847
+ raw: { type: "event_callback", event_id: nextId("e") }
848
+ })
849
+ })
850
+
851
+ const service = ChatTest.of({
852
+ platform,
853
+ selfId,
854
+ makeThread: (kind = "channel") => {
855
+ if (kind !== "thread") return addThread(kind)
856
+ return Effect.gen(function*() {
857
+ const channel = yield* addThread("channel")
858
+ const event = yield* userPosts(channel, { text: "thread opener" })
859
+ const message = (event as ChatEvent.MessageCreated).message
860
+ return yield* Effect.orDie(createThread("makeThread", channel, message.id, undefined))
861
+ })
862
+ },
863
+ userPosts,
864
+ deliver: (event) => Effect.flatMap(ChatHandler, (handler) => handler.handle(event)),
865
+ messages: (thread) =>
866
+ Effect.sync(() => {
867
+ const stored = threads.get(thread.id)
868
+ return stored === undefined ? [] : listMessages(stored).map(toMessage)
869
+ }),
870
+ calls: Effect.sync(() => calls.slice()),
871
+ refuseFiles: (options) =>
872
+ Effect.sync(() => {
873
+ refusedFiles += options?.times ?? 1
874
+ }),
875
+ failNext: (op, reason, failOptions) =>
876
+ Effect.sync(() => {
877
+ if (failOptions?.times === 0) return
878
+ const queue = faults.get(op) ?? []
879
+ queue.push({ reason, remaining: failOptions?.times ?? 1, landed: failOptions?.landed ?? false })
880
+ faults.set(op, queue)
881
+ }),
882
+ clickStop: (messageId) => Effect.map(streamFor("clickStop", messageId), (stream) => void (stream.clicked = true)),
883
+ closeStream: (messageId) => Effect.map(streamFor("closeStream", messageId), (stream) => void (stream.open = false)),
884
+ click: (messageId, id, clickOptions) =>
885
+ Effect.suspend((): Effect.Effect<
886
+ ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged,
887
+ NoSuchElement
888
+ > => {
889
+ const message = messages.get(messageId)
890
+ const element = message?.actions.find((action) => action._tag !== "LinkButton" && action.id === id)
891
+ if (message === undefined || element === undefined || element._tag === "LinkButton") {
892
+ return Effect.fail(new NoSuchElement({ messageId, id }))
893
+ }
894
+ const origin = {
895
+ id,
896
+ thread: message.thread,
897
+ messageId,
898
+ userId: clickOptions?.userId ?? "user",
899
+ raw: { type: "interaction", id: nextId("i"), message: messageId, element: id }
900
+ }
901
+ if (element._tag === "Button") {
902
+ return Effect.succeed(ChatInteraction.ButtonClicked.make({
903
+ ...origin,
904
+ ...(element.value === undefined ? {} : { value: element.value })
905
+ }))
906
+ }
907
+ const option = clickOptions?.option === undefined
908
+ ? element.options[0]
909
+ : element.options.find((option) => option.value === clickOptions.option)
910
+ return option === undefined
911
+ ? Effect.fail(new NoSuchElement({ messageId, id }))
912
+ : Effect.succeed(ChatInteraction.SelectChanged.make({ ...origin, value: option.value }))
913
+ }),
914
+ command: (thread, id, commandOptions) =>
915
+ Effect.sync(() => {
916
+ const text = commandOptions?.text ?? ""
917
+ return ChatInteraction.CommandInvoked.make({
918
+ id,
919
+ text,
920
+ thread,
921
+ userId: commandOptions?.userId ?? "user",
922
+ raw: { type: "command", id: nextId("i"), command: id, text }
923
+ })
924
+ }),
925
+ submit: (from, opened, values, submitOptions) =>
926
+ Effect.sync(() =>
927
+ ChatInteraction.ModalSubmitted.make({
928
+ id: opened.modal.id,
929
+ ...(opened.modal.metadata === undefined ? {} : { metadata: opened.modal.metadata }),
930
+ values: Object.fromEntries(Object.entries(values).filter(([, value]) => value !== "")),
931
+ thread: from.thread,
932
+ ...(from._tag === "CommandInvoked" ? {} : { messageId: from.messageId }),
933
+ userId: submitOptions?.userId ?? from.userId,
934
+ raw: { type: "submission", id: nextId("i"), modal: opened.modal.id }
935
+ })
936
+ ),
937
+ interact: ((event: ChatInteraction.Interaction) =>
938
+ Effect.gen(function*() {
939
+ const reply = yield* ChatInteraction.handle(event, options.interactionDeadline)
940
+ if (event._tag === "ModalSubmitted") return reply
941
+ let refusal: ChatError | undefined
942
+ switch (reply._tag) {
943
+ case "OpenModal": {
944
+ refusal = modalRefusal(reply.modal)
945
+ calls.push({
946
+ op: "openModal",
947
+ thread: event.thread,
948
+ ...(event._tag === "CommandInvoked" ? {} : { messageId: event.messageId }),
949
+ outcome: refusal === undefined ? "ok" : refusal.reason._tag
950
+ })
951
+ break
952
+ }
953
+ case "Respond": {
954
+ const exit = yield* Effect.exit(attempt(
955
+ { op: "respond", thread: event.thread, markdown: reply.markdown },
956
+ answerNeeds(reply.visibility, reply.actions),
957
+ Effect.andThen(
958
+ checkMessageLength(descriptor, "respond", reply.markdown, reply.actions),
959
+ checkActions("respond", reply.actions ?? [])
960
+ ),
961
+ false
962
+ ))
963
+ refusal = Option.getOrUndefined(Exit.findErrorOption(exit))
964
+ break
965
+ }
966
+ case "Defer": {
967
+ const missing = answerNeeds(reply.visibility).find((capability) => !capabilities.has(capability))
968
+ if (missing !== undefined) {
969
+ refusal = chatError("defer", new Unsupported({ capability: missing }))
970
+ break
971
+ }
972
+ const key = event._tag === "CommandInvoked" ? commandKey(event) : undefined
973
+ if (key !== undefined) deferrals.set(key, { at: yield* Clock.currentTimeMillis, used: false })
974
+ break
975
+ }
976
+ }
977
+ if (refusal !== undefined) {
978
+ const handler = yield* ChatInteraction.Handler
979
+ yield* handler.refused(event, refusal)
980
+ }
981
+ return reply
982
+ })) as ChatTest["Service"]["interact"]
983
+ })
984
+
985
+ return { adapter, service }
986
+ }
987
+
988
+ /**
989
+ * Creates a whole chat in memory: `Chat`, its registry and one fake adapter.
990
+ *
991
+ * **When to use**
992
+ *
993
+ * Use to test code that posts and reads through `Chat`, and to run the
994
+ * conformance suite against the fake adapter.
995
+ *
996
+ * **Details**
997
+ *
998
+ * - The platform defaults to `test` and the bot's user id to `bot`.
999
+ * - Every capability is on by default.
1000
+ * - `measure` defaults to a count of code points, and the fake checks every
1001
+ * length with it.
1002
+ * - The default limits are 4000 per message, 10 files of up to 10 MiB, and no
1003
+ * write interval. With `nativeStream` on, a stream takes up to
1004
+ * `messageLength` and lasts 10 minutes.
1005
+ * - The native stream behaves the way Slack's was found to. An append past
1006
+ * `limits.streamLength` fails with `TooLarge` and adds nothing. A stream
1007
+ * past `limits.streamAge`, on `Clock`, is closed. An append without
1008
+ * `flush` holds back an unclosed `<` tail of up to 100 characters, or a
1009
+ * trailing high surrogate. Any other lone surrogate is stored as U+FFFD.
1010
+ * An open stream refuses `edit` and `delete`.
1011
+ * - With `buttons` or `selects` on, a message takes 25 elements, and an
1012
+ * element's id plus encoded value 100 code points. With `modals` on, a
1013
+ * modal's id plus encoded metadata takes 100 code points, and a modal 5
1014
+ * fields. Each limit is there only with its capability.
1015
+ * - `interact` gives a handler 3 seconds by default, on `Clock`.
1016
+ * - With `commands` on, `limits.followUpAge` is 15 minutes.
1017
+ * - Two layers merged with different platforms share one `Chat`, so routing
1018
+ * can be tested. The `ChatTest` service in context is the last one merged.
1019
+ *
1020
+ * @stability unstable
1021
+ * @category layers
1022
+ * @since 4.1.5
1023
+ */
1024
+ export const layer = (options?: {
1025
+ readonly platform?: string | undefined
1026
+ readonly selfId?: string | undefined
1027
+ readonly capabilities?: ReadonlyArray<Capability> | undefined
1028
+ readonly limits?: Partial<Descriptor["limits"]> | undefined
1029
+ readonly measure?: Descriptor["measure"] | undefined
1030
+ readonly interactionDeadline?: Duration.Duration | undefined
1031
+ }): Layer.Layer<Chat.Chat | Registry | ChatTest> =>
1032
+ Layer.effect(
1033
+ ChatTest,
1034
+ Effect.gen(function*() {
1035
+ const registry = yield* Registry
1036
+ const { adapter, service } = makeFake({
1037
+ platform: options?.platform ?? "test",
1038
+ selfId: options?.selfId ?? "bot",
1039
+ capabilities: options?.capabilities ?? allCapabilities,
1040
+ limits: options?.limits ?? {},
1041
+ measure: options?.measure ?? codePoints,
1042
+ interactionDeadline: options?.interactionDeadline ?? Duration.seconds(3)
1043
+ })
1044
+ yield* registry.register(adapter)
1045
+ return service
1046
+ })
1047
+ ).pipe(Layer.provideMerge(Chat.layer))
1048
+
1049
+ // -----------------------------------------------------------------------------
1050
+ // invariants
1051
+ // -----------------------------------------------------------------------------
1052
+
1053
+ /**
1054
+ * Error for a conformance rule or invariant that did not hold.
1055
+ *
1056
+ * **Details**
1057
+ *
1058
+ * `rule` names what failed, and `expected` and `actual` say how. A platform
1059
+ * error behind the failure is in `cause`.
1060
+ *
1061
+ * @stability unstable
1062
+ * @category errors
1063
+ * @since 4.1.5
1064
+ */
1065
+ export class ConformanceFailure extends Schema.TaggedError<ConformanceFailure>(
1066
+ "effect/chat/ChatTest/ConformanceFailure"
1067
+ )("ConformanceFailure", {
1068
+ rule: Schema.String,
1069
+ expected: Schema.String,
1070
+ actual: Schema.String,
1071
+ cause: Schema.optionalKey(Schema.Defect())
1072
+ }) {
1073
+ override get message(): string {
1074
+ return this.rule + ": expected " + this.expected + ", got " + this.actual
1075
+ }
1076
+ }
1077
+
1078
+ const sameMentions = (a: ReadonlyArray<Mention>, b: ReadonlyArray<Mention>): boolean =>
1079
+ a.length === b.length &&
1080
+ a.every((mention, i) => {
1081
+ const other = b[i]
1082
+ return mention.kind === other.kind && mention.id === other.id && mention.start === other.start &&
1083
+ mention.end === other.end && mention.isSelf === other.isSelf
1084
+ })
1085
+
1086
+ const sameReplyTo = (a: ReplyTo | undefined, b: ReplyTo | undefined): boolean =>
1087
+ a === undefined || b === undefined
1088
+ ? a === b
1089
+ : a.messageId === b.messageId && a.authorId === b.authorId && a.isSelf === b.isSelf
1090
+
1091
+ /**
1092
+ * Returns whether two reads of a message are the same message.
1093
+ *
1094
+ * **Details**
1095
+ *
1096
+ * It compares `id`, `thread`, `author.id`, `author.isBot`, `author.isSelf`,
1097
+ * `text`, `mentions`, `replyTo`, `timestamp` and the attachment ids in order.
1098
+ * `raw`, `author.name` and the optional attachment fields are left out.
1099
+ *
1100
+ * @stability unstable
1101
+ * @category comparisons
1102
+ * @since 4.1.5
1103
+ */
1104
+ export const sameMessage = (a: ChatMessage.ChatMessage, b: ChatMessage.ChatMessage): boolean =>
1105
+ a.id === b.id &&
1106
+ ChatThread.equals(a.thread, b.thread) &&
1107
+ a.author.id === b.author.id &&
1108
+ a.author.isBot === b.author.isBot &&
1109
+ a.author.isSelf === b.author.isSelf &&
1110
+ a.text === b.text &&
1111
+ sameMentions(a.mentions, b.mentions) &&
1112
+ sameReplyTo(a.replyTo, b.replyTo) &&
1113
+ DateTime.Equivalence(a.timestamp, b.timestamp) &&
1114
+ a.attachments.length === b.attachments.length &&
1115
+ a.attachments.every((attachment, i) => attachment.id === b.attachments[i].id)
1116
+
1117
+ const canonicalJson = (value: unknown): string =>
1118
+ JSON.stringify(value, (_, v) =>
1119
+ Predicate.isObject(v)
1120
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
1121
+ : v)
1122
+
1123
+ const failure = (rule: string, expected: string, actual: string, cause?: unknown) =>
1124
+ new ConformanceFailure({ rule, expected, actual, ...(cause === undefined ? {} : { cause }) })
1125
+
1126
+ const check = (rule: string, condition: boolean, expected: string, actual: () => string) =>
1127
+ condition ? Effect.void : Effect.fail(failure(rule, expected, actual()))
1128
+
1129
+ const MessageJson = Schema.toCodecJson(ChatMessage.ChatMessage)
1130
+ const EventJson = Schema.toCodecJson(ChatEvent.ChatEvent)
1131
+
1132
+ const roundTrip = <S extends Schema.Codec<any, Schema.Json>>(rule: string, codec: S, value: S["Type"]) =>
1133
+ Effect.gen(function*() {
1134
+ const encoded = yield* Schema.encodeEffect(codec)(value)
1135
+ const decoded = yield* Schema.decodeEffect(codec)(encoded)
1136
+ const again = yield* Schema.encodeEffect(codec)(decoded)
1137
+ yield* check(
1138
+ rule,
1139
+ canonicalJson(encoded) === canonicalJson(again),
1140
+ "an unchanged value after encoding and decoding",
1141
+ () => canonicalJson(again)
1142
+ )
1143
+ return decoded as S["Type"]
1144
+ }).pipe(
1145
+ Effect.catchTag(
1146
+ "SchemaError",
1147
+ (error) => Effect.fail(failure(rule, "a value that encodes and decodes", "SchemaError", error))
1148
+ )
1149
+ )
1150
+
1151
+ const checkThread = Effect.fnUntraced(function*(rule: string, thread: ChatThread.ChatThread, platform: string) {
1152
+ yield* check(rule, thread.platform === platform, "platform " + platform, () => "platform " + thread.platform)
1153
+ const decoded = ChatThread.fromString(ChatThread.toString(thread))
1154
+ yield* check(
1155
+ rule,
1156
+ Option.isSome(decoded) && ChatThread.equals(decoded.value, thread),
1157
+ "a thread that survives its string codec",
1158
+ () => ChatThread.toString(thread)
1159
+ )
1160
+ })
1161
+
1162
+ const checkMessageWith = Effect.fnUntraced(function*(rule: string, message: ChatMessage.ChatMessage, options: {
1163
+ readonly platform: string
1164
+ readonly parseMention: ParseMention
1165
+ }) {
1166
+ yield* checkThread(rule, message.thread, options.platform)
1167
+ const mentions = [...message.mentions].sort((a, b) => a.start - b.start)
1168
+ let end = 0
1169
+ for (const mention of mentions) {
1170
+ yield* check(
1171
+ rule,
1172
+ mention.start >= end && mention.start < mention.end && mention.end <= message.text.length,
1173
+ "mentions inside text without overlap",
1174
+ () => "mention at " + mention.start + "-" + mention.end
1175
+ )
1176
+ end = mention.end
1177
+ const parsed = options.parseMention(message.text.slice(mention.start, mention.end))
1178
+ yield* check(
1179
+ rule,
1180
+ Option.isSome(parsed) && parsed.value.kind === mention.kind && parsed.value.id === mention.id,
1181
+ "a " + mention.kind + " mention token at " + mention.start + "-" + mention.end,
1182
+ () => Option.isSome(parsed) ? "a " + parsed.value.kind + " token" : "no mention token"
1183
+ )
1184
+ }
1185
+ for (const attachment of message.attachments) {
1186
+ yield* check(
1187
+ rule,
1188
+ attachment.id.length > 0 && !("url" in attachment) && !/^[a-z]+:\/\//i.test(attachment.id),
1189
+ "an attachment with an id and no URL",
1190
+ () => "attachment " + (attachment.id.length > 0 ? "with a URL" : "without an id")
1191
+ )
1192
+ }
1193
+ if (message.replyTo !== undefined) {
1194
+ const { authorId, isSelf } = message.replyTo
1195
+ yield* check(
1196
+ rule,
1197
+ (authorId === undefined) === (isSelf === undefined),
1198
+ "replyTo.isSelf set exactly when replyTo.authorId is",
1199
+ () => "authorId " + authorId + ", isSelf " + isSelf
1200
+ )
1201
+ }
1202
+ const decoded = yield* roundTrip(rule, MessageJson, message)
1203
+ yield* check(rule, sameMessage(message, decoded), "the same message after decoding", () => "a different message")
1204
+ })
1205
+
1206
+ /**
1207
+ * Checks the invariants every message holds, for fixture tests and live runs.
1208
+ *
1209
+ * **Details**
1210
+ *
1211
+ * - Every mention sits inside `text`, mentions do not overlap, and each slice
1212
+ * parses with `parseMention` as a token of the mention's kind and id.
1213
+ * - `thread.platform` is the platform, and the thread survives its string
1214
+ * codec.
1215
+ * - The message encodes and decodes through its Schema unchanged, `raw`
1216
+ * included.
1217
+ * - Every attachment has an id and no URL.
1218
+ * - `replyTo.isSelf` is set exactly when `replyTo.authorId` is.
1219
+ *
1220
+ * @stability unstable
1221
+ * @category testing
1222
+ * @since 4.1.5
1223
+ */
1224
+ export const checkMessage = (message: ChatMessage.ChatMessage, options: {
1225
+ readonly platform: string
1226
+ readonly parseMention: ParseMention
1227
+ }): Effect.Effect<void, ConformanceFailure> => checkMessageWith("checkMessage", message, options)
1228
+
1229
+ /**
1230
+ * Checks the invariants every event holds, for fixture tests and live runs.
1231
+ *
1232
+ * **Details**
1233
+ *
1234
+ * - A message event's message passes `checkMessage`, and the event's thread is
1235
+ * the message's.
1236
+ * - `thread.platform` is the platform, and the thread survives its string
1237
+ * codec.
1238
+ * - The event encodes and decodes through its Schema unchanged, `raw`
1239
+ * included, and two decodes have the same `dedupeKey`.
1240
+ * - A reaction's `dedupeKey` differs between added and removed.
1241
+ *
1242
+ * @stability unstable
1243
+ * @category testing
1244
+ * @since 4.1.5
1245
+ */
1246
+ export const checkEvent = (event: ChatEvent.ChatEvent, options: {
1247
+ readonly platform: string
1248
+ readonly parseMention: ParseMention
1249
+ }): Effect.Effect<void, ConformanceFailure> =>
1250
+ Effect.gen(function*() {
1251
+ const rule = "checkEvent"
1252
+ yield* checkThread(rule, event.thread, options.platform)
1253
+ if (event._tag === "MessageCreated") {
1254
+ yield* checkMessageWith(rule, event.message, options)
1255
+ yield* check(
1256
+ rule,
1257
+ ChatThread.equals(event.thread, event.message.thread),
1258
+ "the event's thread equal to the message's",
1259
+ () => ChatThread.toString(event.thread)
1260
+ )
1261
+ } else if (event._tag !== "StopRequested") {
1262
+ const { _tag, ...fields } = event
1263
+ const flipped = _tag === "ReactionAdded"
1264
+ ? ChatEvent.ReactionRemoved.make(fields)
1265
+ : ChatEvent.ReactionAdded.make(fields)
1266
+ yield* check(
1267
+ rule,
1268
+ ChatEvent.dedupeKey(flipped) !== ChatEvent.dedupeKey(event),
1269
+ "different keys for an added and a removed reaction",
1270
+ () => ChatEvent.dedupeKey(event)
1271
+ )
1272
+ }
1273
+ const first = yield* roundTrip(rule, EventJson, event)
1274
+ const second = yield* roundTrip(rule, EventJson, event)
1275
+ const key = ChatEvent.dedupeKey(event)
1276
+ yield* check(
1277
+ rule,
1278
+ ChatEvent.dedupeKey(first) === key && ChatEvent.dedupeKey(second) === key,
1279
+ "the same dedupeKey for every decode",
1280
+ () => ChatEvent.dedupeKey(first) + " and " + ChatEvent.dedupeKey(second)
1281
+ )
1282
+ })
1283
+
1284
+ const InteractionJson = Schema.toCodecJson(ChatInteraction.Interaction)
1285
+
1286
+ /**
1287
+ * Checks the invariants every interaction holds, for a click, a submit or a
1288
+ * command from a fixture.
1289
+ *
1290
+ * **Details**
1291
+ *
1292
+ * - `thread.platform` is the platform, and the thread survives its string
1293
+ * codec.
1294
+ * - The interaction encodes and decodes through its Schema unchanged, `raw`
1295
+ * included.
1296
+ * - A `ModalSubmitted`'s `messageId` is non-empty when it is there. A modal
1297
+ * a command opened has none.
1298
+ * - A `CommandInvoked` has a non-empty `id`.
1299
+ *
1300
+ * It takes no `parseMention` and checks no dedupe key, since an interaction
1301
+ * carries neither.
1302
+ *
1303
+ * @stability unstable
1304
+ * @category testing
1305
+ * @since 4.1.5
1306
+ */
1307
+ export const checkInteraction = (interaction: ChatInteraction.Interaction, options: {
1308
+ readonly platform: string
1309
+ }): Effect.Effect<void, ConformanceFailure> =>
1310
+ Effect.gen(function*() {
1311
+ const rule = "checkInteraction"
1312
+ yield* checkThread(rule, interaction.thread, options.platform)
1313
+ if (interaction._tag === "ModalSubmitted") {
1314
+ yield* check(rule, interaction.messageId !== "", "a submit with no messageId or a non-empty one", () =>
1315
+ "an empty messageId")
1316
+ }
1317
+ if (interaction._tag === "CommandInvoked") {
1318
+ yield* check(rule, interaction.id !== "", "a command with a non-empty id", () =>
1319
+ "an empty id")
1320
+ }
1321
+ yield* roundTrip(rule, InteractionJson, interaction)
1322
+ })
1323
+
1324
+ // -----------------------------------------------------------------------------
1325
+ // conformance
1326
+ // -----------------------------------------------------------------------------
1327
+
1328
+ /**
1329
+ * The click hook of `conformance`: a way to click, for the adapter under
1330
+ * test.
1331
+ *
1332
+ * **Details**
1333
+ *
1334
+ * - `click` clicks the element `id` on a message the suite posted, through
1335
+ * the adapter's real entry, and fails `NoSuchElement` when the message
1336
+ * carries no such element. `option` is as in `ChatTest.click`.
1337
+ * - `submit` submits the modal the last click or command opened, and
1338
+ * submits it again after an `errors` reply. It does nothing when no modal
1339
+ * is open: the rule then fails on the submit its handler never saw.
1340
+ * - `command` sends a command typed at `thread` through the adapter's real
1341
+ * entry. The command rules exist only when it is given. It is optional, so
1342
+ * a hook written before commands still fits.
1343
+ * - All three need `ChatInteraction.Handler` and nothing else. The suite
1344
+ * provides its own recording handler, so the entry must take its handler
1345
+ * at the call, not at layer build.
1346
+ *
1347
+ * @stability unstable
1348
+ * @category testing
1349
+ * @since 4.1.5
1350
+ */
1351
+ export interface Interactions {
1352
+ readonly click: (messageId: string, id: string, options?: {
1353
+ readonly option?: string | undefined
1354
+ }) => Effect.Effect<void, NoSuchElement, ChatInteraction.Handler>
1355
+ readonly submit: (
1356
+ values: Readonly<Record<string, string>>
1357
+ ) => Effect.Effect<void, never, ChatInteraction.Handler>
1358
+ readonly command?:
1359
+ | ((thread: ChatThread.ChatThread, id: string, options?: {
1360
+ readonly text?: string | undefined
1361
+ }) => Effect.Effect<void, never, ChatInteraction.Handler>)
1362
+ | undefined
1363
+ }
1364
+
1365
+ /** What the suite's own `ChatInteraction.Handler` received, and how it answers. */
1366
+ class Recording {
1367
+ readonly clicks: Array<ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged> = []
1368
+ readonly submits: Array<ChatInteraction.ModalSubmitted> = []
1369
+ readonly commands: Array<ChatInteraction.CommandInvoked> = []
1370
+ readonly commandReplies: Array<ChatInteraction.CommandReply> = []
1371
+ readonly refused: Array<ChatError> = []
1372
+ onClick: (event: ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged) => ChatInteraction.ClickReply = () =>
1373
+ ChatInteraction.ack
1374
+ onSubmit: (event: ChatInteraction.ModalSubmitted) => ChatInteraction.SubmitReply = () => ChatInteraction.close
1375
+ onCommand: (event: ChatInteraction.CommandInvoked) => ChatInteraction.CommandReply = (event) =>
1376
+ ChatInteraction.respond({ markdown: conformanceText(event.id), visibility: "public" })
1377
+ readonly handler = ChatInteraction.Handler.of({
1378
+ click: (event) =>
1379
+ Effect.sync(() => {
1380
+ this.clicks.push(event)
1381
+ return this.onClick(event)
1382
+ }),
1383
+ submit: (event) =>
1384
+ Effect.sync(() => {
1385
+ this.submits.push(event)
1386
+ return this.onSubmit(event)
1387
+ }),
1388
+ command: (event) =>
1389
+ Effect.sync(() => {
1390
+ this.commands.push(event)
1391
+ const reply = this.onCommand(event)
1392
+ this.commandReplies.push(reply)
1393
+ return reply
1394
+ }),
1395
+ refused: (_, error) => Effect.sync(() => void this.refused.push(error))
1396
+ })
1397
+ }
1398
+
1399
+ const conformanceButton = (rule: string): ChatUi.Button => ({ _tag: "Button", id: "conformance", label: rule })
1400
+
1401
+ const conformanceSelect = (rule: string): ChatUi.Select => ({
1402
+ _tag: "Select",
1403
+ id: "conformance",
1404
+ placeholder: rule,
1405
+ options: [{ label: "a", value: "a" }, { label: "b", value: "b" }]
1406
+ })
1407
+
1408
+ const describeExit = (exit: Exit.Exit<unknown, unknown>): string => {
1409
+ if (Exit.isSuccess(exit)) return "success"
1410
+ const error = Exit.findErrorOption(exit)
1411
+ if (Option.isNone(error)) return "a defect or interruption"
1412
+ return describeError(error.value)
1413
+ }
1414
+
1415
+ const describeError = (error: unknown): string => {
1416
+ if (!isChatError(error)) return String(error)
1417
+ return error.reason._tag === "Unsupported"
1418
+ ? "Unsupported(" + error.reason.capability + ")"
1419
+ : error.reason._tag
1420
+ }
1421
+
1422
+ const conformanceText = (rule: string) => "conformance " + rule
1423
+
1424
+ class Tester {
1425
+ readonly created: Array<{ readonly thread: ChatThread.ChatThread; readonly id: string }> = []
1426
+ readonly rule: string
1427
+ readonly chat: Chat.Chat["Service"]
1428
+ readonly descriptor: Descriptor
1429
+ readonly options: ConformanceOptions
1430
+ constructor(rule: string, chat: Chat.Chat["Service"], descriptor: Descriptor, options: ConformanceOptions) {
1431
+ this.rule = rule
1432
+ this.chat = chat
1433
+ this.descriptor = descriptor
1434
+ this.options = options
1435
+ }
1436
+
1437
+ get thread() {
1438
+ return this.options.thread
1439
+ }
1440
+
1441
+ readonly recording = new Recording()
1442
+
1443
+ /** Runs an interaction hook with the suite's recording handler. */
1444
+ recorded<A, E>(effect: Effect.Effect<A, E, ChatInteraction.Handler>): Effect.Effect<A, E> {
1445
+ return Effect.provideService(effect, ChatInteraction.Handler, this.recording.handler)
1446
+ }
1447
+
1448
+ /** Clicks through the hook, with the suite's recording handler. */
1449
+ clickExit(messageId: string, id: string, options?: { readonly option?: string | undefined }) {
1450
+ return Effect.exit(this.recorded(this.options.interactions!.click(messageId, id, options)))
1451
+ }
1452
+
1453
+ click(messageId: string, id: string, options?: { readonly option?: string | undefined }) {
1454
+ return Effect.flatMap(
1455
+ this.clickExit(messageId, id, options),
1456
+ (exit) =>
1457
+ Exit.isSuccess(exit) ? Effect.void : Effect.fail(failure(
1458
+ this.rule,
1459
+ "a click on element " + id + " of message " + messageId,
1460
+ describeExit(exit),
1461
+ Option.getOrUndefined(Exit.findErrorOption(exit))
1462
+ ))
1463
+ )
1464
+ }
1465
+
1466
+ /** Sends a command through the hook, with the suite's recording handler. */
1467
+ command(id: string, options?: { readonly text?: string | undefined }) {
1468
+ return this.recorded(this.options.interactions!.command!(this.thread, id, options))
1469
+ }
1470
+
1471
+ submit(values: Readonly<Record<string, string>>) {
1472
+ return this.recorded(this.options.interactions!.submit(values))
1473
+ }
1474
+
1475
+ /** Checks a received interaction with `checkInteraction`, under this rule's name. */
1476
+ checkInteraction(interaction: ChatInteraction.Interaction) {
1477
+ return Effect.mapError(
1478
+ checkInteraction(interaction, { platform: this.options.platform }),
1479
+ (error) => failure(this.rule, error.expected, error.actual, error.cause)
1480
+ )
1481
+ }
1482
+
1483
+ /** A click whose handler answers with `modal`, and what the adapter did with it. */
1484
+ openModal(modal: ChatInteraction.OpenModal) {
1485
+ return Effect.gen({ self: this }, function*() {
1486
+ // A modal opens from a click, on a select when there are no buttons.
1487
+ const element = this.has("buttons") || !this.has("selects")
1488
+ ? conformanceButton(this.rule)
1489
+ : conformanceSelect(this.rule)
1490
+ const posted = yield* this.post({ actions: [element] })
1491
+ this.recording.onClick = () => modal
1492
+ yield* this.click(posted.id, "conformance")
1493
+ return posted
1494
+ })
1495
+ }
1496
+
1497
+ has(capability: Capability) {
1498
+ return this.descriptor.capabilities.has(capability)
1499
+ }
1500
+
1501
+ call<A>(effect: Effect.Effect<A, ChatError>): Effect.Effect<A, ConformanceFailure> {
1502
+ return Effect.mapError(effect, (error) => {
1503
+ const listed = error.reason._tag === "Unsupported" && this.has(error.reason.capability)
1504
+ return failure(
1505
+ this.rule,
1506
+ "success",
1507
+ describeError(error) + (listed ? " for a listed capability" : ""),
1508
+ error
1509
+ )
1510
+ })
1511
+ }
1512
+
1513
+ collect<A>(stream: Stream.Stream<A, ChatError>): Effect.Effect<Array<A>, ConformanceFailure> {
1514
+ return this.call(Stream.runCollect(stream))
1515
+ }
1516
+
1517
+ check(condition: boolean, expected: string, actual: () => string) {
1518
+ return check(this.rule, condition, expected, actual)
1519
+ }
1520
+
1521
+ /** Marks a message the rule posted in its thread for cleanup. */
1522
+ track(posted: Posted) {
1523
+ this.created.push({ thread: this.thread, id: posted.id })
1524
+ }
1525
+
1526
+ post(
1527
+ content: {
1528
+ readonly markdown?: string
1529
+ readonly replyTo?: ReplyTo
1530
+ readonly files?: ReadonlyArray<File>
1531
+ readonly actions?: ReadonlyArray<ChatUi.Action>
1532
+ },
1533
+ thread = this.thread
1534
+ ) {
1535
+ return Effect.tap(
1536
+ this.call(this.chat.post(thread, { markdown: conformanceText(this.rule), ...content })),
1537
+ (posted) => Effect.sync(() => this.created.push({ thread, id: posted.id }))
1538
+ )
1539
+ }
1540
+
1541
+ userPosts(thread = this.thread) {
1542
+ return Effect.flatMap(
1543
+ this.options.userPosts(thread, conformanceText(this.rule)),
1544
+ (event) =>
1545
+ event._tag === "MessageCreated"
1546
+ ? Effect.succeed(event)
1547
+ : Effect.fail(failure(this.rule, "a MessageCreated event from userPosts", event._tag))
1548
+ )
1549
+ }
1550
+
1551
+ expectReason<A>(
1552
+ tag: ChatErrorReason["_tag"],
1553
+ effect: Effect.Effect<A, ChatError>,
1554
+ onSuccess?: (a: A) => void,
1555
+ refine?: { readonly expected: string; readonly test: (reason: ChatErrorReason) => boolean }
1556
+ ): Effect.Effect<void, ConformanceFailure> {
1557
+ return Effect.flatMap(Effect.exit(effect), (exit) => {
1558
+ if (Exit.isSuccess(exit)) onSuccess?.(exit.value)
1559
+ const error = Exit.findErrorOption(exit)
1560
+ const matches = Option.isSome(error) && isChatError(error.value) && error.value.reason._tag === tag &&
1561
+ (refine === undefined || refine.test(error.value.reason))
1562
+ return matches ? Effect.void : Effect.fail(failure(
1563
+ this.rule,
1564
+ refine === undefined ? tag : refine.expected,
1565
+ describeExit(exit),
1566
+ Option.getOrUndefined(error)
1567
+ ))
1568
+ })
1569
+ }
1570
+
1571
+ /**
1572
+ * Calls the op behind `capability`. When the descriptor lacks it, the op
1573
+ * must fail with `Unsupported` naming it. When it is listed, the op must
1574
+ * not fail with `Unsupported` at all, whichever capability that names, so a
1575
+ * descriptor that lies in either direction fails.
1576
+ */
1577
+ probe(capability: Capability): Effect.Effect<void, ConformanceFailure, Registry> {
1578
+ const listed = this.has(capability)
1579
+ const expected = listed ? "no Unsupported for listed " + capability : "Unsupported(" + capability + ")"
1580
+ const expect = <A>(effect: Effect.Effect<A, ChatError>, onSuccess?: (a: A) => void) =>
1581
+ Effect.flatMap(Effect.exit(effect), (exit) => {
1582
+ if (Exit.isSuccess(exit)) onSuccess?.(exit.value)
1583
+ const error = Exit.findErrorOption(exit)
1584
+ const reason = Option.isSome(error) && isChatError(error.value) ? error.value.reason : undefined
1585
+ const holds = listed
1586
+ ? Exit.isSuccess(exit) || (reason !== undefined && reason._tag !== "Unsupported")
1587
+ : reason?._tag === "Unsupported" && reason.capability === capability
1588
+ return holds ? Effect.void : Effect.fail(failure(
1589
+ this.rule,
1590
+ expected,
1591
+ describeExit(exit),
1592
+ Option.getOrUndefined(error)
1593
+ ))
1594
+ })
1595
+ const track = (posted: Posted) => this.track(posted)
1596
+ /** Whether the suite's handler was refused `Unsupported` exactly when the capability is not listed. */
1597
+ const checkRefusal = Effect.suspend(() => {
1598
+ const { refused } = this.recording
1599
+ const refusal = refused.find((error) => error.reason._tag === "Unsupported")
1600
+ return this.check(
1601
+ listed
1602
+ ? refusal === undefined
1603
+ : refusal?.reason._tag === "Unsupported" && refusal.reason.capability === capability,
1604
+ listed ? "no refusal Unsupported for listed " + capability : "a refusal Unsupported(" + capability + ")",
1605
+ () => refused.length === 0 ? "no refusal" : refused.map(describeError).join(", ")
1606
+ )
1607
+ })
1608
+ const { chat, thread } = this
1609
+ const text = conformanceText(this.rule)
1610
+ switch (capability) {
1611
+ case "edit":
1612
+ return Effect.flatMap(this.post({}), (posted) => expect(chat.edit(thread, posted.id, { markdown: text })))
1613
+ case "delete":
1614
+ return Effect.flatMap(this.post({}), (posted) => expect(chat.delete(thread, posted.id)))
1615
+ case "fetchMessage":
1616
+ return Effect.flatMap(this.post({}), (posted) => expect(chat.fetchMessage(thread, posted.id)))
1617
+ case "history":
1618
+ return expect(Stream.runDrain(Stream.take(chat.history(thread, { direction: "backward" }), 1)))
1619
+ case "download":
1620
+ return expect(Stream.runDrain(chat.download(thread, { id: "conformance-missing" }, { maxBytes: 1 })))
1621
+ case "files":
1622
+ return expect(chat.post(thread, { markdown: text, files: [conformanceFile(this.rule)] }), track)
1623
+ case "replyTo":
1624
+ return Effect.flatMap(
1625
+ this.post({}),
1626
+ (target) => expect(chat.post(thread, { markdown: text, replyTo: { messageId: target.id } }), track)
1627
+ )
1628
+ case "startThread":
1629
+ return Effect.flatMap(this.post({}), (posted) => expect(chat.startThread(thread, posted.id)))
1630
+ case "getThread":
1631
+ return expect(chat.getThread(thread))
1632
+ case "opener":
1633
+ return expect(chat.opener(thread))
1634
+ case "getUser":
1635
+ return Effect.flatMap(
1636
+ this.userPosts(),
1637
+ (event) => expect(chat.getUser(this.options.platform, event.message.author.id))
1638
+ )
1639
+ case "buttons":
1640
+ return expect(chat.post(thread, { markdown: text, actions: [conformanceButton(this.rule)] }), track)
1641
+ case "selects":
1642
+ return expect(chat.post(thread, { markdown: text, actions: [conformanceSelect(this.rule)] }), track)
1643
+ case "modals":
1644
+ // Probing a modal requires the interaction hook and a clickable element.
1645
+ return this.options.interactions === undefined || !(this.has("buttons") || this.has("selects"))
1646
+ ? Effect.void
1647
+ : Effect.andThen(this.openModal(probeModal.open()), checkRefusal)
1648
+ case "modalErrors":
1649
+ // Its absence means a degraded answer, not a refusal, so it has no inverse.
1650
+ return Effect.void
1651
+ case "commands":
1652
+ // A deferral built by hand, which no adapter can follow up: it must fail, and not with Unsupported when listed.
1653
+ return expect(chat.followUp(
1654
+ ChatInteraction.defer(
1655
+ ChatInteraction.CommandInvoked.make({
1656
+ id: "conformance",
1657
+ text: "",
1658
+ thread,
1659
+ userId: "conformance",
1660
+ raw: {}
1661
+ }),
1662
+ { visibility: "public" }
1663
+ ),
1664
+ { markdown: text }
1665
+ ))
1666
+ case "ephemeral":
1667
+ // Probing a private answer requires the command hook.
1668
+ return this.options.interactions?.command === undefined
1669
+ ? Effect.void
1670
+ : Effect.suspend(() => {
1671
+ this.recording.onCommand = () => ChatInteraction.respond({ markdown: text })
1672
+ return Effect.andThen(this.command("conformance"), checkRefusal)
1673
+ })
1674
+ case "nativeStream":
1675
+ return Effect.flatMap(
1676
+ Registry,
1677
+ (registry) =>
1678
+ Effect.flatMap(this.call(registry.get(this.options.platform)), (adapter) =>
1679
+ this.check(
1680
+ (adapter.nativeStream !== undefined) === listed,
1681
+ listed ? "a nativeStream, as the descriptor lists it" : "no nativeStream, as the descriptor lacks it",
1682
+ () => adapter.nativeStream === undefined ? "no nativeStream" : "a nativeStream"
1683
+ ))
1684
+ )
1685
+ }
1686
+ }
1687
+
1688
+ get cleanup(): Effect.Effect<void> {
1689
+ return Effect.suspend(() => {
1690
+ if (!this.has("delete")) return Effect.void
1691
+ const created = this.created.splice(0).reverse()
1692
+ return Effect.forEach(created, ({ id, thread }) => Effect.ignore(this.chat.delete(thread, id)), {
1693
+ discard: true
1694
+ })
1695
+ })
1696
+ }
1697
+ }
1698
+
1699
+ const conformanceFile = (rule: string): File => ({
1700
+ name: "conformance.txt",
1701
+ contentType: "text/plain",
1702
+ content: new TextEncoder().encode(conformanceText(rule) + " " + "x".repeat(64))
1703
+ })
1704
+
1705
+ const findIn = (messages: ReadonlyArray<ChatMessage.ChatMessage>, id: string) =>
1706
+ messages.find((message) => message.id === id)
1707
+
1708
+ /** A refusal of the text must not blame the files, or `ChatMarkdown` would post again without them. */
1709
+ const textTooLarge = {
1710
+ expected: "TooLarge without subject files or detail file_refused",
1711
+ test: (reason: ChatErrorReason) =>
1712
+ reason._tag === "TooLarge" && reason.subject !== "files" && reason.detail !== fileRefused
1713
+ }
1714
+
1715
+ const mentionLike = "@everyone @here <@U0000> <!here> <!channel> <@&1> <#C0000>"
1716
+
1717
+ /** Text a platform takes in any quantity: no emoji, which Slack limits separately. */
1718
+ const measureFitsBlock = "a < b & c > d\n\n```ts\nconst x = 1 < 2\n```\n\n\u{1D400}\u{1D401} caf\u00e9\n\n"
1719
+
1720
+ const measureSamples: ReadonlyArray<string> = [
1721
+ "",
1722
+ "x",
1723
+ "hello world",
1724
+ "<",
1725
+ "a < b",
1726
+ "<@U0000>",
1727
+ "&amp; > &",
1728
+ "```\ncode < 1\n```\n",
1729
+ "```",
1730
+ "\u{1D400}\u{1D401}",
1731
+ "\u{1F600}\u{1F44D}\u{1F3FD}",
1732
+ ":grinning:",
1733
+ "caf\u00e9"
1734
+ ]
1735
+
1736
+ const probeModal = ChatInteraction.modal("conformance-modal", {
1737
+ title: "Conformance",
1738
+ fields: { answer: ChatInteraction.textInput({ label: "Answer" }) }
1739
+ })
1740
+
1741
+ /** The fixed schemas of `actions/valueRoundTrips`, each with the value posted. */
1742
+ const valueCases: ReadonlyArray<{ readonly schema: ChatInteraction.ValueSchema; readonly value: unknown }> = [
1743
+ { schema: Schema.String, value: "v1.4.2" },
1744
+ { schema: Schema.Struct({ version: Schema.String, attempt: Schema.Number }), value: { version: "v1", attempt: 2 } },
1745
+ { schema: Schema.Union([Schema.String, Schema.Number]), value: 123 },
1746
+ { schema: Schema.Union([Schema.String, Schema.Number]), value: "123" },
1747
+ { schema: Schema.String, value: "a < b & \"c\" \u{1D400}" }
1748
+ ]
1749
+
1750
+ const sameValue = (a: unknown, b: unknown) => typeof a === typeof b && canonicalJson(a) === canonicalJson(b)
1751
+
1752
+ type ConformanceOptions = Parameters<typeof conformance>[0]
1753
+
1754
+ /** The largest `n` in `[0, limit]` that `fits`, for a `fits` that holds up to some `n` and fails past it. */
1755
+ const largestFitting = (limit: number, fits: (n: number) => boolean): number => {
1756
+ let low = 0
1757
+ let high = limit
1758
+ while (low < high) {
1759
+ const middle = Math.ceil((low + high) / 2)
1760
+ if (fits(middle)) low = middle
1761
+ else high = middle - 1
1762
+ }
1763
+ return low
1764
+ }
1765
+
1766
+ /**
1767
+ * Creates the conformance suite, as plain Effects keyed by rule name, so any
1768
+ * test runner can run them.
1769
+ *
1770
+ * **Details**
1771
+ *
1772
+ * - Each rule needs the adapter under test registered in `Chat` and a way to
1773
+ * make another identity's message appear in `thread`, which must be a
1774
+ * channel the suite may write to.
1775
+ * - A rule is never skipped. When the descriptor lacks a capability a rule
1776
+ * needs, the rule becomes its inverse: the op fails with `Unsupported`.
1777
+ * There is an `unsupported/{capability}` rule for every capability. When
1778
+ * the capability is listed, it calls the op and fails if the op fails with
1779
+ * `Unsupported`, so a descriptor that lies in either direction fails.
1780
+ * - A listed capability never fails with `Unsupported`, which every rule
1781
+ * checks as it goes.
1782
+ * - The three `retries/*` rules exist only when `failNext` is given.
1783
+ * `post/refusedFile` exists only when `refuseFiles` is given.
1784
+ * - The rules that need a click exist only when `interactions` is given,
1785
+ * since neither platform has an API that clicks. A live run leaves it out
1786
+ * and runs only the outbound rules. The suite provides its own recording
1787
+ * `ChatInteraction.Handler` to the hook, so the rules still need only
1788
+ * `Chat` and `Registry`.
1789
+ * - `modalErrors` has no inverse rule: without it an `errors` reply is a
1790
+ * degraded answer, not a refusal.
1791
+ * - The `command/*` rules and `unsupported/ephemeral` exist only when
1792
+ * `interactions.command` is given. `unsupported/commands` always runs: it
1793
+ * calls `followUp` with a deferral the suite builds by hand, which must
1794
+ * fail `Unsupported` without `commands`, and fail some other way with it.
1795
+ * - Every rule deletes what it posted when it ends, pass or fail, when the
1796
+ * platform can delete.
1797
+ *
1798
+ * **Gotchas**
1799
+ *
1800
+ * Rule names are stable, an existing rule is never tightened, and a new rule
1801
+ * arrives only behind a new capability or with a changeset saying third-party
1802
+ * adapters may start failing. `unsupported/buttons` and
1803
+ * `unsupported/selects` are such rules: an adapter that ignores `actions`
1804
+ * and posts anyway fails them. So is `unsupported/commands`: an adapter whose
1805
+ * `followUp` does anything but fail `Unsupported` fails it. The `retries/retrySafe` rule waits for real
1806
+ * time, so run the suite on a live `Clock`.
1807
+ *
1808
+ * @stability unstable
1809
+ * @category testing
1810
+ * @since 4.1.5
1811
+ */
1812
+ export const conformance = (options: {
1813
+ readonly platform: string
1814
+ readonly thread: ChatThread.ChatThread
1815
+ readonly userPosts: (thread: ChatThread.ChatThread, text: string) => Effect.Effect<ChatEvent.ChatEvent>
1816
+ readonly parseMention: ParseMention
1817
+ readonly refuseFiles?: (() => Effect.Effect<void>) | undefined
1818
+ readonly interactions?: Interactions | undefined
1819
+ readonly failNext?:
1820
+ | ((op: string, reason: ChatErrorReason, options?: {
1821
+ readonly times?: number | undefined
1822
+ readonly landed?: boolean | undefined
1823
+ }) => Effect.Effect<void>)
1824
+ | undefined
1825
+ }): Readonly<Record<string, Effect.Effect<void, ConformanceFailure, Chat.Chat | Registry>>> => {
1826
+ const rules: Record<string, Effect.Effect<void, ConformanceFailure, Chat.Chat | Registry>> = {}
1827
+ const { parseMention, platform } = options
1828
+
1829
+ const rule = (
1830
+ name: string,
1831
+ needs: ReadonlyArray<Capability>,
1832
+ body: (t: Tester) => Effect.Effect<void, ConformanceFailure, Registry>
1833
+ ) => {
1834
+ rules[name] = Effect.gen(function*() {
1835
+ const chat = yield* Chat.Chat
1836
+ const descriptor = yield* Effect.mapError(
1837
+ chat.descriptor(platform),
1838
+ (error) => failure(name, "a registered adapter", describeError(error), error)
1839
+ )
1840
+ const t = new Tester(name, chat, descriptor, options)
1841
+ const missing = needs.find((capability) => !t.has(capability))
1842
+ return yield* (missing === undefined ? body(t) : t.probe(missing)).pipe(
1843
+ Effect.ensuring(t.cleanup)
1844
+ )
1845
+ })
1846
+ }
1847
+
1848
+ rule("post/fetchable", ["fetchMessage"], (t) =>
1849
+ Effect.gen(function*() {
1850
+ const posted = yield* t.post({})
1851
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1852
+ yield* t.check(
1853
+ posted.id === message.id && ChatThread.equals(posted.thread, t.thread) &&
1854
+ ChatThread.equals(message.thread, t.thread),
1855
+ "the posted message, addressed to " + ChatThread.toString(t.thread),
1856
+ () => "message " + message.id + " in " + ChatThread.toString(message.thread)
1857
+ )
1858
+ }))
1859
+
1860
+ rule("post/authorIsSelf", ["fetchMessage"], (t) =>
1861
+ Effect.gen(function*() {
1862
+ const posted = yield* t.post({})
1863
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1864
+ yield* t.check(
1865
+ message.author.isSelf && message.author.isBot,
1866
+ "author.isSelf and author.isBot",
1867
+ () => "isSelf " + message.author.isSelf + ", isBot " + message.author.isBot
1868
+ )
1869
+ }))
1870
+
1871
+ rule("post/replyTo", ["replyTo", "fetchMessage"], (t) =>
1872
+ Effect.gen(function*() {
1873
+ const target = yield* t.post({})
1874
+ const reply = yield* t.post({ replyTo: { messageId: target.id } })
1875
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, reply.id))
1876
+ yield* t.check(
1877
+ message.replyTo?.messageId === target.id,
1878
+ "replyTo " + target.id,
1879
+ () => "replyTo " + message.replyTo?.messageId
1880
+ )
1881
+ }))
1882
+
1883
+ rule("post/files", ["files", "download", "fetchMessage"], (t) =>
1884
+ Effect.gen(function*() {
1885
+ const file = conformanceFile(t.rule)
1886
+ const posted = yield* t.post({ files: [file] })
1887
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1888
+ yield* t.check(message.attachments.length === 1, "one attachment", () => message.attachments.length + "")
1889
+ const chunks = yield* t.collect(
1890
+ t.chat.download(t.thread, message.attachments[0], { maxBytes: file.content.length })
1891
+ )
1892
+ const bytes = Bytes.concat(chunks)
1893
+ yield* t.check(
1894
+ Bytes.Equivalence(bytes, file.content),
1895
+ "the uploaded bytes",
1896
+ () => bytes.length + " different bytes"
1897
+ )
1898
+ }))
1899
+
1900
+ const refuseFiles = options.refuseFiles
1901
+ if (refuseFiles !== undefined) {
1902
+ rule("post/refusedFile", ["files", "history"], (t) =>
1903
+ Effect.gen(function*() {
1904
+ const before = yield* t.collect(t.chat.history(t.thread, { direction: "forward" }))
1905
+ yield* refuseFiles()
1906
+ const exit = yield* Effect.exit(t.chat.post(t.thread, {
1907
+ markdown: conformanceText(t.rule),
1908
+ files: [conformanceFile(t.rule)]
1909
+ }))
1910
+ if (Exit.isSuccess(exit)) t.track(exit.value)
1911
+ const after = yield* t.collect(t.chat.history(t.thread, { direction: "forward" }))
1912
+ const beforeIds = new Set(before.map((message) => message.id))
1913
+ for (const message of after) {
1914
+ if (message.author.isSelf && !beforeIds.has(message.id) && !t.created.some(({ id }) => id === message.id)) {
1915
+ t.created.push({ thread: message.thread, id: message.id })
1916
+ }
1917
+ }
1918
+ const error = Exit.findErrorOption(exit)
1919
+ const reason = Option.isSome(error) ? error.value.reason : undefined
1920
+ const listed = reason?._tag === "Unsupported" && t.has(reason.capability)
1921
+ yield* t.check(
1922
+ !listed && reason?.retry === "denied" && reason.detail === fileRefused,
1923
+ "denied with detail file_refused, not Unsupported for a listed capability",
1924
+ () => describeExit(exit) + (listed ? " for a listed capability" : "")
1925
+ )
1926
+ yield* t.check(
1927
+ after.length === before.length && after.every((message, i) => message.id === before[i].id),
1928
+ "no new message",
1929
+ () => after.length + " messages after, " + before.length + " before"
1930
+ )
1931
+ }))
1932
+ }
1933
+
1934
+ rule("post/tooLarge", [], (t) =>
1935
+ t.expectReason(
1936
+ "TooLarge",
1937
+ t.chat.post(t.thread, { markdown: "x".repeat(t.descriptor.limits.messageLength + 1) }),
1938
+ (posted) => t.track(posted),
1939
+ textTooLarge
1940
+ ))
1941
+
1942
+ rule("descriptor/measureFits", [], (t) =>
1943
+ Effect.gen(function*() {
1944
+ const { measure } = t.descriptor
1945
+ const limit = t.descriptor.limits.messageLength
1946
+ const largest = (make: (n: number) => string) => make(largestFitting(limit, (n) => measure(make(n)) <= limit))
1947
+ const blocks = largest((n) => measureFitsBlock.repeat(n))
1948
+ const markdown = largest((n) => blocks + "x".repeat(n))
1949
+ yield* t.post({ markdown })
1950
+ }))
1951
+
1952
+ rule("descriptor/measureAdds", [], (t) =>
1953
+ Effect.gen(function*() {
1954
+ const { measure } = t.descriptor
1955
+ for (const a of measureSamples) {
1956
+ for (const b of measureSamples) {
1957
+ yield* t.check(
1958
+ measure(a + b) <= measure(a) + measure(b),
1959
+ "measure(a + b) <= measure(a) + measure(b)",
1960
+ () => JSON.stringify(a) + " + " + JSON.stringify(b) + " measures " + measure(a + b)
1961
+ )
1962
+ }
1963
+ }
1964
+ const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
1965
+ yield* t.check(measure(letters) === letters.length, "ASCII letters measured at one each", () =>
1966
+ letters.length + " letters measure " + measure(letters))
1967
+ }))
1968
+
1969
+ rule("post/noMentions", ["fetchMessage"], (t) =>
1970
+ Effect.gen(function*() {
1971
+ const posted = yield* t.post({ markdown: mentionLike })
1972
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1973
+ yield* t.check(message.mentions.length === 0, "no mentions", () => message.mentions.length + " mentions")
1974
+ }))
1975
+
1976
+ const goneId = Effect.fnUntraced(function*(t: Tester) {
1977
+ const posted = yield* t.post({})
1978
+ if (!t.has("delete")) return posted.id + "0"
1979
+ yield* t.call(t.chat.delete(t.thread, posted.id))
1980
+ return posted.id
1981
+ })
1982
+
1983
+ rule("edit/keepsId", ["edit", "fetchMessage"], (t) =>
1984
+ Effect.gen(function*() {
1985
+ const posted = yield* t.post({ markdown: conformanceText(t.rule) + " before" })
1986
+ const before = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1987
+ yield* t.call(t.chat.edit(t.thread, posted.id, { markdown: conformanceText(t.rule) + " after" }))
1988
+ const after = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
1989
+ yield* t.check(
1990
+ after.id === posted.id && after.text !== before.text,
1991
+ "the same id with new text",
1992
+ () => "id " + after.id + (after.text === before.text ? " with the old text" : "")
1993
+ )
1994
+ }))
1995
+
1996
+ rule("edit/unknownId", ["edit"], (t) =>
1997
+ Effect.flatMap(
1998
+ goneId(t),
1999
+ (id) => t.expectReason("NotFound", t.chat.edit(t.thread, id, { markdown: conformanceText(t.rule) }))
2000
+ ))
2001
+
2002
+ rule("edit/tooLarge", ["edit"], (t) =>
2003
+ Effect.flatMap(t.post({}), (posted) =>
2004
+ t.expectReason(
2005
+ "TooLarge",
2006
+ t.chat.edit(t.thread, posted.id, { markdown: "x".repeat(t.descriptor.limits.messageLength + 1) }),
2007
+ undefined,
2008
+ textTooLarge
2009
+ )))
2010
+
2011
+ rule("delete/gone", ["delete", "fetchMessage"], (t) =>
2012
+ Effect.gen(function*() {
2013
+ const posted = yield* t.post({})
2014
+ yield* t.call(t.chat.delete(t.thread, posted.id))
2015
+ yield* t.expectReason("NotFound", t.chat.fetchMessage(t.thread, posted.id))
2016
+ }))
2017
+
2018
+ rule(
2019
+ "delete/unknownId",
2020
+ ["delete"],
2021
+ (t) => Effect.flatMap(goneId(t), (id) => t.expectReason("NotFound", t.chat.delete(t.thread, id)))
2022
+ )
2023
+
2024
+ rule("history/order", ["history"], (t) =>
2025
+ Effect.gen(function*() {
2026
+ const a = yield* t.post({ markdown: conformanceText(t.rule) + " a" })
2027
+ const b = yield* t.post({ markdown: conformanceText(t.rule) + " b" })
2028
+ const c = yield* t.post({ markdown: conformanceText(t.rule) + " c" })
2029
+ const backward = yield* t.collect(Stream.take(t.chat.history(t.thread, { direction: "backward" }), 3))
2030
+ const forward = yield* t.collect(
2031
+ Stream.take(t.chat.history(t.thread, { direction: "forward", from: a.id }), 2)
2032
+ )
2033
+ const ids = (messages: ReadonlyArray<ChatMessage.ChatMessage>) => messages.map((m) => m.id).join(",")
2034
+ yield* t.check(ids(backward) === [c.id, b.id, a.id].join(","), "backward " + [c.id, b.id, a.id], () =>
2035
+ "backward " + ids(backward))
2036
+ yield* t.check(ids(forward) === [b.id, c.id].join(","), "forward " + [b.id, c.id], () =>
2037
+ "forward " + ids(forward))
2038
+ }))
2039
+
2040
+ rule("history/fromExclusive", ["history"], (t) =>
2041
+ Effect.gen(function*() {
2042
+ const a = yield* t.post({ markdown: conformanceText(t.rule) + " a" })
2043
+ const b = yield* t.post({ markdown: conformanceText(t.rule) + " b" })
2044
+ const before = yield* t.collect(Stream.take(t.chat.history(t.thread, { direction: "backward", from: b.id }), 1))
2045
+ const after = yield* t.collect(Stream.take(t.chat.history(t.thread, { direction: "forward", from: a.id }), 1))
2046
+ yield* t.check(
2047
+ before[0]?.id === a.id && after[0]?.id === b.id,
2048
+ "the message next to from, not from itself",
2049
+ () => "backward " + before[0]?.id + ", forward " + after[0]?.id
2050
+ )
2051
+ }))
2052
+
2053
+ rule("history/sameAsInbound", ["history"], (t) =>
2054
+ Effect.gen(function*() {
2055
+ const event = yield* t.userPosts()
2056
+ const history = yield* t.collect(Stream.take(t.chat.history(t.thread, { direction: "backward" }), 20))
2057
+ const read = findIn(history, event.message.id)
2058
+ yield* t.check(
2059
+ read !== undefined && sameMessage(event.message, read),
2060
+ "the inbound message in history",
2061
+ () => read === undefined ? "no such message" : "a different message"
2062
+ )
2063
+ }))
2064
+
2065
+ rule("history/startsWithOpener", ["history", "startThread"], (t) =>
2066
+ Effect.gen(function*() {
2067
+ const opener = yield* t.post({ markdown: conformanceText(t.rule) + " opener" })
2068
+ const thread = yield* t.call(t.chat.startThread(t.thread, opener.id, { name: conformanceText(t.rule) }))
2069
+ yield* t.post({ markdown: conformanceText(t.rule) + " reply" }, thread)
2070
+ const first = yield* t.collect(Stream.take(t.chat.history(thread, { direction: "forward" }), 1))
2071
+ yield* t.check(
2072
+ first[0]?.id === opener.id && ChatThread.equals(first[0].thread, t.thread),
2073
+ "the opener first, addressed to " + ChatThread.toString(t.thread),
2074
+ () =>
2075
+ first[0] === undefined
2076
+ ? "an empty history"
2077
+ : "message " + first[0].id + " in " + ChatThread.toString(first[0].thread)
2078
+ )
2079
+ }))
2080
+
2081
+ rule("message/threadStable", ["fetchMessage", "history", "startThread"], (t) =>
2082
+ Effect.gen(function*() {
2083
+ const event = yield* t.userPosts()
2084
+ const id = event.message.id
2085
+ const read = Effect.gen(function*() {
2086
+ const fetched = yield* t.call(t.chat.fetchMessage(t.thread, id))
2087
+ const history = yield* t.collect(Stream.take(t.chat.history(t.thread, { direction: "backward" }), 20))
2088
+ return [fetched, findIn(history, id)] as const
2089
+ })
2090
+ const before = yield* read
2091
+ const thread = yield* t.call(t.chat.startThread(t.thread, id, { name: conformanceText(t.rule) }))
2092
+ yield* t.post({ markdown: conformanceText(t.rule) + " reply" }, thread)
2093
+ const after = yield* read
2094
+ const reads = [event.message, ...before, ...after]
2095
+ yield* t.check(
2096
+ reads.every((message) => message !== undefined && ChatThread.equals(message.thread, t.thread)),
2097
+ "every read addressed to " + ChatThread.toString(t.thread),
2098
+ () => reads.map((message) => message === undefined ? "missing" : ChatThread.toString(message.thread)).join(", ")
2099
+ )
2100
+ }))
2101
+
2102
+ rule("inbound/fetchable", ["fetchMessage"], (t) =>
2103
+ Effect.gen(function*() {
2104
+ const event = yield* t.userPosts()
2105
+ const message = yield* t.call(t.chat.fetchMessage(event.thread, event.message.id))
2106
+ yield* t.check(sameMessage(event.message, message), "the inbound message", () => "a different message")
2107
+ }))
2108
+
2109
+ rule("inbound/notSelf", [], (t) =>
2110
+ Effect.gen(function*() {
2111
+ const event = yield* t.userPosts()
2112
+ yield* t.check(!event.message.author.isSelf, "author.isSelf false", () => "author.isSelf true")
2113
+ yield* checkEvent(event, { platform, parseMention }).pipe(
2114
+ Effect.mapError((error) => failure(t.rule, error.expected, error.actual, error.cause))
2115
+ )
2116
+ }))
2117
+
2118
+ rule("download/maxBytes", ["files", "download", "fetchMessage"], (t) =>
2119
+ Effect.gen(function*() {
2120
+ const file = conformanceFile(t.rule)
2121
+ const posted = yield* t.post({ files: [file] })
2122
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
2123
+ yield* t.check(message.attachments.length === 1, "one attachment", () => message.attachments.length + "")
2124
+ yield* t.expectReason(
2125
+ "TooLarge",
2126
+ Stream.runDrain(t.chat.download(t.thread, message.attachments[0], { maxBytes: 8 }))
2127
+ )
2128
+ }))
2129
+
2130
+ rule("startThread/idempotent", ["startThread"], (t) =>
2131
+ Effect.gen(function*() {
2132
+ const posted = yield* t.post({})
2133
+ const first = yield* t.call(t.chat.startThread(t.thread, posted.id, { name: conformanceText(t.rule) }))
2134
+ const second = yield* t.call(t.chat.startThread(t.thread, posted.id))
2135
+ yield* t.check(
2136
+ ChatThread.equals(first, second),
2137
+ ChatThread.toString(first),
2138
+ () => ChatThread.toString(second)
2139
+ )
2140
+ }))
2141
+
2142
+ rule("opener/noneOutsideThread", ["opener"], (t) =>
2143
+ Effect.flatMap(
2144
+ t.call(t.chat.opener(t.thread)),
2145
+ (opener) => t.check(Option.isNone(opener), "no opener", () => "an opener")
2146
+ ))
2147
+
2148
+ rule("descriptor/streamFitsMessage", ["nativeStream"], (t) => {
2149
+ const { messageLength, streamLength } = t.descriptor.limits
2150
+ return t.check(
2151
+ streamLength !== undefined && streamLength <= messageLength,
2152
+ "limits.streamLength at most " + messageLength,
2153
+ () => "limits.streamLength " + streamLength
2154
+ )
2155
+ })
2156
+
2157
+ const openStream = Effect.fnUntraced(function*(t: Tester, markdown: string) {
2158
+ const registry = yield* Registry
2159
+ const adapter = yield* t.call(registry.get(platform))
2160
+ const native = adapter.nativeStream!
2161
+ const event = yield* t.userPosts()
2162
+ const posted = yield* t.call(native.start(t.thread, { markdown, recipient: event.message.author.id }))
2163
+ t.track(posted)
2164
+ return { native, posted }
2165
+ })
2166
+
2167
+ rule("nativeStream/concatenates", ["nativeStream", "fetchMessage"], (t) =>
2168
+ Effect.gen(function*() {
2169
+ const first = conformanceText(t.rule) + " one"
2170
+ const { native, posted } = yield* openStream(t, first)
2171
+ const appended = yield* t.call(native.append(t.thread, posted.id, " two", { flush: true })).pipe(
2172
+ Effect.ensuring(Effect.ignore(native.stop(t.thread, posted.id, { end: "done" })))
2173
+ )
2174
+ yield* t.check(appended.state === "open" && appended.held === 0, "an open append holding nothing", () =>
2175
+ appended.state + " holding " + appended.held)
2176
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
2177
+ yield* t.check(message.text === first + " two", JSON.stringify(first + " two"), () =>
2178
+ JSON.stringify(message.text))
2179
+ }))
2180
+
2181
+ rule("nativeStream/appendAfterStop", ["nativeStream", "fetchMessage"], (t) =>
2182
+ Effect.gen(function*() {
2183
+ const first = conformanceText(t.rule)
2184
+ const { native, posted } = yield* openStream(t, first)
2185
+ yield* t.call(native.stop(t.thread, posted.id, { end: "done" }))
2186
+ const appended = yield* t.call(native.append(t.thread, posted.id, " after", { flush: true }))
2187
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
2188
+ yield* t.check(
2189
+ appended.state === "closed" && message.text === first,
2190
+ "closed, with the text unchanged",
2191
+ () => appended.state + " with " + JSON.stringify(message.text)
2192
+ )
2193
+ }))
2194
+
2195
+ // --- buttons and modals ----------------------------------------------------
2196
+
2197
+ const limit = (t: Tester, name: "actionsPerMessage" | "actionDataLength" | "modalMetadataLength" | "modalFields") =>
2198
+ Effect.flatMap(
2199
+ t.check(
2200
+ t.descriptor.limits[name] !== undefined,
2201
+ "limits." + name + " on a descriptor with its capability",
2202
+ () => "no limits." + name
2203
+ ),
2204
+ () => Effect.succeed(t.descriptor.limits[name]!)
2205
+ )
2206
+
2207
+ rule("actions/posts", ["buttons"], (t) =>
2208
+ Effect.gen(function*() {
2209
+ const posted = yield* t.post({ actions: [conformanceButton(t.rule)] })
2210
+ if (!t.has("fetchMessage")) return
2211
+ const message = yield* t.call(t.chat.fetchMessage(t.thread, posted.id))
2212
+ yield* t.check(message.id === posted.id, "the posted message " + posted.id, () => "message " + message.id)
2213
+ }))
2214
+
2215
+ rule("actions/tooMany", ["buttons"], (t) =>
2216
+ Effect.gen(function*() {
2217
+ const most = yield* limit(t, "actionsPerMessage")
2218
+ const actions = Array.from({ length: most + 1 }, (_, i): ChatUi.Button => ({
2219
+ _tag: "Button",
2220
+ id: "c" + i,
2221
+ label: "c" + i
2222
+ }))
2223
+ yield* t.expectReason(
2224
+ "TooLarge",
2225
+ t.chat.post(t.thread, { markdown: conformanceText(t.rule), actions }),
2226
+ (posted) => t.track(posted)
2227
+ )
2228
+ }))
2229
+
2230
+ rule("actions/dataTooLarge", ["buttons"], (t) =>
2231
+ Effect.gen(function*() {
2232
+ const most = yield* limit(t, "actionDataLength")
2233
+ const id = most >= "conformance".length ? "conformance" : "c".repeat(most + 1)
2234
+ const value = "x".repeat(most + 1 - id.length)
2235
+ const button: ChatUi.Button = { _tag: "Button", id, label: "c", ...(value === "" ? {} : { value }) }
2236
+ yield* t.expectReason(
2237
+ "TooLarge",
2238
+ t.chat.post(t.thread, { markdown: conformanceText(t.rule), actions: [button] }),
2239
+ (posted) => t.track(posted)
2240
+ )
2241
+ }))
2242
+
2243
+ rule("descriptor/measureAddsActions", ["buttons"], (t) =>
2244
+ Effect.gen(function*() {
2245
+ const { measure } = t.descriptor
2246
+ const button = conformanceButton(t.rule)
2247
+ const sets: ReadonlyArray<ReadonlyArray<ChatUi.Action>> = [
2248
+ [button],
2249
+ [{ ...button, value: "a < b & \u{1D400}" }],
2250
+ [button, { _tag: "LinkButton", label: "Link", url: "https://example.com/?a=1&b=<2>" }],
2251
+ [conformanceSelect(t.rule)]
2252
+ ]
2253
+ for (const markdown of measureSamples) {
2254
+ yield* t.check(measure(markdown, []) === measure(markdown), "measure(md, []) equal to measure(md)", () =>
2255
+ JSON.stringify(markdown) + " measures " + measure(markdown, []) + " and " + measure(markdown))
2256
+ for (const actions of sets) {
2257
+ const both = measure(markdown, actions)
2258
+ yield* t.check(
2259
+ both <= measure(markdown) + measure("", actions) && both >= measure(markdown),
2260
+ "measure(md) <= measure(md, actions) <= measure(md) + measure(\"\", actions)",
2261
+ () =>
2262
+ JSON.stringify(markdown) + " with " + actions.map((action) =>
2263
+ action._tag
2264
+ ) + " measures " + both
2265
+ )
2266
+ }
2267
+ }
2268
+ }))
2269
+
2270
+ rule("descriptor/measureFitsActions", ["buttons"], (t) =>
2271
+ Effect.gen(function*() {
2272
+ const { measure } = t.descriptor
2273
+ const most = t.descriptor.limits.messageLength
2274
+ // A short label, so a platform whose labels are short still takes the button.
2275
+ const actions = [{ ...conformanceButton(t.rule), label: "fits", value: "x" }]
2276
+ const length = largestFitting(most, (n) => measure("x".repeat(n), actions) <= most)
2277
+ yield* t.post({ markdown: "x".repeat(length), actions })
2278
+ }))
2279
+
2280
+ const interactions = options.interactions
2281
+ if (interactions !== undefined) {
2282
+ rule("actions/valueRoundTrips", ["buttons"], (t) =>
2283
+ Effect.gen(function*() {
2284
+ const buttons = valueCases.map(({ schema }, i) =>
2285
+ ChatInteraction.button("v" + i, { label: "v" + i, value: schema })
2286
+ )
2287
+ const posted = yield* t.post({ actions: buttons.map((button, i) => button.of(valueCases[i].value)) })
2288
+ for (const [i, { schema, value }] of valueCases.entries()) {
2289
+ yield* t.click(posted.id, "v" + i)
2290
+ const click = t.recording.clicks[i]
2291
+ const decoded = click?._tag === "ButtonClicked" && click.value !== undefined
2292
+ ? ChatInteraction.decodeValue(schema, click.value)
2293
+ : Option.none()
2294
+ yield* t.check(
2295
+ Option.isSome(decoded) && sameValue(decoded.value, value),
2296
+ "a value that decodes to " + canonicalJson(value),
2297
+ () => click === undefined ? "no click" : "value " + JSON.stringify(click.value)
2298
+ )
2299
+ }
2300
+ }))
2301
+
2302
+ rule("actions/absentValue", ["buttons"], (t) =>
2303
+ Effect.gen(function*() {
2304
+ const posted = yield* t.post({ actions: [conformanceButton(t.rule)] })
2305
+ yield* t.click(posted.id, "conformance")
2306
+ const click = t.recording.clicks[0]
2307
+ yield* t.check(
2308
+ click?._tag === "ButtonClicked" && !("value" in click),
2309
+ "a click with no value key",
2310
+ () => click === undefined ? "no click" : "value " + JSON.stringify(click.value)
2311
+ )
2312
+ }))
2313
+
2314
+ rule("actions/origin", ["buttons"], (t) =>
2315
+ Effect.gen(function*() {
2316
+ const posted = yield* t.post({ actions: [conformanceButton(t.rule)] })
2317
+ yield* t.click(posted.id, "conformance")
2318
+ const click = t.recording.clicks[0]
2319
+ yield* t.check(
2320
+ click !== undefined && click.messageId === posted.id && ChatThread.equals(click.thread, posted.thread),
2321
+ "a click on " + posted.id + " in " + ChatThread.toString(posted.thread),
2322
+ () => click === undefined ? "no click" : click.messageId + " in " + ChatThread.toString(click.thread)
2323
+ )
2324
+ yield* t.checkInteraction(click)
2325
+ }))
2326
+
2327
+ rule("actions/selectValue", ["selects"], (t) =>
2328
+ Effect.gen(function*() {
2329
+ const posted = yield* t.post({ actions: [conformanceSelect(t.rule)] })
2330
+ yield* t.click(posted.id, "conformance", { option: "b" })
2331
+ const event = t.recording.clicks[0]
2332
+ yield* t.check(
2333
+ event?._tag === "SelectChanged" && event.value === "b",
2334
+ "SelectChanged with value b",
2335
+ () => event === undefined ? "no click" : event._tag + " with value " + JSON.stringify(event.value)
2336
+ )
2337
+ yield* t.checkInteraction(event)
2338
+ }))
2339
+
2340
+ rule("edit/removesActions", ["buttons", "edit"], (t) =>
2341
+ Effect.gen(function*() {
2342
+ const posted = yield* t.post({ actions: [conformanceButton(t.rule)] })
2343
+ yield* t.call(t.chat.edit(t.thread, posted.id, { markdown: conformanceText(t.rule) + " edited" }))
2344
+ const exit = yield* t.clickExit(posted.id, "conformance")
2345
+ const error = Exit.findErrorOption(exit)
2346
+ yield* t.check(
2347
+ Option.isSome(error) && error.value._tag === "NoSuchElement",
2348
+ "NoSuchElement",
2349
+ () => describeExit(exit)
2350
+ )
2351
+ }))
2352
+
2353
+ rule("edit/addsActions", ["buttons", "edit"], (t) =>
2354
+ Effect.gen(function*() {
2355
+ const posted = yield* t.post({})
2356
+ yield* t.call(t.chat.edit(t.thread, posted.id, {
2357
+ markdown: conformanceText(t.rule) + " edited",
2358
+ actions: [conformanceButton(t.rule)]
2359
+ }))
2360
+ yield* t.click(posted.id, "conformance")
2361
+ yield* t.check(t.recording.clicks.length === 1, "one click", () => t.recording.clicks.length + " clicks")
2362
+ }))
2363
+
2364
+ rule("modal/origin", ["modals"], (t) =>
2365
+ Effect.gen(function*() {
2366
+ const posted = yield* t.openModal(probeModal.open())
2367
+ yield* t.submit({ answer: "conformance" })
2368
+ const submit = t.recording.submits[0]
2369
+ yield* t.check(
2370
+ submit !== undefined && submit.messageId === posted.id && ChatThread.equals(submit.thread, posted.thread),
2371
+ "a submit from " + posted.id + " in " + ChatThread.toString(posted.thread),
2372
+ () => submit === undefined ? "no submit" : submit.messageId + " in " + ChatThread.toString(submit.thread)
2373
+ )
2374
+ yield* t.checkInteraction(submit)
2375
+ }))
2376
+
2377
+ rule("modal/metadataRoundTrips", ["modals"], (t) =>
2378
+ Effect.gen(function*() {
2379
+ const Metadata = Schema.Struct({ version: Schema.String })
2380
+ const withMetadata = ChatInteraction.modal("conformance-meta", {
2381
+ title: "Conformance",
2382
+ metadata: Metadata,
2383
+ fields: { answer: ChatInteraction.textInput({ label: "Answer" }) }
2384
+ })
2385
+ const value = { version: "v1 < \u{1D400}" }
2386
+ yield* t.openModal(withMetadata.open({ metadata: value }))
2387
+ yield* t.submit({ answer: "conformance" })
2388
+ yield* t.openModal(probeModal.open())
2389
+ yield* t.submit({ answer: "conformance" })
2390
+ const [first, second] = t.recording.submits
2391
+ const decoded = first?.metadata === undefined
2392
+ ? Option.none()
2393
+ : ChatInteraction.decodeValue(Metadata, first.metadata)
2394
+ yield* t.check(
2395
+ Option.isSome(decoded) && sameValue(decoded.value, value),
2396
+ "metadata that decodes to " + canonicalJson(value),
2397
+ () => first === undefined ? "no submit" : "metadata " + JSON.stringify(first.metadata)
2398
+ )
2399
+ yield* t.check(
2400
+ second !== undefined && !("metadata" in second),
2401
+ "a submit with no metadata key",
2402
+ () => second === undefined ? "no submit" : "metadata " + JSON.stringify(second.metadata)
2403
+ )
2404
+ }))
2405
+
2406
+ const refusedTooLarge = Effect.fnUntraced(function*(t: Tester) {
2407
+ yield* t.submit({})
2408
+ const refusal = t.recording.refused[0]
2409
+ yield* t.check(
2410
+ refusal?.reason._tag === "TooLarge" && t.recording.submits.length === 0,
2411
+ "a refusal TooLarge and no modal",
2412
+ () =>
2413
+ (refusal === undefined ? "no refusal" : "a refusal " + describeError(refusal)) +
2414
+ (t.recording.submits.length === 0 ? "" : " and a submit")
2415
+ )
2416
+ })
2417
+
2418
+ rule("modal/metadataTooLarge", ["modals"], (t) =>
2419
+ Effect.gen(function*() {
2420
+ const most = yield* limit(t, "modalMetadataLength")
2421
+ const id = "conformance-big"
2422
+ const big = ChatInteraction.modal(id, {
2423
+ title: "Conformance",
2424
+ metadata: Schema.String,
2425
+ fields: { answer: ChatInteraction.textInput({ label: "Answer" }) }
2426
+ })
2427
+ yield* t.openModal(big.open({ metadata: "x".repeat(Math.max(0, most + 1 - id.length)) }))
2428
+ yield* refusedTooLarge(t)
2429
+ }))
2430
+
2431
+ rule("modal/tooManyFields", ["modals"], (t) =>
2432
+ Effect.gen(function*() {
2433
+ const most = yield* limit(t, "modalFields")
2434
+ const fields: Record<string, ChatInteraction.TextInput> = {}
2435
+ for (let i = 0; i <= most; i++) fields["f" + i] = ChatInteraction.textInput({ label: "F" + i })
2436
+ yield* t.openModal(ChatInteraction.modal("conformance-many", { title: "Conformance", fields }).open())
2437
+ yield* refusedTooLarge(t)
2438
+ }))
2439
+
2440
+ // `modalErrors` means nothing without `modals`, so the rule needs both.
2441
+ rule("modal/errorsKeepOpen", ["modals", "modalErrors"], (t) =>
2442
+ Effect.gen(function*() {
2443
+ t.recording.onSubmit = () =>
2444
+ t.recording.submits.length === 1 ? ChatInteraction.errors({ answer: "Again." }) : ChatInteraction.close
2445
+ yield* t.openModal(probeModal.open())
2446
+ yield* t.submit({ answer: "first" })
2447
+ yield* t.submit({ answer: "second" })
2448
+ const second = t.recording.submits[1]
2449
+ yield* t.check(
2450
+ second !== undefined && second.id === "conformance-modal",
2451
+ "a second submit of the same modal",
2452
+ () => t.recording.submits.length + " submits"
2453
+ )
2454
+ }))
2455
+
2456
+ rule("unsupported/modals", ["buttons"], (t) => t.probe("modals"))
2457
+ }
2458
+
2459
+ if (interactions?.command !== undefined) {
2460
+ const commandId = "conformance-command"
2461
+
2462
+ rule("command/arrives", ["commands"], (t) =>
2463
+ Effect.gen(function*() {
2464
+ const text = "deploy v1 < \u{1D400}"
2465
+ yield* t.command(commandId, { text })
2466
+ const command = t.recording.commands[0]
2467
+ yield* t.check(
2468
+ command !== undefined && command.id === commandId && command.text === text &&
2469
+ ChatThread.equals(command.thread, t.thread),
2470
+ "command " + commandId + " with text " + JSON.stringify(text) + " in " + ChatThread.toString(t.thread),
2471
+ () =>
2472
+ command === undefined
2473
+ ? "no command"
2474
+ : "command " + command.id + " with text " + JSON.stringify(command.text) + " in " +
2475
+ ChatThread.toString(command.thread)
2476
+ )
2477
+ yield* t.checkInteraction(command)
2478
+ }))
2479
+
2480
+ rule("command/emptyText", ["commands"], (t) =>
2481
+ Effect.gen(function*() {
2482
+ yield* t.command(commandId)
2483
+ const command = t.recording.commands[0]
2484
+ yield* t.check(
2485
+ command !== undefined && command.text === "",
2486
+ "a command with text \"\"",
2487
+ () => command === undefined ? "no command" : "text " + JSON.stringify(command.text)
2488
+ )
2489
+ }))
2490
+
2491
+ const noRefusal = (t: Tester) =>
2492
+ t.check(
2493
+ t.recording.commands.length === 1 && t.recording.refused.length === 0,
2494
+ "one command and no refusal",
2495
+ () =>
2496
+ t.recording.commands.length + " commands and refusals " +
2497
+ (t.recording.refused.length === 0 ? "none" : t.recording.refused.map(describeError).join(", "))
2498
+ )
2499
+
2500
+ rule("command/responds", ["commands"], (t) =>
2501
+ Effect.gen(function*() {
2502
+ t.recording.onCommand = () =>
2503
+ ChatInteraction.respond({ markdown: conformanceText(t.rule), visibility: "public" })
2504
+ yield* t.command(commandId)
2505
+ yield* noRefusal(t)
2506
+ }))
2507
+
2508
+ rule("command/respondsPrivately", ["commands", "ephemeral"], (t) =>
2509
+ Effect.gen(function*() {
2510
+ t.recording.onCommand = () => ChatInteraction.respond({ markdown: conformanceText(t.rule) })
2511
+ yield* t.command(commandId)
2512
+ yield* noRefusal(t)
2513
+ }))
2514
+
2515
+ rule("command/respondTooLarge", ["commands"], (t) =>
2516
+ Effect.gen(function*() {
2517
+ const markdown = "x".repeat(t.descriptor.limits.messageLength + 1)
2518
+ t.recording.onCommand = () => ChatInteraction.respond({ markdown, visibility: "public" })
2519
+ yield* t.command(commandId)
2520
+ const refusal = t.recording.refused[0]
2521
+ yield* t.check(
2522
+ refusal !== undefined && textTooLarge.test(refusal.reason),
2523
+ "a refusal " + textTooLarge.expected,
2524
+ () => refusal === undefined ? "no refusal" : "a refusal " + describeError(refusal)
2525
+ )
2526
+ }))
2527
+
2528
+ rule("command/followUp", ["commands"], (t) =>
2529
+ Effect.gen(function*() {
2530
+ t.recording.onCommand = (command) => ChatInteraction.defer(command, { visibility: "public" })
2531
+ yield* t.command(commandId)
2532
+ const deferred = t.recording.commandReplies[0]
2533
+ if (deferred?._tag !== "Defer") {
2534
+ return yield* Effect.fail(
2535
+ failure(t.rule, "a Defer reply", deferred === undefined ? "no command" : deferred._tag)
2536
+ )
2537
+ }
2538
+ yield* noRefusal(t)
2539
+ yield* t.call(t.chat.followUp(deferred, { markdown: conformanceText(t.rule) }))
2540
+ }))
2541
+
2542
+ rule("command/modalOrigin", ["commands", "modals"], (t) =>
2543
+ Effect.gen(function*() {
2544
+ t.recording.onCommand = () => probeModal.open()
2545
+ yield* t.command(commandId)
2546
+ yield* t.submit({ answer: "conformance" })
2547
+ const submit = t.recording.submits[0]
2548
+ yield* t.check(
2549
+ submit !== undefined && submit.messageId === undefined && ChatThread.equals(submit.thread, t.thread),
2550
+ "a submit in " + ChatThread.toString(t.thread) + " with no messageId",
2551
+ () =>
2552
+ submit === undefined
2553
+ ? "no submit"
2554
+ : "a submit in " + ChatThread.toString(submit.thread) + " with messageId " + submit.messageId
2555
+ )
2556
+ yield* t.checkInteraction(submit)
2557
+ }))
2558
+
2559
+ rule("unsupported/ephemeral", ["commands"], (t) => t.probe("ephemeral"))
2560
+ }
2561
+
2562
+ for (const capability of allCapabilities) {
2563
+ if (capability === "modals" || capability === "modalErrors" || capability === "ephemeral") continue
2564
+ rule("unsupported/" + capability, [], (t) => t.probe(capability))
2565
+ }
2566
+
2567
+ const failNext = options.failNext
2568
+ if (failNext !== undefined) {
2569
+ rule("retries/noneWithoutRetries", [], (t) =>
2570
+ Effect.gen(function*() {
2571
+ yield* failNext("post", new RateLimited({}))
2572
+ yield* t.expectReason(
2573
+ "RateLimited",
2574
+ Chat.withoutRetries(t.chat.post(t.thread, { markdown: conformanceText(t.rule) })),
2575
+ (posted) => t.track(posted)
2576
+ )
2577
+ }))
2578
+
2579
+ rule("retries/retrySafe", [], (t) =>
2580
+ Effect.gen(function*() {
2581
+ const retryAfter = Duration.millis(100)
2582
+ yield* failNext("post", new RateLimited({ retryAfter }))
2583
+ const start = yield* DateTime.now
2584
+ yield* t.post({})
2585
+ const elapsed = DateTime.distance(start, yield* DateTime.now)
2586
+ yield* t.check(
2587
+ // One millisecond of slack: a timer and the clock round to whole milliseconds apart.
2588
+ Duration.toMillis(elapsed) + 1 >= Duration.toMillis(retryAfter),
2589
+ "a retry after " + Duration.format(retryAfter),
2590
+ () => "a retry after " + Duration.format(elapsed)
2591
+ )
2592
+ }))
2593
+
2594
+ rule("retries/neverUncertain", [], (t) =>
2595
+ Effect.gen(function*() {
2596
+ yield* failNext("post", new Transport({ retry: "uncertain" }))
2597
+ yield* t.expectReason(
2598
+ "Transport",
2599
+ t.chat.post(t.thread, { markdown: conformanceText(t.rule) }),
2600
+ (posted) => t.track(posted)
2601
+ )
2602
+ }))
2603
+ }
2604
+
2605
+ return rules
2606
+ }