@getstrata/core 0.3.9 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/bootstrap/httpKernel.d.ts +2 -0
  2. package/dist/config/queue.d.ts +8 -0
  3. package/dist/config/rateLimit.d.ts +2 -1
  4. package/dist/core/database/baseRepository.d.ts +16 -4
  5. package/dist/core/database/boundConnection.d.ts +5 -0
  6. package/dist/core/database/index.d.ts +10 -4
  7. package/dist/core/database/migrations/advisoryLock.d.ts +6 -0
  8. package/dist/core/database/migrations/runner.d.ts +8 -2
  9. package/dist/core/database/migrations/types.d.ts +1 -0
  10. package/dist/core/database/model.d.ts +46 -17
  11. package/dist/core/database/query.d.ts +26 -14
  12. package/dist/core/database/relationships.d.ts +32 -2
  13. package/dist/core/database/repositoryConnection.d.ts +4 -0
  14. package/dist/core/database/repositoryQuery.d.ts +16 -1
  15. package/dist/core/database/schema/blueprint.d.ts +47 -0
  16. package/dist/core/database/schema/columnDefinition.d.ts +36 -0
  17. package/dist/core/database/schema/driver.d.ts +8 -0
  18. package/dist/core/database/schema/errors.d.ts +4 -0
  19. package/dist/core/database/schema/grammars/compileStatements.d.ts +8 -0
  20. package/dist/core/database/schema/grammars/createGrammar.d.ts +4 -0
  21. package/dist/core/database/schema/grammars/grammar.d.ts +10 -0
  22. package/dist/core/database/schema/grammars/index.d.ts +7 -0
  23. package/dist/core/database/schema/grammars/mysqlGrammar.d.ts +2 -0
  24. package/dist/core/database/schema/grammars/postgresGrammar.d.ts +2 -0
  25. package/dist/core/database/schema/grammars/sqliteGrammar.d.ts +2 -0
  26. package/dist/core/database/schema/index.d.ts +12 -0
  27. package/dist/core/database/schema/schema.d.ts +21 -0
  28. package/dist/core/database/seeders/runner.d.ts +6 -0
  29. package/dist/core/database/seeders/types.d.ts +8 -0
  30. package/dist/core/database/types.d.ts +39 -2
  31. package/dist/core/database/whereBuilder.d.ts +17 -0
  32. package/dist/core/http/index.d.ts +1 -1
  33. package/dist/core/http/securedRouteModelBinding.d.ts +2 -1
  34. package/dist/core/lifecycle/gracefulShutdown.d.ts +6 -0
  35. package/dist/core/pagination/index.d.ts +11 -1
  36. package/dist/core/queue/failedJobRepository.d.ts +6 -0
  37. package/dist/core/queue/failedJobService.d.ts +15 -0
  38. package/dist/core/queue/failedJobTable.d.ts +3 -0
  39. package/dist/core/queue/jobRegistry.d.ts +14 -0
  40. package/dist/core/queue/jobRunner.d.ts +9 -0
  41. package/dist/core/queue/publicQueue.d.ts +15 -0
  42. package/dist/core/queue/redisQueue.d.ts +29 -0
  43. package/dist/core/queue/resilientQueue.d.ts +9 -0
  44. package/dist/core/queue/types.d.ts +8 -0
  45. package/dist/core/scheduler/schedule.d.ts +15 -0
  46. package/dist/entries/auth/accessControl.js +113 -0
  47. package/dist/entries/auth/authContext.js +15 -0
  48. package/dist/entries/auth/guard.js +2870 -0
  49. package/dist/entries/auth/membershipContext.js +276 -0
  50. package/dist/entries/auth/membershipScope.js +390 -0
  51. package/dist/entries/auth/membershipService.js +477 -0
  52. package/dist/entries/auth/oauth/oidcProvider.js +49 -0
  53. package/dist/entries/auth/oauth/providers.js +71 -0
  54. package/dist/entries/auth/oauth/samlProvider.js +26 -0
  55. package/dist/entries/auth/oauth/types.js +1 -0
  56. package/dist/entries/auth/password.js +15 -0
  57. package/dist/entries/auth/policy.js +134 -0
  58. package/dist/entries/auth/sessionCookie.js +75 -0
  59. package/dist/entries/auth/tokenHash.js +17 -0
  60. package/dist/entries/cache/tags.js +13 -0
  61. package/dist/entries/crypto/fieldEncryption.js +93 -0
  62. package/dist/entries/crypto/mfaSecret.js +105 -0
  63. package/dist/entries/database/factory.js +17 -0
  64. package/dist/entries/database/seeders.js +30 -0
  65. package/dist/entries/database/types.js +1 -0
  66. package/dist/entries/database.js +2218 -0
  67. package/dist/entries/errors/http.js +78 -0
  68. package/dist/entries/http/contentNegotiation.js +26 -0
  69. package/dist/entries/http/csrfToken.js +147 -0
  70. package/dist/entries/http/etag.js +170 -0
  71. package/dist/entries/http/flashSession.js +106 -0
  72. package/dist/entries/http/middleware.js +68 -0
  73. package/dist/entries/http/parseFormBody.js +88 -0
  74. package/dist/entries/http/requestMetaContext.js +18 -0
  75. package/dist/entries/http/resources.js +19 -0
  76. package/dist/entries/http/webErrorResponse.js +3143 -0
  77. package/dist/entries/http/webFormRequest.js +293 -0
  78. package/dist/entries/http.js +3924 -0
  79. package/dist/entries/jobs/dispatchWebhookJob.js +342 -0
  80. package/dist/entries/lifecycle/gracefulShutdown.js +50 -0
  81. package/dist/entries/metrics/prometheus.js +70 -0
  82. package/dist/entries/pagination.js +14 -0
  83. package/dist/entries/queue/createAppQueue.js +2848 -0
  84. package/dist/entries/queue/failedJobService.js +38 -0
  85. package/dist/entries/queue/jobRegistry.js +32 -0
  86. package/dist/entries/queue/jobRunner.js +75 -0
  87. package/dist/entries/queue/publicQueue.js +2476 -0
  88. package/dist/entries/queue/queueMetrics.js +2898 -0
  89. package/dist/entries/queue/types.js +1 -0
  90. package/dist/entries/security/oauthState.js +75 -0
  91. package/dist/entries/security/publicReads.js +33 -0
  92. package/dist/entries/security/safeUrl.js +143 -0
  93. package/dist/entries/security/securityEvents.js +41 -0
  94. package/dist/entries/security/stripeWebhook.js +115 -0
  95. package/dist/entries/security/tokenExpiry.js +16 -0
  96. package/dist/entries/security/totp.js +51 -0
  97. package/dist/entries/storage/storage.js +123 -0
  98. package/dist/entries/tenant/tenantContext.js +30 -0
  99. package/dist/entries/tenant/tenantMiddleware.js +312 -0
  100. package/dist/entries/tracing/traceContext.js +15 -0
  101. package/dist/entries/validation/rules.js +232 -0
  102. package/dist/entries/view.js +3072 -0
  103. package/dist/framework/public-api.d.ts +65 -38
  104. package/dist/index.js +3213 -281
  105. package/dist/modules/user/apiTokenRepository.d.ts +1 -1
  106. package/dist/modules/user/apiTokenTable.d.ts +1 -1
  107. package/dist/modules/user/authService.d.ts +1 -1
  108. package/dist/modules/user/notificationRepository.d.ts +1 -1
  109. package/dist/modules/user/notificationService.d.ts +1 -1
  110. package/dist/modules/user/notificationTable.d.ts +1 -1
  111. package/dist/modules/user/oauthIdentityRepository.d.ts +2 -2
  112. package/dist/modules/user/provider.d.ts +1 -1
  113. package/dist/modules/user/repository.d.ts +1 -1
  114. package/dist/modules/user/table.d.ts +1 -1
  115. package/dist/modules/user/tokenService.d.ts +1 -1
  116. package/package.json +289 -3
