@openclaw/discord 2026.10.10 → 2026.11.5-beta.1

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 (217) hide show
  1. package/dist/.setup/{account-inspect-X_Xlr42B.mjs → account-inspect-CSz5Qodj.mjs} +1 -1
  2. package/dist/.setup/{accounts-C18HNgge.mjs → accounts-DtjvhJUj.mjs} +9 -6
  3. package/dist/.setup/{active-turn-thread-route-BAc_Xik-.mjs → active-turn-thread-route-DkPnk2x8.mjs} +1 -2
  4. package/dist/.setup/{allow-list-D1ZGfhXh.mjs → allow-list-DahA0Jxh.mjs} +3 -150
  5. package/dist/.setup/{api-Bth1wKF9.mjs → api-Bp0HI4q3.mjs} +10 -20
  6. package/dist/.setup/{approval-handler.runtime-BAoEELJJ.mjs → approval-handler.runtime-Cy53ugTf.mjs} +80 -61
  7. package/dist/.setup/{approval-message-updates-Cks-MSCJ.mjs → approval-message-updates-DqOXxPss.mjs} +2 -2
  8. package/dist/.setup/{audit-Dw_rAZIz.mjs → audit-DoPKOfQE.mjs} +4 -4
  9. package/dist/.setup/{channel-BMpMAeQL.mjs → channel-Ds6iuNdy.mjs} +134 -201
  10. package/dist/.setup/channel-access-DhJhVrdZ.mjs +23 -0
  11. package/dist/.setup/channel.setup-BLt9dkIG.mjs +235 -0
  12. package/dist/.setup/{components-BvOWSPxr.mjs → components-WTfUxead.mjs} +208 -426
  13. package/dist/.setup/components.base-C5sAPHe4.mjs +31 -0
  14. package/dist/.setup/{config-schema-Coyq5wOr.mjs → config-schema-GX2yDgIH.mjs} +6 -7
  15. package/dist/.setup/{conversation-binding-route-DOPUZNYo.mjs → conversation-binding-route-CZdm-X5A.mjs} +2 -2
  16. package/dist/.setup/{directory-config-CIqVnQtn.mjs → directory-config-BXJuh9-J.mjs} +1 -1
  17. package/dist/.setup/{directory-live-DUuPEWub.mjs → directory-live-CEopeb8Q.mjs} +55 -62
  18. package/dist/.setup/{discord-eFlHX1Gn.mjs → discord-r79VFjJp.mjs} +1087 -1664
  19. package/dist/.setup/{doctor-Dty_Ossy.mjs → doctor-UfLW8nye.mjs} +3 -5
  20. package/dist/.setup/endpoint-runtime-BM3x-m6O.mjs +138 -0
  21. package/dist/.setup/guilds-DQucP5Tn.mjs +21 -0
  22. package/dist/.setup/{handle-action-DXY91jF-.mjs → handle-action-BarHOi-v.mjs} +15 -15
  23. package/dist/.setup/{handle-action.guild-admin-BvBCfhXF.mjs → handle-action.guild-admin-oRUb8p_O.mjs} +5 -5
  24. package/dist/.setup/listeners-CHgTENFu.mjs +46 -0
  25. package/dist/.setup/{live-policy-config-DO1Fk2hp.mjs → live-policy-config-EKp4O6zx.mjs} +2 -3
  26. package/dist/.setup/{message-handler-fL1j1NiR.mjs → message-handler-DUeT8Asf.mjs} +154 -113
  27. package/dist/.setup/{message-handler.preflight-DkjwNZAd.mjs → message-handler.preflight-C6TNtKW0.mjs} +30 -104
  28. package/dist/.setup/{message-handler.preflight-pluralkit-DR4BnvMU.mjs → message-handler.preflight-pluralkit-6E9TFmmN.mjs} +9 -22
  29. package/dist/.setup/{message-handler.process-ClOwIPDK.mjs → message-handler.process-D8_oQ5Cp.mjs} +256 -367
  30. package/dist/.setup/outbound-payload-DUsrFICb.mjs +445 -0
  31. package/dist/.setup/{outbound-session-route-TFBPPkoz.mjs → outbound-session-route-Cb8cv4Oi.mjs} +138 -86
  32. package/dist/.setup/{preflight-audio-CwtPIsvk.mjs → preflight-audio-r4BbaJxh.mjs} +1 -5
  33. package/dist/.setup/{presence-cache-CgutE4NN.mjs → presence-cache-B3xj3b0l.mjs} +1 -6
  34. package/dist/.setup/{probe-DNge7OEP.mjs → probe-BUmJyH35.mjs} +5 -9
  35. package/dist/.setup/{provider-BBDuE14w.mjs → provider-Dm2ERSxe.mjs} +3600 -4454
  36. package/dist/.setup/{provider-session.runtime-D8hMXXqJ.mjs → provider-session.runtime-DCIqDsIg.mjs} +3 -3
  37. package/dist/.setup/provider.runtime-DmxPGoUg.mjs +1 -0
  38. package/dist/.setup/proxy-fetch-B8cK6FLQ.mjs +29 -0
  39. package/dist/.setup/{realtime-session.runtime-cetognkp.mjs → realtime-session.runtime-WJL6NdwK.mjs} +43 -81
  40. package/dist/.setup/{receive-recovery-C77CVdGM.mjs → receive-recovery-DV_v5ROf.mjs} +13 -27
  41. package/dist/.setup/{resolve-allowlist-common-CI77288n.mjs → resolve-allowlist-common-C37fgnYG.mjs} +3 -12
  42. package/dist/.setup/{resolve-channels-DYc6-xgV.mjs → resolve-channels-CwpnQ7C2.mjs} +5 -4
  43. package/dist/.setup/{resolve-users-BQT7XWF2.mjs → resolve-users-D6jSwe8R.mjs} +4 -7
  44. package/dist/.setup/{runtime-CcijhTJT.mjs → runtime-B-PgPsGR.mjs} +6 -6
  45. package/dist/.setup/{runtime-CI0UJqeS.mjs → runtime-DhOMlnYS.mjs} +196 -235
  46. package/dist/.setup/{secret-config-contract-BdbCvqnM.mjs → secret-config-contract-CP6teHec.mjs} +4 -9
  47. package/dist/.setup/{send-Cbq-IVsS.mjs → send-DnLL6XoO.mjs} +149 -174
  48. package/dist/.setup/{send.components-BV6ucNpJ.mjs → send.components-xB43CksK.mjs} +61 -71
  49. package/dist/.setup/{send.outbound-CGhBhzjQ.mjs → send.outbound-B11X6TOE.mjs} +75 -129
  50. package/dist/.setup/{send.receipt-Dw-_r5Bx.mjs → send.receipt-CMteCIZS.mjs} +29 -31
  51. package/dist/.setup/{send.shared-D4MioxW_.mjs → send.shared-BcLLZBul.mjs} +38 -112
  52. package/dist/.setup/{sender-identity-DrN5c4ec.mjs → sender-identity-CGNpdJmb.mjs} +3 -9
  53. package/dist/.setup/setup-plugin-api-C6AMx3hu.mjs +2 -0
  54. package/dist/.setup/{shared-Bp0sxD5R.mjs → shared-BEYw16he.mjs} +8 -10
  55. package/dist/.setup/shared-interactive-DKBw4SNV.mjs +311 -0
  56. package/dist/.setup/{subagent-hooks-mQbDkvuD.mjs → subagent-hooks-DlYElpXa.mjs} +1 -1
  57. package/dist/.setup/{system-events-2zc2eGfF.mjs → system-events--Pk6y9aP.mjs} +2 -2
  58. package/dist/.setup/{target-resolver-CAHeVfmZ.mjs → target-resolver-Bo9EpGp_.mjs} +3 -3
  59. package/dist/.setup/{thread-bindings-Dg7X_ZXP.mjs → thread-bindings-BF-hr-bg.mjs} +12 -20
  60. package/dist/.setup/{thread-bindings.manager-DCDYksah.mjs → thread-bindings.manager-CQCkha5r.mjs} +22 -42
  61. package/dist/.setup/{thread-bindings.session-updates-C76plLS3.mjs → thread-bindings.session-updates-C2gJAj_I.mjs} +11 -18
  62. package/dist/.setup/{threading-l0UfrE6x.mjs → threading-HA9C2wYR.mjs} +68 -104
  63. package/dist/.setup/{timeouts-DTrUsJ_W.mjs → timeouts-CT9hnmo4.mjs} +1 -1
  64. package/dist/.setup/{transcripts-source-CGgOaWcu.mjs → transcripts-source-DzpzETZR.mjs} +102 -172
  65. package/dist/.setup/{voice-runtime-DY1EwDfi.mjs → voice-runtime-Bo_nsVvX.mjs} +231 -448
  66. package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -1
  67. package/dist/account-inspect-api.js +1 -1
  68. package/dist/action-runtime-api.js +1 -1
  69. package/dist/activities-api.js +285 -337
  70. package/dist/api.js +16 -16
  71. package/dist/assets/embedded-app-sdk.mjs +1 -1
  72. package/dist/channel-config-api.js +1 -1
  73. package/dist/channel-plugin-api.js +1 -1
  74. package/dist/directory-contract-api.js +1 -1
  75. package/dist/runtime-api.js +22 -22
  76. package/dist/secret-contract-api.js +1 -1
  77. package/dist/setup-entry.js +1 -1
  78. package/dist/setup-plugin-api.js +1 -1
  79. package/dist/src/voice/audio-worker.runtime.js +56 -68
  80. package/dist/subagent-hooks-api.js +1 -1
  81. package/dist/transcripts-source-api.js +1 -1
  82. package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.cjs +2 -3
  83. package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.mjs +2 -3
  84. package/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
  85. package/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
  86. package/node_modules/@types/lodash/README.md +1 -1
  87. package/node_modules/@types/lodash/common/function.d.ts +2 -2
  88. package/node_modules/@types/lodash/package.json +2 -2
  89. package/node_modules/@types/node/README.md +1 -1
  90. package/node_modules/@types/node/package.json +2 -2
  91. package/node_modules/@types/node/util.d.ts +6 -3
  92. package/node_modules/discord-api-types/package.json +4 -4
  93. package/node_modules/discord-api-types/rest/v10/index.d.ts +8 -0
  94. package/node_modules/discord-api-types/rest/v10/index.d.ts.map +1 -1
  95. package/node_modules/discord-api-types/rest/v10/index.js +8 -0
  96. package/node_modules/discord-api-types/rest/v10/index.js.map +1 -1
  97. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts +26 -2
  98. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts.map +1 -1
  99. package/node_modules/discord-api-types/rest/v9/index.d.ts +8 -0
  100. package/node_modules/discord-api-types/rest/v9/index.d.ts.map +1 -1
  101. package/node_modules/discord-api-types/rest/v9/index.js +8 -0
  102. package/node_modules/discord-api-types/rest/v9/index.js.map +1 -1
  103. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts +26 -2
  104. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts.map +1 -1
  105. package/node_modules/typebox/build/format/duration.d.mts +2 -2
  106. package/node_modules/typebox/build/format/duration.mjs +2 -2
  107. package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
  108. package/node_modules/typebox/build/format/idn_email.mjs +1 -0
  109. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
  110. package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
  111. package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
  112. package/node_modules/typebox/build/format/ipv4.mjs +2 -2
  113. package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
  114. package/node_modules/typebox/build/format/ipv6.mjs +1 -1
  115. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  116. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  117. package/node_modules/typebox/build/schema/build.mjs +1 -0
  118. package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
  119. package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
  120. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
  121. package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
  122. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
  123. package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
  124. package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
  125. package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
  126. package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
  127. package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
  128. package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
  129. package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
  130. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
  131. package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
  132. package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
  133. package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
  134. package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
  135. package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
  136. package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
  137. package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
  138. package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
  139. package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
  140. package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
  141. package/node_modules/typebox/build/system/memory/create.mjs +18 -13
  142. package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
  143. package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
  144. package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
  145. package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
  146. package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
  147. package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
  148. package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
  149. package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
  150. package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
  151. package/node_modules/typebox/build/system/memory/update.mjs +43 -16
  152. package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
  153. package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
  154. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
  155. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
  156. package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
  157. package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
  158. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
  159. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
  160. package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
  161. package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
  162. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
  163. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
  164. package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
  165. package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
  166. package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
  167. package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
  168. package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
  169. package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
  170. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
  171. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
  172. package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
  173. package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
  174. package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
  175. package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
  176. package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
  177. package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
  178. package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
  179. package/node_modules/typebox/package.json +1 -1
  180. package/node_modules/typebox/readme.md +1 -1
  181. package/node_modules/undici/docs/docs/api/Interceptors.md +15 -2
  182. package/node_modules/undici/lib/dispatcher/client-h2.js +78 -3
  183. package/node_modules/undici/lib/dispatcher/pool-base.js +20 -3
  184. package/node_modules/undici/package.json +3 -3
  185. package/node_modules/undici/types/api.d.ts +1 -1
  186. package/node_modules/undici/types/utility.d.ts +4 -4
  187. package/node_modules/uuid/package.json +17 -17
  188. package/node_modules/zod/package.json +1 -1
  189. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  190. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  191. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  192. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  193. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  194. package/node_modules/zod/src/v4/core/util.ts +13 -0
  195. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  196. package/node_modules/zod/v4/core/compile.cjs +8 -0
  197. package/node_modules/zod/v4/core/compile.js +8 -0
  198. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  199. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  200. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  201. package/node_modules/zod/v4/core/schemas.js +30 -0
  202. package/node_modules/zod/v4/core/util.cjs +15 -0
  203. package/node_modules/zod/v4/core/util.d.cts +2 -0
  204. package/node_modules/zod/v4/core/util.d.ts +2 -0
  205. package/node_modules/zod/v4/core/util.js +14 -0
  206. package/node_modules/zod/v4/core/versions.cjs +1 -1
  207. package/node_modules/zod/v4/core/versions.js +1 -1
  208. package/openclaw.plugin.json +1 -31
  209. package/package.json +8 -8
  210. package/dist/.setup/channel-access-BPrWoEXM.mjs +0 -47
  211. package/dist/.setup/channel.setup-DVe7Y3Jf.mjs +0 -245
  212. package/dist/.setup/outbound-adapter-DWyAWBFh.mjs +0 -537
  213. package/dist/.setup/provider.runtime-BQ1z4Aq1.mjs +0 -1
  214. package/dist/.setup/setup-plugin-api-B4J6wmL1.mjs +0 -2
  215. package/dist/.setup/targets-BaklhOqq.mjs +0 -3
  216. package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
  217. package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
