@guren/server 2.25.0 → 2.26.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 (80) hide show
  1. package/README.md +42 -0
  2. package/dist/{Gate-YOt54xGF.js → Gate-BL_zW82W.js} +1 -1
  3. package/dist/{Job-COMzBNOL.js → Job-DsFMcXVk.js} +35 -3
  4. package/dist/{Resource-BdYd4J9a.js → Resource-gki0_2B6.js} +172 -37
  5. package/dist/agent/scopes.d.ts +1 -3
  6. package/dist/auth/email-verification.d.ts +6 -0
  7. package/dist/auth/index.js +1 -1
  8. package/dist/auth/password-reset.d.ts +8 -2
  9. package/dist/{auth-vFeem6uM.js → auth-DiyWALZT.js} +38 -9
  10. package/dist/authorization/index.js +2 -2
  11. package/dist/{authorization-BLhwA2Yh.js → authorization-E6X6Y-B6.js} +1 -1
  12. package/dist/broadcasting/index.js +1 -1
  13. package/dist/{broadcasting-BUBCPCnu.js → broadcasting-D0vMkKcq.js} +1 -1
  14. package/dist/cache/index.js +1 -1
  15. package/dist/cache/stores/FileStore.d.ts +2 -0
  16. package/dist/cache/stores/MemoryStore.d.ts +1 -0
  17. package/dist/cache/stores/RedisStore.d.ts +1 -0
  18. package/dist/cache/types.d.ts +2 -0
  19. package/dist/{cache-93n2PCnB.js → cache-DcnRufMe.js} +94 -25
  20. package/dist/contained-path-BkNSBljW.js +78 -0
  21. package/dist/container/Container.d.ts +6 -2
  22. package/dist/container/defineModule.d.ts +10 -0
  23. package/dist/{default-application-D5ezhhiV.js → default-application-DWwscxfW.js} +14 -18
  24. package/dist/encryption/index.js +1 -1
  25. package/dist/{encryption-D1dxfMqD.js → encryption-CWK5l22W.js} +1 -1
  26. package/dist/events/EventManager.d.ts +2 -0
  27. package/dist/events/index.js +1 -1
  28. package/dist/{events-c94CdUFc.js → events-DQavGm8W.js} +20 -7
  29. package/dist/health/HealthManager.d.ts +0 -1
  30. package/dist/health/index.js +1 -1
  31. package/dist/{health-CB0oS_UE.js → health-Bg0Xj3aD.js} +8 -8
  32. package/dist/http/Application.d.ts +12 -1
  33. package/dist/http/middleware/rate-limit.d.ts +1 -4
  34. package/dist/i18n/index.js +1 -1
  35. package/dist/{i18n-DqcRD4qL.js → i18n-DmMKcbqj.js} +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.js +61 -50
  38. package/dist/internal/app-conventions.d.ts +6 -0
  39. package/dist/internal/app-conventions.js +9 -0
  40. package/dist/internal/testing.d.ts +1 -1
  41. package/dist/internal/testing.js +2 -2
  42. package/dist/lambda/index.js +66 -28
  43. package/dist/logging/index.js +1 -1
  44. package/dist/{logging-YbKmbAd7.js → logging-Ci0mBk5k.js} +1 -1
  45. package/dist/mail/index.js +1 -1
  46. package/dist/{mail-uRBrUl9q.js → mail-CI2Kfe8P.js} +2 -2
  47. package/dist/mvc/Controller.d.ts +3 -2
  48. package/dist/mvc/inertia/InertiaEngine.d.ts +31 -0
  49. package/dist/mvc/inertia/props.d.ts +71 -0
  50. package/dist/notifications/index.js +1 -1
  51. package/dist/notifications/registry.d.ts +2 -2
  52. package/dist/{notifications-LHuujttf.js → notifications-Bp2uamzD.js} +7 -5
  53. package/dist/providers/ConfigServiceProvider.d.ts +5 -5
  54. package/dist/queue/Job.d.ts +5 -0
  55. package/dist/queue/Worker.d.ts +6 -1
  56. package/dist/queue/drivers/RedisDriver.d.ts +4 -2
  57. package/dist/queue/drivers/SqsDriver.d.ts +31 -2
  58. package/dist/queue/drivers/redis-queue-scripts.d.ts +83 -0
  59. package/dist/queue/index.js +2 -2
  60. package/dist/queue/serialize.d.ts +7 -0
  61. package/dist/queue/types.d.ts +13 -2
  62. package/dist/{queue-BiBn5Sff.js → queue-Bo4Q857L.js} +294 -125
  63. package/dist/redis/RedisEmailVerificationStore.d.ts +2 -0
  64. package/dist/redis/RedisPasswordResetStore.d.ts +2 -0
  65. package/dist/redis/auth-token-scripts.d.ts +4 -0
  66. package/dist/redis/index.js +50 -0
  67. package/dist/runtime/index.js +3 -36
  68. package/dist/scheduling/ScheduledTask.d.ts +2 -1
  69. package/dist/scheduling/index.js +1 -1
  70. package/dist/{scheduling-DhYfbJFj.js → scheduling-DNV5tj44.js} +32 -38
  71. package/dist/serialize-CKXek0Tr.js +17 -0
  72. package/dist/storage/drivers/LocalDriver.d.ts +15 -0
  73. package/dist/storage/index.js +1 -1
  74. package/dist/storage/url-path.d.ts +2 -0
  75. package/dist/{storage-6HLaUf9j.js → storage-wFsUJHZW.js} +78 -28
  76. package/dist/support/contained-path.d.ts +8 -0
  77. package/dist/support/registry-collision.d.ts +12 -0
  78. package/dist/{vite-manifest-C5kqRoBV.js → vite-manifest-DlU94f3Z.js} +2 -2
  79. package/package.json +20 -2
  80. package/dist/trim-slashes-BLY9hKAa.js +0 -22
