@openclaw/discord 2026.11.3 → 2026.11.5-beta.2

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 (220) hide show
  1. package/dist/.setup/{account-inspect-8cCu6uPG.mjs → account-inspect-DGkdWwix.mjs} +1 -1
  2. package/dist/.setup/{accounts-ljrzXBJi.mjs → accounts-C_25wyxC.mjs} +9 -6
  3. package/dist/.setup/{active-turn-thread-route-C4tp9noA.mjs → active-turn-thread-route-KvRTAVE3.mjs} +1 -2
  4. package/dist/.setup/{allow-list-BKqOldGy.mjs → allow-list-BXrS8-R9.mjs} +4 -152
  5. package/dist/.setup/{api-DqmMUZau.mjs → api-BlBD4ism.mjs} +10 -20
  6. package/dist/.setup/{approval-handler.runtime-D0qu1um7.mjs → approval-handler.runtime-BGYjX1t9.mjs} +80 -61
  7. package/dist/.setup/{approval-message-updates-CdurC9Ej.mjs → approval-message-updates-DKsCfxSW.mjs} +2 -2
  8. package/dist/.setup/{audit-ChorIwio.mjs → audit-5b-FXj9R.mjs} +4 -4
  9. package/dist/.setup/{channel-ZilgdF5e.mjs → channel-CWwTHWFo.mjs} +134 -202
  10. package/dist/.setup/channel-access-9cyzozUP.mjs +24 -0
  11. package/dist/.setup/channel.setup-B3MtmBQG.mjs +238 -0
  12. package/dist/.setup/{components-Du9NhD8h.mjs → components-YCvQ6YLS.mjs} +209 -430
  13. package/dist/.setup/components.base-CiS0h_XP.mjs +32 -0
  14. package/dist/.setup/{config-schema-_uBILpQf.mjs → config-schema-BNKN1cu5.mjs} +6 -7
  15. package/dist/.setup/{conversation-binding-route-8Ul1KpGF.mjs → conversation-binding-route-kCTw8cij.mjs} +2 -2
  16. package/dist/.setup/{directory-config-3iVub-3m.mjs → directory-config-Ble81PWH.mjs} +1 -1
  17. package/dist/.setup/{directory-live-BDVl2DoC.mjs → directory-live-DH3tpS3x.mjs} +52 -57
  18. package/dist/.setup/{discord-BMD-JiVS.mjs → discord-DGVSguhx.mjs} +1124 -1710
  19. package/dist/.setup/{doctor-hQKbkNKq.mjs → doctor-eujgbnpZ.mjs} +3 -5
  20. package/dist/.setup/endpoint-runtime-lf4DeLas.mjs +139 -0
  21. package/dist/.setup/guilds-eDq22iSM.mjs +22 -0
  22. package/dist/.setup/{handle-action-B1lmt4ms.mjs → handle-action-CktwmzMz.mjs} +15 -15
  23. package/dist/.setup/{handle-action.guild-admin-B6g31cwt.mjs → handle-action.guild-admin-WLQ7fRqI.mjs} +5 -5
  24. package/dist/.setup/listeners-Df8lx3vK.mjs +47 -0
  25. package/dist/.setup/{live-policy-config-C_Q966Wh.mjs → live-policy-config-DiBVuaU6.mjs} +2 -3
  26. package/dist/.setup/{message-handler-CkI3yMjL.mjs → message-handler-hhNSioxo.mjs} +154 -115
  27. package/dist/.setup/{message-handler.preflight-CEfkFV9U.mjs → message-handler.preflight-BZcZE1o-.mjs} +30 -105
  28. package/dist/.setup/{message-handler.preflight-pluralkit-D5si80_L.mjs → message-handler.preflight-pluralkit-CYZfXXb6.mjs} +9 -22
  29. package/dist/.setup/{message-handler.process-DsMtetRf.mjs → message-handler.process-B0n-mQ99.mjs} +256 -373
  30. package/dist/.setup/outbound-payload-BaZmjewa.mjs +447 -0
  31. package/dist/.setup/{outbound-session-route-BtUpGBTb.mjs → outbound-session-route-Cgx4i9cS.mjs} +139 -86
  32. package/dist/.setup/{preflight-audio-wWgsZG5F.mjs → preflight-audio-C6QtD6HX.mjs} +1 -5
  33. package/dist/.setup/{presence-cache-DCeTsL73.mjs → presence-cache-Dq-3nH7R.mjs} +1 -6
  34. package/dist/.setup/{probe-CBaoCs-c.mjs → probe-DezB-6xz.mjs} +5 -9
  35. package/dist/.setup/{provider-CI_OLfvz.mjs → provider-BN2bCIUp.mjs} +3440 -4308
  36. package/dist/.setup/{provider-session.runtime-TWOo_JZx.mjs → provider-session.runtime-Dr_5X43t.mjs} +3 -3
  37. package/dist/.setup/provider.runtime-BuJpl0Pv.mjs +1 -0
  38. package/dist/.setup/proxy-fetch-BzXwBAXt.mjs +30 -0
  39. package/dist/.setup/{realtime-session.runtime-DvfS4vJj.mjs → realtime-session.runtime-BTDWsV4d.mjs} +44 -81
  40. package/dist/.setup/{receive-recovery-CKvaG2Hf.mjs → receive-recovery-C3Ks4wAQ.mjs} +13 -27
  41. package/dist/.setup/{resolve-allowlist-common-cIjtqh2F.mjs → resolve-allowlist-common-Bk8Fj6Ik.mjs} +3 -13
  42. package/dist/.setup/{resolve-channels-Cj5i7hzj.mjs → resolve-channels-Bp8frXvc.mjs} +7 -8
  43. package/dist/.setup/{resolve-users-BQLbysRB.mjs → resolve-users-Cvcj22sG.mjs} +4 -7
  44. package/dist/.setup/{runtime-RWnuJgWB.mjs → runtime-BJaCvlmq.mjs} +196 -239
  45. package/dist/.setup/{runtime-plifsKg9.mjs → runtime-BMgTyuwg.mjs} +6 -6
  46. package/dist/.setup/{secret-config-contract-z6FhbT8E.mjs → secret-config-contract-B1kE4sDv.mjs} +4 -9
  47. package/dist/.setup/{send-da6ENJ9f.mjs → send-CVW7V-VZ.mjs} +149 -175
  48. package/dist/.setup/{send.components-CWZUuGvA.mjs → send.components-C8YXdnO_.mjs} +59 -71
  49. package/dist/.setup/{send.outbound-qZ3iK3Vq.mjs → send.outbound-Uzcmh3Yd.mjs} +76 -129
  50. package/dist/.setup/{send.receipt-C18khRYH.mjs → send.receipt-NZDOTZBU.mjs} +30 -32
  51. package/dist/.setup/{send.shared-CnlMgoqQ.mjs → send.shared-a_6Oeyg1.mjs} +38 -115
  52. package/dist/.setup/{sender-identity-DgbJykq0.mjs → sender-identity-76HFb8eK.mjs} +3 -9
  53. package/dist/.setup/setup-plugin-api-BExhGEhL.mjs +2 -0
  54. package/dist/.setup/shared-interactive-DmzaoKOM.mjs +316 -0
  55. package/dist/.setup/{shared-CY5vJM48.mjs → shared-yDUSExm2.mjs} +8 -11
  56. package/dist/.setup/{subagent-hooks-CIu2TFz3.mjs → subagent-hooks-CDkdHQyy.mjs} +1 -1
  57. package/dist/.setup/{system-events-DCOLXkwS.mjs → system-events-yfWz150v.mjs} +2 -2
  58. package/dist/.setup/{target-resolver-CApivu3G.mjs → target-resolver-BOOzqxxM.mjs} +3 -3
  59. package/dist/.setup/{thread-bindings-DcvT_JgI.mjs → thread-bindings-zce4cpu_.mjs} +12 -20
  60. package/dist/.setup/{thread-bindings.manager-5Sh7yedN.mjs → thread-bindings.manager-NywKzUtc.mjs} +22 -42
  61. package/dist/.setup/{thread-bindings.session-updates-BMdJeJMc.mjs → thread-bindings.session-updates-D0j7oh8S.mjs} +11 -18
  62. package/dist/.setup/{threading-CzjFeUSe.mjs → threading-DodLYDt-.mjs} +68 -105
  63. package/dist/.setup/{timeouts-CuNARfyw.mjs → timeouts-cIxzatmv.mjs} +1 -1
  64. package/dist/.setup/{transcripts-source-8RDQrSVb.mjs → transcripts-source-ie9GBWaU.mjs} +110 -179
  65. package/dist/.setup/{voice-runtime-BsDILmAv.mjs → voice-runtime-B7V_LTdX.mjs} +231 -452
  66. package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -0
  67. package/dist/account-inspect-api.js +1 -1
  68. package/dist/action-runtime-api.js +1 -2
  69. package/dist/activities-api.js +286 -341
  70. package/dist/api.js +16 -16
  71. package/dist/channel-config-api.js +1 -2
  72. package/dist/channel-plugin-api.js +1 -2
  73. package/dist/contract-api.js +1 -2
  74. package/dist/directory-contract-api.js +1 -1
  75. package/dist/runtime-api.js +22 -22
  76. package/dist/runtime-setter-api.js +1 -2
  77. package/dist/secret-contract-api.js +1 -2
  78. package/dist/security-audit-contract-api.js +1 -2
  79. package/dist/security-contract-api.js +1 -2
  80. package/dist/session-key-api.js +1 -2
  81. package/dist/setup-entry.js +1 -1
  82. package/dist/setup-plugin-api.js +1 -2
  83. package/dist/src/voice/audio-worker.runtime.js +56 -68
  84. package/dist/subagent-hooks-api.js +1 -1
  85. package/dist/thread-binding-api.js +1 -2
  86. package/dist/transcripts-source-api.js +1 -1
  87. package/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
  88. package/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
  89. package/node_modules/@types/lodash/README.md +1 -1
  90. package/node_modules/@types/lodash/common/function.d.ts +2 -2
  91. package/node_modules/@types/lodash/package.json +2 -2
  92. package/node_modules/@types/node/README.md +1 -1
  93. package/node_modules/@types/node/package.json +2 -2
  94. package/node_modules/@types/node/util.d.ts +6 -3
  95. package/node_modules/discord-api-types/package.json +4 -4
  96. package/node_modules/discord-api-types/rest/v10/index.d.ts +8 -0
  97. package/node_modules/discord-api-types/rest/v10/index.d.ts.map +1 -1
  98. package/node_modules/discord-api-types/rest/v10/index.js +8 -0
  99. package/node_modules/discord-api-types/rest/v10/index.js.map +1 -1
  100. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts +26 -2
  101. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts.map +1 -1
  102. package/node_modules/discord-api-types/rest/v9/index.d.ts +8 -0
  103. package/node_modules/discord-api-types/rest/v9/index.d.ts.map +1 -1
  104. package/node_modules/discord-api-types/rest/v9/index.js +8 -0
  105. package/node_modules/discord-api-types/rest/v9/index.js.map +1 -1
  106. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts +26 -2
  107. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts.map +1 -1
  108. package/node_modules/typebox/build/format/duration.d.mts +2 -2
  109. package/node_modules/typebox/build/format/duration.mjs +2 -2
  110. package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
  111. package/node_modules/typebox/build/format/idn_email.mjs +1 -0
  112. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
  113. package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
  114. package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
  115. package/node_modules/typebox/build/format/ipv4.mjs +2 -2
  116. package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
  117. package/node_modules/typebox/build/format/ipv6.mjs +1 -1
  118. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  119. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  120. package/node_modules/typebox/build/schema/build.mjs +1 -0
  121. package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
  122. package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
  123. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
  124. package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
  125. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
  126. package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
  127. package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
  128. package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
  129. package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
  130. package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
  131. package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
  132. package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
  133. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
  134. package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
  135. package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
  136. package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
  137. package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
  138. package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
  139. package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
  140. package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
  141. package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
  142. package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
  143. package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
  144. package/node_modules/typebox/build/system/memory/create.mjs +18 -13
  145. package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
  146. package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
  147. package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
  148. package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
  149. package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
  150. package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
  151. package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
  152. package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
  153. package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
  154. package/node_modules/typebox/build/system/memory/update.mjs +43 -16
  155. package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
  156. package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
  157. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
  158. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
  159. package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
  160. package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
  161. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
  162. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
  163. package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
  164. package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
  165. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
  166. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
  167. package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
  168. package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
  169. package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
  170. package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
  171. package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
  172. package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
  173. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
  174. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
  175. package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
  176. package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
  177. package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
  178. package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
  179. package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
  180. package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
  181. package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
  182. package/node_modules/typebox/package.json +1 -1
  183. package/node_modules/typebox/readme.md +1 -1
  184. package/node_modules/undici/docs/docs/api/Interceptors.md +15 -2
  185. package/node_modules/undici/lib/dispatcher/client-h2.js +78 -3
  186. package/node_modules/undici/lib/dispatcher/pool-base.js +20 -3
  187. package/node_modules/undici/package.json +3 -3
  188. package/node_modules/undici/types/api.d.ts +1 -1
  189. package/node_modules/undici/types/utility.d.ts +4 -4
  190. package/node_modules/uuid/package.json +17 -17
  191. package/node_modules/zod/package.json +1 -1
  192. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  193. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  194. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  195. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  196. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  197. package/node_modules/zod/src/v4/core/util.ts +13 -0
  198. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  199. package/node_modules/zod/v4/core/compile.cjs +8 -0
  200. package/node_modules/zod/v4/core/compile.js +8 -0
  201. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  202. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  203. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  204. package/node_modules/zod/v4/core/schemas.js +30 -0
  205. package/node_modules/zod/v4/core/util.cjs +15 -0
  206. package/node_modules/zod/v4/core/util.d.cts +2 -0
  207. package/node_modules/zod/v4/core/util.d.ts +2 -0
  208. package/node_modules/zod/v4/core/util.js +14 -0
  209. package/node_modules/zod/v4/core/versions.cjs +1 -1
  210. package/node_modules/zod/v4/core/versions.js +1 -1
  211. package/openclaw.plugin.json +1 -31
  212. package/package.json +8 -8
  213. package/dist/.setup/channel-access-DasWY_OV.mjs +0 -48
  214. package/dist/.setup/channel.setup-DaDQdctj.mjs +0 -249
  215. package/dist/.setup/outbound-adapter-DfAanoCO.mjs +0 -543
  216. package/dist/.setup/provider.runtime-DnionCyo.mjs +0 -2
  217. package/dist/.setup/setup-plugin-api-D1QuM187.mjs +0 -3
  218. package/dist/.setup/targets-UWWZ6gF7.mjs +0 -3
  219. package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
  220. package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
