@getstrata/core 3.0.4 → 3.0.7

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 (103) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +17 -9
  3. package/dist/core/auth/policy.d.ts +4 -1
  4. package/dist/core/auth/saml/samlServiceProvider.d.ts +2 -3
  5. package/dist/core/cache/createCacheStore.d.ts +1 -1
  6. package/dist/core/cache/expiration.d.ts +2 -0
  7. package/dist/core/cache/redisCacheScript.d.ts +1 -1
  8. package/dist/core/cache/redisCacheStore.d.ts +5 -5
  9. package/dist/core/cache/repository.d.ts +2 -0
  10. package/dist/core/cache/simpleCache.d.ts +5 -5
  11. package/dist/core/cache/simpleCacheStore.d.ts +3 -3
  12. package/dist/core/cache/store.d.ts +5 -4
  13. package/dist/core/cache/taggedCache.d.ts +2 -0
  14. package/dist/core/cache/tokens.d.ts +1 -1
  15. package/dist/core/config/envSchema.d.ts +13 -0
  16. package/dist/core/contracts/application.d.ts +4 -0
  17. package/dist/core/contracts/di.d.ts +2 -2
  18. package/dist/core/contracts/provider.d.ts +13 -0
  19. package/dist/core/contracts/serviceTokens.d.ts +12 -11
  20. package/dist/core/database/factory.d.ts +3 -0
  21. package/dist/core/database/index.d.ts +1 -1
  22. package/dist/core/database/migrations/declaration.d.ts +11 -0
  23. package/dist/core/database/migrations/runner.d.ts +2 -0
  24. package/dist/core/database/model.d.ts +16 -3
  25. package/dist/core/database/modelQuery.d.ts +1 -10
  26. package/dist/core/database/modelRelationLoader.d.ts +31 -0
  27. package/dist/core/database/mysqlConnection.d.ts +2 -2
  28. package/dist/core/database/mysqlNative.d.ts +2 -0
  29. package/dist/core/database/ormRuntime.d.ts +1 -1
  30. package/dist/core/database/rawMysql.d.ts +1 -1
  31. package/dist/core/events/eventBusClass.d.ts +6 -3
  32. package/dist/core/events/index.d.ts +1 -1
  33. package/dist/core/http/formRequest.d.ts +2 -0
  34. package/dist/core/http/loginThrottleMiddleware.d.ts +1 -2
  35. package/dist/core/http/memoryThrottleMiddleware.d.ts +1 -3
  36. package/dist/core/http/webFormRequest.d.ts +3 -5
  37. package/dist/core/mail/mailer.d.ts +6 -3
  38. package/dist/core/mail/markdownMailable.d.ts +2 -2
  39. package/dist/core/notifications/dispatcher.d.ts +5 -5
  40. package/dist/core/notifications/index.d.ts +1 -1
  41. package/dist/core/notifications/types.d.ts +9 -2
  42. package/dist/core/queue/index.d.ts +8 -3
  43. package/dist/core/queue/queueHandoff.d.ts +2 -2
  44. package/dist/core/runtime/application.d.ts +2 -0
  45. package/dist/core/security/oauthState.d.ts +12 -2
  46. package/dist/core/security/safeUrl.d.ts +1 -11
  47. package/dist/core/storage/storage.d.ts +23 -6
  48. package/dist/core/testing.d.ts +5 -0
  49. package/dist/core/testingState.d.ts +22 -0
  50. package/dist/entries/audit/exportAuditLogs.js +1 -0
  51. package/dist/entries/auth/intendedUrlCookie.js +106 -18
  52. package/dist/entries/auth/jwt.js +68 -6
  53. package/dist/entries/auth/jwtGuard.js +76 -12
  54. package/dist/entries/auth/oauth/samlProvider.js +4 -5
  55. package/dist/entries/auth/passwordConfirmCookie.js +69 -3
  56. package/dist/entries/auth/saml/samlServiceProvider.js +5 -7
  57. package/dist/entries/auth/sessionCookie.js +69 -6
  58. package/dist/entries/auth/sessionGuard.js +69 -6
  59. package/dist/entries/cache/createCacheStore.js +45 -23
  60. package/dist/entries/cache/repository.js +20 -5
  61. package/dist/entries/cache/simpleCache.js +21 -7
  62. package/dist/entries/cache/simpleCacheStore.js +2 -3
  63. package/dist/entries/config/envSchema.js +13 -0
  64. package/dist/entries/contracts/serviceTokens.js +2 -0
  65. package/dist/entries/database/bindings.js +19 -95
  66. package/dist/entries/database/factory.js +4 -0
  67. package/dist/entries/database/migrations.js +714 -1
  68. package/dist/entries/database/ownedReadOnlyObservation.js +1 -5
  69. package/dist/entries/database/sqliteConnection.js +1 -5
  70. package/dist/entries/http/flashMiddleware.js +33 -14
  71. package/dist/entries/http/flashSession.js +33 -14
  72. package/dist/entries/http/formRequest.js +12 -6
  73. package/dist/entries/http/memoryThrottleMiddleware.js +12 -11
  74. package/dist/entries/http/pagination.js +4 -4
  75. package/dist/entries/http/parseMultipartUpload.js +62 -9
  76. package/dist/entries/http/requirePasswordConfirmMiddleware.js +5 -2
  77. package/dist/entries/http/requireWebAuthMiddleware.js +5 -2
  78. package/dist/entries/http/routeModelBinding.js +4 -4
  79. package/dist/entries/http/safeInternalPath.js +5 -2
  80. package/dist/entries/http/scimThrottleMiddleware.js +5 -2
  81. package/dist/entries/http/securedRouteModelBinding.js +4 -4
  82. package/dist/entries/http/throttleMiddleware.js +5 -2
  83. package/dist/entries/http/uploads.js +62 -9
  84. package/dist/entries/http/validation.js +4 -4
  85. package/dist/entries/http/webFormRequest.js +74 -95
  86. package/dist/entries/jobs/exportAuditLogsJob.js +9 -4
  87. package/dist/entries/jobs/invalidateCacheTagsJob.js +9 -4
  88. package/dist/entries/queue/createAppQueue.js +10 -5
  89. package/dist/entries/queue/publicQueue.js +10 -5
  90. package/dist/entries/queue/queueWorkerTransport.js +10 -5
  91. package/dist/entries/queue.js +9 -4
  92. package/dist/entries/runtime/application.js +50 -3
  93. package/dist/entries/security/oauthState.js +61 -2
  94. package/dist/entries/security/tokenExpiry.js +62 -9
  95. package/dist/entries/storage/storage.js +102 -1
  96. package/dist/entries/testing.js +18 -0
  97. package/dist/framework/public-api.d.ts +16 -13
  98. package/dist/index.js +380 -266
  99. package/dist/internal/mysqlNative.js +97 -0
  100. package/dist/internal/ormRuntime.js +41 -4
  101. package/dist/internal/testingState.js +31 -0
  102. package/dist/types/services.d.ts +8 -1
  103. package/package.json +17 -4
package/dist/index.js CHANGED
@@ -1,4 +1,28 @@
1
1
  // @bun
2
+ // ../../src/core/contracts/provider.ts
3
+ function defineProvider(options) {
4
+ const { name, requires, services, setup, boot } = options;
5
+ if (typeof name !== "string" || name.trim().length === 0) {
6
+ throw new TypeError("Provider names must be nonempty strings.");
7
+ }
8
+ if (requires !== undefined && (!Array.isArray(requires) || requires.some((name) => typeof name !== "string" || name.trim().length === 0))) {
9
+ throw new TypeError("Provider dependencies must be an array of nonempty names.");
10
+ }
11
+ if (services !== undefined && !Array.isArray(services)) {
12
+ throw new TypeError("Provider services must be an array.");
13
+ }
14
+ if (setup !== undefined && typeof setup !== "function" || boot !== undefined && typeof boot !== "function") {
15
+ throw new TypeError("Provider hooks must be functions.");
16
+ }
17
+ return Object.freeze({
18
+ name,
19
+ requires: Object.freeze([...requires ?? []]),
20
+ services: Object.freeze([...services ?? []]),
21
+ setup: setup ?? (() => {}),
22
+ ...boot ? { boot } : {}
23
+ });
24
+ }
25
+
2
26
  // ../../src/framework/public-api.ts
3
27
  import { AuthenticationRequiredError as AuthenticationRequiredError2 } from "@getstrata/core/auth/authOutcome";
4
28
  import { Policy, PolicyDeniedError, PolicyGate } from "@getstrata/core/auth/policy";
