@getstrata/core 3.0.5 → 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 (83) hide show
  1. package/CHANGELOG.md +18 -9
  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/store.d.ts +2 -2
  6. package/dist/core/cache/tokens.d.ts +1 -1
  7. package/dist/core/config/envSchema.d.ts +13 -0
  8. package/dist/core/contracts/application.d.ts +4 -0
  9. package/dist/core/contracts/di.d.ts +2 -2
  10. package/dist/core/contracts/provider.d.ts +13 -0
  11. package/dist/core/contracts/serviceTokens.d.ts +12 -11
  12. package/dist/core/database/factory.d.ts +3 -0
  13. package/dist/core/database/index.d.ts +1 -1
  14. package/dist/core/database/migrations/declaration.d.ts +11 -0
  15. package/dist/core/database/migrations/runner.d.ts +2 -0
  16. package/dist/core/database/model.d.ts +16 -3
  17. package/dist/core/database/modelQuery.d.ts +1 -10
  18. package/dist/core/database/modelRelationLoader.d.ts +31 -0
  19. package/dist/core/database/mysqlConnection.d.ts +2 -2
  20. package/dist/core/database/mysqlNative.d.ts +2 -0
  21. package/dist/core/database/ormRuntime.d.ts +1 -1
  22. package/dist/core/database/rawMysql.d.ts +1 -1
  23. package/dist/core/events/eventBusClass.d.ts +6 -3
  24. package/dist/core/events/index.d.ts +1 -1
  25. package/dist/core/http/formRequest.d.ts +2 -0
  26. package/dist/core/http/loginThrottleMiddleware.d.ts +1 -2
  27. package/dist/core/http/memoryThrottleMiddleware.d.ts +1 -3
  28. package/dist/core/http/webFormRequest.d.ts +3 -5
  29. package/dist/core/mail/mailer.d.ts +6 -3
  30. package/dist/core/mail/markdownMailable.d.ts +2 -2
  31. package/dist/core/notifications/dispatcher.d.ts +5 -5
  32. package/dist/core/notifications/index.d.ts +1 -1
  33. package/dist/core/notifications/types.d.ts +9 -2
  34. package/dist/core/queue/index.d.ts +8 -3
  35. package/dist/core/queue/queueHandoff.d.ts +2 -2
  36. package/dist/core/runtime/application.d.ts +2 -0
  37. package/dist/core/security/oauthState.d.ts +12 -2
  38. package/dist/core/security/safeUrl.d.ts +1 -11
  39. package/dist/core/storage/storage.d.ts +23 -6
  40. package/dist/core/testing.d.ts +5 -0
  41. package/dist/core/testingState.d.ts +22 -0
  42. package/dist/entries/audit/exportAuditLogs.js +1 -0
  43. package/dist/entries/auth/intendedUrlCookie.js +68 -2
  44. package/dist/entries/auth/jwt.js +68 -6
  45. package/dist/entries/auth/jwtGuard.js +76 -12
  46. package/dist/entries/auth/oauth/samlProvider.js +4 -5
  47. package/dist/entries/auth/passwordConfirmCookie.js +69 -3
  48. package/dist/entries/auth/saml/samlServiceProvider.js +5 -7
  49. package/dist/entries/auth/sessionCookie.js +69 -6
  50. package/dist/entries/auth/sessionGuard.js +69 -6
  51. package/dist/entries/cache/repository.js +4 -5
  52. package/dist/entries/config/envSchema.js +13 -0
  53. package/dist/entries/contracts/serviceTokens.js +2 -0
  54. package/dist/entries/database/bindings.js +18 -90
  55. package/dist/entries/database/factory.js +4 -0
  56. package/dist/entries/database/migrations.js +714 -1
  57. package/dist/entries/http/formRequest.js +12 -6
  58. package/dist/entries/http/memoryThrottleMiddleware.js +7 -9
  59. package/dist/entries/http/pagination.js +4 -4
  60. package/dist/entries/http/parseMultipartUpload.js +62 -9
  61. package/dist/entries/http/routeModelBinding.js +4 -4
  62. package/dist/entries/http/securedRouteModelBinding.js +4 -4
  63. package/dist/entries/http/uploads.js +62 -9
  64. package/dist/entries/http/validation.js +4 -4
  65. package/dist/entries/http/webFormRequest.js +74 -95
  66. package/dist/entries/jobs/exportAuditLogsJob.js +9 -4
  67. package/dist/entries/jobs/invalidateCacheTagsJob.js +9 -4
  68. package/dist/entries/queue/createAppQueue.js +10 -5
  69. package/dist/entries/queue/publicQueue.js +10 -5
  70. package/dist/entries/queue/queueWorkerTransport.js +10 -5
  71. package/dist/entries/queue.js +9 -4
  72. package/dist/entries/runtime/application.js +50 -3
  73. package/dist/entries/security/oauthState.js +61 -2
  74. package/dist/entries/security/tokenExpiry.js +62 -9
  75. package/dist/entries/storage/storage.js +102 -1
  76. package/dist/entries/testing.js +18 -0
  77. package/dist/framework/public-api.d.ts +16 -13
  78. package/dist/index.js +316 -222
  79. package/dist/internal/mysqlNative.js +97 -0
  80. package/dist/internal/ormRuntime.js +41 -4
  81. package/dist/internal/testingState.js +31 -0
  82. package/dist/types/services.d.ts +4 -1
  83. package/package.json +17 -4
