@getstrata/core 2.2.60 → 3.0.3

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 (330) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/core/audit/exportAuditLogs.d.ts +12 -3
  3. package/dist/core/audit/exportStore.d.ts +6 -2
  4. package/dist/core/audit/siemFormatter.d.ts +2 -2
  5. package/dist/core/auth/abilityCatalog.d.ts +1 -9
  6. package/dist/core/auth/authContext.d.ts +2 -0
  7. package/dist/core/auth/authOutcome.d.ts +32 -0
  8. package/dist/core/auth/authReader.d.ts +22 -0
  9. package/dist/core/auth/basicAuthGuard.d.ts +19 -3
  10. package/dist/core/auth/emailVerification.d.ts +1 -1
  11. package/dist/core/auth/guard.d.ts +27 -6
  12. package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
  13. package/dist/core/auth/jwt.d.ts +5 -4
  14. package/dist/core/auth/jwtGuard.d.ts +7 -6
  15. package/dist/core/auth/membershipContext.d.ts +10 -7
  16. package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
  17. package/dist/core/auth/membershipMiddleware.d.ts +1 -2
  18. package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
  19. package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
  20. package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
  21. package/dist/core/auth/oauth/providers.d.ts +3 -1
  22. package/dist/core/auth/oneTimeToken.d.ts +2 -3
  23. package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
  24. package/dist/core/auth/passwordLogin.d.ts +5 -5
  25. package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
  26. package/dist/core/auth/policy.d.ts +23 -10
  27. package/dist/core/auth/requireAuthCapability.d.ts +3 -0
  28. package/dist/core/auth/resolveMembershipService.d.ts +3 -2
  29. package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
  30. package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
  31. package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
  32. package/dist/core/auth/sessionCookie.d.ts +20 -9
  33. package/dist/core/auth/sessionGuard.d.ts +14 -3
  34. package/dist/core/cache/createCacheStore.d.ts +6 -3
  35. package/dist/core/cache/redisCacheStore.d.ts +5 -1
  36. package/dist/core/cache/repository.d.ts +5 -1
  37. package/dist/core/cache/simpleCache.d.ts +2 -1
  38. package/dist/core/cache/tokens.d.ts +8 -0
  39. package/dist/core/config/applicationConfig.d.ts +21 -0
  40. package/dist/core/config/configSnapshot.d.ts +3 -0
  41. package/dist/core/config/envSchema.d.ts +3 -2
  42. package/dist/core/contracts/application.d.ts +153 -0
  43. package/dist/core/contracts/authUserDirectory.d.ts +24 -7
  44. package/dist/core/contracts/container.d.ts +20 -23
  45. package/dist/core/contracts/di.d.ts +4 -2
  46. package/dist/core/contracts/executionContext.d.ts +5 -0
  47. package/dist/core/contracts/executionOperations.d.ts +10 -0
  48. package/dist/core/contracts/executionOwnership.d.ts +38 -0
  49. package/dist/core/contracts/persistence.d.ts +20 -0
  50. package/dist/core/contracts/serviceTokens.d.ts +32 -18
  51. package/dist/core/contracts/services.d.ts +63 -0
  52. package/dist/core/contracts/token.d.ts +19 -0
  53. package/dist/core/crypto/fieldEncryption.d.ts +19 -7
  54. package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
  55. package/dist/core/crypto/mfaSecret.d.ts +10 -3
  56. package/dist/core/database/baseRepository.d.ts +14 -10
  57. package/dist/core/database/bindings.d.ts +6 -0
  58. package/dist/core/database/bunSql.d.ts +3 -12
  59. package/dist/core/database/definitions.d.ts +209 -0
  60. package/dist/core/database/dialect.d.ts +5 -24
  61. package/dist/core/database/driverPorts.d.ts +116 -0
  62. package/dist/core/database/errors.d.ts +47 -7
  63. package/dist/core/database/factory.d.ts +51 -31
  64. package/dist/core/database/index.d.ts +9 -10
  65. package/dist/core/database/keyset.d.ts +2 -1
  66. package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
  67. package/dist/core/database/manager.d.ts +12 -0
  68. package/dist/core/database/model.d.ts +91 -97
  69. package/dist/core/database/modelQuery.d.ts +9 -5
  70. package/dist/core/database/modelRegistry.d.ts +52 -33
  71. package/dist/core/database/mysqlConnection.d.ts +1 -19
  72. package/dist/core/database/mysqlNative.d.ts +38 -0
  73. package/dist/core/database/nativeTransactions.d.ts +16 -0
  74. package/dist/core/database/ormInternal.d.ts +85 -0
  75. package/dist/core/database/ormRuntime.d.ts +4 -0
  76. package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
  77. package/dist/core/database/postgresNative.d.ts +11 -0
  78. package/dist/core/database/query.d.ts +24 -23
  79. package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
  80. package/dist/core/database/rawMysql.d.ts +7 -0
  81. package/dist/core/database/rawPostgres.d.ts +23 -0
  82. package/dist/core/database/rawSqlite.d.ts +6 -0
  83. package/dist/core/database/relationQueries.d.ts +3 -2
  84. package/dist/core/database/relationQuery.d.ts +24 -6
  85. package/dist/core/database/repositoryQuery.d.ts +6 -1
  86. package/dist/core/database/schema/driver.d.ts +1 -1
  87. package/dist/core/database/seeders/types.d.ts +1 -1
  88. package/dist/core/database/session.d.ts +13 -0
  89. package/dist/core/database/sessionFactory.d.ts +9 -0
  90. package/dist/core/database/sqlDialects.d.ts +22 -0
  91. package/dist/core/database/tokens.d.ts +7 -0
  92. package/dist/core/database/transactionSession.d.ts +43 -0
  93. package/dist/core/errors/http.d.ts +4 -1
  94. package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
  95. package/dist/core/events/index.d.ts +2 -3
  96. package/dist/core/events/outbox/index.d.ts +44 -13
  97. package/dist/core/events/outbox/metrics.d.ts +4 -4
  98. package/dist/core/events/outbox/workerTransport.d.ts +17 -0
  99. package/dist/core/http/authMiddleware.d.ts +2 -2
  100. package/dist/core/http/authorizeMiddleware.d.ts +2 -2
  101. package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
  102. package/dist/core/http/conditionalResponse.d.ts +7 -2
  103. package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
  104. package/dist/core/http/corsMiddleware.d.ts +2 -1
  105. package/dist/core/http/csrfMiddleware.d.ts +6 -1
  106. package/dist/core/http/csrfToken.d.ts +17 -7
  107. package/dist/core/http/databaseError.d.ts +4 -0
  108. package/dist/core/http/etag.d.ts +5 -2
  109. package/dist/core/http/flashMiddleware.d.ts +1 -1
  110. package/dist/core/http/flashSession.d.ts +13 -7
  111. package/dist/core/http/index.d.ts +1 -1
  112. package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
  113. package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
  114. package/dist/core/http/parseMultipartUpload.d.ts +3 -2
  115. package/dist/core/http/requestMetaContext.d.ts +5 -0
  116. package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
  117. package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
  118. package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
  119. package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
  120. package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
  121. package/dist/core/http/response.d.ts +4 -3
  122. package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
  123. package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
  124. package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
  125. package/dist/core/http/signedUrl.d.ts +8 -6
  126. package/dist/core/http/throttleMiddleware.d.ts +9 -5
  127. package/dist/core/http/uploads.d.ts +9 -3
  128. package/dist/core/http/webErrorResponse.d.ts +8 -2
  129. package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
  130. package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
  131. package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
  132. package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
  133. package/dist/core/mail/mailer.d.ts +7 -5
  134. package/dist/core/openapi/generator.d.ts +12 -4
  135. package/dist/core/openapi/registeredRoute.d.ts +4 -4
  136. package/dist/core/queue/createAppQueue.d.ts +9 -4
  137. package/dist/core/queue/failedJobMetrics.d.ts +11 -2
  138. package/dist/core/queue/failedJobRepository.d.ts +6 -3
  139. package/dist/core/queue/failedJobService.d.ts +1 -0
  140. package/dist/core/queue/index.d.ts +16 -6
  141. package/dist/core/queue/jobRegistry.d.ts +3 -2
  142. package/dist/core/queue/jobRunner.d.ts +10 -4
  143. package/dist/core/queue/publicQueue.d.ts +18 -9
  144. package/dist/core/queue/queueConfig.d.ts +20 -10
  145. package/dist/core/queue/queueHandoff.d.ts +31 -0
  146. package/dist/core/queue/queueMetrics.d.ts +10 -3
  147. package/dist/core/queue/queueServices.d.ts +28 -0
  148. package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
  149. package/dist/core/queue/redisQueue.d.ts +19 -10
  150. package/dist/core/queue/redisQueueKeys.d.ts +5 -5
  151. package/dist/core/queue/redisStreams.d.ts +17 -10
  152. package/dist/core/queue/resilientQueue.d.ts +10 -4
  153. package/dist/core/queue/types.d.ts +1 -0
  154. package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
  155. package/dist/core/runtime/application.d.ts +7 -0
  156. package/dist/core/runtime/executionContext.d.ts +9 -0
  157. package/dist/core/runtime/executionTasks.d.ts +49 -0
  158. package/dist/core/runtime/resourceJournal.d.ts +67 -0
  159. package/dist/core/runtime/serviceGraph.d.ts +14 -0
  160. package/dist/core/security/oauthState.d.ts +13 -9
  161. package/dist/core/security/publicReads.d.ts +2 -2
  162. package/dist/core/security/safeFetch.d.ts +1 -0
  163. package/dist/core/security/safeUrl.d.ts +3 -0
  164. package/dist/core/security/scimTenantTokens.d.ts +1 -1
  165. package/dist/core/security/tokenExpiry.d.ts +1 -1
  166. package/dist/core/security/webhookSignature.d.ts +1 -1
  167. package/dist/core/storage/storage.d.ts +24 -16
  168. package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
  169. package/dist/core/tenant/resolveTenant.d.ts +2 -2
  170. package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
  171. package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
  172. package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
  173. package/dist/core/tracing/otel.d.ts +4 -6
  174. package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
  175. package/dist/core/view/etaViewEngine.d.ts +1 -1
  176. package/dist/core/view/index.d.ts +5 -4
  177. package/dist/core/view/tokens.d.ts +8 -0
  178. package/dist/core/view/viewRenderer.d.ts +2 -2
  179. package/dist/core/view/webErrorView.d.ts +8 -7
  180. package/dist/core/view/webLayoutData.d.ts +6 -4
  181. package/dist/entries/audit/exportAuditLogs.js +87 -1024
  182. package/dist/entries/audit/siemFormatter.js +4 -90
  183. package/dist/entries/auth/abilityCatalog.js +28 -0
  184. package/dist/entries/auth/accessControl.js +5 -16
  185. package/dist/entries/auth/accountStateMigration.js +216 -236
  186. package/dist/entries/auth/authOutcome.js +80 -0
  187. package/dist/entries/auth/authReader.js +68 -0
  188. package/dist/entries/auth/basicAuthGuard.js +144 -1249
  189. package/dist/entries/auth/emailVerification.js +2 -2
  190. package/dist/entries/auth/intendedUrlCookie.js +35 -59
  191. package/dist/entries/auth/jwt.js +22 -47
  192. package/dist/entries/auth/jwtGuard.js +99 -231
  193. package/dist/entries/auth/membershipMiddleware.js +71 -10
  194. package/dist/entries/auth/membershipScope.js +16 -22
  195. package/dist/entries/auth/membershipService.js +11 -28
  196. package/dist/entries/auth/oauth/oidcProvider.js +59 -64
  197. package/dist/entries/auth/oauth/providers.js +12 -95
  198. package/dist/entries/auth/oauth/samlProvider.js +53 -1080
  199. package/dist/entries/auth/oneTimeToken.js +27 -289
  200. package/dist/entries/auth/passwordConfirmCookie.js +40 -63
  201. package/dist/entries/auth/passwordLogin.js +94 -399
  202. package/dist/entries/auth/pendingMfaCookie.js +6 -6
  203. package/dist/entries/auth/policy.js +22 -56
  204. package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
  205. package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
  206. package/dist/entries/auth/sessionCookie.js +58 -73
  207. package/dist/entries/auth/sessionGuard.js +95 -248
  208. package/dist/entries/auth/tokenHash.js +11 -43
  209. package/dist/entries/cache/createCacheStore.js +126 -117
  210. package/dist/entries/cache/repository.js +25 -0
  211. package/dist/entries/cache/simpleCache.js +12 -7
  212. package/dist/entries/cache/tokens.js +9 -0
  213. package/dist/entries/config/applicationConfig.js +163 -0
  214. package/dist/entries/config/envSchema.js +21 -4
  215. package/dist/entries/contracts/application.js +1 -0
  216. package/dist/entries/contracts/authUserDirectory.js +10 -0
  217. package/dist/entries/contracts/container.js +99 -26
  218. package/dist/entries/contracts/di.js +3 -0
  219. package/dist/entries/contracts/executionContext.js +7 -0
  220. package/dist/entries/contracts/executionOperations.js +7 -0
  221. package/dist/entries/contracts/executionOwnership.js +7 -0
  222. package/dist/entries/contracts/membership.js +1 -0
  223. package/dist/entries/contracts/persistence.js +1 -0
  224. package/dist/entries/contracts/serviceTokens.js +26 -116
  225. package/dist/entries/contracts/services.js +98 -0
  226. package/dist/entries/contracts/token.js +41 -0
  227. package/dist/entries/crypto/fieldEncryption.js +49 -50
  228. package/dist/entries/crypto/mfaSecret.js +86 -82
  229. package/dist/entries/database/acquisitionMetrics.js +107 -0
  230. package/dist/entries/database/baseRepository.d.ts +2 -0
  231. package/dist/entries/database/bindings.js +2082 -0
  232. package/dist/entries/database/definitions.js +175 -0
  233. package/dist/entries/database/errors.js +114 -89
  234. package/dist/entries/database/factory.js +67 -28
  235. package/dist/entries/database/migrations.js +172 -224
  236. package/dist/entries/database/model.d.ts +1 -0
  237. package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
  238. package/dist/entries/database/query.js +159 -161
  239. package/dist/entries/database/repositoryQuery.d.ts +1 -0
  240. package/dist/entries/database/repositoryQuery.js +1 -1373
  241. package/dist/entries/database/schema.js +216 -236
  242. package/dist/entries/database/session.js +1 -0
  243. package/dist/entries/database/sqliteConnection.js +525 -83
  244. package/dist/entries/database/tokens.js +9 -0
  245. package/dist/entries/errors/http.js +118 -1
  246. package/dist/entries/http/authMiddleware.js +8 -5
  247. package/dist/entries/http/authorizeMiddleware.js +1 -1
  248. package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
  249. package/dist/entries/http/clientIp.js +2 -2
  250. package/dist/entries/http/conditionalResponse.js +19 -7
  251. package/dist/entries/http/corsMiddleware.js +6 -101
  252. package/dist/entries/http/csrfMiddleware.js +92 -106
  253. package/dist/entries/http/csrfToken.js +58 -94
  254. package/dist/entries/http/etag.js +7 -4
  255. package/dist/entries/http/flashMiddleware.js +57 -99
  256. package/dist/entries/http/flashSession.js +41 -68
  257. package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
  258. package/dist/entries/http/metricsMiddleware.js +2 -16
  259. package/dist/entries/http/parseMultipartUpload.js +15 -29
  260. package/dist/entries/http/requireAbilityMiddleware.js +2 -2
  261. package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
  262. package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
  263. package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
  264. package/dist/entries/http/response.js +67 -233
  265. package/dist/entries/http/routeMiddleware.js +0 -14
  266. package/dist/entries/http/scimThrottleMiddleware.js +43 -237
  267. package/dist/entries/http/securedRouteModelBinding.js +37 -25
  268. package/dist/entries/http/securityHeadersMiddleware.js +8 -25
  269. package/dist/entries/http/signedUrl.js +20 -110
  270. package/dist/entries/http/throttleMiddleware.js +41 -185
  271. package/dist/entries/http/uploads.js +9 -24
  272. package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
  273. package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
  274. package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
  275. package/dist/entries/mail/mailer.js +68 -78
  276. package/dist/entries/openapi/generator.js +33 -100
  277. package/dist/entries/queue/createAppQueue.js +416 -256
  278. package/dist/entries/queue/failedJobRepository.js +17 -8
  279. package/dist/entries/queue/failedJobService.js +1 -0
  280. package/dist/entries/queue/jobRunner.js +141 -66
  281. package/dist/entries/queue/publicQueue.js +411 -257
  282. package/dist/entries/queue/queueConfig.js +61 -0
  283. package/dist/entries/queue/queueHandoff.js +318 -0
  284. package/dist/entries/queue/queueMetrics.js +989 -1386
  285. package/dist/entries/queue/queueServices.js +133 -0
  286. package/dist/entries/queue/queueWorkerTransport.js +1703 -0
  287. package/dist/entries/queue/redisQueue.js +282 -180
  288. package/dist/entries/queue.js +6 -45
  289. package/dist/entries/runtime/application.js +1585 -0
  290. package/dist/entries/runtime/asyncContextStore.js +0 -16
  291. package/dist/entries/security/oauthState.js +35 -67
  292. package/dist/entries/security/publicReads.js +4 -4
  293. package/dist/entries/security/safeFetch.js +1 -0
  294. package/dist/entries/security/scimTenantTokens.js +3 -3
  295. package/dist/entries/security/tokenExpiry.js +2 -2
  296. package/dist/entries/security/totp.js +1 -87
  297. package/dist/entries/security/webhookSignature.js +2 -90
  298. package/dist/entries/storage/storage.js +120 -45
  299. package/dist/entries/tenant/databaseTenantContext.js +6 -907
  300. package/dist/entries/tenant/publicTenantHost.js +78 -0
  301. package/dist/entries/tenant/resolveTenant.js +14 -0
  302. package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
  303. package/dist/entries/tenant/tenancyConfig.js +1 -19
  304. package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
  305. package/dist/entries/tracing/tracingMiddleware.js +104 -173
  306. package/dist/entries/view/tokens.js +11 -0
  307. package/dist/framework/public-api.d.ts +62 -44
  308. package/dist/index.js +10435 -11351
  309. package/dist/internal/ormInternal.js +117 -0
  310. package/dist/internal/ormRuntime.js +5000 -0
  311. package/package.json +158 -46
  312. package/dist/core/database/bindConnection.d.ts +0 -1
  313. package/dist/core/database/boundConnection.d.ts +0 -5
  314. package/dist/core/database/defaultConnection.d.ts +0 -7
  315. package/dist/core/database/namedConnections.d.ts +0 -15
  316. package/dist/core/database/readOnlyCollector.d.ts +0 -7
  317. package/dist/core/database/repositoryConnection.d.ts +0 -4
  318. package/dist/core/database/transaction.d.ts +0 -23
  319. package/dist/core/database/transactionControl.d.ts +0 -6
  320. package/dist/core/events/deferredModelEvents.d.ts +0 -7
  321. package/dist/core/facades/index.d.ts +0 -10
  322. package/dist/core/runtime/applicationRegistry.d.ts +0 -18
  323. package/dist/entries/database/bindConnection.js +0 -1
  324. package/dist/entries/database/boundConnection.js +0 -1
  325. package/dist/entries/database/defaultConnection.js +0 -1
  326. package/dist/entries/database/namedConnections.js +0 -1
  327. package/dist/entries/database/repositoryConnection.js +0 -1
  328. package/dist/entries/database/transaction.js +0 -1
  329. package/dist/entries/facades.js +0 -711
  330. package/dist/entries/runtime/applicationRegistry.js +0 -1
