ludicord 2.2.4 → 3.0.0

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 (150) hide show
  1. package/README.md +21 -5
  2. package/dist/activity/game-loop.d.ts +16 -0
  3. package/dist/activity/game-loop.js +33 -0
  4. package/dist/activity/index.d.ts +12 -0
  5. package/dist/activity/index.js +6 -0
  6. package/dist/activity/lifecycle.d.ts +11 -0
  7. package/dist/activity/lifecycle.js +41 -0
  8. package/dist/activity/presence.d.ts +10 -0
  9. package/dist/activity/presence.js +15 -0
  10. package/dist/activity/query.d.ts +21 -0
  11. package/dist/activity/query.js +148 -0
  12. package/dist/activity/shared-state.d.ts +10 -0
  13. package/dist/activity/shared-state.js +100 -0
  14. package/dist/activity/storage.d.ts +16 -0
  15. package/dist/activity/storage.js +88 -0
  16. package/dist/api/runtime.d.ts +5 -2
  17. package/dist/api/runtime.js +53 -10
  18. package/dist/auth/client.d.ts +0 -1
  19. package/dist/auth/client.js +3 -5
  20. package/dist/auth/index.d.ts +0 -1
  21. package/dist/auth/index.js +0 -1
  22. package/dist/auth/server.d.ts +2 -1
  23. package/dist/auth/server.js +161 -16
  24. package/dist/auth/types.d.ts +5 -1
  25. package/dist/auth/types.js +0 -1
  26. package/dist/cli/index.d.ts +0 -1
  27. package/dist/cli/index.js +116 -19
  28. package/dist/cli/project-commands.d.ts +1 -5
  29. package/dist/cli/project-commands.js +14 -162
  30. package/dist/compiler/build.d.ts +10 -1
  31. package/dist/compiler/build.js +124 -16
  32. package/dist/compiler/bundle-report.d.ts +17 -0
  33. package/dist/compiler/bundle-report.js +60 -0
  34. package/dist/compiler/client-entry.d.ts +0 -1
  35. package/dist/compiler/client-entry.js +28 -4
  36. package/dist/compiler/client-tooling.d.ts +0 -1
  37. package/dist/compiler/client-tooling.js +8 -2
  38. package/dist/compiler/index.d.ts +3 -1
  39. package/dist/compiler/index.js +2 -1
  40. package/dist/compiler/scanner.d.ts +0 -1
  41. package/dist/compiler/scanner.js +59 -4
  42. package/dist/compiler/server-bundle.d.ts +1 -2
  43. package/dist/compiler/server-bundle.js +11 -2
  44. package/dist/compiler/type-generation.d.ts +0 -1
  45. package/dist/compiler/type-generation.js +2 -1
  46. package/dist/compiler/write-manifests.d.ts +0 -1
  47. package/dist/compiler/write-manifests.js +0 -1
  48. package/dist/config/defaults.d.ts +0 -1
  49. package/dist/config/defaults.js +14 -2
  50. package/dist/config/environment.d.ts +0 -1
  51. package/dist/config/environment.js +0 -1
  52. package/dist/config/index.d.ts +0 -1
  53. package/dist/config/index.js +0 -1
  54. package/dist/config/loader.d.ts +0 -1
  55. package/dist/config/loader.js +0 -1
  56. package/dist/config/project-root.d.ts +0 -1
  57. package/dist/config/project-root.js +0 -1
  58. package/dist/config/types.d.ts +25 -1
  59. package/dist/config/types.js +0 -1
  60. package/dist/discord/assets.d.ts +5 -0
  61. package/dist/discord/assets.js +29 -0
  62. package/dist/discord/data.d.ts +38 -2
  63. package/dist/discord/data.js +178 -11
  64. package/dist/discord/events.d.ts +28 -2
  65. package/dist/discord/events.js +109 -39
  66. package/dist/discord/index.d.ts +6 -5
  67. package/dist/discord/index.js +3 -3
  68. package/dist/discord/payload.d.ts +6 -0
  69. package/dist/discord/payload.js +5 -0
  70. package/dist/discord/runtime.d.ts +0 -1
  71. package/dist/discord/runtime.js +0 -1
  72. package/dist/discord/safe-area.d.ts +0 -1
  73. package/dist/discord/safe-area.js +0 -1
  74. package/dist/discord/testing.d.ts +0 -1
  75. package/dist/discord/testing.js +0 -1
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.js +3 -1
  78. package/dist/lint/index.d.ts +6 -0
  79. package/dist/lint/index.js +71 -0
  80. package/dist/manifests/types.d.ts +11 -1
  81. package/dist/manifests/types.js +0 -1
  82. package/dist/metadata/index.d.ts +13 -0
  83. package/dist/metadata/index.js +4 -0
  84. package/dist/navigation/index.d.ts +3 -1
  85. package/dist/navigation/index.js +1 -1
  86. package/dist/navigation/link.d.ts +8 -0
  87. package/dist/navigation/link.js +38 -0
  88. package/dist/router/match.d.ts +0 -1
  89. package/dist/router/match.js +0 -1
  90. package/dist/runtime/client/dev-panel.d.ts +0 -1
  91. package/dist/runtime/client/dev-panel.js +722 -38
  92. package/dist/runtime/client/embed-router.d.ts +8 -1
  93. package/dist/runtime/client/embed-router.js +116 -62
  94. package/dist/runtime/client/files.d.ts +5 -1
  95. package/dist/runtime/client/files.js +0 -1
  96. package/dist/runtime/client/minimize-card.d.ts +0 -1
  97. package/dist/runtime/client/minimize-card.js +0 -1
  98. package/dist/runtime/client/minimize.d.ts +0 -1
  99. package/dist/runtime/client/minimize.js +0 -1
  100. package/dist/runtime/client/root.d.ts +5 -3
  101. package/dist/runtime/client/root.js +28 -3
  102. package/dist/runtime/index.d.ts +1 -2
  103. package/dist/runtime/index.js +0 -1
  104. package/dist/runtime/server/dev-server.d.ts +0 -1
  105. package/dist/runtime/server/dev-server.js +191 -30
  106. package/dist/runtime/server/diagnostics.d.ts +1 -1
  107. package/dist/runtime/server/diagnostics.js +5 -4
  108. package/dist/runtime/server/index.d.ts +0 -1
  109. package/dist/runtime/server/index.js +0 -1
  110. package/dist/runtime/server/production-server.d.ts +2 -1
  111. package/dist/runtime/server/production-server.js +145 -25
  112. package/dist/security/discord.d.ts +0 -1
  113. package/dist/security/discord.js +0 -1
  114. package/dist/security/index.d.ts +0 -1
  115. package/dist/security/index.js +0 -1
  116. package/dist/security/secret-scan.d.ts +0 -1
  117. package/dist/security/secret-scan.js +0 -1
  118. package/dist/server/discord-rest.d.ts +42 -7
  119. package/dist/server/discord-rest.js +135 -18
  120. package/dist/server/index.d.ts +7 -2
  121. package/dist/server/index.js +3 -1
  122. package/dist/server/instrumentation.d.ts +16 -0
  123. package/dist/server/instrumentation.js +3 -0
  124. package/dist/server/proxy.d.ts +21 -0
  125. package/dist/server/proxy.js +76 -0
  126. package/dist/server/session.d.ts +0 -1
  127. package/dist/server/session.js +0 -1
  128. package/dist/server/types.d.ts +0 -1
  129. package/dist/server/types.js +0 -1
  130. package/dist/sessions/cookies.d.ts +0 -1
  131. package/dist/sessions/cookies.js +0 -1
  132. package/dist/sessions/crypto.d.ts +0 -1
  133. package/dist/sessions/crypto.js +0 -1
  134. package/dist/sessions/data-store.d.ts +18 -0
  135. package/dist/sessions/data-store.js +45 -0
  136. package/dist/shared/errors.d.ts +0 -1
  137. package/dist/shared/errors.js +0 -1
  138. package/dist/testing/index.d.ts +0 -1
  139. package/dist/testing/index.js +2 -2
  140. package/dist/version.d.ts +1 -2
  141. package/dist/version.js +1 -2
  142. package/dist/ws/client.d.ts +0 -1
  143. package/dist/ws/client.js +0 -1
  144. package/dist/ws/index.d.ts +3 -2
  145. package/dist/ws/index.js +1 -1
  146. package/dist/ws/server.d.ts +5 -3
  147. package/dist/ws/server.js +65 -19
  148. package/dist/ws/shared-state.d.ts +13 -0
  149. package/dist/ws/shared-state.js +137 -0
  150. package/package.json +16 -3
