@getstrata/core 0.5.37 → 0.5.39

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