@@ -1,8 +1,8 @@
1
1
  import { r as isPromiseLike } from "./Logger-DWXdtLSJ.js";
2
2
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
3
- import { createHash } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { dirname, join } from "node:path";
5
- import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, readdir, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
6
6
  import { existsSync } from "node:fs";
7
7
  //#region src/redis/lazy-client.ts
8
8
  /**
@@ -43,8 +43,8 @@ var MemoryStore = class {
43
43
  isExpired(item) {
44
44
  return item.expiresAt !== null && item.expiresAt <= this.now();
45
45
  }
46
- evictIfNeeded() {
47
- if (this.cache.size >= this.maxSize) {
46
+ evictIfNeeded(key) {
47
+ if (!this.cache.has(key) && this.cache.size >= this.maxSize) {
48
48
  const firstKey = this.cache.keys().next().value;
49
49
  if (firstKey !== void 0) this.cache.delete(firstKey);
50
50
  }
@@ -59,13 +59,23 @@ var MemoryStore = class {
59
59
  return item.value;
60
60
  }
61
61
  async set(key, value, ttl) {
62
- this.evictIfNeeded();
62
+ this.evictIfNeeded(key);
63
63
  const expiresAt = ttl ? this.now() + ttl * 1e3 : null;
64
64
  this.cache.set(key, {
65
65
  value,
66
66
  expiresAt
67
67
  });
68
68
  }
69
+ async add(key, value) {
70
+ const item = this.cache.get(key);
71
+ if (item && !this.isExpired(item)) return false;
72
+ this.evictIfNeeded(key);
73
+ this.cache.set(key, {
74
+ value,
75
+ expiresAt: null
76
+ });
77
+ return true;
78
+ }
69
79
  async has(key) {
70
80
  const item = this.cache.get(key);
71
81
  if (!item) return false;
@@ -82,10 +92,14 @@ var MemoryStore = class {
82
92
  this.cache.clear();
83
93
  }
84
94
  async increment(key, value = 1) {
85
- const newValue = (await this.get(key) ?? 0) + value;
86
95
  const item = this.cache.get(key);
87
- const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3)) : void 0;
88
- await this.set(key, newValue, ttl);
96
+ const active = item && !this.isExpired(item) ? item : void 0;
97
+ const newValue = (active?.value ?? 0) + value;
98
+ this.evictIfNeeded(key);
99
+ this.cache.set(key, {
100
+ value: newValue,
101
+ expiresAt: active?.expiresAt ?? null
102
+ });
89
103
  return newValue;
90
104
  }
91
105
  async decrement(key, value = 1) {
@@ -173,6 +187,9 @@ var RedisStore = class {
173
187
  if (ttl) await this.client.setex(prefixedKey, ttl, serialized);
174
188
  else await this.client.set(prefixedKey, serialized);
175
189
  }
190
+ async add(key, value) {
191
+ return await this.client.set(this.prefixKey(key), this.serialize(value), "NX") === "OK";
192
+ }
176
193
  async has(key) {
177
194
  return await this.client.exists(this.prefixKey(key)) > 0;
178
195
  }
@@ -237,6 +254,10 @@ var RedisStore = class {
237
254
  };
238
255
  //#endregion
239
256
  //#region src/cache/stores/FileStore.ts
257
+ const LOCK_TIMEOUT_MS = 5e3;
258
+ function ignoreMissing(error) {
259
+ if (error.code !== "ENOENT") throw error;
260
+ }
240
261
  /** File-based cache store. */
