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