effect 4.1.3 → 4.1.5

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 (782) 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/Chunk.d.ts +5 -0
  17. package/dist/Chunk.d.ts.map +1 -1
  18. package/dist/Chunk.js +7 -2
  19. package/dist/Chunk.js.map +1 -1
  20. package/dist/Clock.d.ts +5 -2
  21. package/dist/Clock.d.ts.map +1 -1
  22. package/dist/Clock.js +2 -1
  23. package/dist/Clock.js.map +1 -1
  24. package/dist/Codegen.d.ts +295 -0
  25. package/dist/Codegen.d.ts.map +1 -0
  26. package/dist/Codegen.js +521 -0
  27. package/dist/Codegen.js.map +1 -0
  28. package/dist/Config.d.ts +31 -2
  29. package/dist/Config.d.ts.map +1 -1
  30. package/dist/Config.js +12 -1
  31. package/dist/Config.js.map +1 -1
  32. package/dist/ConfigProvider.d.ts +11 -1
  33. package/dist/ConfigProvider.d.ts.map +1 -1
  34. package/dist/ConfigProvider.js +17 -6
  35. package/dist/ConfigProvider.js.map +1 -1
  36. package/dist/Effect.d.ts +869 -109
  37. package/dist/Effect.d.ts.map +1 -1
  38. package/dist/Effect.js +400 -47
  39. package/dist/Effect.js.map +1 -1
  40. package/dist/Equivalence.d.ts +11 -9
  41. package/dist/Equivalence.d.ts.map +1 -1
  42. package/dist/Equivalence.js +15 -12
  43. package/dist/Equivalence.js.map +1 -1
  44. package/dist/Fiber.d.ts +58 -8
  45. package/dist/Fiber.d.ts.map +1 -1
  46. package/dist/Fiber.js +28 -4
  47. package/dist/Fiber.js.map +1 -1
  48. package/dist/FiberHandle.d.ts +81 -10
  49. package/dist/FiberHandle.d.ts.map +1 -1
  50. package/dist/FiberHandle.js +40 -8
  51. package/dist/FiberHandle.js.map +1 -1
  52. package/dist/FiberMap.d.ts +80 -10
  53. package/dist/FiberMap.d.ts.map +1 -1
  54. package/dist/FiberMap.js +37 -6
  55. package/dist/FiberMap.js.map +1 -1
  56. package/dist/FiberSet.d.ts +93 -8
  57. package/dist/FiberSet.d.ts.map +1 -1
  58. package/dist/FiberSet.js +46 -4
  59. package/dist/FiberSet.js.map +1 -1
  60. package/dist/Formatter.d.ts +2 -0
  61. package/dist/Formatter.d.ts.map +1 -1
  62. package/dist/Formatter.js +2 -0
  63. package/dist/Formatter.js.map +1 -1
  64. package/dist/LayerMap.d.ts +12 -3
  65. package/dist/LayerMap.d.ts.map +1 -1
  66. package/dist/LayerMap.js +12 -2
  67. package/dist/LayerMap.js.map +1 -1
  68. package/dist/LayerRef.d.ts +2 -2
  69. package/dist/Match.d.ts +12 -0
  70. package/dist/Match.d.ts.map +1 -1
  71. package/dist/Match.js +16 -0
  72. package/dist/Match.js.map +1 -1
  73. package/dist/Metric.js +1 -1
  74. package/dist/Metric.js.map +1 -1
  75. package/dist/Option.d.ts +4 -1
  76. package/dist/Option.d.ts.map +1 -1
  77. package/dist/Option.js +6 -2
  78. package/dist/Option.js.map +1 -1
  79. package/dist/Order.d.ts +7 -5
  80. package/dist/Order.d.ts.map +1 -1
  81. package/dist/Order.js +7 -2
  82. package/dist/Order.js.map +1 -1
  83. package/dist/Pool.d.ts +4 -3
  84. package/dist/Pool.d.ts.map +1 -1
  85. package/dist/Pool.js +21 -18
  86. package/dist/Pool.js.map +1 -1
  87. package/dist/Predicate.d.ts +4 -1
  88. package/dist/Predicate.d.ts.map +1 -1
  89. package/dist/Predicate.js +5 -1
  90. package/dist/Predicate.js.map +1 -1
  91. package/dist/Queue.d.ts +69 -22
  92. package/dist/Queue.d.ts.map +1 -1
  93. package/dist/Queue.js +40 -18
  94. package/dist/Queue.js.map +1 -1
  95. package/dist/Rational.d.ts +179 -0
  96. package/dist/Rational.d.ts.map +1 -1
  97. package/dist/Rational.js +63 -0
  98. package/dist/Rational.js.map +1 -1
  99. package/dist/Request.d.ts +20 -0
  100. package/dist/Request.d.ts.map +1 -1
  101. package/dist/Request.js +20 -0
  102. package/dist/Request.js.map +1 -1
  103. package/dist/Result.d.ts +3 -1
  104. package/dist/Result.d.ts.map +1 -1
  105. package/dist/Result.js +5 -2
  106. package/dist/Result.js.map +1 -1
  107. package/dist/Schema.d.ts +49 -19
  108. package/dist/Schema.d.ts.map +1 -1
  109. package/dist/Schema.js +44 -27
  110. package/dist/Schema.js.map +1 -1
  111. package/dist/SchemaAST.d.ts.map +1 -1
  112. package/dist/SchemaAST.js +11 -4
  113. package/dist/SchemaAST.js.map +1 -1
  114. package/dist/SchemaGetter.d.ts +5 -6
  115. package/dist/SchemaGetter.d.ts.map +1 -1
  116. package/dist/SchemaGetter.js +14 -10
  117. package/dist/SchemaGetter.js.map +1 -1
  118. package/dist/SchemaRepresentation.d.ts +36 -67
  119. package/dist/SchemaRepresentation.d.ts.map +1 -1
  120. package/dist/SchemaRepresentation.js +5 -30
  121. package/dist/SchemaRepresentation.js.map +1 -1
  122. package/dist/SchemaTransformation.d.ts +11 -10
  123. package/dist/SchemaTransformation.d.ts.map +1 -1
  124. package/dist/SchemaTransformation.js +12 -11
  125. package/dist/SchemaTransformation.js.map +1 -1
  126. package/dist/Scope.d.ts +12 -6
  127. package/dist/Scope.d.ts.map +1 -1
  128. package/dist/Scope.js +12 -6
  129. package/dist/Scope.js.map +1 -1
  130. package/dist/ScopedCache.d.ts.map +1 -1
  131. package/dist/ScopedCache.js +2 -1
  132. package/dist/ScopedCache.js.map +1 -1
  133. package/dist/Semaphore.d.ts.map +1 -1
  134. package/dist/Semaphore.js +18 -4
  135. package/dist/Semaphore.js.map +1 -1
  136. package/dist/Stream.d.ts.map +1 -1
  137. package/dist/Stream.js +55 -14
  138. package/dist/Stream.js.map +1 -1
  139. package/dist/String.d.ts +57 -3
  140. package/dist/String.d.ts.map +1 -1
  141. package/dist/String.js +62 -4
  142. package/dist/String.js.map +1 -1
  143. package/dist/Struct.d.ts +135 -1
  144. package/dist/Struct.d.ts.map +1 -1
  145. package/dist/Struct.js +64 -5
  146. package/dist/Struct.js.map +1 -1
  147. package/dist/TextDiff.d.ts +105 -0
  148. package/dist/TextDiff.d.ts.map +1 -1
  149. package/dist/TextDiff.js +137 -24
  150. package/dist/TextDiff.js.map +1 -1
  151. package/dist/TxPriorityQueue.js +2 -2
  152. package/dist/TxPriorityQueue.js.map +1 -1
  153. package/dist/ai/Chat.d.ts +1 -1
  154. package/dist/ai/Chat.d.ts.map +1 -1
  155. package/dist/ai/Chat.js.map +1 -1
  156. package/dist/ai/LanguageModel.d.ts +23 -4
  157. package/dist/ai/LanguageModel.d.ts.map +1 -1
  158. package/dist/ai/LanguageModel.js +9 -5
  159. package/dist/ai/LanguageModel.js.map +1 -1
  160. package/dist/ai/McpClient.d.ts +0 -5
  161. package/dist/ai/McpClient.d.ts.map +1 -1
  162. package/dist/ai/McpClient.js +1 -11
  163. package/dist/ai/McpClient.js.map +1 -1
  164. package/dist/ai/McpSchema.d.ts +128 -128
  165. package/dist/ai/McpSchema.d.ts.map +1 -1
  166. package/dist/ai/McpServer.d.ts +48 -5
  167. package/dist/ai/McpServer.d.ts.map +1 -1
  168. package/dist/ai/McpServer.js +136 -19
  169. package/dist/ai/McpServer.js.map +1 -1
  170. package/dist/ai/Tool.d.ts +3 -2
  171. package/dist/ai/Tool.d.ts.map +1 -1
  172. package/dist/ai/Tool.js +3 -2
  173. package/dist/ai/Tool.js.map +1 -1
  174. package/dist/ai/Toolkit.d.ts.map +1 -1
  175. package/dist/ai/Toolkit.js +5 -1
  176. package/dist/ai/Toolkit.js.map +1 -1
  177. package/dist/ai/WorkloadIdentity.d.ts +111 -0
  178. package/dist/ai/WorkloadIdentity.d.ts.map +1 -0
  179. package/dist/ai/WorkloadIdentity.js +227 -0
  180. package/dist/ai/WorkloadIdentity.js.map +1 -0
  181. package/dist/ai/index.d.ts +5 -0
  182. package/dist/ai/index.d.ts.map +1 -1
  183. package/dist/ai/index.js +5 -0
  184. package/dist/ai/index.js.map +1 -1
  185. package/dist/ai/internal/mcpProtocol/v2024_11_05.js +3 -1
  186. package/dist/ai/internal/mcpProtocol/v2024_11_05.js.map +1 -1
  187. package/dist/ai/internal/mcpProtocol/v2025_03_26.js +3 -1
  188. package/dist/ai/internal/mcpProtocol/v2025_03_26.js.map +1 -1
  189. package/dist/ai/internal/mcpProtocol/v2025_06_18.js +3 -1
  190. package/dist/ai/internal/mcpProtocol/v2025_06_18.js.map +1 -1
  191. package/dist/ai/internal/mcpProtocol/v2025_11_25.js +3 -1
  192. package/dist/ai/internal/mcpProtocol/v2025_11_25.js.map +1 -1
  193. package/dist/ai/internal/mcpRuntime.js +2 -4
  194. package/dist/ai/internal/mcpRuntime.js.map +1 -1
  195. package/dist/ai/internal/mcpSkills.js +80 -2
  196. package/dist/ai/internal/mcpSkills.js.map +1 -1
  197. package/dist/ai/internal/structured-output.js +5 -1
  198. package/dist/ai/internal/structured-output.js.map +1 -1
  199. package/dist/chat/Chat.d.ts +90 -0
  200. package/dist/chat/Chat.d.ts.map +1 -0
  201. package/dist/chat/Chat.js +127 -0
  202. package/dist/chat/Chat.js.map +1 -0
  203. package/dist/chat/ChatAdapter.d.ts +386 -0
  204. package/dist/chat/ChatAdapter.d.ts.map +1 -0
  205. package/dist/chat/ChatAdapter.js +110 -0
  206. package/dist/chat/ChatAdapter.js.map +1 -0
  207. package/dist/chat/ChatError.d.ts +500 -0
  208. package/dist/chat/ChatError.d.ts.map +1 -0
  209. package/dist/chat/ChatError.js +521 -0
  210. package/dist/chat/ChatError.js.map +1 -0
  211. package/dist/chat/ChatEvent.d.ts +321 -0
  212. package/dist/chat/ChatEvent.d.ts.map +1 -0
  213. package/dist/chat/ChatEvent.js +163 -0
  214. package/dist/chat/ChatEvent.js.map +1 -0
  215. package/dist/chat/ChatHandler.d.ts +81 -0
  216. package/dist/chat/ChatHandler.d.ts.map +1 -0
  217. package/dist/chat/ChatHandler.js +85 -0
  218. package/dist/chat/ChatHandler.js.map +1 -0
  219. package/dist/chat/ChatInteraction.d.ts +1519 -0
  220. package/dist/chat/ChatInteraction.d.ts.map +1 -0
  221. package/dist/chat/ChatInteraction.js +1052 -0
  222. package/dist/chat/ChatInteraction.js.map +1 -0
  223. package/dist/chat/ChatMarkdown.d.ts +280 -0
  224. package/dist/chat/ChatMarkdown.d.ts.map +1 -0
  225. package/dist/chat/ChatMarkdown.js +1172 -0
  226. package/dist/chat/ChatMarkdown.js.map +1 -0
  227. package/dist/chat/ChatMessage.d.ts +224 -0
  228. package/dist/chat/ChatMessage.d.ts.map +1 -0
  229. package/dist/chat/ChatMessage.js +172 -0
  230. package/dist/chat/ChatMessage.js.map +1 -0
  231. package/dist/chat/ChatTest.d.ts +407 -0
  232. package/dist/chat/ChatTest.d.ts.map +1 -0
  233. package/dist/chat/ChatTest.js +2145 -0
  234. package/dist/chat/ChatTest.js.map +1 -0
  235. package/dist/chat/ChatThread.d.ts +92 -0
  236. package/dist/chat/ChatThread.d.ts.map +1 -0
  237. package/dist/chat/ChatThread.js +116 -0
  238. package/dist/chat/ChatThread.js.map +1 -0
  239. package/dist/chat/ChatUi.d.ts +362 -0
  240. package/dist/chat/ChatUi.d.ts.map +1 -0
  241. package/dist/chat/ChatUi.js +209 -0
  242. package/dist/chat/ChatUi.js.map +1 -0
  243. package/dist/chat/index.d.ts +60 -0
  244. package/dist/chat/index.d.ts.map +1 -0
  245. package/dist/chat/index.js +61 -0
  246. package/dist/chat/index.js.map +1 -0
  247. package/dist/chat/internal/retries.d.ts +2 -0
  248. package/dist/chat/internal/retries.d.ts.map +1 -0
  249. package/dist/chat/internal/retries.js +7 -0
  250. package/dist/chat/internal/retries.js.map +1 -0
  251. package/dist/cli/CliOutput.d.ts.map +1 -1
  252. package/dist/cli/CliOutput.js +6 -7
  253. package/dist/cli/CliOutput.js.map +1 -1
  254. package/dist/cli/Command.d.ts +20 -2
  255. package/dist/cli/Command.d.ts.map +1 -1
  256. package/dist/cli/Command.js +7 -1
  257. package/dist/cli/Command.js.map +1 -1
  258. package/dist/cli/Prompt.d.ts +5 -6
  259. package/dist/cli/Prompt.d.ts.map +1 -1
  260. package/dist/cli/Prompt.js +9 -4
  261. package/dist/cli/Prompt.js.map +1 -1
  262. package/dist/cli/internal/command.d.ts +1 -1
  263. package/dist/cli/internal/command.d.ts.map +1 -1
  264. package/dist/cli/internal/config.d.ts +1 -1
  265. package/dist/cli/internal/config.d.ts.map +1 -1
  266. package/dist/cli/internal/config.js +3 -3
  267. package/dist/cli/internal/config.js.map +1 -1
  268. package/dist/cli/internal/lexer.js +13 -0
  269. package/dist/cli/internal/lexer.js.map +1 -1
  270. package/dist/cli/internal/parser.js +23 -16
  271. package/dist/cli/internal/parser.js.map +1 -1
  272. package/dist/cli/internal/wizard.d.ts.map +1 -1
  273. package/dist/cli/internal/wizard.js +4 -0
  274. package/dist/cli/internal/wizard.js.map +1 -1
  275. package/dist/cluster/ClusterCron.d.ts +21 -1
  276. package/dist/cluster/ClusterCron.d.ts.map +1 -1
  277. package/dist/cluster/ClusterCron.js +24 -6
  278. package/dist/cluster/ClusterCron.js.map +1 -1
  279. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  280. package/dist/cluster/ClusterWorkflowEngine.js +30 -22
  281. package/dist/cluster/ClusterWorkflowEngine.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 +13 -15
  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/entityManager.js +12 -8
  295. package/dist/cluster/internal/entityManager.js.map +1 -1
  296. package/dist/cluster/internal/entityReaper.js +1 -1
  297. package/dist/cluster/internal/entityReaper.js.map +1 -1
  298. package/dist/crypto/Kdf.d.ts +2 -1
  299. package/dist/crypto/Kdf.d.ts.map +1 -1
  300. package/dist/crypto/Kdf.js +2 -1
  301. package/dist/crypto/Kdf.js.map +1 -1
  302. package/dist/crypto/Password.d.ts +162 -0
  303. package/dist/crypto/Password.d.ts.map +1 -0
  304. package/dist/crypto/Password.js +217 -0
  305. package/dist/crypto/Password.js.map +1 -0
  306. package/dist/crypto/index.d.ts +5 -0
  307. package/dist/crypto/index.d.ts.map +1 -1
  308. package/dist/crypto/index.js +5 -0
  309. package/dist/crypto/index.js.map +1 -1
  310. package/dist/encoding/Base64.d.ts +63 -0
  311. package/dist/encoding/Base64.d.ts.map +1 -1
  312. package/dist/encoding/Base64.js +77 -0
  313. package/dist/encoding/Base64.js.map +1 -1
  314. package/dist/encoding/Base64Url.d.ts +1 -0
  315. package/dist/encoding/Base64Url.d.ts.map +1 -1
  316. package/dist/encoding/Base64Url.js +1 -0
  317. package/dist/encoding/Base64Url.js.map +1 -1
  318. package/dist/encoding/Csv.d.ts.map +1 -1
  319. package/dist/encoding/Csv.js +44 -16
  320. package/dist/encoding/Csv.js.map +1 -1
  321. package/dist/encoding/Hex.d.ts +5 -0
  322. package/dist/encoding/Hex.d.ts.map +1 -1
  323. package/dist/encoding/Hex.js +5 -0
  324. package/dist/encoding/Hex.js.map +1 -1
  325. package/dist/encoding/SchemaBinary.d.ts.map +1 -1
  326. package/dist/encoding/SchemaBinary.js +13 -124
  327. package/dist/encoding/SchemaBinary.js.map +1 -1
  328. package/dist/encoding/Sse.d.ts +1 -0
  329. package/dist/encoding/Sse.d.ts.map +1 -1
  330. package/dist/encoding/Sse.js +7 -5
  331. package/dist/encoding/Sse.js.map +1 -1
  332. package/dist/encoding/Xml.d.ts +117 -11
  333. package/dist/encoding/Xml.d.ts.map +1 -1
  334. package/dist/encoding/Xml.js +332 -42
  335. package/dist/encoding/Xml.js.map +1 -1
  336. package/dist/eventlog/EventJournal.d.ts.map +1 -1
  337. package/dist/eventlog/EventJournal.js +3 -8
  338. package/dist/eventlog/EventJournal.js.map +1 -1
  339. package/dist/eventlog/SqlEventLogServerEncrypted.js +6 -8
  340. package/dist/eventlog/SqlEventLogServerEncrypted.js.map +1 -1
  341. package/dist/http/FindMyWay/internal/router.js +163 -116
  342. package/dist/http/FindMyWay/internal/router.js.map +1 -1
  343. package/dist/http/FindMyWay.d.ts +99 -0
  344. package/dist/http/FindMyWay.d.ts.map +1 -1
  345. package/dist/http/FindMyWay.js +39 -0
  346. package/dist/http/FindMyWay.js.map +1 -1
  347. package/dist/http/HttpClient.d.ts.map +1 -1
  348. package/dist/http/HttpClient.js +1 -1
  349. package/dist/http/HttpClient.js.map +1 -1
  350. package/dist/http/HttpMiddleware.d.ts.map +1 -1
  351. package/dist/http/HttpMiddleware.js +18 -9
  352. package/dist/http/HttpMiddleware.js.map +1 -1
  353. package/dist/http/HttpRouter.d.ts +49 -1
  354. package/dist/http/HttpRouter.d.ts.map +1 -1
  355. package/dist/http/HttpRouter.js +70 -20
  356. package/dist/http/HttpRouter.js.map +1 -1
  357. package/dist/http/HttpServerResponse.d.ts.map +1 -1
  358. package/dist/http/HttpServerResponse.js +24 -58
  359. package/dist/http/HttpServerResponse.js.map +1 -1
  360. package/dist/http/Mime.d.ts.map +1 -1
  361. package/dist/http/Mime.js +3 -2
  362. package/dist/http/Mime.js.map +1 -1
  363. package/dist/http/internal/compression.d.ts.map +1 -1
  364. package/dist/http/internal/compression.js +2 -2
  365. package/dist/http/internal/compression.js.map +1 -1
  366. package/dist/http/internal/mediaType.d.ts.map +1 -0
  367. package/dist/{http-api → http}/internal/mediaType.js +4 -0
  368. package/dist/{http-api → http}/internal/mediaType.js.map +1 -1
  369. package/dist/http/internal/redactedPath.d.ts +2 -0
  370. package/dist/http/internal/redactedPath.d.ts.map +1 -0
  371. package/dist/http/internal/redactedPath.js +138 -0
  372. package/dist/http/internal/redactedPath.js.map +1 -0
  373. package/dist/http/internal/requestState.js +16 -0
  374. package/dist/http/internal/requestState.js.map +1 -1
  375. package/dist/http-api/HttpApi.d.ts +58 -0
  376. package/dist/http-api/HttpApi.d.ts.map +1 -1
  377. package/dist/http-api/HttpApi.js +80 -0
  378. package/dist/http-api/HttpApi.js.map +1 -1
  379. package/dist/http-api/HttpApiBuilder.d.ts.map +1 -1
  380. package/dist/http-api/HttpApiBuilder.js +12 -3
  381. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  382. package/dist/http-api/HttpApiClient.d.ts +1 -1
  383. package/dist/http-api/HttpApiClient.d.ts.map +1 -1
  384. package/dist/http-api/HttpApiClient.js +11 -7
  385. package/dist/http-api/HttpApiClient.js.map +1 -1
  386. package/dist/http-api/HttpApiEndpoint.d.ts.map +1 -1
  387. package/dist/http-api/HttpApiEndpoint.js +1 -1
  388. package/dist/http-api/HttpApiEndpoint.js.map +1 -1
  389. package/dist/http-api/HttpApiScalar.d.ts +4 -0
  390. package/dist/http-api/HttpApiScalar.d.ts.map +1 -1
  391. package/dist/http-api/HttpApiScalar.js +10 -1
  392. package/dist/http-api/HttpApiScalar.js.map +1 -1
  393. package/dist/http-api/HttpApiSchema.d.ts +66 -0
  394. package/dist/http-api/HttpApiSchema.d.ts.map +1 -1
  395. package/dist/http-api/HttpApiSchema.js +67 -2
  396. package/dist/http-api/HttpApiSchema.js.map +1 -1
  397. package/dist/http-api/OpenApi.d.ts +2 -0
  398. package/dist/http-api/OpenApi.d.ts.map +1 -1
  399. package/dist/http-api/internal/httpApiScalar.js +5 -2
  400. package/dist/http-api/internal/httpApiScalar.js.map +1 -1
  401. package/dist/index.d.ts +5 -0
  402. package/dist/index.d.ts.map +1 -1
  403. package/dist/index.js +5 -0
  404. package/dist/index.js.map +1 -1
  405. package/dist/internal/arbitrary/model.js +0 -5
  406. package/dist/internal/arbitrary/model.js.map +1 -1
  407. package/dist/internal/arbitrary/regexp.js +2 -1
  408. package/dist/internal/arbitrary/regexp.js.map +1 -1
  409. package/dist/internal/arbitrary/runner.d.ts.map +1 -1
  410. package/dist/internal/arbitrary/runner.js +21 -16
  411. package/dist/internal/arbitrary/runner.js.map +1 -1
  412. package/dist/internal/arbitrary/schema.js +140 -23
  413. package/dist/internal/arbitrary/schema.js.map +1 -1
  414. package/dist/internal/codegen.d.ts +2 -0
  415. package/dist/internal/codegen.d.ts.map +1 -0
  416. package/dist/internal/codegen.js +59 -0
  417. package/dist/internal/codegen.js.map +1 -0
  418. package/dist/internal/core.js +3 -3
  419. package/dist/internal/core.js.map +1 -1
  420. package/dist/internal/dateTime.js +26 -12
  421. package/dist/internal/dateTime.js.map +1 -1
  422. package/dist/internal/effect.js +21 -7
  423. package/dist/internal/effect.js.map +1 -1
  424. package/dist/internal/hashMap.js +7 -7
  425. package/dist/internal/hashMap.js.map +1 -1
  426. package/dist/internal/matcher.js +2 -1
  427. package/dist/internal/matcher.js.map +1 -1
  428. package/dist/internal/record.js +18 -4
  429. package/dist/internal/record.js.map +1 -1
  430. package/dist/internal/result.js +1 -1
  431. package/dist/internal/result.js.map +1 -1
  432. package/dist/internal/schema/codeExpression.d.ts +4 -0
  433. package/dist/internal/schema/codeExpression.d.ts.map +1 -0
  434. package/dist/internal/schema/codeExpression.js +179 -0
  435. package/dist/internal/schema/codeExpression.js.map +1 -0
  436. package/dist/internal/schema/codeImports.d.ts +8 -0
  437. package/dist/internal/schema/codeImports.d.ts.map +1 -0
  438. package/dist/internal/schema/codeImports.js +135 -0
  439. package/dist/internal/schema/codeImports.js.map +1 -0
  440. package/dist/internal/schema/codeTokens.d.ts +8 -0
  441. package/dist/internal/schema/codeTokens.d.ts.map +1 -0
  442. package/dist/internal/schema/codeTokens.js +17 -0
  443. package/dist/internal/schema/codeTokens.js.map +1 -0
  444. package/dist/internal/schema/fromJsonSchemaDocument.js +141 -35
  445. package/dist/internal/schema/fromJsonSchemaDocument.js.map +1 -1
  446. package/dist/internal/schema/passthrough.d.ts +2 -0
  447. package/dist/internal/schema/passthrough.d.ts.map +1 -0
  448. package/dist/internal/schema/passthrough.js +8 -0
  449. package/dist/internal/schema/passthrough.js.map +1 -0
  450. package/dist/internal/schema/schemaCodegen.d.ts +2 -0
  451. package/dist/internal/schema/schemaCodegen.d.ts.map +1 -0
  452. package/dist/internal/schema/schemaCodegen.js +377 -0
  453. package/dist/internal/schema/schemaCodegen.js.map +1 -0
  454. package/dist/internal/schema/toJsonSchemaDocument.js +11 -4
  455. package/dist/internal/schema/toJsonSchemaDocument.js.map +1 -1
  456. package/dist/internal/trie.js +51 -64
  457. package/dist/internal/trie.js.map +1 -1
  458. package/dist/internal/utf8.d.ts +2 -0
  459. package/dist/internal/utf8.d.ts.map +1 -0
  460. package/dist/internal/utf8.js +151 -0
  461. package/dist/internal/utf8.js.map +1 -0
  462. package/dist/internal/version.js +1 -1
  463. package/dist/jose/Jwks.d.ts +13 -0
  464. package/dist/jose/Jwks.d.ts.map +1 -1
  465. package/dist/jose/Jwks.js +10 -2
  466. package/dist/jose/Jwks.js.map +1 -1
  467. package/dist/observability/OtlpExporter.d.ts.map +1 -1
  468. package/dist/observability/OtlpExporter.js +12 -10
  469. package/dist/observability/OtlpExporter.js.map +1 -1
  470. package/dist/observability/OtlpLogger.d.ts.map +1 -1
  471. package/dist/observability/OtlpLogger.js +5 -3
  472. package/dist/observability/OtlpLogger.js.map +1 -1
  473. package/dist/observability/internal/otlpProtobuf.d.ts +4 -2
  474. package/dist/observability/internal/otlpProtobuf.d.ts.map +1 -1
  475. package/dist/observability/internal/otlpProtobuf.js +238 -156
  476. package/dist/observability/internal/otlpProtobuf.js.map +1 -1
  477. package/dist/persistence/PersistedQueue.d.ts.map +1 -1
  478. package/dist/persistence/PersistedQueue.js +20 -3
  479. package/dist/persistence/PersistedQueue.js.map +1 -1
  480. package/dist/protobuf/ProtobufDescriptor.d.ts +377 -0
  481. package/dist/protobuf/ProtobufDescriptor.d.ts.map +1 -0
  482. package/dist/protobuf/ProtobufDescriptor.js +135 -0
  483. package/dist/protobuf/ProtobufDescriptor.js.map +1 -0
  484. package/dist/protobuf/ProtobufDescriptorProto.d.ts +2083 -0
  485. package/dist/protobuf/ProtobufDescriptorProto.d.ts.map +1 -0
  486. package/dist/protobuf/ProtobufDescriptorProto.js +2674 -0
  487. package/dist/protobuf/ProtobufDescriptorProto.js.map +1 -0
  488. package/dist/protobuf/ProtobufMessage.d.ts +183 -0
  489. package/dist/protobuf/ProtobufMessage.d.ts.map +1 -0
  490. package/dist/protobuf/ProtobufMessage.js +232 -0
  491. package/dist/protobuf/ProtobufMessage.js.map +1 -0
  492. package/dist/protobuf/ProtobufReader.d.ts +350 -0
  493. package/dist/protobuf/ProtobufReader.d.ts.map +1 -0
  494. package/dist/protobuf/ProtobufReader.js +698 -0
  495. package/dist/protobuf/ProtobufReader.js.map +1 -0
  496. package/dist/protobuf/ProtobufWriter.d.ts +224 -0
  497. package/dist/protobuf/ProtobufWriter.d.ts.map +1 -0
  498. package/dist/protobuf/ProtobufWriter.js +483 -0
  499. package/dist/protobuf/ProtobufWriter.js.map +1 -0
  500. package/dist/protobuf/index.d.ts +30 -0
  501. package/dist/protobuf/index.d.ts.map +1 -0
  502. package/dist/protobuf/index.js +31 -0
  503. package/dist/protobuf/index.js.map +1 -0
  504. package/dist/protobuf/internal/binary.d.ts +2 -0
  505. package/dist/protobuf/internal/binary.d.ts.map +1 -0
  506. package/dist/protobuf/internal/binary.js +966 -0
  507. package/dist/protobuf/internal/binary.js.map +1 -0
  508. package/dist/protobuf/internal/resolve.d.ts +2 -0
  509. package/dist/protobuf/internal/resolve.d.ts.map +1 -0
  510. package/dist/protobuf/internal/resolve.js +463 -0
  511. package/dist/protobuf/internal/resolve.js.map +1 -0
  512. package/dist/protobuf/internal/wireType.d.ts +2 -0
  513. package/dist/protobuf/internal/wireType.d.ts.map +1 -0
  514. package/dist/protobuf/internal/wireType.js +10 -0
  515. package/dist/protobuf/internal/wireType.js.map +1 -0
  516. package/dist/reactivity/AsyncResult.d.ts +3 -0
  517. package/dist/reactivity/AsyncResult.d.ts.map +1 -1
  518. package/dist/reactivity/AsyncResult.js +4 -1
  519. package/dist/reactivity/AsyncResult.js.map +1 -1
  520. package/dist/reactivity/Atom.d.ts +10 -4
  521. package/dist/reactivity/Atom.d.ts.map +1 -1
  522. package/dist/reactivity/Atom.js +38 -13
  523. package/dist/reactivity/Atom.js.map +1 -1
  524. package/dist/reactivity/AtomHttpApi.d.ts +5 -0
  525. package/dist/reactivity/AtomHttpApi.d.ts.map +1 -1
  526. package/dist/reactivity/AtomHttpApi.js +5 -1
  527. package/dist/reactivity/AtomHttpApi.js.map +1 -1
  528. package/dist/reactivity/AtomRegistry.js +13 -0
  529. package/dist/reactivity/AtomRegistry.js.map +1 -1
  530. package/dist/reactivity/AtomRpc.d.ts +5 -0
  531. package/dist/reactivity/AtomRpc.d.ts.map +1 -1
  532. package/dist/reactivity/AtomRpc.js +6 -1
  533. package/dist/reactivity/AtomRpc.js.map +1 -1
  534. package/dist/rpc/Rpc.d.ts +25 -0
  535. package/dist/rpc/Rpc.d.ts.map +1 -1
  536. package/dist/rpc/Rpc.js +18 -0
  537. package/dist/rpc/Rpc.js.map +1 -1
  538. package/dist/rpc/RpcClient.d.ts.map +1 -1
  539. package/dist/rpc/RpcClient.js +38 -21
  540. package/dist/rpc/RpcClient.js.map +1 -1
  541. package/dist/rpc/RpcGroup.d.ts +5 -0
  542. package/dist/rpc/RpcGroup.d.ts.map +1 -1
  543. package/dist/rpc/RpcGroup.js.map +1 -1
  544. package/dist/rpc/RpcMiddleware.d.ts +9 -0
  545. package/dist/rpc/RpcMiddleware.d.ts.map +1 -1
  546. package/dist/rpc/RpcMiddleware.js.map +1 -1
  547. package/dist/rpc/RpcSerialization.d.ts +7 -1
  548. package/dist/rpc/RpcSerialization.d.ts.map +1 -1
  549. package/dist/rpc/RpcSerialization.js +22 -5
  550. package/dist/rpc/RpcSerialization.js.map +1 -1
  551. package/dist/rpc/RpcServer.d.ts.map +1 -1
  552. package/dist/rpc/RpcServer.js +33 -18
  553. package/dist/rpc/RpcServer.js.map +1 -1
  554. package/dist/schema/SchemaCompiler/runtime.js +2 -1
  555. package/dist/schema/SchemaCompiler/runtime.js.map +1 -1
  556. package/dist/schema/VariantSchema.d.ts +10 -2
  557. package/dist/schema/VariantSchema.d.ts.map +1 -1
  558. package/dist/schema/VariantSchema.js +7 -1
  559. package/dist/schema/VariantSchema.js.map +1 -1
  560. package/dist/socket/Socket.d.ts +24 -10
  561. package/dist/socket/Socket.d.ts.map +1 -1
  562. package/dist/socket/Socket.js +52 -17
  563. package/dist/socket/Socket.js.map +1 -1
  564. package/dist/sql/Migrator.d.ts +3 -0
  565. package/dist/sql/Migrator.d.ts.map +1 -1
  566. package/dist/sql/Migrator.js +10 -1
  567. package/dist/sql/Migrator.js.map +1 -1
  568. package/dist/sql/SqlModel.d.ts.map +1 -1
  569. package/dist/sql/SqlModel.js +1 -0
  570. package/dist/sql/SqlModel.js.map +1 -1
  571. package/dist/testing/TestClock.js +3 -1
  572. package/dist/testing/TestClock.js.map +1 -1
  573. package/dist/testing/TestConsole.d.ts +96 -0
  574. package/dist/testing/TestConsole.d.ts.map +1 -1
  575. package/dist/testing/TestConsole.js +78 -6
  576. package/dist/testing/TestConsole.js.map +1 -1
  577. package/dist/testing/TestSchema.d.ts +5 -1
  578. package/dist/testing/TestSchema.d.ts.map +1 -1
  579. package/dist/testing/TestSchema.js +7 -2
  580. package/dist/testing/TestSchema.js.map +1 -1
  581. package/dist/workers/SharedMemory.d.ts +115 -0
  582. package/dist/workers/SharedMemory.d.ts.map +1 -0
  583. package/dist/workers/SharedMemory.js +149 -0
  584. package/dist/workers/SharedMemory.js.map +1 -0
  585. package/dist/workers/Transferable.d.ts.map +1 -1
  586. package/dist/workers/Transferable.js +1 -4
  587. package/dist/workers/Transferable.js.map +1 -1
  588. package/dist/workers/index.d.ts +5 -0
  589. package/dist/workers/index.d.ts.map +1 -1
  590. package/dist/workers/index.js +5 -0
  591. package/dist/workers/index.js.map +1 -1
  592. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  593. package/dist/workflow/WorkflowEngine.js +3 -1
  594. package/dist/workflow/WorkflowEngine.js.map +1 -1
  595. package/package.json +7 -4
  596. package/src/Arbitrary.ts +60 -3
  597. package/src/BigInt.ts +247 -9
  598. package/src/Cache.ts +4 -2
  599. package/src/Cause.ts +3 -3
  600. package/src/Chunk.ts +7 -3
  601. package/src/Clock.ts +5 -2
  602. package/src/Codegen.ts +741 -0
  603. package/src/Config.ts +35 -4
  604. package/src/ConfigProvider.ts +24 -7
  605. package/src/Effect.ts +871 -109
  606. package/src/Equivalence.ts +16 -13
  607. package/src/Fiber.ts +58 -8
  608. package/src/FiberHandle.ts +86 -12
  609. package/src/FiberMap.ts +83 -10
  610. package/src/FiberSet.ts +96 -8
  611. package/src/Formatter.ts +2 -0
  612. package/src/LayerMap.ts +14 -4
  613. package/src/LayerRef.ts +2 -2
  614. package/src/Match.ts +16 -0
  615. package/src/Metric.ts +1 -1
  616. package/src/Option.ts +9 -5
  617. package/src/Order.ts +9 -4
  618. package/src/Pool.ts +22 -17
  619. package/src/Predicate.ts +7 -3
  620. package/src/Queue.ts +84 -31
  621. package/src/Rational.ts +198 -0
  622. package/src/Request.ts +20 -0
  623. package/src/Result.ts +9 -6
  624. package/src/Schema.ts +69 -32
  625. package/src/SchemaAST.ts +15 -4
  626. package/src/SchemaGetter.ts +17 -10
  627. package/src/SchemaRepresentation.ts +37 -77
  628. package/src/SchemaTransformation.ts +12 -11
  629. package/src/Scope.ts +12 -6
  630. package/src/ScopedCache.ts +2 -1
  631. package/src/Semaphore.ts +18 -4
  632. package/src/Stream.ts +66 -20
  633. package/src/String.ts +83 -6
  634. package/src/Struct.ts +138 -5
  635. package/src/TextDiff.ts +186 -30
  636. package/src/TxPriorityQueue.ts +2 -2
  637. package/src/ai/Chat.ts +9 -3
  638. package/src/ai/LanguageModel.ts +72 -15
  639. package/src/ai/McpClient.ts +1 -11
  640. package/src/ai/McpServer.ts +146 -25
  641. package/src/ai/Tool.ts +3 -2
  642. package/src/ai/Toolkit.ts +3 -1
  643. package/src/ai/WorkloadIdentity.ts +318 -0
  644. package/src/ai/index.ts +6 -0
  645. package/src/ai/internal/mcpProtocol/v2024_11_05.ts +3 -1
  646. package/src/ai/internal/mcpProtocol/v2025_03_26.ts +3 -1
  647. package/src/ai/internal/mcpProtocol/v2025_06_18.ts +3 -1
  648. package/src/ai/internal/mcpProtocol/v2025_11_25.ts +3 -1
  649. package/src/ai/internal/mcpRuntime.ts +2 -6
  650. package/src/ai/internal/mcpSkills.ts +70 -2
  651. package/src/ai/internal/structured-output.ts +6 -1
  652. package/src/chat/Chat.ts +164 -0
  653. package/src/chat/ChatAdapter.ts +444 -0
  654. package/src/chat/ChatError.ts +684 -0
  655. package/src/chat/ChatEvent.ts +221 -0
  656. package/src/chat/ChatHandler.ts +102 -0
  657. package/src/chat/ChatInteraction.ts +1979 -0
  658. package/src/chat/ChatMarkdown.ts +1406 -0
  659. package/src/chat/ChatMessage.ts +213 -0
  660. package/src/chat/ChatTest.ts +2606 -0
  661. package/src/chat/ChatThread.ts +132 -0
  662. package/src/chat/ChatUi.ts +320 -0
  663. package/src/chat/index.ts +72 -0
  664. package/src/chat/internal/retries.ts +7 -0
  665. package/src/cli/CliOutput.ts +4 -5
  666. package/src/cli/Command.ts +25 -3
  667. package/src/cli/Prompt.ts +15 -9
  668. package/src/cli/internal/config.ts +8 -8
  669. package/src/cli/internal/lexer.ts +14 -0
  670. package/src/cli/internal/parser.ts +28 -20
  671. package/src/cli/internal/wizard.ts +4 -0
  672. package/src/cluster/ClusterCron.ts +33 -10
  673. package/src/cluster/ClusterWorkflowEngine.ts +42 -23
  674. package/src/cluster/Sharding.ts +17 -3
  675. package/src/cluster/ShardingConfig.ts +3 -0
  676. package/src/cluster/SqlMessageStorage.ts +16 -20
  677. package/src/cluster/SqlRunnerStorage.ts +21 -8
  678. package/src/cluster/internal/entityManager.ts +19 -10
  679. package/src/cluster/internal/entityReaper.ts +1 -1
  680. package/src/crypto/Kdf.ts +2 -1
  681. package/src/crypto/Password.ts +258 -0
  682. package/src/crypto/index.ts +6 -0
  683. package/src/encoding/Base64.ts +79 -0
  684. package/src/encoding/Base64Url.ts +1 -0
  685. package/src/encoding/Csv.ts +47 -20
  686. package/src/encoding/Hex.ts +5 -0
  687. package/src/encoding/SchemaBinary.ts +13 -79
  688. package/src/encoding/Sse.ts +7 -5
  689. package/src/encoding/Xml.ts +394 -47
  690. package/src/eventlog/EventJournal.ts +3 -8
  691. package/src/eventlog/SqlEventLogServerEncrypted.ts +9 -9
  692. package/src/http/FindMyWay/internal/router.ts +181 -129
  693. package/src/http/FindMyWay.ts +106 -0
  694. package/src/http/HttpClient.ts +2 -1
  695. package/src/http/HttpMiddleware.ts +34 -10
  696. package/src/http/HttpRouter.ts +84 -20
  697. package/src/http/HttpServerResponse.ts +33 -61
  698. package/src/http/Mime.ts +3 -2
  699. package/src/http/internal/compression.ts +2 -2
  700. package/src/{http-api → http}/internal/mediaType.ts +4 -0
  701. package/src/http/internal/redactedPath.ts +144 -0
  702. package/src/http/internal/requestState.ts +22 -0
  703. package/src/http-api/HttpApi.ts +103 -0
  704. package/src/http-api/HttpApiBuilder.ts +14 -3
  705. package/src/http-api/HttpApiClient.ts +23 -8
  706. package/src/http-api/HttpApiEndpoint.ts +1 -1
  707. package/src/http-api/HttpApiScalar.ts +9 -1
  708. package/src/http-api/HttpApiSchema.ts +69 -3
  709. package/src/http-api/OpenApi.ts +2 -0
  710. package/src/http-api/internal/httpApiScalar.ts +5 -1
  711. package/src/index.ts +6 -0
  712. package/src/internal/arbitrary/model.ts +3 -9
  713. package/src/internal/arbitrary/regexp.ts +3 -1
  714. package/src/internal/arbitrary/runner.ts +28 -14
  715. package/src/internal/arbitrary/schema.ts +140 -35
  716. package/src/internal/codegen.ts +53 -0
  717. package/src/internal/core.ts +3 -3
  718. package/src/internal/dateTime.ts +30 -13
  719. package/src/internal/effect.ts +25 -9
  720. package/src/internal/hashMap.ts +8 -7
  721. package/src/internal/matcher.ts +2 -1
  722. package/src/internal/record.ts +19 -4
  723. package/src/internal/result.ts +1 -1
  724. package/src/internal/schema/codeExpression.ts +179 -0
  725. package/src/internal/schema/codeImports.ts +142 -0
  726. package/src/internal/schema/codeTokens.ts +39 -0
  727. package/src/internal/schema/fromJsonSchemaDocument.ts +154 -34
  728. package/src/internal/schema/passthrough.ts +8 -0
  729. package/src/internal/schema/schemaCodegen.ts +543 -0
  730. package/src/internal/schema/toJsonSchemaDocument.ts +13 -4
  731. package/src/internal/trie.ts +46 -60
  732. package/src/internal/utf8.ts +106 -0
  733. package/src/internal/version.ts +1 -1
  734. package/src/jose/Jwks.ts +23 -4
  735. package/src/observability/OtlpExporter.ts +12 -10
  736. package/src/observability/OtlpLogger.ts +5 -3
  737. package/src/observability/internal/otlpProtobuf.ts +386 -457
  738. package/src/persistence/PersistedQueue.ts +21 -4
  739. package/src/protobuf/ProtobufDescriptor.ts +503 -0
  740. package/src/protobuf/ProtobufDescriptorProto.ts +3611 -0
  741. package/src/protobuf/ProtobufMessage.ts +277 -0
  742. package/src/protobuf/ProtobufReader.ts +756 -0
  743. package/src/protobuf/ProtobufWriter.ts +530 -0
  744. package/src/protobuf/index.ts +36 -0
  745. package/src/protobuf/internal/binary.ts +1215 -0
  746. package/src/protobuf/internal/resolve.ts +533 -0
  747. package/src/protobuf/internal/wireType.ts +9 -0
  748. package/src/reactivity/AsyncResult.ts +6 -1
  749. package/src/reactivity/Atom.ts +55 -16
  750. package/src/reactivity/AtomHttpApi.ts +10 -1
  751. package/src/reactivity/AtomRegistry.ts +16 -0
  752. package/src/reactivity/AtomRpc.ts +11 -1
  753. package/src/rpc/Rpc.ts +31 -0
  754. package/src/rpc/RpcClient.ts +30 -21
  755. package/src/rpc/RpcGroup.ts +5 -0
  756. package/src/rpc/RpcMiddleware.ts +9 -0
  757. package/src/rpc/RpcSerialization.ts +26 -6
  758. package/src/rpc/RpcServer.ts +33 -20
  759. package/src/schema/SchemaCompiler/runtime.ts +2 -3
  760. package/src/schema/VariantSchema.ts +12 -4
  761. package/src/socket/Socket.ts +67 -20
  762. package/src/sql/Migrator.ts +8 -1
  763. package/src/sql/SqlModel.ts +4 -0
  764. package/src/testing/TestClock.ts +1 -1
  765. package/src/testing/TestConsole.ts +119 -9
  766. package/src/testing/TestSchema.ts +8 -3
  767. package/src/workers/SharedMemory.ts +227 -0
  768. package/src/workers/Transferable.ts +1 -5
  769. package/src/workers/index.ts +6 -0
  770. package/src/workflow/WorkflowEngine.ts +3 -1
  771. package/dist/http-api/internal/mediaType.d.ts.map +0 -1
  772. package/dist/internal/schema/toCodeDocument.d.ts +0 -2
  773. package/dist/internal/schema/toCodeDocument.d.ts.map +0 -1
  774. package/dist/internal/schema/toCodeDocument.js +0 -444
  775. package/dist/internal/schema/toCodeDocument.js.map +0 -1
  776. package/dist/observability/internal/protobuf.d.ts +0 -2
  777. package/dist/observability/internal/protobuf.d.ts.map +0 -1
  778. package/dist/observability/internal/protobuf.js +0 -169
  779. package/dist/observability/internal/protobuf.js.map +0 -1
  780. package/src/internal/schema/toCodeDocument.ts +0 -570
  781. package/src/observability/internal/protobuf.ts +0 -225
  782. /package/dist/{http-api → http}/internal/mediaType.d.ts +0 -0