@@ -1,16 +1,4 @@
1
1
  // @bun
2
- var __esm = (fn, res, err) => () => {
3
- if (fn)
4
- try {
5
- res = fn(fn = 0);
6
- } catch (e) {
7
- err = [e];
8
- }
9
- if (err)
10
- throw err[0];
11
- return res;
12
- };
13
-
14
2
  // ../../src/core/runtime/asyncContextStore.ts
15
3
  import { AsyncLocalStorage } from "async_hooks";
16
4
  function createAsyncContextStore(key) {
@@ -24,894 +12,17 @@ function createAsyncContextStore(key) {
24
12
  globalRecord[symbol] = store;
25
13
  return store;
26
14
  }
27
- var init_asyncContextStore = () => {};
28
-
29
- // ../../src/core/database/connectionContext.ts
30
- function runWithDatabaseConnection(connection, callback) {
31
- return activeConnection.run(connection, callback);
32
- }
33
- function getActiveDatabaseConnection(fallback) {
34
- return activeConnection.getStore() ?? fallback;
35
- }
36
- function hasActiveDatabaseConnection() {
37
- return activeConnection.getStore() !== undefined;
38
- }
39
- var activeConnection;
40
- var init_connectionContext = __esm(() => {
41
- init_asyncContextStore();
42
- activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
43
- });
44
-
45
- // ../../src/core/database/transactionControl.ts
46
- function unwrapTransactionRollback(error, depth = 0) {
47
- if (error instanceof TransactionRollback) {
48
- return error;
49
- }
50
- if (depth >= 5 || !(error instanceof Error) || error.cause === undefined) {
51
- return null;
52
- }
53
- return unwrapTransactionRollback(error.cause, depth + 1);
54
- }
55
- function hasActiveTransaction() {
56
- return hasActiveDatabaseConnection() && (transactionScopes.getStore()?.rollback.length ?? 0) > 0;
57
- }
58
- function requestTransactionRollback() {
59
- const state = transactionScopes.getStore();
60
- const index = state ? state.rollback.length - 1 : -1;
61
- if (!state || index < 0) {
62
- return;
63
- }
64
- state.rollback[index] = true;
65
- }
66
- function scopeRequestsRollback() {
67
- const state = transactionScopes.getStore();
68
- if (!state || state.rollback.length === 0) {
69
- return false;
70
- }
71
- return state.rollback[state.rollback.length - 1] === true;
72
- }
73
- async function commitOrRollbackScope(result) {
74
- if (scopeRequestsRollback()) {
75
- throw new TransactionRollback(result);
76
- }
77
- return result;
78
- }
79
- async function settleTransaction(work) {
80
- try {
81
- return await work();
82
- } catch (error) {
83
- const rollback = unwrapTransactionRollback(error);
84
- if (rollback) {
85
- return rollback.result;
86
- }
87
- throw error;
88
- }
89
- }
90
- async function runWithTransactionScope(callback) {
91
- const existing = transactionScopes.getStore();
92
- if (existing) {
93
- existing.rollback.push(false);
94
- try {
95
- return await callback();
96
- } finally {
97
- existing.rollback.pop();
98
- }
99
- }
100
- const state = { rollback: [false] };
101
- return await transactionScopes.run(state, callback);
102
- }
103
- var TransactionRollback, transactionScopes;
104
- var init_transactionControl = __esm(() => {
105
- init_asyncContextStore();
106
- init_connectionContext();
107
- TransactionRollback = class TransactionRollback extends Error {
108
- result;
109
- constructor(result) {
110
- super("Transaction rolled back");
111
- this.name = "TransactionRollback";
112
- this.result = result;
113
- }
114
- };
115
- transactionScopes = createAsyncContextStore("@getstrata/transactionScopes");
116
- });
117
15
 
118
16
  // ../../src/core/tenant/tenantContext.ts
17
+ var tenantContext = createAsyncContextStore("@getstrata/tenantContext");
119
18
  function runWithTenant(tenant, callback) {
120
19
  return tenantContext.run(tenant, callback);
121
20
  }
122
- function currentTenant() {
123
- return tenantContext.getStore() ?? null;
124
- }
125
- var tenantContext;
126
- var init_tenantContext = __esm(() => {
127
- init_asyncContextStore();
128
- tenantContext = createAsyncContextStore("@getstrata/tenantContext");
129
- });
130
-
131
- // ../../src/core/events/eventBus.ts
132
- class EventBus {
133
- constructor() {}
134
- transactionalListeners = new Map;
135
- listenTransactional(event, listener) {
136
- const handlers = this.transactionalListeners.get(event) ?? new Set;
137
- handlers.add(listener);
138
- this.transactionalListeners.set(event, handlers);
139
- return () => {
140
- handlers.delete(listener);
141
- if (!handlers.size)
142
- this.transactionalListeners.delete(event);
143
- };
144
- }
145
- hasTransactionalListeners(event) {
146
- return (this.transactionalListeners.get(event)?.size ?? 0) > 0;
147
- }
148
- async dispatchTransactional(event, payload) {
149
- for (const listener of this.transactionalListeners.get(event) ?? [])
150
- await listener(payload);
151
- }
152
- listeners = new Map;
153
- on(event, listener) {
154
- return this.listen(event, listener);
155
- }
156
- listen(event, listener) {
157
- const handlers = this.listeners.get(event) ?? new Set;
158
- handlers.add(listener);
159
- this.listeners.set(event, handlers);
160
- return () => {
161
- handlers.delete(listener);
162
- if (handlers.size === 0) {
163
- this.listeners.delete(event);
164
- }
165
- };
166
- }
167
- async emit(event, payload) {
168
- await this.dispatch(event, payload);
169
- }
170
- async dispatch(event, payload) {
171
- const handlers = this.listeners.get(event);
172
- if (!handlers || handlers.size === 0) {
173
- return;
174
- }
175
- for (const handler of handlers) {
176
- await handler(payload);
177
- }
178
- }
179
- }
180
- function readSharedEventBus() {
181
- const globalBus = globalThis[EVENT_BUS_KEY];
182
- if (globalBus) {
183
- return globalBus;
184
- }
185
- const bus = new EventBus;
186
- globalThis[EVENT_BUS_KEY] = bus;
187
- return bus;
188
- }
189
- var EVENT_BUS_KEY, eventBus;
190
- var init_eventBus = __esm(() => {
191
- EVENT_BUS_KEY = Symbol.for("@getstrata/eventBus");
192
- eventBus = readSharedEventBus();
193
- });
194
-
195
- // ../../src/core/events/deferredModelEvents.ts
196
- function sameTenant(left, right) {
197
- if (left === null && right === null) {
198
- return true;
199
- }
200
- if (left === null || right === null) {
201
- return false;
202
- }
203
- return left.id === right.id;
204
- }
205
- function groupQueuedModelEvents(queued) {
206
- const groups = [];
207
- for (const item of queued) {
208
- const lastGroup = groups[groups.length - 1];
209
- const last = lastGroup?.[lastGroup.length - 1];
210
- if (!lastGroup || !last || !sameTenant(last.tenant, item.tenant) || "callback" in last !== "callback" in item) {
211
- groups.push([item]);
212
- } else {
213
- lastGroup.push(item);
214
- }
215
- }
216
- return groups;
217
- }
218
- async function dispatchEventBatch(batch) {
219
- for (const item of batch) {
220
- if ("callback" in item)
221
- await item.callback();
222
- else
223
- await eventBus.dispatch(item.event, item.payload);
224
- }
225
- }
226
- async function dispatchQueuedModelEvents(queued) {
227
- if (queued.length === 0) {
228
- return;
229
- }
230
- await Promise.resolve().then(() => init_tenantDatabaseScope());
231
- for (const batch of groupQueuedModelEvents(queued)) {
232
- const tenant = batch[0]?.tenant ?? null;
233
- if (tenant) {
234
- if (batch.some((item) => ("callback" in item))) {
235
- await runWithTenant(tenant, () => dispatchEventBatch(batch));
236
- } else {
237
- await runWithTenantDatabase(tenant, () => dispatchEventBatch(batch));
238
- }
239
- } else {
240
- await dispatchEventBatch(batch);
241
- }
242
- }
243
- }
244
- async function dispatchModelEvent(event, payload) {
245
- await eventBus.dispatchTransactional(event, payload);
246
- const state = deferredModelEvents.getStore();
247
- const frame = state?.frames[state.frames.length - 1];
248
- if (frame) {
249
- frame.push({
250
- event,
251
- payload,
252
- tenant: currentTenant()
253
- });
254
- return;
255
- }
256
- await eventBus.dispatch(event, payload);
257
- }
258
- async function runWithDeferredModelEvents(callback) {
259
- const existing = deferredModelEvents.getStore();
260
- if (existing) {
261
- existing.frames.push([]);
262
- existing.rollbackFrames.push([]);
263
- try {
264
- const result = await callback();
265
- const nested = existing.frames.pop() ?? [];
266
- const rollback = existing.rollbackFrames.pop() ?? [];
267
- existing.rollbackFrames.at(-1)?.push(...rollback);
268
- const parent = existing.frames[existing.frames.length - 1];
269
- if (parent) {
270
- parent.push(...nested);
271
- }
272
- return result;
273
- } catch (error) {
274
- existing.frames.pop();
275
- for (const rollback of (existing.rollbackFrames.pop() ?? []).reverse())
276
- rollback();
277
- throw error;
278
- }
279
- }
280
- const state = { frames: [[]], rollbackFrames: [[]] };
281
- let result;
282
- try {
283
- result = await deferredModelEvents.run(state, callback);
284
- } catch (error) {
285
- for (const rollback of (state.rollbackFrames[0] ?? []).reverse())
286
- rollback();
287
- throw error;
288
- }
289
- await dispatchQueuedModelEvents(state.frames[0] ?? []);
290
- return result;
291
- }
292
- var deferredModelEvents;
293
- var init_deferredModelEvents = __esm(() => {
294
- init_asyncContextStore();
295
- init_tenantContext();
296
- init_eventBus();
297
- deferredModelEvents = createAsyncContextStore("@getstrata/deferredModelEvents");
298
- });
299
-
300
- // ../../src/core/database/acquisitionMetrics.ts
301
- async function observeTransactionAcquisition(metrics, acquire, signal) {
302
- const state = states.get(metrics);
303
- if (!state)
304
- throw new TypeError("Transaction acquisition metrics must be created by the framework factory.");
305
- const started = performance.now();
306
- state.inflight++;
307
- let outcome = "acquired";
308
- try {
309
- return await acquire();
310
- } catch (error) {
311
- outcome = signal?.aborted ? "aborted" : "failed";
312
- throw error;
313
- } finally {
314
- state.inflight--;
315
- const elapsed = Math.max(0, performance.now() - started) / 1000;
316
- const histogram = state.outcomes[outcomes.indexOf(outcome)];
317
- if (histogram) {
318
- histogram.count++;
319
- histogram.sumSeconds += elapsed;
320
- for (let index = 0;index < ACQUISITION_BUCKETS_SECONDS.length; index++) {
321
- const bound = ACQUISITION_BUCKETS_SECONDS[index];
322
- if (bound !== undefined && elapsed <= bound)
323
- histogram.buckets[index] = (histogram.buckets[index] ?? 0) + 1;
324
- }
325
- }
326
- }
327
- }
328
- var ACQUISITION_BUCKETS_SECONDS, outcomes, metricsBrand, states;
329
- var init_acquisitionMetrics = __esm(() => {
330
- ACQUISITION_BUCKETS_SECONDS = [
331
- 0.001,
332
- 0.005,
333
- 0.01,
334
- 0.025,
335
- 0.05,
336
- 0.1,
337
- 0.25,
338
- 0.5,
339
- 1,
340
- 2.5,
341
- 5,
342
- 10
343
- ];
344
- outcomes = ["acquired", "failed", "aborted"];
345
- metricsBrand = Symbol("transaction acquisition metrics");
346
- states = new WeakMap;
347
- });
348
-
349
- // ../../src/core/database/connection.ts
350
- function createDatabaseConnection(source) {
351
- return {
352
- async unsafe(query, params = []) {
353
- return await source.unsafe(query, params);
354
- }
355
- };
356
- }
357
- var init_connection = () => {};
358
-
359
- // ../../src/core/database/boundConnection.ts
360
- function boundConnectionState() {
361
- const globalRecord = globalThis;
362
- const existing = globalRecord[BOUND_CONNECTION_KEY];
363
- if (existing) {
364
- return existing;
365
- }
366
- const created = { connection: null };
367
- globalRecord[BOUND_CONNECTION_KEY] = created;
368
- return created;
369
- }
370
- function getBoundDatabaseConnection() {
371
- return boundConnectionState().connection;
372
- }
373
- var BOUND_CONNECTION_KEY;
374
- var init_boundConnection = __esm(() => {
375
- BOUND_CONNECTION_KEY = Symbol.for("@getstrata/boundDatabaseConnection");
376
- });
377
-
378
- // ../../src/core/database/queryProxy.ts
379
- var POOL_CONNECTION_METHODS;
380
- var init_queryProxy = __esm(() => {
381
- init_connectionContext();
382
- POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
383
- });
384
-
385
- // ../../src/core/database/defaultConnection.ts
386
- function defaultConnectionState() {
387
- const globalRecord = globalThis;
388
- const existing = globalRecord[DEFAULT_CONNECTION_KEY];
389
- if (existing) {
390
- return existing;
391
- }
392
- const created = { pool: null, query: null };
393
- globalRecord[DEFAULT_CONNECTION_KEY] = created;
394
- return created;
395
- }
396
- function getDefaultDatabasePool() {
397
- const pool = defaultConnectionState().pool;
398
- if (!pool) {
399
- throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
400
- }
401
- return pool;
402
- }
403
- function getDefaultDatabaseQuery() {
404
- const query = defaultConnectionState().query;
405
- if (!query) {
406
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
407
- }
408
- return query;
409
- }
410
- var DEFAULT_CONNECTION_KEY;
411
- var init_defaultConnection = __esm(() => {
412
- init_queryProxy();
413
- DEFAULT_CONNECTION_KEY = Symbol.for("@getstrata/defaultDatabaseConnection");
414
- });
415
-
416
- // ../../src/core/database/schema/driver.ts
417
- function normalizeConnectionName(connection) {
418
- const normalized = connection.trim().toLowerCase();
419
- if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
420
- return "pgsql";
421
- }
422
- if (normalized === "mysql" || normalized === "mariadb") {
423
- return "mysql";
424
- }
425
- if (normalized === "sqlite") {
426
- return "sqlite";
427
- }
428
- throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
429
- }
430
- function resolveDriverFromUrl(url) {
431
- const normalized = url.trim().toLowerCase();
432
- if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
433
- return "pgsql";
434
- }
435
- if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
436
- return "mysql";
437
- }
438
- if (normalized.startsWith("sqlite:")) {
439
- return "sqlite";
440
- }
441
- return null;
442
- }
443
- function resolveDatabaseDriver(options = {}) {
444
- const connection = options.connection ?? process.env.DB_CONNECTION;
445
- if (connection) {
446
- return normalizeConnectionName(connection);
447
- }
448
- const url = options.url ?? process.env.DATABASE_URL ?? "";
449
- const fromUrl = resolveDriverFromUrl(url);
450
- if (fromUrl) {
451
- return fromUrl;
452
- }
453
- return "pgsql";
454
- }
455
- var init_driver = () => {};
456
-
457
- // ../../src/core/database/dialect.ts
458
- function assertSafeIdentifier(identifier) {
459
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
460
- throw new Error(`Invalid SQL identifier: ${identifier}`);
461
- }
462
- return identifier;
463
- }
464
- function quoteIdentifierFor(dialect, column) {
465
- return dialect.quoteIdentifier(column);
466
- }
467
- function dialectFor(driver) {
468
- return dialects[driver];
469
- }
470
- function currentSqlDialect() {
471
- return dialectContext.getStore() ?? dialectOverride ?? dialectFor(resolveDatabaseDriver());
472
- }
473
- var postgresDialect, mysqlDialect, sqliteDialect, dialects, dialectContext, dialectOverride = null;
474
- var init_dialect = __esm(() => {
475
- init_asyncContextStore();
476
- init_driver();
477
- postgresDialect = {
478
- driver: "pgsql",
479
- placeholder(index) {
480
- return `$${index}`;
481
- },
482
- quoteIdentifier(identifier) {
483
- return `"${assertSafeIdentifier(identifier)}"`;
484
- },
485
- nowExpression() {
486
- return "NOW()";
487
- },
488
- epochMillisecondsExpression() {
489
- return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)";
490
- },
491
- rowLockClause(skipLocked = false) {
492
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
493
- },
494
- timestampValue(value) {
495
- return value.toISOString();
496
- },
497
- returningClause(columns) {
498
- return ` RETURNING ${columns}`;
499
- },
500
- ilikeOperator() {
501
- return "ILIKE";
502
- },
503
- nullsLastSuffix() {
504
- return " NULLS LAST";
505
- },
506
- castToText(expression) {
507
- return `${expression}::text`;
508
- },
509
- upsertSuffix(conflictColumns, updateColumns) {
510
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
511
- if (updateColumns.length === 0) {
512
- return ` ON CONFLICT (${target}) DO NOTHING`;
513
- }
514
- const assignments = updateColumns.map((column) => {
515
- const quoted = quoteIdentifierFor(this, column);
516
- return `${quoted} = excluded.${quoted}`;
517
- }).join(", ");
518
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
519
- }
520
- };
521
- mysqlDialect = {
522
- driver: "mysql",
523
- placeholder() {
524
- return "?";
525
- },
526
- quoteIdentifier(identifier) {
527
- return `\`${assertSafeIdentifier(identifier)}\``;
528
- },
529
- nowExpression() {
530
- return "CURRENT_TIMESTAMP";
531
- },
532
- epochMillisecondsExpression() {
533
- return "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)";
534
- },
535
- rowLockClause(skipLocked = false) {
536
- return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
537
- },
538
- timestampValue(value) {
539
- return value.toISOString().slice(0, 19).replace("T", " ");
540
- },
541
- returningClause() {
542
- return "";
543
- },
544
- ilikeOperator() {
545
- return "LIKE";
546
- },
547
- nullsLastSuffix() {
548
- return "";
549
- },
550
- castToText(expression) {
551
- return `CAST(${expression} AS CHAR)`;
552
- },
553
- upsertSuffix(conflictColumns, updateColumns) {
554
- if (updateColumns.length === 0) {
555
- const anchor = quoteIdentifierFor(this, conflictColumns[0] ?? "");
556
- return ` ON DUPLICATE KEY UPDATE ${anchor} = ${anchor}`;
557
- }
558
- const assignments = updateColumns.map((column) => {
559
- const quoted = quoteIdentifierFor(this, column);
560
- return `${quoted} = VALUES(${quoted})`;
561
- }).join(", ");
562
- return ` ON DUPLICATE KEY UPDATE ${assignments}`;
563
- }
564
- };
565
- sqliteDialect = {
566
- driver: "sqlite",
567
- placeholder() {
568
- return "?";
569
- },
570
- quoteIdentifier(identifier) {
571
- return `"${assertSafeIdentifier(identifier)}"`;
572
- },
573
- nowExpression() {
574
- return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
575
- },
576
- epochMillisecondsExpression() {
577
- return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
578
- },
579
- rowLockClause() {
580
- return "";
581
- },
582
- timestampValue(value) {
583
- return value.toISOString();
584
- },
585
- returningClause(columns) {
586
- return ` RETURNING ${columns}`;
587
- },
588
- ilikeOperator() {
589
- return "LIKE";
590
- },
591
- nullsLastSuffix() {
592
- return "";
593
- },
594
- castToText(expression) {
595
- return `CAST(${expression} AS TEXT)`;
596
- },
597
- upsertSuffix(conflictColumns, updateColumns) {
598
- const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
599
- if (updateColumns.length === 0) {
600
- return ` ON CONFLICT (${target}) DO NOTHING`;
601
- }
602
- const assignments = updateColumns.map((column) => {
603
- const quoted = quoteIdentifierFor(this, column);
604
- return `${quoted} = excluded.${quoted}`;
605
- }).join(", ");
606
- return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
607
- }
608
- };
609
- dialects = {
610
- pgsql: postgresDialect,
611
- mysql: mysqlDialect,
612
- sqlite: sqliteDialect
613
- };
614
- dialectContext = createAsyncContextStore("@getstrata/sqlDialect");
615
- });
616
-
617
- // ../../src/core/database/repositoryConnection.ts
618
- function resolveRepositoryConnection() {
619
- return getActiveDatabaseConnection(getBoundDatabaseConnection() ?? getDefaultDatabaseQuery());
620
- }
621
- function compileTaggedSql(strings, values) {
622
- const dialect = currentSqlDialect();
623
- let query = strings[0] ?? "";
624
- const params = [];
625
- for (let index = 0;index < values.length; index += 1) {
626
- params.push(values[index]);
627
- query += `${dialect.placeholder(params.length)}${strings[index + 1] ?? ""}`;
628
- }
629
- return { query, params };
630
- }
631
- function isTaggedStrings(value) {
632
- if (!Array.isArray(value) || typeof value[0] !== "string") {
633
- return false;
634
- }
635
- return typeof value.raw !== "undefined";
636
- }
637
- function runOnConnection(connection, args) {
638
- if (typeof connection === "function") {
639
- return connection(...args);
640
- }
641
- if (typeof connection.unsafe !== "function") {
642
- throw new Error("Database connection cannot run SQL.");
643
- }
644
- const strings = args[0];
645
- if (!isTaggedStrings(strings)) {
646
- throw new Error("Database connection cannot run tagged SQL.");
647
- }
648
- const compiled = compileTaggedSql(strings, args.slice(1));
649
- return connection.unsafe(compiled.query, compiled.params);
650
- }
651
- var repositoryConnection;
652
- var init_repositoryConnection = __esm(() => {
653
- init_boundConnection();
654
- init_connectionContext();
655
- init_defaultConnection();
656
- init_dialect();
657
- repositoryConnection = new Proxy(function repositoryConnection() {}, {
658
- apply(_target, _thisArg, args) {
659
- return runOnConnection(resolveRepositoryConnection(), args);
660
- },
661
- get(_target, property) {
662
- const connection = resolveRepositoryConnection();
663
- const value = connection[property];
664
- return typeof value === "function" ? value.bind(connection) : value;
665
- }
666
- });
667
- });
668
-
669
- // ../../src/core/database/transaction.ts
670
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
671
- function scopedConnection(source) {
672
- const connection = createDatabaseConnection(source);
673
- transactionAliases.set(connection, source);
674
- return connection;
675
- }
676
- function isActiveTransactionConnection(connection) {
677
- if (!hasActiveTransaction() || !hasActiveDatabaseConnection())
678
- return false;
679
- const active = getActiveDatabaseConnection(connection);
680
- return connection === active || transactionAliases.get(connection) === active;
681
- }
682
- async function runInSavepoint(connection, operation) {
683
- const inherited = transactionFrame.getStore();
684
- let parent = inherited?.connection === connection ? inherited : outerFrames.get(connection);
685
- if (!parent) {
686
- parent = { connection, childActive: false };
687
- outerFrames.set(connection, parent);
688
- }
689
- if (parent.childActive) {
690
- throw new Error("Concurrent nested transactions on one connection are not supported. Await each transaction before starting the next.");
691
- }
692
- parent.childActive = true;
693
- const name = `strata_${crypto.randomUUID().replaceAll("-", "")}`;
694
- try {
695
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
696
- await connection.unsafe(`SAVEPOINT ${name}`);
697
- try {
698
- const result = await transactionFrame.run({ connection, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await operation(scopedConnection(connection)))));
699
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
700
- return result;
701
- } catch (error) {
702
- await connection.unsafe(`ROLLBACK TO SAVEPOINT ${name}`);
703
- await connection.unsafe(`RELEASE SAVEPOINT ${name}`);
704
- throw error;
705
- }
706
- }));
707
- } finally {
708
- parent.childActive = false;
709
- }
710
- }
711
- function supportsTransactions(connection) {
712
- return typeof connection.begin === "function";
713
- }
714
- async function runInTransaction(operation, options = {}) {
715
- const signal = options.acquisitionSignal;
716
- signal?.throwIfAborted();
717
- const admittedOperation = (connection) => {
718
- signal?.throwIfAborted();
719
- return operation(connection);
720
- };
721
- const pool = options.connection ?? resolveRepositoryConnection();
722
- if (hasActiveDatabaseConnection()) {
723
- const active = getActiveDatabaseConnection(pool);
724
- if (options.connection && options.connection !== active && options.connection !== transactionRoots.get(active) && transactionAliases.get(options.connection) !== active)
725
- throw new Error("Cannot switch database connections within an active transaction.");
726
- return await runInSavepoint(active, admittedOperation);
727
- }
728
- if (!supportsTransactions(pool)) {
729
- throw new Error("Active database connection does not support transactions. Bind a client with begin() via bindDatabaseConnection.");
730
- }
731
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
732
- let reserved;
733
- if (signal || options.acquisitionMetrics) {
734
- if (!pool.reserve)
735
- throw new Error(signal ? "Active database connection does not support cancellable transaction acquisition." : "Active database connection does not support observable transaction acquisition.");
736
- const reserve = pool.reserve.bind(pool);
737
- reserved = options.acquisitionMetrics ? await observeTransactionAcquisition(options.acquisitionMetrics, () => reserve({ signal }), signal) : await reserve({ signal });
738
- }
739
- const connection = reserved ?? pool;
740
- try {
741
- signal?.throwIfAborted();
742
- if (!supportsTransactions(connection))
743
- throw new Error("Reserved database connection does not support transactions.");
744
- return await connection.begin(AsyncLocalStorage2.bind(async (transaction) => {
745
- transactionRoots.set(transaction, pool);
746
- return await runWithDatabaseConnection(transaction, () => transactionFrame.run({ connection: transaction, childActive: false }, () => runWithTransactionScope(async () => commitOrRollbackScope(await admittedOperation(scopedConnection(transaction))))));
747
- }));
748
- } finally {
749
- await reserved?.release();
750
- }
751
- }));
752
- }
753
- var transactionFrame, outerFrames, transactionRoots, transactionAliases;
754
- var init_transaction = __esm(() => {
755
- init_deferredModelEvents();
756
- init_asyncContextStore();
757
- init_acquisitionMetrics();
758
- init_connection();
759
- init_connectionContext();
760
- init_repositoryConnection();
761
- init_transactionControl();
762
- init_acquisitionMetrics();
763
- transactionFrame = createAsyncContextStore("@getstrata/transactionFrame");
764
- outerFrames = new WeakMap;
765
- transactionRoots = new WeakMap;
766
- transactionAliases = new WeakMap;
767
- });
768
-
769
- // ../../src/core/tenant/tenancyConfig.ts
770
- function readTenancyDriver(env = process.env) {
771
- const raw = env.TENANCY_DRIVER?.trim();
772
- if (raw === undefined || raw === "") {
773
- return "rls";
774
- }
775
- if (TENANCY_DRIVERS.includes(raw)) {
776
- return raw;
777
- }
778
- throw new Error(`TENANCY_DRIVER must be one of ${TENANCY_DRIVERS.join(", ")}; received "${raw}".`);
779
- }
780
- function isTenancyEnabled(env = process.env) {
781
- return readTenancyDriver(env) !== "none";
782
- }
783
- function isRlsTenancy(env = process.env) {
784
- return readTenancyDriver(env) === "rls";
785
- }
786
- var TENANCY_DRIVERS;
787
- var init_tenancyConfig = __esm(() => {
788
- TENANCY_DRIVERS = ["rls", "column", "none"];
789
- });
790
-
791
- // ../../src/core/tenant/databaseTenantContext.ts
792
- import { getDefaultDatabasePool as getDefaultDatabasePool2 } from "@getstrata/core/database/defaultConnection";
793
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
794
- async function applyBypassToTransaction(transaction, bypass) {
795
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, [
796
- bypass ? "true" : "false"
797
- ]);
798
- }
799
- function stringifyBypassIdentifier(identifier) {
800
- if (typeof identifier === "number") {
801
- return String(identifier);
802
- }
803
- return identifier.trim();
804
- }
805
- async function applyIdentifierToTransaction(transaction, identifier) {
806
- await transaction.unsafe(`SELECT set_config('app.bypass_identifier', $1, true)`, [
807
- stringifyBypassIdentifier(identifier)
808
- ]);
809
- }
810
- function assertBypassIdentifier(identifier) {
811
- if (typeof identifier === "number") {
812
- if (!Number.isInteger(identifier) || identifier <= 0) {
813
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
814
- }
815
- return;
816
- }
817
- if (typeof identifier === "string" && identifier.trim() !== "") {
818
- return;
819
- }
820
- throw new Error("RLS bypass requires a caller-supplied identifier that pins the row.");
821
- }
822
- async function runWithScopedTenantTransaction(apply, callback) {
823
- if (!isRlsTenancy()) {
824
- return await callback();
825
- }
826
- if (hasActiveDatabaseConnection()) {
827
- const connection = getActiveDatabaseConnection(getDefaultDatabasePool2());
828
- return await runInTransaction(async () => {
829
- const [previous] = await connection.unsafe(`SELECT current_setting('app.tenant_id', true) AS tenant_id,
830
- current_setting('app.bypass_rls', true) AS bypass_rls,
831
- current_setting('app.bypass_identifier', true) AS bypass_identifier`);
832
- await apply(connection);
833
- const result = await callback();
834
- await connection.unsafe(`SELECT set_config('app.tenant_id', $1, true),
835
- set_config('app.bypass_rls', $2, true), set_config('app.bypass_identifier', $3, true)`, [previous?.tenant_id ?? "", previous?.bypass_rls ?? "", previous?.bypass_identifier ?? ""]);
836
- return result;
837
- });
838
- }
839
- const pool = getDefaultDatabasePool2();
840
- const begin = pool.begin;
841
- if (typeof begin !== "function") {
842
- throw new Error("RLS migration bypass requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
843
- }
844
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
845
- return await begin.bind(pool)(AsyncLocalStorage3.bind(async (transaction) => {
846
- await apply(transaction);
847
- return await runWithDatabaseConnection(transaction, () => runWithTransactionScope(async () => commitOrRollbackScope(await callback())));
848
- }));
849
- }));
850
- }
851
- async function runWithMigrationBypass(callback) {
852
- return await runWithScopedTenantTransaction((transaction) => applyBypassToTransaction(transaction, true), callback);
853
- }
854
- async function runWithMigrationBypassForIdentifier(identifier, callback) {
855
- assertBypassIdentifier(identifier);
856
- return await runWithScopedTenantTransaction((transaction) => applyIdentifierToTransaction(transaction, identifier), callback);
857
- }
858
- var init_databaseTenantContext = __esm(() => {
859
- init_connectionContext();
860
- init_transaction();
861
- init_transactionControl();
862
- init_deferredModelEvents();
863
- init_tenancyConfig();
864
- });
865
21
 