@@ -1534,6 +1534,14 @@ class AsyncQueue {
1534
1534
  if (this.closed)
1535
1535
  throw new Error("Async queue is closed.");
1536
1536
  }
1537
+ track(running) {
1538
+ const settled = running.then(() => {}, () => {});
1539
+ this.active.add(settled);
1540
+ settled.then(() => {
1541
+ this.active.delete(settled);
1542
+ });
1543
+ return running;
1544
+ }
1537
1545
  enqueue(task, onError) {
1538
1546
  this.assertOpen();
1539
1547
  const running = new Promise((resolve) => {
@@ -1541,10 +1549,7 @@ class AsyncQueue {
1541
1549
  Promise.resolve().then(task).catch(onError).finally(resolve);
1542
1550
  }, 0);
1543
1551
  });
1544
- this.active.add(running);
1545
- running.then(() => {
1546
- this.active.delete(running);
1547
- });
1552
+ this.track(running);
1548
1553
  }
1549
1554
  async dispatch(job, payload, options) {
1550
1555
  if (options?.handoff !== undefined)
@@ -1606,7 +1611,7 @@ class ResilientQueue extends AsyncQueue {
1606
1611
  });
1607
1612
  return;
1608
1613
  }
1609
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1614
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1610
1615
  }
1611
1616
  }
1612
1617
 
@@ -1531,6 +1531,14 @@ class AsyncQueue {
1531
1531
  if (this.closed)
1532
1532
  throw new Error("Async queue is closed.");
1533
1533
  }
1534
+ track(running) {
1535
+ const settled = running.then(() => {}, () => {});
1536
+ this.active.add(settled);
1537
+ settled.then(() => {
1538
+ this.active.delete(settled);
1539
+ });
1540
+ return running;
1541
+ }
1534
1542
  enqueue(task, onError) {
1535
1543
  this.assertOpen();
1536
1544
  const running = new Promise((resolve) => {
@@ -1538,10 +1546,7 @@ class AsyncQueue {
1538
1546
  Promise.resolve().then(task).catch(onError).finally(resolve);
1539
1547
  }, 0);
1540
1548
  });
1541
- this.active.add(running);
1542
- running.then(() => {
1543
- this.active.delete(running);
1544
- });
1549
+ this.track(running);
1545
1550
  }
1546
1551
  async dispatch(job, payload, options) {
1547
1552
  if (options?.handoff !== undefined)
@@ -1603,7 +1608,7 @@ class ResilientQueue extends AsyncQueue {
1603
1608
  });
1604
1609
  return;
1605
1610
  }
1606
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1611
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1607
1612
  }
1608
1613
  }
1609
1614
 
@@ -1531,6 +1531,14 @@ class AsyncQueue {
1531
1531
  if (this.closed)
1532
1532
  throw new Error("Async queue is closed.");
1533
1533
  }
1534
+ track(running) {
1535
+ const settled = running.then(() => {}, () => {});
1536
+ this.active.add(settled);
1537
+ settled.then(() => {
1538
+ this.active.delete(settled);
1539
+ });
1540
+ return running;
1541
+ }
1534
1542
  enqueue(task, onError) {
1535
1543
  this.assertOpen();
1536
1544
  const running = new Promise((resolve) => {
@@ -1538,10 +1546,7 @@ class AsyncQueue {
1538
1546
  Promise.resolve().then(task).catch(onError).finally(resolve);
1539
1547
  }, 0);
1540
1548
  });