241
262
  var FileStore = class {
242
263
  basePath;
@@ -266,7 +287,36 @@ var FileStore = class {
266
287
  }
267
288
  async writeCacheFile(filePath, item) {
268
289
  await this.ensureDirectory(filePath);
269
- await writeFile(filePath, JSON.stringify(item), "utf-8");
290
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
291
+ try {
292
+ await writeFile(temporary, JSON.stringify(item), "utf-8");
293
+ await rename(temporary, filePath);
294
+ } catch (error) {
295
+ await unlink(temporary).catch(() => void 0);
296
+ throw error;
297
+ }
298
+ }
299
+ async withFileLock(filePath, callback) {
300
+ await this.ensureDirectory(filePath);
301
+ const lockPath = `${filePath}.lock`;
302
+ let deadline = Date.now() + LOCK_TIMEOUT_MS;
303
+ for (;;) try {
304
+ await mkdir(lockPath);
305
+ break;
306
+ } catch (error) {
307
+ if (error.code !== "EEXIST") throw error;
308
+ if (Date.now() >= deadline) {
309
+ await rmdir(lockPath).catch(ignoreMissing);
310
+ deadline = Date.now() + LOCK_TIMEOUT_MS;
311
+ continue;
312
+ }
313
+ await new Promise((resolve) => setTimeout(resolve, 5));
314
+ }
315
+ try {
316
+ return await callback();
317
+ } finally {
318
+ await rmdir(lockPath).catch(ignoreMissing);
319
+ }
270
320
  }
271
321
  async deleteCacheFile(filePath) {
272
322
  try {
@@ -297,6 +347,18 @@ var FileStore = class {
297
347
  expiresAt
298
348
  });
299
349
  }
350
+ async add(key, value) {
351
+ const filePath = this.getFilePath(key);
352
+ return this.withFileLock(filePath, async () => {
353
+ const item = await this.readCacheFile(filePath);
354
+ if (item && !this.isExpired(item)) return false;
355
+ await this.writeCacheFile(filePath, {
356
+ value,
357
+ expiresAt: null
358
+ });
359
+ return true;
360
+ });
361
+ }
300
362
  async has(key) {
301
363
  return await this.get(key) !== null;
302
364
  }
@@ -313,12 +375,17 @@ var FileStore = class {
313
375
  await mkdir(this.basePath, { recursive: true });
314
376
  }
315
377
  async increment(key, value = 1) {
316
- const newValue = (await this.get(key) ?? 0) + value;
317
378
  const filePath = this.getFilePath(key);
318
- const item = await this.readCacheFile(filePath);
319
- const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3)) : void 0;
320
- await this.set(key, newValue, ttl);
321
- return newValue;
379
+ return this.withFileLock(filePath, async () => {
380
+ const item = await this.readCacheFile(filePath);
381
+ const active = item && !this.isExpired(item) ? item : null;
382
+ const newValue = (active?.value ?? 0) + value;
383
+ await this.writeCacheFile(filePath, {
384
+ value: newValue,
385
+ expiresAt: active?.expiresAt ?? null
386
+ });
387
+ return newValue;
388
+ });
322
389
  }
323
390
  async decrement(key, value = 1) {
324
391
  return this.increment(key, -value);
@@ -380,10 +447,7 @@ var FileStore = class {
380
447
  if (!file.endsWith(this.extension)) continue;
381
448
  const filePath = join(subdirPath, file);
382
449
  const item = await this.readCacheFile(filePath);
383
- if (item && this.isExpired(item)) {
384
- await this.deleteCacheFile(filePath);
385
- cleaned++;
386
- }
450
+ if (item && this.isExpired(item) && await this.deleteCacheFile(filePath)) cleaned++;
387
451
  }
388
452
  }
389
453
  return cleaned;
@@ -410,8 +474,14 @@ var TaggedCache = class {
410
474
  const tagKey = `${this.tagSetPrefix}${tag}`;
411
475
  let namespace = await this.store.get(tagKey);
412
476
  if (!namespace) {
413
- namespace = this.generateNamespace();
414
- await this.store.set(tagKey, namespace);
477
+ const proposed = this.generateNamespace();
478
+ if (this.store.add) {
479
+ namespace = await this.store.add(tagKey, proposed) ? proposed : await this.store.get(tagKey);
480
+ if (!namespace) throw new Error("Tag namespace was evicted during initialization; retry the cache operation.");
481
+ } else {
482
+ await this.store.set(tagKey, proposed);
483
+ namespace = proposed;
484
+ }
415
485
  }
416
486
  namespaces.push(namespace);
417
487
  }