@@ -0,0 +1,1979 @@
1
+ /**
2
+ * Typed buttons, selects, modals and slash commands, and the service that
3
+ * receives their clicks, submits and commands.
4
+ *
5
+ * A definition carries an element's id and the schemas of its values. It
6
+ * builds the element to post (`of`, `open`) and gives the typed slot of its
7
+ * handler, the way `Rpc` and `RpcGroup` do. A `group` of definitions becomes a
8
+ * layer of handlers, and `layer` provides the `Handler` service that adapters
9
+ * call.
10
+ *
11
+ * **Example** (A button that opens a modal)
12
+ *
13
+ * ```ts
14
+ * import { Effect, Layer, Schema } from "effect"
15
+ * import { ChatInteraction } from "effect/chat"
16
+ *
17
+ * const Deploy = Schema.Struct({ version: Schema.String })
18
+ *
19
+ * const Reject = ChatInteraction.button("reject", { label: "Reject", style: "danger", value: Deploy })
20
+ * const RejectReason = ChatInteraction.modal("reject-reason", {
21
+ * title: "Reject deploy",
22
+ * metadata: Deploy,
23
+ * fields: {
24
+ * reason: ChatInteraction.textInput({ label: "Reason", multiline: true })
25
+ * }
26
+ * })
27
+ *
28
+ * const Interactions = ChatInteraction.group(Reject, RejectReason).toLayer({
29
+ * reject: (click) => Effect.succeed(RejectReason.open({ metadata: click.value })),
30
+ * "reject-reason": (submit) =>
31
+ * submit.values.reason.length < 10
32
+ * ? Effect.succeed(ChatInteraction.errors({ reason: "Say a bit more." }))
33
+ * : Effect.succeed(ChatInteraction.close)
34
+ * }).pipe(Layer.provideMerge(ChatInteraction.layer()))
35
+ * ```
36
+ *
37
+ * **Details**
38
+ *
39
+ * - Clicks, submits and commands are not `ChatEvent`s. They need an answer
40
+ * inside the platform's 3 seconds, so they go to `Handler`, which answers
41
+ * by return value and has no error channel.
42
+ * - Slack and Discord don't redeliver a click, a submit or a command, so
43
+ * interactions carry no dedupe key. An adapter whose platform does
44
+ * redeliver them documents a delivery key of its own.
45
+ *
46
+ * @stability unstable
47
+ * @since 4.1.5
48
+ */
49
+ import * as Context from "../Context.ts"
50
+ import type * as Duration from "../Duration.ts"
51
+ import * as Effect from "../Effect.ts"
52
+ import * as Exit from "../Exit.ts"
53
+ import * as Fiber from "../Fiber.ts"
54
+ import * as Layer from "../Layer.ts"
55
+ import * as Option from "../Option.ts"
56
+ import * as Schema from "../Schema.ts"
57
+ import * as SchemaAST from "../SchemaAST.ts"
58
+ import type { Scope } from "../Scope.ts"
59
+ import { ChatError, interactionExpired, NotFound } from "./ChatError.ts"
60
+ import { ChatThread } from "./ChatThread.ts"
61
+ import * as ChatUi from "./ChatUi.ts"
62
+
63
+ // -----------------------------------------------------------------------------
64
+ // events
65
+ // -----------------------------------------------------------------------------
66
+
67
+ const origin = {
68
+ thread: ChatThread,
69
+ messageId: Schema.String,
70
+ userId: Schema.String,
71
+ raw: Schema.Json
72
+ }
73
+
74
+ /**
75
+ * Schema for a click on a button.
76
+ *
77
+ * **Details**
78
+ *
79
+ * - `value` is still encoded, and absent for a button with no value.
80
+ * - `thread` and `messageId` are where the message carrying the button
81
+ * lives. `raw` is the platform's interaction payload.
82
+ *
83
+ * **Gotchas**
84
+ *
85
+ * On a command's private answer, `messageId` still tells which answer was
86
+ * clicked, but no message op works with it: `edit`, `delete` and
87
+ * `fetchMessage` can't reach a private answer. On Slack `chat.update` on it
88
+ * answered `message_not_found` live, and `edit` fails `NotFound`. On
89
+ * Discord only the interaction's token reaches it, which is from Discord's
90
+ * docs and was not run. Only `raw` tells the two apart: Slack's
91
+ * `container.is_ephemeral`, Discord's `message.flags` with 64.
92
+ *
93
+ * @stability unstable
94
+ * @category events
95
+ * @since 4.1.5
96
+ */
97
+ export const ButtonClicked = Schema.TaggedStruct("ButtonClicked", {
98
+ id: Schema.String,
99
+ value: Schema.optionalKey(Schema.String),
100
+ ...origin
101
+ })
102
+
103
+ /**
104
+ * A click on a button.
105
+ *
106
+ * @stability unstable
107
+ * @category events
108
+ * @since 4.1.5
109
+ */
110
+ export type ButtonClicked = typeof ButtonClicked.Type
111
+
112
+ /**
113
+ * Schema for a choice in a select on a message. `value` is the chosen
114
+ * option's value, still encoded. `messageId` is as on `ButtonClicked`: on a
115
+ * command's private answer it tells which answer it was, and no message op
116
+ * works with it.
117
+ *
118
+ * @stability unstable
119
+ * @category events
120
+ * @since 4.1.5
121
+ */
122
+ export const SelectChanged = Schema.TaggedStruct("SelectChanged", {
123
+ id: Schema.String,
124
+ value: Schema.String,
125
+ ...origin
126
+ })
127
+
128
+ /**
129
+ * A choice in a select on a message.
130
+ *
131
+ * @stability unstable
132
+ * @category events
133
+ * @since 4.1.5
134
+ */
135
+ export type SelectChanged = typeof SelectChanged.Type
136
+
137
+ /**
138
+ * Schema for a modal submit.
139
+ *
140
+ * **Details**
141
+ *
142
+ * - `thread` and `messageId` are those of the click that opened the modal.
143
+ * A modal a command opened carries the command's `thread` and no
144
+ * `messageId`. A modal opened from a command's private answer carries
145
+ * that answer's id, which no message op works with, as on
146
+ * `ButtonClicked`.
147
+ * - `metadata` is still encoded.
148
+ * - `values` are by field id, still encoded. An optional field left empty
149
+ * has no key.
150
+ *
151
+ * @stability unstable
152
+ * @category events
153
+ * @since 4.1.5
154
+ */
155
+ export const ModalSubmitted = Schema.TaggedStruct("ModalSubmitted", {
156
+ id: Schema.String,
157
+ metadata: Schema.optionalKey(Schema.String),
158
+ values: Schema.Record(Schema.String, Schema.String),
159
+ thread: ChatThread,
160
+ messageId: Schema.optionalKey(Schema.String),
161
+ userId: Schema.String,
162
+ raw: Schema.Json
163
+ })
164
+
165
+ /**
166
+ * A modal submit.
167
+ *
168
+ * @stability unstable
169
+ * @category events
170
+ * @since 4.1.5
171
+ */
172
+ export type ModalSubmitted = typeof ModalSubmitted.Type
173
+
174
+ /**
175
+ * Schema for a slash command.
176
+ *
177
+ * **Details**
178
+ *
179
+ * - `id` is the command's name, without the slash.
180
+ * - `text` is what was typed after the name, as the platform sent it, and
181
+ * empty when nothing was. It is not normalised.
182
+ * - `thread` is where the command was typed. On Slack that is always a
183
+ * channel or a direct: Slack does not deliver an app's command typed in a
184
+ * thread. There is no `messageId`, since a command comes from no message.
185
+ * - `raw` is the platform's payload. It holds what `Chat.followUp` needs,
186
+ * so it is a credential for as long as `limits.followUpAge`.
187
+ *
188
+ * @stability unstable
189
+ * @category events
190
+ * @since 4.1.5
191
+ */
192
+ export const CommandInvoked = Schema.TaggedStruct("CommandInvoked", {
193
+ id: Schema.String,
194
+ text: Schema.String,
195
+ thread: ChatThread,
196
+ userId: Schema.String,
197
+ raw: Schema.Json
198
+ })
199
+
200
+ /**
201
+ * A slash command.
202
+ *
203
+ * @stability unstable
204
+ * @category events
205
+ * @since 4.1.5
206
+ */
207
+ export type CommandInvoked = typeof CommandInvoked.Type
208
+
209
+ /**
210
+ * Schema for what an adapter hands to `Handler`.
211
+ *
212
+ * **Details**
213
+ *
214
+ * Not part of `ChatEvent`: these need an answer inside the platform's 3
215
+ * seconds.
216
+ *
217
+ * @stability unstable
218
+ * @category events
219
+ * @since 4.1.5
220
+ */
221
+ export const Interaction = Schema.Union([ButtonClicked, SelectChanged, ModalSubmitted, CommandInvoked])
222
+
223
+ /**
224
+ * A click, a select choice, a modal submit or a slash command.
225
+ *
226
+ * @stability unstable
227
+ * @category events
228
+ * @since 4.1.5
229
+ */
230
+ export type Interaction = typeof Interaction.Type
231
+
232
+ // -----------------------------------------------------------------------------
233
+ // replies
234
+ // -----------------------------------------------------------------------------
235
+
236
+ /**
237
+ * Schema for the reply that acknowledges a click. It is also what the handler
238
+ * service answers a command with no definition, which the adapter sends
239
+ * nothing for.
240
+ *
241
+ * @stability unstable
242
+ * @category replies
243
+ * @since 4.1.5
244
+ */
245
+ export const Ack = Schema.TaggedStruct("Ack", {})
246
+
247
+ /**
248
+ * The reply that acknowledges a click.
249
+ *
250
+ * @stability unstable
251
+ * @category replies
252
+ * @since 4.1.5
253
+ */
254
+ export type Ack = typeof Ack.Type
255
+
256
+ /**
257
+ * Schema for the reply that opens a modal. A click or a command can return
258
+ * it.
259
+ *
260
+ * @stability unstable
261
+ * @category replies
262
+ * @since 4.1.5
263
+ */
264
+ export const OpenModal = Schema.TaggedStruct("OpenModal", { modal: ChatUi.Modal })
265
+
266
+ /**
267
+ * The reply that opens a modal.
268
+ *
269
+ * @stability unstable
270
+ * @category replies
271
+ * @since 4.1.5
272
+ */
273
+ export type OpenModal = typeof OpenModal.Type
274
+
275
+ /**
276
+ * Schema for the reply that closes a submitted modal.
277
+ *
278
+ * @stability unstable
279
+ * @category replies
280
+ * @since 4.1.5
281
+ */
282
+ export const Close = Schema.TaggedStruct("Close", {})
283
+
284
+ /**
285
+ * The reply that closes a submitted modal.
286
+ *
287
+ * @stability unstable
288
+ * @category replies
289
+ * @since 4.1.5
290
+ */
291
+ export type Close = typeof Close.Type
292
+
293
+ /**
294
+ * Schema for the reply that puts a message under each named field of a
295
+ * submitted modal. `errors` is by field id.
296
+ *
297
+ * **Details**
298
+ *
299
+ * With `modalErrors` the modal stays open with the messages under its
300
+ * fields. Without it the adapter answers some other way: on Discord a private
301
+ * reply lists them and the modal closes.
302
+ *
303
+ * @stability unstable
304
+ * @category replies
305
+ * @since 4.1.5
306
+ */
307
+ export const Errors = Schema.TaggedStruct("Errors", {
308
+ errors: Schema.Record(Schema.String, Schema.String)
309
+ })
310
+
311
+ /**
312
+ * The reply that puts a message under each named field.
313
+ *
314
+ * @stability unstable
315
+ * @category replies
316
+ * @since 4.1.5
317
+ */
318
+ export type Errors = typeof Errors.Type
319
+
320
+ /**
321
+ * What a click's handler may answer.
322
+ *
323
+ * @stability unstable
324
+ * @category replies
325
+ * @since 4.1.5
326
+ */
327
+ export type ClickReply = Ack | OpenModal
328
+
329
+ /**
330
+ * What a submit's handler may answer.
331
+ *
332
+ * @stability unstable
333
+ * @category replies
334
+ * @since 4.1.5
335
+ */
336
+ export type SubmitReply = Close | Errors
337
+
338
+ /**
339
+ * Schema for who sees the answer to a command: `"ephemeral"` for the person
340
+ * who ran it, `"public"` for the channel.
341
+ *
342
+ * @stability unstable
343
+ * @category replies
344
+ * @since 4.1.5
345
+ */
346
+ export const Visibility = Schema.Literals(["ephemeral", "public"])
347
+
348
+ /**
349
+ * Who sees the answer to a command.
350
+ *
351
+ * @stability unstable
352
+ * @category replies
353
+ * @since 4.1.5
354
+ */
355
+ export type Visibility = typeof Visibility.Type
356
+
357
+ /**
358
+ * Schema for the reply that answers a command with a message, at once.
359
+ *
360
+ * **Details**
361
+ *
362
+ * `markdown` and `actions` are rendered and checked the way `post` renders
363
+ * and checks them, with the default post options. `withPostOptions` does
364
+ * not reach it, so it never mentions anyone: on Slack a mention token is
365
+ * escaped and shows as text, and on Discord it renders and notifies nobody.
366
+ * The message gets no id: it cannot be edited, deleted or fetched
367
+ * afterwards. A click on its elements carries a `messageId`, which for a
368
+ * private answer tells which answer it was and works with no message op.
369
+ *
370
+ * @stability unstable
371
+ * @category replies
372
+ * @since 4.1.5
373
+ */
374
+ export const Respond = Schema.TaggedStruct("Respond", {
375
+ markdown: Schema.String,
376
+ actions: Schema.optionalKey(Schema.Array(ChatUi.Action)),
377
+ visibility: Visibility
378
+ })
379
+
380
+ /**
381
+ * The reply that answers a command with a message.
382
+ *
383
+ * @stability unstable
384
+ * @category replies
385
+ * @since 4.1.5
386
+ */
387
+ export type Respond = typeof Respond.Type
388
+
389
+ /**
390
+ * Schema for the reply that says a command's answer comes later, and the
391
+ * value `Chat.followUp` takes to send it.
392
+ *
393
+ * **Details**
394
+ *
395
+ * - It is plain data, so it can go on a queue to another process.
396
+ * - `visibility` is fixed here. `followUp` has none of its own.
397
+ * - The first `followUp` for it is the answer. A second one is
398
+ * platform-specific: Slack posts another message, up to five, and Discord
399
+ * overwrites the first. Neither adapter stops it.
400
+ *
401
+ * **Gotchas**
402
+ *
403
+ * It holds the command's `raw`, which is a credential for as long as
404
+ * `limits.followUpAge`.
405
+ *
406
+ * @stability unstable
407
+ * @category replies
408
+ * @since 4.1.5
409
+ */
410
+ export const Defer = Schema.TaggedStruct("Defer", {
411
+ command: CommandInvoked,
412
+ visibility: Visibility
413
+ })
414
+
415
+ /**
416
+ * The reply that says a command's answer comes later.
417
+ *
418
+ * @stability unstable
419
+ * @category replies
420
+ * @since 4.1.5
421
+ */
422
+ export type Defer = typeof Defer.Type
423
+
424
+ /**
425
+ * What the handler service may answer a command with.
426
+ *
427
+ * **Details**
428
+ *
429
+ * `Ack` is what a command with no definition gets, and the adapter sends
430
+ * nothing for it. A typed command handler cannot return it.
431
+ *
432
+ * @stability unstable
433
+ * @category replies
434
+ * @since 4.1.5
435
+ */
436
+ export type CommandReply = Ack | Respond | OpenModal | Defer
437
+
438
+ /**
439
+ * Schema for what `handle` gives when the handler ran past the deadline.
440
+ *
441
+ * **Gotchas**
442
+ *
443
+ * `Late` is never sent to a platform. It is a tagged struct, so it is itself
444
+ * a JSON value: test for it with `Schema.is(ChatInteraction.Late)`.
445
+ *
446
+ * @stability unstable
447
+ * @category replies
448
+ * @since 4.1.5
449
+ */
450
+ export const Late = Schema.TaggedStruct("Late", {})
451
+
452
+ /**
453
+ * What `handle` gives when the handler ran past the deadline.
454
+ *
455
+ * @stability unstable
456
+ * @category replies
457
+ * @since 4.1.5
458
+ */
459
+ export type Late = typeof Late.Type
460
+
461
+ /**
462
+ * `Errors`, with the field ids it names kept in the type, so a typed submit
463
+ * handler can refuse a field the modal does not have. The extra property
464
+ * exists only in the type.
465
+ *
466
+ * @stability unstable
467
+ * @category replies
468
+ * @since 4.1.5
469
+ */
470
+ export interface FieldErrors<out Field extends string> extends Errors {
471
+ readonly "~fields"?: Field | undefined
472
+ }
473
+
474
+ /**
475
+ * Acknowledges a click.
476
+ *
477
+ * @stability unstable
478
+ * @category replies
479
+ * @since 4.1.5
480
+ */
481
+ export const ack: Ack = Ack.make({})
482
+
483
+ /**
484
+ * Closes a submitted modal.
485
+ *
486
+ * @stability unstable
487
+ * @category replies
488
+ * @since 4.1.5
489
+ */
490
+ export const close: Close = Close.make({})
491
+
492
+ /**
493
+ * Puts a message under each named field of a submitted modal.
494
+ *
495
+ * **Details**
496
+ *
497
+ * In a typed submit handler, only the modal's input ids are accepted.
498
+ *
499
+ * @stability unstable
500
+ * @category replies
501
+ * @since 4.1.5
502
+ */
503
+ export const errors = <const E extends { readonly [field: string]: string }>(
504
+ errors: E
505
+ ): FieldErrors<keyof E & string> => Errors.make({ errors })
506
+
507
+ /**
508
+ * Answers a command with a message, at once.
509
+ *
510
+ * **Details**
511
+ *
512
+ * `visibility` defaults to `"ephemeral"`: only the person who ran the
513
+ * command sees it. A platform without `ephemeral` refuses a private answer
514
+ * and sends nothing. It never sends it publicly instead.
515
+ *
516
+ * @stability unstable
517
+ * @category replies
518
+ * @since 4.1.5
519
+ */
520
+ export const respond = (options: {
521
+ readonly markdown: string
522
+ readonly actions?: ReadonlyArray<ChatUi.Action> | undefined
523
+ readonly visibility?: Visibility | undefined
524
+ }): Respond =>
525
+ Respond.make({
526
+ markdown: options.markdown,
527
+ ...optional("actions", options.actions),
528
+ visibility: options.visibility ?? "ephemeral"
529
+ })
530
+
531
+ /**
532
+ * Answers a command with a promise of a later answer, sent with
533
+ * `Chat.followUp`.
534
+ *
535
+ * **When to use**
536
+ *
537
+ * Use when the work does not fit in the deadline. The handler returns the
538
+ * deferral and hands it to whatever does the work.
539
+ *
540
+ * **Details**
541
+ *
542
+ * - `visibility` defaults to `"ephemeral"`, and holds for the follow-up.
543
+ * - One `Chat.followUp` per deferral is the portable contract. The first
544
+ * call is the answer. A second is platform-specific: a new message on
545
+ * Slack, up to five, and an overwrite of the first on Discord.
546
+ *
547
+ * @stability unstable
548
+ * @category replies
549
+ * @since 4.1.5
550
+ */
551
+ export const defer = (command: CommandInvoked, options?: {
552
+ readonly visibility?: Visibility | undefined
553
+ }): Defer => Defer.make({ command, visibility: options?.visibility ?? "ephemeral" })
554
+
555
+ // -----------------------------------------------------------------------------
556
+ // typed events
557
+ // -----------------------------------------------------------------------------
558
+
559
+ /**
560
+ * A click as a button's handler receives it.
561
+ *
562
+ * **Details**
563
+ *
564
+ * `value` is decoded with the button's value schema, and `undefined` when it
565
+ * has none.
566
+ *
567
+ * @stability unstable
568
+ * @category models
569
+ * @since 4.1.5
570
+ */
571
+ export interface Click<out Value> {
572
+ readonly id: string
573
+ readonly value: Value
574
+ readonly thread: ChatThread
575
+ readonly messageId: string
576
+ readonly userId: string
577
+ readonly raw: Schema.Json
578
+ }
579
+
580
+ /**
581
+ * A choice as a select's handler receives it. `value` is the chosen option,
582
+ * decoded.
583
+ *
584
+ * @stability unstable
585
+ * @category models
586
+ * @since 4.1.5
587
+ */
588
+ export interface Selected<out Value> {
589
+ readonly id: string
590
+ readonly value: Value
591
+ readonly thread: ChatThread
592
+ readonly messageId: string
593
+ readonly userId: string
594
+ readonly raw: Schema.Json
595
+ }
596
+
597
+ /**
598
+ * A submit as a modal's handler receives it, with the metadata and values
599
+ * decoded.
600
+ *
601
+ * **Details**
602
+ *
603
+ * - `values` has one key per input and none for `text`. An optional input
604
+ * left empty is `undefined`.
605
+ * - `messageId` is the message whose element opened the modal, and
606
+ * `undefined` when a command opened it.
607
+ *
608
+ * @stability unstable
609
+ * @category models
610
+ * @since 4.1.5
611
+ */
612
+ export interface Submit<out Metadata, out Values> {
613
+ readonly id: string
614
+ readonly metadata: Metadata
615
+ readonly values: Values
616
+ readonly thread: ChatThread
617
+ readonly messageId: string | undefined
618
+ readonly userId: string
619
+ readonly raw: Schema.Json
620
+ }
621
+
622
+ // -----------------------------------------------------------------------------
623
+ // values
624
+ // -----------------------------------------------------------------------------
625
+
626
+ /**
627
+ * The type id of definitions and groups.
628
+ *
629
+ * @stability unstable
630
+ * @category type ids
631
+ * @since 4.1.5
632
+ */
633
+ export const TypeId = "~effect/chat/ChatInteraction"
634
+
635
+ /**
636
+ * A value's schema.
637
+ *
638
+ * **Details**
639
+ *
640
+ * It may not need services, because it is encoded inside `of` and `open`,
641
+ * which are plain functions.
642
+ *
643
+ * @stability unstable
644
+ * @category models
645
+ * @since 4.1.5
646
+ */
647
+ export type ValueSchema = Schema.Codec<any, any, never, never>
648
+
649
+ type TypeOf<S, Fallback> = S extends ValueSchema ? S["Type"] : Fallback
650
+
651
+ interface Wire {
652
+ readonly raw: boolean
653
+ readonly encode: (value: unknown) => unknown
654
+ readonly decode: (encoded: unknown) => Option.Option<unknown>
655
+ }
656
+
657
+ const wires = new WeakMap<object, Wire>()
658
+
659
+ const stringOnly = (ast: SchemaAST.AST): boolean => {
660
+ switch (ast._tag) {
661
+ case "String":
662
+ case "TemplateLiteral":
663
+ return true
664
+ case "Literal":
665
+ return typeof ast.literal === "string"
666
+ case "Union":
667
+ return ast.types.length > 0 && ast.types.every(stringOnly)
668
+ default:
669
+ return false
670
+ }
671
+ }
672
+
673
+ const wireOf = (schema: ValueSchema): Wire => {
674
+ let wire = wires.get(schema)
675
+ if (wire === undefined) {
676
+ const codec = Schema.toCodecJson(schema)
677
+ const decode = Schema.decodeUnknownOption(codec)
678
+ wire = {
679
+ raw: stringOnly(SchemaAST.toEncoded(codec.ast)),
680
+ encode: Schema.encodeUnknownSync(codec),
681
+ decode: (encoded) => {
682
+ try {
683
+ return decode(encoded)
684
+ } catch {
685
+ return Option.none()
686
+ }
687
+ }
688
+ }
689
+ wires.set(schema, wire)
690
+ }
691
+ return wire
692
+ }
693
+
694
+ /**
695
+ * Encodes a value into the string an element carries.
696
+ *
697
+ * **When to use**
698
+ *
699
+ * Use when routing clicks yourself. `of` and `open` already run it.
700
+ *
701
+ * **Details**
702
+ *
703
+ * The value goes through `Schema.toCodecJson`. The form on the wire is decided
704
+ * once per schema, from the codec's encoded side, never per value:
705
+ *
706
+ * - when the encoded side can only be a string (`String`, a brand of it,
707
+ * string literals, a template literal, or a union of those), the string is
708
+ * sent as it is
709
+ * - otherwise the encoded value goes through `JSON.stringify`, and back
710
+ * through `JSON.parse`
711
+ *
712
+ * **Gotchas**
713
+ *
714
+ * Throws when the value has no JSON form, as `Schema.encodeSync` does.
715
+ *
716
+ * @stability unstable
717
+ * @category values
718
+ * @since 4.1.5
719
+ */
720
+ export const encodeValue = <S extends ValueSchema>(schema: S, value: S["Type"]): string => {
721
+ const wire = wireOf(schema)
722
+ const encoded = wire.encode(value)
723
+ if (wire.raw) return encoded as string
724
+ const json = JSON.stringify(encoded)
725
+ if (json === undefined) throw new Error("ChatInteraction.encodeValue: the value has no JSON form")
726
+ return json
727
+ }
728
+
729
+ /**
730
+ * Decodes the string an element carried, as `encodeValue` wrote it.
731
+ *
732
+ * **Details**
733
+ *
734
+ * Gives none for a string that no longer decodes, which is what a value
735
+ * posted under an older schema can do.
736
+ *
737
+ * @stability unstable
738
+ * @category values
739
+ * @since 4.1.5
740
+ */
741
+ export const decodeValue = <S extends ValueSchema>(schema: S, encoded: string): Option.Option<S["Type"]> => {
742
+ const wire = wireOf(schema)
743
+ if (wire.raw) return wire.decode(encoded)
744
+ let parsed: unknown
745
+ try {
746
+ parsed = JSON.parse(encoded)
747
+ } catch {
748
+ return Option.none()
749
+ }
750
+ return wire.decode(parsed)
751
+ }
752
+
753
+ const optional = <K extends string, V>(key: K, value: V | undefined): { readonly [P in K]?: V } =>
754
+ (value === undefined ? {} : { [key]: value }) as { readonly [P in K]?: V }
755
+
756
+ // -----------------------------------------------------------------------------
757
+ // definitions
758
+ // -----------------------------------------------------------------------------
759
+
760
+ /**
761
+ * A button definition.
762
+ *
763
+ * **Details**
764
+ *
765
+ * `of` gives the element to post. It takes the value when the definition has
766
+ * a schema for one, and `overrides` change the label or style of this one
767
+ * element.
768
+ *
769
+ * **Gotchas**
770
+ *
771
+ * `of` throws when the value cannot be encoded (a schema with no JSON form),
772
+ * as `Schema.encodeSync` does.
773
+ *
774
+ * @stability unstable
775
+ * @category definitions
776
+ * @since 4.1.5
777
+ */
778
+ export interface Button<out Id extends string, out Value extends ValueSchema | undefined = undefined> {
779
+ readonly [TypeId]: typeof TypeId
780
+ readonly kind: "button"
781
+ readonly id: Id
782
+ readonly label: string
783
+ readonly style: ChatUi.ButtonStyle | undefined
784
+ readonly value: Value
785
+ readonly of: (
786
+ ...args: Value extends ValueSchema ? [value: Value["Type"], overrides?: Button.Overrides]
787
+ : [overrides?: Button.Overrides]
788
+ ) => ChatUi.Button
789
+ }
790
+
791
+ /**
792
+ * Types that go with a button definition.
793
+ *
794
+ * @stability unstable
795
+ * @since 4.1.5
796
+ */
797
+ export declare namespace Button {
798
+ /**
799
+ * What one element may change from its definition.
800
+ *
801
+ * @stability unstable
802
+ * @category models
803
+ * @since 4.1.5
804
+ */
805
+ export interface Overrides {
806
+ readonly label?: string | undefined
807
+ readonly style?: ChatUi.ButtonStyle | undefined
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Defines a button.
813
+ *
814
+ * **Details**
815
+ *
816
+ * - The id names the handler in a `group`. It is sent to the platform as is,
817
+ * and counts toward `limits.actionDataLength` with the encoded value.
818
+ * - With no `value` schema the button carries no value, and its click's
819
+ * `value` is `undefined`.
820
+ *
821
+ * @stability unstable
822
+ * @category definitions
823
+ * @since 4.1.5
824
+ */
825
+ export const button = <const Id extends string, Value extends ValueSchema | undefined = undefined>(
826
+ id: Id,
827
+ options: {
828
+ readonly label: string
829
+ readonly style?: ChatUi.ButtonStyle | undefined
830
+ readonly value?: Value
831
+ }
832
+ ): Button<Id, Value> => {
833
+ const value = options.value as Value
834
+ return {
835
+ [TypeId]: TypeId,
836
+ kind: "button",
837
+ id,
838
+ label: options.label,
839
+ style: options.style,
840
+ value,
841
+ of: ((...args: ReadonlyArray<any>): ChatUi.Button => {
842
+ const overrides: Button.Overrides | undefined = value === undefined ? args[0] : args[1]
843
+ return {
844
+ _tag: "Button",
845
+ id,
846
+ label: overrides?.label ?? options.label,
847
+ ...optional("style", overrides?.style ?? options.style),
848
+ ...optional("value", value === undefined ? undefined : encodeValue(value, args[0]))
849
+ }
850
+ }) as Button<Id, Value>["of"]
851
+ }
852
+ }
853
+
854
+ /**
855
+ * A select definition, for a message. Its options are given at the post, to
856
+ * `of`.
857
+ *
858
+ * **Gotchas**
859
+ *
860
+ * `of` throws when an option's value cannot be encoded.
861
+ *
862
+ * @stability unstable
863
+ * @category definitions
864
+ * @since 4.1.5
865
+ */
866
+ export interface Select<out Id extends string, out Value extends ValueSchema | undefined = undefined> {
867
+ readonly [TypeId]: typeof TypeId
868
+ readonly kind: "select"
869
+ readonly id: Id
870
+ readonly placeholder: string | undefined
871
+ readonly value: Value
872
+ readonly of: (options: {
873
+ readonly options: ReadonlyArray<{ readonly label: string; readonly value: TypeOf<Value, string> }>
874
+ readonly selected?: TypeOf<Value, string> | undefined
875
+ }) => ChatUi.Select
876
+ }
877
+
878
+ /**
879
+ * Defines a single-choice select for a message.
880
+ *
881
+ * **Details**
882
+ *
883
+ * With no `value` schema the options' values are plain strings.
884
+ *
885
+ * @stability unstable
886
+ * @category definitions
887
+ * @since 4.1.5
888
+ */
889
+ export const select = <const Id extends string, Value extends ValueSchema | undefined = undefined>(
890
+ id: Id,
891
+ options: {
892
+ readonly placeholder?: string | undefined
893
+ readonly value?: Value
894
+ }
895
+ ): Select<Id, Value> => {
896
+ const value = options.value as Value
897
+ const encode = (option: unknown): string => value === undefined ? option as string : encodeValue(value, option)
898
+ return {
899
+ [TypeId]: TypeId,
900
+ kind: "select",
901
+ id,
902
+ placeholder: options.placeholder,
903
+ value,
904
+ of: (args) => ({
905
+ _tag: "Select",
906
+ id,
907
+ ...optional("placeholder", options.placeholder),
908
+ options: args.options.map((option) => ({ label: option.label, value: encode(option.value) })),
909
+ ...optional("selected", args.selected === undefined ? undefined : encode(args.selected))
910
+ })
911
+ }
912
+ }
913
+
914
+ /**
915
+ * A text input in a modal, one line or several.
916
+ *
917
+ * @stability unstable
918
+ * @category fields
919
+ * @since 4.1.5
920
+ */
921
+ export interface TextInput<out Optional extends boolean = false> {
922
+ readonly [TypeId]: typeof TypeId
923
+ readonly kind: "textInput"
924
+ readonly label: string
925
+ readonly multiline: boolean
926
+ readonly placeholder: string | undefined
927
+ readonly optional: Optional
928
+ readonly minLength: number | undefined
929
+ readonly maxLength: number | undefined
930
+ }
931
+
932
+ /**
933
+ * Defines a text input for a modal. Its id is its key in `fields`.
934
+ *
935
+ * **Details**
936
+ *
937
+ * Its value is a `string`, or `string | undefined` when `optional` is true.
938
+ *
939
+ * @stability unstable
940
+ * @category fields
941
+ * @since 4.1.5
942
+ */
943
+ export const textInput = <const Optional extends boolean = false>(options: {
944
+ readonly label: string
945
+ readonly multiline?: boolean | undefined
946
+ readonly placeholder?: string | undefined
947
+ readonly optional?: Optional | undefined
948
+ readonly minLength?: number | undefined
949
+ readonly maxLength?: number | undefined
950
+ }): TextInput<NoInfer<Optional>> => ({
951
+ [TypeId]: TypeId,
952
+ kind: "textInput",
953
+ label: options.label,
954
+ multiline: options.multiline ?? false,
955
+ placeholder: options.placeholder,
956
+ optional: (options.optional ?? false) as Optional,
957
+ minLength: options.minLength,
958
+ maxLength: options.maxLength
959
+ })
960
+
961
+ /**
962
+ * A select in a modal whose options are fixed in the definition.
963
+ *
964
+ * @stability unstable
965
+ * @category fields
966
+ * @since 4.1.5
967
+ */
968
+ export interface Choice<out Value extends string, out Optional extends boolean = false> {
969
+ readonly [TypeId]: typeof TypeId
970
+ readonly kind: "choice"
971
+ readonly label: string
972
+ readonly placeholder: string | undefined
973
+ readonly options: ReadonlyArray<{ readonly label: string; readonly value: Value }>
974
+ readonly optional: Optional
975
+ }
976
+
977
+ /**
978
+ * Defines a select for a modal whose options are fixed here. Its value is the
979
+ * union of the option values.
980
+ *
981
+ * @stability unstable
982
+ * @category fields
983
+ * @since 4.1.5
984
+ */
985
+ export const choice = <const Value extends string, const Optional extends boolean = false>(options: {
986
+ readonly label: string
987
+ readonly placeholder?: string | undefined
988
+ readonly options: ReadonlyArray<{ readonly label: string; readonly value: Value }>
989
+ readonly optional?: Optional | undefined
990
+ }): Choice<Value, NoInfer<Optional>> => ({
991
+ [TypeId]: TypeId,
992
+ kind: "choice",
993
+ label: options.label,
994
+ placeholder: options.placeholder,
995
+ options: options.options,
996
+ optional: (options.optional ?? false) as Optional
997
+ })
998
+
999
+ /**
1000
+ * A select in a modal whose options are given when the modal opens.
1001
+ *
1002
+ * @stability unstable
1003
+ * @category fields
1004
+ * @since 4.1.5
1005
+ */
1006
+ export interface SelectInput<
1007
+ out Value extends ValueSchema | undefined = undefined,
1008
+ out Optional extends boolean = false
1009
+ > {
1010
+ readonly [TypeId]: typeof TypeId
1011
+ readonly kind: "selectInput"
1012
+ readonly label: string
1013
+ readonly placeholder: string | undefined
1014
+ readonly value: Value
1015
+ readonly optional: Optional
1016
+ }
1017
+
1018
+ /**
1019
+ * Defines a select for a modal. Its id is its key in `fields`, and its
1020
+ * options are given to the modal's `open`.
1021
+ *
1022
+ * @stability unstable
1023
+ * @category fields
1024
+ * @since 4.1.5
1025
+ */
1026
+ export const selectInput = <
1027
+ Value extends ValueSchema | undefined = undefined,
1028
+ const Optional extends boolean = false
1029
+ >(options: {
1030
+ readonly label: string
1031
+ readonly placeholder?: string | undefined
1032
+ readonly value?: Value
1033
+ readonly optional?: Optional | undefined
1034
+ }): SelectInput<Value, NoInfer<Optional>> => ({
1035
+ [TypeId]: TypeId,
1036
+ kind: "selectInput",
1037
+ label: options.label,
1038
+ placeholder: options.placeholder,
1039
+ value: options.value as Value,
1040
+ optional: (options.optional ?? false) as Optional
1041
+ })
1042
+
1043
+ /**
1044
+ * Plain text between a modal's inputs.
1045
+ *
1046
+ * @stability unstable
1047
+ * @category fields
1048
+ * @since 4.1.5
1049
+ */
1050
+ export interface Text {
1051
+ readonly [TypeId]: typeof TypeId
1052
+ readonly kind: "text"
1053
+ readonly text: string
1054
+ }
1055
+
1056
+ /**
1057
+ * Defines plain text for a modal. It has no value, so its key is not in
1058
+ * `submit.values`.
1059
+ *
1060
+ * **Gotchas**
1061
+ *
1062
+ * The text is plain, not Markdown.
1063
+ *
1064
+ * @stability unstable
1065
+ * @category fields
1066
+ * @since 4.1.5
1067
+ */
1068
+ export const text = (text: string): Text => ({ [TypeId]: TypeId, kind: "text", text })
1069
+
1070
+ /**
1071
+ * Any field of a modal.
1072
+ *
1073
+ * @stability unstable
1074
+ * @category fields
1075
+ * @since 4.1.5
1076
+ */
1077
+ export type Field = TextInput<boolean> | Choice<string, boolean> | SelectInput<any, boolean> | Text
1078
+
1079
+ /**
1080
+ * A modal's fields by id, shown in key order.
1081
+ *
1082
+ * @stability unstable
1083
+ * @category fields
1084
+ * @since 4.1.5
1085
+ */
1086
+ export interface Fields {
1087
+ readonly [id: string]: Field
1088
+ }
1089
+
1090
+ type Maybe<A, Optional extends boolean> = Optional extends true ? A | undefined : A
1091
+
1092
+ /**
1093
+ * The decoded value of one field.
1094
+ *
1095
+ * @stability unstable
1096
+ * @category fields
1097
+ * @since 4.1.5
1098
+ */
1099
+ export type FieldValue<F> = F extends TextInput<infer Optional> ? Maybe<string, Optional>
1100
+ : F extends Choice<infer Value, infer Optional> ? Maybe<Value, Optional>
1101
+ : F extends SelectInput<infer Value, infer Optional> ? Maybe<TypeOf<Value, string>, Optional>
1102
+ : never
1103
+
1104
+ /**
1105
+ * `submit.values`: one key per input, none for `text`.
1106
+ *
1107
+ * @stability unstable
1108
+ * @category fields
1109
+ * @since 4.1.5
1110
+ */
1111
+ export type Values<Fs extends Fields> = {
1112
+ readonly [K in keyof Fs as Fs[K] extends Text ? never : K]: FieldValue<Fs[K]>
1113
+ }
1114
+
1115
+ /**
1116
+ * The options `open` must be given: one list per `selectInput` field.
1117
+ *
1118
+ * @stability unstable
1119
+ * @category fields
1120
+ * @since 4.1.5
1121
+ */
1122
+ export type SelectOptions<Fs extends Fields> = {
1123
+ readonly [K in keyof Fs as Fs[K] extends SelectInput<any, any> ? K : never]: Fs[K] extends
1124
+ SelectInput<infer Value, any> ? ReadonlyArray<{ readonly label: string; readonly value: TypeOf<Value, string> }>
1125
+ : never
1126
+ }
1127
+
1128
+ /**
1129
+ * What a modal's `open` takes: the metadata when the modal has a schema for
1130
+ * it, the options of each `selectInput`, and initial values.
1131
+ *
1132
+ * @stability unstable
1133
+ * @category fields
1134
+ * @since 4.1.5
1135
+ */
1136
+ export type OpenOptions<Metadata extends ValueSchema | undefined, Fs extends Fields> =
1137
+ & (Metadata extends ValueSchema ? { readonly metadata: Metadata["Type"] } : {})
1138
+ & ({} extends SelectOptions<Fs> ? {} : { readonly options: SelectOptions<Fs> })
1139
+ & { readonly initial?: { readonly [K in keyof Values<Fs>]?: Values<Fs>[K] | undefined } | undefined }
1140
+
1141
+ /**
1142
+ * A modal definition.
1143
+ *
1144
+ * **Details**
1145
+ *
1146
+ * `open` gives the reply that opens the modal. A click's or a command's
1147
+ * handler can return it.
1148
+ *
1149
+ * **Gotchas**
1150
+ *
1151
+ * `open` throws when the metadata or an option's value cannot be encoded.
1152
+ *
1153
+ * @stability unstable
1154
+ * @category definitions
1155
+ * @since 4.1.5
1156
+ */
1157
+ export interface Modal<
1158
+ out Id extends string,
1159
+ in out Metadata extends ValueSchema | undefined = undefined,
1160
+ in out Fs extends Fields = {}
1161
+ > {
1162
+ readonly [TypeId]: typeof TypeId
1163
+ readonly kind: "modal"
1164
+ readonly id: Id
1165
+ readonly title: string
1166
+ readonly submitLabel: string | undefined
1167
+ readonly metadata: Metadata
1168
+ readonly fields: Fs
1169
+ readonly open: (
1170
+ ...args: {} extends OpenOptions<Metadata, Fs> ? [options?: OpenOptions<Metadata, Fs>]
1171
+ : [options: OpenOptions<Metadata, Fs>]
1172
+ ) => OpenModal
1173
+ }
1174
+
1175
+ /**
1176
+ * Defines a modal.
1177
+ *
1178
+ * **Details**
1179
+ *
1180
+ * - The id names the submit's handler in a `group`. With the encoded
1181
+ * metadata it counts toward `limits.modalMetadataLength`.
1182
+ * - Inputs and texts together count toward `limits.modalFields`.
1183
+ *
1184
+ * **Gotchas**
1185
+ *
1186
+ * A modal the platform will not take can only fail after the click's or
1187
+ * command's handler returned it: the adapter opens nothing and calls
1188
+ * `Handler.refused`. A portable modal has a title of 24 or less, labels of 45
1189
+ * or less, at most 5 fields, and an id plus metadata under 100 characters.
1190
+ *
1191
+ * @stability unstable
1192
+ * @category definitions
1193
+ * @since 4.1.5
1194
+ */
1195
+ export const modal = <
1196
+ const Id extends string,
1197
+ const Fs extends Fields,
1198
+ Metadata extends ValueSchema | undefined = undefined
1199
+ >(
1200
+ id: Id,
1201
+ options: {
1202
+ readonly title: string
1203
+ readonly submitLabel?: string | undefined
1204
+ readonly metadata?: Metadata
1205
+ readonly fields: Fs
1206
+ }
1207
+ ): Modal<Id, Metadata, Fs> => {
1208
+ const metadata = options.metadata as Metadata
1209
+ const open = (args?: {
1210
+ readonly metadata?: unknown
1211
+ readonly options?: { readonly [id: string]: ReadonlyArray<{ readonly label: string; readonly value: unknown }> }
1212
+ readonly initial?: { readonly [id: string]: unknown }
1213
+ }): OpenModal => {
1214
+ const elements: Array<ChatUi.ModalElement> = []
1215
+ for (const [field, definition] of Object.entries(options.fields)) {
1216
+ const initial = args?.initial?.[field]
1217
+ switch (definition.kind) {
1218
+ case "text": {
1219
+ elements.push({ _tag: "Text", text: definition.text })
1220
+ break
1221
+ }
1222
+ case "textInput": {
1223
+ elements.push({
1224
+ _tag: "TextInput",
1225
+ id: field,
1226
+ label: definition.label,
1227
+ ...optional("multiline", definition.multiline ? true : undefined),
1228
+ ...optional("placeholder", definition.placeholder),
1229
+ ...optional("initial", initial as string | undefined),
1230
+ ...optional("optional", definition.optional ? true : undefined),
1231
+ ...optional("minLength", definition.minLength),
1232
+ ...optional("maxLength", definition.maxLength)
1233
+ })
1234
+ break
1235
+ }
1236
+ case "choice":
1237
+ case "selectInput": {
1238
+ const schema: ValueSchema | undefined = definition.kind === "selectInput" ? definition.value : undefined
1239
+ const encode = (value: unknown): string => schema === undefined ? value as string : encodeValue(schema, value)
1240
+ const choices = definition.kind === "choice" ? definition.options : args?.options?.[field] ?? []
1241
+ elements.push({
1242
+ _tag: "SelectInput",
1243
+ id: field,
1244
+ label: definition.label,
1245
+ ...optional("placeholder", definition.placeholder),
1246
+ options: choices.map((option) => ({ label: option.label, value: encode(option.value) })),
1247
+ ...optional("initial", initial === undefined ? undefined : encode(initial)),
1248
+ ...optional("optional", definition.optional ? true : undefined)
1249
+ })
1250
+ break
1251
+ }
1252
+ }
1253
+ }
1254
+ return OpenModal.make({
1255
+ modal: {
1256
+ _tag: "Modal",
1257
+ id,
1258
+ title: options.title,
1259
+ ...optional("submitLabel", options.submitLabel),
1260
+ ...optional("metadata", metadata === undefined ? undefined : encodeValue(metadata, args?.metadata)),
1261
+ elements
1262
+ }
1263
+ })
1264
+ }
1265
+ return {
1266
+ [TypeId]: TypeId,
1267
+ kind: "modal",
1268
+ id,
1269
+ title: options.title,
1270
+ submitLabel: options.submitLabel,
1271
+ metadata,
1272
+ fields: options.fields,
1273
+ open: open as Modal<Id, Metadata, Fs>["open"]
1274
+ }
1275
+ }
1276
+
1277
+ /**
1278
+ * A slash command definition: a name and at most one text argument.
1279
+ *
1280
+ * **Details**
1281
+ *
1282
+ * `description` and `argument` are what registration needs. Slack reads its
1283
+ * own from the app manifest, so there they are documentation.
1284
+ *
1285
+ * @stability unstable
1286
+ * @category definitions
1287
+ * @since 4.1.5
1288
+ */
1289
+ export interface Command<out Id extends string> {
1290
+ readonly [TypeId]: typeof TypeId
1291
+ readonly kind: "command"
1292
+ readonly id: Id
1293
+ readonly description: string
1294
+ readonly argument: {
1295
+ readonly name: string
1296
+ readonly description: string
1297
+ readonly required: boolean
1298
+ } | undefined
1299
+ }
1300
+
1301
+ /**
1302
+ * Defines a slash command.
1303
+ *
1304
+ * **Details**
1305
+ *
1306
+ * - The id is the command's name without the slash. It shares the registry's
1307
+ * id space with buttons, selects and modals.
1308
+ * - Slack sends everything typed after the name as one string. Discord gets
1309
+ * one `STRING` option named `argument.name`, and a command with no
1310
+ * `argument` has no options.
1311
+ * - `argument.required` defaults to false. Discord's client enforces it.
1312
+ * Slack cannot, so a portable handler still checks for an empty `text`.
1313
+ *
1314
+ * **Gotchas**
1315
+ *
1316
+ * A portable name matches `^[a-z0-9_-]{1,31}$` and a portable description is
1317
+ * 100 characters or less. Neither is checked here.
1318
+ *
1319
+ * @stability unstable
1320
+ * @category definitions
1321
+ * @since 4.1.5
1322
+ */
1323
+ export const command = <const Id extends string>(id: Id, options: {
1324
+ readonly description: string
1325
+ readonly argument?: {
1326
+ readonly name: string
1327
+ readonly description: string
1328
+ readonly required?: boolean | undefined
1329
+ } | undefined
1330
+ }): Command<Id> => ({
1331
+ [TypeId]: TypeId,
1332
+ kind: "command",
1333
+ id,
1334
+ description: options.description,
1335
+ argument: options.argument === undefined ? undefined : {
1336
+ name: options.argument.name,
1337
+ description: options.argument.description,
1338
+ required: options.argument.required ?? false
1339
+ }
1340
+ })
1341
+
1342
+ /**
1343
+ * Any definition that has a handler.
1344
+ *
1345
+ * @stability unstable
1346
+ * @category definitions
1347
+ * @since 4.1.5
1348
+ */
1349
+ export type Definition = Button<string, any> | Select<string, any> | Modal<string, any, any> | Command<string>
1350
+
1351
+ // -----------------------------------------------------------------------------
1352
+ // decoding
1353
+ // -----------------------------------------------------------------------------
1354
+
1355
+ const matches = (definition: Definition, event: Interaction): boolean => {
1356
+ switch (event._tag) {
1357
+ case "ButtonClicked":
1358
+ return definition.kind === "button"
1359
+ case "SelectChanged":
1360
+ return definition.kind === "select"
1361
+ case "ModalSubmitted":
1362
+ return definition.kind === "modal"
1363
+ case "CommandInvoked":
1364
+ return definition.kind === "command"
1365
+ }
1366
+ }
1367
+
1368
+ const decodeSubmit = (definition: Modal<string, any, any>, event: ModalSubmitted): Option.Option<unknown> => {
1369
+ let metadata: unknown = undefined
1370
+ if (definition.metadata !== undefined) {
1371
+ if (event.metadata === undefined) return Option.none()
1372
+ const decoded = decodeValue(definition.metadata, event.metadata)
1373
+ if (Option.isNone(decoded)) return decoded
1374
+ metadata = decoded.value
1375
+ }
1376
+ const values: Record<string, unknown> = {}
1377
+ for (const [id, field] of Object.entries(definition.fields as Fields)) {
1378
+ if (field.kind === "text") continue
1379
+ const encoded = Object.hasOwn(event.values, id) ? event.values[id] : undefined
1380
+ if (encoded === undefined) {
1381
+ if (!field.optional) return Option.none()
1382
+ values[id] = undefined
1383
+ continue
1384
+ }
1385
+ switch (field.kind) {
1386
+ case "textInput": {
1387
+ values[id] = encoded
1388
+ break
1389
+ }
1390
+ case "choice": {
1391
+ if (!field.options.some((option) => option.value === encoded)) return Option.none()
1392
+ values[id] = encoded
1393
+ break
1394
+ }
1395
+ case "selectInput": {
1396
+ if (field.value === undefined) {
1397
+ values[id] = encoded
1398
+ break
1399
+ }
1400
+ const decoded = decodeValue(field.value, encoded)
1401
+ if (Option.isNone(decoded)) return decoded
1402
+ values[id] = decoded.value
1403
+ break
1404
+ }
1405
+ }
1406
+ }
1407
+ return Option.some({ ...base(event), metadata, values })
1408
+ }
1409
+
1410
+ const base = (event: ButtonClicked | SelectChanged | ModalSubmitted) => ({
1411
+ id: event.id,
1412
+ thread: event.thread,
1413
+ messageId: event.messageId,
1414
+ userId: event.userId,
1415
+ raw: event.raw
1416
+ })
1417
+
1418
+ /** The event as the definition's handler takes it, or none when its value no longer decodes. */
1419
+ const decodeEvent = (definition: Definition, event: Interaction): Option.Option<unknown> => {
1420
+ switch (event._tag) {
1421
+ case "ButtonClicked": {
1422
+ if (definition.kind !== "button") return Option.none()
1423
+ if (definition.value === undefined) return Option.some({ ...base(event), value: undefined })
1424
+ if (event.value === undefined) return Option.none()
1425
+ return Option.map(decodeValue(definition.value, event.value), (value) => ({ ...base(event), value }))
1426
+ }
1427
+ case "SelectChanged": {
1428
+ if (definition.kind !== "select") return Option.none()
1429
+ if (definition.value === undefined) return Option.some({ ...base(event), value: event.value })
1430
+ return Option.map(decodeValue(definition.value, event.value), (value) => ({ ...base(event), value }))
1431
+ }
1432
+ case "ModalSubmitted": {
1433
+ return definition.kind === "modal" ? decodeSubmit(definition, event) : Option.none()
1434
+ }
1435
+ case "CommandInvoked": {
1436
+ return definition.kind === "command" ? Option.some(event) : Option.none()
1437
+ }
1438
+ }
1439
+ }
1440
+
1441
+ const fallback = (event: Interaction): Ack | Close => event._tag === "ModalSubmitted" ? close : ack
1442
+
1443
+ // -----------------------------------------------------------------------------
1444
+ // groups
1445
+ // -----------------------------------------------------------------------------
1446
+
1447
+ /**
1448
+ * The handler a definition asks for. None has an error channel.
1449
+ *
1450
+ * **Details**
1451
+ *
1452
+ * A button or a select answers `ack` or a modal to open. A modal answers
1453
+ * `close` or `errors` naming its own inputs. A command answers `respond`,
1454
+ * a modal to open or `defer`, and never `ack`: Discord has no silent answer
1455
+ * to a command.
1456
+ *
1457
+ * @stability unstable
1458
+ * @category groups
1459
+ * @since 4.1.5
1460
+ */
1461
+ export type HandlerFor<D extends Definition> = D extends Button<any, infer Value>
1462
+ ? (click: Click<TypeOf<Value, undefined>>) => Effect.Effect<ClickReply, never, any>
1463
+ : D extends Select<any, infer Value> ?
1464
+ (selected: Selected<TypeOf<Value, string>>) => Effect.Effect<ClickReply, never, any>
1465
+ : D extends Modal<any, infer Metadata, infer Fs> ? (
1466
+ submit: Submit<TypeOf<Metadata, undefined>, Values<Fs>>
1467
+ ) => Effect.Effect<Close | FieldErrors<keyof Values<Fs> & string>, never, any>
1468
+ : D extends Command<any> ? (command: CommandInvoked) => Effect.Effect<Respond | OpenModal | Defer, never, any>
1469
+ : never
1470
+
1471
+ /**
1472
+ * One handler per id in the group.
1473
+ *
1474
+ * @stability unstable
1475
+ * @category groups
1476
+ * @since 4.1.5
1477
+ */
1478
+ export type HandlersFrom<D extends Definition> = {
1479
+ readonly [Current in D as Current["id"]]: HandlerFor<Current>
1480
+ }
1481
+
1482
+ /**
1483
+ * The services a set of handlers needs.
1484
+ *
1485
+ * @stability unstable
1486
+ * @category groups
1487
+ * @since 4.1.5
1488
+ */
1489
+ export type HandlersServices<Handlers> = {
1490
+ readonly [K in keyof Handlers]: Handlers[K] extends (...args: any) => Effect.Effect<any, any, infer R> ? R : never
1491
+ }[keyof Handlers]
1492
+
1493
+ /**
1494
+ * A set of definitions whose handlers are registered together.
1495
+ *
1496
+ * **Details**
1497
+ *
1498
+ * - `toLayer` registers the handlers, with their services provided. It needs
1499
+ * the `Registry` that `ChatInteraction.layer` provides.
1500
+ * - `of` is the identity, for handlers written away from `toLayer`.
1501
+ *
1502
+ * **Gotchas**
1503
+ *
1504
+ * Two definitions with one id, in one group or across groups, are a defect
1505
+ * when the layer is built.
1506
+ *
1507
+ * @stability unstable
1508
+ * @category groups
1509
+ * @since 4.1.5
1510
+ */
1511
+ export interface Group<in out D extends Definition> {
1512
+ readonly [TypeId]: typeof TypeId
1513
+ readonly definitions: ReadonlyMap<string, D>
1514
+ readonly add: <const More extends ReadonlyArray<Definition>>(...definitions: More) => Group<D | More[number]>
1515
+ readonly merge: <const Groups extends ReadonlyArray<Group<any>>>(
1516
+ ...groups: Groups
1517
+ ) => Group<D | Group.Definitions<Groups[number]>>
1518
+ readonly toLayer: <Handlers extends HandlersFrom<D>, EX = never, RX = never>(
1519
+ build: Handlers | Effect.Effect<Handlers, EX, RX>
1520
+ ) => Layer.Layer<never, EX, Exclude<RX, Scope> | HandlersServices<Handlers> | Registry>
1521
+ readonly of: <const Handlers extends HandlersFrom<D>>(handlers: Handlers) => Handlers
1522
+ }
1523
+
1524
+ /**
1525
+ * Types that go with a group.
1526
+ *
1527
+ * @stability unstable
1528
+ * @since 4.1.5
1529
+ */
1530
+ export declare namespace Group {
1531
+ /**
1532
+ * The definitions of a group.
1533
+ *
1534
+ * @stability unstable
1535
+ * @category groups
1536
+ * @since 4.1.5
1537
+ */
1538
+ export type Definitions<G> = G extends Group<infer D> ? D : never
1539
+ }
1540
+
1541
+ const groupLists = new WeakMap<Group<any>, ReadonlyArray<Definition>>()
1542
+
1543
+ const makeGroup = <D extends Definition>(list: ReadonlyArray<D>): Group<D> => {
1544
+ const self: Group<D> = {
1545
+ [TypeId]: TypeId,
1546
+ definitions: new Map(list.map((definition) => [definition.id, definition])),
1547
+ add: (...definitions) => makeGroup([...list, ...definitions]),
1548
+ merge: (...groups) => makeGroup([...list, ...groups.flatMap((group) => groupLists.get(group) ?? [])]) as any,
1549
+ toLayer: (build) =>
1550
+ Layer.effectDiscard(Effect.gen(function*() {
1551
+ const handlers: Record<string, (event: any) => Effect.Effect<ClickReply | SubmitReply | CommandReply>> =
1552
+ Effect.isEffect(build)
1553
+ ? yield* build
1554
+ : build as any
1555
+ const context = yield* Effect.context<never>()
1556
+ const registry = yield* Registry
1557
+ yield* registry.register(list.map((definition): Registered => ({
1558
+ definition,
1559
+ handle: (event) => {
1560
+ const typed = decodeEvent(definition, event)
1561
+ return Option.isNone(typed)
1562
+ ? Effect.succeed(fallback(event))
1563
+ : Effect.provideContext(handlers[definition.id](typed.value), context)
1564
+ }
1565
+ })))
1566
+ })) as any,
1567
+ of: (handlers) => handlers
1568
+ }
1569
+ groupLists.set(self, list)
1570
+ return self
1571
+ }
1572
+
1573
+ /**
1574
+ * Groups definitions so their handlers can be registered together.
1575
+ *
1576
+ * @stability unstable
1577
+ * @category groups
1578
+ * @since 4.1.5
1579
+ */
1580
+ export const group = <const Definitions extends ReadonlyArray<Definition>>(
1581
+ ...definitions: Definitions
1582
+ ): Group<Definitions[number]> => makeGroup(definitions)
1583
+
1584
+ // -----------------------------------------------------------------------------
1585
+ // handler service and registry
1586
+ // -----------------------------------------------------------------------------
1587
+
1588
+ /**
1589
+ * What an adapter calls with an interaction. Public, for a consumer that
1590
+ * routes clicks itself.
1591
+ *
1592
+ * **Details**
1593
+ *
1594
+ * - The contract is to answer inside the platform's 3 seconds. There is no
1595
+ * error channel: a handler that cannot do its work still has to answer.
1596
+ * - `refused` is called when a click's handler returned `OpenModal` and no
1597
+ * modal opened, after the click was acked: by the adapter (the platform
1598
+ * has no `modals`, the modal's id plus metadata is over
1599
+ * `limits.modalMetadataLength`, it has more than `limits.modalFields`
1600
+ * fields, a title or label is too long, or the platform refused the call)
1601
+ * or by `handle` (the reply came after the deadline).
1602
+ * - A command's reply can be refused too: a private answer without
1603
+ * `ephemeral`, an element the platform lacks, an answer over
1604
+ * `limits.messageLength` or an element limit, a modal that cannot open,
1605
+ * or a refusal by the platform. A submit's replies always have an answer
1606
+ * the adapter can give.
1607
+ * - `command` answers `Ack` for a command it has no definition for, and the
1608
+ * adapter sends nothing for that. On Discord another library in the same
1609
+ * process can still answer it.
1610
+ *
1611
+ * **Gotchas**
1612
+ *
1613
+ * Neither platform redelivers a click or a submit, so there is no dedupe key.
1614
+ * A submit can still arrive twice for one modal: a handler that runs past
1615
+ * the deadline is interrupted, the platform shows its own error, the modal
1616
+ * stays open and the user can submit again. Nothing marks the second one as
1617
+ * a repeat, and the first run may have been cut off part way.
1618
+ *
1619
+ * @stability unstable
1620
+ * @category services
1621
+ * @since 4.1.5
1622
+ */
1623
+ export class Handler extends Context.Service<Handler, {
1624
+ readonly click: (event: ButtonClicked | SelectChanged) => Effect.Effect<ClickReply>
1625
+ readonly submit: (event: ModalSubmitted) => Effect.Effect<SubmitReply>
1626
+ readonly command: (event: CommandInvoked) => Effect.Effect<CommandReply>
1627
+ readonly refused: (
1628
+ event: ButtonClicked | SelectChanged | CommandInvoked,
1629
+ error: ChatError
1630
+ ) => Effect.Effect<void>
1631
+ }>()("effect/chat/ChatInteraction/Handler") {}
1632
+
1633
+ const lateClick = (event: ButtonClicked | SelectChanged) =>
1634
+ new ChatError({
1635
+ platform: event.thread.platform,
1636
+ op: "openModal",
1637
+ reason: new NotFound({ detail: interactionExpired })
1638
+ })
1639
+
1640
+ /**
1641
+ * Calls `Handler.click`, `Handler.submit` or `Handler.command` and gives
1642
+ * the reply, or `Late` when `deadline` passes first.
1643
+ *
1644
+ * **When to use**
1645
+ *
1646
+ * Use to deliver an interaction from an adapter. This is the one place the
1647
+ * deadline rule lives. Both adapters and
1648
+ * `ChatTest` call it, and a third-party adapter should.
1649
+ *
1650
+ * **Details**
1651
+ *
1652
+ * - A late click leaves its handler running, detached from the caller. When
1653
+ * it later returns `OpenModal`, the modal is dropped and `Handler.refused`
1654
+ * is called with a `ChatError` whose reason is `NotFound`, op `openModal`,
1655
+ * detail `interaction_expired`, platform `event.thread.platform`.
1656
+ * - A late submit or command interrupts its handler. `Late` is given at the
1657
+ * deadline, without waiting for the handler's finalizers to finish. A
1658
+ * command handler that cannot answer in time returns `defer` first.
1659
+ * - `deadline` is the handler's share of the platform's 3 seconds, not the 3
1660
+ * seconds. The adapter subtracts what its own answer costs. This function
1661
+ * knows no platform.
1662
+ *
1663
+ * **Gotchas**
1664
+ *
1665
+ * A late click's handler keeps running only if the runtime lets it. One that
1666
+ * stops work once the response is sent (Cloudflare Workers without
1667
+ * `waitUntil`) kills it.
1668
+ *
1669
+ * @stability unstable
1670
+ * @category handling
1671
+ * @since 4.1.5
1672
+ */
1673
+ export const handle: {
1674
+ /**
1675
+ * Calls `Handler.click`, `Handler.submit` or `Handler.command` and gives
1676
+ * the reply, or `Late` when `deadline` passes first.
1677
+ *
1678
+ * **When to use**
1679
+ *
1680
+ * Use to deliver an interaction from an adapter. This is the one place the
1681
+ * deadline rule lives. Both adapters and
1682
+ * `ChatTest` call it, and a third-party adapter should.
1683
+ *
1684
+ * **Details**
1685
+ *
1686
+ * - A late click leaves its handler running, detached from the caller. When
1687
+ * it later returns `OpenModal`, the modal is dropped and `Handler.refused`
1688
+ * is called with a `ChatError` whose reason is `NotFound`, op `openModal`,
1689
+ * detail `interaction_expired`, platform `event.thread.platform`.
1690
+ * - A late submit or command interrupts its handler. `Late` is given at the
1691
+ * deadline, without waiting for the handler's finalizers to finish. A
1692
+ * command handler that cannot answer in time returns `defer` first.
1693
+ * - `deadline` is the handler's share of the platform's 3 seconds, not the 3
1694
+ * seconds. The adapter subtracts what its own answer costs. This function
1695
+ * knows no platform.
1696
+ *
1697
+ * **Gotchas**
1698
+ *
1699
+ * A late click's handler keeps running only if the runtime lets it. One that
1700
+ * stops work once the response is sent (Cloudflare Workers without
1701
+ * `waitUntil`) kills it.
1702
+ *
1703
+ * @stability unstable
1704
+ * @category handling
1705
+ * @since 4.1.5
1706
+ */
1707
+ (event: ButtonClicked | SelectChanged, deadline: Duration.Duration): Effect.Effect<ClickReply | Late, never, Handler>
1708
+ /**
1709
+ * Calls `Handler.click`, `Handler.submit` or `Handler.command` and gives
1710
+ * the reply, or `Late` when `deadline` passes first.
1711
+ *
1712
+ * **When to use**
1713
+ *
1714
+ * Use to deliver an interaction from an adapter. This is the one place the
1715
+ * deadline rule lives. Both adapters and
1716
+ * `ChatTest` call it, and a third-party adapter should.
1717
+ *
1718
+ * **Details**
1719
+ *
1720
+ * - A late click leaves its handler running, detached from the caller. When
1721
+ * it later returns `OpenModal`, the modal is dropped and `Handler.refused`
1722
+ * is called with a `ChatError` whose reason is `NotFound`, op `openModal`,
1723
+ * detail `interaction_expired`, platform `event.thread.platform`.
1724
+ * - A late submit or command interrupts its handler. `Late` is given at the
1725
+ * deadline, without waiting for the handler's finalizers to finish. A
1726
+ * command handler that cannot answer in time returns `defer` first.
1727
+ * - `deadline` is the handler's share of the platform's 3 seconds, not the 3
1728
+ * seconds. The adapter subtracts what its own answer costs. This function
1729
+ * knows no platform.
1730
+ *
1731
+ * **Gotchas**
1732
+ *
1733
+ * A late click's handler keeps running only if the runtime lets it. One that
1734
+ * stops work once the response is sent (Cloudflare Workers without
1735
+ * `waitUntil`) kills it.
1736
+ *
1737
+ * @stability unstable
1738
+ * @category handling
1739
+ * @since 4.1.5
1740
+ */
1741
+ (event: ModalSubmitted, deadline: Duration.Duration): Effect.Effect<SubmitReply | Late, never, Handler>
1742
+ /**
1743
+ * Calls `Handler.click`, `Handler.submit` or `Handler.command` and gives
1744
+ * the reply, or `Late` when `deadline` passes first.
1745
+ *
1746
+ * **When to use**
1747
+ *
1748
+ * Use to deliver an interaction from an adapter. This is the one place the
1749
+ * deadline rule lives. Both adapters and
1750
+ * `ChatTest` call it, and a third-party adapter should.
1751
+ *
1752
+ * **Details**
1753
+ *
1754
+ * - A late click leaves its handler running, detached from the caller. When
1755
+ * it later returns `OpenModal`, the modal is dropped and `Handler.refused`
1756
+ * is called with a `ChatError` whose reason is `NotFound`, op `openModal`,
1757
+ * detail `interaction_expired`, platform `event.thread.platform`.
1758
+ * - A late submit or command interrupts its handler. `Late` is given at the
1759
+ * deadline, without waiting for the handler's finalizers to finish. A
1760
+ * command handler that cannot answer in time returns `defer` first.
1761
+ * - `deadline` is the handler's share of the platform's 3 seconds, not the 3
1762
+ * seconds. The adapter subtracts what its own answer costs. This function
1763
+ * knows no platform.
1764
+ *
1765
+ * **Gotchas**
1766
+ *
1767
+ * A late click's handler keeps running only if the runtime lets it. One that
1768
+ * stops work once the response is sent (Cloudflare Workers without
1769
+ * `waitUntil`) kills it.
1770
+ *
1771
+ * @stability unstable
1772
+ * @category handling
1773
+ * @since 4.1.5
1774
+ */
1775
+ (event: CommandInvoked, deadline: Duration.Duration): Effect.Effect<CommandReply | Late, never, Handler>
1776
+ /**
1777
+ * Calls `Handler.click`, `Handler.submit` or `Handler.command` and gives
1778
+ * the reply, or `Late` when `deadline` passes first.
1779
+ *
1780
+ * **When to use**
1781
+ *
1782
+ * Use to deliver an interaction from an adapter. This is the one place the
1783
+ * deadline rule lives. Both adapters and
1784
+ * `ChatTest` call it, and a third-party adapter should.
1785
+ *
1786
+ * **Details**
1787
+ *
1788
+ * - A late click leaves its handler running, detached from the caller. When
1789
+ * it later returns `OpenModal`, the modal is dropped and `Handler.refused`
1790
+ * is called with a `ChatError` whose reason is `NotFound`, op `openModal`,
1791
+ * detail `interaction_expired`, platform `event.thread.platform`.
1792
+ * - A late submit or command interrupts its handler. `Late` is given at the
1793
+ * deadline, without waiting for the handler's finalizers to finish. A
1794
+ * command handler that cannot answer in time returns `defer` first.
1795
+ * - `deadline` is the handler's share of the platform's 3 seconds, not the 3
1796
+ * seconds. The adapter subtracts what its own answer costs. This function
1797
+ * knows no platform.
1798
+ *
1799
+ * **Gotchas**
1800
+ *
1801
+ * A late click's handler keeps running only if the runtime lets it. One that
1802
+ * stops work once the response is sent (Cloudflare Workers without
1803
+ * `waitUntil`) kills it.
1804
+ *
1805
+ * @stability unstable
1806
+ * @category handling
1807
+ * @since 4.1.5
1808
+ */
1809
+ (event: Interaction, deadline: Duration.Duration): Effect.Effect<ClickReply | SubmitReply | CommandReply | Late, never, Handler>
1810
+ } = (event: Interaction, deadline: Duration.Duration): Effect.Effect<any, never, Handler> =>
1811
+ // Keep startup and the deadline handoff atomic with respect to caller interruption.
1812
+ Effect.uninterruptibleMask((restore) =>
1813
+ Effect.gen(function*() {
1814
+ const handler = yield* Handler
1815
+ // Detached, so the reply at the deadline waits for neither a late click nor a late submit's cleanup.
1816
+ const fiber: Fiber.Fiber<ClickReply | SubmitReply | CommandReply> = yield* Effect.forkDetach(
1817
+ event._tag === "ModalSubmitted"
1818
+ ? handler.submit(event)
1819
+ : event._tag === "CommandInvoked"
1820
+ ? handler.command(event)
1821
+ : handler.click(event)
1822
+ )
1823
+ const exit = yield* Effect.onInterrupt(
1824
+ restore(Effect.timeoutOption(Fiber.await(fiber), deadline)),
1825
+ () => Fiber.interrupt(fiber)
1826
+ )
1827
+ if (Option.isSome(exit)) return yield* exit.value
1828
+ if (event._tag === "ModalSubmitted" || event._tag === "CommandInvoked") {
1829
+ // Interrupt without delaying the deadline reply.
1830
+ yield* Effect.forkDetach(Fiber.interrupt(fiber))
1831
+ return late
1832
+ }
1833
+ yield* Effect.forkDetach(Effect.flatMap(
1834
+ Fiber.await(fiber),
1835
+ (exit) =>
1836
+ Exit.isSuccess(exit) && exit.value._tag === "OpenModal"
1837
+ ? handler.refused(event, lateClick(event))
1838
+ : Effect.void
1839
+ ))
1840
+ return late
1841
+ })
1842
+ )
1843
+
1844
+ const late: Late = Late.make({})
1845
+
1846
+ /**
1847
+ * One registered definition with its handler, services already provided.
1848
+ *
1849
+ * **Details**
1850
+ *
1851
+ * `handle` answers `ack` or `close` without calling the handler when the
1852
+ * event does not match the definition or its value no longer decodes. A
1853
+ * command that does not match is answered `ack`.
1854
+ *
1855
+ * @stability unstable
1856
+ * @category services
1857
+ * @since 4.1.5
1858
+ */
1859
+ export interface Registered {
1860
+ readonly definition: Definition
1861
+ readonly handle: (event: Interaction) => Effect.Effect<ClickReply | SubmitReply | CommandReply>
1862
+ }
1863
+
1864
+ /**
1865
+ * Where groups put their handlers. `ChatInteraction.layer` provides it.
1866
+ *
1867
+ * **Details**
1868
+ *
1869
+ * `register` dies when an id is already registered.
1870
+ *
1871
+ * @stability unstable
1872
+ * @category services
1873
+ * @since 4.1.5
1874
+ */
1875
+ export class Registry extends Context.Service<Registry, {
1876
+ readonly register: (entries: ReadonlyArray<Registered>) => Effect.Effect<void>
1877
+ readonly get: (id: string) => Effect.Effect<Registered | undefined>
1878
+ }>()("effect/chat/ChatInteraction/Registry") {}
1879
+
1880
+ /**
1881
+ * Why an interaction reached no handler, or why its handler's reply was not
1882
+ * carried out.
1883
+ *
1884
+ * **Details**
1885
+ *
1886
+ * - `UnknownId`: no definition has the id, or it is a definition of another
1887
+ * kind.
1888
+ * - `InvalidValue`: the value or metadata no longer decodes, or a required
1889
+ * input is missing.
1890
+ * - `ReplyRefused`: `Handler.refused` was called, with the adapter's error.
1891
+ *
1892
+ * @stability unstable
1893
+ * @category models
1894
+ * @since 4.1.5
1895
+ */
1896
+ export type Unhandled =
1897
+ | { readonly reason: "UnknownId" | "InvalidValue" }
1898
+ | { readonly reason: "ReplyRefused"; readonly error: ChatError }
1899
+
1900
+ /**
1901
+ * The `Handler` that routes by id to the registered definitions, and an
1902
+ * empty `Registry`. Group layers go on top with `Layer.provideMerge`.
1903
+ *
1904
+ * **Details**
1905
+ *
1906
+ * - An interaction with an unknown id, or with a value that no longer
1907
+ * decodes, is logged and answered `ack` or `close`. `unhandled` sees it
1908
+ * first. It cannot change the answer.
1909
+ * - A command with an unknown id is answered `ack`, which the adapter sends
1910
+ * nothing for, and logged at debug level: on Discord it may belong to
1911
+ * another library in the same process.
1912
+ * - `Handler.refused` is routed to `unhandled` too, as `ReplyRefused`, and
1913
+ * logged.
1914
+ *
1915
+ * @stability unstable
1916
+ * @category layers
1917
+ * @since 4.1.5
1918
+ */
1919
+ export const layer = <R = never>(options?: {
1920
+ readonly unhandled?: ((event: Interaction, why: Unhandled) => Effect.Effect<void, never, R>) | undefined
1921
+ }): Layer.Layer<Handler | Registry, never, R> =>
1922
+ Layer.effectContext(Effect.gen(function*() {
1923
+ const context = yield* Effect.context<R>()
1924
+ const entries = new Map<string, Registered>()
1925
+ const report = (event: Interaction, why: Unhandled, message: string): Effect.Effect<void> =>
1926
+ Effect.andThen(
1927
+ options?.unhandled === undefined ? Effect.void : Effect.provideContext(options.unhandled(event, why), context),
1928
+ (event._tag === "CommandInvoked" && why.reason === "UnknownId"
1929
+ ? Effect.logDebug(message)
1930
+ : Effect.logWarning(message)).pipe(Effect.annotateLogs({
1931
+ "chat.platform": event.thread.platform,
1932
+ "chat.interaction.id": event.id,
1933
+ "chat.interaction.reason": why.reason
1934
+ }))
1935
+ )
1936
+ const route = (event: Interaction): Effect.Effect<ClickReply | SubmitReply | CommandReply> =>
1937
+ Effect.suspend(() => {
1938
+ const entry = entries.get(event.id)
1939
+ if (entry === undefined || !matches(entry.definition, event)) {
1940
+ return Effect.as(
1941
+ report(event, { reason: "UnknownId" }, "ChatInteraction: no handler for this id"),
1942
+ fallback(event)
1943
+ )
1944
+ }
1945
+ if (Option.isNone(decodeEvent(entry.definition, event))) {
1946
+ return Effect.as(
1947
+ report(event, { reason: "InvalidValue" }, "ChatInteraction: the value no longer decodes"),
1948
+ fallback(event)
1949
+ )
1950
+ }
1951
+ return entry.handle(event)
1952
+ })
1953
+ const registry = Registry.of({
1954
+ register: (registered) =>
1955
+ Effect.suspend(() => {
1956
+ const ids = new Set<string>()
1957
+ for (const entry of registered) {
1958
+ const id = entry.definition.id
1959
+ if (entries.has(id) || ids.has(id)) {
1960
+ return Effect.die(new Error("ChatInteraction: the id \"" + id + "\" is already registered"))
1961
+ }
1962
+ ids.add(id)
1963
+ }
1964
+ for (const entry of registered) entries.set(entry.definition.id, entry)
1965
+ return Effect.void
1966
+ }),
1967
+ get: (id) => Effect.sync(() => entries.get(id))
1968
+ })
1969
+ const handler = Handler.of({
1970
+ click: (event) => route(event) as Effect.Effect<ClickReply>,
1971
+ submit: (event) => route(event) as Effect.Effect<SubmitReply>,
1972
+ command: (event) => route(event) as Effect.Effect<CommandReply>,
1973
+ refused: (event, error) =>
1974
+ report(event, { reason: "ReplyRefused", error }, "ChatInteraction: the reply was not carried out").pipe(
1975
+ Effect.annotateLogs("chat.error", error.message)
1976
+ )
1977
+ })
1978
+ return Context.make(Handler, handler).pipe(Context.add(Registry, registry))
1979
+ }))