ludicord 2.2.0 → 2.2.4

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 (166) hide show
  1. package/README.md +8 -6
  2. package/bin/ludicord.js +0 -0
  3. package/dist/api/runtime.d.ts +4 -0
  4. package/dist/api/runtime.js +61 -10
  5. package/dist/auth/client.d.ts +10 -0
  6. package/dist/auth/client.js +81 -8
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/server.js +175 -32
  10. package/dist/auth/types.d.ts +5 -0
  11. package/dist/cli/index.js +14 -13
  12. package/dist/cli/project-commands.js +49 -34
  13. package/dist/compiler/build.js +37 -127
  14. package/dist/compiler/client-entry.d.ts +4 -0
  15. package/dist/compiler/client-entry.js +35 -0
  16. package/dist/compiler/client-tooling.d.ts +5 -0
  17. package/dist/compiler/client-tooling.js +97 -0
  18. package/dist/compiler/scanner.js +8 -0
  19. package/dist/compiler/server-bundle.d.ts +11 -0
  20. package/dist/compiler/server-bundle.js +31 -0
  21. package/dist/compiler/type-generation.js +11 -2
  22. package/dist/config/defaults.js +28 -2
  23. package/dist/config/environment.d.ts +2 -0
  24. package/dist/config/environment.js +18 -0
  25. package/dist/discord/data.d.ts +21 -0
  26. package/dist/discord/data.js +91 -0
  27. package/dist/discord/events.d.ts +42 -4
  28. package/dist/discord/events.js +120 -41
  29. package/dist/discord/index.d.ts +4 -2
  30. package/dist/discord/index.js +2 -1
  31. package/dist/discord/runtime.d.ts +2 -2
  32. package/dist/discord/runtime.js +9 -13
  33. package/dist/discord/testing.d.ts +1 -0
  34. package/dist/discord/testing.js +10 -0
  35. package/dist/manifests/types.d.ts +4 -0
  36. package/dist/navigation/index.d.ts +2 -0
  37. package/dist/runtime/client/dev-panel.d.ts +2 -0
  38. package/dist/runtime/client/dev-panel.js +63 -0
  39. package/dist/runtime/client/embed-router.d.ts +4 -1
  40. package/dist/runtime/client/embed-router.js +69 -17
  41. package/dist/runtime/client/files.d.ts +23 -0
  42. package/dist/runtime/client/files.js +12 -0
  43. package/dist/runtime/client/minimize-card.js +4 -4
  44. package/dist/runtime/client/minimize.d.ts +1 -0
  45. package/dist/runtime/client/minimize.js +1 -0
  46. package/dist/runtime/client/root.d.ts +7 -0
  47. package/dist/runtime/client/root.js +19 -0
  48. package/dist/runtime/index.d.ts +8 -4
  49. package/dist/runtime/index.js +14 -2
  50. package/dist/runtime/server/dev-server.d.ts +1 -0
  51. package/dist/runtime/server/dev-server.js +294 -282
  52. package/dist/runtime/server/diagnostics.d.ts +17 -0
  53. package/dist/runtime/server/diagnostics.js +87 -0
  54. package/dist/runtime/server/index.d.ts +5 -0
  55. package/dist/runtime/server/index.js +3 -0
  56. package/dist/runtime/server/production-server.js +14 -1
  57. package/dist/security/discord.d.ts +9 -0
  58. package/dist/security/discord.js +37 -7
  59. package/dist/security/secret-scan.d.ts +3 -0
  60. package/dist/security/secret-scan.js +40 -0
  61. package/dist/server/discord-rest.d.ts +45 -0
  62. package/dist/server/discord-rest.js +46 -0
  63. package/dist/server/index.d.ts +2 -0
  64. package/dist/server/index.js +1 -0
  65. package/dist/sessions/cookies.d.ts +4 -1
  66. package/dist/sessions/cookies.js +17 -4
  67. package/dist/sessions/crypto.js +6 -0
  68. package/dist/testing/index.d.ts +13 -0
  69. package/dist/testing/index.js +24 -0
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/dist/ws/client.d.ts +6 -0
  73. package/dist/ws/client.js +46 -10
  74. package/dist/ws/server.d.ts +4 -0
  75. package/dist/ws/server.js +36 -15
  76. package/package.json +31 -4
  77. package/dist/api/runtime.d.ts.map +0 -1
  78. package/dist/api/runtime.js.map +0 -1
  79. package/dist/auth/client.d.ts.map +0 -1
  80. package/dist/auth/client.js.map +0 -1
  81. package/dist/auth/index.d.ts.map +0 -1
  82. package/dist/auth/index.js.map +0 -1
  83. package/dist/auth/server.d.ts.map +0 -1
  84. package/dist/auth/server.js.map +0 -1
  85. package/dist/auth/types.d.ts.map +0 -1
  86. package/dist/auth/types.js.map +0 -1
  87. package/dist/cli/index.d.ts.map +0 -1
  88. package/dist/cli/index.js.map +0 -1
  89. package/dist/cli/project-commands.d.ts.map +0 -1
  90. package/dist/cli/project-commands.js.map +0 -1
  91. package/dist/compiler/build.d.ts.map +0 -1
  92. package/dist/compiler/build.js.map +0 -1
  93. package/dist/compiler/index.d.ts.map +0 -1
  94. package/dist/compiler/index.js.map +0 -1
  95. package/dist/compiler/scanner.d.ts.map +0 -1
  96. package/dist/compiler/scanner.js.map +0 -1
  97. package/dist/compiler/type-generation.d.ts.map +0 -1
  98. package/dist/compiler/type-generation.js.map +0 -1
  99. package/dist/compiler/write-manifests.d.ts.map +0 -1
  100. package/dist/compiler/write-manifests.js.map +0 -1
  101. package/dist/config/defaults.d.ts.map +0 -1
  102. package/dist/config/defaults.js.map +0 -1
  103. package/dist/config/index.d.ts.map +0 -1
  104. package/dist/config/index.js.map +0 -1
  105. package/dist/config/loader.d.ts.map +0 -1
  106. package/dist/config/loader.js.map +0 -1
  107. package/dist/config/project-root.d.ts.map +0 -1
  108. package/dist/config/project-root.js.map +0 -1
  109. package/dist/config/types.d.ts.map +0 -1
  110. package/dist/config/types.js.map +0 -1
  111. package/dist/discord/events.d.ts.map +0 -1
  112. package/dist/discord/events.js.map +0 -1
  113. package/dist/discord/index.d.ts.map +0 -1
  114. package/dist/discord/index.js.map +0 -1
  115. package/dist/discord/runtime.d.ts.map +0 -1
  116. package/dist/discord/runtime.js.map +0 -1
  117. package/dist/discord/safe-area.d.ts.map +0 -1
  118. package/dist/discord/safe-area.js.map +0 -1
  119. package/dist/discord/testing.d.ts.map +0 -1
  120. package/dist/discord/testing.js.map +0 -1
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/index.js.map +0 -1
  123. package/dist/manifests/types.d.ts.map +0 -1
  124. package/dist/manifests/types.js.map +0 -1
  125. package/dist/navigation/index.d.ts.map +0 -1
  126. package/dist/navigation/index.js.map +0 -1
  127. package/dist/router/match.d.ts.map +0 -1
  128. package/dist/router/match.js.map +0 -1
  129. package/dist/runtime/client/embed-router.d.ts.map +0 -1
  130. package/dist/runtime/client/embed-router.js.map +0 -1
  131. package/dist/runtime/client/minimize-card.d.ts.map +0 -1
  132. package/dist/runtime/client/minimize-card.js.map +0 -1
  133. package/dist/runtime/client/minimize.d.ts.map +0 -1
  134. package/dist/runtime/client/minimize.js.map +0 -1
  135. package/dist/runtime/index.d.ts.map +0 -1
  136. package/dist/runtime/index.js.map +0 -1
  137. package/dist/runtime/server/dev-server.d.ts.map +0 -1
  138. package/dist/runtime/server/dev-server.js.map +0 -1
  139. package/dist/runtime/server/production-server.d.ts.map +0 -1
  140. package/dist/runtime/server/production-server.js.map +0 -1
  141. package/dist/security/discord.d.ts.map +0 -1
  142. package/dist/security/discord.js.map +0 -1
  143. package/dist/security/index.d.ts.map +0 -1
  144. package/dist/security/index.js.map +0 -1
  145. package/dist/server/index.d.ts.map +0 -1
  146. package/dist/server/index.js.map +0 -1
  147. package/dist/server/session.d.ts.map +0 -1
  148. package/dist/server/session.js.map +0 -1
  149. package/dist/server/types.d.ts.map +0 -1
  150. package/dist/server/types.js.map +0 -1
  151. package/dist/sessions/cookies.d.ts.map +0 -1
  152. package/dist/sessions/cookies.js.map +0 -1
  153. package/dist/sessions/crypto.d.ts.map +0 -1
  154. package/dist/sessions/crypto.js.map +0 -1
  155. package/dist/shared/errors.d.ts.map +0 -1
  156. package/dist/shared/errors.js.map +0 -1
  157. package/dist/testing/index.d.ts.map +0 -1
  158. package/dist/testing/index.js.map +0 -1
  159. package/dist/version.d.ts.map +0 -1
  160. package/dist/version.js.map +0 -1
  161. package/dist/ws/client.d.ts.map +0 -1
  162. package/dist/ws/client.js.map +0 -1
  163. package/dist/ws/index.d.ts.map +0 -1
  164. package/dist/ws/index.js.map +0 -1
  165. package/dist/ws/server.d.ts.map +0 -1
  166. package/dist/ws/server.js.map +0 -1