package/README.md CHANGED
@@ -1,19 +1,35 @@
1
- # ludicord
1
+ <p align="center">
2
+ <a href="https://github.com/mrcholer/ludicord"><img src="https://raw.githubusercontent.com/mrcholer/ludicord/main/.github/assets/ludicord-banner.png" alt="Ludicord" width="900" /></a>
3
+ </p>
4
+
5
+ <h1 align="center">ludicord</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/ludicord"><img alt="npm version" src="https://img.shields.io/npm/v/ludicord?style=flat-square&color=5865F2" /></a>
9
+ <a href="https://www.npmjs.com/package/ludicord"><img alt="npm downloads" src="https://img.shields.io/npm/dm/ludicord?style=flat-square&color=00B0F4" /></a>
10
+ <img alt="Node.js 20.19 or newer" src="https://img.shields.io/badge/node-%3E%3D20.19-339933?style=flat-square&logo=nodedotjs&logoColor=white" />
11
+ <img alt="React 18.3 and 19" src="https://img.shields.io/badge/react-18.3%20%7C%2019-61DAFB?style=flat-square&logo=react&logoColor=111" />
12
+ <a href="https://github.com/mrcholer/ludicord/blob/main/SECURITY.md"><img alt="Security policy" src="https://img.shields.io/badge/security-policy-6D5DFC?style=flat-square" /></a>
13
+ </p>
2
14
 