@@ -50,7 +74,7 @@ import { DATABASE_SESSION_TOKEN as DATABASE_SESSION_TOKEN2 } from "@getstrata/co
50
74
  import {
51
75
  BadRequestError as BadRequestError9,
52
76
  ConflictError as ConflictError3,
53
- ForbiddenError as ForbiddenError15,
77
+ ForbiddenError as ForbiddenError14,
54
78
  HttpError as HttpError3,
55
79
  InternalServerError as InternalServerError3,
56
80
  InvalidCredentialsError as InvalidCredentialsError3,
@@ -61,7 +85,7 @@ import {
61
85
  toHttpError as toHttpError4,
62
86
  UnauthorizedError as UnauthorizedError4,
63
87
  UnprocessableEntityError as UnprocessableEntityError5,
64
- ValidationError as ValidationError5
88
+ ValidationError as ValidationError4
65
89
  } from "@getstrata/core/errors/http";
66
90
  import {
67
91
  createIdentityQueue as createIdentityQueue2,
@@ -73,6 +97,7 @@ import {
73
97
  BaseRepository as BaseRepository4,
74
98
  BelongsToManyRelationQuery,
75
99
  BelongsToRelationQuery,
100
+ createModel,
76
101
  HasManyRelationQuery,
77
102
  HasManyThroughRelationQuery,
78
103
  HasOneRelationQuery,
@@ -609,10 +634,11 @@ function resolveJwtSecret(secret) {
609
634
  throw new TypeError("Explicit JWT secret is required.");
610
635
  }
611
636
  function jwtTtlSeconds(override) {
612
- if (typeof override === "number" && Number.isInteger(override) && override > 0) {
613
- return override;
614
- }
615
- return 3600;
637
+ if (override === undefined)
638
+ return 3600;
639
+ if (!Number.isSafeInteger(override) || override <= 0)
640
+ throw new TypeError("JWT ttlSeconds must be a positive safe integer.");
641
+ return override;
616
642
  }
617
643
  function encodeJson(value) {
618
644
  return Buffer.from(JSON.stringify(value)).toString("base64url");
@@ -1225,7 +1251,7 @@ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
1225
1251
  // ../../src/core/security/safeUrl.ts
1226
1252
  import { lookup as dnsLookupImpl } from "dns/promises";
1227
1253
  import { BadRequestError } from "@getstrata/core/errors/http";
1228
- var dnsLookup = dnsLookupImpl;
1254
+ import { testState } from "#strata-test-state";
1229
1255
  var BLOCKED_HOSTNAMES = new Set([
1230
1256
  "localhost",
1231
1257
  "127.0.0.1",
@@ -1450,7 +1476,7 @@ async function resolveSafeOutboundTarget(rawUrl, options = {}) {
1450
1476
  }
1451
1477
  let results;
1452
1478
  try {
1453
- results = await dnsLookup(hostname, { all: true, verbatim: true });
1479
+ results = testState.dnsLookup ? await testState.dnsLookup(hostname, { all: true, verbatim: true }) : await dnsLookupImpl(hostname, { all: true, verbatim: true });
1454
1480
  } catch {
1455
1481
  throw new BadRequestError("Webhook URL targets a blocked host.");
1456
1482
  }
@@ -1462,12 +1488,6 @@ async function resolveSafeOutboundTarget(rawUrl, options = {}) {
1462
1488
  async function assertSafeOutboundUrlResolved(rawUrl, options = {}) {
1463
1489
  return (await resolveSafeOutboundTarget(rawUrl, options)).url;
1464
1490
  }
1465
- function setDnsLookupForTests(lookupFn) {
1466
- dnsLookup = lookupFn;
1467
- }
1468
- function resetDnsLookupForTests() {
1469
- dnsLookup = dnsLookupImpl;
1470
- }
1471
1491
 
1472
1492
  // ../../src/core/security/safeFetch.ts
1473
1493
  var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
@@ -1885,6 +1905,9 @@ class OidcProvider {
1885
1905
  };
1886
1906
  }
1887
1907
  }
1908
+ // ../../src/core/auth/saml/samlServiceProvider.ts
1909
+ import { testState as testState2 } from "#strata-test-state";
1910
+
1888
1911
  // ../../src/core/runtime/optionalPeer.ts
1889
1912
  function missingOptionalPeer(packageName, reason, error) {
1890
1913
  return new Error(`Install ${packageName} ${reason} (\`bun add ${packageName}\`).`, {
@@ -1992,20 +2015,16 @@ function readSamlEnvOptions(env = process.env) {
1992
2015
  disableRequestedAuthnContext: env.SAML_DISABLE_REQUESTED_AUTHN_CONTEXT === "true"
1993
2016
  };
1994
2017
  }
1995
- var nodeSamlLoader = null;
1996
2018
  async function defaultLoadNodeSaml() {
1997
2019
  return await import("@node-saml/node-saml");
1998
2020
  }
1999
2021
  async function loadNodeSaml() {
2000
2022
  try {
2001
- return await (nodeSamlLoader ?? defaultLoadNodeSaml)();
2023
+ return await (testState2.nodeSamlLoader ?? defaultLoadNodeSaml)();
2002
2024
  } catch (error) {
2003
2025
  throw missingOptionalPeer("@node-saml/node-saml", "to verify SAML assertions", error);
2004
2026
  }
2005
2027
  }
2006
- function setNodeSamlLoaderForTests(loader) {
2007
- nodeSamlLoader = loader;
2008
- }
2009
2028
 
2010
2029
  class SamlServiceProvider {
2011
2030
  client = null;
@@ -2227,6 +2246,15 @@ function copyApplicationConfig(value, ancestors = new Set) {
2227
2246
  // ../../src/core/cache/redisCacheStore.ts
2228
2247
  var {RedisClient } = globalThis.Bun;
2229
2248
 
2249
+ // ../../src/core/cache/expiration.ts
2250
+ function resolveCacheTtl(ttlMs, defaultTtlMs) {
2251
+ const resolved = ttlMs === undefined ? defaultTtlMs : ttlMs;
2252
+ if (resolved !== null && (typeof resolved !== "number" || !Number.isSafeInteger(resolved))) {
2253
+ throw new RangeError("ttlMs must be a safe integer number of milliseconds, or null for forever.");
2254
+ }
2255
+ return resolved;
2256
+ }
2257
+
2230
2258
  // ../../src/core/cache/redisCacheScript.ts
2231
2259
  var CACHE_SCRIPT = `
2232
2260
  local expected = {'hash', 'zset', 'zset', 'hash', 'zset'}
@@ -2302,9 +2330,10 @@ local function read(key, tags)
2302
2330
  return entry.payload
2303
2331
  end
2304
2332
  local function write(key, payload, tags)
2333
+ if not r.forever and r.ttlMs <= 0 then removeEntry(key); return end
2305
2334
  local entry = {payload=payload, tags=tags}
2306
2335
  redis.call('HSET', KEYS[1], 'e:' .. key, cjson.encode(entry))
2307
- redis.call('ZADD', KEYS[2], r.ttlMs == 0 and '+inf' or now + r.ttlMs, key)
2336
+ redis.call('ZADD', KEYS[2], r.forever and '+inf' or now + r.ttlMs, key)
2308
2337
  touch(key)
2309
2338
  local overflow = redis.call('ZCARD', KEYS[3]) - r.capacity
2310
2339
  if overflow > 0 then
@@ -2354,7 +2383,7 @@ elseif r.op == 'get' then
2354
2383
  return response(payload and {kind='value', payload=payload} or {kind='missing'})
2355
2384
  elseif r.op == 'set' then
2356
2385
  local old = redis.call('HGET', KEYS[1], 'e:' .. r.key)
2357
- local tags = old and cjson.decode(old).tags or {}
2386
+ local tags = addTags(old and cjson.decode(old).tags or {}, r.tags)
2358
2387
  write(r.key, r.payload, tags)
2359
2388
  removeMeta(leaseField)
2360
2389
  return response({written=true})
@@ -2434,8 +2463,7 @@ function validateCacheNamespace(namespace) {
2434
2463
  throw new TypeError("Cache namespace must be a nonempty string.");
2435
2464
  }
2436
2465
  function normalizeRedisCacheOptions(ttlMs, maxEntries, options = {}) {
2437
- if (!Number.isSafeInteger(ttlMs) || ttlMs < 0)
2438
- throw new RangeError("ttlMs must be a non-negative safe integer.");
2466
+ resolveCacheTtl(ttlMs, ttlMs);
2439
2467
  if (!Number.isInteger(maxEntries) || maxEntries < 1 || maxEntries > 1e4)
2440
2468
  throw new RangeError("maxEntries must be between 1 and 10000.");
2441
2469
  const copied = copyApplicationConfig(options);
@@ -2495,8 +2523,13 @@ class RedisCacheStore {
2495
2523
  const result = await this.execute("get", key);
2496
2524
  return result.kind === "value" ? JSON.parse(result.payload ?? "null") : undefined;
2497
2525
  }
2498
- async set(key, value, ttlMs) {
2499
- await this.execute("set", key, { payload: this.serialize(value), ttlMs: ttlMs ?? this.ttlMs });
2526
+ async set(key, value, ttlMs, tags = []) {
2527
+ const resolved = resolveCacheTtl(ttlMs, this.ttlMs);
2528
+ await this.execute("set", key, {
2529
+ payload: resolved !== null && resolved <= 0 ? "null" : this.serialize(value),
2530
+ ttlMs: resolved,
2531
+ tags
2532
+ });
2500
2533
  }
2501
2534
  async getOrSet(key, loader, ttlMs) {
2502
2535
  return this.getOrSetTagged(key, loader, [], ttlMs);
@@ -2505,7 +2538,11 @@ class RedisCacheStore {
2505
2538
  const owner = crypto.randomUUID();
2506
2539
  const end = performance.now() + this.options.waitTimeoutMs;
2507
2540
  while (!this.closed) {
2508
- const claim = await this.execute("claim", key, { owner, tags, ttlMs: ttlMs ?? this.ttlMs });
2541
+ const claim = await this.execute("claim", key, {
2542
+ owner,
2543
+ tags,
2544
+ ttlMs: resolveCacheTtl(ttlMs, this.ttlMs)
2545
+ });
2509
2546
  if (claim.kind === "value")
2510
2547
  return JSON.parse(claim.payload ?? "null");
2511
2548
  if (claim.kind === "owner")
@@ -2571,10 +2608,11 @@ class RedisCacheStore {
2571
2608
  controller.signal.throwIfAborted();
2572
2609
  done = true;
2573
2610
  clearInterval(renew);
2611
+ const resolved = resolveCacheTtl(ttlMs, this.ttlMs);
2574
2612
  await this.execute("publish", key, {
2575
2613
  owner,
2576
- payload: this.serialize(value),
2577
- ttlMs: ttlMs ?? this.ttlMs
2614
+ payload: resolved !== null && resolved <= 0 ? "null" : this.serialize(value),
2615
+ ttlMs: resolved
2578
2616
  });
2579
2617
  return value;
2580
2618
  } finally {
@@ -2607,9 +2645,7 @@ class RedisCacheStore {
2607
2645
  prefixes.push(key.slice(0, i));
2608
2646
  if (prefixes.length > 33)
2609
2647
  throw new RangeError("Redis cache identities support at most 32 query separators.");
2610
- const ttlMs = extra.ttlMs ?? this.ttlMs;
2611
- if (typeof ttlMs !== "number" || !Number.isSafeInteger(ttlMs) || ttlMs < 0)
2612
- throw new RangeError("ttlMs must be a non-negative safe integer.");
2648
+ const ttlMs = resolveCacheTtl(extra.ttlMs, this.ttlMs);
2613
2649
  if (!this.client)
2614
2650
  this.client = this.createClient();
2615
2651
  const client = this.client;
@@ -2644,7 +2680,8 @@ class RedisCacheStore {
2644
2680
  ...extra,
2645
2681
  tags,
2646
2682
  prefixes,
2647
- ttlMs
2683
+ ttlMs,
2684
+ forever: ttlMs === null
2648
2685
  })
2649
2686
  ]),
2650
2687
  timeout
@@ -2665,9 +2702,7 @@ var redisCacheStore_default = RedisCacheStore;
2665
2702
 
2666
2703
  // ../../src/core/cache/simpleCache.ts
2667
2704
  function validateSimpleCacheOptions(ttlMs, maxEntries) {
2668
- if (!Number.isFinite(ttlMs) || ttlMs < 0) {
2669
- throw new RangeError("ttlMs must be a non-negative number.");
2670
- }
2705
+ resolveCacheTtl(ttlMs, ttlMs);
2671
2706
  if (!Number.isInteger(maxEntries) || maxEntries < 1) {
2672
2707
  throw new RangeError("maxEntries must be a positive integer.");
2673
2708
  }
@@ -2688,20 +2723,27 @@ class SimpleCache {
2688
2723
  get(key) {
2689
2724
  return this.getFreshEntry(key)?.value;
2690
2725
  }
2691
- set(key, value, ttlMs) {
2726
+ set(key, value, ttlMs, tags = []) {
2692
2727
  const now = Date.now();
2693
- const resolvedTtlMs = ttlMs ?? this.ttlMs;
2728
+ const resolvedTtlMs = resolveCacheTtl(ttlMs, this.ttlMs);
2729
+ if (resolvedTtlMs !== null && resolvedTtlMs <= 0) {
2730
+ this.invalidate(key);
2731
+ return;
2732
+ }
2733
+ this.inflight.delete(key);
2694
2734
  this.cache.set(key, {
2695
2735
  value,
2696
- expiresAt: now + resolvedTtlMs,
2736
+ expiresAt: resolvedTtlMs === null ? Infinity : now + resolvedTtlMs,
2697
2737
  lastAccessedAt: now
2698
2738
  });
2739
+ this.attachTags(key, tags);
2699
2740
  this.evictOverflow();
2700
2741
  }
2701
2742
  async getOrSet(key, loader, ttlMs) {
2702
2743
  return this.getOrSetTagged(key, loader, [], ttlMs);
2703
2744
  }
2704
2745
  async getOrSetTagged(key, loader, tags, ttlMs) {
2746
+ resolveCacheTtl(ttlMs, this.ttlMs);
2705
2747
  this.pruneExpired();
2706
2748
  const cachedEntry = this.getFreshEntry(key);
2707
2749
  if (cachedEntry) {
@@ -2843,7 +2885,7 @@ class SimpleCache {
2843
2885
  oldestKey = key;
2844
2886
  }
2845
2887
  }
2846
- if (!oldestKey) {
2888
+ if (oldestKey === undefined) {
2847
2889
  return;
2848
2890
  }
2849
2891
  this.invalidate(oldestKey);
@@ -2861,9 +2903,8 @@ class SimpleCacheStore {
2861
2903
  get(key) {
2862
2904
  return Promise.resolve(this.cache.get(key));
2863
2905
  }
2864
- set(key, value, ttlMs) {
2865
- this.cache.set(key, value, ttlMs);
2866
- return Promise.resolve();
2906
+ async set(key, value, ttlMs, tags = []) {
2907
+ this.cache.set(key, value, ttlMs, tags);
2867
2908
  }
2868
2909
  getOrSet(key, loader, ttlMs) {
2869
2910
  return this.cache.getOrSet(key, loader, ttlMs);
@@ -2936,13 +2977,18 @@ class TaggedCache {
2936
2977
  constructor(store, tags) {
2937
2978
  this.store = store;
2938
2979
  this.tags = tags;
2980
+ if (typeof store.getOrSetTagged !== "function") {
2981
+ throw new TypeError("Cache tags require atomic tagged loading support.");
2982
+ }
2983
+ }
2984
+ async put(key, value, ttlMs) {
2985
+ await this.store.set(key, value, ttlMs, this.tags);
2986
+ }
2987
+ async forever(key, value) {
2988
+ await this.store.set(key, value, null, this.tags);
2939
2989
  }
2940
2990
  async remember(key, callback, ttlMs) {
2941
- if (this.store.getOrSetTagged)
2942
- return this.store.getOrSetTagged(key, callback, this.tags, ttlMs);
2943
- const value = await this.store.getOrSet(key, callback, ttlMs);
2944
- await this.store.attachTags(key, this.tags);
2945
- return value;
2991
+ return this.store.getOrSetTagged(key, callback, this.tags, ttlMs);
2946
2992
  }
2947
2993
  async flush() {
2948
2994
  return this.store.flushTags(this.tags);
@@ -2962,6 +3008,12 @@ class CacheRepository {
2962
3008
  async get(key) {
2963
3009
  return this.store.get(key);
2964
3010
  }
3011
+ async put(key, value, ttlMs) {
3012
+ await this.store.set(key, value, ttlMs);
3013
+ }
3014
+ async forever(key, value) {
3015
+ await this.store.set(key, value, null);
3016
+ }
2965
3017
  async remember(key, callback, ttlMs) {
2966
3018
  return this.store.getOrSet(key, callback, ttlMs);
2967
3019
  }
@@ -4237,7 +4289,6 @@ import {
4237
4289
 
4238
4290
  // ../../src/core/events/eventBusClass.ts
4239
4291
  class EventBus {
4240
- constructor() {}
4241
4292
  transactionalListeners = new Map;
4242
4293
  listenTransactional(event, listener) {
4243
4294
  const handlers = this.transactionalListeners.get(event) ?? new Set;
@@ -4631,87 +4682,8 @@ function createBoundRegistryFactory(prepared, context, ownership, configuredPool
4631
4682
  };
4632
4683
  }
4633
4684
 
4634
- // ../../src/core/database/mysqlNative.ts
4635
- var MYSQL_SESSION_UTC = "SET time_zone = '+00:00'";
4636
- var mysqlModule;
4637
- var mysqlPending;
4638
- var importMysql = defaultImportMysql;
4639
- async function defaultImportMysql() {
4640
- return import("mysql2/promise");
4641
- }
4642
- function resetMysqlLoaderForTests(importer) {
4643
- mysqlModule = undefined;
4644
- mysqlPending = undefined;
4645
- importMysql = importer ? async () => await importer() : defaultImportMysql;
4646
- }
4647
- function mysqlApi(mod) {
4648
- if (typeof mod.createPool === "function") {
4649
- return mod;
4650
- }
4651
- const withDefault = mod;
4652
- if (typeof withDefault.default?.createPool === "function") {
4653
- return withDefault.default;
4654
- }
4655
- throw new Error("mysql2/promise did not export createPool.");
4656
- }
4657
- async function loadMysql() {
4658
- if (mysqlModule) {
4659
- return mysqlModule;
4660
- }
4661
- if (!mysqlPending) {
4662
- mysqlPending = (async () => {
4663
- let mod;
4664
- try {
4665
- mod = await importMysql();
4666
- } catch (error) {
4667
- mysqlPending = undefined;
4668
- throw missingOptionalPeer("mysql2", "to open a MySQL connection", error);
4669
- }
4670
- try {
4671
- mysqlModule = mysqlApi(mod);
4672
- return mysqlModule;
4673
- } catch (error) {
4674
- mysqlPending = undefined;
4675
- throw error;
4676
- }
4677
- })();
4678
- }
4679
- return mysqlPending;
4680
- }
4681
- function rowsFromResult(result) {
4682
- if (Array.isArray(result)) {
4683
- return result;
4684
- }
4685
- if (result && typeof result === "object") {
4686
- return [result];
4687
- }
4688
- return [];
4689
- }
4690
- async function executeMysql(target, query, params) {
4691
- const [result] = params.length === 0 && target.query ? await target.query(query) : await target.execute(query, [...params]);
4692
- return rowsFromResult(result);
4693
- }
4694
- function pinSessionToUtc(connection) {
4695
- connection.query(MYSQL_SESSION_UTC, (error) => {
4696
- if (error) {
4697
- console.warn("[mysql] Could not set the session time zone to UTC; DATETIME comparisons may drift.");
4698
- }
4699
- });
4700
- }
4701
- function createPoolFromModule(mysql, url, max) {
4702
- const pool = mysql.createPool({
4703
- uri: url,
4704
- timezone: "Z",
4705
- ...max === undefined ? {} : { connectionLimit: max }
4706
- });
4707
- pool.on("connection", (connection) => {
4708
- pinSessionToUtc(connection);
4709
- });
4710
- return pool;
4711
- }
4712
- async function createMysqlPool(url, max) {
4713
- return createPoolFromModule(await loadMysql(), url, max);
4714
- }
4685
+ // ../../src/core/database/rawMysql.ts
4686
+ import { createMysqlPool, executeMysql } from "#strata-mysql-native";
4715
4687
 
4716
4688
  // ../../src/core/database/nativeTransactions.ts
4717
4689
  var failure = (error) => Object.freeze({ error });
@@ -4951,6 +4923,7 @@ function createMysqlPin(connection) {
4951
4923
  async function createRawMysqlPool(options) {
4952
4924
  const pool = await createMysqlPool(options.url, options.max);
4953
4925
  let closed = false;
4926
+ let closing;
4954
4927
  let retainedCleanup;
4955
4928
  const acquire = async () => {
4956
4929
  if (closed)
@@ -5034,11 +5007,16 @@ async function createRawMysqlPool(options) {
5034
5007
  return { ok: false, error, disposition: "unknown", cleanupErrors: [acknowledgement.error] };
5035
5008
  }
5036
5009
  },
5037
- async close() {
5038
- if (retainedCleanup)
5039
- throw retainedCleanup.error;
5040
- await pool.end();
5010
+ close() {
5011
+ if (closing)
5012
+ return closing;
5041
5013
  closed = true;
5014
+ closing = Promise.resolve().then(async () => {
5015
+ if (retainedCleanup)
5016
+ throw retainedCleanup.error;
5017
+ await pool.end();
5018
+ });
5019
+ return closing;
5042
5020
  }
5043
5021
  });
5044
5022
  }
@@ -5112,6 +5090,7 @@ function postgresPin(connection) {
5112
5090
  }
5113
5091
  function createRawPostgresPoolFromNative(pool) {
5114
5092
  let closed = false;
5093
+ let closing;
5115
5094
  return Object.freeze({
5116
5095
  dialect: dialectFor("pgsql"),
5117
5096
  capabilities: Object.freeze({
@@ -5144,9 +5123,12 @@ function createRawPostgresPoolFromNative(pool) {
5144
5123
  return { ok: false, error, disposition: "not-acquired" };
5145
5124
  }
5146
5125
  },
5147
- async close() {
5148
- await pool.close();
5126
+ close() {
5127
+ if (closing)
5128
+ return closing;
5149
5129
  closed = true;
5130
+ closing = Promise.resolve().then(() => pool.close());
5131
+ return closing;
5150
5132
  }
5151
5133
  });
5152
5134
  }
@@ -5162,10 +5144,6 @@ function sqliteFilename(filename) {
5162
5144
  throw new Error("SQLite path is not configured. Pass a filename or :memory:.");
5163
5145
  return filename === ":memory:" ? filename : resolve(filename);
5164
5146
  }
5165
- function isRowReturning(sql) {
5166
- const upper = sql.replace(/\s+/g, " ").trim().toUpperCase();
5167
- return upper.includes(" RETURNING ") || upper.startsWith("SELECT") || upper.startsWith("WITH") || upper.startsWith("PRAGMA") || upper.startsWith("EXPLAIN");
5168
- }
5169
5147
  function openRawSqlitePool(options) {
5170
5148
  let filename;
5171
5149
  try {
@@ -5209,7 +5187,7 @@ function openRawSqlitePool(options) {
5209
5187
  check();
5210
5188
  const query = db.query(statement.text);
5211
5189
  const params = statement.params.map((value) => value instanceof Date ? value.toISOString() : value);
5212
- if (isRowReturning(statement.text))
5190
+ if (query.columnNames.length > 0)
5213
5191
  return Promise.resolve(query.all(...params));
5214
5192
  query.run(...params);
5215
5193
  return Promise.resolve([]);
@@ -6225,7 +6203,7 @@ async function rollbackDatabase(db, migrations, options = {}) {
6225
6203
  return rolledBack;
6226
6204
  }
6227
6205
  async function freshDatabase(db, migrations, options = {}) {
6228
- if (options.destructive && isProductionEnv()) {
6206
+ if (options.destructive && isProductionEnv(options.environment ?? process.env)) {
6229
6207
  throw new Error("Destructive migration reset is only available in development/test environments.");
6230
6208
  }
6231
6209
  validateMigrations(migrations);
@@ -6355,6 +6333,13 @@ function applyCasts(values, casts, direction) {
6355
6333
  return result;
6356
6334
  })();
6357
6335
  }
6336
+ // ../../src/core/database/mysqlConnection.ts
6337
+ import {
6338
+ createMysqlPool as createMysqlPool2,
6339
+ executeMysql as executeMysql2,
6340
+ loadMysql
6341
+ } from "#strata-mysql-native";
6342
+
6358
6343
  // ../../src/core/database/isolatedReadOnlyObservation.ts
6359
6344
  var childSource = `
6360
6345
  import { Database } from 'bun:sqlite';
@@ -6532,22 +6517,39 @@ function createMysqlAdapter(getPool, close, observer) {
6532
6517
  const transactions = new WeakSet;
6533
6518
  const observations = new Set;
6534
6519
  let observationsClosed = false;
6520
+ let closing;
6521
+ const operations = new Set;
6522
+ function assertOpen() {
6523
+ if (observationsClosed)
6524
+ throw new Error("MySQL connection is closed.");
6525
+ }
6526
+ function track(operation) {
6527
+ operations.add(operation);
6528
+ operation.finally(() => operations.delete(operation)).catch(() => {});
6529
+ return operation;
6530
+ }
6535
6531
  const connection = {
6536
6532
  async unsafe(query, params = []) {
6537
6533
  const active = getActiveDatabaseConnection(connection);
6538
6534
  if (transactions.has(active))
6539
6535
  return active.unsafe(query, params);
6540
- return executeMysql(await getPool(), query, params);
6536
+ assertOpen();
6537
+ return track((async () => {
6538
+ return executeMysql2(await getPool(), query, params);
6539
+ })());
6541
6540
  },
6542
6541
  async begin(callback) {
6543
- if (transactions.has(getActiveDatabaseConnection(connection))) {
6544
- throw new Error("Use the active transaction handle for nested MySQL work.");
6545
- }
6546
- const pool = await getPool();
6547
- if (!pool.getConnection)
6548
- throw new Error("MySQL transactions require a pool with getConnection().");
6549
- const reserved = await pool.getConnection();
6550
- return legacyNativeTransaction(createMysqlPin(reserved), callback, transactions);
6542
+ assertOpen();
6543
+ return track((async () => {
6544
+ if (transactions.has(getActiveDatabaseConnection(connection))) {
6545
+ throw new Error("Use the active transaction handle for nested MySQL work.");
6546
+ }
6547
+ const pool = await getPool();
6548
+ if (!pool.getConnection)
6549
+ throw new Error("MySQL transactions require a pool with getConnection().");
6550
+ const reserved = await pool.getConnection();
6551
+ return legacyNativeTransaction(createMysqlPin(reserved), callback, transactions);
6552
+ })());
6551
6553
  },
6552
6554
  async observeReadOnly(operation, options) {
6553
6555
  if (observationsClosed)
@@ -6565,10 +6567,18 @@ function createMysqlAdapter(getPool, close, observer) {
6565
6567
  observations.delete(work);
6566
6568
  }
6567
6569
  },
6568
- async close() {
6570
+ close() {
6571
+ if (transactions.has(getActiveDatabaseConnection(connection)))
6572
+ return Promise.reject(new Error("Cannot close MySQL from inside its active transaction."));
6573
+ if (closing)
6574
+ return closing;
6569
6575
  observationsClosed = true;
6570
- await Promise.allSettled([...observations]);
6571
- await close();
6576
+ closing = Promise.resolve().then(async () => {
6577
+ while (operations.size || observations.size)
6578
+ await Promise.allSettled([...operations, ...observations]);
6579
+ await close();
6580
+ });
6581
+ return closing;
6572
6582
  }
6573
6583
  };
6574
6584
  return connection;
@@ -6585,7 +6595,7 @@ function createMysqlConnection(url) {
6585
6595
  let poolPending;
6586
6596
  function ensurePool() {
6587
6597
  if (!poolPending) {
6588
- poolPending = createMysqlPool(url).catch((error) => {
6598
+ poolPending = createMysqlPool2(url).catch((error) => {
6589
6599
  poolPending = undefined;
6590
6600
  throw error;
6591
6601
  });
@@ -9341,7 +9351,7 @@ function createOutboxWorkerTransport(token, options = {}) {
9341
9351
  pollMs,
9342
9352
  [workerApplicationShutdown]: applicationShutdown
9343
9353
  });
9344
- running = Promise.resolve().then(() => controller.signal.aborted ? undefined : selected.work(workOptions)).catch((error) => {
9354
+ running = Promise.resolve().then(() => controller.signal.aborted || applicationShutdown?.aborted ? undefined : selected.work(workOptions)).catch((error) => {
9345
9355
  if (!controller.signal.aborted && !applicationShutdown?.aborted || !expectedStop(error))
9346
9356
  throw error;
9347
9357
  });
@@ -10135,6 +10145,9 @@ function resolveRequestId(request) {
10135
10145
  var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
10136
10146
  function looksLikeExternalTarget(value) {
10137
10147
  const trimmed = value.trim();
10148
+ if (/[\t\r\n]/.test(trimmed)) {
10149
+ return true;
10150
+ }
10138
10151
  if (!trimmed.startsWith("/") || trimmed.startsWith("//") || trimmed.includes("\\")) {
10139
10152
  return true;
10140
10153
  }
@@ -10160,13 +10173,13 @@ function sanitizeNestedQuery(search) {
10160
10173
  for (const [key, value] of params.entries()) {
10161
10174
  if (NESTED_REDIRECT_KEYS.has(key)) {
10162
10175
  const sanitized = sanitizeInternalPath(value, "/");
10163
- next.set(key, sanitized);
10176
+ next.append(key, sanitized);
10164
10177
  continue;
10165
10178
  }
10166
10179
  if (looksLikeExternalTarget(value) && value.includes("://")) {
10167
10180
  continue;
10168
10181
  }
10169
- next.set(key, value);
10182
+ next.append(key, value);
10170
10183
  }
10171
10184
  const serialized = next.toString();
10172
10185
  return serialized ? `?${serialized}` : "";
@@ -11220,19 +11233,6 @@ function signFlashPayload(payload, issuedAt, options) {
11220
11233
  const signature = createHmac4("sha256", options.secret).update(`${payload}.${issuedAt}`).digest("hex");
11221
11234
  return `${payload}.${issuedAt}.${signature}`;
11222
11235
  }
11223
- function readFlashCookie(request, options) {
11224
- const cookieHeader = request.headers.get("cookie");
11225
- if (!cookieHeader) {
11226
- return null;
11227
- }
11228
- for (const part of cookieHeader.split(";")) {
11229
- const [name, ...rest] = part.trim().split("=");
11230
- if (name === options.cookieName) {
11231
- return decodeURIComponent(rest.join("="));
11232
- }
11233
- }
11234
- return null;
11235
- }
11236
11236
  function parseFlashCookie(cookieValue, options) {
11237
11237
  const parts = cookieValue.split(".");
11238
11238
  if (parts.length < 3) {
@@ -11278,7 +11278,7 @@ function clearFlashCookie(options) {
11278
11278
  return `${options.cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure}`;
11279
11279
  }
11280
11280
  function pullFlash(request, options) {
11281
- const cookieValue = readFlashCookie(request, options);
11281
+ const cookieValue = readRequestCookie(request, options.cookieName);
11282
11282
  if (!cookieValue) {
11283
11283
  return null;
11284
11284
  }
@@ -11334,8 +11334,8 @@ function parseOptionalPositiveIntQueryParam(params, name) {
11334
11334
  if (value === null || value.trim() === "") {
11335
11335
  return;
11336
11336
  }
11337
- const parsed = Number.parseInt(value, 10);
11338
- if (!Number.isInteger(parsed) || parsed <= 0) {
11337
+ const parsed = Number(value);
11338
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
11339
11339
  throw new BadRequestError3(`Invalid query parameter "${name}". Expected a positive integer.`);
11340
11340
  }
11341
11341
  return parsed;
@@ -11431,8 +11431,8 @@ function readOptionalPositiveInt(payload, field) {
11431
11431
  return readRequiredPositiveInt(payload, field);
11432
11432
  }
11433
11433
  function parsePositiveIntParam(value, name = "id") {
11434
- const parsed = Number.parseInt(value, 10);
11435
- if (!Number.isInteger(parsed) || parsed <= 0) {
11434
+ const parsed = Number(value);
11435
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
11436
11436
  throw new BadRequestError3(`Invalid ${name}. Expected a positive integer.`);
11437
11437
  }
11438
11438
  return parsed;
@@ -11443,11 +11443,17 @@ class FormRequest {
11443
11443
  authorize(_request) {
11444
11444
  return true;
11445
11445
  }
11446
+ validatePayload(payload) {
11447
+ return this.parse(payload);
11448
+ }
11449
+ readPayload(request) {
11450
+ return parseJsonBody(request, (payload) => payload);
11451
+ }
11446
11452
  async validate(request) {
11447
- if (!await this.authorize(request)) {
11453
+ if (await this.authorize(request) !== true) {
11448
11454
  throw new ForbiddenError6;
11449
11455
  }
11450
- return await parseJsonBody(request, (payload) => this.parse(payload));
11456
+ return this.validatePayload(await this.readPayload(request));
11451
11457
  }
11452
11458
  }
11453
11459
 
@@ -11901,6 +11907,9 @@ function securedBindRouteModelByKey(param, resolver, authorization, handler, por
11901
11907
  return response;
11902
11908
  };
11903
11909
  }
11910
+ // ../../src/core/http/loginThrottleMiddleware.ts
11911
+ import { testState as testState3 } from "#strata-test-state";
11912
+
11904
11913
  // ../../src/core/runtime/boundedThrottleStore.ts
11905
11914
  class BoundedThrottleStore {
11906
11915
  decayMs;
@@ -12134,7 +12143,6 @@ function createThrottleMiddleware(options) {
12134
12143
  }
12135
12144
 
12136
12145
  // ../../src/core/http/loginThrottleMiddleware.ts
12137
- var resetGeneration = 0;
12138
12146
  function resolveLoginIdentity(request, trustForwardedFor = false) {
12139
12147
  return readClientIp(request, { TRUST_FORWARDED_FOR: String(trustForwardedFor) }) ?? "unknown";
12140
12148
  }
@@ -12157,11 +12165,11 @@ function createMemoryLoginThrottleMiddleware(options) {
12157
12165
  const store = new BoundedThrottleStore(options.decaySeconds * 1000, options);
12158
12166
  if (!Number.isSafeInteger(options.maxAttempts) || options.maxAttempts < 0)
12159
12167
  throw new Error("Invalid memory throttle limit.");
12160
- let generation = resetGeneration;
12168
+ let generation = testState3.loginThrottleGeneration;
12161
12169
  const middleware = async (request, next) => {
12162
- if (generation !== resetGeneration) {
12170
+ if (generation !== testState3.loginThrottleGeneration) {
12163
12171
  store.clear();
12164
- generation = resetGeneration;
12172
+ generation = testState3.loginThrottleGeneration;
12165
12173
  }
12166
12174
  const email = await resolveLoginEmail(request);
12167
12175
  const key = redisThrottleKey(request, options.keyPrefix ?? "login-throttle", JSON.stringify([resolveLoginIdentity(request, options.trustForwardedFor), email]), undefined, options.namespace);
@@ -12204,21 +12212,18 @@ function createLoginThrottleMiddleware(options) {
12204
12212
  }
12205
12213
  return createMemoryLoginThrottleMiddleware(options);
12206
12214
  }
12207
- function resetMemoryLoginThrottleForTests() {
12208
- resetGeneration++;
12209
- }
12210
12215
  // ../../src/core/http/memoryThrottleMiddleware.ts
12211
- var resetGeneration2 = 0;
12216
+ import { testState as testState4 } from "#strata-test-state";
12212
12217
  function createMemoryThrottleMiddleware(options) {
12213
12218
  options = Object.freeze({ ...options });
12214
12219
  const store = new BoundedThrottleStore(options.decaySeconds * 1000, options);
12215
12220
  if (!Number.isSafeInteger(options.maxAttempts) || options.maxAttempts < 0)
12216
12221
  throw new Error("Invalid memory throttle limit.");
12217
- let generation = resetGeneration2;
12222
+ let generation = testState4.throttleGeneration;
12218
12223
  const middleware = async (request, next) => {
12219
- if (generation !== resetGeneration2) {
12224
+ if (generation !== testState4.throttleGeneration) {
12220
12225
  store.clear();
12221
- generation = resetGeneration2;
12226
+ generation = testState4.throttleGeneration;
12222
12227
  }
12223
12228
  let maxAttempts;
12224
12229
  try {
@@ -12235,9 +12240,6 @@ function createMemoryThrottleMiddleware(options) {
12235
12240
  };
12236
12241
  return Object.assign(middleware, { dispose: () => store.dispose(), stats: () => store.stats() });
12237
12242
  }
12238
- function resetMemoryThrottleForTests() {
12239
- resetGeneration2++;
12240
- }
12241
12243
  // ../../src/core/metrics/prometheus.ts
12242
12244
  var HTTP_DURATION_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 1e4];
12243
12245
  function emptyHistogram() {
@@ -12703,9 +12705,6 @@ function createValidateSignatureMiddleware(options) {
12703
12705
  return await next();
12704
12706
  };
12705
12707
  }
12706
- // ../../src/core/http/webFormRequest.ts
12707
- import { ForbiddenError as ForbiddenError12, ValidationError as ValidationError3 } from "@getstrata/core/errors/http";
12708
-
12709
12708
  // ../../src/core/http/parseFormBody.ts
12710
12709
  import { BadRequestError as BadRequestError8 } from "@getstrata/core/errors/http";
12711
12710
  async function parseFormBody(request, options = {}) {
@@ -12737,30 +12736,15 @@ function formDataToRecord(formData, options = {}) {
12737
12736
  }
12738
12737
 
12739
12738
  // ../../src/core/http/webFormRequest.ts
12740
- class WebFormRequest {
12739
+ class WebFormRequest extends FormRequest {
12741
12740
  #preserveRepeated;
12742
12741
  constructor(options = {}) {
12742
+ super();
12743
12743
  this.#preserveRepeated = options.preserveRepeated === true;
12744
12744
  }
12745
- authorize(_request) {
12746
- return true;
12747
- }
12748
- validatePayload(payload) {
12749
- return this.parse(payload);
12750
- }
12751
- async validate(request) {
12752
- if (!await this.authorize(request)) {
12753
- throw new ForbiddenError12;
12754
- }
12755
- const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
12756
- try {
12757
- return this.validatePayload(payload);
12758
- } catch (error) {
12759
- if (error instanceof ValidationError3) {
12760
- throw error;
12761
- }
12762
- throw error;
12763
- }
12745
+ readPayload(request) {
12746
+ const mediaType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
12747
+ return mediaType === "application/json" || mediaType?.match(/^application\/[^/]+\+json$/) ? parseJsonBody(request, (body) => body) : parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
12764
12748
  }
12765
12749
  }
12766
12750
  // ../../src/core/lifecycle/gracefulShutdown.ts
@@ -13481,20 +13465,45 @@ async function sendMarkdownMail(mailer, input) {
13481
13465
  // ../../src/core/notifications/dispatcher.ts
13482
13466
  class NotificationDispatcher {
13483
13467
  mailer;
13484
- databaseStore;
13485
- constructor(mailer, databaseStore = null) {
13468
+ channels;
13469
+ constructor(mailer, databaseStore = null, channels = {}) {
13486
13470
  this.mailer = mailer;
13487
- this.databaseStore = databaseStore;
13471
+ if (!mailer || typeof mailer.send !== "function") {
13472
+ throw new TypeError('Notification channel "mail" requires a mail sender.');
13473
+ }
13474
+ if (databaseStore && typeof databaseStore.create !== "function") {
13475
+ throw new TypeError('Notification channel "database" requires a database store.');
13476
+ }
13477
+ const registrations = Object.create(null);
13478
+ registrations.mail = { send: (recipient, message) => this.sendMail(recipient, message) };
13479
+ if (databaseStore) {
13480
+ registrations.database = {
13481
+ send: (recipient, message) => this.sendDatabase(databaseStore, recipient, message)
13482
+ };
13483
+ }
13484
+ for (const [name, channel] of Object.entries(channels)) {
13485
+ if (!name || !channel || typeof channel.send !== "function") {
13486
+ throw new TypeError(`Invalid notification channel registration: "${name}".`);
13487
+ }
13488
+ const send = channel.send.bind(channel);
13489
+ registrations[name] = Object.freeze({ send });
13490
+ }
13491
+ this.channels = Object.freeze(registrations);
13488
13492
  }
13489
13493
  async send(notifiable, notification) {
13490
- for (const channel of notification.via(notifiable)) {
13491
- if (channel === "mail") {
13492
- await this.sendMail(notifiable, notification);
13493
- continue;
13494
- }
13495
- if (channel === "database") {
13496
- await this.sendDatabase(notifiable, notification);
13494
+ const channels = [...notification.via(notifiable)];
13495
+ const handlers = channels.map((name) => {
13496
+ const channel = Object.hasOwn(this.channels, name) ? this.channels[name] : undefined;
13497
+ if (!channel) {
13498
+ if (name === "database") {
13499
+ throw new Error('Notification channel "database" requires a database store.');
13500
+ }
13501
+ throw new Error(`Unsupported notification channel: "${name}".`);
13497
13502
  }
13503
+ return channel;
13504
+ });
13505
+ for (const channel of handlers) {
13506
+ await channel.send(notifiable, notification);
13498
13507
  }
13499
13508
  }
13500
13509
  async sendMail(notifiable, notification) {
@@ -13517,25 +13526,28 @@ class NotificationDispatcher {
13517
13526
  await this.mailer.send({
13518
13527
  to: String(routed),
13519
13528
  subject: message.subject,
13520
- body: message.body ?? ""
13529
+ body: message.body ?? "",
13530
+ ...message.html !== undefined ? { html: message.html } : {}
13521
13531
  });
13522
13532
  }
13523
- async sendDatabase(notifiable, notification) {
13524
- if (!this.databaseStore) {
13525
- return;
13526
- }
13533
+ async sendDatabase(store, notifiable, notification) {
13527
13534
  const payload = notification.toDatabase(notifiable);
13528
13535
  if (!payload) {
13529
13536
  return;
13530
13537
  }
13531
- await this.databaseStore.create({
13532
- userId: Number(notifiable.getNotificationKey()),
13533
- ...payload
13538
+ const key = notifiable.getNotificationKey();
13539
+ const userId = typeof key === "string" && /^[0-9]+$/.test(key) ? Number(key) : key;
13540
+ if (typeof userId !== "number" || !Number.isSafeInteger(userId) || userId <= 0) {
13541
+ throw new TypeError('Notification channel "database" requires a positive safe-integer user ID.');
13542
+ }
13543
+ await store.create({
13544
+ ...payload,
13545
+ userId
13534
13546
  });
13535
13547
  }
13536
13548
  }
13537
- function createNotificationDispatcher(mailer, databaseStore) {
13538
- return new NotificationDispatcher(mailer, databaseStore ?? null);
13549
+ function createNotificationDispatcher(mailer, databaseStore, channels = {}) {
13550
+ return new NotificationDispatcher(mailer, databaseStore ?? null, channels);
13539
13551
  }
13540
13552
  // ../../src/core/notifications/notification.ts
13541
13553
  class Notification {
@@ -13686,6 +13698,14 @@ class AsyncQueue {
13686
13698
  if (this.closed)
13687
13699
  throw new Error("Async queue is closed.");
13688
13700
  }
13701
+ track(running) {
13702
+ const settled = running.then(() => {}, () => {});
13703
+ this.active.add(settled);
13704
+ settled.then(() => {
13705
+ this.active.delete(settled);
13706
+ });
13707
+ return running;
13708
+ }
13689
13709
  enqueue(task, onError) {
13690
13710
  this.assertOpen();
13691
13711
  const running = new Promise((resolve) => {
@@ -13693,10 +13713,7 @@ class AsyncQueue {
13693
13713
  Promise.resolve().then(task).catch(onError).finally(resolve);
13694
13714
  }, 0);
13695
13715
  });
13696
- this.active.add(running);
13697
- running.then(() => {
13698
- this.active.delete(running);
13699
- });
13716
+ this.track(running);
13700
13717
  }
13701
13718
  async dispatch(job, payload, options) {
13702
13719
  if (options?.handoff !== undefined)
@@ -15036,7 +15053,7 @@ class ResilientQueue extends AsyncQueue {
15036
15053
  });
15037
15054
  return;
15038
15055
  }
15039
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
15056
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
15040
15057
  }
15041
15058
  }
15042
15059
 
@@ -15486,10 +15503,52 @@ function signedWebhookHeaders(secret, body, headerName = "x-strata-signature") {
15486
15503
  };
15487
15504
  }
15488
15505
  // ../../src/core/storage/storage.ts
15489
- import { mkdir, readFile, unlink, writeFile } from "fs/promises";
15506
+ import { mkdir, readFile, stat, unlink, writeFile } from "fs/promises";
15490
15507
  import { dirname, resolve as resolve3 } from "path";
15491
15508
  import { CORE_STORAGE_TOKEN } from "@getstrata/core/contracts/serviceTokens";
15492
15509
  var {S3Client } = globalThis.Bun;
15510
+ function requireStreamingStorage(storage) {
15511
+ if (!("readStream" in storage) || typeof storage.readStream !== "function" || !("writeStream" in storage) || typeof storage.writeStream !== "function")
15512
+ throw new TypeError("Storage does not support streaming.");
15513
+ if (storage instanceof StorageManager)
15514
+ storage.streamingDriver();
15515
+ return storage;
15516
+ }
15517
+ async function openStream(source, missingCode) {
15518
+ const reader = source.getReader();
15519
+ let first;
15520
+ try {
15521
+ first = await reader.read();
15522
+ } catch (error) {
15523
+ reader.releaseLock();
15524
+ if (hasErrorCode(error, missingCode))
15525
+ return null;
15526
+ throw error;
15527
+ }
15528
+ return new ReadableStream({
15529
+ async pull(controller) {
15530
+ try {
15531
+ const next = first ?? await reader.read();
15532
+ first = undefined;
15533
+ if (next.done) {
15534
+ reader.releaseLock();
15535
+ controller.close();
15536
+ } else
15537
+ controller.enqueue(next.value);
15538
+ } catch (error) {
15539
+ reader.releaseLock();
15540
+ controller.error(error);
15541
+ }
15542
+ },
15543
+ async cancel(reason) {
15544
+ try {
15545
+ await reader.cancel(reason);
15546
+ } finally {
15547
+ reader.releaseLock();
15548
+ }
15549
+ }
15550
+ }, { highWaterMark: 0 });
15551
+ }
15493
15552
  function hasErrorCode(error, code) {
15494
15553
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
15495
15554
  }
@@ -15519,6 +15578,24 @@ class LocalStorageDriver {
15519
15578
  throw error;
15520
15579
  }
15521
15580
  }
15581
+ async readStream(path) {
15582
+ const absolutePath = this.resolvePath(path);
15583
+ try {
15584
+ if (!(await stat(absolutePath)).isFile())
15585
+ throw new Error("Storage path is not a file.");
15586
+ } catch (error) {
15587
+ if (hasErrorCode(error, "ENOENT"))
15588
+ return null;
15589
+ throw error;
15590
+ }
15591
+ return openStream(Bun.file(absolutePath).stream(), "ENOENT");
15592
+ }
15593
+ async writeStream(path, contents) {
15594
+ const absolutePath = this.resolvePath(path);
15595
+ await mkdir(dirname(absolutePath), { recursive: true });
15596
+ await Bun.write(absolutePath, contents);
15597
+ return path;
15598
+ }
15522
15599
  async delete(path) {
15523
15600
  try {
15524
15601
  await unlink(this.resolvePath(path));
@@ -15549,6 +15626,33 @@ class S3StorageDriver {
15549
15626
  throw error;
15550
15627
  }
15551
15628
  }
15629
+ readStream(path) {
15630
+ return openStream(this.client.file(path.replace(/^\/+/, "")).stream(), "NoSuchKey");
15631
+ }
15632
+ async writeStream(path, contents) {
15633
+ const file = this.client.file(path.replace(/^\/+/, ""));
15634
+ if (contents instanceof Blob)
15635
+ await file.write(contents);
15636
+ else {
15637
+ const writer = file.writer();
15638
+ try {
15639
+ await contents.pipeTo(new WritableStream({
15640
+ async write(chunk) {
15641
+ await writer.write(chunk);
15642
+ },
15643
+ async close() {
15644
+ await writer.end();
15645
+ }
15646
+ }));
15647
+ } catch (error) {
15648
+ try {
15649
+ await writer.end(error instanceof Error ? error : new Error(String(error)));
15650
+ } catch {}
15651
+ throw error;
15652
+ }
15653
+ }
15654
+ return path;
15655
+ }
15552
15656
  async delete(path) {
15553
15657
  try {
15554
15658
  await this.client.unlink(path.replace(/^\/+/, ""));
@@ -15571,6 +15675,19 @@ class StorageManager {
15571
15675
  get(path) {
15572
15676
  return this.driver.get(path);
15573
15677
  }
15678
+ streamingDriver() {
15679
+ return requireStreamingStorage(this.driver);
15680
+ }
15681
+ readStream(path) {
15682
+ if (!("readStream" in this.driver) || typeof this.driver.readStream !== "function")
15683
+ return Promise.reject(new TypeError("Storage driver does not support streaming reads."));
15684
+ return this.driver.readStream(path);
15685
+ }
15686
+ writeStream(path, contents) {
15687
+ if (!("writeStream" in this.driver) || typeof this.driver.writeStream !== "function")
15688
+ return Promise.reject(new TypeError("Storage driver does not support streaming writes."));
15689
+ return this.driver.writeStream(path, contents);
15690
+ }
15574
15691
  delete(path) {
15575
15692
  return this.driver.delete(path);
15576
15693
  }
@@ -15664,25 +15781,25 @@ function runWithTenantDatabase(selected, policy, tenant, callback) {
15664
15781
  }
15665
15782
  // ../../src/core/tenant/tenantMiddleware.ts
15666
15783
  import { createHash as createHash8 } from "crypto";
15667
- import { ForbiddenError as ForbiddenError14 } from "@getstrata/core/errors/http";
15784
+ import { ForbiddenError as ForbiddenError13 } from "@getstrata/core/errors/http";
15668
15785
 
15669
15786
  // ../../src/core/tenant/publicTenantHost.ts
15670
15787
  import { BlockList, isIP as isIP2 } from "net";
15671
- import { ForbiddenError as ForbiddenError13 } from "@getstrata/core/errors/http";
15788
+ import { ForbiddenError as ForbiddenError12 } from "@getstrata/core/errors/http";
15672
15789
  function normalizeTenantHostname(authority) {
15673
15790
  if (!authority || authority !== authority.trim() || /[\s\\/@?#%,]/.test(authority)) {
15674
- throw new ForbiddenError13("Invalid tenant hostname.");
15791
+ throw new ForbiddenError12("Invalid tenant hostname.");
15675
15792
  }
15676
15793
  let url;
15677
15794
  try {
15678
15795
  url = new URL(`http://${authority}`);
15679
15796
  } catch {
15680
- throw new ForbiddenError13("Invalid tenant hostname.");
15797
+ throw new ForbiddenError12("Invalid tenant hostname.");
15681
15798
  }
15682
15799
  const hostname = url.hostname.toLowerCase().replace(/\.$/, "");
15683
15800
  const ip = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
15684
15801
  if (!isIP2(ip) && (hostname.length > 253 || !hostname.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)))) {
15685
- throw new ForbiddenError13("Invalid tenant hostname.");
15802
+ throw new ForbiddenError12("Invalid tenant hostname.");
15686
15803
  }
15687
15804
  return hostname;
15688
15805
  }
@@ -15705,7 +15822,7 @@ function createPublicTenantSelector(options) {
15705
15822
  const authority = forwarded ?? request.headers.get("host") ?? new URL(request.url).host;
15706
15823
  const id = await options.resolveTenantId(normalizeTenantHostname(authority));
15707
15824
  if (id === null)
15708
- throw new ForbiddenError13("Tenant host not found.");
15825
+ throw new ForbiddenError12("Tenant host not found.");
15709
15826
  if (!Number.isSafeInteger(id) || id <= 0)
15710
15827
  throw new Error("Public tenant resolver returned an invalid identity.");
15711
15828
  return id;
@@ -15731,40 +15848,40 @@ async function resolveTenantForRequest(request, options, resolver, selectPublicT
15731
15848
  const userTenantId = await options.userTenantId(userId);
15732
15849
  if (!isGlobalAdmin(user)) {
15733
15850
  if (Number.isSafeInteger(parsedHeader) && parsedHeader > 0 && parsedHeader !== userTenantId) {
15734
- throw new ForbiddenError14("Tenant header does not match your account.");
15851
+ throw new ForbiddenError13("Tenant header does not match your account.");
15735
15852
  }
15736
15853
  const memberTenant = await resolver(userTenantId);
15737
15854
  if (memberTenant) {
15738
15855
  return memberTenant;
15739
15856
  }
15740
- throw new ForbiddenError14("Tenant not found.");
15857
+ throw new ForbiddenError13("Tenant not found.");
15741
15858
  }
15742
15859
  if (Number.isSafeInteger(parsedHeader) && parsedHeader > 0) {
15743
15860
  const headerTenant = await resolver(parsedHeader);
15744
15861
  if (headerTenant) {
15745
15862
  return headerTenant;
15746
15863
  }
15747
- throw new ForbiddenError14("Tenant not found.");
15864
+ throw new ForbiddenError13("Tenant not found.");
15748
15865
  }
15749
15866
  const adminTenant = await resolver(userTenantId);
15750
15867
  if (adminTenant) {
15751
15868
  return adminTenant;
15752
15869
  }
15753
- throw new ForbiddenError14("Tenant not found.");
15870
+ throw new ForbiddenError13("Tenant not found.");
15754
15871
  }
15755
15872
  }
15756
15873
  const headerTenantId = Number.isSafeInteger(parsedHeader) && parsedHeader > 0 ? parsedHeader : null;
15757
15874
  const tenantId = hostTenantId !== null ? hostTenantId : !options.config.production && options.config.allowDevHeaders && headerTenantId !== null ? headerTenantId : DEFAULT_TENANT.id;
15758
15875
  if (options.config.production && !selectPublicTenant) {
15759
- throw new ForbiddenError14("Public tenant host resolver is required.");
15876
+ throw new ForbiddenError13("Public tenant host resolver is required.");
15760
15877
  }
15761
15878
  const guestTenant = await resolver(tenantId);
15762
15879
  if (selectPublicTenant && !guestTenant)
15763
- throw new ForbiddenError14("Tenant not found.");
15880
+ throw new ForbiddenError13("Tenant not found.");
15764
15881
  if (guestTenant) {
15765
15882
  return guestTenant;
15766
15883
  }
15767
- throw new ForbiddenError14("Tenant not found.");
15884
+ throw new ForbiddenError13("Tenant not found.");
15768
15885
  }
15769
15886
  function createTenantMiddleware(options) {
15770
15887
  const selectPublicTenant = options.publicTenancy ? createPublicTenantSelector(options.publicTenancy) : undefined;
@@ -15772,7 +15889,7 @@ function createTenantMiddleware(options) {
15772
15889
  const tenant = !options.config.enabled ? DEFAULT_TENANT : await resolveTenantForRequest(request, options, async (id) => {
15773
15890
  const value = await options.resolveTenant(id);
15774
15891
  if (!value)
15775
- throw new ForbiddenError14("Tenant not found.");
15892
+ throw new ForbiddenError13("Tenant not found.");
15776
15893
  if (value.id !== id)
15777
15894
  throw new Error("Tenant resolver returned a different tenant identity.");
15778
15895
  return value;
@@ -16130,7 +16247,7 @@ function createTracingMiddleware(runtime) {
16130
16247
  };
16131
16248
  }
16132
16249
  // ../../src/core/validation/rules.ts
16133
- import { ValidationError as ValidationError4 } from "@getstrata/core/errors/http";
16250
+ import { ValidationError as ValidationError3 } from "@getstrata/core/errors/http";
16134
16251
  function required() {
16135
16252
  return (field, value) => {
16136
16253
  if (value === undefined || value === null || typeof value === "string" && value.trim() === "") {
@@ -16186,7 +16303,7 @@ function emailRule() {
16186
16303
  }
16187
16304
  function validateObject(payload, schema) {
16188
16305
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
16189
- throw new ValidationError4("Request body must be a JSON object.");
16306
+ throw new ValidationError3("Request body must be a JSON object.");
16190
16307
  }
16191
16308
  const body = payload;
16192
16309
  const errors = {};
@@ -16203,7 +16320,7 @@ function validateObject(payload, schema) {
16203
16320
  }
16204
16321
  }
16205
16322
  if (Object.keys(errors).length > 0) {
16206
- throw new ValidationError4("The given data was invalid.", errors);
16323
+ throw new ValidationError3("The given data was invalid.", errors);
16207
16324
  }
16208
16325
  return output;
16209
16326
  }
@@ -16633,7 +16750,7 @@ export {
16633
16750
  Factory,
16634
16751
  FailedJobRepository,
16635
16752
  failedJobService_default as FailedJobService,
16636
- ForbiddenError15 as ForbiddenError,
16753
+ ForbiddenError14 as ForbiddenError,
16637
16754
  ForeignIdColumnDefinition,
16638
16755
  FormRequest,
16639
16756
  GuestGuard,
@@ -16699,7 +16816,7 @@ export {
16699
16816
  UnauthorizedError4 as UnauthorizedError,
16700
16817
  UnprocessableEntityError5 as UnprocessableEntityError,
16701
16818
  UnsupportedSchemaFeatureError,
16702
- ValidationError5 as ValidationError,
16819
+ ValidationError4 as ValidationError,
16703
16820
  ViewRenderer,
16704
16821
  WebFormRequest,
16705
16822
  WhereBuilder,
@@ -16785,9 +16902,10 @@ export {
16785
16902
  createMemoryLoginThrottleMiddleware,
16786
16903
  createMemoryThrottleMiddleware,
16787
16904
  createMetricsMiddleware,
16905
+ createModel,
16788
16906
  createMysqlConnection,
16789
16907
  createMysqlConnectionFromPool,
16790
- createMysqlPool,
16908
+ createMysqlPool2 as createMysqlPool,
16791
16909
  createNotificationDispatcher,
16792
16910
  createOidcHandshake,
16793
16911
  createOutboxMetricsCollector,
@@ -16833,6 +16951,7 @@ export {
16833
16951
  currentTraceId,
16834
16952
  defineFactory,
16835
16953
  defineModel,
16954
+ defineProvider,
16836
16955
  defineRepository2 as defineRepository,
16837
16956
  defineTable,
16838
16957
  dehydrateValue,
@@ -16964,11 +17083,8 @@ export {
16964
17083
  requestMetaContext,
16965
17084
  requireAuthCapability,
16966
17085
  requireConfiguredSecret,
17086
+ requireStreamingStorage,
16967
17087
  required,
16968
- resetDnsLookupForTests,
16969
- resetMemoryLoginThrottleForTests,
16970
- resetMemoryThrottleForTests,
16971
- resetMysqlLoaderForTests,
16972
17088
  resolveContentSecurityPolicy,
16973
17089
  resolveCsrfToken,
16974
17090
  resolveCsrfTokenForRequest,
@@ -17018,8 +17134,6 @@ export {
17018
17134
  serializeDate,
17019
17135
  serverHtmxContentSecurityPolicy,
17020
17136
  service3 as service,
17021
- setDnsLookupForTests,
17022
- setNodeSamlLoaderForTests,
17023
17137
  siemEventType,
17024
17138
  signJwt,
17025
17139
  signWebhookBody,