@@ -0,0 +1,91 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { useDiscord } from "./runtime.js";
3
+ import { addDiscordDiagnostic, useDiscordGuild } from "./events.js";
4
+ import { useAuthStatus } from "../auth/client.js";
5
+ export function useDiscordCommands() {
6
+ const discord = useDiscord();
7
+ return useMemo(() => ({
8
+ supports(name) { return typeof discord.sdk?.commands?.[name] === "function"; },
9
+ async call(name, ...args) {
10
+ const command = discord.sdk?.commands?.[name];
11
+ if (discord.status !== "ready" || typeof command !== "function") {
12
+ const message = `LUDICORD5010: Discord command ${name} is not available in this client.`;
13
+ addDiscordDiagnostic(message);
14
+ throw new Error(message);
15
+ }
16
+ try {
17
+ return await command.apply(discord.sdk?.commands, args);
18
+ }
19
+ catch (cause) {
20
+ const message = `LUDICORD5011: Discord command ${name} failed. Check its required scopes and client support.`;
21
+ addDiscordDiagnostic(message);
22
+ throw new Error(message, { cause });
23
+ }
24
+ },
25
+ }), [discord.sdk, discord.status]);
26
+ }
27
+ export function useDiscordGuildMembers(options = {}) {
28
+ const guild = useDiscordGuild();
29
+ const auth = useAuthStatus();
30
+ const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 100) || 100));
31
+ const previousGuild = useRef(undefined);
32
+ const enabled = options.enabled !== false && auth === "authenticated" && guild !== null;
33
+ const [members, setMembers] = useState([]);
34
+ const [status, setStatus] = useState("idle");
35
+ const [error, setError] = useState(null);
36
+ const [next, setNext] = useState(null);
37
+ const [request, setRequest] = useState({ revision: 0, after: "" });
38
+ useEffect(() => {
39
+ if (!enabled) {
40
+ setMembers([]);
41
+ setError(null);
42
+ setStatus("idle");
43
+ setNext(null);
44
+ previousGuild.current = undefined;
45
+ return;
46
+ }
47
+ const changedGuild = previousGuild.current !== guild?.id;
48
+ previousGuild.current = guild?.id;
49
+ const after = changedGuild ? "" : request.after;
50
+ if (changedGuild) {
51
+ setMembers([]);
52
+ setNext(null);
53
+ if (request.after) {
54
+ setRequest((current) => ({ revision: current.revision + 1, after: "" }));
55
+ return;
56
+ }
57
+ }
58
+ const abort = new AbortController();
59
+ setStatus("loading");
60
+ setError(null);
61
+ void fetch(`/_ludicord/auth/guild-members?limit=${limit}${after ? `&after=${encodeURIComponent(after)}` : ""}`, { credentials: "include", signal: abort.signal })
62
+ .then(async (response) => {
63
+ const body = await response.json();
64
+ if (!response.ok)
65
+ throw new Error(body.message ?? "Discord guild members are unavailable.");
66
+ if (abort.signal.aborted)
67
+ return;
68
+ const page = (body.members ?? []).map((member) => ({
69
+ user: { id: member.user.id, username: member.user.username, displayName: member.user.global_name ?? member.user.username,
70
+ avatar: member.user.avatar ? `https://cdn.discordapp.com/avatars/${member.user.id}/${member.user.avatar}.png` : null },
71
+ nickname: member.nick ?? null, roles: member.roles ?? [], ...(member.joined_at === undefined ? {} : { joinedAt: member.joined_at }),
72
+ }));
73
+ setMembers((current) => after === "" ? page : [...current.filter((item) => !page.some((entry) => entry.user.id === item.user.id)), ...page]);
74
+ setNext(body.next ?? null);
75
+ setStatus("ready");
76
+ }).catch((cause) => {
77
+ if (abort.signal.aborted)
78
+ return;
79
+ const failure = cause instanceof Error ? cause : new Error("Discord guild members are unavailable.");
80
+ setError(failure);
81
+ setStatus("error");
82
+ addDiscordDiagnostic(failure.message);
83
+ });
84
+ return () => abort.abort();
85
+ }, [enabled, guild?.id, limit, request]);
86
+ const refresh = useCallback(() => setRequest((current) => ({ revision: current.revision + 1, after: "" })), []);
87
+ const loadMore = useCallback(() => { if (next !== null && status !== "loading")
88
+ setRequest((current) => ({ revision: current.revision + 1, after: next })); }, [next, status]);
89
+ return { members, status, error, hasMore: next !== null, refresh, loadMore };
90
+ }
91
+ //# sourceMappingURL=data.js.map
@@ -12,11 +12,24 @@ export interface LudicordDiscordChannel {
12
12
  readonly name?: string;
13
13
  readonly type?: number;
14
14
  readonly topic?: string;
15
+ readonly guildId?: string;
16
+ readonly kind?: string;
17
+ readonly isVoice?: boolean;
15
18
  }