@@ -423,8 +493,7 @@ var TaggedCache = class {
423
493
  async taggedKey(key) {
424
494
  return `tagged:${await this.getTagNamespace()}:${key}`;
425
495
  }
426
- async trackKey(key) {
427
- const taggedKey = await this.taggedKey(key);
496
+ async trackKey(taggedKey) {
428
497
  for (const tag of this.tags) {
429
498
  const setKey = `${this.tagSetPrefix}${tag}:keys`;
430
499
  const keys = await this.store.get(setKey) ?? [];
@@ -441,7 +510,7 @@ var TaggedCache = class {
441
510
  async set(key, value, ttl) {
442
511
  const taggedKey = await this.taggedKey(key);
443
512
  await this.store.set(taggedKey, value, ttl);
444
- await this.trackKey(key);
513
+ await this.trackKey(taggedKey);
445
514
  }
446
515
  async has(key) {
447
516
  const taggedKey = await this.taggedKey(key);
@@ -456,12 +525,12 @@ var TaggedCache = class {
456
525
  }
457
526
  async increment(key, value = 1) {
458
527
  const taggedKey = await this.taggedKey(key);
459
- await this.trackKey(key);
528
+ await this.trackKey(taggedKey);
460
529
  return this.store.increment(taggedKey, value);
461
530
  }
462
531
  async decrement(key, value = 1) {
463
532
  const taggedKey = await this.taggedKey(key);
464
- await this.trackKey(key);
533
+ await this.trackKey(taggedKey);
465
534
  return this.store.decrement(taggedKey, value);
466
535
  }
467
536
  async remember(key, ttl, callback) {
@@ -0,0 +1,78 @@
1
+ import { basename, dirname, join, sep } from "node:path";
2
+ import { realpath } from "node:fs/promises";
3
+ //#region src/support/trim-slashes.ts
4
+ /**
5
+ * No regex: patterns like `/\/+$/` backtrack quadratically on long slash runs
6
+ * mid-string, and several call sites feed request-derived paths.
7
+ *
8
+ * Twins that cannot import this module: `@guren/cli` (`src/utils.ts`) and
9
+ * `@guren/plugin-cloudflare` (`src/storage/R2Driver.ts`) — keep them in step.
10
+ */
11
+ function trimTrailingSlashes(value) {
12
+ let end = value.length;
13
+ while (end > 0 && value[end - 1] === "/") end--;
14
+ return value.slice(0, end);
15
+ }
16
+ function trimSlashes(value) {
17
+ let start = 0;
18
+ let end = value.length;
19
+ while (start < end && value[start] === "/") start++;
20
+ while (end > start && value[end - 1] === "/") end--;
21
+ return value.slice(start, end);
22
+ }
23
+ //#endregion
24
+ //#region src/support/contained-path.ts
25
+ /**
26
+ * Lexical containment. The trailing separator keeps out a sibling whose name
27
+ * merely extends the root's (`…/inertia` vs `…/inertia-secrets`) and rejects an
28
+ * absolute `candidate`, which `resolve()` returns verbatim. Not sufficient
29
+ * alone: `resolve()` collapses `..` without following symlinks, so use
30
+ * {@link isRealPathWithin} before reading the file.
31
+ */
32
+ function isPathWithin(root, candidate) {
33
+ return candidate.startsWith(root.endsWith(sep) ? root : root + sep);
34
+ }
35
+ /**
36
+ * Containment once both sides are canonicalized. Every reader downstream
37
+ * (`Bun.file().text()`, `new Response(file)`) follows symlinks, so a lexical
38
+ * check alone accepts `<root>/link/secret`. *Both* sides, because a root
39
+ * reached through a symlink is routine (macOS `/var` → `/private/var`) and
40
+ * doing only the candidate would 404 every asset such an app serves.
41
+ */
42
+ async function isRealPathWithin(root, candidate) {
43
+ if (!isPathWithin(root, candidate)) return false;
44
+ const [realRoot, realCandidate] = await Promise.all([canonicalize(root), canonicalize(candidate)]);
45
+ if (!realRoot || !realCandidate) return false;
46
+ return isPathWithin(realRoot, realCandidate);
47
+ }
48
+ async function canonicalize(path) {
49
+ try {
50
+ return await realpath(path);
51
+ } catch {
52
+ return;
53
+ }
54
+ }
55
+ /**
56
+ * The canonical form of a path that need not exist: the deepest ancestor that
57
+ * resolves is canonicalized and the missing tail rejoined, so a caller can
58
+ * judge where a write would land. `undefined` when the path cannot be resolved
59
+ * at all — a link cycle, a directory that will not open — which a containment
60
+ * check must treat as out of bounds rather than as inside.
61
+ */
62
+ async function realPathOfNearestExisting(path) {
63
+ const missing = [];
64
+ let current = path;
65
+ while (true) {
66
+ try {
67
+ return join(await realpath(current), ...missing);
68
+ } catch (error) {
69
+ if (error.code !== "ENOENT") return void 0;
70
+ }
71
+ const parent = dirname(current);
72
+ if (parent === current) return void 0;
73
+ missing.unshift(basename(current));
74
+ current = parent;
75
+ }
76
+ }
77
+ //#endregion
78
+ export { trimTrailingSlashes as a, trimSlashes as i, isRealPathWithin as n, realPathOfNearestExisting as r, isPathWithin as t };
@@ -10,7 +10,7 @@ export declare class Container {
10
10
  protected tags: Map<string, Set<string>>;
11
11
  protected contextualBindings: ContextualBinding[];
12
12
  protected resolvingStack: string[];
13
- protected scopedInstances: Map<string, unknown>[];
13
+ private scope?;
14
14
  protected fakes: Map<string, unknown>;
15
15
  /**
16
16
  * @internal Installed by ProviderManager once every eager provider has booted.
@@ -47,7 +47,11 @@ export declare class Container {
47
47
  tag(keys: string[], tagName: string): this;
48
48
  tagged<T = unknown>(tagName: string): T[];
49
49
  when(concrete: string): ContextualBindingBuilder;
50
- /** Services resolved inside the callback are cached for the scope and released when it ends. */
50
+ /**
51
+ * Services resolved inside the callback are cached for the scope. The cache lives
52
+ * as long as the async context: work detached inside the scope (a timer, an
53
+ * un-awaited promise) keeps it and every cached instance reachable.
54
+ */
51
55
  scoped<T>(callback: () => T): T;
52
56
  scopedAsync<T>(callback: () => Promise<T>): Promise<T>;
53
57
  /**
@@ -1,3 +1,4 @@
1
+ import type { ConfigDefinition } from '../config/define.js';
1
2
  import type { CommandClass } from '../console/types.js';
2
3
  import type { Router } from '../mvc/Router.js';
3
4
  import type { ServiceProviderConstructor } from './ServiceProvider.js';
@@ -26,6 +27,13 @@ export interface ModuleDefinition {
26
27
  * explicit registration keeps a bundled deployment resolving the same set.
27
28
  */
28
29
  commands?: CommandClass[];
30
+ /**
31
+ * Config definitions the module owns (`modules/<name>/config/<key>.ts`),
32
+ * bound after `createApp({ config })` in `modules` order. Keys share the
33
+ * application's one container, so a key the app or another module also
34
+ * defines fails the boot, naming both.
35
+ */
36
+ config?: ReadonlyArray<ConfigDefinition>;
29
37
  }
30
38
  /**
31
39
  * A module as `Application` consumes it: `providers` and `commands` normalized
@@ -37,6 +45,8 @@ export interface GurenModule {
37
45
  routes?: (router: Router) => void | Promise<void>;
38
46
  providers: ServiceProviderConstructor[];
39
47
  commands: CommandClass[];
48
+ /** Optional, unlike `providers`, so a module literal built without `defineModule()` stays valid. */
49
+ config?: ReadonlyArray<ConfigDefinition>;
40
50
  }
41
51
  /** Define a Guren application module without boilerplate. */
42
52
  export declare function defineModule(definition: ModuleDefinition): GurenModule;
@@ -1,4 +1,5 @@
1
1
  import { t as warnOnce } from "./warn-once-p-IlMjra.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
2
3
  //#region src/support/deprecate.ts
3
4
  /** The release these shims were deprecated in, and the one that removes them (RFC 0023 Part 3). */
4
5
  const SINCE = "2.23.0";
@@ -39,7 +40,7 @@ var Container = class Container {
39
40
  tags = /* @__PURE__ */ new Map();
40
41
  contextualBindings = [];
41
42
  resolvingStack = [];
42
- scopedInstances = [];
43
+ scope;
43
44
  fakes = /* @__PURE__ */ new Map();
44
45
  /**
45
46
  * @internal Installed by ProviderManager once every eager provider has booted.
@@ -87,8 +88,8 @@ var Container = class Container {
87
88
  const binding = this.bindings.get(resolvedKey) ?? this.loadDeferred(key, resolvedKey);
88
89
  if (!binding) throw new Error(`Service "${key}" not found in container`);
89
90
  if (binding.singleton && binding.instance !== void 0) return binding.instance;
90
- if (this.scopedInstances.length > 0) {
91
- const currentScope = this.scopedInstances[this.scopedInstances.length - 1];
91
+ const currentScope = this.scope?.getStore();
92
+ if (currentScope) {
92
93
  if (currentScope.has(resolvedKey)) return currentScope.get(resolvedKey);
93
94
  }
94
95
  const contextualFactory = this.findContextualBinding(resolvedKey);
@@ -96,7 +97,7 @@ var Container = class Container {
96
97
  try {
97
98
  const instance = (contextualFactory ?? binding.factory)(this);
98
99
  if (binding.singleton) binding.instance = instance;
99
- if (this.scopedInstances.length > 0 && !binding.singleton) this.scopedInstances[this.scopedInstances.length - 1].set(resolvedKey, instance);
100
+ if (!binding.singleton) currentScope?.set(resolvedKey, instance);
100
101
  return instance;
101
102
  } finally {
102
103
  this.resolvingStack.pop();
@@ -159,22 +160,17 @@ var Container = class Container {
159
160
  } };
160
161
  } };
161
162
  }
162
- /** Services resolved inside the callback are cached for the scope and released when it ends. */
163
+ /**
164
+ * Services resolved inside the callback are cached for the scope. The cache lives
165
+ * as long as the async context: work detached inside the scope (a timer, an
166
+ * un-awaited promise) keeps it and every cached instance reachable.
167
+ */
163
168
  scoped(callback) {
164
- this.scopedInstances.push(/* @__PURE__ */ new Map());
165
- try {
166
- return callback();
167
- } finally {
168
- this.scopedInstances.pop();
169
- }
169
+ this.scope ??= new AsyncLocalStorage();
170
+ return this.scope.run(/* @__PURE__ */ new Map(), callback);
170
171
  }
171
- async scopedAsync(callback) {
172
- this.scopedInstances.push(/* @__PURE__ */ new Map());
173
- try {
174
- return await callback();
175
- } finally {
176
- this.scopedInstances.pop();
177
- }
172
+ scopedAsync(callback) {
173
+ return this.scoped(callback);
178
174
  }
179
175
  fake(key, instance) {
180
176
  const shadowed = this.fakes.has(key) ? { instance: this.fakes.get(key) } : void 0;
@@ -1,5 +1,5 @@
1
1
  import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "../MessageSigner-Bd25ZJAV.js";
2
2
  import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "../Hash-D2DFd8xX.js";
3
3
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "../Random-S0OvCuR8.js";
4
- import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-D1dxfMqD.js";
4
+ import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-CWK5l22W.js";
5
5
  export { Encrypter, MessageSigner, check, createEncrypter, decrypt, deriveAppKey, deriveAppKeyring, encodeDerivedKey, encrypt, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getAppKeyringFromEnv, getEncrypter, hash, hashPassword, hmac, md5, needsRehash, normalizeAppKey, parseAppKey, parsePreviousAppKeys, pick, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, sample, secureCompare, setEncrypter, sha256, sha512, shuffle, signUrl, urlSafeToken, uuid, verifyHmac, verifyPassword, verifySignedUrl };
@@ -1,5 +1,5 @@
1
1
  import { a as generateAppKey, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
2
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-DWwscxfW.js";
3
3
  import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypto";
4
4
  //#region src/encryption/Encrypter.ts
5
5
  /**
@@ -9,6 +9,7 @@ export declare class EventManager {
9
9
  /** Next `listenerSeq` per "<event>\u0000<queue>", never reset; see {@link RegisteredListener.listenerSeq}. */
10
10
  private readonly listenerSeqCounters;
11
11
  private queueDispatcher?;
12
+ private readonly claimedOnce;
12
13
  on<T extends Event>(event: EventClass<T> | string, listener: EventListener<T>, options?: ListenerOptions): EventSubscription;
13
14
  private register;
14
15
  once<T extends Event>(event: EventClass<T> | string, listener: EventListener<T>, options?: Omit<ListenerOptions, 'once'>): EventSubscription;
@@ -18,6 +19,7 @@ export declare class EventManager {
18
19
  * listeners anyway, so this is for a process that emits and never listens.
19
20
  */
20
21
  registerEvent(eventClass: EventClass): void;
22
+ private rememberEventClass;
21
23
  /**
22
24
  * Registers a `Listener` subclass under its own statics: `event`, `priority`,
23
25
  * and `queue` when `shouldQueue`. The instance is built per invocation, so
@@ -1,2 +1,2 @@
1
- import { a as RequestFinished, c as UserLoggedOut, d as EventManager, f as createEventManager, i as JobProcessed, l as createQueueEventDispatcher, n as ApplicationStarted, o as RequestReceived, p as Event, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "../events-c94CdUFc.js";
1
+ import { a as RequestFinished, c as UserLoggedOut, d as EventManager, f as createEventManager, i as JobProcessed, l as createQueueEventDispatcher, n as ApplicationStarted, o as RequestReceived, p as Event, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "../events-DQavGm8W.js";
2
2
  export { ApplicationShutdown, ApplicationStarted, Event, EventManager, JobFailed, JobProcessed, Listener, RequestFinished, RequestReceived, UserAuthenticated, UserLoggedOut, createEventManager, createQueueEventDispatcher };
@@ -1,5 +1,5 @@
1
1
  import { t as warnOnce } from "./warn-once-p-IlMjra.js";
2
- import { d as resolveQueueDriver, l as registerJob, t as Job } from "./Job-COMzBNOL.js";
2
+ import { d as resolveQueueDriver, l as registerJob, p as reportRegistryCollision, t as Job } from "./Job-DsFMcXVk.js";
3
3
  //#region src/events/Event.ts
4
4
  /** Base class for all application events. */
5
5
  var Event = class {
@@ -67,12 +67,13 @@ var EventManager = class {
67
67
  /** Next `listenerSeq` per "<event>\u0000<queue>", never reset; see {@link RegisteredListener.listenerSeq}. */
68
68
  listenerSeqCounters = /* @__PURE__ */ new Map();
69
69
  queueDispatcher;
70
+ claimedOnce = /* @__PURE__ */ new WeakSet();
70
71
  on(event, listener, options = {}) {
71
72
  return this.register(event, listener, options);
72
73
  }
73
74
  register(event, listener, options, failed) {
74
75
  const eventName = this.nameOf(event);
75
- if (typeof event !== "string") this.eventClasses.set(eventName, event);
76
+ if (typeof event !== "string") this.rememberEventClass(eventName, event);
76
77
  const registeredListeners = this.listeners.get(eventName) ?? [];
77
78
  const registered = {
78
79
  listener,
@@ -101,7 +102,11 @@ var EventManager = class {
101
102
  * listeners anyway, so this is for a process that emits and never listens.
102
103
  */
103
104
  registerEvent(eventClass) {
104
- this.eventClasses.set(resolveEventName(eventClass), eventClass);
105
+ this.rememberEventClass(resolveEventName(eventClass), eventClass);
106
+ }
107
+ rememberEventClass(eventName, eventClass) {
108
+ reportRegistryCollision("event", eventName, this.eventClasses.get(eventName), eventClass);
109
+ this.eventClasses.set(eventName, eventClass);
105
110
  }
106
111
  /**
107
112
  * Registers a `Listener` subclass under its own statics: `event`, `priority`,
@@ -163,14 +168,22 @@ var EventManager = class {
163
168
  const registeredListeners = this.listeners.get(eventName);
164
169
  if (!registeredListeners || registeredListeners.length === 0) return;
165
170
  const listenersToCall = [...registeredListeners];
166
- const toRemove = [];
167
171
  const call = async (registered) => {
168
- const queued = await this.invoke(registered, event, eventName);
169
- if (registered.options.once && !queued) toRemove.push(registered);
172
+ if (registered.options.once) {
173
+ if (this.claimedOnce.has(registered)) return;
174
+ this.claimedOnce.add(registered);
175
+ }
176
+ try {
177
+ const queued = await this.invoke(registered, event, eventName);
178
+ if (registered.options.once && !queued) this.forget(eventName, registeredListeners, [registered]);
179
+ if (queued) this.claimedOnce.delete(registered);
180
+ } catch (error) {
181
+ this.claimedOnce.delete(registered);
182
+ throw error;
183
+ }
170
184
  };
171
185
  if (parallel) await Promise.all(listenersToCall.map(call));
172
186
  else for (const registered of listenersToCall) await call(registered);
173
- this.forget(eventName, registeredListeners, toRemove);
174
187
  }
175
188
  /** Resolves whether the listener was sent to a queue rather than run here. */
176
189
  async invoke(registered, event, eventName) {
@@ -12,6 +12,5 @@ export declare class HealthManager {
12
12
  middleware(options?: HealthMiddlewareOptions): Middleware;
13
13
  private runChecks;
14
14
  private runCheck;
15
- private timeoutPromise;
16
15
  }
17
16
  export declare function createHealthManager(): HealthManager;
@@ -1,2 +1,2 @@
1
- import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "../health-CB0oS_UE.js";
1
+ import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "../health-Bg0Xj3aD.js";
2
2
  export { CacheCheck, CustomCheck, DatabaseCheck, HealthCheck, HealthManager, MemoryCheck, RedisCheck, StorageCheck, createHealthManager, customCheck };
@@ -96,8 +96,13 @@ var HealthManager = class {
96
96
  async runCheck(registered) {
97
97
  const { check, options } = registered;
98
98
  const start = performance.now();
99
+ let timer;
99
100
  try {
100
- const result = await Promise.race([check.check(), this.timeoutPromise(options.timeout)]);
101
+ const result = await Promise.race([check.check(), new Promise((_, reject) => {
102
+ timer = setTimeout(() => {
103
+ reject(/* @__PURE__ */ new Error(`Health check timed out after ${options.timeout}ms`));
104
+ }, options.timeout);
105
+ })]);
101
106
  result.duration = Math.round(performance.now() - start);
102
107
  return result;
103
108
  } catch (error) {
@@ -108,15 +113,10 @@ var HealthManager = class {
108
113
  message: error instanceof Error ? error.message : "Check failed with error",
109
114
  duration
110
115
  };
116
+ } finally {
117
+ clearTimeout(timer);
111
118
  }
112
119
  }
113
- timeoutPromise(ms) {
114
- return new Promise((_, reject) => {
115
- setTimeout(() => {
116
- reject(/* @__PURE__ */ new Error(`Health check timed out after ${ms}ms`));
117
- }, ms);
118
- });
119
- }
120
120
  };
121
121
  function createHealthManager() {
122
122
  return new HealthManager();
@@ -89,10 +89,18 @@ export interface ApplicationOptions {
89
89
  readonly env?: EnvSchema;
90
90
  /**
91
91
  * The definitions `config/*.ts` export, resolved against `env` and bound before
92
- * any provider registers (RFC 0027 §2). One definition per key.
92
+ * any provider registers (RFC 0027 §2). One definition per key, counting the
93
+ * `config` of every module.
93
94
  */
94
95
  readonly config?: ReadonlyArray<ConfigDefinition>;
95
96
  }
97
+ /** A config definition and where it was listed: `createApp({ config })[index]`, or a module's `config[index]`. */
98
+ export interface ConfiguredDefinition {
99
+ readonly definition: ConfigDefinition;
100
+ readonly index: number;
101
+ /** The listing module's name; absent for `createApp({ config })`. */
102
+ readonly module?: string;
103
+ }
96
104
  export interface InertiaApplicationOptions {
97
105
  /** Document defaults for server-rendered responses; each per-response {@link InertiaOptions} field overrides its own. */
98
106
  readonly document?: InertiaDocumentOptions;
@@ -183,6 +191,8 @@ export declare class Application {
183
191
  private disposeBunTeardown?;
184
192
  private autoSessionAttached;
185
193
  private readonly cookielessAuthPaths;
194
+ /** {@link configDefinitions} with where each was listed, which ConfigServiceProvider's errors name. */
195
+ readonly configEntries: ReadonlyArray<ConfiguredDefinition>;
186
196
  private routesRegistered;
187
197
  private bootPromise?;
188
198
  constructor(options?: ApplicationOptions);
@@ -190,6 +200,7 @@ export declare class Application {
190
200
  get authOptions(): AuthPluginOptions | undefined;
191
201
  get i18nOptions(): I18nPluginOptions | undefined;
192
202
  get envSchema(): EnvSchema | undefined;
203
+ /** `createApp({ config })`, then each module's `config` in `modules` order (RFC 0002, RFC 0027 §2). */
193
204
  get configDefinitions(): ReadonlyArray<ConfigDefinition>;
194
205
  markAutoSessionAttached(): void;
195
206
  /** Whether `key` is supplied by a deferred provider, which only activates on a `make()` after boot. */
@@ -15,10 +15,7 @@ export interface RateLimitStore {
15
15
  declare abstract class BaseMemoryStore implements RateLimitStore {
16
16
  protected readonly now: () => number;
17
17
  protected cleanupInterval?: ReturnType<typeof setInterval>;
18
- /**
19
- * Unlike the cache sweep, this interval is not `unref()`ed, so a leaked one
20
- * both duplicates work and keeps the process alive on its own.
21
- */
18
+ /** A sweep leaked across a hot reload would run beside this one. */
22
19
  private readonly hotReloadClaim;
23
20
  constructor(cleanupIntervalMs?: number, now?: () => number);
24
21
  abstract get(key: string): Promise<RateLimitEntry | null>;
@@ -1,2 +1,2 @@
1
- import { a as resolveI18n, c as tc, d as Translator, f as getPluralizationRule, i as getI18n, l as tryGetI18n, m as selectPluralForm, n as I18nManager, o as setI18n, p as pluralizationRules, r as createI18n, s as t, t as MemoryLoader, u as JsonLoader } from "../i18n-DqcRD4qL.js";
1
+ import { a as resolveI18n, c as tc, d as Translator, f as getPluralizationRule, i as getI18n, l as tryGetI18n, m as selectPluralForm, n as I18nManager, o as setI18n, p as pluralizationRules, r as createI18n, s as t, t as MemoryLoader, u as JsonLoader } from "../i18n-DmMKcbqj.js";
2
2
  export { I18nManager, JsonLoader, MemoryLoader, Translator, createI18n, getI18n, getPluralizationRule, pluralizationRules, resolveI18n, selectPluralForm, setI18n, t, tc, tryGetI18n };
@@ -1,4 +1,4 @@
1
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
1
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-DWwscxfW.js";
2
2
  import { basename, extname, join } from "node:path";
3
3
  import { readFile, readdir } from "node:fs/promises";
4
4
  //#region src/i18n/pluralization.ts
package/dist/index.d.ts CHANGED
@@ -46,6 +46,8 @@ export { approvalStatusNotFoundMessage, toApprovalStatusReport } from './agent/a
46
46
  export type { ApprovalStatusOutcome, ApprovalStatusReport } from './agent/approval-status.js';
47
47
  export { ViewEngine } from './mvc/ViewEngine.js';
48
48
  export { inertia, setInertiaSsrRenderer, setInertiaDocument } from './mvc/inertia/InertiaEngine.js';
49
+ export { always, defer, isAlwaysProp, isDeferredProp } from './mvc/inertia/props.js';
50
+ export type { AlwaysProp, DeferredProp, InertiaPropInput, InertiaPropsInput, ResolvedInertiaProp, ResolvedInertiaProps, } from './mvc/inertia/props.js';
49
51
  export { setInertiaSharedProps, getInertiaSharedPropsResolver, shareInertiaProps } from './mvc/inertia/shared.js';
50
52
  export type { InertiaDocumentContext, InertiaDocumentOptions, InertiaOptions, InertiaPagePayload, InertiaSsrContext, InertiaSsrOptions, InertiaSsrRenderer, InertiaSsrResult, } from './mvc/inertia/InertiaEngine.js';
51
53
  export type { SharedInertiaPropsResolver, InertiaSharedProps, ResolvedSharedInertiaProps, SharedPropsContainer, } from './mvc/inertia/shared.js';
@@ -103,7 +105,7 @@ export { NodeHasher } from './auth/password/NodeHasher.js';
103
105
  export { DefaultHasher, DefaultHasher as Hash } from './auth/password/DefaultHasher.js';
104
106
  export type { PasswordHashAlgorithm, DefaultHasherOptions } from './auth/password/DefaultHasher.js';
105
107
  export type { PasswordHasherOption } from './auth/password/configured-hasher.js';
106
- export type { ApplicationOptions, AuthPluginOptions, I18nPluginOptions, InertiaApplicationOptions } from './http/Application.js';
108
+ export type { ApplicationOptions, AuthPluginOptions, ConfiguredDefinition, I18nPluginOptions, InertiaApplicationOptions } from './http/Application.js';
107
109
  export { defineEnv, Env, EnvSchema, EnvValidationError, EnvVar, isRawEnvKey } from './config/env.js';
108
110
  export type { AppEnv, EnvProblem, EnvSource, InferEnv, ParsedEnv } from './config/env.js';
109
111
  export { recordEnvReads } from './config/env-reads.js';