@@ -1,105 +1,34 @@
1
- import { l as resolveDiscordAccount } from "./.setup/accounts-C18HNgge.mjs";
2
- import { D as getDiscordEndpointRuntime } from "./.setup/allow-list-D1ZGfhXh.mjs";
1
+ import { n as getDiscordEndpointRuntime } from "./.setup/endpoint-runtime-BM3x-m6O.mjs";
3
2
  import { n as resolveDiscordChannelId$1 } from "./.setup/target-parsing-BiuhcK9Q.mjs";
4
- import { S as parseDiscordActivityCustomId, i as buildDiscordPresentationComponents } from "./.setup/components-BvOWSPxr.mjs";
5
- import { r as sendDiscordComponentMessage } from "./.setup/send.components-BV6ucNpJ.mjs";
6
- import { r as setDiscordActivitiesRuntime, t as DiscordActivitiesRuntime } from "./.setup/runtime-CcijhTJT.mjs";
3
+ import { n as buildDiscordPresentationComponents, p as parseDiscordActivityCustomId } from "./.setup/shared-interactive-DKBw4SNV.mjs";
4
+ import { r as setDiscordActivitiesRuntime, t as DiscordActivitiesRuntime } from "./.setup/runtime-B-PgPsGR.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
- // 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
16
  // extensions/discord/src/activities/rate-limit.ts