@@ -0,0 +1,2870 @@
1
+ // @bun
2
+ // ../../src/domain/abilities.ts
3
+ var MEMBER_ABILITIES = [
4
+ "organizations:read",
5
+ "projects:read",
6
+ "projects:create",
7
+ "tasks:read",
8
+ "tasks:create",
9
+ "comments:read",
10
+ "comments:create",
11
+ "attachments:read",
12
+ "attachments:create",
13
+ "auth:tokens:read",
14
+ "auth:tokens:write"
15
+ ];
16
+ var ADMIN_ABILITIES = [
17
+ ...MEMBER_ABILITIES,
18
+ "organizations:create",
19
+ "organizations:update",
20
+ "organizations:delete",
21
+ "projects:update",
22
+ "projects:delete",
23
+ "tasks:update",
24
+ "tasks:delete",
25
+ "comments:update",
26
+ "comments:delete",
27
+ "attachments:delete",
28
+ "webhooks:read",
29
+ "webhooks:write",
30
+ "audit:read"
31
+ ];
32
+ var PLATFORM_ADMIN_ABILITIES = ["*"];
33
+ function resolveAbilitiesForRole(role) {
34
+ if (role === "admin") {
35
+ return [...PLATFORM_ADMIN_ABILITIES];
36
+ }
37
+ return [...MEMBER_ABILITIES];
38
+ }
39
+
40
+ // ../../src/bootstrap/config.ts
41
+ var CORE_QUEUE_TOKEN = "core.queue";
42
+ var CORE_POLICY_GATE_TOKEN = "core.policyGate";
43
+ var CORE_AUTH_TOKEN = "core.auth";
44
+ var CORE_TOKEN_SERVICE_TOKEN = "core.tokenService";
45
+ var DEFAULT_QUEUE_DRIVER = "sync";
46
+
47
+ // ../../src/core/auth/oauth/oidcProvider.ts
48
+ class OidcProvider {
49
+ options;
50
+ name;
51
+ constructor(options) {
52
+ this.options = options;
53
+ this.name = options.name;
54
+ }
55
+ getAuthorizationUrl(state) {
56
+ const params = new URLSearchParams({
57
+ client_id: this.options.clientId,
58
+ redirect_uri: this.options.redirectUri,
59
+ response_type: "code",
60
+ scope: (this.options.scopes ?? ["openid", "email", "profile"]).join(" "),
61
+ state
62
+ });
63
+ return `${this.options.issuer.replace(/\/$/, "")}/authorize?${params.toString()}`;
64
+ }
65
+ async exchangeCode(code) {
66
+ const tokenResponse = await fetch(`${this.options.issuer.replace(/\/$/, "")}/token`, {
67
+ method: "POST",
68
+ headers: { "content-type": "application/x-www-form-urlencoded" },
69
+ body: new URLSearchParams({
70
+ grant_type: "authorization_code",
71
+ code,
72
+ redirect_uri: this.options.redirectUri,
73
+ client_id: this.options.clientId,
74
+ client_secret: this.options.clientSecret
75
+ })
76
+ });
77
+ const tokenBody = await tokenResponse.json();
78
+ if (!tokenBody.access_token) {
79
+ throw new Error("OIDC token exchange failed.");
80
+ }
81
+ const profileResponse = await fetch(`${this.options.issuer.replace(/\/$/, "")}/userinfo`, {
82
+ headers: { authorization: `Bearer ${tokenBody.access_token}` }
83
+ });
84
+ const profile = await profileResponse.json();
85
+ return {
86
+ providerUserId: profile.sub,
87
+ email: profile.email ?? `${profile.sub}@oidc.local`,
88
+ name: profile.name ?? profile.sub
89
+ };
90
+ }
91
+ }
92
+
93
+ // ../../src/core/auth/oauth/providers.ts
94
+ class GitHubOAuthProvider {
95
+ options;
96
+ name = "github";
97
+ constructor(options) {
98
+ this.options = options;
99
+ }
100
+ getAuthorizationUrl(state) {
101
+ const params = new URLSearchParams({
102
+ client_id: this.options.clientId,
103
+ redirect_uri: this.options.redirectUri,
104
+ scope: "read:user user:email",
105
+ state
106
+ });
107
+ return `https://github.com/login/oauth/authorize?${params.toString()}`;
108
+ }
109
+ async exchangeCode(code) {
110
+ const tokenResponse = await fetch("https://github.com/login/oauth/access_token", {
111
+ method: "POST",
112
+ headers: {
113
+ accept: "application/json",
114
+ "content-type": "application/json"
115
+ },
116
+ body: JSON.stringify({
117
+ client_id: this.options.clientId,
118
+ client_secret: this.options.clientSecret,
119
+ code,
120
+ redirect_uri: this.options.redirectUri
121
+ })
122
+ });
123
+ const tokenBody = await tokenResponse.json();
124
+ if (!tokenBody.access_token) {
125
+ throw new Error("GitHub OAuth token exchange failed.");
126
+ }
127
+ const profileResponse = await fetch("https://api.github.com/user", {
128
+ headers: {
129
+ authorization: `Bearer ${tokenBody.access_token}`,
130
+ accept: "application/json",
131
+ "user-agent": "workhub"
132
+ }
133
+ });
134
+ const profile = await profileResponse.json();
135
+ return {
136
+ providerUserId: String(profile.id),
137
+ email: profile.email ?? `${profile.login}@users.noreply.github.com`,
138
+ name: profile.name ?? profile.login
139
+ };
140
+ }
141
+ }
142
+
143
+ class MockOAuthProvider {
144
+ profile;
145
+ name = "mock";
146
+ constructor(profile) {
147
+ this.profile = profile;
148
+ }
149
+ getAuthorizationUrl(state) {
150
+ return `https://mock.oauth/authorize?state=${encodeURIComponent(state)}`;
151
+ }
152
+ async exchangeCode(code) {
153
+ if (code !== "valid-code") {
154
+ throw new Error("Invalid OAuth code.");
155
+ }
156
+ return this.profile;
157
+ }
158
+ }
159
+
160
+ // ../../src/core/auth/oauth/samlProvider.ts
161
+ class SamlProvider {
162
+ loginUrl;
163
+ name = "saml";
164
+ constructor(loginUrl) {
165
+ this.loginUrl = loginUrl;
166
+ }
167
+ getAuthorizationUrl(state) {
168
+ return `${this.loginUrl}?state=${encodeURIComponent(state)}`;
169
+ }
170
+ async exchangeCode(code) {
171
+ if (!code.startsWith("saml:")) {
172
+ throw new Error("Invalid SAML assertion reference.");
173
+ }
174
+ const [, email, name] = code.split(":");
175
+ return {
176
+ providerUserId: email ?? "saml-user",
177
+ email: email ?? "saml-user@workhub.test",
178
+ name: name ?? "SAML User"
179
+ };
180
+ }
181
+ }
182
+
183
+ // ../../src/config/features.ts
184
+ function readFeatureFlags() {
185
+ return {
186
+ webhooks: (process.env.FEATURE_WEBHOOKS ?? "true") !== "false",
187
+ fullTextSearch: (process.env.FEATURE_SEARCH ?? "true") !== "false",
188
+ auditLog: (process.env.FEATURE_AUDIT_LOG ?? "true") !== "false",
189
+ oauthLogin: (process.env.FEATURE_OAUTH ?? "true") !== "false",
190
+ samlLogin: (process.env.FEATURE_SAML ?? "false") === "true",
191
+ scim: (process.env.FEATURE_SCIM ?? "true") !== "false",
192
+ billing: (process.env.FEATURE_BILLING ?? "true") !== "false",
193
+ siemExport: (process.env.FEATURE_SIEM_EXPORT ?? "true") !== "false",
194
+ publicReads: (process.env.FEATURE_PUBLIC_READS ?? "true") !== "false",
195
+ emailVerification: (process.env.FEATURE_EMAIL_VERIFICATION ?? "false") === "true",
196
+ mfa: (process.env.FEATURE_MFA ?? "false") === "true"
197
+ };
198
+ }
199
+ var featureFlags = readFeatureFlags();
200
+ function isFeatureEnabled(feature) {
201
+ return readFeatureFlags()[feature];
202
+ }
203
+
204
+ // ../../src/core/events/eventBus.ts
205
+ class EventBus {
206
+ constructor() {}
207
+ listeners = new Map;
208
+ listen(event, listener) {
209
+ const handlers = this.listeners.get(event) ?? new Set;
210
+ handlers.add(listener);
211
+ this.listeners.set(event, handlers);
212
+ return () => {
213
+ handlers.delete(listener);
214
+ if (handlers.size === 0) {
215
+ this.listeners.delete(event);
216
+ }
217
+ };
218
+ }
219
+ async dispatch(event, payload) {
220
+ const handlers = this.listeners.get(event);
221
+ if (!handlers || handlers.size === 0) {
222
+ return;
223
+ }
224
+ for (const handler of handlers) {
225
+ await handler(payload);
226
+ }
227
+ }
228
+ }
229
+ var eventBus = new EventBus;
230
+
231
+ // ../../src/core/events/index.ts
232
+ function modelEventName(tableName, action) {
233
+ return `${tableName}.${action}`;
234
+ }
235
+
236
+ // ../../src/core/pagination/index.ts
237
+ function buildPaginationMeta(input) {
238
+ const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
239
+ return {
240
+ page: input.page,
241
+ per_page: input.perPage,
242
+ total: input.total,
243
+ last_page: lastPage
244
+ };
245
+ }
246
+
247
+ // ../../src/core/errors/http.ts
248
+ class HttpError extends Error {
249
+ status;
250
+ details;
251
+ constructor(status, message, details) {
252
+ super(message);
253
+ this.name = new.target.name;
254
+ this.status = status;
255
+ this.details = details;
256
+ }
257
+ }
258
+
259
+ class BadRequestError extends HttpError {
260
+ constructor(message = "Bad Request", details) {
261
+ super(400, message, details);
262
+ }
263
+ }
264
+
265
+ class NotFoundError extends HttpError {
266
+ constructor(message = "Not Found", details) {
267
+ super(404, message, details);
268
+ }
269
+ }
270
+
271
+ class ConflictError extends HttpError {
272
+ constructor(message = "Conflict", details) {
273
+ super(409, message, details);
274
+ }
275
+ }
276
+
277
+ class UnprocessableEntityError extends HttpError {
278
+ constructor(message = "Unprocessable Entity", details) {
279
+ super(422, message, details);
280
+ }
281
+ }
282
+
283
+ class ValidationError extends HttpError {
284
+ constructor(message = "Validation failed", details) {
285
+ super(422, message, details);
286
+ }
287
+ }
288
+
289
+ class ForbiddenError extends HttpError {
290
+ constructor(message = "Forbidden", details) {
291
+ super(403, message, details);
292
+ }
293
+ }
294
+
295
+ class UnauthorizedError extends HttpError {
296
+ constructor(message = "Unauthorized", details) {
297
+ super(401, message, details);
298
+ }
299
+ }
300
+
301
+ class PayloadTooLargeError extends HttpError {
302
+ constructor(message = "Payload Too Large", details) {
303
+ super(413, message, details);
304
+ }
305
+ }
306
+
307
+ class PreconditionFailedError extends HttpError {
308
+ constructor(message = "Precondition Failed", details) {
309
+ super(412, message, details);
310
+ }
311
+ }
312
+
313
+ // ../../src/core/database/errors.ts
314
+ function isPostgresError(error) {
315
+ return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
316
+ }
317
+ function getPostgresSqlState(error) {
318
+ if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
319
+ return error.errno;
320
+ }
321
+ if (typeof error.errno === "number") {
322
+ return String(error.errno).padStart(5, "0");
323
+ }
324
+ if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
325
+ return error.code;
326
+ }
327
+ return;
328
+ }
329
+ function mapDatabaseError(error) {
330
+ if (error instanceof HttpError) {
331
+ return error;
332
+ }
333
+ if (!isPostgresError(error)) {
334
+ const message = error instanceof Error ? error.message : "Database operation failed.";
335
+ return new BadRequestError(message);
336
+ }
337
+ const sqlState = getPostgresSqlState(error);
338
+ switch (sqlState) {
339
+ case "23505":
340
+ return new ConflictError(error.detail ?? "A record with these values already exists.", {
341
+ constraint: error.constraint
342
+ });
343
+ case "23503":
344
+ return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
345
+ constraint: error.constraint
346
+ });
347
+ case "23502":
348
+ return new BadRequestError(error.detail ?? "Required field is missing.", {
349
+ constraint: error.constraint
350
+ });
351
+ case "23514":
352
+ return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
353
+ constraint: error.constraint
354
+ });
355
+ default:
356
+ return new BadRequestError(error.message ?? "Database operation failed.", {
357
+ code: error.code,
358
+ sqlState
359
+ });
360
+ }
361
+ }
362
+ async function withDatabaseErrorHandling(operation) {
363
+ try {
364
+ return await operation();
365
+ } catch (error) {
366
+ throw mapDatabaseError(error);
367
+ }
368
+ }
369
+
370
+ // ../../src/core/database/query.ts
371
+ function quoteIdentifier(identifier) {
372
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
373
+ throw new Error(`Invalid SQL identifier: ${identifier}`);
374
+ }
375
+ return `"${identifier}"`;
376
+ }
377
+ function qualifyColumn(tableName, column) {
378
+ return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
379
+ }
380
+ function resolveQualifiedColumn(defaultTable, columnName) {
381
+ if (columnName.includes(".")) {
382
+ const [table, column] = columnName.split(".", 2);
383
+ if (!table || !column) {
384
+ throw new Error(`Invalid qualified column: ${columnName}`);
385
+ }
386
+ return qualifyColumn(table, column);
387
+ }
388
+ return qualifyColumn(defaultTable, columnName);
389
+ }
390
+ function parseQualifiedColumn(reference) {
391
+ const [table, column] = reference.split(".", 2);
392
+ if (!table || !column) {
393
+ throw new Error(`Join columns must be qualified as table.column: ${reference}`);
394
+ }
395
+ return { table, column };
396
+ }
397
+ function normalizeDirection(direction = "ASC") {
398
+ return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
399
+ }
400
+ function isQueryOperator(value) {
401
+ return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
402
+ }
403
+ function pushParam(values, value) {
404
+ values.push(value);
405
+ return `$${values.length}`;
406
+ }
407
+ function buildInClause(column, values, params) {
408
+ if (values.length === 0) {
409
+ return "1 = 0";
410
+ }
411
+ const placeholders = values.map((value) => pushParam(params, value)).join(", ");
412
+ return `${column} IN (${placeholders})`;
413
+ }
414
+ function buildOperatorClauses(column, operator, params) {
415
+ const clauses = [];
416
+ if (operator.isNull === true) {
417
+ clauses.push(`${column} IS NULL`);
418
+ }
419
+ if (operator.isNull === false) {
420
+ clauses.push(`${column} IS NOT NULL`);
421
+ }
422
+ if (operator.eq !== undefined) {
423
+ if (operator.eq === null) {
424
+ clauses.push(`${column} IS NULL`);
425
+ } else {
426
+ clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
427
+ }
428
+ }
429
+ if (operator.in !== undefined) {
430
+ clauses.push(buildInClause(column, operator.in, params));
431
+ }
432
+ if (operator.gt !== undefined) {
433
+ clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
434
+ }
435
+ if (operator.gte !== undefined) {
436
+ clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
437
+ }
438
+ if (operator.lt !== undefined) {
439
+ clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
440
+ }
441
+ if (operator.lte !== undefined) {
442
+ clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
443
+ }
444
+ if (operator.ilike !== undefined) {
445
+ clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
446
+ }
447
+ if (operator.tsMatch !== undefined) {
448
+ clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
449
+ }
450
+ return clauses;
451
+ }
452
+ function appendWhereParts(tableName, where, params) {
453
+ const clauses = [];
454
+ for (const [columnName, filterValue] of Object.entries(where)) {
455
+ if (filterValue === undefined) {
456
+ continue;
457
+ }
458
+ const column = resolveQualifiedColumn(tableName, columnName);
459
+ if (Array.isArray(filterValue)) {
460
+ clauses.push(buildInClause(column, filterValue, params));
461
+ continue;
462
+ }
463
+ if (isQueryOperator(filterValue)) {
464
+ clauses.push(...buildOperatorClauses(column, filterValue, params));
465
+ continue;
466
+ }
467
+ if (filterValue === null) {
468
+ clauses.push(`${column} IS NULL`);
469
+ continue;
470
+ }
471
+ clauses.push(`${column} = ${pushParam(params, filterValue)}`);
472
+ }
473
+ return clauses.join(" AND ");
474
+ }
475
+ function buildWhereClause(tableName, where = {}) {
476
+ const params = [];
477
+ const body = appendWhereParts(tableName, where, params);
478
+ return {
479
+ clause: body.length > 0 ? ` WHERE ${body}` : "",
480
+ params
481
+ };
482
+ }
483
+ function buildWhereNodeClause(tableName, node, params) {
484
+ if ("where" in node) {
485
+ return appendWhereParts(tableName, node.where, params);
486
+ }
487
+ const grouped = buildWhereGroupClause(tableName, node.group, params);
488
+ if (!grouped) {
489
+ return "";
490
+ }
491
+ return grouped.includes(" OR ") ? `(${grouped})` : grouped;
492
+ }
493
+ function buildWhereGroupClause(tableName, nodes, params) {
494
+ let result = "";
495
+ for (const node of nodes) {
496
+ const part = buildWhereNodeClause(tableName, node, params);
497
+ if (!part) {
498
+ continue;
499
+ }
500
+ if (!result) {
501
+ result = part;
502
+ continue;
503
+ }
504
+ result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
505
+ }
506
+ if (!result) {
507
+ return "";
508
+ }
509
+ return result;
510
+ }
511
+ function buildAdvancedWhereClause(tableName, where = {}, whereNodes = []) {
512
+ const params = [];
513
+ const nodes = [];
514
+ if (Object.keys(where).length > 0) {
515
+ nodes.push({ kind: "and", where });
516
+ }
517
+ nodes.push(...whereNodes);
518
+ const combined = buildWhereGroupClause(tableName, nodes, params);
519
+ return {
520
+ clause: combined ? ` WHERE ${combined}` : "",
521
+ params
522
+ };
523
+ }
524
+ function resolveSoftDeleteColumn(table) {
525
+ if (!table.softDeletes) {
526
+ return null;
527
+ }
528
+ if (table.softDeletes === true) {
529
+ return "deleted_at";
530
+ }
531
+ return table.softDeletes.column ?? "deleted_at";
532
+ }
533
+ function appendSoftDeleteScope(table, options, clauses) {
534
+ const column = resolveSoftDeleteColumn(table);
535
+ if (!column) {
536
+ return;
537
+ }
538
+ const qualifiedColumn = qualifyColumn(table.name, column);
539
+ if (options.onlyTrashed) {
540
+ clauses.push(`${qualifiedColumn} IS NOT NULL`);
541
+ return;
542
+ }
543
+ if (!options.withTrashed) {
544
+ clauses.push(`${qualifiedColumn} IS NULL`);
545
+ }
546
+ }
547
+ function buildQueryWhereClause(table, options = {}, whereNodes = []) {
548
+ const { clause, params } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes);
549
+ const softDeleteClauses = [];
550
+ appendSoftDeleteScope(table, options, softDeleteClauses);
551
+ if (softDeleteClauses.length === 0) {
552
+ return { clause, params };
553
+ }
554
+ const base = clause.replace(/^ WHERE /, "");
555
+ const scope = softDeleteClauses.join(" AND ");
556
+ return {
557
+ clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
558
+ params
559
+ };
560
+ }
561
+ function isQueryOrder(value) {
562
+ return "column" in value;
563
+ }
564
+ function normalizeOrderBy(orderBy) {
565
+ if (!orderBy) {
566
+ return [];
567
+ }
568
+ if (Array.isArray(orderBy)) {
569
+ return orderBy;
570
+ }
571
+ if (isQueryOrder(orderBy)) {
572
+ return [orderBy];
573
+ }
574
+ return Object.entries(orderBy).map(([column, direction]) => ({
575
+ column,
576
+ direction
577
+ }));
578
+ }
579
+ function buildOrderByClause(tableName, orderBy) {
580
+ const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
581
+ return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
582
+ });
583
+ return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
584
+ }
585
+ function buildGroupByClause(tableName, groupBy) {
586
+ if (!groupBy) {
587
+ return "";
588
+ }
589
+ const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
590
+ const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
591
+ return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
592
+ }
593
+ function buildHavingClause(tableName, having, params) {
594
+ if (!having) {
595
+ return "";
596
+ }
597
+ const body = appendWhereParts(tableName, having, params);
598
+ return body.length > 0 ? ` HAVING ${body}` : "";
599
+ }
600
+ function buildJoinClause(joins = []) {
601
+ return joins.map((join) => {
602
+ const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
603
+ const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
604
+ return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
605
+ }).join("");
606
+ }
607
+ function buildLimitClause(limit) {
608
+ if (limit === undefined) {
609
+ return "";
610
+ }
611
+ if (!Number.isInteger(limit) || limit <= 0) {
612
+ throw new Error("Query limit must be a positive integer.");
613
+ }
614
+ return ` LIMIT ${limit}`;
615
+ }
616
+ function buildOffsetClause(offset) {
617
+ if (offset === undefined) {
618
+ return "";
619
+ }
620
+ if (!Number.isInteger(offset) || offset < 0) {
621
+ throw new Error("Query offset must be a non-negative integer.");
622
+ }
623
+ return ` OFFSET ${offset}`;
624
+ }
625
+ function buildReturningColumns(table) {
626
+ return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
627
+ }
628
+ function buildSelectList(table, select, params = []) {
629
+ if (!select || select.length === 0) {
630
+ return buildReturningColumns(table);
631
+ }
632
+ return select.map((item) => {
633
+ if (item.kind === "column") {
634
+ const column2 = qualifyColumn(item.table, item.column);
635
+ return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
636
+ }
637
+ if (item.kind === "literalText") {
638
+ return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
639
+ }
640
+ const column = qualifyColumn(item.table, item.column);
641
+ const placeholder = pushParam(params, item.query);
642
+ return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
643
+ }).join(", ");
644
+ }
645
+ function getDefinedColumnEntries(table, values, options = {}) {
646
+ const record = values;
647
+ const excluded = new Set(options.exclude ?? []);
648
+ return table.columns.flatMap((column) => {
649
+ if (excluded.has(column) || !Object.hasOwn(record, column)) {
650
+ return [];
651
+ }
652
+ const value = record[column];
653
+ if (value === undefined) {
654
+ return [];
655
+ }
656
+ return [[column, value]];
657
+ });
658
+ }
659
+ function buildSelectQuery(table, options = {}, whereNodes = []) {
660
+ const params = [];
661
+ const columns = buildSelectList(table, options.select, params);
662
+ const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
663
+ params.push(...whereParams);
664
+ const joins = buildJoinClause(options.joins);
665
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
666
+ const havingClause = buildHavingClause(table.name, options.having, params);
667
+ const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
668
+ const limit = buildLimitClause(options.limit);
669
+ const offset = buildOffsetClause(options.offset);
670
+ return {
671
+ text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
672
+ params
673
+ };
674
+ }
675
+ function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
676
+ const params = [];
677
+ const { clause, params: whereParams } = buildQueryWhereClause(table, {
678
+ where,
679
+ withTrashed: options.withTrashed,
680
+ onlyTrashed: options.onlyTrashed
681
+ }, whereNodes);
682
+ params.push(...whereParams);
683
+ const joins = buildJoinClause(options.joins);
684
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
685
+ return {
686
+ text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
687
+ params
688
+ };
689
+ }
690
+ function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
691
+ assertSafeProjectionExpression(expression);
692
+ const params = [];
693
+ const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
694
+ params.push(...whereParams);
695
+ const joins = buildJoinClause(options.joins);
696
+ const groupBy = buildGroupByClause(table.name, options.groupBy);
697
+ const orderBy = buildOrderByClause(table.name, options.orderBy);
698
+ const limit = buildLimitClause(options.limit);
699
+ return {
700
+ text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
701
+ params
702
+ };
703
+ }
704
+ var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
705
+ function assertSafeProjectionExpression(expression) {
706
+ if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
707
+ throw new Error(`Unsafe projection expression: ${expression}`);
708
+ }
709
+ }
710
+ function buildGroupedCountQuery(table, column, where = {}, options = {}) {
711
+ const qualifiedColumn = qualifyColumn(table.name, column);
712
+ const { clause, params } = buildQueryWhereClause(table, {
713
+ where,
714
+ ...options
715
+ });
716
+ return {
717
+ text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
718
+ params
719
+ };
720
+ }
721
+ function buildInsertQuery(table, values) {
722
+ const entries = getDefinedColumnEntries(table, values);
723
+ if (entries.length === 0) {
724
+ throw new Error(`Cannot insert into ${table.name} without any column values.`);
725
+ }
726
+ const params = [];
727
+ const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
728
+ const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
729
+ const returningColumns = buildReturningColumns(table);
730
+ return {
731
+ text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
732
+ params
733
+ };
734
+ }
735
+ function buildUpdateQuery(table, id, changes) {
736
+ const entries = getDefinedColumnEntries(table, changes, {
737
+ exclude: [table.primaryKey]
738
+ });
739
+ if (entries.length === 0) {
740
+ throw new Error(`Cannot update ${table.name} without any changed column values.`);
741
+ }
742
+ const params = [];
743
+ const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
744
+ const primaryKeyPlaceholder = pushParam(params, id);
745
+ const returningColumns = buildReturningColumns(table);
746
+ const scopeClauses = [];
747
+ appendSoftDeleteScope(table, {}, scopeClauses);
748
+ const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
749
+ return {
750
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
751
+ params
752
+ };
753
+ }
754
+ function buildSoftDeleteByIdQuery(table, id, deletedAt) {
755
+ const deletedAtColumn = resolveSoftDeleteColumn(table);
756
+ if (!deletedAtColumn) {
757
+ throw new Error(`Table ${table.name} does not support soft deletes.`);
758
+ }
759
+ const returningColumns = buildReturningColumns(table);
760
+ const scopeClauses = [];
761
+ appendSoftDeleteScope(table, {}, scopeClauses);
762
+ const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
763
+ return {
764
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
765
+ params: [deletedAt, id]
766
+ };
767
+ }
768
+ function buildRestoreByIdQuery(table, id) {
769
+ const deletedAtColumn = resolveSoftDeleteColumn(table);
770
+ if (!deletedAtColumn) {
771
+ throw new Error(`Table ${table.name} does not support soft deletes.`);
772
+ }
773
+ const returningColumns = buildReturningColumns(table);
774
+ return {
775
+ text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
776
+ params: [null, id]
777
+ };
778
+ }
779
+ function buildDeleteByIdQuery(table, id) {
780
+ return {
781
+ text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
782
+ params: [id]
783
+ };
784
+ }
785
+
786
+ // ../../src/core/database/relationships.ts
787
+ function hasMany(definition) {
788
+ return {
789
+ type: "hasMany",
790
+ ...definition
791
+ };
792
+ }
793
+ function hasOne(definition) {
794
+ return {
795
+ type: "hasOne",
796
+ ...definition
797
+ };
798
+ }
799
+ function belongsTo(definition) {
800
+ return {
801
+ type: "belongsTo",
802
+ ...definition
803
+ };
804
+ }
805
+ function belongsToMany(definition) {
806
+ return {
807
+ type: "belongsToMany",
808
+ ...definition
809
+ };
810
+ }
811
+ function indexHasManyRelation(parents, children, relation) {
812
+ const groups = new Map;
813
+ for (const parent of parents) {
814
+ groups.set(parent[relation.localKey], []);
815
+ }
816
+ for (const child of children) {
817
+ const key = child[relation.foreignKey];
818
+ const group = groups.get(key);
819
+ if (!group) {
820
+ continue;
821
+ }
822
+ group.push(child);
823
+ }
824
+ return groups;
825
+ }
826
+ function indexHasOneRelation(parents, children, relation) {
827
+ const grouped = indexHasManyRelation(parents, children, relation);
828
+ const result = new Map;
829
+ for (const parent of parents) {
830
+ const matches = grouped.get(parent[relation.localKey]) ?? [];
831
+ result.set(parent[relation.localKey], matches[0]);
832
+ }
833
+ return result;
834
+ }
835
+ function indexBelongsToRelation(children, parents, relation) {
836
+ const parentsById = new Map;
837
+ for (const parent of parents) {
838
+ parentsById.set(parent[relation.ownerKey], parent);
839
+ }
840
+ const result = new Map;
841
+ for (const child of children) {
842
+ const foreignKey = child[relation.foreignKey];
843
+ const parent = parentsById.get(foreignKey);
844
+ if (parent) {
845
+ result.set(foreignKey, parent);
846
+ }
847
+ }
848
+ return result;
849
+ }
850
+ function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
851
+ const relatedById = new Map;
852
+ for (const related of relatedRows) {
853
+ relatedById.set(related[relation.relatedKey], related);
854
+ }
855
+ const groups = new Map;
856
+ for (const parent of parents) {
857
+ groups.set(parent[relation.parentKey], []);
858
+ }
859
+ for (const pivot of pivotRows) {
860
+ const parentId = pivot[relation.foreignPivotKey];
861
+ const relatedId = pivot[relation.relatedPivotKey];
862
+ const group = groups.get(parentId);
863
+ const related = relatedById.get(relatedId);
864
+ if (!group || !related) {
865
+ continue;
866
+ }
867
+ group.push(related);
868
+ }
869
+ return groups;
870
+ }
871
+
872
+ // ../../src/config/database.ts
873
+ function readInteger(name, fallback) {
874
+ const parsed = Number.parseInt(process.env[name] ?? String(fallback), 10);
875
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
876
+ }
877
+ var databaseConfig = {
878
+ url: process.env.DATABASE_URL ?? "",
879
+ poolMax: readInteger("DB_POOL_MAX", 10),
880
+ idleTimeoutSeconds: readInteger("DB_POOL_IDLE_TIMEOUT", 30),
881
+ maxLifetimeSeconds: readInteger("DB_POOL_MAX_LIFETIME", 3600),
882
+ connectionTimeoutSeconds: readInteger("DB_CONNECTION_TIMEOUT", 10)
883
+ };
884
+
885
+ // ../../src/core/database/connectionContext.ts
886
+ import { AsyncLocalStorage } from "async_hooks";
887
+ var activeConnection = new AsyncLocalStorage;
888
+ function runWithDatabaseConnection(connection, callback) {
889
+ return activeConnection.run(connection, callback);
890
+ }
891
+ function getActiveDatabaseConnection(fallback) {
892
+ return activeConnection.getStore() ?? fallback;
893
+ }
894
+
895
+ // ../../src/db/connection/createConnection.ts
896
+ var {SQL } = globalThis.Bun;
897
+ function createDatabaseConnection(config) {
898
+ if (!config.url) {
899
+ throw new Error("DATABASE_URL is not configured. Set DATABASE_URL before starting the app or running integration tests.");
900
+ }
901
+ return new SQL({
902
+ url: config.url,
903
+ max: config.poolMax,
904
+ idleTimeout: config.idleTimeoutSeconds,
905
+ maxLifetime: config.maxLifetimeSeconds,
906
+ connectionTimeout: config.connectionTimeoutSeconds
907
+ });
908
+ }
909
+
910
+ // ../../src/db/connection/index.ts
911
+ var connectionHolder = {
912
+ connection: null
913
+ };
914
+ function getDatabase() {
915
+ if (!connectionHolder.connection) {
916
+ connectionHolder.connection = createDatabaseConnection(databaseConfig);
917
+ }
918
+ return connectionHolder.connection;
919
+ }
920
+ var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
921
+ function resolveDatabase() {
922
+ return getActiveDatabaseConnection(getDatabase());
923
+ }
924
+ function resolveDatabaseForProperty(property) {
925
+ if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
926
+ return getDatabase();
927
+ }
928
+ return resolveDatabase();
929
+ }
930
+ var db = new Proxy(function database() {}, {
931
+ apply(_target, _thisArg, args) {
932
+ return resolveDatabase()(...args);
933
+ },
934
+ get(_target, property) {
935
+ const connection = resolveDatabaseForProperty(property);
936
+ const value = connection[property];
937
+ return typeof value === "function" ? value.bind(connection) : value;
938
+ }
939
+ });
940
+ var connection_default = db;
941
+
942
+ // ../../src/core/database/boundConnection.ts
943
+ var boundConnectionHolder = {
944
+ connection: null
945
+ };
946
+ function bindDatabaseConnection(connection) {
947
+ boundConnectionHolder.connection = connection;
948
+ }
949
+ function getBoundDatabaseConnection() {
950
+ return boundConnectionHolder.connection;
951
+ }
952
+
953
+ // ../../src/core/database/repositoryConnection.ts
954
+ function resolveRepositoryConnection() {
955
+ return getBoundDatabaseConnection() ?? connection_default;
956
+ }
957
+ var repositoryConnection = new Proxy({}, {
958
+ get(_target, property) {
959
+ const connection = resolveRepositoryConnection();
960
+ const value = connection[property];
961
+ return typeof value === "function" ? value.bind(connection) : value;
962
+ }
963
+ });
964
+
965
+ // ../../src/core/database/whereBuilder.ts
966
+ class WhereBuilder {
967
+ nodes = [];
968
+ where(where) {
969
+ this.nodes.push({ kind: "and", where });
970
+ return this;
971
+ }
972
+ orWhere(where) {
973
+ this.nodes.push({ kind: "or", where });
974
+ return this;
975
+ }
976
+ whereGroup(fn) {
977
+ const nested = new WhereBuilder;
978
+ fn(nested);
979
+ if (nested.nodes.length > 0) {
980
+ this.nodes.push({ kind: "and", group: nested.nodes });
981
+ }
982
+ return this;
983
+ }
984
+ orWhereGroup(fn) {
985
+ const nested = new WhereBuilder;
986
+ fn(nested);
987
+ if (nested.nodes.length > 0) {
988
+ this.nodes.push({ kind: "or", group: nested.nodes });
989
+ }
990
+ return this;
991
+ }
992
+ }
993
+
994
+ // ../../src/core/database/repositoryQuery.ts
995
+ class RepositoryQuery {
996
+ repository;
997
+ whereClause;
998
+ queryOptions;
999
+ eagerLoads = [];
1000
+ whereNodes = [];
1001
+ constructor(repository, whereClause = {}, queryOptions = {}) {
1002
+ this.repository = repository;
1003
+ this.whereClause = whereClause;
1004
+ this.queryOptions = queryOptions;
1005
+ }
1006
+ where(input) {
1007
+ if (typeof input === "function") {
1008
+ const builder = new WhereBuilder;
1009
+ input(builder);
1010
+ this.whereNodes.push(...builder.nodes);
1011
+ return this;
1012
+ }
1013
+ this.whereClause = { ...this.whereClause, ...input };
1014
+ return this;
1015
+ }
1016
+ orWhere(input) {
1017
+ if (typeof input === "function") {
1018
+ const builder = new WhereBuilder;
1019
+ input(builder);
1020
+ if (builder.nodes.length > 0) {
1021
+ this.whereNodes.push({ kind: "or", group: builder.nodes });
1022
+ }
1023
+ return this;
1024
+ }
1025
+ this.whereNodes.push({ kind: "or", where: input });
1026
+ return this;
1027
+ }
1028
+ orderBy(orderBy) {
1029
+ this.queryOptions = { ...this.queryOptions, orderBy };
1030
+ return this;
1031
+ }
1032
+ limit(limit) {
1033
+ this.queryOptions = { ...this.queryOptions, limit };
1034
+ return this;
1035
+ }
1036
+ offset(offset) {
1037
+ this.queryOptions = { ...this.queryOptions, offset };
1038
+ return this;
1039
+ }
1040
+ join(left, right) {
1041
+ return this.addJoin("inner", left, right);
1042
+ }
1043
+ leftJoin(left, right) {
1044
+ return this.addJoin("left", left, right);
1045
+ }
1046
+ groupBy(groupBy) {
1047
+ this.queryOptions = { ...this.queryOptions, groupBy };
1048
+ return this;
1049
+ }
1050
+ having(having) {
1051
+ this.queryOptions = { ...this.queryOptions, having };
1052
+ return this;
1053
+ }
1054
+ withHasMany(as, relation, childRepository, options = {}) {
1055
+ this.eagerLoads.push({
1056
+ kind: "hasMany",
1057
+ as,
1058
+ relation,
1059
+ repository: childRepository,
1060
+ options
1061
+ });
1062
+ return this;
1063
+ }
1064
+ withBelongsTo(as, relation, parentRepository, options = {}) {
1065
+ this.eagerLoads.push({
1066
+ kind: "belongsTo",
1067
+ as,
1068
+ relation,
1069
+ repository: parentRepository,
1070
+ options
1071
+ });
1072
+ return this;
1073
+ }
1074
+ async get() {
1075
+ const rows = await this.repository.findAll(this.buildOptions());
1076
+ return await this.attach(rows);
1077
+ }
1078
+ async first() {
1079
+ const rows = await this.get();
1080
+ return rows[0] ?? null;
1081
+ }
1082
+ async paginate(options) {
1083
+ return await this.repository.paginate({
1084
+ ...this.buildOptions(),
1085
+ page: options.page,
1086
+ perPage: options.perPage
1087
+ });
1088
+ }
1089
+ buildOptions() {
1090
+ return {
1091
+ ...this.queryOptions,
1092
+ where: this.whereClause,
1093
+ whereNodes: this.whereNodes
1094
+ };
1095
+ }
1096
+ addJoin(type, left, right) {
1097
+ const leftRef = parseQualifiedColumn(left);
1098
+ const rightRef = parseQualifiedColumn(right);
1099
+ const table = type === "inner" ? rightRef.table : rightRef.table;
1100
+ const joins = this.queryOptions.joins ?? [];
1101
+ const existing = joins.find((join) => join.table === table && join.type === type);
1102
+ if (existing) {
1103
+ existing.on.push({ left: leftRef, right: rightRef });
1104
+ return this;
1105
+ }
1106
+ this.queryOptions = {
1107
+ ...this.queryOptions,
1108
+ joins: [
1109
+ ...joins,
1110
+ {
1111
+ type,
1112
+ table,
1113
+ on: [{ left: leftRef, right: rightRef }]
1114
+ }
1115
+ ]
1116
+ };
1117
+ return this;
1118
+ }
1119
+ async attach(rows) {
1120
+ if (rows.length === 0 || this.eagerLoads.length === 0) {
1121
+ return rows.map((row) => ({ ...row }));
1122
+ }
1123
+ let result = rows.map((row) => ({ ...row }));
1124
+ for (const load of this.eagerLoads) {
1125
+ if (load.kind === "hasMany") {
1126
+ const relation2 = load.relation;
1127
+ const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
1128
+ result = result.map((row) => ({
1129
+ ...row,
1130
+ [load.as]: grouped2.get(row[relation2.localKey]) ?? []
1131
+ }));
1132
+ continue;
1133
+ }
1134
+ const relation = load.relation;
1135
+ const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
1136
+ result = result.map((row) => ({
1137
+ ...row,
1138
+ [load.as]: grouped.get(row[relation.foreignKey])
1139
+ }));
1140
+ }
1141
+ return result;
1142
+ }
1143
+ }
1144
+
1145
+ // ../../src/core/database/baseRepository.ts
1146
+ class BaseRepository {
1147
+ table;
1148
+ connection;
1149
+ constructor(table, connection = repositoryConnection) {
1150
+ this.table = table;
1151
+ this.connection = connection;
1152
+ }
1153
+ async findAll(options = {}) {
1154
+ return await withDatabaseErrorHandling(async () => {
1155
+ const { whereNodes, ...queryOptions } = options;
1156
+ const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
1157
+ return await this.connection.unsafe(text, params);
1158
+ });
1159
+ }
1160
+ async paginate(options) {
1161
+ const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
1162
+ const total = await this.countWhere(where, {
1163
+ withTrashed: options.withTrashed,
1164
+ onlyTrashed: options.onlyTrashed,
1165
+ joins: options.joins,
1166
+ groupBy: options.groupBy
1167
+ }, whereNodes);
1168
+ const offset = (page - 1) * perPage;
1169
+ const data = await this.findAll({
1170
+ ...queryOptions,
1171
+ where,
1172
+ whereNodes,
1173
+ limit: perPage,
1174
+ offset
1175
+ });
1176
+ return {
1177
+ data,
1178
+ meta: buildPaginationMeta({ page, perPage, total })
1179
+ };
1180
+ }
1181
+ async chunk(count, callback, options = {}) {
1182
+ if (!Number.isInteger(count) || count <= 0) {
1183
+ throw new Error("Chunk size must be a positive integer.");
1184
+ }
1185
+ let offset = 0;
1186
+ while (true) {
1187
+ const rows = await this.findAll({
1188
+ ...options,
1189
+ limit: count,
1190
+ offset
1191
+ });
1192
+ if (rows.length === 0) {
1193
+ return;
1194
+ }
1195
+ const shouldContinue = await callback(rows);
1196
+ if (shouldContinue === false || rows.length < count) {
1197
+ return;
1198
+ }
1199
+ offset += count;
1200
+ }
1201
+ }
1202
+ async cursorPaginate(options) {
1203
+ const {
1204
+ perPage,
1205
+ cursor,
1206
+ cursorColumn = this.table.primaryKey,
1207
+ direction = "asc",
1208
+ where = {},
1209
+ whereNodes,
1210
+ ...queryOptions
1211
+ } = options;
1212
+ if (!Number.isInteger(perPage) || perPage <= 0) {
1213
+ throw new Error("Cursor page size must be a positive integer.");
1214
+ }
1215
+ const cursorWhere = { ...where };
1216
+ if (cursor !== undefined) {
1217
+ cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
1218
+ }
1219
+ const rows = await this.findAll({
1220
+ ...queryOptions,
1221
+ where: cursorWhere,
1222
+ whereNodes,
1223
+ orderBy: { [cursorColumn]: direction },
1224
+ limit: perPage + 1
1225
+ });
1226
+ const hasMore = rows.length > perPage;
1227
+ const data = hasMore ? rows.slice(0, perPage) : rows;
1228
+ const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
1229
+ const prevCursor = cursor ?? null;
1230
+ return {
1231
+ data,
1232
+ meta: {
1233
+ per_page: perPage,
1234
+ next_cursor: nextCursor,
1235
+ prev_cursor: prevCursor,
1236
+ has_more: hasMore
1237
+ }
1238
+ };
1239
+ }
1240
+ async findById(id) {
1241
+ return await this.firstOrNull({
1242
+ [this.table.primaryKey]: id
1243
+ });
1244
+ }
1245
+ async findByIdOrThrow(id, errorFactory) {
1246
+ const record = await this.findById(id);
1247
+ if (record) {
1248
+ return record;
1249
+ }
1250
+ throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
1251
+ }
1252
+ async findByIds(ids) {
1253
+ const uniqueIds = [...new Set(ids)];
1254
+ if (uniqueIds.length === 0) {
1255
+ return [];
1256
+ }
1257
+ return await this.findWhere({
1258
+ [this.table.primaryKey]: uniqueIds
1259
+ });
1260
+ }
1261
+ async firstOrNull(where, options = {}) {
1262
+ const [record] = await this.findAll({ ...options, where, limit: 1 });
1263
+ return record ?? null;
1264
+ }
1265
+ async create(values) {
1266
+ return await withDatabaseErrorHandling(async () => {
1267
+ const { text, params } = buildInsertQuery(this.table, values);
1268
+ const [record] = await this.connection.unsafe(text, params);
1269
+ if (!record) {
1270
+ throw new Error(`Insert into ${this.table.name} did not return a record.`);
1271
+ }
1272
+ const entity = record;
1273
+ await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
1274
+ return entity;
1275
+ });
1276
+ }
1277
+ async updateById(id, changes) {
1278
+ return await withDatabaseErrorHandling(async () => {
1279
+ const { text, params } = buildUpdateQuery(this.table, id, changes);
1280
+ const [record] = await this.connection.unsafe(text, params);
1281
+ const entity = record ?? null;
1282
+ if (entity) {
1283
+ await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
1284
+ }
1285
+ return entity;
1286
+ });
1287
+ }
1288
+ async updateByIdOrThrow(id, changes, errorFactory) {
1289
+ const record = await this.updateById(id, changes);
1290
+ if (record) {
1291
+ return record;
1292
+ }
1293
+ throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
1294
+ }
1295
+ async deleteById(id) {
1296
+ if (resolveSoftDeleteColumn(this.table)) {
1297
+ return await this.softDeleteById(id);
1298
+ }
1299
+ return await this.forceDeleteById(id);
1300
+ }
1301
+ async softDeleteById(id) {
1302
+ return await withDatabaseErrorHandling(async () => {
1303
+ const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
1304
+ const [record] = await this.connection.unsafe(text, params);
1305
+ if (!record) {
1306
+ return false;
1307
+ }
1308
+ await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
1309
+ return true;
1310
+ });
1311
+ }
1312
+ async forceDeleteById(id) {
1313
+ return await withDatabaseErrorHandling(async () => {
1314
+ const { text, params } = buildDeleteByIdQuery(this.table, id);
1315
+ const [row] = await this.connection.unsafe(text, params);
1316
+ if (!row) {
1317
+ return false;
1318
+ }
1319
+ await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
1320
+ id
1321
+ });
1322
+ return true;
1323
+ });
1324
+ }
1325
+ async restoreById(id) {
1326
+ return await withDatabaseErrorHandling(async () => {
1327
+ const { text, params } = buildRestoreByIdQuery(this.table, id);
1328
+ const [record] = await this.connection.unsafe(text, params);
1329
+ if (!record) {
1330
+ return null;
1331
+ }
1332
+ const entity = record;
1333
+ await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
1334
+ return entity;
1335
+ });
1336
+ }
1337
+ withConnection(connection) {
1338
+ const clone = Object.create(Object.getPrototypeOf(this));
1339
+ Object.assign(clone, this);
1340
+ clone.connection = connection;
1341
+ return clone;
1342
+ }
1343
+ getConnection() {
1344
+ return this.connection;
1345
+ }
1346
+ getTable() {
1347
+ return this.table;
1348
+ }
1349
+ query(where = {}) {
1350
+ return new RepositoryQuery(this, where);
1351
+ }
1352
+ async findWhere(where, options = {}) {
1353
+ return await this.findAll({ ...options, where });
1354
+ }
1355
+ async countWhere(where = {}, options = {}, whereNodes = []) {
1356
+ const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
1357
+ const [row] = await this.connection.unsafe(text, params);
1358
+ return Number(row?.count ?? 0);
1359
+ }
1360
+ async averageColumn(column, where = {}) {
1361
+ const qualifiedColumn = qualifyColumn(this.table.name, column);
1362
+ return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
1363
+ }
1364
+ async averageExpression(expression, alias, where = {}) {
1365
+ const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
1366
+ const [row] = await this.connection.unsafe(text, params);
1367
+ return Math.round(Number(row?.[alias] ?? 0));
1368
+ }
1369
+ async pluckNumberValues(expression, alias, options = {}) {
1370
+ const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
1371
+ const rows = await this.connection.unsafe(text, params);
1372
+ return rows.flatMap((row) => {
1373
+ const value = row[alias];
1374
+ return value === null || value === undefined ? [] : [Number(value)];
1375
+ });
1376
+ }
1377
+ async countGroupedBy(column, where = {}) {
1378
+ const { text, params } = buildGroupedCountQuery(this.table, column, where);
1379
+ const rows = await this.connection.unsafe(text, params);
1380
+ return rows.map(({ value, count }) => ({
1381
+ value,
1382
+ count: Number(count)
1383
+ }));
1384
+ }
1385
+ async findByHasManyRelation(relation, parentId, options = {}) {
1386
+ return await this.findWhere({
1387
+ [relation.foreignKey]: parentId
1388
+ }, options);
1389
+ }
1390
+ async loadHasManyForParents(parents, relation, options = {}) {
1391
+ if (parents.length === 0) {
1392
+ return indexHasManyRelation(parents, [], relation);
1393
+ }
1394
+ const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
1395
+ const children = await this.findWhere({
1396
+ [relation.foreignKey]: parentIds
1397
+ }, options);
1398
+ return indexHasManyRelation(parents, children, relation);
1399
+ }
1400
+ async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
1401
+ if (children.length === 0) {
1402
+ return new Map;
1403
+ }
1404
+ const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
1405
+ const parents = await parentRepository.withConnection(this.connection).findWhere({
1406
+ [relation.ownerKey]: ownerIds
1407
+ }, options);
1408
+ return indexBelongsToRelation(children, parents, relation);
1409
+ }
1410
+ }
1411
+ var baseRepository_default = BaseRepository;
1412
+ // ../../src/core/database/connection.ts
1413
+ function createDatabaseConnection2(source) {
1414
+ return {
1415
+ async unsafe(query, params = []) {
1416
+ return await source.unsafe(query, params);
1417
+ }
1418
+ };
1419
+ }
1420
+ // ../../src/core/database/model.ts
1421
+ var modelRepositories = new WeakMap;
1422
+ var modelGlobalScopes = new WeakMap;
1423
+ var modelBooted = new WeakSet;
1424
+ function resolveModelRepository(model) {
1425
+ const repository = modelRepositories.get(model);
1426
+ if (!repository) {
1427
+ throw new Error(`${model.name}.repository() is not implemented.`);
1428
+ }
1429
+ return repository;
1430
+ }
1431
+ function modelStatics(model) {
1432
+ return model;
1433
+ }
1434
+ function ensureBooted(model) {
1435
+ if (modelBooted.has(model)) {
1436
+ return;
1437
+ }
1438
+ modelBooted.add(model);
1439
+ const boot = model.boot;
1440
+ if (typeof boot === "function") {
1441
+ boot.call(model);
1442
+ }
1443
+ }
1444
+ function getGlobalScopes(model) {
1445
+ return modelGlobalScopes.get(model) ?? [];
1446
+ }
1447
+ function hydrateValue(value, cast) {
1448
+ if (value === null || value === undefined) {
1449
+ return value;
1450
+ }
1451
+ switch (cast) {
1452
+ case "date":
1453
+ case "datetime":
1454
+ return value instanceof Date ? value : new Date(String(value));
1455
+ case "json":
1456
+ return typeof value === "string" ? JSON.parse(value) : value;
1457
+ case "bool":
1458
+ case "boolean":
1459
+ return value === true || value === 1 || value === "1" || value === "true";
1460
+ default:
1461
+ return value;
1462
+ }
1463
+ }
1464
+ function dehydrateValue(value, cast) {
1465
+ if (value === null || value === undefined) {
1466
+ return value;
1467
+ }
1468
+ switch (cast) {
1469
+ case "date":
1470
+ case "datetime":
1471
+ return value instanceof Date ? value : new Date(String(value));
1472
+ case "json":
1473
+ return typeof value === "string" ? value : JSON.stringify(value);
1474
+ case "bool":
1475
+ case "boolean":
1476
+ return Boolean(value);
1477
+ default:
1478
+ return value;
1479
+ }
1480
+ }
1481
+ function filterMassAssignable(fillable, guarded, input) {
1482
+ const resolvedGuarded = guarded ?? true;
1483
+ if (fillable && fillable.length > 0) {
1484
+ const allowed = new Set(fillable);
1485
+ return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
1486
+ }
1487
+ if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
1488
+ return {};
1489
+ }
1490
+ const blocked = new Set(resolvedGuarded);
1491
+ return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
1492
+ }
1493
+ function applyCasts(values, casts, direction) {
1494
+ if (Object.keys(casts).length === 0) {
1495
+ return values;
1496
+ }
1497
+ const result = { ...values };
1498
+ const castFn = direction === "hydrate" ? hydrateValue : dehydrateValue;
1499
+ for (const [key, cast] of Object.entries(casts)) {
1500
+ if (key in result && cast) {
1501
+ result[key] = castFn(result[key], cast);
1502
+ }
1503
+ }
1504
+ return result;
1505
+ }
1506
+ function applyTimestampsOnCreate(columns, values, enabled) {
1507
+ if (!enabled) {
1508
+ return values;
1509
+ }
1510
+ const now = new Date;
1511
+ const result = { ...values };
1512
+ if (columns.includes("created_at")) {
1513
+ result.created_at = now;
1514
+ }
1515
+ if (columns.includes("updated_at")) {
1516
+ result.updated_at = now;
1517
+ }
1518
+ return result;
1519
+ }
1520
+ function applyTimestampsOnUpdate(columns, values, enabled) {
1521
+ if (!enabled) {
1522
+ return values;
1523
+ }
1524
+ const result = { ...values };
1525
+ if (columns.includes("updated_at")) {
1526
+ result.updated_at = new Date;
1527
+ }
1528
+ return result;
1529
+ }
1530
+
1531
+ class Model {
1532
+ attributes;
1533
+ repository;
1534
+ static $fillable;
1535
+ static $guarded;
1536
+ static $casts = {};
1537
+ static $timestamps = true;
1538
+ _exists;
1539
+ constructor(attributes, repository, exists = true) {
1540
+ this.attributes = attributes;
1541
+ this.repository = repository;
1542
+ this._exists = exists;
1543
+ }
1544
+ get $exists() {
1545
+ return this._exists;
1546
+ }
1547
+ get(key) {
1548
+ return this.attributes[key];
1549
+ }
1550
+ get id() {
1551
+ return this.attributes[this.primaryKey()];
1552
+ }
1553
+ toObject() {
1554
+ return { ...this.attributes };
1555
+ }
1556
+ primaryKey() {
1557
+ throw new Error(`${this.constructor.name}.primaryKey() is not implemented.`);
1558
+ }
1559
+ static primaryKeyField() {
1560
+ return resolveModelRepository(Model).getTable().primaryKey;
1561
+ }
1562
+ static hydrateAttributes(attributes) {
1563
+ const casts = Model.$casts ?? {};
1564
+ return applyCasts(attributes, casts, "hydrate");
1565
+ }
1566
+ static dehydrateAttributes(attributes) {
1567
+ const casts = Model.$casts ?? {};
1568
+ return applyCasts(attributes, casts, "dehydrate");
1569
+ }
1570
+ static fromRecord(record, repository, exists = true) {
1571
+ const hydrated = Model.hydrateAttributes(record);
1572
+ return new Model(hydrated, repository, exists);
1573
+ }
1574
+ static boot() {}
1575
+ static addGlobalScope(_name, scope) {
1576
+ ensureBooted(Model);
1577
+ const existing = modelGlobalScopes.get(Model) ?? [];
1578
+ modelGlobalScopes.set(Model, [
1579
+ ...existing,
1580
+ scope
1581
+ ]);
1582
+ }
1583
+ static repository() {
1584
+ return resolveModelRepository(this);
1585
+ }
1586
+ static query() {
1587
+ ensureBooted(this);
1588
+ const repository = resolveModelRepository(Model);
1589
+ let query = repository.query();
1590
+ for (const scope of getGlobalScopes(Model)) {
1591
+ query = scope(query);
1592
+ }
1593
+ return query;
1594
+ }
1595
+ static async create(attributes) {
1596
+ const statics = modelStatics(this);
1597
+ ensureBooted(Model);
1598
+ const repository = resolveModelRepository(Model);
1599
+ const table = repository.getTable();
1600
+ const timestamps = statics.$timestamps ?? true;
1601
+ const assignable = filterMassAssignable(statics.$fillable, statics.$guarded, attributes);
1602
+ const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
1603
+ const payload = statics.dehydrateAttributes(withTimestamps);
1604
+ const record = await repository.create(payload);
1605
+ return statics.fromRecord(record, repository, true);
1606
+ }
1607
+ static async find(id) {
1608
+ const statics = modelStatics(this);
1609
+ const repository = resolveModelRepository(Model);
1610
+ const primaryKey = statics.primaryKeyField();
1611
+ const record = await Model.query.call(Model).where({ [primaryKey]: id }).first();
1612
+ return record ? statics.fromRecord(record, repository, true) : null;
1613
+ }
1614
+ static async findOrFail(id, errorFactory) {
1615
+ const model = await Model.find.call(Model, id);
1616
+ if (model) {
1617
+ return model;
1618
+ }
1619
+ throw errorFactory?.(id) ?? new NotFoundError(`${Model.name} ${String(id)} not found.`);
1620
+ }
1621
+ static async all(options = {}) {
1622
+ const statics = modelStatics(this);
1623
+ const repository = resolveModelRepository(Model);
1624
+ let query = Model.query.call(Model);
1625
+ if (options.orderBy) {
1626
+ query = query.orderBy(options.orderBy);
1627
+ }
1628
+ if (options.limit !== undefined) {
1629
+ query = query.limit(options.limit);
1630
+ }
1631
+ const rows = await query.get();
1632
+ return rows.map((row) => statics.fromRecord(row, repository, true));
1633
+ }
1634
+ static async firstWhere(where, options = {}) {
1635
+ const statics = modelStatics(this);
1636
+ const repository = resolveModelRepository(Model);
1637
+ let query = Model.query.call(Model).where(where);
1638
+ if (options.orderBy) {
1639
+ query = query.orderBy(options.orderBy);
1640
+ }
1641
+ const record = await query.first();
1642
+ return record ? statics.fromRecord(record, repository, true) : null;
1643
+ }
1644
+ async save() {
1645
+ const ModelClass = modelStatics(this.constructor);
1646
+ const timestamps = ModelClass.$timestamps ?? true;
1647
+ const casts = ModelClass.$casts ?? {};
1648
+ const table = this.repository.getTable();
1649
+ if (this.$exists) {
1650
+ const changes = applyTimestampsOnUpdate(table.columns, applyCasts(this.attributes, casts, "dehydrate"), timestamps);
1651
+ const record2 = await this.repository.updateByIdOrThrow(this.id, changes);
1652
+ this.attributes = ModelClass.hydrateAttributes(record2);
1653
+ return this;
1654
+ }
1655
+ const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, this.attributes);
1656
+ const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
1657
+ const payload = ModelClass.dehydrateAttributes(withTimestamps);
1658
+ const record = await this.repository.create(payload);
1659
+ this.attributes = ModelClass.hydrateAttributes(record);
1660
+ this._exists = true;
1661
+ return this;
1662
+ }
1663
+ async update(changes) {
1664
+ const ModelClass = modelStatics(this.constructor);
1665
+ const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
1666
+ Object.assign(this.attributes, assignable);
1667
+ return await this.save();
1668
+ }
1669
+ async delete() {
1670
+ if (resolveSoftDeleteColumn(this.repository.getTable())) {
1671
+ return await this.repository.deleteById(this.id);
1672
+ }
1673
+ return await this.repository.forceDeleteById(this.id);
1674
+ }
1675
+ async forceDelete() {
1676
+ return await this.repository.forceDeleteById(this.id);
1677
+ }
1678
+ async restore() {
1679
+ const ModelClass = modelStatics(this.constructor);
1680
+ const record = await this.repository.restoreById(this.id);
1681
+ if (!record) {
1682
+ return null;
1683
+ }
1684
+ this.attributes = ModelClass.hydrateAttributes(record);
1685
+ return this;
1686
+ }
1687
+ async loadHasMany(as, relation, childRepository, options = {}) {
1688
+ const grouped = await childRepository.withConnection(this.repository.getConnection()).loadHasManyForParents([this.attributes], relation, options);
1689
+ const loaded = grouped.get(this.attributes[relation.localKey]) ?? [];
1690
+ return Object.assign(this, { [as]: loaded });
1691
+ }
1692
+ async loadHasOne(as, relation, childRepository, options = {}) {
1693
+ const loaded = await this.loadHasMany(as, relation, childRepository, { ...options, limit: 1 });
1694
+ const value = loaded[as]?.[0];
1695
+ return Object.assign(this, { [as]: value });
1696
+ }
1697
+ async loadBelongsTo(as, relation, parentRepository, options = {}) {
1698
+ const grouped = await this.repository.loadBelongsToForParents([this.attributes], relation, parentRepository, options);
1699
+ const loaded = grouped.get(this.attributes[relation.foreignKey]);
1700
+ return Object.assign(this, { [as]: loaded });
1701
+ }
1702
+ async loadBelongsToMany(as, relation, relatedRepository, options = {}) {
1703
+ const connection = this.repository.getConnection();
1704
+ const parentId = this.attributes[relation.parentKey];
1705
+ const pivotRows = await connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} = $1`, [parentId]);
1706
+ if (pivotRows.length === 0) {
1707
+ return Object.assign(this, { [as]: [] });
1708
+ }
1709
+ const relatedIds = [
1710
+ ...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
1711
+ ];
1712
+ const relatedRows = await relatedRepository.withConnection(connection).findAll({
1713
+ ...options,
1714
+ where: {
1715
+ [relation.relatedKey]: relatedIds
1716
+ }
1717
+ });
1718
+ const grouped = indexBelongsToManyRelation([this.attributes], pivotRows, relatedRows, relation);
1719
+ const loaded = grouped.get(parentId) ?? [];
1720
+ return Object.assign(this, { [as]: loaded });
1721
+ }
1722
+ mergeAttributes(patch) {
1723
+ Object.assign(this.attributes, patch);
1724
+ return this;
1725
+ }
1726
+ }
1727
+ function registerModelRepository(model, repository) {
1728
+ modelRepositories.set(model, repository);
1729
+ ensureBooted(model);
1730
+ return model;
1731
+ }
1732
+ // ../../src/core/database/schema/columnDefinition.ts
1733
+ class ColumnDefinition {
1734
+ name;
1735
+ kind;
1736
+ length;
1737
+ isNullable = false;
1738
+ isPrimary = false;
1739
+ isUnique = false;
1740
+ autoIncrement = false;
1741
+ defaultValue;
1742
+ checkExpression;
1743
+ foreignKey;
1744
+ constructor(name, kind) {
1745
+ this.name = name;
1746
+ this.kind = kind;
1747
+ }
1748
+ nullable() {
1749
+ this.isNullable = true;
1750
+ return this;
1751
+ }
1752
+ notNullable() {
1753
+ this.isNullable = false;
1754
+ return this;
1755
+ }
1756
+ default(value) {
1757
+ if (typeof value === "boolean") {
1758
+ this.defaultValue = value ? "TRUE" : "FALSE";
1759
+ return this;
1760
+ }
1761
+ if (typeof value === "number") {
1762
+ this.defaultValue = String(value);
1763
+ return this;
1764
+ }
1765
+ this.defaultValue = `'${value.replace(/'/g, "''")}'`;
1766
+ return this;
1767
+ }
1768
+ defaultRaw(expression) {
1769
+ this.defaultValue = expression;
1770
+ return this;
1771
+ }
1772
+ unique() {
1773
+ this.isUnique = true;
1774
+ return this;
1775
+ }
1776
+ primary() {
1777
+ this.isPrimary = true;
1778
+ return this;
1779
+ }
1780
+ check(expression) {
1781
+ this.checkExpression = expression;
1782
+ return this;
1783
+ }
1784
+ }
1785
+
1786
+ class ForeignIdColumnDefinition extends ColumnDefinition {
1787
+ constructor(name) {
1788
+ super(name, "foreignId");
1789
+ this.notNullable();
1790
+ }
1791
+ references(table, column = "id") {
1792
+ this.foreignKey = {
1793
+ referencesTable: table,
1794
+ referencesColumn: column
1795
+ };
1796
+ return this;
1797
+ }
1798
+ constrained(table) {
1799
+ const referencesTable = table ?? inferReferencedTable(this.name);
1800
+ return this.references(referencesTable);
1801
+ }
1802
+ cascadeOnDelete() {
1803
+ if (!this.foreignKey) {
1804
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
1805
+ }
1806
+ this.foreignKey.onDelete = "cascade";
1807
+ return this;
1808
+ }
1809
+ nullOnDelete() {
1810
+ if (!this.foreignKey) {
1811
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
1812
+ }
1813
+ this.foreignKey.onDelete = "set null";
1814
+ return this;
1815
+ }
1816
+ }
1817
+ function inferReferencedTable(columnName) {
1818
+ if (!columnName.endsWith("_id")) {
1819
+ throw new Error(`Cannot infer referenced table from column ${columnName}`);
1820
+ }
1821
+ return columnName.slice(0, -3);
1822
+ }
1823
+
1824
+ // ../../src/core/database/schema/blueprint.ts
1825
+ class Blueprint {
1826
+ table;
1827
+ action;
1828
+ columns = [];
1829
+ indexes = [];
1830
+ droppedColumns = [];
1831
+ droppedIndexes = [];
1832
+ constructor(table, action) {
1833
+ this.table = table;
1834
+ this.action = action;
1835
+ }
1836
+ id(name = "id") {
1837
+ const column = new ColumnDefinition(name, "id");
1838
+ column.primary();
1839
+ column.autoIncrement = true;
1840
+ this.columns.push(column);
1841
+ return column;
1842
+ }
1843
+ string(name, length) {
1844
+ const column = new ColumnDefinition(name, "string");
1845
+ column.length = length;
1846
+ column.notNullable();
1847
+ this.columns.push(column);
1848
+ return column;
1849
+ }
1850
+ text(name) {
1851
+ const column = new ColumnDefinition(name, "text");
1852
+ column.notNullable();
1853
+ this.columns.push(column);
1854
+ return column;
1855
+ }
1856
+ boolean(name) {
1857
+ const column = new ColumnDefinition(name, "boolean");
1858
+ column.notNullable();
1859
+ this.columns.push(column);
1860
+ return column;
1861
+ }
1862
+ integer(name) {
1863
+ const column = new ColumnDefinition(name, "integer");
1864
+ column.notNullable();
1865
+ this.columns.push(column);
1866
+ return column;
1867
+ }
1868
+ bigInteger(name) {
1869
+ const column = new ColumnDefinition(name, "bigInteger");
1870
+ column.notNullable();
1871
+ this.columns.push(column);
1872
+ return column;
1873
+ }
1874
+ timestamp(name) {
1875
+ const column = new ColumnDefinition(name, "timestamp");
1876
+ column.notNullable();
1877
+ this.columns.push(column);
1878
+ return column;
1879
+ }
1880
+ json(name) {
1881
+ const column = new ColumnDefinition(name, "json");
1882
+ column.notNullable();
1883
+ this.columns.push(column);
1884
+ return column;
1885
+ }
1886
+ jsonb(name) {
1887
+ const column = new ColumnDefinition(name, "jsonb");
1888
+ column.notNullable();
1889
+ this.columns.push(column);
1890
+ return column;
1891
+ }
1892
+ foreignId(name) {
1893
+ const column = new ForeignIdColumnDefinition(name);
1894
+ this.columns.push(column);
1895
+ return column;
1896
+ }
1897
+ timestamps() {
1898
+ this.timestamp("created_at").defaultRaw("NOW()");
1899
+ this.timestamp("updated_at").defaultRaw("NOW()");
1900
+ }
1901
+ softDeletes() {
1902
+ this.timestamp("deleted_at").nullable();
1903
+ }
1904
+ dropColumn(name) {
1905
+ this.droppedColumns.push(name);
1906
+ }
1907
+ dropSoftDeletes() {
1908
+ this.dropColumn("deleted_at");
1909
+ this.dropIndex(`idx_${this.table}_deleted_at`);
1910
+ }
1911
+ dropIndex(name) {
1912
+ this.droppedIndexes.push(name);
1913
+ }
1914
+ unique(columns, name) {
1915
+ this.indexes.push({
1916
+ name,
1917
+ columns: Array.isArray(columns) ? columns : [columns],
1918
+ kind: "unique"
1919
+ });
1920
+ }
1921
+ index(columns, options = {}) {
1922
+ this.indexes.push({
1923
+ name: options.name,
1924
+ columns: Array.isArray(columns) ? columns : [columns],
1925
+ kind: "index",
1926
+ order: options.order
1927
+ });
1928
+ }
1929
+ partialIndex(columns, where, nameOrOptions) {
1930
+ const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
1931
+ this.indexes.push({
1932
+ name: options.name,
1933
+ columns: Array.isArray(columns) ? columns : [columns],
1934
+ kind: options.unique ? "uniquePartial" : "partial",
1935
+ where
1936
+ });
1937
+ }
1938
+ fullText(columns, name) {
1939
+ this.indexes.push({
1940
+ name,
1941
+ columns: Array.isArray(columns) ? columns : [columns],
1942
+ kind: "fullText"
1943
+ });
1944
+ }
1945
+ ginIndex(column, name) {
1946
+ this.indexes.push({
1947
+ name,
1948
+ columns: [column],
1949
+ kind: "gin"
1950
+ });
1951
+ }
1952
+ }
1953
+ // ../../src/core/database/schema/driver.ts
1954
+ function normalizeConnectionName(connection) {
1955
+ const normalized = connection.trim().toLowerCase();
1956
+ if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
1957
+ return "pgsql";
1958
+ }
1959
+ if (normalized === "mysql" || normalized === "mariadb") {
1960
+ return "mysql";
1961
+ }
1962
+ if (normalized === "sqlite") {
1963
+ return "sqlite";
1964
+ }
1965
+ throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
1966
+ }
1967
+ function resolveDriverFromUrl(url) {
1968
+ const normalized = url.trim().toLowerCase();
1969
+ if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
1970
+ return "pgsql";
1971
+ }
1972
+ if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
1973
+ return "mysql";
1974
+ }
1975
+ if (normalized.startsWith("sqlite:")) {
1976
+ return "sqlite";
1977
+ }
1978
+ return null;
1979
+ }
1980
+ function resolveDatabaseDriver(options = {}) {
1981
+ const connection = options.connection ?? process.env.DB_CONNECTION;
1982
+ if (connection) {
1983
+ return normalizeConnectionName(connection);
1984
+ }
1985
+ const url = options.url ?? process.env.DATABASE_URL ?? "";
1986
+ const fromUrl = resolveDriverFromUrl(url);
1987
+ if (fromUrl) {
1988
+ return fromUrl;
1989
+ }
1990
+ return "pgsql";
1991
+ }
1992
+ // ../../src/core/database/schema/errors.ts
1993
+ class UnsupportedSchemaFeatureError extends Error {
1994
+ constructor(feature, driver) {
1995
+ super(`${feature} is not supported for the ${driver} driver`);
1996
+ this.name = "UnsupportedSchemaFeatureError";
1997
+ }
1998
+ }
1999
+ // ../../src/core/database/schema/grammars/grammar.ts
2000
+ function compileColumnType(driver, column) {
2001
+ switch (column.kind) {
2002
+ case "id":
2003
+ return compileIdType(driver);
2004
+ case "string":
2005
+ return compileStringType(driver, column.length);
2006
+ case "text":
2007
+ return compileTextType(driver);
2008
+ case "boolean":
2009
+ return compileBooleanType(driver);
2010
+ case "integer":
2011
+ case "foreignId":
2012
+ return compileIntegerType(driver);
2013
+ case "bigInteger":
2014
+ return compileBigIntegerType(driver);
2015
+ case "timestamp":
2016
+ return compileTimestampType(driver);
2017
+ case "json":
2018
+ return compileJsonType(driver);
2019
+ case "jsonb":
2020
+ return compileJsonbType(driver);
2021
+ default:
2022
+ throw new Error(`Unsupported column kind: ${column.kind}`);
2023
+ }
2024
+ }
2025
+ function compileIdType(driver) {
2026
+ switch (driver) {
2027
+ case "pgsql":
2028
+ return "SERIAL";
2029
+ case "mysql":
2030
+ return "BIGINT UNSIGNED";
2031
+ case "sqlite":
2032
+ return "INTEGER";
2033
+ }
2034
+ }
2035
+ function compileStringType(driver, length) {
2036
+ switch (driver) {
2037
+ case "pgsql":
2038
+ return "TEXT";
2039
+ case "mysql":
2040
+ return length ? `VARCHAR(${length})` : "VARCHAR(255)";
2041
+ case "sqlite":
2042
+ return "TEXT";
2043
+ }
2044
+ }
2045
+ function compileTextType(driver) {
2046
+ switch (driver) {
2047
+ case "pgsql":
2048
+ case "sqlite":
2049
+ return "TEXT";
2050
+ case "mysql":
2051
+ return "TEXT";
2052
+ }
2053
+ }
2054
+ function compileBooleanType(driver) {
2055
+ switch (driver) {
2056
+ case "pgsql":
2057
+ return "BOOLEAN";
2058
+ case "mysql":
2059
+ return "BOOLEAN";
2060
+ case "sqlite":
2061
+ return "INTEGER";
2062
+ }
2063
+ }
2064
+ function compileIntegerType(driver) {
2065
+ switch (driver) {
2066
+ case "pgsql":
2067
+ return "INTEGER";
2068
+ case "mysql":
2069
+ return "INT";
2070
+ case "sqlite":
2071
+ return "INTEGER";
2072
+ }
2073
+ }
2074
+ function compileBigIntegerType(driver) {
2075
+ switch (driver) {
2076
+ case "pgsql":
2077
+ return "BIGINT";
2078
+ case "mysql":
2079
+ return "BIGINT";
2080
+ case "sqlite":
2081
+ return "INTEGER";
2082
+ }
2083
+ }
2084
+ function compileTimestampType(driver) {
2085
+ switch (driver) {
2086
+ case "pgsql":
2087
+ return "TIMESTAMPTZ";
2088
+ case "mysql":
2089
+ return "TIMESTAMP";
2090
+ case "sqlite":
2091
+ return "TEXT";
2092
+ }
2093
+ }
2094
+ function compileJsonType(driver) {
2095
+ switch (driver) {
2096
+ case "pgsql":
2097
+ return "JSONB";
2098
+ case "mysql":
2099
+ return "JSON";
2100
+ case "sqlite":
2101
+ return "TEXT";
2102
+ }
2103
+ }
2104
+ function compileJsonbType(driver) {
2105
+ switch (driver) {
2106
+ case "pgsql":
2107
+ return "JSONB";
2108
+ case "mysql":
2109
+ return "JSON";
2110
+ case "sqlite":
2111
+ return "TEXT";
2112
+ }
2113
+ }
2114
+
2115
+ // ../../src/core/database/schema/grammars/compileStatements.ts
2116
+ function compileCreateTable(driver, blueprint) {
2117
+ const table = quoteIdentifier(blueprint.table);
2118
+ const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
2119
+ for (const index of blueprint.indexes) {
2120
+ if (index.kind === "unique" && index.columns.length > 1) {
2121
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2122
+ parts.push(`UNIQUE (${columns})`);
2123
+ }
2124
+ }
2125
+ const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
2126
+ ${parts.join(`,
2127
+ `)}
2128
+ )`];
2129
+ for (const index of blueprint.indexes) {
2130
+ if (index.kind === "unique" && index.columns.length === 1) {
2131
+ continue;
2132
+ }
2133
+ if (index.kind === "index") {
2134
+ statements.push(compileIndex(driver, blueprint.table, index));
2135
+ } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
2136
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2137
+ }
2138
+ }
2139
+ return statements;
2140
+ }
2141
+ function compileAlterTable(driver, blueprint) {
2142
+ const statements = [];
2143
+ const table = quoteIdentifier(blueprint.table);
2144
+ for (const column of blueprint.columns) {
2145
+ const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
2146
+ statements.push(`ALTER TABLE ${table}
2147
+ ${addPrefix} ${compileColumn(driver, column, "alter")}`);
2148
+ }
2149
+ for (const columnName of blueprint.droppedColumns) {
2150
+ const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
2151
+ statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
2152
+ }
2153
+ for (const indexName of blueprint.droppedIndexes) {
2154
+ statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
2155
+ }
2156
+ for (const index of blueprint.indexes) {
2157
+ if (index.kind === "index" || index.kind === "unique") {
2158
+ statements.push(compileIndex(driver, blueprint.table, index));
2159
+ } else {
2160
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2161
+ }
2162
+ }
2163
+ return statements;
2164
+ }
2165
+ function compileDropTable(driver, tableName) {
2166
+ const cascade = driver === "pgsql" ? " CASCADE" : "";
2167
+ return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
2168
+ }
2169
+ function compileColumn(driver, column, mode) {
2170
+ const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
2171
+ if (column.autoIncrement && driver === "mysql") {
2172
+ parts[1] = `${parts[1]} AUTO_INCREMENT`;
2173
+ }
2174
+ if (column.isPrimary && mode === "create") {
2175
+ if (driver === "sqlite") {
2176
+ parts.push("PRIMARY KEY AUTOINCREMENT");
2177
+ } else {
2178
+ parts.push("PRIMARY KEY");
2179
+ }
2180
+ } else if (!column.isNullable) {
2181
+ parts.push("NOT NULL");
2182
+ } else if (column.isNullable) {
2183
+ parts.push("NULL");
2184
+ }
2185
+ if (column.defaultValue !== undefined) {
2186
+ parts.push(`DEFAULT ${column.defaultValue}`);
2187
+ }
2188
+ if (column.isUnique) {
2189
+ parts.push("UNIQUE");
2190
+ }
2191
+ if (column.checkExpression) {
2192
+ parts.push(`CHECK (${column.checkExpression})`);
2193
+ }
2194
+ if (column.foreignKey) {
2195
+ const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
2196
+ const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
2197
+ let clause = `REFERENCES ${reference}`;
2198
+ if (onDelete === "cascade") {
2199
+ clause += " ON DELETE CASCADE";
2200
+ } else if (onDelete === "set null") {
2201
+ clause += " ON DELETE SET NULL";
2202
+ }
2203
+ parts.push(clause);
2204
+ }
2205
+ return parts.join(" ");
2206
+ }
2207
+ function compileIndex(_driver, tableName, index) {
2208
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
2209
+ const columns = index.columns.map((column) => {
2210
+ const quoted = quoteIdentifier(column);
2211
+ if (index.order === "desc") {
2212
+ return `${quoted} DESC`;
2213
+ }
2214
+ return quoted;
2215
+ }).join(", ");
2216
+ const unique = index.kind === "unique" ? "UNIQUE " : "";
2217
+ return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
2218
+ }
2219
+ function compileSpecialIndex(driver, tableName, index) {
2220
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
2221
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2222
+ switch (index.kind) {
2223
+ case "partial":
2224
+ case "uniquePartial": {
2225
+ if (driver !== "pgsql") {
2226
+ throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
2227
+ }
2228
+ const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
2229
+ return [
2230
+ `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
2231
+ ];
2232
+ }
2233
+ case "gin": {
2234
+ if (driver !== "pgsql") {
2235
+ throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
2236
+ }
2237
+ return [
2238
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
2239
+ ];
2240
+ }
2241
+ case "fullText": {
2242
+ if (driver === "mysql") {
2243
+ return [
2244
+ `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
2245
+ ];
2246
+ }
2247
+ if (driver === "pgsql") {
2248
+ throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
2249
+ }
2250
+ throw new UnsupportedSchemaFeatureError("fullText()", driver);
2251
+ }
2252
+ default:
2253
+ return [];
2254
+ }
2255
+ }
2256
+ function defaultIndexName(tableName, columns, kind) {
2257
+ return `idx_${tableName}_${columns.join("_")}_${kind}`;
2258
+ }
2259
+ function compileBlueprint(driver, blueprint) {
2260
+ switch (blueprint.action) {
2261
+ case "create":
2262
+ return compileCreateTable(driver, blueprint);
2263
+ case "alter":
2264
+ return compileAlterTable(driver, blueprint);
2265
+ case "drop":
2266
+ return compileDropTable(driver, blueprint.table);
2267
+ default:
2268
+ throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
2269
+ }
2270
+ }
2271
+ // ../../src/core/database/schema/grammars/createGrammar.ts
2272
+ function createGrammar(driver) {
2273
+ return {
2274
+ driver,
2275
+ compile(blueprint) {
2276
+ return compileBlueprint(driver, blueprint);
2277
+ }
2278
+ };
2279
+ }
2280
+
2281
+ // ../../src/core/database/schema/grammars/mysqlGrammar.ts
2282
+ var MySqlGrammar = createGrammar("mysql");
2283
+
2284
+ // ../../src/core/database/schema/grammars/postgresGrammar.ts
2285
+ var PostgresGrammar = createGrammar("pgsql");
2286
+
2287
+ // ../../src/core/database/schema/grammars/sqliteGrammar.ts
2288
+ var SqliteGrammar = createGrammar("sqlite");
2289
+
2290
+ // ../../src/core/database/schema/grammars/index.ts
2291
+ function grammarForDriver(driver) {
2292
+ switch (driver) {
2293
+ case "pgsql":
2294
+ return PostgresGrammar;
2295
+ case "mysql":
2296
+ return MySqlGrammar;
2297
+ case "sqlite":
2298
+ return SqliteGrammar;
2299
+ default:
2300
+ throw new Error(`Unsupported database driver: ${driver}`);
2301
+ }
2302
+ }
2303
+ // ../../src/core/database/schema/schema.ts
2304
+ class SchemaBuilder {
2305
+ #driver;
2306
+ #statements = [];
2307
+ constructor(driver) {
2308
+ this.#driver = driver;
2309
+ }
2310
+ create(table, callback) {
2311
+ const blueprint = new Blueprint(table, "create");
2312
+ callback(blueprint);
2313
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2314
+ return this;
2315
+ }
2316
+ table(table, callback) {
2317
+ const blueprint = new Blueprint(table, "alter");
2318
+ callback(blueprint);
2319
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2320
+ return this;
2321
+ }
2322
+ drop(table) {
2323
+ const blueprint = new Blueprint(table, "drop");
2324
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2325
+ return this;
2326
+ }
2327
+ toSql() {
2328
+ return [...this.#statements];
2329
+ }
2330
+ async execute(db2) {
2331
+ for (const statement of this.#statements) {
2332
+ await db2.unsafe(statement);
2333
+ }
2334
+ }
2335
+ }
2336
+
2337
+ class Schema {
2338
+ static builder(driver) {
2339
+ return new SchemaBuilder(driver ?? resolveDatabaseDriver());
2340
+ }
2341
+ static async run(db2, driver, callback) {
2342
+ const schema = Schema.builder(driver);
2343
+ await callback(schema);
2344
+ await schema.execute(db2);
2345
+ }
2346
+ }
2347
+ function createSchemaBuilder(db2, driver) {
2348
+ const builder = Schema.builder(driver);
2349
+ return Object.assign(builder, {
2350
+ async commit() {
2351
+ await builder.execute(db2);
2352
+ }
2353
+ });
2354
+ }
2355
+ // ../../src/core/database/table.ts
2356
+ function defineTable(definition) {
2357
+ return definition;
2358
+ }
2359
+ // ../../src/core/database/transaction.ts
2360
+ async function runInTransaction(operation) {
2361
+ return await connection_default.begin(async (transaction) => {
2362
+ return await operation(createDatabaseConnection2(transaction));
2363
+ });
2364
+ }
2365
+ // ../../src/modules/user/apiTokenTable.ts
2366
+ var apiTokenTable = defineTable({
2367
+ name: "api_token",
2368
+ primaryKey: "id",
2369
+ columns: [
2370
+ "id",
2371
+ "user_id",
2372
+ "name",
2373
+ "token_hash",
2374
+ "abilities",
2375
+ "last_used_at",
2376
+ "expires_at",
2377
+ "created_at"
2378
+ ],
2379
+ defaultOrderBy: { column: "id", direction: "ASC" }
2380
+ });
2381
+
2382
+ // ../../src/core/auth/password.ts
2383
+ async function hashPassword(password) {
2384
+ return await Bun.password.hash(password, {
2385
+ algorithm: "bcrypt",
2386
+ cost: 10
2387
+ });
2388
+ }
2389
+ async function verifyPassword(password, passwordHash) {
2390
+ return await Bun.password.verify(password, passwordHash);
2391
+ }
2392
+
2393
+ // ../../src/core/crypto/fieldEncryption.ts
2394
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from "crypto";
2395
+ var ENCRYPTION_PREFIX = "enc:v1:";
2396
+ var IV_LENGTH = 12;
2397
+ var TAG_LENGTH = 16;
2398
+ function resolveEncryptionKey() {
2399
+ const raw = process.env.KMS_ENCRYPTION_KEY?.trim();
2400
+ if (!raw) {
2401
+ return null;
2402
+ }
2403
+ if (/^[0-9a-f]{64}$/i.test(raw)) {
2404
+ return Buffer.from(raw, "hex");
2405
+ }
2406
+ const decoded = Buffer.from(raw, "base64");
2407
+ if (decoded.length === 32) {
2408
+ return decoded;
2409
+ }
2410
+ throw new Error("KMS_ENCRYPTION_KEY must be 32 bytes (hex or base64).");
2411
+ }
2412
+ function isFieldEncryptionEnabled() {
2413
+ const featureFlag = process.env.FEATURE_FIELD_ENCRYPTION;
2414
+ if (featureFlag === "false") {
2415
+ return false;
2416
+ }
2417
+ if (featureFlag === "true") {
2418
+ return true;
2419
+ }
2420
+ return (process.env.APP_ENV ?? "local") === "production";
2421
+ }
2422
+ function encryptField(plaintext, key) {
2423
+ const iv = randomBytes(IV_LENGTH);
2424
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
2425
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
2426
+ const tag = cipher.getAuthTag();
2427
+ const payload = Buffer.concat([iv, encrypted, tag]).toString("base64");
2428
+ return `${ENCRYPTION_PREFIX}${payload}`;
2429
+ }
2430
+ function decryptField(value, key) {
2431
+ if (!value.startsWith(ENCRYPTION_PREFIX)) {
2432
+ return value;
2433
+ }
2434
+ const payload = Buffer.from(value.slice(ENCRYPTION_PREFIX.length), "base64");
2435
+ const iv = payload.subarray(0, IV_LENGTH);
2436
+ const tag = payload.subarray(payload.length - TAG_LENGTH);
2437
+ const ciphertext = payload.subarray(IV_LENGTH, payload.length - TAG_LENGTH);
2438
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
2439
+ decipher.setAuthTag(tag);
2440
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
2441
+ }
2442
+ function hashLookupValue(normalizedValue, key) {
2443
+ return createHmac("sha256", key).update(normalizedValue).digest("hex");
2444
+ }
2445
+ function normalizeEmail(email) {
2446
+ return email.trim().toLowerCase();
2447
+ }
2448
+ function protectEmail(email) {
2449
+ const normalized = normalizeEmail(email);
2450
+ const key = resolveEncryptionKey();
2451
+ if (!key || !isFieldEncryptionEnabled()) {
2452
+ return { storedEmail: normalized, emailLookup: normalized };
2453
+ }
2454
+ return {
2455
+ storedEmail: encryptField(normalized, key),
2456
+ emailLookup: hashLookupValue(normalized, key)
2457
+ };
2458
+ }
2459
+ function revealEmail(storedEmail) {
2460
+ const key = resolveEncryptionKey();
2461
+ if (!key || !storedEmail.startsWith(ENCRYPTION_PREFIX)) {
2462
+ return storedEmail;
2463
+ }
2464
+ return decryptField(storedEmail, key);
2465
+ }
2466
+ function emailLookupForQuery(email) {
2467
+ const normalized = normalizeEmail(email);
2468
+ const key = resolveEncryptionKey();
2469
+ if (!key || !isFieldEncryptionEnabled()) {
2470
+ return normalized;
2471
+ }
2472
+ return hashLookupValue(normalized, key);
2473
+ }
2474
+
2475
+ // ../../src/core/crypto/mfaSecret.ts
2476
+ function protectMfaSecret(secret) {
2477
+ const key = resolveEncryptionKey();
2478
+ if (!isFieldEncryptionEnabled() || !key) {
2479
+ return secret;
2480
+ }
2481
+ return encryptField(secret, key);
2482
+ }
2483
+ function revealMfaSecret(stored) {
2484
+ if (!stored) {
2485
+ return null;
2486
+ }
2487
+ const key = resolveEncryptionKey();
2488
+ if (!isFieldEncryptionEnabled() || !key || !stored.startsWith("enc:v1:")) {
2489
+ return stored;
2490
+ }
2491
+ return decryptField(stored, key);
2492
+ }
2493
+
2494
+ // ../../src/core/auth/authContext.ts
2495
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2496
+ var authContext = new AsyncLocalStorage2;
2497
+ function runWithAuthUser(user, callback) {
2498
+ return authContext.run(user, callback);
2499
+ }
2500
+ function currentAuthUser() {
2501
+ return authContext.getStore() ?? null;
2502
+ }
2503
+
2504
+ // ../../src/core/http/requestMetaContext.ts
2505
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2506
+ var requestMetaContext = new AsyncLocalStorage3;
2507
+ function runWithRequestMeta(meta, callback) {
2508
+ return requestMetaContext.run(meta, callback);
2509
+ }
2510
+ function currentRequestMeta() {
2511
+ return requestMetaContext.getStore() ?? {
2512
+ ipAddress: null,
2513
+ userAgent: null
2514
+ };
2515
+ }
2516
+
2517
+ // ../../src/core/security/securityEvents.ts
2518
+ function logSecurityEvent(event, details = {}) {
2519
+ const meta = currentRequestMeta();
2520
+ const user = currentAuthUser();
2521
+ console.log(JSON.stringify({
2522
+ level: "security",
2523
+ event,
2524
+ timestamp: new Date().toISOString(),
2525
+ ip_address: meta.ipAddress ?? null,
2526
+ user_agent: meta.userAgent ?? null,
2527
+ user_id: user?.id ?? null,
2528
+ ...details
2529
+ }));
2530
+ }
2531
+
2532
+ // ../../src/core/security/tokenExpiry.ts
2533
+ function resolveDefaultTokenExpiryDays() {
2534
+ const raw = process.env.API_TOKEN_DEFAULT_EXPIRY_DAYS?.trim();
2535
+ if (!raw) {
2536
+ return null;
2537
+ }
2538
+ const parsed = Number.parseInt(raw, 10);
2539
+ if (!Number.isInteger(parsed) || parsed <= 0) {
2540
+ return null;
2541
+ }
2542
+ return parsed;
2543
+ }
2544
+
2545
+ // ../../src/core/security/totp.ts
2546
+ import { createHmac as createHmac2 } from "crypto";
2547
+ function decodeBase32(input) {
2548
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2549
+ const normalized = input.replace(/=+$/u, "").toUpperCase();
2550
+ let bits = "";
2551
+ for (const char of normalized) {
2552
+ const value = alphabet.indexOf(char);
2553
+ if (value === -1) {
2554
+ throw new Error("Invalid base32 character in MFA secret.");
2555
+ }
2556
+ bits += value.toString(2).padStart(5, "0");
2557
+ }
2558
+ const bytes = [];
2559
+ for (let index = 0;index + 8 <= bits.length; index += 8) {
2560
+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));
2561
+ }
2562
+ return Buffer.from(bytes);
2563
+ }
2564
+ function generateTotp(secret, counter, digits = 6) {
2565
+ const key = decodeBase32(secret);
2566
+ const buffer = Buffer.alloc(8);
2567
+ buffer.writeBigUInt64BE(BigInt(counter));
2568
+ const digest = createHmac2("sha1", key).update(buffer).digest();
2569
+ const lastByte = digest[digest.length - 1] ?? 0;
2570
+ const offset = lastByte & 15;
2571
+ const b0 = digest[offset] ?? 0;
2572
+ const b1 = digest[offset + 1] ?? 0;
2573
+ const b2 = digest[offset + 2] ?? 0;
2574
+ const b3 = digest[offset + 3] ?? 0;
2575
+ const code = (b0 & 127) << 24 | (b1 & 255) << 16 | (b2 & 255) << 8 | b3 & 255;
2576
+ return String(code % 10 ** digits).padStart(digits, "0");
2577
+ }
2578
+ function verifyTotp(secret, token, window = 1) {
2579
+ const normalized = token.trim();
2580
+ if (!/^\d{6}$/u.test(normalized)) {
2581
+ return false;
2582
+ }
2583
+ const timestep = Math.floor(Date.now() / 30000);
2584
+ for (let offset = -window;offset <= window; offset += 1) {
2585
+ if (generateTotp(secret, timestep + offset) === normalized) {
2586
+ return true;
2587
+ }
2588
+ }
2589
+ return false;
2590
+ }
2591
+
2592
+ // ../../src/core/tenant/tenantContext.ts
2593
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2594
+ var tenantContext = new AsyncLocalStorage4;
2595
+ function runWithTenant(tenant, callback) {
2596
+ return tenantContext.run(tenant, callback);
2597
+ }
2598
+ function currentTenant() {
2599
+ return tenantContext.getStore() ?? null;
2600
+ }
2601
+ function currentTenantId() {
2602
+ return currentTenant()?.id ?? 1;
2603
+ }
2604
+ function rateLimitMultiplierForPlan(plan) {
2605
+ switch (plan) {
2606
+ case "enterprise":
2607
+ return 4;
2608
+ case "pro":
2609
+ return 2;
2610
+ default:
2611
+ return 1;
2612
+ }
2613
+ }
2614
+
2615
+ // ../../src/modules/user/authService.ts
2616
+ class AuthService {
2617
+ users;
2618
+ tokens;
2619
+ oauthIdentities;
2620
+ oauthProviders = new Map;
2621
+ constructor(users, tokens, oauthIdentities) {
2622
+ this.users = users;
2623
+ this.tokens = tokens;
2624
+ this.oauthIdentities = oauthIdentities;
2625
+ }
2626
+ registerOAuthProvider(provider) {
2627
+ this.oauthProviders.set(provider.name, provider);
2628
+ }
2629
+ getOAuthProvider(name) {
2630
+ return this.oauthProviders.get(name);
2631
+ }
2632
+ async loginWithPassword(email, password, options = {}) {
2633
+ const user = await this.users.findByEmail(email);
2634
+ if (!user?.password_hash) {
2635
+ logSecurityEvent("auth_login_failed", { reason: "unknown_user", email });
2636
+ throw new UnauthorizedError("Invalid credentials.");
2637
+ }
2638
+ const valid = await verifyPassword(password, user.password_hash);
2639
+ if (!valid) {
2640
+ logSecurityEvent("auth_login_failed", { reason: "invalid_password", user_id: user.id });
2641
+ throw new UnauthorizedError("Invalid credentials.");
2642
+ }
2643
+ if (isFeatureEnabled("emailVerification") && !user.email_verified_at) {
2644
+ logSecurityEvent("auth_login_blocked", { reason: "email_unverified", user_id: user.id });
2645
+ throw new UnauthorizedError("Email address is not verified.");
2646
+ }
2647
+ if (isFeatureEnabled("mfa") && user.mfa_enabled) {
2648
+ const mfaSecret = revealMfaSecret(user.mfa_secret);
2649
+ if (!mfaSecret || !options.mfaCode || !verifyTotp(mfaSecret, options.mfaCode)) {
2650
+ logSecurityEvent("auth_login_failed", { reason: "invalid_mfa", user_id: user.id });
2651
+ throw new UnauthorizedError("Invalid MFA code.");
2652
+ }
2653
+ }
2654
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: "password" });
2655
+ return await this.tokens.createToken(user.id, {
2656
+ name: "password-login",
2657
+ abilities: resolveAbilitiesForRole(user.role),
2658
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
2659
+ });
2660
+ }
2661
+ async loginWithOAuth(providerName, code) {
2662
+ const provider = this.oauthProviders.get(providerName);
2663
+ if (!provider) {
2664
+ throw new UnauthorizedError("Unsupported OAuth provider.");
2665
+ }
2666
+ const profile = await provider.exchangeCode(code);
2667
+ const user = await this.findOrCreateOAuthUser(providerName, profile);
2668
+ logSecurityEvent("auth_login_success", { user_id: user.id, method: `oauth:${providerName}` });
2669
+ return await this.tokens.createToken(user.id, {
2670
+ name: `${providerName}-oauth`,
2671
+ abilities: resolveAbilitiesForRole(user.role),
2672
+ expiresInDays: resolveDefaultTokenExpiryDays() ?? undefined
2673
+ });
2674
+ }
2675
+ buildOAuthAuthorizationUrl(providerName, state) {
2676
+ const provider = this.oauthProviders.get(providerName);
2677
+ if (!provider) {
2678
+ throw new UnauthorizedError("Unsupported OAuth provider.");
2679
+ }
2680
+ return provider.getAuthorizationUrl(state);
2681
+ }
2682
+ async findOrCreateOAuthUser(providerName, profile) {
2683
+ const existingIdentity = await this.oauthIdentities.findByProviderUser(providerName, profile.providerUserId);
2684
+ if (existingIdentity) {
2685
+ return await this.users.findByIdOrThrow(existingIdentity.user_id);
2686
+ }
2687
+ const existingUser = await this.users.findByEmail(profile.email);
2688
+ const user = existingUser ?? await this.users.create({
2689
+ name: profile.name,
2690
+ email: profile.email,
2691
+ role: "member",
2692
+ tenant_id: currentTenantId(),
2693
+ email_verified_at: new Date,
2694
+ created_at: new Date,
2695
+ updated_at: new Date
2696
+ });
2697
+ await this.oauthIdentities.create({
2698
+ user_id: user.id,
2699
+ provider: providerName,
2700
+ provider_user_id: profile.providerUserId,
2701
+ email: profile.email,
2702
+ created_at: new Date
2703
+ });
2704
+ return user;
2705
+ }
2706
+ }
2707
+
2708
+ // ../../src/modules/user/notificationTable.ts
2709
+ var notificationTable = defineTable({
2710
+ name: "notification",
2711
+ primaryKey: "id",
2712
+ columns: ["id", "user_id", "tenant_id", "type", "title", "body", "data", "read_at", "created_at"],
2713
+ defaultOrderBy: { column: "created_at", direction: "DESC" }
2714
+ });
2715
+
2716
+ // ../../src/modules/user/oauthIdentityRepository.ts
2717
+ var oauthIdentityTable = defineTable({
2718
+ name: "oauth_identity",
2719
+ primaryKey: "id",
2720
+ columns: ["id", "user_id", "provider", "provider_user_id", "email", "created_at"]
2721
+ });
2722
+
2723
+ // ../../src/modules/user/table.ts
2724
+ var userTable = defineTable({
2725
+ name: "users",
2726
+ primaryKey: "id",
2727
+ columns: [
2728
+ "id",
2729
+ "name",
2730
+ "email",
2731
+ "email_lookup",
2732
+ "role",
2733
+ "tenant_id",
2734
+ "password_hash",
2735
+ "email_verified_at",
2736
+ "mfa_secret",
2737
+ "mfa_enabled",
2738
+ "created_at",
2739
+ "updated_at"
2740
+ ],
2741
+ defaultOrderBy: { column: "id", direction: "ASC" }
2742
+ });
2743
+
2744
+ // ../../src/core/auth/tokenHash.ts
2745
+ import { createHash, createHmac as createHmac3 } from "crypto";
2746
+ function resolveTokenPepper() {
2747
+ return process.env.TOKEN_HASH_PEPPER?.trim() ?? "workhub-dev-token-pepper";
2748
+ }
2749
+ function hashApiToken(token) {
2750
+ const pepper = resolveTokenPepper();
2751
+ if (pepper && pepper !== "workhub-dev-token-pepper") {
2752
+ return createHmac3("sha256", pepper).update(token).digest("hex");
2753
+ }
2754
+ return createHash("sha256").update(token).digest("hex");
2755
+ }
2756
+
2757
+ // ../../src/modules/user/provider.ts
2758
+ var tokenServiceToken = CORE_TOKEN_SERVICE_TOKEN;
2759
+
2760
+ // ../../src/core/auth/guard.ts
2761
+ function devHeaderAbilities(role) {
2762
+ if (role === "admin") {
2763
+ return [...ADMIN_ABILITIES];
2764
+ }
2765
+ return [...MEMBER_ABILITIES];
2766
+ }
2767
+
2768
+ class GuestGuard {
2769
+ resolve(request) {
2770
+ const userId = request.headers.get("x-authenticated-user-id");
2771
+ if (!userId) {
2772
+ return null;
2773
+ }
2774
+ const role = request.headers.get("x-authenticated-user-role");
2775
+ return {
2776
+ id: userId,
2777
+ abilities: devHeaderAbilities(role),
2778
+ ...role ? { role } : {}
2779
+ };
2780
+ }
2781
+ }
2782
+
2783
+ class ApiTokenGuard {
2784
+ options;
2785
+ constructor(options) {
2786
+ this.options = options;
2787
+ }
2788
+ resolve(request) {
2789
+ const authorization = request.headers.get("authorization");
2790
+ if (!authorization?.startsWith("Bearer ")) {
2791
+ return null;
2792
+ }
2793
+ const token = authorization.slice("Bearer ".length).trim();
2794
+ if (token !== this.options.token) {
2795
+ return null;
2796
+ }
2797
+ return this.options.user;
2798
+ }
2799
+ }
2800
+
2801
+ class DatabaseTokenGuard {
2802
+ container;
2803
+ constructor(container) {
2804
+ this.container = container;
2805
+ }
2806
+ async resolve(request) {
2807
+ const authorization = request.headers.get("authorization");
2808
+ if (!authorization?.startsWith("Bearer ")) {
2809
+ return null;
2810
+ }
2811
+ const token = authorization.slice("Bearer ".length).trim();
2812
+ if (!token) {
2813
+ return null;
2814
+ }
2815
+ if (!this.container.has(tokenServiceToken)) {
2816
+ return null;
2817
+ }
2818
+ const tokenService = this.container.resolve(tokenServiceToken);
2819
+ return await tokenService.resolveUserFromToken(token);
2820
+ }
2821
+ }
2822
+
2823
+ class CompositeGuard {
2824
+ guards;
2825
+ constructor(guards) {
2826
+ this.guards = guards;
2827
+ }
2828
+ async resolve(request) {
2829
+ for (const guard of this.guards) {
2830
+ const user = await Promise.resolve(guard.resolve(request));
2831
+ if (user) {
2832
+ return user;
2833
+ }
2834
+ }
2835
+ return null;
2836
+ }
2837
+ }
2838
+
2839
+ class AuthManager {
2840
+ guard;
2841
+ constructor(guard) {
2842
+ this.guard = guard;
2843
+ }
2844
+ async resolve(request) {
2845
+ if (request) {
2846
+ return await Promise.resolve(this.guard.resolve(request));
2847
+ }
2848
+ return currentAuthUser();
2849
+ }
2850
+ user(request) {
2851
+ return this.resolve(request);
2852
+ }
2853
+ async check(request) {
2854
+ return await this.user(request) !== null;
2855
+ }
2856
+ async requireUser(request) {
2857
+ const user = await this.user(request);
2858
+ if (!user) {
2859
+ throw new UnauthorizedError;
2860
+ }
2861
+ return user;
2862
+ }
2863
+ }
2864
+ export {
2865
+ GuestGuard,
2866
+ DatabaseTokenGuard,
2867
+ CompositeGuard,
2868
+ AuthManager,
2869
+ ApiTokenGuard
2870
+ };