1541
- this.active.add(running);
1542
- running.then(() => {
1543
- this.active.delete(running);
1544
- });
1549
+ this.track(running);
1545
1550
  }
1546
1551
  async dispatch(job, payload, options) {
1547
1552
  if (options?.handoff !== undefined)
@@ -1603,7 +1608,7 @@ class ResilientQueue extends AsyncQueue {
1603
1608
  });
1604
1609
  return;
1605
1610
  }
1606
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1611
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1607
1612
  }
1608
1613
  }
1609
1614
 
@@ -23,6 +23,14 @@ class AsyncQueue {
23
23
  if (this.closed)
24
24
  throw new Error("Async queue is closed.");
25
25
  }
26
+ track(running) {
27
+ const settled = running.then(() => {}, () => {});
28
+ this.active.add(settled);
29
+ settled.then(() => {
30
+ this.active.delete(settled);
31
+ });
32
+ return running;
33
+ }
26
34
  enqueue(task, onError) {
27
35
  this.assertOpen();
28
36
  const running = new Promise((resolve) => {
@@ -30,10 +38,7 @@ class AsyncQueue {
30
38
  Promise.resolve().then(task).catch(onError).finally(resolve);
31
39
  }, 0);
32
40
  });
33
- this.active.add(running);
34
- running.then(() => {
35
- this.active.delete(running);
36
- });
41
+ this.track(running);
37
42
  }
