@getstrata/core 0.5.49 → 0.5.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +4 -2
  2. package/dist/core/auth/membershipContextMiddleware.d.ts +1 -1
  3. package/dist/core/auth/scimAuthMiddleware.d.ts +1 -1
  4. package/dist/core/database/errors.d.ts +1 -1
  5. package/dist/core/facades/index.d.ts +1 -1
  6. package/dist/core/http/authMiddleware.d.ts +2 -2
  7. package/dist/core/http/authorizeMiddleware.d.ts +2 -2
  8. package/dist/core/http/index.d.ts +1 -1
  9. package/dist/core/http/requireAuthMiddleware.d.ts +1 -1
  10. package/dist/core/http/requireWebAuthMiddleware.d.ts +1 -1
  11. package/dist/core/http/securedRouteModelBinding.d.ts +1 -1
  12. package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
  13. package/dist/core/queue/failedJobRepository.d.ts +1 -1
  14. package/dist/core/queue/failedJobTable.d.ts +1 -1
  15. package/dist/core/runtime/applicationRegistry.d.ts +3 -3
  16. package/dist/core/tracing/tracingMiddleware.d.ts +1 -1
  17. package/dist/entries/audit/exportAuditLogs.js +9 -175
  18. package/dist/entries/auth/membershipMiddleware.js +2 -74
  19. package/dist/entries/auth/scimAuthMiddleware.js +10 -93
  20. package/dist/entries/auth/sessionGuard.js +0 -6
  21. package/dist/entries/database/errors.js +6 -66
  22. package/dist/entries/database/model.js +2 -65
  23. package/dist/entries/http/authMiddleware.js +1 -23
  24. package/dist/entries/http/authorizeMiddleware.js +2 -89
  25. package/dist/entries/http/bodySizeLimitMiddleware.js +1 -66
  26. package/dist/entries/http/conditionalResponse.js +3 -66
  27. package/dist/entries/http/csrfMiddleware.js +2 -65
  28. package/dist/entries/http/etag.js +3 -66
  29. package/dist/entries/http/formRequest.js +5 -107
  30. package/dist/entries/http/pagination.js +8 -110
  31. package/dist/entries/http/parseFormBody.js +1 -66
  32. package/dist/entries/http/parseMultipartUpload.js +3 -66
  33. package/dist/entries/http/requireAbilityMiddleware.js +2 -89
  34. package/dist/entries/http/requireAuthMiddleware.js +1 -66
  35. package/dist/entries/http/requireGlobalAdminMiddleware.js +4 -128
  36. package/dist/entries/http/requireWebAuthMiddleware.js +2 -65
  37. package/dist/entries/http/routeModelBinding.js +3 -108
  38. package/dist/entries/http/securedRouteModelBinding.js +15 -203
  39. package/dist/entries/http/throttleMiddleware.js +2 -44
  40. package/dist/entries/http/webErrorResponse.js +25 -93
  41. package/dist/entries/http/webFormRequest.js +8 -109
  42. package/dist/entries/jobs/dispatchWebhookJob.js +5 -174
  43. package/dist/entries/logging/requestLoggingMiddleware.js +2 -25
  44. package/dist/entries/queue/createAppQueue.js +4 -2324
  45. package/dist/entries/queue/failedJobRepository.js +4 -2324
  46. package/dist/entries/queue/publicQueue.js +4 -2324
  47. package/dist/entries/queue/queueMetrics.js +4 -2324
  48. package/dist/entries/security/safeFetch.js +1 -68
  49. package/dist/entries/security/safeUrl.js +1 -68
  50. package/dist/entries/security/stripeWebhook.js +1 -68
  51. package/dist/entries/tenant/databaseTenantContext.js +3 -105
  52. package/dist/entries/tenant/tenantDatabaseScope.js +3 -58
  53. package/dist/entries/validation/rules.js +1 -66
  54. package/dist/entries/view.js +5 -16
  55. package/dist/framework/public-api.d.ts +3 -2
  56. package/dist/index.js +3 -0
  57. package/package.json +2 -2
@@ -21,2331 +21,11 @@ var queueConfig = {
21
21
  backoffMs: Number(process.env.QUEUE_BACKOFF_MS ?? "1000")
22
22
  };
23
23
 
