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.
- package/README.md +21 -5
- package/dist/activity/game-loop.d.ts +16 -0
- package/dist/activity/game-loop.js +33 -0
- package/dist/activity/index.d.ts +12 -0
- package/dist/activity/index.js +6 -0
- package/dist/activity/lifecycle.d.ts +11 -0
- package/dist/activity/lifecycle.js +41 -0
- package/dist/activity/presence.d.ts +10 -0
- package/dist/activity/presence.js +15 -0
- package/dist/activity/query.d.ts +21 -0
- package/dist/activity/query.js +148 -0
- package/dist/activity/shared-state.d.ts +10 -0
- package/dist/activity/shared-state.js +100 -0
- package/dist/activity/storage.d.ts +16 -0
- package/dist/activity/storage.js +88 -0
- package/dist/api/runtime.d.ts +5 -2
- package/dist/api/runtime.js +53 -10
- package/dist/auth/client.d.ts +0 -1
- package/dist/auth/client.js +3 -5
- package/dist/auth/index.d.ts +0 -1
- package/dist/auth/index.js +0 -1
- package/dist/auth/server.d.ts +2 -1
- package/dist/auth/server.js +161 -16
- package/dist/auth/types.d.ts +5 -1
- package/dist/auth/types.js +0 -1
- package/dist/cli/index.d.ts +0 -1
- package/dist/cli/index.js +116 -19
- package/dist/cli/project-commands.d.ts +1 -5
- package/dist/cli/project-commands.js +14 -162
- package/dist/compiler/build.d.ts +10 -1
- package/dist/compiler/build.js +124 -16
- package/dist/compiler/bundle-report.d.ts +17 -0
- package/dist/compiler/bundle-report.js +60 -0
- package/dist/compiler/client-entry.d.ts +0 -1
- package/dist/compiler/client-entry.js +28 -4
- package/dist/compiler/client-tooling.d.ts +0 -1
- package/dist/compiler/client-tooling.js +8 -2
- package/dist/compiler/index.d.ts +3 -1
- package/dist/compiler/index.js +2 -1
- package/dist/compiler/scanner.d.ts +0 -1
- package/dist/compiler/scanner.js +59 -4
- package/dist/compiler/server-bundle.d.ts +1 -2
- package/dist/compiler/server-bundle.js +11 -2
- package/dist/compiler/type-generation.d.ts +0 -1
- package/dist/compiler/type-generation.js +2 -1
- package/dist/compiler/write-manifests.d.ts +0 -1
- package/dist/compiler/write-manifests.js +0 -1
- package/dist/config/defaults.d.ts +0 -1
- package/dist/config/defaults.js +14 -2
- package/dist/config/environment.d.ts +0 -1
- package/dist/config/environment.js +0 -1
- package/dist/config/index.d.ts +0 -1
- package/dist/config/index.js +0 -1
- package/dist/config/loader.d.ts +0 -1
- package/dist/config/loader.js +0 -1
- package/dist/config/project-root.d.ts +0 -1
- package/dist/config/project-root.js +0 -1
- package/dist/config/types.d.ts +25 -1
- package/dist/config/types.js +0 -1
- package/dist/discord/assets.d.ts +5 -0
- package/dist/discord/assets.js +29 -0
- package/dist/discord/data.d.ts +38 -2
- package/dist/discord/data.js +178 -11
- package/dist/discord/events.d.ts +28 -2
- package/dist/discord/events.js +109 -39
- package/dist/discord/index.d.ts +6 -5
- package/dist/discord/index.js +3 -3
- package/dist/discord/payload.d.ts +6 -0
- package/dist/discord/payload.js +5 -0
- package/dist/discord/runtime.d.ts +0 -1
- package/dist/discord/runtime.js +0 -1
- package/dist/discord/safe-area.d.ts +0 -1
- package/dist/discord/safe-area.js +0 -1
- package/dist/discord/testing.d.ts +0 -1
- package/dist/discord/testing.js +0 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +3 -1
- package/dist/lint/index.d.ts +6 -0
- package/dist/lint/index.js +71 -0
- package/dist/manifests/types.d.ts +11 -1
- package/dist/manifests/types.js +0 -1
- package/dist/metadata/index.d.ts +13 -0
- package/dist/metadata/index.js +4 -0
- package/dist/navigation/index.d.ts +3 -1
- package/dist/navigation/index.js +1 -1
- package/dist/navigation/link.d.ts +8 -0
- package/dist/navigation/link.js +38 -0
- package/dist/router/match.d.ts +0 -1
- package/dist/router/match.js +0 -1
- package/dist/runtime/client/dev-panel.d.ts +0 -1
- package/dist/runtime/client/dev-panel.js +722 -38
- package/dist/runtime/client/embed-router.d.ts +8 -1
- package/dist/runtime/client/embed-router.js +116 -62
- package/dist/runtime/client/files.d.ts +5 -1
- package/dist/runtime/client/files.js +0 -1
- package/dist/runtime/client/minimize-card.d.ts +0 -1
- package/dist/runtime/client/minimize-card.js +0 -1
- package/dist/runtime/client/minimize.d.ts +0 -1
- package/dist/runtime/client/minimize.js +0 -1
- package/dist/runtime/client/root.d.ts +5 -3
- package/dist/runtime/client/root.js +28 -3
- package/dist/runtime/index.d.ts +1 -2
- package/dist/runtime/index.js +0 -1
- package/dist/runtime/server/dev-server.d.ts +0 -1
- package/dist/runtime/server/dev-server.js +191 -30
- package/dist/runtime/server/diagnostics.d.ts +1 -1
- package/dist/runtime/server/diagnostics.js +5 -4
- package/dist/runtime/server/index.d.ts +0 -1
- package/dist/runtime/server/index.js +0 -1
- package/dist/runtime/server/production-server.d.ts +2 -1
- package/dist/runtime/server/production-server.js +145 -25
- package/dist/security/discord.d.ts +0 -1
- package/dist/security/discord.js +0 -1
- package/dist/security/index.d.ts +0 -1
- package/dist/security/index.js +0 -1
- package/dist/security/secret-scan.d.ts +0 -1
- package/dist/security/secret-scan.js +0 -1
- package/dist/server/discord-rest.d.ts +42 -7
- package/dist/server/discord-rest.js +135 -18
- package/dist/server/index.d.ts +7 -2
- package/dist/server/index.js +3 -1
- package/dist/server/instrumentation.d.ts +16 -0
- package/dist/server/instrumentation.js +3 -0
- package/dist/server/proxy.d.ts +21 -0
- package/dist/server/proxy.js +76 -0
- package/dist/server/session.d.ts +0 -1
- package/dist/server/session.js +0 -1
- package/dist/server/types.d.ts +0 -1
- package/dist/server/types.js +0 -1
- package/dist/sessions/cookies.d.ts +0 -1
- package/dist/sessions/cookies.js +0 -1
- package/dist/sessions/crypto.d.ts +0 -1
- package/dist/sessions/crypto.js +0 -1
- package/dist/sessions/data-store.d.ts +18 -0
- package/dist/sessions/data-store.js +45 -0
- package/dist/shared/errors.d.ts +0 -1
- package/dist/shared/errors.js +0 -1
- package/dist/testing/index.d.ts +0 -1
- package/dist/testing/index.js +2 -2
- package/dist/version.d.ts +1 -2
- package/dist/version.js +1 -2
- package/dist/ws/client.d.ts +0 -1
- package/dist/ws/client.js +0 -1
- package/dist/ws/index.d.ts +3 -2
- package/dist/ws/index.js +1 -1
- package/dist/ws/server.d.ts +5 -3
- package/dist/ws/server.js +65 -19
- package/dist/ws/shared-state.d.ts +13 -0
- package/dist/ws/shared-state.js +137 -0
- package/package.json +16 -3
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export function defineProxy(proxy) {
|
|
2
|
+
return proxy;
|
|
3
|
+
}
|
|
4
|
+
function toWebRequest(request, signal) {
|
|
5
|
+
const origin = `${request.protocol}://${request.get("host") ?? "localhost"}`;
|
|
6
|
+
const headers = new Headers();
|
|
7
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
8
|
+
if (value !== undefined)
|
|
9
|
+
headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
10
|
+
}
|
|
11
|
+
return new Request(new URL(request.originalUrl, origin), {
|
|
12
|
+
method: request.method,
|
|
13
|
+
headers,
|
|
14
|
+
signal,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
async function sendProxyResponse(request, response, result) {
|
|
18
|
+
response.status(result.status);
|
|
19
|
+
for (const [name, value] of result.headers) {
|
|
20
|
+
if (name.toLowerCase() !== "set-cookie")
|
|
21
|
+
response.setHeader(name, value);
|
|
22
|
+
}
|
|
23
|
+
for (const cookie of result.headers.getSetCookie())
|
|
24
|
+
response.appendHeader("set-cookie", cookie);
|
|
25
|
+
if (request.method === "HEAD" || result.body === null) {
|
|
26
|
+
response.end();
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
response.send(Buffer.from(await result.arrayBuffer()));
|
|
30
|
+
}
|
|
31
|
+
export function createProxyMiddleware(options) {
|
|
32
|
+
return async (request, response, next) => {
|
|
33
|
+
if (request.path === "/_ludicord" || request.path.startsWith("/_ludicord/")) {
|
|
34
|
+
next();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
const abort = () => controller.abort(new Error("The client disconnected."));
|
|
39
|
+
request.once("aborted", abort);
|
|
40
|
+
try {
|
|
41
|
+
const source = typeof options.source === "function" ? options.source() : options.source;
|
|
42
|
+
if (source === undefined) {
|
|
43
|
+
next();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const module = await options.loadModule(source);
|
|
47
|
+
const proxy = module.default ?? module.proxy;
|
|
48
|
+
if (typeof proxy !== "function") {
|
|
49
|
+
throw new Error("LUDICORD3005: app/proxy.ts must export a default proxy function.");
|
|
50
|
+
}
|
|
51
|
+
const result = await proxy(toWebRequest(request, controller.signal), {
|
|
52
|
+
environment: options.environment,
|
|
53
|
+
projectRoot: options.projectRoot,
|
|
54
|
+
});
|
|
55
|
+
if (result === undefined) {
|
|
56
|
+
next();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (!(result instanceof Response)) {
|
|
60
|
+
throw new TypeError("LUDICORD3005: app/proxy.ts must return a Response or undefined.");
|
|
61
|
+
}
|
|
62
|
+
await sendProxyResponse(request, response, result);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const source = typeof options.source === "function" ? options.source() : options.source;
|
|
66
|
+
await options.onError?.(error, source ?? "app/proxy.ts", {
|
|
67
|
+
method: request.method,
|
|
68
|
+
url: request.originalUrl,
|
|
69
|
+
});
|
|
70
|
+
next(error);
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
request.off("aborted", abort);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
package/dist/server/session.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
import type { LudicordSession } from "../auth/types.js";
|
|
2
2
|
export declare function getLudicordSession(request: Request, secret?: string | undefined): LudicordSession | null;
|
|
3
3
|
export declare function requireLudicordSession(request: Request, secret?: string): LudicordSession;
|
|
4
|
-
//# sourceMappingURL=session.d.ts.map
|
package/dist/server/session.js
CHANGED
package/dist/server/types.d.ts
CHANGED
package/dist/server/types.js
CHANGED
|
@@ -13,4 +13,3 @@ export declare function parseCookies(cookieHeader: string | undefined): Readonly
|
|
|
13
13
|
export declare function parseSessionCookie(cookieHeader: string | undefined, secret: string, options?: {
|
|
14
14
|
readonly allowDevelopment?: boolean;
|
|
15
15
|
}): LudicordSession | null;
|
|
16
|
-
//# sourceMappingURL=cookies.d.ts.map
|
package/dist/sessions/cookies.js
CHANGED
|
@@ -2,4 +2,3 @@ import type { LudicordSession } from "../auth/types.js";
|
|
|
2
2
|
export declare function sealLudicordSession(session: LudicordSession, secret: string): string;
|
|
3
3
|
export declare function unsealLudicordSession(value: string, secret: string): LudicordSession | null;
|
|
4
4
|
export declare function safeEqual(left: string, right: string): boolean;
|
|
5
|
-
//# sourceMappingURL=crypto.d.ts.map
|
package/dist/sessions/crypto.js
CHANGED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DiscordRawPayload } from "../discord/payload.js";
|
|
2
|
+
export interface LudicordExtendedSessionData {
|
|
3
|
+
readonly userRaw?: DiscordRawPayload;
|
|
4
|
+
readonly guildRaw?: DiscordRawPayload;
|
|
5
|
+
}
|
|
6
|
+
export interface LudicordSessionDataStore {
|
|
7
|
+
get(id: string): LudicordExtendedSessionData | null | Promise<LudicordExtendedSessionData | null>;
|
|
8
|
+
set(id: string, data: LudicordExtendedSessionData, expiresAt: number): void | Promise<void>;
|
|
9
|
+
delete(id: string): void | Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Zero-configuration session-data storage for one Ludicord process. Production
|
|
13
|
+
* clusters can provide a shared adapter through createLudicordProductionServer.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createMemorySessionDataStore(options?: {
|
|
16
|
+
readonly maxEntries?: number;
|
|
17
|
+
readonly now?: () => number;
|
|
18
|
+
}): LudicordSessionDataStore;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-configuration session-data storage for one Ludicord process. Production
|
|
3
|
+
* clusters can provide a shared adapter through createLudicordProductionServer.
|
|
4
|
+
*/
|
|
5
|
+
export function createMemorySessionDataStore(options = {}) {
|
|
6
|
+
const maxEntries = options.maxEntries ?? 2_000;
|
|
7
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1 || maxEntries > 100_000) {
|
|
8
|
+
throw new Error("LUDICORD6013: Session data maxEntries must be an integer between 1 and 100000.");
|
|
9
|
+
}
|
|
10
|
+
const now = options.now ?? Date.now;
|
|
11
|
+
const entries = new Map();
|
|
12
|
+
const prune = () => {
|
|
13
|
+
const current = now();
|
|
14
|
+
for (const [id, entry] of entries) {
|
|
15
|
+
if (entry.expiresAt <= current)
|
|
16
|
+
entries.delete(id);
|
|
17
|
+
}
|
|
18
|
+
while (entries.size >= maxEntries) {
|
|
19
|
+
const oldest = entries.keys().next().value;
|
|
20
|
+
if (oldest === undefined)
|
|
21
|
+
break;
|
|
22
|
+
entries.delete(oldest);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
get(id) {
|
|
27
|
+
const entry = entries.get(id);
|
|
28
|
+
if (entry === undefined)
|
|
29
|
+
return null;
|
|
30
|
+
if (entry.expiresAt <= now()) {
|
|
31
|
+
entries.delete(id);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return entry.data;
|
|
35
|
+
},
|
|
36
|
+
set(id, data, expiresAt) {
|
|
37
|
+
entries.delete(id);
|
|
38
|
+
prune();
|
|
39
|
+
entries.set(id, { data, expiresAt });
|
|
40
|
+
},
|
|
41
|
+
delete(id) {
|
|
42
|
+
entries.delete(id);
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
package/dist/shared/errors.d.ts
CHANGED
package/dist/shared/errors.js
CHANGED
package/dist/testing/index.d.ts
CHANGED
package/dist/testing/index.js
CHANGED
|
@@ -6,7 +6,8 @@ import { createRoot } from "react-dom/client";
|
|
|
6
6
|
import { setMockSessionForTesting } from "../auth/client.js";
|
|
7
7
|
import { LudicordRoot } from "../runtime/client/root.js";
|
|
8
8
|
export function createMockSession(overrides = {}) {
|
|
9
|
-
return { authenticated: true, user: { id: "mock-user", username: "mock_user", displayName: "Mock User", avatar: null
|
|
9
|
+
return { authenticated: true, user: { id: "mock-user", username: "mock_user", displayName: "Mock User", avatar: null,
|
|
10
|
+
raw: { id: "mock-user", username: "mock_user", global_name: "Mock User", avatar: null } },
|
|
10
11
|
applicationId: "mock-application", instanceId: "mock-instance", guildId: "mock-guild", channelId: "mock-channel",
|
|
11
12
|
scopes: ["identify", "guilds"], issuedAt: Date.now(), expiresAt: Date.now() + 3_600_000, ...overrides };
|
|
12
13
|
}
|
|
@@ -25,4 +26,3 @@ export async function renderLudicordActivity(children, options = {}) {
|
|
|
25
26
|
container.remove(); if (options.session !== undefined)
|
|
26
27
|
setMockSessionForTesting(null); } };
|
|
27
28
|
}
|
|
28
|
-
//# sourceMappingURL=index.js.map
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
export declare const LUDICORD_VERSION: "
|
|
2
|
-
//# sourceMappingURL=version.d.ts.map
|
|
1
|
+
export declare const LUDICORD_VERSION: "3.0.0";
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
export const LUDICORD_VERSION = "
|
|
2
|
-
//# sourceMappingURL=version.js.map
|
|
1
|
+
export const LUDICORD_VERSION = "3.0.0";
|
package/dist/ws/client.d.ts
CHANGED
package/dist/ws/client.js
CHANGED
package/dist/ws/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { useWS } from "./client.js";
|
|
2
2
|
export { defineWS } from "./server.js";
|
|
3
|
-
export
|
|
3
|
+
export { defineSharedActivityState } from "./shared-state.js";
|
|
4
|
+
export type { LudicordWSConnection, LudicordWSConnectionOptions, LudicordWSStatus, } from "./client.js";
|
|
4
5
|
export type { LudicordWebSocketClient, LudicordWebSocketRoute, LudicordWSEventEnvelope, } from "./server.js";
|
|
5
|
-
|
|
6
|
+
export type { LudicordSharedStateContext, LudicordSharedStateOptions } from "./shared-state.js";
|
package/dist/ws/index.js
CHANGED
package/dist/ws/server.d.ts
CHANGED
|
@@ -55,18 +55,20 @@ export interface WebSocketRuntimeOptions {
|
|
|
55
55
|
readonly maxPayload?: number;
|
|
56
56
|
readonly compression?: boolean;
|
|
57
57
|
readonly backpressureLimit?: number;
|
|
58
|
+
readonly maxMessagesPerSecond?: number;
|
|
58
59
|
readonly allowDevelopmentSessions?: boolean;
|
|
59
60
|
readonly enabled?: boolean;
|
|
60
|
-
readonly onError?: (error: unknown, file?: string) => void
|
|
61
|
+
readonly onError?: (error: unknown, file?: string) => void | Promise<void>;
|
|
61
62
|
}
|
|
62
63
|
export interface LudicordWebSocketRuntime {
|
|
63
64
|
readonly server: WebSocketServer;
|
|
64
65
|
readonly clientCount: () => number;
|
|
65
66
|
heartbeatNow(): void;
|
|
66
67
|
reload(): void;
|
|
67
|
-
close(
|
|
68
|
+
close(options?: {
|
|
69
|
+
readonly gracePeriodMs?: number;
|
|
70
|
+
}): Promise<void>;
|
|
68
71
|
}
|
|
69
72
|
export declare function defineWS<const TRoute extends LudicordWebSocketRoute>(route: TRoute): TRoute;
|
|
70
73
|
export declare function attachWebSocketRuntime(httpServer: HttpServer, options: WebSocketRuntimeOptions): LudicordWebSocketRuntime;
|
|
71
74
|
export {};
|
|
72
|
-
//# sourceMappingURL=server.d.ts.map
|
package/dist/ws/server.js
CHANGED
|
@@ -55,6 +55,8 @@ class RuntimeClient {
|
|
|
55
55
|
id = randomUUID();
|
|
56
56
|
memberships = new Set();
|
|
57
57
|
alive = true;
|
|
58
|
+
messageWindowStarted = Date.now();
|
|
59
|
+
messageCount = 0;
|
|
58
60
|
room;
|
|
59
61
|
activity;
|
|
60
62
|
constructor(socket, ludicord, params, rooms, routeClients, backpressureLimit, routeKey) {
|
|
@@ -122,6 +124,14 @@ class RuntimeClient {
|
|
|
122
124
|
close(code = 1000, reason = "") {
|
|
123
125
|
this.socket.close(code, reason);
|
|
124
126
|
}
|
|
127
|
+
acceptMessage(limit, now = Date.now()) {
|
|
128
|
+
if (now - this.messageWindowStarted >= 1_000) {
|
|
129
|
+
this.messageWindowStarted = now;
|
|
130
|
+
this.messageCount = 0;
|
|
131
|
+
}
|
|
132
|
+
this.messageCount += 1;
|
|
133
|
+
return this.messageCount <= limit;
|
|
134
|
+
}
|
|
125
135
|
}
|
|
126
136
|
function normalizeRoom(name) {
|
|
127
137
|
const normalized = name.trim();
|
|
@@ -156,11 +166,25 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
156
166
|
const loadModule = options.loadModule ?? defaultLoader;
|
|
157
167
|
const heartbeatInterval = options.heartbeatInterval ?? 30_000;
|
|
158
168
|
const backpressureLimit = options.backpressureLimit ?? 1_048_576;
|
|
169
|
+
const maxMessagesPerSecond = options.maxMessagesPerSecond ?? 120;
|
|
170
|
+
if (!Number.isSafeInteger(maxMessagesPerSecond) ||
|
|
171
|
+
maxMessagesPerSecond < 1 ||
|
|
172
|
+
maxMessagesPerSecond > 10_000) {
|
|
173
|
+
throw new Error("LUDICORD9004: websocket.maxMessagesPerSecond must be an integer between 1 and 10000.");
|
|
174
|
+
}
|
|
159
175
|
const wss = new WebSocketServer({
|
|
160
176
|
noServer: true,
|
|
161
177
|
maxPayload: options.maxPayload ?? 1_048_576,
|
|
162
178
|
perMessageDeflate: options.compression ?? false,
|
|
163
179
|
});
|
|
180
|
+
const reportError = (error, file) => {
|
|
181
|
+
try {
|
|
182
|
+
void Promise.resolve(options.onError?.(error, file)).catch(() => undefined);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
// Error reporting must never create a second WebSocket failure.
|
|
186
|
+
}
|
|
187
|
+
};
|
|
164
188
|
const onUpgrade = (request, socket, head) => {
|
|
165
189
|
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
166
190
|
if (!pathname.startsWith("/ws/") && pathname !== "/ws")
|
|
@@ -206,31 +230,35 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
206
230
|
client.alive = true;
|
|
207
231
|
});
|
|
208
232
|
webSocket.on("message", (raw) => {
|
|
209
|
-
void dispatchMessage(client, route, raw.toString());
|
|
233
|
+
void dispatchMessage(client, route, raw.toString(), selected.route.file);
|
|
210
234
|
});
|
|
211
235
|
webSocket.on("close", (code, reason) => {
|
|
212
236
|
clients.delete(client);
|
|
213
237
|
routeClients.delete(client);
|
|
214
238
|
rooms.remove(client);
|
|
215
|
-
void Promise.resolve().then(() => route.disconnect?.(client, code, reason.toString())).catch((error) =>
|
|
239
|
+
void Promise.resolve().then(() => route.disconnect?.(client, code, reason.toString())).catch((error) => reportError(error, selected.route.file));
|
|
216
240
|
});
|
|
217
241
|
void Promise.resolve().then(() => route.connect?.(client)).catch((error) => {
|
|
218
|
-
|
|
242
|
+
reportError(error, selected.route.file);
|
|
219
243
|
client.close(1011, "Connect handler failed");
|
|
220
244
|
});
|
|
221
245
|
});
|
|
222
246
|
}
|
|
223
247
|
catch (error) {
|
|
224
|
-
|
|
248
|
+
reportError(error, selected.route.file);
|
|
225
249
|
rejectUpgrade(socket, 500, "Internal Server Error");
|
|
226
250
|
}
|
|
227
|
-
})().catch((error) => {
|
|
251
|
+
})().catch((error) => { reportError(error); rejectUpgrade(socket, 400, "Bad Request"); });
|
|
228
252
|
};
|
|
229
|
-
async function dispatchMessage(client, route, raw) {
|
|
253
|
+
async function dispatchMessage(client, route, raw, file) {
|
|
230
254
|
if (client.ludicord.expiresAt <= Date.now()) {
|
|
231
255
|
client.close(1008, "Session expired");
|
|
232
256
|
return;
|
|
233
257
|
}
|
|
258
|
+
if (!client.acceptMessage(maxMessagesPerSecond)) {
|
|
259
|
+
client.close(1008, "Message rate limit exceeded");
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
234
262
|
let envelope;
|
|
235
263
|
try {
|
|
236
264
|
envelope = JSON.parse(raw);
|
|
@@ -261,7 +289,7 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
261
289
|
await handler(client, envelope.data);
|
|
262
290
|
}
|
|
263
291
|
catch (error) {
|
|
264
|
-
|
|
292
|
+
reportError(error, file);
|
|
265
293
|
client.sendInternal("error", { code: "LUDICORD_EVENT_HANDLER_FAILED" });
|
|
266
294
|
}
|
|
267
295
|
}
|
|
@@ -282,6 +310,7 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
282
310
|
const heartbeat = setInterval(heartbeatNow, heartbeatInterval);
|
|
283
311
|
heartbeat.unref();
|
|
284
312
|
httpServer.on("upgrade", onUpgrade);
|
|
313
|
+
let closePromise = null;
|
|
285
314
|
return {
|
|
286
315
|
server: wss,
|
|
287
316
|
clientCount: () => clients.size,
|
|
@@ -290,24 +319,41 @@ export function attachWebSocketRuntime(httpServer, options) {
|
|
|
290
319
|
for (const client of clients)
|
|
291
320
|
client.close(1012, "Ludicord route updated");
|
|
292
321
|
},
|
|
293
|
-
|
|
322
|
+
close(closeOptions = {}) {
|
|
323
|
+
if (closePromise !== null)
|
|
324
|
+
return closePromise;
|
|
294
325
|
httpServer.off("upgrade", onUpgrade);
|
|
295
326
|
clearInterval(heartbeat);
|
|
296
|
-
|
|
297
|
-
|
|
327
|
+
const gracePeriodMs = closeOptions.gracePeriodMs ?? 1_000;
|
|
328
|
+
if (!Number.isSafeInteger(gracePeriodMs) || gracePeriodMs < 0 || gracePeriodMs > 120_000) {
|
|
329
|
+
throw new Error("LUDICORD9005: WebSocket shutdown gracePeriodMs must be an integer between 0 and 120000.");
|
|
298
330
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
331
|
+
closePromise = (async () => {
|
|
332
|
+
const closing = [...wss.clients].map((socket) => new Promise((resolve) => {
|
|
333
|
+
if (socket.readyState === WebSocket.CLOSED) {
|
|
334
|
+
resolve();
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
socket.once("close", () => resolve());
|
|
338
|
+
if (socket.readyState === WebSocket.OPEN)
|
|
339
|
+
socket.close(1001, "Server shutting down");
|
|
340
|
+
}));
|
|
341
|
+
if (closing.length > 0 && gracePeriodMs > 0) {
|
|
342
|
+
let timer;
|
|
343
|
+
await Promise.race([
|
|
344
|
+
Promise.allSettled(closing),
|
|
345
|
+
new Promise((resolve) => { timer = setTimeout(resolve, gracePeriodMs); }),
|
|
346
|
+
]);
|
|
347
|
+
if (timer !== undefined)
|
|
348
|
+
clearTimeout(timer);
|
|
303
349
|
}
|
|
304
350
|
for (const socket of wss.clients)
|
|
305
351
|
socket.terminate();
|
|
306
|
-
wss.close(() => resolve());
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
352
|
+
await new Promise((resolve) => wss.close(() => resolve()));
|
|
353
|
+
clients.clear();
|
|
354
|
+
clientsByRoute.clear();
|
|
355
|
+
})();
|
|
356
|
+
return closePromise;
|
|
310
357
|
},
|
|
311
358
|
};
|
|
312
359
|
}
|
|
313
|
-
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LudicordWebSocketClient, LudicordWebSocketRoute } from "./server.js";
|
|
2
|
+
export interface LudicordSharedStateContext {
|
|
3
|
+
readonly key: string;
|
|
4
|
+
readonly client: LudicordWebSocketClient;
|
|
5
|
+
}
|
|
6
|
+
export interface LudicordSharedStateOptions<T> {
|
|
7
|
+
readonly initialState: T | ((context: LudicordSharedStateContext) => T);
|
|
8
|
+
readonly validate?: (value: unknown, context: LudicordSharedStateContext) => value is T;
|
|
9
|
+
readonly maxRooms?: number;
|
|
10
|
+
readonly roomTtl?: number;
|
|
11
|
+
readonly maxValueBytes?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare function defineSharedActivityState<T>(options: LudicordSharedStateOptions<T>): LudicordWebSocketRoute;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { defineWS } from "./server.js";
|
|
2
|
+
const SUBSCRIBE_EVENT = "ludicord:shared:subscribe";
|
|
3
|
+
const SET_EVENT = "ludicord:shared:set";
|
|
4
|
+
const STATE_EVENT = "ludicord:shared:state";
|
|
5
|
+
function record(value) {
|
|
6
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
7
|
+
}
|
|
8
|
+
function stateKey(value) {
|
|
9
|
+
if (typeof value !== "string" || value.trim() === "" || value.length > 128) {
|
|
10
|
+
throw new Error("LUDICORD9201: Shared Activity state keys must contain 1-128 characters.");
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
function roomKey(client) {
|
|
15
|
+
const instanceId = client.ludicord.instanceId;
|
|
16
|
+
if (instanceId === undefined || instanceId === "") {
|
|
17
|
+
throw new Error("LUDICORD9202: Shared Activity state requires a verified Activity instance.");
|
|
18
|
+
}
|
|
19
|
+
return `${client.ludicord.applicationId}:${instanceId}`;
|
|
20
|
+
}
|
|
21
|
+
export function defineSharedActivityState(options) {
|
|
22
|
+
const maxRooms = options.maxRooms ?? 1_000;
|
|
23
|
+
const roomTtl = options.roomTtl ?? 60 * 60 * 1_000;
|
|
24
|
+
const maxValueBytes = options.maxValueBytes ?? 64 * 1_024;
|
|
25
|
+
if (!Number.isSafeInteger(maxRooms) || maxRooms < 1 || maxRooms > 100_000)
|
|
26
|
+
throw new Error("LUDICORD9203: maxRooms must be between 1 and 100000.");
|
|
27
|
+
if (!Number.isSafeInteger(roomTtl) || roomTtl < 1_000 || roomTtl > 7 * 24 * 60 * 60 * 1_000)
|
|
28
|
+
throw new Error("LUDICORD9203: roomTtl must be between 1000 milliseconds and 7 days.");
|
|
29
|
+
if (!Number.isSafeInteger(maxValueBytes) || maxValueBytes < 16 || maxValueBytes > 1_048_576)
|
|
30
|
+
throw new Error("LUDICORD9203: maxValueBytes must be between 16 and 1048576.");
|
|
31
|
+
const rooms = new Map();
|
|
32
|
+
const prune = (now = Date.now()) => {
|
|
33
|
+
for (const [key, room] of rooms)
|
|
34
|
+
if (now - room.touchedAt > roomTtl)
|
|
35
|
+
rooms.delete(key);
|
|
36
|
+
};
|
|
37
|
+
const roomFor = (client) => {
|
|
38
|
+
prune();
|
|
39
|
+
const key = roomKey(client);
|
|
40
|
+
const existing = rooms.get(key);
|
|
41
|
+
if (existing !== undefined) {
|
|
42
|
+
existing.touchedAt = Date.now();
|
|
43
|
+
return existing;
|
|
44
|
+
}
|
|
45
|
+
while (rooms.size >= maxRooms) {
|
|
46
|
+
const oldest = [...rooms].sort((left, right) => left[1].touchedAt - right[1].touchedAt)[0];
|
|
47
|
+
if (oldest === undefined)
|
|
48
|
+
break;
|
|
49
|
+
rooms.delete(oldest[0]);
|
|
50
|
+
}
|
|
51
|
+
const room = { values: new Map(), touchedAt: Date.now() };
|
|
52
|
+
room.touchedAt = Date.now();
|
|
53
|
+
rooms.set(key, room);
|
|
54
|
+
return room;
|
|
55
|
+
};
|
|
56
|
+
const initial = (key, client) => typeof options.initialState === "function"
|
|
57
|
+
? options.initialState({ key, client })
|
|
58
|
+
: options.initialState;
|
|
59
|
+
const serializableSize = (value) => {
|
|
60
|
+
try {
|
|
61
|
+
const serialized = JSON.stringify(value);
|
|
62
|
+
return serialized === undefined ? null : Buffer.byteLength(serialized);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const current = (key, client) => {
|
|
69
|
+
const room = roomFor(client);
|
|
70
|
+
const existing = room.values.get(key);
|
|
71
|
+
if (existing !== undefined)
|
|
72
|
+
return existing;
|
|
73
|
+
const value = initial(key, client);
|
|
74
|
+
const context = { key, client };
|
|
75
|
+
if (options.validate !== undefined && !options.validate(value, context)) {
|
|
76
|
+
throw new Error("LUDICORD9204: initialState did not pass shared state validation.");
|
|
77
|
+
}
|
|
78
|
+
const size = serializableSize(value);
|
|
79
|
+
if (size === null)
|
|
80
|
+
throw new Error("LUDICORD9204: initialState must be JSON-serializable.");
|
|
81
|
+
if (size > maxValueBytes)
|
|
82
|
+
throw new Error("LUDICORD9204: initialState exceeds maxValueBytes.");
|
|
83
|
+
const created = { value, revision: 0 };
|
|
84
|
+
room.values.set(key, created);
|
|
85
|
+
return created;
|
|
86
|
+
};
|
|
87
|
+
const send = (client, key, value) => client.emit(STATE_EVENT, { key, value: value.value, revision: value.revision });
|
|
88
|
+
return defineWS({
|
|
89
|
+
connect(client) {
|
|
90
|
+
try {
|
|
91
|
+
client.activity.join();
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
client.close(1008, "Activity instance required");
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
events: {
|
|
98
|
+
[SUBSCRIBE_EVENT](client, payload) {
|
|
99
|
+
const key = stateKey(record(payload)?.key);
|
|
100
|
+
send(client, key, current(key, client));
|
|
101
|
+
},
|
|
102
|
+
[SET_EVENT](client, payload) {
|
|
103
|
+
const source = record(payload);
|
|
104
|
+
const key = stateKey(source?.key);
|
|
105
|
+
const previous = current(key, client);
|
|
106
|
+
const expectedRevision = source?.revision;
|
|
107
|
+
if (typeof expectedRevision === "number" && expectedRevision !== previous.revision) {
|
|
108
|
+
send(client, key, previous);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const context = { key, client };
|
|
112
|
+
if (options.validate !== undefined && !options.validate(source?.value, context)) {
|
|
113
|
+
client.close(1008, "Invalid shared state");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const size = serializableSize(source?.value);
|
|
117
|
+
if (size === null) {
|
|
118
|
+
client.close(1008, "Shared state must be serializable");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (size > maxValueBytes) {
|
|
122
|
+
client.close(1009, "Shared state exceeds limit");
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const next = { value: source?.value, revision: previous.revision + 1 };
|
|
126
|
+
roomFor(client).values.set(key, next);
|
|
127
|
+
client.activity.broadcast(STATE_EVENT, { key, value: next.value, revision: next.revision }, { includeSelf: true });
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
disconnect(client) {
|
|
131
|
+
try {
|
|
132
|
+
client.activity.leave();
|
|
133
|
+
}
|
|
134
|
+
catch { /* The client may have lacked an instance. */ }
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ludicord",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Full-stack React framework for Discord Activities.",
|
|
5
5
|
"homepage": "https://github.com/mrcholer/ludicord#readme",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/mrcholer/ludicord
|
|
8
|
+
"url": "git+https://github.com/mrcholer/ludicord.git",
|
|
9
9
|
"directory": "packages/ludicord"
|
|
10
10
|
},
|
|
11
11
|
"bugs": {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"publishConfig": {
|
|
17
17
|
"access": "public",
|
|
18
18
|
"registry": "https://registry.npmjs.org/",
|
|
19
|
-
"provenance":
|
|
19
|
+
"provenance": true
|
|
20
20
|
},
|
|
21
21
|
"engines": {
|
|
22
22
|
"node": ">=20.19.0"
|
|
@@ -46,6 +46,16 @@
|
|
|
46
46
|
"import": "./dist/navigation/index.js",
|
|
47
47
|
"default": "./dist/navigation/index.js"
|
|
48
48
|
},
|
|
49
|
+
"./metadata": {
|
|
50
|
+
"types": "./dist/metadata/index.d.ts",
|
|
51
|
+
"import": "./dist/metadata/index.js",
|
|
52
|
+
"default": "./dist/metadata/index.js"
|
|
53
|
+
},
|
|
54
|
+
"./activity": {
|
|
55
|
+
"types": "./dist/activity/index.d.ts",
|
|
56
|
+
"import": "./dist/activity/index.js",
|
|
57
|
+
"default": "./dist/activity/index.js"
|
|
58
|
+
},
|
|
49
59
|
"./discord": {
|
|
50
60
|
"types": "./dist/discord/index.d.ts",
|
|
51
61
|
"import": "./dist/discord/index.js",
|
|
@@ -115,8 +125,11 @@
|
|
|
115
125
|
"dependencies": {
|
|
116
126
|
"@discord/embedded-app-sdk": "^2.4.0",
|
|
117
127
|
"@jridgewell/trace-mapping": "^0.3.31",
|
|
128
|
+
"@typescript-eslint/parser": "^8.69.0",
|
|
118
129
|
"@vitejs/plugin-react": "^5.1.2",
|
|
119
130
|
"esbuild": "^0.28.2",
|
|
131
|
+
"eslint": "^10.10.0",
|
|
132
|
+
"eslint-plugin-react-hooks": "^7.1.1",
|
|
120
133
|
"express": "^5.2.1",
|
|
121
134
|
"magic-string": "^0.30.17",
|
|
122
135
|
"typescript": "^5.9.3",
|