84
17
  const TOKEN_RATE_LIMIT = 10;
85
18
  const TOKEN_GLOBAL_RATE_LIMIT = 60;
86
19
  const TOKEN_RATE_WINDOW_MS = 6e4;
87
20
  const TOKEN_RATE_MAX_KEYS = 1024;
88
21
  var TokenRateLimiter = class {
89
- constructor(now) {
90
- this.now = now;
22
+ constructor() {
91
23
  this.attempts = /* @__PURE__ */ new Map();
92
24
  this.globalAttempts = [];
93
25
  }
94
26
  allowKey(key) {
95
- const now = this.now();
27
+ const now = Date.now();
96
28
  const active = (this.attempts.get(key) ?? []).filter((timestamp) => timestamp > now - TOKEN_RATE_WINDOW_MS);
97
29
  const allowed = active.length < TOKEN_RATE_LIMIT;
98
30
  if (allowed) {
99
- if (!this.attempts.has(key) && this.attempts.size >= TOKEN_RATE_MAX_KEYS) {
100
- const oldestKey = this.attempts.keys().next().value;
101
- if (typeof oldestKey === "string") this.attempts.delete(oldestKey);
102
- }
31
+ if (!this.attempts.has(key) && this.attempts.size >= TOKEN_RATE_MAX_KEYS) pruneMapToMaxSize(this.attempts, 1023);
103
32
  active.push(now);
104
33
  }
105
34
  this.attempts.delete(key);
@@ -107,7 +36,7 @@ var TokenRateLimiter = class {
107
36
  return allowed;
108
37
  }
109
38
  reserveGlobal() {
110
- const now = this.now();
39
+ const now = Date.now();
111
40
  this.globalAttempts = this.globalAttempts.filter((reservation) => reservation.at > now - TOKEN_RATE_WINDOW_MS);
112
41
  if (this.globalAttempts.length >= TOKEN_GLOBAL_RATE_LIMIT) return null;
113
42
  const reservation = { at: now };
@@ -245,11 +174,178 @@ run().catch((error) => {
245
174
  }
246
175
  });
247
176
  `;
248
- // extensions/discord/src/activities/http.ts
177
+ // extensions/discord/src/activities/store.ts
178
+ const DAY_MS = 864e5;
179
+ const DISCORD_EPOCH_MS = 14200704e5;
180
+ const WIDGET_TTL_MS = 7 * DAY_MS;
181
+ const SESSION_TTL_MS = 9e5;
182
+ const DOC_TOKEN_TTL_MS = 6e4;
183
+ const PENDING_LAUNCH_TTL_MS = 12e4;
184
+ function openDiscordActivityStores(openKeyedStore) {
185
+ const openStore = (namespace, maxEntries, defaultTtlMs) => openKeyedStore({
186
+ namespace,
187
+ maxEntries,
188
+ overflowPolicy: "evict-oldest",
189
+ defaultTtlMs
190
+ });
191
+ return {
192
+ widgets: openStore("activities-widgets", 64, WIDGET_TTL_MS),
193
+ sessions: openStore("activities-sessions", 256, SESSION_TTL_MS),
194
+ docTokens: openStore("activities-doc-tokens", 256, DOC_TOKEN_TTL_MS),
195
+ launches: openStore("activities-launches", 256, PENDING_LAUNCH_TTL_MS)
196
+ };
197
+ }
198
+ function pendingLaunchKey(accountId, channelId, discordUserId) {
199
+ return `${accountId}:${channelId}:${discordUserId}`;
200
+ }
201
+ async function applyActivityStoreIntent(store, key, intent) {
202
+ let observed = await store.observe(key);
203
+ while (true) {
204
+ const result = await store.compareAndApply(key, observed.comparison, intent(observed.value));
205
+ if (result.status !== "conflict") return result.status;
206
+ observed = result.current;
207
+ }
208
+ }
209
+ var DiscordActivityStore = class {
210
+ constructor(stores) {
211
+ this.stores = stores;
212
+ }
213
+ async createWidget(value) {
214
+ const id = randomBytes(16).toString("base64url");
215
+ await this.stores.widgets.register(id, {
216
+ ...value,
217
+ deliveredMessageId: null
218
+ });
219
+ return id;
220
+ }
221
+ async markWidgetDelivered(id, messageId) {
222
+ if (!/^\d+$/u.test(messageId)) throw new Error("Discord Activity delivery returned an invalid message ID");
223
+ if (await applyActivityStoreIntent(this.stores.widgets, id, (widget) => widget ? {
224
+ operation: "update",
225
+ action: "set",
226
+ value: {
227
+ ...widget,
228
+ deliveredMessageId: messageId
229
+ }
230
+ } : {
231
+ operation: "update",
232
+ action: "keep"
233
+ }) === "unchanged") throw new Error("Discord Activity widget disappeared before delivery was recorded");
234
+ }
235
+ async deleteWidget(id) {
236
+ await this.stores.widgets.delete(id);
237
+ }
238
+ async lookupWidget(id) {
239
+ return await this.stores.widgets.lookup(id);
240
+ }
241
+ async latestPostedWidgetForChannel(accountId, channelId) {
242
+ const entries = await this.stores.widgets.entries();
243
+ let match;
244
+ for (const entry of entries) {
245
+ if (entry.value.accountId !== accountId || entry.value.channelId !== channelId) continue;
246
+ if (entry.value.deliveredMessageId === null) continue;
247
+ const deliveryOrder = entry.value.deliveredMessageId ? BigInt(entry.value.deliveredMessageId) : BigInt(Math.max(0, Math.trunc(entry.value.createdAt - DISCORD_EPOCH_MS))) << 22n;
248
+ if (!match || deliveryOrder > match.deliveryOrder) match = {
249
+ entry,
250
+ deliveryOrder
251
+ };
252
+ }
253
+ return match ? {
254
+ id: match.entry.key,
255
+ widget: match.entry.value
256
+ } : null;
257
+ }
258
+ async createSession(value) {
259
+ const token = randomBytes(32).toString("base64url");
260
+ await this.stores.sessions.register(token, value);
261
+ return token;
262
+ }
263
+ async lookupSession(token) {
264
+ return await this.stores.sessions.lookup(token);
265
+ }
266
+ async createDocToken(value) {
267
+ const token = randomBytes(32).toString("base64url");
268
+ await this.stores.docTokens.register(token, value);
269
+ return token;
270
+ }
271
+ async consumeDocToken(token) {
272
+ return await this.stores.docTokens.consume(token);
273
+ }
274
+ async recordPendingLaunch(params) {
275
+ const key = pendingLaunchKey(params.accountId, params.channelId, params.discordUserId);
276
+ const { widgetId, createdAt } = params;
277
+ await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
278
+ operation: "update",
279
+ action: "set",
280
+ value: existing && (existing.state === "ambiguous" || existing.widgetId !== widgetId) ? {
281
+ state: "ambiguous",
282
+ createdAt
283
+ } : {
284
+ state: "single",
285
+ widgetId,
286
+ createdAt
287
+ }
288
+ }));
289
+ }
290
+ async retirePendingLaunch(accountId, channelId, discordUserId, widgetId) {
291
+ const key = pendingLaunchKey(accountId, channelId, discordUserId);
292
+ await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
293
+ operation: "delete",
294
+ action: existing?.state === "single" && existing.widgetId === widgetId ? "delete" : "keep"
295
+ }));
296
+ }
297
+ async consumePendingLaunch(accountId, channelId, discordUserId) {
298
+ const launch = await this.stores.launches.consume(pendingLaunchKey(accountId, channelId, discordUserId));
299
+ return launch?.state === "single" ? launch : void 0;
300
+ }
301
+ };
302
+ // extensions/discord/src/activities/register.ts
249
303
  const BODY_MAX_BYTES = 8192;
250
304
  const JSON_CONTENT_TYPE = "application/json; charset=utf-8";
251
305
  const WIDGET_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
252
306
  const DOC_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
307
+ const DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token";
308
+ const DISCORD_USER_URL = "https://discord.com/api/v10/users/@me";
309
+ const DISCORD_HOST = "discord.com";
310
+ const DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS = 15e3;
311
+ const JSON_MAX_BYTES = 65536;
312
+ const INSTANCE_ID_MAX_LENGTH = 256;
313
+ function normalizeInstanceId(value) {
314
+ const instanceId = normalizeBoundedOptionalString(value, INSTANCE_ID_MAX_LENGTH);
315
+ return instanceId && !containsAsciiControlCharacter(instanceId) ? instanceId : void 0;
316
+ }
317
+ async function fetchDiscordJson(params) {
318
+ const endpoint = Object.hasOwn(params, "endpointRuntime") ? params.endpointRuntime : getDiscordEndpointRuntime();
319
+ const liveUrl = new URL(params.url);
320
+ const endpointPath = liveUrl.pathname === "/api/oauth2/token" ? "/oauth2/token" : liveUrl.pathname.startsWith("/api/v10/") ? liveUrl.pathname.slice(8) : void 0;
321
+ if (endpoint && !endpointPath) throw new Error("Discord Activity request is outside the configured endpoint routes");
322
+ const { response, release } = endpoint ? {
323
+ response: await endpoint.fetch(`${endpoint.descriptor.restApiBaseUrl}${endpointPath}${liveUrl.search}`, {
324
+ ...params.init,
325
+ signal: params.init.signal ? AbortSignal.any([params.init.signal, AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS)
326
+ }),
327
+ release: async () => {}
328
+ } : await fetchWithSsrFGuard({
329
+ url: params.url,
330
+ fetchImpl: params.fetchImpl,
331
+ init: params.init,
332
+ policy: { allowedHostnames: [DISCORD_HOST] },
333
+ auditContext: params.auditContext,
334
+ timeoutMs: DISCORD_ACTIVITY_REQUEST_TIMEOUT_MS
335
+ });
336
+ try {
337
+ if (!response.ok) {
338
+ await response.body?.cancel().catch(() => void 0);
339
+ return { ok: false };
340
+ }
341
+ return {
342
+ ok: true,
343
+ body: await readProviderJsonResponse(response, "Discord Activity OAuth", { maxBytes: JSON_MAX_BYTES })
344
+ };
345
+ } finally {
346
+ await release();
347
+ }
348
+ }
253
349
  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 *`;
254
350
  function respond(res, statusCode, body, contentType, headers) {
255
351
  res.statusCode = statusCode;
@@ -286,30 +382,60 @@ function extractApplicationId(req) {
286
382
  function bearerToken(req) {
287
383
  return ((readHeader(req, "authorization")?.trim())?.match(/^Bearer\s+([A-Za-z0-9_-]{43})$/i))?.[1];
288
384
  }
289
- function createDiscordActivityHttpHandler(deps) {
290
- const fetchGuard = deps.fetchGuard ?? fetchWithSsrFGuard$1;
291
- const limiter = new TokenRateLimiter(deps.now ?? Date.now);
292
- const readVendorAsset = deps.readVendorAsset ?? ((assetPath) => fs.readFile(assetPath));
293
- const reportError = deps.logError ?? logError;
294
- const bodyTimeoutMs = deps.bodyTimeoutMs ?? WEBHOOK_BODY_READ_DEFAULTS.preAuth.timeoutMs;
385
+ const DISCORD_WIDGET_HTML_MAX_BYTES = 49152;
386
+ const unavailable = () => ({
387
+ ok: false,
388
+ error: {
389
+ code: "unavailable",
390
+ message: "Discord Activities are unavailable for the current channel and account."
391
+ }
392
+ });
393
+ function resolveDiscordChannelId(context) {
394
+ const raw = context.nativeChannelId?.trim() || context.currentMessagingTarget?.trim() || context.currentChannelId?.trim() || context.deliveryContext?.to?.trim();
395
+ if (!raw) return;
396
+ try {
397
+ return resolveDiscordChannelId$1(raw);
398
+ } catch {
399
+ return;
400
+ }
401
+ }
402
+ function resolveDiscordPresentationRoute(context, runtime) {
403
+ if (context.messageChannel !== "discord") return;
404
+ const cfg = runtime.currentConfig();
405
+ const channelId = resolveDiscordChannelId(context);
406
+ const activityAccount = runtime.resolveAccount(context.accountId ?? context.deliveryContext?.accountId, cfg);
407
+ if (!channelId || !activityAccount) return;
408
+ return {
409
+ account: activityAccount,
410
+ cfg,
411
+ channelId
412
+ };
413
+ }
414
+ function registerDiscordActivities(api) {
415
+ setDiscordActivitiesRuntime(void 0);
416
+ const store = new DiscordActivityStore(openDiscordActivityStores(api.runtime.state.openKeyedStoreV2.bind(api.runtime.state)));
417
+ const runtime = new DiscordActivitiesRuntime(store, () => api.runtime.config.current());
418
+ setDiscordActivitiesRuntime(runtime);
419
+ const vendorAssetPath = api.resolvePath("assets/embedded-app-sdk.mjs");
420
+ const limiter = new TokenRateLimiter();
421
+ const bodyTimeoutMs = WEBHOOK_BODY_READ_DEFAULTS.preAuth.timeoutMs;
295
422
  let vendorAsset;
296
423
  let pendingLaunchFailureLogged = false;
297
424
  function logPendingLaunchFailure(error) {
298
425
  if (pendingLaunchFailureLogged) return;
299
426
  pendingLaunchFailureLogged = true;
300
- reportError(`discord activity: failed to consume pending launch: ${String(error)}`);
427
+ logError(`discord activity: failed to consume pending launch: ${String(error)}`);
301
428
  }
302
429
  async function handleToken(req, res) {
303
- const cfg = deps.runtime.currentConfig();
430
+ const cfg = runtime.currentConfig();
304
431
  const sourceIp = resolveRequestClientIp(req, cfg.gateway?.trustedProxies, cfg.gateway?.allowRealIpFallback === true) ?? "unknown";
305
432
  if (!limiter.allowKey(sourceIp)) return respondJson(res, 429, { error: "too many token requests" });
306
433
  const applicationId = extractApplicationId(req);
307
- const account = deps.runtime.resolveHttpAccount(applicationId);
434
+ const account = runtime.resolveHttpAccount(applicationId);
308
435
  if (!account) return respondJson(res, 503, { error: "Discord Activities is not fully configured" });
309
436
  const endpointRuntime = getDiscordEndpointRuntime() ?? null;
310
437
  const fetchAccountJson = (params) => fetchDiscordJson({
311
438
  ...params,
312
- fetchGuard,
313
439
  fetchImpl: account.proxyFetch,
314
440
  endpointRuntime
315
441
  }).catch(() => void 0);
@@ -356,7 +482,7 @@ function createDiscordActivityHttpHandler(deps) {
356
482
  if (!userResponse) return respondJson(res, 503, { error: "Discord user lookup unavailable" });
357
483
  const discordUserId = typeof userResponse.body?.id === "string" ? userResponse.body.id : void 0;
358
484
  if (!userResponse.ok || !discordUserId) return respondJson(res, 401, { error: "Discord user lookup failed" });
359
- const minted = await deps.runtime.store.createSession({
485
+ const minted = await runtime.store.createSession({
360
486
  discordUserId,
361
487
  accountId: account.accountId
362
488
  });
@@ -371,39 +497,47 @@ function createDiscordActivityHttpHandler(deps) {
371
497
  }
372
498
  async function handleWidget(req, res, url) {
373
499
  const token = bearerToken(req);
374
- const session = token ? await deps.runtime.store.lookupSession(token) : void 0;
500
+ const session = token ? await runtime.store.lookupSession(token) : void 0;
375
501
  if (!session) return respondJson(res, 401, { error: "invalid session" });
376
502
  const customId = url.searchParams.get("custom_id")?.trim() ?? "";
377
503
  const instanceId = normalizeInstanceId(url.searchParams.get("instance_id"));
378
- const account = deps.runtime.resolveAccount(session.accountId);
379
- const channelId = instanceId && account ? await resolveActivityInstanceChannel({
380
- fetchGuard,
381
- applicationId: account.applicationId,
382
- instanceId,
383
- discordUserId: session.discordUserId,
384
- botAuth: account.botAuth,
385
- proxyFetch: account.proxyFetch
386
- }) : void 0;
504
+ const account = runtime.resolveAccount(session.accountId);
505
+ let channelId;
506
+ if (instanceId && account) {
507
+ const discordUserId = session.discordUserId;
508
+ const endpointRuntime = getDiscordEndpointRuntime() ?? null;
509
+ const result = await fetchDiscordJson({
510
+ fetchImpl: account.proxyFetch,
511
+ url: `https://discord.com/api/v10/applications/${encodeURIComponent(account.applicationId)}/activity-instances/${encodeURIComponent(instanceId)}`,
512
+ init: { headers: { Authorization: `Bot ${account.botAuth}` } },
513
+ auditContext: "discord.activities.instance",
514
+ endpointRuntime
515
+ }).catch(() => void 0);
516
+ if (result?.ok && Array.isArray(result.body?.users) && result.body.users.includes(discordUserId)) {
517
+ const value = asOptionalRecord(result.body.location)?.channel_id;
518
+ channelId = typeof value === "string" && /^\d+$/.test(value) ? value : void 0;
519
+ }
520
+ }
387
521
  if (!channelId) return respondJson(res, 404, { error: "widget not found" });
388
522
  let resolved = null;
389
523
  const requestedWidgetId = WIDGET_ID_PATTERN.test(customId) ? customId : parseDiscordActivityCustomId(customId)?.widgetId;
390
524
  if (requestedWidgetId) {
391
- const widget = await deps.runtime.store.lookupWidget(requestedWidgetId);
525
+ const widget = await runtime.store.lookupWidget(requestedWidgetId);
392
526
  if (widget?.accountId !== session.accountId || widget.channelId !== channelId) return respondJson(res, 404, { error: "widget not found" });
393
527
  resolved = {
394
528
  id: requestedWidgetId,
395
529
  widget
396
530
  };
397
531
  try {
398
- await deps.runtime.store.retirePendingLaunch(session.accountId, channelId, session.discordUserId, requestedWidgetId);
532
+ await runtime.store.retirePendingLaunch(session.accountId, channelId, session.discordUserId, requestedWidgetId);
399
533
  } catch (error) {
400
534
  logPendingLaunchFailure(error);
401
535
  }
402
536
  } else {
403
537
  try {
404
- const pendingLaunch = await deps.runtime.store.consumePendingLaunch(session.accountId, channelId, session.discordUserId);
538
+ const pendingLaunch = await runtime.store.consumePendingLaunch(session.accountId, channelId, session.discordUserId);
405
539
  if (pendingLaunch) {
406
- const widget = await deps.runtime.store.lookupWidget(pendingLaunch.widgetId);
540
+ const widget = await runtime.store.lookupWidget(pendingLaunch.widgetId);
407
541
  if (widget?.accountId === session.accountId && widget.channelId === channelId) resolved = {
408
542
  id: pendingLaunch.widgetId,
409
543
  widget
@@ -412,10 +546,10 @@ function createDiscordActivityHttpHandler(deps) {
412
546
  } catch (error) {
413
547
  logPendingLaunchFailure(error);
414
548
  }
415
- resolved ??= await deps.runtime.store.latestPostedWidgetForChannel(session.accountId, channelId);
549
+ resolved ??= await runtime.store.latestPostedWidgetForChannel(session.accountId, channelId);
416
550
  }
417
551
  if (!resolved) return respondJson(res, 404, { error: "widget not found" });
418
- const docToken = await deps.runtime.store.createDocToken({
552
+ const docToken = await runtime.store.createDocToken({
419
553
  widgetId: resolved.id,
420
554
  accountId: session.accountId
421
555
  });
@@ -427,80 +561,49 @@ function createDiscordActivityHttpHandler(deps) {
427
561
  }
428
562
  async function handleDocument(res, widgetId, token) {
429
563
  if (!WIDGET_ID_PATTERN.test(widgetId) || !DOC_TOKEN_PATTERN.test(token)) return notFound(res, true);
430
- const capability = await deps.runtime.store.consumeDocToken(token);
564
+ const capability = await runtime.store.consumeDocToken(token);
431
565
  if (!capability || capability.widgetId !== widgetId) return notFound(res, true);
432
- const widget = await deps.runtime.store.lookupWidget(widgetId);
566
+ const widget = await runtime.store.lookupWidget(widgetId);
433
567
  if (!widget || widget.accountId !== capability.accountId) return notFound(res, true);
434
568
  return respond(res, 200, widget.html, "text/html; charset=utf-8", { "Content-Security-Policy": DISCORD_ACTIVITY_WIDGET_CSP });
435
569
  }
436
- return { handleHttpRequest: async (req, res) => {
437
- const url = new URL(req.url ?? "/", "http://localhost");
438
- if (url.pathname !== "/discord/activity" && !url.pathname.startsWith(`/discord/activity/`)) return false;
439
- if (!deps.runtime.hasEnabledAccounts()) return false;
440
- const relative = url.pathname.slice(17) || "/";
441
- 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 });
442
- if (req.method === "GET" && relative === "/shell.js") return respond(res, 200, DISCORD_ACTIVITY_SHELL_JS, "text/javascript; charset=utf-8");
443
- if (req.method === "GET" && relative === "/vendor/embedded-app-sdk.mjs") {
444
- const pendingAsset = vendorAsset ??= readVendorAsset(deps.vendorAssetPath);
445
- try {
446
- return respond(res, 200, await pendingAsset, "text/javascript; charset=utf-8");
447
- } catch {
448
- if (vendorAsset === pendingAsset) vendorAsset = void 0;
449
- return notFound(res);
570
+ api.registerHttpRoute({
571
+ path: DISCORD_ACTIVITY_ROUTE_PREFIX,
572
+ auth: "plugin",
573
+ match: "prefix",
574
+ handler: async (req, res) => {
575
+ const url = new URL(req.url ?? "/", "http://localhost");
576
+ if (url.pathname !== "/discord/activity" && !url.pathname.startsWith(`/discord/activity/`)) return false;
577
+ if (!runtime.hasEnabledAccounts()) return false;
578
+ const relative = url.pathname.slice(17) || "/";
579
+ 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 });
580
+ if (req.method === "GET" && relative === "/shell.js") return respond(res, 200, DISCORD_ACTIVITY_SHELL_JS, "text/javascript; charset=utf-8");
581
+ if (req.method === "GET" && relative === "/vendor/embedded-app-sdk.mjs") {
582
+ const pendingAsset = vendorAsset ??= fs.readFile(vendorAssetPath);
583
+ try {
584
+ return respond(res, 200, await pendingAsset, "text/javascript; charset=utf-8");
585
+ } catch {
586
+ if (vendorAsset === pendingAsset) vendorAsset = void 0;
587
+ return notFound(res);
588
+ }
450
589
  }
451
- }
452
- if (req.method === "POST" && relative === "/api/token") return await handleToken(req, res);
453
- if (req.method === "GET" && relative === "/api/widget") return await handleWidget(req, res, url);
454
- const documentMatch = relative.match(/^\/api\/widget\/([^/]+)\/doc$/);
455
- if (req.method === "GET" && documentMatch?.[1]) {
456
- let widgetId;
457
- try {
458
- widgetId = decodeURIComponent(documentMatch[1]);
459
- } catch {
460
- return notFound(res, true);
590
+ if (req.method === "POST" && relative === "/api/token") return await handleToken(req, res);
591
+ if (req.method === "GET" && relative === "/api/widget") return await handleWidget(req, res, url);
592
+ const documentMatch = relative.match(/^\/api\/widget\/([^/]+)\/doc$/);
593
+ if (req.method === "GET" && documentMatch?.[1]) {
594
+ let widgetId;
595
+ try {
596
+ widgetId = decodeURIComponent(documentMatch[1]);
597
+ } catch {
598
+ return notFound(res, true);
599
+ }
600
+ return await handleDocument(res, widgetId, url.searchParams.get("wt") ?? "");
461
601
  }
462
- return await handleDocument(res, widgetId, url.searchParams.get("wt") ?? "");
602
+ return notFound(res);
463
603
  }
464
- return notFound(res);
465
- } };
466
- }
467
- // extensions/discord/src/activities/presenter.ts
468
- const DISCORD_WIDGET_HTML_MAX_BYTES = 49152;
469
- const unavailable = () => ({
470
- ok: false,
471
- error: {
472
- code: "unavailable",
473
- message: "Discord Activities are unavailable for the current channel and account."
474
- }
475
- });
476
- function resolveDiscordChannelId(context) {
477
- const raw = context.nativeChannelId?.trim() || context.currentMessagingTarget?.trim() || context.currentChannelId?.trim() || context.deliveryContext?.to?.trim();
478
- if (!raw) return;
479
- try {
480
- return resolveDiscordChannelId$1(raw);
481
- } catch {
482
- return;
483
- }
484
- }
485
- function resolveDiscordPresentationRoute(context, runtime) {
486
- if (context.messageChannel !== "discord") return;
487
- const cfg = runtime.currentConfig();
488
- const account = resolveDiscordAccount({
489
- cfg,
490
- accountId: context.accountId ?? context.deliveryContext?.accountId
491
604
  });
492
- const channelId = resolveDiscordChannelId(context);
493
- const activityAccount = runtime.resolveAccount(account.accountId, cfg);
494
- if (!channelId || !activityAccount) return;
495
- return {
496
- account: activityAccount,
497
- cfg,
498
- channelId
499
- };
500
- }
501
- /** Presents a canonical core widget document in the active Discord channel. */
502
- function createDiscordWidgetPresenter(runtime) {
503
- return {
605
+ /** Presents a canonical core widget document in the active Discord channel. */
606
+ api.registerWidgetPresenter({
504
607
  target: "current_channel",
505
608
  description: "Post an Activity launch button in the current Discord channel",
506
609
  capabilities: {
@@ -534,16 +637,11 @@ function createDiscordWidgetPresenter(runtime) {
534
637
  let result;
535
638
  let deliveredResult;
536
639
  let deliveryRecord;
537
- let deliveryRecordError;
538
- const recordDelivery = async (deliveryResult) => {
640
+ const recordDelivery = (deliveryResult) => {
539
641
  deliveredResult = deliveryResult;
540
- deliveryRecord ??= runtime.store.markWidgetDelivered(widgetId, deliveryResult.messageId);
541
- try {
542
- await deliveryRecord;
543
- } catch (error) {
544
- deliveryRecordError ??= new Error("Discord widget was delivered, but its delivery state could not be saved", { cause: error });
545
- throw deliveryRecordError;
546
- }
642
+ return deliveryRecord ??= runtime.store.markWidgetDelivered(widgetId, deliveryResult.messageId).catch((error) => {
643
+ throw new Error("Discord widget was delivered, but its delivery state could not be saved", { cause: error });
644
+ });
547
645
  };
548
646
  try {
549
647
  const components = buildDiscordPresentationComponents({ blocks: [{
@@ -557,6 +655,7 @@ function createDiscordWidgetPresenter(runtime) {
557
655
  }]
558
656
  }] });
559
657
  if (!components) throw new Error("Discord widget launch button could not be rendered");
658
+ const { sendDiscordComponentMessage } = await import("./.setup/send.components-xB43CksK.mjs").then((n) => n.i);
560
659
  result = await sendDiscordComponentMessage(`channel:${route.channelId}`, {
561
660
  ...components,
562
661
  text: title
@@ -568,11 +667,11 @@ function createDiscordWidgetPresenter(runtime) {
568
667
  });
569
668
  await recordDelivery(result);
570
669
  } catch (error) {
571
- if (deliveryRecordError) throw deliveryRecordError;
572
670
  if (!deliveredResult) {
573
671
  await runtime.store.deleteWidget(widgetId);
574
672
  throw error;
575
673
  }
674
+ await deliveryRecord;
576
675
  result = deliveredResult;
577
676
  }
578
677
  return {
@@ -583,157 +682,6 @@ function createDiscordWidgetPresenter(runtime) {
583
682
  }
584
683
  };
585
684
  }
586
- };
587
- }
588
- // extensions/discord/src/activities/store.ts
589
- const DAY_MS = 864e5;
590
- const DISCORD_EPOCH_MS = 14200704e5;
591
- const WIDGET_TTL_MS = 7 * DAY_MS;
592
- const SESSION_TTL_MS = 9e5;
593
- const DOC_TOKEN_TTL_MS = 6e4;
594
- const PENDING_LAUNCH_TTL_MS = 12e4;
595
- function requireAtomicComparison(store) {
596
- if (!store.observe || !store.compareAndApply) throw new Error("Discord Activities require atomic plugin state comparisons");
597
- return store;
598
- }
599
- function openDiscordActivityStores(openKeyedStore) {
600
- const openStore = (namespace, maxEntries, defaultTtlMs) => openKeyedStore({
601
- namespace,
602
- maxEntries,
603
- overflowPolicy: "evict-oldest",
604
- defaultTtlMs
605
- });
606
- return {
607
- widgets: requireAtomicComparison(openStore("activities-widgets", 64, WIDGET_TTL_MS)),
608
- sessions: openStore("activities-sessions", 256, SESSION_TTL_MS),
609
- docTokens: openStore("activities-doc-tokens", 256, DOC_TOKEN_TTL_MS),
610
- launches: requireAtomicComparison(openStore("activities-launches", 256, PENDING_LAUNCH_TTL_MS))
611
- };
612
- }
613
- function pendingLaunchKey(accountId, channelId, discordUserId) {
614
- return `${accountId}:${channelId}:${discordUserId}`;
615
- }
616
- async function applyActivityStoreIntent(store, key, intent) {
617
- let observed = await store.observe(key);
618
- while (true) {
619
- const result = await store.compareAndApply(key, observed.comparison, intent(observed.value));
620
- if (result.status !== "conflict") return result.status;
621
- observed = result.current;
622
- }
623
- }
624
- var DiscordActivityStore = class {
625
- constructor(stores) {
626
- this.stores = stores;
627
- this.lastWidgetCreatedAt = 0;
628
- }
629
- async createWidget(value) {
630
- const id = randomBytes(16).toString("base64url");
631
- const createdAt = Math.max(value.createdAt, this.lastWidgetCreatedAt + 1);
632
- this.lastWidgetCreatedAt = createdAt;
633
- await this.stores.widgets.register(id, {
634
- ...value,
635
- createdAt,
636
- deliveredMessageId: null
637
- });
638
- return id;
639
- }
640
- async markWidgetDelivered(id, messageId) {
641
- if (!/^\d+$/u.test(messageId)) throw new Error("Discord Activity delivery returned an invalid message ID");
642
- if (await applyActivityStoreIntent(this.stores.widgets, id, (widget) => widget ? {
643
- operation: "update",
644
- action: "set",
645
- value: {
646
- ...widget,
647
- deliveredMessageId: messageId
648
- }
649
- } : {
650
- operation: "update",
651
- action: "keep"
652
- }) === "unchanged") throw new Error("Discord Activity widget disappeared before delivery was recorded");
653
- }
654
- async deleteWidget(id) {
655
- await this.stores.widgets.delete(id);
656
- }
657
- async lookupWidget(id) {
658
- return await this.stores.widgets.lookup(id);
659
- }
660
- async latestPostedWidgetForChannel(accountId, channelId) {
661
- const entries = await this.stores.widgets.entries();
662
- let match;
663
- for (const entry of entries) {
664
- if (entry.value.accountId !== accountId || entry.value.channelId !== channelId) continue;
665
- if (entry.value.deliveredMessageId === null) continue;
666
- const deliveryOrder = entry.value.deliveredMessageId ? BigInt(entry.value.deliveredMessageId) : BigInt(Math.max(0, Math.trunc(entry.value.createdAt - DISCORD_EPOCH_MS))) << 22n;
667
- if (!match || deliveryOrder > match.deliveryOrder) match = {
668
- entry,
669
- deliveryOrder
670
- };
671
- }
672
- return match ? {
673
- id: match.entry.key,
674
- widget: match.entry.value
675
- } : null;
676
- }
677
- async createSession(value) {
678
- const token = randomBytes(32).toString("base64url");
679
- await this.stores.sessions.register(token, value);
680
- return token;
681
- }
682
- async lookupSession(token) {
683
- return await this.stores.sessions.lookup(token);
684
- }
685
- async createDocToken(value) {
686
- const token = randomBytes(32).toString("base64url");
687
- await this.stores.docTokens.register(token, value);
688
- return token;
689
- }
690
- async consumeDocToken(token) {
691
- return await this.stores.docTokens.consume(token);
692
- }
693
- async recordPendingLaunch(params) {
694
- const key = pendingLaunchKey(params.accountId, params.channelId, params.discordUserId);
695
- const { widgetId, createdAt } = params;
696
- await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
697
- operation: "update",
698
- action: "set",
699
- value: existing && (existing.state === "ambiguous" || existing.widgetId !== widgetId) ? {
700
- state: "ambiguous",
701
- createdAt
702
- } : {
703
- state: "single",
704
- widgetId,
705
- createdAt
706
- }
707
- }));
708
- }
709
- async retirePendingLaunch(accountId, channelId, discordUserId, widgetId) {
710
- const key = pendingLaunchKey(accountId, channelId, discordUserId);
711
- await applyActivityStoreIntent(this.stores.launches, key, (existing) => ({
712
- operation: "delete",
713
- action: existing?.state === "single" && existing.widgetId === widgetId ? "delete" : "keep"
714
- }));
715
- }
716
- async consumePendingLaunch(accountId, channelId, discordUserId) {
717
- const launch = await this.stores.launches.consume(pendingLaunchKey(accountId, channelId, discordUserId));
718
- return launch?.state === "single" ? launch : void 0;
719
- }
720
- };
721
- // extensions/discord/src/activities/register.ts
722
- function registerDiscordActivities(api) {
723
- setDiscordActivitiesRuntime(void 0);
724
- const store = new DiscordActivityStore(openDiscordActivityStores(api.runtime.state.openKeyedStore.bind(api.runtime.state)));
725
- const runtime = new DiscordActivitiesRuntime(store, api.config, api.runtime.config?.current ? () => api.runtime.config.current() : void 0);
726
- setDiscordActivitiesRuntime(runtime);
727
- const http = createDiscordActivityHttpHandler({
728
- runtime,
729
- vendorAssetPath: api.resolvePath("assets/embedded-app-sdk.mjs")
730
- });
731
- api.registerHttpRoute({
732
- path: DISCORD_ACTIVITY_ROUTE_PREFIX,
733
- auth: "plugin",
734
- match: "prefix",
735
- handler: http.handleHttpRequest
736
685
  });
737
- api.registerWidgetPresenter(createDiscordWidgetPresenter(runtime));
738
686
  }
739
687
  export { registerDiscordActivities };