@guren/server 2.10.0 → 2.11.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 (91) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/http/resources/Resource.d.ts +23 -3
  32. package/dist/i18n/index.js +2 -30
  33. package/dist/i18n-mcWi7LCd.js +617 -0
  34. package/dist/index.js +7515 -7276
  35. package/dist/lambda/index.js +114 -71
  36. package/dist/logging/index.js +2 -24
  37. package/dist/logging-CPaRMuPP.js +518 -0
  38. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  39. package/dist/mail/index.js +2 -27
  40. package/dist/mail-DfEfSQEr.js +699 -0
  41. package/dist/mcp/index.js +2 -10
  42. package/dist/notifications/index.js +2 -33
  43. package/dist/notifications-BGqmUNZ8.js +759 -0
  44. package/dist/queue/index.js +3 -42
  45. package/dist/queue-CXrRK85G.js +948 -0
  46. package/dist/redis/index.js +672 -642
  47. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  48. package/dist/runtime/index.js +472 -616
  49. package/dist/scheduling/index.js +2 -29
  50. package/dist/scheduling-CPiEdtQd.js +839 -0
  51. package/dist/storage/index.js +2 -15
  52. package/dist/storage-tWHMv2H_.js +841 -0
  53. package/dist/support/expiry.js +69 -12
  54. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  55. package/dist/vite/index.js +118 -181
  56. package/dist/vite/plugin.d.ts +1 -1
  57. package/dist/vite-dev-server-BSJkduhZ.js +131 -0
  58. package/package.json +6 -5
  59. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  60. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  61. package/dist/chunk-2SC566CD.js +0 -376
  62. package/dist/chunk-2V3YID4H.js +0 -20
  63. package/dist/chunk-3KV5X2FL.js +0 -31
  64. package/dist/chunk-63SKW5PS.js +0 -457
  65. package/dist/chunk-6J6B5KOB.js +0 -425
  66. package/dist/chunk-A5JJ7XTH.js +0 -24
  67. package/dist/chunk-AZOYI43J.js +0 -18
  68. package/dist/chunk-B5E5VBDI.js +0 -115
  69. package/dist/chunk-DAQKYKLH.js +0 -182
  70. package/dist/chunk-DRNPVBAA.js +0 -1002
  71. package/dist/chunk-EI5GYMAT.js +0 -853
  72. package/dist/chunk-H3B23O6T.js +0 -271
  73. package/dist/chunk-HPET6XY5.js +0 -853
  74. package/dist/chunk-HR2KZ3WL.js +0 -616
  75. package/dist/chunk-IOTWFHZU.js +0 -558
  76. package/dist/chunk-K6CUBJX6.js +0 -642
  77. package/dist/chunk-KTNJG7R7.js +0 -911
  78. package/dist/chunk-LAJQCSSF.js +0 -355
  79. package/dist/chunk-LHR6OHI7.js +0 -189
  80. package/dist/chunk-N7PLD7MB.js +0 -729
  81. package/dist/chunk-Q2P6YLRR.js +0 -24
  82. package/dist/chunk-QQKTH5KX.js +0 -114
  83. package/dist/chunk-SFQP6O52.js +0 -126
  84. package/dist/chunk-SQR7277M.js +0 -911
  85. package/dist/chunk-T2FFUU6J.js +0 -484
  86. package/dist/chunk-TVV5YNEC.js +0 -1842
  87. package/dist/chunk-UY3AZSYL.js +0 -14
  88. package/dist/chunk-V4DNC2ER.js +0 -114
  89. package/dist/chunk-VSA3QY5Q.js +0 -274
  90. package/dist/chunk-YSOJKAAU.js +0 -427
  91. package/dist/errors-PUNHAFL2.js +0 -34