16
19
  export interface LudicordDiscordGuild {
17
20
  readonly id: string;
18
21
  readonly name?: string;
19
22
  readonly icon?: string | null;
23
+ readonly description?: string | null;
24
+ readonly memberCount?: number;
25
+ readonly features?: readonly string[];
26
+ }
27
+ export interface LudicordGuildMember {
28
+ readonly user: LudicordDiscordUser;
29
+ readonly nickname?: string | null;
30
+ readonly avatar?: string | null;
31
+ readonly roles: readonly string[];
32
+ readonly joinedAt?: string;
20
33
  }
21
34
  export interface LudicordParticipant {
22
35
  readonly id: string;
@@ -44,16 +57,41 @@ export interface LudicordDiscordEventSnapshot {
44
57
  readonly locale: string | null;
45
58
  readonly diagnostics: readonly string[];
46
59
  readonly scopes: readonly string[];
60
+ readonly channelMembers: readonly LudicordDiscordUser[];
61
+ readonly currentGuildMember: LudicordGuildMember | null;
62
+ readonly entitlements: readonly Readonly<Record<string, unknown>>[];
47
63
  }
48
- export declare function initializeDiscordEventStore(sdk: DiscordSdkLike, scopes?: readonly string[]): Promise<void>;
49
- export declare function initializeDiscordEventsFromEnvironment(discord: DiscordRuntimeSnapshot): Promise<void>;
50
- export declare function setDiscordUserFromAuth(user: LudicordSessionUser): void;
51
- export declare function setDiscordGuildFromAuth(guildId: string | undefined, guildName: string | undefined): void;
64
+ export declare function channelTypeName(type: number): string;
65
+ export declare function addDiscordDiagnostic(message: string): void;
66
+ export declare function initializeDiscordEventStore(sdk: DiscordSdkLike, scopes?: readonly string[], channelId?: string, guildId?: string): Promise<void>;
67
+ export declare function initializeDiscordEventsFromEnvironment(discord: DiscordRuntimeSnapshot, grantedScopes?: readonly string[]): Promise<void>;
68
+ export declare function setDiscordUserFromAuth(user: LudicordSessionUser | null): void;
69
+ export declare function enrichDiscordContext(context: {
70
+ guild?: {
71
+ id: string;
72
+ name: string;
73
+ icon?: string | null;
74
+ description?: string | null;
75
+ approximate_member_count?: number;
76
+ features?: readonly string[];
77
+ };
78
+ channel?: {
79
+ id: string;
80
+ name?: string;
81
+ type: number;
82
+ guild_id?: string;
83
+ topic?: string | null;
84
+ };
85
+ }): void;
86
+ export declare function setDiscordGuildFromAuth(guildId: string | undefined, guildName: string | undefined, guildIcon?: string | null): void;
52
87
  export declare function diagnoseDiscordScope(scope: string, feature: string): void;
53
88
  export declare function useDiscordUser(): LudicordDiscordUser | null;
54
89
  export declare function useDiscordChannel(): LudicordDiscordChannel | null;
55
90
  export declare function useDiscordGuild(): LudicordDiscordGuild | null;
56
91
  export declare function useParticipants(): readonly LudicordParticipant[];
92
+ export declare function useChannelMembers(): readonly LudicordDiscordUser[];
93
+ export declare function useCurrentGuildMember(): LudicordGuildMember | null;
94
+ export declare function useDiscordEntitlements(): readonly Readonly<Record<string, unknown>>[];
57
95
  export declare function useVoiceState(): readonly LudicordVoiceState[];
58
96
  export declare function useSpeakingUsers(): readonly string[];
59
97
  export declare function useIsSpeaking(userId: string | null | undefined): boolean;
@@ -33,6 +33,9 @@ class DiscordEventStore {
33
33
  locale: null,
34
34
  diagnostics: [],
35
35
  scopes: [],
36
+ channelMembers: [],
37
+ currentGuildMember: null,
38
+ entitlements: [],
36
39
  };
37
40
  listeners = new Set();
38
41
  subscribe = (listener) => {
@@ -99,14 +102,13 @@ function normalizeParticipant(value) {
99
102
  : undefined;
100
103
  if (id === undefined)
101
104
  return null;
105
+ const displayName = [source.nickname, source.display_name, source.global_name, source.username].find((value) => typeof value === "string" && value !== "");
102
106
  return {
103
107
  id,
104
108
  ...(typeof source.username === "string"
105
109
  ? { username: source.username }
106
110
  : {}),
107
- ...(typeof source.display_name === "string"
108
- ? { displayName: source.display_name }
109
- : {}),
111
+ ...(displayName === undefined ? {} : { displayName }),
110
112
  ...(typeof source.avatar === "string" || source.avatar === null
111
113
  ? { avatar: discordAvatarUrl(id, source.avatar) }
112
114
  : {}),
@@ -127,11 +129,12 @@ function normalizeVoiceState(payload) {
127
129
  if (typeof value !== "object" || value === null)
128
130
  return null;
129
131
  const source = value;
132
+ const payloadUser = valueFromPayload(payload, ["user"]);
130
133
  const userId = typeof source.user_id === "string"
131
134
  ? source.user_id
132
135
  : typeof source.userId === "string"
133
136
  ? source.userId
134
- : undefined;
137
+ : stringFromPayload(payloadUser, ["id"]);
135
138
  if (userId === undefined)
136
139
  return null;
137
140
  return {
@@ -186,8 +189,26 @@ function eventHandler(event, payload) {
186
189
  });
187
190
  return;
188
191
  }
189
- if (event === "CURRENT_GUILD_MEMBER_UPDATE")
192
+ if (event === "CURRENT_GUILD_MEMBER_UPDATE") {
193
+ const source = payload;
194
+ const user = normalizeUser(valueFromPayload(payload, ["user"])) ?? eventStore.getSnapshot().user;
195
+ if (source !== null && typeof source === "object" && user !== null) {
196
+ const nickname = typeof source.nick === "string" ? source.nick : null;
197
+ eventStore.update({ currentGuildMember: {
198
+ user, nickname,
199
+ roles: Array.isArray(source.roles) ? source.roles.filter((role) => typeof role === "string") : [],
200
+ avatar: typeof source.avatar === "string" ? source.avatar : null,
201
+ } });
202
+ }
190
203
  return;
204
+ }
205
+ if (event === "ENTITLEMENT_CREATE" && typeof payload === "object" && payload !== null) {
206
+ const entitlement = (valueFromPayload(payload, ["entitlement"]) ?? payload);
207
+ if (typeof entitlement.id !== "string")
208
+ return;
209
+ eventStore.update((current) => ({ ...current, entitlements: [...current.entitlements.filter((item) => item.id !== entitlement.id), entitlement].slice(-500) }));
210
+ return;
211
+ }
191
212
  if (event === "ACTIVITY_LAYOUT_MODE_UPDATE") {
192
213
  eventStore.update({
193
214
  layoutMode: layoutModeFromPayload(payload) ?? null,
@@ -196,22 +217,33 @@ function eventHandler(event, payload) {
196
217
  }
197
218
  if (event === "ORIENTATION_UPDATE") {
198
219
  eventStore.update({
199
- orientation: stringFromPayload(payload, ["orientation"]) ?? null,
220
+ orientation: stringFromPayload(payload, ["orientation"]) ??
221
+ { 0: "portrait", 1: "landscape" }[Number(valueFromPayload(payload, ["screen_orientation"]))] ?? null,
200
222
  });
201
223
  return;
202
224
  }
203
225
  if (event === "THERMAL_STATE_UPDATE") {
204
226
  eventStore.update({
205
- thermalState: stringFromPayload(payload, ["thermal_state", "thermalState"]) ?? null,
227
+ thermalState: stringFromPayload(payload, ["thermal_state", "thermalState"]) ??
228
+ { 0: "nominal", 1: "fair", 2: "serious", 3: "critical" }[Number(valueFromPayload(payload, ["thermal_state", "thermalState"]))] ?? null,
206
229
  });
207
230
  }
208
231
  }
232
+ async function bounded(operation) {
233
+ let timer;
234
+ try {
235
+ return await Promise.race([operation, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error("Discord capability timed out.")), 5000); })]);
236
+ }
237
+ finally {
238
+ clearTimeout(timer);
239
+ }
240
+ }
209
241
  async function initialParticipants(sdk) {
210
- const command = sdk.commands?.getActivityInstanceConnectedParticipants;
242
+ const command = sdk.commands?.getInstanceConnectedParticipants ?? sdk.commands?.getActivityInstanceConnectedParticipants;
211
243
  if (typeof command !== "function")
212
244
  return;
213
245
  try {
214
- const result = await command();
246
+ const result = await bounded(command.call(sdk.commands));
215
247
  eventStore.update({ participants: normalizeParticipants(result) });
216
248
  }
217
249
  catch {
@@ -224,7 +256,7 @@ async function initialChannel(sdk, channelId) {
224
256
  if (commands === undefined || channelId === undefined || typeof command !== "function")
225
257
  return;
226
258
  try {
227
- const result = await command.call(commands, { channel_id: channelId });
259
+ const result = await bounded(command.call(commands, { channel_id: channelId }));
228
260
  if (typeof result !== "object" || result === null)
229
261
  return;
230
262
  const channel = result;
@@ -235,6 +267,8 @@ async function initialChannel(sdk, channelId) {
235
267
  ...(typeof channel.name === "string" ? { name: channel.name } : {}),
236
268
  ...(typeof channel.type === "number" ? { type: channel.type } : {}),
237
269
  ...(typeof channel.topic === "string" ? { topic: channel.topic } : {}),
270
+ ...(typeof channel.guild_id === "string" ? { guildId: channel.guild_id } : {}),
271
+ ...(typeof channel.type === "number" ? { kind: channelTypeName(channel.type), isVoice: channel.type === 2 || channel.type === 13 } : {}),
238
272
  },
239
273
  ...(typeof channel.guild_id === "string"
240
274
  ? {
@@ -245,53 +279,85 @@ async function initialChannel(sdk, channelId) {
245
279
  }
246
280
  : {}),
247
281
  }));
282
+ const voices = valueFromPayload(result, ["voice_states"]);
283
+ if (Array.isArray(voices)) {
284
+ eventStore.update({
285
+ voiceStates: voices.map(normalizeVoiceState).filter((value) => value !== null),
286
+ channelMembers: voices.map((voice) => normalizeUser(valueFromPayload(voice, ["user"]))).filter((value) => value !== null),
287
+ });
288
+ }
248
289
  }
249
290
  catch {
250
- // Channel lookup requires the guilds scope and may be unavailable.
291
+ addDiscordDiagnostic("Channel details unavailable. Guild channels require the guilds scope; group DMs also require approved dm_channels.read access.");
251
292
  }
252
293
  }
253
- export async function initializeDiscordEventStore(sdk, scopes = []) {
294
+ export function channelTypeName(type) {
295
+ return { 0: "text", 1: "dm", 2: "voice", 3: "group-dm", 4: "category", 5: "announcement", 10: "announcement-thread", 11: "public-thread", 12: "private-thread", 13: "stage", 14: "directory", 15: "forum", 16: "media" }[type] ?? "unknown";
296
+ }
297
+ export function addDiscordDiagnostic(message) {
298
+ const current = eventStore.getSnapshot();
299
+ if (!current.diagnostics.includes(message))
300
+ eventStore.update({ diagnostics: [...current.diagnostics, message] });
301
+ }
302
+ export async function initializeDiscordEventStore(sdk, scopes = [], channelId, guildId) {
254
303
  if (activeController?.sdk === sdk)
255
304
  return;
256
305
  await activeController?.cleanup();
257
306
  eventStore.update({ scopes: [...scopes] });
258
307
  const subscriptions = [];
259
- if (typeof sdk.subscribe === "function") {
260
- for (const event of EVENT_NAMES) {
261
- const listener = (payload) => eventHandler(event, payload);
262
- try {
263
- await sdk.subscribe(event, listener);
264
- subscriptions.push({ event, listener });
265
- }
266
- catch {
267
- // Unsupported optional events are ignored by capability.
268
- }
269
- }
270
- }
308
+ let active = true;
271
309
  activeController = {
272
310
  sdk,
273
311
  async cleanup() {
274
- if (typeof sdk.unsubscribe === "function") {
275
- await Promise.allSettled(subscriptions.map(({ event, listener }) => sdk.unsubscribe?.(event, listener)));
276
- }
312
+ active = false;
313
+ if (typeof sdk.unsubscribe === "function")
314
+ await Promise.allSettled(subscriptions.map(({ event, listener, args }) => bounded(Promise.resolve(sdk.unsubscribe?.(event, listener, args)))));
277
315
  },
278
316
  };
279
- await initialParticipants(sdk);
317
+ if (typeof sdk.subscribe === "function") {
318
+ await Promise.all(EVENT_NAMES.map(async (event) => {
319
+ const listener = (payload) => { if (active)
320
+ eventHandler(event, payload); };
321
+ const args = channelId !== undefined && ["VOICE_STATE_UPDATE", "SPEAKING_START", "SPEAKING_STOP"].includes(event)
322
+ ? { channel_id: channelId } : event === "CURRENT_GUILD_MEMBER_UPDATE" && guildId !== undefined ? { guild_id: guildId } : undefined;
323
+ subscriptions.push({ event, listener, ...(args === undefined ? {} : { args }) });
324
+ try {
325
+ await bounded(Promise.resolve(sdk.subscribe?.(event, listener, args)));
326
+ }
327
+ catch { /* Optional capabilities must not block the Activity. */ }
328
+ }));
329
+ }
330
+ if (active)
331
+ await initialParticipants(sdk);
280
332
  }
281
- export async function initializeDiscordEventsFromEnvironment(discord) {
333
+ export async function initializeDiscordEventsFromEnvironment(discord, grantedScopes) {
282
334
  if (discord.status !== "ready" || discord.sdk === null)
283
335
  return;
284
336
  const config = globalThis.__LUDICORD_PUBLIC_CONFIG__;
285
- await initializeDiscordEventStore(discord.sdk, config?.scopes ?? ["identify"]);
337
+ await initializeDiscordEventStore(discord.sdk, grantedScopes ?? config?.scopes ?? ["identify"], discord.channelId, discord.guildId);
286
338
  const effectiveChannelId = discord.channelId ?? discord.sdk.channelId;
287
339
  const effectiveGuildId = discord.guildId ?? discord.sdk.guildId;
288
340
  eventStore.update({
289
341
  channel: effectiveChannelId === undefined ? null : { id: effectiveChannelId },
290
- guild: effectiveGuildId === undefined ? null : { id: effectiveGuildId },
342
+ guild: effectiveGuildId === undefined ? null : { ...eventStore.getSnapshot().guild, id: effectiveGuildId },
291
343
  });
292
344
  await initialChannel(discord.sdk, effectiveChannelId);
345
+ const localeCommand = discord.sdk.commands?.userSettingsGetLocale;
346
+ if (typeof localeCommand === "function") {
347
+ try {
348
+ const result = await bounded(localeCommand.call(discord.sdk.commands));
349
+ const locale = stringFromPayload(result, ["locale"]);
350
+ if (locale !== undefined)
351
+ eventStore.update({ locale });
352
+ }
353
+ catch { /* Optional on older clients. */ }
354
+ }
293
355
  }
294
356
  export function setDiscordUserFromAuth(user) {
357
+ if (user === null) {
358
+ eventStore.update({ user: null, currentGuildMember: null, guild: null, channel: null, channelMembers: [], entitlements: [], scopes: [] });
359
+ return;
360
+ }
295
361
  eventStore.update({
296
362
  user: {
297
363
  id: user.id,
@@ -301,17 +367,27 @@ export function setDiscordUserFromAuth(user) {
301
367
  },
302
368
  });
303
369
  }
304
- export function setDiscordGuildFromAuth(guildId, guildName) {
305
- if (guildId !== undefined || guildName !== undefined) {
306
- eventStore.update((current) => ({
307
- ...current,
308
- guild: {
309
- id: guildId ?? current.guild?.id ?? "",
310
- ...(guildName ? { name: guildName } : current.guild?.name ? { name: current.guild.name } : {}),
311
- ...(current.guild?.icon ? { icon: current.guild.icon } : {}),
312
- },
313
- }));
370
+ export function enrichDiscordContext(context) {
371
+ const guild = context.guild;
372
+ const channel = context.channel;
373
+ if (guild)
374
+ eventStore.update({ guild: { id: guild.id, name: guild.name, icon: guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png` : null,
375
+ ...(guild.description === undefined ? {} : { description: guild.description }), ...(guild.approximate_member_count === undefined ? {} : { memberCount: guild.approximate_member_count }), ...(guild.features === undefined ? {} : { features: guild.features }) } });
376
+ if (channel)
377
+ eventStore.update({ channel: { id: channel.id, type: channel.type, kind: channelTypeName(channel.type), isVoice: [2, 13].includes(channel.type),
378
+ ...(channel.name === undefined ? {} : { name: channel.name }), ...(channel.guild_id === undefined ? {} : { guildId: channel.guild_id }), ...(channel.topic == null ? {} : { topic: channel.topic }) } });
379
+ }
380
+ export function setDiscordGuildFromAuth(guildId, guildName, guildIcon) {
381
+ if (guildId === undefined) {
382
+ eventStore.update({ guild: null });
383
+ return;
314
384
  }
385
+ const previous = eventStore.getSnapshot().guild;
386
+ eventStore.update({ guild: {
387
+ ...(previous?.id === guildId ? previous : {}), id: guildId,
388
+ ...(guildName === undefined ? {} : { name: guildName }),
389
+ ...(guildIcon === undefined ? {} : { icon: guildIcon }),
390
+ } });
315
391
  }
316
392
  export function diagnoseDiscordScope(scope, feature) {
317
393
  const snapshot = eventStore.getSnapshot();
@@ -353,6 +429,9 @@ export function useDiscordGuild() {
353
429
  export function useParticipants() {
354
430
  return useEventSnapshot().participants;
355
431
  }
432
+ export function useChannelMembers() { return useEventSnapshot().channelMembers; }
433
+ export function useCurrentGuildMember() { return useEventSnapshot().currentGuildMember; }
434
+ export function useDiscordEntitlements() { return useEventSnapshot().entitlements; }
356
435
  export function useVoiceState() {
357
436
  diagnoseDiscordScope("rpc.voice.read", "useVoiceState()");
358
437
  return useEventSnapshot().voiceStates;
@@ -1,7 +1,9 @@
1
1
  export { initializeDiscord, initializeDiscordFromEnvironment, useActivityInstance, useDiscord, } from "./runtime.js";
2
- export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, } from "./events.js";
2
+ export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, useChannelMembers, useCurrentGuildMember, useDiscordEntitlements, channelTypeName, } from "./events.js";
3
3
  export { LUDICORD_SAFE_AREA_CSS, LUDICORD_SAFE_AREA_STYLE_ID, getLudicordSafeAreaInsets, installLudicordSafeAreaVariables, useLudicordSafeArea, } from "./safe-area.js";
4
4
  export type { ActivityInstanceState, LudicordDiscordStatus, DiscordRuntimeOptions, DiscordRuntimeSnapshot, DiscordSdkLike, } from "./runtime.js";
5
- export type { LudicordDiscordChannel, LudicordDiscordEventSnapshot, LudicordDiscordGuild, LudicordDiscordUser, LudicordParticipant, LudicordVoiceState, } from "./events.js";
5
+ export type { LudicordDiscordChannel, LudicordDiscordEventSnapshot, LudicordDiscordGuild, LudicordDiscordUser, LudicordParticipant, LudicordVoiceState, LudicordGuildMember, } from "./events.js";
6
6
  export type { LudicordSafeAreaInsets } from "./safe-area.js";
7
+ export { useDiscordCommands, useDiscordGuildMembers } from "./data.js";
8
+ export type { LudicordDiscordCommand } from "./data.js";
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export { initializeDiscord, initializeDiscordFromEnvironment, useActivityInstance, useDiscord, } from "./runtime.js";
2
- export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, } from "./events.js";
2
+ export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, useChannelMembers, useCurrentGuildMember, useDiscordEntitlements, channelTypeName, } from "./events.js";
3
3
  export { LUDICORD_SAFE_AREA_CSS, LUDICORD_SAFE_AREA_STYLE_ID, getLudicordSafeAreaInsets, installLudicordSafeAreaVariables, useLudicordSafeArea, } from "./safe-area.js";
4
+ export { useDiscordCommands, useDiscordGuildMembers } from "./data.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -2,8 +2,8 @@ export type LudicordDiscordStatus = "idle" | "connecting" | "ready" | "outside-d
2
2
  export interface DiscordSdkLike {
3
3
  ready(): Promise<void>;
4
4
  readonly commands?: Readonly<Record<string, unknown>>;
5
- subscribe?(event: string, listener: (payload: unknown) => void): Promise<void> | void;
6
- unsubscribe?(event: string, listener: (payload: unknown) => void): Promise<void> | void;
5
+ subscribe?(event: string, listener: (payload: unknown) => void, args?: Readonly<Record<string, unknown>>): Promise<void> | void;
6
+ unsubscribe?(event: string, listener: (payload: unknown) => void, args?: Readonly<Record<string, unknown>>): Promise<void> | void;
7
7
  readonly instanceId?: string | null;
8
8
  readonly channelId?: string | null;
9
9
  readonly guildId?: string | null;
@@ -29,28 +29,23 @@ class DiscordRuntimeStore {
29
29
  initialize(options) {
30
30
  if (this.initialization !== null)
31
31
  return this.initialization;
32
- this.initialization = this.performInitialization(options);
32
+ this.initialization = this.performInitialization(options).catch((error) => { this.initialization = null; throw error; });
33
33
  return this.initialization;
34
34
  }
35
35
  async performInitialization(options) {
36
36
  const clientId = options.clientId?.trim();
37
+ const outsideDiscord = options.outsideDiscord ?? "error";
38
+ if (options.factory === undefined && !hasDiscordFrameContext() && (outsideDiscord === "allow" || outsideDiscord === "mock")) {
39
+ const snapshot = { status: "outside-discord", sdk: null, error: null, ...(clientId ? { applicationId: clientId } : {}) };
40
+ this.update(snapshot);
41
+ return snapshot;
42
+ }
37
43
  if (clientId === undefined || clientId === "") {
38
44
  const error = new LudicordDiscordError("LUDICORD5001", "Missing LUDICORD_DISCORD_CLIENT_ID.");
39
45
  this.update({ status: "error", sdk: null, error });
40
46
  throw error;
41
47
  }
42
- const outsideDiscord = options.outsideDiscord ?? "error";
43
48
  if (options.factory === undefined && !hasDiscordFrameContext()) {
44
- if (outsideDiscord === "allow" || outsideDiscord === "mock") {
45
- const snapshot = {
46
- status: "outside-discord",
47
- sdk: null,
48
- error: null,
49
- applicationId: clientId,
50
- };
51
- this.update(snapshot);
52
- return snapshot;
53
- }
54
49
  const error = new LudicordDiscordError("LUDICORD5002", "Discord Activity context was not detected.");
55
50
  this.update({
56
51
  status: "error",
@@ -68,8 +63,9 @@ class DiscordRuntimeStore {
68
63
  });
69
64
  const factory = options.factory ??
70
65
  ((applicationId) => new DiscordSDK(applicationId));
71
- const sdk = factory(clientId);
66
+ let sdk = null;
72
67
  try {
68
+ sdk = factory(clientId);
73
69
  await withTimeout(sdk.ready(), options.timeoutMs ?? 10_000, "Discord SDK ready() timed out.");
74
70
  const searchParams = typeof window !== "undefined"
75
71
  ? new URLSearchParams(window.location.search)
@@ -5,6 +5,7 @@ export interface MockDiscordController {
5
5
  readonly factory: NonNullable<DiscordRuntimeOptions["factory"]>;
6
6
  readonly constructorCalls: () => number;
7
7
  readonly readyCalls: () => number;
8
+ emit(event: string, payload: unknown): void;
8
9
  }
9
10
  export declare function createMockDiscord(overrides?: Partial<DiscordSdkLike>): MockDiscordController;
10
11
  export { resetDiscordRuntimeForTesting };
@@ -3,7 +3,15 @@ export function createMockDiscord(overrides = {}) {
3
3
  let constructors = 0;
4
4
  let readyCalls = 0;
5
5
  const providedReady = overrides.ready;
6
+ const listeners = new Map();
6
7
  const sdk = {
8
+ commands: {
9
+ getInstanceConnectedParticipants: async () => ({ participants: [] }),
10
+ getChannel: async ({ channel_id }) => ({ id: channel_id, name: "Mock voice", type: 2, voice_states: [] }),
11
+ userSettingsGetLocale: async () => ({ locale: "en-US" }),
12
+ },
13
+ async subscribe(event, listener) { const entries = listeners.get(event) ?? new Set(); entries.add(listener); listeners.set(event, entries); },
14
+ async unsubscribe(event, listener) { listeners.get(event)?.delete(listener); },
7
15
  ...overrides,
8
16
  async ready() {
9
17
  readyCalls += 1;
@@ -18,6 +26,8 @@ export function createMockDiscord(overrides = {}) {
18
26
  },
19
27
  constructorCalls: () => constructors,
20
28
  readyCalls: () => readyCalls,
29
+ emit(event, payload) { for (const listener of listeners.get(event) ?? [])
30
+ listener(payload); },
21
31
  };
22
32
  }
23
33
  export { resetDiscordRuntimeForTesting };
@@ -4,6 +4,10 @@ export interface ActivityManifest {
4
4
  readonly layout?: string;
5
5
  readonly loading?: string;
6
6
  readonly error?: string;
7
+ readonly minimize?: string;
8
+ readonly authLoading?: string;
9
+ readonly authError?: string;
10
+ readonly authDenied?: string;
7
11
  }
8
12
  export interface RouteParameter {
9
13
  readonly name: string;
@@ -10,6 +10,8 @@ export type LudicordApiRoute = RegisteredRoute<"api">;
10
10
  export type LudicordWebSocketRoute = RegisteredRoute<"websocket">;
11
11
  export type LudicordGeneratedConfig = RegisteredValue<"config", Readonly<Record<string, unknown>>>;
12
12
  type LudicordGeneratedEmbedParams = RegisteredMap<"embedParams">;
13
+ export type LudicordApiParams<TRoute extends string = LudicordApiRoute> = TRoute extends keyof RegisteredMap<"apiParams"> ? RegisteredMap<"apiParams">[TRoute] : Readonly<Record<string, string>>;
14
+ export type LudicordWebSocketParams<TRoute extends string = LudicordWebSocketRoute> = TRoute extends keyof RegisteredMap<"websocketParams"> ? RegisteredMap<"websocketParams">[TRoute] : Readonly<Record<string, string>>;
13
15
  export type LudicordEmbedParams<TRoute extends string = LudicordEmbedPattern> = TRoute extends keyof LudicordGeneratedEmbedParams ? LudicordGeneratedEmbedParams[TRoute] : Readonly<Record<string, string>>;
14
16
  export interface LudicordEmbedRouter {
15
17
  push(path: LudicordEmbedRoute): void;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=dev-panel.d.ts.map