38
43
  async dispatch(job, payload, options) {
39
44
  if (options?.handoff !== undefined)
@@ -959,6 +959,32 @@ import {
959
959
  service as service2,
960
960
  valueService as valueService2
961
961
  } from "@getstrata/core/contracts/services";
962
+
963
+ // ../../src/core/contracts/provider.ts
964
+ function defineProvider(options) {
965
+ const { name, requires, services, setup, boot } = options;
966
+ if (typeof name !== "string" || name.trim().length === 0) {
967
+ throw new TypeError("Provider names must be nonempty strings.");
968
+ }
969
+ if (requires !== undefined && (!Array.isArray(requires) || requires.some((name) => typeof name !== "string" || name.trim().length === 0))) {
970
+ throw new TypeError("Provider dependencies must be an array of nonempty names.");
971
+ }
972
+ if (services !== undefined && !Array.isArray(services)) {
973
+ throw new TypeError("Provider services must be an array.");
974
+ }
975
+ if (setup !== undefined && typeof setup !== "function" || boot !== undefined && typeof boot !== "function") {
976
+ throw new TypeError("Provider hooks must be functions.");
977
+ }
978
+ return Object.freeze({
979
+ name,
980
+ requires: Object.freeze([...requires ?? []]),
981
+ services: Object.freeze([...services ?? []]),
982
+ setup: setup ?? (() => {}),
983
+ ...boot ? { boot } : {}
984
+ });
985
+ }
986
+
987
+ // ../../src/core/runtime/application.ts
962
988
  function deferred() {
963
989
  let resolve;
964
990
  let reject;
@@ -1045,6 +1071,12 @@ function normalize(input) {
1045
1071
  if (item.requires !== undefined && !Array.isArray(item.requires)) {
1046
1072
  throw new TypeError("Provider dependencies must be an array.");
1047
1073
  }
1074
+ if (item.services !== undefined && !Array.isArray(item.services)) {
1075
+ throw new TypeError("Provider services must be an array.");
1076
+ }
1077
+ if (item.boot !== undefined && typeof item.boot !== "function") {
1078
+ throw new TypeError("Provider boot must be a function.");
1079
+ }
1048
1080
  const requires = [...item.requires ?? []];
1049
1081
  for (const dependency of requires)
1050
1082
  declarationName2(dependency);
@@ -1052,6 +1084,8 @@ function normalize(input) {
1052
1084
  return Object.freeze({
1053
1085
  name: item.name,
1054
1086
  setup: item.setup,
1087
+ ...item.boot ? { boot: item.boot } : {},
1088
+ services: Object.freeze([...item.services ?? []]),
1055
1089
  requires: Object.freeze(requires)
1056
1090
  });
1057
1091
  });
@@ -1090,7 +1124,11 @@ function normalize(input) {
1090
1124
  transports: orderedTransports,
1091
1125
  shutdownTimeoutMs: timeout(input.shutdownTimeoutMs),
1092
1126
  startupCleanupTimeoutMs: timeout(input.startupCleanupTimeoutMs),
1093
- services: compileServiceGraph(input.services, input.overrides)
1127
+ services: compileServiceGraph([
1128
+ ...input.services ?? [],
1129
+ ...providers.flatMap((item) => item.services ?? []),
1130
+ ...transports.flatMap((item) => item.services ?? [])
1131
+ ], input.overrides)
1094
1132
  };
1095
1133
  }
1096
1134
 
@@ -1431,7 +1469,15 @@ class OwnedApplication {
1431
1469
  await this.definition.services.start(this.services, this.cancellation.signal, {
1432
1470
  acquire: (group, spec, signal, validate) => this.journal.acquire(group, spec, signal, validate)
1433
1471
  });
1434
- for (const provider of [...this.definition.providers, ...this.definition.transports]) {
1472
+ const hooks = [
1473
+ ...this.definition.providers.map((provider) => ({ provider, hook: provider.setup })),
1474
+ ...this.definition.providers.flatMap((provider) => provider.boot ? [{ provider, hook: provider.boot }] : []),
1475
+ ...this.definition.transports.flatMap((provider) => [
1476
+ { provider, hook: provider.setup },
1477
+ ...provider.boot ? [{ provider, hook: provider.boot }] : []
1478
+ ])
1479
+ ];
1480
+ for (const { provider, hook } of hooks) {
1435
1481
  if (this.cancellation.signal.aborted)
1436
1482
  throw this.cancelled;
1437
1483
  let active = true;
@@ -1454,7 +1500,7 @@ class OwnedApplication {
1454
1500
  return result;
1455
1501
  }
1456
1502
  });
1457
- const operation = leasedOperation(() => provider.setup(scope), () => {
1503
+ const operation = leasedOperation(() => hook(scope), () => {
1458
1504
  active = false;
1459
1505
  });
1460
1506
  operation.invoke();
@@ -1579,6 +1625,7 @@ export {
1579
1625
  CORE_EXECUTION_CONTEXT_TOKEN2 as CORE_EXECUTION_CONTEXT_TOKEN,
1580
1626
  aliasService2 as aliasService,
1581
1627
  createApplication,
1628
+ defineProvider,
1582
1629
  resourceService2 as resourceService,
1583
1630
  service2 as service,
1584
1631
  valueService2 as valueService
@@ -2,6 +2,38 @@
2
2
  // ../../src/core/security/oauthState.ts
3
3
  import { createHmac, randomBytes, timingSafeEqual } from "crypto";
4
4
 
5
+ // ../../src/core/http/cookies.ts
6
+ function readRequestCookie(request, name) {
7
+ const cookies = request.cookies;
8
+ if (cookies && typeof cookies.get === "function") {
9
+ const value = cookies.get(name);
10
+ if (value) {
11
+ return value;
12
+ }
13
+ }
14
+ const header = request.headers.get("cookie");
15
+ if (!header) {
16
+ return null;
17
+ }
18
+ for (const part of header.split(";")) {
19
+ const idx = part.indexOf("=");
20
+ if (idx === -1)
21
+ continue;
22
+ const cookieName = part.slice(0, idx).trim();
23
+ if (cookieName !== name)
24
+ continue;
25
+ try {
26
+ return decodeURIComponent(part.slice(idx + 1).trim());
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ function readBunRequestCookie(request, name) {
34
+ return request.cookies.get(name) ?? readRequestCookie(request, name);
35
+ }
36
+
5
37
  // ../../src/core/runtime/appEnv.ts
6
38
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
7
39
  function normalizeEnvValue(value) {
@@ -58,6 +90,7 @@ function otelServiceName(env = process.env) {
58
90
 
59
91
  // ../../src/core/security/oauthState.ts
60
92
  var OAUTH_STATE_COOKIE = "oauth_state";
93
+ var SAML_STATE_COOKIE = "saml_state";
61
94
  var OIDC_PKCE_COOKIE = "oidc_pkce";
62
95
  var OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
63
96
  function resolveOAuthStateSecret() {
@@ -104,11 +137,33 @@ function createOAuthStateCookie(options) {
104
137
  cookie: `${OAUTH_STATE_COOKIE}=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${options?.production ?? isProductionEnv() ? "; Secure" : ""}`
105
138
  };
106
139
  }
107
- function verifyOAuthState(_request, returnedState, options) {
140
+ function verifyOAuthState(request, returnedState, options) {
141
+ return verifyBrowserState(request, returnedState, OAUTH_STATE_COOKIE, options);
142
+ }
143
+ function verifyBrowserState(request, returnedState, cookieName, options) {
108
144
  if (!returnedState || returnedState.trim().length === 0) {
109
145
  return false;
110
146
  }
111
- return verifySignedOAuthStateValue(returnedState.trim(), options);
147
+ const state = returnedState.trim();
148
+ const cookie = readRequestCookie(request, cookieName);
149
+ if (!cookie)
150
+ return false;
151
+ const expected = Buffer.from(cookie);
152
+ const actual = Buffer.from(state);
153
+ return expected.length === actual.length && timingSafeEqual(expected, actual) && verifySignedOAuthStateValue(state, options);
154
+ }
155
+ function createSamlStateCookie(options) {
156
+ const { state } = createOAuthState(options);
157
+ return {
158
+ state,
159
+ cookie: `${SAML_STATE_COOKIE}=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=None; Max-Age=600; Secure`
160
+ };
161
+ }
162
+ function verifySamlState(request, returnedState, options) {
163
+ return verifyBrowserState(request, returnedState, SAML_STATE_COOKIE, options);
164
+ }
165
+ function clearSamlStateCookie() {
166
+ return `${SAML_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=None; Max-Age=0; Secure`;
112
167
  }
113
168
  function clearOAuthStateCookie(options) {
114
169
  return `${OAUTH_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${options?.production ?? isProductionEnv() ? "; Secure" : ""}`;
@@ -186,12 +241,16 @@ function unsealOidcPkceValue(rawValue, returnedState, options) {
186
241
  export {
187
242
  OAUTH_STATE_COOKIE,
188
243
  OIDC_PKCE_COOKIE,
244
+ SAML_STATE_COOKIE,
189
245
  clearOAuthStateCookie,
190
246
  clearOidcPkceCookie,
247
+ clearSamlStateCookie,
191
248
  createOAuthState,
192
249
  createOAuthStateCookie,
250
+ createSamlStateCookie,
193
251
  readOidcPkceCookie,
194
252
  sealOidcPkceCookie,
195
253
  verifyOAuthState,
254
+ verifySamlState,
196
255
  verifySignedOAuthStateValue
197
256
  };
@@ -1,15 +1,68 @@
1
1
  // @bun
2
- // ../../src/core/security/tokenExpiry.ts
3
- function resolveDefaultTokenExpiryDays(value) {
4
- const raw = value?.trim();
5
- if (!raw) {
6
- return null;
2
+ // ../../src/core/config/envSchema.ts
3
+ function defineEnvSchema(schema) {
4
+ return schema;
5
+ }
6
+ function validateEnv(schema, env = process.env) {
7
+ const resolved = {};
8
+ for (const [name, rule] of Object.entries(schema)) {
9
+ if (rule.integer) {
10
+ if (rule.minimum !== undefined && !Number.isSafeInteger(rule.minimum) || rule.maximum !== undefined && !Number.isSafeInteger(rule.maximum) || rule.minimum !== undefined && rule.maximum !== undefined && rule.minimum > rule.maximum) {
11
+ throw new TypeError(`Environment integer rule for "${name}" has invalid bounds.`);
12
+ }
13
+ }
14
+ const rawValue = env[name];
15
+ if (rawValue !== undefined && typeof rawValue !== "string") {
16
+ throw new TypeError(`Environment variable "${name}" must be a string.`);
17
+ }
18
+ const value = rawValue === undefined || rawValue.trim() === "" ? rule.default : rawValue;
19
+ if (value !== undefined && typeof value !== "string") {
20
+ throw new TypeError(`Environment variable "${name}" must resolve to a string.`);
21
+ }
22
+ if (value === undefined || value.trim() === "") {
23
+ if (rule.required) {
24
+ throw new Error(`Missing required environment variable "${name}".`);
25
+ }
26
+ continue;
27
+ }
28
+ if (rule.integer) {
29
+ const completeInteger = /^[+-]?\d+$/.test(value.trim());
30
+ const parsed = Number.parseInt(value, 10);
31
+ const minimum = rule.minimum ?? Number.NEGATIVE_INFINITY;
32
+ const maximum = rule.maximum ?? Number.POSITIVE_INFINITY;
33
+ if (!completeInteger || !Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {
34
+ const comparison = minimum !== Number.NEGATIVE_INFINITY && maximum !== Number.POSITIVE_INFINITY ? `an integer between ${minimum} and ${maximum}` : maximum !== Number.POSITIVE_INFINITY ? `an integer <= ${maximum}` : minimum === Number.NEGATIVE_INFINITY ? "an integer" : `an integer >= ${minimum}`;
35
+ throw new Error(`Environment variable "${name}" must be ${comparison}.`);
36
+ }
37
+ }
38
+ if (rule.pattern && !new RegExp(rule.pattern.source, rule.pattern.flags).test(value)) {
39
+ throw new Error(`Environment variable "${name}" has an invalid format.`);
40
+ }
41
+ Object.defineProperty(resolved, name, {
42
+ value,
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true
46
+ });
7
47
  }
8
- const parsed = Number.parseInt(raw, 10);
9
- if (!Number.isInteger(parsed) || parsed <= 0) {
10
- return null;
48
+ return resolved;
49
+ }
50
+ function resolveEnv(schema, env = process.env) {
51
+ const validated = validateEnv(schema, env);
52
+ const resolved = {};
53
+ for (const [name, rule] of Object.entries(schema)) {
54
+ const value = validated[name];
55
+ Object.defineProperty(resolved, name, {
56
+ value: value === undefined ? undefined : rule.integer ? Number(value) : value,
57
+ enumerable: true
58
+ });
11
59
  }
12
- return parsed;
60
+ return Object.freeze(resolved);
61
+ }
62
+
63
+ // ../../src/core/security/tokenExpiry.ts
64
+ function resolveDefaultTokenExpiryDays(value) {
65
+ return resolveEnv({ API_TOKEN_DEFAULT_EXPIRY_DAYS: { integer: true, minimum: 1 } }, { API_TOKEN_DEFAULT_EXPIRY_DAYS: value }).API_TOKEN_DEFAULT_EXPIRY_DAYS ?? null;
13
66
  }
14
67
  export {
15
68
  resolveDefaultTokenExpiryDays
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // ../../src/core/storage/storage.ts
3
- import { mkdir, readFile, unlink, writeFile } from "fs/promises";
3
+ import { mkdir, readFile, stat, unlink, writeFile } from "fs/promises";
4
4
  import { dirname, resolve as resolve2 } from "path";
5
5
  import { CORE_STORAGE_TOKEN } from "@getstrata/core/contracts/serviceTokens";
6
6
  var {S3Client } = globalThis.Bun;
@@ -81,6 +81,48 @@ function assertUrlPathUnderRoot(rootDirectory, urlPathname) {
81
81
  }
82
82
 
83
83
  // ../../src/core/storage/storage.ts
84
+ function requireStreamingStorage(storage) {
85
+ if (!("readStream" in storage) || typeof storage.readStream !== "function" || !("writeStream" in storage) || typeof storage.writeStream !== "function")
86
+ throw new TypeError("Storage does not support streaming.");
87
+ if (storage instanceof StorageManager)
88
+ storage.streamingDriver();
89
+ return storage;
90
+ }
91
+ async function openStream(source, missingCode) {
92
+ const reader = source.getReader();
93
+ let first;
94
+ try {
95
+ first = await reader.read();
96
+ } catch (error) {
97
+ reader.releaseLock();
98
+ if (hasErrorCode(error, missingCode))
99
+ return null;
100
+ throw error;
101
+ }
102
+ return new ReadableStream({
103
+ async pull(controller) {
104
+ try {
105
+ const next = first ?? await reader.read();
106
+ first = undefined;
107
+ if (next.done) {
108
+ reader.releaseLock();
109
+ controller.close();
110
+ } else
111
+ controller.enqueue(next.value);
112
+ } catch (error) {
113
+ reader.releaseLock();
114
+ controller.error(error);
115
+ }
116
+ },
117
+ async cancel(reason) {
118
+ try {
119
+ await reader.cancel(reason);
120
+ } finally {
121
+ reader.releaseLock();
122
+ }
123
+ }
124
+ }, { highWaterMark: 0 });
125
+ }
84
126
  function hasErrorCode(error, code) {
85
127
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
86
128
  }
@@ -110,6 +152,24 @@ class LocalStorageDriver {
110
152
  throw error;
111
153
  }
112
154
  }
155
+ async readStream(path) {
156
+ const absolutePath = this.resolvePath(path);
157
+ try {
158
+ if (!(await stat(absolutePath)).isFile())
159
+ throw new Error("Storage path is not a file.");
160
+ } catch (error) {
161
+ if (hasErrorCode(error, "ENOENT"))
162
+ return null;
163
+ throw error;
164
+ }
165
+ return openStream(Bun.file(absolutePath).stream(), "ENOENT");
166
+ }
167
+ async writeStream(path, contents) {
168
+ const absolutePath = this.resolvePath(path);
169
+ await mkdir(dirname(absolutePath), { recursive: true });
170
+ await Bun.write(absolutePath, contents);
171
+ return path;
172
+ }
113
173
  async delete(path) {
114
174
  try {
115
175
  await unlink(this.resolvePath(path));
@@ -140,6 +200,33 @@ class S3StorageDriver {
140
200
  throw error;
141
201
  }
142
202
  }
203
+ readStream(path) {
204
+ return openStream(this.client.file(path.replace(/^\/+/, "")).stream(), "NoSuchKey");
205
+ }
206
+ async writeStream(path, contents) {
207
+ const file = this.client.file(path.replace(/^\/+/, ""));
208
+ if (contents instanceof Blob)
209
+ await file.write(contents);
210
+ else {
211
+ const writer = file.writer();
212
+ try {
213
+ await contents.pipeTo(new WritableStream({
214
+ async write(chunk) {
215
+ await writer.write(chunk);
216
+ },
217
+ async close() {
218
+ await writer.end();
219
+ }
220
+ }));
221
+ } catch (error) {
222
+ try {
223
+ await writer.end(error instanceof Error ? error : new Error(String(error)));
224
+ } catch {}
225
+ throw error;
226
+ }
227
+ }
228
+ return path;
229
+ }
143
230
  async delete(path) {
144
231
  try {
145
232
  await this.client.unlink(path.replace(/^\/+/, ""));
@@ -162,6 +249,19 @@ class StorageManager {
162
249
  get(path) {
163
250
  return this.driver.get(path);
164
251
  }
252
+ streamingDriver() {
253
+ return requireStreamingStorage(this.driver);
254
+ }
255
+ readStream(path) {
256
+ if (!("readStream" in this.driver) || typeof this.driver.readStream !== "function")
257
+ return Promise.reject(new TypeError("Storage driver does not support streaming reads."));
258
+ return this.driver.readStream(path);
259
+ }
260
+ writeStream(path, contents) {
261
+ if (!("writeStream" in this.driver) || typeof this.driver.writeStream !== "function")
262
+ return Promise.reject(new TypeError("Storage driver does not support streaming writes."));
263
+ return this.driver.writeStream(path, contents);
264
+ }
165
265
  delete(path) {
166
266
  return this.driver.delete(path);
167
267
  }
@@ -238,6 +338,7 @@ export {
238
338
  StorageManager,
239
339
  createS3Client,
240
340
  createStorageDriver,
341
+ requireStreamingStorage,
241
342
  resolveS3Config,
242
343
  resolveStorageConfig,
243
344
  snapshotStorageConfig
@@ -0,0 +1,18 @@
1
+ // @bun
2
+ // ../../src/core/testing.ts
3
+ import { resetMysqlLoaderForTests } from "#strata-mysql-native";
4
+ import {
5
+ resetDnsLookupForTests,
6
+ resetMemoryLoginThrottleForTests,
7
+ resetMemoryThrottleForTests,
8
+ setDnsLookupForTests,
9
+ setNodeSamlLoaderForTests
10
+ } from "#strata-test-state";
11
+ export {
12
+ resetDnsLookupForTests,
13
+ resetMemoryLoginThrottleForTests,
14
+ resetMemoryThrottleForTests,
15
+ resetMysqlLoaderForTests,
16
+ setDnsLookupForTests,
17
+ setNodeSamlLoaderForTests
18
+ };