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
@@ -1,5 +1,5 @@
1
1
  import { createServer } from "node:http";
2
- import { existsSync, watch } from "node:fs";
2
+ import { existsSync, readFileSync, rmSync, watch } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -18,9 +18,22 @@ import { loadLudicordConfig } from "../../config/loader.js";
18
18
  import { loadProjectEnvironment } from "../../config/environment.js";
19
19
  import { LUDICORD_VERSION } from "../../version.js";
20
20
  import { diagnostic, sourceFrame, watchProjectTypes } from "./diagnostics.js";
21
+ import { createProxyMiddleware } from "../../server/proxy.js";
21
22
  const ENTRY = "virtual:ludicord-activity-entry";
22
23
  const RESOLVED_ENTRY = "\0" + ENTRY;
23
24
  const PANEL = "virtual:ludicord-dev-panel";
25
+ const RESOLVED_PANEL = "\0" + PANEL;
26
+ function escapeHtml(value) {
27
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
28
+ }
29
+ function developmentErrorPage(issue) {
30
+ const location = issue.file === undefined ? "Activity runtime" : `${issue.file}:${issue.line ?? 1}:${issue.column ?? 1}`;
31
+ return `<!doctype html>
32
+ <html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />
33
+ <title>Ludicord development error</title><style>
34
+ :root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#000;color:#fafafa}*{box-sizing:border-box}body{min-height:100vh;margin:0;display:grid;place-items:center;padding:24px;background:radial-gradient(620px circle at 50% 40%,rgba(255,68,56,.16),transparent 70%),#000}.panel{width:min(680px,100%);max-height:90vh;overflow:auto;border:1px solid #1f1f1f;border-radius:20px;background:#0a0a0a;box-shadow:0 30px 80px rgba(0,0,0,.65)}header{display:flex;align-items:center;padding:14px 16px}.pill{display:inline-flex;align-items:center;gap:7px;padding:6px 12px;border:1px solid rgba(255,68,56,.35);border-radius:999px;color:#ff4438;background:rgba(255,68,56,.13);font-size:12px;font-weight:500}.dot{width:6px;height:6px;border-radius:50%;background:#ff4438}article{padding:8px 24px 24px}h1{margin:2px 0 14px;font-size:20px;line-height:1.45;overflow-wrap:anywhere}.file{color:#8c8c8c;font:12px ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere}pre{max-height:45vh;margin:18px 0 0;padding:16px;overflow:auto;border:1px solid #1f1f1f;border-radius:10px;color:#fafafa;background:#000;font:12px/1.8 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap}footer{display:flex;align-items:center;gap:12px;padding:14px 20px;border-top:1px solid #1f1f1f;color:#8c8c8c;font-size:12px}button{margin-left:auto;padding:7px 13px;border:1px solid #1f1f1f;border-radius:8px;color:#fafafa;background:#131313;font:inherit;cursor:pointer}button:hover{border-color:#8c8c8c}@media(max-width:600px){body{padding:10px}.panel{border-radius:16px}article{padding:6px 18px 18px}}
35
+ </style></head><body><section class="panel" role="alert"><header><span class="pill"><span class="dot"></span>${escapeHtml(issue.kind ?? "runtime")} error</span></header><article><h1>${escapeHtml(issue.message)}</h1><div class="file">${escapeHtml(location)}</div><pre>${escapeHtml(issue.frame ?? "Fix the error in your source. Ludicord will retry automatically.")}</pre></article><footer><span>Waiting for a successful rebuild…</span><button type="button" onclick="location.reload()">Retry now</button></footer></section><script>setInterval(async()=>{try{const response=await fetch(location.href,{headers:{accept:'text/html'},cache:'no-store'});if(response.ok)location.reload()}catch{}},1200)</script></body></html>`;
36
+ }
24
37
  export async function createLudicordDevServer(options) {
25
38
  const projectRoot = path.resolve(options.projectRoot);
26
39
  loadProjectEnvironment(projectRoot, "development");
@@ -37,10 +50,16 @@ export async function createLudicordDevServer(options) {
37
50
  let sourceWatcher;
38
51
  const changedFiles = new Map();
39
52
  let graph;
53
+ let graphDirectory;
54
+ let instrumentationCleanup;
55
+ let instrumentation;
40
56
  let revision = 0;
41
57
  const runId = randomUUID();
58
+ const devToken = randomUUID();
59
+ const panelSource = readFileSync(fileURLToPath(new URL("../client/dev-panel.js", import.meta.url)), "utf8");
42
60
  const serverIssues = new Set();
43
61
  const reportedErrors = new WeakSet();
62
+ const reportedRequestErrors = new WeakSet();
44
63
  let closed = false;
45
64
  let rebuilding = Promise.resolve();
46
65
  const publish = () => vite?.ws.send({ type: "custom", event: "ludicord:diagnostics", data: { issues: [...issues.values()] } });
@@ -57,22 +76,100 @@ export async function createLudicordDevServer(options) {
57
76
  console.error(item.stack);
58
77
  publish();
59
78
  };
79
+ const notifyRequestError = async (error, source, file, request) => {
80
+ if (error !== null && typeof error === "object") {
81
+ if (reportedRequestErrors.has(error))
82
+ return;
83
+ reportedRequestErrors.add(error);
84
+ }
85
+ const notify = instrumentation?.onRequestError;
86
+ if (notify === undefined)
87
+ return;
88
+ try {
89
+ await notify(error, {
90
+ environment: "development",
91
+ projectRoot,
92
+ source,
93
+ ...(file === undefined ? {} : { file }),
94
+ ...(request === undefined ? {} : request),
95
+ });
96
+ }
97
+ catch (notificationError) {
98
+ report(notificationError, "app/instrumentation.ts");
99
+ }
100
+ };
101
+ const scanManifests = () => {
102
+ const next = generateManifests(projectRoot);
103
+ generateLudicordTypes(projectRoot, next, config);
104
+ return next;
105
+ };
60
106
  const refreshManifests = () => {
61
- manifests = generateManifests(projectRoot);
62
- generateLudicordTypes(projectRoot, manifests, config);
107
+ manifests = scanManifests();
63
108
  return manifests;
64
109
  };
65
- const rebuildServer = (file) => {
110
+ const rebuildServer = (file, candidateManifests = manifests) => {
66
111
  rebuilding = rebuilding.then(async () => {
67
112
  if (closed)
68
113
  return;
69
114
  const started = performance.now();
70
115
  const name = file === undefined ? "server routes" : normalizePath(path.relative(projectRoot, file));
71
- if (manifests.api.length + manifests.websocket.length > 0)
116
+ const nextDirectory = path.join(projectRoot, ".ludicord", "dev", runId, String(++revision));
117
+ const serverEntryCount = candidateManifests.api.length + candidateManifests.websocket.length +
118
+ Number(candidateManifests.activity.instrumentation !== undefined) + Number(candidateManifests.activity.proxy !== undefined);
119
+ if (serverEntryCount > 0)
72
120
  console.log("compiling " + name);
73
121
  try {
74
- const next = await bundleServerGraph(projectRoot, path.join(projectRoot, ".ludicord", "dev", runId, String(++revision)), manifests);
122
+ const next = await bundleServerGraph(projectRoot, nextDirectory, candidateManifests);
123
+ const instrumentationFile = candidateManifests.activity.instrumentation;
124
+ let nextInstrumentationCleanup;
125
+ let nextInstrumentation;
126
+ if (instrumentationFile !== undefined) {
127
+ const loaded = await next.loadModule(path.join(projectRoot, instrumentationFile));
128
+ const candidate = loaded.default ?? (typeof loaded.register === "function" ? loaded : undefined);
129
+ if (candidate === undefined)
130
+ throw new Error("LUDICORD3004: app/instrumentation.ts must export a default instrumentation object with register().");
131
+ nextInstrumentation = candidate;
132
+ const previousInstrumentation = instrumentation;
133
+ await instrumentationCleanup?.();
134
+ instrumentationCleanup = undefined;
135
+ instrumentation = undefined;
136
+ try {
137
+ const cleanup = await nextInstrumentation.register({ environment: "development", projectRoot });
138
+ if (typeof cleanup === "function")
139
+ nextInstrumentationCleanup = cleanup;
140
+ }
141
+ catch (registrationError) {
142
+ if (previousInstrumentation !== undefined) {
143
+ try {
144
+ const restoredCleanup = await previousInstrumentation.register({ environment: "development", projectRoot });
145
+ instrumentation = previousInstrumentation;
146
+ if (typeof restoredCleanup === "function")
147
+ instrumentationCleanup = restoredCleanup;
148
+ }
149
+ catch (restoreError) {
150
+ report(restoreError, "app/instrumentation.ts");
151
+ }
152
+ }
153
+ throw registrationError;
154
+ }
155
+ }
156
+ else {
157
+ await instrumentationCleanup?.();
158
+ instrumentationCleanup = undefined;
159
+ instrumentation = undefined;
160
+ }
161
+ const previousDirectory = graphDirectory;
162
+ manifests = candidateManifests;
75
163
  graph = next;
164
+ graphDirectory = nextDirectory;
165
+ instrumentationCleanup = nextInstrumentationCleanup;
166
+ instrumentation = nextInstrumentation;
167
+ if (previousDirectory !== undefined) {
168
+ try {
169
+ rmSync(previousDirectory, { recursive: true, force: true });
170
+ }
171
+ catch { /* A stale dev bundle can be removed during shutdown or the next rebuild. */ }
172
+ }
76
173
  for (const key of serverIssues)
77
174
  issues.delete(key);
78
175
  serverIssues.clear();
@@ -82,11 +179,12 @@ export async function createLudicordDevServer(options) {
82
179
  }
83
180
  if (file !== undefined)
84
181
  websocket?.reload();
85
- if (manifests.api.length + manifests.websocket.length > 0)
182
+ if (serverEntryCount > 0)
86
183
  console.log("compiled " + name + " (" + Math.round(performance.now() - started) + "ms)");
87
184
  publish();
88
185
  }
89
186
  catch (error) {
187
+ rmSync(nextDirectory, { recursive: true, force: true });
90
188
  report(error, file ?? "server routes", "compile");
91
189
  const item = diagnostic(error, projectRoot, file ?? "server routes", "compile");
92
190
  serverIssues.add("compile:" + (item.file ?? "runtime"));
@@ -96,7 +194,7 @@ export async function createLudicordDevServer(options) {
96
194
  };
97
195
  const isServerFile = (file) => {
98
196
  const relative = normalizePath(path.relative(projectRoot, file));
99
- return /^app\/(api|ws)\//.test(relative) || graph?.dependencies.has(path.resolve(file)) === true;
197
+ return /^app\/(api|ws)\//.test(relative) || /^app\/(proxy|instrumentation)\.[cm]?[jt]s$/.test(relative) || graph?.dependencies.has(path.resolve(file)) === true;
100
198
  };
101
199
  const plugin = {
102
200
  name: "ludicord:activity-runtime", enforce: "pre",
@@ -104,10 +202,16 @@ export async function createLudicordDevServer(options) {
104
202
  if (id === ENTRY)
105
203
  return RESOLVED_ENTRY;
106
204
  if (id === PANEL)
107
- return fileURLToPath(new URL("../client/dev-panel.js", import.meta.url));
205
+ return RESOLVED_PANEL;
206
+ return undefined;
207
+ },
208
+ load(id) {
209
+ if (id === RESOLVED_ENTRY)
210
+ return clientEntry(projectRoot, manifests, config, true);
211
+ if (id === RESOLVED_PANEL)
212
+ return `globalThis.__LUDICORD_DEV_TOKEN__=${JSON.stringify(devToken)};\n${panelSource}`;
108
213
  return undefined;
109
214
  },
110
- load(id) { return id === RESOLVED_ENTRY ? clientEntry(projectRoot, manifests, config, true) : undefined; },
111
215
  configureServer(server) {
112
216
  server.watcher.add(path.join(projectRoot, "app"));
113
217
  },
@@ -130,9 +234,28 @@ export async function createLudicordDevServer(options) {
130
234
  customLogger: ludicordLogger((error) => report(error, undefined, "compile")),
131
235
  server: {
132
236
  middlewareMode: true, allowedHosts: config.server.allowedHosts === true ? true : [...config.server.allowedHosts],
237
+ // Compile modules when the browser requests them. Vite's speculative
238
+ // pre-transform can still be running when a middleware-mode server is
239
+ // closed, which produces a false esbuild "build was canceled" error.
240
+ preTransformRequests: false,
133
241
  hmr: options.hmr === false ? false : { server: httpServer, overlay: false },
134
242
  watch: { ignored: ["**/.ludicord/**", "**/.dact/**"] },
135
243
  },
244
+ optimizeDeps: {
245
+ // Optimize the fixed browser runtime up front. Discovery can outlive a
246
+ // short dev session and report false esbuild cancellation/filesystem
247
+ // errors after the project or its temporary cache has been removed.
248
+ noDiscovery: true,
249
+ holdUntilCrawlEnd: false,
250
+ include: [
251
+ "react",
252
+ "react/jsx-runtime",
253
+ "react/jsx-dev-runtime",
254
+ "react-dom",
255
+ "react-dom/client",
256
+ "@discord/embedded-app-sdk",
257
+ ],
258
+ },
136
259
  resolve: { dedupe: ["react", "react-dom"], alias: clientAliases(projectRoot) },
137
260
  plugins: [plugin, ...await clientPlugins(projectRoot, (file, elapsed) => {
138
261
  if (elapsed === undefined)
@@ -159,10 +282,11 @@ export async function createLudicordDevServer(options) {
159
282
  changedFiles.set(file, setTimeout(() => {
160
283
  changedFiles.delete(file);
161
284
  try {
162
- refreshManifests();
285
+ const nextManifests = scanManifests();
163
286
  if (isServerFile(file))
164
- void rebuildServer(file);
287
+ void rebuildServer(file, nextManifests);
165
288
  else {
289
+ manifests = nextManifests;
166
290
  const entry = vite?.moduleGraph.getModuleById(RESOLVED_ENTRY);
167
291
  if (entry)
168
292
  vite?.moduleGraph.invalidateModule(entry);
@@ -185,17 +309,34 @@ export async function createLudicordDevServer(options) {
185
309
  loadModule: (file) => loadModule(file),
186
310
  ...(process.env.LUDICORD_SESSION_SECRET === undefined ? {} : { sessionSecret: process.env.LUDICORD_SESSION_SECRET }),
187
311
  heartbeatInterval: config.websocket.heartbeatInterval, maxPayload: config.websocket.maxPayload,
188
- compression: config.websocket.compression, enabled: config.websocket.enabled, allowDevelopmentSessions: true,
189
- onError: (error, file) => report(error, file),
312
+ compression: config.websocket.compression, maxMessagesPerSecond: config.websocket.maxMessagesPerSecond,
313
+ enabled: config.websocket.enabled, allowDevelopmentSessions: true,
314
+ onError: (error, file) => { report(error, file); void notifyRequestError(error, "websocket", file); },
190
315
  });
191
316
  app.use("/_ludicord/auth", createLudicordAuthRouter({
192
317
  ...(config.discord.clientId === undefined ? {} : { clientId: config.discord.clientId }), production: false,
193
318
  activityInstanceVerification: config.discord.auth.activityInstanceVerification,
194
319
  }));
195
- app.get("/_ludicord/dev/diagnostics", (_request, response) => response.json({ issues: [...issues.values()] }));
196
- app.post("/_ludicord/dev/error", express.json({ limit: "64kb" }), async (request, response) => {
320
+ const requireDevToken = (request, response, next) => {
321
+ const remote = request.socket.remoteAddress ?? "";
322
+ const loopback = remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
323
+ if (loopback || request.get("x-ludicord-dev-token") === devToken) {
324
+ next();
325
+ return;
326
+ }
327
+ response.status(404).end();
328
+ };
329
+ app.get("/_ludicord/dev/diagnostics", requireDevToken, (_request, response) => {
330
+ response.setHeader("Cache-Control", "no-store");
331
+ response.json({ issues: [...issues.values()] });
332
+ });
333
+ app.post("/_ludicord/dev/error", requireDevToken, express.json({ limit: "64kb" }), async (request, response) => {
197
334
  const body = request.body;
198
- let item = diagnostic({ message: typeof body.message === "string" ? body.message : "Activity runtime error", stack: typeof body.stack === "string" ? body.stack : undefined }, projectRoot);
335
+ let item = diagnostic({
336
+ message: typeof body.message === "string" ? body.message : "Activity runtime error",
337
+ stack: typeof body.stack === "string" ? body.stack : undefined,
338
+ componentStack: typeof body.componentStack === "string" ? body.componentStack : undefined,
339
+ }, projectRoot);
199
340
  const stack = typeof body.stack === "string" ? body.stack : "";
200
341
  const match = [...stack.matchAll(/https?:\/\/[^\s)]+?((?:\/@fs\/|\/app\/|\/components\/|\/lib\/)[^\s)]*?):(\d+):(\d+)/g)][0];
201
342
  if (match?.[1]) {
@@ -227,21 +368,31 @@ export async function createLudicordDevServer(options) {
227
368
  console.error("Ludicord runtime error · " + (item.file ?? "Activity") + "\n" + item.message + (item.frame ? "\n" + item.frame : ""));
228
369
  response.json(item);
229
370
  });
371
+ app.use(createProxyMiddleware({
372
+ projectRoot,
373
+ environment: "development",
374
+ source: () => manifests.activity.proxy === undefined
375
+ ? undefined
376
+ : path.join(projectRoot, manifests.activity.proxy),
377
+ loadModule: (file) => loadModule(file),
378
+ onError: async (error, file, request) => {
379
+ report(error, file);
380
+ await notifyRequestError(error, "proxy", file, request);
381
+ },
382
+ }));
230
383
  app.use(createApiMiddleware({
231
384
  projectRoot, getRoutes: () => manifests.api, loadModule: (file) => loadModule(file),
232
385
  ...(process.env.LUDICORD_SESSION_SECRET === undefined ? {} : { sessionSecret: process.env.LUDICORD_SESSION_SECRET }),
233
386
  proxyVerification: config.discord.auth.proxyVerification,
234
387
  ...(process.env.LUDICORD_DISCORD_PUBLIC_KEY === undefined ? {} : { discordPublicKey: process.env.LUDICORD_DISCORD_PUBLIC_KEY }),
235
- bodyLimit: config.server.limits.body, allowDevelopmentSessions: true, onError: (error, file) => report(error, file),
388
+ bodyLimit: config.server.limits.body, requestTimeout: config.server.requestTimeout,
389
+ allowDevelopmentSessions: true, onError: async (error, file, request) => {
390
+ report(error, file);
391
+ await notifyRequestError(error, "api", file, request);
392
+ },
236
393
  }));
237
394
  app.get("/_ludicord/manifest", (_request, response) => {
238
- try {
239
- response.json(refreshManifests());
240
- }
241
- catch (error) {
242
- report(error, undefined, "compile");
243
- response.status(500).json({ error: "LUDICORD_INVALID_MANIFEST" });
244
- }
395
+ response.json(manifests);
245
396
  });
246
397
  app.get("/", async (request, response, next) => {
247
398
  try {
@@ -253,10 +404,17 @@ export async function createLudicordDevServer(options) {
253
404
  }
254
405
  });
255
406
  app.use(vite.middlewares);
256
- app.use((error, _request, response, _next) => {
407
+ app.use(async (error, request, response, _next) => {
257
408
  report(error);
258
- if (!response.headersSent)
259
- response.status(500).json({ error: "LUDICORD_DEV_ERROR", message: "See the Ludicord error panel or terminal for the source location." });
409
+ await notifyRequestError(error, "server", undefined, { method: request.method, url: request.originalUrl });
410
+ if (response.headersSent)
411
+ return;
412
+ const item = diagnostic(error, projectRoot, undefined, "runtime");
413
+ if (request.accepts("html")) {
414
+ response.status(500).type("html").send(developmentErrorPage(item));
415
+ return;
416
+ }
417
+ response.status(500).json({ error: "LUDICORD_DEV_ERROR", issue: item });
260
418
  });
261
419
  let typeSignature = "";
262
420
  typeWatcher = watchProjectTypes(projectRoot, (items) => {
@@ -287,7 +445,7 @@ export async function createLudicordDevServer(options) {
287
445
  const environments = [".env", ".env.local", ".env.development", ".env.development.local"].filter((name) => existsSync(path.join(projectRoot, name)));
288
446
  return "Ludicord " + LUDICORD_VERSION + "\nDiscord Activity Framework\n\n Local: " + url +
289
447
  (environments.length ? "\n Environment: " + environments.join(", ") : "") +
290
- "\n\n✓ app/pages.tsx\n✓ Embed router\n" + (options.hmr === false ? "– HMR disabled" : "✓ HMR") + "\n✓ API / WS hot updates\n\nReady";
448
+ "\n\n✓ app/pages.tsx\n✓ Embed router\n" + (options.hmr === false ? "– HMR disabled" : "✓ HMR") + "\n✓ API / WS / proxy hot updates\n\nReady";
291
449
  },
292
450
  async close() {
293
451
  if (closed)
@@ -300,6 +458,8 @@ export async function createLudicordDevServer(options) {
300
458
  await rebuilding;
301
459
  await websocket?.close();
302
460
  await vite?.close();
461
+ await instrumentationCleanup?.();
462
+ rmSync(path.join(projectRoot, ".ludicord", "dev", runId), { recursive: true, force: true });
303
463
  const ending = new Promise((resolve) => httpServer.close(() => resolve()));
304
464
  httpServer.closeAllConnections();
305
465
  await ending;
@@ -314,9 +474,10 @@ export async function createLudicordDevServer(options) {
314
474
  clearTimeout(timer);
315
475
  await websocket?.close();
316
476
  await vite?.close();
477
+ await instrumentationCleanup?.();
317
478
  httpServer.closeAllConnections();
318
479
  httpServer.close();
480
+ rmSync(path.join(projectRoot, ".ludicord", "dev", runId), { recursive: true, force: true });
319
481
  throw error;
320
482
  }
321
483
  }
322
- //# sourceMappingURL=dev-server.js.map
@@ -5,6 +5,7 @@ export interface LudicordDiagnostic {
5
5
  readonly column?: number;
6
6
  readonly frame?: string;
7
7
  readonly stack?: string;
8
+ readonly componentStack?: string;
8
9
  readonly kind: "compile" | "type" | "runtime";
9
10
  }
10
11
  export declare function redact(message: string): string;
@@ -14,4 +15,3 @@ export declare function checkProjectTypes(root: string): readonly LudicordDiagno
14
15
  export declare function watchProjectTypes(root: string, publish: (items: readonly LudicordDiagnostic[]) => void): {
15
16
  close(): void;
16
17
  } | undefined;
17
- //# sourceMappingURL=diagnostics.d.ts.map
@@ -4,10 +4,11 @@ import { fileURLToPath } from "node:url";
4
4
  import ts from "typescript";
5
5
  export function redact(message) {
6
6
  let text = message;
7
- for (const key of ["LUDICORD_DISCORD_CLIENT_SECRET", "LUDICORD_SESSION_SECRET", "LUDICORD_DISCORD_BOT_TOKEN"]) {
8
- const value = process.env[key];
9
- if (value)
7
+ const sensitiveName = /(?:secret|token|password|private|database_url|api_key|access_key)/i;
8
+ for (const [key, value] of Object.entries(process.env)) {
9
+ if (value && value.length >= 4 && sensitiveName.test(key)) {
10
10
  text = text.split(value).join("[redacted]");
11
+ }
11
12
  }
12
13
  return text;
13
14
  }
@@ -55,6 +56,7 @@ export function diagnostic(error, root, file, kind = "runtime") {
55
56
  ...(line === undefined ? {} : { line }), ...(column === undefined ? {} : { column }),
56
57
  ...(frame === undefined ? {} : { frame: redact(frame) }),
57
58
  ...(value?.stack === undefined ? {} : { stack: redact(value.stack) }),
59
+ ...(value?.componentStack === undefined ? {} : { componentStack: redact(value.componentStack) }),
58
60
  };
59
61
  }
60
62
  function tsDiagnostic(item, root) {
@@ -84,4 +86,3 @@ export function watchProjectTypes(root, publish) {
84
86
  };
85
87
  return ts.createWatchProgram(host);
86
88
  }
87
- //# sourceMappingURL=diagnostics.js.map
@@ -2,4 +2,3 @@ export { createLudicordDevServer } from "./dev-server.js";
2
2
  export { createLudicordProductionServer } from "./production-server.js";
3
3
  export type { LudicordDevServer, LudicordDevServerOptions } from "./dev-server.js";
4
4
  export type { LudicordProductionServer, LudicordProductionServerOptions } from "./production-server.js";
5
- //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,2 @@
1
1
  export { createLudicordDevServer } from "./dev-server.js";
2
2
  export { createLudicordProductionServer } from "./production-server.js";
3
- //# sourceMappingURL=index.js.map
@@ -2,10 +2,12 @@ import type { Express } from "express";
2
2
  import type { LudicordBuildMetadata } from "../../compiler/build.js";
3
3
  import type { LudicordManifests } from "../../manifests/types.js";
4
4
  import type { LudicordWebSocketRuntime } from "../../ws/server.js";
5
+ import type { LudicordSessionDataStore } from "../../sessions/data-store.js";
5
6
  export interface LudicordProductionServerOptions {
6
7
  readonly projectRoot: string;
7
8
  readonly port?: number;
8
9
  readonly host?: string;
10
+ readonly sessionDataStore?: LudicordSessionDataStore;
9
11
  }
10
12
  export interface LudicordProductionServer {
11
13
  readonly app: Express;
@@ -19,4 +21,3 @@ export interface LudicordProductionServer {
19
21
  close(): Promise<void>;
20
22
  }
21
23
  export declare function createLudicordProductionServer(options: LudicordProductionServerOptions): Promise<LudicordProductionServer>;
22
- //# sourceMappingURL=production-server.d.ts.map