@@ -0,0 +1,345 @@
1
+ //#region src/health/HealthCheck.ts
2
+ /**
3
+ * Abstract base class for health checks.
4
+ */
5
+ var HealthCheck = class {
6
+ /**
7
+ * Create a healthy result.
8
+ */
9
+ healthy(message, meta) {
10
+ return this.result("healthy", message, meta);
11
+ }
12
+ /**
13
+ * Create a degraded result.
14
+ */
15
+ degraded(message, meta) {
16
+ return this.result("degraded", message, meta);
17
+ }
18
+ /**
19
+ * Create an unhealthy result.
20
+ */
21
+ unhealthy(message, meta) {
22
+ return this.result("unhealthy", message, meta);
23
+ }
24
+ /**
25
+ * Create an unhealthy result from a caught error.
26
+ */
27
+ handleError(error, fallbackMessage) {
28
+ return this.unhealthy(error instanceof Error ? error.message : fallbackMessage);
29
+ }
30
+ /**
31
+ * Create a check result.
32
+ */
33
+ result(status, message, meta) {
34
+ const result = {
35
+ name: this.name,
36
+ status,
37
+ duration: 0
38
+ };
39
+ if (message !== void 0) result.message = message;
40
+ if (meta !== void 0) result.meta = meta;
41
+ return result;
42
+ }
43
+ };
44
+ //#endregion
45
+ //#region src/health/HealthManager.ts
46
+ /**
47
+ * Health check manager.
48
+ */
49
+ var HealthManager = class {
50
+ checks = /* @__PURE__ */ new Map();
51
+ /**
52
+ * Register a health check.
53
+ */
54
+ register(check, options = {}) {
55
+ this.checks.set(check.name, {
56
+ check,
57
+ options: {
58
+ timeout: options.timeout ?? 5e3,
59
+ critical: options.critical ?? false
60
+ }
61
+ });
62
+ return this;
63
+ }
64
+ /**
65
+ * Unregister a health check.
66
+ */
67
+ unregister(name) {
68
+ this.checks.delete(name);
69
+ return this;
70
+ }
71
+ /**
72
+ * Get all registered check names.
73
+ */
74
+ getCheckNames() {
75
+ return Array.from(this.checks.keys());
76
+ }
77
+ /**
78
+ * Run all health checks.
79
+ */
80
+ async check() {
81
+ return this.runChecks(this.getCheckNames());
82
+ }
83
+ /**
84
+ * Run specific health checks.
85
+ */
86
+ async checkOnly(names) {
87
+ const validNames = names.filter((name) => this.checks.has(name));
88
+ return this.runChecks(validNames);
89
+ }
90
+ /**
91
+ * Get a specific check result.
92
+ */
93
+ async getCheck(name) {
94
+ const registered = this.checks.get(name);
95
+ if (!registered) return null;
96
+ return this.runCheck(registered);
97
+ }
98
+ /**
99
+ * Create middleware for health endpoints.
100
+ */
101
+ middleware(options = {}) {
102
+ return async (ctx, next) => {
103
+ const report = options.checks ? await this.checkOnly(options.checks) : await this.check();
104
+ const statusCode = report.status === "healthy" ? 200 : report.status === "degraded" ? 200 : 503;
105
+ ctx.res = ctx.json({
106
+ status: report.status,
107
+ timestamp: report.timestamp.toISOString(),
108
+ ...options.detailed === false ? {} : { checks: report.checks.map((check) => ({
109
+ name: check.name,
110
+ status: check.status,
111
+ message: check.message,
112
+ duration: check.duration,
113
+ meta: check.meta
114
+ })) }
115
+ }, statusCode);
116
+ };
117
+ }
118
+ /**
119
+ * Run the specified checks.
120
+ */
121
+ async runChecks(names) {
122
+ const results = [];
123
+ let overallStatus = "healthy";
124
+ await Promise.all(names.map(async (name) => {
125
+ const registered = this.checks.get(name);
126
+ if (!registered) return;
127
+ const result = await this.runCheck(registered);
128
+ results.push(result);
129
+ if (result.status === "unhealthy") {
130
+ if (registered.options.critical) overallStatus = "unhealthy";
131
+ else if (overallStatus !== "unhealthy") overallStatus = "degraded";
132
+ } else if (result.status === "degraded" && overallStatus === "healthy") overallStatus = "degraded";
133
+ }));
134
+ results.sort((a, b) => a.name.localeCompare(b.name));
135
+ return {
136
+ status: overallStatus,
137
+ timestamp: /* @__PURE__ */ new Date(),
138
+ checks: results
139
+ };
140
+ }
141
+ /**
142
+ * Run a single check with timeout.
143
+ */
144
+ async runCheck(registered) {
145
+ const { check, options } = registered;
146
+ const start = performance.now();
147
+ try {
148
+ const result = await Promise.race([check.check(), this.timeoutPromise(options.timeout)]);
149
+ result.duration = Math.round(performance.now() - start);
150
+ return result;
151
+ } catch (error) {
152
+ const duration = Math.round(performance.now() - start);
153
+ return {
154
+ name: check.name,
155
+ status: "unhealthy",
156
+ message: error instanceof Error ? error.message : "Check failed with error",
157
+ duration
158
+ };
159
+ }
160
+ }
161
+ /**
162
+ * Create a timeout promise.
163
+ */
164
+ timeoutPromise(ms) {
165
+ return new Promise((_, reject) => {
166
+ setTimeout(() => {
167
+ reject(/* @__PURE__ */ new Error(`Health check timed out after ${ms}ms`));
168
+ }, ms);
169
+ });
170
+ }
171
+ };
172
+ /**
173
+ * Create a health manager.
174
+ */
175
+ function createHealthManager() {
176
+ return new HealthManager();
177
+ }
178
+ //#endregion
179
+ //#region src/health/checks/DatabaseCheck.ts
180
+ /**
181
+ * Health check for database connectivity.
182
+ */
183
+ var DatabaseCheck = class extends HealthCheck {
184
+ name;
185
+ db;
186
+ query;
187
+ constructor(db, options = {}) {
188
+ super();
189
+ this.db = db;
190
+ this.name = options.name ?? "database";
191
+ this.query = options.query ?? "SELECT 1";
192
+ }
193
+ async check() {
194
+ try {
195
+ await this.db.query(this.query);
196
+ return this.healthy("Database connection is healthy");
197
+ } catch (error) {
198
+ return this.handleError(error, "Database connection failed");
199
+ }
200
+ }
201
+ };
202
+ //#endregion
203
+ //#region src/health/checks/RedisCheck.ts
204
+ /**
205
+ * Health check for Redis connectivity.
206
+ */
207
+ var RedisCheck = class extends HealthCheck {
208
+ name;
209
+ redis;
210
+ constructor(redis, options = {}) {
211
+ super();
212
+ this.redis = redis;
213
+ this.name = options.name ?? "redis";
214
+ }
215
+ async check() {
216
+ try {
217
+ const response = await this.redis.ping();
218
+ if (response === "PONG") return this.healthy("Redis connection is healthy");
219
+ return this.degraded(`Redis ping returned: ${response}`);
220
+ } catch (error) {
221
+ return this.handleError(error, "Redis connection failed");
222
+ }
223
+ }
224
+ };
225
+ //#endregion
226
+ //#region src/health/checks/CacheCheck.ts
227
+ /**
228
+ * Health check for cache functionality.
229
+ */
230
+ var CacheCheck = class extends HealthCheck {
231
+ name;
232
+ cache;
233
+ testKey;
234
+ constructor(cache, options = {}) {
235
+ super();
236
+ this.cache = cache;
237
+ this.name = options.name ?? "cache";
238
+ this.testKey = options.testKey ?? "__health_check__";
239
+ }
240
+ async check() {
241
+ const testValue = `health_check_${Date.now()}`;
242
+ try {
243
+ await this.cache.put(this.testKey, testValue, 60);
244
+ const retrieved = await this.cache.get(this.testKey);
245
+ await this.cache.forget(this.testKey);
246
+ if (retrieved === testValue) return this.healthy("Cache is functioning correctly");
247
+ return this.degraded(`Cache read/write mismatch: expected "${testValue}", got "${retrieved}"`);
248
+ } catch (error) {
249
+ return this.handleError(error, "Cache operation failed");
250
+ }
251
+ }
252
+ };
253
+ //#endregion
254
+ //#region src/health/checks/StorageCheck.ts
255
+ /**
256
+ * Health check for storage functionality.
257
+ */
258
+ var StorageCheck = class extends HealthCheck {
259
+ name;
260
+ storage;
261
+ testPath;
262
+ constructor(storage, options = {}) {
263
+ super();
264
+ this.storage = storage;
265
+ this.name = options.name ?? "storage";
266
+ this.testPath = options.testPath ?? "__health_check__.txt";
267
+ }
268
+ async check() {
269
+ const testContent = `health_check_${Date.now()}`;
270
+ try {
271
+ await this.storage.put(this.testPath, testContent);
272
+ const retrieved = await this.storage.get(this.testPath);
273
+ await this.storage.delete(this.testPath);
274
+ if (retrieved && retrieved.toString() === testContent) return this.healthy("Storage is functioning correctly");
275
+ return this.degraded("Storage read/write mismatch");
276
+ } catch (error) {
277
+ return this.handleError(error, "Storage operation failed");
278
+ }
279
+ }
280
+ };
281
+ //#endregion
282
+ //#region src/health/checks/MemoryCheck.ts
283
+ /**
284
+ * Health check for memory usage.
285
+ */
286
+ var MemoryCheck = class extends HealthCheck {
287
+ name;
288
+ thresholdMb;
289
+ criticalThresholdMb;
290
+ constructor(options = {}) {
291
+ super();
292
+ this.name = options.name ?? "memory";
293
+ this.thresholdMb = options.thresholdMb ?? 512;
294
+ this.criticalThresholdMb = options.criticalThresholdMb ?? 1024;
295
+ }
296
+ async check() {
297
+ const usage = process.memoryUsage();
298
+ const usedMb = Math.round(usage.heapUsed / 1024 / 1024);
299
+ const meta = {
300
+ usedMb,
301
+ totalMb: Math.round(usage.heapTotal / 1024 / 1024),
302
+ rssMb: Math.round(usage.rss / 1024 / 1024),
303
+ thresholdMb: this.thresholdMb,
304
+ criticalThresholdMb: this.criticalThresholdMb
305
+ };
306
+ if (usedMb >= this.criticalThresholdMb) return this.unhealthy(`Memory usage critical: ${usedMb}MB (threshold: ${this.criticalThresholdMb}MB)`, meta);
307
+ if (usedMb >= this.thresholdMb) return this.degraded(`Memory usage elevated: ${usedMb}MB (threshold: ${this.thresholdMb}MB)`, meta);
308
+ return this.healthy(`Memory usage normal: ${usedMb}MB`, meta);
309
+ }
310
+ };
311
+ //#endregion
312
+ //#region src/health/checks/CustomCheck.ts
313
+ /**
314
+ * Custom health check with callback.
315
+ */
316
+ var CustomCheck = class extends HealthCheck {
317
+ name;
318
+ callback;
319
+ constructor(name, callback) {
320
+ super();
321
+ this.name = name;
322
+ this.callback = callback;
323
+ }
324
+ async check() {
325
+ try {
326
+ const result = await this.callback();
327
+ switch (result.status) {
328
+ case "healthy": return this.healthy(result.message, result.meta);
329
+ case "degraded": return this.degraded(result.message, result.meta);
330
+ case "unhealthy": return this.unhealthy(result.message, result.meta);
331
+ default: return this.unhealthy("Unknown status returned from check");
332
+ }
333
+ } catch (error) {
334
+ return this.unhealthy(error instanceof Error ? error.message : "Custom check failed");
335
+ }
336
+ }
337
+ };
338
+ /**
339
+ * Create a custom health check.
340
+ */
341
+ function customCheck(name, callback) {
342
+ return new CustomCheck(name, callback);
343
+ }
344
+ //#endregion
345
+ export { CacheCheck as a, HealthManager as c, StorageCheck as i, createHealthManager as l, customCheck as n, RedisCheck as o, MemoryCheck as r, DatabaseCheck as s, CustomCheck as t, HealthCheck as u };
@@ -0,0 +1,281 @@
1
+ //#region src/support/stack-frames.ts
2
+ /**
3
+ * Which `(` opens the parenthesized location group at the end of a stack frame.
4
+ *
5
+ * That one question is all the package's two frame readers agree on — the debug
6
+ * error page's `parseStackTrace` and the hot-reload registry's
7
+ * `parseFrameLocation`. Everything after it differs on purpose: peeling
8
+ * `:line[:column]` off the right (the page requires a column and keeps the
9
+ * function name; the registry accepts a bare `:line`), and deciding which
10
+ * locations are worth keeping at all (the registry rejects `eval` groups and
11
+ * synthetic paths, because keying an owner on text that is not a path is worse
12
+ * than not keying it; the page is happy to display whatever it was handed).
13
+ * Keep every parenthesis fix here so those two cannot drift.
14
+ *
15
+ * A third reader, `packages/orm/src/active-connections.ts`, carries a copy of
16
+ * the function below whose *body* is identical character for character; only
17
+ * the prose around it differs, to speak about connections rather than frames.
18
+ * That package must not import this one, so the two are kept in step by hand —
19
+ * fix both, or neither.
20
+ */
21
+ const OPEN_PAREN = 40;
22
+ const CLOSE_PAREN = 41;
23
+ /** The characters a stack frame can never span, so a scan stops at them. */
24
+ function isLineTerminator(code) {
25
+ return code === 10 || code === 13 || code === 8232 || code === 8233;
26
+ }
27
+ /**
28
+ * The index of the `(` that matches the `)` at `closeIndex`, or `undefined`
29
+ * when the frame carries no usable `(` at all.
30
+ *
31
+ * `closeIndex` is a parameter rather than derived here because each caller
32
+ * already knows where its frame ends and gets there differently — two trim a
33
+ * copy of the frame, the ORM's twin keeps an `end` offset to avoid allocating
34
+ * one. It must point at the frame's final `)`; anything else is rejected.
35
+ *
36
+ * Neither the leftmost nor the rightmost `(` is right in general. A path may
37
+ * contain one — `at fn (/app (old)/x.ts:1:2)` needs the outer, *leftmost* pair
38
+ * — and so may the function name in front of it — `at weird (name)
39
+ * (/app/x.ts:1:2)` needs the outer, *rightmost* pair. Depth is what actually
40
+ * tells the two apart; a fixed "first" or "last" gets one of them wrong, and a
41
+ * frame carrying both — `at weird (name) (/app (old)/x.ts:1:2)`, which is one
42
+ * developer's checkout directory away from ordinary — is misread by either.
43
+ *
44
+ * A scan is also the only form that stays linear. Lazily matching from the
45
+ * leftmost `(` retries the whole suffix at every parenthesis, which is
46
+ * quadratic on a frame carrying many unmatched ones. Characters are compared by
47
+ * code rather than tested against a pattern for the same reason the patterns
48
+ * went: this loop runs over every character of every frame, and the one input
49
+ * whose length nothing bounds is a frame — an error message can embed
50
+ * request-derived text, and a continuation line of one that starts `at ` and
51
+ * ends `)` is scanned in full.
52
+ *
53
+ * Depth alone would reject a frame whose location holds an *unmatched* `)`, as
54
+ * `/app/name).ts` or a URL ending `?label=)` does — the scan runs off the front
55
+ * still owing a paren, and the frame is dropped rather than displayed. So the
56
+ * leftmost `(` the scan passed is kept as a fallback for exactly that case.
57
+ * Only frames the depth rule rejects outright can reach it, so it is never
58
+ * worse than depth alone, and it is the reading that keeps such a path whole.
59
+ *
60
+ * The scan stops at a line terminator: a path could never span one, so neither
61
+ * a balanced `(` nor the fallback may come from the far side of a break.
62
+ */
63
+ function matchingOpenParen(frame, closeIndex) {
64
+ if (frame.charCodeAt(closeIndex) !== CLOSE_PAREN) return;
65
+ let depth = 0;
66
+ let leftmostOpen;
67
+ for (let index = closeIndex; index >= 0; index--) {
68
+ const code = frame.charCodeAt(index);
69
+ if (isLineTerminator(code)) break;
70
+ if (code === CLOSE_PAREN) depth++;
71
+ else if (code === OPEN_PAREN) {
72
+ if (--depth === 0) return index;
73
+ leftmostOpen = index;
74
+ }
75
+ }
76
+ return leftmostOpen;
77
+ }
78
+ //#endregion
79
+ //#region src/hot-reload/hot-disposables.ts
80
+ /**
81
+ * Stops the timers a previous module evaluation left running.
82
+ *
83
+ * `bun --hot` re-runs the module graph inside the same process. Anything the
84
+ * previous evaluation built is dropped on the floor — but a `setInterval`
85
+ * callback keeps its owner reachable, so a store, manager, or scheduler that
86
+ * nothing references any more goes on firing forever. One extra timer per
87
+ * reload, each one retaining the dead object graph behind it.
88
+ *
89
+ * `globalThis` survives re-evaluation, so it is where the previous owner's
90
+ * teardown is parked — the same storage `Application.listen()` uses for the Bun
91
+ * and Vite dev servers, and the same approach `@guren/orm` uses for database
92
+ * connections. Bun does not expose `import.meta.hot` to `bun --hot` (checked on
93
+ * 1.3.14), so there is no reload hook to register with instead.
94
+ *
95
+ * This is deliberately not the ORM's registry with the names changed. Closing a
96
+ * connection is an async operation that can hang on a wedged socket, which is
97
+ * what forces that module's serialized claims and teardown timeout. Every
98
+ * teardown here is synchronous — `clearInterval`, and the `destroy()`/`stop()`
99
+ * methods wrapping it — so a claim can simply run the previous teardown inline
100
+ * and be done. Sharing the registries would buy machinery neither side needs in
101
+ * the same shape.
102
+ *
103
+ * Its twin is `packages/orm/src/active-connections.ts`. `parseFrameLocation` and
104
+ * `describeCallerFile`'s walk past a synthetic frame follow the same rule in
105
+ * both — a fix to either has to be carried to the other by hand. That has
106
+ * already failed once: this walk predates the ORM's, and the ORM kept keying
107
+ * handles to `unknown` in the meantime. Nothing forces the duplication —
108
+ * `@guren/server` already depends on `@guren/orm`, so this layer could live
109
+ * there and be imported here — it is only that the shared part is small next to
110
+ * the two packages' very different teardown semantics (see above). Extract the
111
+ * rest if it drifts again.
112
+ *
113
+ * One piece already went that way, for a reason worth recording: the debug error
114
+ * page turned out to read frames too, and had written its own, wrong version of
115
+ * the paren rule. That scan now lives in `../support/stack-frames`, imported by
116
+ * both readers in this package — the ORM's copy of it is still hand-synced like
117
+ * everything else here.
118
+ *
119
+ * An owner is identified by the file that built it plus a discriminator, so it
120
+ * is replaced only by a later evaluation of that same file. Keying on the exact
121
+ * line would be more precise, but a line number changes the moment anything
122
+ * above it does — adding an import would orphan the previous entry and leak the
123
+ * timer it was holding, during the very workflow this exists to fix. The file is
124
+ * stable across every edit that isn't a rename.
125
+ */
126
+ const REGISTRY_KEY = Symbol.for("guren.server.hotDisposables");
127
+ function getRegistry() {
128
+ const scope = globalThis;
129
+ return scope[REGISTRY_KEY] ??= /* @__PURE__ */ new Map();
130
+ }
131
+ /**
132
+ * Whether modules can be re-evaluated in this process.
133
+ *
134
+ * `bun --watch` restarts the process instead, which drops every timer with it,
135
+ * so `--hot` is the only mode that leaks. Everywhere else — production, tests,
136
+ * CLI commands, serverless — nothing is ever torn down automatically.
137
+ *
138
+ * Exported so callers can skip building the `Error` whose stack identifies them:
139
+ * capturing one formats the whole stack into a string, and outside `--hot` it
140
+ * would only be thrown away.
141
+ */
142
+ function isHotReloadRuntime() {
143
+ return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
144
+ }
145
+ /**
146
+ * Paths the engine reports for code that has no source location.
147
+ *
148
+ * A class that runs code without declaring a constructor — a subclass, or any
149
+ * class carrying a field initializer — gets an implicit one, and JSC reports it
150
+ * as `at new Owner (unknown:1:28)`: a frame sitting between the code that ran
151
+ * and the code that actually wrote `new`. Taking it would key every such owner
152
+ * in the process to the string `unknown`, collapsing owners built in different
153
+ * files into one slot where each new one stops the last. `native` shows up the
154
+ * same way for built-ins (`at map (native:1:11)`).
155
+ */
156
+ const SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set([
157
+ "unknown",
158
+ "native",
159
+ "<anonymous>"
160
+ ]);
161
+ const LOCATION_SUFFIX = /:\d+(?::\d+)?$/;
162
+ /** Both match one character, so neither can backtrack the way `\s*` in a pattern can. */
163
+ const WHITESPACE = /\s/;
164
+ const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
165
+ /**
166
+ * What a bare `at …` frame carries, with surrounding whitespace dropped.
167
+ *
168
+ * Scanned rather than captured with `/^\s*at\s+(.+?)\s*$/`, whose lazy body and
169
+ * greedy tail both laid claim to the same spaces: a frame padded with a run of
170
+ * them took time cubic in the run's length before concluding it did not match.
171
+ *
172
+ * One case is read differently on purpose. Where the frame is `at` and nothing
173
+ * but whitespace, the pattern handed back a single space as the body; this
174
+ * rejects it. The two agree at the only boundary that matters, because a body
175
+ * carrying no `:line` is discarded by the caller either way.
176
+ */
177
+ function parseBareFrame(frame) {
178
+ const end = frame.trimEnd().length;
179
+ let cursor = 0;
180
+ while (cursor < end && WHITESPACE.test(frame[cursor])) cursor += 1;
181
+ if (!frame.startsWith("at", cursor)) return void 0;
182
+ const afterAt = cursor + 2;
183
+ let start = afterAt;
184
+ while (start < end && WHITESPACE.test(frame[start])) start += 1;
185
+ if (start === afterAt) return void 0;
186
+ const body = frame.slice(start, end);
187
+ return LINE_TERMINATOR.test(body) ? void 0 : body;
188
+ }
189
+ /**
190
+ * The text inside the parentheses that close a frame, or `undefined` when the
191
+ * frame does not end in one.
192
+ *
193
+ * Which `(` opens them is `matchingOpenParen`'s problem — both the path and the
194
+ * function name in front of it may contain parentheses, and neither end of the
195
+ * frame is the right place to look in general.
196
+ */
197
+ function parenthesizedLocation(frame) {
198
+ const trimmed = frame.trimEnd();
199
+ if (!trimmed.endsWith(")")) return;
200
+ const open = matchingOpenParen(trimmed, trimmed.length - 1);
201
+ return open === void 0 ? void 0 : trimmed.slice(open + 1, -1);
202
+ }
203
+ /**
204
+ * The path a single stack frame points at, without its line and column.
205
+ *
206
+ * The parenthesized shape is read first because its parentheses bound the path;
207
+ * the bare `at /path/file.ts:1:2` can only be bounded by whitespace, which would
208
+ * truncate `/Users/me/My Projects/app.ts` to `Projects/app.ts`. Nothing
209
+ * constrains what the path may contain — spaces and parentheses are both
210
+ * ordinary in a macOS directory name.
211
+ *
212
+ * The trailing `:line` is what proves this is a location at all rather than a
213
+ * bare function name, so `at native` and `at <anonymous>` yield nothing. An
214
+ * `eval` group is rejected outright: V8 nests the real location inside
215
+ * `eval at fn (/app/x.ts:1:2), <anonymous>:1:1`, and keying an owner on text
216
+ * that is not a path is worse than not keying it — an owner with no key is left
217
+ * alone, which is the safe failure.
218
+ */
219
+ function parseFrameLocation(frame) {
220
+ const location = parenthesizedLocation(frame) ?? parseBareFrame(frame);
221
+ if (!location || location.startsWith("eval at ") || !LOCATION_SUFFIX.test(location)) return;
222
+ return location.replace(LOCATION_SUFFIX, "");
223
+ }
224
+ /**
225
+ * The file that built the timer owner.
226
+ *
227
+ * `stack` must come from an `Error` constructed inside the constructor or
228
+ * factory itself, so frame 0 is `Error`, frame 1 is that function, and frame 2
229
+ * is the caller — or the first frame after it that names a real file, since the
230
+ * engine may have synthesized the frames in between. Only the path is kept: a
231
+ * reload re-runs the same file, but not necessarily at the same line.
232
+ */
233
+ function describeCallerFile(stack) {
234
+ for (const frame of stack?.split("\n").slice(2) ?? []) {
235
+ const path = parseFrameLocation(frame);
236
+ if (path && !SYNTHETIC_FRAME_PATHS.has(path)) return path;
237
+ }
238
+ }
239
+ /**
240
+ * Identity for a timer owner across hot reloads, or `undefined` when the owner
241
+ * must be left alone.
242
+ *
243
+ * `target` separates owners that share a call site — the name of a cache store,
244
+ * say — so one module building several does not collapse them into a slot where
245
+ * each new one stops the last.
246
+ */
247
+ function hotReloadKey(scope, stack, target) {
248
+ if (!isHotReloadRuntime()) return;
249
+ const callerFile = describeCallerFile(stack);
250
+ return callerFile ? `${scope}|${callerFile}|${target}` : void 0;
251
+ }
252
+ /**
253
+ * Records `dispose` as the live owner for this identity, stops whichever owner
254
+ * held it before, and hands back the claim so the new owner can give it up.
255
+ *
256
+ * Returns `undefined` outside `--hot`, or when the stack does not name a caller
257
+ * — the owner is then simply left alone, which is how things behaved before this
258
+ * registry existed.
259
+ *
260
+ * A teardown that throws is reported and swallowed: the replacement has already
261
+ * been built by the time this runs, and refusing to register it would leak the
262
+ * very timer this is here to stop.
263
+ */
264
+ function claimHotDisposable(scope, stack, target, dispose) {
265
+ const key = hotReloadKey(scope, stack, target);
266
+ if (!key) return;
267
+ const registry = getRegistry();
268
+ const previous = registry.get(key);
269
+ registry.delete(key);
270
+ if (previous && previous !== dispose) try {
271
+ previous();
272
+ } catch (error) {
273
+ console.warn("[guren] Failed to stop the previous hot-reload disposable:", error);
274
+ }
275
+ registry.set(key, dispose);
276
+ return { release() {
277
+ if (registry.get(key) === dispose) registry.delete(key);
278
+ } };
279
+ }
280
+ //#endregion
281
+ export { isHotReloadRuntime as n, matchingOpenParen as r, claimHotDisposable as t };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Test-only helpers for the hot-reload registry.
3
3
  *