@@ -1,106 +1,34 @@
1
- import { l as resolveDiscordAccount } from "./.setup/accounts-ljrzXBJi.mjs";
2
- import { D as getDiscordEndpointRuntime } from "./.setup/allow-list-BKqOldGy.mjs";
1
+ import { n as getDiscordEndpointRuntime } from "./.setup/endpoint-runtime-lf4DeLas.mjs";
3
2
  import { n as resolveDiscordChannelId$1 } from "./.setup/target-parsing-C-HyNxcE.mjs";
4
- import { S as parseDiscordActivityCustomId, i as buildDiscordPresentationComponents } from "./.setup/components-Du9NhD8h.mjs";
5
- import { r as sendDiscordComponentMessage } from "./.setup/send.components-CWZUuGvA.mjs";
6
- import { r as setDiscordActivitiesRuntime, t as DiscordActivitiesRuntime } from "./.setup/runtime-plifsKg9.mjs";
3
+ import { n as buildDiscordPresentationComponents, p as parseDiscordActivityCustomId } from "./.setup/shared-interactive-DmzaoKOM.mjs";
4
+ import { r as setDiscordActivitiesRuntime, t as DiscordActivitiesRuntime } from "./.setup/runtime-BMgTyuwg.mjs";
7
5
  import { asOptionalRecord, normalizeBoundedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
8
- import { randomBytes } from "node:crypto";
9
- import { fetchWithSsrFGuard as fetchWithSsrFGuard$1 } from "openclaw/plugin-sdk/ssrf-runtime";
6
+ import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
10
7
  import { logError } from "openclaw/plugin-sdk/logging-core";
8
+ import { randomBytes } from "node:crypto";
9
+ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
11
10
  import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
12
11
  import fs from "node:fs/promises";
12
+ import { containsAsciiControlCharacter } from "openclaw/plugin-sdk/string-normalization-runtime";
13
13
  import { resolveRequestClientIp } from "openclaw/plugin-sdk/webhook-ingress";
14
14
  import { WEBHOOK_BODY_READ_DEFAULTS, readJsonBodyWithLimit, sendHttpRequestRejection } from "openclaw/plugin-sdk/webhook-request-guards";
15
15
  import { WIDGET_CDN_ORIGINS } from "openclaw/plugin-sdk/widget-html";
16
- import { containsAsciiControlCharacter } from "openclaw/plugin-sdk/string-normalization-runtime";
17
- //#region extensions/discord/src/activities/discord-api.ts
18
- const DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token";
19
- const DISCORD_USER_URL = "https://discord.com/api/v10/users/@me";
20
- const DISCORD_HOST = "discord.com";
21
- const DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS = 15e3;
22
- const JSON_MAX_BYTES = 65536;
23
- const INSTANCE_ID_MAX_LENGTH = 256;
24
- function normalizeInstanceId(value) {
25
- const instanceId = normalizeBoundedOptionalString(value, INSTANCE_ID_MAX_LENGTH);
26
- return instanceId && !containsAsciiControlCharacter(instanceId) ? instanceId : void 0;
27
- }
28
- async function fetchDiscordJson(params) {
29
- const endpoint = Object.hasOwn(params, "endpointRuntime") ? params.endpointRuntime : getDiscordEndpointRuntime();
30
- const liveUrl = new URL(params.url);
31
- const endpointPath = liveUrl.pathname === "/api/oauth2/token" ? "/oauth2/token" : liveUrl.pathname.startsWith("/api/v10/") ? liveUrl.pathname.slice(8) : void 0;
32
- if (endpoint && !endpointPath) throw new Error("Discord Activity request is outside the configured endpoint routes");
33
- const { response, release } = endpoint ? {
34
- response: await endpoint.fetch(`${endpoint.descriptor.restApiBaseUrl}${endpointPath}${liveUrl.search}`, {
35
- ...params.init,
36
- signal: params.init.signal ? AbortSignal.any([params.init.signal, AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)
37
- }),
38
- release: async () => {}
39
- } : await params.fetchGuard({
40
- url: params.url,
41
- fetchImpl: params.fetchImpl,
42
- init: params.init,
43
- policy: { allowedHostnames: [DISCORD_HOST] },
44
- auditContext: params.auditContext,
45
- timeoutMs: DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS
46
- });
47
- try {
48
- if (!response.ok) {
49
- await response.body?.cancel().catch(() => void 0);
50
- return {
51
- ok: false,
52
- status: response.status
53
- };
54
- }
55
- return {
56
- ok: true,
57
- status: response.status,
58
- body: await readProviderJsonResponse(response, "Discord Activity OAuth", { maxBytes: JSON_MAX_BYTES })
59
- };
60
- } finally {
61
- await release();
62
- }
63
- }
64
- async function resolveActivityInstanceChannel(params) {
65
- const endpointRuntime = getDiscordEndpointRuntime() ?? null;
66
- let result;
67
- try {
68
- result = await fetchDiscordJson({
69
- fetchGuard: params.fetchGuard,
70
- fetchImpl: params.proxyFetch,
71
- url: `https://discord.com/api/v10/applications/${encodeURIComponent(params.applicationId)}/activity-instances/${encodeURIComponent(params.instanceId)}`,
72
- init: { headers: { Authorization: `Bot ${params.botAuth}` } },
73
- auditContext: "discord.activities.instance",
74
- endpointRuntime
75
- });
76
- } catch {
77
- return;
78
- }
79
- if (!result.ok || !Array.isArray(result.body?.users) || !result.body.users.includes(params.discordUserId) || !result.body.location || typeof result.body.location !== "object") return;
80
- const channelId = result.body.location.channel_id;
81
- return typeof channelId === "string" && /^\d+$/.test(channelId) ? channelId : void 0;
82
- }
83
- //#endregion
84
16
  //#region extensions/discord/src/activities/rate-limit.ts
85
17
  const TOKEN_RATE_LIMIT = 10;
86
18
  const TOKEN_GLOBAL_RATE_LIMIT = 60;
87
19
  const TOKEN_RATE_WINDOW_MS = 6e4;
88
20
  const TOKEN_RATE_MAX_KEYS = 1024;
89
21
  var TokenRateLimiter = class {
90
- constructor(now) {
91
- this.now = now;
22
+ constructor() {
92
23
  this.attempts = /* @__PURE__ */ new Map();
93
24
  this.globalAttempts = [];
94
25
  }
95
26
  allowKey(key) {
96
- const now = this.now();
27
+ const now = Date.now();
97
28
  const active = (this.attempts.get(key) ?? []).filter((timestamp) => timestamp > now - TOKEN_RATE_WINDOW_MS);
98
29
  const allowed = active.length < TOKEN_RATE_LIMIT;
99
30
  if (allowed) {
100
- if (!this.attempts.has(key) && this.attempts.size >= TOKEN_RATE_MAX_KEYS) {
101
- const oldestKey = this.attempts.keys().next().value;
102
- if (typeof oldestKey === "string") this.attempts.delete(oldestKey);
103
- }
31
+ if (!this.attempts.has(key) && this.attempts.size >= TOKEN_RATE_MAX_KEYS) pruneMapToMaxSize(this.attempts, 1023);
104
32
  active.push(now);
105
33
  }
106
34
  this.attempts.delete(key);
@@ -108,7 +36,7 @@ var TokenRateLimiter = class {
108
36
  return allowed;
109
37
  }
110
38
  reserveGlobal() {
111
- const now = this.now();
39
+ const now = Date.now();
112
40
  this.globalAttempts = this.globalAttempts.filter((reservation) => reservation.at > now - TOKEN_RATE_WINDOW_MS);
113
41
  if (this.globalAttempts.length >= TOKEN_GLOBAL_RATE_LIMIT) return null;
114
42
  const reservation = { at: now };
@@ -248,11 +176,179 @@ run().catch((error) => {
248
176
  });
249
177
  `;
250
178
  //#endregion
251
- //#region extensions/discord/src/activities/http.ts
179
+ //#region extensions/discord/src/activities/store.ts
180
+ const DAY_MS = 864e5;
181
+ const DISCORD_EPOCH_MS = 14200704e5;
182
+ const WIDGET_TTL_MS = 7 * DAY_MS;
183
+ const SESSION_TTL_MS = 9e5;
184
+ const DOC_TOKEN_TTL_MS = 6e4;
185
+ const PENDING_LAUNCH_TTL_MS = 12e4;
186
+ function openDiscordActivityStores(openKeyedStore) {
187
+ const openStore = (namespace, maxEntries, defaultTtlMs) => openKeyedStore({
188
+ namespace,
189
+ maxEntries,
190
+ overflowPolicy: "evict-oldest",
191
+ defaultTtlMs
192
+ });
193
+ return {
194
+ widgets: openStore("activities-widgets", 64, WIDGET_TTL_MS),
195
+ sessions: openStore("activities-sessions", 256, SESSION_TTL_MS),
196
+ docTokens: openStore("activities-doc-tokens", 256, DOC_TOKEN_TTL_MS),
197
+ launches: openStore("activities-launches", 256, PENDING_LAUNCH_TTL_MS)
198
+ };
199
+ }
200
+ function pendingLaunchKey(accountId, channelId, discordUserId) {
201
+ return `${accountId}:${channelId}:${discordUserId}`;
202
+ }
203
+ async function applyActivityStoreIntent(store, key, intent) {
204
+ let observed = await store.observe(key);
205
+ while (true) {
206
+ const result = await store.compareAndApply(key, observed.comparison, intent(observed.value));
207
+ if (result.status !== "conflict") return result.status;
208
+ observed = result.current;
209
+ }
210
+ }
211
+ var DiscordActivityStore = class {
212
+ constructor(stores) {
213
+ this.stores = stores;
214
+ }
215
+ async createWidget(value) {
216
+ const id = randomBytes(16).toString("base64url");
217
+ await this.stores.widgets.register(id, {
218
+ ...value,
219
+ deliveredMessageId: null
220
+ });
221
+ return id;
222
+ }
223
+ async markWidgetDelivered(id, messageId) {
224
+ if (!/^\d+$/u.test(messageId)) throw new Error("Discord Activity delivery returned an invalid message ID");
225
+ if (await applyActivityStoreIntent(this.stores.widgets, id, (widget) => widget ? {
226
+ operation: "update",
227
+ action: "set",
228
+ value: {
229
+ ...widget,
230
+ deliveredMessageId: messageId
231
+ }
232
+ } : {
233
+ operation: "update",
234
+ action: "keep"
235
+ }) === "unchanged") throw new Error("Discord Activity widget disappeared before delivery was recorded");
236
+ }
237
+ async deleteWidget(id) {
238
+ await this.stores.widgets.delete(id);
239
+ }
240
+ async lookupWidget(id) {
241
+ return await this.stores.widgets.lookup(id);
242
+ }
243
+ async latestPostedWidgetForChannel(accountId, channelId) {
244
+ const entries = await this.stores.widgets.entries();
245
+ let match;
246
+ for (const entry of entries) {
247
+ if (entry.value.accountId !== accountId || entry.value.channelId !== channelId) continue;
248
+ if (entry.value.deliveredMessageId === null) continue;
249
+ const deliveryOrder = entry.value.deliveredMessageId ? BigInt(entry.value.deliveredMessageId) : BigInt(Math.max(0, Math.trunc(entry.value.createdAt - DISCORD_EPOCH_MS))) << 22n;
250
+ if (!match || deliveryOrder > match.deliveryOrder) match = {
251
+ entry,
252
+ deliveryOrder
253
+ };
254
+ }
255
+ return match ? {
256
+ id: match.entry.key,
257
+ widget: match.entry.value
258
+ } : null;
259
+ }
260
+ async createSession(value) {
261
+ const token = randomBytes(32).toString("base64url");
262
+ await this.stores.sessions.register(token, value);
263
+ return token;
264
+ }
265
+ async lookupSession(token) {
266
+ return await this.stores.sessions.lookup(token);
267
+ }
268
+ async createDocToken(value) {
269
+ const token = randomBytes(32).toString("base64url");
270
+ await this.stores.docTokens.register(token, value);
271
+ return token;
272
+ }
273
+ async consumeDocToken(token) {
274
+ return await this.stores.docTokens.consume(token);
275
+ }
276
+ async recordPendingLaunch(params) {
277
+ const key = pendingLaunchKey(params.accountId, params.channelId, params.discordUserId);
278
+ const { widgetId, createdAt } = params;
279
+ await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
280
+ operation: "update",
281
+ action: "set",
282
+ value: existing && (existing.state === "ambiguous" || existing.widgetId !== widgetId) ? {
283
+ state: "ambiguous",
284
+ createdAt
285
+ } : {
286
+ state: "single",
287
+ widgetId,
288
+ createdAt
289
+ }
290
+ }));
291
+ }
292
+ async retirePendingLaunch(accountId, channelId, discordUserId, widgetId) {
293
+ const key = pendingLaunchKey(accountId, channelId, discordUserId);
294
+ await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
295
+ operation: "delete",
296
+ action: existing?.state === "single" && existing.widgetId === widgetId ? "delete" : "keep"
297
+ }));
298
+ }
299
+ async consumePendingLaunch(accountId, channelId, discordUserId) {
300
+ const launch = await this.stores.launches.consume(pendingLaunchKey(accountId, channelId, discordUserId));
301
+ return launch?.state === "single" ? launch : void 0;
302
+ }
303
+ };
304
+ //#endregion
305
+ //#region extensions/discord/src/activities/register.ts
252
306
  const BODY_MAX_BYTES = 8192;
253
307
  const JSON_CONTENT_TYPE = "application/json; charset=utf-8";
254
308
  const WIDGET_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
255
309
  const DOC_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
310
+ const DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token";
311
+ const DISCORD_USER_URL = "https://discord.com/api/v10/users/@me";
312
+ const DISCORD_HOST = "discord.com";
313
+ const DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS = 15e3;
314
+ const JSON_MAX_BYTES = 65536;
315
+ const INSTANCE_ID_MAX_LENGTH = 256;
316
+ function normalizeInstanceId(value) {
317
+ const instanceId = normalizeBoundedOptionalString(value, INSTANCE_ID_MAX_LENGTH);
318
+ return instanceId && !containsAsciiControlCharacter(instanceId) ? instanceId : void 0;
319
+ }
320
+ async function fetchDiscordJson(params) {
321
+ const endpoint = Object.hasOwn(params, "endpointRuntime") ? params.endpointRuntime : getDiscordEndpointRuntime();
322
+ const liveUrl = new URL(params.url);
323
+ const endpointPath = liveUrl.pathname === "/api/oauth2/token" ? "/oauth2/token" : liveUrl.pathname.startsWith("/api/v10/") ? liveUrl.pathname.slice(8) : void 0;
324
+ if (endpoint && !endpointPath) throw new Error("Discord Activity request is outside the configured endpoint routes");
325
+ const { response, release } = endpoint ? {
326
+ response: await endpoint.fetch(`${endpoint.descriptor.restApiBaseUrl}${endpointPath}${liveUrl.search}`, {
327
+ ...params.init,
328
+ signal: params.init.signal ? AbortSignal.any([params.init.signal, AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)
329
+ }),
330
+ release: async () => {}
331
+ } : await fetchWithSsrFGuard({
332
+ url: params.url,
333
+ fetchImpl: params.fetchImpl,
334
+ init: params.init,
335
+ policy: { allowedHostnames: [DISCORD_HOST] },
336
+ auditContext: params.auditContext,
337
+ timeoutMs: DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS
338
+ });
339
+ try {
340
+ if (!response.ok) {
341
+ await response.body?.cancel().catch(() => void 0);
342
+ return { ok: false };
343
+ }
344
+ return {
345
+ ok: true,
346
+ body: await readProviderJsonResponse(response, "Discord Activity OAuth", { maxBytes: JSON_MAX_BYTES })
347
+ };
348
+ } finally {
349
+ await release();
350
+ }
351
+ }
256
352
  const DISCORD_ACTIVITY_WIDGET_CSP = `sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline' ${WIDGET_CDN_ORIGINS.join(" ")}; style-src 'unsafe-inline' ${WIDGET_CDN_ORIGINS.join(" ")}; img-src data: blob:; font-src data: ${WIDGET_CDN_ORIGINS.join(" ")}; connect-src 'none'; frame-ancestors *`;
257
353
  function respond(res, statusCode, body, contentType, headers) {
258
354
  res.statusCode = statusCode;
@@ -289,30 +385,60 @@ function extractApplicationId(req) {
289
385
  function bearerToken(req) {
290
386
  return ((readHeader(req, "authorization")?.trim())?.match(/^Bearer\s+([A-Za-z0-9_-]{43})$/i))?.[1];
291
387
  }
292
- function createDiscordActivityHttpHandler(deps) {
293
- const fetchGuard = deps.fetchGuard ?? fetchWithSsrFGuard$1;
294
- const limiter = new TokenRateLimiter(deps.now ?? Date.now);
295
- const readVendorAsset = deps.readVendorAsset ?? ((assetPath) => fs.readFile(assetPath));
296
- const reportError = deps.logError ?? logError;
297
- const bodyTimeoutMs = deps.bodyTimeoutMs ?? WEBHOOK_BODY_READ_DEFAULTS.preAuth.timeoutMs;
388
+ const DISCORD_WIDGET_HTML_MAX_BYTES = 49152;
389
+ const unavailable = () => ({
390
+ ok: false,
391
+ error: {
392
+ code: "unavailable",
393
+ message: "Discord Activities are unavailable for the current channel and account."
394
+ }
395
+ });
396
+ function resolveDiscordChannelId(context) {
397
+ const raw = context.nativeChannelId?.trim() || context.currentMessagingTarget?.trim() || context.currentChannelId?.trim() || context.deliveryContext?.to?.trim();
398
+ if (!raw) return;
399
+ try {
400
+ return resolveDiscordChannelId$1(raw);
401
+ } catch {
402
+ return;
403
+ }
404
+ }
405
+ function resolveDiscordPresentationRoute(context, runtime) {
406
+ if (context.messageChannel !== "discord") return;
407
+ const cfg = runtime.currentConfig();
408
+ const channelId = resolveDiscordChannelId(context);
409
+ const activityAccount = runtime.resolveAccount(context.accountId ?? context.deliveryContext?.accountId, cfg);
410
+ if (!channelId || !activityAccount) return;
411
+ return {
412
+ account: activityAccount,
413
+ cfg,
414
+ channelId
415
+ };
416
+ }
417
+ function registerDiscordActivities(api) {
418
+ setDiscordActivitiesRuntime(void 0);
419
+ const store = new DiscordActivityStore(openDiscordActivityStores(api.runtime.state.openKeyedStoreV2.bind(api.runtime.state)));
420
+ const runtime = new DiscordActivitiesRuntime(store, () => api.runtime.config.current());
421
+ setDiscordActivitiesRuntime(runtime);
422
+ const vendorAssetPath = api.resolvePath("assets/embedded-app-sdk.mjs");
423
+ const limiter = new TokenRateLimiter();
424
+ const bodyTimeoutMs = WEBHOOK_BODY_READ_DEFAULTS.preAuth.timeoutMs;
298
425
  let vendorAsset;
299
426
  let pendingLaunchFailureLogged = false;
300
427
  function logPendingLaunchFailure(error) {
301
428
  if (pendingLaunchFailureLogged) return;
302
429
  pendingLaunchFailureLogged = true;
303
- reportError(`discord activity: failed to consume pending launch: ${String(error)}`);
430
+ logError(`discord activity: failed to consume pending launch: ${String(error)}`);
304
431
  }
305
432
  async function handleToken(req, res) {
306
- const cfg = deps.runtime.currentConfig();
433
+ const cfg = runtime.currentConfig();
307
434
  const sourceIp = resolveRequestClientIp(req, cfg.gateway?.trustedProxies, cfg.gateway?.allowRealIpFallback === true) ?? "unknown";
308
435
  if (!limiter.allowKey(sourceIp)) return respondJson(res, 429, { error: "too many token requests" });
309
436
  const applicationId = extractApplicationId(req);
310
- const account = deps.runtime.resolveHttpAccount(applicationId);
437
+ const account = runtime.resolveHttpAccount(applicationId);
311
438
  if (!account) return respondJson(res, 503, { error: "Discord Activities is not fully configured" });
312
439
  const endpointRuntime = getDiscordEndpointRuntime() ?? null;
313
440
  const fetchAccountJson = (params) => fetchDiscordJson({
314
441
  ...params,
315
- fetchGuard,
316
442
  fetchImpl: account.proxyFetch,
317
443
  endpointRuntime
318
444
  }).catch(() => void 0);
@@ -359,7 +485,7 @@ function createDiscordActivityHttpHandler(deps) {
359
485
  if (!userResponse) return respondJson(res, 503, { error: "Discord user lookup unavailable" });
360
486
  const discordUserId = typeof userResponse.body?.id === "string" ? userResponse.body.id : void 0;
361
487
  if (!userResponse.ok || !discordUserId) return respondJson(res, 401, { error: "Discord user lookup failed" });
362
- const minted = await deps.runtime.store.createSession({
488
+ const minted = await runtime.store.createSession({
363
489
  discordUserId,
364
490
  accountId: account.accountId
365
491
  });
@@ -374,39 +500,47 @@ function createDiscordActivityHttpHandler(deps) {
374
500
  }
375
501
  async function handleWidget(req, res, url) {
376
502
  const token = bearerToken(req);
377
- const session = token ? await deps.runtime.store.lookupSession(token) : void 0;
503
+ const session = token ? await runtime.store.lookupSession(token) : void 0;
378
504
  if (!session) return respondJson(res, 401, { error: "invalid session" });
379
505
  const customId = url.searchParams.get("custom_id")?.trim() ?? "";
380
506
  const instanceId = normalizeInstanceId(url.searchParams.get("instance_id"));
381
- const account = deps.runtime.resolveAccount(session.accountId);
382
- const channelId = instanceId && account ? await resolveActivityInstanceChannel({
383
- fetchGuard,
384
- applicationId: account.applicationId,
385
- instanceId,
386
- discordUserId: session.discordUserId,
387
- botAuth: account.botAuth,
388
- proxyFetch: account.proxyFetch
389
- }) : void 0;
507
+ const account = runtime.resolveAccount(session.accountId);
508
+ let channelId;
509
+ if (instanceId && account) {
510
+ const discordUserId = session.discordUserId;
511
+ const endpointRuntime = getDiscordEndpointRuntime() ?? null;
512
+ const result = await fetchDiscordJson({
513
+ fetchImpl: account.proxyFetch,
514
+ url: `https://discord.com/api/v10/applications/${encodeURIComponent(account.applicationId)}/activity-instances/${encodeURIComponent(instanceId)}`,
515
+ init: { headers: { Authorization: `Bot ${account.botAuth}` } },
516
+ auditContext: "discord.activities.instance",
517
+ endpointRuntime
518
+ }).catch(() => void 0);
519
+ if (result?.ok && Array.isArray(result.body?.users) && result.body.users.includes(discordUserId)) {
520
+ const value = asOptionalRecord(result.body.location)?.channel_id;
521
+ channelId = typeof value === "string" && /^\d+$/.test(value) ? value : void 0;
522
+ }
523
+ }
390
524
  if (!channelId) return respondJson(res, 404, { error: "widget not found" });
391
525
  let resolved = null;
392
526
  const requestedWidgetId = WIDGET_ID_PATTERN.test(customId) ? customId : parseDiscordActivityCustomId(customId)?.widgetId;
393
527
  if (requestedWidgetId) {
394
- const widget = await deps.runtime.store.lookupWidget(requestedWidgetId);
528
+ const widget = await runtime.store.lookupWidget(requestedWidgetId);
395
529
  if (widget?.accountId !== session.accountId || widget.channelId !== channelId) return respondJson(res, 404, { error: "widget not found" });
396
530
  resolved = {
397
531
  id: requestedWidgetId,
398
532
  widget
399
533
  };
400
534
  try {
401
- await deps.runtime.store.retirePendingLaunch(session.accountId, channelId, session.discordUserId, requestedWidgetId);
535
+ await runtime.store.retirePendingLaunch(session.accountId, channelId, session.discordUserId, requestedWidgetId);
402
536
  } catch (error) {
403
537
  logPendingLaunchFailure(error);
404
538
  }
405
539
  } else {
406
540
  try {
407
- const pendingLaunch = await deps.runtime.store.consumePendingLaunch(session.accountId, channelId, session.discordUserId);
541
+ const pendingLaunch = await runtime.store.consumePendingLaunch(session.accountId, channelId, session.discordUserId);
408
542
  if (pendingLaunch) {
409
- const widget = await deps.runtime.store.lookupWidget(pendingLaunch.widgetId);
543
+ const widget = await runtime.store.lookupWidget(pendingLaunch.widgetId);
410
544
  if (widget?.accountId === session.accountId && widget.channelId === channelId) resolved = {
411
545
  id: pendingLaunch.widgetId,
412
546
  widget
@@ -415,10 +549,10 @@ function createDiscordActivityHttpHandler(deps) {
415
549
  } catch (error) {
416
550
  logPendingLaunchFailure(error);
417
551
  }
418
- resolved ??= await deps.runtime.store.latestPostedWidgetForChannel(session.accountId, channelId);
552
+ resolved ??= await runtime.store.latestPostedWidgetForChannel(session.accountId, channelId);
419
553
  }
420
554
  if (!resolved) return respondJson(res, 404, { error: "widget not found" });
421
- const docToken = await deps.runtime.store.createDocToken({
555
+ const docToken = await runtime.store.createDocToken({
422
556
  widgetId: resolved.id,
423
557
  accountId: session.accountId
424
558
  });
@@ -430,81 +564,49 @@ function createDiscordActivityHttpHandler(deps) {
430
564
  }
431
565
  async function handleDocument(res, widgetId, token) {
432
566
  if (!WIDGET_ID_PATTERN.test(widgetId) || !DOC_TOKEN_PATTERN.test(token)) return notFound(res, true);
433
- const capability = await deps.runtime.store.consumeDocToken(token);
567
+ const capability = await runtime.store.consumeDocToken(token);
434
568
  if (!capability || capability.widgetId !== widgetId) return notFound(res, true);
435
- const widget = await deps.runtime.store.lookupWidget(widgetId);
569
+ const widget = await runtime.store.lookupWidget(widgetId);
436
570
  if (!widget || widget.accountId !== capability.accountId) return notFound(res, true);
437
571
  return respond(res, 200, widget.html, "text/html; charset=utf-8", { "Content-Security-Policy": DISCORD_ACTIVITY_WIDGET_CSP });
438
572
  }
439
- return { handleHttpRequest: async (req, res) => {
440
- const url = new URL(req.url ?? "/", "http://localhost");
441
- if (url.pathname !== "/discord/activity" && !url.pathname.startsWith(`/discord/activity/`)) return false;
442
- if (!deps.runtime.hasEnabledAccounts()) return false;
443
- const relative = url.pathname.slice(17) || "/";
444
- if (req.method === "GET" && (relative === "/" || relative === "/index.html")) return respond(res, 200, DISCORD_ACTIVITY_SHELL_HTML, "text/html; charset=utf-8", { "Content-Security-Policy": DISCORD_ACTIVITY_SHELL_CSP });
445
- if (req.method === "GET" && relative === "/shell.js") return respond(res, 200, DISCORD_ACTIVITY_SHELL_JS, "text/javascript; charset=utf-8");
446
- if (req.method === "GET" && relative === "/vendor/embedded-app-sdk.mjs") {
447
- const pendingAsset = vendorAsset ??= readVendorAsset(deps.vendorAssetPath);
448
- try {
449
- return respond(res, 200, await pendingAsset, "text/javascript; charset=utf-8");
450
- } catch {
451
- if (vendorAsset === pendingAsset) vendorAsset = void 0;
452
- return notFound(res);
573
+ api.registerHttpRoute({
574
+ path: DISCORD_ACTIVITY_ROUTE_PREFIX,
575
+ auth: "plugin",
576
+ match: "prefix",
577
+ handler: async (req, res) => {
578
+ const url = new URL(req.url ?? "/", "http://localhost");
579
+ if (url.pathname !== "/discord/activity" && !url.pathname.startsWith(`/discord/activity/`)) return false;
580
+ if (!runtime.hasEnabledAccounts()) return false;
581
+ const relative = url.pathname.slice(17) || "/";
582
+ if (req.method === "GET" && (relative === "/" || relative === "/index.html")) return respond(res, 200, DISCORD_ACTIVITY_SHELL_HTML, "text/html; charset=utf-8", { "Content-Security-Policy": DISCORD_ACTIVITY_SHELL_CSP });
583
+ if (req.method === "GET" && relative === "/shell.js") return respond(res, 200, DISCORD_ACTIVITY_SHELL_JS, "text/javascript; charset=utf-8");
584
+ if (req.method === "GET" && relative === "/vendor/embedded-app-sdk.mjs") {
585
+ const pendingAsset = vendorAsset ??= fs.readFile(vendorAssetPath);
586
+ try {
587
+ return respond(res, 200, await pendingAsset, "text/javascript; charset=utf-8");
588
+ } catch {
589
+ if (vendorAsset === pendingAsset) vendorAsset = void 0;
590
+ return notFound(res);
591
+ }
453
592
  }
454
- }
455
- if (req.method === "POST" && relative === "/api/token") return await handleToken(req, res);
456
- if (req.method === "GET" && relative === "/api/widget") return await handleWidget(req, res, url);
457
- const documentMatch = relative.match(/^\/api\/widget\/([^/]+)\/doc$/);
458
- if (req.method === "GET" && documentMatch?.[1]) {
459
- let widgetId;
460
- try {
461
- widgetId = decodeURIComponent(documentMatch[1]);
462
- } catch {
463
- return notFound(res, true);
593
+ if (req.method === "POST" && relative === "/api/token") return await handleToken(req, res);
594
+ if (req.method === "GET" && relative === "/api/widget") return await handleWidget(req, res, url);
595
+ const documentMatch = relative.match(/^\/api\/widget\/([^/]+)\/doc$/);
596
+ if (req.method === "GET" && documentMatch?.[1]) {
597
+ let widgetId;
598
+ try {
599
+ widgetId = decodeURIComponent(documentMatch[1]);
600
+ } catch {
601
+ return notFound(res, true);
602
+ }
603
+ return await handleDocument(res, widgetId, url.searchParams.get("wt") ?? "");
464
604
  }
465
- return await handleDocument(res, widgetId, url.searchParams.get("wt") ?? "");
605
+ return notFound(res);
466
606
  }
467
- return notFound(res);
468
- } };
469
- }
470
- //#endregion
471
- //#region extensions/discord/src/activities/presenter.ts
472
- const DISCORD_WIDGET_HTML_MAX_BYTES = 49152;
473
- const unavailable = () => ({
474
- ok: false,
475
- error: {
476
- code: "unavailable",
477
- message: "Discord Activities are unavailable for the current channel and account."
478
- }
479
- });
480
- function resolveDiscordChannelId(context) {
481
- const raw = context.nativeChannelId?.trim() || context.currentMessagingTarget?.trim() || context.currentChannelId?.trim() || context.deliveryContext?.to?.trim();
482
- if (!raw) return;
483
- try {
484
- return resolveDiscordChannelId$1(raw);
485
- } catch {
486
- return;
487
- }
488
- }
489
- function resolveDiscordPresentationRoute(context, runtime) {
490
- if (context.messageChannel !== "discord") return;
491
- const cfg = runtime.currentConfig();
492
- const account = resolveDiscordAccount({
493
- cfg,
494
- accountId: context.accountId ?? context.deliveryContext?.accountId
495
607
  });
496
- const channelId = resolveDiscordChannelId(context);
497
- const activityAccount = runtime.resolveAccount(account.accountId, cfg);
498
- if (!channelId || !activityAccount) return;
499
- return {
500
- account: activityAccount,
501
- cfg,
502
- channelId
503
- };
504
- }
505
- /** Presents a canonical core widget document in the active Discord channel. */
506
- function createDiscordWidgetPresenter(runtime) {
507
- return {
608
+ /** Presents a canonical core widget document in the active Discord channel. */
609
+ api.registerWidgetPresenter({
508
610
  target: "current_channel",
509
611
  description: "Post an Activity launch button in the current Discord channel",
510
612
  capabilities: {
@@ -538,16 +640,11 @@ function createDiscordWidgetPresenter(runtime) {
538
640
  let result;
539
641
  let deliveredResult;
540
642
  let deliveryRecord;
541
- let deliveryRecordError;
542
- const recordDelivery = async (deliveryResult) => {
643
+ const recordDelivery = (deliveryResult) => {
543
644
  deliveredResult = deliveryResult;
544
- deliveryRecord ??= runtime.store.markWidgetDelivered(widgetId, deliveryResult.messageId);
545
- try {
546
- await deliveryRecord;
547
- } catch (error) {
548
- deliveryRecordError ??= new Error("Discord widget was delivered, but its delivery state could not be saved", { cause: error });
549
- throw deliveryRecordError;
550
- }
645
+ return deliveryRecord ??= runtime.store.markWidgetDelivered(widgetId, deliveryResult.messageId).catch((error) => {
646
+ throw new Error("Discord widget was delivered, but its delivery state could not be saved", { cause: error });
647
+ });
551
648
  };
552
649
  try {
553
650
  const components = buildDiscordPresentationComponents({ blocks: [{
@@ -561,6 +658,7 @@ function createDiscordWidgetPresenter(runtime) {
561
658
  }]
562
659
  }] });
563
660
  if (!components) throw new Error("Discord widget launch button could not be rendered");
661
+ const { sendDiscordComponentMessage } = await import("./.setup/send.components-C8YXdnO_.mjs").then((n) => n.i);
564
662
  result = await sendDiscordComponentMessage(`channel:${route.channelId}`, {
565
663
  ...components,
566
664
  text: title
@@ -572,11 +670,11 @@ function createDiscordWidgetPresenter(runtime) {
572
670
  });
573
671
  await recordDelivery(result);
574
672
  } catch (error) {
575
- if (deliveryRecordError) throw deliveryRecordError;
576
673
  if (!deliveredResult) {
577
674
  await runtime.store.deleteWidget(widgetId);
578
675
  throw error;
579
676
  }
677
+ await deliveryRecord;
580
678
  result = deliveredResult;
581
679
  }
582
680
  return {
@@ -587,160 +685,7 @@ function createDiscordWidgetPresenter(runtime) {
587
685
  }
588
686
  };
589
687
  }
590
- };
591
- }
592
- //#endregion
593
- //#region extensions/discord/src/activities/store.ts
594
- const DAY_MS = 864e5;
595
- const DISCORD_EPOCH_MS = 14200704e5;
596
- const WIDGET_TTL_MS = 7 * DAY_MS;
597
- const SESSION_TTL_MS = 9e5;
598
- const DOC_TOKEN_TTL_MS = 6e4;
599
- const PENDING_LAUNCH_TTL_MS = 12e4;
600
- function requireAtomicComparison(store) {
601
- if (!store.observe || !store.compareAndApply) throw new Error("Discord Activities require atomic plugin state comparisons");
602
- return store;
603
- }
604
- function openDiscordActivityStores(openKeyedStore) {
605
- const openStore = (namespace, maxEntries, defaultTtlMs) => openKeyedStore({
606
- namespace,
607
- maxEntries,
608
- overflowPolicy: "evict-oldest",
609
- defaultTtlMs
610
- });
611
- return {
612
- widgets: requireAtomicComparison(openStore("activities-widgets", 64, WIDGET_TTL_MS)),
613
- sessions: openStore("activities-sessions", 256, SESSION_TTL_MS),
614
- docTokens: openStore("activities-doc-tokens", 256, DOC_TOKEN_TTL_MS),
615
- launches: requireAtomicComparison(openStore("activities-launches", 256, PENDING_LAUNCH_TTL_MS))
616
- };
617
- }
618
- function pendingLaunchKey(accountId, channelId, discordUserId) {
619
- return `${accountId}:${channelId}:${discordUserId}`;
620
- }
621
- async function applyActivityStoreIntent(store, key, intent) {
622
- let observed = await store.observe(key);
623
- while (true) {
624
- const result = await store.compareAndApply(key, observed.comparison, intent(observed.value));
625
- if (result.status !== "conflict") return result.status;
626
- observed = result.current;
627
- }
628
- }
629
- var DiscordActivityStore = class {
630
- constructor(stores) {
631
- this.stores = stores;
632
- this.lastWidgetCreatedAt = 0;
633
- }
634
- async createWidget(value) {
635
- const id = randomBytes(16).toString("base64url");
636
- const createdAt = Math.max(value.createdAt, this.lastWidgetCreatedAt + 1);
637
- this.lastWidgetCreatedAt = createdAt;
638
- await this.stores.widgets.register(id, {
639
- ...value,
640
- createdAt,
641
- deliveredMessageId: null
642
- });
643
- return id;
644
- }
645
- async markWidgetDelivered(id, messageId) {
646
- if (!/^\d+$/u.test(messageId)) throw new Error("Discord Activity delivery returned an invalid message ID");
647
- if (await applyActivityStoreIntent(this.stores.widgets, id, (widget) => widget ? {
648
- operation: "update",
649
- action: "set",
650
- value: {
651
- ...widget,
652
- deliveredMessageId: messageId
653
- }
654
- } : {
655
- operation: "update",
656
- action: "keep"
657
- }) === "unchanged") throw new Error("Discord Activity widget disappeared before delivery was recorded");
658
- }
659
- async deleteWidget(id) {
660
- await this.stores.widgets.delete(id);
661
- }
662
- async lookupWidget(id) {
663
- return await this.stores.widgets.lookup(id);
664
- }
665
- async latestPostedWidgetForChannel(accountId, channelId) {
666
- const entries = await this.stores.widgets.entries();
667
- let match;
668
- for (const entry of entries) {
669
- if (entry.value.accountId !== accountId || entry.value.channelId !== channelId) continue;
670
- if (entry.value.deliveredMessageId === null) continue;
671
- const deliveryOrder = entry.value.deliveredMessageId ? BigInt(entry.value.deliveredMessageId) : BigInt(Math.max(0, Math.trunc(entry.value.createdAt - DISCORD_EPOCH_MS))) << 22n;
672
- if (!match || deliveryOrder > match.deliveryOrder) match = {
673
- entry,
674
- deliveryOrder
675
- };
676
- }
677
- return match ? {
678
- id: match.entry.key,
679
- widget: match.entry.value
680
- } : null;
681
- }
682
- async createSession(value) {
683
- const token = randomBytes(32).toString("base64url");
684
- await this.stores.sessions.register(token, value);
685
- return token;
686
- }
687
- async lookupSession(token) {
688
- return await this.stores.sessions.lookup(token);
689
- }
690
- async createDocToken(value) {
691
- const token = randomBytes(32).toString("base64url");
692
- await this.stores.docTokens.register(token, value);
693
- return token;
694
- }
695
- async consumeDocToken(token) {
696
- return await this.stores.docTokens.consume(token);
697
- }
698
- async recordPendingLaunch(params) {
699
- const key = pendingLaunchKey(params.accountId, params.channelId, params.discordUserId);
700
- const { widgetId, createdAt } = params;
701
- await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
702
- operation: "update",
703
- action: "set",
704
- value: existing && (existing.state === "ambiguous" || existing.widgetId !== widgetId) ? {
705
- state: "ambiguous",
706
- createdAt
707
- } : {
708
- state: "single",
709
- widgetId,
710
- createdAt
711
- }
712
- }));
713
- }
714
- async retirePendingLaunch(accountId, channelId, discordUserId, widgetId) {
715
- const key = pendingLaunchKey(accountId, channelId, discordUserId);
716
- await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
717
- operation: "delete",
718
- action: existing?.state === "single" && existing.widgetId === widgetId ? "delete" : "keep"
719
- }));
720
- }
721
- async consumePendingLaunch(accountId, channelId, discordUserId) {
722
- const launch = await this.stores.launches.consume(pendingLaunchKey(accountId, channelId, discordUserId));
723
- return launch?.state === "single" ? launch : void 0;
724
- }
725
- };
726
- //#endregion
727
- //#region extensions/discord/src/activities/register.ts
728
- function registerDiscordActivities(api) {
729
- setDiscordActivitiesRuntime(void 0);
730
- const store = new DiscordActivityStore(openDiscordActivityStores(api.runtime.state.openKeyedStore.bind(api.runtime.state)));
731
- const runtime = new DiscordActivitiesRuntime(store, api.config, api.runtime.config?.current ? () => api.runtime.config.current() : void 0);
732
- setDiscordActivitiesRuntime(runtime);
733
- const http = createDiscordActivityHttpHandler({
734
- runtime,
735
- vendorAssetPath: api.resolvePath("assets/embedded-app-sdk.mjs")
736
- });
737
- api.registerHttpRoute({
738
- path: DISCORD_ACTIVITY_ROUTE_PREFIX,
739
- auth: "plugin",
740
- match: "prefix",
741
- handler: http.handleHttpRequest
742
688
  });
743
- api.registerWidgetPresenter(createDiscordWidgetPresenter(runtime));
744
689
  }
745
690
  //#endregion
746
691
  export { registerDiscordActivities };