@getstrata/core 0.5.47 → 0.5.49

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