3
15
  The full-stack React framework and CLI for Discord Activities.
4
16
 
5
17
  ```bash
6
18
  ludicord dev
19
+ ludicord lint
7
20
  ludicord build
21
+ ludicord analyze
8
22
  ludicord start
9
23
  ```
10
24
 
11
- Public entry points include `ludicord`, `ludicord/config`, `ludicord/navigation`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
25
+ Public entry points include `ludicord`, `ludicord/config`, `ludicord/metadata`, `ludicord/navigation`, `ludicord/activity`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
12
26
 
13
27
  See the public [documentation](https://github.com/mrcholer/ludicord/blob/main/docs/README.md), [release history](https://github.com/mrcholer/ludicord/blob/main/CHANGELOG.md), and [issue tracker](https://github.com/mrcholer/ludicord/issues). The public repository contains documentation and release information, not the framework implementation.
14
28
 
15
- Automatic files: `app/layout.tsx`, `loading.tsx`, `error.tsx`, `minimize.tsx`, and `app/auth/{loading,error,denied}.tsx`. Default-export the component and the framework connects it. Embeds use `export default function embed()`.
29
+ Automatic files: `app/metadata.ts`, `proxy.ts`, `instrumentation.ts`, `layout.tsx`, `loading.tsx`, `error.tsx`, `global-error.tsx`, `not-found.tsx`, `minimize.tsx`, and `app/auth/{loading,error,denied}.tsx`. Embed folders may also inherit nested `layout.tsx` and nearest `loading.tsx`/`error.tsx`. Route groups such as `(games)` organize embed/API/WS source without changing URLs. Default-export the component or convention object and the framework connects it. Embeds use `export default function embed()`.
30
+
31
+ Development includes API/WS/proxy hot updates, TypeScript diagnostics, React Hooks linting, React Strict Mode, a Ludicord browser error panel with mapped source locations, and branded compile timing. Production uses atomic output, client bundle analysis, and safe errors without source disclosure.
16
32
 
17
- Development includes API/WS hot updates, TypeScript diagnostics, a Ludicord browser error panel with mapped source locations, and branded compile timing. Production uses safe errors without source disclosure.
33
+ Discord helpers include complete raw user/channel/guild/member/role/participant/event payloads beside convenient normalized fields, Activity participants, voice/layout events, typed SDK commands, verified permission bitfields, channel/role/member resources, and paginated guild members. Full member lists require a server-only bot token and the GUILD_MEMBERS intent.
18
34
 
19
- Discord helpers include detailed channel/guild hooks, Activity participants, voice/layout events, typed SDK commands, and permission-gated paginated guild members. Full member lists require a server-only bot token and the GUILD_MEMBERS intent.
35
+ Activity hooks add scoped persistence, cached queries, lifecycle readiness, raw Discord-event callbacks, presence summaries, animation frames, and revision-safe shared instance state. Use normal React state for local UI and these helpers where Discord Activity behavior needs a framework-owned lifecycle.
@@ -0,0 +1,16 @@
1
+ export interface LudicordGameFrame {
2
+ readonly time: number;
3
+ readonly delta: number;
4
+ readonly frame: number;
5
+ }
6
+ export interface LudicordGameLoopOptions {
7
+ readonly enabled?: boolean;
8
+ readonly pauseWhenHidden?: boolean;
9
+ readonly maxDelta?: number;
10
+ }
11
+ export interface LudicordGameLoop {
12
+ readonly running: boolean;
13
+ readonly start: () => void;
14
+ readonly stop: () => void;
15
+ }
16
+ export declare function useGameLoop(callback: (frame: LudicordGameFrame) => void, options?: LudicordGameLoopOptions): LudicordGameLoop;
@@ -0,0 +1,33 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ export function useGameLoop(callback, options = {}) {
3
+ const callbackRef = useRef(callback);
4
+ callbackRef.current = callback;
5
+ const [running, setRunning] = useState(options.enabled ?? true);
6
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
7
+ const maxDelta = options.maxDelta ?? 100;
8
+ if (!Number.isFinite(maxDelta) || maxDelta <= 0) {
9
+ throw new Error("LUDICORD2202: useGameLoop() maxDelta must be a positive number.");
10
+ }
11
+ useEffect(() => {
12
+ if (!running || typeof requestAnimationFrame === "undefined")
13
+ return;
14
+ let request = 0;
15
+ let previous = null;
16
+ let frame = 0;
17
+ const tick = (time) => {
18
+ request = requestAnimationFrame(tick);
19
+ if (pauseWhenHidden && typeof document !== "undefined" && document.visibilityState === "hidden") {
20
+ previous = time;
21
+ return;
22
+ }
23
+ const delta = previous === null ? 0 : Math.min(maxDelta, Math.max(0, time - previous));
24
+ previous = time;
25
+ callbackRef.current({ time, delta, frame: frame++ });
26
+ };
27
+ request = requestAnimationFrame(tick);
28
+ return () => cancelAnimationFrame(request);
29
+ }, [maxDelta, pauseWhenHidden, running]);
30
+ const start = useCallback(() => setRunning(true), []);
31
+ const stop = useCallback(() => setRunning(false), []);
32
+ return useMemo(() => ({ running, start, stop }), [running, start, stop]);
33
+ }
@@ -0,0 +1,12 @@
1
+ export { useActivityLifecycle } from "./lifecycle.js";
2
+ export type { LudicordActivityLifecycle } from "./lifecycle.js";
3
+ export { useActivityStorage } from "./storage.js";
4
+ export type { LudicordActivityStorage, LudicordActivityStorageOptions, LudicordActivityStorageScope, } from "./storage.js";
5
+ export { useActivityQuery, clearActivityQueryCache } from "./query.js";
6
+ export type { LudicordActivityQuery, LudicordActivityQueryKey, LudicordActivityQueryOptions, LudicordActivityQueryStatus, } from "./query.js";
7
+ export { useGameLoop } from "./game-loop.js";
8
+ export type { LudicordGameFrame, LudicordGameLoop, LudicordGameLoopOptions } from "./game-loop.js";
9
+ export { useActivityPresence } from "./presence.js";
10
+ export type { LudicordActivityPresence } from "./presence.js";
11
+ export { useSharedActivityState } from "./shared-state.js";
12
+ export type { LudicordSharedActivityState } from "./shared-state.js";
@@ -0,0 +1,6 @@
1
+ export { useActivityLifecycle } from "./lifecycle.js";
2
+ export { useActivityStorage } from "./storage.js";
3
+ export { useActivityQuery, clearActivityQueryCache } from "./query.js";
4
+ export { useGameLoop } from "./game-loop.js";
5
+ export { useActivityPresence } from "./presence.js";
6
+ export { useSharedActivityState } from "./shared-state.js";
@@ -0,0 +1,11 @@
1
+ import type { LudicordDiscordStatus } from "../discord/runtime.js";
2
+ export interface LudicordActivityLifecycle {
3
+ readonly visibility: DocumentVisibilityState | "unknown";
4
+ readonly visible: boolean;
5
+ readonly focused: boolean;
6
+ readonly online: boolean;
7
+ readonly discordStatus: LudicordDiscordStatus;
8
+ readonly discordReady: boolean;
9
+ readonly websocketReady: boolean;
10
+ }
11
+ export declare function useActivityLifecycle(): LudicordActivityLifecycle;
@@ -0,0 +1,41 @@
1
+ import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
2
+ import { useDiscord } from "../discord/runtime.js";
3
+ import { isWebSocketRuntimeReady, subscribeWebSocketRuntime } from "../ws/client.js";
4
+ function browserLifecycle() {
5
+ if (typeof document === "undefined" || typeof navigator === "undefined") {
6
+ return { visibility: "unknown", focused: false, online: true };
7
+ }
8
+ return {
9
+ visibility: document.visibilityState,
10
+ focused: typeof document.hasFocus === "function" ? document.hasFocus() : true,
11
+ online: navigator.onLine,
12
+ };
13
+ }
14
+ export function useActivityLifecycle() {
15
+ const discord = useDiscord();
16
+ const websocketReady = useSyncExternalStore(subscribeWebSocketRuntime, isWebSocketRuntimeReady, () => false);
17
+ const [browser, setBrowser] = useState(browserLifecycle);
18
+ useEffect(() => {
19
+ const update = () => setBrowser(browserLifecycle());
20
+ document.addEventListener("visibilitychange", update);
21
+ window.addEventListener("focus", update);
22
+ window.addEventListener("blur", update);
23
+ window.addEventListener("online", update);
24
+ window.addEventListener("offline", update);
25
+ update();
26
+ return () => {
27
+ document.removeEventListener("visibilitychange", update);
28
+ window.removeEventListener("focus", update);
29
+ window.removeEventListener("blur", update);
30
+ window.removeEventListener("online", update);
31
+ window.removeEventListener("offline", update);
32
+ };
33
+ }, []);
34
+ return useMemo(() => ({
35
+ ...browser,
36
+ visible: browser.visibility === "visible",
37
+ discordStatus: discord.status,
38
+ discordReady: discord.status === "ready",
39
+ websocketReady,
40
+ }), [browser, discord.status, websocketReady]);
41
+ }
@@ -0,0 +1,10 @@
1
+ import type { LudicordParticipant, LudicordVoiceState } from "../discord/events.js";
2
+ export interface LudicordActivityPresence {
3
+ readonly participants: readonly LudicordParticipant[];
4
+ readonly participantCount: number;
5
+ readonly currentParticipant: LudicordParticipant | null;
6
+ readonly voiceStates: readonly LudicordVoiceState[];
7
+ readonly speakingUserIds: readonly string[];
8
+ readonly alone: boolean;
9
+ }
10
+ export declare function useActivityPresence(): LudicordActivityPresence;
@@ -0,0 +1,15 @@
1
+ import { useMemo } from "react";
2
+ import { useDiscordData } from "../discord/events.js";
3
+ export function useActivityPresence() {
4
+ const data = useDiscordData();
5
+ return useMemo(() => ({
6
+ participants: data.participants,
7
+ participantCount: data.participants.length,
8
+ currentParticipant: data.user === null
9
+ ? null
10
+ : data.participants.find(({ id }) => id === data.user?.id) ?? null,
11
+ voiceStates: data.voiceStates,
12
+ speakingUserIds: data.speakingUserIds,
13
+ alone: data.participants.length <= 1,
14
+ }), [data.participants, data.speakingUserIds, data.user, data.voiceStates]);
15
+ }
@@ -0,0 +1,21 @@
1
+ export type LudicordActivityQueryStatus = "idle" | "loading" | "refreshing" | "ready" | "error";
2
+ export type LudicordActivityQueryKey = string | readonly unknown[];
3
+ export interface LudicordActivityQueryOptions<T> {
4
+ readonly enabled?: boolean;
5
+ readonly initialData?: T;
6
+ readonly staleTime?: number;
7
+ readonly retries?: number;
8
+ readonly timeout?: number;
9
+ }
10
+ export interface LudicordActivityQuery<T> {
11
+ readonly data: T | undefined;
12
+ readonly status: LudicordActivityQueryStatus;
13
+ readonly error: Error | null;
14
+ readonly updatedAt: number | null;
15
+ readonly refetch: () => Promise<T>;
16
+ readonly mutate: (value: T | ((current: T | undefined) => T)) => void;
17
+ }
18
+ export declare function useActivityQuery<T>(key: LudicordActivityQueryKey, query: (context: {
19
+ readonly signal: AbortSignal;
20
+ }) => Promise<T>, options?: LudicordActivityQueryOptions<T>): LudicordActivityQuery<T>;
21
+ export declare function clearActivityQueryCache(key?: LudicordActivityQueryKey): void;
@@ -0,0 +1,148 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
2
+ const queryCache = new Map();
3
+ const MAX_QUERY_CACHE_ENTRIES = 500;
4
+ function serializeKey(key) {
5
+ if (typeof key === "string") {
6
+ if (key.trim() === "")
7
+ throw new Error("LUDICORD2203: useActivityQuery() requires a non-empty key.");
8
+ return key;
9
+ }
10
+ try {
11
+ return JSON.stringify(key);
12
+ }
13
+ catch {
14
+ throw new Error("LUDICORD2203: useActivityQuery() keys must be JSON-serializable.");
15
+ }
16
+ }
17
+ function entryFor(key, initialData) {
18
+ const existing = queryCache.get(key);
19
+ if (existing !== undefined)
20
+ return existing;
21
+ if (queryCache.size >= MAX_QUERY_CACHE_ENTRIES) {
22
+ const removable = [...queryCache].find(([, entry]) => entry.listeners.size === 0 && entry.promise === undefined);
23
+ if (removable !== undefined)
24
+ queryCache.delete(removable[0]);
25
+ }
26
+ const entry = {
27
+ snapshot: {
28
+ data: initialData,
29
+ status: initialData === undefined ? "idle" : "ready",
30
+ error: null,
31
+ updatedAt: initialData === undefined ? null : Date.now(),
32
+ },
33
+ listeners: new Set(),
34
+ };
35
+ queryCache.set(key, entry);
36
+ return entry;
37
+ }
38
+ function publish(entry, snapshot) {
39
+ entry.snapshot = snapshot;
40
+ for (const listener of entry.listeners)
41
+ listener();
42
+ }
43
+ function wait(delay, signal) {
44
+ return new Promise((resolve, reject) => {
45
+ const onAbort = () => {
46
+ clearTimeout(timer);
47
+ reject(signal.reason);
48
+ };
49
+ const timer = setTimeout(() => {
50
+ signal.removeEventListener("abort", onAbort);
51
+ resolve();
52
+ }, delay);
53
+ signal.addEventListener("abort", onAbort, { once: true });
54
+ });
55
+ }
56
+ async function execute(entry, query, options, force) {
57
+ if (!force && entry.promise !== undefined)
58
+ return entry.promise;
59
+ if (force)
60
+ entry.controller?.abort(new Error("Ludicord query replaced by refetch()."));
61
+ const controller = new AbortController();
62
+ entry.controller = controller;
63
+ const retries = options.retries ?? 1;
64
+ const timeout = options.timeout ?? 30_000;
65
+ if (!Number.isSafeInteger(retries) || retries < 0 || retries > 10)
66
+ throw new Error("LUDICORD2204: Query retries must be between 0 and 10.");
67
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 900_000)
68
+ throw new Error("LUDICORD2204: Query timeout must be between 1 and 900000 milliseconds.");
69
+ publish(entry, {
70
+ ...entry.snapshot,
71
+ status: entry.snapshot.data === undefined ? "loading" : "refreshing",
72
+ error: null,
73
+ });
74
+ let timer;
75
+ const promise = (async () => {
76
+ timer = setTimeout(() => controller.abort(new Error("Ludicord Activity query timed out.")), timeout);
77
+ for (let attempt = 0;; attempt += 1) {
78
+ try {
79
+ const data = await query({ signal: controller.signal });
80
+ if (entry.controller !== controller)
81
+ return data;
82
+ const snapshot = { data, status: "ready", error: null, updatedAt: Date.now() };
83
+ publish(entry, snapshot);
84
+ return data;
85
+ }
86
+ catch (cause) {
87
+ if (controller.signal.aborted || attempt >= retries) {
88
+ const error = cause instanceof Error ? cause : new Error(String(cause));
89
+ if (entry.controller === controller)
90
+ publish(entry, { ...entry.snapshot, status: "error", error });
91
+ throw error;
92
+ }
93
+ await wait(Math.min(250 * 2 ** attempt, 2_000), controller.signal);
94
+ }
95
+ }
96
+ })().finally(() => {
97
+ clearTimeout(timer);
98
+ if (entry.controller === controller)
99
+ delete entry.controller;
100
+ if (entry.promise === promise)
101
+ delete entry.promise;
102
+ });
103
+ entry.promise = promise;
104
+ return promise;
105
+ }
106
+ export function useActivityQuery(key, query, options = {}) {
107
+ const serializedKey = serializeKey(key);
108
+ const entry = useMemo(() => entryFor(serializedKey, options.initialData), [serializedKey]);
109
+ const queryRef = useRef(query);
110
+ queryRef.current = query;
111
+ const optionsRef = useRef(options);
112
+ optionsRef.current = options;
113
+ const snapshot = useSyncExternalStore((listener) => { entry.listeners.add(listener); return () => entry.listeners.delete(listener); }, () => entry.snapshot, () => entry.snapshot);
114
+ const enabled = options.enabled ?? true;
115
+ const staleTime = options.staleTime ?? 0;
116
+ useEffect(() => {
117
+ if (!enabled || entry.promise !== undefined)
118
+ return;
119
+ const fresh = entry.snapshot.updatedAt !== null && Date.now() - entry.snapshot.updatedAt <= staleTime;
120
+ if (!fresh)
121
+ void execute(entry, queryRef.current, optionsRef.current, false).catch(() => undefined);
122
+ }, [enabled, entry, staleTime]);
123
+ const refetch = useCallback(() => execute(entry, queryRef.current, optionsRef.current, true), [entry]);
124
+ const mutate = useCallback((next) => {
125
+ const current = entry.snapshot.data;
126
+ const data = typeof next === "function" ? next(current) : next;
127
+ publish(entry, { data, status: "ready", error: null, updatedAt: Date.now() });
128
+ }, [entry]);
129
+ return {
130
+ data: snapshot.data,
131
+ status: snapshot.status,
132
+ error: snapshot.error,
133
+ updatedAt: snapshot.updatedAt,
134
+ refetch,
135
+ mutate,
136
+ };
137
+ }
138
+ export function clearActivityQueryCache(key) {
139
+ if (key !== undefined) {
140
+ const serialized = serializeKey(key);
141
+ queryCache.get(serialized)?.controller?.abort(new Error("Ludicord query cache cleared."));
142
+ queryCache.delete(serialized);
143
+ return;
144
+ }
145
+ for (const entry of queryCache.values())
146
+ entry.controller?.abort(new Error("Ludicord query cache cleared."));
147
+ queryCache.clear();
148
+ }
@@ -0,0 +1,10 @@
1
+ import type { Dispatch, SetStateAction } from "react";
2
+ import type { LudicordWSConnectionOptions, LudicordWSRoute, LudicordWSStatus } from "../ws/client.js";
3
+ export interface LudicordSharedActivityState<T> {
4
+ readonly value: T;
5
+ readonly revision: number;
6
+ readonly synchronized: boolean;
7
+ readonly status: LudicordWSStatus;
8
+ readonly setValue: Dispatch<SetStateAction<T>>;
9
+ }
10
+ export declare function useSharedActivityState<T>(route: LudicordWSRoute, key: string, initialValue: T | (() => T), options?: LudicordWSConnectionOptions): LudicordSharedActivityState<T>;
@@ -0,0 +1,100 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { useWS } from "../ws/client.js";
3
+ export function useSharedActivityState(route, key, initialValue, options = {}) {
4
+ if (key.trim() === "" || key.length > 128)
5
+ throw new Error("LUDICORD2205: Shared Activity state keys must contain 1-128 characters.");
6
+ const connection = useWS(route, options);
7
+ const resolveInitial = () => typeof initialValue === "function" ? initialValue() : initialValue;
8
+ const [value, setState] = useState(resolveInitial);
9
+ const [revision, setRevision] = useState(0);
10
+ const [synchronized, setSynchronized] = useState(false);
11
+ const valueRef = useRef(value);
12
+ valueRef.current = value;
13
+ const revisionRef = useRef(revision);
14
+ revisionRef.current = revision;
15
+ const pendingRef = useRef(null);
16
+ const inFlightRef = useRef(null);
17
+ const snapshotReadyRef = useRef(false);
18
+ const flush = useCallback(() => {
19
+ if (connection.status !== "open" ||
20
+ !snapshotReadyRef.current ||
21
+ inFlightRef.current !== null ||
22
+ pendingRef.current === null)
23
+ return;
24
+ const pending = pendingRef.current;
25
+ pendingRef.current = null;
26
+ const inFlight = { value: pending.value, baseRevision: revisionRef.current };
27
+ inFlightRef.current = inFlight;
28
+ try {
29
+ connection.emit("ludicord:shared:set", {
30
+ key,
31
+ value: inFlight.value,
32
+ revision: inFlight.baseRevision,
33
+ });
34
+ }
35
+ catch {
36
+ inFlightRef.current = null;
37
+ pendingRef.current = pending;
38
+ }
39
+ }, [connection, key]);
40
+ useEffect(() => {
41
+ setState(resolveInitial());
42
+ setRevision(0);
43
+ setSynchronized(false);
44
+ pendingRef.current = null;
45
+ inFlightRef.current = null;
46
+ snapshotReadyRef.current = false;
47
+ }, [key, route]);
48
+ useEffect(() => connection.on("ludicord:shared:state", (payload) => {
49
+ if (typeof payload !== "object" || payload === null)
50
+ return;
51
+ const source = payload;
52
+ if (source.key !== key || typeof source.revision !== "number")
53
+ return;
54
+ snapshotReadyRef.current = true;
55
+ const inFlight = inFlightRef.current;
56
+ if (inFlight !== null && source.revision <= inFlight.baseRevision)
57
+ return;
58
+ inFlightRef.current = null;
59
+ revisionRef.current = source.revision;
60
+ setRevision(source.revision);
61
+ const pending = pendingRef.current;
62
+ if (pending !== null) {
63
+ valueRef.current = pending.value;
64
+ setState(pending.value);
65
+ setSynchronized(false);
66
+ flush();
67
+ return;
68
+ }
69
+ valueRef.current = source.value;
70
+ setState(source.value);
71
+ setSynchronized(true);
72
+ }), [connection, flush, key]);
73
+ useEffect(() => {
74
+ if (connection.status === "open") {
75
+ snapshotReadyRef.current = false;
76
+ setSynchronized(false);
77
+ try {
78
+ connection.emit("ludicord:shared:subscribe", { key });
79
+ }
80
+ catch { /* A close racing with this effect will reconnect and subscribe again. */ }
81
+ return;
82
+ }
83
+ snapshotReadyRef.current = false;
84
+ if (inFlightRef.current !== null) {
85
+ pendingRef.current = { value: valueRef.current };
86
+ inFlightRef.current = null;
87
+ }
88
+ }, [connection, connection.status, key]);
89
+ const setValue = useCallback((next) => {
90
+ const resolved = typeof next === "function"
91
+ ? next(valueRef.current)
92
+ : next;
93
+ valueRef.current = resolved;
94
+ setState(resolved);
95
+ setSynchronized(false);
96
+ pendingRef.current = { value: resolved };
97
+ flush();
98
+ }, [flush]);
99
+ return useMemo(() => ({ value, revision, synchronized, status: connection.status, setValue }), [connection.status, revision, setValue, synchronized, value]);
100
+ }
@@ -0,0 +1,16 @@
1
+ import type { Dispatch, SetStateAction } from "react";
2
+ export type LudicordActivityStorageScope = "activity" | "user" | "guild" | "channel";
3
+ export interface LudicordActivityStorageOptions<T> {
4
+ readonly scope?: LudicordActivityStorageScope;
5
+ readonly storage?: Storage;
6
+ readonly serialize?: (value: T) => string;
7
+ readonly deserialize?: (value: string) => T;
8
+ }
9
+ export interface LudicordActivityStorage<T> {
10
+ readonly value: T;
11
+ readonly key: string | null;
12
+ readonly available: boolean;
13
+ readonly setValue: Dispatch<SetStateAction<T>>;
14
+ readonly remove: () => void;
15
+ }
16
+ export declare function useActivityStorage<T>(key: string, initial: T | (() => T), options?: LudicordActivityStorageOptions<T>): LudicordActivityStorage<T>;
@@ -0,0 +1,88 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { useDiscordChannel, useDiscordGuild, useDiscordUser } from "../discord/events.js";
3
+ function initialValue(value) {
4
+ return typeof value === "function" ? value() : value;
5
+ }
6
+ function browserStorage() {
7
+ if (typeof window === "undefined")
8
+ return undefined;
9
+ try {
10
+ return window.localStorage;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ function deserializeJson(value) {
17
+ return JSON.parse(value);
18
+ }
19
+ export function useActivityStorage(key, initial, options = {}) {
20
+ if (key.trim() === "")
21
+ throw new Error("LUDICORD2201: useActivityStorage() requires a non-empty key.");
22
+ const user = useDiscordUser();
23
+ const guild = useDiscordGuild();
24
+ const channel = useDiscordChannel();
25
+ const scope = options.scope ?? "activity";
26
+ const identity = scope === "activity" ? "root" :
27
+ scope === "user" ? user?.id : scope === "guild" ? guild?.id : channel?.id;
28
+ const storageKey = identity === undefined || identity === null
29
+ ? null
30
+ : `ludicord:${scope}:${identity}:${key}`;
31
+ const serialize = options.serialize ?? JSON.stringify;
32
+ const deserialize = options.deserialize ?? (deserializeJson);
33
+ const storage = options.storage ?? browserStorage();
34
+ const initialRef = useRef(initial);
35
+ initialRef.current = initial;
36
+ const fallback = useMemo(() => initialValue(initialRef.current), [storageKey]);
37
+ const read = useCallback(() => {
38
+ if (storageKey === null || storage === undefined)
39
+ return fallback;
40
+ try {
41
+ const value = storage.getItem(storageKey);
42
+ return value === null ? fallback : deserialize(value);
43
+ }
44
+ catch {
45
+ return fallback;
46
+ }
47
+ }, [deserialize, fallback, storage, storageKey]);
48
+ const [value, setState] = useState(read);
49
+ useEffect(() => {
50
+ setState(read());
51
+ if (storageKey === null || storage === undefined || typeof window === "undefined")
52
+ return;
53
+ const update = (event) => {
54
+ if (event.storageArea === storage && event.key === storageKey)
55
+ setState(read());
56
+ };
57
+ window.addEventListener("storage", update);
58
+ return () => window.removeEventListener("storage", update);
59
+ }, [read, storage, storageKey]);
60
+ const setValue = useCallback((next) => {
61
+ setState((current) => {
62
+ const resolved = typeof next === "function"
63
+ ? next(current)
64
+ : next;
65
+ if (storageKey !== null && storage !== undefined) {
66
+ try {
67
+ const encoded = serialize(resolved);
68
+ if (typeof encoded === "string")
69
+ storage.setItem(storageKey, encoded);
70
+ else
71
+ storage.removeItem(storageKey);
72
+ }
73
+ catch { /* State remains usable when storage is blocked, full, or not serializable. */ }
74
+ }
75
+ return resolved;
76
+ });
77
+ }, [serialize, storage, storageKey]);
78
+ const remove = useCallback(() => {
79
+ if (storageKey !== null && storage !== undefined) {
80
+ try {
81
+ storage.removeItem(storageKey);
82
+ }
83
+ catch { /* Ignore unavailable storage. */ }
84
+ }
85
+ setState(fallback);
86
+ }, [fallback, storage, storageKey]);
87
+ return { value, key: storageKey, available: storageKey !== null && storage !== undefined, setValue, remove };
88
+ }
@@ -22,10 +22,13 @@ export interface ApiRuntimeOptions {
22
22
  readonly discordPublicKey?: string;
23
23
  readonly now?: () => number;
24
24
  readonly bodyLimit?: string | number;
25
+ readonly requestTimeout?: number;
25
26
  readonly allowDevelopmentSessions?: boolean;
26
- readonly onError?: (error: unknown, file: string) => void;
27
+ readonly onError?: (error: unknown, file: string, request: {
28
+ readonly method: string;
29
+ readonly url: string;
30
+ }) => void | Promise<void>;
27
31
  }
28
32
  export declare function parseBodyLimit(limit?: string | number): number;
29
33
  export declare function createApiMiddleware(options: ApiRuntimeOptions): (request: ExpressRequest, response: ExpressResponse, next: NextFunction) => Promise<void>;
30
34
  export {};
31
- //# sourceMappingURL=runtime.d.ts.map