866
22
  // ../../src/core/tenant/tenantDatabaseScope.ts
867
- import { getDefaultDatabasePool as getDefaultDatabasePool3 } from "@getstrata/core/database/defaultConnection";
868
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
869
- async function applyTenantContextToTransaction(transaction, tenantId) {
870
- await transaction.unsafe(`SELECT set_config('app.tenant_id', $1, true)`, [String(tenantId)]);
871
- await transaction.unsafe(`SELECT set_config('app.bypass_rls', $1, true)`, ["false"]);
872
- }
873
- async function runWithTenantDatabase(tenant, callback) {
874
- const outerTenant = currentTenant();
875
- if (hasActiveDatabaseConnection() && outerTenant && outerTenant.id !== tenant.id) {
876
- throw new Error("Cannot switch tenants inside an active database transaction.");
877
- }
878
- if (!isTenancyEnabled() || !isRlsTenancy()) {
879
- return await runWithTenant(tenant, callback);
880
- }
881
- if (hasActiveDatabaseConnection()) {
882
- const activeConnection = getActiveDatabaseConnection(getDefaultDatabasePool3());
883
- return await runWithScopedTenantTransaction(() => applyTenantContextToTransaction(activeConnection, tenant.id), () => runWithTenant(tenant, callback));
884
- }
885
- const pool = getDefaultDatabasePool3();
886
- const begin = pool.begin;
887
- if (typeof begin !== "function") {
888
- throw new Error("RLS tenant scope requires a pool that supports begin(). Session-scoped set_config is not used on pooled connections.");
889
- }
890
- return await settleTransaction(() => runWithDeferredModelEvents(async () => {
891
- return await begin.bind(pool)(AsyncLocalStorage4.bind(async (transaction) => {
892
- await applyTenantContextToTransaction(transaction, tenant.id);
893
- return await runWithDatabaseConnection(transaction, async () => {
894
- return await runWithTransactionScope(async () => commitOrRollbackScope(await runWithTenant(tenant, callback)));
895
- });
896
- }));
897
- }));
23
+ function runWithTenantDatabase(selected, policy, tenant, callback) {
24
+ return policy.run(selected, { kind: "tenant", tenantId: tenant.id }, (child) => runWithTenant(tenant, () => callback(child)));
898
25
  }
899
- function isInsideTenantDatabaseScope(tenantId = currentTenant()?.id) {
900
- return hasActiveDatabaseConnection() && currentTenant()?.id === tenantId;
901
- }
902
- var init_tenantDatabaseScope = __esm(() => {
903
- init_connectionContext();
904
- init_transactionControl();
905
- init_deferredModelEvents();
906
- init_databaseTenantContext();
907
- init_tenancyConfig();
908
- init_tenantContext();
909
- });
910
-
911
- // entries/tenant/tenantDatabaseScope.ts
912
- init_tenantDatabaseScope();
913
26
  export {
914
- applyTenantContextToTransaction,
915
- isInsideTenantDatabaseScope,
916
27
  runWithTenantDatabase
917
28
  };