24
- // ../../src/core/events/eventBus.ts
25
- class EventBus {
26
- constructor() {}
27
- listeners = new Map;
28
- listen(event, listener) {
29
- const handlers = this.listeners.get(event) ?? new Set;
30
- handlers.add(listener);
31
- this.listeners.set(event, handlers);
32
- return () => {
33
- handlers.delete(listener);
34
- if (handlers.size === 0) {
35
- this.listeners.delete(event);
36
- }
37
- };
38
- }
39
- async dispatch(event, payload) {
40
- const handlers = this.listeners.get(event);
41
- if (!handlers || handlers.size === 0) {
42
- return;
43
- }
44
- for (const handler of handlers) {
45
- await handler(payload);
46
- }
47
- }
48
- }
49
- var eventBus = new EventBus;
50
-
51
- // ../../src/core/events/index.ts
52
- function modelEventName(tableName, action) {
53
- return `${tableName}.${action}`;
54
- }
55
-
56
- // ../../src/core/pagination/index.ts
57
- function buildPaginationMeta(input) {
58
- const lastPage = Math.max(1, Math.ceil(input.total / input.perPage));
59
- return {
60
- page: input.page,
61
- per_page: input.perPage,
62
- total: input.total,
63
- last_page: lastPage
64
- };
65
- }
66
-
67
- // ../../src/core/errors/http.ts
68
- class HttpError extends Error {
69
- status;
70
- details;
71
- constructor(status, message, details) {
72
- super(message);
73
- this.name = new.target.name;
74
- this.status = status;
75
- this.details = details;
76
- }
77
- }
78
-
79
- class BadRequestError extends HttpError {
80
- constructor(message = "Bad Request", details) {
81
- super(400, message, details);
82
- }
83
- }
84
-
85
- class NotFoundError extends HttpError {
86
- constructor(message = "Not Found", details) {
87
- super(404, message, details);
88
- }
89
- }
90
-
91
- class ConflictError extends HttpError {
92
- constructor(message = "Conflict", details) {
93
- super(409, message, details);
94
- }
95
- }
96
-
97
- class UnprocessableEntityError extends HttpError {
98
- constructor(message = "Unprocessable Entity", details) {
99
- super(422, message, details);
100
- }
101
- }
102
-
103
- class ValidationError extends HttpError {
104
- constructor(message = "Validation failed", details) {
105
- super(422, message, details);
106
- }
107
- }
108
-
109
- class ForbiddenError extends HttpError {
110
- constructor(message = "Forbidden", details) {
111
- super(403, message, details);
112
- }
113
- }
114
-
115
- class UnauthorizedError extends HttpError {
116
- constructor(message = "Unauthorized", details) {
117
- super(401, message, details);
118
- }
119
- }
120
-
121
- class PayloadTooLargeError extends HttpError {
122
- constructor(message = "Payload Too Large", details) {
123
- super(413, message, details);
124
- }
125
- }
126
-
127
- class PreconditionFailedError extends HttpError {
128
- constructor(message = "Precondition Failed", details) {
129
- super(412, message, details);
130
- }
131
- }
132
-
133
- // ../../src/core/database/errors.ts
134
- function isPostgresError(error) {
135
- return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
136
- }
137
- function getPostgresSqlState(error) {
138
- if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno)) {
139
- return error.errno;
140
- }
141
- if (typeof error.errno === "number") {
142
- return String(error.errno).padStart(5, "0");
143
- }
144
- if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
145
- return error.code;
146
- }
147
- return;
148
- }
149
- function mapDatabaseError(error) {
150
- if (error instanceof HttpError) {
151
- return error;
152
- }
153
- if (!isPostgresError(error)) {
154
- const message = error instanceof Error ? error.message : "Database operation failed.";
155
- return new BadRequestError(message);
156
- }
157
- const sqlState = getPostgresSqlState(error);
158
- switch (sqlState) {
159
- case "23505":
160
- return new ConflictError(error.detail ?? "A record with these values already exists.", {
161
- constraint: error.constraint
162
- });
163
- case "23503":
164
- return new UnprocessableEntityError(error.detail ?? "Referenced record does not exist.", {
165
- constraint: error.constraint
166
- });
167
- case "23502":
168
- return new BadRequestError(error.detail ?? "Required field is missing.", {
169
- constraint: error.constraint
170
- });
171
- case "23514":
172
- return new BadRequestError(error.detail ?? "Value violates a database constraint.", {
173
- constraint: error.constraint
174
- });
175
- default:
176
- return new BadRequestError(error.message ?? "Database operation failed.", {
177
- code: error.code,
178
- sqlState
179
- });
180
- }
181
- }
182
- async function withDatabaseErrorHandling(operation) {
183
- try {
184
- return await operation();
185
- } catch (error) {
186
- throw mapDatabaseError(error);
187
- }
188
- }
189
-
190
- // ../../src/core/database/query.ts
191
- function quoteIdentifier(identifier) {
192
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
193
- throw new Error(`Invalid SQL identifier: ${identifier}`);
194
- }
195
- return `"${identifier}"`;
196
- }
197
- function qualifyColumn(tableName, column) {
198
- return `${quoteIdentifier(tableName)}.${quoteIdentifier(column)}`;
199
- }
200
- function resolveQualifiedColumn(defaultTable, columnName) {
201
- if (columnName.includes(".")) {
202
- const [table, column] = columnName.split(".", 2);
203
- if (!table || !column) {
204
- throw new Error(`Invalid qualified column: ${columnName}`);
205
- }
206
- return qualifyColumn(table, column);
207
- }
208
- return qualifyColumn(defaultTable, columnName);
209
- }
210
- function parseQualifiedColumn(reference) {
211
- const [table, column] = reference.split(".", 2);
212
- if (!table || !column) {
213
- throw new Error(`Join columns must be qualified as table.column: ${reference}`);
214
- }
215
- return { table, column };
216
- }
217
- function normalizeDirection(direction = "ASC") {
218
- return direction.toUpperCase() === "DESC" ? "DESC" : "ASC";
219
- }
220
- function isQueryOperator(value) {
221
- return value !== null && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object";
222
- }
223
- function pushParam(values, value) {
224
- values.push(value);
225
- return `$${values.length}`;
226
- }
227
- function buildInClause(column, values, params) {
228
- if (values.length === 0) {
229
- return "1 = 0";
230
- }
231
- const placeholders = values.map((value) => pushParam(params, value)).join(", ");
232
- return `${column} IN (${placeholders})`;
233
- }
234
- function buildOperatorClauses(column, operator, params) {
235
- const clauses = [];
236
- if (operator.isNull === true) {
237
- clauses.push(`${column} IS NULL`);
238
- }
239
- if (operator.isNull === false) {
240
- clauses.push(`${column} IS NOT NULL`);
241
- }
242
- if (operator.eq !== undefined) {
243
- if (operator.eq === null) {
244
- clauses.push(`${column} IS NULL`);
245
- } else {
246
- clauses.push(`${column} = ${pushParam(params, operator.eq)}`);
247
- }
248
- }
249
- if (operator.in !== undefined) {
250
- clauses.push(buildInClause(column, operator.in, params));
251
- }
252
- if (operator.gt !== undefined) {
253
- clauses.push(`${column} > ${pushParam(params, operator.gt)}`);
254
- }
255
- if (operator.gte !== undefined) {
256
- clauses.push(`${column} >= ${pushParam(params, operator.gte)}`);
257
- }
258
- if (operator.lt !== undefined) {
259
- clauses.push(`${column} < ${pushParam(params, operator.lt)}`);
260
- }
261
- if (operator.lte !== undefined) {
262
- clauses.push(`${column} <= ${pushParam(params, operator.lte)}`);
263
- }
264
- if (operator.ilike !== undefined) {
265
- clauses.push(`${column} ILIKE ${pushParam(params, `%${operator.ilike}%`)}`);
266
- }
267
- if (operator.tsMatch !== undefined) {
268
- clauses.push(`${column} @@ plainto_tsquery('english', ${pushParam(params, operator.tsMatch)})`);
269
- }
270
- return clauses;
271
- }
272
- function appendWhereParts(tableName, where, params) {
273
- const clauses = [];
274
- for (const [columnName, filterValue] of Object.entries(where)) {
275
- if (filterValue === undefined) {
276
- continue;
277
- }
278
- const column = resolveQualifiedColumn(tableName, columnName);
279
- if (Array.isArray(filterValue)) {
280
- clauses.push(buildInClause(column, filterValue, params));
281
- continue;
282
- }
283
- if (isQueryOperator(filterValue)) {
284
- clauses.push(...buildOperatorClauses(column, filterValue, params));
285
- continue;
286
- }
287
- if (filterValue === null) {
288
- clauses.push(`${column} IS NULL`);
289
- continue;
290
- }
291
- clauses.push(`${column} = ${pushParam(params, filterValue)}`);
292
- }
293
- return clauses.join(" AND ");
294
- }
295
- function buildWhereClause(tableName, where = {}) {
296
- const params = [];
297
- const body = appendWhereParts(tableName, where, params);
298
- return {
299
- clause: body.length > 0 ? ` WHERE ${body}` : "",
300
- params
301
- };
302
- }
303
- function buildWhereNodeClause(tableName, node, params) {
304
- if ("where" in node) {
305
- return appendWhereParts(tableName, node.where, params);
306
- }
307
- const grouped = buildWhereGroupClause(tableName, node.group, params);
308
- if (!grouped) {
309
- return "";
310
- }
311
- return grouped.includes(" OR ") ? `(${grouped})` : grouped;
312
- }
313
- function buildWhereGroupClause(tableName, nodes, params) {
314
- let result = "";
315
- for (const node of nodes) {
316
- const part = buildWhereNodeClause(tableName, node, params);
317
- if (!part) {
318
- continue;
319
- }
320
- if (!result) {
321
- result = part;
322
- continue;
323
- }
324
- result = node.kind === "or" ? `${result} OR ${part}` : `${result} AND ${part}`;
325
- }
326
- if (!result) {
327
- return "";
328
- }
329
- return result;
330
- }
331
- function buildAdvancedWhereClause(tableName, where = {}, whereNodes = [], params = []) {
332
- const nodes = [];
333
- if (Object.keys(where).length > 0) {
334
- nodes.push({ kind: "and", where });
335
- }
336
- nodes.push(...whereNodes);
337
- const combined = buildWhereGroupClause(tableName, nodes, params);
338
- return {
339
- clause: combined ? ` WHERE ${combined}` : "",
340
- params
341
- };
342
- }
343
- function resolveSoftDeleteColumn(table) {
344
- if (!table.softDeletes) {
345
- return null;
346
- }
347
- if (table.softDeletes === true) {
348
- return "deleted_at";
349
- }
350
- return table.softDeletes.column ?? "deleted_at";
351
- }
352
- function appendSoftDeleteScope(table, options, clauses) {
353
- const column = resolveSoftDeleteColumn(table);
354
- if (!column) {
355
- return;
356
- }
357
- const qualifiedColumn = qualifyColumn(table.name, column);
358
- if (options.onlyTrashed) {
359
- clauses.push(`${qualifiedColumn} IS NOT NULL`);
360
- return;
361
- }
362
- if (!options.withTrashed) {
363
- clauses.push(`${qualifiedColumn} IS NULL`);
364
- }
365
- }
366
- function buildQueryWhereClause(table, options = {}, whereNodes = [], params = []) {
367
- const { clause, params: whereParams } = buildAdvancedWhereClause(table.name, options.where ?? {}, whereNodes, params);
368
- const softDeleteClauses = [];
369
- appendSoftDeleteScope(table, options, softDeleteClauses);
370
- if (softDeleteClauses.length === 0) {
371
- return { clause, params: whereParams };
372
- }
373
- const base = clause.replace(/^ WHERE /, "");
374
- const scope = softDeleteClauses.join(" AND ");
375
- return {
376
- clause: base ? ` WHERE (${base}) AND ${scope}` : ` WHERE ${scope}`,
377
- params: whereParams
378
- };
379
- }
380
- function isQueryOrder(value) {
381
- return "column" in value;
382
- }
383
- function normalizeOrderBy(orderBy) {
384
- if (!orderBy) {
385
- return [];
386
- }
387
- if (Array.isArray(orderBy)) {
388
- return orderBy;
389
- }
390
- if (isQueryOrder(orderBy)) {
391
- return [orderBy];
392
- }
393
- return Object.entries(orderBy).map(([column, direction]) => ({
394
- column,
395
- direction
396
- }));
397
- }
398
- function buildOrderByClause(tableName, orderBy) {
399
- const parts = normalizeOrderBy(orderBy).map(({ column, direction }) => {
400
- return `${resolveQualifiedColumn(tableName, column)} ${normalizeDirection(direction)}`;
401
- });
402
- return parts.length > 0 ? ` ORDER BY ${parts.join(", ")}` : "";
403
- }
404
- function buildGroupByClause(tableName, groupBy) {
405
- if (!groupBy) {
406
- return "";
407
- }
408
- const columns = (Array.isArray(groupBy) ? groupBy : [groupBy]).map((column) => String(column));
409
- const parts = columns.map((column) => resolveQualifiedColumn(tableName, column));
410
- return parts.length > 0 ? ` GROUP BY ${parts.join(", ")}` : "";
411
- }
412
- function buildHavingClause(tableName, having, params) {
413
- if (!having) {
414
- return "";
415
- }
416
- const body = appendWhereParts(tableName, having, params);
417
- return body.length > 0 ? ` HAVING ${body}` : "";
418
- }
419
- function buildJoinClause(joins = []) {
420
- return joins.map((join) => {
421
- const joinType = join.type === "left" ? "LEFT JOIN" : "INNER JOIN";
422
- const onClause = join.on.map(({ left, right }) => `${qualifyColumn(left.table, left.column)} = ${qualifyColumn(right.table, right.column)}`).join(" AND ");
423
- return ` ${joinType} ${quoteIdentifier(join.table)} ON ${onClause}`;
424
- }).join("");
425
- }
426
- function buildLimitClause(limit) {
427
- if (limit === undefined) {
428
- return "";
429
- }
430
- if (!Number.isInteger(limit) || limit <= 0) {
431
- throw new Error("Query limit must be a positive integer.");
432
- }
433
- return ` LIMIT ${limit}`;
434
- }
435
- function buildOffsetClause(offset) {
436
- if (offset === undefined) {
437
- return "";
438
- }
439
- if (!Number.isInteger(offset) || offset < 0) {
440
- throw new Error("Query offset must be a non-negative integer.");
441
- }
442
- return ` OFFSET ${offset}`;
443
- }
444
- function buildReturningColumns(table) {
445
- return table.columns.map((column) => qualifyColumn(table.name, column)).join(", ");
446
- }
447
- function buildSelectList(table, select, params = []) {
448
- if (!select || select.length === 0) {
449
- return buildReturningColumns(table);
450
- }
451
- return select.map((item) => {
452
- if (item.kind === "column") {
453
- const column2 = qualifyColumn(item.table, item.column);
454
- return item.as ? `${column2} AS ${quoteIdentifier(item.as)}` : column2;
455
- }
456
- if (item.kind === "literalText") {
457
- return `${pushParam(params, item.value)}::text AS ${quoteIdentifier(item.as)}`;
458
- }
459
- const column = qualifyColumn(item.table, item.column);
460
- const placeholder = pushParam(params, item.query);
461
- return `ts_rank(${column}, plainto_tsquery('english', ${placeholder})) AS ${quoteIdentifier(item.as)}`;
462
- }).join(", ");
463
- }
464
- function getDefinedColumnEntries(table, values, options = {}) {
465
- const record = values;
466
- const excluded = new Set(options.exclude ?? []);
467
- return table.columns.flatMap((column) => {
468
- if (excluded.has(column) || !Object.hasOwn(record, column)) {
469
- return [];
470
- }
471
- const value = record[column];
472
- if (value === undefined) {
473
- return [];
474
- }
475
- return [[column, value]];
476
- });
477
- }
478
- function buildSelectQuery(table, options = {}, whereNodes = []) {
479
- const params = [];
480
- const columns = buildSelectList(table, options.select, params);
481
- const { clause } = buildQueryWhereClause(table, options, whereNodes, params);
482
- const joins = buildJoinClause(options.joins);
483
- const groupBy = buildGroupByClause(table.name, options.groupBy);
484
- const havingClause = buildHavingClause(table.name, options.having, params);
485
- const orderBy = buildOrderByClause(table.name, options.orderBy ?? table.defaultOrderBy);
486
- const limit = buildLimitClause(options.limit);
487
- const offset = buildOffsetClause(options.offset);
488
- return {
489
- text: `SELECT ${columns} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${havingClause}${orderBy}${limit}${offset}`,
490
- params
491
- };
492
- }
493
- function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
494
- const params = [];
495
- const { clause, params: whereParams } = buildQueryWhereClause(table, {
496
- where,
497
- withTrashed: options.withTrashed,
498
- onlyTrashed: options.onlyTrashed
499
- }, whereNodes);
500
- params.push(...whereParams);
501
- const joins = buildJoinClause(options.joins);
502
- const groupBy = buildGroupByClause(table.name, options.groupBy);
503
- return {
504
- text: `SELECT COUNT(*) AS count FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}`,
505
- params
506
- };
507
- }
508
- function buildProjectionQuery(table, expression, alias, options = {}, whereNodes = []) {
509
- assertSafeProjectionExpression(expression);
510
- const params = [];
511
- const { clause, params: whereParams } = buildQueryWhereClause(table, options, whereNodes);
512
- params.push(...whereParams);
513
- const joins = buildJoinClause(options.joins);
514
- const groupBy = buildGroupByClause(table.name, options.groupBy);
515
- const orderBy = buildOrderByClause(table.name, options.orderBy);
516
- const limit = buildLimitClause(options.limit);
517
- return {
518
- text: `SELECT ${expression} AS ${quoteIdentifier(alias)} FROM ${quoteIdentifier(table.name)}${joins}${clause}${groupBy}${orderBy}${limit}`,
519
- params
520
- };
521
- }
522
- var SAFE_PROJECTION_EXPRESSION = /^(COUNT\(\*\)|(?:"[\w_]+"(?:\."[\w_]+")?)|(?:AVG|SUM|MIN|MAX)\((?:"[\w_]+"(?:\."[\w_]+")?)\))$/;
523
- function assertSafeProjectionExpression(expression) {
524
- if (!SAFE_PROJECTION_EXPRESSION.test(expression.trim())) {
525
- throw new Error(`Unsafe projection expression: ${expression}`);
526
- }
527
- }
528
- function buildGroupedCountQuery(table, column, where = {}, options = {}) {
529
- const qualifiedColumn = qualifyColumn(table.name, column);
530
- const { clause, params } = buildQueryWhereClause(table, {
531
- where,
532
- ...options
533
- });
534
- return {
535
- text: `SELECT ${qualifiedColumn} AS ${quoteIdentifier("value")}, COUNT(*) AS ${quoteIdentifier("count")} FROM ${quoteIdentifier(table.name)}${clause} GROUP BY ${qualifiedColumn} ORDER BY ${qualifiedColumn} ASC`,
536
- params
537
- };
538
- }
539
- function buildInsertQuery(table, values) {
540
- const entries = getDefinedColumnEntries(table, values);
541
- if (entries.length === 0) {
542
- throw new Error(`Cannot insert into ${table.name} without any column values.`);
543
- }
544
- const params = [];
545
- const columns = entries.map(([column]) => quoteIdentifier(column)).join(", ");
546
- const placeholders = entries.map(([, value]) => pushParam(params, value)).join(", ");
547
- const returningColumns = buildReturningColumns(table);
548
- return {
549
- text: `INSERT INTO ${quoteIdentifier(table.name)} (${columns}) VALUES (${placeholders}) RETURNING ${returningColumns}`,
550
- params
551
- };
552
- }
553
- function buildUpdateQuery(table, id, changes) {
554
- const entries = getDefinedColumnEntries(table, changes, {
555
- exclude: [table.primaryKey]
556
- });
557
- if (entries.length === 0) {
558
- throw new Error(`Cannot update ${table.name} without any changed column values.`);
559
- }
560
- const params = [];
561
- const setClause = entries.map(([column, value]) => `${quoteIdentifier(column)} = ${pushParam(params, value)}`).join(", ");
562
- const primaryKeyPlaceholder = pushParam(params, id);
563
- const returningColumns = buildReturningColumns(table);
564
- const scopeClauses = [];
565
- appendSoftDeleteScope(table, {}, scopeClauses);
566
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
567
- return {
568
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${setClause} WHERE ${quoteIdentifier(table.primaryKey)} = ${primaryKeyPlaceholder}${scopeSuffix} RETURNING ${returningColumns}`,
569
- params
570
- };
571
- }
572
- function buildSoftDeleteByIdQuery(table, id, deletedAt) {
573
- const deletedAtColumn = resolveSoftDeleteColumn(table);
574
- if (!deletedAtColumn) {
575
- throw new Error(`Table ${table.name} does not support soft deletes.`);
576
- }
577
- const returningColumns = buildReturningColumns(table);
578
- const scopeClauses = [];
579
- appendSoftDeleteScope(table, {}, scopeClauses);
580
- const scopeSuffix = scopeClauses.length > 0 ? ` AND ${scopeClauses.join(" AND ")}` : "";
581
- return {
582
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2${scopeSuffix} RETURNING ${returningColumns}`,
583
- params: [deletedAt, id]
584
- };
585
- }
586
- function buildRestoreByIdQuery(table, id) {
587
- const deletedAtColumn = resolveSoftDeleteColumn(table);
588
- if (!deletedAtColumn) {
589
- throw new Error(`Table ${table.name} does not support soft deletes.`);
590
- }
591
- const returningColumns = buildReturningColumns(table);
592
- return {
593
- text: `UPDATE ${quoteIdentifier(table.name)} SET ${quoteIdentifier(deletedAtColumn)} = $1 WHERE ${quoteIdentifier(table.primaryKey)} = $2 AND ${qualifyColumn(table.name, deletedAtColumn)} IS NOT NULL RETURNING ${returningColumns}`,
594
- params: [null, id]
595
- };
596
- }
597
- function buildDeleteByIdQuery(table, id) {
598
- return {
599
- text: `DELETE FROM ${quoteIdentifier(table.name)} WHERE ${quoteIdentifier(table.primaryKey)} = $1 RETURNING ${quoteIdentifier(table.primaryKey)} AS ${quoteIdentifier("deleted_id")}`,
600
- params: [id]
601
- };
602
- }
603
-
604
- // ../../src/core/database/relationships.ts
605
- function hasMany(definition) {
606
- return {
607
- type: "hasMany",
608
- ...definition
609
- };
610
- }
611
- function hasOne(definition) {
612
- return {
613
- type: "hasOne",
614
- ...definition
615
- };
616
- }
617
- function belongsTo(definition) {
618
- return {
619
- type: "belongsTo",
620
- ...definition
621
- };
622
- }
623
- function belongsToMany(definition) {
624
- return {
625
- type: "belongsToMany",
626
- ...definition
627
- };
628
- }
629
- function indexHasManyRelation(parents, children, relation) {
630
- const groups = new Map;
631
- for (const parent of parents) {
632
- groups.set(parent[relation.localKey], []);
633
- }
634
- for (const child of children) {
635
- const key = child[relation.foreignKey];
636
- const group = groups.get(key);
637
- if (!group) {
638
- continue;
639
- }
640
- group.push(child);
641
- }
642
- return groups;
643
- }
644
- function indexHasOneRelation(parents, children, relation) {
645
- const grouped = indexHasManyRelation(parents, children, relation);
646
- const result = new Map;
647
- for (const parent of parents) {
648
- const matches = grouped.get(parent[relation.localKey]) ?? [];
649
- result.set(parent[relation.localKey], matches[0]);
650
- }
651
- return result;
652
- }
653
- function indexBelongsToRelation(children, parents, relation) {
654
- const parentsById = new Map;
655
- for (const parent of parents) {
656
- parentsById.set(parent[relation.ownerKey], parent);
657
- }
658
- const result = new Map;
659
- for (const child of children) {
660
- const foreignKey = child[relation.foreignKey];
661
- const parent = parentsById.get(foreignKey);
662
- if (parent) {
663
- result.set(foreignKey, parent);
664
- }
665
- }
666
- return result;
667
- }
668
- function indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation) {
669
- const relatedById = new Map;
670
- for (const related of relatedRows) {
671
- relatedById.set(related[relation.relatedKey], related);
672
- }
673
- const groups = new Map;
674
- for (const parent of parents) {
675
- groups.set(parent[relation.parentKey], []);
676
- }
677
- for (const pivot of pivotRows) {
678
- const parentId = pivot[relation.foreignPivotKey];
679
- const relatedId = pivot[relation.relatedPivotKey];
680
- const group = groups.get(parentId);
681
- const related = relatedById.get(relatedId);
682
- if (!group || !related) {
683
- continue;
684
- }
685
- group.push(related);
686
- }
687
- return groups;
688
- }
689
- function morphMany(definition) {
690
- return {
691
- type: "morphMany",
692
- ...definition
693
- };
694
- }
695
- function morphOne(definition) {
696
- return {
697
- type: "morphOne",
698
- ...definition
699
- };
700
- }
701
- function morphTo(definition) {
702
- return {
703
- type: "morphTo",
704
- ...definition
705
- };
706
- }
707
- function indexMorphManyRelation(parents, children, relation) {
708
- const groups = new Map;
709
- for (const parent of parents) {
710
- groups.set(parent[relation.localKey], []);
711
- }
712
- for (const child of children) {
713
- if (child[relation.morphTypeKey] !== relation.morphType) {
714
- continue;
715
- }
716
- const key = child[relation.morphIdKey];
717
- const group = groups.get(key);
718
- if (!group) {
719
- continue;
720
- }
721
- group.push(child);
722
- }
723
- return groups;
724
- }
725
- function indexMorphOneRelation(parents, children, relation) {
726
- const grouped = indexMorphManyRelation(parents, children, relation);
727
- const result = new Map;
728
- for (const parent of parents) {
729
- const matches = grouped.get(parent[relation.localKey]) ?? [];
730
- result.set(parent[relation.localKey], matches[0]);
731
- }
732
- return result;
733
- }
734
- function indexMorphToRelation(children, parentsByType, relation) {
735
- const result = new Map;
736
- for (const child of children) {
737
- const morphType = String(child[relation.morphTypeKey]);
738
- const parents = parentsByType.get(morphType);
739
- if (!parents) {
740
- continue;
741
- }
742
- const parent = parents.get(child[relation.morphIdKey]);
743
- if (parent) {
744
- result.set(child[relation.morphIdKey], parent);
745
- }
746
- }
747
- return result;
748
- }
749
-
750
- // ../../src/core/database/boundConnection.ts
751
- var boundConnectionHolder = {
752
- connection: null
753
- };
754
- function bindDatabaseConnection(connection) {
755
- boundConnectionHolder.connection = connection;
756
- }
757
- function getBoundDatabaseConnection() {
758
- return boundConnectionHolder.connection;
759
- }
760
- function resetBoundDatabaseConnection() {
761
- boundConnectionHolder.connection = null;
762
- }
763
-
764
- // ../../src/core/runtime/asyncContextStore.ts
765
- import { AsyncLocalStorage } from "async_hooks";
766
- function createAsyncContextStore(key) {
767
- const symbol = Symbol.for(key);
768
- const globalRecord = globalThis;
769
- const existing = globalRecord[symbol];
770
- if (existing) {
771
- return existing;
772
- }
773
- const store = new AsyncLocalStorage;
774
- globalRecord[symbol] = store;
775
- return store;
776
- }
777
-
778
- // ../../src/core/database/connectionContext.ts
779
- var activeConnection = createAsyncContextStore("@getstrata/databaseConnectionContext");
780
- function runWithDatabaseConnection(connection, callback) {
781
- return activeConnection.run(connection, callback);
782
- }
783
- function getActiveDatabaseConnection(fallback) {
784
- return activeConnection.getStore() ?? fallback;
785
- }
786
- function hasActiveDatabaseConnection() {
787
- return activeConnection.getStore() !== undefined;
788
- }
789
-
790
- // ../../src/core/database/queryProxy.ts
791
- var POOL_CONNECTION_METHODS = new Set(["begin", "close", "connect"]);
792
- function createDatabaseQueryProxy(pool) {
793
- function resolveDatabase() {
794
- return getActiveDatabaseConnection(pool);
795
- }
796
- function resolveDatabaseForProperty(property) {
797
- if (typeof property === "string" && POOL_CONNECTION_METHODS.has(property)) {
798
- return pool;
799
- }
800
- return resolveDatabase();
801
- }
802
- return new Proxy(function database() {}, {
803
- apply(_target, _thisArg, args) {
804
- return resolveDatabase()(...args);
805
- },
806
- get(_target, property) {
807
- const connection = resolveDatabaseForProperty(property);
808
- const value = connection[property];
809
- return typeof value === "function" ? value.bind(connection) : value;
810
- }
811
- });
812
- }
813
-
814
- // ../../src/core/database/defaultConnection.ts
815
- var defaultPool = {
816
- connection: null
817
- };
818
- var defaultQuery = {
819
- connection: null
820
- };
821
- function registerDefaultDatabasePool(connection) {
822
- defaultPool.connection = connection;
823
- defaultQuery.connection = createDatabaseQueryProxy(connection);
824
- }
825
- function getDefaultDatabasePool() {
826
- if (!defaultPool.connection) {
827
- throw new Error("Default database pool is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
828
- }
829
- return defaultPool.connection;
830
- }
831
- function getDefaultDatabaseQuery() {
832
- if (!defaultQuery.connection) {
833
- throw new Error("Default database query handle is not registered. Call registerDefaultDatabasePool() during app bootstrap.");
834
- }
835
- return defaultQuery.connection;
836
- }
837
-
838
- // ../../src/core/database/repositoryConnection.ts
839
- function resolveRepositoryConnection() {
840
- return getBoundDatabaseConnection() ?? getDefaultDatabaseQuery();
841
- }
842
- var repositoryConnection = new Proxy(function repositoryConnection2() {}, {
843
- apply(_target, _thisArg, args) {
844
- return resolveRepositoryConnection()(...args);
845
- },
846
- get(_target, property) {
847
- const connection = resolveRepositoryConnection();
848
- const value = connection[property];
849
- return typeof value === "function" ? value.bind(connection) : value;
850
- }
851
- });
852
-
853
- // ../../src/core/database/whereBuilder.ts
854
- class WhereBuilder {
855
- nodes = [];
856
- where(where) {
857
- this.nodes.push({ kind: "and", where });
858
- return this;
859
- }
860
- orWhere(where) {
861
- this.nodes.push({ kind: "or", where });
862
- return this;
863
- }
864
- whereGroup(fn) {
865
- const nested = new WhereBuilder;
866
- fn(nested);
867
- if (nested.nodes.length > 0) {
868
- this.nodes.push({ kind: "and", group: nested.nodes });
869
- }
870
- return this;
871
- }
872
- orWhereGroup(fn) {
873
- const nested = new WhereBuilder;
874
- fn(nested);
875
- if (nested.nodes.length > 0) {
876
- this.nodes.push({ kind: "or", group: nested.nodes });
877
- }
878
- return this;
879
- }
880
- }
881
-
882
- // ../../src/core/database/repositoryQuery.ts
883
- class RepositoryQuery {
884
- repository;
885
- whereClause;
886
- queryOptions;
887
- eagerLoads = [];
888
- whereNodes = [];
889
- constructor(repository, whereClause = {}, queryOptions = {}) {
890
- this.repository = repository;
891
- this.whereClause = whereClause;
892
- this.queryOptions = queryOptions;
893
- }
894
- where(input) {
895
- if (typeof input === "function") {
896
- const builder = new WhereBuilder;
897
- input(builder);
898
- this.whereNodes.push(...builder.nodes);
899
- return this;
900
- }
901
- this.whereClause = { ...this.whereClause, ...input };
902
- return this;
903
- }
904
- orWhere(input) {
905
- if (typeof input === "function") {
906
- const builder = new WhereBuilder;
907
- input(builder);
908
- if (builder.nodes.length > 0) {
909
- this.whereNodes.push({ kind: "or", group: builder.nodes });
910
- }
911
- return this;
912
- }
913
- this.whereNodes.push({ kind: "or", where: input });
914
- return this;
915
- }
916
- orderBy(orderBy) {
917
- this.queryOptions = { ...this.queryOptions, orderBy };
918
- return this;
919
- }
920
- limit(limit) {
921
- this.queryOptions = { ...this.queryOptions, limit };
922
- return this;
923
- }
924
- offset(offset) {
925
- this.queryOptions = { ...this.queryOptions, offset };
926
- return this;
927
- }
928
- join(left, right) {
929
- return this.addJoin("inner", left, right);
930
- }
931
- leftJoin(left, right) {
932
- return this.addJoin("left", left, right);
933
- }
934
- groupBy(groupBy) {
935
- this.queryOptions = { ...this.queryOptions, groupBy };
936
- return this;
937
- }
938
- having(having) {
939
- this.queryOptions = { ...this.queryOptions, having };
940
- return this;
941
- }
942
- withHasMany(as, relation, childRepository, options = {}) {
943
- this.eagerLoads.push({
944
- kind: "hasMany",
945
- as,
946
- relation,
947
- repository: childRepository,
948
- options
949
- });
950
- return this;
951
- }
952
- withBelongsTo(as, relation, parentRepository, options = {}) {
953
- this.eagerLoads.push({
954
- kind: "belongsTo",
955
- as,
956
- relation,
957
- repository: parentRepository,
958
- options
959
- });
960
- return this;
961
- }
962
- withMorphMany(as, relation, childRepository, options = {}) {
963
- this.eagerLoads.push({
964
- kind: "morphMany",
965
- as,
966
- relation,
967
- repository: childRepository,
968
- options
969
- });
970
- return this;
971
- }
972
- withMorphOne(as, relation, childRepository, options = {}) {
973
- this.eagerLoads.push({
974
- kind: "morphOne",
975
- as,
976
- relation,
977
- repository: childRepository,
978
- options
979
- });
980
- return this;
981
- }
982
- withMorphTo(as, relation, repositoriesByType, options = {}) {
983
- this.eagerLoads.push({
984
- kind: "morphTo",
985
- as,
986
- relation,
987
- repository: this.repository,
988
- morphRepositories: repositoriesByType,
989
- options
990
- });
991
- return this;
992
- }
993
- async get() {
994
- const rows = await this.repository.findAll(this.buildOptions());
995
- return await this.attach(rows);
996
- }
997
- async first() {
998
- const rows = await this.get();
999
- return rows[0] ?? null;
1000
- }
1001
- async paginate(options) {
1002
- return await this.repository.paginate({
1003
- ...this.buildOptions(),
1004
- page: options.page,
1005
- perPage: options.perPage
1006
- });
1007
- }
1008
- buildOptions() {
1009
- return {
1010
- ...this.queryOptions,
1011
- where: this.whereClause,
1012
- whereNodes: this.whereNodes
1013
- };
1014
- }
1015
- addJoin(type, left, right) {
1016
- const leftRef = parseQualifiedColumn(left);
1017
- const rightRef = parseQualifiedColumn(right);
1018
- const table = type === "inner" ? rightRef.table : rightRef.table;
1019
- const joins = this.queryOptions.joins ?? [];
1020
- const existing = joins.find((join) => join.table === table && join.type === type);
1021
- if (existing) {
1022
- existing.on.push({ left: leftRef, right: rightRef });
1023
- return this;
1024
- }
1025
- this.queryOptions = {
1026
- ...this.queryOptions,
1027
- joins: [
1028
- ...joins,
1029
- {
1030
- type,
1031
- table,
1032
- on: [{ left: leftRef, right: rightRef }]
1033
- }
1034
- ]
1035
- };
1036
- return this;
1037
- }
1038
- async attach(rows) {
1039
- if (rows.length === 0 || this.eagerLoads.length === 0) {
1040
- return rows.map((row) => ({ ...row }));
1041
- }
1042
- let result = rows.map((row) => ({ ...row }));
1043
- for (const load of this.eagerLoads) {
1044
- if (load.kind === "hasMany") {
1045
- const relation2 = load.relation;
1046
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadHasManyForParents(rows, relation2, load.options);
1047
- result = result.map((row) => ({
1048
- ...row,
1049
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
1050
- }));
1051
- continue;
1052
- }
1053
- if (load.kind === "morphMany") {
1054
- const relation2 = load.relation;
1055
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphManyForParents(rows, relation2, load.options);
1056
- result = result.map((row) => ({
1057
- ...row,
1058
- [load.as]: grouped2.get(row[relation2.localKey]) ?? []
1059
- }));
1060
- continue;
1061
- }
1062
- if (load.kind === "morphOne") {
1063
- const relation2 = load.relation;
1064
- const grouped2 = await load.repository.withConnection(this.repository.getConnection()).loadMorphOneForParents(rows, relation2, load.options);
1065
- result = result.map((row) => ({
1066
- ...row,
1067
- [load.as]: grouped2.get(row[relation2.localKey])
1068
- }));
1069
- continue;
1070
- }
1071
- if (load.kind === "morphTo") {
1072
- const relation2 = load.relation;
1073
- const grouped2 = await this.repository.loadMorphToForChildren(rows, relation2, load.morphRepositories ?? new Map, load.options);
1074
- result = result.map((row) => ({
1075
- ...row,
1076
- [load.as]: grouped2.get(row[relation2.morphIdKey])
1077
- }));
1078
- continue;
1079
- }
1080
- const relation = load.relation;
1081
- const grouped = await this.repository.loadBelongsToForParents(rows, relation, load.repository, load.options);
1082
- result = result.map((row) => ({
1083
- ...row,
1084
- [load.as]: grouped.get(row[relation.foreignKey])
1085
- }));
1086
- }
1087
- return result;
1088
- }
1089
- }
1090
-
1091
- // ../../src/core/database/baseRepository.ts
1092
- class BaseRepository {
1093
- table;
1094
- connection;
1095
- constructor(table, connection = repositoryConnection) {
1096
- this.table = table;
1097
- this.connection = connection;
1098
- }
1099
- async findAll(options = {}) {
1100
- return await withDatabaseErrorHandling(async () => {
1101
- const { whereNodes, ...queryOptions } = options;
1102
- const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
1103
- return await this.connection.unsafe(text, params);
1104
- });
1105
- }
1106
- async paginate(options) {
1107
- const { whereNodes, where = {}, page, perPage, ...queryOptions } = options;
1108
- const total = await this.countWhere(where, {
1109
- withTrashed: options.withTrashed,
1110
- onlyTrashed: options.onlyTrashed,
1111
- joins: options.joins,
1112
- groupBy: options.groupBy
1113
- }, whereNodes);
1114
- const offset = (page - 1) * perPage;
1115
- const data = await this.findAll({
1116
- ...queryOptions,
1117
- where,
1118
- whereNodes,
1119
- limit: perPage,
1120
- offset
1121
- });
1122
- return {
1123
- data,
1124
- meta: buildPaginationMeta({ page, perPage, total })
1125
- };
1126
- }
1127
- async chunk(count, callback, options = {}) {
1128
- if (!Number.isInteger(count) || count <= 0) {
1129
- throw new Error("Chunk size must be a positive integer.");
1130
- }
1131
- let offset = 0;
1132
- while (true) {
1133
- const rows = await this.findAll({
1134
- ...options,
1135
- limit: count,
1136
- offset
1137
- });
1138
- if (rows.length === 0) {
1139
- return;
1140
- }
1141
- const shouldContinue = await callback(rows);
1142
- if (shouldContinue === false || rows.length < count) {
1143
- return;
1144
- }
1145
- offset += count;
1146
- }
1147
- }
1148
- async cursorPaginate(options) {
1149
- const {
1150
- perPage,
1151
- cursor,
1152
- cursorColumn = this.table.primaryKey,
1153
- direction = "asc",
1154
- where = {},
1155
- whereNodes,
1156
- ...queryOptions
1157
- } = options;
1158
- if (!Number.isInteger(perPage) || perPage <= 0) {
1159
- throw new Error("Cursor page size must be a positive integer.");
1160
- }
1161
- const cursorWhere = { ...where };
1162
- if (cursor !== undefined) {
1163
- cursorWhere[cursorColumn] = direction === "asc" ? { gt: cursor } : { lt: cursor };
1164
- }
1165
- const rows = await this.findAll({
1166
- ...queryOptions,
1167
- where: cursorWhere,
1168
- whereNodes,
1169
- orderBy: { [cursorColumn]: direction },
1170
- limit: perPage + 1
1171
- });
1172
- const hasMore = rows.length > perPage;
1173
- const data = hasMore ? rows.slice(0, perPage) : rows;
1174
- const nextCursor = hasMore ? data[data.length - 1]?.[cursorColumn] ?? null : null;
1175
- const prevCursor = cursor ?? null;
1176
- return {
1177
- data,
1178
- meta: {
1179
- per_page: perPage,
1180
- next_cursor: nextCursor,
1181
- prev_cursor: prevCursor,
1182
- has_more: hasMore
1183
- }
1184
- };
1185
- }
1186
- async findById(id) {
1187
- return await this.firstOrNull({
1188
- [this.table.primaryKey]: id
1189
- });
1190
- }
1191
- async findByIdOrThrow(id, errorFactory) {
1192
- const record = await this.findById(id);
1193
- if (record) {
1194
- return record;
1195
- }
1196
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
1197
- }
1198
- async findByIds(ids) {
1199
- const uniqueIds = [...new Set(ids)];
1200
- if (uniqueIds.length === 0) {
1201
- return [];
1202
- }
1203
- return await this.findWhere({
1204
- [this.table.primaryKey]: uniqueIds
1205
- });
1206
- }
1207
- async firstOrNull(where, options = {}) {
1208
- const [record] = await this.findAll({ ...options, where, limit: 1 });
1209
- return record ?? null;
1210
- }
1211
- async create(values) {
1212
- return await withDatabaseErrorHandling(async () => {
1213
- const { text, params } = buildInsertQuery(this.table, values);
1214
- const [record] = await this.connection.unsafe(text, params);
1215
- if (!record) {
1216
- throw new Error(`Insert into ${this.table.name} did not return a record.`);
1217
- }
1218
- const entity = record;
1219
- await eventBus.dispatch(modelEventName(this.table.name, "created"), entity);
1220
- return entity;
1221
- });
1222
- }
1223
- async updateById(id, changes) {
1224
- return await withDatabaseErrorHandling(async () => {
1225
- const { text, params } = buildUpdateQuery(this.table, id, changes);
1226
- const [record] = await this.connection.unsafe(text, params);
1227
- const entity = record ?? null;
1228
- if (entity) {
1229
- await eventBus.dispatch(modelEventName(this.table.name, "updated"), entity);
1230
- }
1231
- return entity;
1232
- });
1233
- }
1234
- async updateByIdOrThrow(id, changes, errorFactory) {
1235
- const record = await this.updateById(id, changes);
1236
- if (record) {
1237
- return record;
1238
- }
1239
- throw errorFactory?.(id) ?? new Error(`${this.table.name} ${String(id)} was not found.`);
1240
- }
1241
- async deleteById(id) {
1242
- if (resolveSoftDeleteColumn(this.table)) {
1243
- return await this.softDeleteById(id);
1244
- }
1245
- return await this.forceDeleteById(id);
1246
- }
1247
- async softDeleteById(id) {
1248
- return await withDatabaseErrorHandling(async () => {
1249
- const { text, params } = buildSoftDeleteByIdQuery(this.table, id, new Date);
1250
- const [record] = await this.connection.unsafe(text, params);
1251
- if (!record) {
1252
- return false;
1253
- }
1254
- await eventBus.dispatch(modelEventName(this.table.name, "deleted"), record);
1255
- return true;
1256
- });
1257
- }
1258
- async forceDeleteById(id) {
1259
- return await withDatabaseErrorHandling(async () => {
1260
- const { text, params } = buildDeleteByIdQuery(this.table, id);
1261
- const [row] = await this.connection.unsafe(text, params);
1262
- if (!row) {
1263
- return false;
1264
- }
1265
- await eventBus.dispatch(modelEventName(this.table.name, "force-deleted"), {
1266
- id
1267
- });
1268
- return true;
1269
- });
1270
- }
1271
- async restoreById(id) {
1272
- return await withDatabaseErrorHandling(async () => {
1273
- const { text, params } = buildRestoreByIdQuery(this.table, id);
1274
- const [record] = await this.connection.unsafe(text, params);
1275
- if (!record) {
1276
- return null;
1277
- }
1278
- const entity = record;
1279
- await eventBus.dispatch(modelEventName(this.table.name, "restored"), entity);
1280
- return entity;
1281
- });
1282
- }
1283
- withConnection(connection) {
1284
- const clone = Object.create(Object.getPrototypeOf(this));
1285
- Object.assign(clone, this);
1286
- clone.connection = connection;
1287
- return clone;
1288
- }
1289
- getConnection() {
1290
- return this.connection;
1291
- }
1292
- getTable() {
1293
- return this.table;
1294
- }
1295
- query(where = {}) {
1296
- return new RepositoryQuery(this, where);
1297
- }
1298
- async findWhere(where, options = {}) {
1299
- return await this.findAll({ ...options, where });
1300
- }
1301
- async countWhere(where = {}, options = {}, whereNodes = []) {
1302
- const { text, params } = buildCountQuery(this.table, where, options, whereNodes);
1303
- const [row] = await this.connection.unsafe(text, params);
1304
- return Number(row?.count ?? 0);
1305
- }
1306
- async averageColumn(column, where = {}) {
1307
- const qualifiedColumn = qualifyColumn(this.table.name, column);
1308
- return await this.averageExpression(`AVG(${qualifiedColumn})`, "value", where);
1309
- }
1310
- async averageExpression(expression, alias, where = {}) {
1311
- const { text, params } = buildProjectionQuery(this.table, expression, alias, { where });
1312
- const [row] = await this.connection.unsafe(text, params);
1313
- return Math.round(Number(row?.[alias] ?? 0));
1314
- }
1315
- async pluckNumberValues(expression, alias, options = {}) {
1316
- const { text, params } = buildProjectionQuery(this.table, expression, alias, options);
1317
- const rows = await this.connection.unsafe(text, params);
1318
- return rows.flatMap((row) => {
1319
- const value = row[alias];
1320
- return value === null || value === undefined ? [] : [Number(value)];
1321
- });
1322
- }
1323
- async countGroupedBy(column, where = {}) {
1324
- const { text, params } = buildGroupedCountQuery(this.table, column, where);
1325
- const rows = await this.connection.unsafe(text, params);
1326
- return rows.map(({ value, count }) => ({
1327
- value,
1328
- count: Number(count)
1329
- }));
1330
- }
1331
- async findByHasManyRelation(relation, parentId, options = {}) {
1332
- return await this.findWhere({
1333
- [relation.foreignKey]: parentId
1334
- }, options);
1335
- }
1336
- async loadHasManyForParents(parents, relation, options = {}) {
1337
- if (parents.length === 0) {
1338
- return indexHasManyRelation(parents, [], relation);
1339
- }
1340
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
1341
- const children = await this.findWhere({
1342
- [relation.foreignKey]: parentIds
1343
- }, options);
1344
- return indexHasManyRelation(parents, children, relation);
1345
- }
1346
- async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
1347
- if (children.length === 0) {
1348
- return new Map;
1349
- }
1350
- const ownerIds = [...new Set(children.map((child) => child[relation.foreignKey]))];
1351
- const parents = await parentRepository.withConnection(this.connection).findWhere({
1352
- [relation.ownerKey]: ownerIds
1353
- }, options);
1354
- return indexBelongsToRelation(children, parents, relation);
1355
- }
1356
- async loadMorphManyForParents(parents, relation, options = {}) {
1357
- if (parents.length === 0) {
1358
- return indexMorphManyRelation(parents, [], relation);
1359
- }
1360
- const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
1361
- const children = await this.findWhere({
1362
- [relation.morphTypeKey]: relation.morphType,
1363
- [relation.morphIdKey]: parentIds
1364
- }, options);
1365
- return indexMorphManyRelation(parents, children, relation);
1366
- }
1367
- async loadMorphOneForParents(parents, relation, options = {}) {
1368
- const grouped = await this.loadMorphManyForParents(parents, relation, options);
1369
- const result = new Map;
1370
- for (const parent of parents) {
1371
- const matches = grouped.get(parent[relation.localKey]) ?? [];
1372
- result.set(parent[relation.localKey], matches[0]);
1373
- }
1374
- return result;
1375
- }
1376
- async loadMorphToForChildren(children, relation, repositoriesByType, options = {}) {
1377
- if (children.length === 0) {
1378
- return new Map;
1379
- }
1380
- const idsByType = new Map;
1381
- for (const child of children) {
1382
- const morphType = String(child[relation.morphTypeKey]);
1383
- const morphId = child[relation.morphIdKey];
1384
- const ids = idsByType.get(morphType) ?? new Set;
1385
- ids.add(morphId);
1386
- idsByType.set(morphType, ids);
1387
- }
1388
- const parentsByType = new Map;
1389
- for (const [morphType, ids] of idsByType) {
1390
- const repository = repositoriesByType.get(morphType);
1391
- if (!repository) {
1392
- continue;
1393
- }
1394
- const ownerKey = repository.getTable().primaryKey;
1395
- const parents = await repository.withConnection(this.connection).findWhere({
1396
- [ownerKey]: [...ids]
1397
- }, options);
1398
- const indexed = new Map;
1399
- for (const parent of parents) {
1400
- indexed.set(parent[ownerKey], parent);
1401
- }
1402
- parentsByType.set(morphType, indexed);
1403
- }
1404
- return indexMorphToRelation(children, parentsByType, relation);
1405
- }
1406
- }
1407
- var baseRepository_default = BaseRepository;
1408
- // ../../src/core/database/model.ts
1409
- var modelRepositories = new WeakMap;
1410
- var modelGlobalScopes = new WeakMap;
1411
- var modelBooted = new WeakSet;
1412
- function resolveModelRepository(model) {
1413
- const repository = modelRepositories.get(model);
1414
- if (!repository) {
1415
- throw new Error(`${model.name}.repository() is not implemented.`);
1416
- }
1417
- return repository;
1418
- }
1419
- function modelStatics(model) {
1420
- return model;
1421
- }
1422
- function ensureBooted(model) {
1423
- if (modelBooted.has(model)) {
1424
- return;
1425
- }
1426
- modelBooted.add(model);
1427
- const boot = model.boot;
1428
- if (typeof boot === "function") {
1429
- boot.call(model);
1430
- }
1431
- }
1432
- function getGlobalScopes(model) {
1433
- return modelGlobalScopes.get(model) ?? [];
1434
- }
1435
- function hydrateValue(value, cast) {
1436
- if (value === null || value === undefined) {
1437
- return value;
1438
- }
1439
- switch (cast) {
1440
- case "date":
1441
- case "datetime":
1442
- return value instanceof Date ? value : new Date(String(value));
1443
- case "json":
1444
- return typeof value === "string" ? JSON.parse(value) : value;
1445
- case "bool":
1446
- case "boolean":
1447
- return value === true || value === 1 || value === "1" || value === "true";
1448
- default:
1449
- return value;
1450
- }
1451
- }
1452
- function dehydrateValue(value, cast) {
1453
- if (value === null || value === undefined) {
1454
- return value;
1455
- }
1456
- switch (cast) {
1457
- case "date":
1458
- case "datetime":
1459
- return value instanceof Date ? value : new Date(String(value));
1460
- case "json":
1461
- return typeof value === "string" ? value : JSON.stringify(value);
1462
- case "bool":
1463
- case "boolean":
1464
- return Boolean(value);
1465
- default:
1466
- return value;
1467
- }
1468
- }
1469
- function filterMassAssignable(fillable, guarded, input) {
1470
- const resolvedGuarded = guarded ?? true;
1471
- if (fillable && fillable.length > 0) {
1472
- const allowed = new Set(fillable);
1473
- return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
1474
- }
1475
- if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
1476
- return {};
1477
- }
1478
- const blocked = new Set(resolvedGuarded);
1479
- return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
1480
- }
1481
- function applyCasts(values, casts, direction) {
1482
- if (Object.keys(casts).length === 0) {
1483
- return values;
1484
- }
1485
- const result = { ...values };
1486
- const castFn = direction === "hydrate" ? hydrateValue : dehydrateValue;
1487
- for (const [key, cast] of Object.entries(casts)) {
1488
- if (key in result && cast) {
1489
- result[key] = castFn(result[key], cast);
1490
- }
1491
- }
1492
- return result;
1493
- }
1494
- function applyTimestampsOnCreate(columns, values, enabled) {
1495
- if (!enabled) {
1496
- return values;
1497
- }
1498
- const now = new Date;
1499
- const result = { ...values };
1500
- if (columns.includes("created_at")) {
1501
- result.created_at = now;
1502
- }
1503
- if (columns.includes("updated_at")) {
1504
- result.updated_at = now;
1505
- }
1506
- return result;
1507
- }
1508
- function applyTimestampsOnUpdate(columns, values, enabled) {
1509
- if (!enabled) {
1510
- return values;
1511
- }
1512
- const result = { ...values };
1513
- if (columns.includes("updated_at")) {
1514
- result.updated_at = new Date;
1515
- }
1516
- return result;
1517
- }
1518
-
1519
- class Model {
1520
- attributes;
1521
- repository;
1522
- static $fillable;
1523
- static $guarded;
1524
- static $casts = {};
1525
- static $timestamps = true;
1526
- _exists;
1527
- constructor(attributes, repository, exists = true) {
1528
- this.attributes = attributes;
1529
- this.repository = repository;
1530
- this._exists = exists;
1531
- }
1532
- get $exists() {
1533
- return this._exists;
1534
- }
1535
- get(key) {
1536
- return this.attributes[key];
1537
- }
1538
- get id() {
1539
- return this.attributes[this.primaryKey()];
1540
- }
1541
- toObject() {
1542
- return { ...this.attributes };
1543
- }
1544
- primaryKey() {
1545
- throw new Error(`${this.constructor.name}.primaryKey() is not implemented.`);
1546
- }
1547
- static primaryKeyField() {
1548
- return resolveModelRepository(this).getTable().primaryKey;
1549
- }
1550
- static hydrateAttributes(attributes) {
1551
- const casts = modelStatics(this).$casts ?? {};
1552
- return applyCasts(attributes, casts, "hydrate");
1553
- }
1554
- static dehydrateAttributes(attributes) {
1555
- const casts = modelStatics(this).$casts ?? {};
1556
- return applyCasts(attributes, casts, "dehydrate");
1557
- }
1558
- static fromRecord(record, repository, exists = true) {
1559
- const statics = modelStatics(this);
1560
- const hydrated = statics.hydrateAttributes(record);
1561
- return new statics(hydrated, repository, exists);
1562
- }
1563
- static boot() {}
1564
- static addGlobalScope(_name, scope) {
1565
- ensureBooted(this);
1566
- const existing = modelGlobalScopes.get(this) ?? [];
1567
- modelGlobalScopes.set(this, [
1568
- ...existing,
1569
- scope
1570
- ]);
1571
- }
1572
- static repository() {
1573
- return resolveModelRepository(this);
1574
- }
1575
- static query() {
1576
- ensureBooted(this);
1577
- const repository = resolveModelRepository(this);
1578
- let query = repository.query();
1579
- for (const scope of getGlobalScopes(this)) {
1580
- query = scope(query);
1581
- }
1582
- return query;
1583
- }
1584
- static async create(attributes) {
1585
- const statics = modelStatics(this);
1586
- ensureBooted(this);
1587
- const repository = resolveModelRepository(this);
1588
- const table = repository.getTable();
1589
- const timestamps = statics.$timestamps ?? true;
1590
- const assignable = filterMassAssignable(statics.$fillable, statics.$guarded, attributes);
1591
- const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
1592
- const payload = statics.dehydrateAttributes(withTimestamps);
1593
- const record = await repository.create(payload);
1594
- return statics.fromRecord(record, repository, true);
1595
- }
1596
- static async find(id) {
1597
- const statics = modelStatics(this);
1598
- const repository = resolveModelRepository(this);
1599
- const primaryKey = repository.getTable().primaryKey;
1600
- const record = await Model.query.call(this).where({ [primaryKey]: id }).first();
1601
- return record ? statics.fromRecord(record, repository, true) : null;
1602
- }
1603
- static async findOrFail(id, errorFactory) {
1604
- const model = await Model.find.call(this, id);
1605
- if (model) {
1606
- return model;
1607
- }
1608
- throw errorFactory?.(id) ?? new NotFoundError(`${this.name} ${String(id)} not found.`);
1609
- }
1610
- static async all(options = {}) {
1611
- const statics = modelStatics(this);
1612
- const repository = resolveModelRepository(this);
1613
- let query = Model.query.call(this);
1614
- if (options.orderBy) {
1615
- query = query.orderBy(options.orderBy);
1616
- }
1617
- if (options.limit !== undefined) {
1618
- query = query.limit(options.limit);
1619
- }
1620
- const rows = await query.get();
1621
- return rows.map((row) => statics.fromRecord(row, repository, true));
1622
- }
1623
- static async firstWhere(where, options = {}) {
1624
- const statics = modelStatics(this);
1625
- const repository = resolveModelRepository(this);
1626
- let query = Model.query.call(this).where(where);
1627
- if (options.orderBy) {
1628
- query = query.orderBy(options.orderBy);
1629
- }
1630
- const record = await query.first();
1631
- return record ? statics.fromRecord(record, repository, true) : null;
1632
- }
1633
- async save() {
1634
- const ModelClass = modelStatics(this.constructor);
1635
- const timestamps = ModelClass.$timestamps ?? true;
1636
- const casts = ModelClass.$casts ?? {};
1637
- const table = this.repository.getTable();
1638
- if (this.$exists) {
1639
- const changes = applyTimestampsOnUpdate(table.columns, applyCasts(this.attributes, casts, "dehydrate"), timestamps);
1640
- const record2 = await this.repository.updateByIdOrThrow(this.id, changes);
1641
- this.attributes = ModelClass.hydrateAttributes(record2);
1642
- return this;
1643
- }
1644
- const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, this.attributes);
1645
- const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
1646
- const payload = ModelClass.dehydrateAttributes(withTimestamps);
1647
- const record = await this.repository.create(payload);
1648
- this.attributes = ModelClass.hydrateAttributes(record);
1649
- this._exists = true;
1650
- return this;
1651
- }
1652
- async update(changes) {
1653
- const ModelClass = modelStatics(this.constructor);
1654
- const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
1655
- Object.assign(this.attributes, assignable);
1656
- return await this.save();
1657
- }
1658
- async delete() {
1659
- if (resolveSoftDeleteColumn(this.repository.getTable())) {
1660
- return await this.repository.deleteById(this.id);
1661
- }
1662
- return await this.repository.forceDeleteById(this.id);
1663
- }
1664
- async forceDelete() {
1665
- return await this.repository.forceDeleteById(this.id);
1666
- }
1667
- async restore() {
1668
- const ModelClass = modelStatics(this.constructor);
1669
- const record = await this.repository.restoreById(this.id);
1670
- if (!record) {
1671
- return null;
1672
- }
1673
- this.attributes = ModelClass.hydrateAttributes(record);
1674
- return this;
1675
- }
1676
- async loadHasMany(as, relation, childRepository, options = {}) {
1677
- const grouped = await childRepository.withConnection(this.repository.getConnection()).loadHasManyForParents([this.attributes], relation, options);
1678
- const loaded = grouped.get(this.attributes[relation.localKey]) ?? [];
1679
- return Object.assign(this, { [as]: loaded });
1680
- }
1681
- async loadHasOne(as, relation, childRepository, options = {}) {
1682
- const loaded = await this.loadHasMany(as, relation, childRepository, { ...options, limit: 1 });
1683
- const value = loaded[as]?.[0];
1684
- return Object.assign(this, { [as]: value });
1685
- }
1686
- async loadBelongsTo(as, relation, parentRepository, options = {}) {
1687
- const grouped = await this.repository.loadBelongsToForParents([this.attributes], relation, parentRepository, options);
1688
- const loaded = grouped.get(this.attributes[relation.foreignKey]);
1689
- return Object.assign(this, { [as]: loaded });
1690
- }
1691
- async loadBelongsToMany(as, relation, relatedRepository, options = {}) {
1692
- const connection = this.repository.getConnection();
1693
- const parentId = this.attributes[relation.parentKey];
1694
- const pivotRows = await connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} = $1`, [parentId]);
1695
- if (pivotRows.length === 0) {
1696
- return Object.assign(this, { [as]: [] });
1697
- }
1698
- const relatedIds = [
1699
- ...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
1700
- ];
1701
- const relatedRows = await relatedRepository.withConnection(connection).findAll({
1702
- ...options,
1703
- where: {
1704
- [relation.relatedKey]: relatedIds
1705
- }
1706
- });
1707
- const grouped = indexBelongsToManyRelation([this.attributes], pivotRows, relatedRows, relation);
1708
- const loaded = grouped.get(parentId) ?? [];
1709
- return Object.assign(this, { [as]: loaded });
1710
- }
1711
- mergeAttributes(patch) {
1712
- Object.assign(this.attributes, patch);
1713
- return this;
1714
- }
1715
- }
1716
- function registerModelRepository(model, repository) {
1717
- modelRepositories.set(model, repository);
1718
- ensureBooted(model);
1719
- return model;
1720
- }
1721
- // ../../src/core/database/schema/columnDefinition.ts
1722
- class ColumnDefinition {
1723
- name;
1724
- kind;
1725
- length;
1726
- isNullable = false;
1727
- isPrimary = false;
1728
- isUnique = false;
1729
- autoIncrement = false;
1730
- defaultValue;
1731
- checkExpression;
1732
- foreignKey;
1733
- constructor(name, kind) {
1734
- this.name = name;
1735
- this.kind = kind;
1736
- }
1737
- nullable() {
1738
- this.isNullable = true;
1739
- return this;
1740
- }
1741
- notNullable() {
1742
- this.isNullable = false;
1743
- return this;
1744
- }
1745
- default(value) {
1746
- if (typeof value === "boolean") {
1747
- this.defaultValue = value ? "TRUE" : "FALSE";
1748
- return this;
1749
- }
1750
- if (typeof value === "number") {
1751
- this.defaultValue = String(value);
1752
- return this;
1753
- }
1754
- this.defaultValue = `'${value.replace(/'/g, "''")}'`;
1755
- return this;
1756
- }
1757
- defaultRaw(expression) {
1758
- this.defaultValue = expression;
1759
- return this;
1760
- }
1761
- unique() {
1762
- this.isUnique = true;
1763
- return this;
1764
- }
1765
- primary() {
1766
- this.isPrimary = true;
1767
- return this;
1768
- }
1769
- check(expression) {
1770
- this.checkExpression = expression;
1771
- return this;
1772
- }
1773
- }
1774
-
1775
- class ForeignIdColumnDefinition extends ColumnDefinition {
1776
- constructor(name) {
1777
- super(name, "foreignId");
1778
- this.notNullable();
1779
- }
1780
- references(table, column = "id") {
1781
- this.foreignKey = {
1782
- referencesTable: table,
1783
- referencesColumn: column
1784
- };
1785
- return this;
1786
- }
1787
- constrained(table) {
1788
- const referencesTable = table ?? inferReferencedTable(this.name);
1789
- return this.references(referencesTable);
1790
- }
1791
- cascadeOnDelete() {
1792
- if (!this.foreignKey) {
1793
- throw new Error(`Foreign key is not defined for column ${this.name}`);
1794
- }
1795
- this.foreignKey.onDelete = "cascade";
1796
- return this;
1797
- }
1798
- nullOnDelete() {
1799
- if (!this.foreignKey) {
1800
- throw new Error(`Foreign key is not defined for column ${this.name}`);
1801
- }
1802
- this.foreignKey.onDelete = "set null";
1803
- return this;
1804
- }
1805
- }
1806
- function inferReferencedTable(columnName) {
1807
- if (!columnName.endsWith("_id")) {
1808
- throw new Error(`Cannot infer referenced table from column ${columnName}`);
1809
- }
1810
- return columnName.slice(0, -3);
1811
- }
1812
-
1813
- // ../../src/core/database/schema/blueprint.ts
1814
- class Blueprint {
1815
- table;
1816
- action;
1817
- columns = [];
1818
- indexes = [];
1819
- droppedColumns = [];
1820
- droppedIndexes = [];
1821
- constructor(table, action) {
1822
- this.table = table;
1823
- this.action = action;
1824
- }
1825
- id(name = "id") {
1826
- const column = new ColumnDefinition(name, "id");
1827
- column.primary();
1828
- column.autoIncrement = true;
1829
- this.columns.push(column);
1830
- return column;
1831
- }
1832
- string(name, length) {
1833
- const column = new ColumnDefinition(name, "string");
1834
- column.length = length;
1835
- column.notNullable();
1836
- this.columns.push(column);
1837
- return column;
1838
- }
1839
- text(name) {
1840
- const column = new ColumnDefinition(name, "text");
1841
- column.notNullable();
1842
- this.columns.push(column);
1843
- return column;
1844
- }
1845
- boolean(name) {
1846
- const column = new ColumnDefinition(name, "boolean");
1847
- column.notNullable();
1848
- this.columns.push(column);
1849
- return column;
1850
- }
1851
- integer(name) {
1852
- const column = new ColumnDefinition(name, "integer");
1853
- column.notNullable();
1854
- this.columns.push(column);
1855
- return column;
1856
- }
1857
- bigInteger(name) {
1858
- const column = new ColumnDefinition(name, "bigInteger");
1859
- column.notNullable();
1860
- this.columns.push(column);
1861
- return column;
1862
- }
1863
- timestamp(name) {
1864
- const column = new ColumnDefinition(name, "timestamp");
1865
- column.notNullable();
1866
- this.columns.push(column);
1867
- return column;
1868
- }
1869
- json(name) {
1870
- const column = new ColumnDefinition(name, "json");
1871
- column.notNullable();
1872
- this.columns.push(column);
1873
- return column;
1874
- }
1875
- jsonb(name) {
1876
- const column = new ColumnDefinition(name, "jsonb");
1877
- column.notNullable();
1878
- this.columns.push(column);
1879
- return column;
1880
- }
1881
- foreignId(name) {
1882
- const column = new ForeignIdColumnDefinition(name);
1883
- this.columns.push(column);
1884
- return column;
1885
- }
1886
- timestamps() {
1887
- this.timestamp("created_at").defaultRaw("NOW()");
1888
- this.timestamp("updated_at").defaultRaw("NOW()");
1889
- }
1890
- softDeletes() {
1891
- this.timestamp("deleted_at").nullable();
1892
- }
1893
- dropColumn(name) {
1894
- this.droppedColumns.push(name);
1895
- }
1896
- dropSoftDeletes() {
1897
- this.dropColumn("deleted_at");
1898
- this.dropIndex(`idx_${this.table}_deleted_at`);
1899
- }
1900
- dropIndex(name) {
1901
- this.droppedIndexes.push(name);
1902
- }
1903
- unique(columns, name) {
1904
- this.indexes.push({
1905
- name,
1906
- columns: Array.isArray(columns) ? columns : [columns],
1907
- kind: "unique"
1908
- });
1909
- }
1910
- index(columns, options = {}) {
1911
- this.indexes.push({
1912
- name: options.name,
1913
- columns: Array.isArray(columns) ? columns : [columns],
1914
- kind: "index",
1915
- order: options.order
1916
- });
1917
- }
1918
- partialIndex(columns, where, nameOrOptions) {
1919
- const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
1920
- this.indexes.push({
1921
- name: options.name,
1922
- columns: Array.isArray(columns) ? columns : [columns],
1923
- kind: options.unique ? "uniquePartial" : "partial",
1924
- where
1925
- });
1926
- }
1927
- fullText(columns, name) {
1928
- this.indexes.push({
1929
- name,
1930
- columns: Array.isArray(columns) ? columns : [columns],
1931
- kind: "fullText"
1932
- });
1933
- }
1934
- ginIndex(column, name) {
1935
- this.indexes.push({
1936
- name,
1937
- columns: [column],
1938
- kind: "gin"
1939
- });
1940
- }
1941
- }
1942
- // ../../src/core/database/schema/driver.ts
1943
- function normalizeConnectionName(connection) {
1944
- const normalized = connection.trim().toLowerCase();
1945
- if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
1946
- return "pgsql";
1947
- }
1948
- if (normalized === "mysql" || normalized === "mariadb") {
1949
- return "mysql";
1950
- }
1951
- if (normalized === "sqlite") {
1952
- return "sqlite";
1953
- }
1954
- throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
1955
- }
1956
- function resolveDriverFromUrl(url) {
1957
- const normalized = url.trim().toLowerCase();
1958
- if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
1959
- return "pgsql";
1960
- }
1961
- if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
1962
- return "mysql";
1963
- }
1964
- if (normalized.startsWith("sqlite:")) {
1965
- return "sqlite";
1966
- }
1967
- return null;
1968
- }
1969
- function resolveDatabaseDriver(options = {}) {
1970
- const connection = options.connection ?? process.env.DB_CONNECTION;
1971
- if (connection) {
1972
- return normalizeConnectionName(connection);
1973
- }
1974
- const url = options.url ?? process.env.DATABASE_URL ?? "";
1975
- const fromUrl = resolveDriverFromUrl(url);
1976
- if (fromUrl) {
1977
- return fromUrl;
1978
- }
1979
- return "pgsql";
1980
- }
1981
- // ../../src/core/database/schema/errors.ts
1982
- class UnsupportedSchemaFeatureError extends Error {
1983
- constructor(feature, driver) {
1984
- super(`${feature} is not supported for the ${driver} driver`);
1985
- this.name = "UnsupportedSchemaFeatureError";
1986
- }
1987
- }
1988
- // ../../src/core/database/schema/grammars/grammar.ts
1989
- function compileColumnType(driver, column) {
1990
- switch (column.kind) {
1991
- case "id":
1992
- return compileIdType(driver);
1993
- case "string":
1994
- return compileStringType(driver, column.length);
1995
- case "text":
1996
- return compileTextType(driver);
1997
- case "boolean":
1998
- return compileBooleanType(driver);
1999
- case "integer":
2000
- case "foreignId":
2001
- return compileIntegerType(driver);
2002
- case "bigInteger":
2003
- return compileBigIntegerType(driver);
2004
- case "timestamp":
2005
- return compileTimestampType(driver);
2006
- case "json":
2007
- return compileJsonType(driver);
2008
- case "jsonb":
2009
- return compileJsonbType(driver);
2010
- default:
2011
- throw new Error(`Unsupported column kind: ${column.kind}`);
2012
- }
2013
- }
2014
- function compileIdType(driver) {
2015
- switch (driver) {
2016
- case "pgsql":
2017
- return "SERIAL";
2018
- case "mysql":
2019
- return "BIGINT UNSIGNED";
2020
- case "sqlite":
2021
- return "INTEGER";
2022
- }
2023
- }
2024
- function compileStringType(driver, length) {
2025
- switch (driver) {
2026
- case "pgsql":
2027
- return "TEXT";
2028
- case "mysql":
2029
- return length ? `VARCHAR(${length})` : "VARCHAR(255)";
2030
- case "sqlite":
2031
- return "TEXT";
2032
- }
2033
- }
2034
- function compileTextType(driver) {
2035
- switch (driver) {
2036
- case "pgsql":
2037
- case "sqlite":
2038
- return "TEXT";
2039
- case "mysql":
2040
- return "TEXT";
2041
- }
2042
- }
2043
- function compileBooleanType(driver) {
2044
- switch (driver) {
2045
- case "pgsql":
2046
- return "BOOLEAN";
2047
- case "mysql":
2048
- return "BOOLEAN";
2049
- case "sqlite":
2050
- return "INTEGER";
2051
- }
2052
- }
2053
- function compileIntegerType(driver) {
2054
- switch (driver) {
2055
- case "pgsql":
2056
- return "INTEGER";
2057
- case "mysql":
2058
- return "INT";
2059
- case "sqlite":
2060
- return "INTEGER";
2061
- }
2062
- }
2063
- function compileBigIntegerType(driver) {
2064
- switch (driver) {
2065
- case "pgsql":
2066
- return "BIGINT";
2067
- case "mysql":
2068
- return "BIGINT";
2069
- case "sqlite":
2070
- return "INTEGER";
2071
- }
2072
- }
2073
- function compileTimestampType(driver) {
2074
- switch (driver) {
2075
- case "pgsql":
2076
- return "TIMESTAMPTZ";
2077
- case "mysql":
2078
- return "TIMESTAMP";
2079
- case "sqlite":
2080
- return "TEXT";
2081
- }
2082
- }
2083
- function compileJsonType(driver) {
2084
- switch (driver) {
2085
- case "pgsql":
2086
- return "JSONB";
2087
- case "mysql":
2088
- return "JSON";
2089
- case "sqlite":
2090
- return "TEXT";
2091
- }
2092
- }
2093
- function compileJsonbType(driver) {
2094
- switch (driver) {
2095
- case "pgsql":
2096
- return "JSONB";
2097
- case "mysql":
2098
- return "JSON";
2099
- case "sqlite":
2100
- return "TEXT";
2101
- }
2102
- }
2103
-
2104
- // ../../src/core/database/schema/grammars/compileStatements.ts
2105
- function compileCreateTable(driver, blueprint) {
2106
- const table = quoteIdentifier(blueprint.table);
2107
- const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
2108
- for (const index of blueprint.indexes) {
2109
- if (index.kind === "unique" && index.columns.length > 1) {
2110
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2111
- parts.push(`UNIQUE (${columns})`);
2112
- }
2113
- }
2114
- const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
2115
- ${parts.join(`,
2116
- `)}
2117
- )`];
2118
- for (const index of blueprint.indexes) {
2119
- if (index.kind === "unique" && index.columns.length === 1) {
2120
- continue;
2121
- }
2122
- if (index.kind === "index") {
2123
- statements.push(compileIndex(driver, blueprint.table, index));
2124
- } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
2125
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2126
- }
2127
- }
2128
- return statements;
2129
- }
2130
- function compileAlterTable(driver, blueprint) {
2131
- const statements = [];
2132
- const table = quoteIdentifier(blueprint.table);
2133
- for (const column of blueprint.columns) {
2134
- const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
2135
- statements.push(`ALTER TABLE ${table}
2136
- ${addPrefix} ${compileColumn(driver, column, "alter")}`);
2137
- }
2138
- for (const columnName of blueprint.droppedColumns) {
2139
- const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
2140
- statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
2141
- }
2142
- for (const indexName of blueprint.droppedIndexes) {
2143
- statements.push(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
2144
- }
2145
- for (const index of blueprint.indexes) {
2146
- if (index.kind === "index" || index.kind === "unique") {
2147
- statements.push(compileIndex(driver, blueprint.table, index));
2148
- } else {
2149
- statements.push(...compileSpecialIndex(driver, blueprint.table, index));
2150
- }
2151
- }
2152
- return statements;
2153
- }
2154
- function compileDropTable(driver, tableName) {
2155
- const cascade = driver === "pgsql" ? " CASCADE" : "";
2156
- return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
2157
- }
2158
- function compileColumn(driver, column, mode) {
2159
- const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
2160
- if (column.autoIncrement && driver === "mysql") {
2161
- parts[1] = `${parts[1]} AUTO_INCREMENT`;
2162
- }
2163
- if (column.isPrimary && mode === "create") {
2164
- if (driver === "sqlite") {
2165
- parts.push("PRIMARY KEY AUTOINCREMENT");
2166
- } else {
2167
- parts.push("PRIMARY KEY");
2168
- }
2169
- } else if (!column.isNullable) {
2170
- parts.push("NOT NULL");
2171
- } else if (column.isNullable) {
2172
- parts.push("NULL");
2173
- }
2174
- if (column.defaultValue !== undefined) {
2175
- parts.push(`DEFAULT ${column.defaultValue}`);
2176
- }
2177
- if (column.isUnique) {
2178
- parts.push("UNIQUE");
2179
- }
2180
- if (column.checkExpression) {
2181
- parts.push(`CHECK (${column.checkExpression})`);
2182
- }
2183
- if (column.foreignKey) {
2184
- const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
2185
- const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
2186
- let clause = `REFERENCES ${reference}`;
2187
- if (onDelete === "cascade") {
2188
- clause += " ON DELETE CASCADE";
2189
- } else if (onDelete === "set null") {
2190
- clause += " ON DELETE SET NULL";
2191
- }
2192
- parts.push(clause);
2193
- }
2194
- return parts.join(" ");
2195
- }
2196
- function compileIndex(_driver, tableName, index) {
2197
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
2198
- const columns = index.columns.map((column) => {
2199
- const quoted = quoteIdentifier(column);
2200
- if (index.order === "desc") {
2201
- return `${quoted} DESC`;
2202
- }
2203
- return quoted;
2204
- }).join(", ");
2205
- const unique = index.kind === "unique" ? "UNIQUE " : "";
2206
- return `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
2207
- }
2208
- function compileSpecialIndex(driver, tableName, index) {
2209
- const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
2210
- const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
2211
- switch (index.kind) {
2212
- case "partial":
2213
- case "uniquePartial": {
2214
- if (driver !== "pgsql") {
2215
- throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
2216
- }
2217
- const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
2218
- return [
2219
- `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
2220
- ];
2221
- }
2222
- case "gin": {
2223
- if (driver !== "pgsql") {
2224
- throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
2225
- }
2226
- return [
2227
- `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
2228
- ];
2229
- }
2230
- case "fullText": {
2231
- if (driver === "mysql") {
2232
- return [
2233
- `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
2234
- ];
2235
- }
2236
- if (driver === "pgsql") {
2237
- throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
2238
- }
2239
- throw new UnsupportedSchemaFeatureError("fullText()", driver);
2240
- }
2241
- default:
2242
- return [];
2243
- }
2244
- }
2245
- function defaultIndexName(tableName, columns, kind) {
2246
- return `idx_${tableName}_${columns.join("_")}_${kind}`;
2247
- }
2248
- function compileBlueprint(driver, blueprint) {
2249
- switch (blueprint.action) {
2250
- case "create":
2251
- return compileCreateTable(driver, blueprint);
2252
- case "alter":
2253
- return compileAlterTable(driver, blueprint);
2254
- case "drop":
2255
- return compileDropTable(driver, blueprint.table);
2256
- default:
2257
- throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
2258
- }
2259
- }
2260
- // ../../src/core/database/schema/grammars/createGrammar.ts
2261
- function createGrammar(driver) {
2262
- return {
2263
- driver,
2264
- compile(blueprint) {
2265
- return compileBlueprint(driver, blueprint);
2266
- }
2267
- };
2268
- }
2269
-
2270
- // ../../src/core/database/schema/grammars/mysqlGrammar.ts
2271
- var MySqlGrammar = createGrammar("mysql");
2272
-
2273
- // ../../src/core/database/schema/grammars/postgresGrammar.ts
2274
- var PostgresGrammar = createGrammar("pgsql");
2275
-
2276
- // ../../src/core/database/schema/grammars/sqliteGrammar.ts
2277
- var SqliteGrammar = createGrammar("sqlite");
2278
-
2279
- // ../../src/core/database/schema/grammars/index.ts
2280
- function grammarForDriver(driver) {
2281
- switch (driver) {
2282
- case "pgsql":
2283
- return PostgresGrammar;
2284
- case "mysql":
2285
- return MySqlGrammar;
2286
- case "sqlite":
2287
- return SqliteGrammar;
2288
- default:
2289
- throw new Error(`Unsupported database driver: ${driver}`);
2290
- }
2291
- }
2292
- // ../../src/core/database/schema/schema.ts
2293
- class SchemaBuilder {
2294
- #driver;
2295
- #statements = [];
2296
- constructor(driver) {
2297
- this.#driver = driver;
2298
- }
2299
- create(table, callback) {
2300
- const blueprint = new Blueprint(table, "create");
2301
- callback(blueprint);
2302
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2303
- return this;
2304
- }
2305
- table(table, callback) {
2306
- const blueprint = new Blueprint(table, "alter");
2307
- callback(blueprint);
2308
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2309
- return this;
2310
- }
2311
- drop(table) {
2312
- const blueprint = new Blueprint(table, "drop");
2313
- this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
2314
- return this;
2315
- }
2316
- toSql() {
2317
- return [...this.#statements];
2318
- }
2319
- async execute(db) {
2320
- for (const statement of this.#statements) {
2321
- await db.unsafe(statement);
2322
- }
2323
- }
2324
- }
24
+ // ../../src/core/queue/failedJobRepository.ts
25
+ import { BaseRepository } from "@getstrata/core/database";
2325
26
 
2326
- class Schema {
2327
- static builder(driver) {
2328
- return new SchemaBuilder(driver ?? resolveDatabaseDriver());
2329
- }
2330
- static async run(db, driver, callback) {
2331
- const schema = Schema.builder(driver);
2332
- await callback(schema);
2333
- await schema.execute(db);
2334
- }
2335
- }
2336
- function createSchemaBuilder(db, driver) {
2337
- const builder = Schema.builder(driver);
2338
- return Object.assign(builder, {
2339
- async commit() {
2340
- await builder.execute(db);
2341
- }
2342
- });
2343
- }
2344
- // ../../src/core/database/table.ts
2345
- function defineTable(definition) {
2346
- return definition;
2347
- }
2348
27
  // ../../src/core/queue/failedJobTable.ts
28
+ import { defineTable } from "@getstrata/core/database";
2349
29
  var failedJobTable = defineTable({
2350
30
  name: "failed_job",
2351
31
  primaryKey: "id",
@@ -2354,7 +34,7 @@ var failedJobTable = defineTable({
2354
34
  });
2355
35
 
2356
36
  // ../../src/core/queue/failedJobRepository.ts
2357
- class FailedJobRepository extends baseRepository_default {
37
+ class FailedJobRepository extends BaseRepository {
2358
38
  constructor() {
2359
39
  super(failedJobTable);
2360
40
  }