4
- * Not reachable from any tsup entry point, so it never ships — it lives beside
4
+ * Not reachable from any tsdown entry point, so it never ships — it lives beside
5
5
  * the code it exercises because both test files in this directory need it and
6
6
  * `@guren/server` has no shared test-support module.
7
7
  */
@@ -2,8 +2,28 @@ import type { ResourceData, ResourceClass } from './types.js';
2
2
  /**
3
3
  * Abstract base class for API resources.
4
4
  * Transforms model data into API response format.
5
+ *
6
+ * `TData` names the payload `toArray()` builds, so `toJSON()` reports it too:
7
+ * `class PostResource extends Resource<PostRecord, PostResourceData>`. Without
8
+ * it every subclass had to restate the payload in an override whose only body
9
+ * was `return super.toJSON() as PostResourceData` — a cast that says nothing a
10
+ * type parameter cannot, and one nothing checks against the `toArray()` right
11
+ * above it.
12
+ *
13
+ * It defaults to `ResourceData` so `Resource<T>` and those overrides keep
14
+ * compiling: an override narrowing the return type stays assignable to the
15
+ * base. The polymorphic alternative (`toJSON(): ReturnType<this['toArray']>`)
16
+ * needs no parameter at all but rejects every existing override, which is a
17
+ * breaking change for code the scaffolds have been emitting all along.
18
+ *
19
+ * `TData` is a claim about `toArray()`, not about `toJSON()`'s every key:
20
+ * `additional()` takes arbitrary `ResourceData` and is spread *after* the
21
+ * payload, so a key that collides overwrites a typed field while the return
22
+ * type still reads `TData`. That hole is not new — it is what the
23
+ * `super.toJSON() as PostResourceData` override asserted past — but the type
24
+ * parameter does not close it. `additional()` is for keys beside the payload.
5
25
  */
6
- export declare abstract class Resource<T> {
26
+ export declare abstract class Resource<T, TData extends ResourceData = ResourceData> {
7
27
  /**
8
28
  * The underlying resource.
9
29
  */
@@ -17,11 +37,11 @@ export declare abstract class Resource<T> {
17
37
  * Transform the resource into an array/object.
18
38
  * Must be implemented by subclasses.
19
39
  */
20
- abstract toArray(): ResourceData;
40
+ abstract toArray(): TData;
21
41
  /**
22
42
  * Transform the resource to JSON.
23
43
  */
24
- toJSON(): ResourceData;
44
+ toJSON(): TData;
25
45
  /**
26
46
  * Add additional data to the resource.
27
47
  */